Teacher Xiao Zhen from Peking University's "Blockchain Technology and Application" series of course study notes [22] Ethereum-Smart Contract-2

Smart Contract-1

Table of contents

1. Creation and operation of smart contracts

        1. Creation of smart contracts

        2. Gasoline fee

        3. Error handling

        4. Nested calls

Two, thinking

        1. GasLimit and GasUsed

        2. The difference between GasLimit in Ethereum and Bitcoin

1. Creation and operation of smart contracts

1. Creation of smart contracts

        The smart contract initiates a transfer transaction from an external account , transfers it to the address 0x0, and then puts the code of the contract to be released into the data field. To create a contract, you need to initiate a transfer transaction, transfer money to the address 0, and the transfer amount is 0. In fact, you don’t really want to transfer money, but you want to publish a smart contract. Just put the code of the released smart contract into the data field, and the code of the contract must be compiled into bytecode, and then run on the EVM. JVM, Java Virtual Machine, aims to enhance portability . EVM is similar to this design idea. By adding a layer of virtual machine, it provides a consistent platform for the operation of smart contracts. EVM is sometimes called Worldwide Computer (a computer all over the world). The addressing space of EVM is very large, 256 bits, and unsigned int is 256 bits.

        Comparing Bitcoin and Ethereum, the programming models of these two blockchains have very different design concepts. The design concept of Bitcoin is simple, and the functions of the scripting language are very limited, such as: no support for loops. Ethereum needs to provide a Turing-complete programming model , Turing-complete Programming Model, that is, many functions are difficult to implement on the Bitcoin platform, or even impossible to implement. For the Ethereum platform, it is easy to implement. There are also problems in this way: what should I do if there is an infinite loop? When a full node receives a call to a smart contract, how does it know whether the execution of the call will cause an infinite loop?

        But there is no way , this is actually a Halting Problem, and the Halting Problem is unsolvable. The problem here is not NPC . NPC problems can be solved, but there is no polynomial time solution. Many NPC problems have natural exponential solutions, such as the Hamiltonian circuit problem. It is actually very difficult to judge whether a graph has a Hamiltonian circuit. It is easy to solve. It is very easy to want a solution. If the complexity is not considered, you can enumerate all the possibilities. For example, there are n vertices, and the arrangement of n vertices is n! With so many combinations, check whether each combination constitutes a legal circuit, and you will know whether he has a Hamiltonian circuit, so the Hamiltonian circuit problem is solvable, but the complexity of the solution is exponential . The Halting Problem is fundamentally unsolvable . It can be proved theoretically that there is no such algorithm that can determine whether the program will halt for any given input program. At this time, we will push this problem to the account that initiated the transaction . Ethereum has introduced a gas fee mechanism, that is, the corresponding gas fee needs to be paid when initiating a call to a smart contract.

2. Gasoline fee

(1) Data structure

