A Secure and Efficient Energy Trading Model Using Blockchain for a 5G-Deployed Smart Community

Department of Computer Science, COMSATS University Islamabad, Islamabad 44000, Pakistan School of Computer Science, University of Technology Sydney, Ultimo, NSW 2007, Australia School of Information Technology, Illinois State University USA, Normal, IL 61761, USA Department of Information Technology, College of Computer, Qassim University, Buraydah, Saudi Arabia Department of CSE, University of Engineering and Technology Peshawar, Peshawar 25000, Pakistan Hamdard Institute of Engineering and Technology, Hamdard University, Islamabad 44000, Pakistan


Introduction
Globally, the residential smart homes' market size is expected to be more than $50 billion before the year 2023. It is also observed that the number of households, which migrates to smart homes, has increased at an annual average growth rate of 14% from 2017. The increase in the number of smart homes has two impacts: benefits and issues. The benefits of the increase in the smart homes include saving of money, time, and energy as well as increase in the user comfort. However, privacy and security challenges increase. In smart grids, a nanogrid is a smart home that has energy storage and generation sources, e.g., small scale wind turbines and photovoltaics [1]. The generated energy is stored using batteries and plug-in Electric Vehicles (EVs). A group of connected nanogrids within nearby neighborhoods establishes a microgrid, which allows local energy trading between the smart homes. There are two approaches to perform energy trading in the power system: centralized and distributed. The centralized approach is also known as the traditional energy trading system. It is a conventional approach that the smart grid uses for energy management. In the approach, a central control unit is used that manages, processes, and regulates energy transactions. However, this approach has some challenges, such as a single point of failure and security-privacy-related problems. Among the solutions provided to solve the centralized approach problems is the introduction of a distributed model. In [2], the authors propose a Peer-to-Peer (P2P) method for smart grid operations. The work provides an overview of the proposed strategies for wireless communication, distributed P2P energy trading, and P2P power grid control unit that enables the smart grid operations. The authors in [3] propose an energy trading model between islanded microgrids using distributed convex optimization techniques. In the model, a subgradient-based cost minimization algorithm is implemented, which converges to an optimal solution with minimum communication overhead. In [4], the authors propose a virtual framework incorporated with communication constraints, which also considers its impact on energy trading cost. The authors modify the distributed energy trading framework considered in the literature with more communication constraints, where the impact of the resulting virtualized microgrid framework is investigated on the overall trading costs. The authors in [5] propose a hierarchical framework to identify and categorize the key technologies and elements involved in P2P energy trading. The framework is developed and simulated using game theory. In distributed energy systems, adversary users heavily threaten the security and privacy of the system through many malicious exploitations [6], e.g., node impersonation, falsification, privacy leakages, and advertising fraudulent energy services.
Environmental pollution and climate change are major issues that disturb the Smart Communities (SCs). These issues are caused due to a tremendous increase in greenhouse gas emissions generated from fossil fuel-based vehicles. The introduction of EVs is among the solutions that are generally being accepted to resolve the environmental pollution problems [7]. As a long-term automotive technology, EVs are becoming popular in minimizing the total dependency on fossil fuel-based vehicles and reducing the emissions of greenhouse gas. However, as the number of EVs increases, the unorganized charging of EVs creates a new peak load. The reason is that it causes a serious energy instability problem in the distributed energy system. In order to overcome this issue, the capacity of power delivery is increased to solve the needs of new peak demand that is generated by the unorganized EVs. However, this results in a huge infrastructure cost. Moreover, a smart grid-based method is developed to enable EVs to communicate with the power grid and manage their charging needs. However, this process can cause a single point of failure as it is implemented in a centralized model. In addition, demand-supply mismatch and lack of trust challenges are still not resolved in the energy system. Another solution to manage energy for both residential homes and EVs is by exploring load forecasting models. In [8], the authors propose a Recurrent Inception Convolution Neural Network (RICNN) that combines 1-Dimensional CNN (1-D CNN) and Recurrent Neural Network (RNN) to forecast consumers' energy usage. The 1-D convolution inception module is used to calibrate the time forecasting, and the hidden state vector values are computed from the nearest time steps. The model is verified in terms of energy usage data of three large energy distribution complexes in South Korea. The authors in [9] present a probabilistic forecasting model for consumers to predict uncertainty and variability of the future load. In the model, Long Short-Term Memory (LSTM) is adopted to learn both the short-term and long-term dependencies among the load dataset. Pinball loss is used for training the parameters. The experiments are conducted using an open source dataset of Ireland. However, the energy management models, i.e., load forecasting models, use a centralized approach, which inherited its challenges.
Currently, as a result of the high benefit of Fifth-Generation (5G) technology against the previous-generation technologies (first generation-fourth generation) in terms of the number of network connections, power consumption, security, reliability, and transfer speed, various countries across the world have adopted it [10,11]. Based on [12], the 5G network is found to be very flexible and multifunctional. Therefore, different problems are solved in terms of power application and cost analysis. The 5G technology provides intelligence, sensing, and convergence of pervasive broadband that makes a great change in the SC and smart industrial markets. Using 5G technology in a smart grid, novel business frameworks are created at both the consumer and utility sides with fog and edge computing together with intelligent and automated controls [13]. The technology depends on very small cell functions for its slicing network that gives various advantages at the transmission side and the distribution side to perform on in a ubiquitous fashion. Therefore, the need for 5G in smart grids and other places where new power grids can benefit the access of information is highly required. A lot of research works have been conducted to explore the potential benefit of using 5G technology for the demand response management and Internet of Things in smart grids [14,15]. However, the full potentials of 5G technology in smart grids are not utilized.
To address the above mentioned challenges, an efficient solution is required to ensure irrevocable, transparent, and distributed digital transactions. Blockchain technology is a distributed network that is able to solve the problems associated with the centralized approach [16,17]. It addresses the problems in a decentralized and distributed manner. Using the blockchain, transactions are stored in a decentralized system [18]. The network's nodes in the blockchain maintain all of the executed transactions. Thus, compromising 2 Wireless Communications and Mobile Computing the security of the network is merely not possible as it needs to control the miners that maintain the entire network security [19]. The blockchain users that are responsible for securing, verifying, and adding transactions into blocks of the network are called miners or validators. The mining process is performed according to the rules given by a consensus mechanism [20][21][22]. A consensus mechanism in the blockchain is used to permit untrusted peers to agree on the global state of the network [23]. In the blockchain, each block is cryptographically linked with its prior block forming a secured chain [24]. However, the lack of trust and privacy of users and demand-supply mismatch are still not fully solved using blockchain. This research work proposes a distributed, verifiable, anonymous, and privacy-preserving energy trading system. The system enables users to trade and communicate securely using blockchain in 5G network. In the system, a reputationbased privacy-preserving EVs' matching scheme is proposed. Also, the proposed system incorporates identitybased encryption (ID-based encryption) and homomorphic encryption (HE) techniques to protect the privacy of the transactions and users, respectively. An energy allocation model is also proposed in order to motivate residential prosumers to participate in the energy trading. The model is developed based on the consumers' historical contributions and the type of their transactions.
The remainder of this paper is structured as follows. Sections 2 and 3 present the related work and problem statement, respectively. Sections 4, 5, 6, 7, and 8 discuss the proposed system model, proposed solutions, proposed methodology, and its security and privacy analyses. Section 9 presents the simulation results and their discussion while the conclusion and future work are given in Section 10.

