Privacy-Preserving Peer-to-Peer Energy Trading in Blockchain-Enabled Smart Grids Using Functional Encryption

.


Introduction
Distributed renewable energy sources, such as solar panels and wind turbines, are drastically changing the way electricity is generated and consumed [1,2]. Energy prosumers, i.e., energy consumers producing their own electrical power, are rapidly proliferating. Advanced smart grid technologies enable these prosumers to trade surplus energy with other peer prosumers through peer-to-peer (P2P) energy trading [3]. P2P energy trading is expected to be one of the most important elements of next-generation power systems [1]. It can provide numerous benefits, such as increasing the overall efficiency of power systems and reducing power outages. For customers, it may create a competitive energy market and allow access to alternative energy sources according to their individual preferences [1].
In many ongoing trials, P2P energy trading is being facilitated by blockchain technology through blockchain's distributive nature and capacity to run smart contracts [3,4]. Such trading systems cannot be fully independent of the existing infrastructure, but the integration of new systems into conventional centralized energy systems is crucial [4]. An electric power system requires two fundamental components: the physical system for electricity transmission and the information system for settlement, balancing, and billing. In the P2P trading context, a blockchain can provide a partial solution for the latter, such as matching and contracting between sellers and buyers and recording transactions in blocks are validated by all participants ("nodes") based on a well-defined consensus protocol without a trusted third party. Although the blockchain concept originated from Bitcoin [5], the script language for Bitcoin is too limited to perform general transactions because it is designed mainly for a single-purpose application (i.e., exchanging Bitcoin cryptocurrency). For example, Bitcoin does not support the execution of loops or complex programs. Ethereum [10] is the most well-known solution of this problem. The Ethereum protocol supports a Turing-complete programming language and enables users to create virtually any form of transaction or application using smart contracts [11,12]. Smart contracts are computer programs that securely reside on the blockchain and automatically execute the specified function [1,13]. An Ethereum smart contract can be written in the Solidity language and is created by sending a contract-creation transaction to the blockchain network. Smart contracts are run on the Ethereum Virtual Machine (EVM), which is maintained by Ethereum nodes in a decentralized and distributed manner [14]. Because Ethereum supports complex applications, EVM requires a method of validating the smart contract. To prevent poorly written code, such as an infinite loop, Solidity uses 'gas' as the fundamental unit of computation when running a smart contract [15]. If the smart contract requires more gas than the gas limit defined at the time of its deployment, its execution is terminated, thereby avoiding any waste of resources.
Blockchain has the potential to fulfill various requirements for P2P applications; however, it faces a confidentiality issue [16,17]. Because the design philosophy of a blockchain is to provide integrity through publicly verifiable transactions, all the data and transactions on the blockchain are visible to all the participating nodes. Most blockchains, including Ethereum, provide simple anonymity by generating pseudorandom addresses instead of permanent user IDs. However, the transactions of the same user can be linked through the address, although his/her real ID is not revealed. There is a well-known attack wherein an attacker can trace the transmission history to match a pseudorandom address with a person holding a coin. To solve this problem, mixing services were designed to exchange a user's coin with those of other users randomly, so that the original owner of the coin is not identified. Mixcoin [18] and Coinshuffle [19] are examples of such services. Another approach is to provide zero-knowledge proof on the blockchain, such as zk-SNARK [20] and BulletProof [21]. Zerocash [22] and Zether [23] are well-known applications of zero-knowledge proof. However, Zerocash [22] and Zether [23], as well as mixing services, are limited to the confidential transfer of cryptocurrency, i.e., ensuring user anonymity when cryptocurrency is transferred. Although zk-SNARK [20] and BulletProof [21] can have a wider range of applications, they are not designed for directly performing confidential transactions, but for confidentially verifying the validity of a transaction. The challenge encountered when implementing a confidential transaction is that users must disclose their data to all blockchain nodes to perform transactions over the blockchain.
Therefore, a method of performing transactions (i.e., smart contracts) is required without opening the data to the nodes. Hawk [24] is a framework that builds privacy-preserving smart contracts. It effectively solved the issue discussed earlier, but by introducing a third party called the manager. The manager must be involved in every confidential transaction, thus causing transaction execution to require many interactions between the users and the manager.

Peer-to-Peer Energy Trading Through Blockchain
Recently, the energy business has been considering decentralized systems owing to the necessity of energy-sector decentralization and the fact that renewable energy is not suitable for the centralized legacy system [25,26]. Blockchain meets these demands; thus, there have been many trials of P2P energy trading based on blockchain technologies. Power Ledger [27] and LO3 Energy's Brooklyn Microgrid [28,29] are the best-known projects that use blockchains. Power Ledger is a P2P energy trading platform that uses blockchains; it was developed in Australia and has expanded its territory to include India, Japan, and other countries. Brooklyn Microgrid is an energy marketplace for the residents of Brooklyn, New York. There are other platforms, such as Slock.it [30] and SolarCoin [31], but they do not address the privacy issue. Additionally, there are P2P energy trading systems for specific purposes, such as electric vehicle charging [32] and campus-scale energy auction [33]. However, the privacy issue was not addressed effectively in these systems, either.
To tackle the privacy threat against P2P energy trading, various approaches have been proposed. Li et al. [34] and Kang et al. [35] provided pseudonym-based solutions for P2P energy trading on consortium-based blockchains. Aitzhan and Svetinovic [7] presented a token-based energy trading system to enable peers to perform anonymous transactions on a Bitcoin-based blockchain. This can also be categorized as a pseudonym-based approach, where only the identities of peers are protected, but the transaction data are visible to all blockchain nodes. Gai et al. [36] proposed to prevent linking attacks and malicious data mining by adding noise to the trading distribution, which is similar to the well-known smart meter data obfuscation techniques [37][38][39] to prevent non-intrusive appliance load monitoring (NIALM) [40]. To be precise, the privacy-preserving mechanism in Reference [36] was to achieve differential privacy by creating dummy accounts and dividing accounts. Therefore, only the statistical information for each peer is protected, but the transaction data are not protected. To the best of our knowledge, there has been no proposal to protect transaction data while performing prosumer matching on a blockchain.
Finally, blockchains can be used for purposes different from trade negotiation. For example, Munsing et al. [41] proposed the use of a blockchain to decentralize the optimization of energy resources. Luo et al. [42] proposed to use a separate agent system for negotiation and a blockchain only as a transaction settlement mechanism.

