Blockchain Based Sustainable Local Energy Trading Considering Home Energy Management and Demurrage Mechanism

With the increase in local energy generation from Renewable Energy Sources (RESs), the concept of decentralized peer-to-peer Local Energy Market (LEM) is becoming popular. In this paper, a blockchain-based LEM is investigated, where consumers and prosumers in a small community trade energy without the need for a third party. In the proposed model, a Home Energy Management (HEM) system and demurrage mechanism are introduced, which allow both the prosumers and consumers to optimize their energy consumption and to minimize electricity costs. This method also allows end-users to shift their load to off-peak hours and to use cheap energy from the LEM. The proposed solution shows how energy consumption and electricity cost are optimized using HEM and demurrage mechanism. It also provides economic benefits at both the community and end-user levels and provides sufficient energy to the LEM. The simulation results show that electricity cost is reduced up to 44.73% and 28.55% when the scheduling algorithm is applied using the Critical Peak Price (CPP) and Real-Time Price (RTP) schemes, respectively. Similarly, 65.15% and 35.09% of costs are reduced when CPP and RTP are applied with demurrage mechanism. Moreover, 51.80% and 44.37% electricity costs reduction is observed when CPP and RTP are used with both demurrage and scheduling algorithm. We also carried out security vulnerability analysis to ensure that our energy trading smart contract is secure and bug-free against the common vulnerabilities and attacks.


Introduction
Currently, energy is primarily produced by large, centralized energy-plant rendering through Nonrenewable Energy Sources (NRESs). The use of centralized energy plants run by NRESs causes energy losses during power transmission and environmental degradation. The high penetration of Renewable Energy Sources (RESs) into the power system reduces the environmental crisis and the energy losses as energy is generated close to where it is consumed. Another solution to centralized energy generation is the introduction of Distributed Energy Resources (DERs). DER increases the overall cost savings for the customer, allows consumers to control their power, and reduces gas emissions by shifting from NRES to RES.
As a result of the rapid increase in DERs' connections, conventional consumers of energy are transforming into prosumers, i.e., someone who simultaneously generates and consumes energy. DER simply mean electricity resources, which are connected directly to Low Voltage (LV) or Medium Voltage (MV) distributed system [1]. DERs include both energy storage technology and generation units such as flywheels, batteries, Superconducting Magnetic Energy Storage (SMES), Photovoltaics (PVs), micro-turbines, and Electric Vehicles (EV) as illustrated in Figure 1, and Nomenclature shows the list of abbreviations and symbols in this research work. The figure depicts the technologies that support the DER system. For more information about technologies mentioned in the figure, please refer to Reference [1]. It is challenging to forecast the intermittent energy generation of DER. Due to this issue, prosumers curtail their surplus electricity, store it in a device, transport it to the main grid, or trade it with neighbors (other consumers) [2]. Customer in this paper refers to both consumer and prosumer, especially in a situation where both perform the same function. The direct buying or selling of energy among prosumers and consumers is known as Peer-to-Peer (P2P) trading of energy. Trading of energy among prosumers and consumers is one of the rapidly growing concepts in distributed networks. The sharing economy model is the foundation of P2P energy exchange in a distributed local electricity network [3]. A node in a network of energy trading is referred to as local energy prosumer or consumer. A node is also known as a peer who directly sells or purchases energy with other peers without the involvement of an intermediary controller. The current energy markets lack the ability to react in real-time or near real-time to the intermittent and volatile nature of RES generation [4]. In addition, market prices are usually set at the national level, which does not show the availability of local surplus energy or energy supply shortages [5]. However, modern market techniques must also reflect the locality of their services in order to promote DER's inclusion into the power system. Microgrids are a geographically small community of numerous connected DER and loads [6] and can also improve energy supply stability since they provide the opportunity to supply power in the case of superordinate grid energy failures [7].
The advancement in information and communication technology allows P2P energy trading to take place. In conventional energy trading, the flow of transactions is unidirectional, whereby energy is transmitted from a single source of energy generation to customers from a very long distance while the flow of cash goes the other way round. However, P2P energy trading needs multidirectional trading within a local area and allows advanced communication. The challenges identified in P2P energy trading are information security, information leakages, privacy, loss of data, etc. Most of these problems can be addressed using blockchain technology.
The evolving technology, blockchain [8], brings new potential for decentralized network designs and provides transparent and user-friendly frameworks [9]. It creates opportunities for energy users to be involved in making choices about who supplies their energy and the technologies used to generate it.
In recent years, industries, academics, and research domains are involved in utilizing blockchain technology with its potentials to decentralize the complex energy market's networks and P2P energy trading. The authors in Reference [10] propose a small machine-to-machine energy market based on blockchain with a customer and two suppliers in a chemical industry. The proposed system uses proof-of-concept algorithm for consensus. The proposed work shows that blockchain can create a small-scale energy market. In another work [11], the authors examine neighborhood energy growth into local self-sufficient utility production. The authors further explore the opportunities of microgrid energy markets based on blockchain for the development of distributed RES platforms and the associated problems for Australia's conventional power grid. It is explicitly stated that the usage of modern distributed ledger (blockchain) in transactions of energy makes microgrids more robust by establishing confidence among the agents involved, particularly with regard to energy delivery and financial payments processes. The authors in Reference [12] utilize blockchain-based technology to establish a continuous auction platform. The auction mechanism in the model allows supply and demand to keep adding and matching without discrete clearing steps. The authors in Reference [13] present a P2P negotiation model in Local Energy Market (LEM) that has randomized sellers and buyers matching without a central authority. The trading takes place between directly affected parties on a bilateral basis. LEM is a regionally limited market system with special sale price mechanisms among interdependent customers (generators, prosumers, and consumers). The customers can either have an energy generation or demand at any given time slot.
In Reference [14], the authors present a combinatorial double auction technique for pricing and distribution of energy resources, taking into account the needs of energy consumers and prosumers in particular. In this research work, we propose a secure, decentralized, anonymous, transparent, immutable, and verifiable energy trading mechanism. The objective of the proposed work is to maximize energy supplies and economic benefits at all levels for both the community and end-users.
The remaining part of this paper is organized as follows: related work and problem statement are discussed in Sections 2 and 3. Section 4 presents the proposed system model and its description. Section 5 elaborates price model and cost model of consumers and prosumers and discusses self-sufficiency and self-consumption, while security analysis and simulation results are presented in Sections 6 and 7. Finally, the conclusion and future work are presented in Section 8.