Related Work
In this section, a detailed literature review is presented, which is divided into energy trading and EVs' charging load forecasting.

Energy Trading.
In [19], the authors propose a localized P2P energy trading model for EVs using consortium blockchain. The model uses an iterative double auction mechanism to optimize price and quantity of energy during trading. Furthermore, the goal of the model is to maximize social welfare and to protect EVs' privacy. The authors in [25] analyze the effects of the EV's charging position. The results show that charging at foreign stations can cause penetration of privacy far more than charging at home. The authors in [26] propose an effective privacy reservation system for EVs and charging stations. The system also provides penalty and authentication mechanisms. However, the system is centrally controlled and managed, which makes the management more challenging when the number of users increases. In [27], the authors implement an integrated system that combines charging prioritization, encryption mechanism, and payment framework for the dynamic charging model. Computational and communication overheads are reduced in the system. However, the system does not eliminate the issue of a single point of failure.
In [28], the authors develop an accurate, confidential, and automated model for charging stations' selection based on EVs' distance and energy cost. They also implement a blockchain-based payment mechanism where EVs send their charging requests and charging stations send proposals, which is similar to an auction mechanism. However, increasing the overall system's efficiency is not considered in the model. In [29], the authors propose a secure communication model that has a privacy-preserving payment process for EVs' monitoring system. In addition, communication and computational overheads are reduced in the model. However, a mechanism to authenticate and verify users in the model is not included. In [30], a new communication model for on-the-move charging of EVs based on a subscribe/publish method for dissemination of appropriate data to EVs is proposed. The model allows the EVs' users to make optimal decisions about where to charge their EVs. In [31], a three-party model that is integrated with EVs in a smart grid context is proposed. In the model, two schemes are also proposed that focus on EV-centered and SC-centered. Furthermore, a demand-on-schedule energy management system is proposed. The system combines SCs and EVs to achieve an efficient resource management system in the power generation network. The model allows complex and flexible interactions between energy grids, SCs, and EVs.

Electric
Vehicles' Charging Load Forecasting. The authors in [32] propose a one-step short-term load forecasting for the EV model using CNN with a niche immunity lion technique. The model is improved by incorporating niche immunity to obtain better forecasting results. As shown in the experimental results, traditional forecasting models have less accuracy than the deep learning models when the dataset is small. Similarly, authors in [33] propose a model for short-term load forecasting by incorporating LSTM in the conventional RNN scheme. LSTM solves the gradient vanishing problem in the RNN network. The authors in [34] propose an LSTM model for electricity load forecasting of individual residential homes.
In [35], the authors propose a system that predicts the daily load of EV charging stations using the Back Propagation Neural Network (BPNN). A fuzzy clustering approach based on the method of transfer closure is implemented to pick the actual load data, which is similar to the predicted data to enhance the predictive precision. However, BPNN causes overfitting and gets trapped into the local minimum easily. Similarly, in [36], the authors propose a short-term load forecasting scheme for EVs' charging stations using Radial Basis Function Neural Networks (RBFNNs). The proposed scheme is modified using the fuzzy control theory [37] to address the issues of trapping into local minimum and overfitting. The experimental results show that the forecasting accuracy increases exponentially. However, the forecasting systems are implemented using a centralized approach, which are prone to privacy-and security-related issues, and a single point of failure.
3.1. Motivation and Problem Statement. The attention of many automobile companies has been attracted to develop EVs as a result of the excessive greenhouse gas emissions from petroleum machines. Concerning this, the automobile companies manufacture a large number of EVs to provide an eco-friendly and sustainable conveyance system. However, this results in an insufficient charging infrastructure to cater to the needs of energy users due to massive penetration of EVs in the SC. Many research works provide solutions to the lingering problems. For example, inefficient allocation of resources, leakage of sensitive information of EVs, and a single point of failure are the problems in the existing works, which are not fully solved. Therefore, improvements in the literature are strongly needed. The authors in [38] propose a model for distributed privacy preserving and efficient matching of charging demander with charging suppliers. This model uses the bichromatic mutual nearest neighbor (BMNN) to address the issue of exposing driving patterns, schedules, and whereabouts of EVs. However, the pieces of information transmitted or received are not verified and not guaranteed to be from legitimate users.
On the other hand, blockchain permits users to have a distributed and decentralized P2P network where nontrusted users communicate verifiably with each other. Several methods to secure P2P energy trading are proposed in the blockchain-based models. In [44], the authors propose an optimal scheduling algorithm for charging Hybrid EVs (HEVs). The model adopts consortium blockchain to ensure the users' privacy and secure the energy trading. In the model, the scheduling algorithm is aimed at reducing energy cost and optimizing the satisfaction function of users while targeting different performance metrics. The targeted metrics include waiting time, EV driving speed, discharging location, and charging entities. The optimization technique used in solving the problem is an improved Nondominated Sorting Genetic Algorithm (NSGA). However, the privacy of transmitted information is not guaranteed using blockchain technology alone [45,46]. The reason is that the contents of all monetary balance and transactions are visible to the public, which allows the information to be easily accessed. Also, consortium blockchain is partially secure and less efficient as compared to other categories of blockchain technology. Similarly, in [39], the authors examine the adaptability of consortium blockchain to set up a stable electricity trading network. The blockchain-based network provides distributed storage and maintenance of the authorized nodes. However, relying on the merits of consortium blockchain cannot guarantee the reliability of the network's security. Also, it does not prevent the information from internal attackers. The authors in [40] propose an effective solution to reduce the excessive operational overhead in the trading model. The overhead increases when nodes are motivated to use local energy out of their self-interest as elaborated in [47]. As a result, it may be tantamount to a high cost of transportation for the trading partners. However, this mechanism decreases the financial benefits of the system. Also, privacy and security of the trading data are overlooked.
In terms of optimal energy allocation, many research works are studied in the literature based on prosumers' reputation. These works use different performance parameters to determine the reputation. The performance metrics used are historical energy supply contribution, rate of past participation of a prosumer, and load demand in the current time interval. The authors in [41,48] propose a contributionbased allocation of energy policy to establish models that simplify energy trading in the electricity markets. In these models, the energy allocator collects excess energy from providers and allocates it to the energy deficit prosumers. However, these models do not consider the starvation level (SL) of consumers and the design of a proper mechanism to detect malicious energy transactions. The authors in [42] propose a novel Starvation-Free Optimal Energy Allocation Policy (SF-OEAP). The model is based on three parameters for prosumers in the smart distributed network of an energy market. The parameters are revenue index, prediction accuracy, and energy starvation. The Distribution System Operator (DSO) collects excess energy from energy generators and performs a fair energy allocation between consumers. However, the authors in [41,42,48] do not consider any mechanism to detect malicious transactions, which plays an important role to determine the reward for the prosumers and make the system free from malicious activities. In spite of the observable advantages of using blockchain [19,39,43] to establish a trustworthy platform, the privacy concern and other related issues still restrict its implementation in energy trading systems. In this study, a mechanism to solve the privacy and security issue and the lack of optimal fairness in energy allocation is proposed. The challenges to be solved also include operational inefficiency of the system, a single point of failure, and absence of an optimal scheduling algorithm for users. The proposed research work is an extension of [49,50]. Table 1 shows the comparison between the proposed model and the existing models.

