介紹
Geth是由以太坊基金會提供的官方客戶端軟件贪嫂,用Go編程語言編寫的椰于。Geth提供了一個交互式命令控制臺勤婚,通過命令控制臺中包含了以太坊的各種功能(API)呛伴。全名go-ethereum,github地址go-ethereum季春。wiki里為使用文檔洗搂。
安裝geth
以下為Mac下面安裝geth,其他系統(tǒng)下安裝可查看Building-Ethereum
brew tap ethereum/ethereum
brew install ethereum
使用geth
啟動geth
安裝好之后,進入一個自己創(chuàng)建的目錄蚕脏,運行最簡單的命令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到當前目錄秦驯。當然啟動命令還有挺多其他參數(shù),我們使用geth help
能夠看到一些命令行參數(shù)的文檔挣棕。
命令行參數(shù)
在wiki文檔Command Line Options译隘,能看到所有的命令行參數(shù)÷逍模或者直接在命令行里執(zhí)行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 [選項] 命令 [命令選項] [參數(shù)…]
VERSION:
1.8.13-stable
COMMANDS:
命令:
account Manage accounts
管理賬戶
attach Start an interactive JavaScript environment (connect to node)
啟動交互式JavaScript環(huán)境(連接到節(jié)點)
bug opens a window to report a bug on the geth repo
上報bug Issues
console Start an interactive JavaScript environment
啟動交互式JavaScript環(huán)境
copydb Create a local chain from a target chaindata folder
從目標區(qū)塊鏈數(shù)據(jù)文件夾創(chuàng)建本地鏈
dump Dump a specific block from storage
轉(zhuǎn)存一個特定的塊存儲
dumpconfig Show configuration values
顯示配置值
export Export blockchain into file
導出區(qū)塊鏈到文件
export-preimages Export the preimage database into an RLP stream
import Import a blockchain file
導入一個區(qū)塊鏈文件
import-preimages Import the preimage database from an RLP stream
init Bootstrap and initialize a new genesis block
啟動并初始化一個新的創(chuàng)世紀塊
js Execute the specified JavaScript files
執(zhí)行指定的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
監(jiān)控和可視化節(jié)點指標
removedb Remove blockchain and state databases
刪除區(qū)塊鏈和狀態(tài)數(shù)據(jù)庫
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
數(shù)據(jù)庫和keystore密鑰的數(shù)據(jù)目錄
--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網(wǎng)絡(luò):預先配置的POW(proof-of-work)測試網(wǎng)絡(luò)
--rinkeby Rinkeby network: pre-configured proof-of-authority test network
Rinkeby網(wǎng)絡(luò): 預先配置的POA(proof-of-authority)測試網(wǎng)絡(luò)
--syncmode "fast" Blockchain sync mode ("fast", "full", or "light")
區(qū)塊鏈的同步模式 ("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:
開發(fā)者模式選項
--dev Ephemeral proof-of-authority network with a pre-funded developer account, mining enabled
使用POA共識網(wǎng)絡(luò),默認預分配一個開發(fā)者賬戶并且會自動開啟挖礦词身。
--dev.period value Block period to use in developer mode (0 = mine only if transaction pending) (default: 0)
開發(fā)者模式下挖礦周期 (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服務(wù)器
--rpcaddr value HTTP-RPC server listening interface (default: "localhost")
HTTP-RPC服務(wù)器接口地址(默認值:“l(fā)ocalhost”)
--rpcport value HTTP-RPC server listening port (default: 8545)
HTTP-RPC服務(wù)器監(jiān)聽端口(默認值: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:
日志和調(diào)試選項:
--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
參數(shù)使用例子
console和attach
為了使用geth創(chuàng)建一個新帳戶厅目,我們必須首先在控制臺模式下啟動geth。
geth console
與 geth attach
都可以打開一個JavaScript環(huán)境和節(jié)點進行交互法严,但是geth console
會啟動節(jié)點损敷,geth attach
是通過rpc或者ipc和已經(jīng)啟動的節(jié)點進行交互。在geth console
里面可以使用所有模塊的api深啤,但是geth attach
只能使用已經(jīng)打開的模塊的api拗馒,如果節(jié)點沒有打開rpc geth attach
甚至都不能連接上節(jié)點
geth console
geth attach
日志
使用geth console
的時候你會發(fā)現(xiàn)一直會輸出信息,如:
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
查看日志動態(tài):
tail -f eth.log
--dev
以下代碼表示在開發(fā)者模式下啟動交互式JavaScript環(huán)境,指定為開發(fā)模式這樣就不用同步公有鏈上的區(qū)塊呈昔,公有鏈的數(shù)據(jù)量幾十個G太大了挥等,共識速度 也比較慢:
geth --dev console 2>> eth.log
數(shù)據(jù)存放目錄--datadir
設(shè)置數(shù)據(jù)庫和keystore密鑰的數(shù)據(jù)存放目錄,默認目錄你能在geth help
的時候--datadir
后面看到堤尾,我這里默認的是"/Users/dasheng/Library/Ethereum"
触菜,現(xiàn)在在我當前的目錄/Users/dasheng/My/BlockChain/Test
,設(shè)置為--datadir DataDir
哀峻,就會在當前目錄下創(chuàng)建一個DataDir
文件夾。
啟動后你在這個文件夾下面可以看到geth
(用于存儲公鏈的數(shù)據(jù))哲泊、keystore
(用于存儲秘鑰)兩個文件夾剩蟀,里面存儲的就是對應(yīng)的數(shù)據(jù)了。
? ~ cd /Users/dasheng/My/BlockChain/Test
? Test geth --datadir DataDir --dev console 2>> eth.log
啟動HTTP-RPC
--rpc 啟用HTTP-RPC服務(wù)器
--rpcaddr value HTTP-RPC服務(wù)器接口地址(默認值:“l(fā)ocalhost”)
--rpcport value HTTP-RPC服務(wù)器監(jiān)聽端口(默認值:8545)
--rpcapi value 基于HTTP-RPC接口提供的API切威,默認只有eth,net,web3
--rpccorsdomain value 允許跨域請求的域名列表(逗號分隔)(瀏覽器強制)
關(guān)于以太坊中的RPC機制可以參考以太坊RPC機制與API實例這篇文章育特,寫的比較詳細。下面我簡單的說一下使用。
RPC(remote process call)缰冤,名曰遠程過程調(diào)用犬缨。意思就是兩臺物理位置不同的服務(wù)器,其中一臺服務(wù)器的應(yīng)用想調(diào)用另一臺服務(wù)器上某個應(yīng)用的函數(shù)或者方法棉浸,由于不在同一個內(nèi)存空間不能直接調(diào)用怀薛,因此需要通過網(wǎng)絡(luò)來表達語義以及傳入的參數(shù)。RPC是跨操作系統(tǒng)迷郑,跨編程語言的網(wǎng)絡(luò)通信方式枝恋。
geth --rpc --rpcapi "db,eth,net,web3,personal" --datadir DataDir --dev console 2>> eth.log
這里我們使用--rpc
表示啟用HTTP-RPC,我們可以指定監(jiān)聽地址以及端口嗡害,如果不寫--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調(diào)用的同源限制鹃骂,請求會失敗。
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服務(wù)了首妖。
請求的json數(shù)據(jù)為:
{"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":67}
同步模式--syncmode
同步模式有三種:"fast", "full", or "light"
geth --syncmode "fast" --datadir DataDir --cache=512 console
"full":
獲取區(qū)塊的header
獲取區(qū)塊的body
從創(chuàng)始塊開始校驗每一個元素
下載所有區(qū)塊數(shù)據(jù)信息
"fast":
獲取區(qū)塊的header
獲取區(qū)塊的body
在同步到當前塊之前不處理任何事務(wù)偎漫,然后獲得一個快照,像full節(jié)點一樣進行后面的同步操作有缆。沿著區(qū)塊下載最近數(shù)據(jù)庫中的交易象踊,有可能丟失歷史數(shù)據(jù)。
使用此模式時注意需要設(shè)置–cache棚壁,默認16M杯矩,我這里設(shè)置的是512M
"Ligth":
僅獲取當前狀態(tài)。驗證元素需要向full節(jié)點發(fā)起相應(yīng)的請求袖外。
退出geth控制臺
exit