美文网首页
二、搭建以太坊私链及客户端基本操作

二、搭建以太坊私链及客户端基本操作

作者: 7f027f718030 | 来源:发表于2018-03-20 14:04 被阅读0次

1、搭建私有链,创建自己的创始区块

建立私链根目录

$makedir geth-private-chain
$cd get-private-chain

创始区块的配置写在json文件中,我们需要将下面文件的内容保存为一个json文件
ps:下面所有操作的根目录都为: get-private-chain

{
      "config": {
        "chainId": 10, 
        "homesteadBlock": 0,
        "eip155Block": 0,
        "eip158Block": 0
      },
   "alloc"   : {},
   "coinbase"  : "0x0000000000000000000000000000000000000000",
   "difficulty" : "0x20000",
   "extraData" : "",
   "gasLimit"  : "0x2fefd8",
   "nonce"   : "0x0000000000000042",
   "mixhash"  :"0x0000000000000000000000000000000000000000000000000000000000000000",
   "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
   "timestamp" : "0x00"
}
KEY
mixhash 与nonce配合用于挖矿,由上一个区块的一部分生成的hash。注意他和nonce的设置需要满足以太坊的Yellow paper, 4.3.4. Block Header Validity, (44)章节所描述的条件。
nonce nonce就是一个64位随机数,用于挖矿,注意他和mixhash的设置需要满足以太坊的Yellow paper, 4.3.4. Block Header Validity, (44)章节所描述的条件。
difficulty 设置当前区块的难度,如果难度过大,cpu挖矿就很难,这里设置较小难度
alloc 用来预置账号以及账号的以太币数量,因为私有链挖矿比较容易,所以我们不需要预置有币的账号,需要的时候自己创建即可以。
coinbase 矿工的账号,随便填
timestamp 设置创世块的时间戳
parentHash 上一个区块的hash值,因为是创世块,所以这个值是0
extraData 附加信息,随便填,可以填你的个性信息
gasLimit 该值设置对GAS的消耗总量限制,用来限制区块能包含的交易信息总和,因为我们是私有链,所以填最大。

此文件可以从官网直接复制,原始的chainId为0,但有可能在部署合约时出现问题,建议修改为10或其他数字

建立存放区块数据的目录

$makedir data0

目录结构为

geth-private-chain
|-----data0
|-----genesis.json
$ ls
data0       genesis.json

初始化以太坊私链数据

$ geth init genesis.json --datadir data0

geth是命令,init是命令选项,genesis.json 是init的参数,表示按照配置文件进行初始化。--datadir data0,指定区块链的数据存放目录为data0。

运行命令,执行的结果如下,表示初始化成功:

INFO [03-12|14:36:52] Maximum peer count                 ETH=25 LES=0 total=25
INFO [03-12|14:36:52] Allocated cache and file handles   database=/Users/HaoZai/geth-private-chian/data0/geth/chaindata cache=16 handles=16
INFO [03-12|14:36:52] Writing custom genesis block 
INFO [03-12|14:36:52] Persisted trie from memory database nodes=0 size=0.00B time=136.941µs gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [03-12|14:36:52] Successfully wrote genesis state database=chaindata                hash=5e1fc7…d790e0
INFO [03-12|14:36:52] Allocated cache and file handles database=/Users/HaoZai/geth-private-chian/data0/geth/lightchaindata cache=16 handles=16
INFO [03-12|14:36:52] Writing custom genesis block 
INFO [03-12|14:36:52] Persisted trie from memory       database   nodes=0 size=0.00B time=1.775µs  gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [03-12|14:36:52] Successfully wrote genesis state database=lightchaindata              hash=5e1fc7…d790e0

初始化成功后,会生成如下的目录结构

