區塊鏈-私鏈建立與智慧合約部署實踐
準備:
ECS+ubuntu 16.0+go+go-ethereum
1.創世鏈節點:
{
"config": {
"chainId": 12345,
"homesteadBlock":0,
"eip155Block":0,
"eip158Block":0
},
“coinbase”:”0x0000000000000000000000000000000000000000”,
“difficulty”:”0x400”,
“extraData”:”0x123456”,
“gasLimit”:”0xffffffff”,
“nonce”:”0x0000000000000042”,
“mixhash”:”0x0000000000000000000000000000000000000000000000000000000000000000”, “parentHash”: “0x0000000000000000000000000000000000000000000000000000000000000000”,
“timestamp”:”0x00”,
“alloc”: { }
}
欄位講解:
mixhash:與nonce配合用於挖礦,由上一個區塊的一部分生成的hash。注意他和nonce的設定需要滿足以太坊
nonce: nonce就是一個64位隨機數,用於挖礦,注意他和mixhash的設定需要滿足以太坊的Yellow paper,
difficulty: 設定當前區塊的難度,如果難度過大,cpu挖礦就很難,這裡設定較小難度
alloc: 用來預置賬號以及賬號的以太幣數量,因為私有鏈挖礦比較容易,所以我們不需要預置有幣的賬號,需要的時候自己建立即可以。
coinbase: 礦工的賬號,隨便填
timestamp: 設定創世塊的時間戳
parentHash: 上一個區塊的hash值,因為是創世塊,所以這個值是0
extraData: 附加資訊,隨便填,可以填你的個性資訊,必須為十六進位制的偶位字串
gasLimit: 該值設定對GAS的消耗總量限制,用來限制區塊能包含的交易資訊總和,因為我們是私有鏈,所以填最大。
2.geth –datadir “./” init genesis.json 建立創世節點
3.geth –datadir “./” –nodiscover console 2>>geth.log 新建私有鏈,且日誌輸出到geth.log
4.啟動節點 進入控制檯:geth –datadir ./ –networkid 314590 –ipcdisable –port 61910 –rpcport 8200 console
- tail -f geth.log 動態展示geth.log日誌更新資訊
6.eth.accounts 展示使用者陣列
7.acc0=eth.accounts[0]
8.eth.getBalance(acc0)
9.執行miner.start()時,geth console返回null。
解決方案1:先執行personal.listAccounts檢視當前節點是否存在賬號地址,再用eth.coinbase檢視是否設定了coinbase賬戶地址,如果沒有則使用miner.setEtherbase(eth.accounts[0])設定coinbase地址。再啟動miner.start()
10.轉賬:eth.sendTransaction({from:”address1”,to:”address2”,gas:31000,gasPrice:web3.toWei(300,’gwei’),value:1})
console打印出fullhash,根據hashid去檢視交易狀態
11.txpool.status 檢視礦池中未打包交易
{
pending:1,
queued:0
}
- eth.getBlock(number) 檢視交易區塊資訊
13.eth.getTransaction(fullhash)
如果執行了交易但檢視txpool.status時,還是存在未交易資料,先查查是否在挖礦中,挖礦中才能進行區塊更新
14.再檢視txpool.status
{
pending:0,
queued:0
}
15.部署智慧合約:
線上編寫編譯solc程式碼
Hello World程式碼:
pragma solidity ^0.4.18; contract hello { string greeting; function hello(string _greeting) public { greeting = _greeting; } function say() constant public returns (string) { return greeting; } }
點選Details獲取部署程式碼,替換變數字串 var _greeting = “Hello World”;
修改後,直接拷貝到geth console控制檯,點選回車,返回Contract mined! address:XXXXX transactionHash:XXXXX
(注意需要保持挖礦狀態才能部署上去,同時記得unlock操作的賬號,personal.unlockAccount(address,’XXX’))
執行合約:
hello.say()
“Hello World”
等待解決問題:
1.ssh伺服器重連時進入geth控制檯報錯,需要如何解決,Fatal: Error starting protocol stack: datadir already used by another process
學習資料: