ETH官方客戶端Geth的使用(一)

區塊鏈阿特拉斯發表於2018-08-12

介紹

Geth是由以太坊基金會提供的官方客戶端軟體,用Go程式語言編寫的。Geth提供了一個互動式命令控制檯,通過命令控制檯中包含了以太坊的各種功能(API)。全名go-ethereum,github地址go-ethereum。wiki裡為使用文件

安裝geth

以下為Mac下面安裝geth,其他系統下安裝可檢視Building-Ethereum

brew tap ethereum/ethereum
brew install ethereum
複製程式碼

使用geth

啟動geth

安裝好之後,進入一個自己建立的目錄,執行最簡單的命令geth console 2>>eth.log啟動,以下為啟動後的效果。

➜  BlockChain cd Test 
➜  Test geth console 2>>eth.log
Welcome to the Geth JavaScript console!

instance: Geth/v1.8.13-stable/darwin-amd64/go1.10.3
 modules: admin:1.0 debug:1.0 eth:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0

> 
複製程式碼

以上是一個最簡單的啟動命令,啟動一個控制檯並輸出日誌eth.log到當前目錄。當然啟動命令還有挺多其他引數,我們使用geth help能夠看到一些命令列引數的文件。

命令列引數

在wiki文件Command Line Options,能看到所有的命令列引數。或者直接在命令列裡執行geth help

NAME:
   geth - the go-ethereum command line interface
   geth - go-ethereum 命令列介面
   
   Copyright 2013-2018 The go-ethereum Authors

USAGE:
   geth [options] command [command options] [arguments...]
   geth [選項]     命令    [命令選項]          [引數…]
   
VERSION:
   1.8.13-stable
複製程式碼
COMMANDS:
命令:

   account           Manage accounts
                     管理賬戶
                     
   attach            Start an interactive JavaScript environment (connect to node)
                     啟動互動式JavaScript環境(連線到節點)
                     
   bug               opens a window to report a bug on the geth repo
                     上報bug Issues
                     
   console           Start an interactive JavaScript environment
                     啟動互動式JavaScript環境
                     
   copydb            Create a local chain from a target chaindata folder
                     從目標區塊鏈資料資料夾建立本地鏈
                     
   dump              Dump a specific block from storage
                     轉存一個特定的塊儲存
                     
   dumpconfig        Show configuration values
                     顯示配置值
                     
   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
                     啟動並初始化一個新的創世紀塊
                     
   js                Execute the specified JavaScript files
                     執行指定的JavaScript檔案(多個)
                     
   license           Display license information
                     顯示許可資訊
                     
   makecache         Generate ethash verification cache (for testing)
                     生成ethash驗證快取(用於測試)
                     
   makedag           Generate ethash mining DAG (for testing)
                     生成ethash 挖礦DAG(用於測試)
                     
   monitor           Monitor and visualize node metrics
                     監控和視覺化節點指標
                     
   removedb          Remove blockchain and state databases
                     刪除區塊鏈和狀態資料庫
                     
   version           Print version numbers
                     列印版本號
                     
   wallet            Manage Ethereum presale wallets
                     管理Ethereum預售錢包
                     
   help, h           Shows a list of commands or help for one command
                     顯示一個命令或幫助一個命令列表
複製程式碼
ETHEREUM OPTIONS:
ETHEREUM選項:

  --config value                               TOML configuration file
  --datadir "/Users/dasheng/Library/Ethereum"  Data directory for the databases and keystore
                                                資料庫和keystore金鑰的資料目錄
  
  --keystore                                   Directory for the keystore (default = inside the datadir)
  --nousb                                      Disables monitoring for and managing USB hardware wallets
  --networkid value                            Network identifier (integer, 1=Frontier, 2=Morden (disused), 3=Ropsten, 4=Rinkeby) (default: 1)
  --testnet                                    Ropsten network: pre-configured proof-of-work test network
                                               Ropsten網路:預先配置的POW(proof-of-work)測試網路
                                
  --rinkeby                                    Rinkeby network: pre-configured proof-of-authority test network
                                               Rinkeby網路: 預先配置的POA(proof-of-authority)測試網路
  
  --syncmode "fast"                            Blockchain sync mode ("fast", "full", or "light")
                                               區塊鏈的同步模式 ("fast", "full", or "light")
  
  --gcmode value                               Blockchain garbage collection mode ("full", "archive") (default: "full")
  --ethstats value                             Reporting URL of a ethstats service (nodename:secret@host:port)
  --identity value                             Custom node name
  --lightserv value                            Maximum percentage of time allowed for serving LES requests (0-90) (default: 0)
  --lightpeers value                           Maximum number of LES client peers (default: 100)
  --lightkdf                                   Reduce key-derivation RAM & CPU usage at some expense of KDF strength
