geth 基本使用

概要

geth 是以太坊的官方 golang 客户端. 经过 geth 的使用能够直观的了解以太坊, 乃至区块链的运做.javascript

下面, 经过 geth 来构造一次搭建私链, 建立帐户, 挖矿, 交易的流程.java

搭建私链

作实验, 搭建私链是第一步, 若是直接在 ETH 公链上实验的话, 会消耗真实的以太币, 并且在真实的公链上, 我的的电脑几乎不可能挖到矿的.git

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

genesis.json:golang

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

配置以后, 启动web

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

建立帐户

建立帐户很简单, 登陆 geth 的 javascript consolejson

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

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

登陆以后:区块链

> 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
相关文章
相关标签/搜索