Related Work
The authors in Reference [8] proposed an NRGcoin model, also called a novel decentralized digital currency. The model allows locally generated renewable energy from prosumers to be sold using the digital currency organized by the market paradigm of buyers and sellers of green energy in a smart grid. The authors in Reference [12] presented an adaptive aggressive strategy in a microgrid using blockchain-based Continuous Double Auction (CDA), putting forward a new perspective on an energy market. However, various bid combinations may have distinct initial conditions, and there is an inadequate flexibility to change the bid quantity during the CDA bid process.
Similarly, in Reference [15], the authors presented a secure credit-based system of payment by reducing wait times for transaction confirmation of the energy chain in permissioned blockchain-based Industrial Internet of Things (IIoTs). Reducing the wait time makes electricity trading faster and responses more frequent. The authors also used an optimal pricing mechanism by exploring the idea of stackelberg game theory to optimize bank utility credit-based loans.
The authors in Reference [16] proposed a P2P Electricity Trading system with COnsortium blockchaiN (PETCON) model to conduct secure private P2P trading of energy between plugin hybrid electric vehicles. The study focused on establishing trust and used the anonymous property of blockchains to defend the user's privacy. In Reference [17][18][19], an approach based on the power quality perceived by a specific economical category is proposed. However, the proposed model does not consider security issues, privacy leakages, and single point of failure.
The authors in Reference [20] attempted to provide a decentralize and secure transaction using blockchain technology in the smart grid. In the research, participants anonymously negotiate the trading price and perform secure transactions using anonymous, encrypted messaging streams and multi-signatures. The proposed work is different from this research work by willingly allowing or encouraging all prosumers to become sellers and self-sufficient consumers in peak hours of energy generation. Similarly, in Reference [21], the authors proposed a system of distributed energy trading to encourage P2P sharing of electricity between prosumers. There are two layers in the proposed model. In the first layer, the agent coalition mechanism is proposed to allow prosumers to establish a coalition and to negotiate energy trading. A blockchain-based settlement of transactions is proposed in the second layer. A distributed approach to control Demand Response (DR) systems in a smart grid context is proposed in Reference [22]. The elements of the grid are integrated with the smart contract's blockchain framework to ensure the verification of DR agreements, the programmatic definition of expected energy flexibility levels, the balance within production and demand of energy, and the validation of DR agreements. In Reference [23], Thakur et al. presented a distributed, scalable, and secure blockchain-based network for coalition structure creation and microgrid energy trading. However, the determination of the trading price between the parties is difficult to reach via negotiation. Similarly, the research work in Reference [24] aimed to provide an energy trading model that will facilitate a sustainable transaction of energy ecosystems among smart homes' consumers and prosumers. However, energy and profit optimizations are not considered.
The work proposed in Reference [25] not only decreases the peak to average ratio, benefiting the grid, but also smoothens the dips of the profile load caused by constraints in supply. Also, the work proposed an enhanced blockchain approach to implement a distributed microgrid network that handles the micro-payment along with the exchange of energy and information. Furthermore, a noncooperative theoretical game approach is proposed for a Demand Side Management (DSM) model that incorporates storage components. Privacy has been highlighted as a major barrier to customer engagement in the research. The authors in Reference [26] proposed an Internet of Things (IoT) system to account for power flows as well as a blockchain platform to resolve the need for a centralized entity. It allows LEM to manage the decentralized transfers of energy without the need for central control. On the other hand, a new approach for smart city network architecture is proposed [27]. The architecture combined the benefits of blockchain technology and emerging Software-Defined Network (SDN). The rapid growth in volume and number for the connected IoT devices came with challenges: for instance, bandwidth bottleneck, scalability, privacy, and high latency in the current architecture of smart city networks. The current limitations are drastically reduced by introducing blockchain and by dividing the architecture into the core and edge networks. However, there are still some issues that are left unresolved, such as memory scalability, high latency, and efficient deployment of edge nodes. An interesting lab-scale implementation is proposed in Reference [28]. For the sake of sharing solar energy, this framework depends on a hyperledger fabric blockchain platform.
In another work [29], the authors propose a survey on distributed energy trading principles in a smart grid. The authors discussed topics like the advantages of distributed energy trading and reasons behind its implementation, the technology needed to develop these framework, and a review of past literature work. Mengelkamp et al. [30] identified seven microgrid electricity market principles and assessed the Brooklyn Microgrid in compliance with those principles. The authors developed and modeled a local power market with a more realistic emphasis on a private Ethereum blockchain that allows users to exchange locally generated energy supply on a distributed and decentralized exchange system without the involvement of control authority. However, efficient allocation and pricing mechanisms are not developed. Furthermore, Table 1 gives a summary of the related work.

