A Blockchain-Enabled Decentralized Energy Trading Mechanism for Islanded Networked Microgrids

Interconnected microgrids are becoming a building block in smart systems. Initiating secure and efficient energy trading mechanisms among networked microgrids for reliability and economic mutual benefits have become a crucial task. Recently, integrating blockchain technologies into the energy sector have gained significant amount of interest, e.g. transactive grid. This paper proposes a two-layer secured smart contract-based energy trading mechanism to allow microgrids to establish coalitions, adjust the electricity-trading price, and achieve transparent and decentralized secure transactions without intervention of a third trusted party. Since reliability benefits are main drivers of microgrids operation in islanded mode, a new decentralized smart contract based-energy trading model for islanded networked microgrids is proposed in the first layer with an objective to achieve demand generation balance. In the second layer, and to achieve a higher security, all executed contracts are verified and saved in a blockchain based on a new developed two-phase consensus method that utilizes practical Byzantine Fault Tolerance (pBFT), and a modified Proof of Stake (PoS). Simulations are conducted in Python environment to validate the proposed energy trading model.

T Time horizon (24- The power grid is emerging from centralized power grid, with electric power plants connected to the transmission system, to a decentralized grid, with distributed renewable generating units connected directly to distribution networks close to demand consumption [1]. Microgrids applications have emerged significantly over the past few years and are anticipated to even be deployed in a more comprehensive fashion in the near future. This deployment is because of the increased interest in the smart grid technology, where future smart grid can be pictured as systems of interconnected smart microgrids [1]. IEEE standard 1547.4 [2], has confirmed that representing the large power grids by a group of interconnected microgrids significantly enhances the reliability, resiliency, and sustainability of the network. Thus, recently, a great deal of attention has been paid to the networked microgrid operation. Due to different energy profiles, some microgrids may have deficit energy conditions, while others are having surplus energy supplies. Therefore, when the utility grid tie is unavailable, it becomes imperative to establish coalition formation and energy trading negotiation mechanisms to ensure adequate power sharing among networked microgrids to balance local power generation and demand. This constitutes one of the main drives of this work. Centralized energy trading models are hard to scale for a large number of entities, as well as the centralized scheme is susceptible to cyber-attacks [3]. In addition, the emergence of blockchain and the great attention given to it has led to tremendous amount of interest in using it within information infrastructure to assure secure and decentralized energy trading [3]. This fact is considered as a second driver of this work. In the U.S., the Brooklyn Microgrid project is an example of a first successful Peer-to-Peer (P2P) blockchain system operating through smart meters, where prosumers are able to trade energy based on pre-determined bid price [4].

A. LITERATURE REVIEW AND RESEARCH GAP
Integrating blockchain techniques in energy trading for networked microgrids is relatively a new area that has gained lots of interest recently. In the literature, numerous models have been developed for P2P energy trading without integrating blockchain technology, the following section will shed the light on the most related work [5]- [13]. An energy trading model for community-based microgrid in the presence of the utility grid was proposed in [5], in which a market operator determines the spot price by intersecting the demand and the ascending plot of the submitted bids where all offered bids are compared with utility price. The work in [6] proposed a modified auction-based mechanism for a smart community that relies on the interactions between a shared facility controllers (SFCs) and the residential units using a central auctioneer where the auction price is determined using a Stackelberg game. A Stackelberg game to model the interaction between producers and consumers is also adopted in [7] as a noncooperative game for developing a P2P energy trading model in virtual microgrids. Similarly, the model proposed in [8] is formulated as a Stackelberg game, in which a central operator of the microgrid is the leader of the game setting internal buying and selling prices, while, PV prosumers are the followers of the game adjusting their energy sharing profiles in response to the developed internal prices. The trading model in [9] is designed as an auction game to trade energy between energy demanders and producer within a grid connected communitybased DC microgrid. In this case, the demander submits bids to compete for DC power packets, and a controller decides the energy allocation and power packet scheduling. In [10], two auction schemes are developed for a smart multi-energy system considering the day-ahead and real time markets. A multi-agent system manager sells electricity, gas, and heat to users and also trades energy with external systems. Further, a multi-agent based-game theory reversed auction model is introduced in [11] to trade energy between local resources of a grid connected microgrid system. Authors in [12] developed a two-stage bidding strategy for P2P trading of Nanogrid. In the first stage, a two-step price predictor with an objective to promote the utilization of local renewable energy is developed for transaction adjustment; whereas a gametheoretic technique is developed in stage two to increase the social welfare. In [13], a distributed iterative method for P2P trading between PV prosumers within a microgrid system is developed, where an energy-sharing model with price-based demand response is proposed. A dynamical internal pricing model is formulated based on the supply and demand ratio (SDR) of exchanged PV energy.
Developing the pricing and negotiation mechanism of P2P energy trading models is mainly affected by the objective of the energy trading, thus, it must be clearly defined [14]. P2P trading can be utilized for both grid-connected and islanded microgrid networks. In the grid-connected mode, the objective of each microgrid is to minimize its operation cost [15]. On the contrary, in islanded interconnected microgrids, when the grid backup is absent, the objective of each microgrid is to achieve a reliable power supply by balancing power demand and generation [15]. The main objective of each peer in most of the models in the literature is to maximize economic benefits considering grid connected mode, where the connection with the power grid guarantees demand-generation balance. Hence, the main incentive mechanism for peers to participate in the trading process is maximizing their economic benefits, where each microgrids will only interact with other microgrids if such interactions lead to additional economic benefits. There is a need for developing innovative decentralized P2P energy trading mechanisms for islanded networked microgrid 211292 VOLUME 8, 2020 system with an appropriate pricing schemes that can incentivize the participation of all microgrids with an objective of maintaining local demand-generation balance. In addition, energy transactions are required to be securely executed without intervention of a third trusted party. Few trading models for islanded microgrids are available in the literature. For instance, the work in [16] proposes a double sided-auction implemented by an aggregator considering approximate price anticipation process. In [17], a nonconvex optimization problem derived from the Stackelberg game-theoretic approach and backward induction is solved by developing a decentralized bilevel iterative algorithm. However, trading models for islanded microgrids in the literature assume that islanded microgrids have sufficient local power sources, that is, demand-generation balance can be always assured locally. Besides, P2P-based auction models are designed assuming the presence of aggregator or auctioneer that facilitates the trading and pricing mechanisms.
In terms of integration blockchain technology, few studies have focused on developing decentralized energy trading using blockchain technology [18]- [22]. For instance, the work in [18] proposes a two layers algorithm for blockchain based-energy trading negotiation and transaction settlement among grid connected networked prosumers. In [19], a smart contract method based on energy tokens, where the energy token represents a unit of power at a fixed price is proposed. Authors in [20] extends the energy token method by using a linear time-based value depreciation model for the energy tokens. This method stimulates energy trading by incentivizing the buying and selling of tokens within a time limit. An incentivizing method utilizing Nash bargaining theory is presented in [21]. In [22], the impact of applying load management on reducing the energy cost bought from a blockchain based P2P energy trading market is studied. Proof of Work (PoW) as the blockchain consensus method is used in this work. The system security and privacy are crucial to the successful operation of interconnected energy trading systems, and recently proposed models have turned to blockchain technology to address these concerns [23]- [28]. A blockchain model for detecting data corruption produced by third-part intrusion is proposed in [23]. A modified blockchain approach including a data restoration technique for the event of corruption is presented in [24]. A unified energy blockchain based on consortium blockchain for secure P2P energy trading in industrial internet of things is presented in [25]. To increase the system security and privacy, differentially private energy trading auction using consortium blockchain for microgrids systems is proposed in [26]. The use of practical Byzantine Fault Tolerance (pBFT) as an alternative to inefficient consensus algorithms is proposed in [27]. Energy trading based on blockchain implementation using Hyperledger Fabric considering different energy transaction scenarios and crowdsources is presented in [28]. A secure and efficient Vehicle-to-Grid (V2G) energy trading model by combining blockchain, edge computing, and contract theory is proposed in [29]. In this model, a Stackelberg game-theory is used to determine the optimal pricing strategy of edge computing service. Similarly, a model for Internet of electric vehicles (IoEV)-based demand response (DR) using consortium blockchain, contract theoretical modeling, and computational intelligence is proposed in [30]. In this work, all transactions are created, propagated, and verified by authorized local energy aggregators (LEAGs) with moderate cost, and PoW consensus protocol is adopted by for verifying all created blocks. In the context of using pBFT method, a Tendermint consensus algorithm based on pBFT and Proof of Stake (PoS) is utilized for developing Ethereum smart-contract blockchain node, named ''Hyperledger Burrow'' [31]. Additional hybrid consensus methods have been proposed in the literature, including a two-phase consensus algorithm that combines pBFT with PoW [32], and pBFT with Proof of Authority (PoA) [33].
Based on aforementioned review, it was found that the following two aspects must be tackled for developing innovative blockchain-enabled P2P energy trading models: (i) How to determine the energy trading price and amount, especially for isolated networked microgrids when the utility tie and its retail price is unavailable? (ii) Once a trading transaction is completed, there is a need to develop more secure, energy and time efficiency consensus algorithms to settle those transactions in the blockchain. Besides, existence of malicious nodes that might invalidate the voting process of the consensus mechanism, and manipulate the recorded data need to be considered in the algorithm's development. Otherwise, the blockchain system may become insecure, unreliable, and inefficient.

B. ORIGINAL CONTRIBUTION
To tackle the above two challenges, this paper proposes a two-layer blockchain-based energy trading algorithm for a group of isolated interconnected microgrids. The two-layer algorithm develops a smart contract-based energy trading mechanism in layer one, and a transaction settlement method is developed in the second layer. The proposed blockchain based contract settlement protocol utilizes a two-phase consensus algorithm consisting of pBFT and a modified PoS to ensure system security, energy and time efficiency.
The contribution of this work can be summarized as follows.
1) Significantly distinguished from the work in [2]- [21] that focus on maximizing economic benefits assuming that utility grid back-up and sufficient local resources are available to satisfy generation demand mismatch, the developed price adjustment mechanism promotes the balance of supply and demand between the islanded networked MGs, as well as assuring price fairness multi-agents negotiation mechanism. It is unique for isolated networked MGs when the utility backup is unavailable and achieving reliable operation is the main social welfare for all MGs.
2) Develop a smart contract-based energy trading mechanism to allow microgrids to establish coalitions, negotiate the electricity-trading price, and amount. Instead of completing VOLUME 8, 2020 a transaction through an auction mechanism as widely proposed in the literature, our method is uniquely developed in such a way that the pre-determined smart contracts executed autonomously in a local energy marketplace, where peers (seller and buyer) do not share their data including the energy prices during the trading process. It contributes to the need to develop more privacy-preserving negotiation mechanism for P2P trading models.
3) Distinguished from the work in [14]- [33], this work proposes a new blockchain based contract settlement protocol utilizing a two-phase consensus algorithm consisting of pBFT and a modified PoS to ensure system security, energy and time efficiency. 4) Unlike the two-phase consensus algorithm proposed in [31] that utilizes a PoS selection process based on a predictable weighted round-robin fashion, where a malicious attacker can accurately target a future validator based on the known parameters, our proposed modified PoS method uses a nodes weighting factor that only increases their chance of selection. The selection of the validator is still conducted utilizing a pseudo-random number generator, making it impossible to accurately predict a future validator based on known information. Furthermore, Hyperledger Burrow [31] relies on a PoS method where the stake of a node is some resource of value which must be wagered to receive consideration to be selected as a validator. In our method, the stake of a node is determined by its level of participation in past contracts. For example, a node which participated in three contracts (buyer or seller) in the previous time interval t would have a stake of 3. In this way, a node does not have to offer a resource or asset during consensus to be considered as a candidate for validator.
The remainder of this paper is organized as follows: section II provides an overview of blockchain and smart contracts technologies. Section III introduces the energy trading model. In section IV, the numerical simulation results are presented and discussed. Effectiveness of the model results is further demonstrated through a comparative case in section V. The paper is concluded in section VI.

