# Resource Sharing of Smart City Based on Blockchain

Authors: Tao Huang
Journal: Wireless Communications and Mobile Computing
 (2021)

---

## Abstract

The concept of smart city refers to the improvement of the quality of life of the city by making full use of idle resources by sharing. However, limited by the technical level, the current resource sharing system mostly adopts centralized data storage mode. Systems managed in this way are vulnerable to multiple threats. The tested blockchain technology with the characteristics of decentralization and tamper resistance can effectively prevent various risks. Starting with the architecture of blockchain intelligent contract, this paper puts forward a structural optimization factor model of intelligent contract. To optimize the structure of blockchain intelligent contract, the gas optimization theory is put forward by changing the order, reducing the use of costly EVM data fields, reducing redundant fields, and optimizing intelligent contract codes. Experimental analysis of the proposed model is carried out, and the effectiveness of the proposed method is verified by comparing the transaction execution time of cost calculation with the cost of executing gas, which can provide reference for the selection of intelligent contract organization structure of smart city resource sharing system.


---

## Body

## 1. Introduction

The concept of smart city refers to the improvement of the quality of life of the city by making full use of idle resources by sharing. Due to the limitation of technical level, most of the current resource sharing systems adopt centralized data storage mode. Systems managed in this way are vulnerable to multiple threats. In addition, the traditional sharing method cannot establish an objective and true credit mechanism for bad users, which leads to potential safety hazards. The tested blockchain technology with the characteristics of decentralization and tamper resistance can effectively prevent various risks. This paper proposes an algorithm to predict transaction execution time and gas execution cost and verifies the effectiveness of the algorithm by experiments, which can provide reference for the selection of intelligent contract organization structure in smart city resource sharing system.Literature [1] proposes a method based on network tomography to realize low-cost, scalable, and flexible monitoring deployment of the road network system. It can complete the path matching of smart city system. Literature [2] studies the specific positioning and components of data center. Based on the construction requirements of data center, it constructs an architecture of smart city, related contents, and construction ideas that data center should contain in it and discusses the application of data center in smart city. Literature [3] proposes an infrastructure based on blockchain to realize sustainable Internet of Things (IoT) sharing economy in super smart cities, so as to support space-time intelligent contract services for security and privacy. Literature [4] constructs the smart city blockchain vehicle information network system. By running the system in a decentralized way, a multipoint collaborative transportation management system can be built. Literature [5] proposes an efficient, scalable, and blockchain-based distributed smart city network architecture-light-fidelity (Li-Fi) communication technology. In order to solve the rapid increase in the number and diversity of smart devices connected to the Internet, literature [6] establishes a new multi-interconnection system framework of smart cities. Through the design of hybrid architecture, the architecture is divided into two parts: core network and edge network, which improves the efficiency and solves the limitations of the current architecture. Literature [7] proposes a multivariate system model which is divided into core network and edge network and puts forward a working proof scheme in the model. Literature [8] uses blockchain technology to take a global view of the security policy in the system and integrate it into the FIWARE platform. Literature [9] deeply explores the association between sensor networks and blockchain smart contracts. The concept of “rolling blockchain” is put forward, which can be used as a network node to build wireless sensor networks with the participation of smart cars. Literature [10] puts forward a workflow chart of technical experiment to explore how blockchain technology can protect the integrity of sensor data when the Internet of Things is the infrastructure. A data management framework of Internet of Things is constructed, which can strengthen data-driven operation. Literature [11] identifies the basic elements of smart cities, then provides a detailed literature on the existing technologies for realizing smart cities, highlights their shortcomings, and explains how blockchain can help the effective implementation of these technologies. Literature [12] proposes a decentralized architecture using blockchain, which can run ledger services on distributed networks. Literature [13] proposes a blockchain-based power transaction (B-ET) ecosystem and designs an intelligent contract to ensure that the transaction is conducted in a safe and reliable way. Literature [14] proposes an infrastructure based on blockchain to support space-time intelligent contract services for security and privacy, which can be used for sustainable sharing economy in megasmart cities. Literature [15] proposes a smart city information exchange blockchain network, which is helpful to establish sharing among several untrusted organizations. The proposed approach enables one organization to safely use data from another organization to participate in business operations without having to access the data.According to the research status proposed in this paper, there is no description of the differences in contracts in blockchain. However, there is no intelligent contract method for resource sharing mechanism. The intelligent contract method proposed in this paper can reduce the operating cost and improve the overall performance.


## 2. Brief Introduction of Blockchain Intelligent Contract

### 2.1. Brief Introduction of Blockchain Technology

#### 2.1.1. Blockchain Technology

Blockchain is a distributed ledger, which can provide verifiable evidence of transactions between sender and receiver. It has no central repository, and it is continuously maintained by many investors (possibly individuals or organizations).From the perspective of discipline boundary, the research topics of blockchain include mathematics, cryptography, data network, and many other directions. In practical application, blockchain plays its sharing function, which can be applied to the network architecture where multiple individuals interact, and has antitampering function. Blockchain can reduce the probability of omitting all transaction information in the network and complete the necessary repair and maintenance work at the necessary time. Blockchain is essentially a distributed database. Bitcoin, Ethereum, etc. use blockchain as the underlying technology and use the Hasi specification method to generate a series of data fields. These data blocks all have data messages that generate the next block, and they all contain a record of the complete error process, which is used to verify whether the information is valid and ensure its security.The three types of blockchain are private chain, alliance chain, and public chain. All data in the public chain is accessible to the public, including Bitcoin and Ethereum. However, alliance chain and private chain will have access restrictions in Table1.Table 1
Differences between block chains.
PropertyPrivate chainAlliance chainPublic chainParticipantMembers within the organizationAlliance memberAnyoneRead permissionRestrictedPublic or restrictedPublicConsensus mechanismsSolo and PBFSPBFS, Kafka, RaftPoW, PoS, and DpoSEfficiencyHighLowLowRepresentsMultichainHyperledger fabricBitcoin and EthereumThe relationship between blockchain and multiple data blocks can be understood as the relationship between record list and record chain. Blockchain network can be regarded as a decentralized account book of public network. The ledger is also publicly shared among users. Blockchain creates a constant database for transactions between individuals in the network. Each item stores data with a timestamp and is linked to the previous item, and each digital record or transaction can be reorganized into a block linked to a particular participant. At a certain level, these individual data blocks together constitute an information network that is difficult to modify and attack, and only when there is consensus among individuals can it be maintained and updated. Blockchain technology ensures the credibility of information in the matching system by this method. In short, you can think of blockchain as a record-based repository, which can replicate data on a large peer-to-peer computer network instead of a central server.Blockchain uses the Secure Hash Algorithm (SHA) or Hash Encryption Method. Hashing algorithms do not use secrets such as passwords or keys to provide security. A hashing algorithm can convert any part of information data such as numbers (such as text and pictures) into data fields having a prescribed length. The National Institute of Standards and Technology (NIST) has developed a hash specification, which is publicly available to government and private users.


#### 2.1.2. P2P Networks

