使用Geth搭建私链
Go-ethereum客户端通常被称为Geth,它是个命令行界面,执行在Go上实现的完整以太坊节点。Geth得益于Go语言的多平台特性,支持在多个平台上使用(比如Windows、Linux、Mac)。Geth是以太坊协议的具体落地实现,通过Geth,你可以实现以太坊的各种功能,如账户的新建编辑删除,开启挖矿,ether币的转移,智能合约的部署和执行等等。以下操作均在windows平台下操作
安装
前往官网下载https://geth.ethereum.org/downloads/
下载完成后,找个目录安装即可
测试
- 将安装目录配置到环境变量中
- 版本测试
在cmd中输入
geth -version
显示:
Incorrect Usage. flag provided but not defined: -version
NAME:
geth - the go-ethereum command line interface
Copyright 2013-2021 The go-ethereum Authors
USAGE:
geth [options] [command] [command options] [arguments...]
VERSION:
1.10.4-stable-aa637fd3
......
搭建
建立一个文件夹privatechain,用来保存初始化信息
在该文件夹下再建一个名为data0的文件夹用来保存数据
以及一个json文件,例如:genesis.json
具体内容可为:
{
"config": {
"chainId": 6668,
"homesteadBlock": 0,
"eip150Block": 0,
"eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"eip155Block": 0,
"eip158Block": 0,
"byzantiumBlock": 0,
"constantinopleBlock": 0,
"petersburgBlock": 0,
"istanbulBlock": 0,
"ethash": {}
},
"nonce": "0x0",
"timestamp": "0x5ddf8f3e",
"extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
"gasLimit": "0x47b760",
"difficulty": "20000",
"mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"coinbase": "0x0000000000000000000000000000000000000000",
"alloc": {
},
"number": "0x0",
"gasUsed": "0x0",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000"
}
之后确保在privatechain目录下
执行命令
geth --datadir data0 init genesis.json
geth --datadir data0 --networkid 6668 console --nodiscover
后续启动时采用:
geth --datadir data0 --networkid 6668 --rpc console --nodiscover 2>output.log --allow-insecure-unlock
快速启动:
geth --datadir . --networkid 6668 --dev --rpc console --nodiscover 2>output.log.
操作
- 查看账户
eth.accounts
- 创建一个新账户
personal.newAccount()
- 解锁一个账户(此处采用第0个账户)
personal.unlockAccount(eth.accounts[0])
- 查询账户余额
eth.getBalance(eth.accounts[0])
- 启动&停止挖矿
start的10表示启动10个线程来操作
miner.start(10)
miner.stop
- 查询矿工账户
默认为第一个账户
eth.coinbase
- 将wei转换为以太币
getBalance()返回值的单位是wei,wei是以太币的最小单位,1个以太币=10的18次方个wei。要查看有多少个以太币,可以用web3.fromWei()将返回值换算成以太币:
web3.fromWei(eth.getBalance(eth.accounts[0]),'ether')
- 转账
转账后要有人挖矿才能成功
eth.sendTransaction({from: eth.accounts[0],to:eth.accounts[1],value:web3.toWei(10,'ether')})
- 查看交易
eth.getTransaction("交易哈希")
- 查看区块
eth.getBlock(int block)
其他
Json-RPC调用
例子:
curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":1}' http://localhost:8545