Research Contributions.
The primary contributions of the proposed work are presented as follows.
(i) A secure energy trading model and an optimal energy scheduling algorithm for users are proposed using blockchain and smart contract. The proposed model ensures that the transaction is verified and it came from a legitimate user (ii) An improved privacy-preserving and EVs' matching mechanism is proposed by integrating the reputations of users. The mechanism helps to prevent exposing the EVs' privacy (iii) A novel method for calculating the reward index (RI) between prosumers is proposed. Furthermore, a Reward-based Starvation-Free Energy Allocation Policy (RSFEAP) algorithm is presented to 4 Wireless Communications and Mobile Computing distribute energy between prosumers. The proposed algorithm motivates prosumers to subjectively share their resources. It also ensures efficient and stable operations of the network as well as establishes a fair trading environment (iv) ID-based encryption and HE techniques are incorporated into the proposed system to protect the privacy of the transactions and users, respectively (v) A short-term load forecasting model for EVs' charging using multiple linear regression (MLR) is proposed to accurately plan and manage the uncertainty of EVs' intermittent charging behavior (vi) Simulation study and theoretical analysis are employed to show the effectiveness of the proposed system. Furthermore, the security vulnerabilities of the smart contracts are analyzed to make the system bug-free against attacks

The Proposed System Model
The proposed system model deployed in the 5G network is divided into two components: residential energy prosumers and EVs. The model is discussed in the following sections.

Electric Vehicles' Component.
In Figure 1, the overall system model is presented. More elaboration about the communication devices can be found in [38]. ESEVs receive a charging request from EBEVs and respond them in a distributed fashion. In this component, the selection of ESEVs is based on their reputation points. The reputation points are submitted to and retrieved from the blockchain. This ensures the integrity of the reputation points and also verifies its source. By considering the reputation points, the EVs' locations are outright hidden. In the model, it is assumed that all EVs are situated within a short proximity. Thus, the EVs' reputation points are considered instead of the distance between EBEVs and ESEVs. When the EVs' selection is complete, the ESEV's location to EBEV is identified using Partially HE (PHE). After the completion of the search and match process, the energy trading takes place using a smart contract along with the monetary process. Additionally, the information of EBEVs and ESEVs is verified and is stored in the blockchain.
Moreover, EVs have more benefits over the conventional vehicles based on oil supply safety, containment of global warming, emissions reduction, and energy savings. However, as the number of EVs increases in SC, the load profile distributed energy network greatly changes [51]. As a result, the power grids' reliability and stability can occur because of the charging demand randomness and the intermittent behavior of renewable energy source [52]. To tackle the aforementioned problem, load forecasting is required. The integration of forecasting models for EVs' charging is a possible method to reduce energy transmission line loss and enhance the usage of local energy consumption as well as improve the advantage of renewable energy development where the generated energy is directly sold to EVs. Therefore, EVs' load forecasting is introduced to properly plan and manage the intermittent charging and discharging behavior of the vehicles.

Homomorphic Encryption.
HE is a cryptographic system, which was first proposed in 1970s [53]. It is an encryption process that allows a specific type of mathematical computation to be executed on a ciphertext, which further generates another ciphertext. Thus, the output of the generated encrypted text matches the plaintext operations as if the operations are performed directly on the plaintext without any sign of distortion or alteration. This method allows users to perform operations on an encrypted data without knowing the real data supplied from the sender or having the public key to decrypt the encrypted message. It also provides the prospect for privacy preservation in many applications, e.g., storing data in cloud, and improving election security and transparency. Furthermore, HE solves the challenges of maintaining the confidentiality of processed and stored data in a database faced by other non-HE techniques. It is subdivided into Fully HE (FHE) and PHE [54]. FHE allows all computations (multiplication and addition) on ciphertext while PHE supports either multiplication or addition. In this paper, Paillier's cryptosystem is used, which is classified under PHE. It is more efficient and simpler than the FHE scheme [55]. The Paillier system has three steps: decryption, 5 Wireless Communications and Mobile Computing encryption, and key generation. The equations of the cryptosystem are adopted from [38].
p and q are two large prime numbers that are selected with the same bit length in the key generation step, setting n = pq and λ = ðp − 1Þðq − 1Þ. μ and g are computed from λ and n, which are μ = ðλ mod n 2 Þ −1 mod n, and g = ðn + 1 Þ. The encryption and decryption keys are defined as ðn, gÞ and ðλ, μÞ, respectively. A random integer rεℤ n is selected when encryption is performed on a plaintext (i.e., Eða, rÞ).
At the encryption step, the data is encrypted using the following equation.
While at the decryption step, the data is decrypted using the following equation.
where LðuÞ = ðu − 1Þ/n. Both encryption and decryption functions must satisfy the following equations.
where a and c are plaintexts.

Adversary
Model. In the proposed model, an Honestbut-Curious (HBC) adversary model is adopted specifically at the privacy-preserving search and match part. The commonly used adversary model in studying privacypreserving matching profile is HBC [56]. The users in this model carefully report and respond to other users' queries.
In this model, we assume that some nodes in the blockchain are malicious nodes, which can attack the system in two ways. ðQ 1 Þ The attacker will try to understand other users' location even though they are not matched ðQ 2 Þ The attacker may try to understand and change reputations of other users to gain advantage of being selected It is further assumed that the attacker has adequate power to breach any node's privacy in the system. Also, the attackers are unable to take over more than 51% of the computational power in the blockchain. It is further assumed that the minority nodes in the network have malicious behavior and are not more than 50%.

4.2.
Residential Energy Component. The residential energy component is also an important component in the proposed system model. This component consists of an aggregator (AG) and a set of participating prosumers ðProsumer 1 , Prosumer 2 , ⋯, Prosumer n Þ in the distributed network. The prosumers in the network are interlinked and share energy using dedicated power-sharing lines. Both AG and prosumers interact and trade energy through the blockchain. It is assumed that in a given time slot, every prosumer is able to produce energy G, and it has a load L. When G j ≥ L j ,   Wireless Communications and Mobile Computing the jth prosumer becomes the energy seller (provider), whereas, when G j < L j , the prosumer becomes the energy buyer (consumer) and purchases energy either from the main grid or another prosumer with surplus energy. AG is an autonomous entity between the seller and buyer that gathers the surplus energy from the energy providers. AG is encouraged to have its own energy storage devices to store energy and maintain the system's stability and reliability, e.g., ultracapacitor and batteries. The sum of surplus energy from providers is given as A typical scenario where consumers request energy from AG is depicted in Figure 1. AG plays a good role in this component as an independent system. It is an equitable entity, which has full control over prosumers. Additionally, AG uses the RSFEAP algorithm to allocate the available energy to consumers, which is collected from the providers and distributed to the consumers. Besides that, AG distributes rewards to prosumers after the collection of all necessary transactions' data, as shown in Figure 2. Moreover, the data used to communicate between AG and prosumers is invariably passed through an encryption mechanism before the communication takes place. The encryption technique used in this component is ID-based encryption. The details of the encryption process are presented in Section 7.1.