P2P (peer-to-peer) network is a peer-to-peer network architecture. At present, the dominant network structure is client-server mode. In this network structure, there are two roles: client and server, and the server serves the client as a center. Through the P2P network, the traditional top-down structure is broken, but each node provides services to each other, and each node is both a client and a server. This decentralized approach allows permissions to be distributed over multiple network nodes instead of centralizing on a single central server.Because of the decentralized propagation of the P2P network, the blockchain technology can distribute data fields to each node through intelligent contracts to realize distributed accounting. In this manner, multiple copies of the data fields are provided and stored in each node where consensus is reached. When the ledger is threatened by tampering, attack, etc., only the data nodes stored on a single node are maliciously attacked, and the whole blockchain network will not be affected. Therefore, by increasing the geometric multiples of attack cost and difficulty, the blockchain network meets the requirements of tamper resistance and transaction security, and the blockchain network has the characteristics of decentralization and extensibility.Each node in a peer-to-peer network has two functions, one is to maintain its own data information, and the other is to verify and propagate the data information of other nodes. Blockchain spreads the transaction data to individuals in each regional network, and after being tested by preset judgment conditions, it continuously spreads effective information in the network. It is this mechanism that ensures the accuracy and effectiveness of data information stored in blockchain network. Individuals in the regional chain network are distinguished by their own accommodation limits and are divided into all nodes with all information data from the establishment of the whole network to the current time, and light nodes with relatively weak accommodation capacity, such as various hard disks, which can only retain some information associated with themselves. There is interactive function between full node and light node. The decision mechanism of each individual in the local area network is formulated by the asymmetric encryption algorithm, so as to judge the transaction data. During the transaction, the public key (used to validate the transaction data) is paired with the private key (used to encrypt the transaction data).The node uses the private key to sign the transaction information and then initiates the transaction. Once the transaction is accepted by the corresponding node, the initiator’s public key is used to verify the received transaction. In blockchain technology, two parties who do not know each other do not need to be certified by centralized certification bodies but only need to trust the algorithm-based trading rules to establish mutual trust and reach consensus.The emergence of the P2P technology provides an efficient and fast way for users to download network resources. Adding recommendation algorithm to the P2P sharing platform can enable users to capture the resources they are interested in in a small range, so as to effectively improve the utilization rate of resources and realize the rapid use and sharing of resources.


#### 2.1.3. Consensus Mechanism

The blockchain network has decentralized and scalable data storage mode, which requires high trust between nodes, which needs to be realized by different consensus methods. At present, common consensus methods mainly include proof of rights and interests, proof of workload, proof of entrusted rights and interests, and practical byzantine fault tolerance in Table2.Table 2
Common blockchain consensus mechanism.
Consensus methodProof of rights and interestsProof of workloadProof of entrusted rights and interestsPractical byzantine fault toleranceConsensus efficiencyGeneralLowHighHighThe trust environment usedUntrustedUntrustedUntrustedSemitrustedComputing power/resource consumptionGeneralHighLowLowThe ratio of fault-tolerant nodesAs the case may beLess than or equal to 25%As the case may beLess than or equal to 33.3%Security threatCandidate cheatingComputing power centralizationCandidate cheatingMaster node failureAmong the four common blockchain consensus mechanisms, this paper adopts the consensus mechanism of entrusted rights and interests proof. In cryptocurrency technology, the consensus algorithm of entrusted rights proof is used to ensure the security and reliability of the whole blockchain network.


### 2.2. Smart Contracts

Intelligent contract is the core of resource sharing system. The research on intelligent contract operation mechanism and Ethernet gas mechanism can provide reference for the selection of intelligent contract organization structure of smart city resource sharing system. Smart contract can help make decisions, provide verification and execution functions, store data and trade functions for the system, and realize the applications needed by a variety of resource sharing systems. Figure1 shows how smart contracts work. With the spread of transaction data, intelligent contracts are constantly taking effect at various nodes in the blockchain network. Smart contracts can be preinstalled with relevant condition settings and corresponding rules. When the conditions are met, corresponding operations can be performed when relevant functions are automatically triggered, thus realizing comprehensive management and control of physical and digital assets.Figure 1
Operation mechanism of smart contract.


### 2.3. Encryption Algorithm

Encryption can protect data from theft or tampering. This key can be used for user authentication. There are three general and widely used encryption schemes: symmetric encryption, asymmetric encryption, and hash function. This paper introduces the homomorphic encryption algorithm.Homomorphic encryption is regarded as a bright pearl in the field of cryptography, which is a method of processing data without accessing the data itself, that is, the result of processing ciphertext in encrypted state is the same as that of corresponding plaintext operation. Homomorphic encryption can realize ciphertext addition and multiplication at any time. In 2009, Pascal Paillier proposed a provable additive homomorphic secure encryption system. This scheme allows any computable function to operate the encrypted data, but it needs to be improved in practical application.Assuming thatM represents a set of plaintext and C represents a set of ciphertext, for a given key k satisfying formula (1), it is called homomorphic encryption scheme.
(1)∀m1,m2∈M,Em1⊙Mm2⟵Em1⊙CEm2.Among them, the symbol can be calculated directly in the setM and can be calculated directly in the set C, and neither calculation process needs any encryption and decryption.At present, the additive homomorphism schemes are mainly Paillier, the multiplicative homomorphism schemes are RSA and ElGamal, the hybrid encryption schemes are BGV, EHC, NEHE, etc. and are given, and the ciphertext of + can be calculated. The principle of the algorithm is as follows:Key generation section is as follows:Step 1.
p and q are two independent large prime numbers randomly selected, and gcdpq,p−1q−1=1, where gcd denotes finding the greatest common divisor.Step 2.
Calculate the parametern=pq, λ=lcmp−1q−1, where lcm is the least common multiple.Step 3.
Choose a random integeri, and i∈Zn2∗.Step 4.
Calculateμ=Liλmodn2−1modn, where Lu=u−1/n.Step 5.
The public key isn,i, and the private key is λ,μ.Data encryption process is as follows:Step 1.
ChooseP as plaintext, and 0≤p<n.Step 2.
Choose the random numberr, and 0<r<n,r∈Zn∗.Step 3.
Calculate the ciphertextC=ip∙rnmodn2.Homomorphic computation is as follows:Step 1.
Additive homomorphism of ciphertext:DEm1,r1·Em2,r2modn2=m1+m2modn.Step 2.
The ciphertext is multiplicative homomorphism with the constantk: DEm1,r1kmodn2=kmk1modn.Decryption process is as follows:Step 1.
The data ciphertext isC∈Zn2∗.Step 2.
The data plaintextP=LCλmodn2·μmodn is calculated.


## 2.1. Brief Introduction of Blockchain Technology

### 2.1.1. Blockchain Technology

Blockchain is a distributed ledger, which can provide verifiable evidence of transactions between sender and receiver. It has no central repository, and it is continuously maintained by many investors (possibly individuals or organizations).From the perspective of discipline boundary, the research topics of blockchain include mathematics, cryptography, data network, and many other directions. In practical application, blockchain plays its sharing function, which can be applied to the network architecture where multiple individuals interact, and has antitampering function. Blockchain can reduce the probability of omitting all transaction information in the network and complete the necessary repair and maintenance work at the necessary time. Blockchain is essentially a distributed database. Bitcoin, Ethereum, etc. use blockchain as the underlying technology and use the Hasi specification method to generate a series of data fields. These data blocks all have data messages that generate the next block, and they all contain a record of the complete error process, which is used to verify whether the information is valid and ensure its security.The three types of blockchain are private chain, alliance chain, and public chain. All data in the public chain is accessible to the public, including Bitcoin and Ethereum. However, alliance chain and private chain will have access restrictions in Table1.Table 1
Differences between block chains.
PropertyPrivate chainAlliance chainPublic chainParticipantMembers within the organizationAlliance memberAnyoneRead permissionRestrictedPublic or restrictedPublicConsensus mechanismsSolo and PBFSPBFS, Kafka, RaftPoW, PoS, and DpoSEfficiencyHighLowLowRepresentsMultichainHyperledger fabricBitcoin and EthereumThe relationship between blockchain and multiple data blocks can be understood as the relationship between record list and record chain. Blockchain network can be regarded as a decentralized account book of public network. The ledger is also publicly shared among users. Blockchain creates a constant database for transactions between individuals in the network. Each item stores data with a timestamp and is linked to the previous item, and each digital record or transaction can be reorganized into a block linked to a particular participant. At a certain level, these individual data blocks together constitute an information network that is difficult to modify and attack, and only when there is consensus among individuals can it be maintained and updated. Blockchain technology ensures the credibility of information in the matching system by this method. In short, you can think of blockchain as a record-based repository, which can replicate data on a large peer-to-peer computer network instead of a central server.Blockchain uses the Secure Hash Algorithm (SHA) or Hash Encryption Method. Hashing algorithms do not use secrets such as passwords or keys to provide security. A hashing algorithm can convert any part of information data such as numbers (such as text and pictures) into data fields having a prescribed length. The National Institute of Standards and Technology (NIST) has developed a hash specification, which is publicly available to government and private users.


