Ethereum practice finishing (II) geth client

zhutianxiang 2021-09-15 11:36:09 阅读数:463

ethereum practice finishing ii geth

Geth

There are many Ethereum clients , Developed based on various languages , This is related to the value of blockchain advocating openness .Geth( Full name go-ethereum) It is a client developed by Ethereum's official Community , Is the leader in the client . We can use Geth Command to build Ethereum private chain , It can also be based on Geth Interactive command console provided , Interact with the Ethereum network environment .

Geth install

Geth Is based on GO Language client , You need to install goland.

install Go Language environment

Download binary package :go1.4.linux-amd64.tar.gz;

Extract the downloaded binary package to /usr/local Catalog :

$ tar -C /usr/local -zxvf go1.17.linux-amd64.tar.gz

Set the environment variable :

$ export PATH=$PATH:/usr/local/go/bin

Effective environment variables :

$ source /etc/profile

verification :

$ go env

Source code compilation and installation geth

Download the source code :

$ cd /usr/local
$ git clone https://github.com/ethereum/go-ethereum.git

Compile source code :

$ cd go-ethereum
$ make geth

Domestic users may not be able to access the compilation process proxy.golang.org, You can set the agent before executing :

$ go env -w GOPROXY=https://goproxy.cn
$ make geth

Set the environment variable :

export PATH=$PATH:/usr/local/go-ethereum/build/bin

Effective environment variables :

$ source /etc/profile

verification :

$ geth version

Geth Start node

Connect the main chain network

Start a node to connect to the Ethereum main chain , And enter JavaScript Interactive console :

$ geth console

After executing the command , Enter the following :

Welcome to the Geth JavaScript console!
instance: Geth/v1.10.8-unstable-dfeb2f7e-20210823/darwin-amd64/go1.17
at block: 0 (Thu Jan 01 1970 08:00:00 GMT+0800 (CST))
datadir: /Users/zhutx/Library/Ethereum
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

After a while , The console began to continuously output information , Indicates that the node is in fast sync (Fast-Sync) Pattern , Download the latest blockchain data and status . You can see from the output when you first execute the command , Data is stored in by default /Users/zhutx/Library/Ethereum Under the table of contents .

It is impractical to develop and test on the main chain , Now you can stop the node . The blockchain data downloaded by the node will quickly occupy a lot of storage space , You can delete this directory

Connect the test network

Programs always need to be tested during the development phase , We can start the node and connect to the Ethereum test network :

$ mkdir testdir
// Connect Ropsten Test network , Specify the storage directory as testdir
$ geth --ropsten --datadir "./testdir" console

If you connect to the test network for development , Related operations still need to pay for fuel (Gas) Expensive , In addition to mining to get ether for the account , We can also directly use the website that provides faucet service ( Such as :https://faucet.ropsten.be/), Enter the account address of your own test chain , Get ether directly ( The Ethernet currency of the test chain has no real value ).


geth There are a lot of parameters , The commonly used will be introduced in the following , Here are no examples , You can see for yourself (geth --help).


Geth Build a private chain

utilize Geth We can also build our own Ethereum private chain .

Create a data storage directory

$ mkdir blockchain
$ cd blockchain

Write Genesis block configuration

$ vim gensis.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": "0x00002",
"mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"coinbase": "0x0000000000000000000000000000000000000000",
"alloc": {},
"number": "0x0",
"gasUsed": "0x0",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000"
}

Description of Chuangshi block parameters 【TODO】:

Parameters describe

Initialize blockchain

// Create a new directory to store blockchain data
$ mkdir db
// Initialize blockchain
$ geth --datadir "./db" init gensis.json

After successful initialization , Will be in db Produced under the catalogue geth and keystore Catalog , At this time, the directory structure is as follows :

blockchain
├── db
│   ├── geth
│   │   ├── chaindata
│   │   │   ├── 000001.ldb
│   │   │   ├── CURRENT
│   │   │   ├── LOCK
│   │   │   ├── LOG
│   │   │   └── MANIFEST-000000
│   │   ├── lightchaindata
│   │   │   ├── 000001.log
│   │   │   ├── CURRENT
│   │   │   ├── LOCK
│   │   │   ├── LOG
│   │   │   └── MANIFEST-000000
│   └── keystore
└── gensis.jso