Types of Blockchain/Techniques Objectives Research Achievements Limitations
Public blockchain and noncooperative game theoretic approach [25] Decrease the peak to average ratio and smoothen the fluctuation in profile of the energy load consumption

Electricity cost minimization
Proposed an LEM by integrating DR Privacy leakage, security concern, and single point of failure SDR method with compensation price [32] Electricity cost minimization Proposed P2P sharing of energy in a neighborhood with several PV storage systems Privacy leakage, security concern, and single point of failure

Problem Statement
The authors in Reference [30] proposed a decentralized market mechanism using a private blockchain and an auction method to determine the price. However, trading of surplus energy through auction or bidding is logically impossible for all users [33]. The reason is that some consumers or prosumers cannot participate in the trading due to limited time, lack of expertise, and above all, lack of technology. Similarly, another problem arose in References [31,32], and there is a possibility for the occurrence of single point of failure since the proposed models allowed a third party to serve as a controller to manage or control prosumers' batteries and all transaction information. Moreover, the system is prone to privacy threats, i.e., information disclosure and security concern. Additionally, including a third party requires a central processing center to process and collect the information of all participants, which is challenging in DER. Two problems naturally arise when relying on a third party. Firstly, intensive communication infrastructures are needed in the case of a central controller. Secondly, it is difficult to encourage a large number of participants in energy trading. The exponential development of energy trading shows the importance of related research.
Generally, according to the literature discussed in References [30][31][32], most of the research do not emphasize how to resolve the privacy and security challenges and a single point of failure problem. Moreover, none of the literature explicitly considers resolving the issues of energy hoarders in peak generation hours. Also, the research work does not consider combining the conventional LEM mechanism, HEM system, and blockchain technology concurrently. Combining these mechanisms will centrally merge their benefits in a single pool. We propose an LEM using private blockchain by considering the HEM system and demurrage mechanism in a community with residential PV energy generations. The proposed model allows prosumers and consumers to manage their resources and information in a decentralized, secure, trustful, transparent, anonymous, and verifiable manner. The comparison of existing work with proposed model is given in Table 2. The main research contributions of the proposed work are as follows: • an LEM using private blockchain is proposed, which considers both HEM system and demurrage mechanism simultaneously, • a dynamic pricing mechanism is proposed for energy trading to take place. This mechanism ensures that all members participating in local energy trading gain better economic benefits. This pricing model is modified from the Supply and Demand Ratio (SDR) mechanism [32] to include demurrage value, and • a thorough assessment is conducted in the research to evaluate the economic benefits of the buyers and sellers of locally generated energy in a residential community. Also, based on the proposed system, the potential security risks of the energy trading system are analyzed. Conclusively, a complete security protection technique is provided against these security vulnerabilities in the system. Table 2. Comparison with existing work. : considered; X: not considered.

References Blockchain Demurrage Mechanism SDR Scheduling
Base Paper 1 [30] X X X Base Paper 2 [31] X X X Base Paper 3 [32] X X X Proposed Model

Proposed System Model
In this section, the proposed system model is first presented; thereafter, the blockchain technology in LEM is elaborated. Lastly, the optimization problem formulation is discussed.

Description of the System Model
The proposed model comprises three participants: prosumers, consumers, and the main grid as depicted in Figure 2, which is inspired by References [30][31][32]. Prosumers and consumers participate in the local energy trading when PV energy generation is at its peak. The prosumers are equipped with PV solar panels, which generate electricity, and equipped with smart meters that record, monitor, and transmit energy information (both generation and consumption) to the blockchain through smart contract, while the consumers are equipped only with smart meters through which energy consumption information is generated and sent to the blockchain using smart contracts for future purposes. The main grid supplies energy to the local community when the local energy generated is insufficient to satisfy the user's demand. According to the proposed model, both prosumers and consumers optimize their electricity consumption through shifting demand from on-peak hours to off-peak hours, as discussed in the next subsection. The pricing model and demand shifting are executed at the individual local level, i.e., the consumers and prosumers level. The pricing model is developed using SDR by including the demurrage mechanism. Details on the pricing model are discussed in Section 5. Transactions information, payment processes, and market platforms are executed on the private blockchain through the smart contract to get rid of the third party. The blockchain technology provides a secure, decentralized, transparent, anonymous, and verified information platform. Demurrage is a mechanism used to disincentivize energy hoarding and to foster price signals to customers. This mechanism allows customers to shift their electricity consumption to a period where local energy generation is overflowing. With the demurrage mechanism, the redemptive value of the energy-backed price declines with time.

