geth 基本使用

概要

geth 是以太坊的官方 golang 客户端. 通过 geth 的使用可以直观的了解以太坊, 乃至区块链的运作.

下面, 通过 geth 来构造一次搭建私链, 创建账户, 挖矿, 交易的流程.

搭建私链

做实验, 搭建私链是第一步, 如果直接在 ETH 公链上实验的话, 会消耗真实的以太币, 而且在真实的公链上, 个人的电脑几乎不可能挖到矿的.

通过 geth 搭建私链很简单, 首先需要定义创世区块, 参考: https://github.com/ethereum/go-ethereum/wiki/Private-network

genesis.json:

{
  "config": {
    "chainId": 100,
    "homesteadBlock":0,
    "eip155Block":0,
    "eip158Block":0
  },
  "nonce": "0x0000000000000042",
  "timestamp": "0x0",
  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "gasLimit": "0x80000000",
  "difficulty": "0x1",
  "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "coinbase": "0x3333333333333333333333333333333333333333",
  "alloc": {     }
}

配置之后, 启动

mkdir geth-test
cd geth-test
geth --datadri ./data init genesis.json

创建账户

创建账户很简单, 登录 geth 的 javascript console

geth --datadir ./data --networkid 100 console

其中 networkid 就是 genesis.json 中配置的 chainId

登录之后:

> personal.newAccount()   # 创建新的账户
> eth.accounts            # 查看目前有哪些账户

挖矿

开始挖矿很简单, 接着在上面的 console 中操作

> miner.start()

等待几分钟之后, 再

> miner.stop() 

我的测试机器 2CPU 8G 内存, 大概挖了 5 分钟, 挖到的 eth 如下:

> acc0 = eth.accounts[0]   # 这个私链上目前只有一个测试账号
> eth.getBalance(acc0)     # 这里使用 wei 作为单位
2.46e+21
> web3.fromWei(eth.getBalance(acc0), 'ether')  # 相当于 2460 个以太币
2460

私链上挖到的以太币是不能在公链交易的, 这个是用来测试用的, 不然就发了 😃

交易

挖矿很简单, 交易也简单, 为了交易, 我们还需要再创建一个账户

> personal.newAccount()
> eth.accounts
["0xd4b42869954689395e502daa6dd9a02aa34dbaff", "0x500aaa5b196741a4c768fa972b5f16a7e0c9c1e5"]
> acc0 = eth.accounts[0]
> acc1 = eth.accounts[1]
> web3.fromWei(eth.getBalance(acc0), 'ether')   # acc0 的余额
2460
> web3.fromWei(eth.getBalance(acc1), 'ether')   # acc1 的余额
0
> val = web3.toWei(1)   # 准备转账的金额 1 eth
"1000000000000000000"

> eth.sendTransaction({from: acc0, to: acc1, value: val})     # 执行转账, 如果这里出现错误, 提示账户被锁定的话, 解锁账户
> personal.unlockAccount(acc0)                                # 解锁时, 输入创建账户时的密码
Unlock account 0xd4b42869954689395e502daa6dd9a02aa34dbaff
Password:
true

> eth.sendTransaction({from: acc0, to: acc1, value: val})     # 再次转账, 这次应该能够成功, 如果第一次就成功的话, 不需要这步

# 再次查看余额, 发现2个账户的余额没变
> web3.fromWei(eth.getBalance(acc0), 'ether')
2460
> web3.fromWei(eth.getBalance(acc1), 'ether')
0

# 余额没变, 是因为我们前面已经停止挖矿(miner.stop()), 没有矿工来确认这笔交易了
> miner.start()
> miner.stop()     # 启动10来秒左右再 stop

# 再次查看余额, acc1 账户上多了 1 个以太币, 但是 acc0的以太币不减反增, 这是因为刚才的挖矿产生的以太币以及交易手续费都给了 acc0
# 这里的挖矿时如果不指定账号, 默认会把挖到的以太币给 eth.accounts 中的第一个账号
> web3.fromWei(eth.getBalance(acc0), 'ether')
2494
> web3.fromWei(eth.getBalance(acc1), 'ether')
1
posted @ 2019-09-17 18:50  wang_yb  阅读(6507)  评论(0编辑  收藏  举报