Go-ethereum 源码解析之 consensus/consensus.go

Go-ethereum 源码解析之 consensus/consensus.go

// Package consensus implements different Ethereum consensus engines.
package consensus

import (
    "math/big"

    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/core/state"
    "github.com/ethereum/go-ethereum/core/types"
    "github.com/ethereum/go-ethereum/params"
    "github.com/ethereum/go-ethereum/rpc"
)

// ChainReader defines a small collection of methods needed to access the local
// blockchain during header and/or uncle verification.
type ChainReader interface {
    // Config retrieves the blockchain's chain configuration.
    Config() *params.ChainConfig

    // CurrentHeader retrieves the current header from the local chain.
    CurrentHeader() *types.Header

    // GetHeader retrieves a block header from the database by hash and number.
    GetHeader(hash common.Hash, number uint64) *types.Header

    // GetHeaderByNumber retrieves a block header from the database by number.
    GetHeaderByNumber(number uint64) *types.Header

    // GetHeaderByHash retrieves a block header from the database by its hash.
    GetHeaderByHash(hash common.Hash) *types.Header

    // GetBlock retrieves a block from the database by hash and number.
    GetBlock(hash common.Hash, number uint64) *types.Block
}

// Engine is an algorithm agnostic consensus engine.
type Engine interface {
    // Author retrieves the Ethereum address of the account that minted the given
    // block, which may be different from the header's coinbase if a consensus
    // engine is based on signatures.
    Author(header *types.Header) (common.Address, error)

    // VerifyHeader checks whether a header conforms to the consensus rules of a
    // given engine. Verifying the seal may be done optionally here, or explicitly
    // via the VerifySeal method.
    VerifyHeader(chain ChainReader, header *types.Header, seal bool) error

    // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers
    // concurrently. The method returns a quit channel to abort the operations and
    // a results channel to retrieve the async verifications (the order is that of
    // the input slice).
    VerifyHeaders(chain ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error)

    // VerifyUncles verifies that the given block's uncles conform to the consensus
    // rules of a given engine.
    VerifyUncles(chain ChainReader, block *types.Block) error

    // VerifySeal checks whether the crypto seal on a header is valid according to
    // the consensus rules of the given engine.
    VerifySeal(chain ChainReader, header *types.Header) error

    // Prepare initializes the consensus fields of a block header according to the
    // rules of a particular engine. The changes are executed inline.
    Prepare(chain ChainReader, header *types.Header) error

    // Finalize runs any post-transaction state modifications (e.g. block rewards)
    // and assembles the final block.
    // Note: The block header and state database might be updated to reflect any
    // consensus rules that happen at finalization (e.g. block rewards).
    Finalize(chain ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction,
        uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error)

    // Seal generates a new sealing request for the given input block and pushes
    // the result into the given channel.
    //
    // Note, the method returns immediately and will send the result async. More
    // than one result may also be returned depending on the consensus algorithm.
    Seal(chain ChainReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error

    // SealHash returns the hash of a block prior to it being sealed.
    SealHash(header *types.Header) common.Hash

    // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
    // that a new block should have.
    CalcDifficulty(chain ChainReader, time uint64, parent *types.Header) *big.Int

    // APIs returns the RPC APIs this consensus engine provides.
    APIs(chain ChainReader) []rpc.API

    // Close terminates any background threads maintained by the consensus engine.
    Close() error
}

// PoW is a consensus engine based on proof-of-work.
type PoW interface {
    Engine

    // Hashrate returns the current mining hashrate of a PoW consensus engine.
    Hashrate() float64
}

Appendix A. 总体批注

包 consensus 实现了不同的以太坊共识引擎。

文件 consensus/consensus.go 主要定义了共识引擎的基本接口,便于将共识引擎的具体实现与共识引擎的基本接口进行分离,便于扩展共识引擎的具体实现。同时,定义了链获取器接口,便于查询链上的区块和区块头等信息。

1. type ChainReader interface

接口 ChainReader 定义了在区块头和/或叔区块验证期间访问本地区块链所需的一些方式。

  • 通过方法 Config() 用于获取区块链的链配置信息。
  • 通过方法 CurrentHeader() 用于从本地链获取当前的区块头。
  • 通过方法 GetHeader() 根据区块哈希和编号从数据库获取区块头。
  • 通过方法 GetHeaderByNumber() 根据区块编号从数据库获取区块头。
  • 通过方法 GetHeaderByHash() 根据区块哈希从数据库获取区块头。
  • 通过方法 GetBlock() 根据区块哈希和编号从数据库获取区块。

2. type Engine interface

接口 Engine 是一种算法不可知的共识引擎。

  • 通过方法 Author() 获取挖出给定区块的账户的以太坊地址,如果共识引擎基于是签名算法的,则可能与区块头中的 coinbase 不同。
  • 通过方法 VerifyHeader() 检查区块头是否符合给定引擎的共识规则。可以在此处选择性地验证签名,或者通过方法 VerifySeal() 明确地验证签名。
  • 通过方法 VerifyHeaders() 与方法 VerifyHeader() 类似,但能够同时验证一批区块头。该方法返回一个退出通道以中止操作,并返回结果通道以获取异步验证结果(顺序是输入切片的顺序)
  • 通过方法 VerifyUncles() 验证给定区块的叔区块是否符合给定引擎的共识规则。
  • 通过方法 VerifySeal() 根据给定引擎的共识规则检查区块头中的签名是否有效。
  • 通过方法 Prepare() 根据特定引擎的共识规则初始化区块头的共识字段。更改以内联方式执行。
  • 通过方法 Finalize() 运行任何后事务状态修改(例如区块奖励)并组装最终的区块。注意:可以更新区块头和状态数据库以反映在最终确定时发生的任何共识规则(例如区块奖励)。
  • 通过方法 Seal() 为给定的输入区块生成新的签名请求,并将结果推送到给定的通道。
  • 通过方法 SealHash() 返回区块在被签名之前的哈希值。
  • 通过方法 CalcDifficulty() 是难度调整算法。它返回了新区块应该具有的难度。
  • 通过方法 API() 返回此共识引擎提供的 RPC API。
  • 通过方法 Close() 会终止共识引擎维护的所有后台线程。

3. PoW

基于 proof-of-work 的共识引擎。

  • Engine: 这里 Go 语言的继承语法,表明 PoW 包含 Engine 的所有接口方法。

  • 通过方法 Hashrate() 返回 PoW 共识引擎的当前挖矿哈希率。

Appendix B. 详细批注

1. type ChainReader interface

接口 ChainReader 定义了在区块头和/或叔区块验证期间访问本地区块链所需的一些方式。

(1) Config() *params.ChainConfig

方法 Config() 用于获取区块链的链配置信息。

(2) CurrentHeader() *types.Header

方法 CurrentHeader() 用于从本地链获取当前的区块头。

(3) GetHeader(hash common.Hash, number uint64) *types.Header

方法 GetHeader() 根据区块哈希和编号从数据库获取区块头。

(4) GetHeaderByNumber(number uint64) *types.Header

方法 GetHeaderByNumber() 根据区块编号从数据库获取区块头。

(5) GetHeaderByHash(hash common.Hash) *types.Header

方法 GetHeaderByHash() 根据区块哈希从数据库获取区块头。

(6) GetBlock(hash common.Hash, number uint64) *types.Block

方法 GetBlock() 根据区块哈希和编号从数据库获取区块。

2. type Engine interface

接口 Engine 是一种算法不可知的共识引擎。

(1) Author(header *types.Header) (common.Address, error)

方法 Author() 获取挖出给定区块的账户的以太坊地址,如果共识引擎基于是签名算法的,则可能与区块头中的 coinbase 不同。

实际上,对于 PoW 共识引擎来说,账户地址就是区块头中的 coinbase。但是对于 PoA 共识引擎来说,账户地址需要从区块头中的 extraData 中的最后 65 个字节的签名信息来恢复。

(2) VerifyHeader(chain ChainReader, header *types.Header, seal bool) error

方法 VerifyHeader() 检查区块头是否符合给定引擎的共识规则。可以在此处选择性地验证签名,或者通过方法 VerifySeal() 明确地验证签名。

(3) VerifyHeaders(chain ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error)

方法 VerifyHeaders() 与方法 VerifyHeader() 类似,但能够同时验证一批区块头。该方法返回一个退出通道以中止操作,并返回结果通道以获取异步验证结果(顺序是输入切片的顺序)

这个函数的返回结果 chan<- struct{} 需要特别留意,Go 语言往往用通道 chan<- struct{} 来表示退出协程。这种写法往往用于函数内部开启了新的协程执行相应逻辑,并通过此结果通道接收调用方的终止消息来终止此函数内部开启的新协程。

具体可以通过查看方法 Clique.VerifyHeaders() 来了解。在方法 Clique.VerifyHeaders() 内部,先定义了通道 abort := make(chan struct{}),并将其作为结果返回。由于 Go 有垃圾回收机制,因此 abort 使用的内存并不会泄漏。另外,开启了一个新的协程执行相应逻辑,并在新协程内部持续接收来自通道 abort 的终止消息,当接收到终止消息后立刻退出新协程。

(4) VerifyUncles(chain ChainReader, block *types.Block) error

方法 VerifyUncles() 验证给定区块的叔区块是否符合给定引擎的共识规则。

(5) VerifySeal(chain ChainReader, header *types.Header) error

方法 VerifySeal() 根据给定引擎的共识规则检查区块头中的签名是否有效。

(6) Prepare(chain ChainReader, header *types.Header) error

方法 Prepare() 根据特定引擎的共识规则初始化区块头的共识字段。更改以内联方式执行。

这里可能只会初始化区块头中的一部分字段,或者即使全部初始化了,有些字段的内容也会在方法 Finalize() 中得到调整。

??? 此方法初始化的区块头中已经包含了最终的签名信息、投票信息、授权签名者列表等吗,即 Clique 共识引擎相关的字段 Coinbase、Nonce、Extra、MixDigest 等都已经被最终确定下来了吗?

(7) Finalize(chain ChainReader, header *types.Header, state state.StateDB, txs []types.Transaction,

    uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error)

方法 Finalize() 运行任何后事务状态修改(例如区块奖励)并组装最终的区块。注意:可以更新区块头和状态数据库以反映在最终确定时发生的任何共识规则(例如区块奖励)。

方法 Finalize() 与方法 Prepare() 相比,不仅仅在于处理区块头,而是组装了最终的区块,包括:区块头、事务列表、收据列表、叔区块列表、几棵 MPT 树的根哈希等。

??? 此方法组装的区块是不是就代表本地节点最新挖出的区块呢?

(8) Seal(chain ChainReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error

方法 Seal() 为给定的输入区块生成新的签名请求,并将结果推送到给定的通道。

注意,该方法会立即返回并通过异步方式发送结果。根据共识算法,也可以返回多个结果。

此方法生成的区块是包含了签名的区块,表明这个时候区块已经是确定下来的了,因为整个区块头已经确定了,区块头确定表明区块头中的三棵 MPT 树(状态树、事务树、收据树)的根哈希值被确定,进而表明三棵树也已经被确定。同时,区块头中的叔区块列表的哈希值被确定,进而表明区块头中的叔区块信息也被确定下来。总之,这一步生成的区块是本地节点最新挖出的区块了。

(9) SealHash(header *types.Header) common.Hash

方法 SealHash() 返回区块在被签名之前的哈希值。

需要区分区块的哈希值和区块的签名哈希值。

  • 区块的哈希值,是由区块头中的字段生成的哈希值。哈希值中已经包含了区块的签名信息。
  • 区块的签名哈希值,是对区块头中 Extra 字段的最后 65 个字节不包含在内的哈希值,然后最后字段 Extra 的最后 65 个字节存放签名。哈希值中没有包含区块的签名信息。

(10) CalcDifficulty(chain ChainReader, time uint64, parent *types.Header) *big.Int

方法 CalcDifficulty() 是难度调整算法。它返回了新区块应该具有的难度。

(11) APIs(chain ChainReader) []rpc.API

方法 API() 返回此共识引擎提供的 RPC API。

(12) Close() error

方法 Close() 会终止共识引擎维护的所有后台线程。

3. PoW

基于 proof-of-work 的共识引擎。

  • Engine: 这里 Go 语言的继承语法,表明 PoW 包含 Engine 的所有接口方法。

(1) Hashrate() float64

方法 Hashrate() 返回 PoW 共识引擎的当前挖矿哈希率。

注意,此方法只有 PoW 共识引擎有,而 PoA 共识引擎并没有。

Reference

  1. https://github.com/ethereum/go-ethereum/blob/master/consensus/consensus.go

Contributor

  1. Windstamp, https://github.com/windstamp

你可能感兴趣的:(Go-ethereum 源码解析之 consensus/consensus.go)