The Proposed Solution for Electric Vehicles' Component
In this section, privacy-preserving reputation-based distributed matching, smart contracts, and EVs' charging load forecasting are discussed.

Privacy-Preserving Reputation-Based Distributed
Matching. In this study, a blockchain-based decentralized and distributed reputation system is proposed. The complete layout of the proposed system is given in Algorithm 1. In the system, once EBEV makes a request for charging, the algorithm checks for ESEV that has the highest reputation points without considering the distance. If ESEV with the highest reputation points accepts the charging request from EBEV, then the algorithm matches ESEV with EBEV. Otherwise, ESEV with the second-highest reputation points will be considered by the algorithm. The sequence continues until EBES and ESEV are matched. To preserve the privacy of EVs, ESEVs are chosen based on their reputation points without considering the information on EBEV's whereabouts. After selecting ESEV, communication between the two parties takes place using the Paillier cryptosystem based on homomorphic computation.

Calculating Reputation.
EBEVs submit ratings of ESEV after the energy trading task is completed. Afterwards, the process of calculating reputation points is initiated in the blockchain. At the initial stage, EVs first register themselves and obtain initial reputation and credibility points. These points are publically available for all the involved EVs. The actual reputation is the total accumulated rating provided by the EBEV users for the services received along with the raters' credibility, which are discussed and presented in Section 5.2.2. The usage of the credibility method gives more weight to the reputation points of a rater with higher credibility as compared to the one with less credibility. The mechanism to obtain the EVs' credibility is not extensively discussed in this research. When EBEVs are confirmed to be trustworthy, their credibility increases; otherwise, their credibility decreases.  7 Wireless Communications and Mobile Computing reputation points, which are retrieved from the blockchain. EBEV ensures that the reputation points are verified because they are stored in the blockchain. This method gives a logical approach to hide the ESEV location. Let the ciphertext of a be EðaÞ using the Paillier cryptosystem. Also, an encrypted squared distance computation between an ESEV S j at location loc S j = ðx j , y j Þ and an EBEV D i at location loc D i = ðx i , y i Þ is achieved using the following equations [38].
In the proposed model, each EV has PHE keys to encrypt the transactions between ESEV and EBEV. Furthermore, Algorithms 2 and 3 are inspired from [38], which show the communication between EBEV and ESEV in a privacy-preserved manner.

Smart Contracts of Energy Blockchain.
In a blockchain network, smart contracts are a collection of rules that digitally facilitates, enforces, and verifies the contract made by the participants in the network [57]. The smart contract provides a credible transaction that is made automatically with-out involving a third-party. In addition, the transaction that is performed using a smart contract is traceable, auditable, and irrevocable. The proposed smart contracts in this model, i.e., reputation and energy trading, are discussed in the following sections.

Smart Contract for Energy
Trading. The energy trading smart contract comprises of three essential functions: selling, buying, and creating storage. The selling and buying functions work hand-in-hand, which enable EVs to sell or buy energy. When the energy trading begins, the smart contract whileD not matched with Sdo 4: Find distance of D based on reputation in a privacy 5: preserved manner; 6: ifS i accepts the request then 7: Match D with S i ; 8: Break; 9: i + +; Algorithm 1: Generic-matching function.

Wireless Communications and Mobile Computing
first checks the available credit of EBEV. It is necessary to confirm whether the EBEV user has enough money to purchase energy or not. Afterwards, it also checks whether ESEV has enough energy to sell or not. The smart contract also checks whether EBEV has enough energy storage capacity to accommodate the purchased energy or not. After all conditions are checked and returned true, then the ESEV's account is credited with the digital coin while it is deducted from EBEV's account. On the other hand, the energy from the storage of ESEV is subtracted and is added to the EBEV's storage. The createstorage function allows ESEVs to display the amount of available energy to sell out with their respective prices. The pseudocode of the energy trading's smart contract is given in Algorithm 4.

Reputation-Based Smart Contract. EBEV contacts
ESEVs through the smart contract to utilize their charging services. In the public setting, various ESEVs are available with different capabilities, intentions, and services. After interacting with an ESEV, the EBEV user evaluates ESEV based on its energy services that affects the energy demander. The reputation points of each ESEV depend on EBEVs' ratings. Due to the fact that some EBEVs may misbehave, therefore, their integrity must be taken into consideration. EBEV with higher credibility point acts honestly as compared to one with less points. Therefore, EBEV rates ESEVs fairly to increase their credibility significantly. The reputation points are the cumulated ratings of EBEVs with their credibility points. The smart contract for reputation comprises two main functions: the viewing aggregated feedback and feedback submit. The viewing aggregated feedback allows both EBEVs and ESEVs to check their available ratings. The feedback submit function allows EBEVs to assess ESEV after a transaction of energy takes place. The ESEVs' reputation is calculated using the following equation [58].
where I is a unique identification for each ESEV that is evaluated while the total number of EBEV-rated ESEVs is M. The credibility of EBEV m is Cred m . R m is the rating of node I given by EBEV m, and the total reputation points of node I is R I . To reduce the execution and transaction gas consumption of the blockchain, the mathematical computations for reputation and EBEVs' credibility are done off-chain. Off-chain computation is defined as the computational model where the functions of state transition are calculated by a trusted entity that is not on the blockchain. The resulting transition state then continues on-chain after verifying the computation of the state transition [59]. The computation results are transferred to the reputation's smart contract for further processing. The pseudocode of the smart contract for reputation is given in Algorithm 5.

Energy Load Forecasting for Charging Consumption
Based on Multiple Linear Regression. In this work, a forecasting approach is employed to predict the EVs' charging consumption load based on regression analysis. Regression analysis [60] is a type of predictive technique for modeling and investigating relationship between independent and dependent variables. These predictive techniques are commonly used for forecasting, time series modeling, and finding a collective relationship between variables. Regression analysis is divided into linear, multiple logistics, polynomial, stepwise, ridge, lasso, and elasticNet regression. In this model, MLR is used.

Multiple Linear
Regression. MLR determines the relationship between the variables that are independent and dependent. The equations presented for MLR are adopted from [61], which are expressed in the following equation.
According to Equation (10), used to calculate the α regression coefficient, the expected load could be predicted as represented in Equation (11) using the MLR method.
y is the forecasted value of y. In this model, error is the absolute difference between the actual and forecasted values.

