Get the list of names with the given value hash, at the current block height.
        This excludes revoked names and expired names.

        Return None if there are no such names
506242
def get_names_with_value_hash( self, value_hash ):
        
        cur = self.db.cursor()
        names = namedb_get_names_with_value_hash( cur, value_hash, self.lastblock )
        return names
78210
def lookup(feature, name)
      value = @hash[feature]
      value = value[name] if value.is_a? Hash
      fail IndexError, "No CmdRef defined for #{feature}, #{name}" if value.nil?
      value
    end
574464
def namedb_get_name_DID_info(cur, name, block_height):
    
    # get the latest creator addresses for this name, as well as where this name was created in the blockchain
    sql = "SELECT name_records.name,history.creator_address,history.block_id,history.vtxindex FROM name_records JOIN history ON name_records.name = history.history_id " + \
          "WHERE name = ? AND creator_address IS NOT NULL AND history.block_id <= ? ORDER BY history.block_id DESC, history.vtxindex DESC LIMIT 1;"
    args = (name,block_height)

    # log.debug(namedb_format_query(sql, args))
    rows = namedb_query_execute(cur, sql, args)
    row = rows.fetchone()
    if row is None:
        return None
    
    creator_address = row['creator_address']
    latest_block_height = row['block_id']
    latest_vtxindex = row['vtxindex']

    # how many names has this address created up to this name?
    query = "SELECT COUNT(*) FROM name_records JOIN history ON name_records.name = history.history_id " + \
            "WHERE history.creator_address = ? AND (history.block_id < ? OR (history.block_id = ? AND history.vtxindex <= ?));"

    args = (creator_address,latest_block_height,latest_block_height,latest_vtxindex)

    # log.debug(namedb_format_query(query, args))
    count_rows = namedb_query_execute(cur, query, args)
    count_row = count_rows.fetchone()
    if count_row is None:
        return None

    count = count_row['COUNT(*)'] - 1

    return {'name_type': 'name', 'address': str(creator_address), 'index': count}
359443
def GET_names( self, path_info ):
        

        include_expired = False

        qs_values = path_info['qs_values']
        page = qs_values.get('page', None)
        if page is None:
            log.error("Page required")
            return self._reply_json({'error': 'page= argument required'}, status_code=400)

        try:
            page = int(page)
            if page < 0:
                raise ValueError("Page is negative")

        except ValueError:
            log.error("Invalid page")
            return self._reply_json({'error': 'Invalid page= value'}, status_code=400)

        if qs_values.get('all', '').lower() in ['1', 'true']:
            include_expired = True

        offset = page * 100
        count = 100

        blockstackd_url = get_blockstackd_url()
        res = blockstackd_client.get_all_names(offset, count, include_expired=include_expired, hostport=blockstackd_url)
        if json_is_error(res):
            log.error("Failed to list all names (offset={}, count={}): {}".format(offset, count, res['error']))
            return self._reply_json({'error': 'Failed to list all names'}, status_code=res.get('http_status', 502))

        return self._reply_json(res)
1303281
def get_DID_name(self, did):
        
        did = str(did)
        did_info = None
        try:
            did_info = parse_DID(did)
            assert did_info['name_type'] == 'name'
        except Exception as e:
            if BLOCKSTACK_DEBUG:
                log.exception(e)

            raise ValueError("Invalid DID: {}".format(did))

        cur = self.db.cursor()
        historic_name_info = namedb_get_historic_names_by_address(cur, did_info['address'], offset=did_info['index'], count=1)
        if historic_name_info is None:
            # no such name
            return None

        name = historic_name_info[0]['name']
        block_height = historic_name_info[0]['block_id']
        vtxindex = historic_name_info[0]['vtxindex']
                    
        log.debug("DID {} refers to {}-{}-{}".format(did, name, block_height, vtxindex))

        name_rec = self.get_name(name, include_history=True, include_expired=True)
        if name_rec is None:
            # dead
            return None

        name_rec_latest = None
        found = False

        for height in sorted(name_rec['history'].keys()):
            if found:
                break

            if height < block_height:
                continue

            for state in name_rec['history'][height]:
                if height == block_height and state['vtxindex'] < vtxindex:
                    # too soon
                    continue

                if state['op'] == NAME_PREORDER:
                    # looped to the next iteration of this name
                    found = True
                    break

                if state['revoked']:
                    # revoked
                    log.debug("DID {} refers to {}-{}-{}, which is revoked at {}-{}".format(did, name, block_height, vtxindex, height, state['vtxindex']))
                    return None

                name_rec_latest = state

        return name_rec_latest