Function-Hiding Inner Product Functional Encryption
Functional encryption (FE) is a special type of encryption scheme that supports operations on encrypted data [43][44][45]. In this section, we will explain only the special FE scheme, i.e., function-hiding inner product encryption (FHIPE) [46][47][48][49][50], although the original FE can provide a wider range of functions and properties. Let x and y be two vectors, and let E(x) and E(y) be their encryption. Roughly speaking, the decryption operation takes two ciphertexts E(x) and E(y) as inputs, and produces the inner product of x and y, which is denoted as x, y . This operation can be performed by any party but reveals no information about either x or y, except x, y .
In this study, we use the practical FHIPE scheme, Π IPE , proposed by Kim et al. in 2018 [50]. This scheme uses pairing-based asymmetric bilinear groups. Therefore, we begin the description of Π IPE with some definitions and properties of pairings. Let P ∈ G 1 and Q ∈ G 2 be generators of G 1 and G 2 , respectively, where G 1 and G 2 are two distinct groups of prime order q. Let e : G 1 × G 2 → G T be a mapping that maps two group elements from G 1 and G 2 onto a target group G T . We write the group operations in G 1 , G 2 , and G T multiplicatively. Let the tuple (G 1 , G 2 , G T , q, e) be an asymmetric bilinear group that satisfies the following properties: • Both the bilinear map e and the group operations in G 1 , G 2 , and G T can be computed efficiently.

•
Map e is bilinear for all x, y ∈ Z q . In other words, map e satisfies e(P x , Q y ) = e(P, Q) xy .
For a group element P ∈ G 1 and a row vector v = (v 1 , . . . , v n ), P v denotes the vector of group elements (P v 1 , . . . , P v n ) as in Reference [50]. The bilinear map over groups is extended to vectors as follows: where v = (v 1 , . . . , v n ) and w = (w 1 , . . . , w n ). Now, we are ready to explain Π IPE . Many inner product encryption schemes typically consist of four probabilistic polynomial time (PPT) algorithms: setup, key generation, encryption, and decryption [46][47][48][49][50]. However, it is more intuitive to use the notations, left and right encryptions, instead of key generation and encryption, respectively. This notation was already used in Reference [50]. Then, the Π IPE scheme is defined with four PPT algorithms, Setup, LeftEncrypt, RightEncrypt, and Decrypt, as follows: • Setup(1 λ ) → (op, sk): Given a security parameter λ, the setup algorithm Setup outputs the public parameters op and the secret key sk corresponding to λ. Concretely, Setup samples an asymmetric bilinear group (G 1 , G 2 , G T , q, e), and chooses generators P ∈ G 1 and Q ∈ G 2 . Next, the algorithm samples the matrix B ← GL n (Z q ), where GL n (Z q ) is the general linear group of (n × n) matrices over Z q . Then, the algorithm sets the matrix B * = det(B) · (B −1 ) using det(B), the determinant of B, and (B −1 ) , the transpose matrix of B −1 . Finally, the setup algorithm outputs the public parameters op = (G 1 , G 2 , G T , q, e) and the secret key sk = (op, P, Q, B, B * ). • LeftEncrypt(sk, α, x) → E L (x): Given the secret key sk, a uniformly random element α ∈ Z q , and a row vector x = (x 1 , . . . , x n ), the left encryption algorithm LeftEncrypt outputs a left encryption: • RightEncrypt(sk, β, y) → E R (y): Given the secret key sk, a uniformly random element β ∈ Z q , and a row vector y = (y 1 , . . . , y n ), the right encryption algorithm RightEncrypt outputs a right encryption: • Decrypt(op, E L (x), E R (y)) → z: Given the public parameters op, the left encryption E L (x) = (L 1 , L 2 ), and the right encryption E R (y) = (R 1 , R 2 ), the decryption algorithm Decrypt computes: Then, it checks whether there is a z satisfying (D 1 ) z = D 2 by solving a discrete logarithm problem [51] and either outputs z or a symbol implying that a valid z cannot be found. If there is such a z, then z = x, y .

System Components
We consider a microgrid system consisting of prosumers, smart meters, an energy storage, a DSO, and a blockchain. Figure 1 illustrates the proposed system model. Each smart meter is connected to a prosumer that we simply call a user. According to the convention in relevant literature [7,52], we assume that a smart meter is a sealed tamper-proof device, i.e., even the user of the smart meter cannot extract or inject secret keying material, although the user initiates the power trading transactions by providing his/her smart meter with the desired amount and price of power to be sold or bought. Therefore, we assume that a smart meter never performs a malicious function, i.e., it is a trusted party. In addition, we consider a smart meter as not only a metering device but also a network node that provides the user with a connection to the outside world, such as the blockchain. However, it is also possible to set up a separate device for this purpose, if necessary. An energy storage is an energy pool equipped with a bi-directional communication flow. It is connected with each smart meter through a local distribution network. It is also connected to a DSO and a transmission system operator (TSO) that transmits electrical power from power plants through a transmission line. We assume that the energy storage is also a trusted party. In this paper, we do not deal with the details of power-transmission lines involving TSOs and power plants. A DSO is responsible for both the uni-directional power distribution from the transmission line and the bi-directional distribution between the prosumers via the energy storage. For the latter P2P energy trading, the DSO becomes a mediator and updates the seller credit and the buyer debit according to the seller-buyer matching information provided by the blockchain. The DSO also serves as an LSE, and each user has an account registered to the DSO. Thus, the DSO periodically charges each account associated with a user at a rate decided by (usage of energy from power plants) − (energy sale credit) + (energy purchase debit) + (fees for transaction mediation and distribution). The fees are not only for mediating P2P trading but also for the transmission and distribution of power from power plants, as in a traditional energy service. The blockchain provides the peer users with a platform for energy trading where users can anonymously negotiate energy prices without revealing their identity or prices to any third party except the DSO. The blockchain implements this functionality by performing operations on users' encrypted bids with functional encryption. Finally, we assume that all data communication lines are protected by a proper traditional end-to-end encryption mechanism.