The Proposed Solution for Residential Prosumers' Component
The role of blockchain in fair energy trading and the method to compute rewards for prosumers are discussed in this section. According to the energy requirement, every energy consumer decides its starvation parameter and sends it to AG. AG uses the RSFEAP algorithm to distribute energy across all prosumers based on their energy contribution, type of transactions, and starvation parameters.
6.1. Fair Energy Trading Using Blockchain Technology. In this study, a blockchain-based model is developed to decentralize the energy systems. The model comprises of energy consumers, energy providers, and AG as users. These users coordinate and communicate via blockchain to facilitate the decentralization of energy demand and generation. However, maintaining and storing energy transactions using a centralized system is still an open research problem. Therefore, transactions in energy trading are coordinated, recorded, and maintained with the support of blockchain technology in a decentralized manner. The blockchain technology has many features: consensus mechanism, selfenforced smart contract, immutability, etc. A consensus mechanism is a collection of protocols that enables untrusted prosumers to agree on a global state of the network. In this work, Proof of Work (PoW) [62] is used. A self-enforced smart contract is an agreement embedded as a computer code that is managed by the blockchain. The information immutability feature helps to ensure that the transactions recorded on the blockchain remain unaltered after miners' verification.

Parameters for Fair Energy
Allocation. This section discusses the parameters used for the energy allocation algorithm across residential prosumers.

10
Wireless Communications and Mobile Computing consumers might not receive energy, and they need to purchase the required energy at a very high price from the main grid. In RSFEAP, the minimum energy requirement of each prosumer is represented in the form of percentage. The starvation factor S is used to define the threshold for the energy requirement. Based on the threshold, each consumer meets its minimum energy requirement S × E arq to avoid energy starvation. The SL parameter is calculated using the following equation [42].
At every time slot, AG receives details of providers' excess energy E as and consumers' energy request E arq . RSFEAP guarantees optimal prosumer-generated energy allocation E allocR to each consumer.

Reward
Index. In this model, RI plays a vital role for a fair energy allocation. It is mandatory to compute the RI carefully to have fair energy allocation and trading mechanisms. In the process of deciding the reward of a prosumer i, two factors are considered, which are given below.
In Equations (13)- (16), C i is the amount of energy contributions provided by a prosumer till the present interval and C Total is the sum of the energy contributions recorded by AG till the present interval. Y i is the quantifier for valid and malicious transactions recorded by the miners in the blockchain while θ is the index of each transaction (valid or malicious) recorded. In the computation of RI, both energy contributions and transaction types are treated with equal preference. However, there may be a situation where AG gives a higher preference to the type of transactions executed rather than the energy contributed. In such a situation, the preference values of a user will be multiplied by the weight factor ρðρ > 0Þ. We assume to take the value of ρ as 1 in this paper since preferences to both transaction types and energy contributions provided in the past are the same. Therefore, a prosumer that shares surplus energy in the past will get rewards in the future when energy is needed. The reward depends on the type of transactions conducted by the prosumer, which decreases with an increase in malicious activity during energy transactions. Conclusively, when a prosumer purchases energy, AG and miners store the information about the exact net energy shared by the prosumer in the blockchain ledger. AG uses the information to compute the RI and update it regularly. RI is considered in RSFEAP to show the consistency and credibility of prosumers in the system.

Valid and Malicious
Transactions. The valid and malicious transaction (VMT) algorithm consists of punishment and reward mechanisms. There are two types of actions to be punished: first, when consumer i attempts to alter his record to favor himself; second, when consumer i broadcasts a forged request. On the other hand, it is rewarded when a prosumer i acts honestly and performs a valid transaction. As shown in Algorithm 6, if a malicious transaction is not detected by the miners, the transaction is said to be valid and its index θ i will be set to zero (0). Therefore, the prosumers' RI will increase. On the other hand, if a malicious act is detected based on the mentioned actions, then AG will collect evidence to make a judgment and send it to the miners for validation. If any prosumer is caught with malicious activity, its transaction index θ i will increase by 1, which will decrease the RI.
6.3. Optimization Formulation. AG optimally distributes energy to every consumer based on the aforementioned parameters. Hence, to efficiently allocate energy A i ðE i,allocR Þ to meet the consumers' demand, an optimization problem is formulated. The optimization formulation given in this research is similar to [42].
According to the optimization problem given in Equation (17), some assumptions are made. AG will not distribute energy E i,allocR to the consumer that will exceed its energy requirement (E i,arq ) and will fall below its starvation level (SL × E i,arq ). Therefore, the consumer will be able to satisfy its minimum demand. Also, RSFEAP places a restriction on the total energy distributed to the consumers so that it cannot exceed the total energy aggregated from prosumers with surplus energy E. The consumers' objective functions are given from the AG perspective, as shown in the following equation.
Solving the following constrained optimization problem, RSFEAP of AG is developed. ⋯, ng, E arq = fE 1,arq , E 2,arq , ⋯, E n,arq g be the set of exact energy request by the consumers, and C = fC 1 , C 2 , ⋯, C n g be the set of energy contributions made by the prosumers. The optimal value of the optimization is computed using the following equation.
where β and α are that weight factors, which are used to control the preference of every parameter of RSFEAP. β + α = 1 and 0 ≤ β, α ≤ 1: (b) Solution: if ∑ i∈Cs E i,allocR ≤ E, then all consumers are allocated with their requested energy, i.e., E i,allocR = E i,arq . On the other hand, an optimal energy allocation mechanism is used for the nontrivial case, i.e., when considering ∑ i∈Cs E i,allocR > E. In such a situation, one can obtain closed-form solution given by Theorem 1.
(c) Theorem 1: an optimized allocation of energy E * i,allocR = fE * i,allocR | i ∈ Csg from the defined problem is given below and < E i,arq , where υ is a real number that satisfies ∑ i∈Cs E * i,allocR = E.
(d) The proof that shows that the objective function is concave: Since the second derivative of the objective function is negative where 0 < β≤1, then it is purely concave function.
(e) Proof: since all the constraints are linear and the objective function is purely concave, the conditions of Karush-Kuhn-Tucker (KKT) [42] guarantee Prob lem 1 given as follows.
which is further simplified to the following equation: In Equation (27), the second term can be represented as given in Equation (32) below. φ in the expression is used for the second inequality constraint.
And the last term in Equation (27), can be shown as By solving Equations (31), (32), and (33), the stationary condition in Equation (27) is satisfied, which is expressed in the following equation.
while the complementary slackness condition is shown as Finally, the dual feasibility condition in Equation (26) is expressed in the following equation.
The inequality constraint and objective function are convex and differentiable while the equality constraint functions are affine. Therefore, the KKT conditions have an optimal solution [48,63]. To satisfy Equation (40), three possible cases are gener-  (27)), and the result of E * i,allocR is generated as follows.
where Equation (42) is further simplified to give the following equation.
Considering a case E * i,allocR = E i,arq , there exists a value of λ i taken from Equation (39). The value of φ i can be substituted in the stationary condition in Equation (27), and the E * i,allocR results are given as follows.
where Equations (44) and (45) are further simplified to give the following equation: Furthermore, we consider a case S × E i,arq = E * i,allocR where φ = 0 from complementary slackness condition in Equation (39). The value of φ i can be substituted in the stationary condition in Equation (27), and the E * i,allocR results are given in Equations (48)- (51).
which produce Therefore, there exists an optimal allocation of energy E * i,allocR = fE * i,allocR | i ∈ Csg of Problem 1 in Equation (22). From the three cases given above and the primal feasibility condition in Equation (37), the optimal solution is given by Equation (22). Furthermore, the solution to the problem defined in this paper uses quadratic programming. It is because the objective function is a quadratic problem with linear constraints.