Start the private chain

$ geth --rpc --rpcport 8545 --rpccorsdomain "*" --datadir "./db" --port 30303 --rpcapi "eth,net,web3,personal,admin,shh,txpool,debug,miner" --networkid 100000 --rpcaddr=0.0.0.0 --nodiscover --allow-insecure-unlock console 2>> eth.log

Relevant startup parameters can be understood by yourself


Geth Of JavaScript Console

stay Geth Of JavaScript The console has built-in objects , Through these objects, we can easily interact with Ethereum :

  • eth: Provides methods for operating blockchain
  • net: Provides a view of p2p The method of network state
  • admin: Provides methods for managing nodes
  • miner: Provide methods to start and stop mining
  • personal: Provides methods for managing accounts
  • txpool: Provides a way to view the transaction memory pool
  • web3: In addition to the methods contained in the above objects , There are also some methods of unit conversion

On the private chain we built above , Use the transfer business to demonstrate JavaScript Some operations of the console , Just make an understanding :

0. Get into JavaScript Console Environmental Science

If... Is not entered when starting the node console, You can go alone attach command , Enter the JavaScript Command environment :

cd blockchain
$ geth --datadir "./db" attach ipc:./db/geth.ipc

1. New account

Pass in the account password , Successful execution returns the public key :

> personal.newAccount("123456")
"0xf05ed6c1bab6800d94ae3af4471b77caf07860f0"

The generated account file is in keystore Under the folder . We did it twice , Generate 2 Account number for transfer standby .

2. View account

> eth.accounts
["0xf05ed6c1bab6800d94ae3af4471b77caf07860f0", "0x8efa17c5646c60d4b67d118445f2b9614d9ea3e7"]

3. Check the balance

> balance = web3.fromWei(eth.getBalance(eth.accounts[0]), "ether")
0

eth.getBalance( Account public key ), Return the balance of the account , Unit is wei,web3.fromWei take wei convert to ether.

4. dig

In order to get ether , You need to start mining first , We set the first account as the mining account :

> miner.setEtherbase(eth.accounts[0])
true

Check if the setting is successful :

> eth.coinbase
"0xf05ed6c1bab6800d94ae3af4471b77caf07860f0"

Start mining :

> miner.start(1)
null

Dig for a while , Suspend mining after ensuring that there is a balance in the account , Open it when the transaction needs to pack blocks .

In the area of blockchain , Transfer accounts 、 Deploy smart contracts 、 Calling smart contracts and other operations are transactions . Not a narrow concept of trading

Close mining :

> miner.stop()

Check the balance again :

> balance = web3.fromWei(eth.getBalance(eth.accounts[0]), "ether")
234

Now the account has 234 Etheric money , The account needs to be unlocked before the transfer transaction , Otherwise, an error will be reported .

5. Unlock the account

> personal.unlockAccount(eth.accounts[0], "123456")
true

6. transaction

Give me the change 34 Transfer to another account :

> eth.sendTransaction({from: eth.accounts[0], to: eth.accounts[1], value: web3.toWei(34, "ether")})
"0x47872d357a318f0213e63d40311a990cb0d467ad2bb79a6d8c82a9b667a079b9"

Send a transfer transaction to the blockchain network , Return to transaction hash, At this time, the transaction is waiting to be packaged in the transaction pool .

View transaction pool status :

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

pending Indicates a transaction that has been submitted but has not yet been processed , Show that 1 Transactions waiting to be packaged .

see pending Transaction details :

> txpool.inspect.pending
{
0xf05ED6C1baB6800D94Ae3af4471B77caf07860f0: {
0: "0x8eFA17c5646c60D4B67D118445f2B9614D9Ea3e7: 34000000000000000000 wei + 21000 gas × 1000000000 wei"
}
}

In order for the transaction to be processed , Mining must be started . For the convenience of analysis , Let's stop mining when we reach a block :

