第01课:以太坊节点部署及基本命令操作

第01课:以太坊节点部署及基本命令操作

区块链诞生自中本聪的比特币,自 2009 年以来,出现了各种各样的类比特币的基于公有区块链的数字货币,目前各个国家及企业机构都对区块链投入巨大的财力和人力来对区块链技术进行研究。

http://gitbook.cn/gitchat/column/5ad98d9479e8c577efc7557d?utm_source=blog18042401

区块链简介

这里引用工信部指导发布的《中国区块链技术和应用发展白皮书 2016》中的解释:

广义来讲,区块链技术是利用块链式数据结构来验证与存储数据、利用分布式节点共识算法来生成和更新数据、利用密码学的方式保证数据传输和访问的安全、利用由自动化脚本代码组成的智能合约来编程和操作数据的一种全新的分布式基础架构与计算范式。

简单来说,区块链就是一个去中心化的分布式账本数据库,而大家耳熟能详的比特币、以太币等就是这个分布式账本上流通的数字货币。

第一代的比特币引爆了区块链技术,但它能做的事情很少;而以以太坊为代表的第二代区块链技术,引入了图灵完备的机制,它是一个平台和一种编程语言。在以太坊上面可以进行编程操作,比如发布智能合约、发布属于自己的代币,进而衍生出各类应用。

本系列课程目标

本系列课程的目标是快速带领大家进入以太坊的世界,通过私有节点的部署、公链的同步、以太坊的基本命令操作、JSON-RPC 接口的调用、代币的快速开发及发布、如何在 Etherscan 上对代币进行操作、代币的 Java 调用、以太坊的数字货币钱包开发等。

通过本系列课程的学习,可以达到从入门到对以太坊的功能及周边知识有一个系统的了解。如果有一定的编程基础可以快速开发出自己的一套代币,并通过 JSON-RPC 调用这套代币;另一方面,也可以开发出一套简单的以太坊数字货币钱包。

本节课程简介

无论是学习以太坊技术,还是搭建自己的以太坊服务器或部署相关智能合约都需要了解以太坊节点的部署步骤。本篇文章的内容是将带领大家学习一下如何安装部署以太坊的 Geth 节点。

以太坊的钱包

以太坊的钱包有不少,比如 Geth、Ethereum Wallet、Parity 等,还有一些轻量级的 App 钱包,如 imtoken 等。前面一类钱包是需要同步节点数据,而后面的 App 则有相应的平台将数据同步完成。

而作为开发者或学习者必定要选择前面一类钱包,而像 Ethereum Wallet 有友好的用户界面,针对炒币人员或存储以太币或简单转账可进行使用;而对于开发人员来说还是需要官方的专业钱包——Geth。

如果是在 Linux 系统下启动 Ethereum Wallet 钱包,通过 ps 命令会看到,其实它内置了 Geth 钱包程序,只是在外面用 JavaScript 封装了一层可视化操作界面。

实战经验

如果是建立交易平台或提供外部服务器或者学习相关技术(更好的了解底层)一定要选择 Geth 钱包进行部署,这也是官方指定版本。

Geth 下载 & 安装

下载

以太坊的官网地址详见这里,官网会自动识别当前系统,在首页提供对应操作系统的下载链接;也可直接访问 Geth 下载专区进行下载,由于官网的下载经常抽风,可通过此镜像下载。 在官网的页面会看到 4 种类型的程序,分别支持 Win、Mac、Linux 和源码安装,根据自己的系统选择对应的安装程序。

安装

安装步骤没有过多可介绍的,直接执行对应的程序即可安装。如果采用源代码安装需先搭建 Go 编程语言环境,同时需要一定的 Go 语言基础,然后参考 GitHub 上的安装步骤安装即可。此非本节重点内容这里就不再赘述了。

无论在什么操作系统下安装完成,我们能够找的可执行的程序是 Geth。下面介绍本节课的重点,即基于 Geth 的启动和参数说明。

下面以 Windows 操作系统为例,安装过程中的每一步操作如下:

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

Geth 程序启动

如果大家比较着急,可以直接执行 Geth 程序。在 Windows 下通过 cmd 命令进入命令窗口,定位到 geth.exe 所在目录,然后执行即可启动。Mac 和 Linux 环境按照 Linux 操作,通过 cd 命令进入 geth 所在目录,执行 ./geth 即可启动程序,后面的内容操作不同的系统对应不同的操作方式,我们不再进行每个系统的区分,统一按照 Linux 系统来操作,毕竟最终还是要部署到 Linux 操作系统上的。

当然,如果你有一定的耐心,那么还是等一下,了解相关的参数即配置项之后再启动程序。

核心命令和参数

我们可以通过 help 命令来先了解查看一下基本使用参数情况:

>./geth -h

NAME:
   geth - the go-ethereum command line interface

   Copyright 2013-2017 The go-ethereum Authors

USAGE:
   geth [options] command [command options] [arguments...]