type txdata struct {
    AccountNonce uint64          `json:"nonce"    gencodec:"required"`
    Price       *big.Int         `json:"gasPrice" gencodec:"required"`
    GasLimit    uint64           `json:"gas"      gencodec:"required"`
    Recipient   *common.Address  `json:"to"       rlp:"nil"` //nil means contract creation
    Amount      *big.Int         `json:"value"    gencodec:"required"`
    Payload     []byte           `json:"input"    gencodec:"required"`
Picture 1-1

When a full node receives a call to a smart contract, it first calculates the maximum gas fee that may be spent according to the GasLimit         given during the call , and deducts the gas fee from the account that initiated the call at one time, and then Then, according to the actual implementation situation, calculate how much money was actually spent, and refund more and make up less. In fact, it is not called more refund and less compensation. If the gas fee is not enough, it will cause a rollback. Different instructions consume different gasoline costs. Simple instructions (such as addition and subtraction) consume very little gasoline, while complex instructions consume more gasoline. Take the hash operation, one instruction can be completed, but the gas fee is more expensive. In addition to the amount of calculation, the instructions that need to store the state also consume a lot of gasoline. In contrast, if you're just reading public data, those instructions can be free.

3. Error handling

        Transactions in Ethereum are executed atomically. That is, a transaction is either fully executed or not executed at all, not only part of it. This transaction includes both ordinary transfer transactions and calls to smart contracts, so if any error occurs during the execution of smart contracts, it will cause the execution of the entire transaction to roll back and return to the state before the start of execution. It's as if the transaction was never executed at all . So what happens when an error occurs?

(1) After the transaction is executed, if it is found that the gas fee has not reached the original GasLimit, then the excess gas fee will be returned to this account. At the beginning, the gas fee will be deducted according to the maximum GasLimit, and the remaining gas will be refunded after the operation is completed; if the transaction is executed halfway and the GasLimit has been exhausted, the execution of the contract will return to the state before the execution started , this is a kind of error handling, and the gas fee that has been consumed at this time is not refundable. The execution status needs to be rolled back, but the gas fee that has already been consumed will not be refunded , otherwise malicious nodes will launch a delayed service attack , publish a contract with a large amount of calculation, and then keep adjusting the contract, every time The gas fee given is not enough, and the gas fee will be refunded in the end, so there is no loss for this node, but the miners waste a lot of resources in vain.

(2) The assert statement and the require statement are both used to judge a certain condition. If the condition is not met, an exception will be thrown. The assert statement is generally used to judge a certain internal condition, and the require statement is generally used to judge a certain external condition, such as judging whether the input of a function meets the requirements.

function bid() public payable {
    //对于能接收以太币的函数,关键字payable是必须的。
    
    //拍卖尚未结束
    require(now <= auctionEnd);
}

        In the above example, the bid is a simple function. Here, the function is judged. If the current time now<=auctionEnd, the end time of the auction, it will continue to execute, otherwise, an exception will be thrown. The third statement is revert() , which throws an exception unconditionally. If the revert statement is executed, it will automatically roll back. The throw statement was used in the earlier version, but it is recommended to use the revert statement in the new version of solidity. There is no such try-catch structure in solidity , and some programming languages ​​​​like Java (the user can define what to do after a problem occurs, he has this try-catch).

4. Nested calls

        An error in the smart contract will cause a rollback . If the called smart contract has an error during nested calls (one smart contract calls another smart contract), it will not necessarily lead to a chained rollback (the smart contract that initiated the call is followed by Rollback), depends on the method of calling this smart contract. If it is called directly, there will be a chain rollback, and the entire transaction will be rolled back; if the calling method is call, it will not cause chain rollback. Will only cause the current call to fail and return a false return value. In some cases, on the surface, you do not call any function, such as transferring money to an account. If the account is a contract account, the transfer operation may trigger a call to the function (because there is a fallback() function ), which is a nested call. When one contract transfers money to another contract, it is possible to call the fallback function in this contract.

Two, thinking

1. GasLimit and GasUsed

        The GasLimit and GasUsed in the Block Header are related to gas fees, and the GasUsed in the Block Header is the sum of the gas fees consumed by all transactions in the block. GasLimit is actually not like this. Publishing a block requires a certain amount of resources, and there is a limit to the consumed resources.

        In Bitcoin, there is a limit to the published blocks. The size limit cannot exceed 1M. If there is no limit to the published blocks, some miners may pack a large number of transactions into one block and then publish it. , then this super large block will consume a lot of resources on the blockchain, so it stipulates that each block cannot exceed 1M at most. Bitcoin transactions are relatively simple. Basically, the number of bytes in the transaction can be used to measure how much resources the transaction consumes. However, the logic of the smart contract in Ethereum is very complicated, and some transactions may be very small in terms of the number of bytes. Yes, but the resources he consumes may be large, for example, he may call other contracts, so it is charged according to the specific operation of the transaction, which is the gas fee.

        GasLimit is the upper limit of gasoline consumed by all transactions in the block. It does not add the GasLimit of each transaction in the block together. In that case, there is no limit. The GasLimit of each transaction is set by the account that issued the transaction. How much is up to you. However, there is an upper limit to the gas that can actually be consumed by all transactions in this block. If a large block goes out, it will not benefit the operation of the entire system.

2. The difference between GasLimit in Ethereum and Bitcoin

        Bitcoin limit resources are limited according to size (upper limit 1M), which is written in the agreement. Some people think that 1M is too small, and some forked coins are created to increase this upper limit. There is also an upper limit in Ethereum - GasLimit, but each miner can fine-tune the GasLimit when releasing a block, and can adjust it up or down based on the GasLimit \frac{1}{1024}. If there is a situation like Bitcoin, everyone thinks that the GasLimit is too small, then it can be increased by 1/1024 when releasing the block. Due to the fast block generation speed of Ethereum, the average block generation time is only a dozen seconds. If everyone thinks that the current GasLimit is too small, it can be doubled soon. Of course, the same reason may also be lowered, so the GasLimit actually obtained by this mechanism is an average value of the GasLimit that all miners think is reasonable. Some miners think it should be raised, and some miners think it should be lowered. After the miners obtain the right to bookkeeping, they will fine-tune the upward or downward adjustment according to their own wishes, and finally the GasLimit of the entire system tends to an average opinion of all miners.

Guess you like

Origin blog.csdn.net/YSL_Lsy_/article/details/126558667