Abstract
A Smart Community (SC) is an essential part of the Internet of Energy (IoE), which helps to integrate Electric Vehicles (EVs) and distributed renewable energy sources in a smart grid. As a result of the potential privacy and security challenges in the distributed energy system, it is becoming a great problem to optimally schedule EVs’ charging with different energy consumption patterns and perform reliable energy trading in the SC. In this paper, a blockchainbased privacypreserving energy trading system for 5Gdeployed SC is proposed. The proposed system is divided into two components: EVs and residential prosumers. In this system, a reputationbased distributed matching algorithm for EVs and a Rewardbased Starvation Free Energy Allocation Policy (RSFEAP) for residential homes are presented. A shortterm load forecasting model for EVs’ charging using multiple linear regression is proposed to plan and manage the intermittent charging behavior of EVs. In the proposed system, identitybased encryption and homomorphic encryption techniques are integrated to protect the privacy of transactions and users, respectively. The performance of the proposed system for EVs’ component is evaluated using convergence duration, forecasting accuracy, and executional and transactional costs as performance metrics. For the residential prosumers’ component, the performance is evaluated using reward index, type of transactions, energy contributed, average convergence time, and the number of iterations as performance metrics. The simulation results for EVs’ charging forecasting gives an accuracy of 99.25%. For the EVs matching algorithm, the proposed privacypreserving algorithm converges faster than the bichromatic mutual nearest neighbor algorithm. For RSFEAP, the number of iterations for 50 prosumers is 8, which is smaller than the benchmark. Its convergence duration is also 10 times less than the benchmark scheme. Moreover, security and privacy analyses are presented. Finally, we carry out security vulnerability analysis of smart contracts to ensure that the proposed smart contracts are secure and bugfree against the common vulnerabilities’ attacks. The results show that the smart contracts are secure against both internal and external attacks.
1. 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 plugin 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 securityprivacyrelated problems. Among the solutions provided to solve the centralized approach problems is the introduction of a distributed model. In [2], the authors propose a PeertoPeer (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 subgradientbased 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 fuelbased vehicles. The introduction of EVs is among the solutions that are generally being accepted to resolve the environmental pollution problems [7]. As a longterm automotive technology, EVs are becoming popular in minimizing the total dependency on fossil fuelbased 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 gridbased 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, demandsupply 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 1Dimensional CNN (1D CNN) and Recurrent Neural Network (RNN) to forecast consumers’ energy usage. The 1D 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 ShortTerm Memory (LSTM) is adopted to learn both the shortterm and longterm 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 FifthGeneration (5G) technology against the previousgeneration 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 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–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 demandsupply mismatch are still not fully solved using blockchain.
This research work proposes a distributed, verifiable, anonymous, and privacypreserving energy trading system. The system enables users to trade and communicate securely using blockchain in 5G network. In the system, a reputationbased privacypreserving EVs’ matching scheme is proposed. Also, the proposed system incorporates identitybased encryption (IDbased 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.
2. Related Work
In this section, a detailed literature review is presented, which is divided into energy trading and EVs’ charging load forecasting.
2.1. 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 blockchainbased 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 privacypreserving 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 onthemove 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 threeparty model that is integrated with EVs in a smart grid context is proposed. In the model, two schemes are also proposed that focus on EVcentered and SCcentered. Furthermore, a demandonschedule 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.
2.2. Electric Vehicles’ Charging Load Forecasting
The authors in [32] propose a onestep shortterm 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 shortterm 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 shortterm 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 securityrelated issues, and a single point of failure.
3. Motivation, Problem Statement, and Contributions
This section presents the motivation, problem statement, and research contributions.
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 ecofriendly 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 blockchainbased 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 blockchainbased 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 selfinterest 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 StarvationFree Optimal Energy Allocation Policy (SFOEAP). 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.
3.2. 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 privacypreserving 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 Rewardbased StarvationFree Energy Allocation Policy (RSFEAP) algorithm is presented to 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)IDbased encryption and HE techniques are incorporated into the proposed system to protect the privacy of the transactions and users, respectively(v)A shortterm 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 bugfree against attacks
4. 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.
4.1. Electric Vehicles’ Component
In Figure 1, the overall system model is presented. The proposed system model is divided into two components: EVs and residential energy prosumers. In the EVs’ component, the component is categorized into three parts: (i) privacypreserving search and match scheduling, (ii) validation of transactions and blockchainbased EVs’ energy trading, and (iii) load forecasting for EVs. The proposed component has two users groups, which are energybuying EVs (EBEVs) and energyselling EVs (ESEVs). Examples of ESEVs are V2V chargers, public/private charging stations, and residential stations. The system is assumed to have no central scheduler. In the EVs’ component, the EBEV user initiates a local query using communication devices that help to search for available ESEV in the 5Gdeployed SC. The communication between EBEVs and ESEVs is done by either LongTerm Evolution (LTE) or Dedicated ShortRange Communications (DSRC). 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.
4.1.1. 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 nonHE 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, encryption, and key generation. The equations of the cryptosystem are adopted from [38].
and are two large prime numbers that are selected with the same bit length in the key generation step, setting and . and are computed from and , which are , and . The encryption and decryption keys are defined as and , respectively. A random integer is selected when encryption is performed on a plaintext (i.e., ).
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 . Both encryption and decryption functions must satisfy the following equations.
where and are plaintexts.
4.1.2. Adversary Model
In the proposed model, an HonestbutCurious (HBC) adversary model is adopted specifically at the privacypreserving 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.
The attacker will try to understand other users’ location even though they are not matched
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 in the distributed network. The prosumers in the network are interlinked and share energy using dedicated powersharing 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 , and it has a load . When , the prosumer becomes the energy seller (provider), whereas, when , 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 IDbased encryption. The details of the encryption process are presented in Section 7.1.
5. The Proposed Solution for Electric Vehicles’ Component
In this section, privacypreserving reputationbased distributed matching, smart contracts, and EVs’ charging load forecasting are discussed.
5.1. PrivacyPreserving ReputationBased Distributed Matching
In this study, a blockchainbased 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 secondhighest 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.

5.1.1. 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.
5.1.2. PrivacyPreserving ReputationBased Distance and Location Calculations
To compute the distance between EBEV and ESEV, the EBEV user needs to know the ESEV’s 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 be using the Paillier cryptosystem. Also, an encrypted squared distance computation between an ESEV at location and an EBEV at location 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 privacypreserved manner.


5.2. 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 without involving a thirdparty. 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.
5.2.1. 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 handinhand, which enable EVs to sell or buy energy. When the energy trading begins, the smart contract 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 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.

5.2.2. ReputationBased 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 is a unique identification for each ESEV that is evaluated while the total number of EBEVrated ESEVs is . The credibility of EBEV is . is the rating of node given by EBEV , and the total reputation points of node is . To reduce the execution and transaction gas consumption of the blockchain, the mathematical computations for reputation and EBEVs’ credibility are done offchain. Offchain 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 onchain 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.

5.3. 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.
5.3.1. 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.
where is the EVs’ charging load consumption, are the independent variables, are regression coefficients with respect to the independent variables, and denotes the error rate. For multiple observations, Equation (6) is split as presented in the following equation.
These equations are represented in the form of matrices as follows.
where,
The matrices and contain information of both dependent and independent variables of the actual data. The from Equation (8) is derived by Equation (10) using the least square method.
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.
is the forecasted value of . In this model, error is the absolute difference between the actual and forecasted values.
6. 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 blockchainbased 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 selfenforced 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.
6.2. Parameters for Fair Energy Allocation
This section discusses the parameters used for the energy allocation algorithm across residential prosumers.
6.2.1. Starvation Level Parameter
The consumers in the reward based energy allocation model are served with excessive energy available in the system. It is found that some prosumers in the network show a negligible contribution, have a high rate of malicious transactions, or are incapable of contributing energy. In this case, the 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 is used to define the threshold for the energy requirement. Based on the threshold, each consumer meets its minimum energy requirement 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 and consumers’ energy request . RSFEAP guarantees optimal prosumergenerated energy allocation to each consumer.
6.2.2. Reward Index
In this model, plays a vital role for a fair energy allocation. It is mandatory to compute the carefully to have fair energy allocation and trading mechanisms. In the process of deciding the reward of a prosumer , two factors are considered, which are given below. (1)The amount of energy contributions provided by the prosumer in the past(2)The number of valid or malicious transactions performed in the present or past by the prosumers
Hence, RI is computed as follows.
In Equations (13)–(16), is the amount of energy contributions provided by a prosumer till the present interval and is the sum of the energy contributions recorded by AG till the present interval. 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 . We assume to take the value of as 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.
6.2.3. 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 attempts to alter his record to favor himself; second, when consumer broadcasts a forged request. On the other hand, it is rewarded when a prosumer 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 will be set to zero (). 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 will increase by , 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 to meet the consumers’ demand, an optimization problem is formulated. The optimization formulation given in this research is similar to [42].
such that,
According to the optimization problem given in Equation (17), some assumptions are made. AG will not distribute energy to the consumer that will exceed its energy requirement () and will fall below its starvation level (). 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 . 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. (a)Problem 1: let the set of all consumers be , be the set of exact energy request by the consumers, and be the set of energy contributions made by the prosumers. The optimal value of the optimization is computed using the following equation.
such that
where and are that weight factors, which are used to control the preference of every parameter of RSFEAP. and , (b)Solution: if , then all consumers are allocated with their requested energy, i.e., . On the other hand, an optimal energy allocation mechanism is used for the nontrivial case, i.e., when considering . In such a situation, one can obtain closedform solution given by Theorem .(c)Theorem 1: an optimized allocation of energy from the defined problem is given below
where is a real number that satisfies . (d)The proof that shows that the objective function is concave:
Since the second derivative of the objective function is negative where , then it is purely concave function. (e)Proof: since all the constraints are linear and the objective function is purely concave, the conditions of KarushKuhnTucker (KKT) [42] guarantee given as follows.(1)Complementary slackness:(2)Primal feasibility:(3)Dual feasibility:(4)Stationary:
Generally, the constraint vectors are represented as single column vectors.
We define lagrange multipliers for inequality constraints and multipliers for equality constraints. Hence,
From Equation (27), is derived as given in the following equation. 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.
In the primal feasibility condition, , and is solved as where Equations (35) and (36) give 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 generated for : , , and . We first consider a case . It is clear that and . The and values are then substituted in the stationary condition in Equation ((27)), and the result of is generated as follows. where Equation (42) is further simplified to give the following equation.
Considering a case , there exists a value of taken from Equation (39). The value of can be substituted in the stationary condition in Equation (27), and the results are given as follows. where Equations (44) and (45) are further simplified to give the following equation: which produces
Furthermore, we consider a case where from complementary slackness condition in Equation (39). The value of can be substituted in the stationary condition in Equation (27), and the results are given in Equations (48)–(51). which produce
Therefore, there exists an optimal allocation of energy of Problem 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.
6.4. 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 and the total energy needed by the energy consumers is . 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 is less than or equal to the total energy available (2)When the total energy request from consumers is greater than the total energy available
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–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 (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 , vector , upper bound , lower bound , and inequality constraints and . Hessian matrix as shown in lines 13 and 14 of Algorithm 7 is a symmetric matrix. (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 , and the constant vector of overall surplus energy in the current time interval is represented as . The boundaries for energy allocations are represented as the upper and lower bound vectors (line 18). is the maximum limit set by AG for over allocating energy to consumers. On the other hand, is the lower threshold value set by each consumer to stop himself from falling into starvation. Therefore, these input parameters help the to be executed and return the optimal energy allocation vector .
7. Proposed Methodology

7.1. 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., IDbased 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 offchain, 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, IDbased encryption and HE techniques are adopted.
7.2. Bilinear Map Theory
This section presents bilinear map theory as follows. (i)The three cyclic groups of prime order are denoted as and (ii) and are generated from and , respectively, as and (iii)Bilinear map is presented as
The bilinear map properties are given as follows: (i)Nondegenerate: (ii)Bilinear: , and we have
The proposed scheme is defined by Boneh and Franklin’s IDbased 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 such that is a bilinear map and is a generator. is randomly selected, and is defined as the master key where can be calculated. Let and be the three cryptographic hash functions. The system’s parameters are published as .
7.2.2. Generating Private and Public Keys
(i)User registers with AG using its ID number and personal information(ii)The client generates a public key based on the ID of , which produces (iii)Private Key Generator (PKG) calculates the ’s private key locally as then passes it to via a secure channel
7.2.3. Sending Message to the Blockchain
(i)Initially, user encrypts a private message as follows(a)Picks (b)Calculates , (c)(ii)After encryption, the user sends the encrypted message to the blockchain
7.2.4. Getting Message from the Blockchain
(i)System sends encrypted message to and decrypts data as follows (a) where is just the plaintext
8. 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 IDbased 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.
8.2. 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.
8.3. 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 .
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 .
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.
Proposition 3. All energy trading tasks are open and trustworthy in the proposed system .
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 tamperproof and traceable.
8.4. 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 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 blocklevel 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.
9. Simulation Results
This section presents the experimental setup and the simulation results of the proposed energy trading model.
9.1. Experimental Setup
The network topology of 100 ESEVs and 100 EBEVs is generated within an area of 1 km by 1 km. The locations of ESEVs and EBEVs are allocated with uniform distribution. Generally, 512bit primes for and , as given in Paillier’s cryptosystem, are used for the PHE calculations. 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 E16015 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 , , and are set as , , and in the simulations, respectively. The dataset used for the EVs’ charging load forecasting is taken from [67]. Figure 3 shows the normalized EVs’ charging load of Boulder city, Colorado, from 1st January 2018 to 30 May 2019 (17 months). The dataset contains transactions of EV charging for different locations. It consists of numerous metadata for the charging transactions like plug type, charging time, and gasoline savings. In the proposed work, the energy consumption and charging time are considered. For regression models, the most popular performance measures are forecasting accuracy, Mean Square Error (MSE), Mean Absolute Error (MAE), Mean Absolute Percentage Error (MAPE), and Root Mean Square Error (RMSE) [68]. Therefore, in the proposed model, we use the same parameters.
9.2. Results for the Electric Vehicle Component
In this section, performance metrics and experimental results for the EVs’ component are discussed.
9.2.1. Performance Metrics for the Electric Vehicle Component
The effectiveness of the performance of the EVs’ component is evaluated using the following performance metrics. For the searching and matching algorithm, convergence duration is used. For evaluating the EVs’ load forecasting accuracy, MSE, MAE, MAPE, and RMSE are used. For the blockchain, execution and transaction gas consumption are used for the performance evaluation. The performance parameters are discussed as follows. (i)Convergence duration: it is the aggregated time interval that the algorithm requires to converge. It includes both computational and communication overheads that are caused by the transmitted messages and encryption process, respectively(ii)RMSE, MAPE, MAE, and MSE are defined in the following equations [69]
where and are the actual and forecasted EVs’ charging loads at point , respectively, while the total number of EVs’ charging points is . (iii)Executional and transactional costs: executional cost is the operational cost consumed for each line of code in the smart contract’s function. The total amount of gas consumed by smart contracts’ functions for sending data to the blockchain is called the transactional cost
9.2.2. Results of ReputationBased PrivacyPreservation for the Matching EVs
In Figure 4, a comparison between the existing BMNNbased matching algorithm [38] and the proposed reputationbased 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 BMNNmatching process. Because of this, the matching algorithm based on BMNN increases additional communication and computational overheads. The overall convergence duration of the BMNNbased 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.
9.2.3. 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 , , , , and functions. From the tables, it is shown that the maximum gas is consumed by the 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 , , , and which consume the least cost as the functions do not require additional uploading data.
9.2.4. Results of EVs’ Charging Load Forecasting Using MLR
A shortterm 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 crossvalidation method.
9.3. Results for Residential Prosumers’ Component
In this section, performance metrics and experimental results for the residential prosumers’ component are presented.
9.3.1. 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.
9.3.2. Experimental Results for Residential Prosumers’ Component
The energy providers and consumers with surplus and deficit energy register their energy requests with AG via blockchainbased smart contracts. The data used for the simulations is taken from [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–72], transactions using blockchain are proved to be secured, distributed, traceable, and verifiable. In this research work, a cryptosystem technique using the IDbased encryption technique is incorporated into the system that helps to conceal energy transactional data.
In , two prosumers, i.e., and , which are energy consumers, register their energy requests as 18 MWh and 9 MWh, respectively. On the other hand, and , which are energy providers, register their surplus energy as 15 MWh and 7 MWh, respectively. The total surplus energy at time interval is 22 MWh. After receiving the registered information, AG checks the available energy and the total energy that is requested by the energy consumers using the proposed RFEAP algorithm, i.e., Algorithm 7. If , 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., , for optimal allocation of energy between consumers that use the novel RIbased algorithm. Considering the situation in , ; 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 is the same, which makes the algorithm serve the consumers with equal importance. In this case, the optimal energy allocation for and 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 , , , and are all energy consumers while 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 gets higher consideration for the allocation of energy because it has higher RI value than both and . Moreover, gets higher preference than because of the similar reason for . The same process of the proposed reward energy allocation is applied for and , 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 across all the four time intervals is given in Figure 11. It is observed that the RI of has the highest value at 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 all of the time slots is presented in Figures 12–15. Important ratios, i.e., , , and for the energy prosumers are investigated during the fair energy distribution. Here, is the ratio of each energy consumer’s RI to the total RI of all the energy consumers, is the ratio of each allocated energy for a consumer to the sum of all the surplus energy during the allocation, and 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 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 SFOEAP [42] is shown in Figures 7–10. In terms of average convergence time and maximum iterations, the proposed model is better than the SFOEAP 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 prosumers is , which is less than than the number of benchmark scheme’s iterations. Similarly, the convergence time for the proposed model is approximately 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 realtime electricity market.
10. Conclusion and Future Work
This study proposes a blockchainbased privacypreserving energy trading system for 5Gdeployed SCs. The proposed system has two components: EVs and residential prosumers. In the proposed system, an RSFEAP algorithm for residential homes and a reputationbased 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 IDbased 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 energydistributed 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 bugfree 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.
Nomenclature
1D CNN:  1Dimensional convolutional neural network 
AG:  Aggregator 
BPNN:  Back propagation neural network 
BMNN:  Bichromatic mutual nearest neighbor 
CNN:  Convolutional neural network 
DSRC:  Dedicated shortrange communication 
EBEVs:  Energybuying EVs 
ESEVs:  Energyselling EVs 
EVs:  Electric Vehicles 
FHE:  Fully HE 
HBC:  HonestbutCurious 
HE:  Homomorphic encryption 
HEVs:  Hybrid EVs 
IDBased:  Identitybased 
IoE:  Internet of energy 
KKT:  KarushKuhnTucker 
LSTM:  Long shortterm memory 
LTE:  Longterm evolution 
MAE:  Mean absolute error 
MAPE:  Mean absolute percentage error 
MLR:  Multiple linear regression 
MSE:  Mean square error 
NSGA:  Nondominated sorting genetic algorithm 
P2P:  Peertopeer 
PHE:  Partially HE 
PKG:  Private key generator 
PoW:  Proof of work 
RBFNN:  Radial basis function neural network 
RI:  Reward index 
RICNN:  Recurrent inception convolution neural network 
RMSE:  Root mean square error 
RNN:  Recurrent neural network 
RSFEAP:  Rewardbased starvationfree energy allocation policy 
SCs:  Smart communities 
SFOEAP:  Starvationfree optimal energy allocation policy 
SG:  Smart grid 
SL:  Starvation level 
V2G:  Vehicletogrid 
V2V:  Vehicletovehicle 
:  Actual energy request of consumers 
:  Actual EVs’ load 
:  Available surplus energy of provider 
:  Energy demand 
:  Encryption of the plaintext 
:  Forecasted EVs’ charging load consumption 
:  Generation of energy 
:  Optimal energy allocation 
:  Starvation factor 
:  Sum of available energy from providers 
:  Sum of energy requested from consumers 
:  Sum of valid and malicious transactions 
:  The amount of energy contributed by prosumer 
:  The credibility value of 
, , and :  Three cylic groups of prime order 
:  The quantifier for valid and malicious transactions recorded by the miners 
:  The total energy contributed 
:  The location of the user 
:  The rating given by node 
:  The reputation value of node 
:  Transaction index 
and :  Two prime numbers that are selected for the HE 
:  Regression coefficient. 
Data Availability
No data were used to support this study.
Conflicts of Interest
The authors declare that they have no conflicts of interest.