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

Authors: Adamu Sani Yahaya; Nadeem Javaid; Sameeh Ullah; Rabiya Khalid; Muhammad Umar Javed; Rehan Ullah Khan; Zahid Wadud; Muhammad Asghar Khan
Journal: Wireless Communications and Mobile Computing
 (2022)

---

## 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 blockchain-based privacy-preserving energy trading system for 5G-deployed SC is proposed. The proposed system is divided into two components: EVs and residential prosumers. In this system, a reputation-based distributed matching algorithm for EVs and a Reward-based Starvation Free Energy Allocation Policy (RSFEAP) for residential homes are presented. A short-term 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, identity-based 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 privacy-preserving 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 bug-free against the common vulnerabilities’ attacks. The results show that the smart contracts are secure against both internal and external attacks.


---

## Body

## 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 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 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 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 reputation-based privacy-preserving EVs’ matching scheme is proposed. Also, the proposed system incorporates identity-based 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. Sections2 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 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.


### 2.2. 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.


## 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 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.


## 2.2. 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. 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 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 contribution-based 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.Table 1
The comparison of the proposed model with existing models.
ReferencesABCDEFBase paper 1 [19]YesNoNoYesNoNoBase paper 2 [38]NoYesYesNoNoNoBase paper 3 [39]YesNoNoYesNoNoBase paper 4 [40]YesNoNoYesNoNoBase paper 5 [41]NoNoYesNoNoNoBase paper 6 [42]NoNoYesNoNoNoBase paper 7 [43]YesNoNoYesNoNoProposed modelYesYesYesYesYesYesA: blockchain; B: encryption; C: fair allocation algorithm; D: malicious detection; E: privacy and security analysis; F: reputation.


### 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 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 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


## 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 contribution-based 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.Table 1
The comparison of the proposed model with existing models.
ReferencesABCDEFBase paper 1 [19]YesNoNoYesNoNoBase paper 2 [38]NoYesYesNoNoNoBase paper 3 [39]YesNoNoYesNoNoBase paper 4 [40]YesNoNoYesNoNoBase paper 5 [41]NoNoYesNoNoNoBase paper 6 [42]NoNoYesNoNoNoBase paper 7 [43]YesNoNoYesNoNoProposed modelYesYesYesYesYesYesA: blockchain; B: encryption; C: fair allocation algorithm; D: malicious detection; E: privacy and security analysis; F: reputation.


## 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 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 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


## 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 Figure1, 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) privacy-preserving search and match scheduling, (ii) validation of transactions and blockchain-based EVs’ energy trading, and (iii) load forecasting for EVs. The proposed component has two users groups, which are energy-buying EVs (EBEVs) and energy-selling 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 5G-deployed SC. The communication between EBEVs and ESEVs is done by either Long-Term Evolution (LTE) or Dedicated Short-Range 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.Figure 1
The proposed system model.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 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, 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−1q−1. μ and g are computed from λ and n, which are μ=λmodn2−1modn, 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., Ea,r).At the encryption step, the data is encrypted using the following equation.(1)Ea,r=ga.rnmodn2.While at the decryption step, the data is decrypted using the following equation.(2)Db=LEa,rλmodn2μmodn,whereLu=u−1/n. Both encryption and decryption functions must satisfy the following equations.
(3)Ea·Ec=Ea+c,Eac=Eac,wherea and c are plaintexts.


#### 4.1.2. Adversary Model

In the proposed model, an Honest-but-Curious (HBC) adversary model is adopted specifically at the privacy-preserving search and match part. The commonly used adversary model in studying privacy-preserving 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.Q1 The attacker will try to understand other users’ location even though they are not matchedQ2 The attacker may try to understand and change reputations of other users to gain advantage of being selectedIt 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 prosumersProsumer1,Prosumer2,⋯,Prosumern 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 Gj≥Lj, the jth prosumer becomes the energy seller (provider), whereas, when Gj<Lj, 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 Ej,as=Gj−Lj, E=∑j∈ProsumerEj,as.A typical scenario where consumers request energy from AG is depicted in Figure1. 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.Figure 2
Reward allocation.


## 4.1. Electric Vehicles’ Component

In Figure1, 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) privacy-preserving search and match scheduling, (ii) validation of transactions and blockchain-based EVs’ energy trading, and (iii) load forecasting for EVs. The proposed component has two users groups, which are energy-buying EVs (EBEVs) and energy-selling 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 5G-deployed SC. The communication between EBEVs and ESEVs is done by either Long-Term Evolution (LTE) or Dedicated Short-Range 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.Figure 1
The proposed system model.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 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, 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−1q−1. μ and g are computed from λ and n, which are μ=λmodn2−1modn, 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., Ea,r).At the encryption step, the data is encrypted using the following equation.(1)Ea,r=ga.rnmodn2.While at the decryption step, the data is decrypted using the following equation.(2)Db=LEa,rλmodn2μmodn,whereLu=u−1/n. Both encryption and decryption functions must satisfy the following equations.
(3)Ea·Ec=Ea+c,Eac=Eac,wherea and c are plaintexts.


### 4.1.2. Adversary Model

In the proposed model, an Honest-but-Curious (HBC) adversary model is adopted specifically at the privacy-preserving search and match part. The commonly used adversary model in studying privacy-preserving 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.Q1 The attacker will try to understand other users’ location even though they are not matchedQ2 The attacker may try to understand and change reputations of other users to gain advantage of being selectedIt 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.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 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, 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−1q−1. μ and g are computed from λ and n, which are μ=λmodn2−1modn, 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., Ea,r).At the encryption step, the data is encrypted using the following equation.(1)Ea,r=ga.rnmodn2.While at the decryption step, the data is decrypted using the following equation.(2)Db=LEa,rλmodn2μmodn,whereLu=u−1/n. Both encryption and decryption functions must satisfy the following equations.
(3)Ea·Ec=Ea+c,Eac=Eac,wherea and c are plaintexts.


## 4.1.2. Adversary Model

In the proposed model, an Honest-but-Curious (HBC) adversary model is adopted specifically at the privacy-preserving search and match part. The commonly used adversary model in studying privacy-preserving 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.Q1 The attacker will try to understand other users’ location even though they are not matchedQ2 The attacker may try to understand and change reputations of other users to gain advantage of being selectedIt 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 prosumersProsumer1,Prosumer2,⋯,Prosumern 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 Gj≥Lj, the jth prosumer becomes the energy seller (provider), whereas, when Gj<Lj, 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 Ej,as=Gj−Lj, E=∑j∈ProsumerEj,as.A typical scenario where consumers request energy from AG is depicted in Figure1. 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.Figure 2
Reward allocation.


## 5. 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.


### 5.1. 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 Algorithm1. 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.Algorithm 1: Generic-matching function.
Input: D and S;Output: matched result;1:function Generic-matching(D, S)2:i=1;3:  whileD not matched with Sdo4:   Find distance of D based on reputation in a privacy5:   preserved manner;6:ifSi accepts the request then7:Match D withSi;8:Break;9:i++;


