ETH trunk interface

Functions that ETH relay can provide

1. 接受其他服务端脸上的相关服务请求,中继处理请求业务,将处理后的响应返回给用户。如查询余额等
2. 发起交易的功能,包括ETH转账和ERC20转账
3. 用户的钱包创建
4. 对链上区块相关事件的监听,目前可以实现的监听事件包括但不限于如下:
	a. ERC20 Token的授权Approve事件
	b. Token转账Transfer的结果事件
	c. WETH Token置换ETH事件
	d. 新区块生成事件
	e. 遍历一个区块事件
	f. 区块分查事件

insert image description here

block traversal

In relay development, event monitoring is the most difficult development.
The technical principle of event monitoring is mainly to achieve the goal by obtaining the transaction information inside a block and parsing the "EventLog" (log event) in the transaction information.
At present, ETH provides web.js library, which has block event monitoring function, but it is not perfect, and has the following deficiencies:

  1. If the client's process is killed, the monitoring action will be lost
  2. If the block number of the last successfully traversed block is stored, the data of the newly generated block within the time period will be lost when restarting
  3. The complete monitoring process consumes device resources on the client side and affects user experience

Why monitor?
Centralized exchanges need to do such things, such as recharging or withdrawing cash, all need to monitor the data on the chain. After the transfer on the chain is successful, then modify the database of the centralized server. If it is not monitored, in terms of cash withdrawal, if If the transaction on the chain fails, but the value of the user in the centralization decreases, there will be problems.

In the ETH mechanism, events such as authorization, transactions, and contract releases on the chain are all transaction information. Each transaction information can be extracted and divided into different functions and businesses.

RPC interface (Remote Process Call, remote procedure call)

insert image description here

There are many ways to implement the RPC interface based on the communication protocol, but there are mainly the following two methods:

  1. Same as "RESTful API", implemented based on application layer HTTP/HTTPS protocol
  2. Implementation of the TCP protocol based on the transport layer, also known as the implementation of Socket (nested words)

The difference between the two methods lies in the location of the request and response, one is at the application layer and the other is at the transport layer.
The RPC interface and the "RESTful API" interface are implemented in the HTTP/HTTPS protocol, and there is almost no difference in speed,
but the RPC interface implemented based on the TCP protocol of the transport layer, except for the level of data transmission stream, is less than the "RESTful" interface. In addition to being faster than it, the overall datagram level during transmission also reduces the amount of HTTP/HTTPS header data and the time consumption of assembly. That is to say, when the RPC interface is implemented based on the TCP protocol of the transport layer, the RPC interface not only requests and responds faster than the "RESTful" interface, but also has relatively less data volume.

Common RPC frameworks are as follows:

  1. JSON-RPC
  2. XML-RPC
  3. Protobuf-RPC
  4. SOAP-RPC

In short: The RPC protocol is to standardize a data format for interaction between a client and a server that implements the RPC interface.

The general flow of RPC interface implementation:

  1. The service call scheme serializes and encodes the functions and parameters of an RPC interface according to the standardized encoding method
  2. Sent to the provider of the service, that is, the server
  3. The server side extracts the corresponding parameters after deserialization
  4. Then by calling the relevant function
  5. Finally, the result is returned to the caller on the server side

Three important parameters accompanying the ETH RPC interface

Before understanding the ETH RPC interface, first understand 3 parameters, because these 3 parameters will appear in each interface.

  • genesis, which represents the earliest, which is equivalent to earliest in the early source code version
  • pending, which represents the waiting or pending state
  • latest, which represents the latest completed

ETH RPC interface

1.eth_blockNumber

This interface can obtain 3 types of block heights according to the passed parameters (genesis, pending, latest)

  1. genesis, which represents the genesis block, because the earliest block number can be specified, so the genesis block is not necessarily 0
  2. Pending, which represents the block that is currently being mined by minter, represents the block that is being packaged for transactions. A block will not be fully uploaded to the chain until a certain transaction is packaged.
  3. latest, the height of the latest block generated on the current chain

2.eth_getBlockByNumber

This interface obtains part of the information of the block according to the height of the block. It is an interface mainly used to obtain the block data information when traversing the block. This interface can provide the following data:

  1. Partial fields of the block header
  2. All transaction hash arrays packaged in this block

That is to say, the structure of the returned data is Block, that is, the information contained in this structure can be obtained.