Blockchain Technology and Smart Contract in LEM
This section discusses blockchain technology and smart contract in LEM.

Blockchain Technology in LEM
We modeled a blockchain-based architecture to decentralize an LEM within a small community with many residential PV systems, as represented in Figure 3. The framework comprises nodes in the network, which are prosumer, consumer, and the main grid. These nodes can coordinate through blockchain's infrastructure to support the decentralization of energy generation and demand. Moreover, a copy of the blockchain ledger is created at an individual level (node). The challenges in P2P energy trading are identified as lack of data security and privacy. However, the problems can be addressed using decentralized and distributed blockchain ledger features. The issues of storing and maintaining energy transactions in a centralized approach are still open research challenges. In a decentralized manner, energy transactions can be maintained locally and stored in the blockchain. The process is done with the help of customers' unique identifier that shares and replicates the copy of the transaction to all the peers in the network for validation. The benefits of using blockchain technology in the proposed system are information immutability, self-enforced smart contract, security, etc. Information immutability in blockchain technology ensures that all information stored in Ethereum blockchain remains unchanged after validation. To achieve consensus among the energy trading participants, we adopt a Proof of Work (PoW) consensus mechanism [10].

Smart Contract in LEM
The author in Reference [34] defined smart contracts as a collection of instructions or rules that execute the terms of contracts. It is also suggested to convert contractual clauses, e.g., bonding, collateral, etc., into code and to incorporate them into hardware and software that could self-impose them so as to reduce or remove the need for trusted third parties. A smart contract is a set of blockchain's residing code or script. There is a unique address for each entity stored in a blockchain. According to the rules set, smart contracts are performed independently and automatically on each node in the network. It means that each node operates a virtual machine in the smart contract-enabled blockchain and that the blockchain serves as a distributed virtual machine [35].
In the proposed model, smart contracts are the collection of guidelines that regulate energy trading mechanisms (energy selling and buying) as well as monitor and record all the energy transactions information. Besides that, the smart contract is responsible for executing all payment processes between the prosumers, consumers, and the main grid. Due to the limited availability of mathematical functions in blockchain to calculate demurrage and their expensive gas consumption, we perform the arithmetic calculation off-chain and passed the results to the smart contracts. Algorithm 1 shows the excerpt of the smart contract. if <quantity of energy to sell is not enough> then 3: terminate 4: end if 5: if <Time is within the demurrage agreed time> then 6: update consumer's and prosumer's quantity

Optimization Problem
The optimization problem is categorized based on appliance scheduling in each time slot to reduce the cost of electricity. Power rating and appliance status (ON or OFF) are the attributes associated with each appliance. The description and specifications of the household appliances are provided in Table 3. The multi-objectives scheduling problem formulation is explained and presented in the next subsections. Table 3. Specification of appliances [36]. LoT: Length of Operational Time.

Shiftable
Air Based on the pattern of energy consumption and operational behavior, residential appliances are classified, i.e., appliances that are shiftable and nonshiftable, which are explained below.
Shiftable appliances: shiftable appliances for household load are categorized into interruptible and uninterruptible load. Interruptible appliances are the kind of devices that can be shifted and interrupted at any time, even when they start their operation, and have a fixed energy consumption rate. Examples of interruptible appliances are water heater, refrigerator, air conditioner, etc. The uninterruptible loads are the kind of appliances which can be shifted to any time slot before they are turned on but, once they start their operation, they cannot be interrupted unless they finish their LoT. Examples are dishwasher, cloth dryer, washing machine, etc. Let the shiftable appliances number be N shi f table for all appliances in the smart home, and Y ap (t) represents appliance status at time interval t ∈ T as demonstrated in Equation (1).
Non-shiftable appliances: non-shiftable appliances, sometimes referred to as unchangeable household devices, are those appliances that are not manageable, for example, fan, light, tv, etc.

Cost of Electricity
The reduction in costs of electricity is described as the lowest possible rates (charges) of energy loads consumed issued by the utility to energy users. For minimizing the problem of electricity costs, we consider non-shiftable and shiftable appliances loads. The problem is formulated as given in Equation (2): where E Price a (t) represents the price of electric energy consumed at any time interval t. a is the index for the overall number of appliances in the smart home, and time index is represented as t with maximum threshold of T hours of a day. N a is the total number of appliances in a smart home.

Energy Consumption
The energy consumption is shifted from on-peak to off-peak hours in a stable manner with the aid of the HEM system. The shift in energy load over a period of time is based on demand and is inversely proportional to the market price of the electricity. It is mathematically represented in Equation (3): where the energy consumption of shiftable and non-shiftable appliances is given as P consumption . The electricity load is divided based on the consumer's behavior and household appliances operation.
ρ represents each appliance power rating, and S shi f table represents the collection of household appliances that are shiftable. The number of non-shiftable appliances is denoted as N nonshi f table for all household appliances. S nonshi f table represents the collection of household appliances that are non-shiftable.

Load Balancing
The stability of the power grid is essential to ensure the reliability and sustainability of grid operations and management. A decrease in the Peak-to-Average Ratio (PAR) helps to maintain the reliability of the utility, thereby reducing the cost of electricity. It is mathematically shown in Equation (4): where P consumption is calculated using Equation (3).