geth-private-chian/ 
|----data0/
|      |----geth/
|      |      |---chaindata/          //存放数据区块的目录
|      |      |    |---000001.log
|      |      |    |---LOG
|      |      |    |---CURRENT
|      |      |    |---LOCK
|      |      |    |---MANIFEST-000000
|      |      |----lightchaindata/
|      |----keystore/                   //存放用户信息的目录,此时为空,刚初始化,还未创建任何用户
|----genesise.json
Haozai-Macbook:geth-private-chian HaoZai$ geth --datadir data0 --networkid 1108 console
INFO [03-12|14:41:23] Maximum peer count            ETH=25 LES=0 total=25
INFO [03-12|14:41:23] Starting peer-to-peer node        instance=Geth/v1.8.2-stable/darwin-amd64/go1.10
INFO [03-12|14:41:23] Allocated cache and file handles     database=/Users/HaoZai/geth-private-chian/data0/geth/chaindata cache=768 handles=128
WARN [03-12|14:41:23] Upgrading database to use lookup entries 
INFO [03-12|14:41:23] Database deduplication successful    deduped=0
INFO [03-12|14:41:23] Initialised chain configuration     config="{ChainID: 10 Homestead: 0 DAO: <nil> DAOSupport: false EIP150: <nil> EIP155: 0 EIP158: 0 Byzantium: <nil> Constantinople: <nil> Engine: unknown}"
INFO [03-12|14:41:23] Disk storage enabled for ethash caches  dir=/Users/HaoZai/geth-private-chian/data0/geth/ethash count=3
INFO [03-12|14:41:23] Disk storage enabled for ethash DAGs   dir=/Users/HaoZai/.ethash               count=2
INFO [03-12|14:41:23] Initialising Ethereum protocol      versions="[63 62]" network=1108
INFO [03-12|14:41:23] Loaded most recent local header     number=0 hash=5e1fc7…d790e0 td=131072
INFO [03-12|14:41:23] Loaded most recent local full block   number=0 hash=5e1fc7…d790e0 td=131072
INFO [03-12|14:41:23] Loaded most recent local fast block   number=0 hash=5e1fc7…d790e0 td=131072
INFO [03-12|14:41:23] Regenerated local transaction journal  transactions=0 accounts=0
INFO [03-12|14:41:23] Starting P2P networking 
INFO [03-12|14:41:25] UDP listener up             self=enode://43e1647742e194501c44f2b765e06366d3ede47355e3c158c642e22a1a1c13288b492e6c02d27554ee26d9dcb91a032a09e6aeebac01fe98bbcc212296fa1ca8@[::]:30303
INFO [03-12|14:41:25] RLPx listener up            self=enode://43e1647742e194501c44f2b765e06366d3ede47355e3c158c642e22a1a1c13288b492e6c02d27554ee26d9dcb91a032a09e6aeebac01fe98bbcc212296fa1ca8@[::]:30303
INFO [03-12|14:41:25] IPC endpoint opened         url=/Users/HaoZai/geth-private-chian/data0/geth.ipc

Welcome to the Geth JavaScript console!

instance: Geth/v1.8.2-stable/darwin-amd64/go1.10
modules: admin:1.0 debug:1.0 eth:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0
>
  • 查看私链下的账户
> eth.accounts
[]

PS:初始化不会创建账户,keystore目录为空,还不存在任何账户

  • 新建账户,两种方式
> personal.newAccount()   //通过密码形式创建张华
Passphrase: 
Repeat passphrase: 
"0xe2d463c53f5b4b8c48420304965af10db7290b65"
> 
> personal.newAccount('1111')  //把密码作为参数创建账户
"0xf7cd6aee057409e8ecfa88a8e5b18033d456ff05"
> eth.accounts
["0xe2d463c53f5b4b8c48420304965af10db7290b65", "0xf7cd6aee057409e8ecfa88a8e5b18033d456ff05"]

再次运行查看账户命令,以数组形式返回刚才创建的两个账户

  • 查看每个账户下的以太币数量
> u0=eth.accounts[0]
"0xe2d463c53f5b4b8c48420304965af10db7290b65"
> u1=eth.accounts[1]
"0xf7cd6aee057409e8ecfa88a8e5b18033d456ff05"

> eth.getBalance(u0)
0
> eth.getBalance(u1)
0

PS:只是创建了账户,还未经过任何交易或挖矿奖励,因此这里每个账户的比特币数量都是0,

  • 启动挖矿命令
>miner.start(2)  //这里的参数2,指启动两个现成进行挖矿

返回如下结果(忽略其中很多无用的输出,检出重点)

INFO [03-12|14:55:37] Updated mining threads          threads=2 //线程数为 2
INFO [03-12|14:55:37] Transaction pool price threshold updated price=18000000000
INFO [03-12|14:55:37] Etherbase automatically configured    address=0xE2D463c53f5b4b8c48420304965af10Db7290B65 //自动设置第一个账户为矿机账号
INFO [03-12|14:55:37] Starting mining operation 
null  //此处为start命令返回的结果,按道理应该是 true,为什么是 null?
//第 1 个区块
INFO [03-12|14:55:37] Commit new mining work          number=1 txs=0 uncles=0 elapsed=423.284µs
INFO [03-12|14:58:27] Successfully sealed new block      number=1 hash=516d22…7b94ac
INFO [03-12|14:58:27] mined potential block         number=1 hash=516d22…7b94ac
//第 2 个区块
INFO [03-12|14:58:27] Commit new mining work          number=2 txs=0 uncles=0 elapsed=131.175µs
INFO [03-12|14:58:29] Successfully sealed new block      number=2 hash=700256…f3f9c4
INFO [03-12|14:58:29] 🔨 mined potential block         number=2 hash=700256…f3f9c4
//第 3 个区块
INFO [03-12|14:58:29] Commit new mining work          number=3 txs=0 uncles=0 elapsed=123.273µs
INFO [03-12|14:58:29] Successfully sealed new block      number=3 hash=93f7de…005bdc
INFO [03-12|14:58:29] 🔨 mined potential block         number=3 hash=93f7de…005bdc