// Block表示以太坊区块链中的一个完整的区块。
type Block struct {
    
    
	// block的header指向的是一个的结构体,其中带有该block的所有属性信息
	header       *Header
	// 叔块block的数组
	uncles       []*Header
	// 当前该区块所有打包的交易记录
	transactions Transactions
	// 缓存,应该是该区块的的hash及区块大小
	hash atomic.Value
	size atomic.Value

	// total difficulty,当前区块总共的难度值=前一个区块的td+当前区块header中的difficulty。
	td *big.Int
	// 区块被接受的时间
	ReceivedAt   time.Time
	// 记录区块是从哪个P2P网络传过来的
	ReceivedFrom interface{
    
    }
}

3.eth_getTransactionByHash

This interface can obtain the detailed information of a transaction based on the hash value of the transaction record.
This interface provides a transaction query function. After obtaining the transaction block information, obtain the hash value of the packaged transaction from the block information, and extract all transaction information. Transactions in the pending (waiting or pending) state will return empty. You can also judge whether a transaction is successful or not based on this feature of the interface.
The structure for getting data is Transaction.

// Transaction is an Ethereum transaction.
type Transaction struct {
    
    
	inner TxData    // Consensus contents of a transaction
	time  time.Time // Time first seen locally (spam avoidance)

	// caches
	hash atomic.Value
	size atomic.Value
	from atomic.Value
}

// TxData is the underlying data of a transaction.
//
// This is implemented by DynamicFeeTx, LegacyTx and AccessListTx.
type TxData interface {
    
    
	txType() byte // returns the type ID
	copy() TxData // creates a deep copy and initializes all fields

	chainID() *big.Int
	accessList() AccessList
	data() []byte
	gas() uint64
	gasPrice() *big.Int
	gasTipCap() *big.Int
	gasFeeCap() *big.Int
	value() *big.Int
	nonce() uint64
	to() *common.Address

	rawSignatureValues() (v, r, s *big.Int)
	setSignatureValues(chainID, v, r, s *big.Int)
}

4.eth_getTransactionReceipt

This interface can obtain the transaction receipt information according to the hash value of a transaction.
The data returned by this interface is the same as eth_TransactionByHash to a certain extent, but the data returned by this interface is more detailed, such as transaction logs, which are also the main data source for event monitoring. Like eth_getTransactionByHash, the transaction in the pending state will return empty. The returned structure is Receipt

// Receipt represents the results of a transaction.
type Receipt struct {
    
    
	// Consensus fields: These fields are defined by the Yellow Paper
	Type      uint8  `json:"type,omitempty"`
	PostState []byte `json:"root"`
	// 当这笔交易是成功的,该值为true,即 1 ,否则为 false
	Status    uint64 `json:"status"`
	// 该字段和GasUsed不一样,它所代表的是当前的交易 所在区块的列表中,
	// 当前TransactionIndex之上的包含的其他所有交易的Gas之和。
	// 例如,TransactionIndex = 4,
	// 那么它的CumulativeGasUsed数值就是下标为 01234的交易的GasUsed数值之和
	CumulativeGasUsed uint64 `json:"cumulativeGasUsed" gencodec:"required"`
	Bloom             Bloom  `json:"logsBloom"         gencodec:"required"`
	// 由当前交易生成的事件(Event)日志
	Logs              []*Log `json:"logs"              gencodec:"required"`

	// Implementation fields: These fields are added by geth when processing a transaction.
	// They are stored in the chain database.
	TxHash common.Hash `json:"transactionHash" gencodec:"required"`
	// 合约地址,只有在当前交易是合约创建的情况才会有值
	// 对应的是新创建合约的ETH地址,其他情况为空
	ContractAddress common.Address `json:"contractAddress"`
	GasUsed         uint64         `json:"gasUsed" gencodec:"required"`

	// Inclusion information: These fields provide information about the inclusion of the
	// transaction corresponding to this receipt.
	BlockHash        common.Hash `json:"blockHash,omitempty"`
	BlockNumber      *big.Int    `json:"blockNumber,omitempty"`
	TransactionIndex uint        `json:"transactionIndex"`
}

5.eth_getBalance

This interface obtains the ETH value of an ETH address, that is, the ETH balance. It is not to obtain the balance of ERC20 Token or other Tokens.

6.eth_sendRawTransaction 和 eth_sendTransaction

For details, please jump to the trigger interface of all transactions. The transaction types that eth_sendRawTransaction can complete include eth_sendTransaction.

7.eth_getTransactionCount