Threat Model and Security Goals
Based on the above system model, we assume the following threat model.

•
The blockchain never deviates from the protocol specified by smart contracts. In addition, the integrity of the data written on the blockchain is guaranteed by the nature of the blockchain. However, each node participating in the blockchain network can see all the details of all the transactions and their related data if they are not encrypted. Therefore, from the viewpoint of the DSO and the users, the blockchain can be considered an honest-but-curious adversary that aims at obtaining any useful information from the user transactions but implements the protocol honestly and correctly.

•
When mediating an energy transaction, the DSO may try to manipulate either the energy price or trading amount between the matched seller and buyer artificially to maximize its profit. Let us assume that the desired prices of a seller and a buyer are pp S and pp B , respectively. The matching for energy trading is successful when pp S ≤ pp B . If pp S = pp B , the transactions are performed with this matched price. In contrast, if pp S < pp B , the price is settled according to a predefined policy, e.g., (pp S + pp B )/2. However, abusing the property that the users cannot see the other party's encrypted bid, the DSO may try to buy the energy for pp S and sell it for pp B . Second, assume that the desired trading amounts of a seller and a buyer are pa S and pa B , respectively. Then, the matched trading amount must be min(pa S , pa B ). However, if the fee for mediating P2P trading is not profitable enough, in comparison with that for legacy transmission and distribution, the DSO may attempt to intentionally reduce the volume of P2P transactions.

•
Users may attempt to repudiate the amount and price of power that they had declared when initiating a bid.
To address the above threats, a P2P energy trading system must satisfy the following goals.
• User Privacy: The identities of users participating in P2P transactions must be kept private from blockchain nodes. The peers that conduct power transactions must not learn each other's identities. The identity of a user must not be linkable through multiple transactions involving this user. • DSO Privacy: Because the DSO's profit depends on the fees for transaction mediation, the statistics on the transactions mediated by the DSO may reveal a significant portion of the company's trade secrets. Therefore, the contents of each bid, such as the amount and price of power, must be kept private from blockchain nodes. • Verifiability of transactions and integrity of bids: Let S and B be the sets of sellers and buyers that uploaded bids on the blockchain, respectively. Let pp U and pa U be the price and amount of power declared by a user U ∈ S ∪ B, respectively. If min S∈S pp S ≤ max B∈B pp B , it must be guaranteed that the seller with the minimum bid, i.e., S m = argmin S∈S pp S , and the buyer with the maximum bid, i.e., B M = argmax B∈B pp B , will be matched for the P2P transaction. All operations must be verifiable by any participating user. Furthermore, the DSO must not be able to modify pp S m , pa S m , pp B M , and pa B M when mediating the transaction.

Proposed Energy Trading System
In this section, we first explain the proposed algorithm that matches a seller and a buyer in a privacy-preserving manner using functional encryption. Then, we combine this algorithm with the system model explained in the previous section to build a prototype energy trading system.