INFO [03-12|14:58:29] Commit new mining work          number=4 txs=0 uncles=0 elapsed=161.181µs
INFO [03-12|14:58:32] Successfully sealed new block      number=4 hash=c056e9…5e0b12
INFO [03-12|14:58:32] 🔨 mined potential block         number=4 hash=c056e9…5e0b12

INFO [03-12|14:58:32] Commit new mining work          number=5 txs=0 uncles=0 elapsed=136.386µs
INFO [03-12|14:58:34] Successfully sealed new block      number=5 hash=dd22e3…b04d54
INFO [03-12|14:58:34] 🔨 mined potential block         number=5 hash=dd22e3…b04d54

INFO [03-12|14:58:34] Commit new mining work          number=6 txs=0 uncles=0 elapsed=170.81µs
INFO [03-12|14:58:43] Successfully sealed new block      number=6 hash=4b2f3f…910609
INFO [03-12|14:58:43] 🔨 mined potential block         number=6 hash=4b2f3f…910609

INFO [03-12|14:58:43] Commit new mining work          number=7 txs=0 uncles=0 elapsed=119.437µs
INFO [03-12|14:58:43] Successfully sealed new block      number=7 hash=e40528…354748
INFO [03-12|14:58:43] 🔗 block reached canonical chain     number=2 hash=700256…f3f9c4
INFO [03-12|14:58:43] 🔨 mined potential block         number=7 hash=e40528…354748
//第 8 个区块
INFO [03-12|14:58:43] Commit new mining work          number=8 txs=0 uncles=0 elapsed=248.772µs
INFO [03-12|14:58:46] Successfully sealed new block      number=8 hash=4fad7c…5e318e
INFO [03-12|14:58:46] 🔗 block reached canonical chain     number=3 hash=93f7de…005bdc
INFO [03-12|14:58:46] 🔨 mined potential block         number=8 hash=4fad7c…5e318e
//提交第 9 个区块的挖矿操作
INFO [03-12|14:58:46] Commit new mining work          number=9 txs=0 uncles=0 elapsed=139.52µs

//第9区块还未返回结果,停止挖矿任务
> miner.stop()
true

查看当前每个账户的以太币数量

> eth.getBalance(u0)
40000000000000000000
> eth.getBalance(u1)
0

PS:因为是以第一个账户为矿工,所以只有 u0 获得了奖励,每挖出一个区块奖励5个以太币,这里显示的单位是wei,1eth=10的18次幂
查看当前挖矿的状态,返回 false

> eth.mining
false
  • 打印基础账户,等于第一个账户的地址
> eth.coinbase
"0xe2d463c53f5b4b8c48420304965af10db7290b65"
> u0
"0xe2d463c53f5b4b8c48420304965af10db7290b65"
> u1
"0xf7cd6aee057409e8ecfa88a8e5b18033d456ff05"
  • 换算成以太币
> web3.fromWei(eth.getBalance(u0),'ether')
40
  • 查看当前区块的数量
> eth.blockNumber
8
  • Wei 与 Eth 互转操作
> acmount=web3.fromWei(1,'ether')
"0.000000000000000001"
> acmount=web3.toWei(1,'ether')
"1000000000000000000"
  • 查看 eth 对象
> eth
{
accounts:["0xe2d463c53f5b4b8c48420304965af10db7290b65","0xf7cd6aee057409e8ecfa88a8e5b18033d456ff05"], //当前账户
blockNumber: 8, //区块数量
coinbase: "0xe2d463c53f5b4b8c48420304965af10db7290b65", //基础账户
compile: {
  lll: function(),
  serpent: function(),
  solidity: function()
 },
 defaultAccount: undefined,
 defaultBlock: "latest",
 gasPrice: 18000000000,
 hashrate: 0,
 mining: false,  // 因为已经停止挖矿,所以这里为 false
 pendingTransactions: [],
 protocolVersion: "0x3f",
 syncing: false,
 call: function(),
 contract: function(abi),
 estimateGas: function(),
 filter: function(options, callback, filterCreationErrorCallback),
 getAccounts: function(callback),
 getBalance: function(),
 getBlock: function(),
 getBlockNumber: function(callback),
 getBlockTransactionCount: function(),
 getBlockUncleCount: function(),
 getCode: function(),
 getCoinbase: function(callback),
 getCompilers: function(),
 getGasPrice: function(callback),
 getHashrate: function(callback),
 getMining: function(callback),
 getPendingTransactions: function(callback),
 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()
}
  • 以太币交易操作