II. BLOCKCHAIN AND SMART CONTRACT: AN OVERVIEW
Blockchain concept was proposed for a first time in 2008 [34], which can be defined as is a chain that is constructed from many blocks that contain information [35]. All information is then updated synchronously to the entire network so that each peer (node in the network) keeps a record of the same ledger. Using its consensus algorithm, integrity of the information recorded in the ledger can be assured without intervention of a third authority [36]. Various consensus algorithms have been developed such as PoW, PoS, Delegated Proof of Stake (DPoS), Ripple Protocol Consensus Algorithm (RPCA) and AlgoRand [36]. The consensus algorithm is the most important factor of the entire blockchain system, because its efficiency determines the blockchain's performance directly. The main attribute of this technology is to track all created chained-blocks so that no block could be removed or manipulated. This makes the blockchain technology a very secure and trusted decentralized technique for transferring money, and contracts without relying on a trusted third-party [35]. The blockchain is a popular choice for secure transactions in decentralized networks due to the immutability of the blockchain record and the consensus methods used to validate information appended to the chain [37]. The data contained in a block includes the identification of the parties participating in the transaction, the amount of goods being transacted, the timestamp of the execution of the transaction, and an alpha-numeric string called a hash. Aside from the data contained in the block, a unique hash is generated which is appended to the block that identifies each block and its contents [35]. Each block in the chain includes its own hash, and therefore, the blocks are chained together by these uniquely generated hashes. If any of the data in a chained block is modified, the hash associated with that block will change, no longer matching the hash used in the next block and thereby breaking the chain. The smart contract is defined as a computerized transaction protocol that executes the terms of a contract [14]. By converting contractual conditions into code and embedding them into property that enables selfexecuting of trusted transactions and agreements between different, anonymous nodes without the need for a central authority. For blockchain applications, smart contracts are scripts stored on the blockchain with a unique hash [14]. A smart contract is triggered by addressing a transaction to it. It then executes independently and automatically in a prescribed manner on every node in the network, according to the data that was included in the triggering transaction.