Energy Allocation
Algorithm. Before the energy transactions start, the prosumers' information is collected by AG to allocate the energy to them. For each time interval, the total available energy provided by the energy providers is E and the total energy needed by the energy consumers is E c . In this work, the proposed energy allocation algorithm, i.e., Algorithm 7, is derived from [42], and it has two conditions, which are as follows: (1) When the total energy request from consumers E c is less than or equal to the total energy available E (2) When the total energy request from consumers E c is greater than the total energy available E In the first condition, consumers receive the same amount of energy that they requested. In the second condition, consumers receive an optimal amount of energy as shown in Algorithm 7 (lines [12][13][14][15][16][17][18][19][20][21][22]. In these lines, the interior point method of quadratic programming is used to solve the optimization problem where the optimal allocation of energy is produced. A MATLAB function called quadprogð Þf unction (line 21) is often used to solve a quadratic objective function. This function requires various input parameters, both in the form of vectors and matrices. These input parameters are the Hessian matrix H, vector f T , upper bound ub, lower bound lb, and inequality constraints A and b. Hessian matrix H as shown in lines 13 and 14 of Algorithm 7 is a symmetric matrix. f T (line 14) is a vector represented as the linear term of the objective function (line 13). The linear coefficient in inequality constraint is represented as A, and the constant vector of overall surplus energy in the current time interval is represented as b. The boundaries for energy allocations S × E i,arq ≤ E i,allocR ≤ E i,arq are represented as the upper and lower bound vectors (line 18). ub is the maximum limit set by AG for over allocating energy to consumers. On the other hand, lb is the lower threshold value set by each consumer to stop himself from falling into starvation. Therefore, these input parameters help the quadprogðÞf unction to be executed and return the optimal energy allocation vector E allocR .

Privacy and Security Construction for Residential
Prosumers. In this research work, an encryption mechanism is used to protect users' information for the residential prosumer component. Sensitive data that does not affect the trading mechanism is encrypted and is stored in the blockchain. The focus of the research is to partially encrypt the users' data by allowing the energy and price values to be sent unencrypted to the blockchain. This process allows the energy traders to participate in trading without adding burden to the system by concealing irrelevant information. It is important to use encryption techniques to turn the plaintext into ciphertext to maintain the system's security and improve the users' privacy in the blockchain. Therefore, an asymmetric encryption technique is used to encrypt the data before recording it on the blockchain. Moreover, a privacy protection technique, i.e., ID-based encryption, is implemented. The technique that is used is based on the bilinear map theory. It is known that the Ethereum blockchain does not support complex mathematical computations [59]. Moreover, the Ethereum blockchain is adopted due to its stronger security capability and less time consumption as compared to IOTA during validation process [64]. Therefore, all the complex computations are done off-chain, and the computed results are forwarded to the blockchain for further computation and storage. Similarly, the blockchain execution and transaction costs are reduced, and also, the efficiency of the allocation process is not affected. In order to protect the users' information, additional encryption techniques are required. Therefore, in the proposed system, ID-based encryption and HE techniques are adopted.

Bilinear Map
Theory. This section presents bilinear map theory as follows.
(i) The three cyclic groups of prime order P are denoted as G 1 , G 2 , and G 3 (ii) g 1 and g 2 are generated from G 1 and G 2 , respectively, as g 1 ∈ G 1 and g 2 ∈ G 2 (iii) Bilinear map is presented as eð,Þ: The bilinear map properties are given as follows: 14 Wireless Communications and Mobile Computing (i) Nondegenerate: eðg 1 , g 2 Þ ≠ 1 (ii) Bilinear: ∀v ∈ G 1 , ∀u ∈ G 2 , and b, a ∈ ℤ, we have eð v b , u a Þ = eðv, uÞ ba The proposed scheme is defined by Boneh and Franklin's ID-based system, implemented in 2001 [65], which can be used for privacy protection in the blockchain. The following are the steps of the encryption process. 7.2.1. Initialization. Construct two groups of elliptic curves G 1 , G 2 such that |G 1 | = |G 2 | = q, eð,Þ: G 1 × G 1 ⟶ G 2 is a bilinear map and P ∈ G 1 is a generator. s ∈ ℤ * q is randomly selected, and s is defined as the master key where P pub = s · P can be calculated. Let h : f0, 1g n ⟶ G 1 , h 1 : f0, 1g n ⟶ G 2 , and h 2 : f0, 1g n ⟶ ℤ * q be the three cryptographic hash functions. The system's parameters are published as fG 1 , G 2 , e; ;n, q, P, P pub , hð Þ, h 1 ð Þ, h 2 ð Þg.

Security and Privacy Analyses
This section analyzes the privacy and security of the energy trading model. The model is analyzed on the bases of the secret key security, passive attack, and disguised attack. Moreover, the smart contracts are analyzed using the Oyente security analysis tool.
8.1. Security of Secret Key. The most essential and sensitive part of the ID-based encryption technique is the master or secret key. Once the secret key is revealed, the whole system is under threat. Therefore, the secret key must be cautiously and carefully stored. In traditional encryption systems, central authority controls and manages the secret key, which raises issues of security and centralization. However, in this model, each node generates its master key instead of a single PKG. Similarly, for the EV's component, the communication is done using Paillier encryption, which allows the receiver of the encrypted message to perform an action on the ciphertext without having the keys. Therefore, in encryption, sharing of keys is not required. These encryption processes resolve the centralization and security problems of the secret keys.

Passive
Attack. The passive attack comprises traffic analysis and information monitoring. In a transaction, the passive attacker can have access to two different types of users' information: data and addresses. The address is not reversible because it is a user's hash signature. Thus, the only target point of the attacker is the plaintext information given by the users and is the focus of this research work. The IDbased encryption technique is used to protect and encrypt information where only a string of unrecognized characters can be seen. Similarly, for the EV's component, Paillier encryption is used to protect the privacy of the users' location. These strings are readable when the user is in possession of the private key, which makes the system passive attack resistant.

Disguise Attack.
In this attack, a disguised attacker may have the ID of the legitimate user, so he can pretend to be another user. Even if the attacker receives the encoded data, it is difficult to regenerate the original information without the private key. Thus, this makes the system resistant to the disguised attacker. Further, different cases of EVs' security and privacy issues exist. Therefore, three (3) propositions are defined and analyzed.

Proposition 1.
The attacker cannot learn other users' location information in the system before matching with the users ðQ 1 Þ.
We assume that users interact with each other via secure channels, i.e., through the blockchain or the Paillier encryption technique. The Paillier encryption technique allows ESEV to work on encrypted data without knowing the actual information from the EBEV user. Additionally, the selection of ESEVs is based on the reputation values they have before the match is made. This makes the proposed system conceal the location information of both ESEVs and EBEVs. Proposition 2. The internal and external attacks from the computing nodes cannot compromise the proposed system ðQ 2 Þ.
It is clear that the reliability of the proposed system depends on the security provided by the blockchain. Generally, it is assumed that the attacker cannot control more than 51% of the computing nodes in the blockchain. The internal and external attacks on the computing nodes are unable to breach the whole system because the attackers need to control more than 50% of the nodes. PoW consensus mechanism prevents the system from both internal and external attacks. All operations in the smart contracts are constantly executed on blockchain and the computed results are stored in it. This process guarantees the trustworthiness of the system. Also, the operations and the results obtained are verified by the miners in the proposed system. Conclusively, the data stored in the blockchain is made tamper-proof and traceable.

