概要
geth 是以太坊的官方 golang 客戶端. 通過 geth 的使用可以直觀的了解以太坊, 乃至區塊鏈的運作.
下面, 通過 geth 來構造一次搭建私鏈, 創建賬戶, 挖礦, 交易的流程.
搭建私鏈
做實驗, 搭建私鏈是第一步, 如果直接在 ETH 公鏈上實驗的話, 會消耗真實的以太幣, 而且在真實的公鏈上, 個人的電腦幾乎不可能挖到礦的.
通過 geth 搭建私鏈很簡單, 首先需要定義創世區塊, 參考: https://github.com/ethereum/go-ethereum/wiki/Private-network
genesis.json:
{
"config": {
"chainId": 100,
"homesteadBlock":0,
"eip155Block":0,
"eip158Block":0
},
"nonce": "0x0000000000000042",
"timestamp": "0x0",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"gasLimit": "0x80000000",
"difficulty": "0x1",
"mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"coinbase": "0x3333333333333333333333333333333333333333",
"alloc": { }
}
配置之后, 啟動
mkdir geth-test
cd geth-test
geth --datadri ./data init genesis.json
創建賬戶
創建賬戶很簡單, 登錄 geth 的 javascript console
geth --datadir ./data --networkid 100 console
其中 networkid 就是 genesis.json 中配置的 chainId
登錄之后:
> personal.newAccount() # 創建新的賬戶
> eth.accounts # 查看目前有哪些賬戶
挖礦
開始挖礦很簡單, 接着在上面的 console 中操作
> miner.start()
等待幾分鍾之后, 再
> miner.stop()
我的測試機器 2CPU 8G 內存, 大概挖了 5 分鍾, 挖到的 eth 如下:
> acc0 = eth.accounts[0] # 這個私鏈上目前只有一個測試賬號
> eth.getBalance(acc0) # 這里使用 wei 作為單位
2.46e+21
> web3.fromWei(eth.getBalance(acc0), 'ether') # 相當於 2460 個以太幣
2460
注 私鏈上挖到的以太幣是不能在公鏈交易的, 這個是用來測試用的, 不然就發了 😃
交易
挖礦很簡單, 交易也簡單, 為了交易, 我們還需要再創建一個賬戶
> personal.newAccount()
> eth.accounts
["0xd4b42869954689395e502daa6dd9a02aa34dbaff", "0x500aaa5b196741a4c768fa972b5f16a7e0c9c1e5"]
> acc0 = eth.accounts[0]
> acc1 = eth.accounts[1]
> web3.fromWei(eth.getBalance(acc0), 'ether') # acc0 的余額
2460
> web3.fromWei(eth.getBalance(acc1), 'ether') # acc1 的余額
0
> val = web3.toWei(1) # 准備轉賬的金額 1 eth
"1000000000000000000"
> eth.sendTransaction({from: acc0, to: acc1, value: val}) # 執行轉賬, 如果這里出現錯誤, 提示賬戶被鎖定的話, 解鎖賬戶
> personal.unlockAccount(acc0) # 解鎖時, 輸入創建賬戶時的密碼
Unlock account 0xd4b42869954689395e502daa6dd9a02aa34dbaff
Password:
true
> eth.sendTransaction({from: acc0, to: acc1, value: val}) # 再次轉賬, 這次應該能夠成功, 如果第一次就成功的話, 不需要這步
# 再次查看余額, 發現2個賬戶的余額沒變
> web3.fromWei(eth.getBalance(acc0), 'ether')
2460
> web3.fromWei(eth.getBalance(acc1), 'ether')
0
# 余額沒變, 是因為我們前面已經停止挖礦(miner.stop()), 沒有礦工來確認這筆交易了
> miner.start()
> miner.stop() # 啟動10來秒左右再 stop
# 再次查看余額, acc1 賬戶上多了 1 個以太幣, 但是 acc0的以太幣不減反增, 這是因為剛才的挖礦產生的以太幣以及交易手續費都給了 acc0
# 這里的挖礦時如果不指定賬號, 默認會把挖到的以太幣給 eth.accounts 中的第一個賬號
> web3.fromWei(eth.getBalance(acc0), 'ether')
2494
> web3.fromWei(eth.getBalance(acc1), 'ether')
1