VERSION:
   1.7.3-stable-4bb3c89d

COMMANDS:
   account     Manage accounts
   attach      Start an interactive JavaScript environment (connect to node)
   bug         opens a window to report a bug on the geth repo
   console     Start an interactive JavaScript environment
   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
   import      Import a blockchain file
   init        Bootstrap and initialize a new genesis block
   js          Execute the specified JavaScript files
   license     Display license information
   makecache   Generate ethash verification cache (for testing)
   makedag     Generate ethash mining DAG (for testing)
   monitor     Monitor and visualize node metrics
   removedb    Remove blockchain and state databases
   version     Print version numbers
   wallet      Manage Ethereum presale wallets
   help, h     Shows a list of commands or help for one command

ETHEREUM OPTIONS:
  --config value                           TOML configuration file
  --datadir "/Users/zzs/Library/Ethereum"  Data directory for the databases and 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
  --rinkeby                                Rinkeby network: pre-configured proof-of-authority test network
  --syncmode "fast"                        Blockchain sync mode ("fast", "full", or "light")
  --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: 20)
  --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
  --dev.period value  Block period to use in developer mode (0 = mine only if transaction pending) (default: 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/zzs/.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 (min 16MB / database forced) (default: 128)
  --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:
  --rpc                  Enable the HTTP-RPC server
  --rpcaddr value        HTTP-RPC server listening interface (default: "localhost")
  --rpcport value        HTTP-RPC server listening port (default: 8545)
  --rpcapi value         API's offered over the HTTP-RPC interface
  --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)
  --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: 8)
  --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: 10)
  --gpopercentile value  Suggested gas price is the given percentile of a set of recent transaction gas prices (default: 50)

VIRTUAL MACHINE OPTIONS:
  --vmdebug  Record information useful for VM and contract debugging

LOGGING AND DEBUGGING OPTIONS:
  --metrics                 Enable metrics collection and reporting
  --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)
  --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

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
  --light  Enable light client mode

MISC OPTIONS:
  --help, -h  show help


COPYRIGHT:
   Copyright 2013-2017 The go-ethereum Authors

参数和操作何其多啊,不过,不用担心也不要害怕,掌握其中几个重要的参数即可成功的部署启动 Geth 节点,通过 help 命令可以方便的获得相关的命令和参数。

当我们直接执行 Geth 命令时,程序会按照默认参数进行启动,所谓默认参数就是上面我们 help 查看到的,说明中有 default 项的参数值,默认参数值并不能很好的满足我们的需求。

数据目录

datadir 参数,指定 Geth 区块数据及私钥存储目录,如果未指定 Windows 系统将在 C 盘下存储,Linux 系统将在用户对应的 home 目录下存储。此时,启动命令为:

>./geth --datadir /Users/zzs/develop/eth/geth/data-test

上面就将所有的数据存储在了 data-test 目录下。

实战经验

启动时一定要指定一个足够大硬盘的路径,不建议使用默认路径,此路径在后面使用的过程中会频繁用到,如果私钥文件没有单独存储,那么也将存储在此目录下。

开启 JSON-RPC

单独启动程序是无法进行 JSON-RPC 与之交互的。因此,Geth 提供了以下两个参数:

--rpc 

--rpcapi "db,eth,net,web3,miner,personal"
  • 第一个参数 rpc 是告诉节点开启 JSON-RPC 服务;
  • 第二个参数指定 rpc 服务支持哪些角色的 rpc 来操作。

其中,第二个参数的区别及支持哪些操作命令内容比较多,在后面的章节中我们会对此参数的内容进行详细的示例讲解,这里先不着急。

此时,启动 Geth 的命令已经变成如下:

>./geth --datadir /Users/zzs/develop/eth/geth/data-test --rpc --rpcapi "db,eth,net,web3,miner,personal"

实战经验

在真实生产环境中 rpcapi 的 personal、admin 等级别较高的操作权限慎重开启,一旦使用不当会导致系统安全问题。

ipcpath 和 attach

此参数指定 ipc 临时文件的路径,默认在 datadir 指定的目录之下,当节点启动会生成一个名字为 geth.ipc 的文件,当程序关闭时此文件随之消失。

可配合 attach 命令来进入与 geth 节点进行 js 交互的窗口。基本命令如下:

>./geth attach rpc:/Users/zzs/develop/eth/geth/data-test/geth.ipc

以上操作为 Linux 操作,如果 Windows 操作系统未修改 datadir 路径可直接执行 attach 命令,无需添加后面的路径信息。

实战经验

真实环境中我们一般采用后台进程的形式来启动 Geth,Linux 下为在启动参数后面添加 & 符号来启动。此时如果我们想通过命令行来进行交互,即可使用此命令来进入交互窗口。

console

通过此命令可以直接启动 Geth 并进入交互窗口,使用示例:

