上篇文章,我們編譯了go-ethereum的源代碼,大家體驗了一下開發環境,使用了開發工具,我們從這章開始,進入ETH的學習階段,我會在每章完成后,給大家提出一些思考,幫助大家,
1、搭建前準備
如果是使用虛擬機上安裝的 Ubuntu,請在虛擬機中打開終端,安裝SSH,
命令如下:
sudo apt-get install ssh
Windows上,安裝 SSH終端工具MobaXterm Professional Edition,自己安裝,MAC系統,自帶遠程工具,或者選擇自己喜歡的遠程工具如putty或者其他,
編輯器 Visual Studio Code ,可以安裝在windows環境下或者MAC下,如果想通過Visual Studio Code操作ubuntu下的檔案,請在Visual Studio Code安裝拓展插件,
點擊左側狀態欄”擴展“ 輸入 Remote Development 點擊安裝,安裝后,會有檔案,詳細介紹如何連接遠程主機,及操作檔案,如下圖:

Ubuntu下安裝命令
上篇文章,我們通過編譯源代碼的方式,自己編譯了geth客戶端,如果僅僅是使用ETH網路,我們可以只安裝ETH客戶端即可,根據自己場景需要決定,
命令如下:
sudo apt-get install software-properties-common
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo add-apt-repository -y ppa:ethereum/ethereum-dev
sudo apt-get update
sudo apt-get install ethereum
安裝測驗
安裝好后,我們輸入如下命令:
geth -h
顯示如下:
NAME:
geth - the go-ethereum command line interface
Copyright 2013-2019 The go-ethereum Authors
USAGE:
geth [options] command [command options] [arguments...]
VERSION:
1.9.19-stable-3e064192
COMMANDS:
account Manage accounts
attach Start an interactive JavaScript environment (connect to node)
console Start an interactive JavaScript environment
copydb Create a local chain from a target chaindata folder
dump Dump a specific block from storage
dumpconfig Show configuration values
dumpgenesis Dumps genesis block JSON configuration to stdout
export Export blockchain into file
export-preimages Export the preimage database into an RLP stream
import Import a blockchain file
import-preimages Import the preimage database from an RLP stream
init Bootstrap and initialize a new genesis block
inspect Inspect the storage size for each type of data in the database
js Execute the specified JavaScript files
license Display license information
makecache Generate ethash verification cache (for testing)
makedag Generate ethash mining DAG (for testing)
removedb Remove blockchain and state databases
retesteth Launches geth in retesteth mode
show-deprecated-flags Show flags that have been deprecated
version Print version numbers
wallet Manage Ethereum presale wallets
help, h Shows a list of commands or help for one command
ETHEREUM OPTIONS:
--config value TOML configuration file
--datadir value Data directory for the databases and keystore (default: "/home/cuijb/.ethereum")
--datadir.ancient value Data directory for ancient chain segments (default = inside chaindata)
--keystore value Directory for the keystore (default = inside the datadir)
--nousb Disables monitoring for and managing USB hardware wallets
--pcscdpath value Path to the smartcard daemon (pcscd) socket file (default: "/run/pcscd/pcscd.comm")
--networkid value Network identifier (integer, 1=Frontier, 3=Ropsten, 4=Rinkeby, 5=G?rli) (default: 1)
--goerli G?rli network: pre-configured proof-of-authority test network
--rinkeby Rinkeby network: pre-configured proof-of-authority test network
--yolov1 YOLOv1 network: pre-configured proof-of-authority shortlived test network.
--ropsten Ropsten network: pre-configured proof-of-work test network
--syncmode value Blockchain sync mode ("fast", "full", or "light") (default: fast)
--exitwhensynced Exits after block synchronisation completes
--gcmode value Blockchain garbage collection mode ("full", "archive") (default: "full")
--txlookuplimit value Number of recent blocks to maintain transactions index by-hash for (default = index all blocks) (default: 0)
--ethstats value Reporting URL of a ethstats service (nodename:secret@host:port)
--identity value Custom node name
--lightkdf Reduce key-derivation RAM & CPU usage at some expense of KDF strength
--whitelist value Comma separated block number-to-hash mappings to enforce (<number>=<hash>)
LIGHT CLIENT OPTIONS:
--light.serve value Maximum percentage of time allowed for serving LES requests (multi-threaded processing allows values over 100) (default: 0)
--light.ingress value Incoming bandwidth limit for serving light clients (kilobytes/sec, 0 = unlimited) (default: 0)
--light.egress value Outgoing bandwidth limit for serving light clients (kilobytes/sec, 0 = unlimited) (default: 0)
--light.maxpeers value Maximum number of light clients to serve, or light servers to attach to (default: 100)
--ulc.servers value List of trusted ultra-light servers
--ulc.fraction value Minimum % of trusted ultra-light servers required to announce a new head (default: 75)
--ulc.onlyannounce Ultra light server sends announcements only
--light.nopruning Disable ancient light chain data pruning
DEVELOPER CHAIN OPTIONS:
--dev Ephemeral proof-of-authority network with a pre-funded developer account, mining enabled
--dev.period value Block period to use in developer mode (0 = mine only if transaction pending) (default: 0)
ETHASH OPTIONS:
--ethash.cachedir value Directory to store the ethash verification caches (default = inside the datadir)
--ethash.cachesinmem value Number of recent ethash caches to keep in memory (16MB each) (default: 2)
--ethash.cachesondisk value Number of recent ethash caches to keep on disk (16MB each) (default: 3)
--ethash.cacheslockmmap Lock memory maps of recent ethash caches
--ethash.dagdir value Directory to store the ethash mining DAGs (default: "/home/cuijb/.ethash")
--ethash.dagsinmem value Number of recent ethash mining DAGs to keep in memory (1+GB each) (default: 1)
--ethash.dagsondisk value Number of recent ethash mining DAGs to keep on disk (1+GB each) (default: 2)
--ethash.dagslockmmap Lock memory maps for recent ethash mining DAGs
TRANSACTION POOL OPTIONS:
--txpool.locals value Comma separated accounts to treat as locals (no flush, priority inclusion)
--txpool.nolocals Disables price exemptions for locally submitted transactions
--txpool.journal value Disk journal for local transaction to survive node restarts (default: "transactions.rlp")
--txpool.rejournal value Time interval to regenerate the local transaction journal (default: 1h0m0s)
--txpool.pricelimit value Minimum gas price limit to enforce for acceptance into the pool (default: 1)
--txpool.pricebump value Price bump percentage to replace an already existing transaction (default: 10)
--txpool.accountslots value Minimum number of executable transaction slots guaranteed per account (default: 16)
--txpool.globalslots value Maximum number of executable transaction slots for all accounts (default: 4096)
--txpool.accountqueue value Maximum number of non-executable transaction slots permitted per account (default: 64)
--txpool.globalqueue value Maximum number of non-executable transaction slots for all accounts (default: 1024)
--txpool.lifetime value Maximum amount of time non-executable transaction are queued (default: 3h0m0s)
PERFORMANCE TUNING OPTIONS:
--cache value Megabytes of memory allocated to internal caching (default = 4096 mainnet full node, 128 light mode) (default: 1024)
--cache.database value Percentage of cache memory allowance to use for database io (default: 50)
--cache.trie value Percentage of cache memory allowance to use for trie caching (default = 15% full mode, 30% archive mode) (default: 15)
--cache.trie.journal value Disk journal directory for trie cache to survive node restarts (default: "triecache")
--cache.trie.rejournal value Time interval to regenerate the trie cache journal (default: 1h0m0s)
--cache.gc value Percentage of cache memory allowance to use for trie pruning (default = 25% full mode, 0% archive mode) (default: 25)
--cache.snapshot value Percentage of cache memory allowance to use for snapshot caching (default = 10% full mode, 20% archive mode) (default: 10)
--cache.noprefetch Disable heuristic state prefetch during block import (less CPU and disk IO, more time waiting for data)
ACCOUNT OPTIONS:
--unlock value Comma separated list of accounts to unlock
--password value Password file to use for non-interactive password input
--signer value External signer (url or path to ipc file)
--allow-insecure-unlock Allow insecure account unlocking when account-related RPCs are exposed by http
API AND CONSOLE OPTIONS:
--ipcdisable Disable the IPC-RPC server
--ipcpath value Filename for IPC socket/pipe within the datadir (explicit paths escape it)
--http Enable the HTTP-RPC server
--http.addr value HTTP-RPC server listening interface (default: "localhost")
--http.port value HTTP-RPC server listening port (default: 8545)
--http.api value API's offered over the HTTP-RPC interface
--http.corsdomain value Comma separated list of domains from which to accept cross origin requests (browser enforced)
--http.vhosts value Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (default: "localhost")
--ws Enable the WS-RPC server
--ws.addr value WS-RPC server listening interface (default: "localhost")
--ws.port value WS-RPC server listening port (default: 8546)
--ws.api value API's offered over the WS-RPC interface
--ws.origins value Origins from which to accept websockets requests
--graphql Enable GraphQL on the HTTP-RPC server. Note that GraphQL can only be started if an HTTP server is started as well.
--graphql.corsdomain value Comma separated list of domains from which to accept cross origin requests (browser enforced)
--graphql.vhosts value Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (default: "localhost")
--rpc.gascap value Sets a cap on gas that can be used in eth_call/estimateGas (0=infinite) (default: 25000000)
--rpc.txfeecap value Sets a cap on transaction fee (in ether) that can be sent via the RPC APIs (0 = no cap) (default: 1)
--jspath loadScript JavaScript root path for loadScript (default: ".")
--exec value Execute JavaScript statement
--preload value Comma separated list of JavaScript files to preload into the console
NETWORKING OPTIONS:
--bootnodes value Comma separated enode URLs for P2P discovery bootstrap
--bootnodesv4 value Comma separated enode URLs for P2P v4 discovery bootstrap (light server, full nodes) (deprecated, use --bootnodes)
--bootnodesv5 value Comma separated enode URLs for P2P v5 discovery bootstrap (light server, light nodes) (deprecated, use --bootnodes)
--discovery.dns value Sets DNS discovery entry points (use "" to disable DNS)
--port value Network listening port (default: 30303)
--maxpeers value Maximum number of network peers (network disabled if set to 0) (default: 50)
--maxpendpeers value Maximum number of pending connection attempts (defaults used if set to 0) (default: 0)
--nat value NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>) (default: "any")
--nodiscover Disables the peer discovery mechanism (manual peer addition)
--v5disc Enables the experimental RLPx V5 (Topic Discovery) mechanism
--netrestrict value Restricts network communication to the given IP networks (CIDR masks)
--nodekey value P2P node key file
--nodekeyhex value P2P node key as hex (for testing)
MINER OPTIONS:
--mine Enable mining
--miner.threads value Number of CPU threads to use for mining (default: 0)
--miner.notify value Comma separated HTTP URL list to notify of new work packages
--miner.gasprice value Minimum gas price for mining a transaction (default: 1000000000)
--miner.gastarget value Target gas floor for mined blocks (default: 8000000)
--miner.gaslimit value Target gas ceiling for mined blocks (default: 8000000)
--miner.etherbase value Public address for block mining rewards (default = first account) (default: "0")
--miner.extradata value Block extra data set by the miner (default = client version)
--miner.recommit value Time interval to recreate the block being mined (default: 3s)
--miner.noverify Disable remote sealing verification
GAS PRICE ORACLE OPTIONS:
--gpo.blocks value Number of recent blocks to check for gas prices (default: 20)
--gpo.percentile value Suggested gas price is the given percentile of a set of recent transaction gas prices (default: 60)
VIRTUAL MACHINE OPTIONS:
--vmdebug Record information useful for VM and contract debugging
--vm.evm value External EVM configuration (default = built-in interpreter)
--vm.ewasm value External ewasm configuration (default = built-in interpreter)
LOGGING AND DEBUGGING OPTIONS:
--fakepow Disables proof-of-work verification
--nocompaction Disables db compaction after import
--verbosity value Logging verbosity: 0=silent, 1=error, 2=warn, 3=info, 4=debug, 5=detail (default: 3)
--vmodule value Per-module verbosity: comma-separated list of <pattern>=<level> (e.g. eth/*=5,p2p=4)
--backtrace value Request a stack trace at a specific logging statement (e.g. "block.go:271")
--debug Prepends log messages with call-site location (file and line number)
--pprof Enable the pprof HTTP server
--pprof.addr value pprof HTTP server listening interface (default: "127.0.0.1")
--pprof.port value pprof HTTP server listening port (default: 6060)
--pprof.memprofilerate value Turn on memory profiling with the given rate (default: 524288)
--pprof.blockprofilerate value Turn on block profiling with the given rate (default: 0)
--pprof.cpuprofile value Write CPU profile to the given file
--trace value Write execution trace to the given file
METRICS AND STATS OPTIONS:
--metrics Enable metrics collection and reporting
--metrics.expensive Enable expensive metrics collection and reporting
--metrics.addr value Enable stand-alone metrics HTTP server listening interface (default: "127.0.0.1")
--metrics.port value Metrics HTTP server listening port (default: 6060)
--metrics.influxdb Enable metrics export/push to an external InfluxDB database
--metrics.influxdb.endpoint value InfluxDB API endpoint to report metrics to (default: "http://localhost:8086")
--metrics.influxdb.database value InfluxDB database name to push reported metrics to (default: "geth")
--metrics.influxdb.username value Username to authorize access to the database (default: "test")
--metrics.influxdb.password value Password to authorize access to the database (default: "test")
--metrics.influxdb.tags value Comma-separated InfluxDB tags (key/values) attached to all measurements (default: "host=localhost")
WHISPER (EXPERIMENTAL) OPTIONS:
--shh Enable Whisper
--shh.maxmessagesize value Max message size accepted (default: 1048576)
--shh.pow value Minimum POW accepted (default: 0.2)
--shh.restrict-light Restrict connection between two whisper light clients
ALIASED (deprecated) OPTIONS:
--rpc Enable the HTTP-RPC server (deprecated, use --http)
--rpcaddr value HTTP-RPC server listening interface (deprecated, use --http.addr) (default: "localhost")
--rpcport value HTTP-RPC server listening port (deprecated, use --http.port) (default: 8545)
--rpccorsdomain value Comma separated list of domains from which to accept cross origin requests (browser enforced) (deprecated, use --http.corsdomain)
--rpcvhosts value Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (deprecated, use --http.vhosts) (default: "localhost")
--rpcapi value API's offered over the HTTP-RPC interface (deprecated, use --http.api)
--wsaddr value WS-RPC server listening interface (deprecated, use --ws.addr) (default: "localhost")
--wsport value WS-RPC server listening port (deprecated, use --ws.port) (default: 8546)
--wsorigins value Origins from which to accept websockets requests (deprecated, use --ws.origins)
--wsapi value API's offered over the WS-RPC interface (deprecated, use --ws.api)
--gpoblocks value Number of recent blocks to check for gas prices (deprecated, use --gpo.blocks) (default: 20)
--gpopercentile value Suggested gas price is the given percentile of a set of recent transaction gas prices (deprecated, use --gpo.percentile) (default: 60)
--graphql.addr value GraphQL server listening interface (deprecated, graphql can only be enabled on the HTTP-RPC server endpoint, use --graphql)
--graphql.port value GraphQL server listening port (deprecated, graphql can only be enabled on the HTTP-RPC server endpoint, use --graphql) (default: 8545)
--pprofport value pprof HTTP server listening port (deprecated, use --pprof.port) (default: 6060)
--pprofaddr value pprof HTTP server listening interface (deprecated, use --pprof.addr) (default: "127.0.0.1")
--memprofilerate value Turn on memory profiling with the given rate (deprecated, use --pprof.memprofilerate) (default: 524288)
--blockprofilerate value Turn on block profiling with the given rate (deprecated, use --pprof.blockprofilerate) (default: 0)
--cpuprofile value Write CPU profile to the given file (deprecated, use --pprof.cpuprofile)
MISC OPTIONS:
--snapshot Enables snapshot-database mode -- experimental work in progress feature
--help, -h show help
COPYRIGHT:
Copyright 2013-2020 The go-ethereum Authors
這里列出了所有geth客戶端引數和注解,
我們會在我們適合的場景下,講解部分引數的使用說明,
2、同步以太放主網節點,
同步主網節點,需要滿足一下條件:
1、空余磁盤 500G 以上,目前,全球交易資料大約在350G 以上,
2、需要足夠的帶寬,
2.1 同步命令
mkdir /data
cd /data
mkdir gethdata
cd gethdata
編輯啟動腳本 start.sh
nohup ./geth --datadir="/data/gethdata" --rpc --rpcaddr=0.0.0.0 --rpcport=8545 --cache=512 --maxpeers 9999 --rpcapi="web3,eth,net,personal,db,admin" --rpccorsdomain="*" > ./geth.log &2>1
保存到start.sh
引數注解:
| 引數 | 注解 | 配置 |
|---|---|---|
| - -datadir | Data directory for the databases and keystore (default: “/home/cuijb/.ethereum”) | “/data/gethdata” |
| –rpc | Enable the HTTP-RPC server (deprecated, use --http) | |
| –rpcaddr | HTTP-RPC server listening interface (deprecated, use --http.addr) (default: “localhost”) | 0.0.0.0(任何IP都可以,也可以指定固定IP) |
| –rpcport | HTTP-RPC server listening port (deprecated, use --http.port) (default: 8545) | 8545(可以自定義) |
| –cache | Megabytes of memory allocated to internal caching (default = 4096 mainnet full node, 128 light mode) (default: 1024) | 512 |
| –maxpeers | Maximum number of network peers (network disabled if set to 0) (default: 50) | 9999 |
| –rpcapi | API’s offered over the HTTP-RPC interface (deprecated, use --http.api) | “web3,eth,net,personal,db,admin” |
| –rpccorsdomain | Comma separated list of domains from which to accept cross origin requests (browser enforced) (deprecated, use --http.corsdomain) | “*” |
啟動腳本
sh start.sh
查看log,看到如下log資訊,此時已經同步了全球節點
INFO [09-10|15:57:09.796] Imported new chain segment blocks=1 txs=162 mgas=12.484 elapsed=248.253ms mgasps=50.286 number=10832767 hash=8b5be8…08f966 dirty=127.90MiB
INFO [09-10|15:57:15.836] Imported new chain segment blocks=1 txs=117 mgas=12.482 elapsed=344.367ms mgasps=36.245 number=10832768 hash=a38168…5aa6c3 dirty=127.90MiB
INFO [09-10|15:57:43.895] Imported new chain segment blocks=1 txs=273 mgas=12.496 elapsed=1.216s mgasps=10.275 number=10832769 hash=51bc39…2b681b dirty=127.90MiB
INFO [09-10|15:57:44.677] Imported new chain segment blocks=1 txs=253 mgas=12.496 elapsed=774.446ms mgasps=16.135 number=10832770 hash=4485d1…e61833 dirty=127.90MiB
INFO [09-10|15:57:51.106] Imported new chain segment blocks=1 txs=129 mgas=12.498 elapsed=441.170ms mgasps=28.330 number=10832771 hash=27c629…1d5dc2 dirty=127.90MiB
INFO [09-10|15:57:51.279] Chain reorg detected number=10832770 hash=4485d1…e61833 drop=1 dropfrom=27c629…1d5dc2 add=1 addfrom=055cd3…a29d53
INFO [09-10|15:57:51.280] Imported new chain segment blocks=1 txs=116 mgas=12.486 elapsed=172.617ms mgasps=72.335 number=10832771 hash=055cd3…a29d53 dirty=127.90MiB
INFO [09-10|15:58:03.087] Imported new chain segment blocks=1 txs=158 mgas=12.492 elapsed=340.944ms mgasps=36.639 number=10832772 hash=ebf6b0…f9aa4c dirty=127.90MiB
INFO [09-10|15:58:08.593] Deep froze chain segment blocks=6 elapsed=1.040s number=10742771 hash=dc96e0…365518
INFO [09-10|15:58:13.424] Imported new chain segment blocks=1 txs=151 mgas=12.481 elapsed=271.234ms mgasps=46.014 number=10832773 hash=bebad3…ee47d6 dirty=127.90MiB
啟動geth客戶端
剛才我們通過后臺的方式啟動了節點,通過以下方式打開geth客戶端,加載.ipc檔案的辦法啟動,我們查看如下引數,及說明,
| 引數 | 說明 |
|---|---|
| attach | Start an interactive JavaScript environment (connect to node) |
命令如下:
geth attach ipc:/data/gethdata/geth.ipc
//或者
geth attach ipc:http://192.168.31.43:8545
注解:兩種方式,都是打開geth客戶端,兩個命令,實作的功能有區別,第一個,可以開始挖礦,第二個無法開始,還有其他區別,大家研究,今天我們通過第一種辦法啟動,
顯示如下:
Welcome to the Geth JavaScript console!
instance: Geth/v1.9.9-stable-01744997/linux-amd64/go1.13.5
at block: 10832862 (Thu, 10 Sep 2020 16:18:02 CST)
datadir: /data/gethdata
modules: admin:1.0 debug:1.0 eth:1.0 ethash:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0
>
上面告訴你,啟動了ETH節點的模塊,
admin:1.0 debug:1.0 eth:1.0 ethash:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0
這些模塊的使用,會在后續的場景里,做介紹,
現在我們就可以與以太坊網路互動了,以太坊開發團隊提供了功能強大的客戶端互動工具及互動命令集web3.js,這部分內容,我們會在后續的章節里 詳細闡述,
如果操作全球節點,就需要自己購買以太坊,目前以太放價格是400美金一個,還是有點貴,
3、搭建以太放私有鏈節點
搭建私有鏈節點,可以更好的與區塊鏈互動,自己挖礦,挖出自己鏈上的ETH,方便操作網路,更方便我們除錯以太坊源代碼,甚至,我們可以開發出一套自己適用的區塊鏈出來,開始干吧,
3.1、創世塊
現在通過配置創世塊來創建私有鏈,同一個網路中,創世塊必須是一樣的,否則無法聯通,
創建一個eth的根目錄,在根目錄下新建創世塊json檔案genesis.json,
cd /data
mkdir gethdata
cd gethdata
vim genesis.json
粘貼如下內容
{
"config": {
"chainId": 8888,
"homesteadBlock": 0,
"daoForkBlock": 0,
"daoForkSupport": true,
"eip150Block": 0,
"eip155Block": 0,
"eip158Block": 0,
"byzantiumBlock": 0,
"constantinopleBlock": 0,
"petersburgBlock": 0,
"ethash": {}
},
"nonce": "0x42",
"timestamp": "0x0",
"extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa",
"gasLimit": "0xffffffff",
"difficulty": "0x1",
"alloc": {
"093f59f1d91017d30d8c2caa78feb5beb0d2cfaf": {
"balance": "0xffffffffffffffff"
},
"ddf7202cbe0aaed1c2d5c4ef05e386501a054406": {
"balance": "0xffffffffffffffff"
}
}
}
保存檔案,輸入
:wq
退出編輯模式,
主網默認 chainId 1 ,我們搭建自己的私鏈,需要設定為 非 1 ,我們設定 8888即可,
引數解釋:
| 引數名稱 | 引數描述 |
|---|---|
| config | 鏈的一些基本配置 |
| nonce | nonce就是一個64位亂數,用于挖礦,注意他和mixhash的設定需要滿足以太坊的Yellow paper, 4.3.4. Block Header Validity, (44)章節所描述的條件, |
| difficulty | 設定當前區塊的難度,如果難度過大,cpu挖礦就很難,這里設定較小難度 |
| alloc | 用來預置賬號以及賬號的以太幣數量,因為私有鏈挖礦比較容易,所以我們不需要預置有幣的賬號,需要的時候自己創建即可以, |
| coinbase | 礦工的賬號,隨便填 |
| timestamp | 設定創世塊的時間戳 |
| extraData | 附加資訊,隨便填,可以填你的個性資訊 |
| gasLimit | 該值設定對GAS的消耗總量限制,用來限制區塊能包含的交易資訊總和,因為我們是私有鏈,所以填最大, |
3.2 啟動私有鏈節點
3.2.1 初始化區塊鏈
引數注解:
| 引數 | 注解 | 備注 |
|---|---|---|
| init | Bootstrap and initialize a new genesis block | 建立創世區塊 |
命令如下
cd /data/
mkdir gethdata //已經創建檔案夾的,此處略過,
cd gethdata
geth --datadir "./" init genesis.json
顯示如下:
INFO [09-10|17:06:25.183] Maximum peer count ETH=50 LES=0 total=50
INFO [09-10|17:06:25.183] Smartcard socket not found, disabling err="stat /run/pcscd/pcscd.comm: no such file or directory"
INFO [09-10|17:06:25.184] Set global gas cap cap=25000000
INFO [09-10|17:06:25.185] Allocated cache and file handles database=/home/cuijb/geth/geth/chaindata cache=16.00MiB handles=16
INFO [09-10|17:06:25.231] Writing custom genesis block
INFO [09-10|17:06:25.232] Persisted trie from memory database nodes=3 size=407.00B time="71.856μs" gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [09-10|17:06:25.232] Successfully wrote genesis state database=chaindata hash="b25dc8…866dfa"
INFO [09-10|17:06:25.233] Allocated cache and file handles database=/home/cuijb/geth/geth/lightchaindata cache=16.00MiB handles=16
INFO [09-10|17:06:25.239] Writing custom genesis block
INFO [09-10|17:06:25.240] Persisted trie from memory database nodes=3 size=407.00B time="53.712μs" gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [09-10|17:06:25.240] Successfully wrote genesis state database=lightchaindata hash="b25dc8…866dfa"
恭喜,創世區塊創建成功,
3.2.3、啟動區塊鏈網路
撰寫啟動腳本 start.sh
nohup geth --rpc --rpccorsdomain "*" --datadir "./" --port 30304 --rpcapi "db,eth,net,web3,personal,web3" --networkid 8888 --rpcport 8545 --rpcaddr "0.0.0.0" --allow-insecure-unlock > ./geth.log &2>1
保存腳本,
這里需要特殊說明一下,私有鏈腳本與主網腳本的區別
| 引數 | 注解 | 備注 |
|---|---|---|
| –networkid | Network identifier (integer, 1=Frontier, 3=Ropsten, 4=Rinkeby, 5=G?rli) (default: 1) | 8888 |
| –allow-insecure-unlock | Allow insecure account unlocking when account-related RPCs are exposed by http |
注解: 1、networkid 選項,主網配置為 1 ,其他3、4、5都是以太坊坊社區部署的測驗網路,我們是建立自己的私鏈,定義為8888,
2、allow-insecure-unlock選項,方便我們解鎖節點賬戶,如果是主網,不建議配置,否則,你存入節點賬戶的錢,會瞬間被黑客黑走,如何黑走,下面章節,分享黑客如何攻擊區塊鏈節點,
啟動腳本
sh start.sh
查看log,顯示如下:
cuijb@cuijb-VirtualBox:~/geth$ tail -f geth.log
INFO [09-10|20:09:02.427] Regenerated local transaction journal transactions=0 accounts=0
INFO [09-10|20:09:02.433] Allocated fast sync bloom size=512.00MiB
INFO [09-10|20:09:02.471] Initialized fast sync bloom items=3 errorrate=0.000 elapsed=2.759ms
INFO [09-10|20:09:02.473] Starting peer-to-peer node instance=Geth/v1.9.19-stable-3e064192/linux-amd64/go1.14.2
INFO [09-10|20:09:02.501] New local node record seq=1 id=68445c44ed2df2b1 ip=127.0.0.1 udp=30304 tcp=30304
INFO [09-10|20:09:02.504] IPC endpoint opened url=/home/cuijb/geth/geth.ipc
ERROR[09-10|20:09:02.504] Unavailable modules in HTTP API list unavailable=[db] available="[admin debug web3 eth txpool personal ethash miner net]"
INFO [09-10|20:09:02.506] HTTP server started endpoint=[::]:8545 cors=* vhosts=localhost
INFO [09-10|20:09:02.519] Started P2P networking self=enode://36e36f39e9de61f999a1f03830487e11c62d244277e2a3dc8abc5985078560090e6938ef7cb506336433132983ec30653deb1addfca421161e21d691542c8a16@127.0.0.1:30304
INFO [09-10|20:09:04.330] New local node record seq=2 id=68445c44ed2df2b1 ip=223.74.158.88 udp=16706 tcp=30304
INFO [09-10|20:09:12.825] Looking for peers peercount=0 tried=102 static=0
INFO [09-10|20:09:24.156] Looking for peers peercount=0 tried=85 static=0
INFO [09-10|20:09:34.158] Looking for peers peercount=1 tried=64 static=0
如果,顯示這樣的資訊,我們就需要啟動礦工,
進入geth客戶端( Geth JavaScript console)
命令如下:
geth attach ipc:/data/gethdata/geth.ipc
顯示如下:
Welcome to the Geth JavaScript console!
instance: Geth/v1.9.19-stable-3e064192/linux-amd64/go1.14.2
at block: 0 (Thu Jan 01 1970 08:00:00 GMT+0800 (CST))
datadir: /data/gethdata
modules: admin:1.0 debug:1.0 eth:1.0 ethash:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0
>
輸入:
eth
如下:
eth
{
accounts: [],
blockNumber: 0,
coinbase: undefined,
compile: {
lll: function(),
serpent: function(),
solidity: function()
},
defaultAccount: undefined,
defaultBlock: "latest",
gasPrice: 1000000000,
hashrate: 0,
mining: false,
pendingTransactions: [],
protocolVersion: "0x41",
syncing: false,
call: function(),
chainId: function(),
contract: function(abi),
estimateGas: function(),
fillTransaction: function(),
filter: function(options, callback, filterCreationErrorCallback),
getAccounts: function(callback),
getBalance: function(),
getBlock: function(),
getBlockByHash: function(),
getBlockByNumber: function(),
getBlockNumber: function(callback),
getBlockTransactionCount: function(),
getBlockUncleCount: function(),
getCode: function(),
getCoinbase: function(callback),
getCompilers: function(),
getGasPrice: function(callback),
getHashrate: function(callback),
getHeaderByHash: function(),
getHeaderByNumber: function(),
getMining: function(callback),
getPendingTransactions: function(callback),
getProof: function(),
getProtocolVersion: function(callback),
getRawTransaction: function(),
getRawTransactionFromBlock: function(),
getStorageAt: function(),
getSyncing: function(callback),
getTransaction: function(),
getTransactionCount: function(),
getTransactionFromBlock: function(),
getTransactionReceipt: function(),
getUncle: function(),
getWork: function(),
iban: function(iban),
icapNamereg: function(),
isSyncing: function(callback),
namereg: function(),
resend: function(),
sendIBANTransaction: function(),
sendRawTransaction: function(),
sendTransaction: function(),
sign: function(),
signTransaction: function(),
submitTransaction: function(),
submitWork: function()
}
這里顯示與以太放網路互動的一些方法,
我們看到 accounts: [], 說明,我們還沒有創建賬戶,我們在節點上創建第一個賬戶,
創建賬戶
personal.newAccount("111111")
"0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed"
注解:personal.newAccount(“密碼”),這個密碼,就是我們要操作第一個賬戶的時候,使用的密碼,
查看賬戶
> eth.accounts
["0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed"]
我么再次geth客戶端,輸入 eth
> eth
{
accounts: ["0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed"],
blockNumber: 0,
coinbase: "0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed",
compile: {
lll: function(),
serpent: function(),
solidity: function()
},
我們可以清楚看到 accounts[]里多了一個地址,我們再多創建幾個地址,你們觀察一下,
你們會清楚的看到,accounts[0]=coinbase,
開始挖礦
miner.start()
null
你的礦工,開始幫我挖礦了,你很快就會變成很有錢的人了,
注解:miner.start(number),number默認不填,表示,啟動1個執行緒挖礦,你也可以多啟動幾個執行緒開始挖礦,那么number就設定多少,
查詢挖礦狀態
> eth.mining
true
true 說明,正在挖礦中,
停止挖礦
> miner.stop()
null
查詢挖礦狀態
> eth.mining
false
false 礦工停止挖礦
啟動礦工
miner.start()
null
我們開始查看log資訊
cuijb@cuijb-VirtualBox:~/geth$ tail -f geth.log
INFO [09-10|20:29:31.319] Generating DAG in progress epoch=0 percentage=71 elapsed=5m55.753s
INFO [09-10|20:29:33.128] Looking for peers peercount=1 tried=60 static=0
INFO [09-10|20:29:36.133] Generating DAG in progress epoch=0 percentage=72 elapsed=6m0.568s
INFO [09-10|20:29:41.135] Generating DAG in progress epoch=0 percentage=73 elapsed=6m5.570s
INFO [09-10|20:29:43.227] Looking for peers peercount=1 tried=41 static=0
INFO [09-10|20:29:46.176] Generating DAG in progress epoch=0 percentage=74 elapsed=6m10.611s
INFO [09-10|20:29:50.879] Generating DAG in progress epoch=0 percentage=75 elapsed=6m15.314s
INFO [09-10|20:29:53.693] Looking for peers peercount=0 tried=79 static=0
INFO [09-10|20:29:55.444] Generating DAG in progress epoch=0 percentage=76 elapsed=6m19.878s
INFO [09-10|20:30:00.043] Generating DAG in progress epoch=0 percentage=77 elapsed=6m24.478s
INFO [09-10|20:30:03.743] Looking for peers peercount=1 tried=87 static=0
INFO [09-10|20:30:04.725] Generating DAG in progress epoch=0 percentage=78 elapsed=6m29.159s
INFO [09-10|20:30:09.271] Generating DAG in progress epoch=0 percentage=79 elapsed=6m33.706s
INFO [09-10|20:30:13.809] Looking for peers peercount=0 tried=18 static=0
INFO [09-10|20:30:14.240] Generating DAG in progress epoch=0 percentage=80 elapsed=6m38.675s
INFO [09-10|20:30:19.477] Generating DAG in progress epoch=0 percentage=81 elapsed=6m43.912s
INFO [09-10|20:30:24.011] Looking for peers peercount=0 tried=94 static=0
INFO [09-10|20:30:24.489] Generating DAG in progress epoch=0 percentage=82 elapsed=6m48.924s
INFO [09-10|20:30:29.588] Generating DAG in progress epoch=0 percentage=83 elapsed=6m54.023s
INFO [09-10|20:30:34.314] Looking for peers peercount=1 tried=80 static=0
INFO [09-10|20:30:34.316] Generating DAG in progress epoch=0 percentage=84 elapsed=6m58.751s
INFO [09-10|20:30:39.184] Generating DAG in progress epoch=0 percentage=85 elapsed=7m3.619s
INFO [09-10|20:30:44.269] Generating DAG in progress epoch=0 percentage=86 elapsed=7m8.703s
INFO [09-10|20:30:44.447] Looking for peers peercount=0 tried=65 static=0
INFO [09-10|20:30:49.497] Generating DAG in progress epoch=0 percentage=87 elapsed=7m13.932s
INFO [09-10|20:30:54.345] Generating DAG in progress epoch=0 percentage=88 elapsed=7m18.780s
INFO [09-10|20:30:54.475] Looking for peers peercount=1 tried=69 static=0
INFO [09-10|20:30:59.214] Generating DAG in progress epoch=0 percentage=89 elapsed=7m23.649s
INFO [09-10|20:31:04.078] Generating DAG in progress epoch=0 percentage=90 elapsed=7m28.513s
INFO [09-10|20:31:04.477] Looking for peers peercount=0 tried=29 static=0
INFO [09-10|20:31:09.165] Generating DAG in progress epoch=0 percentage=91 elapsed=7m33.599s
INFO [09-10|20:31:14.419] Generating DAG in progress epoch=0 percentage=92 elapsed=7m38.854s
INFO [09-10|20:31:14.640] Looking for peers peercount=2 tried=107 static=0
INFO [09-10|20:31:19.658] Generating DAG in progress epoch=0 percentage=93 elapsed=7m44.093s
INFO [09-10|20:31:24.834] Generating DAG in progress epoch=0 percentage=94 elapsed=7m49.269s
INFO [09-10|20:31:30.079] Generating DAG in progress epoch=0 percentage=95 elapsed=7m54.514s
INFO [09-10|20:31:34.749] Looking for peers peercount=1 tried=24 static=0
INFO [09-10|20:31:34.943] Generating DAG in progress epoch=0 percentage=96 elapsed=7m59.378s
INFO [09-10|20:31:40.429] Generating DAG in progress epoch=0 percentage=97 elapsed=8m4.864s
INFO [09-10|20:31:44.820] Looking for peers peercount=1 tried=101 static=0
INFO [09-10|20:31:45.436] Generating DAG in progress epoch=0 percentage=98 elapsed=8m9.871s
INFO [09-10|20:31:50.699] Generating DAG in progress epoch=0 percentage=99 elapsed=8m15.134s
INFO [09-10|20:31:50.702] Generated ethash verification cache epoch=0 elapsed=8m15.137s
INFO [09-10|20:31:52.354] Successfully sealed new block number=1 sealhash="b1077b…7283ce" hash="3de7b9…309a81" elapsed=8m17.473s
INFO [09-10|20:31:52.354] 🔨 mined potential block number=1 hash="3de7b9…309a81"
INFO [09-10|20:31:52.375] Commit new mining work number=2 sealhash="ac6dd9…0f2149" uncles=0 txs=0 gas=0 fees=0 elapsed="139.91μs"
INFO [09-10|20:31:54.845] Looking for peers peercount=1 tried=46 static=0
INFO [09-10|20:32:02.128] Generating DAG in progress epoch=1 percentage=0 elapsed=9.724s
INFO [09-10|20:32:04.014] Successfully sealed new block number=2 sealhash="ac6dd9…0f2149" hash="1297c3…6287c5" elapsed=11.639s
INFO [09-10|20:32:04.015] 🔨 mined potential block number=2 hash="1297c3…6287c5"
INFO [09-10|20:32:04.015] Commit new mining work number=3 sealhash="b05dc9…0b3b20" uncles=0 txs=0 gas=0 fees=0 elapsed="149.168μs"
INFO [09-10|20:32:04.764] Successfully sealed new block number=3 sealhash="b05dc9…0b3b20" hash="3ef80c…559305" elapsed=749.123ms
INFO [09-10|20:32:04.764] 🔨 mined potential block number=3 hash="3ef80c…559305"
INFO [09-10|20:32:04.765] Commit new mining work number=4 sealhash="c42df7…426749" uncles=0 txs=0 gas=0 fees=0 elapsed="98.08μs"
INFO [09-10|20:32:05.117] Looking for peers peercount=1 tried=72 static=0
INFO [09-10|20:32:08.364] Successfully sealed new block number=4 sealhash="c42df7…426749" hash="9ef7c2…9c4a9f" elapsed=3.599s
INFO [09-10|20:32:08.364] 🔨 mined potential block number=4 hash="9ef7c2…9c4a9f"
INFO [09-10|20:32:08.365] Commit new mining work number=5 sealhash="d780b4…9ef989" uncles=0 txs=0 gas=0 fees=0 elapsed="239.711μs"
INFO [09-10|20:32:08.670] Successfully sealed new block number=5 sealhash="d780b4…9ef989" hash="110d9b…b27f30" elapsed=305.643ms
INFO [09-10|20:32:08.671] 🔨 mined potential block number=5 hash="110d9b…b27f30"
注解:
1、Generating DAG in progress 中 percentage 一定要達到 100
后,網路才能啟動,礦工開始有收益,
2、顯示 Successfully sealed new block number=1 sealhash=“b1077b…7283ce” hash=“3de7b9…309a81” elapsed=8m17.473s 說明,礦工已經開始作業,礦工已經開始幫主人賺錢了,
查看我們的收益,輸入如下命令:
切換geth客戶端
eth.getBalance(eth.accounts[0])
120000000000000000000
礦工才開始作業,我的賬戶有很多 ETH幣,其實不要多想,我們看到的數量單位只是Wei,
3.2、Ether幣的基本單位
Ether幣最小的單位是Wei,也是命令列默認的單位, 然后每1000個進一個單位,依次是
- kwei (1000 Wei)
- mwei (1000 KWei)
- gwei (1000 mwei)
- szabo (1000 gwei)
- finney (1000 szabo)
- ether (1000 finney)
簡單地說就是就是1 以太幣 = 1000000000000000000 Wei (10的18次方wei)
上面查詢余額,其實是很少的,
3.3 、如何進行ether 和 Wei之間的轉換
Ether–> Wei:web3.toWei
> web3.toWei(1)
"1000000000000000000"
> web3.toWei(1.2345678)
"1234567800000000000"
>
Wei –> Ether: web3.fromWei
> web3.fromWei(10000000000000000)
"0.01"
> web3.fromWei(1000000000000000000)
"1"
>
現在再次查詢一下,我的余額
> web3.fromWei(eth.getBalance(eth.coinbase))
1566
3.4 轉賬操作
再創建一個賬戶
> personal.newAccount("111111")
"0xab9836f46e51fb4e25e3aaa248a441d86595b628"
查詢賬戶串列
> eth.accounts
["0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed", "0xab9836f46e51fb4e25e3aaa248a441d86595b628"]
開始轉賬
/*定義第一個賬戶*/
> acc0=eth.accounts[0]
"0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed"
/*定義第二個賬戶*/
> acc1=eth.accounts[1]
"0xab9836f46e51fb4e25e3aaa248a441d86595b628"
/*定義轉賬金額,轉為為Wei*/
> amount = web3.toWei(12.345)
"12345000000000000000"
/*解鎖第一個賬戶*/
> personal.unlockAccount(acc0)
Unlock account 0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed
Passphrase:
true
/*開始轉賬*/
> eth.sendTransaction({from:acc0,to:acc1,value:amount})
"0xd2ee2d8c73bad76e07d0c7d7551ca2dc0ea5ac615cfb627408853d67b1ad1819"
/*查詢第二個賬戶余額*/
> web3.fromWei(eth.getBalance(acc1))
12.345
/*鏈上查詢這筆交易情況*/
> eth.getTransaction("0xd2ee2d8c73bad76e07d0c7d7551ca2dc0ea5ac615cfb627408853d67b1ad1819")
{
blockHash: "0xf35ddb73525baeecb248045908568f752bd9b2fb77f78da0532778219360729f",
blockNumber: 828,
from: "0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed",
gas: 21000,
gasPrice: 1000000000,
hash: "0xd2ee2d8c73bad76e07d0c7d7551ca2dc0ea5ac615cfb627408853d67b1ad1819",
input: "0x",
nonce: 0,
r: "0x31ef99aa435375cfc90d33ff25314868586ba8967ff2d0e1bc44a9ac32891b0e",
s: "0x3655f99471c93ed9894edc0dffdf281fba8b081bc9dbd07dfaa241c5a77ff105",
to: "0xab9836f46e51fb4e25e3aaa248a441d86595b628",
transactionIndex: 0,
v: "0x4594",
value: 12345000000000000000
}
/*鏈上查詢這筆交易憑據*/
>eth.getTransactionReceipt("0xd2ee2d8c73bad76e07d0c7d7551ca2dc0ea5ac615cfb627408853d67b1ad1819")
{
blockHash: "0xf35ddb73525baeecb248045908568f752bd9b2fb77f78da0532778219360729f",
blockNumber: 828,
contractAddress: null,
cumulativeGasUsed: 21000,
from: "0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed",
gasUsed: 21000,
logs: [],
logsBloom: "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
status: "0x1",
to: "0xab9836f46e51fb4e25e3aaa248a441d86595b628",
transactionHash: "0xd2ee2d8c73bad76e07d0c7d7551ca2dc0ea5ac615cfb627408853d67b1ad1819",
transactionIndex: 0
}
>
我們體驗了一次從 account[0] ----> account[1] 轉移了 12.345 個ETH 的程序,
通過這兩章的練習,我們思考一下:
1、轉移的12.345個ETH,區塊鏈將資料保存在哪里,
2、通過這筆轉賬,我們思考一下 ,一個交易的生命周期,
大家可以將自己的思考,在下面留言,一起交流,
2020年9月10日晚,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/11524.html
標籤:AI
上一篇:區塊鏈技術詳解
