Get a block height from a consensus hash
    Returns the block height on success
    Returns {'error': ...} on failure
554190
def get_block_from_consensus(consensus_hash, hostport=None, proxy=None):
    
    assert hostport or proxy, 'Need hostport or proxy'
    if proxy is None:
        proxy = connect_hostport(hostport)

    consensus_schema = {
        'type': 'object',
        'properties': {
            'block_id': {
                'anyOf': [
                    {
                        'type': 'integer',
                        'minimum': 0,
                    },
                    {
                        'type': 'null',
                    },
                ],
            },
        },
        'required': [
            'block_id'
        ],
    }

    schema = json_response_schema( consensus_schema )
    resp = {}
    try:
        resp = proxy.get_block_from_consensus(consensus_hash)
        resp = json_validate( schema, resp )
        if json_is_error(resp):
            log.error("Failed to find block ID for %s" % consensus_hash)
            return resp

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

        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['block_id']
433804
def height
      return nil if header.version < 2
      coinbase_tx = transactions[0]
      return nil unless coinbase_tx.coinbase_tx?
      buf = StringIO.new(coinbase_tx.inputs[0].script_sig.to_payload)
      len = Bitcoin.unpack_var_int_from_io(buf)
      buf.read(len).reverse.bth.to_i(16)
    end
337318
def handle_headers( self, message_header, block_headers_message ):
        
        log.debug("handle headers (%s)" % len(block_headers_message.headers))

        block_headers = block_headers_message.headers

        serializer = BlockHeaderSerializer()

        # verify that the local header chain connects to this sequence
        current_height = SPVClient.height( self.path )
        if current_height is None:
            assert USE_TESTNET
            current_height = -1

        assert (current_height >= 0 and USE_MAINNET) or USE_TESTNET, "Invalid height %s" % current_height
    
        last_header = None

        if current_height >= 0:
            last_header = SPVClient.read_header( self.path, current_height )
            log.debug("Receive %s headers (%s to %s)" % (len(block_headers), current_height, current_height + len(block_headers)))

        else:
            # first testnet header
            log.debug("Receive %s testnet headers (%s to %s)" % (len(block_headers), current_height + 1, current_height + len(block_headers)))
            last_header = {
                "version": block_headers[0].version,
                "prev_block_hash": "%064x" % block_headers[0].prev_block,
                "merkle_root": "%064x" % block_headers[0].merkle_root,
                "timestamp": block_headers[0].timestamp,
                "bits": block_headers[0].bits,
                "nonce": block_headers[0].nonce,
                "hash": block_headers[0].calculate_hash()
            }

        if (USE_MAINNET or (USE_TESTNET and current_height >= 0)) and last_header['hash'] != self.hash_to_string(block_headers[0].prev_block):
            raise Exception("Received discontinuous block header at height %s: hash '%s' (expected '%s')" % \
                    (current_height,
                    self.hash_to_string(block_headers[0].prev_block),
                    last_header['hash'] ))

        header_start = 1
        if USE_TESTNET and current_height < 0:
            # save initial header
            header_start = 0

        # verify that this sequence of headers constitutes a hash chain 
        for i in xrange(header_start, len(block_headers)):
            prev_block_hash = self.hash_to_string(block_headers[i].prev_block)
            if i > 0 and prev_block_hash != block_headers[i-1].calculate_hash():
                raise Exception("Block '%s' is not continuous with block '%s'" % \
                        prev_block_hash,
                        block_headers[i-1].calculate_hash())

        if current_height < 0:
            # save the first header 
            if not os.path.exists(self.path):
                with open(self.path, "wb") as f:
                    block_header_serializer = BlockHeaderSerializer()
                    bin_data = block_header_serializer.serialize( block_headers[0] )
                    f.write( bin_data )

            # got all headers, including the first
            current_height = 0

        # insert into to local headers database
        next_block_id = current_height + 1
        for block_header in block_headers:
            with open(self.path, "rb+") as f:

                # omit tx count 
                block_header.txns_count = 0
                bin_data = serializer.serialize( block_header )

                if len(bin_data) != BLOCK_HEADER_SIZE:
                    raise Exception("Block %s (%s) has %s-byte header" % (next_block_id, block_header.calculate_hash(), len(bin_data)))

                # NOTE: the fact that we use seek + write ensures that we can:
                # * restart synchronizing at any point
                # * allow multiple processes to work on the chain safely (even if they're duplicating effort)
                f.seek( BLOCK_HEADER_SIZE * next_block_id, os.SEEK_SET )
                f.write( bin_data )

                if SPVClient.height( self.path ) >= self.last_block_id - 1:
                    break

                next_block_id += 1
            
        current_block_id = SPVClient.height( self.path )
        if current_block_id >= self.last_block_id - 1:
            # got all headers
            self.loop_exit()
            return

        prev_block_header = SPVClient.read_header( self.path, current_block_id )
        prev_block_hash = prev_block_header['hash']
        self.send_getheaders( prev_block_hash )