### 2.1.2. P2P Networks

P2P (peer-to-peer) network is a peer-to-peer network architecture. At present, the dominant network structure is client-server mode. In this network structure, there are two roles: client and server, and the server serves the client as a center. Through the P2P network, the traditional top-down structure is broken, but each node provides services to each other, and each node is both a client and a server. This decentralized approach allows permissions to be distributed over multiple network nodes instead of centralizing on a single central server.Because of the decentralized propagation of the P2P network, the blockchain technology can distribute data fields to each node through intelligent contracts to realize distributed accounting. In this manner, multiple copies of the data fields are provided and stored in each node where consensus is reached. When the ledger is threatened by tampering, attack, etc., only the data nodes stored on a single node are maliciously attacked, and the whole blockchain network will not be affected. Therefore, by increasing the geometric multiples of attack cost and difficulty, the blockchain network meets the requirements of tamper resistance and transaction security, and the blockchain network has the characteristics of decentralization and extensibility.Each node in a peer-to-peer network has two functions, one is to maintain its own data information, and the other is to verify and propagate the data information of other nodes. Blockchain spreads the transaction data to individuals in each regional network, and after being tested by preset judgment conditions, it continuously spreads effective information in the network. It is this mechanism that ensures the accuracy and effectiveness of data information stored in blockchain network. Individuals in the regional chain network are distinguished by their own accommodation limits and are divided into all nodes with all information data from the establishment of the whole network to the current time, and light nodes with relatively weak accommodation capacity, such as various hard disks, which can only retain some information associated with themselves. There is interactive function between full node and light node. The decision mechanism of each individual in the local area network is formulated by the asymmetric encryption algorithm, so as to judge the transaction data. During the transaction, the public key (used to validate the transaction data) is paired with the private key (used to encrypt the transaction data).The node uses the private key to sign the transaction information and then initiates the transaction. Once the transaction is accepted by the corresponding node, the initiator’s public key is used to verify the received transaction. In blockchain technology, two parties who do not know each other do not need to be certified by centralized certification bodies but only need to trust the algorithm-based trading rules to establish mutual trust and reach consensus.The emergence of the P2P technology provides an efficient and fast way for users to download network resources. Adding recommendation algorithm to the P2P sharing platform can enable users to capture the resources they are interested in in a small range, so as to effectively improve the utilization rate of resources and realize the rapid use and sharing of resources.


### 2.1.3. Consensus Mechanism

The blockchain network has decentralized and scalable data storage mode, which requires high trust between nodes, which needs to be realized by different consensus methods. At present, common consensus methods mainly include proof of rights and interests, proof of workload, proof of entrusted rights and interests, and practical byzantine fault tolerance in Table2.Table 2
Common blockchain consensus mechanism.
Consensus methodProof of rights and interestsProof of workloadProof of entrusted rights and interestsPractical byzantine fault toleranceConsensus efficiencyGeneralLowHighHighThe trust environment usedUntrustedUntrustedUntrustedSemitrustedComputing power/resource consumptionGeneralHighLowLowThe ratio of fault-tolerant nodesAs the case may beLess than or equal to 25%As the case may beLess than or equal to 33.3%Security threatCandidate cheatingComputing power centralizationCandidate cheatingMaster node failureAmong the four common blockchain consensus mechanisms, this paper adopts the consensus mechanism of entrusted rights and interests proof. In cryptocurrency technology, the consensus algorithm of entrusted rights proof is used to ensure the security and reliability of the whole blockchain network.


## 2.1.1. Blockchain Technology

Blockchain is a distributed ledger, which can provide verifiable evidence of transactions between sender and receiver. It has no central repository, and it is continuously maintained by many investors (possibly individuals or organizations).From the perspective of discipline boundary, the research topics of blockchain include mathematics, cryptography, data network, and many other directions. In practical application, blockchain plays its sharing function, which can be applied to the network architecture where multiple individuals interact, and has antitampering function. Blockchain can reduce the probability of omitting all transaction information in the network and complete the necessary repair and maintenance work at the necessary time. Blockchain is essentially a distributed database. Bitcoin, Ethereum, etc. use blockchain as the underlying technology and use the Hasi specification method to generate a series of data fields. These data blocks all have data messages that generate the next block, and they all contain a record of the complete error process, which is used to verify whether the information is valid and ensure its security.The three types of blockchain are private chain, alliance chain, and public chain. All data in the public chain is accessible to the public, including Bitcoin and Ethereum. However, alliance chain and private chain will have access restrictions in Table1.Table 1
Differences between block chains.
PropertyPrivate chainAlliance chainPublic chainParticipantMembers within the organizationAlliance memberAnyoneRead permissionRestrictedPublic or restrictedPublicConsensus mechanismsSolo and PBFSPBFS, Kafka, RaftPoW, PoS, and DpoSEfficiencyHighLowLowRepresentsMultichainHyperledger fabricBitcoin and EthereumThe relationship between blockchain and multiple data blocks can be understood as the relationship between record list and record chain. Blockchain network can be regarded as a decentralized account book of public network. The ledger is also publicly shared among users. Blockchain creates a constant database for transactions between individuals in the network. Each item stores data with a timestamp and is linked to the previous item, and each digital record or transaction can be reorganized into a block linked to a particular participant. At a certain level, these individual data blocks together constitute an information network that is difficult to modify and attack, and only when there is consensus among individuals can it be maintained and updated. Blockchain technology ensures the credibility of information in the matching system by this method. In short, you can think of blockchain as a record-based repository, which can replicate data on a large peer-to-peer computer network instead of a central server.Blockchain uses the Secure Hash Algorithm (SHA) or Hash Encryption Method. Hashing algorithms do not use secrets such as passwords or keys to provide security. A hashing algorithm can convert any part of information data such as numbers (such as text and pictures) into data fields having a prescribed length. The National Institute of Standards and Technology (NIST) has developed a hash specification, which is publicly available to government and private users.


## 2.1.2. P2P Networks