Privacy-Preserving Matching Algorithm
First, we design a matching strategy that matches a seller and buyer pair for energy trading. Next, we extend this strategy to a privacy-preserving matching algorithm. As in the previous section, let S and B be the sets of sellers and buyers who want to trade energy, respectively. Let pp U be the power price declared by a user U ∈ S ∪ B. As in a typical matching strategy for various trading markets and auctions, e.g., a stock market, we will match the seller with the minimum bid, i.e., S m = argmin S∈S pp S , to the buyer with the maximum bid, i.e., B M = argmax B∈B pp B . Therefore, matching is not possible if min S∈S pp S > max B∈B pp B . To identify S m and B M easily, we maintain two array-based heap data structures: a min-heap H S for sellers and a max-heap H B for buyers, where the primary keys are the bid values. Therefore, S m and B M can be found at the roots of H S and H B , respectively. The insertion and deletion of a bid can be completed in either O(log 2 |S|) or O(log 2 |B|) time. After S m and B M are matched, the amount of power to be traded is decided as min(pa S m , pa B M ), where pa U is the power amount declared in user U's bid.
To perform the above-mentioned matching and heap updating in a privacy-preserving manner, we designed a vector encoding method for power prices. For simplicity, we assume that a price is an element selected from an ordered set P ⊂ Z, where Z is the set of integers. The elements in P are sorted in increasing order. We label these elements as p 1 , . . . , p |P| , starting from the smallest. For example, if P = {11, 12, . . . , 20}, then p 1 = 11, p 2 = 12, . . . , p 10 = 20. We also define index P (p i ) where 1 ≤ i ≤ |P|. For example, index P (13) = 3. In a situation where decimal fractions are allowed for a price, appropriate scaling and quantization methods can be applied. To apply the FHIPE scheme [50] explained in Section 2.3, we encode a price value pp U ∈ P with two |P|-dimensional vectors, U L and U R , which we call left and right vectors, respectively. We encode U L , so that its elements with index < index P (pp U ) are 0, and the other elements are 1. Meanwhile, a one-hot encoding is used for U R . For example, if pp U = 15, U L = (0, 0, 0, 0, 1, 1, 1, 1, 1, 1), and U R = (0, 0, 0, 0, 1, 0, 0, 0, 0, 0). When the prices pp U 1 and pp U 2 are submitted by two users U 1 and U 2 as (U L 1 , U R 1 ) and (U L 2 , U R 2 ), respectively, the comparison of pp U 1 and pp U 2 can be performed by computing an inner product. To be precise, U L 1 , U R 2 = 1 is equivalent to pp U 1 ≤ pp U 2 . For example, pp U 1 = 15 is encoded as we are ready to design a privacy-preserving matching algorithm. To submit a bid, a user U first encrypts the bid using FHIPE [50] with a secret key sk and random α, β ∈ Z q as follows: If U wants to sell electricity, U submits an encrypted bid as a selling bid. Then, U is added to the seller set S, and the pair (E L (U L ), E R (U R )) is added to the min-heap. If U's bid is a buying bid, U is added to B, and (E L (U L ), E R (U R )) is added to the max-heap. The bid values in these heaps must be maintained as ciphertexts. We denote these two encrypted heaps as EH S and EH B . We implemented a heap as an array of elements, where each heap element is a structure consisting of an encrypted bid and auxiliary data. When an encrypted bid (E L (U L ), E R (U R )) is added to either EH S or EH B , the encrypted bids must be compared in the ciphertext domain. This is possible by performing an FHIPE decryption operation.
) be the encrypted bids of U 1 and U 2 , respectively. We have seen in Section 2.
This operation enables anyone who possesses the public parameters op and ciphertext (E L (U L 1 ), E R (U R 2 )) to compare pp U 1 and pp U 2 . Note that "Decrypt" does not mean recovering either U L 1 or U R 2 . Therefore, the comparison of E L (U L 1 ) and E R (U R 2 ) is possible without revealing their actual values. As a more intuitive notation, we will use the notation COMP( ) hereafter, which returns 1 when pp U 1 ≤ pp U 2 . Algorithm 1 is the procedure INSERT for inserting a new element into an encrypted min-heap using COMP. As in a typical complete binary tree implementation, the root node is placed at EH S [1]. The left and right children of . It is the same as the legacy heap operation, except that elements are compared over the ciphertext domain. Similarly, the procedure REMOVEMIN(EH S ) for removing the top element, i.e., the minimum, from the encrypted heap EH S is defined in a straightforward way. Heap operations for an encrypted max-heap are defined in an analogous way. Algorithm 2 is the procedure for finding a possible match.

Privacy-Preserving Energy Trading Protocol
In this subsection, we present the proposed privacy-preserving energy trading protocol. The protocol comprises three stages: the setup, bidding and matching, and trading stages. Figure 2 shows the setup stage of our protocol, which begins with the DSO performing the Setup algorithm of FHIPE. The DSO generates public parameters op and a secret key sk. In addition, a smart contract for peer matching is created on the blockchain with op. The validity of this smart contract can be verified by any party because op is open to the public. When a user connects a smart meter to the DSO's network, a setup request is generated and forwarded to the DSO. When the DSO receives this request, the pair (op, sk) is sent to the smart meter. The address of the smart contract is also sent to the smart meter. When the smart meter successfully receives the (op, sk) pair and the smart contract address, it notifies the user of the setup completion.

Algorithm 1 INSERT procedure for encrypted min-heap EH S .
Input: E L (U L ), E R (U R ), auxiliary data Output: none 1: idx ←(size of (EH S ))+1 Insert the new item as the last leaf node.
Perform upheap to restore the heap-order. 6:    Figure 3 demonstrates the bidding and matching stage. When users want to trade energy, they provide the smart meter with the details of the desired trade, i.e., the intent to buy or sell the electrical power, power amount, and price per unit, which we denote as intent, pa ∈ Z, and pp ∈ P, respectively, where P is the set of valid bids. The smart meter randomly generates a one-time identifier OID, which can be considered a pseudonym for privacy. Then, the relation between U ID and OID is registered to the DSO for this session, where U ID is the permanent ID of the user. pp is encoded into two |P|-dimensional vectors U L and U R using the encoding method explained in Section 4.1. These two vectors are encrypted using the FHIPE operations as follows: E L (U L ) ← LeftEncrypt(sk, α, U L ) and E R (U R ) ← RightEncrypt(sk, β, U R ). We will use a simplified notation EPP ← E(α, β, pp) to cover the entire vector encoding and FHIPE encryption procedures, i.e., EPP = (E L (U L ), E R (U R )). In addition, a hash function H is computed to commit to pa, pp, OID, α, and β with a random number r. The smart meter submits the encrypted bid EPP, together with intent, OID, and the commitment c to the blockchain by calling the smart contract created by the DSO in the setup phase. Many smart meters submit their encrypted bids similarly. The blockchain maintains EH S and EH B to manage these bids. Whenever a new bid EPP is received, either EH S or EH B is updated according to Algorithm 1, where auxiliary data contain the intent, OID, and c, corresponding to EPP. For simplicity, we denoted this operation as INSERT(EPP) in Figure 3. We denoted the encrypted bid, intent, OID, and c submitted by another smart meter as EPP , intent , OID , and c , respectively, to distinguish them from the ones submitted from U's smart meter. These data are also inserted into either EH S or EH B according to their intent value. The submission and insertion of encrypted bids and auxiliary data are performed continuously at the request of smart meters. When both EH S and EH B are nonempty and a trigger condition is satisfied, a matching operation is performed on the blockchain using Algorithm 2. With regard to the trigger condition, we may consider various cases. For example, the matching may be performed whenever a new bid is submitted. Matching may also be performed periodically for the waiting bids. If the matching is successful, the encrypted bids and auxiliary data of S m and B M are returned by Algorithm 2. Blockchain nodes forward these data to the appropriate smart meters, and each of the two smart meters notifies its user that it was selected for trading. The DSO also obtains the information about the matched users. For simplicity, we will use subscripts S and B to represent a matched seller and buyer, respectively, i.e., the auxiliary data for the matched seller and buyer are (intent S , OID S , c S ) and (intent B , OID B , c B ), respectively. Their encrypted bids will be written as EPP S and EPP B , i.e.,  Figure 4 demonstrates the trading stage. Let U S and U B be the two matched users with OID S and OID B , and let SM S and SM B be their smart meters, respectively. When a smart meter is informed by the blockchain that its OID has been selected for trading, it sends the DSO all the data for opening the commitment. For example, SM S transmits OID S , pa S , pp S , α S , β S , and r S . The DSO verifies that these values are the same as those committed at the bidding and matching stage by comparing the hash value H(pa S , pp S , OID S , α S , β S , r S ) with the corresponding commitment c S . The DSO also verifies that the price pp S has been appropriately encoded in the encrypted bid EPP S by comparing EPP S with a reproduced ciphertext E(α S , β S , pp S ). Similar verifications are repeated for c B and EPP B . The DSO then decides a negotiated price PP according to a predefined policy (e.g., the average of pp S and pp B .) The DSO forwards all the data received from SM B to SM S , and vice versa. PP is also sent to the two smart meters. After verifying the other party's c and EPP, each smart meter verifies that PP conforms to the price-decision policy. The DSO and two smart meters compute the trading amount PA ← min(pa S , pa B ). If all verifications are successful and PA is successfully decided, the smart meters send an "ok" message to the DSO. Then, SM S feeds energy to the energy storage, and SM B consumes the energy provided by the energy storage. The energy storage reports the amounts of fed and consumed energy to the DSO, as well as the identifiers SM S and SM B of the corresponding smart meters. The DSO combines this information and the stored (U ID, OID) relations to identify U S and U B and adjusts their account balances. The two users U S and U B are notified that their balances were updated.