1202945
def get_name_at(name, block_id, include_expired=False, hostport=None, proxy=None):
    
    assert hostport or proxy, 'Need hostport or proxy'
    if proxy is None:
        proxy = connect_hostport(hostport)

    namerec_schema = {
        'type': 'object',
        'properties': NAMEOP_SCHEMA_PROPERTIES,
        'required': NAMEOP_SCHEMA_REQUIRED
    }

    namerec_list_schema = {
        'type': 'object',
        'properties': {
            'records': {
                'anyOf': [
                    {
                        'type': 'array',
                        'items': namerec_schema
                    },
                    {
                        'type': 'null',
                    },
                ],
            },
        },
        'required': [
            'records'
        ],
    }

    resp_schema = json_response_schema( namerec_list_schema )
    resp = {}
    try:
        if include_expired:
            resp = proxy.get_historic_name_at(name, block_id)
        if not include_expired or 'KeyError' in resp.get('error', ''):
            resp = proxy.get_name_at(name, block_id)

        assert resp, "No such name {} at block {}".format(name, block_id)

        resp = json_validate(resp_schema, resp)
        if json_is_error(resp):
            return resp

    except ValidationError as e:
        if BLOCKSTACK_DEBUG:
            log.exception(e)

        resp = {'error': 'Server response did not match expected schema.  You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
        return resp

    except socket.timeout:
        log.error("Connection timed out")
        resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
        return resp

    except socket.error as se:
        log.error("Connection error {}".format(se.errno))
        resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
        return resp

    except Exception as ee:
        if BLOCKSTACK_DEBUG:
            log.exception(ee)

        log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
        resp = {'error': 'Failed to contact Blockstack node.  Try again with `--debug`.', 'http_status': 500}
        return resp

    return resp['records']
262308
def namedb_get_num_names( cur, current_block, include_expired=False ):
    
    unexpired_query = ""
    unexpired_args = ()

    if not include_expired:
        # count all names, including expired ones
        unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block )
        unexpired_query = 'WHERE {}'.format(unexpired_query)

    query = "SELECT COUNT(name_records.name) FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id " + unexpired_query + ";"
    args = unexpired_args

    num_rows = namedb_select_count_rows( cur, query, args, count_column='COUNT(name_records.name)' )
    return num_rows
458132
def get_index_range(blockchain_name, blockchain_client, impl, working_dir):
    

    start_block = config.get_first_block_id(impl)
    try:
        current_block = get_blockchain_height(blockchain_name, blockchain_client)
    except Exception, e:
        log.exception(e)
        return None, None

    saved_block = StateEngine.get_lastblock(impl, working_dir)

    if saved_block is None:
        saved_block = 0
    elif saved_block == current_block:
        start_block = saved_block
    elif saved_block < current_block:
        start_block = saved_block + 1

    return start_block, current_block
295700
def GET_name_info( self, path_info, name ):
        
        if not check_name(name) and not check_subdomain(name):
            return self._reply_json({'error': 'Invalid name or subdomain'}, status_code=400)

        blockstackd_url = get_blockstackd_url()

        name_rec = None
        try:
            name_rec = blockstackd_client.get_name_record(name, include_history=False, hostport=blockstackd_url)
        except ValueError:
            return self._reply_json({'error': 'Invalid argument: not a well-formed name or subdomain'}, status_code=400)

        if 'error' in name_rec:
            if 'not found' in name_rec['error'].lower():
                return self._reply_json({'status': 'available'}, status_code=404)

            elif 'failed to load subdomain' in name_rec['error'].lower():

                # try to redirect to resolver, if given
                _, _, domain_name = blockstackd_scripts.is_address_subdomain(name)
                domain_rec = blockstackd_client.get_name_record(domain_name, include_history=False, hostport=blockstackd_url)

                if 'error' in domain_rec:
                    # no resolver known for on-chain name
                    return self._reply_json({'status': 'available', 'more': 'failed to look up parent domain'}, status_code=404)

                resolver_target = domain_rec.get('resolver', None)
                if resolver_target is None:
                    # no _resolver
                    return self._reply_json({'status': 'available',  'more': 'failed to find parent domain\'s resolver'}, status_code=404)

                redirect_location = resolver_target + '/v1/names/' + name
                log.debug("Redirect lookup on {} to {}".format(name, redirect_location))

                self._send_headers(status_code=301, more_headers={ 'Location': redirect_location })
                return self.wfile.write(json.dumps({'status': 'redirect'}))

            elif 'expired' in name_rec['error'].lower():
                return self._reply_json({'error': name_rec['error']}, status_code=404)

            else:
                return self._reply_json({'error': 'Blockstack daemon error: {}'.format(name_rec['error'])}, status_code=name_rec.get('http_status', 502))


        zonefile_txt = None

        if 'zonefile' in name_rec:
            zonefile_txt = base64.b64decode(name_rec['zonefile'])

        ret = {}

        if blockstackd_scripts.is_subdomain(name):
            # subdomain
            address = name_rec['address']
            if address:
                address = virtualchain.address_reencode(str(address))

            log.debug("{} is registered_subdomain".format(name))
            ret = {
                'status': 'registered_subdomain',
                'zonefile': zonefile_txt,
                'zonefile_hash': name_rec['value_hash'],
                'address': name_rec['address'],
                'blockchain': 'bitcoin',
                'last_txid': name_rec['txid'],
                'did': name_rec.get('did', {'error': 'Not supported for this name'})
            }

        else:
            status = 'revoked' if name_rec['revoked'] else 'registered'
            address = name_rec['address']
            if address:
                address = virtualchain.address_reencode(str(address))

            log.debug("{} is {}".format(name, status))
            ret = {
                'status': status,
                'zonefile': zonefile_txt,
                'zonefile_hash': name_rec['value_hash'],
                'address': address,
                'last_txid': name_rec['txid'],
                'blockchain': 'bitcoin',
                'expire_block': name_rec['expire_block'],      # expire_block is what blockstack.js expects
                'renewal_deadline': name_rec['renewal_deadline'],
                'grace_period': name_rec.get('grace_period', False),
                'resolver': name_rec.get('resolver', None),
                'did': name_rec.get('did', {'error': 'Not supported for this name'})
            }

        return self._reply_json(ret)