> miner.start(1);admin.sleepBlocks(1);miner.stop();
INFO [08-24|02:29:13.504] Updated mining threads threads=1
INFO [08-24|02:29:13.504] Transaction pool price threshold updated price=1,000,000,000
INFO [08-24|02:29:13.505] Commit new mining work number=118 sealhash=a408a5..244a99 uncles=0 txs=0 gas=0 fees=0 elapsed="146.423µs"
INFO [08-24|02:29:13.505] Commit new mining work number=118 sealhash=ed24ca..e08e23 uncles=0 txs=1 gas=21000 fees=2.1e-05 elapsed="350.824µs"
INFO [08-24|02:29:15.927] Successfully sealed new block number=118 sealhash=ed24ca..e08e23 hash=c0b43c..28c921 elapsed=2.422s
INFO [08-24|02:29:15.927] mined potential block number=118 hash=c0b43c..28c921
INFO [08-24|02:29:15.927] Commit new mining work number=119 sealhash=e9df41..7397c0 uncles=0 txs=0 gas=0 fees=0 elapsed="187.308µs"

View the balance of the transferor and the transferor respectively :

> balance = web3.fromWei(eth.getBalance(eth.accounts[0]), "ether")
202
> balance = web3.fromWei(eth.getBalance(eth.accounts[1]), "ether")
34

You can see the transfer in account eth.accounts[1] Yes 34 An ether , And transfer out account eth.accounts[0] The account balance is not 200, Because the account has mining income ;

7. block

See the transaction details :

> eth.getTransaction("0x47872d357a318f0213e63d40311a990cb0d467ad2bb79a6d8c82a9b667a079b9")
{
blockHash: "0xc0b43c476fc4406b4db342beed0ed0b0d4bad02330b2b353a354b558bc28c921",
blockNumber: 118,
from: "0xf05ed6c1bab6800d94ae3af4471b77caf07860f0",
gas: 21000,
gasPrice: 1000000000,
hash: "0x47872d357a318f0213e63d40311a990cb0d467ad2bb79a6d8c82a9b667a079b9",
input: "0x",
nonce: 0,
r: "0xe1d9e0678c2a67c0fcec81cab407f20caca4ff617fbc697249409d3d78a74ef0",
s: "0x6db176315eebaafc07c695549fccbfed0dbe1317a3ffbbf398d9c3aa6b8bb250",
to: "0x8efa17c5646c60d4b67d118445f2b9614d9ea3e7",
transactionIndex: 0,
type: "0x0",
v: "0x557",
value: 34000000000000000000
}

The above command is to view the details when the transaction is initiated , If you want to view the details when the transaction is packaged into the block , Use the following command :

> eth.getTransactionReceipt("0x47872d357a318f0213e63d40311a990cb0d467ad2bb79a6d8c82a9b667a079b9")
{
blockHash: "0xc0b43c476fc4406b4db342beed0ed0b0d4bad02330b2b353a354b558bc28c921",
blockNumber: 118,
contractAddress: null, // If it's a contract creation transaction , The contract address is returned , Other situations return to null
cumulativeGasUsed: 21000, // Of accumulated telephone charges gas Gross value
effectiveGasPrice: 1000000000,
from: "0xf05ed6c1bab6800d94ae3af4471b77caf07860f0",
gasUsed: 21000, // The number of separate calls for executing the current transaction gas
logs: [],
logsBloom: "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
status: "0x1",
to: "0x8efa17c5646c60d4b67d118445f2b9614d9ea3e7", // If it's a contract creation transaction , return null
transactionHash: "0x47872d357a318f0213e63d40311a990cb0d467ad2bb79a6d8c82a9b667a079b9",
transactionIndex: 0, // The serial number of the transaction in the block
type: "0x0"
}

Here are the commands for other query blocks :

View the current block count :

> eth.blockNumber
118

View the latest block :