Objective Function
The aggregated objective function is represented as a function of multi-objective optimization techniques to reduce energy cost and energy consumption in residential homes of prosumers and consumers while maximizing energy consumption from LEM. The optimization techniques are adopted from References [36,37] to achieve the overall objectives. The load scheduling is carried out using earliglow-based optimization algorithm. The earliglow algorithm is a hybrid algorithm, which is a combination of jaya and strawberry algorithms. To evaluate the HEM consumption and electricity cost, we consider Real-Time Price (RTP) scheme and Critical Peak Price (CPP) scheme to show the effectiveness of the optimization technique. The objective function is computed using Equations (2) and (3).

Price and Cost Models
This section discusses the price model, cost model of the consumer and prosumer, and self-consumption and self-sufficiency.

Price Model
The PV generation at the ith prosumer premises in a given interval of time t is defined as follows: where NB represents the prosumers' number (N ≥ NB) in the network. The consumption of prosumers or consumers at time t is defined as follows: where the consumers number in the network is represented as N. For any prosumer i, the net power in a given time t is represented as follows: As all customers have different electricity consumption patterns. The customers can serve as either sellers or buyers depending on the net power at a certain time slot. Therefore, the Total Selling Power (TSP) and the Total Buying Power (TBP) are defined as follows: According to economics theory [38], price and SDR relationships are inversely proportional. Similarly, as the price model in Reference [32] is formulated based on SDR. In this research, we apply the same price model, which is modified by introducing a demurrage mechanism. The TBP is the prosumer's or consumer's energy consumptions, and the TSP is the PV power generations. Therefore, the SDR at time slot t is represented as follows: The selling and buying prices change over the period of time of the day. Therefore, the prices are assumed to be where selling and buying prices at time slot t at the prosumer's side are represented as Pr sell (t) and Pr buy (t), respectively. The purchasing and selling powers to utility grid are represented as α buy (t) and α sell (t) at time slot t, respectively. In order to motivate both consumers and prosumers to fully participate in energy trading, especially, at peak PV generation, the prosumer or consumer buying prices (Pr buy (t)) should not be greater than the price (α buy (t)) of energy bought from the main grid. Additionally, the selling price (Pr sell (t)) of the prosumer(s) must not be less than the selling price (α sell (t)) of the utility grid. Thus, the buying price Pr buy (t) and selling price Pr sell (t) are represented as a function of SDR(t): In our scenario, the demurrage mechanism will be triggered whenever the prosumer or consumer hoards energy or delays to buy energy within peak power generation periods. In this case, the condition of the given SDR(t) will be slightly different, i.e., the buying price will be slightly higher and the selling price will be slightly lower than the utility grid's buying and selling price. This is to encourage participants to patronize local energy generated at on-peak hours, while at peak power generation, the prices obey the SDR pricing model. When SDR(t) = 1, both the buying and selling power in the neighborhood are the same (TBP(t) = TSP(t)) and no power is needed to import from or export to the utility grid. Also, both selling price and buying price are equal to the utility grid selling price, along with the compensation price (Pr sell (t) = Pr buy (t) = α sell (t) + α). When SDR(t) = 0, this means that there is no selling power in the neighborhood. All customers must buy energy from the main grid with a grid price of α buy (t). Therefore, the buying and selling prices are equal to the main grid's buying price (Pr sell (t) = Pr buy (t) = α buy (t)). The compensation price α is introduced to compensate the prosumer to ensure that all prosumers are better remunerated when participating in local energy trading. It also ensures that the selling and buying prices are not the same when SDR(t) > 1, and it provides more economic benefits to the prosumers than the consumers. The buying and selling prices will variably change based on Equations (11) and (12), when 0 < SDR(t) < 1. Figure 4 shows the relationship between SDR(t) and the proposed buying or selling prices. The figure shows that SDR(t) is reduced when power consumption increases. An increase in SDR(t) decreases both the selling and buying prices and vice versa. To increase the selling price, the participants must increase their energy consumption and the buyer would also need to decrease their energy consumption for a lower buying price.  In order to discourage energy hoarders and to encourage consumers to purchase energy at peak power generation hours, we introduce a demurrage mechanism in prosumer buying and selling prices [39]. Let β be the demurrage value as represented in Equations (13) and (14). The new buying and selling prices are Pr buyβ (t) and Pr sellβ (t), which are derived from the demurrage mechanism and are represented in Equations (15) and (16), while Equation (17) represents the combination of buying and selling price with demurrage: Pr Pr buyβ (t) = Pr buyβ (t), 0 ≤ t ≤ Max, Pr i (t) = Pr sellβ (t).

Cost Model of Consumers and Prosumers
Prosumers and consumers involved in energy trading DR are expected to have some portion of shiftable loads. Participants change their energy profile consumption because of the price incentives. This makes the initial energy consumption TP i (t) change from the actual values. The energy consumption adjusted is given in Equation (18): The adjusted net consumption for both prosumer and consumer at time slot t is updated as in Equation (19): The cost function for PV prosumers i at time slot t is defined in Equation (20): The total cost for PV prosumers i for a day is defined in Equation (21): Cost(y i (t)). (21) Pr i (t) is the customer price at time slot t, which can be either the buying or selling price. The status of the price is determined by the net power to be either the buying or selling price Pr i (t) and is given in Equation (22).
In the energy scheduling process, we have two constraints: min(TP i ) ≤ y i (t) ≤ max(TP i ). (24) Equation (23) means that the total energy before and after shifting the load is assumed to be unchanged, while Equation (24) means that the shifted electricity load must lie between the minimum and maximum electricity loads of the original customer profile.