III. THE PROPOSED ENERGY TRADING MODEL
The flowchart of the overall trading model is shown in Fig.1 and described in details in the following sections.

A. DESCRIPTION OF SYSTEM MODEL
The entire interconnected islanded microgrids system is modeled as a distributed multi-agent network, where each agent (MG) is a node of the network. Multi-agent coalition refers to a way to cooperate agents to complete a task, where none of them can complete it independently [18]. Based on this definition, it was assumed that each MG (agent) consists of only renewable distributed generation and power demand. Since all MGs are connected to each other and disconnected from the power grid, thus, the grid back up is unavailable. Therefore, the task of all MG's operator in the islanded system is to balance local renewable generation and demand. Hence, achieving zero net load is used to measure the level of satisfaction of all participants in the P2P trading. It should be noted that the net load is defined as demand minus renewable generation. All MGs in the islanded system share a common interest which is satisfying their net load; hence, they agree to work in a collaborative manner to satisfy their net load. It was also assumed that each MG does not have sufficient non-renewable local resources (e.g, dispatchable units, storage, controllable loads). Therefore, each MG is extensively incentivized to participate in the P2P trading to balance their net load. This incentive mechanism can be justified based on the fact that reliability benefits are main drivers of microgrids operation in islanded mode [15]. Limited capacity of local resources can be used only as a back-up if the power exchanged in the P2P trading is insufficient to balance their net load. Therefore, it is not required to formulate a scheduling optimization problem since dispatchable units, storage and controllable loads are not primarily used to balance the net load.
In terms of the model architecture, each node represents a microgrid consisting of renewable generators, and power demand, local controller, and trade controller in a layered architecture. The renewable distributed generation and power demand are located in the physical resource layer. On top of that there is the local controller (LC), which is mandated to manage the load and renewable generation data (forecasting hourly net load). In the event of energy deficit or surplus, the local controller forwards the information to the trade controller (TC) which is tasked with buying or selling energy to satisfy microgrid's hourly net load for a day ahead 24-h time horizon. A graphical illustration of the system model is given in Fig. 2.