> eth.getBlock('latest')
{
difficulty: 131886,
extraData: "0xd683010a08846765746886676f312e3137856c696e7578",
gasLimit: 5273553,
gasUsed: 21000,
hash: "0xc0b43c476fc4406b4db342beed0ed0b0d4bad02330b2b353a354b558bc28c921",
logsBloom: "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
miner: "0xf05ed6c1bab6800d94ae3af4471b77caf07860f0",
mixHash: "0x009c9034e94034344fc03dd6914d3753a8b98b8a3b0e3b5d11d473d9ad5a1402",
nonce: "0x66f00bbbcd357270",
number: 118,
parentHash: "0xa475ef4ac3b9c1d9b8390e5044a1d11186c57b6c369756b642420f345b7ec82f",
receiptsRoot: "0x056b23fbba480696b65fe5a59b8f2148a1299103c4f57df839233af2cf4ca2d2",
sha3Uncles: "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
size: 649,
stateRoot: "0x798af7bcb3bd31b18c955c05e694ae342d1db654681b1703b817ff6e02639d69",
timestamp: 1629743353,
totalDifficulty: 15897610,
transactions: ["0x47872d357a318f0213e63d40311a990cb0d467ad2bb79a6d8c82a9b667a079b9"],
transactionsRoot: "0x979e07128c057ff81e2eaaba45b3704be371ffcb794876f570f88e88e00cd313",
uncles: []
}

eth.getBlock(blockNumber|blockHash)) You can get the information of specific blocks .


Geth Multi node networking

The current private chain is a single node ( node 1), Now let's get another node ( node 2) Connect in , Form a simplest Ethereum private chain network .

node 2 install geth After the client , Enter into JavaScript Console , Enter the following command to get the node 2 Information about :

> admin.nodeInfo
{
enode: "enode://5873af9deabd8f7e40878ce0e3caec0bb86c79cf9bd99781be2aaab8a61e3c24aded28102971a38a7cb0ff2749b3a1b3624232cc96ac4f76dc9f035232629652@127.0.0.1:30303?discport=0",
enr: "enr:-Ja4QCuP0rodmA2imicnqbuZ14kPiMqPrX-Dp_5z8FU1l1PvcU0IKz4cynQppjEqVguSlU_Tn-UlVkaw_ehxcCsM0XoEg2V0aMfGhJPR68WAgmlkgnY0gmlwhH8AAAGJc2VjcDI1NmsxoQJYc6-d6r2PfkCHjODjyuwLuGx5z5vZl4G-Kqq4ph48JIRzbmFwwIN0Y3CCdl8",
id: "37829b9d6cdb1610dca7ba713a1c0647d6474957c686a3b4967b7cd77f0d47a5",
ip: "127.0.0.1",
listenAddr: "[::]:30303",
name: "Geth/v1.10.8-unstable-dfeb2f7e-20210823/linux-amd64/go1.17",
ports: {
discovery: 0,
listener: 30303
},
protocols: {
eth: {
config: {
byzantiumBlock: 0,
chainId: 666,
constantinopleBlock: 0,
eip150Block: 0,
eip150Hash: "0x0000000000000000000000000000000000000000000000000000000000000000",
eip155Block: 0,
eip158Block: 0,
ethash: {},
homesteadBlock: 0,
istanbulBlock: 0,
petersburgBlock: 0
},
difficulty: 15897610,
genesis: "0xd3d6bb893a6e274cab241245d5df1274c58d664fbb1bfd6e59141c2e0bc5304a",
head: "0xc0b43c476fc4406b4db342beed0ed0b0d4bad02330b2b353a354b558bc28c921",
network: 100000
},
snap: {}
}
}

In fact, only nodes are used 2 Inside enode Information , You can get it directly enode:

> admin.nodeInfo.enode
"enode://5873af9deabd8f7e40878ce0e3caec0bb86c79cf9bd99781be2aaab8a61e3c24aded28102971a38a7cb0ff2749b3a1b3624232cc96ac4f76dc9f035232629652@127.0.0.1:30303?discport=0"

At the node 1 Execute the command to connect the node 2:

127.0.0.1 Change to node 2 The public address of
> admin.addPeer("enode://5873af9deabd8f7e40878ce0e3caec0bb86c79cf9bd99781be2aaab8a61e3c24aded28102971a38a7cb0ff2749b3a1b3624232cc96ac4f76dc9f035232629652@127.0.0.1:30303?discport=0")
true

After successful connection , node 2 Will start synchronizing nodes 1 Block of , After synchronization , Start mining at any node , The other node synchronizes the block , Send a transaction to a node , Another node will also receive the transaction .

The following command can view the connected remote nodes :

> admin.peers
版权声明:本文为[zhutianxiang]所创,转载请带上原文链接,感谢。 https://netfreeman.com/2021/09/20210909154727230v.html