Simulation and Performance Analysis
In this section, we verify the feasibility of the proposed system by implementing a prototype. To simulate the system illustrated in Figure 1, we implemented a DSO, private Ethereum blockchain, and smart meter. The DSO was implemented on a desktop server with an Intel Core i7-7700 CPU (3.60 GHz) and 16 GB RAM, and the private Ethereum blockchain was implemented on a desktop server with the same configuration. To simulate a smart meter, we used a Raspberry Pi 2 with an ARM Coretex-A7 quad-core CPU (900 MHz) and 1 GB RAM. The software for the DSO and smart meter was implemented in the C++ programming language, and the blockchain codes were implemented in the Solidity and Go languages. Figure 5 illustrates the internal components of the DSO, blockchain, and smart meter. The DSO contains storage module to store the open parameter op, secret key sk, (U ID, OID) pairs, and contract results to calculate the charges associated with users. The blockchain nodes provide storage to maintain two encrypted heaps EH S and EH B . The smart meter contains a storage module to store op, sk, permanent U ID, smart contract address, and the session information including the one-time identifier OID, bid (pa, pp), and the randomizers (α, β, r) for hiding pp and pa. The smart meter must be equipped with a measurement module. Because the smart meter feeds and receives energy, it should be bi-directional. However, we did not equip the smart meter with the actual power measurement module in our implementation as power measurement was not a primary concern in our experiment. Finally, each party contains an FHIPE module to perform cryptographic operations and a network module to communicate with others. Figure 5 also shows the data flows between the internal components in each stage. The data flows in the setup stage, bidding and matching stage, and the trading stage are shown as blue, red, and green lines, respectively. Most of the data flows depicted in Figure 5 are straightforward according to the protocol description in the previous section. Therefore, we focus on the data exchange involving the FHIPE modules below. Because the cryptographic operations performed by the three parties are different, their FHIPE modules contain different algorithms. Specifically, the DSO performs Setup in the setup stage (Figure 2), producing (op, sk). The DSO also performs LeftEncrypt and RightEncrypt for the verification of encrypted bids in the trading stage ( Figure 4). Its FHIPE module takes (α S , β S , pp S ) and (α B , β B , pp B ) as input and produces EPP S and EPP B to be compared with those received from the blockchain in the bidding and matching stage. The FHIPE module in the smart meter performs LeftEncrypt and RightEncrypt operations for generating its encrypted bid EPP in the bidding and matching stage ( Figure 3) and verifying the counterpart's bid (α , β , pp , pa ) in the trading stage ( Figure 4). The FHIPE module in the blockchain repeatedly performs COMP, i.e., Decrypt, for the INSERT and MATCHING operations in the bidding and matching stage (Figure 3). The Decrypt operation requires pairing computation e. We used an optimal Ate pairing [53] with a pairing-friendly Barreto-Naehrig (BN) curve [54], as defined by Ethereum.
According to Section 2.3, the Setup, LeftEncrypt, and RightEncrypt operations performed by the DSO and smart meter require the implementation of group operations on G 1 and G 2 . To be precise, these operations are point operations on a pairing-friendly BN curve because G 1 and G 2 are BN curve groups that enable pairing operations on the blockchain. To implement the group operations, we also must implement the underlying finite field operations and big number operations. We used the pairing-based cryptography library (MCL) [55], for elliptic curve operations, the GNU Multiple Precision Arithmetic Library (GMP) [56], for big number arithmetic operations, and the library for doing number theory (NTL) [57], for operations over a finite field, vector, and matrix. The MCL library supports optimizations for BN curves in two layers. First, it supports the generalized lazy reduction technique and the new squaring formula proposed in Reference [58] for the underlying finite field. Second, in a higher layer, it supports an efficient scalar multiplication method using the skew Frobenius map on BN curves [59]. For the smart meter, we implemented the FHIPE module, applying these optimization methods. For the DSO, we adopted the FHIPE module in Reference [60], where the above optimization methods, as well as parallel processing, were applied. For the Decrypt operation performed by the blockchain, we used the pre-compiled contract provided by Ethereum. Now, we present our experimental results. Table 1 summarizes the performance of FHIPE operations by each party for |P| = 10, 20, 30, 40, and 50, where |P| is the number of possible choices for power price per unit, i.e., the dimension of the left and right vectors. The values in the table are the averages of 1000 iterations for each parameter combination. We observed that the smart meter required significantly more time than the DSO for performing the same operations, i.e., LeftEncrypt and RightEncrypt. For example, when |P| = 10, LeftEncrypt in the smart meter required 62.040 milliseconds, but the same operation in DSO was performed in 0.120 ms, which is 0.19% of the time consumed by the smart meter. RightEncrypt consumed 351.538 ms in the smart meter and 0.566 ms in the DSO. The DSO required only 0.16% of the time required by the smart meter because the smart meter resource is very constrained compared to the DSO, and an additional optimization method, i.e., parallel processing, was applied to the DSO. However, it must be noted that all operations were completed in less than 2 s, even in the smart meter. Next, we analyzed the performance of the proposed protocol. First, we evaluated the bidding and matching stage by measuring the transaction throughput, where a transaction covers the following portion of Figure 3: the smart meter's encrypting a bid into EPP, computing the commitment c, and sending intent, EPP, OID, and c to the blockchain, and a blockchain node's mining a block containing the execution of INSERT and MATCHING procedure, and sending the result back to the smart meter. In the experiment, we considered two setups. For the first setup, we measured the throughput with a single smart meter. The second and third columns in Table 2 present the experimental result in two units: transactions per second (tps) and kilobits per second (kbps). The values are the averages for 1000 bids, where the bid values were randomly selected from P, and the intent to either buy or sell was also randomly selected for each bid. The results indicate that an entire transaction is completed in roughly a second when |P| = 10 and in a little more than 4 s even when |P| = 50. The second setup is for multiple smart meters. Recall that in the first setup, the measured time covered the operations for both the smart meter and the blockchain. However, in a more realistic situation, the blockchain does not have to wait until a smart meter completes its task. Instead, it is reasonable to assume that many smart meters generate encrypted bids in parallel, and the blockchain continues its transactions without stalling. Therefore, to simulate this situation, we pre-generated 1000 bids and fed them to the blockchain. According to the experimental results presented in the fourth and fifth columns of the table, when |P| = 10, the throughput was doubled compared to the single smart meter case. When |P| = 50, the throughput increased by 41%. For reference, we also presented the measured throughputs when the bid protection was not applied, i.e., the bids were not encrypted. The last two columns of Table 2 show that the transactions were performed up to 13.712/0.330 ≈ 41.55 times faster when the bidding and matching stage was implemented without encryption.
We also analyzed the Ethereum gas consumption in the bidding and matching stage of the proposed protocol. In the protocol, the two dominant operations that consume gas are heap node creation and COMP operation. First, when an encrypted bid is inserted into an encrypted heap according to Algorithm 1, a new leaf node containing (EPP, intent, OID, c) is created, which requires non-negligible memory, thereby consuming gas. Second, according to the specification of go-ethereum [61], which is an EVM implemented with the Go language, a combined pairing operation involving an n-dimensional vector consumes 80,000n + 100,000 gas [62]. In our case, a COMP operation requires a combined pairing operation with n = |P| and some additional operations. The COMP operation is used to manage two encrypted heaps, EH S and EH B , i.e., it is repeatedly used for the INSERT and MATCHING procedures, as shown in Algorithm 1 and Algorithm 2. Although we did not demonstrate an explicit algorithm, the REMOVEMIN procedure also repeatedly calls COMP. Table 3 details the gas consumption of these two dominating operations. We measured the consumed gas for 100 iterations, and the values presented in the table are the averages. It can be inferred from the experimental result that the gas consumption of heap node creation increased by a similar amount each time |P| was increased by 10. For example, the difference in gas consumption between |P| = 10 and |P| = 20 was 1,334,272, and the difference between |P| = 20 and |P| = 30 was 1,334,236. We also observe that the gas consumption of COMP was slightly greater than 80,000 × |P| + 100,000. Table 3. Amount of gas consumed to perform a heap node creation and COMP operation. Regarding the performance of the trading stage, the dominant operations for this stage are LeftEncrypt and RightEncrypt operations of the DSO and two smart meters, because other operations, such as hash computation, are negligible. As the operations of the two smart meters are independently performed in parallel, the time required for this stage is roughly 2 × (DSO's left and right encryption time) + (smart meter's left and right encryption time). It is roughly 415 ms for |P| = 10 and 1.88 s for |P| = 50 according to Table 1.

