Building an Ethereum private blockchain based on Mac environment for mining simulation

The first step: installation of related software

  • go-ethereum client installation
  • The Go-ethereum client is usually called Geth, which is a command-line interface that executes the complete Ethereum node implemented on Go. Geth benefits from the multi-platform nature of the Go language and supports use on multiple platforms (such as Windows, Linux, Mac). Geth is based on the specific implementation of the Ethereum protocol. Through Geth, you can implement various functions of Ethereum, such as the creation and deletion of new accounts, the opening of mining, the transfer of ether coins, and the deployment and execution of smart contracts.

Geth can connect using the following three JSON RPC protocols:

  • Internal Process Communication (IPC) : Internal communication, usually used in a computer.
  • Remote program call (RCP) : Communication across computers. Usually TCP and HTTP protocols are used.
  • WS (Web sockets) : Use sockets to connect to Geth.

Chain ID meaning:

  • chain ID: 1 Mainnet public chain
  • chain ID: 2 Morden network (only open to some people)
  • chain ID: 3 Ropsten network
  • chain ID: 4 Rinkeby network
  • Chain ID greater than 4 is a private network
  • Use Geth --testnet to connect to the Ropsten network and Geth --rinkeby to connect to the Rinkeby network.
  • The installation command is as follows:
brew tap ethereum/ethereum
brew install ethereum
  • My display interface

  • Check whether the installation is successful, enter the following command
geth --help
  •  The following interface appears, that is the installation is successful

Step 2: Build a private chain

  • Ethereum supports custom creation blocks. To run a private chain, we need to define our own creation blocks. The creation block information is written in a json format configuration file. First save the following content to a json file, generally named after genesis.json.
  • Prerequisite operation commands are as follows
mkdir myeth
cd myeth
vi genesis.json
  • The content of the json file is as follows: just copy it directly.
{
  "config": {
        "chainId": 666999, 
        "homesteadBlock": 0,
        "eip150Block": 0,
        "eip155Block": 0,
        "eip158Block": 0
    },
  "alloc"      : {},
  "coinbase"   : "0x0000000000000000000000000000000000000000",
  "difficulty" : "0x20000",
  "extraData"  : "",
  "gasLimit"   : "0x2fefd8",
  "nonce"      : "0x0000000000000042",
  "mixhash"    : "0x0000000000000000000000000000000000000000000000000000000000000000",
  "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
  "timestamp"  : "0x00"
}
  • Explanation of the above parameters

  • Note, I refer to many articles are missing the sentence eip150Block: 0, this will be wrong.
  • The error condition is Failed to wirte genesis block: unsupported ordering

Network initialization

  • Enter the geth init command, genesis.json file, the folder for storing block data and keystore to initialize.
geth init "/Users/chy/Desktop/myeth/genesis.json" --datadir "/Users/chy/Desktop/myeth/chaindata"
  • The genesis block has been generated and the Geth node can be started. The IPC protocol is used by default when Geth starts. To ensure that the Geth node can be accessed through the PRC protocol, the RPC parameter needs to be included in the command 
  • The command operation is as follows

 Set up the environment in which the node runs

geth --datadir "/Users/chy/Desktop/myeth/chaindata" --rpc --rpcapi "eth,web3,miner,admin,personal,net" --rpccorsdomain "*" --nodiscover --networkid 15 –allow-insecure-unlock
  • Explanation of commands
  • –Datadir: specify the storage location of the blockchain data; this requires everyone to adjust according to the actual situation and replace their own path
  • –Rpc: indicates to enable HTTP-RPC service;
  • –Rpcapi “eth, web3, miner, admin, personal, net”: This command indicates the command that allows access via RPC. By default, Geth allows web3.
  • –Nodiscover: Turn off the node discovery mechanism to prevent joining strange nodes with the same initial configuration;
  • –Identity: Specify the node ID to facilitate the identification of your own node among a large group of nodes;
  • –Rpcport: Specify the HTTP-RPC service listening port number (default is 8545);
  • –Rpcaddr: specify the IP address;
  • –Port: Specify the port number used to connect with other nodes (default is 30303);
  • –Maxpeers 0 If you do not want someone to connect to your test chain, use maxpeers 0. Or, you can adjust the parameters when you know exactly how many nodes you want to connect.
  • Use without command -allow-insecure-unlock when the unlock will error Error: account unlock with HTTP access is forbidden, turned out to be for security reasons, the HTTP channel is disabled by default unlock the account, issues related reference
  • After executing the above command, it was found that Fatal: Error starting protocol stack: datadir already used by another process. This problem is because it is necessary to forcibly shut down the running geth process. The command is as follows: 54148 is the ID number of the geth process
  • Add the parameter –allow-insecure-unlock again to restart the g private chain. Now execute the unlock account command to succeed.

geth --datadir "/Users/chy/Desktop/myeth/chaindata" --rpc --rpcapi "eth,web3,miner,admin,personal,net" --rpccorsdomain "*" --nodiscover --networkid 15 --allow-insecure-unlock
ps aux | grep "geth"
kill -9 54148
  • The enode information is the identity of the node on the network. If other nodes are ready to join this network, they need to provide their own enode values. RPC access can be through http://127.0.0.1:8545 or http: // localhost: 8545, and IPC access can be through the ** \. \ Pipe \ geth.ipc ** command. The command is continuously run in the form of a service. You need to open a command line window again , but the original window cannot be closed . Enter the command as follows:

