# 区块、链

## 准备

### Hash

1. Hash也称散列、哈希。基本原理就是把任意长度的输入，通过Hash算法变成固定长度的输出（更多解释见[知乎](https://www.zhihu.com/question/26762707/answer/890181997)）
2. 特点是：相同的输入一定得到相同的输出，不同的输入大概率得到不同的输出
3. 举例：用shell命令行下的`md5sum` 来计算任意的字符的MD5哈希

   ```bash
   $ md5sum <<< haha
   7494ab07987ba112bd5c4f9857ccfb3f  -
   $ md5sum <<< hehe
   e4439267203fb5277d347e6cd6e440b5  -
   $ md5sum <<< hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
   6f2362c812dcfd693da2e3ae537cfb41  -
   ```
4. 常见的hash算法：
   * 文件防篡改：MD5
   * 比特币挖矿：SHA256
   * 证明数据片段：Merkle root
   * 文本去重：SimHash

## 区块

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

### block header

1. 比特币的block header（[Github](https://github.com/bitcoin/bitcoin/blob/v22.0/src/primitives/block.h#L24)）

```cpp
int32_t nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
uint32_t nTime;
uint32_t nBits;
uint32_t nNonce;
```

2. 以太坊的block header（[Github](https://github.com/ethereum/go-ethereum/blob/v1.10.11/core/types/block.go#L70)）

```go
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"`
```

3. 当前我们只需要关注其中两个字段（其他字段会在后续课程中解释）
   * `hashPrevBlock` /`ParentHash`，上一个block header的hash
   * `hashMerkleRoot`/`TxHash`，tx list的hash

### block body

<figure><img src="/files/UnBHFmDKtvzZI9WCCU8L" alt=""><figcaption></figcaption></figure>

block body

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

## 链

<figure><img src="/files/H8ztYm67ZN2ZsFbNridQ" alt=""><figcaption></figcaption></figure>

1. block header通过`ParentHash`指向唯一的上个block header，并最终形成一条链
   1. 高度为0的block称之为Genesis，即创世区块
      1. 写死在程序里（[Github](https://github.com/bitcoin/bitcoin/blob/v22.0/src/chainparams.cpp#L53)）
      2. 也可以在[btc.com](https://btc.com/btc/block/0)上看到比特币的创世区块，以及中本聪留下的那句话

         ![比特币创世区块上记录的报纸头条文章标题](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/bb3608d8-0cfa-4a8a-81d2-daabac45cb9d/EqyhCKuXIAAOl0z.jpeg)

         比特币创世区块上记录的报纸头条文章标题
   2. 高度最高的block称之为Tip，即最新区块
   3. 可以在[etherscan](https://etherscan.io/blocks)上观察以太坊链的情况
2. `TxHash`和`ParentHash`相结合，赋予了区块链**不可篡改**的特性


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://bitvm.gitbook.io/doc/bitvm/base-knowlege/qu-kuai-lian.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