P2P (peer-to-peer) network is a peer-to-peer network architecture. At present, the dominant network structure is client-server mode. In this network structure, there are two roles: client and server, and the server serves the client as a center. Through the P2P network, the traditional top-down structure is broken, but each node provides services to each other, and each node is both a client and a server. This decentralized approach allows permissions to be distributed over multiple network nodes instead of centralizing on a single central server.Because of the decentralized propagation of the P2P network, the blockchain technology can distribute data fields to each node through intelligent contracts to realize distributed accounting. In this manner, multiple copies of the data fields are provided and stored in each node where consensus is reached. When the ledger is threatened by tampering, attack, etc., only the data nodes stored on a single node are maliciously attacked, and the whole blockchain network will not be affected. Therefore, by increasing the geometric multiples of attack cost and difficulty, the blockchain network meets the requirements of tamper resistance and transaction security, and the blockchain network has the characteristics of decentralization and extensibility.Each node in a peer-to-peer network has two functions, one is to maintain its own data information, and the other is to verify and propagate the data information of other nodes. Blockchain spreads the transaction data to individuals in each regional network, and after being tested by preset judgment conditions, it continuously spreads effective information in the network. It is this mechanism that ensures the accuracy and effectiveness of data information stored in blockchain network. Individuals in the regional chain network are distinguished by their own accommodation limits and are divided into all nodes with all information data from the establishment of the whole network to the current time, and light nodes with relatively weak accommodation capacity, such as various hard disks, which can only retain some information associated with themselves. There is interactive function between full node and light node. The decision mechanism of each individual in the local area network is formulated by the asymmetric encryption algorithm, so as to judge the transaction data. During the transaction, the public key (used to validate the transaction data) is paired with the private key (used to encrypt the transaction data).The node uses the private key to sign the transaction information and then initiates the transaction. Once the transaction is accepted by the corresponding node, the initiator’s public key is used to verify the received transaction. In blockchain technology, two parties who do not know each other do not need to be certified by centralized certification bodies but only need to trust the algorithm-based trading rules to establish mutual trust and reach consensus.The emergence of the P2P technology provides an efficient and fast way for users to download network resources. Adding recommendation algorithm to the P2P sharing platform can enable users to capture the resources they are interested in in a small range, so as to effectively improve the utilization rate of resources and realize the rapid use and sharing of resources.


## 2.1.3. Consensus Mechanism

The blockchain network has decentralized and scalable data storage mode, which requires high trust between nodes, which needs to be realized by different consensus methods. At present, common consensus methods mainly include proof of rights and interests, proof of workload, proof of entrusted rights and interests, and practical byzantine fault tolerance in Table2.Table 2
Common blockchain consensus mechanism.
Consensus methodProof of rights and interestsProof of workloadProof of entrusted rights and interestsPractical byzantine fault toleranceConsensus efficiencyGeneralLowHighHighThe trust environment usedUntrustedUntrustedUntrustedSemitrustedComputing power/resource consumptionGeneralHighLowLowThe ratio of fault-tolerant nodesAs the case may beLess than or equal to 25%As the case may beLess than or equal to 33.3%Security threatCandidate cheatingComputing power centralizationCandidate cheatingMaster node failureAmong the four common blockchain consensus mechanisms, this paper adopts the consensus mechanism of entrusted rights and interests proof. In cryptocurrency technology, the consensus algorithm of entrusted rights proof is used to ensure the security and reliability of the whole blockchain network.


## 2.2. Smart Contracts

Intelligent contract is the core of resource sharing system. The research on intelligent contract operation mechanism and Ethernet gas mechanism can provide reference for the selection of intelligent contract organization structure of smart city resource sharing system. Smart contract can help make decisions, provide verification and execution functions, store data and trade functions for the system, and realize the applications needed by a variety of resource sharing systems. Figure1 shows how smart contracts work. With the spread of transaction data, intelligent contracts are constantly taking effect at various nodes in the blockchain network. Smart contracts can be preinstalled with relevant condition settings and corresponding rules. When the conditions are met, corresponding operations can be performed when relevant functions are automatically triggered, thus realizing comprehensive management and control of physical and digital assets.Figure 1
Operation mechanism of smart contract.


## 2.3. Encryption Algorithm

Encryption can protect data from theft or tampering. This key can be used for user authentication. There are three general and widely used encryption schemes: symmetric encryption, asymmetric encryption, and hash function. This paper introduces the homomorphic encryption algorithm.Homomorphic encryption is regarded as a bright pearl in the field of cryptography, which is a method of processing data without accessing the data itself, that is, the result of processing ciphertext in encrypted state is the same as that of corresponding plaintext operation. Homomorphic encryption can realize ciphertext addition and multiplication at any time. In 2009, Pascal Paillier proposed a provable additive homomorphic secure encryption system. This scheme allows any computable function to operate the encrypted data, but it needs to be improved in practical application.Assuming thatM represents a set of plaintext and C represents a set of ciphertext, for a given key k satisfying formula (1), it is called homomorphic encryption scheme.
(1)∀m1,m2∈M,Em1⊙Mm2⟵Em1⊙CEm2.Among them, the symbol can be calculated directly in the setM and can be calculated directly in the set C, and neither calculation process needs any encryption and decryption.At present, the additive homomorphism schemes are mainly Paillier, the multiplicative homomorphism schemes are RSA and ElGamal, the hybrid encryption schemes are BGV, EHC, NEHE, etc. and are given, and the ciphertext of + can be calculated. The principle of the algorithm is as follows:Key generation section is as follows:Step 1.
p and q are two independent large prime numbers randomly selected, and gcdpq,p−1q−1=1, where gcd denotes finding the greatest common divisor.Step 2.
Calculate the parametern=pq, λ=lcmp−1q−1, where lcm is the least common multiple.Step 3.
Choose a random integeri, and i∈Zn2∗.Step 4.
Calculateμ=Liλmodn2−1modn, where Lu=u−1/n.Step 5.
The public key isn,i, and the private key is λ,μ.Data encryption process is as follows:Step 1.
ChooseP as plaintext, and 0≤p<n.Step 2.
Choose the random numberr, and 0<r<n,r∈Zn∗.Step 3.
Calculate the ciphertextC=ip∙rnmodn2.Homomorphic computation is as follows:Step 1.
Additive homomorphism of ciphertext:DEm1,r1·Em2,r2modn2=m1+m2modn.Step 2.
The ciphertext is multiplicative homomorphism with the constantk: DEm1,r1kmodn2=kmk1modn.Decryption process is as follows:Step 1.
The data ciphertext isC∈Zn2∗.Step 2.
The data plaintextP=LCλmodn2·μmodn is calculated.


## 3. Research on the Factor Model of Structural Optimization of Smart Contract

### 3.1. Research on Gas Optimization Theory

The execution of each transaction in Ethereum has the attribute of transaction cost, that is, the gas consumed by transaction execution. When a transaction contains data fields, transaction costs consist of execution costs and additional costs per byte in the data fields. If the transaction cost isGl, the execution cost is Ge, and the data cost is Gd, there are
(2)Gl=Ge+Gd.Ethereum foundation predefines the consensus rule of gas benchmark measurement according to opcodes, so the gas consumed by each EVM opcode is fixed. The execution cost is available in the transaction log and can be debugged in a debug manner, such as in the online compilation environment Remix, to obtain all the opcodes during the execution of the transaction in sequence. Let each opcode costGas be G, and there are
(3)Ge=∑Go.In the data cost, except that each transaction has a fixed valueGas cost, the Gas cost is different according to the byte type of the data field. The fixed cost per transaction is 21,000 Gas, 68 Gas is required for each nonzero byte of data or code in the transaction, and 4 Gas is required for each zero byte of data or code. Then, let the number of nonzero bytes and zero bytes of the additional data field of the transaction be Nx and Ny; then there are
(4)Gd=21000+68Nx+4Ny.According to formula (1), the transaction cost of each transaction in Ethereum is positively correlated with the data cost and execution cost. From formula (2) and formula (3), we know the formation mode of data consumption and execution consumption in Ethernet Square and put forward the optimization methods from these two aspects to reduce gas consumption.According to the above theory, the smart contract code is optimized by reducing gas cost from three aspects: changing the order of variables, reducing the use of expensive EVM opcodes, and reducing redundancy and unreasonable design of smart contract codes.


