[关闭]
@qidiandasheng 2018-09-10T17:20:37.000000Z 字数 12271 阅读 9625

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

区块链


介绍

Geth是由以太坊基金会提供的官方客户端软件,用Go编程语言编写的。Geth提供了一个交互式命令控制台,通过命令控制台中包含了以太坊的各种功能(API)。全名go-ethereum,github地址go-ethereum。wiki里为使用文档

安装更新geth

以下为Mac下面安装geth,其他系统下安装可查看Building-Ethereum

  1. brew tap ethereum/ethereum
  2. brew install ethereum

更新:

  1. brew upgrade ethereum/ethereum/ethereum

使用geth

启动geth

安装好之后,进入一个自己创建的目录,运行最简单的命令geth console 2>>eth.log启动,以下为启动后的效果。

  1. BlockChain cd Test
  2. Test geth console 2>>eth.log
  3. Welcome to the Geth JavaScript console!
  4. instance: Geth/v1.8.13-stable/darwin-amd64/go1.10.3
  5. 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
  6. >

以上是一个最简单的启动命令,启动一个控制台并输出日志eth.log到当前目录。当然启动命令还有挺多其他参数,我们使用geth help能够看到一些命令行参数的文档。

命令行参数

在wiki文档Command Line Options,能看到所有的命令行参数。或者直接在命令行里执行geth help

  1. NAME:
  2. geth - the go-ethereum command line interface
  3. geth - go-ethereum 命令行接口
  4. Copyright 2013-2018 The go-ethereum Authors
  5. USAGE:
  6. geth [options] command [command options] [arguments...]
  7. geth [选项] 命令 [命令选项] [参数…]
  8. VERSION:
  9. 1.8.13-stable
  1. COMMANDS:
  2. 命令:
  3. account Manage accounts
  4. 管理账户
  5. attach Start an interactive JavaScript environment (connect to node)
  6. 启动交互式JavaScript环境(连接到节点)
  7. bug opens a window to report a bug on the geth repo
  8. 上报bug Issues
  9. console Start an interactive JavaScript environment
  10. 启动交互式JavaScript环境
  11. copydb Create a local chain from a target chaindata folder
  12. 从目标区块链数据文件夹创建本地链
  13. dump Dump a specific block from storage
  14. 转存一个特定的块存储
  15. dumpconfig Show configuration values
  16. 显示配置值
  17. export Export blockchain into file
  18. 导出区块链到文件
  19. export-preimages Export the preimage database into an RLP stream
  20. import Import a blockchain file
  21. 导入一个区块链文件
  22. import-preimages Import the preimage database from an RLP stream
  23. init Bootstrap and initialize a new genesis block
  24. 启动并初始化一个新的创世纪块
  25. js Execute the specified JavaScript files
  26. 执行指定的JavaScript文件(多个)
  27. license Display license information
  28. 显示许可信息
  29. makecache Generate ethash verification cache (for testing)
  30. 生成ethash验证缓存(用于测试)
  31. makedag Generate ethash mining DAG (for testing)
  32. 生成ethash 挖矿DAG(用于测试)
  33. monitor Monitor and visualize node metrics
  34. 监控和可视化节点指标
  35. removedb Remove blockchain and state databases
  36. 删除区块链和状态数据库
  37. version Print version numbers
  38. 打印版本号
  39. wallet Manage Ethereum presale wallets
  40. 管理Ethereum预售钱包
  41. help, h Shows a list of commands or help for one command
  42. 显示一个命令或帮助一个命令列表
  1. ETHEREUM OPTIONS:
  2. ETHEREUM选项:
  3. --config value TOML configuration file
  4. --datadir "/Users/dasheng/Library/Ethereum" Data directory for the databases and keystore
  5. 数据库和keystore密钥的数据目录
  6. --keystore Directory for the keystore (default = inside the datadir)
  7. --nousb Disables monitoring for and managing USB hardware wallets
  8. --networkid value Network identifier (integer, 1=Frontier, 2=Morden (disused), 3=Ropsten, 4=Rinkeby) (default: 1)
  9. --testnet Ropsten network: pre-configured proof-of-work test network
  10. Ropsten网络:预先配置的POW(proof-of-work)测试网络
  11. --rinkeby Rinkeby network: pre-configured proof-of-authority test network
  12. Rinkeby网络: 预先配置的POA(proof-of-authority)测试网络
  13. --syncmode "fast" Blockchain sync mode ("fast", "full", or "light")
  14. 区块链的同步模式 ("fast", "full", or "light")
  15. --gcmode value Blockchain garbage collection mode ("full", "archive") (default: "full")
  16. --ethstats value Reporting URL of a ethstats service (nodename:secret@host:port)
  17. --identity value Custom node name
  18. --lightserv value Maximum percentage of time allowed for serving LES requests (0-90) (default: 0)
  19. --lightpeers value Maximum number of LES client peers (default: 100)
  20. --lightkdf Reduce key-derivation RAM & CPU usage at some expense of KDF strength
  1. DEVELOPER CHAIN OPTIONS:
  2. 开发者模式选项
  3. --dev Ephemeral proof-of-authority network with a pre-funded developer account, mining enabled
  4. 使用POA共识网络,默认预分配一个开发者账户并且会自动开启挖矿。
  5. --dev.period value Block period to use in developer mode (0 = mine only if transaction pending) (default: 0)
  6. 开发者模式下挖矿周期 (0 = 仅在交易时) (默认: 0)
  1. ETHASH OPTIONS:
  2. --ethash.cachedir Directory to store the ethash verification caches (default = inside the datadir)
  3. --ethash.cachesinmem value Number of recent ethash caches to keep in memory (16MB each) (default: 2)
  4. --ethash.cachesondisk value Number of recent ethash caches to keep on disk (16MB each) (default: 3)
  5. --ethash.dagdir "/Users/dasheng/.ethash" Directory to store the ethash mining DAGs (default = inside home folder)
  6. --ethash.dagsinmem value Number of recent ethash mining DAGs to keep in memory (1+GB each) (default: 1)
  7. --ethash.dagsondisk value Number of recent ethash mining DAGs to keep on disk (1+GB each) (default: 2)
  1. TRANSACTION POOL OPTIONS:
  2. --txpool.nolocals Disables price exemptions for locally submitted transactions
  3. --txpool.journal value Disk journal for local transaction to survive node restarts (default: "transactions.rlp")
  4. --txpool.rejournal value Time interval to regenerate the local transaction journal (default: 1h0m0s)
  5. --txpool.pricelimit value Minimum gas price limit to enforce for acceptance into the pool (default: 1)
  6. --txpool.pricebump value Price bump percentage to replace an already existing transaction (default: 10)
  7. --txpool.accountslots value Minimum number of executable transaction slots guaranteed per account (default: 16)
  8. --txpool.globalslots value Maximum number of executable transaction slots for all accounts (default: 4096)
  9. --txpool.accountqueue value Maximum number of non-executable transaction slots permitted per account (default: 64)
  10. --txpool.globalqueue value Maximum number of non-executable transaction slots for all accounts (default: 1024)
  11. --txpool.lifetime value Maximum amount of time non-executable transaction are queued (default: 3h0m0s)
  1. PERFORMANCE TUNING OPTIONS:
  2. --cache value Megabytes of memory allocated to internal caching (default: 1024)
  3. --cache.database value Percentage of cache memory allowance to use for database io (default: 75)
  4. --cache.gc value Percentage of cache memory allowance to use for trie pruning (default: 25)
  5. --trie-cache-gens value Number of trie node generations to keep in memory (default: 120)
  1. ACCOUNT OPTIONS:
  2. --unlock value Comma separated list of accounts to unlock
  3. --password value Password file to use for non-interactive password input
  1. API AND CONSOLE OPTIONS:
  2. API和控制台选项:
  3. --rpc Enable the HTTP-RPC server
  4. 启用HTTP-RPC服务器
  5. --rpcaddr value HTTP-RPC server listening interface (default: "localhost")
  6. HTTP-RPC服务器接口地址(默认值:“localhost”)
  7. --rpcport value HTTP-RPC server listening port (default: 8545)
  8. HTTP-RPC服务器监听端口(默认值:8545)
  9. --rpcapi value API's offered over the HTTP-RPC interface
  10. 基于HTTP-RPC接口提供的API
  11. --ws Enable the WS-RPC server
  12. --wsaddr value WS-RPC server listening interface (default: "localhost")
  13. --wsport value WS-RPC server listening port (default: 8546)
  14. --wsapi value API's offered over the WS-RPC interface
  15. --wsorigins value Origins from which to accept websockets requests
  16. --ipcdisable Disable the IPC-RPC server
  17. --ipcpath Filename for IPC socket/pipe within the datadir (explicit paths escape it)
  18. --rpccorsdomain value Comma separated list of domains from which to accept cross origin requests (browser enforced)
  19. 允许跨域请求的域名列表(逗号分隔)(浏览器强制)
  20. --rpcvhosts value Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (default: "localhost")
  21. --jspath loadScript JavaScript root path for loadScript (default: ".")
  22. --exec value Execute JavaScript statement
  23. --preload value Comma separated list of JavaScript files to preload into the console
  1. NETWORKING OPTIONS:
  2. --bootnodes value Comma separated enode URLs for P2P discovery bootstrap (set v4+v5 instead for light servers)
  3. --bootnodesv4 value Comma separated enode URLs for P2P v4 discovery bootstrap (light server, full nodes)
  4. --bootnodesv5 value Comma separated enode URLs for P2P v5 discovery bootstrap (light server, light nodes)
  5. --port value Network listening port (default: 30303)
  6. --maxpeers value Maximum number of network peers (network disabled if set to 0) (default: 25)
  7. --maxpendpeers value Maximum number of pending connection attempts (defaults used if set to 0) (default: 0)
  8. --nat value NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>) (default: "any")
  9. --nodiscover Disables the peer discovery mechanism (manual peer addition)
  10. --v5disc Enables the experimental RLPx V5 (Topic Discovery) mechanism
  11. --netrestrict value Restricts network communication to the given IP networks (CIDR masks)
  12. --nodekey value P2P node key file
  13. --nodekeyhex value P2P node key as hex (for testing)
  1. MINER OPTIONS:
  2. --mine Enable mining
  3. --minerthreads value Number of CPU threads to use for mining (default: 4)
  4. --etherbase value Public address for block mining rewards (default = first account created) (default: "0")
  5. --targetgaslimit value Target gas limit sets the artificial target gas floor for the blocks to mine (default: 4712388)
  6. --gasprice "18000000000" Minimal gas price to accept for mining a transactions
  7. --extradata value Block extra data set by the miner (default = client version)
  1. GAS PRICE ORACLE OPTIONS:
  2. --gpoblocks value Number of recent blocks to check for gas prices (default: 20)
  3. --gpopercentile value Suggested gas price is the given percentile of a set of recent transaction gas prices (default: 60)
  4. VIRTUAL MACHINE OPTIONS:
  5. --vmdebug Record information useful for VM and contract debugging
  1. LOGGING AND DEBUGGING OPTIONS:
  2. 日志和调试选项:
  3. --fakepow Disables proof-of-work verification
  4. --nocompaction Disables db compaction after import
  5. --verbosity value Logging verbosity: 0=silent, 1=error, 2=warn, 3=info, 4=debug, 5=detail (default: 3)
  6. 日志详细度:0=silent, 1=error, 2=warn, 3=info, 4=debug, 5=detail (default: 3)
  7. --vmodule value Per-module verbosity: comma-separated list of <pattern>=<level> (e.g. eth/*=5,p2p=4)
  8. --backtrace value Request a stack trace at a specific logging statement (e.g. "block.go:271")
  9. --debug Prepends log messages with call-site location (file and line number)
  10. --pprof Enable the pprof HTTP server
  11. --pprofaddr value pprof HTTP server listening interface (default: "127.0.0.1")
  12. --pprofport value pprof HTTP server listening port (default: 6060)
  13. --memprofilerate value Turn on memory profiling with the given rate (default: 524288)
  14. --blockprofilerate value Turn on block profiling with the given rate (default: 0)
  15. --cpuprofile value Write CPU profile to the given file
  16. --trace value Write execution trace to the given file
  1. METRICS AND STATS OPTIONS:
  2. --metrics Enable metrics collection and reporting
  3. --metrics.influxdb Enable metrics export/push to an external InfluxDB database
  4. --metrics.influxdb.endpoint value InfluxDB API endpoint to report metrics to (default: "http://localhost:8086")
  5. --metrics.influxdb.database value InfluxDB database name to push reported metrics to (default: "geth")
  6. --metrics.influxdb.username value Username to authorize access to the database (default: "test")
  7. --metrics.influxdb.password value Password to authorize access to the database (default: "test")
  8. --metrics.influxdb.host.tag host InfluxDB host tag attached to all measurements (default: "localhost")
  1. WHISPER (EXPERIMENTAL) OPTIONS:
  2. --shh Enable Whisper
  3. --shh.maxmessagesize value Max message size accepted (default: 1048576)
  4. --shh.pow value Minimum POW accepted (default: 0.2)
  5. DEPRECATED OPTIONS:
  6. --fast Enable fast syncing through state downloads (replaced by --syncmode)
  7. --light Enable light client mode (replaced by --syncmode)
  8. MISC OPTIONS:
  9. --help, -h show help
  10. COPYRIGHT:
  11. 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甚至都不能连接上节点

  1. geth console
  1. geth attach

日志

使用geth console的时候你会发现一直会输出信息,如:

  1. 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):

  1. geth --verbosity 0 console

我们还可以把日志输入到文件中(不知道这里的2是什么意思,好像不代表详细度):

  1. geth --verbosity 0 console 2>> eth.log

查看日志动态:

  1. tail -f eth.log

--dev

以下代码表示在开发者模式下启动交互式JavaScript环境,指定为开发模式这样就不用同步公有链上的区块,公有链的数据量几十个G太大了,共识速度 也比较慢:

  1. 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(用于存储秘钥)两个文件夹,里面存储的就是对应的数据了。

  1. ~ cd /Users/dasheng/My/BlockChain/Test
  2. Test geth --datadir DataDir --dev console 2>> eth.log

启动HTTP-RPC

  1. --rpc 启用HTTP-RPC服务器
  2. --rpcaddr value HTTP-RPC服务器接口地址(默认值:“localhost”)
  3. --rpcport value HTTP-RPC服务器监听端口(默认值:8545)
  4. --rpcapi value 基于HTTP-RPC接口提供的API,默认只有eth,net,web3
  5. --rpccorsdomain value 允许跨域请求的域名列表(逗号分隔)(浏览器强制)

关于以太坊中的RPC机制可以参考以太坊RPC机制与API实例这篇文章,写的比较详细。下面我简单的说一下使用。

RPC(remote process call),名曰远程过程调用。意思就是两台物理位置不同的服务器,其中一台服务器的应用想调用另一台服务器上某个应用的函数或者方法,由于不在同一个内存空间不能直接调用,因此需要通过网络来表达语义以及传入的参数。RPC是跨操作系统,跨编程语言的网络通信方式。

  1. 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。

  1. geth --rpc --rpcaddr 127.0.0.1 --rpcport 10070 --rpcapi "personal,db,eth,net,web3" -datadir DataDir --dev console 2>> eth.log

如果你要使用浏览器来访问的话,就要强制指定--rpccorsdomain选项,否则的话由于JavaScript调用的同源限制,请求会失败。

  1. 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服务了。

请求的json数据为:

  1. {"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":67}

同步模式--syncmode

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

  1. geth --syncmode "fast" --datadir DataDir --cache=512 console

"full":

获取区块的header
获取区块的body
从创始块开始校验每一个元素
下载所有区块数据信息

"fast":

获取区块的header
获取区块的body
在同步到当前块之前不处理任何事务,然后获得一个快照,像full节点一样进行后面的同步操作。沿着区块下载最近数据库中的交易,有可能丢失历史数据。
使用此模式时注意需要设置–cache,默认16M,我这里设置的是512M

"Ligth":

仅获取当前状态。验证元素需要向full节点发起相应的请求。

退出geth控制台

  1. exit

参考

GETH客户端基本操作
以太坊客户端Geth命令用法-参数详解
通过Geth搭建多节点私有链

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注