Geth部署以太坊私鏈及基本操作
以太坊是一個為去中心化應用程序而生的全球開源平台。
在以太坊上,你可以通過編寫代碼管理數字資產、運行程序,更重要的是,這一切都不受地域限製。
Go Ethereum(Geth)是以太坊官方以Go語言編寫,完全開源。
為了方便學習,我們將先在本地通過Geth部署一套以太坊,便於我們以後的學習使用。
環境
我在GCP上麵開了一台2核4G內存100G硬盤的VPS用來做測試,再創建VPS的時候記得開啟允許HTTP流量、允許HTTPS流量,並允許全部端口訪問
- 查看係統信息
$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=20.04
DISTRIB_CODENAME=focal
DISTRIB_DESCRIPTION="Ubuntu 20.04.1 LTS"
- 當前操作用戶
$ whoami
root
- 更新係統到最新版並安裝所需軟件包
$ apt update && apt upgrade -y
- 關閉Firewalld(可選)
$ systemctl disable firewalld
- 重啟
$ reboot
安裝
我將在Ubuntu 20.04
下麵安裝geth,如果你是其他平台,可以參考官方的安裝指南,官方文檔支持多種方式多種平台的安裝
$ apt install software-properties-common vim -y
$ add-apt-repository -y ppa:ethereum/ethereum
$ apt update
$ apt install ethereum -y
查看幫助文檔
$ geth --help
查看geth版本
$ geth version
Geth
Version: 1.9.22-stable
Git Commit: c71a7e26a8b1e332bbf3262d88ba3ff32071456c
Architecture: amd64
Protocol Versions: [65 64 63]
Go Version: go1.15
Operating System: linux
GOPATH=
GOROOT=go
部署
- 創建geth數據存放目錄
$ mkdir /usr/local/etc/geth
- 創建賬戶
$ geth --datadir /usr/local/etc/geth/ account new
......
# 輸入密碼
Password:
Repeat password:
# 記住下麵的key
Your new key was generated
Public address of the key: 0xD31F14a7C839d352FE3EBD8745a0868Be042fBEa
......
- 準備創世區塊配置文件
$ vim /usr/local/etc/geth/genesis.json
{
"config":{
"chainId":9,
"homesteadBlock":0,
"eip150Block":0,
"eip155Block":0,
"eip158Block":0,
"byzantiumBlock":0,
"constantinopleBlock":0,
"petersburgBlock":0,
"istanbulBlock":0
},
"alloc":{
"0xD31F14a7C839d352FE3EBD8745a0868Be042fBEa":{
"balance":"1000000000000000000000000"
}
},
"coinbase":"0x0000000000000000000000000000000000000000",
"difficulty":"0x20000",
"extraData":"",
"gasLimit":"0x2fefd8",
"nonce":"0x0000000000000042",
"mixhash":"0x0000000000000000000000000000000000000000000000000000000000000000",
"parentHash":"0x0000000000000000000000000000000000000000000000000000000000000000",
"timestamp":"0x00"
}
參數說明
參數 | 說明 |
---|---|
config.chainId | 網絡ID,由於是私鏈,可以隨便設置 |
alloc | 預置賬號的餘額 |
coinbase | 礦工的默認賬戶 |
difficulty | 當前區塊的難度,如果難度過大,CPU挖礦就很難,這裏設置較小難度 |
extraData | 附加信息,隨便填 |
gasLimit | 該值設置對GAS的消耗總量限製,用來限製區塊能包含的交易信息總和,因為我們是私有鏈,所以填最大 |
nonce | 64位隨機數,用於挖礦 |
mixhash | 與nonce配合用於挖礦,由上一個區塊的一部分生成的hash |
parentHash | 上一個區塊的hash值,因為是創世塊,所以這個值是0 |
timestamp | 設置創世塊的時間戳 |
- 初始化
$ geth --nousb --datadir /usr/local/etc/geth init /usr/local/etc/geth/genesis.json
啟動
$ geth --nousb \
--identity "mychain1" \
--networkid 9 \
--datadir /usr/local/etc/geth \
--cache 2048 \
--allow-insecure-unlock \
--http \
--http.addr 0.0.0.0 \
--http.port 23456 \
--http.api admin,debug,web3,eth,txpool,personal,ethash,miner,net \
--http.corsdomain "*"
參數說明
參數 | 說明 |
---|---|
--nousb |
關閉USB硬件錢包 |
--identity "mychain1" |
自定義節點名稱 |
--networkid 9 |
設置networkid |
--datadir /usr/local/etc/geth |
數據和密鑰的數據目錄 |
--cache 2048 |
緩存大小,單位M |
--allow-insecure-unlock |
允許通過HTTP-RPC的解鎖account |
--http |
開啟HTTP-RPC服務 |
--http.addr 0.0.0.0 |
HTTP-RPC服務監聽的地址 |
--http.port 23456 |
HTTP-RPC服務監聽的端口 |
--http.api admin,debug,web3,eth,txpool,personal,ethash,miner,net |
開啟那些HTTP-RPC服務API |
--http.corsdomain "*" |
允許那些域名跨域鏈接,可以填寫域名列表,我這裏寫*則表示允許全部 |
通過systemd
管理geth進程
$ vim /etc/systemd/system/geth.service
[Unit]
Description=Geth
After=network.target nss-lookup.target
Wants=network-online.target
[Service]
Type=simple
User=root
CapabilityBoundingSet=CAP_NET_BIND_SERVICE CAP_NET_RAW
NoNewPrivileges=yes
WorkingDirectory=/usr/local/etc/geth
ExecStart=/bin/sh -c '/usr/bin/geth --nousb --identity "mychain1" --networkid 9 --datadir /usr/local/etc/geth --cache 2048 --allow-insecure-unlock --http --http.addr 0.0.0.0 --http.port 23456 --http.api admin,debug,web3,eth,txpool,personal,ethash,miner,net --http.corsdomain "*" >> /usr/local/etc/geth/geth.log 2>&1'
Restart=on-failure
RestartPreventExitStatus=23
[Install]
WantedBy=multi-user.target
- 重載配置文件
$ systemctl daemon-reload
- 啟動並開機啟動
$ systemctl enable --now geth
Created symlink /etc/systemd/system/multi-user.target.wants/geth.service → /etc/systemd/system/geth.service.
- 查看狀態
$ systemctl status geth
● geth.service - Geth
Loaded: loaded (/etc/systemd/system/geth.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2020-10-14 09:19:23 UTC; 3s ago
Main PID: 3231 (sh)
Tasks: 10 (limit: 4713)
Memory: 39.6M
CGroup: /system.slice/geth.service
├─3231 /bin/sh -c /usr/bin/geth --nousb --identity "mychain1" --networkid 9 --datadir /usr/local/etc/geth --cache 2048 --allow-insecure-unlock --http --http.addr 0.0.0.0 --http.port 23456 --http.api admin,debug,web3,eth,txpool,person
al,ethash,miner,net --http.corsdomain "*" >> /usr/local/etc/geth/geth.log 2>&1
└─3232 /usr/bin/geth --nousb --identity mychain1 --networkid 9 --datadir /usr/local/etc/geth --cache 2048 --allow-insecure-unlock --http --http.addr 0.0.0.0 --http.port 23456 --http.api admin,debug,web3,eth,txpool,personal,ethash,min
er,net --http.corsdomain *
Oct 14 09:19:23 geth systemd[1]: Started Geth.
- 查看日誌
$ tail -f /usr/local/etc/geth/geth.log
- 開放端口
如果你開啟了Firewalld
服務,還需要開放23456端口
以供外部訪問
$ firewall-cmd --add-port=23456/tcp --permanent
success
$ firewall-cmd --reload
success
基本操作
在接下來的操作中,我們將在客戶端通過Web3.py於與以太坊進行交互,Web3.py是用於與以太坊進行交互的Python庫
- 安裝pip包
$ pip3 install web3
- 進入python交互式程序
$ python3
- 基本操作
創建連接
>>> from web3 import Web3
>>> web3 = Web3(Web3.HTTPProvider("http://34.92.29.146:23456", request_kwargs={'timeout': 60}))
是否連接
>>> web3.isConnected()
True
查看客戶端版本
>>> web3.clientVersion
'Geth/mychain1/v1.9.22-stable-c71a7e26/linux-amd64/go1.15'
列出所有賬戶
>>> web3.eth.accounts
['0xD31F14a7C839d352FE3EBD8745a0868Be042fBEa']
創建賬戶,並返回賬戶地址
>>> web3.parity.personal.new_account('ansheng.me')
'0xAD606Fa02F3D66D749085B7f0D18Da3f85aC1f7F'
>>> web3.eth.accounts
['0xD31F14a7C839d352FE3EBD8745a0868Be042fBEa', '0xAD606Fa02F3D66D749085B7f0D18Da3f85aC1f7F']
查看賬戶餘額
>>> for address in web3.eth.accounts: print(address, web3.eth.getBalance(address))
...
0xD31F14a7C839d352FE3EBD8745a0868Be042fBEa 1000000000000000000000000
0xAD606Fa02F3D66D749085B7f0D18Da3f85aC1f7F 0
開始挖礦,1表示啟用的線程數
>>> web3.geth.miner.start(1)
開始挖礦之後我們需要查看日誌,直到出現以下內容才表示礦機已經開始工作,如果礦機不工作,下麵的轉賬等操作都是無法進行的,我這裏用了6分35秒,時間還是挺久的
$ tail -f /usr/local/etc/geth/geth.log
······
INFO [10-14|08:34:01.829] Generating DAG in progress epoch=0 percentage=99 elapsed=6m35.928s
INFO [10-14|08:34:01.832] Generated ethash verification cache epoch=0 elapsed=6m35.931s
INFO [10-14|08:34:03.645] Successfully sealed new block number=1 sealhash="286785…cb4fda" hash="383e18…dfadb5" elapsed=6m38.496s
INFO [10-14|08:34:03.645] mined potential block number=1 hash="383e18…dfadb5"
INFO [10-14|08:34:03.646] Commit new mining work number=2 sealhash="be3fbb…d5a1f4" uncles=0 txs=0 gas=0 fees=0 elapsed="166.792µs"
······
解鎖account,如果要進行交易操作,我們必須解鎖account,否則無法進行交易,web3.eth.coinbase
是預設餘額的賬戶
>>> web3.eth.coinbase
'0xD31F14a7C839d352FE3EBD8745a0868Be042fBEa'
>>> web3.geth.personal.unlock_account(web3.eth.coinbase, 'ansheng.me', 600) # (地址, 密碼, 解鎖時長)
True
估算一筆交易需要多少gas
>>> web3.eth.estimateGas({'to': '0xAD606Fa02F3D66D749085B7f0D18Da3f85aC1f7F','from': web3.eth.coinbase,'value': 100})
21000
進行轉賬,返回一個交易ID
>>> web3.eth.sendTransaction({'to': '0xAD606Fa02F3D66D749085B7f0D18Da3f85aC1f7F','from': web3.eth.coinbase,'value': 100})
HexBytes('0x87967cc25217c145e40a11818544d576365fbac944f16e42b2ee75280163f2d7')
查看交易信息,如果發現blockHash為None,有可能是礦機還沒有啟動或者礦機還沒有處理,等待一下在查詢即可
>>> web3.eth.getTransaction('0x87967cc25217c145e40a11818544d576365fbac944f16e42b2ee75280163f2d7')
AttributeDict({'blockHash': HexBytes('0x7e40f68be09961e6ea2767c291b5fccfbdc6de5dae5ee32593b61cdfe6d43613'), 'blockNumber': 30, 'from': '0xD31F14a7C839d352FE3EBD8745a0868Be042fBEa', 'gas': 121000, 'gasPrice': 1000000000, 'hash': HexBytes('0x87967cc25217c145e40a11818544d576365fbac944f16e42b2ee75280163f2d7'), 'input': '0x', 'nonce': 1, 'to': '0xAD606Fa02F3D66D749085B7f0D18Da3f85aC1f7F', 'transactionIndex': 0, 'value': 100, 'v': 53, 'r': HexBytes('0x78b85a707c1174e8bd6bb92f8f8a08aaa3d05df62d83fef4c424548fb841a160'), 's': HexBytes('0x1db825aae194940277335c113336cd8f27ef8b9a83cd705cbb27460e681b6757')})
查看收據
>>> web3.eth.getTransactionReceipt('0x87967cc25217c145e40a11818544d576365fbac944f16e42b2ee75280163f2d7')
AttributeDict({'blockHash': HexBytes('0x7e40f68be09961e6ea2767c291b5fccfbdc6de5dae5ee32593b61cdfe6d43613'), 'blockNumber': 30, 'contractAddress': None, 'cumulativeGasUsed': 21000, 'from': '0xD31F14a7C839d352FE3EBD8745a0868Be042fBEa', 'gasUsed': 21000, 'logs': [], 'logsBloom': HexBytes('0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'), 'status': 1, 'to': '0xAD606Fa02F3D66D749085B7f0D18Da3f85aC1f7F', 'transactionHash': HexBytes('0x87967cc25217c145e40a11818544d576365fbac944f16e42b2ee75280163f2d7'), 'transactionIndex': 0})
查詢賬戶下麵的交易筆數
>>> web3.eth.getTransactionCount('0xAD606Fa02F3D66D749085B7f0D18Da3f85aC1f7F')
0
>>> web3.eth.getTransactionCount(web3.eth.coinbase)
1
查看最新塊編號
>>> web3.eth.blockNumber
76
查看某個區塊信息
>>> web3.eth.getBlock(70)
AttributeDict({'difficulty': 133575, 'extraData': HexBytes('0xd683010916846765746886676f312e3135856c696e7578'), 'gasLimit': 3363639, 'gasUsed': 0, 'hash': HexBytes('0x89ca2885f01d1d60114784cbb7e60c98992bfd53a4fb2994554523f6507408bd'), 'logsBloom': HexBytes('0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'), 'miner': '0xD31F14a7C839d352FE3EBD8745a0868Be042fBEa', 'mixHash': HexBytes('0xda2bba8feeda0d8ecb77c003efd0064c43712bb8d2b8aa962a4cb3823c6e8bf0'), 'nonce': HexBytes('0x3c6269471b595232'), 'number': 70, 'parentHash': HexBytes('0xf20363ee879612c43cf7730e0ba8d98360401288ea000f056037b21593e2c881'), 'receiptsRoot': HexBytes('0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421'), 'sha3Uncles': HexBytes('0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'), 'size': 534, 'stateRoot': HexBytes('0x66a24b0a9a45905371a4ae5dd9f13531a8a45c02fdef848a0e756204abc816e5'), 'timestamp': 1602668396, 'totalDifficulty': 9360476, 'transactions': [], 'transactionsRoot': HexBytes('0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421'), 'uncles': []})
若要查詢最近的一個區塊信息,可以通過以下方式
>>> web3.eth.getBlock('latest')
檢查賬戶餘額,因為礦機一直在工作,所以0xD31F14a7C839d352FE3EBD8745a0868Be042fBEa
賬戶餘額會增加
>>> for address in web3.eth.accounts: print(address, web3.eth.getBalance(address))
...
0xD31F14a7C839d352FE3EBD8745a0868Be042fBEa 1000195999999999999999800
0xAD606Fa02F3D66D749085B7f0D18Da3f85aC1f7F 100
停止挖礦
>>> web3.geth.miner.stop()
相關說明:
1、VIP會員無限製任意下載,免積分。立即前往開通>>
2、下載積分可通過日常 簽到、綁定郵箱 以及 積分兌換 等途徑獲得!
3、本站資源大多存儲在雲盤,如出現鏈接失效請評論反饋,如有密碼,均為:www.ipipn.com。
4、所有站內資源僅供學習交流使用。未經原版權作者許可,禁止用於任何商業環境,否則後果自負。為尊重作者版權,請購買正版作品。
5、站內資源來源於網絡公開發表文件或網友分享,如侵犯您的權益,請聯係管理員處理。
6、本站提供的源碼、模板、軟件工具等其他資源,都不包含技術服務,請大家諒解!
7、源碼、模板等資源會隨著技術、壞境的升級而存在部分問題,還請慎重選擇。
PS.源碼均收集自網絡,如有侵犯閣下權益,請發信件至: admin@ipipn.com .
源站網 » Geth部署以太坊私鏈及基本操作