#### 3.1.1. Change the Order of the Quantities

The EVM virtual machine executes in a 32-byte group each time, so the compiler will try to merge variables into 32 bytes for execution. However, the compiler cannot automatically optimize variable grouping, and it divides 32 bytes into groups according to variables of static size. According to the different byte types of different variables, the access order can be adjusted to optimize.


#### 3.1.2. Reduce the Use of Expensive EVM Opcodes

Gas of EVM opcode has been defined in advance. For example, adding ADD opcode consumes 3 Gas, dividing DIV opcode consumes 5 Gas, while SSTORE opcode means writing data, which requires 20000 Gas for the first writing and 5000 Gas for remodification. Therefore, taking SSTORE opcode as an example, it is expensive to modify it again, and the optimization direction needs to avoid repeated writing, that is, it can write as much data as possible at one time.


#### 3.1.3. Optimize Smart Contract Code to Reduce Redundancy and Unreasonable Design Code

Reducing redundant and unreasonable code design can reduce the gas cost caused by code transmission and also reduce the use of EVM opcodes, thus reducing the gas cost more effectively. Therefore, it is necessary to try our best to remove redundant and unreasonable codes in the system with intelligent contract as the core.


### 3.2. Algorithm Establishment

Different from Bitcoin, the Ethernet platform uses Merkle Patricia tree instead of Merkle tree. By modifying the block structure, it avoids the fact that the original node can only obtain the global state of the system through the processed transactions, so that each region can clearly give the global state of the system. The structure of the MPT tree (that is, the Merkle Patricia tree) is the organizational structure of the Patricia tree. Ethernet uses the MPT tree to store the account Trie for special processing of key values and uses a special hexadecimal prefix (HP) encoding for key values, which corresponds to 16 characters in the alphabet. And before the node is inserted into the MPT tree, the key value is hashed once again bysha3, so that the key value is random, so the MPT tree used in the global state of Ethernet can be regarded as a random 16-fork Patricia tree. According to the relationship between tree height expectation and node size of randomly asymptotic Patricia tree, the relationship between tree height expectation and node number of binary Patricia tree is as follows:
(5)EHn~clogn,wherec=2log21/∑jPj2.Since the MPT tree in the global state can be regarded as a random Patricia tree with 16 forks (Pj=1/16, 1≤j≤16), according to formula (4), we can deduce the following:
(6)EHn~logn/2.When an intelligent contract executes a new transaction, i.e., inserting or modifying leaf nodes in an MPT tree, all hash values on the path will be updated because of the characteristics of the Merkle tree, that is, all nonleaf node values of tree height will be updated. And because the MPT node is stored in LevelDB, the database needs to be read and updated. Assuming that the average time of each node in MPT ist (including the time of calculating Hash and accessing database), then when the transaction scale reaches r and then executes another transaction, it can be concluded that the average time required to modify MPT tree is
(7)Tmptn=tlogn/2.Set the deployment intelligent contract consumption gas toGdeploy and the one-time transaction consumption gas to Gtran; then the total consumption gas when the transaction amount is n:
(8)GN=Gdeploy+∑Gtran.By analyzing the MPT tree of the underlying structure of Ethernet Square as a 16-fork Patricia tree, the relationship between transaction volume and tree height is determined. Since updating the transaction node will result in updating thelogn node, the relationship between transaction volume and time is derived. Gas cost, additional data size, and EVM opcode have definite calculation formulas, so gas cost can also be derived from transaction volume.When the data is dispersed into the newly created smart contract, the read time is positively correlated with the height of the global state tree. But with it, there is a lot of gas expenditure, which is used to create new smart contracts. Therefore, according to the actual system, the transaction execution time and gas consumption can be predicted from the transaction scale, and these two factors can be considered to choose different intelligent contract organization structures for the system.


### 3.3. Algorithm Verification

Any one of the three organizational architectures of intelligent contract is based on MPT tree, so it can be used for algorithm verification. This verification chooses a single intelligent contract. Considering the execution time and execution cost, the smart contract with code simplification is adopted, as shown in Code1; this code uses the structure Dealing, links the structure with a mapping index, and then executes build Dealing, saving the Dealing information in the Single Contract Model’s storage space, and the newly added Dealing storage will enter the Single Contract Model’s storage Trie.Code 1: Simplified code for a single smart contract.
contract SingleContractModel{uint cnt;struct Dealing{uint dealingValue; }mapping(uint => Dealing) private Dealings;function buildDealing(uint _dealing Value){cnt += 1;var newDealing = Dealing({dealingValue:_dealingValue });Dealings[ent] = newDealing;}}If the transaction volume isn, the successful execution time of the transaction is t (including calculating the sha30 hash function and the time of database access), and a data structure is changed in one transaction; the average time of the next transaction after n transactions that have been executed is
(9)Tn=tlogan/2a>0.Each transaction changes the data structurea=1, and the average time to access the database t=0.12ms (since LevelDB random access dramatically degrades performance with the increase of data volume, t will continue to increase, which is only an average in the simple use test here). When Gdeploy=119799 and the control input data is always 1, then Gtran1=62319 and Gtran=47319 are measured. The next transaction after n transactions are executed:
(10)Tpredictn=0.06logn.After the transaction volume isn, the consumption gas is
(11)Gpredictn=47319n+87480.In this experiment, a dedicated Ethernet chain is built on the server, and 10 Ethernet nodes are deployed. Deploy the above simplified contract, which generates transaction structure data every time it is called. Execute transactions randomly in the system. The Ethernet node prints logs internally and records the consumption of transaction time, gas consumed by transactions, and transaction volume in the global intelligent contract account. When the transaction volume reaches millions, stop the above experiment, write data analysis scripts, and extract data such as processing log time. Under different transaction volumes, the offset value between the forecast time and the test transaction execution time is shown in Table3.Table 3
Offsets between predicted events and test time.
Trading volume2000004000006000008000001000000Test time (s)0.2890.2650.2140.3360.346Forecast events (s)0.3180.3360.3460.3540.360Offset value (s)0.0290.0710.1320.0180.014By comparing the error between the predicted value and the test time, the blockchain method in this paper can have little correlation with the actual business occurrence time. It shows that the test time is safe and reasonable, which can represent the good performance of the system.Because the prediction curve in this paper is calculated with a fixedt value, the t value in the real environment is from small to large, which is mainly determined by the reading performance of LevelDB. Within 200000 data, the predicted value is significantly larger than the experimental data, because the actual time is smaller than the fixed value used in calculation. With the increase of trading volume, the distribution of experimental data on both sides of the curve is more obvious, and the prediction is effective. The overall offset value is less than 0.1 s, which is acceptable and proves the effectiveness of the algorithm. Once the smart contract structure is fixed and the input data is fixed, it can be seen from the above that the consumption of gas is fixed and can be completely calculated, so the algorithm is correct.After the above verification, it can be seen that the prediction algorithm is effective. Then, according to the system transaction volume and the implementation of the specific system intelligent contract code, we can choose the time and gas cost and then choose different intelligent contract organization modes.


## 3.1. Research on Gas Optimization Theory