This interface can obtain the transaction serial number Nonce of the current wallet address according to an ETH wallet address. The second parameter of this interface is genesis, pending, latest, and each parameter corresponds to the following functions:

  1. When fetching genesis: Get the Nonce serial number when the current ETH address initiates the transaction for the first time
  2. When fetching pending: Get the current ETH address and submit the Nonce sequence number corresponding to the transaction order that is in the pending state and waiting to be packaged by the block. If the currently queried address does not have a transaction in the pending state, then the Nonce serial number same as latest is returned.
  3. When fetching latest: Get the value of the Nonce sequence number plus 1 corresponding to the transaction order submitted by the current ETH address and successfully packaged in the block. For example, the Nonce corresponding to the last successful transaction of address A is 8, then when the incoming parameter of the call interface is latest, the obtained result is 9, that is, 8+1.
  4. In eth_getTransaction, the Nonce query satisfies: pending>=latest>=genesis

8.eth_getCode

This interface judges whether the current address is a contract address or a non-contract address based on the ETH address. If not, the return value is "0x", otherwise, it returns the hexadecimal code when the smart contract was originally created.

9.eth_estimateGas

This interface is used to estimate how much GasLimit a transaction will consume, and the estimated value does not involve GasPrice.
The data in the input parameter is the estimated data volume, and the estimated result value is proportional to the data volume.
This interface will be used when the wallet initiates a transaction to allow the user to choose the gas fee, and it will be withdrawn to the maximum value in the gas fee progress bar. The maximum value is generally the value returned by this interface.

10.eth_call

This is the universal RPC interface used by ETH to access smart contracts , that is, any public function on any smart contract can be accessed using this interface.

eth_getBalance is used to query the ETH balance, but the ERC20 Token balance needs to be queried through eth_call. The input parameters of this interface are the same as those of eth_sendRawTransaction/eth_sendTransaction.
The eth_call interface is a read-only interface that will not change the data on the blockchain and can access all functions in the ETH smart contract.

The read-only feature of eth_call is understood from the upper level of the source code
. When executing the contract code, the EVM
first uses the block number blockNumber to find out the corresponding block information,
and then systematically instantiates a variable named status according to the data of this block. , the corresponding EVM instance is instantiated by status,
and then the variable value of the contract code is instantiated according to the information provided by the block, that is, the variable value of the function of the smart contract is determined by the current block height before it is executed.
That is to say, when eth_call calls the transfer function, it will directly modify the value at the memory level of the code, without broadcasting and modifying it to the data level.

node link

There are currently two ways to obtain node links

  1. Purchase the server by yourself, then start the ETH node service program, such as Geth, and then obtain the interface link provided by the node program.
  2. Use the node link provided by the third-party service platform

For the first method, the operation process is to download the source code of the corresponding ETH node version first, then self-compile according to the compilation method of the document, generate an executable program, and then deploy it to the server. It should be noted that the source code of ETH nodes not only has versions with different version numbers, but also versions in different computer languages. The official Geth is a version developed in Golang language.

The advantages and disadvantages of the overall implementation of the first method:
(1) Highly customizable

  • You can configure the configuration file for node startup by yourself
  • You can modify the source code by yourself for secondary development and then compile it
  • You can set up related operation modes such as service gateway and node cluster by yourself
  • You can participate in the public chain minter and earn ETH income

(2) The difficulty of technical requirements is relatively high

  • Users are required to master and understand the meaning and impact of each attribute in the configuration file
  • Users are required to understand some server-side operation and maintenance knowledge
  • Users are required to understand the compilation commands of the corresponding node programming language, and even have used the language

(3) High self-operation and maintenance costs

  • It is required to monitor the operation of the node service
  • Requires implementation of node programs, as some issues are able to auto-restart after being killed
  • In the case of clusters, it is required to ensure the stability of each service

(4) Expenses for self-paid servers and other products

The second option

  • It is suitable for use in the learning stage and when online business does not require a high degree of customization

Compared with the first scheme, the second scheme has opposite advantages and disadvantages.
The second option is also the most convenient and cheap, since only one link is required.

Implementation of the second option

link acquisition

The node link can be obtained for free according to https://infura.io/ .
Infura is a foreign cluster that hosts ETH nodes. It also allows developers to apply for their own ETH node links (including mainnet and testnet) for free. It has complete functions and is convenient.

Detail go to 153 and 159。

Guess you like

Origin blog.csdn.net/wjl__ai__/article/details/125211499