Self-Consumption and Self-Sufficiency
Self-consumption and self-sufficiency ideas are adopted from Reference [40], which are mathematically expressed in the next subsections.

Self-consumption
Self-consumption can be determined as the total power consumption of a prosumer TP i (t) and the total power generated from on-site PV system by the prosumer P i (t). The energy generated on-site is limited by taking the smallest load between the generation or load profile of the customer, which is shown in Equation (25). Self-consumption is represented in Equation (26).

Self-Sufficiency
Self-sufficiency is calculated using Equation (27). A prosumer's self-sufficiency defines the share of the total load supplied by the PV system.

Self-Sufficiency
The relationship between self-sufficiency and self-consumption is expressed as follows:

Security Analysis
In this section, a security analysis is discussed, which ranges from vulnerability analysis of the smart contract and the tool used to perform the analysis to the overall security analysis of the system.

Vulnerability Analysis of Smart Contract
Ethereum smart contracts are still advancing; therefore, the code in the contracts can contain some bugs and may result in a serious security vulnerability. It is necessary to develop bug-free and secure smart contracts code. In 2016, the insecure smart contract allowed the loss of more than 3 million ether as a result of re-entrancy vulnerability [41]. Thus, careful inspection of the code and the need for secure smart contracts using automated tools are necessary and very important. The common attacks and security vulnerabilities identified against smart contracts are summarized as follows [42,43].
• Re-entrancy vulnerability: This type of attack happens when the same function is being called continuously over and over so that executing another function will be impossible. • Timestamp dependence: The miners can manipulate the transaction timestamp, so it is essential to handle all use cases, which include both indirect and direct timestamps. The miners can change the block timestamp to their advantage, which manipulates the execution of the output. Integer underflow and overflow: Underflow and overflow happens when the value given to a variable is more than the permitted limit for that data type. It is very common for the integer data type in solidity, and all data should be carefully verified at the time of variable assignment. • Assertion failure: If the "uint" is of higher value for a number used in traditional JavaScript, an assertion failure happens when it is not defined in quotations so that the input can indeed be read as a string and manipulated as a large number.

Oyente Tool
Oyente tool is an automated tool used to check possible violations or security vulnerabilities in smart contracts' code and is developed by Loi et al. [42,44] as an open-source tool.
Our energy trading smart contract is evaluated with oyente tool against the commonly known attacks and vulnerabilities of security. As shown in Table 4, all reported results were "False", which means that the smart contract of energy trading is bug-free and that it is secure enough from the abovementioned vulnerabilities. Each function in the contract is evaluated with the tool, in which the results show better functionalities for ensuring smooth trading among the participants. The oyente tool analyses the smart contract on the basis of symbolic execution mechanism. Every path of symbolic execution has a path condition, i.e., a formula, which is developed based on the inputs obeying particular secure rules identifying potential vulnerabilities to security. The inputs selected must be in line with the rules given in order to follow the path. A path is feasible if and only if its condition is satisfiable; otherwise, the path is infeasible [42]. The main objectives of symbolic execution are given as follows [42]: to investigate all execution paths using symbolic values for all variables, 2.
to cross-check whether any of the properties are violated, 3.
to store the behavior of the smart contract in every path, and 4.
to summarize the conditions on the input for each path.

Security Analysis of the Overall System
Potential attacks and threats are described in this section for the overall system as are how security goals can be achieved. The potential attacks in this research is similar to that of [42], therefore, we adopted same style of discussion. Our system's main security features are inherited from the blockchain technology. These features are integrity, trust, decentralization, availability, and non-repudiation. The system also manages access control and authentication through blockchain's smart contract feature by applying restrict modifiers, which restrict some functions' execution by certain actors. In addition, the system is protected against replay and Man-In-The-Middle (MITM) attacks as all messages are timestamped and signed cryptographically. Integrity is an important element that helps to ensure that vital information cannot be modified. The solution proposed offers the opportunity to trace historical events via logs. The immutability of blockchain ensures the integrity of messages shared between the two parties and logs as well as the events executed. To ensure availability, it should be remembered that the proposed smart contracts, which are built on blockchain, would always be available to the entities involved in the energy trading to perform their functions. It ensures easy access to services. The model is secured from Denial of Service (DoS) attacks, since the energy transactions are recorded in a distributed and decentralized private Ethereum ledger and are not subject to failure, compromise, or hacking. The Ethereum blockchain is Distributed DoS (DDoS) resistant and highly robust as it is globally distributed and protected by many mining nodes that host duplicate data with extreme integrity and consistency. Generally, in blockchain, confidentiality can be achieved using permissioned or private blockchain, such as that of hyperledger, multichain, or private Ethereum blockchain networks. In our scenario, the proposed system allows only authorized users. Thus, we use private Ethereum blockchain to perform energy trading transactions and to store the generated results for future purposes.

