Energy 199 (2020) 117417 Contents lists available at ScienceDirect Energy journal homepage: www.elsevier.com/locate/energy Smart contract architecture for decentralized energy trading and management based on blockchains Dong Han a, *, Chengzhenghao Zhang a, Jian Ping b, Zheng Yan b a b Department of Electrical Engineering, University of Shanghai for Science and Technology, Shanghai, China Key Laboratory of Control of Power Transmission and Conversion, Ministry of Education, Shanghai Jiao Tong University, China a r t i c l e i n f o a b s t r a c t Article history: Received 11 November 2019 Received in revised form 14 March 2020 Accepted 16 March 2020 Available online 19 March 2020 A blockchain-based smart contract has the potential to allow the performance of credible transactions without third parties. This paper presents a universal framework for a blockchain platform that enables peer-to-peer (P2P) energy trading in the retail electricity market. Focusing attention on seeking energymatching pairs from the supply and demand sides, and encouraging direct energy trading between producers and consumers, the P2P energy trading mechanism is proposed. The designed multidimensional blockchain platform implements a complete energy trading process. As smart contracts strictly execute the trading and payment rules without human interaction, the security and fairness of energy trading are significantly enhanced. Case studies in the Ethereum private chain demonstrate that the proposed mechanism has obvious advantages in reflecting market quotations, balancing profits of players, and facilitating the utilization of renewables. Based on such characteristics, players are incentivized to participate in the P2P energy trading. Moreover, the authentic gas consumption and computational time to the smart contract indicate that this platform is able to achieve an efficient and effective transaction with multi-player participation. © 2020 Elsevier Ltd. All rights reserved. Keywords: Peer-to-Peer energy trading Distributed energy resources Double auction Blockchain Smart contract 1. Introduction The electric industry is undergoing significant changes, with respect to the increased adoption of distributed energy resources (DERs) at the distribution level [1]. In deregulated power systems, consumers with DERs can perform energy trading by managing their consumption, generation, and storage of energy [2]. Under the traditional paradigm, it is necessary to establish a centralized energy-transaction system for organizing the participation of consumers in retail electricity markets. Centralized energy trading results in more transaction costs and causes inefficient management. A sharing economy enables P2P energy trading among consumers within a local electricity distribution network. P2P energy trading is decentralized and is usually implemented by direct endto-end power exchanges. Different from centralized energy trading, multidirectional trading is encouraged in P2P mode, which enables energy matching based on users’ preferences. Thus, advanced information and communication technology-based online services are used to support the implementation of P2P energy trading. * Corresponding author. E-mail address: han_dong@usst.edu.cn (D. Han). https://doi.org/10.1016/j.energy.2020.117417 0360-5442/© 2020 Elsevier Ltd. All rights reserved. Previous work provided pilot experiences and technical guidance for developing the P2P energy trading platform. Piclo is an online platform for renewable energy trading in the UK, which performs end-to-end energy matching for retail-level transactions [3]. Likewise, the Vandebron platform in the Netherlands enables direct power transactions between energy suppliers and consumers. The existing P2P energy trading platforms are nearly always designed using conventional database technologies, which causes problems of transaction intractability, privacy protection, and data modification. The emergence of blockchains has brought about the opportunity to securely automate the procedure of P2P energy trading. A blockchain is an open and distributed ledger that records transactions between two parties efficiently and in a verifiable and permanent manner [4]. It is noteworthy that a smart contract is one of the key elements in executing the procedure of the blockchain platform without a human interface [5]. Smart contracts are well suited to conduct rules for direct end-to-end transactions of energy autonomously based on local consumer preferences. The blockchain-based smart contract has the potential to enhance security and ensure fairness for decentralized energy systems’ management [6]. 2 D. Han et al. / Energy 199 (2020) 117417 Nomenclature P i, C j ðiÞ The ith producer and the jth consumer ðjÞ sbid , bbid M, N Bid price of Pi and Cj Number of producers and consumers engaging in energy trading ði;jÞ q(i,j) clr, pclr Clearing amount and price of energy that Pi sells to Cj ðiÞ ðjÞ gbid , cbid ðiÞ ðjÞ gres , cres pbuy, psel ðiÞ Bid amount of Pi and Cj Bid amount without exchange of Pi and Cj Purchasing and selling price of the DSO ðjÞ gact , cact Actual amount of energy generation or consumption for Pi and Cj Dg(i), Dc(j) Deviation between bid amount and actual amount for Pi and Cj In 2016, the Brooklyn Microgrid project exploited the Exergy platform, where consumers purchase electricity directly from neighbor photovoltaic producers using blockchains. Meanwhile, the academic literature [7e13] presents applications of blockchain technology related to energy trading and management from the perspectives of the market mechanism, consensus algorithm, and smart contract formation. In Refs. [7], a unified energy blockchain was proposed for secure-based P2P energy trading. Besides, a credit-based payment scheme to support frequent energy trading, enabling fast payment, was designed [8]. proposed a blockchainbased solution for the energy trade among microgrids. Through a number of experimental results, the fast convergence speed and better scalability of this solution were proved [9]. presented a decentralized, real-time, uniform-price, double-auction energy market and implemented it on the Ethereum network. Three different approaches for calling the market-clearing function were compared [10]. built a secure and efficient energy trading scheme based on blockchains. By combining the PoS (Proof of Stakes) consensus with the TOPSIS (Technique for Order Preference by Similarity to an Ideal Solution) comprehensive evaluation method, a new credibility-based equity proof consensus was proposed [11]. studied the security risk of recently proposed authenticated key management schemes in smart grids and proposed a new, provably secure and authenticated keyless scheme based on blockchain. Service providers and end-user devices can obtain secure authentication without any third party [12]. discussed several projects using blockchain for trading and managing renewable energy and conducted experiments on mining efficiency of different encrypted digital coins. In Ref. [13], a game-theoretic approach for the demand side management model that incorporates storage components is suggested, and blockchain technology is applied for efficiency and trustworthiness. The aim of this work is to design a framework for a blockchainenabled smart contract that facilitates the implementation of retail P2P energy trading. In contrast with the existing literature, the prominent novelty and contribution of this paper are as follows: We present a P2P energy trading mechanism with the doubleauction principle to facilitate direct energy trading among producers and consumers, as well as restrict their transaction behaviors. A multidimensional blockchain platform framework is designed to provide visual interfaces for users and to achieve complete cyber-physical communication during the energy trading. The components and techniques involved are clearly introduced. psbp, pssp ðiÞ ðjÞ rpro , rcon prew P, C ðiÞ System buy and sell price for imbalanced energy Fees of rewards for Pi and Cj Incentive price for reward Struct array of producers and consumers ðjÞ dpro , dcon Ethereum account address of Pi and Cj ddso Ethereum account address of the DSO dsmc Address of the smart contract msg.sender Ethereum account address of the current user f Deviation amount between demand and supply x, y Total bid amount and actual amount of energy rimb Deviation rate between x and y e Total expected income or cost b Total bid income or cost rauc Deviation rate between e and b We set out the smart contract architecture for the P2P energy trading process, applicable to the small-scale integrated energy system with digital monitoring and control. We also show that using smart contracts to implement the instruction of decentralized energy trading between different producers and consumers is feasible. The remainder of this paper is organized as follows. In Section 2, the P2P energy trading mechanism design is outlined. An overview of the blockchain platform for P2P energy trading is presented in Section 3. The smart contract framework and its execution are outlined in Section 4. The results of the case studies are shown and discussed in Section 5. Section 6 summarizes the main conclusions and contributions of this study. 2. P2P energy trading mechanism There is an obvious trend that producers sell energy to multiple consumers; meanwhile, consumers purchase energy from multiple producers in the retail electricity market. Traditional energy consumers are becoming prosumers due to the increased installation of DERs such as roof-top PV (photovoltaic) panels and distributed wind-driven generators [14]. The parallel technological advances in smart meters and the Internet of Things (IoTs) enable real-time measurement of the power system [15]. Overall, it is necessary to propose a proper decentralized energy trading mechanism to take advantage of the above changes and facilitate decentralized energy trading. Recently, the bilateral P2P energy trading has become the preferred choice for a growing number of producers and consumers, due to economical pricing and flexibility. A P2P energy trading refers to direct energy trading between producers and consumers without conventional energy suppliers. This is the converse of unilateral energy trading with conventional energy suppliers, who sell energy at a higher price and purchase energy at a lower price [16,17]. As shown on the left side of Fig. 1, the proposed P2P energy trading mechanism consists of closed bidding, energy exchange, and settlement. The players mainly involve renewable producers, producers, consumers, and the distribution system operator (DSO). The price model of the double auction is adopted to facilitate the consumption of renewable energy and balance the benefits of producers and consumers. Inherently, the double auction is a suitable representation for a market that involves multiple sellers and buyers [18]. It enables sellers and buyers to bid to meet their own needs, which includes the prices and quantities of goods. D. Han et al. / Energy 199 (2020) 117417 3 Fig. 1. The schematic diagram of P2P energy trading mechanism. In the closed bidding period, each producer and consumer submit the bid amount, the bid price, and the energy type or preference. The platform adds them to the producer group P or consumer group C according to their roles. In the energy exchange period, the platform settles the energy transaction through the queue and auctions. Firstly, the platform constructs the price sequence of producers in increasing order, as follows: ð1Þ ð2Þ ðiÞ ðMÞ sbid sbid / sbid / sbid (1) ði;jÞ ðiÞ ðjÞ qclr ¼ minimize gres ; cres ðiÞ (4) ðiÞ where gbid and gres are the bid amount and the bid amount without ðjÞ ðjÞ exchanged of Pi, respectively, cbid and cres are the bid amount and the bid amount without exchanged of Cj. The first matching round ðiÞ ðjÞ terminates only if sbid > bbid . The second matching round is performed for all producers and consumers, and its adopted rule is similar to that of the first matching round. After the two P2P ðiÞ ðiÞ where sbid denotes the bid price of the ith producer Pi, M is the ðMÞ number of producers engaging in energy trading, and sbid denotes the highest bid price for all producers. Next, the platform constructs the price sequence of consumers in decreasing order, as follows: ð1Þ ð2Þ ðjÞ ðNÞ bbid bbid / bbid / bbid (2) ðjÞ ðNÞ number of consumers engaging in energy trading, and bbid denotes the lowest bid price for all consumers. Whenever two producers or consumers have equal prices, they will be queued in chronological order of bidding. Following this queuing process, the platform confirms the clearing price and amount for energy exchanged between each producer and consumer by two rounds of P2P matching. The first matching round is performed for renewable producers and conðiÞ ðjÞ sumers with a preference for renewable energy. While sbid < bbid , Pi ði;jÞ sells the amount of energy 1:qclr to Cj at the clearing price pclr , as follows: ðiÞ ðjÞ s þ bbid ði;jÞ pclr ¼ bid 2 ðiÞ amount of energy gres at the DSO’s purchasing price pbuy. ConðjÞ sumers whose cres s 0 buy the amount of energy c(j) res from DSO at the DSO’s selling price psel. Due to the intermittent nature of operations and the deviation of predictions for DERs, there may be an energy imbalance in the ðiÞ system [20,21]. The actual amounts of energy supply gact and enðjÞ ergy consumption cact where bbid denotes the bid price of the jth consumer Cj, N is the ði;jÞ matching rounds, producers whose gres s 0 sell to the DSO the (3) are recorded by smart meters. Once the energy imbalance is identified, the DSO provides energy balance services to keep the system stable. During the settlement period, the platform transfers fees of the energy balance services and rewards the producers and consumers who bid sincerely. Producers and consumers who under-generate or over-demand purchase the amount of energy |Dg(i)| or |Dc(j)| at the system buy price (SBP) psbp from the DSO. Producers and consumers who over-generate or under-demand sell the amount of energy |Dg(i)| or |Dc(j)| at the system sell price (SSP) pssp to the DSO [22], as follows: ðiÞ ðiÞ DgðiÞ ¼ gbid gact (5) ðjÞ ðjÞ DcðjÞ ¼ cbid cact (6) For producers and consumers who contribute to the energy ðiÞ ðiÞ balance in the system, which represents their gact ¼ gbid or 4 D. Han et al. / Energy 199 (2020) 117417 Fig. 3. The operational mechanism of smart contracts. Fig. 2. The framework of the proposed blockchain platform. ðjÞ ðjÞ ðiÞ ðjÞ cact ¼ cbid , they will receive the fees of rewards rpro or rcon at the price prew from the platform, as follows: ðiÞ ðiÞ ðjÞ ðjÞ rpro ¼ prew ,gbid rcon ¼ prew ,cbid (7) Block: The block is comprised of a header and body. The header encapsulates the hash of current and previous blocks, the timestamp, and other information. The body mainly involves the details of the transactions. Node: The basic element of the blockchain system that stores the full blockchain and broadcasts the transaction. Miner node: A special node with the extra ability to attain financial benefits by packing the transactions into blocks and linking the blocks. P2P network: All nodes share the public ledger in this P2P network, without a centralized control actor. Transaction: A sequence of operations applied in some states, such as the transfer of digital assets. Consensus: An agreement specifying the approach for selecting the miner node with the mining priority and verifying the new transactions. Mining: The process of new transaction packing and new block generation. (8) As shown on the right side of Fig. 1, The excess energy imbalance for the retail market need to be settled with the support from the real-time market [19]. In the real-time market, energy transfers according to the day-ahead dispatch. The independent system operator (ISO) keeps the energy balance of the real-time market with balancing generators. Then, the ISO settles the amount and fees for the imbalanced energy. If the DSO is unable to keep the energy balance of the retail market, he needs to buy or to sell energy from the real-time market, fees of this energy are then transferred during the settlement period. 3. Overview of blockchain platform 3.1. Blockchain background A blockchain is a continuously growing distributed database, which stores transactions in sealed blocks. The security, auditability, and tamper-proof capabilities of the blockchain make it an ideal technique to structure a P2P energy trading platform. The basic concepts of a blockchain are briefly introduced as follows [23,24]: 3.2. Multidimensional framework of the blockchain platform The framework of the proposed blockchain platform is shown in Fig. 2, which is divided into three dimensions. The components such as producers, consumers, DSO, and electric equipment do not belong to the blockchain network. Consequently, the prominent contribution of this platform is that all of these components are creatively connected in the blockchain network. In the first dimension, the platform is categorized into three interoperable layers, depending on the type of constituent. Each layer is introduced as follows. The infrastructure layer consists of players and electrical equipment. The players refer to producers, consumers, and DSOs. They form the game network to achieve their own maximum benefits. The electrical equipment involves DERs, loads, smart meters, and transformers [25]. They form the physical electric distribution network, where the P2P energy trading is implemented. The communication layer consists of hardware devices and software applications. The hardware devices refer to wired or wireless communication connections, routers, and computers installed on the Linux system. They construct a basic environment D. Han et al. / Energy 199 (2020) 117417 for running software applications. The software applications refer to a Web frontend, Node.js backend, and Python backend [26]. The visual page provided by the Web frontend is convenient for players to log in, input, and query. The Node.js backend is the intermediate application, which connects the Web frontend with the blockchain layer. The machine data from smart meters is transferred to the script data and sent to the blockchain by the Python backend [27]. The blockchain layer consists of the nodes and blockchains. The nodes are connected in the P2P network by downloading the previous blockchain [28]. Generally, the computers of the communication layer will also be used as the hardware carriers of those nodes. There are a variety of blockchains that can be used as the underlying technology of this layer, for example, Bitcoin, Ethereum, and Hyperledger. During the process of broadcasting and mining, the transactions, such as the storage of bidding information and the computation of energy matching, are packaged in the new block. The second dimension is categorized based on the types of players. The producers and consumers refer to one single player or united players with DERs or loads connected to the electric distribution system. The DSO is the organization that monitors and controls the electric distribution system. The third dimension shows the time sequence of the P2P energy trading process. In the closed bidding period, the producers and consumers input the bidding information, using the computers. In the energy exchange period, the energy is exchanged from the generation devices to the consumption devices, and the DSO provides energy balance services. In the settlement period, the smart meters upload the data of the actual amount of energy, using the computers. 4. Model architecture for smart contracts 4.1. The Ethereum system During energy trading, the cyber-physical communication, executable energy trading mechanism, and digital financial assets are requested at the same time. It is necessary to look for the most suitable blockchain to handle the platform. Among popular blockchains, Ethereum is adopted as the underlying technology of this platform since it facilitates the development of decentralized applications in extensive fields and supports smart contracts [29]. The Geth (Go Ethereum) client of Ethereum provides programmers and users with a convenient tool to operate a blockchain; meanwhile, it has an interface to communicate with Node.js and Python programs. Each node is associated with an account that manages the digital assets, Ethers, of Ethereum. The smart contract of Ethereum is considered to be the computer protocol on the blockchain and enables the energy trading mechanism to be executable [30]. If the conditions are met, it is strictly executed according to the designed algorithm. The unit gas is used to measure resource consumption of transactions, and it is paid with Ethers at the gas price [31]. The operational mechanism of smart contracts is shown in Fig. 3, which can be summarized in three steps: 1. Deployment: We used the Solidity programming language to design the smart contract and applied the browser-based Remix to compile it into Web3deploy code. Then, we deployed the Web3deploy code on the blockchain [32]. 5 2. Broadcasting: The full nodes control the Geth client and broadcast the transactions in the blockchain system. The sendTransaction() approach is appropriate for transactions relating to gas consumption, such as transferring digital assets and modifying the blockchain data. Conversely, the call() approach is appropriate for transactions not relating to gas consumption, such as queries of blockchain data. 3. Mining: For the PoS consensus, adopted by Ethereum, the Ethers in accounts are treated as stakes. A miner node with a preferential stake is selected to compute the transactions and pack these into the new block [33]. Through verification, if the results of the computation are accepted by other nodes, the new block will be included in the local blockchains of each node. 4.2. Smart contract for P2P energy trading This smart contract is designed according to the P2P energy trading mechanism, as proposed in Section 2. It consists of closed bid, energy exchange, settlement, and payment functions. The variables d (i) pro, d (j) con, and ddso represent the Ethereum account addresses of Pi, Cj and DSO, and the variable dsmc represents the address of the smart contract. The mapping for Players[address] is defined to record the details of producers, consumers, and DSOs. Before the energy trade, Pi, Cj, and DSO need to transfer a certain amount of Ethers to the smart contract. A mapping for Balances [address] is introduced to record those Ethers. This paper makes the assumption that the producers and consumers have adequate Ethers and flow the established process. The closed bidding function is shown in Algorithm 1, which receives inputs of the bid amount and bid price. The bid amount and bid price are stored in Players[msg.sender] (line 1). If the producers and consumers bid for the first time, Players[msg.sender] of them will be inserted into the struct array, P and C (lines 2e6). Otherwise, this algorithm updates the new Players[msg.sender] of them in the previous struct array, P and C (lines 7e11). By providing producers and consumers for the universal interface, this function effectively shortens the length of codes and saves the consumption of gas. Algorithm 1 Closed bid. 6 D. Han et al. / Energy 199 (2020) 117417 The energy exchange function is shown in Algorithm 2. The struct array, P and C, are sorted based on the bubble sort algorithm (line 1). Producers with renewable energy and consumers with a preference for renewable energy are selected to trade energy with each other (lines 2e8). Then, all producers and consumers trade energy with each other (lines 9e11). Producers and consumers with excess trade demand will trade energy with the DSO uniformly (lines 12e17). Once an energy trade happens, the payment function is called upon to transfer the Ethers (lines 7, 14, and 17). Algorithm 3 Settlement. Algorithm 2 Energy exchange. The payment function is shown in Algorithm 4, which receives the inputs address of receiver, address of sender, amount of energy, and price of energy. If the Balances[address] of the sender is enough, the transfer of Ethers is executed normally (lines 1e3). Otherwise, the transfer is canceled (lines 4e5). Using the mapping balances [address] and the balance verification, this smart contract eliminates the payment risk [34]. Algorithm 4 Payment. The settlement function is shown in Algorithm 3, which receives the inputs psbp, pssp, and brew. Each producer transfers the energy balance fee with the DSO (lines 1e5). In addition, the producers with accurate power prediction will receive reward Ethers from the smart contract (lines 6e7). A similar process is performed among consumers (lines 8e9). D. Han et al. / Energy 199 (2020) 117417 5. Case study This section provides case studies to demonstrate the application of the proposed P2P energy trading mechanism in the blockchain platform. 7 below the average clearing price will reduce more cost to consumers. To analyze overall auction results of the market, Fig. 7 shows the ði;jÞ clearing price pclr of each confirmed energy exchange. The deviaPM ðiÞ P ðjÞ tion amount f ¼ N j1 cbid ¼ i1 gbid determines the condition of supply and demand. In the evening (0e4 h and 21e24 h), the increasing charge demand of EV 1 and EV 2 causes an increase in f, 5.1. Simulation setup As shown in Fig. 4, the proposed architecture is tested in a microgrid (MG). There are nine players connected in this MG which includes 4 consumers (Load1, EV1, EV2, and Load2), 4 producers (PV, WP, FP1, and FP2), and the DSO. Among the consumers, Load1 and EV1 have preference options for renewable energy generated from PV and WP. The Ethereum private chain is configured by Geth v1.9.2 client, and each player is viewed as a miner node. The exchange rate is assumed to be 1 Ether ¼ $304. Ubuntu 16.04.4 with an Intel Core i7-5500 CPU, an 8G memory, and a 240G hard disk is used to perform the efficient operation. Referring to the real unit time of piclo and the assumed unit time in paper [11], the unit time is set to half an hour. In the one-day simulation. Producers and consumers bid every half an hour, and then the platform activates the energy exchange and settlement process. 5.2. Evaluation of peer-to-peer energy trading results ðiÞ ðiÞ Fig. 5 and Fig. 6 shows the bid price sbid /bbid and clearing price ði;jÞ pclrof each producer and consumer, the average clearing price is considered as the benchmark in this study. In terms of the bid price, for consumers, Load1, EV1, and Load2 adopt conservative bid strategies, since their bid prices are higher than the average clearing price. Conversely, EV2 adopts an aggressive bid strategy. For producers, the bid price strategies of WP, FP1, and FP2 are similar, while those of PV present a unique trend. The relatively adjustable generation of WP, FP1, and FP2 gives them more freedom to bid. As an example, they reduce the bid prices at the low demand time (10:00) to make sure their energy is traded. In contrast, PV has a slight boundedness to bid, since it is almost impossible to change his generation spontaneously. However, he also has a chance to bid a low price to enhance his competitiveness during the highgeneration period (12:00e14:00). In terms of the clearing price, a point in Figs. 5 and 6 represents the clearing price of a confirmed energy exchange. The clearing price above the average clearing price will bring more income to producers, while the clearing price Fig. 4. Schematic diagram of the simulation. ði;jÞ and that further causes an increase in pclr . Conversely, in the morning (4e6 h), f decreases gradually with the completion of ði;jÞ electric vehicle charging; hence, there is a slight decrease in pclr . At dusk (18e19 h), the generation capacity of PV is limited by the lack ði;jÞ of light, and that causes a short increase in f and pclr . In the highest ði;jÞ demand point (3:30), f ¼ 2.66 kWh, and pclr is in the interval from 332 106eth/kWh to 410 106eth/kWh. In the lowest demand ði;jÞ point (21:00), f ¼ 2.80 kWh, and pclr is in the interval from 148 106eth/kWh to 251 106eth/kWh. From this simulation ði;jÞ result, we find that the clearing price pclr is significantly influenced by f. In other words, low demand features low clearing prices, and high demand features high clearing prices. As shown in Fig. 8, we further evaluate the individual auction input and output in one day. By comparing the total bid and clearing amount, we find that most of the energy is traded through auctions. In terms of the price, the clearing prices are in the interval from 256.43 106eth/kWh to 310.18 106eth/kWh, and they are always between the bid prices of producers and consumers. Generally, Fig. 6 is used as an important basis for evaluating the bid strategies of producers and consumers. As an example, the aggressive bid strategy of EV2 brings him the cheapest average clearing price 256.43 106eth/kWh; however, it causes a mass of energy fail to be traded. On the contrary, the conservative bid strategy of EV1 raises the total clearing amount with a high average clearing price. The conservative strategy of Load1 brings him a more positive auction result than other consumers. Since he traded 139.85 kWh, which is almost identical to his total bid amount; meanwhile, his average clearing price 265.97 106eth/kWh is relatively cheaper than his average bid price 350.81 106eth/ kWh. In the same way, Fig. 9 shows the comparison between the total expected income/cost e and the bid income/cost b of each producer and consumer. As can be seen, b of producers is always below their e, while b of consumer is always above their e. This trend is the same as the bid and clearing price trend in Fig. 8. The ratio rauc ¼ |be|/e 100% is defined to describe the deviation between b and e, and it is in the interval from 11.90% to 46.94%. Producers and consumers are pleased with bid results when rauc is high. Among all producers and consumers, PV is most satisfied with his bid result. As shown in Fig. 5 (a) and 5 (c), although Load1 and EV2 adopt different strategies, their rauc are similar. The results in Figs. 8 and 9 indicate that the auction results are based on bids of producers and consumers, both conservative and aggressive bid strategies have their pros and cons, and they may lead to completely different or identical results. In a word, this platform provides producers and consumers an opportunity to obtain positive profit by competition. Fig. 10 shows constituents of the confirmed energy exchange. Overall, 41.80% and 41.92% of energy is traded in the first and second matching round, the other energy is traded with the DSO. In terms of the individual constituents, PV and WP sold 97.34% and 98.50% of energy through auctions, this energy is bought by Load 1 and EV1. FP1 and FP2 sold 71.02% and 75.05% of energy through auctions, this energy is bought by Load1, EV1, EV2, and Load2, respectively. This result indicates that even without the help of 8 D. Han et al. / Energy 199 (2020) 117417 Fig. 5. Bid and clearing prices of consumers in one day. D. Han et al. / Energy 199 (2020) 117417 9 Fig. 6. Bid and clearing prices of producers in one day. Fig. 7. Market clearing prices and deviation amount in one day. Fig. 8. Individual auction input and output in one day. DSO, 83.72% of the energy is traded among the producers and consumers, that includes most of the renewable energy. Consequently, the proposed mechanism facilitates direct energy trading among producers and consumers, and it promotes the consumption of renewable energy. Fig. 11 shows the comparison between total bid amount of enP PN ðjÞ ðiÞ ergy x ¼ M i1 gbid þ j1 cbid and total actual amount of energy PM ðiÞ PN ðjÞ y ¼ i1 gact þ j1 cact. The ratio of energy imbalance rimb ¼ |x-y|/ x 100% is defined to describe the degree of energy imbalance, producers and consumers bid sincerely and energy imbalance is slight when rimb is low. We can see that rimb is in the interval from 0% to 13.05%. From 9:30 to 17:00, rimb is below 4.54%, since the relatively stable generation and consumption of devices facilitates the prediction of power. In the worst-case scenario (7:30), the DSO balances 3.5 kWh. Overall, the DSO balances 25.88 kWh in one day which accounts for 2.91% of the total actual energy. This result 10 D. Han et al. / Energy 199 (2020) 117417 Fig. 9. Individual auction income and cost in one day. Fig. 12. The gas consumption of main algorithms under different number of players. 5.3. Evaluation of computational cost Fig. 10. Constituents of the total confirmed energy exchange in one day. Fig. 12 shows how the gas consumption and number of times that Algorithm 4 is called change when the number of players is increased. The initial three players refer to the Load1, PV, and DSO. The number of players is increased gradually according to the rule of adding one producer and then one consumer. It can be observed that as the number of players increases, the gas consumption of the Algorithm 2 and Algorithm 3 both increase at a slower speed. Notice that the gas consumption of Algorithm 2 (49.13e279.287 104) is slightly higher than Algorithm 3 (40.33e157.24 104) because of the greater amount of logical statements. In special circumstances, the gas consumption of Algorithm 2 and the operation times of Algorithm 4 are the same with 7 and 8 players. The reason for this is that the deviation amount f < 0 before FP2 engages in energy trading, hence, he is unable to sell any energy to the consumers. The settlement for each producer and consumer is constant even if they don’t sell or buy any energy during the energy exchange period. Hence, the variation trend of Algorithm 3 is stable compared with Algorithm 2. Obviously, the capacity of players to engage in energy trading is limited by the gas consumption of the smart contract. Relative to the upper gas limit of 6,718,904 gas/block in the Ethereum public Fig. 11. The energy imbalances in one day. indicates that the proposed mechanism avoids serious energy imbalances effectively since it motivates producers and consumers to bid sincerely. Fig. 13. The computational time of main algorithms under different number of miner nodes. Ethereum private chain 0x764836f8740ec154f162bb1ce156eacbffe0e253 New contract 110 0x35352ebd94e21a0d1e51957fd6b29bff2949f588624bcd400439fb752be8440a 0x16a59b8c9144e1729e67eedb7df8cf14cc758789 6604479 15 s Ropsten test network 0xa826bc23df61f055bf3369048dc294362b8709db New contract 6456245 0x7a95da6d500e8a40b9b7614b7a899340de6d1bb42fa829957a7ca08f833187d6 0x8f954222e523c06b3553c850032ba29b9d609ad4 6604479 4s Blockchain type Sender Receiver Block number Transaction hash Contract hash Gas consumption Computational time Table 1 The comparison of contract deployment between Ropsten test network and Ethereum private chain. D. Han et al. / Energy 199 (2020) 117417 11 chain [35], the proposed smart contract is able to support energy trading for more than 25 players at the same time. The distributed computation is an alternative solution to the problem of gas consumption overruns due to increased players. As an example, we assume that there are 2 m producers and 2n consumers after sorting by bidding price. The energy trading of the top m producers with 2n consumers is confirmed by the first computation, and the energy trading of the last m producers with 2n consumers is confirmed by the second computation. The specific times of distributed operations are determined by the practical number of players. Fig. 13 shows how the computational time changes when the number of miner nodes is increased. Predictably, as the number of miner nodes increases, the operation time of Algorithm 2 and Algorithm 3 decreases for both. The operation time of Algorithm 2 is slightly higher than Algorithm 3, which is similar to Fig. 12. However, there is a lower limit of operation time. After the number of miner nodes increased to 6, the operation time started to stabilize in the interval from 13.00s to 19.25s. Generally, the operation time of a transaction in the blockchain is affected by the number of miner nodes, the complexity of the smart contract, and the configuration of computers, etc. In this simulation, it is most economical to use about 6 miner nodes. It is worth mentioning that faster blockchain transaction confirmation is implemented with a higher gas price in the massive blockchain. However, this effect is not evident for this simulated small Ethereum private chain. In order to evaluate the performance of this blockchain platform, the same smart contract was deployed on the Ropsten test network. The source smart contract code of the address 0x8f954222e523c06b3553c850032ba29b9d609ad4 was also published in the Ropsten test network [36]. Table 1 presents the contract deployment details about the Ropsten test network and the Ethereum private blockchain. We find that the gas consumption of both is 6604479, and the Ropsten test network completes the contract deployment in 4 s. This result demonstrates the authenticity of statistical data to the proposed smart contract in this simulation. Further, it is realistic to achieve rapid energy trading by this smart contract. 5.4. Method comparison To illustrate the merits of the proposed method, we repeat the simulation using the conventional double auction [9,18]. As shown in Figure A.1 and Algorthim A 1, the conventional double auction first computes the intersection point Q of supply curve and demand curve. Then, for the k producers and l consumers to the left of Q, they trade energy at the same clearing price pQ, as follows: ðkÞ ðlÞ s þ bbid pQ ¼ bid 2 (9) Fig. 14 shows results of this repeated simulation using the same input data. The clearing price in Fig. 14 (a) generally follows f as in Fig. 7. However, the change in supply and demand is sometimes incompletely reflected by this single clearing price curve (19:30e23:30). Compared with Fig. 8, the average clearing prices in Fig. 14 (b) are closer to the average bid prices of producers. In terms of the consumption of renewable energy, PV and WP successfully sell 83.93% and 82.63% energy through auctions in Fig. 14 (c), which are less than the ratios in Fig. 10. As shown in Fig. 14 (d), the gas consumption of Algorthim A 1 is in the interval from 53.13 104 to 268.75 104, which is a little more than the gas consumption in Fig. 12. 12 D. Han et al. / Energy 199 (2020) 117417 Fig. 14. Results of the simulation using the conventional double auction. D. Han et al. / Energy 199 (2020) 117417 By comparing, we find that the proposed method is able to reflect accurate market quotations. It has obvious advantages in balancing the profits of players and facilitating the consumption of renewable energy. Although it achieves a complicated match, a little more gas is consumed. 13 Algorthim A 1 Energy exchange (conventional double auction). 6. Conclusion This paper has proposed an innovative blockchain platform framework to bridge producers’ resources and consumers’ requirements in peer-to-peer energy trading. The three-step P2P energy trading mechanism adopts the double auction principle to enhance the vitality of the market. To realize the process, the threedimensional platform provides a visual interface for the users and a stable measuring system for the equipment. A smart contract composed of four core algorithms was developed; the objective of each algorithm is to save gas consumption and ensure security. The feasibility and efficiency of the proposed framework are demonstrated through an experimental evaluation in an Ethereum private chain. In one-day energy trading, 83.72% energy is successfully traded through auctions, and the average clearing prices are always between the bid prices of producers and consumers. The DSO just balances 2.91% of the total actual energy, since the mechanism motivates producers and consumers to bid sincerely. Moreover, the proposed smart contract supports energy trading for more than 25 players at the same time, and the operation time stabilizes in the interval from 13.00s to 19.25s with more than six miner nodes. This study is devoted to promoting the applicability of blockchains in the field of energy trading. Future works should consider enriching the functions of the platform and testing it in different environments. Declaration of competing interest The authors declare that they have no known competing financial interests or personal relationships that could have appeared to influence the work reported in this paper. CRediT authorship contribution statement Dong Han: Methodology, Writing - original draft, Writing - review & editing. Chengzhenghao Zhang: Software, Validation, Visualization. Jian Ping: Formal analysis, Investigation. Zheng Yan: Formal analysis, Investigation. Acknowledgment This paper is supported by the National Natural Science Foundation of China (No. 51777126). Fig. A.1. An illustrative example of the conventional double auction. References Appendix A [1] Rahimi F, Ipakchi A, Fletcher F. The changing electrical landscape: end-to-end power system operation under the transactive energy paradigm. IEEE Power Energy Mag MayeJune 2016;14(3):52e62. https://doi.org/10.1109/ MPE.2016.2524966. [2] Morstyn T, Farrell N, Darby SJ, McCulloch MD. Using peer-to-peer energy trading platforms to incentivize prosumers to form federated power plants. Nature Energy Feb. 2018;3:94e101. https://doi.org/10.1038/s41560-017- 14 D. Han et al. / Energy 199 (2020) 117417 0075-y. [3] Good Energy, Oct. Shaping the future of energy with the Piclo trial. 2015 [Online]. Available: https://www.goodenergy.co.uk. [4] Dinh TTA, Liu R, Zhang M, Chen G, Ooi BC, Wang J. Untangling blockchain: a data processing view of blockchain systems. IEEE Trans Knowl Data Eng Jan. 2018;30(7):1366e85. https://doi.org/10.1109/TKDE.2017.2781227. [5] Thomas L, Zhou Y, Long C, Wu J, Jenkins N. A general form of smart contract for decentralized energy systems management. Nature Energy Jan. 2019;4: 140e9. https://doi.org/10.1038/s41560-018-0317. [6] Li Z, Guo H, Wang WM, Guan Y, Barenji AV, Huang GQ. A blockchain and AutoML approach for open and automated customer service. IEEE Trans on Industrial Informatics Jun. 2019;15(6):3642e51. https://doi.org/10.1109/ TII.2019.2900987. [7] Li Z, Kang J, Yu R, Ye D, Deng Q, Zhang Y. Consortium blockchain for secure energy trading in industrial internet of Things. IEEE Trans on Industrial Informatics Aug. 2018;14(8):3690e700. https://doi.org/10.1109/ TII.2017.2786307. [8] Thakur S, Breslin J. Peer to peer energy trade among microgrids using blockchain based distributed coalition formation method. Technology and Economics of Smart Grids and Sustainable Energy May. 2018;3(5):1e17. https://doi.org/10.1007/s40866-018-0044-y. [9] Foti M, Vavalis M. Blockchain based uniform price double auctions for energy markets. Appl Energy 2019;158:Nov. https://doi.org/10.1016/ j.apenergy.2019.113604. [10] Guan Z, Liu X, Wang N, Wu J, Du X, Guizani M. Towards secure and efficient energy trading in IIoT-enabled energy internet: a blockchain approach. Future Generat Comput Syst Oct. 2019:1e10. https://doi.org/10.1016/ j.future.2019.09.027. Available online:. [11] Zhang H, Wang J, Ding Y. Blockchain-based decentralized and secure keyless signature scheme for smart grid. Energy Aug. 2019;180:955e67. https:// doi.org/10.1016/j.energy.2019.05.127. [12] Li J, Li N, Peng J, Cui H, Wu Z. Energy consumption of cryptocurrency mining: a study of electricity consumption in mining cryptocurrencies. Energy Feb. 2019;168:160e8. https://doi.org/10.1016/j.energy.2018.11.046. [13] Noor S, Yang W, Guo M, Dam KHv, Wang X. Energy Demand Side Management within micro-grid networks enhanced by blockchain. Appl Energy Oct. 2018;228:1385e98. https://doi.org/10.1016/j.apenergy.2018.07.012. [14] Thomas D, Iain M, Dale G. Virtual power plants leveraging energy flexibility in regional markets. CIRED - Open Access Proceedings Journal Oct. 2017;(1): 2939e43. https://doi.org/10.1049/oap-cired.2017.0867. 2017. [15] Wang Q, Zhu X, Ni Y, Gu L, Zhu H. “Blockchain for the IoT and industrial IoT: a review,” Internet of Things. July 2019. p. 4792e803. https://doi.org/10.1016/ j.iot.2019.100081 [Online]. Available:. [16] Zhang C, Wu J, Zhou Y, Cheng M, Long C. Peer-to-Peer energy trading in a Microgrid. Appl Energy Jun. 2018;202:1e12. https://doi.org/10.1016/ j.apenergy.2018.03.010. [17] Sorin E, Bobo L, Pinson P. Consensus-based approach to peer-to-peer electricity markets with product differentiation. IEEE Trans Power Syst Mar. 2019;34(2):994e1004. https://doi.org/10.1109/TPWRS.2018.2872880. [18] Wang Y, Saad W, Han Z, Poor HV, Başar T. A game-theoretic approach to energy trading in the smart grid. IEEE Transactions on Smart Grid May 2014;5(3):1439e50. https://doi.org/10.1109/TSG.2013.2284664. [19] Quint D, Dahlke S. The impact of wind generation on wholesale electricity market prices in the midcontinent independent system operator energy market: an empirical investigation. Energy Feb. 2019;163:456e66. https:// doi.org/10.1016/j.energy.2018.12.028. [20] Wang H, Yan Z, Shahidehpour M, Xu X, Zhou Q. Quantitative evaluations of uncertainties in Multivariate operations of microgrids. IEEE Trans on Smart Grid, early access Feb. 2020. https://doi.org/10.1109/TSG.2020.2971689. 1e1. [21] Liu WH, Ho WS, Lee MY, Hashim H, Lim JS, Klemes JJ, YeeMah AX. Development and optimization of an integrated energy network with centralized and decentralized energy systems using mathematical modelling approach. Energy Sep. 2019;183:617e29. https://doi.org/10.1016/j.energy.2019.06.158. [22] Elexon, June 27. Imbalance pricing guidance [Online]. Available: https://www. elexon.co.uk/documents/training-guidance/bsc-guidance-notes/imbalancepricing; 2019. [23] Bai L, Hu M, Liu M, Wang J. BPIIoT: a light-weighted blockchain-based platform for industrial IoT. IEEE Access 2019;7:58381e93. https://doi.org/ 10.1109/ACCESS.2019.2914223. [24] Lu Q, Xu X, Liu Y, Weber I, Zhu L, Zhang W, uBaaS “. A unified blockchain as a service platform. Future Generat Comput Syst Dec. 2019;101:564e75. https:// doi.org/10.1016/j.future.2019.05.051. [25] Guelpa E, Bischi A, Verda V, Chertkov M, Lund H. Towards future infrastructures for sustainable multi-energy systems: a review. Energy Oct 2019;184:2e21. https://doi.org/10.1109/TII.2019.2901011. [26] Tilkov S, Vinoski S. Node.js: using JavaScript to build high-performance network programs. IEEE Internet Computing Nov.eDec. 2010;14(6):80e3. https://doi.org/10.1109/MIC.2010.145. [27] Melo WS, Bessani A, Neves N, Santin AO, Carmo LFRC. Using blockchains to implement distributed measuring systems. IEEE Transactions on Instrumentation and Measurement May 2019;68(5):1503e14. https://doi.org/10.1109/ TIM.2019.2898013. [28] Lee JY. A decentralized token economy: how blockchain and cryptocurrency can revolutionize business. Bus Horiz Nov.eDec. 2019;62(6):773e84. https:// doi.org/10.1016/j.bushor.2019.08.003. [29] Daniel F, Guida L. A service-oriented perspective on blockchain smart contracts. IEEE Internet Computing Jan.eFeb. 2019;23(1):46e53. https://doi.org/ 10.1109/MIC.2018.2890624. [30] Guadamuz A. “All watched over by machines of loving grace: a critical look at smart contracts,” Computer Law & Security Review. Aug. 2019. p. 1e16. https:// doi.org/10.1016/j.clsr.2019.105338 [Online]. Available:. [31] Cruz JP, Kaji Y, Yanai N. “RBAC-SC: role-based access control using smart contract. IEEE Access 2018;6:12240e51. https://doi.org/10.1109/ ACCESS.2018.2812844. [32] Pinna A, Ibba S, Baralla G, Tonelli R, Marchesi M. A massive analysis of Ethereum smart contracts empirical study and code metrics. IEEE Access 2019;7. https://doi.org/10.1109/ACCESS.2019.2921936. [33] Wang W, Hoang DT, Hu P, Xiong Z, Niyato D, Wang P, Wen Y, Kim DI. A survey on consensus mechanisms and mining strategy management in blockchain networks. IEEE Access 2019;7:22328e70. https://doi.org/10.1109/ ACCESS.2019.2896108. [34] Hasan H, AlHadhrami E, AlDhaheri A, Salah K, Jayaraman R. Smart contractbased approach for efficient shipment management. Comput Ind Eng Oct. 2019;136:149e59. https://doi.org/10.1016/j.cie.2019.07.022. [35] Ozyilmaz KR, Yurdakul A. Designing a blockchain-based IoT with Ethereum, swarm, and LoRa: the software solution to create high availability with minimal security risks. IEEE Consumer Electronics Magazine Mar. 2019;8(2): 28e34. https://doi.org/10.1109/MCE.2018.2880806. [36] GitHub [Online]. Available: https://github.com/zczhzczh/message.