> amount=web3.toWei(1,'ether')
"1000000000000000000"
> eth.sendTransaction({from:u0,to:u1,value:amount})
Error: authentication needed: password or unlock
  at web3.js:3143:20
  at web3.js:6347:15
  at web3.js:5081:36
  at <anonymous>:1:1

PS:这里提示需要密码认证,账户每隔一段时间就会自动上锁,因此需要创建用户时的密码解锁

> personal.unlockAccount(u0)
Unlock account 0xe2d463c53f5b4b8c48420304965af10db7290b65
Passphrase: 
true

输入密码,解锁用户,再重新发起交易

> eth.sendTransaction({from:u0,to:u1,value:amount})
INFO [03-12|23:23:03] Submitted transaction          fullhash=0x039235641128e2192883802594f6de746459fc9154cad7ce17ba4342c9c2b027 recipient=0xf7cd6Aee057409E8eCfa88A8e5b18033d456ff05
"0x039235641128e2192883802594f6de746459fc9154cad7ce17ba4342c9c2b027"

ps:交易已经提交,是否成功了呢?No,交易的确认,这里仅仅是提交了交易任务

> txpool.status
{
 pending: 1,
 queued: 0
}

ps: pending=1,表示有一条交易,但还未被处理
我们再次提交一条交易,转账 2 比特币

> amount=web3.toWei(2,'ether')
"2000000000000000000"
> eth.sendTransaction({from:u0,to:u1,value:amount})
INFO [03-12|23:23:56] Submitted transaction          fullhash=0x991ea03c44915d2383863ce31d7e61015e066e58d81bff352f10dbf68ca1ec17 recipient=0xf7cd6Aee057409E8eCfa88A8e5b18033d456ff05
"0x991ea03c44915d2383863ce31d7e61015e066e58d81bff352f10dbf68ca1ec17"

再次查看交易池的状态

> txpool.status
{
 pending: 2,    //这里的pending 变成了 2,两个任务提交后还未被处理
 queued: 0
}

要使交易被处理,必须挖矿,获得新的区块记录交易数据。

  • 启动挖矿,获取下一个区块,就停止挖矿操作
> miner.start(1);admin.sleepBlocks(1);miner.stop();
INFO [03-12|23:26:06] Updated mining threads          threads=1
INFO [03-12|23:26:06] Transaction pool price threshold updated price=18000000000
INFO [03-12|23:26:06] Starting mining operation 
INFO [03-12|23:26:06] Commit new mining work          number=9 txs=2 uncles=0 elapsed=1.970ms
INFO [03-12|23:26:19] Successfully sealed new block      number=9 hash=31655d…7cec9b
INFO [03-12|23:26:19] 🔨 mined potential block         number=9 hash=31655d…7cec9b

再次查看交易池对象的状态

> txpool.status
{
 pending: 0,  //两个任务都被提交并处理,此处的 pending 值变成了 0
 queued: 0
}
  • 查看两个账户的余额,分别是42, 3。
> web3.fromWei(eth.getBalance(u0),'ether')
42
> web3.fromWei(eth.getBalance(u1))
3

ps:账户u1因为是矿工账号,每挖一个区块就获得5个比特币,因此40-3+5=42

  • 查询交易,根据交易返回的哈希值,可以查询该交易的数据内容
    查询第一笔交易内容
> eth.getTransaction('0x039235641128e2192883802594f6de746459fc9154cad7ce17ba4342c9c2b027')
{
 blockHash: "0x31655d1b7b60001e851849db4734742c24374f5ca82313cfb2b32fb0f27cec9b",
 blockNumber: 9, //该条交易被记录在第 9 区块
 from: "0xe2d463c53f5b4b8c48420304965af10db7290b65",//该笔交易的发起账号地址
 gas: 90000,
 gasPrice: 18000000000,
 hash: "0x039235641128e2192883802594f6de746459fc9154cad7ce17ba4342c9c2b027",
 input: "0x",
 nonce: 0,
 r: "0xfb0a7541c5ada67a1c34dde394178fb154401f28300659d86b9c4f2bf3cf4028",
 s: "0x263f46bcef9bbff8f24de845fce5bf80f2a22511d0f69f00b052ac140689c93c",
 to: "0xf7cd6aee057409e8ecfa88a8e5b18033d456ff05", //该笔交易的接收账号地址
 transactionIndex: 0,   //第 0 条交易
 v: "0x38",
 value: 1000000000000000000    //交易额度
}

