Ethereum related to Ethereum blockchain

Posted by Thumper on Mon, 04 Oct 2021 02:06:49 +0200

This article refers to the blog link: https://blog.csdn.net/qq_41966713/article/details/103882422

Quick operation

The premise is to download the Geth client and create the genesis block configuration file genesis.json

  1. Open private chain client
"""
# First, initialize the genesis block configuration file genesis.json, and save the data to the data directory
geth --datadir data init genesis.json
"""
# Open the first private chain node and save the data to the data directory
geth --datadir data --networkid 20200107 --http --http.addr 0.0.0.0 --http.port 8546 --http.corsdomain "*" --http.vhosts "*" --nodiscover --port 16333  --allow-insecure-unlock console
# --The value of the http.addr option is 0.0.0.0, that is, the HTTP-RPC server listening interface (default: "localhost" only listens to the local) supports all functions such as local and remote.
# --http.vhosts option, vhosts value, comma separated list of virtual host names from which requests are accepted (server enforced). The "*" wildcard is accepted. (the default value is "localhost")

"""
# Initialize the second private chain node locally and save the data to the data1 directory
geth --datadir data init genesis.json

# Open the second private chain node client locally
geth --datadir data1 --networkid 20200107 --http --http.addr 0.0.0.0 --http.port 8547 --http.corsdomain "*" --http.vhosts "*" --nodiscover --port 16334  --allow-insecure-unlock --ipcpath "geth_data1.rpc" console
"""

"""
# Multi node link and synchronization.

# Switch to the console of the first private chain node to obtain the enode information of the first private chain node.
admin.nodeInfo.enode
# Switch to the console of the second private chain node and add enode information of the first private chain node.
admin.addPeer("enode"://[::]:prot")
"""
  1. Account and transfer
personal.listAccounts  # View account list information
eth.accounts  # Or web3.eth.accounts
eth.accounts[0]  # View first account
eth.coinbase  # Namely: query the current absenteeism account

personal.newAccount('123456')  # The parameter is the account password. After the creation is successful, you will be prompted to save the key file, etc.

eth.accounts  # View account
eth.blockNumber # View block height
eth.getBlock(0)  # View Genesis block
eth.getBlock(eth.blockNumber).miner  # Get the name of the miner who dug the last block

miner.setEtherbase(eth.accounts[0])  # Set the first account as a miner

admin.nodeInfo  # View current node information
#Execute admin.addPeer("URL of own node") on other clients to tell them to add their own nodes
admin.nodeInfo.enode

eth.getBalance(eth.accounts[0])  # View first account balance
eth.getBalance(eth.accounts[1])  # View second account balance

# ether =wei * 10^18, that is, the accuracy can reach 18 bits.
web3.fromWei(1000000000000000000,"ether")   # wei to ether
web3.toWei(1)  # ether to wei

# Query the balance of the 1st / 2nd account (note that web3.fromWei means to convert wei unit to ether, because wei is the mine by default)
web3.fromWei(web3.eth.getBalance(web3.eth.accounts[0]),"ether")  
web3.fromWei(web3.eth.getBalance(web3.eth.accounts[1]),"ether") 

# Transfer can only be performed after the account is unlocked,
personal.unlockAccount(web3.eth.accounts[0])  # Unlock account

# Transfer: transfer from the first account to the second account, and the number of transfers is 5 eth
web3.eth.sendTransaction({from:web3.eth.accounts[0] , to:web3.eth.accounts[1], value:web3.toWei(5, "ether")})
  1. Mining confirmation transaction and exit console
miner.start();admin.sleepBlocks(1);miner.stop()  # Command combination: start mining, pause after packing a block, and stop mining.

exit  # Exit private chain client JS console

1, Geth client

1.1 windows System Download geth client:

Official website address: https://geth.ethereum.org/downloads/

1.2 installation geth:

Double click the EXE installation file in the next step. After installation, two files appear in the installation directory: geth.exe and uninstall.exe;
The PATH system variable will be automatically added after exe installation.
If the prompt PATH not update appears after the installation, you can manually add the directory where get.exe is located to the system variable PATH.

1.3 cmd verify geth and connect to the public network:

1.3.1 verify installation and version
Open cmd anywhere, enter geth -help, help information appears, geth version is output, and geth version information appears, indicating that the installation is successful.

1.3.2 run Geth client and connect to the main network
geth --datadir ./data
or
geth --datadir data --sycnmode fast

be careful:
Parameter -- datadir specifies the directory of data storage;
Parameter -- sycnmode specifies that the data synchronization mode fast is the fast synchronization mode. Only each block header and block body will be downloaded, but all transactions will not be verified until all blocks are synchronized.
If you do not add any parameters, just use the geth command, or double-click geth.exe in the installation directory, it will automatically connect to the Ethereum public network and start synchronizing blocks

