区块链笔记(1)-使用go-ethereum建立私链 geth版本 1.8.1

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lhtzbj12/article/details/79405238

1、安装go-ethereum客户端

当前版本1.8.1,make之前先安装golang的环境,笔者golang版本1.9.2,ubuntu 17.10

git clone https://github.com/ethereum/go-ethereum.git
cd  go-ethereum
make geth

2、初始化

找个地方新建文件genesis.json,下面的内容来自官网,但是chainId不为0,否则出现insufficient funds for gas * price + value

{
  "config": {
        "chainId": 12,
        "homesteadBlock": 0,
        "eip155Block": 0,
        "eip158Block": 0
    },
  "alloc"      : {},
  "coinbase"   : "0x0000000000000000000000000000000000000000",
  "difficulty" : "0x20000",
  "extraData"  : "",
  "gasLimit"   : "0x2fefd8",
  "nonce"      : "0x0000000000000042",
  "mixhash"    : "0x0000000000000000000000000000000000000000000000000000000000000000",
  "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
  "timestamp"  : "0x00"
}

在终端使用以下命令进行初始化

geth init ./genesis.json --datadir "./chain"

显示结果

$ geth init ./genesis.json --datadir './chain'
INFO [02-28|10:25:05] Maximum peer count                       ETH=25 LES=0 total=25
INFO [02-28|10:25:05] Allocated cache and file handles         database=E:\\Projects\\Geth\\'\\chain'\\geth\\chaindata cache=16 handles=16
INFO [02-28|10:25:05] Writing custom genesis block
INFO [02-28|10:25:05] Persisted trie from memory database      nodes=0 size=0.00B time=7.0004ms gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [02-28|10:25:05] Successfully wrote genesis state         database=chaindata                                      hash=5e1fc7…d790e0
INFO [02-28|10:25:05] Allocated cache and file handles         database=E:\\Projects\\Geth\\'\\chain'\\geth\\lightchaindata cache=16 handles=16
INFO [02-28|10:25:06] Writing custom genesis block
INFO [02-28|10:25:06] Persisted trie from memory database      nodes=0 size=0.00B time=0s       gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [02-28|10:25:06] Successfully wrote genesis state         database=lightchaindata                                      hash=5e1fc7…d790e0

3、启用私链

注:下面的命令将把日志输入到eth_output.log,并开启Geth javascript console(后面简称web3 console)

geth --networkid 12 --datadir "./chain" --nodiscover  console  2>>eth_output.log
参数 参数说明
datadir 设置当前区块链网络数据存放的位置
console 启动命令行模式,可以在geth里执行命令
nodiscover 关闭p2p网络的自动发现,不会被网上看到
networkid 网络标识,私有链取一个大于4的随意的值

使用下面的命令查看日志

tail -f eth_output.log

内容如下:

~/geth$ tail -f eth_output.log
INFO [02-27|22:13:16] Initialising Ethereum protocol           versions="[63 62]" network=1
INFO [02-27|22:13:16] Database deduplication successful        deduped=0
INFO [02-27|22:13:16] Loaded most recent local header          number=0 hash=7d416a…b75a26 td=65536
INFO [02-27|22:13:16] Loaded most recent local full block      number=0 hash=7d416a…b75a26 td=65536
INFO [02-27|22:13:16] Loaded most recent local fast block      number=0 hash=7d416a…b75a26 td=65536
INFO [02-27|22:13:16] Regenerated local transaction journal    transactions=0 accounts=0
INFO [02-27|22:13:16] Starting P2P networking 
INFO [02-27|22:13:16] RLPx listener up                         self="enode://287b1fb473949dbbbb4edc63e92de98b1021b91c50f68b07f75cf47e0f8253e0f439f6f86e7b49fcf760e6f5f24b9938f83156fca8efd1bc74e1bd4f97cf3e6b@[::]:30303?discport=0"
INFO [02-27|22:13:16] IPC endpoint opened                      url=/home/sd/geth/chain/geth.ipc
INFO [02-27|22:13:16] Mapped network port                      proto=tcp extport=30303 intport=30303 interface=NAT-PMP(192.168.31.1)