Results and Simulations
This section gives the simulation results and their discussions.

Assessment Metrics
In this paper, we consider electricity cost, self-sufficiency, and self-consumption as assessment metrics to evaluate the performance of a community and individual customers. Besides that, the simulation setup of the proposed system is presented in this subsection.

Simulation Setup
We perform the simulations by considering 100 households (N), which include both residents with a PV system (NB) and without PV systems. In the simulations, we assume that all residents with PV systems have the same PV generation capacity and that all households have the same pattern of electricity consumption profile. One day (24 hr) with one-hour resolution is simulated for energy load and generation of customers' profile. The proposed market mechanism is implemented in a private Ethereum blockchain network through a smart contract. Solidity scripting language and JavaScript programs are used to develop smart contracts and Application User Interface (API). These programs allow communication between smart contracts and API. All these programs are executed on the Node.js runtime environment. We use a basic concept of blockchain technology with no transaction cost and compensation for miners.
The computational experiments are conducted on a desktop computer with the following specifications. The configuration of the experimental environment is AMD E1-6015 APU with radeon (TM) R2 graphics 1.4 GHz processor and 4.00 GB RAM, and the operating system is Microsoft Windows 10. The simulation results of the proposed model are generated using MATLAB2018a. We took the appliances' load consumption datasets for the simulations from Reference [36], and the parameters used in the simulations are given in Table 5.

Results of Internal Prices
The main grid's buying and selling prices for the CPP and RTP pricing schemes are collected from the Scandinavian electricity market Nordpoolspot, which is an European based utility company [45]. From the grid prices schemes, it is observed that the price signal is at its peak between 10:00 to approximately 18:00. These peak hour price signals happen to occur during peak hours of energy generation as shown in Figure 5. In this paper, customers are encouraged to participate in local energy trading during peak hours of PV generation in such a way that the energy generated at peak hours is utilized. According to Equations (10)- (17), SDR(t) decides the internal prices for each time slot. As depicted in Figure 4, it is clearly shown that the buying and selling prices change with an increase in SDR(t). As shown in Figure 6a,b, the modified dynamic price model discourages customers from participating during low energy generation. Additionally, a prosumer that refused to sell surplus energy during peak generation will be disincentivized. The disincentive is applied using a demurrage mechanism in which the redemptive value of the energy-backed prices declines with time. It further leads to either increase in the selling prices or decrease in the buying prices and makes them worse than the utility selling and buying prices. The reason for the results shown in Figure 6a,b is that the demurrage mechanism is triggered when consumers delay buying local energy. As a result, all the prices will be affected. The mechanism will also penalize the consumer by increasing the buying price and by decreasing the selling price value for the prosumers whenever they hoard energy. Generally, an increase in SDR(t) decreases both the selling and buying prices and vice versa. However, the SDR(t) would be enhanced by adjusting the electricity load consumption, in which the value of the prices are reduced.

Results of Customers Cost
The results in Figure 5 show the typical energy consumption for an average household and the PV energy generation of a residential prosumer. The results show that the average energy demand for a day is approximately the same for all hours except from 10:00 to approximately 18:00, whereby the consumption is higher. It causes an issue in a typical average household which abruptly increases the electricity cost while trading energy using utility prices. As a result of this problem, electricity load optimization takes place. In our scenario, we first optimize the average household electricity load by shifting the electricity load from on-peak hours to off-peak hours as shown in Figure 7. The reason for applying the scheduling algorithm is to shift all shiftable appliances to a cheaper price hour that reduces the total electricity cost for a day. The electricity load shifting is carried out using the scheduling algorithm. The scheduling algorithm is adopted from Reference [36] to shift the electricity load to off-peak hours. As discussed in the previous sections, the role of the customers depends on the net load power. Figure 8 shows a net load power of a prosumer after shifting the electricity load.  The results in Figures 9a and 10a show that, after applying the optimization algorithm, the electricity cost reduces drastically when using utility prices. Still, the electricity costs are higher between 10:00 and 18:00. To further reduce the electricity cost, we trade with locally generated energy, where the prices are lower than the utility electricity prices. (b) Figure 9. (a) Electricity cost for a single household with scheduled and unscheduled consumption using CPP; (b) electricity cost of scheduled, scheduled with demurrage, and unscheduled without demurrage using CPP. The results in Figures 9b and 10b show that the customers achieve effective cost savings with local energy trading as compared with the main grid. The economic benefits of trading with local energy not only are for prosumers but also involves the consumers too. Moreover, the results in Figures 11a  and 12a show the electricity cost savings when trading with purely locally generated energy and when trading with either utility with scheduled appliances load or a combination of both methods by taking CPP and RTP as base pricing schemes. It is because the dynamic prices for LEM are always better depending on the SDR(t) as compared to the utility prices.
Furthermore, Figure 11b shows that the economic benefit gained by a prosumer is approximately equal to the consumers' total electricity cost when using the CPP scheme. Moreover, Figure 12b shows the profit gained by prosumers when using the RTP scheme. However, the findings show that the economic benefits gained using CPP is much better than RTP. This is because the RTP scheme changes in real time for consumers' usage behaviors. In RTP, price changes on an hourly basis and consumers are charged with different prices at each interval of time, while the CPP scheme defines distinct pricing frameworks for different seasons and annual events, which allows proper planning for the energy users.  Figure 11. (a) Comparison of total P2P cost with demurrage, total P2P and scheduled cost with demurrage, total cost scheduled without demurrage, and total unscheduled cost using CPP; (b) comparison of consumer cost, prosumer cost and profit, and prosumer profit using CPP. Electricity Cost (Cents) (b) Figure 12. (a) Comparison of total P2P cost with demurrage, total P2P and scheduled cost with demurrage, total cost scheduled without demurrage, and total unscheduled cost using RTP; (b) comparison of consumer cost, prosumer cost and profit, and prosumer profit using RTP.