The execution of each transaction in Ethereum has the attribute of transaction cost, that is, the gas consumed by transaction execution. When a transaction contains data fields, transaction costs consist of execution costs and additional costs per byte in the data fields. If the transaction cost isGl, the execution cost is Ge, and the data cost is Gd, there are
(2)Gl=Ge+Gd.Ethereum foundation predefines the consensus rule of gas benchmark measurement according to opcodes, so the gas consumed by each EVM opcode is fixed. The execution cost is available in the transaction log and can be debugged in a debug manner, such as in the online compilation environment Remix, to obtain all the opcodes during the execution of the transaction in sequence. Let each opcode costGas be G, and there are
(3)Ge=∑Go.In the data cost, except that each transaction has a fixed valueGas cost, the Gas cost is different according to the byte type of the data field. The fixed cost per transaction is 21,000 Gas, 68 Gas is required for each nonzero byte of data or code in the transaction, and 4 Gas is required for each zero byte of data or code. Then, let the number of nonzero bytes and zero bytes of the additional data field of the transaction be Nx and Ny; then there are
(4)Gd=21000+68Nx+4Ny.According to formula (1), the transaction cost of each transaction in Ethereum is positively correlated with the data cost and execution cost. From formula (2) and formula (3), we know the formation mode of data consumption and execution consumption in Ethernet Square and put forward the optimization methods from these two aspects to reduce gas consumption.According to the above theory, the smart contract code is optimized by reducing gas cost from three aspects: changing the order of variables, reducing the use of expensive EVM opcodes, and reducing redundancy and unreasonable design of smart contract codes.


### 3.1.1. Change the Order of the Quantities

The EVM virtual machine executes in a 32-byte group each time, so the compiler will try to merge variables into 32 bytes for execution. However, the compiler cannot automatically optimize variable grouping, and it divides 32 bytes into groups according to variables of static size. According to the different byte types of different variables, the access order can be adjusted to optimize.


### 3.1.2. Reduce the Use of Expensive EVM Opcodes

Gas of EVM opcode has been defined in advance. For example, adding ADD opcode consumes 3 Gas, dividing DIV opcode consumes 5 Gas, while SSTORE opcode means writing data, which requires 20000 Gas for the first writing and 5000 Gas for remodification. Therefore, taking SSTORE opcode as an example, it is expensive to modify it again, and the optimization direction needs to avoid repeated writing, that is, it can write as much data as possible at one time.


### 3.1.3. Optimize Smart Contract Code to Reduce Redundancy and Unreasonable Design Code

Reducing redundant and unreasonable code design can reduce the gas cost caused by code transmission and also reduce the use of EVM opcodes, thus reducing the gas cost more effectively. Therefore, it is necessary to try our best to remove redundant and unreasonable codes in the system with intelligent contract as the core.


## 3.1.1. Change the Order of the Quantities

The EVM virtual machine executes in a 32-byte group each time, so the compiler will try to merge variables into 32 bytes for execution. However, the compiler cannot automatically optimize variable grouping, and it divides 32 bytes into groups according to variables of static size. According to the different byte types of different variables, the access order can be adjusted to optimize.


## 3.1.2. Reduce the Use of Expensive EVM Opcodes

Gas of EVM opcode has been defined in advance. For example, adding ADD opcode consumes 3 Gas, dividing DIV opcode consumes 5 Gas, while SSTORE opcode means writing data, which requires 20000 Gas for the first writing and 5000 Gas for remodification. Therefore, taking SSTORE opcode as an example, it is expensive to modify it again, and the optimization direction needs to avoid repeated writing, that is, it can write as much data as possible at one time.


## 3.1.3. Optimize Smart Contract Code to Reduce Redundancy and Unreasonable Design Code

Reducing redundant and unreasonable code design can reduce the gas cost caused by code transmission and also reduce the use of EVM opcodes, thus reducing the gas cost more effectively. Therefore, it is necessary to try our best to remove redundant and unreasonable codes in the system with intelligent contract as the core.


## 3.2. Algorithm Establishment

Different from Bitcoin, the Ethernet platform uses Merkle Patricia tree instead of Merkle tree. By modifying the block structure, it avoids the fact that the original node can only obtain the global state of the system through the processed transactions, so that each region can clearly give the global state of the system. The structure of the MPT tree (that is, the Merkle Patricia tree) is the organizational structure of the Patricia tree. Ethernet uses the MPT tree to store the account Trie for special processing of key values and uses a special hexadecimal prefix (HP) encoding for key values, which corresponds to 16 characters in the alphabet. And before the node is inserted into the MPT tree, the key value is hashed once again bysha3, so that the key value is random, so the MPT tree used in the global state of Ethernet can be regarded as a random 16-fork Patricia tree. According to the relationship between tree height expectation and node size of randomly asymptotic Patricia tree, the relationship between tree height expectation and node number of binary Patricia tree is as follows:
(5)EHn~clogn,wherec=2log21/∑jPj2.Since the MPT tree in the global state can be regarded as a random Patricia tree with 16 forks (Pj=1/16, 1≤j≤16), according to formula (4), we can deduce the following:
(6)EHn~logn/2.When an intelligent contract executes a new transaction, i.e., inserting or modifying leaf nodes in an MPT tree, all hash values on the path will be updated because of the characteristics of the Merkle tree, that is, all nonleaf node values of tree height will be updated. And because the MPT node is stored in LevelDB, the database needs to be read and updated. Assuming that the average time of each node in MPT ist (including the time of calculating Hash and accessing database), then when the transaction scale reaches r and then executes another transaction, it can be concluded that the average time required to modify MPT tree is
(7)Tmptn=tlogn/2.Set the deployment intelligent contract consumption gas toGdeploy and the one-time transaction consumption gas to Gtran; then the total consumption gas when the transaction amount is n:
(8)GN=Gdeploy+∑Gtran.By analyzing the MPT tree of the underlying structure of Ethernet Square as a 16-fork Patricia tree, the relationship between transaction volume and tree height is determined. Since updating the transaction node will result in updating thelogn node, the relationship between transaction volume and time is derived. Gas cost, additional data size, and EVM opcode have definite calculation formulas, so gas cost can also be derived from transaction volume.When the data is dispersed into the newly created smart contract, the read time is positively correlated with the height of the global state tree. But with it, there is a lot of gas expenditure, which is used to create new smart contracts. Therefore, according to the actual system, the transaction execution time and gas consumption can be predicted from the transaction scale, and these two factors can be considered to choose different intelligent contract organization structures for the system.


## 3.3. Algorithm Verification