Range of Price Consumed Gas Heap Node Creation COMP
For an objective evaluation of the performance of the proposed system, we compare it with the performance of previous blockchain-based privacy-perserving applications. Because these applications were not for P2P energy trading, direct comparison with the proposed system is not possible. However, they can be the reference for the performance of our system. First, we examine Zerocash [22] that ensures user anonymity for cryptocurrency transfer. The main cryptographic primitive of Zerocash is zero-knowledge Succinct Non-interactive Arguments of Knowledge (zk-SNARKs), which are composed of KeyGen, Prove, and Verify algorithms. In Reference [22], the following six functions for Zerocash were defined by using these algorithms; Setup, CreateAddress, Mint, Pour, VerifyTransaction, and Receive. Among them, the Pour function actually transfers cryptocurrency. According to the experimental results on an Intel i7-4770 @ 3.40 GHZ CPU and 16 GB RAM, the Prove algorithm needed 2 min 2 s, while the Verify algorithm needed only 5.4 ms [22]. Because the dominant operation of the Pour function is Prove, a Pour operation needed 2 min 2 s. In contrast, the dominant blockchain operation in the proposed system is COMP, which is based on the similar operation to the underlying operation of Verify of Zerocash. We already verified in Tables 1 and 2 that COMP is completed in tens of milliseconds and an entire transaction is completed in a few seconds.
Next, we examine the performance of Hawk [24]. Hawk is a more general framework for building privacy-preserving smart contracts. As in Zerocash, the KeyGen, Prove and Verify algorithms were defined for zk-SNARKs, and they were used to design Pour, Freeze, Compute, and Finalize operations. Among the applications of Hawk presented in Reference [24], we may refer to the auction application. This application is composed of user-side and manager-side operations. According to the experimental results on Amazon EC2 r3.8xlarge virtual machines in a 27 GB, 4-core environment, the manager-side Finalize operation for selecting a winner required 469.7 s for 100 participants. According to Table 2