528500
func (db *DB) RetrieveBlockHeight(hash string) (int64, error) {
	var blockHeight int64
	err := db.QueryRow(db.getBlockHeightSQL, hash).Scan(&blockHeight)
	return blockHeight, err
}
334601
func (apic *APICache) GetBlockHash(height int64) string {
	if !apic.IsEnabled() {
		return ""
	}
	hash, ok := apic.blockHash(height)
	if !ok {
		return ""
	}
	return hash.String()
}
99249
def get_canonical_block_by_number(self, block_number: BlockNumber) -> BaseBlock:
        
        validate_uint256(block_number, title="Block Number")
        return self.get_block_by_hash(self.chaindb.get_canonical_block_hash(block_number))
520025
def get_block_by_height(self, height: int, is_full: bool = False) -> dict:
        
        payload = self.generate_json_rpc_payload(RpcMethod.GET_BLOCK, [height, 1])
        response = self.__post(self.__url, payload)
        if is_full:
            return response
        return response['result']
1160278
def GET_blockchain_ops( self, path_info, blockchain_name, blockheight ):
        
        try:
            blockheight = int(blockheight)
            assert check_block(blockheight)
        except:
            return self._reply_json({'error': 'Invalid block'}, status_code=400)

        if blockchain_name != 'bitcoin':
            # not supported
            return self._reply_json({'error': 'Unsupported blockchain'}, status_code=404)
        
        blockstackd_url = get_blockstackd_url()
        nameops = blockstackd_client.get_blockstack_transactions_at(int(blockheight), hostport=blockstackd_url)
        if json_is_error(nameops):
            # error
            status_code = nameops.get('http_status', 502)
            return self._reply_json({'error': nameops['error']}, status_code=status_code)

        self._reply_json(nameops)
        return
793362
def rpc_get_block_from_consensus( self, consensus_hash, **con_info ):
        
        if not check_string(consensus_hash, min_length=LENGTHS['consensus_hash']*2, max_length=LENGTHS['consensus_hash']*2, pattern=OP_CONSENSUS_HASH_PATTERN):
            return {'error': 'Not a valid consensus hash', 'http_status': 400}

        db = get_db_state(self.working_dir)
        block_id = db.get_block_from_consensus( consensus_hash )
        db.close()
        return self.success_response( {'block_id': block_id} )
570726
def get_snapshots(working_dir, start_block=None, end_block=None):
    

    # make this usable even if we haven't explicitly configured virtualchain 
    impl = sys.modules[__name__]
    return BlockstackDB.get_consensus_hashes(impl, working_dir, start_block_height=start_block, end_block_height=end_block)
464691
func (s *NeutrinoClient) GetBlockHash(height int64) (*chainhash.Hash, error) {
	return s.CS.GetBlockHash(height)
}
538002
def getblock(self, hash: str) -> dict:
        ''''''

        return cast(dict, self.api_fetch('getblock?hash=' + hash))
28826
function getBlockHmac(key, blockIndex, blockLength, blockData) {
    return getHmacKey(key, new Int64(blockIndex)).then(function(blockKey) {
        var blockDataForHash = new Uint8Array(blockData.byteLength + 4 + 8);
        var blockDataForHashView = new DataView(blockDataForHash.buffer);
        blockDataForHash.set(new Uint8Array(blockData), 4 + 8);
        blockDataForHashView.setInt32(0, blockIndex, true);
        blockDataForHashView.setInt32(8, blockLength, true);
        return CryptoEngine.hmacSha256(blockKey, blockDataForHash.buffer);
    });
}
1167897
def rpc_get_blockstack_ops_at(self, block_id, offset, count, **con_info):
        
        if not check_block(block_id):
            return {'error': 'Invalid block height', 'http_status': 400}

        if not check_offset(offset):
            return {'error': 'Invalid offset', 'http_status': 400}

        if not check_count(count, 10):
            return {'error': 'Invalid count', 'http_status': 400}

        db = get_db_state(self.working_dir)
        nameops = db.get_all_blockstack_ops_at(block_id, offset=offset, count=count)
        db.close()

        log.debug("{} name operations at block {}, offset {}, count {}".format(len(nameops), block_id, offset, count))
        ret = []
        
        for nameop in nameops:
            assert 'opcode' in nameop, 'BUG: missing opcode in {}'.format(json.dumps(nameop, sort_keys=True))
            canonical_op = self.sanitize_rec(nameop)
            ret.append(canonical_op)
        
        return self.success_response({'nameops': ret})
1170129
def rpc_get_num_blockstack_ops_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)
        count = db.get_num_blockstack_ops_at( block_id )
        db.close()

        log.debug("{} name operations at {}".format(count, block_id))
        return self.success_response({'count': count})
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} )
979161
def get_consensus(block):
    """"""
    from collections import Counter

    # Take aligned (non-insert) chars from all rows; transpose
    columns = zip(*[[c for c in row['seq'] if not c.islower()]
                    for row in block['sequences']])
    cons_chars = [Counter(col).most_common()[0][0] for col in columns]
    cons_chars = [c if c != '-' else 'X' for c in cons_chars]
    assert len(cons_chars) == block['query_length']
    cons_sequence = {
        'index': 1,
        'id': 'consensus',
        'description': '',
        'dbxrefs': {},
        'phylum': '',
        'taxchar': '',
        'head_len': None,
        'tail_len': None,
        'head_seq': '',
        'tail_seq': '',
        'length': block['query_length'],
        'seq': ''.join(cons_chars),
    }
    return cons_sequence