#### 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 Section5.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. Privacy-Preserving Reputation-Based 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 ofa be Ea using the Paillier cryptosystem. Also, an encrypted squared distance computation between an ESEV Sj at location locSj=xj,yj and an EBEV Di at location locDi=xi,yi is achieved using the following equations [38].
(4)Disti,j=∣locDi−locSj∣=xi−xj2+yi−yj2,EDisti,j=Exi2−2xixj+xj2+yi2−2yiyj+yj2.In the proposed model, each EV has PHE keys to encrypt the transactions between ESEV and EBEV. Furthermore, Algorithms2 and 3 are inspired from [38], which show the communication between EBEV and ESEV in a privacy-preserved manner.Algorithm 2: EBEV function.
Output: send distance;1:function EBEV()2:notmatched = True;3:  whilenotmatcheddo4:System broadcast the need for matching;5:if only one supplier S1 responds then6:S=S1;7:   else8:S = select the ESEV user with the highest-reputation points;9:Sendmessage(propose, D, S);10:msg = getMessage();11:if msg = accepted then12:add EBEV’s loc(x, y) and calculate encrypted squared distance;13:Sendmessage(encrypted(distance));14:notmatched = False;Algorithm 3: ESEV function.
Output: request result;1:function ESEV()2:notmatched = True;3:  whilenotmatcheddo4:msg=getMessage;5:   ifmsg.type=propose & Si accept proposal then6:respond with encrypted loc(x,y);7:Sendmessage(accept, S, D);8:notmatched = False;9:else10:Sendmessage(reject, S, D);


### 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 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.


#### 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 hand-in-hand, 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. Thecreatestorage 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.Algorithm 4: Smart contract for energy trading.
Input: energy requested from EBEV;Output: (1) ESEV gives energy to EBEV; (2) EBEV sends money to ESEV;1:function EnergyTrading()2:if(EBEV available balance<EV’s charging cost)then3:returnfalse;4:if(ESEV available energy<EV’s requested energy)then5:returnfalse;6:if(EBEV storage<amount of energy purchased)then7:returnfalse;8:else9:Subtract amount from EBEV’s account balance;10:Add amount to ESEV account balance;11:Store transaction;12:Subtract energy from storage of ESEV;13:   Add energy to storage of EBEV;14:Store transaction;15returnupdated information;


#### 5.2.2. 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: theviewing 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].
(5)RI=∑m=0MCredm×Rm∑m=0MCredm,whereI 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 Credm. Rm is the rating of node I given by EBEV m, and the total reputation points of node I is RI. 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.Algorithm 5: Smart contract for reputation.
Output: (1) EBEV rated ESEV; (2) EV view reputation points;1:function SubmitFeedback()2:Positive or negative rating point is added;3:returnTrue;4:function ViewFeedback()5:Returnaggregated feedback;


### 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.
(6)y=α0+α1x1+α2x2+⋯+αrxr+ε,wherey is the EVs’ charging load consumption, x1,x2,⋯,xr are the independent variables, α1,α2,⋯,αr 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.
(7)y1=α0+α1x11+α2x12+⋯+αrx1r+ε1,y2=α0+α1x21+α2x22+⋯+αrx2r+ε2,⋯yi=α0+α1xi1+α2xi2+⋯+αrxir+εi,⋯yn=α0+α1xn1+α2xn2+⋯+αrxnr+εn.These equations are represented in the form of matrices as follows.(8)y=αX+ε,where,(9)y=y1y2...yn,X=x11x12⋯x1rx21x22⋯x2r...xn1xn2⋯xnr,α=α1α2...αr,ε=ε1ε2...εn.The matricesy and X 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.
(10)α=X′X−1X′y.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.
(11)y^=Xα.y^ is the forecasted value of y. In this model, error is the absolute difference between the actual and forecasted values.


## 5.1. 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 Algorithm1. 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.Algorithm 1: Generic-matching function.
Input: D and S;Output: matched result;1:function Generic-matching(D, S)2:i=1;3:  whileD not matched with Sdo4:   Find distance of D based on reputation in a privacy5:   preserved manner;6:ifSi accepts the request then7:Match D withSi;8:Break;9:i++;


### 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 Section5.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. Privacy-Preserving Reputation-Based 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 ofa be Ea using the Paillier cryptosystem. Also, an encrypted squared distance computation between an ESEV Sj at location locSj=xj,yj and an EBEV Di at location locDi=xi,yi is achieved using the following equations [38].
(4)Disti,j=∣locDi−locSj∣=xi−xj2+yi−yj2,EDisti,j=Exi2−2xixj+xj2+yi2−2yiyj+yj2.In the proposed model, each EV has PHE keys to encrypt the transactions between ESEV and EBEV. Furthermore, Algorithms2 and 3 are inspired from [38], which show the communication between EBEV and ESEV in a privacy-preserved manner.Algorithm 2: EBEV function.
Output: send distance;1:function EBEV()2:notmatched = True;3:  whilenotmatcheddo4:System broadcast the need for matching;5:if only one supplier S1 responds then6:S=S1;7:   else8:S = select the ESEV user with the highest-reputation points;9:Sendmessage(propose, D, S);10:msg = getMessage();11:if msg = accepted then12:add EBEV’s loc(x, y) and calculate encrypted squared distance;13:Sendmessage(encrypted(distance));14:notmatched = False;Algorithm 3: ESEV function.
Output: request result;1:function ESEV()2:notmatched = True;3:  whilenotmatcheddo4:msg=getMessage;5:   ifmsg.type=propose & Si accept proposal then6:respond with encrypted loc(x,y);7:Sendmessage(accept, S, D);8:notmatched = False;9:else10:Sendmessage(reject, S, D);


## 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 Section5.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. Privacy-Preserving Reputation-Based 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 ofa be Ea using the Paillier cryptosystem. Also, an encrypted squared distance computation between an ESEV Sj at location locSj=xj,yj and an EBEV Di at location locDi=xi,yi is achieved using the following equations [38].
(4)Disti,j=∣locDi−locSj∣=xi−xj2+yi−yj2,EDisti,j=Exi2−2xixj+xj2+yi2−2yiyj+yj2.In the proposed model, each EV has PHE keys to encrypt the transactions between ESEV and EBEV. Furthermore, Algorithms2 and 3 are inspired from [38], which show the communication between EBEV and ESEV in a privacy-preserved manner.Algorithm 2: EBEV function.
Output: send distance;1:function EBEV()2:notmatched = True;3:  whilenotmatcheddo4:System broadcast the need for matching;5:if only one supplier S1 responds then6:S=S1;7:   else8:S = select the ESEV user with the highest-reputation points;9:Sendmessage(propose, D, S);10:msg = getMessage();11:if msg = accepted then12:add EBEV’s loc(x, y) and calculate encrypted squared distance;13:Sendmessage(encrypted(distance));14:notmatched = False;Algorithm 3: ESEV function.
Output: request result;1:function ESEV()2:notmatched = True;3:  whilenotmatcheddo4:msg=getMessage;5:   ifmsg.type=propose & Si accept proposal then6:respond with encrypted loc(x,y);7:Sendmessage(accept, S, D);8:notmatched = False;9:else10:Sendmessage(reject, S, D);


## 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 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.


### 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 hand-in-hand, 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. Thecreatestorage 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.Algorithm 4: Smart contract for energy trading.
Input: energy requested from EBEV;Output: (1) ESEV gives energy to EBEV; (2) EBEV sends money to ESEV;1:function EnergyTrading()2:if(EBEV available balance<EV’s charging cost)then3:returnfalse;4:if(ESEV available energy<EV’s requested energy)then5:returnfalse;6:if(EBEV storage<amount of energy purchased)then7:returnfalse;8:else9:Subtract amount from EBEV’s account balance;10:Add amount to ESEV account balance;11:Store transaction;12:Subtract energy from storage of ESEV;13:   Add energy to storage of EBEV;14:Store transaction;15returnupdated information;