For the complete geth command, refer to geth help or the official website address:
https://geth.ethereum.org/docs/interface/command-line-options

The operation master network has certain requirements for configuration, and a private chain can be built for blockchain test and development.

1.4 modify data storage address

cmd after entering geth -help, you can view the default data storage address through the datadir option. The system default address is generally located at C:\Users\Administrator\AppData\Local\Ethereum
or
C:\Users\Administrator\data\geth\chaindata

Run the cmd command to establish a hard link to modify the data storage address:
mklink /j C:\Users\Administrator\AppData\Local\Ethereum D:\java\Ethereum

2, Eth private chain construction

2.1 Genesis block configuration file genesis.json

Create the private chain folder PrivateChain in any directory, and create the genesis.json file in its directory. The configuration content of the genesis.json file is as follows:

{
  "nonce": "0x0000000000000042",
  "difficulty": "0x00002",
  "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "coinbase": "0x0000000000000000000000000000000000000000",
  "timestamp": "0x00",
  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa",
  "gasLimit": "0xffffffff",
  "alloc": {
    "3282791d6fd713f1e94f4bfd565eaa78b3a0599d": {
      "balance": "1337000000000000000000"
    },
    "17961d633bcf20a7b029a7d94b7df4da2ec5427f": {
      "balance": "229427000000000000000"
    }
  },

  "config": {
    "chainId": 666,
    "homesteadBlock": 0,
    "eip150Block": 0,
    "eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "eip155Block": 0,
    "eip158Block": 0,
    "byzantiumBlock": 0,
    "constantinopleBlock": 0,
    "petersburgBlock": 0,
    "istanbulBlock": 0,
    "ethash": {}
  }
}

Key value pair meaning:
mixhash refers to the hash generated by a part of the previous block in cooperation with nonce for mining. Note that his and nonce settings need to meet Ethereum's Yellow paper, 4.3.4. Block Header Validity
Nonce: nonce is a 64 bit random number used for mining. Note that the settings of nonce and mixhash need to meet the conditions described in Yellow paper, 4.3.4. Block Header Validity, (44) of Ethereum.
Difficulty: set the difficulty of the current block. If the difficulty is too large, it will be difficult for cpu to mine. Set a smaller difficulty here
alloc is used to preset the account number and the number of etheric coins in the account
coinbase is the miner's account number
Timestamp: set the timestamp of the creation block
parentHash is the hash value of the previous block. Because it is a creation block, this value is 0
extraData is: additional information. You can fill in your personality information at will
gasLimit: this value sets the total consumption limit of GAS, which is used to limit the total amount of transaction information that can be contained in the block. Because we are a private chain, we fill in the maximum.

chainId: the chainId of Ethereum main network is 1, which is mainly used to prevent transaction replay in different Ethereum isomorphic networks. It is mainly used when signing and verifying transactions.
When creating a new EVM chain, you need to specify the ChainId in the genesis file. This ChainId should not be the same as the ChainId of any existing EVM chain that is already running publicly, otherwise you can spend a sum of money by mistake due to a configuration error. The following is an example of the genesis file configuration. The occupied ChainId can be accessed through this ChainId list website see.

Note: for the difference between chainId and networkId, please refer to the following link: https://www.jianshu.com/p/b8730a05eb36

2.2 initialize Genesis block

Run the cmd command under the PrivateChain directory to initialize the genesis block configuration file genesis.json:

geth --datadir data --networkid 20200107 --rpc --rpccorsdomain "*" init genesis.json

– in datadir data, data is the name of the folder, and the private chain data will be stored in this folder (that is, create a new data file in the privateChain directory). When you want to create other private chain nodes in the same computer, you can create another folder, such as data2, and then distinguish different private chain nodes through – datadir data2. If – datadir is not set, the data of the Ethereum main network will be read. The default location is C:\Users\Administrator\AppData\Local\Ethereum, which can be viewed through the datadir option in get - help.

– networkid 20140628 is the private chain network id, which can be arbitrarily modified to its own id. in order to build other nodes under the private chain, the networkid must be the same.
be careful:
NetworkId cannot be specified through the configuration file, but can only be specified through the parameter -- NetworkId. Therefore, we need to remember to add this parameter to our private chain node. If this parameter is not added and the network type is not specified, the default NetworkId value is the same as that of the Ethereum master network.
ChainId is used to prevent transaction replay in different Ethereum isomorphic networks. It is mainly used when signing and verifying transactions. NetworkId is used to identify the blockchain network.

init initializes genesis.json and creates the creation block (the first node is created when the block is created).

If the creation is successful, the following files will appear under privateChain: geth and keystore
The geth folder is used to store the relevant data of the private chain, and the keystore folder is used to store the user information of the chain. After a series of actions around the private chain are completed.