B. SELLERS AND BUYERS IDENTIFICATION
We assume that all microgrids have the capability to forecast their power demand and generation for a particular time slot t. Forecasting the microgrid demand and renewable generation and uncertainty modeling are not the focus of this work. Hence. the energy production and consumption for each time interval t in the time horizon T is generated randomly by utilizing the Mersenne Twister pseudo-random number generator [38], The Mersenne Twister outputs a statistically uniform distribution between the upper and lower bounds detailed in equations (1), and (2) obtained from [39] with a slight modification. Utilizing Mersenne Twister pseudorandom number generator was based on the fact that for each time horizon T there is a maximum value for the renewable generation and electric load, below which the sub-horizon values are permitted to vary in a quasi-random fashion dictated by a Mersenne Twister pseudo random number generator [40].
The local controller determines the renewable generation based-net load of each microgrid by: where P net (t) < 0 denotes an energy surplus while P net (t) > 0 indicates an energy deficit. If P net = 0 the microgrid has reached generation-demand balance. For all time intervals where P net = 0, the local controller notifies the trade controller of the need to buy or sell energy. A microgrid with a negative net load is identified as a seller, whereas a microgrid with a positive net load is identified as a buyer as shown in equations (4) and (5).

C. PRICE ADJUSTMENT AND CONTRACT MATCHING MECHANISM
The local controller forwards the energy deficit or surplus to the trade controller. The trade controllers for each microgrid interface with each other in a local energy trading marketplace. The marketplace concept for contract's matching is a commonly used platform for peers that are willing to participate in trading, including in major stock markets such as, the NYSE [41]. For each round r in the time interval t (hourly time interval) in 24-h day ahead scenario, pre-determined energy selling smart contracts are offered at fixed prices by microgrids with surplus power, and energy buying contracts are offered by microgrids with power deficit. Both sellers and buyers aim to get their contracts matched and executed to satisfy their net load since grid backup is absent. The contract matching process is developed as follows. 1) Sellers start with high energy prices and making progressively lower offers for trades to potential buyers after each unsuccessful offering round. Conversely, buyers start with low prices and making progressively higher offers for trades to potential sellers.
2) For each round r in the time interval t, an autonomous contract matching round is done in the marketplace considering the following possible scenarios: (i) If P sell ≤ P buy the contract is automatically executed.
(ii) If P sell > P buy , the buyer moves on to the next available contract.
(iii) If after the first trading round the offered contract did not get matched, the seller must lower its contract selling price using (6) and the buyer must increase the desired purchase price using (7). The contract will be automatically executed when the pre-conditions of the selling and buying contracts match in the next matching rounds.
The contract price adjustment mechanism is developed as follows.
1) For time intervals when P net < 0, the microgrid is designated as a seller (P net is identified as P net sell ) and the trade controller authors a smart energy contract containing the amount of surplus power for sale and the price per kW of the power being sold. The seller calculates the desired selling price for each contract offering round as shown in (6).
Pr sell (r) = FP sell − τ C bss P batt + αC cur P net sell − P batt + A i,j C tr P net sell (6) Since grid tie is unavailable for the islanded system, the seller initially attempts to sell with a price higher than utility price, where FP sell is a fixed desired initial selling price given by FP sell > P utility . To ensure price fairness and avoid price adjustment manipulation by the seller, a maximum threshold for FPsell is specified by the marketplace and agreed on by all MG's operators (in this study, it is set to not exceed 1.5 times the utility price). If the offered contract did not get matched in the first round, the seller must lower its selling price. The price is reduced considering the operation cost of battery storage, curtailment cost, and transmission cost, where the second term in (6) represents the battery operation cost for each charging cycle, and the third term represents the energy curtailment cost. The cost of curtailment is modeled as a loss of revenue where C cur = FP sell in the first round and Pr sell (r − 1) for all sequential rounds. It should be noted that curtailment is applied only when the surplus power (P net sell ) is higher than the battery charging limit for each round (|P net sell |>L bss ). Hence, the curtailed amount of power for each round is a percentage of the difference between the surplus power and the power charged in the battery (α( P net sell −P batt )). It should be noted that τ is a binary value (0 for the first round, 1 for all sequential rounds). The fourth term indicates the transmission cost, where A is the distance matrix that represents the distance between any two microgrids in the network, i is the buyer MG index and j is the seller MG index; hence A i,j is the distance between MG i, and MG j.
The price adjustment process in (6) is developed based on the fact that sellers would tend to charge and curtail surplus power to satisfy its net load if they did not sell their excess power. This is a reasonable adjustment since the microgrid will have to pay these costs if the trading scheme is unavailable. The seller will go back and adjust its selling price after each round until it gets its contract matched and executed.
2) For time intervals where P net > 0, the microgrid is designated as a buyer (P net is identified as P net buy ) and the trade controller enters the marketplace to evaluate potential contract purchases. The buyer enters the marketplace with a desired purchase price calculated using (7).
Pr buy (r) = FP buy + τ (C D P D + βC sh (P net buy − P D )) (7) It should be noted that FP buy is a fixed buying price given as a percentage of the utility grid retail price where FP buy < Pr utility (buyer intends to pay less). To avoid manipulation of the price adjustment by the buyer, a minimum threshold for FPbuy is specified by the marketplace and agreed on by all MG's operator (50% of the utility price is adopted in this study). In addition, all cost parameters (e.g, C D , C sh , C cur , C tr ) used in price adjustment equations are constant and determined by the local marketplace in which all peers are trading. If the offered buying contract did not get matched, the buyer will increase its offered buying price. The price is increased considering the operation cost of dispatchable units, and load shedding cost, where the second term in (7) denotes the dispatchable unit operation cost for a committed cycle, and the third term indicates the load shedding cost. It should be noted that load shedding is applied only when the deficit power (P net buy ) is larger than the backup dispatchable units output power limit for each round (|P net buy | > L res ). Hence, the amount of deficit power to be shed is a percentage of the difference between the deficit power and the power supplied by the dispatchable unit (β ( P net sell − P batt )). The price adjustment process in (7) is designed based on the fact that buyers would have to get power from back up dispatchable units, as well as applying load shedding to balance its deficit net load if they did not buy power. The buyer will go back and adjust (increase) its buying price after each round until it gets its contract matched and executed.
The complete contract price adjustment and execution algorithm is shown in Table 1.
Sellers and buyers prepare their contract condition offchain, and then they compile and deploy their smart contract for possible execution to the local marketplace using an appropriate blockchain architecture that supports smart contract and deterministic consensus protocols. Hyperledger is a private blockchain software [42] that provides a modular architecture that makes it simple to implement smart contracts, and deterministic pBFT-bases distributed consensus [43]. For instance, the energy trading model proposed in [44] adopted Hyperledger platform for implementing the proposed model.
To avoid trade manipulation, prospective energy buyers do not share their desired purchase prices with energy sellers. Sellers that are aware of desired buying prices can manipulate trade by i) overvaluing their contracts by holding to a higher price knowing that prospective buyers will raise the desired buying price to meet energy demands or ii) undervaluing their contracts in order to undercut competition and execute more contracts. The converse is true for buyers manipulating buying prices. Therefore, prices should not be shared between buyers and sellers during contract's matching process. This is done by encrypting the data included in the contract before it is broadcast in the marketplace. For instance, the confidential transactions technique discussed in [45] can be adopted where the buyer and seller have contracts that contain price and other confidential information. The technique of confidential transactions is to keep the price amount secret and to grant verifiers the ability to check the validity of amounts [46]. In this case, buyer and seller perform a two-stage encryption process. At first, buyer and seller perform cryptographic hash operation on their contracts to preserve the confidentiality and authenticity of data to each other. Then, the buyer adds a public-key or asymmetric cryptography to further protect data from 3 rd party (intruder) intervention/malicious party. In particular, each of the buyer and seller generate a public-key and a private-key. The buyer then encrypts its (cryptographic hashed) contracts with the public key of the seller. The seller then decrypts data using its own private key. Once the seller decrypts the other party's data, its smart contract system performs price-matching. Note that this price-matching operation contains a smart algorithm that can work on the cryptographic-hash (price) amounts from buyer and seller and make a decision [45]. Once this contract matching operation is done, it informs the buyers and the sellers about its decision. In this way, buyer and seller are not exposed to the price of each other and hence the overall confidentiality is preserved.