Vulnerability Analysis of Smart
Contract. This section discusses the security vulnerability analyses of the smart contracts. It also highlights the best way to develop and write smart contracts, so that they can withstand all possible attacks. In addition to the encryption mechanism, blockchain technology is used to strengthen the overall security of the system. The blockchain comes with its advantages as well as some security problems. Among the security challenges, blockchain provides a solution to the Distributed Denial of Service (DDoS) attack. The reason is that all energy transactions are recorded on the private Ethereum storage in a decentralized and distributed fashion and therefore are not prone to a single point of failure. This technology has the ability to store data that cannot be altered or changed (immutability feature) as long as it is confirmed by the validators. The blockchain's immutability feature helps to ensure the integrity of all shared data between the involved parties. The data can only be attacked if and only if an attacker or group of attackers control more than 50% of the network. Moreover, this type of attack is almost impossible in the proposed system because the network uses the PoW consensus mechanism.
Smart contracts' developers must ensure that the contract code is free of bugs and security vulnerabilities. The proposed smart contracts are analyzed using Oyente security 16 Wireless Communications and Mobile Computing analysis tool to check for the known bugs and security vulnerabilities. The security vulnerabilities include reentrancy vulnerability, timestamp dependence, callstack depth vulnerability, transaction ordering attack, parity multisig bug 2, and assertion failure. The results of the proposed smart contracts analysis are presented in Table 2. The EVM byte codes are evaluated by Oyente and the corresponding call graphs are produced for each contract. Oyente conducts the block-level smart contract code analysis by following the rules given in Ethereum's yellow papers [58,66]. The results show that the proposed smart contract is secure and resistant to all the aforementioned attacks and vulnerabilities. It also shows that there is no unhandled exception, which may result in overflow or underflow of integer operations in the proposed smart contract's callee and caller functions. Moreover, external calls are reduced and all evaluations are performed to ensure gas availability. The external call reduction prevents the proposed smart contract from reentracy attack. Similarly, external calls are also reduced to protect the system from callstack attacks. Table 2 also shows that there is no possible vulnerability associated with the proposed smart contracts, which may lead to timestamp dependency, transaction ordering dependency, and parity multisig bug 2 issues.

Simulation Results
This section presents the experimental setup and the simulation results of the proposed energy trading model. The smart contracts are implemented on the Ethereum blockchain. The Ethereum blockchain is adopted due to its stronger security capability and less time consumption as compared to IOTA during validation process [64]. For fair energy allocation, four energy prosumers and one AG are considered. A day of 24 hours is divided into 24 slots (interval of 1 hour each). The data used for the prosumers' first 4 time intervals is obtained from study [42]. The computational experiments are conducted on a desktop computer with the following specifications: AMD E1-6015 APU with Radeon (TM) R2 graphics, 1.4 GHz processor, operating system is Microsoft Windows 10 with 4.00 GB of RAM, and codes are executed using MATLAB2018a. The values of S, α, and β are set as 0:8, 0:6, and 0:4 in the simulations, respectively. The dataset used for the EVs' charging load forecasting is taken from [67]. Figure 3 shows the nor- where y i andŷ i are the actual and forecasted EVs'  Figure 4, a comparison between the existing BMNN-based matching algorithm [38] and the proposed reputation-based matching algorithm in terms of convergence duration is presented. In the proposed reputation process, AG arranges EVs in a list according to their reputation points. So, an EBEV selects ESEV with the highest reputation that is presented at the top of the list. On the other hand, to find the perfect match, EBEV communicates with all the closest EVs when using the BMNN-matching process.

Wireless Communications and Mobile Computing
Because of this, the matching algorithm based on BMNN increases additional communication and computational overheads. The overall convergence duration of the BMNN-based matching algorithm is compared with the proposed algorithm as shown in Figure 4. In all situations, as the communication range increases, and the number of rounds grows, such that no EV accepting the charging request is left. Thus, the communication duration also grows. The proposed algorithm's overall convergence duration reduces by approximately 2000 ms as compared to that of the BMNN algorithm's convergence duration.

Results of Reputation and Energy Trading Using
Blockchain. Smart contracts are deployed to perform energy trading between EBEVs and ESEVs. Tables 3 and 4 depict the numerical findings of the transactional and executional costs for the proposed smart contracts: reputation and energy trading. The important functions of the proposed smart contracts include the GiveKwh, CreateStorage, SellE nergy, BuyEnergy, and ContractCreation functions. From the tables, it is shown that the maximum gas is consumed by the CreateStorage function. The reason is that the information uploaded on the proposed system requires more time and cost as compared to other functions. The gas consumption depends on the data size, which will be added to the proposed energy trading system. The other functions are GiveKwh, SellEnergy, BuyEnergy, and ContractCreatio n which consume the least cost as the functions do not require additional uploading data.

Results of EVs' Charging Load Forecasting Using MLR.
A short-term charging load forecasting model using MLR is proposed to manage and plan for EVs' charging behavior as shown in Figure 5. Incorporating the forecasting model in the proposed system can help both the charging stations and EVs to properly plan ahead of the EVs' charging in order to maintain the usage of EVs and balance the energy consumption in SC as well as to perform a profitable energy trading. The forecasting model is divided into five stages, which are the input stage, splitting EVs' dataset and normalization stage, training stage, forecasting stage, and the final stage where the forecasting results are obtained. Figure 3 shows the normalized EVs' charging load of Boulder city, Colorado, from 1st January 2018 to 30 May 2019 (17 months). The normalization graph shows different variations of energy consumption across the days. The dataset is divided into training and testing samples at a ratio of 75 : 25. Afterwards, the normalized data is forwarded to the forecasting engine for prediction. The actual and the forecasted EVs' charging load are presented in Figure 6. In the figure, the red curve is the forecasted load and the blue curve is the actual load. As shown in the figure, the proposed model gives excellent prediction results. The forecasted result almost fits in the actual data, which shows a high accuracy of the proposed forecasting model. Error rates of the performance metrics are given in Table 5. From both the table and figure, it is observed that the result of the proposed forecasting model is good as the error rates from all the performance metrics are significantly low. To be precise, the forecasted accuracy of the proposed model is 99.25%. From Figure 6, it is seen that the MLR model accurately maps the actual consumption of the electricity load. This implies that the model intelligently avoids the chance of overfitting during the forecasting of unseen periods of electricity consumption. Moreover, the forecasting curve of the MLR model shows that it perfectly learns the complex patterns of the data during the testing phase. Furthermore, overfitting a regression scheme is caused as a result of trying to estimate many parameters from very scanty data. However, to estimate the coefficients for the entire terms in the proposed scheme, a single sample is used for each polynomial, interaction, and predictor. In addition, we avoid overfitting using the cross-validation method.
9.3. Results for Residential Prosumers' Component. In this section, performance metrics and experimental results for the residential prosumers' component are presented.

