安装Geth并搭建自己的以太坊私链
安装Geth
sudo apt-get install software-properties-common
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install ethereum
然后执行
geth version
如果出现类似于下面这种版本信息,则说明安装成功
Geth
Version: 1.10.2-stable
Git Commit: 97d11b0187b4695ccf44e3b71b54155fe405a36f
Architecture: amd64
Go Version: go1.16
Operating System: linux
GOPATH=/root/workspace
GOROOT=go
要查看Geth的帮助信息,可以执行:
geth --help
搭建自己的以太坊私链
首先,新建一个文件夹,在这个文件夹下创建一个genisis.json文件,文件内容如下:
{
"config": {
"chainId": 123,
"homesteadBlock": 0,
"eip150Block": 0,
"eip155Block": 0,
"eip158Block": 0,
"byzantiumBlock": 0,
"constantinopleBlock": 0,
"petersburgBlock": 0,
"istanbulBlock": 0
},
"alloc": {},
"coinbase": "0x0000000000000000000000000000000000000000",
"difficulty": "0x2000",
"extraData": "",
"gasLimit": "0x2fefd8",
"nonce": "0x0000000000000042",
"mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"timestamp": "0x00"
}
这个文件其实就是创世块中的一些配置
初始化创世区块
geth --datadir (指定的目录 用.表示当前目录) init genesis.json
启动私链
geth --datadir 上面指定的目录 --networkid 123
这里的123就是上面Json文件中的"chainId"
- 如果要进行交互,可以进入控制台,在启动命令后加上 console
geth --datadir data --networkid 123 console
- 如果想让数据在日志踪显示,可以再加上2>output.log
geth --datadir data --networkid 123 console 2>output.log
在命令行下
- 退出命令行按ctrl + d
- 可以通过输入web3, eth, personal等命令查看对应的函数
- 添加账户
personal.newAccount("111111") # 111111表示密码
- 查看现有账户
eth.accounts
- 查看余额
eth.getBalance(eth.accounts[0])
- 查看现有区块个数
eth.blockNumber
- 启动/停止挖矿
miner.start(1)
miner.stop()
注意,这里有的时候miner.start(1)可能查看eth.blockNumber时没有增长,此时应检查是否设置miner地址:
personal.listAccounts
eth.coinbase # coinbase是当前挖矿所得收益存入的地址
此时设置miner地址:
miner.setEtherbase(eth.coinbase) # 或
miner.setEtherbase(eth.accounts[0])
设置好后再执行挖矿命令
(如果还是不行可以先退出命令行再重新启动私链,我就是重启好的_(:з」∠)_)
- 转账
转账前需要先解锁被转账的账户
personal.unlockAccount(eth.accounts[0])
eth.sendTransaction({from:eth.accounts[0],to:eth.accounts[1],value:3000000000000000000})
- 获得区块信息
eth.getBlock(1)
- 数值转换
将Wei转换为ether
web3.fromWei(100000000000000,'ether')
将ether转换为Wei
web3.toWei(10,'ether')
关于智能合约的编译及部署
Solidity编译器
-
Remix
Remix是一个基于Web浏览器的Solidity IDE,可在线使用而无需安装任何东西
Remix编译器 -
Solc
Solc是Solidity的命令行编译器
安装Solc
npm install -g solc # -g表示全局安装
# 或者:
sudo add-apt-repository ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install solc
智能合约与DApp
Reference
如何搭建私链
启动miner.start(1)无效的问题解决
尚硅谷区块链教程
Ubuntu安装solc
web3.js documentation & API