Geth attach rpc:http://localhost:8545
  • The following page appears, enter the control page. Use the IPC protocol to connect to the node so that other commands can be executed.

Interactive execution environment

  • This is an interactive JavaScript execution environment where JavaScript code can be executed, where> is the command prompt. In this environment, some JavaScript objects for operating Ethereum are also built in, and these objects can be used directly. These objects mainly include:
  • eth: contains some methods related to the operation of the blockchain;
  • net: contains some methods to view the p2p network status;
  • admin: contains some methods related to managing nodes;
  • miner: contains some methods to start and stop mining;
  • personal: mainly contains some methods for managing accounts;
  • txpool: contains some methods to view the transaction memory pool;
  • web3: contains the above objects, and also contains some unit conversion methods.

Common commands:

  • personal.newAccount (): create an account;
  • personal.unlockAccount (): Unlock account;
  • eth.accounts: enumerate the accounts in the system;
  • eth.getBalance (): View account balance, the unit of return value is Wei (Wei is the smallest currency denomination unit in Ethereum, similar to Satoshi in Bitcoin, 1 ether = 10 ^ 18 Wei);
  • eth.blockNumber: List the total number of blocks;
  • eth.getTransaction (): Get transaction;
  • eth.getBlock (): Get block;
  • miner.start (): start mining;
  • miner.stop (): stop mining;
  • web3.fromWei (): Convert Wei to Ether;
  • web3.toWei (): Convert Ether to Wei;
  • txpool.status: status in the transaction pool;
  • admin.addPeer (): connect to other nodes;

Step 3: Set up an account

  • After connecting to the Geth node, the next step is to set up a coinbase or etherbase account. To create an account, you can use the newAccout method of the personal object and set a password (the password is not visible). The command is as follows.
personal.newAccount()
  • If you need to change the original coinbase account address, you can operate it through the setEtherBase function of the address.miner object. This operation will replace the original coinbase account with a new account. The command is as follows
miner.setEtherbase("0x19b4029dad20824db6dc201437f9cac2a7e1fc5c")
  • Execute the query command, you can see that the set address has taken effect. Mining can now be started. Since there is only one miner who will receive all the mining rewards, the Ether of the coinbase account will gradually increase.
eth.coinbase
  • Create another account in the same way
  • View current users
eth.accounts
  • The code executes as follows

Step 4: Start mining

  • The parameter in start represents the number of threads used for mining. The command is as follows
miner.start(8)
  • At this time, switch to the command line window that created the private chain, and you can see the output of the mining process. This refers to the first window we created at the time.

  • If it is the first time mining, DAG related files need to be generated, which takes a certain amount of time. No need after the second time.

  • Because I am mining for the second time, there is no above file.

  • When using the input log method, you can enter the command tail -f geth.log to track the progress of mining
  • View the Ether balances of the account 0 that has been mined and the account 1 that has not been mined. The command to view the balance of the wallet is as follows. Change the 0 to 1 to view the balance of the second account.
eth.getBalance(eth.accounts[0])
  • The implementation is as follows:


 

  • Mining a block will reward 5 ether, and the rewards from mining will enter the miner's account. This account is called coinbase. By default, coinbase is the first account in the local account.

  • The unit of the return value of getBalance () is wei, wei is the smallest unit of Ether, 1 Ether = 10 to the 18th power of wei. To see how many Ethereum there are, you can use web3.fromWei () to convert the return value to Ethereum

  • Stop mining, the command is as follows

miner.stop()
  • The overall operation layout, dynamic monitoring of user input on the left, and Ethereum Javascript Console on the right The page layout is as follows

Step 5: Make a transaction

  • We want to transfer from account 0 to account 1. You need to unlock the account before you can transfer, otherwise you will get an error.
  • The unlock command is as follows
personal.unlockAccount(eth.accounts[0])
  • Initiate a transaction, transfer 200 Ether from account 0 to account 1, the command is as follows
personal.unlockAccount(eth.accounts[0])
amount = web3.toWei(200,'ether')
eth.sendTransaction({from:eth.accounts[0],to:eth.accounts[1],value:amount})
  • At this point, the transaction has been submitted to the blockchain, and the hash of the transaction has been returned, but it has not yet been processed. There is a transaction to be confirmed in the local transaction pool. You can use eth.getBlock ("pending", true) .transactions to view the current pending Confirm the transaction.
eth.getBlock("pending", true).transactions
  • For transactions to be processed, mining must be done. Here we start mining, and then stop mining after waiting for a block to be mined. The command is as follows:

miner.start(1);admin.sleepBlocks(1);miner.stop();
web3.fromWei(eth.getBalance(eth.accounts[1]),'ether')
  • At this point, the transaction has taken effect and account 1 should have received 200 ether.

Reference documents

 

Published 76 original articles · won praise 2 · Views 3773

Guess you like

Origin blog.csdn.net/CHYabc123456hh/article/details/105588927