1164732
def rpc_get_blockstack_ops_hash_at( self, block_id, **con_info ):
        
        if not check_block(block_id):
            return {'error': 'Invalid block height', 'http_status': 400}

        db = get_db_state(self.working_dir)
        ops_hash = db.get_block_ops_hash( block_id )
        db.close()

        return self.success_response( {'ops_hash': ops_hash} )
628346
def namedb_get_num_names_in_namespace( cur, namespace_id, current_block ):
    
    unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block )

    query = "SELECT COUNT(name_records.name) FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id WHERE name_records.namespace_id = ? AND " + unexpired_query + " ORDER BY name;"
    args = (namespace_id,) + unexpired_args

    num_rows = namedb_select_count_rows( cur, query, args, count_column='COUNT(name_records.name)' )
    return num_rows
278027
def get_consensus_hashes(cls, impl, working_dir, start_block_height=None, end_block_height=None, db_con=None, completeness_check=True):
        
        if (start_block_height is None and end_block_height is not None) or (start_block_height is not None and end_block_height is None):
            raise ValueError("Need either both or neither start/end block height")

        we_opened = False
        if db_con is not None:
            con = db_con

        else:
            assert impl and working_dir, 'Need impl and working_dir if db_con is not given'
            con = cls.db_open(impl, working_dir)
            we_opened = True

        range_query = ''
        range_args = ()

        if start_block_height and end_block_height:
            range_query += ' WHERE block_id >= ? AND block_id < ?'
            range_args += (start_block_height,end_block_height)

        query = 'SELECT block_id,consensus_hash FROM snapshots' + range_query + ';'
        args = range_args

        rows = cls.db_query_execute(con, query, range_args, verbose=False)
        ret = {}
        block_min = None
        block_max = None

        for r in rows:
            block_id = int(r['block_id'])
            ret[block_id] = r['consensus_hash']

            if block_min is None or block_min > block_id:
                block_min = block_id

            if block_max is None or block_max < block_id:
                block_max = block_id

        if we_opened:
            con.close()
       
        if completeness_check:
            # sanity check
            for i in range(block_min,block_max+1):
                ch = ret.get(i, None)

                assert ch is not None, 'Missing consensus hash for {}'.format(i)
                assert isinstance(ret[i], (str,unicode)), 'consensus hash for {} is type {}'.format(i, type(ret[i]))

        return ret
856339
def has_name_in(cls, names):
        """"""
        return cls.sha512.in_({
            cls.hash_name(name)
            for name in names
        })
689573
def get_block_containing_tx(self, txid):
        
        blocks = list(backend.query.get_block_with_transaction(self.connection, txid))
        if len(blocks) > 1:
            logger.critical('Transaction id %s exists in multiple blocks', txid)

        return [block['height'] for block in blocks]
1220534
def collect_blocks(self):
        
        if self.mode == 'spark':
            return self.values.tordd().sortByKey().values().collect()

        if self.mode == 'local':
            return self.values.values.flatten().tolist()
1232671
def values(key)
      h = hash(key)

      hoff = @hashes[(h % 256)*2]
      hlen = @hashes[(h % 256)*2 + 1]

      return [] if hlen == 0
      off = (h / 256) % hlen

      vals = []

      # FIXME: Is this potentially an infinite loop (if full)?
      # Easy to avoid by exiting if off reaches the same value twice.

      while
          (slot = read(hoff + off * hashref_size .. hoff + off * hashref_size + hashref_size - 1)) &&
          (dslot = ary_unpack(slot,2)) && dslot[1] != 0

        if dslot[0] == h
          pos = dslot[1]

          rkey, value = read_entry(pos)
          if rkey == key
            vals << value
          end
        end
        off = (off + 1) % hlen
      end
      return vals
    end
1196410
def get_raise_list(self, data):
        
        return_list = []
        lst = self.get_list_key(data, 'raise')
        for l in lst:
            # assume raises are only a name and a description
            name, desc, _ = l
            return_list.append((name, desc))

        return return_list