2.3 open private chain client

Run the cmd command under the PrivateChain directory to open the private chain client:

geth --datadir data --networkid 20200107 --rpc --rpccorsdomain "*" --nodiscover --port 16333 --rpcport 8546 --allow-insecure-unlock console

or

geth --identity "myblockchain" –rpc --rpcaddr 127.0.0.1 --rpccorsdomain "*" --datadir data --port"16333" --rpcport 8546 --rpcapi "db,eth,net,web3" --allow-insecure-unlock --networkid 20200107 console

Command meaning:
rpc: start rpc communication to deploy and debug smart contracts
rpcapi, that is, set the rpc clients that are allowed to connect. Generally, DB, ETH, net and Web3 are enabled by default
rpcaddr: local IP address or public chain server address (127.0.0.1 by default, which can only be accessed locally)
– allow secure unlock: Unlock http. If it is not set, the account cannot be unlocked through HTTP
rpcport is the ipc service port. The default port number is 8545

After the private chain is successfully opened, you will be prompted to welcome to the JS console:
welcome to the Geth JavaScript console!

Enter exit to exit.

2.4 accounts / mining / transactions

2.4.1 viewing and creating accounts:

personal.listAccounts  # View account list information
eth.accounts  # Or web3.eth.accounts
eth.accounts[0]  # View first account
eth.coinbase  # Namely: query the current absenteeism account

personal.newAccount('123456')  # The parameter is the account password. After the creation is successful, you will be prompted to save the key file, etc.

2.4.2 transfer unlocking and other orders

eth.accounts  # View account
eth.blockNumber # View block height
eth.getBlock(0)  # View Genesis block
eth.getBlock(eth.blockNumber).miner  # Get the name of the miner who dug the last block

miner.setEtherbase(eth.accounts[0])  # Set the first account as a miner

admin.nodeInfo  # View current node information
#Execute admin.addPeer("URL of own node") on other clients to tell them to add their own nodes
admin.nodeInfo.enode

eth.getBalance(eth.accounts[0])  # View first account balance
eth.getBalance(eth.accounts[1])  # View second account balance

# ether =wei * 10^18, that is, the accuracy can reach 18 bits.
web3.fromWei(1000000000000000000,"ether")   # wei to ether
web3.toWei(1)  # ether to wei

# Query the balance of the 1st / 2nd account (note that web3.fromWei means to convert wei unit to ether, because wei is the mine by default)
web3.fromWei(web3.eth.getBalance(web3.eth.accounts[0]),"ether")  
web3.fromWei(web3.eth.getBalance(web3.eth.accounts[1]),"ether") 

# Transfer can only be performed after the account is unlocked,
personal.unlockAccount(web3.eth.accounts[0])  # Unlock account

# Transfer: transfer from the first account to the second account, and the number of transfers is 5 eth
web3.eth.sendTransaction({from:web3.eth.accounts[0] , to:web3.eth.accounts[1], value:web3.toWei(5, "ether")})

The transfer operation can only be performed after the account is unlocked. Here, note the parameter - allow secure unlock - that needs to be included in the cmd command to open the private chain client
For security reasons, account unlocking via HTTP channel is prohibited by default

resolvent:
You can add parameters to the startup command: – allow -insecure -unlock
Exit the geth client first, and then restart the private chain client. Add the parameter – allow secure unlock to unlock HTTP

exit  # Exit the geth client first
geth --datadir data --networkid 20200107 --rpc --rpccorsdomain "*" --nodiscover --port 16333 --rpcport 8546 --allow-insecure-unlock console

The transfer has been submitted successfully, but the transaction has not been completed. The miner needs to submit a new block for mining, add the transfer transaction in the block, and submit the new block to the network node (calculated as a percentage) for confirmation before the transaction takes effect.

2.4.2 Mining: miner.start(2)

miner.start();admin.sleepBlocks(1);miner.stop()  # Command combination: start mining, pause after packing a block, and stop mining.

Mining: miner.start(2)
Parameter 2 means to start two threads, 1 means to mine with only one thread, and if it is empty, it means that all processes mine.

It will be initialized for the first time, wait patiently, and start mining when the progress percentage reaches 100.
Prompt:
mined potential block indicates that the mine has been excavated;
commit new mining work means that a new mining work has been submitted;

After successful mining, stop mining and check the account balance again

web3.fromWei(web3.eth.getBalance(web3.eth.accounts[0]),"ether")  
web3.fromWei(web3.eth.getBalance(web3.eth.accounts[1]),"ether") 

If the eht of account 1 is more than that of our first query, it is because new coins will be dug in the project of mining synchronous transaction again.
If the balance of query account 2 increases, the transfer is successful.

At this point, a simple private chain is built successfully.

3, Eth private chain creation node and synchronization

Topics: Blockchain