### 5.2.2. 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: theviewing 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].
(5)RI=∑m=0MCredm×Rm∑m=0MCredm,whereI 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 Credm. Rm is the rating of node I given by EBEV m, and the total reputation points of node I is RI. 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.Algorithm 5: Smart contract for reputation.
Output: (1) EBEV rated ESEV; (2) EV view reputation points;1:function SubmitFeedback()2:Positive or negative rating point is added;3:returnTrue;4:function ViewFeedback()5:Returnaggregated feedback;


## 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 hand-in-hand, 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. Thecreatestorage 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.Algorithm 4: Smart contract for energy trading.
Input: energy requested from EBEV;Output: (1) ESEV gives energy to EBEV; (2) EBEV sends money to ESEV;1:function EnergyTrading()2:if(EBEV available balance<EV’s charging cost)then3:returnfalse;4:if(ESEV available energy<EV’s requested energy)then5:returnfalse;6:if(EBEV storage<amount of energy purchased)then7:returnfalse;8:else9:Subtract amount from EBEV’s account balance;10:Add amount to ESEV account balance;11:Store transaction;12:Subtract energy from storage of ESEV;13:   Add energy to storage of EBEV;14:Store transaction;15returnupdated information;


## 5.2.2. 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: theviewing 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].
(5)RI=∑m=0MCredm×Rm∑m=0MCredm,whereI 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 Credm. Rm is the rating of node I given by EBEV m, and the total reputation points of node I is RI. 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.Algorithm 5: Smart contract for reputation.
Output: (1) EBEV rated ESEV; (2) EV view reputation points;1:function SubmitFeedback()2:Positive or negative rating point is added;3:returnTrue;4:function ViewFeedback()5:Returnaggregated feedback;


## 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.
(6)y=α0+α1x1+α2x2+⋯+αrxr+ε,wherey is the EVs’ charging load consumption, x1,x2,⋯,xr are the independent variables, α1,α2,⋯,αr 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.
(7)y1=α0+α1x11+α2x12+⋯+αrx1r+ε1,y2=α0+α1x21+α2x22+⋯+αrx2r+ε2,⋯yi=α0+α1xi1+α2xi2+⋯+αrxir+εi,⋯yn=α0+α1xn1+α2xn2+⋯+αrxnr+εn.These equations are represented in the form of matrices as follows.(8)y=αX+ε,where,(9)y=y1y2...yn,X=x11x12⋯x1rx21x22⋯x2r...xn1xn2⋯xnr,α=α1α2...αr,ε=ε1ε2...εn.The matricesy and X 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.
(10)α=X′X−1X′y.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.
(11)y^=Xα.y^ is the forecasted value of y. In this model, error is the absolute difference between the actual and forecasted values.


## 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.
(6)y=α0+α1x1+α2x2+⋯+αrxr+ε,wherey is the EVs’ charging load consumption, x1,x2,⋯,xr are the independent variables, α1,α2,⋯,αr 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.
(7)y1=α0+α1x11+α2x12+⋯+αrx1r+ε1,y2=α0+α1x21+α2x22+⋯+αrx2r+ε2,⋯yi=α0+α1xi1+α2xi2+⋯+αrxir+εi,⋯yn=α0+α1xn1+α2xn2+⋯+αrxnr+εn.These equations are represented in the form of matrices as follows.(8)y=αX+ε,where,(9)y=y1y2...yn,X=x11x12⋯x1rx21x22⋯x2r...xn1xn2⋯xnr,α=α1α2...αr,ε=ε1ε2...εn.The matricesy and X 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.
(10)α=X′X−1X′y.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.
(11)y^=Xα.y^ is the forecasted value of y. 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 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, self-enforced 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.


### 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 factorS is used to define the threshold for the energy requirement. Based on the threshold, each consumer meets its minimum energy requirement S×Earq to avoid energy starvation. The SL parameter is calculated using the following equation [42].
(12)SL=1−EallocREarq×EallocR.At every time slot, AG receives details of providers’ excess energyEas and consumers’ energy request Earq. RSFEAP guarantees optimal prosumer-generated energy allocation EallocR to each consumer.