複製程式碼
DEVELOPER CHAIN OPTIONS:
開發者模式選項

  --dev               Ephemeral proof-of-authority network with a pre-funded developer account, mining enabled
                      使用POA共識網路,預設預分配一個開發者賬戶並且會自動開啟挖礦。
                      
  --dev.period value  Block period to use in developer mode (0 = mine only if transaction pending) (default: 0)
                      開發者模式下挖礦週期 (0 = 僅在交易時) (預設: 0)
複製程式碼
ETHASH OPTIONS:
  --ethash.cachedir                         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.dagdir "/Users/dasheng/.ethash"  Directory to store the ethash mining DAGs (default = inside home folder)
  --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)
複製程式碼
TRANSACTION POOL OPTIONS:
  --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: 1024)
  --cache.database value   Percentage of cache memory allowance to use for database io (default: 75)
  --cache.gc value         Percentage of cache memory allowance to use for trie pruning (default: 25)
  --trie-cache-gens value  Number of trie node generations to keep in memory (default: 120)
複製程式碼
ACCOUNT OPTIONS:
  --unlock value    Comma separated list of accounts to unlock
  --password value  Password file to use for non-interactive password input
複製程式碼
API AND CONSOLE OPTIONS:
API和控制檯選項:

  --rpc                  Enable the HTTP-RPC server
                         啟用HTTP-RPC伺服器
                         
  --rpcaddr value        HTTP-RPC server listening interface (default: "localhost")
                         HTTP-RPC伺服器介面地址(預設值:“localhost”)
                         
  --rpcport value        HTTP-RPC server listening port (default: 8545)
                         HTTP-RPC伺服器監聽埠(預設值:8545)
                         
  --rpcapi value         API's offered over the HTTP-RPC interface
                         基於HTTP-RPC介面提供的API
                         
  --ws                   Enable the WS-RPC server
  --wsaddr value         WS-RPC server listening interface (default: "localhost")
  --wsport value         WS-RPC server listening port (default: 8546)
  --wsapi value          API's offered over the WS-RPC interface
  --wsorigins value      Origins from which to accept websockets requests
  --ipcdisable           Disable the IPC-RPC server
  --ipcpath              Filename for IPC socket/pipe within the datadir (explicit paths escape it)
  --rpccorsdomain value  Comma separated list of domains from which to accept cross origin requests (browser enforced)
                         允許跨域請求的域名列表(逗號分隔)(瀏覽器強制)
                         
  --rpcvhosts value      Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (default: "localhost")
  --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 (set v4+v5 instead for light servers)
  --bootnodesv4 value   Comma separated enode URLs for P2P v4 discovery bootstrap (light server, full nodes)
  --bootnodesv5 value   Comma separated enode URLs for P2P v5 discovery bootstrap (light server, light nodes)
  --port value          Network listening port (default: 30303)
  --maxpeers value      Maximum number of network peers (network disabled if set to 0) (default: 25)
  --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
  --minerthreads value      Number of CPU threads to use for mining (default: 4)
  --etherbase value         Public address for block mining rewards (default = first account created) (default: "0")
  --targetgaslimit value    Target gas limit sets the artificial target gas floor for the blocks to mine (default: 4712388)
  --gasprice "18000000000"  Minimal gas price to accept for mining a transactions
  --extradata value         Block extra data set by the miner (default = client version)
複製程式碼
GAS PRICE ORACLE OPTIONS:
  --gpoblocks value      Number of recent blocks to check for gas prices (default: 20)
  --gpopercentile 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
