一、前言
通过前面章节学习了以太坊的基本架构之后,我们通过自己搭建一个单节点,并覆盖以太坊主要流程来讲解代码。在这一节,你将学会:如何初始化创世区块
二、代码研究
2.1 准备工作
-
以太坊源码 V 1.8.0
-
golang 1.9+
-
windows 系统下 goland 2018+
本系列文章主要是研究以太坊源码,所以以太坊的编译工作不详细展开,有需要的可以参考这篇文章。
2.2 genesis.json 文件
假设你已经在 goland 正确设置好了项目,那么下面使用一个示例创世文件初始化自己的私有网络创世块。
{
"config": {
"chainId": 399,
"homesteadBlock": 0,
"eip150Block": 0,
"eip155Block": 0,
"eip158Block": 0,
"byzantiumBlock": 0,
"constantinopleBlock": 0,
"petersburgBlock": 0
},
"alloc": {
"0x0000000000000000000000000000000000000001": {
"balance": "0x84595161401484a000000"
},
},
"coinbase": "0x0000000000000000000000000000000000000000",
"difficulty": "0x20000",
"extraData": "",
"gasLimit": "0x2fefd8",
"nonce": "0x000000000000ff42",
"mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"timestamp": "0x00"
}
-
保存创世文件
在项目目录下,src 同级目录新建一个测试数据文件夹testdata
,将上面的内容保存到创世文件genesis.json
中,并存放在 testdata 文件夹。 -
准备配置运行参数
接着,使用 goland 打开 Ethereum-V1.8.0 的工程,找到go-ethereum/cmd/geth
文件夹 - 右键 - 选择Create Run Configuration
- 点击go build github.com/...
。 -
配置运行参数
点击后,在配置菜单中Program arguments
栏设置--datadir=./testdata init ./testdir/genesis.json
,点击 “OK”。保存配置。 -
设置断点,开始调试。
然后按住组合键Ctrl+Shift+F
查找initGenesis
函数。在函数入口设置断点。点击debug 按钮,程序停在断点处。
接下来,就看下 initGenesis
函数到底干了啥。
2.3 initGeness 函数
initGenesis 函数在命令行参数中设置 “init” 命令时被调用,用给定 Json 格式的创世文件初来始化创世块,如果失败,创世文件将不写入创世块。
// initGenesis will initialise the given JSON format genesis file and writes it as
// the zero'd block (i.e. genesis) or will fail hard if it can't succeed.
func initGenes