D. TWO-PHASE BLOCKCHAIN CONSENSUS PROTOCOL
To enable a trusted settlement of electricity trading transactions, a smart blockchain based-contracts protocol for transaction settlement is developed. The proposed blockchain method uses a traditional distributed ledger consisting of blocks of data that are connected in a single chain. These blocks of data contain the details of the finalized contract from the trading marketplace, including the network address of the buyer and seller, the amount of energy being trading, the price per kilowatt of the contract, the timestamp when the contract was executed, the hash from the previous block, and a new hash generated using the SHA-256 hashing algorithm. Because this ledger chain is a distributed ledger, each node of the network maintains a copy of the ledger.
Before a block is appended to the ledger chain, it must be validated using a consensus method. A two-phase consensus process method is proposed. In the first phase, a pBFT is adopted. pBFT has been proposed in recent years as a viable alternative to popular consensus methods such as PoW and PoS. Byzantine Fault Tolerance (BFT) refers to the ability for a distributed network to reach an assured consensus despite the presence of faulty or malicious nodes that propagate false data. The consensus process developed in this work is shown in Fig.3.
The pBFT is an optimized application of traditional BFT method, which ensures consensus for any network of size 3f + 1 when there exists 2f + 1 validating responses (where f denotes the maximum number of faulty nodes).
The pBFT works by a voting consensus where each node has an equally weighted vote value. For each block validation process the following steps are implemented.
1) Initiate: a random node (microgrid) is selected to be the primary node. The primary node broadcasts the proposed block including the contract data to each of the secondary nodes in the network.
2) Acknowledge: Each of the secondary nodes broadcasts a vote to acknowledge their receipt of the proposed block to each node.
3) Validate: After receiving 2f + 1 approval messages, a node will broadcast a validation message if the data in the proposed block is valid.
Finalize: When 2f + 1 validation messages are received, the block has been validated and is moved to the second phase of the consensus process.
It should be noted that the pBFT is secure for any network of size 3f + 1 where f is the maximum number of faulty nodes. Therefore, in a system where greater than 1/3 of nodes are faulty (corrupted or non-functioning), the pBFT no longer ensures a secure consensus. In our model, the voting criteria is selected to be 2f + 1 because this criteria is greater than 2/3 of the network size. While a 2/3 criteria is sufficiently safe, the margin of error is a motivating factor for introducing the modified PoS as a second phase of consensus.
To ensure a high level of security, a simultaneous second phase of consensus is conducted using a modified version of PoS. For this consensus method, each microgrid is assigned a semi-random value generated using a weighting factor. This weighting factor corresponds to the recent history of participation in the energy trading marketplace, where microgrids with higher levels of participation are assigned higher weighting factors. The microgrid with the highest stake value during each consensus round is chosen as the validator node. The validator node constructs a block using the same contract data as was broadcast in the pBFT and compares its block to the one validated using the pBFT consensus. If these two blocks match, the validator broadcasts a final confirmation that the block is valid, and it is appended to the public chain. If the two blocks do not match, it indicates a cyber-attack activity that has manipulated the formed block, and an alarm will be activated to report a data manipulation incident. The overall two-phase consensus algorithm is illustrated in Table 2, where each microgrid is described as a prosumer.
In comparison with other common blockchain consensus methods, pBFT shows several advantages. Firstly, pBFT has no fixed time requirement before consensus can be reached. PoW and traditional PoS both have fixed time interval requirements before a proposed block can be validated. Additionally, pBFT does not require additional resources specific to the blockchain protocol, where it only uses existing network topology to perform digital communications. PoW requires expensive computing equipment to perform tasks which consume significant amounts of energy. Furthermore, traditional PoS requires nodes to have expendable financial resources in order to wager for validation rights. It is worth mentioning that pBFT-based consensus has a scalability issue when it is used for a massive number of nodes. However, partitioning the network into smaller groups called federates resulting in an improved scale up to 1000 nodes [43].