Any one of the three organizational architectures of intelligent contract is based on MPT tree, so it can be used for algorithm verification. This verification chooses a single intelligent contract. Considering the execution time and execution cost, the smart contract with code simplification is adopted, as shown in Code1; this code uses the structure Dealing, links the structure with a mapping index, and then executes build Dealing, saving the Dealing information in the Single Contract Model’s storage space, and the newly added Dealing storage will enter the Single Contract Model’s storage Trie.Code 1: Simplified code for a single smart contract.
contract SingleContractModel{uint cnt;struct Dealing{uint dealingValue; }mapping(uint => Dealing) private Dealings;function buildDealing(uint _dealing Value){cnt += 1;var newDealing = Dealing({dealingValue:_dealingValue });Dealings[ent] = newDealing;}}If the transaction volume isn, the successful execution time of the transaction is t (including calculating the sha30 hash function and the time of database access), and a data structure is changed in one transaction; the average time of the next transaction after n transactions that have been executed is
(9)Tn=tlogan/2a>0.Each transaction changes the data structurea=1, and the average time to access the database t=0.12ms (since LevelDB random access dramatically degrades performance with the increase of data volume, t will continue to increase, which is only an average in the simple use test here). When Gdeploy=119799 and the control input data is always 1, then Gtran1=62319 and Gtran=47319 are measured. The next transaction after n transactions are executed:
(10)Tpredictn=0.06logn.After the transaction volume isn, the consumption gas is
(11)Gpredictn=47319n+87480.In this experiment, a dedicated Ethernet chain is built on the server, and 10 Ethernet nodes are deployed. Deploy the above simplified contract, which generates transaction structure data every time it is called. Execute transactions randomly in the system. The Ethernet node prints logs internally and records the consumption of transaction time, gas consumed by transactions, and transaction volume in the global intelligent contract account. When the transaction volume reaches millions, stop the above experiment, write data analysis scripts, and extract data such as processing log time. Under different transaction volumes, the offset value between the forecast time and the test transaction execution time is shown in Table3.Table 3
Offsets between predicted events and test time.
Trading volume2000004000006000008000001000000Test time (s)0.2890.2650.2140.3360.346Forecast events (s)0.3180.3360.3460.3540.360Offset value (s)0.0290.0710.1320.0180.014By comparing the error between the predicted value and the test time, the blockchain method in this paper can have little correlation with the actual business occurrence time. It shows that the test time is safe and reasonable, which can represent the good performance of the system.Because the prediction curve in this paper is calculated with a fixedt value, the t value in the real environment is from small to large, which is mainly determined by the reading performance of LevelDB. Within 200000 data, the predicted value is significantly larger than the experimental data, because the actual time is smaller than the fixed value used in calculation. With the increase of trading volume, the distribution of experimental data on both sides of the curve is more obvious, and the prediction is effective. The overall offset value is less than 0.1 s, which is acceptable and proves the effectiveness of the algorithm. Once the smart contract structure is fixed and the input data is fixed, it can be seen from the above that the consumption of gas is fixed and can be completely calculated, so the algorithm is correct.After the above verification, it can be seen that the prediction algorithm is effective. Then, according to the system transaction volume and the implementation of the specific system intelligent contract code, we can choose the time and gas cost and then choose different intelligent contract organization modes.


## 4. Performance Test

Gas is the consumption unit for deploying and executing smart contracts in Ethereum, which represents the amount of computation required to execute transaction operations. Therefore, the constraint of gas factor must be considered when designing related business process contracts. Gas mechanism can encourage computing nodes to participate in negotiation mechanism to create transactions, thus ensuring that Ethernet can continue to be decentralized without trust under increasingly complex intelligent contracts in Figure2.Figure 2
Ethernet MPT tree in gas theory.Gas is an important performance index in Ethernet Square system. Therefore, the next step will be to analyze and test from the perspective of gas consumption. First, the function code was specified for the gas optimization analysis, the detailed optimization method was elaborated, and then for the function for the Gas test, and the Gas trend graph and optimization percentage were drawn to verify whether the gas optimization method is effective. Finally, according to the optimization theory, the code of the whole intelligent contract is processed by these three methods in turn, and the optimization results are checked by comparing the gas test values before and after optimization in Figure3.Figure 3
Transition of global state Trie of Ethereum.


### 4.1. Gas Optimization Analysis

According to the gas optimization theory proposed in section3, the intelligent contract code is optimized by reducing gas cost from three aspects: changing the order of variables, reducing the use of expensive EVM opcodes, and reducing redundancy and unreasonable design of intelligent contract codes. The following is a detailed explanation and example of manual optimization for specific functions.


#### 4.1.1. Change the Order of the Quantities

The EVM virtual machine can only read sequentially and process variables in a group of 32 bytes. The declared variable type unit64 occupies 64 bits, that is, 8 bytes, unit256 occupies 256 bits, that is, 32 bytes, the variable type address occupies 160 bits, that is, 20 bytes, string is a variable length variable, that occupies different bytes according to the stored variable length, and state occupies 8 bits, that is, 1 byte according to the defined type of enumeration. Then, considering the unreasonable order of variables, try to sort them in a group of 32 bytes, and put the variables updated at the same time together to effectively reduce gas consumption. The manually optimized code is shown in Codes2 and 3.Code 2: before manual optimization of specified structure.
Struct Dealing {adress userAddress;Uint256 date;Uint64 dealingNo;Uint64 publishingNo;Address publisherAddress;Uint64 price;State state;String newTime;}Enum State {Created, Pending, Completed, Stopped}Code 3: Code after manual optimization of specified structure.
‘Struct Dealing {Uint64 dealingNo;Uint64 publishingNo;Uint64 price;Address publisherAddress;adress userAddress;State state;String newTime;Uint256 date;}Enum State {Created, Pending, Completed, Stopped}


#### 4.1.2. Reduce the Use of Expensive EVM Opcodes

Call the function personAllDealing(), tempNo as a temporary variable, get the total number of orders for the user, and write that number to the return value result. The global variables cntDealing and tempNo are counted in a self-growing way and are used in their functions. However, cntDealing has a better way, that is, after tempNo++ gets the final result, it directly assigns a value to cntDealing once. That is, cntDealing = tempNo is used instead of cntDealing for optimization purposes in Figures4 and 5.Figure 4
Organizational architecture of smart contract.Figure 5
Account Trie and storage Trie.


#### 4.1.3. Optimize Smart Contract Code to Reduce Redundancy and Unreasonable Design Code

The function of tempNo is to obtain all the orders of the user. This operation can be calculated after the client obtains all the order information. There is no need to consume gas calculation in the intelligent contract, so this part of unreasonable design code is removed to reduce gas consumption.As shown in Table4 and Figure 6, it is the change trend of consuming gas by manually optimizing the specified function personAllDealingO in three ways in turn and initiating the same order data information query. It can be seen from the chart that the consumption of gas has dropped significantly. After three optimizations, the transaction cost of gas has dropped by 12.9%, so it can be proved that it is effective to optimize smart contracts from three aspects: changing sequence variables, reducing expensive gas instructions, and reducing unreasonable codes.Table 4
Formulating function gas consumption.
Gas consumptionTransaction costExecution costDate costOriginal distribution841776290521272Change sequence variable835766134721274Reducing high energy consumption directive768625672721272Redundant code cut720225175020270Figure 6
Line chart of gas consumption of function.


### 4.2. Gas Optimization Test

Functions in blockchain intelligent contract architecture consume gas with the selection of associated bytes or the distributed output of contracts. Therefore, by integrating the information contained in contracts into EVM function codes, the gas consumption of contract-related function codes is tested and improved.Table5 and Figure 7 show the trend chart of gas cost for deploying smart contracts. It can be seen that the consumption of gas in millions has decreased. Because the smart contract has been written as concise and reasonable as possible, the cost of gas transaction has decreased by 8.22% after the final three methods, thus completing the gas optimization and testing of smart contract.Table 5
Gas expenditure for smart contract deployment.
Gas consumptionTransaction costExecution costDate costOriginal distribution487380236701881203614Variable sequence486359236625821201010Control modify variable operation486041536620631198352Reduce useless code447317433570741116100Figure 7
Gas consumption trend chart of smart contract deployment.As can be seen in Figure7, the execution cost can be reduced a lot through blockchain. Among all indicators, the execution cost of blockchain is lower than the conversion cost. The greater the change, the better the performance, and the lower the cost of the proposed method.


## 4.1. Gas Optimization Analysis

According to the gas optimization theory proposed in section3, the intelligent contract code is optimized by reducing gas cost from three aspects: changing the order of variables, reducing the use of expensive EVM opcodes, and reducing redundancy and unreasonable design of intelligent contract codes. The following is a detailed explanation and example of manual optimization for specific functions.


### 4.1.1. Change the Order of the Quantities