>./geth --datadir /Users/zzs/develop/eth/geth/data-test --rpc --rpcapi "db,eth,net,web3,miner,personal" console

和 attach 的效果一样,但不建议直接使用 console 进入,否则,一旦退出程序 Geth 节点也随之关闭了,建议使用 attach 模式。

数据存储目录结构

通过上面的参数调整我们已经能够正常启动一个公有链的 Geth 程序了,关于公有链同步会遇到的问题我们将在下一章节进行详细介绍。先来看一下指定的 datadir 目录下都有什么。

datadir 目录下有两个子目录,分别为 geth 和 keystore,其中 geth 目录下存储了区块链同步下来的数据和节点(node)相关个数据。而 keystore 目录下将存储经过加密的私钥文件,不过现在还未生成地址,此目录暂时为空。文件名类似如下格式:

UTC--2018-02-22T08-21-53.763257000Z--c180962e3f348c71bc6aab30552da9e514429ca1

实战经验

keystore 目录下的文件一定要慎重保管,一旦丢失将永远丢失对应地址上的资产,它们和创建账户时设置的密码一一匹配。同时,也要确保此文件放置在公网中,导致账号资产被盗。

基本操作命令

基本操作命令官方文档中已经有相应的说明,这里就简单举例介绍一下相关的操作,以下命令都需要先进入控制台操作窗口。

(1)创建账户

查看此节点下的所有账户:

eth.accounts

(2)查看块高

eth.blockNumber

(3)创建账户

注意:创建账户需要用 pesonal 角色,其中参数为密码:

#方式一:
>personal.newAccount("111111")
"0xbe2f1213da9807e9d64e8ae607be1c86bd53c210"
#方式二:
> personal.newAccount()
Passphrase:
Repeat passphrase:
"0xbe2f1213da9807e9d64e8ae607be1c86bd53c210"

此处建议使用不添加参数的创建模式,这样就不会明文暴露密码信息。当创建账户完成之后,再进入 keystore 目录下就可以看到创建账户对应的加密私钥文件了。

(4)查看账户余额

其中参数为区块链地址:

eth.getBalance("0xbe2f1213da9807e9d64e8ae607be1c86bd53c210")

(5)转账

比如从账户 0x7d1f7be4112ce63b9de04a0bf95c1e87e430bd1b 转账 1 个以太币到 0x587e57a516730381958f86703b1f8e970ff445d9。

eth.sendTransaction({from:"0x7d1f7be4112ce63b9de04a0bf95c1e87e430bd1b",to:"0x587e57a516730381958f86703b1f8e970ff445d9",value:web3.toWei(1,"ether")})

当直接执行此方法时会抛出异常:

account is locked
    at web3.js:3119:20
    at web3.js:6023:15
    at web3.js:4995:36
    at <anonymous>:1:1

此异常说明需要执行账户解锁操作。

(6)解锁转出账户

其中第一个参数为转出账户,第二个参数为密码,也可以直接填写第一个参数,然后通过命令行提示再输入密码。

personal.unlockAccount("0x7d1f7be4112ce63b9de04a0bf95c1e87e430bd1b","111111")

解锁之后即可进行转账操作。

实战经验

需要注意的是默认解锁时间为 300 秒,可设置解锁时间防止被盗。

(1)启动挖矿

miner.start()

(2)停止挖矿

miner.stop()

当在执行挖矿时日志会不停刷屏,不用管,只要命令输入全,执行即可停止挖矿。

实战经验

关于上面的命令操作,在使用中有一个小技巧,比如在交互窗口想查看 eth 都有什么操作命令,可输入 eth.,然后连着敲击两下 tab 键接口展示此角色的所有操作命令,比如:

>eth.
#敲击两下tab
eth._requestManager            eth.defaultAccount             eth.getBlockNumber             eth.getMining                  eth.getTransactionCount        eth.isSyncing                  eth.sendTransaction
eth.accounts                   eth.defaultBlock               eth.getBlockTransactionCount   eth.getPendingTransactions     eth.getTransactionFromBlock    eth.mining                     eth.sign
eth.blockNumber                eth.estimateGas                eth.getBlockUncleCount         eth.getProtocolVersion         eth.getTransactionReceipt      eth.namereg                    eth.signTransaction
eth.call                       eth.filter                     eth.getCode                    eth.getRawTransaction          eth.getUncle                   eth.pendingTransactions        eth.submitTransaction
eth.coinbase                   eth.gasPrice                   eth.getCoinbase                eth.getRawTransactionFromBlock eth.getWork                    eth.protocolVersion            eth.submitWork
eth.compile                    eth.getAccounts                eth.getCompilers               eth.getStorageAt               eth.hashrate                   eth.resend                     eth.syncing
eth.constructor                eth.getBalance                 eth.getGasPrice                eth.getSyncing                 eth.iban                       eth.sendIBANTransaction
eth.contract                   eth.getBlock                   eth.getHashrate                eth

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325772223&siteId=291194637