Security Analysis
In this section, we examine whether the proposed system satisfies the security goals defined in Section 3.2.

•
User Privacy: Users are identified on the blockchain with the one-time pseudonym OID of their smart meter for each trading session. Because OID is an ephemeral identifier, the other peers connected to the blockchain do not learn the user's permanent identifier U ID. In addition, the activities of the same user in two different sessions cannot be linked because the OID is refreshed every session. The U ID is revealed to the DSO through the initiation message from the smart meter to the DSO in Figure 3, but this is not a violation of our security goal. • DSO Privacy: What the blockchain nodes see in the bidding and matching stage are the tuples (intent, EPP, OID, c) for each bid and the matching results. Although EPP and c contain the pp and pa for the bid, they are protected by the FHIPE and cryptographic hash function. From the one-way property of the cryptographic hash function, it is evident that the pa for the bid is protected. The proof that pp is well protected will be presented in the Appendix A. In the trading stage, pa and pp values are opened to the two smart meters, which is necessary for energy trading. However, these values are protected from the other parties because all data communication lines are protected by an end-to-end encryption mechanism according to the system model in Section 3.1.

•
Verifiability of transactions and integrity of bids: Because the blockchain is honest-but-curious, it honestly performs heap updates (Algorithm 1) and peer matching (Algorithm 2). Therefore, the seller with the minimum bid and the buyer with the maximum bid are always matched with each other. Whether the operations are being performed correctly is verifiable by any user connected to a blockchain node, although the actual contents of the bids are protected by FHIPE. With regard to the integrity of a bid, the blockchain guarantees integrity by nature. Therefore, no one can modify the data on the blockchain, such as intent, EPP, OID, and c, without properly calling smart contracts. According to Figure 3, c B on the blockchain is sent to SM S . Therefore, if the DSO attempts to modify either pa B or pp B in Figure 4, SM S will notice this modification through the verification of c B . Additionally, by comparing EPP B with E(α B , β B , pp B ), SM S can verify that pp B had been properly encoded in the EPP B that was used for comparison and matching. SM B can verify the integrity of pa S and pp S in the same way. • Nonrepudiation of bids: Because smart meters are tamper-proof, the users cannot revoke their bids by manipulating the smart meter. Furthermore, once the encrypted bid EPP and commitment c are uploaded on the blockchain, their integrity is protected by the blockchain. Because c is bound to pa and pp using a cryptographic hash function, neither pa nor pp can be denied.

Discussion
In this paper, we proposed a P2P energy trading system on a blockchain where peer matching is performed on the encrypted bids by a functional encryption-based smart contract. We also verified the feasibility of the proposed system by implementing a prototype composed of smart meters, a DSO, and private Ethereum blockchain. However, the system could be improved in several ways. First, we only considered the case where new encrypted bids are inserted into the heap. However, it would be desirable if there were a mechanism to remove a bid when it expires. Second, the dimension of the vectors encoding bid values is proportional to the range of possible bid values. If we can use a more compact encoding, e.g., a binary encoding, we can significantly reduce the time and gas consumption for bid generation and peer-matching. Finally, the smart meter performance can be improved by adopting more implementation optimization. We shall address these issues in future research.
The proposed method provides the means to hide the electricity price and amount contained in a bid, but it does not tell a prosumer what price to bid. Many relevant studies have been conducted to improve the energy management and optimize the costs. Various techniques, such as fuzzy logic [63], cooperative game theory [64], genetic algorithms [65], and deep recurrent neural networks [66], have been proposed. Specifically, a reinforcement learning-based strategy (Fuzzy Q-learning) was recently proposed to improve the decision-making process of P2P power trading [67]. These strategies may be combined with our privacy-enhancing method.
Furthermore, the proposed system may be combined with other privacy-preserving techniques for smart grids. In recent years, extensive research on smart meter data obfuscation has been conducted to prevent the leakage of smart meter readings [37][38][39]. However, these methods are adding noise to the measurements; thus, they affect the billing and control functionalities [68]. Therefore, many studies have proposed the use of batteries to mask the energy-consumption statistics [68][69][70]. The advantage of using batteries is that they not only improve privacy but also reduce energy costs when charging and discharging are cleverly controlled. For this purpose, multiobjective optimization methods have been proposed to simultaneously minimize privacy leakage and energy cost [69,70]. However, these proposals assume that energy prices are set up by the utility company, and the prosumer's active pricing mechanism with P2P trading has not been considered. Therefore, it would be very interesting if we combined the proposed system with these battery-enabled data protection methods. This may ensure privacy in two aspects: protection of power-consumption and P2P transaction data.

Conflicts of Interest:
The authors declare no conflict of interest.

Abbreviations
The following abbreviations are used in this manuscript:

