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

介绍

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

请求的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搭建多节点私有链

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值