IV. SIMULATION RESULTS AND DISCUSSION
The proposed model was simulated using Python 3.6 in Microsoft Visual Studio Professional 2017 on a quad-core 2 GHz CPU equipped with 16 GB RAM. For adjusting the contract price, the charge cost of the battery storage (C bss ) is considered to be 0.03 $/kW [47], with a charging limit per round of 2 kW. Whereas, the adopted operation cost of dispatchable unit (C D ) is 0.25 $/kWh [48], with a slight modification considering a ramp rate of 5 kW per round. The load shedding cost (C sh ) adopted in in this study is 1.0 $/kW [49]. The maximum curtailment ratio for each round (α) is taken as 1% of the hourly surplus net load value. The load shedding ratio for each round (β) is taken as 4% of the deficit hourly net load value. Transmission cost (C tr ) is considered to be 2.8×10 −6 $/(kWh. km) [50]. The simulation is carried out for day ahead time horizon with T = 24 hours, t = 1 hour and up to 20 microgrids forming the networked system (incremental increase of 5 microgrids). Using equations (6) and (7), buyer and seller (microgrids) successfully adjusted their desired buying and selling prices where 216 successful contracts were executed with a total traded power of 419.63 kW during the 24-h day-ahead time horizon in the case of 10 interconnected microgrid system, whereas 456 successful contracts were executed with a total traded power of 937.17 kW in the case of 20 interconnected microgrid system. Fig. 4 shows an example of the progressive price adjustment to the desired buyer (MG2) and seller (MG5) prices over successive contract matching rounds for one contract. It is clear that the seller decreases the price after each round (blue line), while the buyer increases his offered purchase price after each round (red line), and a contract match occurred at a price of 0.198 $/kW. Initially the seller set its selling price to 0.25 $/kW, and buyer set its price to 0.15 $/kW, so there was no contract match in the first round. In the second round the seller decreases its price to 0.2329 $/kW based on (6), and the buyer increases its price to 0.175 $/kW based on (7). However, there was still no contract price match. In the third round, the seller decreases its price to 0.215 $/kW, and buyer increases its price to 0.2 $/kW. In the fourth round, the seller reduces its price to 0.198 $/kW, and the buyer increases its price to 0.225 $/kW hence, a contract is executed at the offerd seller price of 0.198 $/kW (for 1.69 kW transaction) because the seller price now is less than the buyer price.
Additionally, the average computation time required to complete discrete tasks (price adjustment, contract offering for possible matching) required to execute a final contract is recorded for a varying number of microgrids in the network, as shown in Fig. 5. The average computation time to execute all contracts in the case of 20 microgrids is found to be less than one second (around 15.25ms), which demonstrates the efficiency of the proposed trading model. It can also be noted that the average contract matching time increases with the increase in the number of microgrids in the network in almost a linear relationship. This is because when the number of microgrids increases, for a certain task, more microgrids would have the opportunity to participate in the local marketplace and conduct price adjustment process to execute their contracts. This can be verified by looking at Fig. 6 that shows the relationship between the number of formed contracts and the number of interconnected microgrids.
It was found that the model has successfully satisfied the objective of all networked MGs by balancing their net load, as well as allowing them to trade at their offered desired price. Each microgrid with power deficit successfully purchased  power to meet demands while microgrids with power surplus sold off their excess power; hence, demand-generation balance for the islanded interconnected system has been achieved.
For secure settlement of all transactions, all executed contracts are saved in the blockchain where each block in the contract chain contains only one energy trading contract. All blocks are created and a blockchain is formed and verified using the proposed two-phase consensus mechanism. Each validated block in the chain contains, (i) buyer and seller identification IDs, (ii) amount of traded power, (iii) a transaction price in $/kW, (iv) the timestamp of the execution of the transaction, (v) an alpha-numeric string called a hash, which is taken from the previous block (Each block also references a previous block, known as the parent block, through the ''previous block hash''). A sample of two contracts data included in the generated blocks is shown in Fig.7.
In order to investigate the impact of the microgrids number in the network on the validation time required for the proposed consensus method, the validation time is measured as the difference between transaction submission time and confirmation time. The average validation time for this method was calculated for an increasing number of microgrids, as shown in Fig. 8.
It can be observed that the validation time increases accordingly (approximately a linear increase rate) with the increase  in the number of networked microgrids. This is due to the fact that more microgrids (more nodes in the network) will increase the number of executed contracts, and formed blocks, which would correspondingly require a longer time for the validation process. The validation time required to validate all created blocks in a 20 microgrids network is found to be around 1.9 seconds as shown in Fig 8.

