上篇文章,我们编译了go-ethereum的源代码,大家体验了一下开发环境,使用了开发工具,我们从这章开始,进入ETH的学习阶段。我会在每章完成后,给大家提出一些思考。帮助大家。
1、搭建前准备
如果是使用虚拟机上安装的 Ubuntu。请在虚拟机中打开终端,安装SSH。
命令如下:
sudo apt-get install ssh
Windows上,安装 SSH终端工具MobaXterm Professional Edition,自己安装。MAC系统,自带远程工具,或者选择自己喜欢的远程工具如putty或者其他。
编辑器 Visual Studio Code ,可以安装在windows环境下或者MAC下。如果想通过Visual Studio Code操作ubuntu下的文件,请在Visual Studio Code安装拓展插件。
点击左侧状态栏”扩展“ 输入 Remote Development 点击安装,安装后,会有文档,详细介绍如何连接远程主机,及操作文件。如下图:
Ubuntu下安装命令
上篇文章,我们通过编译源代码的方式,自己编译了geth客户端,如果仅仅是使用ETH网络,我们可以只安装ETH客户端即可。根据自己场景需要决定。
命令如下:
sudo apt-get install software-properties-common
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo add-apt-repository -y ppa:ethereum/ethereum-dev
sudo apt-get update
sudo apt-get install ethereum
安装测试
安装好后,我们输入如下命令:
geth -h
显示如下:
NAME:
geth - the go-ethereum command line interface
Copyright 2013-2019 The go-ethereum Authors
USAGE:
geth [options] command [command options] [arguments...]
VERSION:
1.9.19-stable-3e064192
COMMANDS:
account Manage accounts
attach Start an interactive JavaScript environment (connect to node)
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
dumpgenesis Dumps genesis block JSON configuration to stdout
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
inspect Inspect the storage size for each type of data in the database
js Execute the specified JavaScript files
license Display license information
makecache Generate ethash verification cache (for testing)
makedag Generate ethash mining DAG (for testing)
removedb Remove blockchain and state databases
retesteth Launches geth in retesteth mode
show-deprecated-flags Show flags that have been deprecated
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 value Data directory for the databases and keystore (default: "/home/cuijb/.ethereum")
--datadir.ancient value Data directory for ancient chain segments (default = inside chaindata)
--keystore value Directory for the keystore (default = inside the datadir)
--nousb Disables monitoring for and managing USB hardware wallets
--pcscdpath value Path to the smartcard daemon (pcscd) socket file (default: "/run/pcscd/pcscd.comm")
--networkid value Network identifier (integer, 1=Frontier, 3=Ropsten, 4=Rinkeby, 5=Görli) (default: 1)
--goerli Görli network: pre-configured proof-of-authority test network
--rinkeby Rinkeby network: pre-configured proof-of-authority test network
--yolov1 YOLOv1 network: pre-configured proof-of-authority shortlived test network.
--ropsten Ropsten network: pre-configured proof-of-work test network
--syncmode value Blockchain sync mode ("fast", "full", or "light") (default: fast)
--exitwhensynced Exits after block synchronisation completes
--gcmode value Blockchain garbage collection mode ("full", "archive") (default: "full")
--txlookuplimit value Number of recent blocks to maintain transactions index by-hash for (default = index all blocks) (default: 0)
--ethstats value Reporting URL of a ethstats service (nodename:secret@host:port)
--identity value Custom node name
--lightkdf Reduce key-derivation RAM & CPU usage at some expense of KDF strength
--whitelist value Comma separated block number-to-hash mappings to enforce (<number>=<hash>)
LIGHT CLIENT OPTIONS:
--light.serve value Maximum percentage of time allowed for serving LES requests (multi-threaded processing allows values over 100) (default: 0)
--light.ingress value Incoming bandwidth limit for serving light clients (kilobytes/sec, 0 = unlimited) (default: 0)
--light.egress value Outgoing bandwidth limit for serving light clients (kilobytes/sec, 0 = unlimited) (default: 0)
--light.maxpeers value Maximum number of light clients to serve, or light servers to attach to (default: 100)
--ulc.servers value List of trusted ultra-light servers
--ulc.fraction value Minimum % of trusted ultra-light servers required to announce a new head (default: 75)
--ulc.onlyannounce Ultra light server sends announcements only
--light.nopruning Disable ancient light chain data pruning
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 value 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.cacheslockmmap Lock memory maps of recent ethash caches
--ethash.dagdir value Directory to store the ethash mining DAGs (default: "/home/cuijb/.ethash")
--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)
--ethash.dagslockmmap Lock memory maps for recent ethash mining DAGs
TRANSACTION POOL OPTIONS:
--txpool.locals value Comma separated accounts to treat as locals (no flush, priority inclusion)
--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 = 4096 mainnet full node, 128 light mode) (default: 1024)
--cache.database value Percentage of cache memory allowance to use for database io (default: 50)
--cache.trie value Percentage of cache memory allowance to use for trie caching (default = 15% full mode, 30% archive mode) (default: 15)
--cache.trie.journal value Disk journal directory for trie cache to survive node restarts (default: "triecache")
--cache.trie.rejournal value Time interval to regenerate the trie cache journal (default: 1h0m0s)
--cache.gc value Percentage of cache memory allowance to use for trie pruning (default = 25% full mode, 0% archive mode) (default: 25)
--cache.snapshot value Percentage of cache memory allowance to use for snapshot caching (default = 10% full mode, 20% archive mode) (default: 10)
--cache.noprefetch Disable heuristic state prefetch during block import (less CPU and disk IO, more time waiting for data)
ACCOUNT OPTIONS:
--unlock value Comma separated list of accounts to unlock
--password value Password file to use for non-interactive password input
--signer value External signer (url or path to ipc file)
--allow-insecure-unlock Allow insecure account unlocking when account-related RPCs are exposed by http
API AND CONSOLE OPTIONS:
--ipcdisable Disable the IPC-RPC server
--ipcpath value Filename for IPC socket/pipe within the datadir (explicit paths escape it)
--http Enable the HTTP-RPC server
--http.addr value HTTP-RPC server listening interface (default: "localhost")
--http.port value HTTP-RPC server listening port (default: 8545)
--http.api value API's offered over the HTTP-RPC interface
--http.corsdomain value Comma separated list of domains from which to accept cross origin requests (browser enforced)
--http.vhosts value Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (default: "localhost")
--ws Enable the WS-RPC server
--ws.addr value WS-RPC server listening interface (default: "localhost")
--ws.port value WS-RPC server listening port (default: 8546)
--ws.api value API's offered over the WS-RPC interface
--ws.origins value Origins from which to accept websockets requests
--graphql Enable GraphQL on the HTTP-RPC server. Note that GraphQL can only be started if an HTTP server is started as well.
--graphql.corsdomain value Comma separated list of domains from which to accept cross origin requests (browser enforced)
--graphql.vhosts value Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (default: "localhost")
--rpc.gascap value Sets a cap on gas that can be used in eth_call/estimateGas (0=infinite) (default: 25000000)
--rpc.txfeecap value Sets a cap on transaction fee (in ether) that can be sent via the RPC APIs (0 = no cap) (default: 1)
--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
--bootnodesv4 value Comma separated enode URLs for P2P v4 discovery bootstrap (light server, full nodes) (deprecated, use --bootnodes)
--bootnodesv5 value Comma separated enode URLs for P2P v5 discovery bootstrap (light server, light nodes) (deprecated, use --bootnodes)
--discovery.dns value Sets DNS discovery entry points (use "" to disable DNS)
--port value Network listening port (default: 30303)
--maxpeers value Maximum number of network peers (network disabled if set to 0) (default: 50)
--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
--miner.threads value Number of CPU threads to use for mining (default: 0)
--miner.notify value Comma separated HTTP URL list to notify of new work packages
--miner.gasprice value Minimum gas price for mining a transaction (default: 1000000000)
--miner.gastarget value Target gas floor for mined blocks (default: 8000000)
--miner.gaslimit value Target gas ceiling for mined blocks (default: 8000000)
--miner.etherbase value Public address for block mining rewards (default = first account) (default: "0")
--miner.extradata value Block extra data set by the miner (default = client version)
--miner.recommit value Time interval to recreate the block being mined (default: 3s)
--miner.noverify Disable remote sealing verification
GAS PRICE ORACLE OPTIONS:
--gpo.blocks value Number of recent blocks to check for gas prices (default: 20)
--gpo.percentile 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
--vm.evm value External EVM configuration (default = built-in interpreter)
--vm.ewasm value External ewasm configuration (default = built-in interpreter)
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)
--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
--pprof.addr value pprof HTTP server listening interface (default: "127.0.0.1")
--pprof.port value pprof HTTP server listening port (default: 6060)
--pprof.memprofilerate value Turn on memory profiling with the given rate (default: 524288)
--pprof.blockprofilerate value Turn on block profiling with the given rate (default: 0)
--pprof.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.expensive Enable expensive metrics collection and reporting
--metrics.addr value Enable stand-alone metrics HTTP server listening interface (default: "127.0.0.1")
--metrics.port value Metrics HTTP server listening port (default: 6060)
--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.tags value Comma-separated InfluxDB tags (key/values) attached to all measurements (default: "host=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)
--shh.restrict-light Restrict connection between two whisper light clients
ALIASED (deprecated) OPTIONS:
--rpc Enable the HTTP-RPC server (deprecated, use --http)
--rpcaddr value HTTP-RPC server listening interface (deprecated, use --http.addr) (default: "localhost")
--rpcport value HTTP-RPC server listening port (deprecated, use --http.port) (default: 8545)
--rpccorsdomain value Comma separated list of domains from which to accept cross origin requests (browser enforced) (deprecated, use --http.corsdomain)
--rpcvhosts value Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (deprecated, use --http.vhosts) (default: "localhost")
--rpcapi value API's offered over the HTTP-RPC interface (deprecated, use --http.api)
--wsaddr value WS-RPC server listening interface (deprecated, use --ws.addr) (default: "localhost")
--wsport value WS-RPC server listening port (deprecated, use --ws.port) (default: 8546)
--wsorigins value Origins from which to accept websockets requests (deprecated, use --ws.origins)
--wsapi value API's offered over the WS-RPC interface (deprecated, use --ws.api)
--gpoblocks value Number of recent blocks to check for gas prices (deprecated, use --gpo.blocks) (default: 20)
--gpopercentile value Suggested gas price is the given percentile of a set of recent transaction gas prices (deprecated, use --gpo.percentile) (default: 60)
--graphql.addr value GraphQL server listening interface (deprecated, graphql can only be enabled on the HTTP-RPC server endpoint, use --graphql)
--graphql.port value GraphQL server listening port (deprecated, graphql can only be enabled on the HTTP-RPC server endpoint, use --graphql) (default: 8545)
--pprofport value pprof HTTP server listening port (deprecated, use --pprof.port) (default: 6060)
--pprofaddr value pprof HTTP server listening interface (deprecated, use --pprof.addr) (default: "127.0.0.1")
--memprofilerate value Turn on memory profiling with the given rate (deprecated, use --pprof.memprofilerate) (default: 524288)
--blockprofilerate value Turn on block profiling with the given rate (deprecated, use --pprof.blockprofilerate) (default: 0)
--cpuprofile value Write CPU profile to the given file (deprecated, use --pprof.cpuprofile)
MISC OPTIONS:
--snapshot Enables snapshot-database mode -- experimental work in progress feature
--help, -h show help
COPYRIGHT:
Copyright 2013-2020 The go-ethereum Authors
这里列出了所有geth客户端参数和注解。
我们会在我们适合的场景下,讲解部分参数的使用说明。
2、同步以太放主网节点。
同步主网节点,需要满足一下条件:
1、空余磁盘 500G 以上。目前,全球交易数据大约在350G 以上。
2、需要足够的带宽。
2.1 同步命令
mkdir /data
cd /data
mkdir gethdata
cd gethdata
编辑启动脚本 start.sh
nohup ./geth --datadir="/data/gethdata" --rpc --rpcaddr=0.0.0.0 --rpcport=8545 --cache=512 --maxpeers 9999 --rpcapi="web3,eth,net,personal,db,admin" --rpccorsdomain="*" > ./geth.log &2>1
保存到start.sh
参数注解:
参数 | 注解 | 配置 |
---|---|---|
- -datadir | Data directory for the databases and keystore (default: “/home/cuijb/.ethereum”) | “/data/gethdata” |
–rpc | Enable the HTTP-RPC server (deprecated, use --http) | |
–rpcaddr | HTTP-RPC server listening interface (deprecated, use --http.addr) (default: “localhost”) | 0.0.0.0(任何IP都可以,也可以指定固定IP) |
–rpcport | HTTP-RPC server listening port (deprecated, use --http.port) (default: 8545) | 8545(可以自定义) |
–cache | Megabytes of memory allocated to internal caching (default = 4096 mainnet full node, 128 light mode) (default: 1024) | 512 |
–maxpeers | Maximum number of network peers (network disabled if set to 0) (default: 50) | 9999 |
–rpcapi | API’s offered over the HTTP-RPC interface (deprecated, use --http.api) | “web3,eth,net,personal,db,admin” |
–rpccorsdomain | Comma separated list of domains from which to accept cross origin requests (browser enforced) (deprecated, use --http.corsdomain) | “*” |
启动脚本
sh start.sh
查看log,看到如下log信息,此时已经同步了全球节点
INFO [09-10|15:57:09.796] Imported new chain segment blocks=1 txs=162 mgas=12.484 elapsed=248.253ms mgasps=50.286 number=10832767 hash=8b5be8…08f966 dirty=127.90MiB
INFO [09-10|15:57:15.836] Imported new chain segment blocks=1 txs=117 mgas=12.482 elapsed=344.367ms mgasps=36.245 number=10832768 hash=a38168…5aa6c3 dirty=127.90MiB
INFO [09-10|15:57:43.895] Imported new chain segment blocks=1 txs=273 mgas=12.496 elapsed=1.216s mgasps=10.275 number=10832769 hash=51bc39…2b681b dirty=127.90MiB
INFO [09-10|15:57:44.677] Imported new chain segment blocks=1 txs=253 mgas=12.496 elapsed=774.446ms mgasps=16.135 number=10832770 hash=4485d1…e61833 dirty=127.90MiB
INFO [09-10|15:57:51.106] Imported new chain segment blocks=1 txs=129 mgas=12.498 elapsed=441.170ms mgasps=28.330 number=10832771 hash=27c629…1d5dc2 dirty=127.90MiB
INFO [09-10|15:57:51.279] Chain reorg detected number=10832770 hash=4485d1…e61833 drop=1 dropfrom=27c629…1d5dc2 add=1 addfrom=055cd3…a29d53
INFO [09-10|15:57:51.280] Imported new chain segment blocks=1 txs=116 mgas=12.486 elapsed=172.617ms mgasps=72.335 number=10832771 hash=055cd3…a29d53 dirty=127.90MiB
INFO [09-10|15:58:03.087] Imported new chain segment blocks=1 txs=158 mgas=12.492 elapsed=340.944ms mgasps=36.639 number=10832772 hash=ebf6b0…f9aa4c dirty=127.90MiB
INFO [09-10|15:58:08.593] Deep froze chain segment blocks=6 elapsed=1.040s number=10742771 hash=dc96e0…365518
INFO [09-10|15:58:13.424] Imported new chain segment blocks=1 txs=151 mgas=12.481 elapsed=271.234ms mgasps=46.014 number=10832773 hash=bebad3…ee47d6 dirty=127.90MiB
启动geth客户端
刚才我们通过后台的方式启动了节点。通过以下方式打开geth客户端,加载.ipc文件的办法启动,我们查看如下参数,及说明。
参数 | 说明 |
---|---|
attach | Start an interactive JavaScript environment (connect to node) |
命令如下:
geth attach ipc:/data/gethdata/geth.ipc
//或者
geth attach ipc:http://192.168.31.43:8545
注解:两种方式,都是打开geth客户端,两个命令,实现的功能有区别。第一个,可以开始挖矿。第二个无法开始。还有其他区别。大家研究。今天我们通过第一种办法启动。
显示如下:
Welcome to the Geth JavaScript console!
instance: Geth/v1.9.9-stable-01744997/linux-amd64/go1.13.5
at block: 10832862 (Thu, 10 Sep 2020 16:18:02 CST)
datadir: /data/gethdata
modules: admin:1.0 debug:1.0 eth:1.0 ethash:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0
>
上面告诉你,启动了ETH节点的模块。
admin:1.0 debug:1.0 eth:1.0 ethash:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0
这些模块的使用,会在后续的场景里,做介绍。
现在我们就可以与以太坊网络交互了。以太坊开发团队提供了功能强大的客户端交互工具及交互命令集web3.js,这部分内容,我们会在后续的章节里 详细阐述。
如果操作全球节点,就需要自己购买以太坊,目前以太放价格是400美金一个,还是有点贵。
3、搭建以太放私有链节点
搭建私有链节点,可以更好的与区块链交互,自己挖矿,挖出自己链上的ETH。方便操作网络。更方便我们调试以太坊源代码,甚至,我们可以开发出一套自己适用的区块链出来。开始干吧。
3.1、创世块
现在通过配置创世块来创建私有链。同一个网络中,创世块必须是一样的,否则无法联通。
创建一个eth的根目录,在根目录下新建创世块json文件genesis.json。
cd /data
mkdir gethdata
cd gethdata
vim genesis.json
粘贴如下内容
{
"config": {
"chainId": 8888,
"homesteadBlock": 0,
"daoForkBlock": 0,
"daoForkSupport": true,
"eip150Block": 0,
"eip155Block": 0,
"eip158Block": 0,
"byzantiumBlock": 0,
"constantinopleBlock": 0,
"petersburgBlock": 0,
"ethash": {
}
},
"nonce": "0x42",
"timestamp": "0x0",
"extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa",
"gasLimit": "0xffffffff",
"difficulty": "0x1",
"alloc": {
"093f59f1d91017d30d8c2caa78feb5beb0d2cfaf": {
"balance": "0xffffffffffffffff"
},
"ddf7202cbe0aaed1c2d5c4ef05e386501a054406": {
"balance": "0xffffffffffffffff"
}
}
}
保存文件,输入
:wq
退出编辑模式。
主网默认 chainId 1 ,我们搭建自己的私链,需要设定为 非 1 ,我们设定 8888即可。
参数解释:
参数名称 | 参数描述 |
---|---|
config | 链的一些基本配置 |
nonce | nonce就是一个64位随机数,用于挖矿,注意他和mixhash的设置需要满足以太坊的Yellow paper, 4.3.4. Block Header Validity, (44)章节所描述的条件。 |
difficulty | 设置当前区块的难度,如果难度过大,cpu挖矿就很难,这里设置较小难度 |
alloc | 用来预置账号以及账号的以太币数量,因为私有链挖矿比较容易,所以我们不需要预置有币的账号,需要的时候自己创建即可以。 |
coinbase | 矿工的账号,随便填 |
timestamp | 设置创世块的时间戳 |
extraData | 附加信息,随便填,可以填你的个性信息 |
gasLimit | 该值设置对GAS的消耗总量限制,用来限制区块能包含的交易信息总和,因为我们是私有链,所以填最大。 |
3.2 启动私有链节点
3.2.1 初始化区块链
参数注解:
参数 | 注解 | 备注 |
---|---|---|
init | Bootstrap and initialize a new genesis block | 建立创世区块 |
命令如下
cd /data/
mkdir gethdata //已经创建文件夹的,此处略过。
cd gethdata
geth --datadir "./" init genesis.json
显示如下:
INFO [09-10|17:06:25.183] Maximum peer count ETH=50 LES=0 total=50
INFO [09-10|17:06:25.183] Smartcard socket not found, disabling err="stat /run/pcscd/pcscd.comm: no such file or directory"
INFO [09-10|17:06:25.184] Set global gas cap cap=25000000
INFO [09-10|17:06:25.185] Allocated cache and file handles database=/home/cuijb/geth/geth/chaindata cache=16.00MiB handles=16
INFO [09-10|17:06:25.231] Writing custom genesis block
INFO [09-10|17:06:25.232] Persisted trie from memory database nodes=3 size=407.00B time="71.856µs" gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [09-10|17:06:25.232] Successfully wrote genesis state database=chaindata hash="b25dc8…866dfa"
INFO [09-10|17:06:25.233] Allocated cache and file handles database=/home/cuijb/geth/geth/lightchaindata cache=16.00MiB handles=16
INFO [09-10|17:06:25.239] Writing custom genesis block
INFO [09-10|17:06:25.240] Persisted trie from memory database nodes=3 size=407.00B time="53.712µs" gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [09-10|17:06:25.240] Successfully wrote genesis state database=lightchaindata hash="b25dc8…866dfa"
恭喜,创世区块创建成功。
3.2.3、启动区块链网络
编写启动脚本 start.sh
nohup geth --rpc --rpccorsdomain "*" --datadir "./" --port 30304 --rpcapi "db,eth,net,web3,personal,web3" --networkid 8888 --rpcport 8545 --rpcaddr "0.0.0.0" --allow-insecure-unlock > ./geth.log &2>1
保存脚本。
这里需要特殊说明一下,私有链脚本与主网脚本的区别
参数 | 注解 | 备注 |
---|---|---|
–networkid | Network identifier (integer, 1=Frontier, 3=Ropsten, 4=Rinkeby, 5=Görli) (default: 1) | 8888 |
–allow-insecure-unlock | Allow insecure account unlocking when account-related RPCs are exposed by http |
注解: 1、networkid 选项,主网配置为 1 ,其他3、4、5都是以太坊坊社区部署的测试网络,我们是建立自己的私链,定义为8888。
2、allow-insecure-unlock选项,方便我们解锁节点账户,如果是主网,不建议配置,否则,你存入节点账户的钱,会瞬间被黑客黑走。如何黑走,下面章节,分享黑客如何攻击区块链节点。
启动脚本
sh start.sh
查看log,显示如下:
cuijb@cuijb-VirtualBox:~/geth$ tail -f geth.log
INFO [09-10|20:09:02.427] Regenerated local transaction journal transactions=0 accounts=0
INFO [09-10|20:09:02.433] Allocated fast sync bloom size=512.00MiB
INFO [09-10|20:09:02.471] Initialized fast sync bloom items=3 errorrate=0.000 elapsed=2.759ms
INFO [09-10|20:09:02.473] Starting peer-to-peer node instance=Geth/v1.9.19-stable-3e064192/linux-amd64/go1.14.2
INFO [09-10|20:09:02.501] New local node record seq=1 id=68445c44ed2df2b1 ip=127.0.0.1 udp=30304 tcp=30304
INFO [09-10|20:09:02.504] IPC endpoint opened url=/home/cuijb/geth/geth.ipc
ERROR[09-10|20:09:02.504] Unavailable modules in HTTP API list unavailable=[db] available="[admin debug web3 eth txpool personal ethash miner net]"
INFO [09-10|20:09:02.506] HTTP server started endpoint=[::]:8545 cors=* vhosts=localhost
INFO [09-10|20:09:02.519] Started P2P networking self=enode://36e36f39e9de61f999a1f03830487e11c62d244277e2a3dc8abc5985078560090e6938ef7cb506336433132983ec30653deb1addfca421161e21d691542c8a16@127.0.0.1:30304
INFO [09-10|20:09:04.330] New local node record seq=2 id=68445c44ed2df2b1 ip=223.74.158.88 udp=16706 tcp=30304
INFO [09-10|20:09:12.825] Looking for peers peercount=0 tried=102 static=0
INFO [09-10|20:09:24.156] Looking for peers peercount=0 tried=85 static=0
INFO [09-10|20:09:34.158] Looking for peers peercount=1 tried=64 static=0
如果,显示这样的信息,我们就需要启动矿工。
进入geth客户端( Geth JavaScript console)
命令如下:
geth attach ipc:/data/gethdata/geth.ipc
显示如下:
Welcome to the Geth JavaScript console!
instance: Geth/v1.9.19-stable-3e064192/linux-amd64/go1.14.2
at block: 0 (Thu Jan 01 1970 08:00:00 GMT+0800 (CST))
datadir: /data/gethdata
modules: admin:1.0 debug:1.0 eth:1.0 ethash:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0
>
输入:
eth
如下:
eth
{
accounts: [],
blockNumber: 0,
coinbase: undefined,
compile: {
lll: function(),
serpent: function(),
solidity: function()
},
defaultAccount: undefined,
defaultBlock: "latest",
gasPrice: 1000000000,
hashrate: 0,
mining: false,
pendingTransactions: [],
protocolVersion: "0x41",
syncing: false,
call: function(),
chainId: function(),
contract: function(abi),
estimateGas: function(),
fillTransaction: function(),
filter: function(options, callback, filterCreationErrorCallback),
getAccounts: function(callback),
getBalance: function(),
getBlock: function(),
getBlockByHash: function(),
getBlockByNumber: function(),
getBlockNumber: function(callback),
getBlockTransactionCount: function(),
getBlockUncleCount: function(),
getCode: function(),
getCoinbase: function(callback),
getCompilers: function(),
getGasPrice: function(callback),
getHashrate: function(callback),
getHeaderByHash: function(),
getHeaderByNumber: function(),
getMining: function(callback),
getPendingTransactions: function(callback),
getProof: function(),
getProtocolVersion: function(callback),
getRawTransaction: function(),
getRawTransactionFromBlock: function(),
getStorageAt: function(),
getSyncing: function(callback),
getTransaction: function(),
getTransactionCount: function(),
getTransactionFromBlock: function(),
getTransactionReceipt: function(),
getUncle: function(),
getWork: function(),
iban: function(iban),
icapNamereg: function(),
isSyncing: function(callback),
namereg: function(),
resend: function(),
sendIBANTransaction: function(),
sendRawTransaction: function(),
sendTransaction: function(),
sign: function(),
signTransaction: function(),
submitTransaction: function(),
submitWork: function()
}
这里显示与以太放网络交互的一些方法。
我们看到 accounts: [], 说明,我们还没有创建账户,我们在节点上创建第一个账户。
创建账户
personal.newAccount("111111")
"0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed"
注解:personal.newAccount(“密码”),这个密码,就是我们要操作第一个账户的时候,使用的密码。
查看账户
> eth.accounts
["0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed"]
我么再次geth客户端,输入 eth
> eth
{
accounts: ["0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed"],
blockNumber: 0,
coinbase: "0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed",
compile: {
lll: function(),
serpent: function(),
solidity: function()
},
我们可以清楚看到 accounts[]里多了一个地址。我们再多创建几个地址,你们观察一下。
你们会清楚的看到,accounts[0]=coinbase。
开始挖矿
miner.start()
null
你的矿工,开始帮我挖矿了,你很快就会变成很有钱的人了。
注解:miner.start(number),number默认不填,表示,启动1个线程挖矿,你也可以多启动几个线程开始挖矿,那么number就设定多少。
查询挖矿状态
> eth.mining
true
true 说明,正在挖矿中。
停止挖矿
> miner.stop()
null
查询挖矿状态
> eth.mining
false
false 矿工停止挖矿
启动矿工
miner.start()
null
我们开始查看log信息
cuijb@cuijb-VirtualBox:~/geth$ tail -f geth.log
INFO [09-10|20:29:31.319] Generating DAG in progress epoch=0 percentage=71 elapsed=5m55.753s
INFO [09-10|20:29:33.128] Looking for peers peercount=1 tried=60 static=0
INFO [09-10|20:29:36.133] Generating DAG in progress epoch=0 percentage=72 elapsed=6m0.568s
INFO [09-10|20:29:41.135] Generating DAG in progress epoch=0 percentage=73 elapsed=6m5.570s
INFO [09-10|20:29:43.227] Looking for peers peercount=1 tried=41 static=0
INFO [09-10|20:29:46.176] Generating DAG in progress epoch=0 percentage=74 elapsed=6m10.611s
INFO [09-10|20:29:50.879] Generating DAG in progress epoch=0 percentage=75 elapsed=6m15.314s
INFO [09-10|20:29:53.693] Looking for peers peercount=0 tried=79 static=0
INFO [09-10|20:29:55.444] Generating DAG in progress epoch=0 percentage=76 elapsed=6m19.878s
INFO [09-10|20:30:00.043] Generating DAG in progress epoch=0 percentage=77 elapsed=6m24.478s
INFO [09-10|20:30:03.743] Looking for peers peercount=1 tried=87 static=0
INFO [09-10|20:30:04.725] Generating DAG in progress epoch=0 percentage=78 elapsed=6m29.159s
INFO [09-10|20:30:09.271] Generating DAG in progress epoch=0 percentage=79 elapsed=6m33.706s
INFO [09-10|20:30:13.809] Looking for peers peercount=0 tried=18 static=0
INFO [09-10|20:30:14.240] Generating DAG in progress epoch=0 percentage=80 elapsed=6m38.675s
INFO [09-10|20:30:19.477] Generating DAG in progress epoch=0 percentage=81 elapsed=6m43.912s
INFO [09-10|20:30:24.011] Looking for peers peercount=0 tried=94 static=0
INFO [09-10|20:30:24.489] Generating DAG in progress epoch=0 percentage=82 elapsed=6m48.924s
INFO [09-10|20:30:29.588] Generating DAG in progress epoch=0 percentage=83 elapsed=6m54.023s
INFO [09-10|20:30:34.314] Looking for peers peercount=1 tried=80 static=0
INFO [09-10|20:30:34.316] Generating DAG in progress epoch=0 percentage=84 elapsed=6m58.751s
INFO [09-10|20:30:39.184] Generating DAG in progress epoch=0 percentage=85 elapsed=7m3.619s
INFO [09-10|20:30:44.269] Generating DAG in progress epoch=0 percentage=86 elapsed=7m8.703s
INFO [09-10|20:30:44.447] Looking for peers peercount=0 tried=65 static=0
INFO [09-10|20:30:49.497] Generating DAG in progress epoch=0 percentage=87 elapsed=7m13.932s
INFO [09-10|20:30:54.345] Generating DAG in progress epoch=0 percentage=88 elapsed=7m18.780s
INFO [09-10|20:30:54.475] Looking for peers peercount=1 tried=69 static=0
INFO [09-10|20:30:59.214] Generating DAG in progress epoch=0 percentage=89 elapsed=7m23.649s
INFO [09-10|20:31:04.078] Generating DAG in progress epoch=0 percentage=90 elapsed=7m28.513s
INFO [09-10|20:31:04.477] Looking for peers peercount=0 tried=29 static=0
INFO [09-10|20:31:09.165] Generating DAG in progress epoch=0 percentage=91 elapsed=7m33.599s
INFO [09-10|20:31:14.419] Generating DAG in progress epoch=0 percentage=92 elapsed=7m38.854s
INFO [09-10|20:31:14.640] Looking for peers peercount=2 tried=107 static=0
INFO [09-10|20:31:19.658] Generating DAG in progress epoch=0 percentage=93 elapsed=7m44.093s
INFO [09-10|20:31:24.834] Generating DAG in progress epoch=0 percentage=94 elapsed=7m49.269s
INFO [09-10|20:31:30.079] Generating DAG in progress epoch=0 percentage=95 elapsed=7m54.514s
INFO [09-10|20:31:34.749] Looking for peers peercount=1 tried=24 static=0
INFO [09-10|20:31:34.943] Generating DAG in progress epoch=0 percentage=96 elapsed=7m59.378s
INFO [09-10|20:31:40.429] Generating DAG in progress epoch=0 percentage=97 elapsed=8m4.864s
INFO [09-10|20:31:44.820] Looking for peers peercount=1 tried=101 static=0
INFO [09-10|20:31:45.436] Generating DAG in progress epoch=0 percentage=98 elapsed=8m9.871s
INFO [09-10|20:31:50.699] Generating DAG in progress epoch=0 percentage=99 elapsed=8m15.134s
INFO [09-10|20:31:50.702] Generated ethash verification cache epoch=0 elapsed=8m15.137s
INFO [09-10|20:31:52.354] Successfully sealed new block number=1 sealhash="b1077b…7283ce" hash="3de7b9…309a81" elapsed=8m17.473s
INFO [09-10|20:31:52.354] mined potential block number=1 hash="3de7b9…309a81"
INFO [09-10|20:31:52.375] Commit new mining work number=2 sealhash="ac6dd9…0f2149" uncles=0 txs=0 gas=0 fees=0 elapsed="139.91µs"
INFO [09-10|20:31:54.845] Looking for peers peercount=1 tried=46 static=0
INFO [09-10|20:32:02.128] Generating DAG in progress epoch=1 percentage=0 elapsed=9.724s
INFO [09-10|20:32:04.014] Successfully sealed new block number=2 sealhash="ac6dd9…0f2149" hash="1297c3…6287c5" elapsed=11.639s
INFO [09-10|20:32:04.015] mined potential block number=2 hash="1297c3…6287c5"
INFO [09-10|20:32:04.015] Commit new mining work number=3 sealhash="b05dc9…0b3b20" uncles=0 txs=0 gas=0 fees=0 elapsed="149.168µs"
INFO [09-10|20:32:04.764] Successfully sealed new block number=3 sealhash="b05dc9…0b3b20" hash="3ef80c…559305" elapsed=749.123ms
INFO [09-10|20:32:04.764] mined potential block number=3 hash="3ef80c…559305"
INFO [09-10|20:32:04.765] Commit new mining work number=4 sealhash="c42df7…426749" uncles=0 txs=0 gas=0 fees=0 elapsed="98.08µs"
INFO [09-10|20:32:05.117] Looking for peers peercount=1 tried=72 static=0
INFO [09-10|20:32:08.364] Successfully sealed new block number=4 sealhash="c42df7…426749" hash="9ef7c2…9c4a9f" elapsed=3.599s
INFO [09-10|20:32:08.364] mined potential block number=4 hash="9ef7c2…9c4a9f"
INFO [09-10|20:32:08.365] Commit new mining work number=5 sealhash="d780b4…9ef989" uncles=0 txs=0 gas=0 fees=0 elapsed="239.711µs"
INFO [09-10|20:32:08.670] Successfully sealed new block number=5 sealhash="d780b4…9ef989" hash="110d9b…b27f30" elapsed=305.643ms
INFO [09-10|20:32:08.671] mined potential block number=5 hash="110d9b…b27f30"
注解:
1、Generating DAG in progress 中 percentage 一定要达到 100
后,网络才能启动,矿工开始有收益。
2、显示 Successfully sealed new block number=1 sealhash=“b1077b…7283ce” hash=“3de7b9…309a81” elapsed=8m17.473s 说明,矿工已经开始工作。矿工已经开始帮主人赚钱了。
查看我们的收益,输入如下命令:
切换geth客户端
eth.getBalance(eth.accounts[0])
120000000000000000000
矿工才开始工作,我的账户有很多 ETH币,其实不要多想,我们看到的数量单位只是Wei。
3.2、Ether币的基本单位
Ether币最小的单位是Wei,也是命令行默认的单位, 然后每1000个进一个单位,依次是
简单地说就是就是1 以太币 = 1000000000000000000 Wei (10的18次方wei)
上面查询余额,其实是很少的。
3.3 、如何进行ether 和 Wei之间的转换
Ether–> Wei:web3.toWei
> web3.toWei(1)
"1000000000000000000"
> web3.toWei(1.2345678)
"1234567800000000000"
>
Wei –> Ether: web3.fromWei
> web3.fromWei(10000000000000000)
"0.01"
> web3.fromWei(1000000000000000000)
"1"
>
现在再次查询一下,我的余额
> web3.fromWei(eth.getBalance(eth.coinbase))
1566
3.4 转账操作
再创建一个账户
> personal.newAccount("111111")
"0xab9836f46e51fb4e25e3aaa248a441d86595b628"
查询账户列表
> eth.accounts
["0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed", "0xab9836f46e51fb4e25e3aaa248a441d86595b628"]
开始转账
/*定义第一个账户*/
> acc0=eth.accounts[0]
"0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed"
/*定义第二个账户*/
> acc1=eth.accounts[1]
"0xab9836f46e51fb4e25e3aaa248a441d86595b628"
/*定义转账金额,转为为Wei*/
> amount = web3.toWei(12.345)
"12345000000000000000"
/*解锁第一个账户*/
> personal.unlockAccount(acc0)
Unlock account 0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed
Passphrase:
true
/*开始转账*/
> eth.sendTransaction({
from:acc0,to:acc1,value:amount})
"0xd2ee2d8c73bad76e07d0c7d7551ca2dc0ea5ac615cfb627408853d67b1ad1819"
/*查询第二个账户余额*/
> web3.fromWei(eth.getBalance(acc1))
12.345
/*链上查询这笔交易情况*/
> eth.getTransaction("0xd2ee2d8c73bad76e07d0c7d7551ca2dc0ea5ac615cfb627408853d67b1ad1819")
{
blockHash: "0xf35ddb73525baeecb248045908568f752bd9b2fb77f78da0532778219360729f",
blockNumber: 828,
from: "0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed",
gas: 21000,
gasPrice: 1000000000,
hash: "0xd2ee2d8c73bad76e07d0c7d7551ca2dc0ea5ac615cfb627408853d67b1ad1819",
input: "0x",
nonce: 0,
r: "0x31ef99aa435375cfc90d33ff25314868586ba8967ff2d0e1bc44a9ac32891b0e",
s: "0x3655f99471c93ed9894edc0dffdf281fba8b081bc9dbd07dfaa241c5a77ff105",
to: "0xab9836f46e51fb4e25e3aaa248a441d86595b628",
transactionIndex: 0,
v: "0x4594",
value: 12345000000000000000
}
/*链上查询这笔交易凭据*/
>eth.getTransactionReceipt("0xd2ee2d8c73bad76e07d0c7d7551ca2dc0ea5ac615cfb627408853d67b1ad1819")
{
blockHash: "0xf35ddb73525baeecb248045908568f752bd9b2fb77f78da0532778219360729f",
blockNumber: 828,
contractAddress: null,
cumulativeGasUsed: 21000,
from: "0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed",
gasUsed: 21000,
logs: [],
logsBloom: "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
status: "0x1",
to: "0xab9836f46e51fb4e25e3aaa248a441d86595b628",
transactionHash: "0xd2ee2d8c73bad76e07d0c7d7551ca2dc0ea5ac615cfb627408853d67b1ad1819",
transactionIndex: 0
}
>
我们体验了一次从 account[0] ----> account[1] 转移了 12.345 个ETH 的过程。
通过这两章的练习,我们思考一下:
1、转移的12.345个ETH,区块链将数据保存在哪里。
2、通过这笔转账,我们思考一下 ,一个交易的生命周期。
大家可以将自己的思考,在下面留言,一起交流。
2020年9月10日晚。