Performance Metrics for the Residential Prosumers'
Component. The performance of the residential prosumers' component is evaluated using the following performance metrics: RI, type of transactions performed, the energy contributed, average convergence time, and the number of iterations.

Experimental Results for Residential Prosumers'
Component. The energy providers and consumers with surplus and deficit energy register their energy requests with AG via blockchain-based smart contracts. The data used   [42] and is presented in Table 6. In this scenario, some users are registered as energy consumers while others are registered as energy providers. The prosumers' registration takes place via blockchain. According to previous research works [70][71][72], transactions using blockchain are proved to be secured, distributed, traceable, and verifiable. In this research work, a cryptosystem technique using the ID-based encryption technique is incorporated into the system that helps to conceal energy transactional data.
In T1, two prosumers, i.e., Prosumer 1 and Prosumer 2, which are energy consumers, register their energy requests as 18 MWh and 9 MWh, respectively. On the other hand, Prosumer 3 and Prosumer 4, which are energy providers, register their surplus energy as 15 MWh and 7 MWh, respectively. The total surplus energy at time interval T1 is 22 MWh. After receiving the registered information, AG checks the available energy E and the total energy that is requested by the energy consumers E c using the proposed RFEAP algorithm, i.e., Algorithm 7. If E c ≤ E, then the situation is simple; therefore, AG distributes the total surplus energy based on the exact amount of consumers' energy requests. If the aforementioned condition is false, AG uses the second condition, i.e., E c > E, for optimal allocation of energy between consumers that use the novel RI-based algorithm. Considering the situation in T1, E c > E; therefore, the surplus energy is allocated using the second condition of the fair energy allocation algorithm. Also, AG uses Algorithm 6 and Equation (16) to compute the RI's parameter that helps to optimally allocate energy to consumers. The values of RI and energy allocated for consumers in different time slots are given in Table 6. From the table, it is depicted that RI for the consumers at T1 is the same, which makes the algorithm serve the consumers with equal importance. In this case, the optimal energy allocation for Prosumer 1 and Prosumer 2 is to get energy according to the ratio of their request, i.e., 14.8 MWh and 7.2 MWh, respectively. In the second time interval T2, Prosumer 1, Prosumer 2, and Prosumer 3 are all energy consumers while Prosumer 4 is the energy provider. The total surplus energy at the time interval is 23 MWh, and the total energy requested by the consumers is 28 MWh. It is observed in Table 6 that the Consumer 3 gets higher consideration for the allocation of energy because it has higher RI value than both Prosumers 1 and 2. Moreover, Prosumer 2 gets higher preference than Prosumer 1 because of the similar reason for Prosumer 3.   The same process of the proposed reward energy allocation is applied for T3 and T4, in which the energy is fairly distributed between the consumers.
Note that the empty bars in Figures 7-11 depict that the prosumers are energy providers at those time intervals during fair energy allocation. The energy allocation for Prosumer 1 across all the four time intervals is given in Figure 11. It is observed that the RI of Prosumer 1 has the highest value at T1 as shown in Table 6; therefore, RSFEAP gives higher preference to it when allocating energy, whereas the other consumers share the remaining surplus energy based on their SL and RI. In other time intervals, the same rule applies to other consumers. As discussed previously, the starvation value and RI of each prosumer depends on the energy requested, past contributions, and type of transactions. The impact of RI on the fair energy allocation for      Figures 12-15. Important ratios, i.e., RI i /Sumð RIÞ, E i,allocR /E, and E i,arq /E c for the energy prosumers are investigated during the fair energy distribution. Here, RI i /Sumð RIÞ is the ratio of each energy consumer's RI to the total RI of all the energy consumers, E i,allocR /E is the ratio of each allocated energy for a consumer to the sum of all the surplus energy during the allocation, and E i,arq /E c is the ratio of each actual energy request by a consumer to the sum of all consumers' energy requests. In Figures 12-15, it is shown that the amount of allocated energy is large when the RI ratio is large; otherwise, it is less. The effects of malicious and valid transactions are also investigated as depicted in Figures 16-18. It is clearly shown in Figures 16 and 17 that an increase in malicious transactions decreases the amount of energy contributions made by the prosumers. On the other hand, an increase in the number of honest and valid transactions increases the energy contributions. The valid and malicious transactions directly affect RI of each prosumer as shown in Figure 18. As observed

22
Wireless Communications and Mobile Computing from the figure, when prosumers' contributions increase, RI also increases. The model prevents the proposed system against continuous malicious transactions. The comparison of energy level generated for each consumer by RSFEAP and SF-OEAP [42] is shown in Figures 7-10. In terms of average convergence time and maximum iterations, the proposed model is better than the SF-OEAP algorithm [42]. The convergence time and maximum iterations of the proposed model are shown in Figures 19 and 20, respectively. The results in Figure 19 show that the number of iterations increases with the increase in the number of prosumers where the number of iterations for 50 prosumers is 8, which is less than than the number of benchmark scheme's iterations. Similarly, the convergence time for the proposed model is approximately 10 times less than the benchmark algorithm. The reason is that the proposed algorithm performs the energy allocation based on reputation value, which is obtained directly from the blockchain. While in the benchmark algorithm, all the computations are done in the algorithm. As a result, the computational time and the number of iterations are reduced. This shows that the proposed model is faster than the benchmark schemes for implementation in real-time electricity market.

Conclusion and Future Work
This study proposes a blockchain-based privacy-preserving energy trading system for 5G-deployed SCs. The proposed system has two components: EVs and residential prosumers. In the proposed system, an RSFEAP algorithm for residential homes and a reputation-based distributed matching algorithm of EBEV with ESEV are presented. The RSFEAP algorithm is proposed to efficiently allocate energy to the residential consumers. The matching algorithm is proposed to match ESEV with EBEV in a secured and distributed manner. A shortterm load forecasting model for EVs' charging using MLR is proposed to plan and manage the uncertainty of the charging behavior of EVs. The proposed system integrates ID-based encryption and HE techniques to protect the privacy of transaction data and users, respectively. Simulations are conducted and findings depict that the proposed system achieves promising performance. In the simulations, the EVs' charging load forecasting shows a better performance with an accuracy of 99.25%. In the RSFEAP, the number of iterations for 50 prosumers is 8, which is smaller than the benchmark scheme while the convergence duration is also 10 times less than the benchmark scheme. RSFEAP ensures a fair distribution of energy to each consumer in the energy-distributed system. Similarly, the proposed matching algorithm of EBEV with ESEV converges faster as compared to the existing BMNN algorithm with convergence duration of approximately 2000 ms. In the blockchain, the proposed smart contracts consume reasonable executional and transactional costs. Furthermore, in the proposed system, privacy and security and smart contract analyses are performed. The obtained results depict that the proposed smart contracts and overall system are bug-free and secure against security attacks and vulnerabilities.
In future, we intend to improve the EVs' charging load forecasting efficiency as well as the prediction accuracy. The increase in the number of charging EVs increases the amount of data, which will be used for improving EVs' charging load forecasting. Furthermore, the performance of the proposed system will be optimized and explored using hardware implementation. The integration of encryption mechanism, allocation algorithm, and blockchain in energy trading domain is still an open research topic and will be considered.