#### 6.2.2. 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.
(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 prosumersHence, RI is computed as follows.(13)Yi=1−e−θ/100,(14)θ=0,ifvalidtransaction,1,ifmalicioustransaction,(15)Ci=Ci−Ci×Yi,(16)RIi=CiCTotal.In Equations (13)–(16), Ci is the amount of energy contributions provided by a prosumer till the present interval and CTotal is the sum of the energy contributions recorded by AG till the present interval. Yi 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.


#### 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 consumeri 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.Algorithm 6: VMT algorithm.
Inputθi, Ci, CTotal;OutputCTotalandCi;1:function FindMaliciousTransaction(θi, Ci, CTotal)2:if(malicious transaction)then3:θi=θi+1;4:Yi=1−e−θ/100;5:Ci=Ci−Ci×Yi;6:UpdateCTotalwith newCi;7:else8:UpdateCi;9:UpdateCTotalwith newCi;10:returnCTotalandCi;


### 6.3. Optimization Formulation

AG optimally distributes energy to every consumer based on the aforementioned parameters. Hence, to efficiently allocate energyAiEi,allocR to meet the consumers’ demand, an optimization problem is formulated. The optimization formulation given in this research is similar to [42].
(17)max∑i∈CsAiEi,allocR,such that,S×Ei,arq≤Ei,allocR≤Ei,arq,(18)∑i∈CsEi,allocR≤E.According to the optimization problem given in Equation (17), some assumptions are made. AG will not distribute energy Ei,allocR to the consumer that will exceed its energy requirement (Ei,arq) and will fall below its starvation level (SL×Ei,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.
(19)AiEi,allocR=αRIiEi,allocR+βSLi.Solving the following constrained optimization problem, RSFEAP of AG is developed.(a)
Problem 1: let the set of all consumers be Cs=1,2,⋯,n, Earq¯=E1,arq,E2,arq,⋯,En,arq be the set of exact energy request by the consumers, and C¯=C1,C2,⋯,Cn be the set of energy contributions made by the prosumers. The optimal value of the optimization is computed using the following equation.(20)max∑i∈CsαRIiEi,allocR+βSLi,such thatS×Ei,arq≤Ei,allocR≤Ei,arq,(21)∑i∈CsEi,allocR≤E,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∈CsEi,allocR≤E, then all consumers are allocated with their requested energy, i.e., Ei,allocR=Ei,arq. On the other hand, an optimal energy allocation mechanism is used for the nontrivial case, i.e., when considering ∑i∈CsEi,allocR>E. In such a situation, one can obtain closed-form solution given by Theorem 1.(c)
Theorem 1: an optimized allocation of energy Ei,allocR∗=Ei,allocR∗∣i∈Cs from the defined problem is given below(22)Ei,allocR∗=αRIi+β−υ2βEi,arq,ifEi,allocR>S×Ei,arqand<Ei,arq,S×Ei,arq,ifEi,allocR≤S×Ei,arq,Ei,arq,otherwise,whereυ is a real number that satisfies ∑i∈CsEi,allocR∗=E.
(d)
The proof that shows that the objective function is concave:(23)AiEi,allocR=αRIiEi,allocR+βSLi,AiEi,allocR=αRIiEi,allocR+β1−EallocREarq×EallocR,Ai′Ei,allocR=αRIi+β−2βEallocREarq,Ai′′Ei,allocR=−2βEarqSince the second derivative of the objective function is negative where0<β≤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 Problem1 given as follows.(1)
Complementary slackness:(24)λihix∗=0.(2)
Primal feasibility:(25)hix∗≤0,gjx∗=0.(3)
Dual feasibility:(26)λi=0.(4)
Stationary:(27)0∈∂fx∗+∑i=1mλi∂hix∗+∑j=1rυj∂gjx∗.Generally, the constraint vectors are represented as single column vectors.(28)hx=h1xh2x⋮hmx,gx=g1xg2x⋮grx.We definem lagrange multipliers for λi inequality constraints and r multipliers υj for r equality constraints. Hence,
(29)λ=λ1λ2⋮λm,υ=υ1υ2⋮υr.From Equation (27), ∂fx∗ is derived as given in the following equation.
(30)∂fx∗=∂AiEi,allocR,which is further simplified to the following equation:
(31)∂fx∗=αRIi+β−2βEi,allocR∗Ei,arq.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.
(32)∑i=1m∂hix∗=−λi+φi.And the last term in Equation (27), can be shown as
(33)∑j=1r∂gjx∗=υ.By solving Equations (31), (32), and (33), the stationary condition in Equation (27) is satisfied, which is expressed in the following equation.
(34)αRIi+β−2βEi,allocR∗Ei,arq+λi−φ−υ=0.In the primal feasibility condition,hix∗≤0, and gjx∗≤0 is solved as
(35)S×Ei,arq−Ei,allocR∗≤0,(36)Ei,allocR∗−Ei,arq≤0,where Equations (35) and (36) give the following equation.
(37)∑i=1nEi,allocR∗≤0,while the complementary slackness condition is shown as(38)λiS×Ei,arq−Ei,allocR∗=0,(39)φiEi,allocR∗−Ei,arq=0.Finally, the dual feasibility condition in Equation (26) is expressed in the following equation.
(40)λi=0,φi=0.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 Ei,allocR∗: S×Ei,arq≤Ei,allocR∗≤Ei,arq, Ei,allocR∗=Ei,arq, and S×Ei,arq=Ei,allocR∗. We first consider a case S×Ei,arq≤Ei,allocR∗≤Ei,arq. It is clear that λi=0 and φi=0. The λi and φi values are then substituted in the stationary condition in Equation ((27)), and the result of Ei,allocR∗ is generated as follows.
(41)αRIi+β−2βEi,allocR∗Ei,arq−υ=0,(42)αRIi+β−υ=2βEi,allocR∗Ei,arq,where Equation (42) is further simplified to give the following equation.
(43)αRIi+β−υ2βEi,arq=Ei,allocR∗.Considering a caseEi,allocR∗=Ei,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 Ei,allocR∗ results are given as follows.
(44)αRIi+β−2βEi,allocR∗Ei,arq−φi−υ=0,(45)αRIi+β−υEi,arq2β−Ei,allocR∗=φiEi,arq2β,where Equations (44) and (45) are further simplified to give the following equation:
(46)αRIi+β−υEi,arq2β=Ei,allocR∗+φiEi,arq2β≥0,which produces
(47)αRIi+β−υEi,arq2β≥Ei,arq.Furthermore, we consider a caseS×Ei,arq=Ei,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 Ei,allocR∗ results are given in Equations (48)–(51).
(48)αRIi+β−2βEi,allocR∗Ei,arq+λi−υ=0,(49)αRIi+β−υEi,arq2β−Ei,allocR∗=−λiEi,arq2β,(50)αRIi+β−υEi,arq2β=Ei,allocR∗−λiEi,arq2β≥0,which produce
(51)αRIi+β−υEi,arq2β≥S×Ei,arq.Therefore, there exists an optimal allocation of energyEi,allocR∗=Ei,allocR∗∣i∈Cs 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.


### 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 isE and the total energy needed by the energy consumers is Ec. 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 consumersEc is less than or equal to the total energy available E(2)
When the total energy request from consumersEc is greater than the total energy available EIn 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 Algorithm7 (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 quadprogfunction (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 fT, 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. fT (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×Ei,arq≤Ei,allocR≤Ei,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 quadprogfunction to be executed and return the optimal energy allocation vector EallocR.


## 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, self-enforced 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.


## 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 factorS is used to define the threshold for the energy requirement. Based on the threshold, each consumer meets its minimum energy requirement S×Earq to avoid energy starvation. The SL parameter is calculated using the following equation [42].
(12)SL=1−EallocREarq×EallocR.At every time slot, AG receives details of providers’ excess energyEas and consumers’ energy request Earq. RSFEAP guarantees optimal prosumer-generated energy allocation EallocR to each consumer.


### 6.2.2. 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.
(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 prosumersHence, RI is computed as follows.(13)Yi=1−e−θ/100,(14)θ=0,ifvalidtransaction,1,ifmalicioustransaction,(15)Ci=Ci−Ci×Yi,(16)RIi=CiCTotal.In Equations (13)–(16), Ci is the amount of energy contributions provided by a prosumer till the present interval and CTotal is the sum of the energy contributions recorded by AG till the present interval. Yi 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.


### 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 consumeri 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.Algorithm 6: VMT algorithm.
Inputθi, Ci, CTotal;OutputCTotalandCi;1:function FindMaliciousTransaction(θi, Ci, CTotal)2:if(malicious transaction)then3:θi=θi+1;4:Yi=1−e−θ/100;5:Ci=Ci−Ci×Yi;6:UpdateCTotalwith newCi;7:else8:UpdateCi;9:UpdateCTotalwith newCi;10:returnCTotalandCi;


## 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 factorS is used to define the threshold for the energy requirement. Based on the threshold, each consumer meets its minimum energy requirement S×Earq to avoid energy starvation. The SL parameter is calculated using the following equation [42].
(12)SL=1−EallocREarq×EallocR.At every time slot, AG receives details of providers’ excess energyEas and consumers’ energy request Earq. RSFEAP guarantees optimal prosumer-generated energy allocation EallocR to each consumer.


## 6.2.2. 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.
(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 prosumersHence, RI is computed as follows.(13)Yi=1−e−θ/100,(14)θ=0,ifvalidtransaction,1,ifmalicioustransaction,(15)Ci=Ci−Ci×Yi,(16)RIi=CiCTotal.In Equations (13)–(16), Ci is the amount of energy contributions provided by a prosumer till the present interval and CTotal is the sum of the energy contributions recorded by AG till the present interval. Yi 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.


## 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 consumeri 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.Algorithm 6: VMT algorithm.
Inputθi, Ci, CTotal;OutputCTotalandCi;1:function FindMaliciousTransaction(θi, Ci, CTotal)2:if(malicious transaction)then3:θi=θi+1;4:Yi=1−e−θ/100;5:Ci=Ci−Ci×Yi;6:UpdateCTotalwith newCi;7:else8:UpdateCi;9:UpdateCTotalwith newCi;10:returnCTotalandCi;


## 6.3. Optimization Formulation

AG optimally distributes energy to every consumer based on the aforementioned parameters. Hence, to efficiently allocate energyAiEi,allocR to meet the consumers’ demand, an optimization problem is formulated. The optimization formulation given in this research is similar to [42].
(17)max∑i∈CsAiEi,allocR,such that,S×Ei,arq≤Ei,allocR≤Ei,arq,(18)∑i∈CsEi,allocR≤E.According to the optimization problem given in Equation (17), some assumptions are made. AG will not distribute energy Ei,allocR to the consumer that will exceed its energy requirement (Ei,arq) and will fall below its starvation level (SL×Ei,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.
(19)AiEi,allocR=αRIiEi,allocR+βSLi.Solving the following constrained optimization problem, RSFEAP of AG is developed.(a)
Problem 1: let the set of all consumers be Cs=1,2,⋯,n, Earq¯=E1,arq,E2,arq,⋯,En,arq be the set of exact energy request by the consumers, and C¯=C1,C2,⋯,Cn be the set of energy contributions made by the prosumers. The optimal value of the optimization is computed using the following equation.(20)max∑i∈CsαRIiEi,allocR+βSLi,such thatS×Ei,arq≤Ei,allocR≤Ei,arq,(21)∑i∈CsEi,allocR≤E,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∈CsEi,allocR≤E, then all consumers are allocated with their requested energy, i.e., Ei,allocR=Ei,arq. On the other hand, an optimal energy allocation mechanism is used for the nontrivial case, i.e., when considering ∑i∈CsEi,allocR>E. In such a situation, one can obtain closed-form solution given by Theorem 1.(c)
Theorem 1: an optimized allocation of energy Ei,allocR∗=Ei,allocR∗∣i∈Cs from the defined problem is given below(22)Ei,allocR∗=αRIi+β−υ2βEi,arq,ifEi,allocR>S×Ei,arqand<Ei,arq,S×Ei,arq,ifEi,allocR≤S×Ei,arq,Ei,arq,otherwise,whereυ is a real number that satisfies ∑i∈CsEi,allocR∗=E.
(d)
The proof that shows that the objective function is concave:(23)AiEi,allocR=αRIiEi,allocR+βSLi,AiEi,allocR=αRIiEi,allocR+β1−EallocREarq×EallocR,Ai′Ei,allocR=αRIi+β−2βEallocREarq,Ai′′Ei,allocR=−2βEarqSince the second derivative of the objective function is negative where0<β≤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 Problem1 given as follows.(1)
Complementary slackness:(24)λihix∗=0.(2)
Primal feasibility:(25)hix∗≤0,gjx∗=0.(3)
Dual feasibility:(26)λi=0.(4)
Stationary:(27)0∈∂fx∗+∑i=1mλi∂hix∗+∑j=1rυj∂gjx∗.Generally, the constraint vectors are represented as single column vectors.(28)hx=h1xh2x⋮hmx,gx=g1xg2x⋮grx.We definem lagrange multipliers for λi inequality constraints and r multipliers υj for r equality constraints. Hence,
(29)λ=λ1λ2⋮λm,υ=υ1υ2⋮υr.From Equation (27), ∂fx∗ is derived as given in the following equation.
(30)∂fx∗=∂AiEi,allocR,which is further simplified to the following equation:
(31)∂fx∗=αRIi+β−2βEi,allocR∗Ei,arq.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.
(32)∑i=1m∂hix∗=−λi+φi.And the last term in Equation (27), can be shown as
(33)∑j=1r∂gjx∗=υ.By solving Equations (31), (32), and (33), the stationary condition in Equation (27) is satisfied, which is expressed in the following equation.
(34)αRIi+β−2βEi,allocR∗Ei,arq+λi−φ−υ=0.In the primal feasibility condition,hix∗≤0, and gjx∗≤0 is solved as
(35)S×Ei,arq−Ei,allocR∗≤0,(36)Ei,allocR∗−Ei,arq≤0,where Equations (35) and (36) give the following equation.
(37)∑i=1nEi,allocR∗≤0,while the complementary slackness condition is shown as(38)λiS×Ei,arq−Ei,allocR∗=0,(39)φiEi,allocR∗−Ei,arq=0.Finally, the dual feasibility condition in Equation (26) is expressed in the following equation.
(40)λi=0,φi=0.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 Ei,allocR∗: S×Ei,arq≤Ei,allocR∗≤Ei,arq, Ei,allocR∗=Ei,arq, and S×Ei,arq=Ei,allocR∗. We first consider a case S×Ei,arq≤Ei,allocR∗≤Ei,arq. It is clear that λi=0 and φi=0. The λi and φi values are then substituted in the stationary condition in Equation ((27)), and the result of Ei,allocR∗ is generated as follows.
(41)αRIi+β−2βEi,allocR∗Ei,arq−υ=0,(42)αRIi+β−υ=2βEi,allocR∗Ei,arq,where Equation (42) is further simplified to give the following equation.
(43)αRIi+β−υ2βEi,arq=Ei,allocR∗.Considering a caseEi,allocR∗=Ei,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 Ei,allocR∗ results are given as follows.
(44)αRIi+β−2βEi,allocR∗Ei,arq−φi−υ=0,(45)αRIi+β−υEi,arq2β−Ei,allocR∗=φiEi,arq2β,where Equations (44) and (45) are further simplified to give the following equation:
(46)αRIi+β−υEi,arq2β=Ei,allocR∗+φiEi,arq2β≥0,which produces
(47)αRIi+β−υEi,arq2β≥Ei,arq.Furthermore, we consider a caseS×Ei,arq=Ei,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 Ei,allocR∗ results are given in Equations (48)–(51).
(48)αRIi+β−2βEi,allocR∗Ei,arq+λi−υ=0,(49)αRIi+β−υEi,arq2β−Ei,allocR∗=−λiEi,arq2β,(50)αRIi+β−υEi,arq2β=Ei,allocR∗−λiEi,arq2β≥0,which produce
(51)αRIi+β−υEi,arq2β≥S×Ei,arq.Therefore, there exists an optimal allocation of energyEi,allocR∗=Ei,allocR∗∣i∈Cs 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.


## 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 isE and the total energy needed by the energy consumers is Ec. 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 consumersEc is less than or equal to the total energy available E(2)
When the total energy request from consumersEc is greater than the total energy available EIn 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 Algorithm7 (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 quadprogfunction (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 fT, 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. fT (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×Ei,arq≤Ei,allocR≤Ei,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 quadprogfunction to be executed and return the optimal energy allocation vector EallocR.


## 7. Proposed Methodology

Algorithm 7: RSFEAP algorithm.
Input:Earq, Eas, C;Output:EallocR;1:t=1;2:whilet≤Ntime-slotsdo3:E=∑i=1kEi,as;4:Ec=∑i=1kEi,arq;5:CTotal=∑i=1kCi;6:ComputeRIfor each consumer using Equation ((16));7:ifEc≤Ethen8:fori=1tonnumber of consumersdo9:Ei,allocR=Ei,arq;10:else11:fEi,allocR=∑i∈CsαRIiEi,allocR+β1−Ei,allocR/Ei,arq·Ei,allocR;12:fEi,allocR=1/2Ei,allocRTHEi,allocR+fTEi,allocR;13:14:H=a110⋯00a22⋯0⋮⋮⋱⋮00⋯ann, fT=a11a22⋮ann;15:16:A=a11a22⋯ann, b=E1;17:18:ub=E1,arqE2,arq⋮En,arq, lb=S×E1,arqS×E2,arq⋮S×En,arq;19:20:Ei,allocR=quadprogrH,f,A,b,lb,ub;21:t++;


### 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., 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.


### 7.2. Bilinear Map Theory

This section presents bilinear map theory as follows.(i)
The three cyclic groups of prime orderP are denoted as G1,G2, and G3(ii)
g1 and g2 are generated from G1 and G2, respectively, as g1∈G1 and g2∈G2(iii)
Bilinear map is presented ase,:G1×G2⟶G3The bilinear map properties are given as follows:(i)
Nondegenerate: eg1,g2≠1(ii)
Bilinear: ∀v∈G1,∀u∈G2, and b,a∈ℤ, we have evb,ua=ev,ubaThe 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 curvesG1,G2 such that ∣G1∣=∣G2∣=q,e,:G1×G1⟶G2 is a bilinear map and P∈G1 is a generator. s∈ℤq∗ is randomly selected, and s is defined as the master key where Ppub=s·P can be calculated. Let h:0,1n⟶G1,h1:0,1n⟶G2, and h2:0,1n⟶ℤq∗ be the three cryptographic hash functions. The system’s parameters are published as G1,G2,e,,n,q,P,Ppub,h,h1,h2.


#### 7.2.2. Generating Private and Public Keys

(i)
UserA registers with AG using its ID number and personal information(ii)
The client generates a public key based on the ID ofA, which produces Πid=hid(iii)
Private Key Generator (PKG) calculates theA’s private key locally as Sid=s.Πid, then passes it to A via a secure channel


#### 7.2.3. Sending Message to the Blockchain

(i)
Initially, userA encrypts a private message M as follows(a)
Picksr∈ℤq∗(b)
Calculatesgid=eΠid,Ppub, V=r·P(c)
U=M⊗h1gidr(ii)
After encryption, the user sends the encrypted messageV,U to the blockchain


#### 7.2.4. Getting Message from the Blockchain

(i)
System sends encrypted messageV,U to A and A decrypts data as follows
(a)
M=U⊗h1eSid,V, where M is just the plaintext


## 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., 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.


## 7.2. Bilinear Map Theory

This section presents bilinear map theory as follows.(i)
The three cyclic groups of prime orderP are denoted as G1,G2, and G3(ii)
g1 and g2 are generated from G1 and G2, respectively, as g1∈G1 and g2∈G2(iii)
Bilinear map is presented ase,:G1×G2⟶G3The bilinear map properties are given as follows:(i)
Nondegenerate: eg1,g2≠1(ii)
Bilinear: ∀v∈G1,∀u∈G2, and b,a∈ℤ, we have evb,ua=ev,ubaThe 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 curvesG1,G2 such that ∣G1∣=∣G2∣=q,e,:G1×G1⟶G2 is a bilinear map and P∈G1 is a generator. s∈ℤq∗ is randomly selected, and s is defined as the master key where Ppub=s·P can be calculated. Let h:0,1n⟶G1,h1:0,1n⟶G2, and h2:0,1n⟶ℤq∗ be the three cryptographic hash functions. The system’s parameters are published as G1,G2,e,,n,q,P,Ppub,h,h1,h2.


### 7.2.2. Generating Private and Public Keys

(i)
UserA registers with AG using its ID number and personal information(ii)
The client generates a public key based on the ID ofA, which produces Πid=hid(iii)
Private Key Generator (PKG) calculates theA’s private key locally as Sid=s.Πid, then passes it to A via a secure channel


### 7.2.3. Sending Message to the Blockchain

(i)
Initially, userA encrypts a private message M as follows(a)
Picksr∈ℤq∗(b)
Calculatesgid=eΠid,Ppub, V=r·P(c)
U=M⊗h1gidr(ii)
After encryption, the user sends the encrypted messageV,U to the blockchain


### 7.2.4. Getting Message from the Blockchain

(i)
System sends encrypted messageV,U to A and A decrypts data as follows
(a)
M=U⊗h1eSid,V, where M is just the plaintext


## 7.2.1. Initialization

Construct two groups of elliptic curvesG1,G2 such that ∣G1∣=∣G2∣=q,e,:G1×G1⟶G2 is a bilinear map and P∈G1 is a generator. s∈ℤq∗ is randomly selected, and s is defined as the master key where Ppub=s·P can be calculated. Let h:0,1n⟶G1,h1:0,1n⟶G2, and h2:0,1n⟶ℤq∗ be the three cryptographic hash functions. The system’s parameters are published as G1,G2,e,,n,q,P,Ppub,h,h1,h2.


## 7.2.2. Generating Private and Public Keys

(i)
UserA registers with AG using its ID number and personal information(ii)
The client generates a public key based on the ID ofA, which produces Πid=hid(iii)
Private Key Generator (PKG) calculates theA’s private key locally as Sid=s.Πid, then passes it to A via a secure channel


## 7.2.3. Sending Message to the Blockchain

(i)
Initially, userA encrypts a private message M as follows(a)
Picksr∈ℤq∗(b)
Calculatesgid=eΠid,Ppub, V=r·P(c)
U=M⊗h1gidr(ii)
After encryption, the user sends the encrypted messageV,U to the blockchain


## 7.2.4. Getting Message from the Blockchain

(i)
System sends encrypted messageV,U to A and A decrypts data as follows
(a)
M=U⊗h1eSid,V, where M 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 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.


### 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 ID-based 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 usersQ1.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 systemQ2.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 systemQ2.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.


### 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 Table2. 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.Table 2
Report of the security vulnerability using Oyente tool for energy trading and reputation smart contracts.
Parameters12EVM code coverage47.9%42.5%Integer underflowFalseFalseInteger overflowFalseFalseParity multisig bug 2FalseFalseCallstack depth attack vulnerabilityFalseFalseTransaction-ordering dependence (TOD)FalseFalseTimestamp dependenceFalseFalseReentrancy vulnerabilityFalseFalse1: energy trading contract; 2: reputation contract.


## 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.


## 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 ID-based 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 usersQ1.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 systemQ2.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 systemQ2.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.


## 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 Table2. 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.Table 2
Report of the security vulnerability using Oyente tool for energy trading and reputation smart contracts.
Parameters12EVM code coverage47.9%42.5%Integer underflowFalseFalseInteger overflowFalseFalseParity multisig bug 2FalseFalseCallstack depth attack vulnerabilityFalseFalseTransaction-ordering dependence (TOD)FalseFalseTimestamp dependenceFalseFalseReentrancy vulnerabilityFalseFalse1: energy trading contract; 2: reputation contract.


## 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, 512-bit primes forq and p, 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 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 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.Figure 3
Normalized EVs’ load consumption.


### 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](52)RMSE=∑i=1wyi−y^i2yi,(53)MAPE=1w∑i=1wyi−y^iyi,(54)MAE=1w∑i=1wyi−y^i,(55)MSE=∑i=1wyi−y^i2w,whereyi and y^i are the actual and forecasted EVs’ charging loads at point i, respectively, while the total number of EVs’ charging points is w.
(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 Reputation-Based Privacy-Preservation for the Matching EVs

In Figure4, 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. 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.Figure 4
Total convergence duration of the proposed matching of EBEV with ESEV.


#### 9.2.3. Results of Reputation and Energy Trading Using Blockchain

Smart contracts are deployed to perform energy trading between EBEVs and ESEVs. Tables3 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, SellEnergy, 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 ContractCreation which consume the least cost as the functions do not require additional uploading data.Table 3
Energy trading smart contract cost.
Function123GiveKwh43257205776.3834E-14CreateStorage1269061048662.31772E-13SellEnergy237967962.4592E-14BuyEnergy235745742.4148E-14Contract creation182652113351253.16165E-121: transactional cost (Gwei); 2: executional cost (Gwei); 3: actual cost (Ether).Table 4
Reputation smart contract cost.
Function123Submit feedback4406974170578.57754E-13Contract creation201761714789413.49656E-121: transactional cost (Gwei); 2: executional cost (Gwei); 3: actual cost (Ether).


#### 9.2.4. 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 Figure5. 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%.Figure 5
EV load forecasting model.Figure 6
Comparison of actual and forecasted EVs’ energy load consumption.Table 5
Forecasting error comparison.
MSEMAERMSEMAPEAccuracy0.01880.61610.75010.748099.2519From Figure6, 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.


#### 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 blockchain-based 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 ID-based encryption technique is incorporated into the system that helps to conceal energy transactional data.Table 6
Overall energy allocation.
SlotEareqMWhEcMWhEMWhEasMWhEallocRMWh RSFEAPEallocMWh SF-OEAPRIT1−18,−9,0,027220,0,15,714.8,7.2,0,014.8,7.2,0,020,20,30,15T2−6,−11,−11,028230,0,0,234.8,8.8,9.4,04.8,8.8,9.4,05,30,45,30T3−8,0,−17,025210,4,0,46.4,0,14.6,06.4,0,14.6,05,30,30,20T4−15,−17,0,032260,0,13,1312,14,0,012,14,0,05,30,30,20InT1, two prosumers, i.e., Prosumer1 and Prosumer2, which are energy consumers, register their energy requests as 18 MWh and 9 MWh, respectively. On the other hand, Prosumer3 and Prosumer4, 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 Ec using the proposed RFEAP algorithm, i.e., Algorithm 7. If Ec≤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., Ec>E, for optimal allocation of energy between consumers that use the novel RI-based algorithm. Considering the situation in T1, Ec>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 Prosumer1 and Prosumer2 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, Prosumer1, Prosumer2, and Prosumer3 are all energy consumers while Prosumer4 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 Consumer3 gets higher consideration for the allocation of energy because it has higher RI value than both Prosumers1 and 2. Moreover, Prosumer2 gets higher preference than Prosumer1 because of the similar reason for Prosumer3. 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 Figures7–11 depict that the prosumers are energy providers at those time intervals during fair energy allocation. The energy allocation for Prosumer1 across all the four time intervals is given in Figure 11. It is observed that the RI of Prosumer1 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 all of the time slots is presented in Figures 12–15. Important ratios, i.e., RIi/SumRI¯, Ei,allocR/E, and Ei,arq/Ec for the energy prosumers are investigated during the fair energy distribution. Here, RIi/SumRI¯ is the ratio of each energy consumer’s RI to the total RI of all the energy consumers, Ei,allocR/E is the ratio of each allocated energy for a consumer to the sum of all the surplus energy during the allocation, and Ei,arq/Ec 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 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.Figure 7
Comparison of allocated energy (Ei,allocR) to prosumers at T1 time slot.Figure 8
Comparison of allocated energy (Ei,allocR) to prosumers at T2 time slot.Figure 9
Comparison of allocated energy (Ei,allocR) to prosumers at T3 time slot.Figure 10
Comparison of allocated energy (Ei,allocR) to prosumers at T4 time slot.Figure 11
Comparison of energy allocated (E1,allocR) to consumer-1 in each time slot.Figure 12
Impact of reward index on energy allocation to prosumers atT1 time slot.Figure 13
Impact of reward index on energy allocation to prosumers atT2 time slot.Figure 14
Impact of reward index on energy allocation to prosumers atT3 time slot.Figure 15
Impact of reward index on energy allocation to prosumers atT4 time slot.Figure 16
The valid and malicious transactions in the system.Figure 17
Impact of malicious transactions in the energy contribution forC2, C3, and C4.Figure 18
The effects of contributions on energy allocation.Figure 19
Average convergence time against the number of prosumers.Figure 20
Number of maximum iterations against number of prosumers.


## 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, 512-bit primes forq and p, 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 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 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.Figure 3
Normalized EVs’ load consumption.


## 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](52)RMSE=∑i=1wyi−y^i2yi,(53)MAPE=1w∑i=1wyi−y^iyi,(54)MAE=1w∑i=1wyi−y^i,(55)MSE=∑i=1wyi−y^i2w,whereyi and y^i are the actual and forecasted EVs’ charging loads at point i, respectively, while the total number of EVs’ charging points is w.
(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 Reputation-Based Privacy-Preservation for the Matching EVs

In Figure4, 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. 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.Figure 4
Total convergence duration of the proposed matching of EBEV with ESEV.


### 9.2.3. Results of Reputation and Energy Trading Using Blockchain

Smart contracts are deployed to perform energy trading between EBEVs and ESEVs. Tables3 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, SellEnergy, 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 ContractCreation which consume the least cost as the functions do not require additional uploading data.Table 3
Energy trading smart contract cost.
Function123GiveKwh43257205776.3834E-14CreateStorage1269061048662.31772E-13SellEnergy237967962.4592E-14BuyEnergy235745742.4148E-14Contract creation182652113351253.16165E-121: transactional cost (Gwei); 2: executional cost (Gwei); 3: actual cost (Ether).Table 4
Reputation smart contract cost.
Function123Submit feedback4406974170578.57754E-13Contract creation201761714789413.49656E-121: transactional cost (Gwei); 2: executional cost (Gwei); 3: actual cost (Ether).


### 9.2.4. 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 Figure5. 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%.Figure 5
EV load forecasting model.Figure 6
Comparison of actual and forecasted EVs’ energy load consumption.Table 5
Forecasting error comparison.
MSEMAERMSEMAPEAccuracy0.01880.61610.75010.748099.2519From Figure6, 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.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](52)RMSE=∑i=1wyi−y^i2yi,(53)MAPE=1w∑i=1wyi−y^iyi,(54)MAE=1w∑i=1wyi−y^i,(55)MSE=∑i=1wyi−y^i2w,whereyi and y^i are the actual and forecasted EVs’ charging loads at point i, respectively, while the total number of EVs’ charging points is w.
(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 Reputation-Based Privacy-Preservation for the Matching EVs

In Figure4, 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. 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.Figure 4
Total convergence duration of the proposed matching of EBEV with ESEV.


## 9.2.3. Results of Reputation and Energy Trading Using Blockchain

Smart contracts are deployed to perform energy trading between EBEVs and ESEVs. Tables3 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, SellEnergy, 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 ContractCreation which consume the least cost as the functions do not require additional uploading data.Table 3
Energy trading smart contract cost.
Function123GiveKwh43257205776.3834E-14CreateStorage1269061048662.31772E-13SellEnergy237967962.4592E-14BuyEnergy235745742.4148E-14Contract creation182652113351253.16165E-121: transactional cost (Gwei); 2: executional cost (Gwei); 3: actual cost (Ether).Table 4
Reputation smart contract cost.
Function123Submit feedback4406974170578.57754E-13Contract creation201761714789413.49656E-121: transactional cost (Gwei); 2: executional cost (Gwei); 3: actual cost (Ether).


## 9.2.4. 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 Figure5. 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%.Figure 5
EV load forecasting model.Figure 6
Comparison of actual and forecasted EVs’ energy load consumption.Table 5
Forecasting error comparison.
MSEMAERMSEMAPEAccuracy0.01880.61610.75010.748099.2519From Figure6, 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.


### 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 blockchain-based 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 ID-based encryption technique is incorporated into the system that helps to conceal energy transactional data.Table 6
Overall energy allocation.
SlotEareqMWhEcMWhEMWhEasMWhEallocRMWh RSFEAPEallocMWh SF-OEAPRIT1−18,−9,0,027220,0,15,714.8,7.2,0,014.8,7.2,0,020,20,30,15T2−6,−11,−11,028230,0,0,234.8,8.8,9.4,04.8,8.8,9.4,05,30,45,30T3−8,0,−17,025210,4,0,46.4,0,14.6,06.4,0,14.6,05,30,30,20T4−15,−17,0,032260,0,13,1312,14,0,012,14,0,05,30,30,20InT1, two prosumers, i.e., Prosumer1 and Prosumer2, which are energy consumers, register their energy requests as 18 MWh and 9 MWh, respectively. On the other hand, Prosumer3 and Prosumer4, 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 Ec using the proposed RFEAP algorithm, i.e., Algorithm 7. If Ec≤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., Ec>E, for optimal allocation of energy between consumers that use the novel RI-based algorithm. Considering the situation in T1, Ec>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 Prosumer1 and Prosumer2 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, Prosumer1, Prosumer2, and Prosumer3 are all energy consumers while Prosumer4 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 Consumer3 gets higher consideration for the allocation of energy because it has higher RI value than both Prosumers1 and 2. Moreover, Prosumer2 gets higher preference than Prosumer1 because of the similar reason for Prosumer3. 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 Figures7–11 depict that the prosumers are energy providers at those time intervals during fair energy allocation. The energy allocation for Prosumer1 across all the four time intervals is given in Figure 11. It is observed that the RI of Prosumer1 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 all of the time slots is presented in Figures 12–15. Important ratios, i.e., RIi/SumRI¯, Ei,allocR/E, and Ei,arq/Ec for the energy prosumers are investigated during the fair energy distribution. Here, RIi/SumRI¯ is the ratio of each energy consumer’s RI to the total RI of all the energy consumers, Ei,allocR/E is the ratio of each allocated energy for a consumer to the sum of all the surplus energy during the allocation, and Ei,arq/Ec 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 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.Figure 7
Comparison of allocated energy (Ei,allocR) to prosumers at T1 time slot.Figure 8
Comparison of allocated energy (Ei,allocR) to prosumers at T2 time slot.Figure 9
Comparison of allocated energy (Ei,allocR) to prosumers at T3 time slot.Figure 10
Comparison of allocated energy (Ei,allocR) to prosumers at T4 time slot.Figure 11
Comparison of energy allocated (E1,allocR) to consumer-1 in each time slot.Figure 12
Impact of reward index on energy allocation to prosumers atT1 time slot.Figure 13
Impact of reward index on energy allocation to prosumers atT2 time slot.Figure 14
Impact of reward index on energy allocation to prosumers atT3 time slot.Figure 15
Impact of reward index on energy allocation to prosumers atT4 time slot.Figure 16
The valid and malicious transactions in the system.Figure 17
Impact of malicious transactions in the energy contribution forC2, C3, and C4.Figure 18
The effects of contributions on energy allocation.Figure 19
Average convergence time against the number of prosumers.Figure 20
Number of maximum iterations against number of prosumers.


## 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 blockchain-based 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 ID-based encryption technique is incorporated into the system that helps to conceal energy transactional data.Table 6
Overall energy allocation.
SlotEareqMWhEcMWhEMWhEasMWhEallocRMWh RSFEAPEallocMWh SF-OEAPRIT1−18,−9,0,027220,0,15,714.8,7.2,0,014.8,7.2,0,020,20,30,15T2−6,−11,−11,028230,0,0,234.8,8.8,9.4,04.8,8.8,9.4,05,30,45,30T3−8,0,−17,025210,4,0,46.4,0,14.6,06.4,0,14.6,05,30,30,20T4−15,−17,0,032260,0,13,1312,14,0,012,14,0,05,30,30,20InT1, two prosumers, i.e., Prosumer1 and Prosumer2, which are energy consumers, register their energy requests as 18 MWh and 9 MWh, respectively. On the other hand, Prosumer3 and Prosumer4, 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 Ec using the proposed RFEAP algorithm, i.e., Algorithm 7. If Ec≤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., Ec>E, for optimal allocation of energy between consumers that use the novel RI-based algorithm. Considering the situation in T1, Ec>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 Prosumer1 and Prosumer2 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, Prosumer1, Prosumer2, and Prosumer3 are all energy consumers while Prosumer4 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 Consumer3 gets higher consideration for the allocation of energy because it has higher RI value than both Prosumers1 and 2. Moreover, Prosumer2 gets higher preference than Prosumer1 because of the similar reason for Prosumer3. 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 Figures7–11 depict that the prosumers are energy providers at those time intervals during fair energy allocation. The energy allocation for Prosumer1 across all the four time intervals is given in Figure 11. It is observed that the RI of Prosumer1 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 all of the time slots is presented in Figures 12–15. Important ratios, i.e., RIi/SumRI¯, Ei,allocR/E, and Ei,arq/Ec for the energy prosumers are investigated during the fair energy distribution. Here, RIi/SumRI¯ is the ratio of each energy consumer’s RI to the total RI of all the energy consumers, Ei,allocR/E is the ratio of each allocated energy for a consumer to the sum of all the surplus energy during the allocation, and Ei,arq/Ec 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 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.Figure 7
Comparison of allocated energy (Ei,allocR) to prosumers at T1 time slot.Figure 8
Comparison of allocated energy (Ei,allocR) to prosumers at T2 time slot.Figure 9
Comparison of allocated energy (Ei,allocR) to prosumers at T3 time slot.Figure 10
Comparison of allocated energy (Ei,allocR) to prosumers at T4 time slot.Figure 11
Comparison of energy allocated (E1,allocR) to consumer-1 in each time slot.Figure 12
Impact of reward index on energy allocation to prosumers atT1 time slot.Figure 13
Impact of reward index on energy allocation to prosumers atT2 time slot.Figure 14
Impact of reward index on energy allocation to prosumers atT3 time slot.Figure 15
Impact of reward index on energy allocation to prosumers atT4 time slot.Figure 16
The valid and malicious transactions in the system.Figure 17
Impact of malicious transactions in the energy contribution forC2, C3, and C4.Figure 18
The effects of contributions on energy allocation.Figure 19
Average convergence time against the number of prosumers.Figure 20
Number of maximum iterations against number of prosumers.


## 10. 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 short-term 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.



---

*Source: 6953125-2022-01-17.xml*