The EVM virtual machine can only read sequentially and process variables in a group of 32 bytes. The declared variable type unit64 occupies 64 bits, that is, 8 bytes, unit256 occupies 256 bits, that is, 32 bytes, the variable type address occupies 160 bits, that is, 20 bytes, string is a variable length variable, that occupies different bytes according to the stored variable length, and state occupies 8 bits, that is, 1 byte according to the defined type of enumeration. Then, considering the unreasonable order of variables, try to sort them in a group of 32 bytes, and put the variables updated at the same time together to effectively reduce gas consumption. The manually optimized code is shown in Codes2 and 3.Code 2: before manual optimization of specified structure.
Struct Dealing {adress userAddress;Uint256 date;Uint64 dealingNo;Uint64 publishingNo;Address publisherAddress;Uint64 price;State state;String newTime;}Enum State {Created, Pending, Completed, Stopped}Code 3: Code after manual optimization of specified structure.
‘Struct Dealing {Uint64 dealingNo;Uint64 publishingNo;Uint64 price;Address publisherAddress;adress userAddress;State state;String newTime;Uint256 date;}Enum State {Created, Pending, Completed, Stopped}


### 4.1.2. Reduce the Use of Expensive EVM Opcodes

Call the function personAllDealing(), tempNo as a temporary variable, get the total number of orders for the user, and write that number to the return value result. The global variables cntDealing and tempNo are counted in a self-growing way and are used in their functions. However, cntDealing has a better way, that is, after tempNo++ gets the final result, it directly assigns a value to cntDealing once. That is, cntDealing = tempNo is used instead of cntDealing for optimization purposes in Figures4 and 5.Figure 4
Organizational architecture of smart contract.Figure 5
Account Trie and storage Trie.


### 4.1.3. Optimize Smart Contract Code to Reduce Redundancy and Unreasonable Design Code

The function of tempNo is to obtain all the orders of the user. This operation can be calculated after the client obtains all the order information. There is no need to consume gas calculation in the intelligent contract, so this part of unreasonable design code is removed to reduce gas consumption.As shown in Table4 and Figure 6, it is the change trend of consuming gas by manually optimizing the specified function personAllDealingO in three ways in turn and initiating the same order data information query. It can be seen from the chart that the consumption of gas has dropped significantly. After three optimizations, the transaction cost of gas has dropped by 12.9%, so it can be proved that it is effective to optimize smart contracts from three aspects: changing sequence variables, reducing expensive gas instructions, and reducing unreasonable codes.Table 4
Formulating function gas consumption.
Gas consumptionTransaction costExecution costDate costOriginal distribution841776290521272Change sequence variable835766134721274Reducing high energy consumption directive768625672721272Redundant code cut720225175020270Figure 6
Line chart of gas consumption of function.


## 4.1.1. Change the Order of the Quantities

The EVM virtual machine can only read sequentially and process variables in a group of 32 bytes. The declared variable type unit64 occupies 64 bits, that is, 8 bytes, unit256 occupies 256 bits, that is, 32 bytes, the variable type address occupies 160 bits, that is, 20 bytes, string is a variable length variable, that occupies different bytes according to the stored variable length, and state occupies 8 bits, that is, 1 byte according to the defined type of enumeration. Then, considering the unreasonable order of variables, try to sort them in a group of 32 bytes, and put the variables updated at the same time together to effectively reduce gas consumption. The manually optimized code is shown in Codes2 and 3.Code 2: before manual optimization of specified structure.
Struct Dealing {adress userAddress;Uint256 date;Uint64 dealingNo;Uint64 publishingNo;Address publisherAddress;Uint64 price;State state;String newTime;}Enum State {Created, Pending, Completed, Stopped}Code 3: Code after manual optimization of specified structure.
‘Struct Dealing {Uint64 dealingNo;Uint64 publishingNo;Uint64 price;Address publisherAddress;adress userAddress;State state;String newTime;Uint256 date;}Enum State {Created, Pending, Completed, Stopped}


## 4.1.2. Reduce the Use of Expensive EVM Opcodes

Call the function personAllDealing(), tempNo as a temporary variable, get the total number of orders for the user, and write that number to the return value result. The global variables cntDealing and tempNo are counted in a self-growing way and are used in their functions. However, cntDealing has a better way, that is, after tempNo++ gets the final result, it directly assigns a value to cntDealing once. That is, cntDealing = tempNo is used instead of cntDealing for optimization purposes in Figures4 and 5.Figure 4
Organizational architecture of smart contract.Figure 5
Account Trie and storage Trie.


## 4.1.3. Optimize Smart Contract Code to Reduce Redundancy and Unreasonable Design Code

The function of tempNo is to obtain all the orders of the user. This operation can be calculated after the client obtains all the order information. There is no need to consume gas calculation in the intelligent contract, so this part of unreasonable design code is removed to reduce gas consumption.As shown in Table4 and Figure 6, it is the change trend of consuming gas by manually optimizing the specified function personAllDealingO in three ways in turn and initiating the same order data information query. It can be seen from the chart that the consumption of gas has dropped significantly. After three optimizations, the transaction cost of gas has dropped by 12.9%, so it can be proved that it is effective to optimize smart contracts from three aspects: changing sequence variables, reducing expensive gas instructions, and reducing unreasonable codes.Table 4
Formulating function gas consumption.
Gas consumptionTransaction costExecution costDate costOriginal distribution841776290521272Change sequence variable835766134721274Reducing high energy consumption directive768625672721272Redundant code cut720225175020270Figure 6
Line chart of gas consumption of function.


## 4.2. Gas Optimization Test

Functions in blockchain intelligent contract architecture consume gas with the selection of associated bytes or the distributed output of contracts. Therefore, by integrating the information contained in contracts into EVM function codes, the gas consumption of contract-related function codes is tested and improved.Table5 and Figure 7 show the trend chart of gas cost for deploying smart contracts. It can be seen that the consumption of gas in millions has decreased. Because the smart contract has been written as concise and reasonable as possible, the cost of gas transaction has decreased by 8.22% after the final three methods, thus completing the gas optimization and testing of smart contract.Table 5
Gas expenditure for smart contract deployment.
Gas consumptionTransaction costExecution costDate costOriginal distribution487380236701881203614Variable sequence486359236625821201010Control modify variable operation486041536620631198352Reduce useless code447317433570741116100Figure 7
Gas consumption trend chart of smart contract deployment.As can be seen in Figure7, the execution cost can be reduced a lot through blockchain. Among all indicators, the execution cost of blockchain is lower than the conversion cost. The greater the change, the better the performance, and the lower the cost of the proposed method.


## 5. Conclusion

In this paper, the optimization factors of intelligent contract structure of smart city sharing system are studied. The structure of intelligent contract can be divided into two situations: the code structure of intelligent contract and the organizational structure of intelligent contract. The key factor affecting the performance of intelligent contract includes gas cost. Firstly, based on the composition of gas cost of transaction, the gas optimization theory is put forward, and the way to optimize intelligent contract code by changing the order of variables, reducing the use of expensive EVM opcodes, and reducing redundant codes is put forward, which provides a basis for the optimization of intelligent contract code in the final system. In addition, an algorithm for predicting transaction execution time and gas execution cost is proposed. According to the different transaction volume of specific systems and the implementation mode of intelligent contracts, the reference of intelligent contract organization structure is given, and the effectiveness of the algorithm is verified by experiments, which provides the implementation basis for intelligent contract organization structure and the basis for the implementation of smart city sharing system.



---

*Source: 5886024-2021-10-20.xml*