V. EFFECTIVENESS OF OBTAINED RESULTS
To ensure effectiveness of the proposed model, the model results were compared with the results of the recent work proposed in [18] and [51]. Table 3 depicts the full comparison, which demonstrates the time efficiency of the proposed energy trading model (less negotiation time for the same number of nodes, and improvement in the success rate of the transaction, where all deficit and surplus power are satisfied).
The proposed method is time efficient compared to the traditional methods that applies a direct price negotiation between peers. In traditional direct price negotiation methods, both negotiators are fully dedicated to take advantage of the offered contracts by the other peer and bring the other peer closer to their offered price. This increases the contract determination computation time and might lead to unsuccessful negotiation process, which can cause a reliability problem when the grid back up is absent for isolated networked microgrids. For a quick comparison of our negotiation method with the commonly used game theory-based developed algorithms in the literature, our contract determination time (conversion time) is compared with the result of the two game theory-based algorithms proposed in [51] as shown in Table 3.
In the case of 20 interconnected microgrids, the results in [51] show an average convergence times of 0.025 sec, and 0.05 sec, respectively. However, our negotiation method shows a shorter negotiation time of 0.0155 sec for the same number of microgrids as shown in Fig.6, which demonstrates the time efficiency of the proposed energy trading model. Finally, and with regard to justifying the fast validation time of our proposed consensus method, the work in [52] confirms that in networked computer systems, a pBFT algorithm can be executed in the order of milliseconds. Furthermore, in the modified PoS algorithm being proposed in the second phase of the consensus process, the stake is calculated automatically based on pre-existing data without a time constraint. Therefore, the PoS algorithm does not significantly impact the validation time.