Appendix A. Security Proof
In this section, we prove that pp is well protected by FHIPE. We first review the security properties of the FHIPE scheme Π IPE in Reference [50]. Next, we prove the security of the proposed protocol using reduction from Π IPE .
Appendix A.1. Review of the Security of the FHIPE scheme Π IPE Previous works on inner product encryption, including Π IPE [50] we used considered an indistinguishability notion of security [50]. We review the security notion of Π IPE defined in Reference [50]. Specifically, an experiment between a challenger and an adversary A that can make the left and right encryption oracle queries is defined as follows. [50]). Let b ∈ {0, 1}. The challenger computes (op, sk) ← Setup(1 λ ), gives op to the adversary A, and then responds to each oracle query type made by A in the following manner.
-Left encryption oracle. On input a pair of vectors x 0 , x 1 ∈ Z n q \ {0}, the challenger computes and returns E L (x b ) ← LeftEncrypt(sk, α, x b ) using a random element α ∈ Z q . -Right encryption oracle. On input a pair of vectors y 0 , y 1 ∈ Z n q \ {0}, the challenger computes and returns E R (y b ) ← RightEncrypt(sk, β, y b ) using a random element β ∈ Z q . Eventually, A outputs a bit b , which is also the output of the experiment, denoted by Then, the security of an FHIPE scheme is defined using an indistinguishability notion as follows: Definition A2 (Admissibility of A [50]). For an adversary A, let Q L and Q R be the total number of left and right encryption oracle queries made by A, respectively. For b ∈ {0, 1}, let x ∈ Z n q \{0} be the corresponding vectors that A submits to the left and right encryption oracles, respectively. We say that A is admissible if for all i ∈ {1, . . . , Q L } and j ∈ {1, . . . , Q R }, we have that: Definition A3 (IND-Security for IPE [50]). We define an inner product encryption scheme denoted as Π IPE = (Setup, LeftEncrypt, RightEncrypt, Decrypt) as fully-secure if for all efficient and admissible adversaries A: where negl(λ) denotes a negligible function in λ.
Theorem A1 ( [50]). The inner product encryption scheme Π IPE is IND-secure in the generic group model. Remark A1. The original statement in Theorem 7 in Reference [50] is that the inner product encryption scheme Π IPE is SIM-secure in the generic group model. It was also remarked in Remark 5 in Reference [50] that a SIM-secure IPE scheme is also IND-secure. We merged these two statements into Theorem A1. See Reference [50] for more information on the SIM-security and a generic group model.

Appendix A.2. Proof of the Security of the Proposed System
We denote the proposed privacy-preserving P2P energy trading protocol by Π PPET . Our threat model in Section 3.2 assumed that a blockchain is honest-but-curious. That is, the blockchain nodes might attempt to extract useful information regarding the power price pp of a user. Regarding the security against the honest-but-curious blockchain, we define an indistinguishability notion of security for Π PPET . Then, we prove the IND-security of Π PPET using that of Π IPE . Our proof is a modification of the security proof of two-input functional encryption in the full version of Reference [50].
First, we define the following experiment between a challenger and an adversary A * that can make two oracle queries, LeftEncrypt and RightEncrypt.
). Let b ∈ {0, 1}. The challenger computes (op, sk) ← Setup(1 λ ) using Π IPE , gives op to the adversary A * , and then responds to each oracle query type made by A * in the following manner.
-LeftEncrypt oracle. On input a pair of two messages x 0 , x 1 ∈ {z, . . . , z + (n − 1)} for a positive integer z, the challenger encodes x 0 , x 1 to U L 0 , U L 1 ∈ Z n q \ {0} according to the description of Section 4.1, computes and returns E L (U L b ) ← LeftEncrypt(sk, α, U L b ) using a random element α ∈ Z q . -RightEncrypt oracle. On input a pair of two messages y 0 , y 1 ∈ {z, . . . , z + (n − 1)} for a positive integer z, the challenger encodes y 0 , y 1 to U R 0 , U R 1 ∈ Z n q \ {0} according to the description of Section 4.1, computes and returns E R (U R b ) ← RightEncrypt(sk, β, U R b ) using a random element β ∈ Z q . Eventually, A * outputs a bit b , which is also the output of the experiment, denoted by Expt ∈ {z, . . . , z + (n − 1)} be the corresponding messages that A * submits to the LeftEncrypt and RightEncrypt oracles, respectively. We say that A * is admissible if for all i ∈ {1, . . . , Q L } and j ∈ {1, . . . , Q R }, we have that: where f is a function that computes the inner product of the two vectors encoded from the two input integers, i.e., f (x Theorem A2. If Π IPE is IND-secure (according to Definition A3) in the generic group model, then Π PPET constructed with Π IPE is IND-secure (according to Definition A6) in the generic group model.

Proof of Theorem A2.
To perform a reduction proof of the security for Π PPET , assume that there exists an efficient and admissible adversary A * . We will show that A * can be used as a subroutine for the adversary A. That is, we design A that simulates the LeftEncrypt and RightEncrypt oracles of Expt However, the construction of A contradicts Theorem A1, which states that an efficient and admissible A with non-negligible advantage does not exist. This completes the proof. Return b .

5:
Wait until A * submits a query Q. 6: if Q = (x 0 , x 1 ) is a LeftEncrypt oracle query then 7: Encode x 0 , x 1 ∈ {z, . . . , z + (n − 1)} to U L 0 , U L 1 ∈ Z n q \{0}. z is a positive integer and U L b is a vector encoded according to the description of Section 4.1. and receive E L (U L b ).

11:
Encode y 0 , y 1 ∈ {z, . . . , z + (n − 1)} to U R 0 , U R 1 ∈ Z n q \{0}. z is a positive integer and U R b is a vector encoded according to the description of Section 4.1. and receive E R (U R b ).

13:
Provide E R (U R b ) to A * .