查询第二笔交易内容

> eth.getTransaction('0x991ea03c44915d2383863ce31d7e61015e066e58d81bff352f10dbf68ca1ec17')
{
   blockHash: "0x31655d1b7b60001e851849db4734742c24374f5ca82313cfb2b32fb0f27cec9b",
   blockNumber: 9,   //该条交易被记录在第 9 区块
   from: "0xe2d463c53f5b4b8c48420304965af10db7290b65",  //该笔交易的发起账号地址
   gas: 90000,
   gasPrice: 18000000000,
   hash: "0x991ea03c44915d2383863ce31d7e61015e066e58d81bff352f10dbf68ca1ec17",
   input: "0x",
   nonce: 1,
   r: "0x5867dbfa40f1ea43b7b791b4306fb78948992289509af3ef07a23d4e4376bc9e",
   s: "0x78c71836cce53bcb1c81fe9b7e6efae7d4d1d9e483485a0a977292350381477f",
   to: "0xf7cd6aee057409e8ecfa88a8e5b18033d456ff05",   //该笔交易的接收账号地址
   transactionIndex: 1,  //第 1 条交易
   v: "0x37",
   value: 2000000000000000000  //交易额度
}
  • 查看区块内容,这里查询第9区块内容,验证上述两笔交易是否存在
> eth.getBlock(9)
{
    difficulty: 131072,
    extraData: "0xd783010802846765746886676f312e31308664617277696e",
    gasLimit: 3169294,
    gasUsed: 42000,
    hash: "0x31655d1b7b60001e851849db4734742c24374f5ca82313cfb2b32fb0f27cec9b",
    logsBloom:"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
    miner: "0xe2d463c53f5b4b8c48420304965af10db7290b65",  //矿工账号地址,奖励会发放到次矿工
    mixHash: "0xaed7970963913fbef04fd92d341bd01c802e3a17a897d0666918d6c1e6f836cf",
    nonce: "0x4f52ee328ec62233",
    number: 9,  //区块号
    parentHash: "0x4fad7ce8e03b0b1f58b691e019e2e45b8db08db9176d0603832f99b2015e318e",
    receiptsRoot: "0x87c123b7108d5f4cff435404a984c52842c71f0d9fffb8a41744d2f80d18585d",
    sha3Uncles: "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
    size: 760,
    stateRoot: "0x2cfe64cf081483fea64ead3639bb2e352a13b11b21779107eaef8683f085e10a",
    timestamp: 1520868366,
    totalDifficulty: 1312064,
    transactions: ["0x039235641128e2192883802594f6de746459fc9154cad7ce17ba4342c9c2b027", "0x991ea03c44915d2383863ce31d7e61015e066e58d81bff352f10dbf68ca1ec17"], //上面两笔交易的哈希值
    transactionsRoot: "0x54f42a4444125c2e369b075442bb2d3b46756fe215a5332dd869bae56621cb4f",
    uncles: []
}
  • 退出以太控制台
> exit
INFO [03-13|10:01:26] IPC endpoint closed           endpoint=/Users/HaoZai/geth-private-chian/data0/geth.ipc
INFO [03-13|10:01:26] Writing cached state to disk       block=27 hash=2f5509…334855 root=9b2193…ff92ca
INFO [03-13|10:01:26] Persisted trie from memory database   nodes=3 size=514.00B time=841.642µs gcnodes=0 gcsize=0.00B gctime=0s livenodes=45 livesize=5.92kB
INFO [03-13|10:01:26] Writing cached state to disk       block=26 hash=6cb0e7…2abfa6 root=7bb30d…895aa7
INFO [03-13|10:01:26] Persisted trie from memory database   nodes=2 size=263.00B time=39.712µs gcnodes=0 gcsize=0.00B gctime=0s livenodes=43 livesize=5.66kB
INFO [03-13|10:01:26] Blockchain manager stopped 
INFO [03-13|10:01:26] Stopping Ethereum protocol 
INFO [03-13|10:01:26] Ethereum protocol stopped 
INFO [03-13|10:01:26] Transaction pool stopped 
INFO [03-13|10:01:26] Database closed             database=/Users/HaoZai/geth-private-chian/data0/geth/chaindata

相关文章

网友评论

      本文标题:二、搭建以太坊私链及客户端基本操作

      本文链接:https://www.haomeiwen.com/subject/vxrafftx.html