介绍

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.3modules: 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 interfacegeth - go-ethereum 命令行接口Copyright 2013-2018 The go-ethereum AuthorsUSAGE: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 Issuesconsole           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 streamimport            Import a blockchain file导入一个区块链文件import-preimages  Import the preimage database from an RLP streaminit              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 networkRopsten网络:预先配置的POW(proof-of-work)测试网络--rinkeby                                    Rinkeby network: pre-configured proof-of-authority test networkRinkeby网络: 预先配置的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 helpCOPYRIGHT: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服务了。

image

请求的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

作者:区块链阿特拉斯
链接:https://www.jianshu.com/p/e1292dcc72c1
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

ETH官方客户端Geth的使用相关推荐

  1. 安装以太坊客户端geth的方法

    geth是以太坊的官方客户端,它是一个命令行工具,提供很多命令和选项,可以运行以太坊节点.创建和管理账户.发送交易.挖矿.部署智能合约等. 下面介绍geth的三种安装方法: 直接下载可执行文件 在线安 ...

  2. 从3年前接触区块链,到开发出装机量最大客户端Geth,看看人家的职业发展之路 | 人物志...

    记者 | Aholiab 出品 | 区块链大本营 Go-Ethereum,因为是用Go语言编写的,也简称为Geth.Go-Ethereum是以太坊基金会提供的官方客户端软件,也是目前使用最为广泛的客户 ...

  3. 比特币官方客户端钱包是用什么语言开发的_『学概念找员外』比特币网络(三)...

    「力场 lichang.io」公链挖矿第一社区! 网络大小 比特币网络大小很难测量,因为它随时都在变化,而且没有一个中央权威机构.有些人通过研究给了一些估计:往高说,每个月可能有100万个IP地址成为 ...

  4. 12306 android目录,12306官方客户端上线12小时 各大安卓应用商店发布情况对比

    春运大潮即将来临.不少用户都在手机上下载相关的查票抢票软件.12月8日零点,中国铁道部门的官方手机购票客户端--"铁路12306"安卓版正式上线试运营.但截止到目前,各大应用商店里 ...

  5. ubuntu20.04安装以太坊客户端(geth和ganache)

    本文介绍安装两种以太坊客户端Geth和Ganache. 先安装git: sudo apt install -y git 查看git版本: git --version 使用git从github拉取get ...

  6. navicat和mysql有必要都装吗_干掉Navicat!MySQL官方客户端到底行不行?

    在我们选择工具的时候,往往会优先选择那些免费又好用的工具!Navicat作为一款付费软件,虽然功能强大,但也阻止不了我们探索新工具的步伐.最近体验了一把MySQL的官方客户端工具MySQL Workb ...

  7. eth geth 安卓_零基础学习以太坊开发--安装和使用以太坊客户端geth

    一.预备知识 想从事区块链开发,了解以太坊开发的程序员,在刚开始接触以太坊的时候,发现有很多的新名词: EVM solidity go-ethereum(geth) pyethereum Testrp ...

  8. 干掉Navicat:正版,MySQL官方客户端真香!

    点击上方蓝色"方志朋",选择"设为星标" 回复"666"获取独家整理的学习资料! 如果使用Navicat的话,避免不了需要到处寻找破解版,或 ...

  9. 干掉Navicat:正版 MySQL 官方客户端真香!

    如果使用Navicat的话,避免不了需要到处寻找破解版,或者license(笔者很肯定的说,没有几个人会购买正版Navicat的license).个人使用暂且不提,如果是公司内使用,还是有法律风险的. ...

最新文章

  1. C++ STL: 基本六大部件概览 及 各个容器使用方式和底层实现概览
  2. 语义分割--Label Refinement Network for Coarse-to-Fine Semantic Segmentation
  3. 搭建SSH框架之一(资料准备)
  4. nodeJs多线程 -- 学习记录
  5. 报告解读丨基于消费者洞察的鞋服品牌数字化营销新思路
  6. ios html5 网页取消默认样式
  7. 【Linux驱动】linux内核模块简介
  8. python后端开发学什么_零基础学Python,这是阿里Python8年开发经验写给你的学习路线图...
  9. 安卓设置原生alert设置圆角_每个月流量都超额?安卓、苹果用户可以尝试更改这些设置...
  10. AOP处理事务静、动态代理(jdk方法)
  11. webstorm界面主题
  12. CSS如何设置div半透明效果
  13. 软电话HTML界面,软电话条对接
  14. 利用Python进行博客图片压缩
  15. 【GNN】高被引图神经网络(GNN)全面综述论文
  16. java 从set取值_怎样从java集合类set中取出数据?
  17. 对垒以太网10BASE-T1S,CAN XL能后来居上么?
  18. 三星970PRO用于高速采集存储系统
  19. 国外服务器网站打开速度慢,使用国外服务器时访问为什么很慢?
  20. SPL工业智能:发现时序数据的异常

热门文章

  1. 解决 emulator-5554 disconnected! Cancelling
  2. Linux的excel函数怎么编写,Excel中怎么编写自定义函数
  3. css处理图片上的文字(内阴影)
  4. was进程内存占用过大_linux服务器内存占用过大
  5. GIS从二维到三维有多远
  6. GDAL学习笔记02:GDAL基础知识
  7. 淘客大户快到碗里来。
  8. 【生活】外包到阿里工作2年是一种什么样的体验
  9. 如何区分SEO、SEM和网站优化
  10. 基于深度学习的高精度交警检测识别系统(PyTorch+Pyside6+YOLOv5模型)