Feasible Region for Energy Load and Electricity Cost
A Feasible Region (FR) [36], solution space or feasible set is a collection of possible points that satisfy constraints of the objective problem. In this article, CPP price signal cost for a household lies in the range of (11.40, 111858.75) cents and the load consumption without the HEM model and demurrage mechanism lies between (1.00, 13.25) kW for the four possible cases, as shown in Tables 6  and 7. Moreover, the price signal cost for the RTP scheme falls inside the range of (10.63, 5167.50) cents for each household. Likewise, in each situation (case), the hourly energy consumption for every household comes within the range of (1.00, 13.25) kW in the RTP pricing scheme. As it can be seen in Tables 6 and 7, to satisfy FR with modified price, the hourly electricity cost has to be less than or equal to the maximum of 11858.75 and 5167.50 cents without HEM and demurrage mechanisms, respectively. Similarly, each household energy consumption satisfies the optimization problem constraints given in Equations (23) and (24) and falls within the FR boundary. To compute the FR points, the maximum and minimum energy loads are multiplied with maximum and minimum electricity cost prices collected from the utility and the agreed price from local energy trading. The modified prices achieve optimal electricity cost for every time interval as compared to the original price, which falls within the FR range.
Furthermore, the demurrage mechanism affects electricity cost of the prosumers when energy is hoarded and increases cost when consumers delay purchasing energy at the agreed time. These effects depend on the agreement made by the prosumers and the consumers involved in the energy trading process.

Performance with Different Numbers of Customers Involved in P2P Sharing of Energy
In reality, it is almost impossible to find all the customers participating in local energy trading. Some might wish to be involved in local energy trading while others do not. In this study, we consider different numbers of customers participating in energy trading to carry out the evaluation . The number of customers in the evaluation varies from "0" to "100", with an interval of "20" as an increment. The number "100" means that all the customers are prosumers, while the number "0" implies that all the customers are not participating in local energy trading. We assume that the PV power generations of all the prosumers are the same and that the energy consumptions are also the same. As depicted in Figure 13, a decrease in the number of customers participating in energy trading increases the self-consumption of energy. According to Equation (28), in terms of self-sufficiency, when the number of customers participating in energy trading increases, the self-sufficiency of energy also increases. Self-Consumption

Conclusions and Future Work
In this work, we propose an LEM using private blockchain within a small community with many PV systems. In this research, users perform trading using a simple exchange mechanism to eradicate the problem of auctions, as stated in the literature. A dynamic pricing model and HEM system are introduced to increase economic benefits at both the community and individual levels. The simulation findings demonstrate that the proposed method reduces electricity cost and optimizes energy consumption, especially at peak hours. With CPP, the electricity costs are reduced up to 44.73% when the scheduling algorithm is applied. It reduced the electricity cost up to 65.17% when the P2P price model and demurrage are used. Furthermore, it reduced the electricity cost up to 51.80% when applying the P2P pricing model and the scheduling algorithm with demurrage at peak hours. Similarly, with the RTP scheme, the proposed method that implements the P2P price model with demurrage mechanism and scheduling algorithm reduces the electricity cost up to 44.37% as compared to 28.55% when scheduling algorithm is used and to 35.09% when P2P pricing model with demurrage mechanism is applied at peak hours. Moreover, the proposed method achieves optimal electricity cost for each time slot as compared to the utility prices and falls within the FR range. Additionally, the proposed model balances the local energy demand and generation of households without violating the customers' comfort. Furthermore, security vulnerability analysis is carried out, and the results show that the energy trading smart contract is secure and bug-free against the known vulnerabilities and attacks.
In the future, penalty policy will be incorporated to evaluate prediction deviations in the forecast profile and to improve trading within the neighborhoods. Additionally, a robust mechanism will be developed to solve the issues of the creation of rebounce in off-peak hours.

Conflicts of Interest:
The author declares no conflict of interest.

(t)
Price of electric energy consumed Pr buy (t) Prosumer's buying price at t Pr buyβ (t) Prosumer's buying price at t with demurrage Pr sell (t) Prosumer's selling price at time t Pr sellβ (t) Prosumer's selling price at time t with demurrage P i (t) PV energy generated at ith prosumer in a time slot t S shi f table Set of shiftable household appliances S nonshi f table Set of non-shiftable household appliances SDR(t) Supply and demand ratio t Time slot TBP(t) Total buying power P consumption Total consumption of energy for both non-shiftable and shiftable appliances Cost(i) Total cost for all consumers N a Total number of appliances in smart home TSP(t) Total selling power