複製程式碼
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)
                            日誌詳細度: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
  --pprofaddr value         pprof HTTP server listening interface (default: "127.0.0.1")
  --pprofport value         pprof HTTP server listening port (default: 6060)
  --memprofilerate value    Turn on memory profiling with the given rate (default: 524288)
  --blockprofilerate value  Turn on block profiling with the given rate (default: 0)
  --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.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.host.tag host   InfluxDB host tag attached to all measurements (default: "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)
  
DEPRECATED OPTIONS:
  --fast   Enable fast syncing through state downloads (replaced by --syncmode)
  --light  Enable light client mode (replaced by --syncmode)
  
MISC OPTIONS:
  --help, -h  show help
  

COPYRIGHT:
   Copyright 2013-2018 The go-ethereum Authors
複製程式碼

引數使用例子

console和attach

為了使用geth建立一個新帳戶,我們必須首先在控制檯模式下啟動geth。

geth consolegeth attach都可以開啟一個JavaScript環境和節點進行互動,但是geth console會啟動節點,geth attach是通過rpc或者ipc和已經啟動的節點進行互動。在geth console裡面可以使用所有模組的api,但是geth attach只能使用已經開啟的模組的api,如果節點沒有開啟rpc geth attach甚至都不能連線上節點

geth console
複製程式碼
geth attach
複製程式碼

日誌

使用geth console的時候你會發現一直會輸出資訊,如:

INFO [08-12|13:24:11.607] Upgrading chain index                    type=bloombits percentage=88
複製程式碼

使用命令--verbosity,後面的值表示日誌詳細度:0=silent, 1=error, 2=warn, 3=info, 4=debug, 5=detail (預設為: 3):

geth --verbosity 0 console
複製程式碼

我們還可以把日誌輸入到檔案中(不知道這裡的2是什麼意思,好像不代表詳細度):

geth --verbosity 0 console 2>> eth.log
複製程式碼

檢視日誌動態:

tail -f eth.log
複製程式碼

--dev

以下程式碼表示在開發者模式下啟動互動式JavaScript環境,指定為開發模式這樣就不用同步公有鏈上的區塊,公有鏈的資料量幾十個G太大了,共識速度 也比較慢:

geth --dev console 2>> eth.log
複製程式碼

資料存放目錄--datadir

設定資料庫和keystore金鑰的資料存放目錄,預設目錄你能在geth help的時候--datadir後面看到,我這裡預設的是"/Users/dasheng/Library/Ethereum",現在在我當前的目錄/Users/dasheng/My/BlockChain/Test,設定為--datadir DataDir,就會在當前目錄下建立一個DataDir資料夾。

啟動後你在這個資料夾下面可以看到geth(用於儲存公鏈的資料)、keystore(用於儲存祕鑰)兩個資料夾,裡面儲存的就是對應的資料了。

➜  ~ cd /Users/dasheng/My/BlockChain/Test
➜  Test geth --datadir DataDir --dev console 2>> eth.log
複製程式碼

啟動HTTP-RPC

--rpc                  啟用HTTP-RPC伺服器
                         
--rpcaddr value        HTTP-RPC伺服器介面地址(預設值:“localhost”)
                         
--rpcport value        HTTP-RPC伺服器監聽埠(預設值:8545)
                         
--rpcapi value         基於HTTP-RPC介面提供的API,預設只有eth,net,web3

--rpccorsdomain value  允許跨域請求的域名列表(逗號分隔)(瀏覽器強制)
複製程式碼

關於以太坊中的RPC機制可以參考以太坊RPC機制與API例項這篇文章,寫的比較詳細。下面我簡單的說一下使用。

RPC(remote process call),遠端過程呼叫。意思就是兩臺物理位置不同的伺服器,其中一臺伺服器的應用想呼叫另一臺伺服器上某個應用的函式或者方法,由於不在同一個記憶體空間不能直接呼叫,因此需要通過網路來表達語義以及傳入的引數。RPC是跨作業系統,跨程式語言的網路通訊方式。

geth --rpc --rpcapi "db,eth,net,web3,personal" --datadir DataDir --dev console 2>> eth.log
複製程式碼

這裡我們使用--rpc表示啟用HTTP-RPC,我們可以指定監聽地址以及埠,如果不寫--rpcaddr--rpcport``的話,就是預設的http://localhost:8545。--rpcapi`表示基於HTTP-RPC介面提供的API,預設只有eth,net,web3。

geth  --rpc --rpcaddr 127.0.0.1 --rpcport 10070 --rpcapi "personal,db,eth,net,web3" -datadir DataDir --dev console 2>> eth.log
複製程式碼

如果你要使用瀏覽器來訪問的話,就要強制指定--rpccorsdomain選項,否則的話由於JavaScript呼叫的同源限制,請求會失敗。

geth  --rpc --rpcaddr 127.0.0.1 --rpcport 10070 --rpcapi "personal,db,eth,net,web3" --rpccorsdomain "http://localhost:10070" -datadir DataDir --dev console 2>> eth.log
複製程式碼

然後我們就可以用Postman來測試上面的HTTP-RPC服務了。

ETH官方客戶端Geth的使用(一)

請求的json資料為:

{"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":67}
複製程式碼

同步模式--syncmode

同步模式有三種:"fast", "full", or "light"

geth --syncmode "fast" --datadir DataDir --cache=512 console
複製程式碼

"full":

獲取區塊的header
獲取區塊的body
從創始塊開始校驗每一個元素
下載所有區塊資料資訊

"fast":

獲取區塊的header
獲取區塊的body
在同步到當前塊之前不處理任何事務,然後獲得一個快照,像full節點一樣進行後面的同步操作。沿著區塊下載最近資料庫中的交易,有可能丟失歷史資料。
使用此模式時注意需要設定–cache,預設16M,我這裡設定的是512M

"Ligth":

僅獲取當前狀態。驗證元素需要向full節點發起相應的請求。

退出geth控制檯

exit
複製程式碼

參考

GETH客戶端基本操作

以太坊客戶端Geth命令用法-引數詳解

通過Geth搭建多節點私有鏈

相關文章