保证您更舒适的阅读体验和持续更新,本文已转移至我的个人博客,请您访问http://anemone.top/以确保您阅读的文章是最新版本,以及看到新的文章
目前网上写的私有链搭建的步骤均没有介绍如何初始化账户及初始金额的问题,本文记录一下使用Geth构造一个私有链的完整步骤。
0x01 创建新账户
如果需要在私有链上初始化一些账户以及给这些账户发放一定数量的以太币,就需要新建一些账户。使用account new
命令新建账户:
$ mkdir testchain # 新建一个文件夹放置数据
$ geth --datadir "./testchain" account new # 新建账户,需要设置密码
WARN [10-23|20:08:07] No etherbase set and no accounts found as default
Your new account is locked with a password. Please give a password. Do not forget this password.
Passphrase:
Repeat passphrase:
Address: {28c67f4a957fcd814effce00863eb3aeb9e9884a}
$ ls ./testchain
keystore
$ ls ./testchain/keystore/ # 账户文件
UTC--2018-10-23T12-08-15.951611300Z--28c67f4a957fcd814effce00863eb3aeb9e9884a
0x02 编写配置文件
在testchain
目录下新建genesis.json
文件,内容如下:
{
"config":{
"homesteadBlock":0
},
"nonce": "0x0000000000000042",
"timestamp": "0x0",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"extraData": "0x",
"gasLimit": "0x8000000000000000",
"difficulty": "0x02",
"mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"coinbase": "0x28c67f4a957fcd814effce00863eb3aeb9e9884a",
"alloc": {
"0x28c67f4a957fcd814effce00863eb3aeb9e9884a":{"balance":"2000000000000000000000000"}
}
}
其中,coinbase
指挖矿的报酬发送到的账户,alloc
指初始化账户及其初始金额,注意这里的地址都需要是新建的账户;difficulty
指挖矿难度,gasLimit
指一个区块中的Gas限制,即打包区块时所有的交易Gas花费不得超过该值。
0x03 使用命令构造创始块
若文件夹下有旧区块信息需要先删除:
geth --datadir "./testchain" removedb
使用genesis.json创建创始块
geth --datadir "./testchain" init ./testchain/genesis.json
0x04 启动节点
创始块完成后可以使用geth启动节点并开始挖矿了,具体命令如下:
geth --fast --identity "TestNode0" --rpc -rpcaddr "0.0.0.0" --rpcport "8545" --rpccorsdomain "*" --port "30303" --nodiscover --rpcapi "db,eth,net,web3,miner,net,personal,net,txpool,admin,debug" --networkid 1900 --datadir "./testchain" --nat "any" --mine --minerthreads "1"
其中一些重要参数的含义为:
--identity:节点名称
--rpc -rpcaddr "0.0.0.0" --rpcport "8545":节点开放rpc连接,监听地址为0.0.0.0:8545
--rpcapi:rpc提供的api类型
--rpccorsdomain:rpc允许接入本节点的网段,分号隔开
--port:节点间联系使用的端口号
--networkid:区块链的网络号,唯一的标识一条区块链,比如说1=主链, 3=Ropsten测试链, 4=Rinkeby测试链
--mine --minerthreads 1:启动挖矿,开放1个线程
启动节点后,一条私有链就可以使用了,即可以连接该节点发布智能合约,或者发起新的交易。
例如:连接节点,查看账户
$ geth attach http://localhost:8545
Welcome to the Geth JavaScript console!
instance: Geth/TestNode0/v1.7.0-unstable/linux-amd64/go1.10.1
coinbase: 0x28c67f4a957fcd814effce00863eb3aeb9e9884a
at block: 13 (Tue, 23 Oct 2018 20:55:04 DST)
datadir: /home/anemone/testchain
modules: admin:1.0 debug:1.0 eth:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0
> eth.accounts
["0x28c67f4a957fcd814effce00863eb3aeb9e9884a"]
>