Ubuntu 创建私有链

2022-09-27 09:14:55 浏览数 (1)

geth 安装

代码语言:javascript复制
sudo apt-get install software-properties-common
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install ethereum

定义创世区块

代码语言:javascript复制
# genesis.json 文件
{
  "config": {
    "chainId": 666,
    "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": "0x00001",
  "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "coinbase": "0x0000000000000000000000000000000000000000",
  "alloc": { },
  "number": "0x0",
  "gasUsed": "0x0",
  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000"
}
# 创建创世区块
geth --datadir data init genesis.json

启动

代码语言:javascript复制
# geth help 查看具体命令
geth --datadir="data" console 2>eth.log

使用

代码语言:javascript复制
# 区块高度
eth.blockNumber

# 创建用户(密码 123)
personal.newAccount("123")

# 所有账户信息
eth.accounts

# 启动挖矿
miner.start()

# 挖矿中?
eth.mining

# 停止挖矿
miner.stop()

# get 账户余额
eth.getBalance(eth.accounts[0])

# 转账(sendTx后需要有人挖矿)
amount = web3.toWei(8,'ether')
eth.sendTransaction({from:eth.accounts[0],to:eth.accounts[1],value:amount})

eth.getTransaction("txID")

web3 调用

代码语言:javascript复制
 npm install web3 --save
代码语言:javascript复制
 # test.js
 
var Web3 = require('web3'); //引入web3
//console.log(Web3);
if (typeof web3 !== 'undefined') {
//console.log(1);
  web3 = new Web3(web3.currentProvider);
} else {
//console.log(2);
  // set the provider you want from Web3.providers
  web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
//此处是获取所有的用户列表,在回调中直接打印出来
 web3.eth.getAccounts().then(console.log);
var v = web3.version;  //获取web3的版本
console.log(v);
代码语言:javascript复制
node test.js

0 人点赞