准备工作
0.安装geth(Mac系统)
brew install ethereum
1.查看geth版本
geth version
Geth
Version: 1.10.1-stable
Architecture: amd64
Go Version: go1.16
Operating System: darwin
GOPATH=
GOROOT=go
同步公网数据
1.指定数据目录同步区块(默认Ethereum主网、full模式)
geth --datadir ./data
2.以快速模式同步主网区块 只会下载区块头和地址,不会验证所有交易(Ethereum)
geth --datadir . --syncmode fast
3.同步测试网络的区块(Ropsten)
geth --testnet --datadir . --syncmode fast
搭建私链
0.定义genesis.json
查找官网最新版本
{
"config": {
"chainId": 523,
"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": "0x00002",
"mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"coinbase": "0x0000000000000000000000000000000000000000",
"alloc": {
"0Bbf9E54c4c5737aaBd484168fAe8D1905B972CC" : {"balance" : "30000000000000000000"}
},
"number": "0x0",
"gasUsed": "0x0",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000"
}
1.创建私链
创建一条以genesis.json作为创世块的区块链
geth --datadir . init genesis.json
目录下生成geth和keystore两个新文件.
- geth保存的是区块链的相关信息
- keystore中保存的是该链条中的用户信息
2.启动私链
1.快速启动私链,将networkid设置为与创世块配置里的chainId一致
geth --datadir . --networkid 523
2.附带参数启动私链
geth --datadir . --rpc --networkid 523 --nodiscover console 2>eth_output.log --allow-insecure-unlock
参数列表(部分):
console 启动控制台
2>eth_output.log 日志重定向
–datadir 指定数据目录,其中 . 表示当前目录
–nodiscover 禁止发现节点
–rpc 启用rpc服务,默认端口号8545
–allow-insecure-unlock 允许http的方式unlock
–rpcapi 表示可以通过rpc调用的对象
–rpcaddr rpc监听地址,默认为127.0.0.1,只能本地访问
示例:
geniusdew@localhost mychain % geth --datadir . --rpc --networkid 523 --nodiscover console 2>eth_output.log --allow-insecure-unlock
Welcome to the Geth JavaScript console!
instance: Geth/v1.10.1-stable/darwin-amd64/go1.16
coinbase: 0xd99edf84a65cfe91e82bc6b2c258469fb0cc337e
at block: 209 (Tue Mar 23 2021 10:55:44 GMT+0800 (CST))
datadir: /Users/geniusdew/ZLocalRepository/study_code/geth/mychain
modules: admin:1.0 debug:1.0 eth:1.0 ethash:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0
To exit, press ctrl-d
>
3.启动采用权威证明的网络
–dev 启动采用权威证明的网络,会预先有一个开发者账号,可以直接挖矿
geth --datadir . --dev console 2>output.log
3.账号操作
创建账号
personal.newAccount()
或
personal.newAccount(“123456”)
查看账号
eth.accounts
查看账号余额
eth.getBalance(eth.accounts[0])
解锁账号
personal.unlockAccount(eth.accounts[0])
示例:
> personal.unlockAccount(eth.accounts[0])
Unlock account 0xd99edf84a65cfe91e82bc6b2c258469fb0cc337e
Passphrase:
true
4.挖矿操作
miner.start()
miner.stop()
示例:
> miner.start()
null
> miner.stop();
null
5.发送交易
eth.sendTransaction({from:eth.accounts[0],to:"0x0Bbf9E54c4c5737aaBd484168fAe8D1905B972CC",value:web3.toWei(5,'ether')})
ps: 如有Error: invalid sender,更换官网最新的genesis.json解决
发送交易后需要挖矿打包交易才生效
>eth.sendTransaction({from:eth.accounts[0],to:"0x0Bbf9E54c4c5737aaBd484168fAe8D1905B972CC",value:web3.toWei(5,'ether')})
"0x92c22e3f3df2623b2d24560820a978b1ec557e8eafff29293f943b20cca3d528"
6.查看区块高度
eth.blockNumber
> eth.blockNumber
231
7.查询块信息
eth.getBlock(blockNumber)
> eth.getBlock('210')
{
difficulty: 131072,
extraData: "0xd783010a01846765746886676f312e31368664617277696e",
gasLimit: 5768887,
gasUsed: 21000,
hash: "0xda1a20b7feb72db05a755903f965fb2abc723c22351f47bcac386c8d267d7a0e",
logsBloom: "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
miner: "0xd99edf84a65cfe91e82bc6b2c258469fb0cc337e",
mixHash: "0x3b438231a843cc85ce2a1d67cb876d82ff03a82bf5b1bd48692d16cbad094a35",
nonce: "0x39ebaedaa8526b1f",
number: 210,
parentHash: "0x3d3d44e76c886668224ee13106e425bb4f4a9cee602f5b276e8399fd3fe9cbcf",
receiptsRoot: "0x056b23fbba480696b65fe5a59b8f2148a1299103c4f57df839233af2cf4ca2d2",
sha3Uncles: "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
size: 648,
stateRoot: "0xa3174e56937f1690fec2f19172f38285fb91ff6b9e265898b3fbe0bd508ddeea",
timestamp: 1616556099,
totalDifficulty: 28336449,
transactions: ["0x92c22e3f3df2623b2d24560820a978b1ec557e8eafff29293f943b20cca3d528"],
transactionsRoot: "0x98204ebd3e73f45b68052d6fdcbae7dda0f7b3a991ed3c2ac6a6d81d3447c584",
uncles: []
}
Number
- 区块号。当这个区块处于pending
将会返回null
。hash
- 字符串,区块的哈希串。当这个区块处于pending
将会返回null
。parentHash
- 字符串,32字节的父区块的哈希值。nonce
- 字符串,8字节。POW生成的哈希。当这个区块处于pending
将会返回null
。sha3Uncles
- 字符串,32字节。叔区块的哈希值。logsBloom
- 字符串,区块日志的布隆过滤器9。当这个区块处于pending
将会返回null
。transactionsRoot
- 字符串,32字节,区块的交易前缀树的根。stateRoot
- 字符串,32字节。区块的最终状态前缀树的根。miner
- 字符串,20字节。这个区块获得奖励的矿工。difficulty
-BigNumber
类型。当前块的难度,整数。totalDifficulty
-BigNumber
类型。区块链到当前块的总难度,整数。extraData
- 字符串。当前块的extra data
字段。size
-Number
。当前这个块的字节大小。gasLimit
-Number
,当前区块允许使用的最大gas
。gasUsed
- 当前区块累计使用的总的gas
。timestamp
-Number
。区块打包时的unix
时间戳。transactions
- 数组。交易对象。或者是32字节的交易哈希。uncles
- 数组。叔哈希的数组。
8.查询交易
eth.getTransaction(transactionHash)
> eth.getTransaction('0x92c22e3f3df2623b2d24560820a978b1ec557e8eafff29293f943b20cca3d528')
{
blockHash: "0xda1a20b7feb72db05a755903f965fb2abc723c22351f47bcac386c8d267d7a0e",
blockNumber: 210,
from: "0xd99edf84a65cfe91e82bc6b2c258469fb0cc337e",
gas: 21000,
gasPrice: 1000000000,
hash: "0x92c22e3f3df2623b2d24560820a978b1ec557e8eafff29293f943b20cca3d528",
input: "0x",
nonce: 3,
r: "0xa5d9949c37c32b63c163d77ee1b0d4f1d5b3a8979b83fbf3984aa66904aba42e",
s: "0x48d7787e6bf5915f53d9f144a3ca7db7dd611ccfaa921f7f5c3f572f60305442",
to: "0x0bbf9e54c4c5737aabd484168fae8d1905b972cc",
transactionIndex: 0,
type: "0x0",
v: "0x42",
value: 5000000000000000000
}
hash
:String
- 32字节,交易的哈希值。nonce
:Number
- 交易的发起者在之前进行过的交易数量。blockHash
:String
- 32字节。交易所在区块的哈希值。当这个区块处于pending
将会返回null
。blockNumber
:Number
- 交易所在区块的块号。当这个区块处于pending
将会返回null
。transactionIndex
:Number
- 整数。交易在区块中的序号。当这个区块处于pending
将会返回null
。from
:String
- 20字节,交易发起者的地址。to
:String
- 20字节,交易接收者的地址。当这个区块处于pending
将会返回null
。value
:BigNumber
- 交易附带的货币量,单位为Wei
。gasPrice
:BigNumber
- 交易发起者配置的gas
价格,单位是wei
。gas
:Number
- 交易发起者提供的gas
。.input
:String
- 交易附带的数据。
9.web3.js API
> web3
{
admin: {
datadir: "/Users/geniusdew/ZLocalRepository/study_code/geth/mychain",
nodeInfo: {
enode: "enode://db0ce649873026ce079453d8e353cf01b3144d1eaf6e7e48911c719eb038e72f94066d3e8d2fedd67f921606f46d4efe025a7550618b41c47181aecbc0fb97f1@127.0.0.1:30303?discport=0",
enr: "enr:-Ja4QO73yq8mKrUmQTKDT0by_YZ1UPTySZ3sdw0VmtPOsYbXQZPDA7CLzneJ5638CnqOWiqSVDO2HZbGbUp-rxI-fw8Gg2V0aMfGhJuyGhKAgmlkgnY0gmlwhH8AAAGJc2VjcDI1NmsxoQPbDOZJhzAmzgeUU9jjU88BsxRNHq9ufkiRHHGesDjnL4RzbmFwwIN0Y3CCdl8",
id: "eaf56b16216635c9f2c651e7be483fa81b225d87116c108120443eff3a650ec6",
ip: "127.0.0.1",
listenAddr: "[::]:30303",
name: "Geth/v1.10.1-stable/darwin-amd64/go1.16",
ports: {
discovery: 0,
listener: 30303
},
protocols: {
eth: {...},
snap: {}
}
},
peers: [],
addPeer: function(),
addTrustedPeer: function(),
clearHistory: function(),
exportChain: function(),
getDatadir: function(callback),
getNodeInfo: function(callback),
getPeers: function(callback),
importChain: function(),
removePeer: function(),
removeTrustedPeer: function(),
sleep: function(),
sleepBlocks: function(),
startRPC: function(),
startWS: function(),
stopRPC: function(),
stopWS: function()
},
bzz: {
hive: undefined,
info: undefined,
blockNetworkRead: function(),
download: function(),
get: function(),
getHive: function(callback),
getInfo: function(callback),
modify: function(),
put: function(),
retrieve: function(),
store: function(),
swapEnabled: function(),
syncEnabled: function(),
upload: function()
},
currentProvider: {
send: function(),
sendAsync: function()
},
db: {
getHex: function(),
getString: function(),
putHex: function(),
putString: function()
},
debug: {
accountRange: function(),
backtraceAt: function(),
blockProfile: function(),
chaindbCompact: function(),
chaindbProperty: function(),
cpuProfile: function(),
dumpBlock: function(),
freeOSMemory: function(),
freezeClient: function(),
gcStats: function(),
getBadBlocks: function(),
getBlockRlp: function(),
getModifiedAccountsByHash: function(),
getModifiedAccountsByNumber: function(),
goTrace: function(),
memStats: function(),
mutexProfile: function(),
preimage: function(),
printBlock: function(),
seedHash: function(),
setBlockProfileRate: function(),
setGCPercent: function(),
setHead: function(),
setMutexProfileFraction: function(),
stacks: function(),
standardTraceBadBlockToFile: function(),
standardTraceBlockToFile: function(),
startCPUProfile: function(),
startGoTrace: function(),
stopCPUProfile: function(),
stopGoTrace: function(),
storageRangeAt: function(),
testSignCliqueBlock: function(),
traceBadBlock: function(),
traceBlock: function(),
traceBlockByHash: function(),
traceBlockByNumber: function(),
traceBlockFromFile: function(),
traceCall: function(),
traceTransaction: function(),
verbosity: function(),
vmodule: function(),
writeBlockProfile: function(),
writeMemProfile: function(),
writeMutexProfile: function()
},
eth: {
accounts: ["0xd99edf84a65cfe91e82bc6b2c258469fb0cc337e"],
blockNumber: 231,
coinbase: "0xd99edf84a65cfe91e82bc6b2c258469fb0cc337e",
compile: {
lll: function(),
serpent: function(),
solidity: function()
},
defaultAccount: undefined,
defaultBlock: "latest",
gasPrice: 1000000000,
hashrate: 0,
mining: false,
pendingTransactions: [],
protocolVersion: undefined,
syncing: false,
call: function(),
chainId: function(),
contract: function(abi),
estimateGas: function(),
fillTransaction: function(),
filter: function(options, callback, filterCreationErrorCallback),
getAccounts: function(callback),
getBalance: function(),
getBlock: function(),
getBlockByHash: function(),
getBlockByNumber: function(),
getBlockNumber: function(callback),
getBlockTransactionCount: function(),
getBlockUncleCount: function(),
getCode: function(),
getCoinbase: function(callback),
getCompilers: function(),
getGasPrice: function(callback),
getHashrate: function(callback),
getHeaderByHash: function(),
getHeaderByNumber: function(),
getMining: function(callback),
getPendingTransactions: function(callback),
getProof: function(),
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()
},
ethash: {
getHashrate: function(),
getWork: function(),
submitHashRate: function(),
submitWork: function()
},
isIBAN: undefined,
miner: {
getHashrate: function(),
setEtherbase: function(),
setExtra: function(),
setGasPrice: function(),
setRecommitInterval: function(),
start: function(),
stop: function()
},
net: {
listening: true,
peerCount: 0,
version: "523",
getListening: function(callback),
getPeerCount: function(callback),
getVersion: function(callback)
},
personal: {
listAccounts: ["0xd99edf84a65cfe91e82bc6b2c258469fb0cc337e"],
listWallets: [{
accounts: [...],
status: "Locked",
url: "keystore:///Users/geniusdew/ZLocalRepository/study_code/geth/mychain/keystore/UTC--2021-03-19T05-47-27.991858000Z--d99edf84a65cfe91e82bc6b2c258469fb0cc337e"
}],
deriveAccount: function(),
ecRecover: function(),
getListAccounts: function(callback),
getListWallets: function(callback),
importRawKey: function(),
initializeWallet: function(),
lockAccount: function(),
newAccount: function(),
openWallet: function(),
sendTransaction: function(),
sign: function(),
signTransaction: function(),
unlockAccount: function(),
unpair: function()
},
providers: {
HttpProvider: function(host, timeout, user, password),
IpcProvider: function(path, net)
},
rpc: {
modules: {
admin: "1.0",
debug: "1.0",
eth: "1.0",
ethash: "1.0",
miner: "1.0",
net: "1.0",
personal: "1.0",
rpc: "1.0",
txpool: "1.0",
web3: "1.0"
},
getModules: function(callback)
},
settings: {
defaultAccount: undefined,
defaultBlock: "latest"
},
shh: {
addPrivateKey: function(),
addSymKey: function(),
deleteKeyPair: function(),
deleteSymKey: function(),
generateSymKeyFromPassword: function(),
getPrivateKey: function(),
getPublicKey: function(),
getSymKey: function(),
hasKeyPair: function(),
hasSymKey: function(),
info: function(),
markTrustedPeer: function(),
newKeyPair: function(),
newMessageFilter: function(options, callback, filterCreationErrorCallback),
newSymKey: function(),
post: function(),
setMaxMessageSize: function(),
setMinPoW: function(),
version: function()
},
txpool: {
content: {
pending: {},
queued: {}
},
inspect: {
pending: {},
queued: {}
},
status: {
pending: 0,
queued: 0
},
getContent: function(callback),
getInspect: function(callback),
getStatus: function(callback)
},
version: {
api: "0.20.1",
ethereum: undefined,
network: "523",
node: "Geth/v1.10.1-stable/darwin-amd64/go1.16",
whisper: undefined,
getEthereum: function(callback),
getNetwork: function(callback),
getNode: function(callback),
getWhisper: function(callback)
},
BigNumber: function a(e,n),
createBatch: function(),
fromAscii: function(str),
fromDecimal: function(value),
fromICAP: function(icap),
fromUtf8: function(str),
fromWei: function(number, unit),
isAddress: function(address),
isChecksumAddress: function(address),
isConnected: function(),
padLeft: function(string, chars, sign),
padRight: function(string, chars, sign),
reset: function(keepIsSyncing),
setProvider: function(provider),
sha3: function(string, options),
toAscii: function(hex),
toBigNumber: function(number),
toChecksumAddress: function(address),
toDecimal: function(value),
toHex: function(val),
toUtf8: function(hex),
toWei: function(number, unit)
}