'Return address\'s firstbits, or the longest of multiple
firstbits values if chain_id is not given, or None if address
has not appeared, or the empty string if address has appeared
but has no firstbits.'

def get_firstbits(store, address_version=None, db_pubkey_hash=None, chain_id=None):

    (vers, dbhash) = (store.binin(address_version), db_pubkey_hash)
    rows = store.selectall(('\n                                                SELECT    fb.firstbits\n                                                        FROM    abe_firstbits    fb\n                                                        JOIN    pubkey    ON    (fb.pubkey_id    =    pubkey.pubkey_id)\n                                                        JOIN    chain_candidate    cc    ON    (fb.block_id    =    cc.block_id)\n                                                    WHERE    cc.in_longest    =    1\n                                                            AND    fb.address_version    =    ?\n                                                            AND    pubkey.pubkey_hash    =    ?' + ('' if (chain_id is None) else '\n                                                            AND    cc.chain_id    =    ?')), ((vers, dbhash) if (chain_id is None) else (vers, dbhash, chain_id)))
    if (not rows):
        return None
    ret = ''
    for (fb,) in rows:
        if (len(fb) > len(ret)):
            ret = fb
    return ret
