ETH源码阅读(区块Header的存储)

区块Header在db中存储

key:h + number(区块高度) + block hash(区块hash)

value:Header

1.hash和number得到key

go-ethereum/core/rawdb/schema.go

//h + number + block hash
// headerKey = headerPrefix + num (uint64 big endian) + hash
func headerKey(number uint64, hash common.Hash) []byte {
    return append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
}
2.通过block hash和block number得到Header

go-ethereum/core/rawdb/accessors_chain.go

// ReadHeader retrieves the block header corresponding to the hash.
func ReadHeader(db DatabaseReader, hash common.Hash, number uint64) *types.Header {
    data := ReadHeaderRLP(db, hash, number) //通过hash和number得到key,再通过key去db读取data
    if len(data) == 0 {
        return nil
    }
    header := new(types.Header)
    if err := rlp.Decode(bytes.NewReader(data), header); err != nil { //data解析成Header
        log.Error("Invalid block header RLP", "hash", hash, "err", err)
        return nil
    }
    return header
}

你可能感兴趣的:(ETH源码阅读(区块Header的存储))