在web3 console里内置了一些用来操作以太坊的Javascript对象。主要有:

  • eth:包含一些跟操作区块链相关的方法
  • net:包含以下查看p2p网络状态的方法
  • admin:包含一些与管理节点相关的方法
  • miner:包含启动&停止挖矿的一些方法
  • personal:主要包含一些管理账户的方法
  • txpool:包含一些查看交易内存池的方法
  • web3:包含了以上对象,还包含一些单位换算的方法

4、新建帐户

下面的命令不做特殊说明,都是在web3 console里输入

可以用下面命令查看已有帐户

eth.accounts

创建帐户,下面123456是密码,执行2次,建立两个帐户用于后面的转帐

personal.newAccount("123456")

会在 datadir(当前文中为./chain)里生成keystore,每个帐户一个文件,内容示例如下

{
    "address": "514b18f2054ecd174ef00f79e5e6b6df3ef4494d",
    "crypto": {
        "cipher": "aes-128-ctr",
        "ciphertext": "4531f38141f9daaad578c6e00b99f47aa374f36c2a87d0ffbafb1ca0b33f1fe0",
        "cipherparams": {
            "iv": "b120f958450c12504c8d54afe170c250"
        },
        "kdf": "scrypt",
        "kdfparams": {
            "dklen": 32,
            "n": 262144,
            "p": 1,
            "r": 8,
            "salt": "e0d8f92937268ab78b78a669a66e59d2db5f8562b1fdb3c6cfc60ce95c1bc20f"
        },
        "mac": "6bf3a5946e638fc4ea2a95c08997380238d1be189eb044fbe68fe58a36d7c6bd"
    },
    "id": "c30cb668-a8b7-406c-9ac8-eab245dec9c1",
    "version": 3
}

5、挖矿

设置挖矿的帐户(可以跳过,直接start使用第1个帐户挖矿)
使用的命令查看coinbase的账户地址

eth.coinbase

设置coinbase

miner.setEtherbase(eth.accounts[0])

开始挖矿,默认使用第1个帐户挖矿

miner.start()

挖到时,显示内容如下:

INFO [02-27|22:26:25] ? block reached canonical chain          number=86 hash=164326…acb82f
INFO [02-27|22:26:25] ? mined potential block                  number=91 hash=8f7693…1aa8b9
INFO [02-27|22:26:25] Commit new mining work                   number=92 txs=0 uncles=0 elapsed=208.882µs
INFO [02-27|22:26:27] Successfully sealed new block            number=92 hash=efdd93…daae6e

停止挖矿,停止挖矿后,以太币则不会产生,同样智能合约、转帐等操作也不会起作用。

miner.stop()

查看余额,以太币最小单位是wei(18个0),可以用formWei进行格式化

acc0 = web3.eth.accounts[0] //给帐户取别名
eth.getBalance(acc0)        //显示以wei为单位
web3.fromWei(eth.getBalance(acc0))  //显示以ether为单位

可以写javascript脚本,查看所有帐户余额
allBal.js,不支持let等ES5以后的特性

function AllBalance() {
    var totalBalance = 0
    for(var acci in eth.accounts){
        var acc = web3.eth.accounts[acci]
        var balance = web3.fromWei(web3.eth.getBalance(acc))
        console.log('account:'+acc+'\t balance:'+balance+'  ether')
        totalBalance += parseFloat(balance)
    }
    console.log('total balance: '+totalBalance)
}
AllBalance()

在web3 console里使用以下命令加载js

loadScript('allBal.js')

6、转帐

从第1个帐户转3 ether到第2个帐户,在挖矿时,转帐结果才生效

//给账户取个别名
acc0 = web3.eth.accounts[0]
acc1 = web3.eth.accounts[1]
eth.sendTransaction({from:acc0,to:acc1,value:web3.toWei(3,"ether")})

如果错误提示:authentication needed:password or unlock
则需要先解锁,从第1帐户转出,因此解锁第1个帐户

personal.unlockAccount(acc0,"123456")

解锁完成后,再进行转帐

eth.sendTransaction({from:acc0,to:acc1,value:web3.toWei(3,"ether")})

7、疑问

  • 挖到矿以后,关闭终端,再打开终端,查余额为0?

猜你喜欢

转载自blog.csdn.net/lhtzbj12/article/details/79405238
今日推荐