下载和安装 Geth
访问 https://geth.ethereum.org/downloads/
添加到环境变量。
创建数据目录
PS C:\Repo\mygeth> mkdir data
PS C:\Repo\mygeth> geth account new --datadir data
途中会输入密码。然后得到一个初始地址
Public address of the key: 0x04529c3bABFA852f99bADdB873731A3410aCcBE9
Path of the secret key file: data\keystore\UTC--2021-12-13T07-18-54.250642000Z--04529c3babfa852f99baddb873731a3410accbe9
创建 Genesis Block
私有网络,通过 genesis.json
配置。注意几个字段:
config
:决定了以太坊平台特性的启用状态。gasLimit
:初始块的 gasLimitalloc
:初始 ETH 分配
在以太坊区块链上执行写入操作都需要支付 gas ,以太坊定义了货币是 1ETH, 且 1 ETH = 1e18 Wei。Wei 是其中的最小额,在整个工作中,发送代币、调用合约都要支付 gas,且以 Wei 作为单位来计算。1 Gwei = 1e9 Wei。详见以太坊黄皮书。 gasPrice 是以太坊内计算消耗 1 个 gas 对应多少 Gwei 的标准量,单位是 Gwei gasLimit 是消耗 gas 的上限单位。在完成交易中最多使用多少个 gas,默认标准的 ETH 转账是 21000 个单位的 Gas。但是更复杂的代码写入需要消耗更多的 gas limit. gasLimit 不够矿工消耗会导致代码执行中断
配置文件的写法取决于选择的共识算法。
共识算法
以太坊支持两种共识算法 1:
- clique 实现 PoA(权威证明)共识
- ethash 实现 PoW(工作量证明)共识
其中 ethash 是默认的。
Ethash 示例
genesis.json
{
"config": {
"chainId": 15,
"homesteadBlock": 0,
"eip150Block": 0,
"eip155Block": 0,
"eip158Block": 0,
"byzantiumBlock": 0,
"constantinopleBlock": 0,
"petersburgBlock": 0,
"ethash": {}
},
"difficulty": "1",
"gasLimit": "8000000",
"alloc": {
"04529c3babfa852f99baddb873731a3410accbe9": { "balance": "300000" },
"f41c74c9ae680c1aa78f42e5647a62f353b7bdde": { "balance": "400000" }
}
}
创建一个使用此 Genesis Block 的区块链节点:
geth init --datadir data genesis.json
之后的运行都通过下面的命令,从而从之前定义的地方继续:
geth --datadir data --networkid 15
安排硬分叉
为了启用新特性,必须硬分叉。假设当前位于 35421
,我们打算从 40000
开始 Istanbul Fork,则配置如下:
{
"config": {
// ...
"istanbulBlock": 40000,
// ...
},
// ...
}
并运行
geth init --datadir data genesis.json
网络设置
bootstrap 节点:在任何结点都可以用作入口点,建议使用特定结点作为会合结点,从而其它节点可以加入。这样的节点称为 bootstrap 节点。
启用 30303
端口 (TCP && UDP)
设置 ip:
geth --datadir data --networkid 15 --nat extip:172.16.254.4
之后需要连接进来。
对于 Linux,新开终端执行:
geth attach data/geth.ipc --exec admin.nodeInfo.enr
对于 Windows:
geth attach ipc:\\.\pipe\geth.ipc
这样可以进入 JS Console
REPL
在交互界面,可执行一些命令。
> eth.accounts
["0x04529c3babfa852f99baddb873731a3410accbe9"]
> personal.newAccount("123456")
"0xacc9150f4d8c5664bd98a51c3aca63f5b5938fd5"
> miner.start()
null
> miner.stop()
true
> user1=eth.accounts[0]
"0xacc9150f4d8c5664bd98a51c3aca63f5b5938fd5"
> user2=eth.accounts[1]
"0xa6b519c11b19fd73d08262a8e964ccda3509c015"
> eth.getBalance(user1)
0
> eth.getBalance(user2)
0
转账(需要先解锁):
web3.personal.unlockAccount(web3.personal.listAccounts[0], null, 60)
eth.sendTransaction({from: "0xceee57f2b700c2f37d1476a7974965e149fce2d4",to: "0x7aa4a14286a25e3a275d7a122c23dc3c107a636a", value: "74000000000000000"})
其它
为了直观观察区块链状态,可以安装 区块链浏览器
官方教程,可以访问:https://ethereum.org/zh/developers/tutorials/
参考
https://geth.ethereum.org/docs/interface/private-network