<aside> 💡 区块链的基础数据结构

</aside>

准备

Hash

  1. Hash也称散列、哈希。基本原理就是把任意长度的输入,通过Hash算法变成固定长度的输出(更多解释见知乎

  2. 特点是:相同的输入一定得到相同的输出,不同的输入大概率得到不同的输出

  3. 举例:用shell命令行下的md5sum 来计算任意的字符的MD5哈希

    $ md5sum <<< haha
    7494ab07987ba112bd5c4f9857ccfb3f  -
    $ md5sum <<< hehe
    e4439267203fb5277d347e6cd6e440b5  -
    $ md5sum <<< hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
    6f2362c812dcfd693da2e3ae537cfb41  -
    
  4. 常见的hash算法:

    1. 文件防篡改:MD5
    2. 比特币挖矿:SHA256
    3. 证明数据片段:Merkle root
    4. 文本去重:SimHash

区块

区块(block)由区块头(block header)和交易列表(transaction list,tx list)组成,block之间通过block header的hash连接成了一个链表结构。

block header

  1. 比特币的block header(Github
int32_t nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
uint32_t nTime;
uint32_t nBits;
uint32_t nNonce;
  1. 以太坊的block header(Github
ParentHash  common.Hash    `json:"parentHash"       gencodec:"required"`
UncleHash   common.Hash    `json:"sha3Uncles"       gencodec:"required"`
Coinbase    common.Address `json:"miner"            gencodec:"required"`
Root        common.Hash    `json:"stateRoot"        gencodec:"required"`
TxHash      common.Hash    `json:"transactionsRoot" gencodec:"required"`
ReceiptHash common.Hash    `json:"receiptsRoot"     gencodec:"required"`
Bloom       Bloom          `json:"logsBloom"        gencodec:"required"`
Difficulty  *big.Int       `json:"difficulty"       gencodec:"required"`
Number      *big.Int       `json:"number"           gencodec:"required"`
GasLimit    uint64         `json:"gasLimit"         gencodec:"required"`
GasUsed     uint64         `json:"gasUsed"          gencodec:"required"`
Time        uint64         `json:"timestamp"        gencodec:"required"`
Extra       []byte         `json:"extraData"        gencodec:"required"`
MixDigest   common.Hash    `json:"mixHash"`
Nonce       BlockNonce     `json:"nonce"`

// BaseFee was added by EIP-1559 and is ignored in legacy headers.
BaseFee *big.Int `json:"baseFeePerGas" rlp:"optional"`
  1. 当前我们只需要关注其中两个字段(其他字段会在后续课程中解释)
    1. hashPrevBlock /ParentHash,上一个block header的hash
    2. hashMerkleRoot/TxHash,tx list的hash

block body

block body

block body

  1. block body就是tx list,block header通过TxHash指向唯一的tx list
  2. 从tx hash list得到TxHash的hash算法叫做默克尔树(Merkle tree),相比其他的hash算法有特殊的性质(可以简洁地证明tx存在其中)