VI. CONCLUSION
In this paper, a two-layer blockchain-based energy trading algorithm for a group of isolated, yet interconnected microgrids is proposed. The two-layer algorithm develops a preconditioned smart contract-based energy trading in layer one, and a novel two-phase blockchain-based contract settlement protocol is developed in the second layer. It was found that the proposed electricity trading mechanism can efficiently promote energy trading between isolated networked microgrids to assure system reliability when the grid backup is unavailable, as well as offers a price fairness negotiation mechanism for all peers in the islanded network. It also promotes the use of renewable energy sources. In addition, the proposed smart contract trading mechanism is executed in a local energy market where peers do not share their data, which guarantees privacy preservation for all microgrids in the network. Results have also shown that the proposed method is a time-efficient method compared with traditional P2P price negotiation protocols available in the literature. Furthermore, the verification of the transactions before adding them into the blockchain is done using a novel two-phase consensus algorithm. The adopted pBFT in the developed consensus algorithm takes into account the existence of malicious nodes that might invalidate the voting process of the consensus mechanism. Meanwhile, it is both time and energy efficient method compared with traditional PoW-based consensus methods that require expensive computing equipment to perform tasks resulting in significant energy consumption. Future work may focus on developing an energy transaction model based-blockchain considering technical operation aspects of networked microgrids (e.g. tie-line congestion and voltage stability).