Blockchain-Enabled Microgrids: Toward Peer-to-Peer Energy Trading and Flexible Demand Management

: The energy transition to a decarbonized energy scenario leads toward distributed energy resources in which end users can both generate and consume renewable electricity. As a result, several challenges arise in terms of decentralized energy resource management and grid reliability. With microgrids, the cooperation of distributed energy resources is improved, and with peer-to-peer energy exchange and demand response programs, better energy allocation and ﬂexible management of consumption loads according to the needs of supply systems are achieved. However, effective peer-to-peer energy allocation and ﬂexible demand management in microgrids require the development of market structures, pricing mechanisms, and demand response strategies enabled by a reliable communication system. In this ﬁeld, blockchain offers a decentralized communication tool for energy transactions that can provide transparency, security, and immutability. Therefore, this paper provides a comprehensive review of key factors for peer-to-peer energy trading and ﬂexible energy demand management in blockchain-enabled microgrids. The goal is to provide guidelines on the basic components that are useful in ensuring efﬁcient operation of microgrids. Finally, using a holistic view of technology adoption as a tool for peer-to-peer communication in microgrids, this paper reviews projects aimed at implementing blockchain in energy trading and ﬂexible demand management.


Introduction
Awareness about the consequences of climate change and the finite nature of fossil fuels has led to many policy changes around the world, ushering in the energy transition to a sustainable energy landscape [1,2].With electrification as a key component for decarbonization [3,4], to meet the growing demand for electricity, distributed energy resources (DERs) have been characterized by widespread implementation [4].Energy sources such as renewables, energy storage, and electric vehicles are increasingly popular [4], transforming energy systems toward decentralized electricity supply by introducing management challenges.With microgrid systems, several distributed energy assets can be managed by defining the operational boundaries of the system, both at the virtual and physical layers.Due to the intermittent nature of DERs (i.e., dependence on external conditions), the physical constraints of the electricity microgrid may experience potential imbalances between supply and demand.By fostering peer-to-peer (P2P) energy trading and flexible energy demand management, better energy allocation and integration of distributed resources is achieved according to the needs of microgrid systems.Through P2P energy trading, users trade locally produced energy at cheaper prices compared to the wholesale electricity market, while reducing electricity transmission losses.Meanwhile, by shifting consumption loads to the energy supply, transactions are managed according to the Energies 2023, 16, 6741 2 of 24 operating conditions of the microgrid, while improving profits.To achieve efficient management of interactions between DERs within microgrids, implementation of a reliable communication system is necessary.In this field, the blockchain, with its distributed ledger technology (DLT) features, offers a decentralized management tool for P2P microgrids, ensuring security, transparency, and immutability of energy transaction data.Implemented through smart contracts, blockchains unlock transactive energy in microgrids, ensuring automated and coordinated transactions for P2P energy trading according to reliable grid working conditions [5,6].
Application of DLTs within the energy sector and especially, blockchain, is a popular topic within the current literature.Obtaining a state-of-the-art analysis of these applications within the energy sector and on P2P energy trading, has already provided several review papers.In their systematic review of 140 blockchain research projects and startups, Andoni et al. [7] provided an in-depth survey of blockchain technology applications in the energy sector (Figure 1).Starting with an overview of DLT principles and consensus mechanisms, major applications are found in decentralized energy trading, which includes wholesale, retail, and P2P.The disruptive potential of creating a new market or value network from the application of blockchain technologies has been analyzed by Johanning et al. [8].Within the work, blockchain technologies represent a useful tool for transforming processes within energy systems.In addition, business processes and information flow between actors for different aspects of the energy system were identified.Among the challenges, the authors discussed the lack of sufficient documentation of the trading process and the imagined system within the analyzed projects, which causes difficulties in analyzing the real potential of blockchain technology within P2P energy trading.Additional challenges to be addressed were highlighted by Wang et al. [9].Their paper shows the need to address technological, economic, social, and regulatory challenges to be solved before large-scale adoption of blockchain-based energy trading.The first challenges include low transaction efficiency and high transaction cost, security and privacy, the ability to handle large amounts of sensor data communication, and the inability to reach quick price agreements.At the social and regulatory levels, there is a lack of trust in terms of using the technology due to privacy concerns and a lack of regulatory framework, respectively.Similarly, these challenges are reviewed by Ahl et al. [10] within a microgrid context.An analytical framework is proposed to highlight the challenges of blockchain-based P2P microgrids at the technological, economic, social, environmental, and institutional levels.
Energies 2023, 15, x FOR PEER REVIEW 2 of 25 reducing electricity transmission losses.Meanwhile, by shifting consumption loads to the energy supply, transactions are managed according to the operating conditions of the microgrid, while improving profits.To achieve efficient management of interactions between DERs within microgrids, implementation of a reliable communication system is necessary.In this field, the blockchain, with its distributed ledger technology (DLT) features, offers a decentralized management tool for P2P microgrids, ensuring security, transparency, and immutability of energy transaction data.Implemented through smart contracts, blockchains unlock transactive energy in microgrids, ensuring automated and coordinated transactions for P2P energy trading according to reliable grid working conditions [5,6].Application of DLTs within the energy sector and especially, blockchain, is a popular topic within the current literature.Obtaining a state-of-the-art analysis of these applications within the energy sector and on P2P energy trading, has already provided several review papers.In their systematic review of 140 blockchain research projects and startups, Andoni et al. [7] provided an in-depth survey of blockchain technology applications in the energy sector (Figure 1).Starting with an overview of DLT principles and consensus mechanisms, major applications are found in decentralized energy trading, which includes wholesale, retail, and P2P.The disruptive potential of creating a new market or value network from the application of blockchain technologies has been analyzed by Johanning et al. [8].Within the work, blockchain technologies represent a useful tool for transforming processes within energy systems.In addition, business processes and information flow between actors for different aspects of the energy system were identified.Among the challenges, the authors discussed the lack of sufficient documentation of the trading process and the imagined system within the analyzed projects, which causes difficulties in analyzing the real potential of blockchain technology within P2P energy trading.Additional challenges to be addressed were highlighted by Wang et al. [9].Their paper shows the need to address technological, economic, social, and regulatory challenges to be solved before large-scale adoption of blockchain-based energy trading.The first challenges include low transaction efficiency and high transaction cost, security and privacy, the ability to handle large amounts of sensor data communication, and the inability to reach quick price agreements.At the social and regulatory levels, there is a lack of trust in terms of using the technology due to privacy concerns and a lack of regulatory framework, respectively.Similarly, these challenges are reviewed by Ahl et al. [10] within a microgrid context.An analytical framework is proposed to highlight the challenges of blockchain-based P2P microgrids at the technological, economic, social, environmental, and institutional levels.The many opportunities for the application of blockchain technology in the energy sector are clear from the reviews offered in the literature.With its main application in decentralized energy trading, blockchain technology can create a new P2P network of value by transforming processes within energy systems.These processes concern a P2P market characterized by a group of self-interested parties whose preferences and transaction conditions The many opportunities for the application of blockchain technology in the energy sector are clear from the reviews offered in the literature.With its main application in decentralized energy trading, blockchain technology can create a new P2P network of value by transforming processes within energy systems.These processes concern a P2P market characterized by a group of self-interested parties whose preferences and transaction conditions influence energy assets on multiple levels.There is a lack of documentation of trading processes and designed energy systems enabled through blockchain to address Energies 2023, 16, 6741 3 of 24 multi-sectoral challenges at different levels of the energy market.Consequently, it is necessary to define a microgrid for P2P trading without compromising supply reliability and neglecting individual demand for energy goods and services.Therefore, flexible energy management via blockchain toward an efficient P2P microgrid system requires the definition and cooperation of multi-sectoral tools to offer the meeting of participants engaged at different levels of energy markets.
Starting with a general overview of P2P energy trading and flexible energy management in microgrids, this article aims to provide a review on P2P energy trading and flexible demand-side management.It proposes provision of guidelines on the basic components useful for efficient microgrid operation, such as blockchain-based efficient communication systems, market structures, pricing mechanisms, and strategies for flexible energy demand management.Finally, using a holistic view of blockchain adoption in P2P energy trading for flexible DER management in microgrids, this paper reviews projects and trading platforms aimed at implementing the technology.Figure 2 shows an overview of grouped keywords of the papers that were analyzed within this review paper.The keywords were weighted according to the frequency of their appearance in the reviewed papers.
Energies 2023, 15, x FOR PEER REVIEW 3 of 25 influence energy assets on multiple levels.There is a lack of documentation of trading processes and designed energy systems enabled through blockchain to address multi-sectoral challenges at different levels of the energy market.Consequently, it is necessary to define a microgrid for P2P trading without compromising supply reliability and neglecting individual demand for energy goods and services.Therefore, flexible energy management via blockchain toward an efficient P2P microgrid system requires the definition and cooperation of multi-sectoral tools to offer the meeting of participants engaged at different levels of energy markets.
Starting with a general overview of P2P energy trading and flexible energy management in microgrids, this article aims to provide a review on P2P energy trading and flexible demand-side management.It proposes provision of guidelines on the basic components useful for efficient microgrid operation, such as blockchain-based efficient communication systems, market structures, pricing mechanisms, and strategies for flexible energy demand management.Finally, using a holistic view of blockchain adoption in P2P energy trading for flexible DER management in microgrids, this paper reviews projects and trading platforms aimed at implementing the technology.Figure 2 shows an overview of grouped keywords of the papers that were analyzed within this review paper.The keywords were weighted according to the frequency of their appearance in the reviewed papers.After an overview of P2P energy trading and flexible energy management in microgrids (Section 2), this paper provides a definition and description of the main operation of DLTs, with a focus on blockchain (Section 3).Section 4 focuses on market structures and mechanisms for P2P energy trading within blockchain-enabled microgrids.Section 5 will discuss automated P2P energy trading based on smart contracts for an economic energy market through balanced and optimized pricing.Section 6, on the other hand, will discuss automated P2P interaction for flexible and secure energy management within microgrids based on demand-side management strategies.An overview of active projects in blockchain-based P2P energy trading for convenient, flexible, and secure energy dispatch among DERs in microgrids is then provided (Section 7).Section 8 discusses the main outcomes and insights of our review by giving a critical view on the current literature, while Section 9 summarizes and highlights the most important results of our literature review.After an overview of P2P energy trading and flexible energy management in microgrids (Section 2), this paper provides a definition and description of the main operation of DLTs, with a focus on blockchain (Section 3).Section 4 focuses on market structures and mechanisms for P2P energy trading within blockchain-enabled microgrids.Section 5 will discuss automated P2P energy trading based on smart contracts for an economic energy market through balanced and optimized pricing.Section 6, on the other hand, will discuss automated P2P interaction for flexible and secure energy management within microgrids based on demand-side management strategies.An overview of active projects in blockchain-based P2P energy trading for convenient, flexible, and secure energy dispatch among DERs in microgrids is then provided (Section 7).Section 8 discusses the main outcomes and insights of our review by giving a critical view on the current literature, while Section 9 summarizes and highlights the most important results of our literature review.

P2P Energy Trading and Flexible Energy Management in Microgrids
The introduction of intermittent DERs for energy supply introduces management challenges and leads to a potential imbalance in terms of meeting consumption loads.Indeed, renewable DERs, such as solar, wind, and hydropower, due to their dependence on climate conditions, can stress power grid constraints due to bidirectional energy flows in case of surpluses.Consequently, the path to a decarbonized power grid through electrification requires a flexible structure for managing DERs according to energy system conditions and a new allocation of energy value.With the introduction of P2P energy trading and flexible energy demand management, better energy allocation and integration of distributed resources is achieved according to the needs of energy systems.P2P energy trading is a sharing economic model in which individual peers can sell or buy energy from "underutilized assets" more flexibly and efficiently by engaging in collaborative energy transactions facilitated by advanced ICTs (e.g., sensors and smart meters) [11][12][13].Typically, the negotiation process takes place through a platform that acts as a coordinator of energy trading at more affordable prices than the sale market to foster distributed generation balancing [13].By setting their own market strategy and monitoring the condition of energy assets behind the meter, each peer can trade energy while increasing profits.The export price of energy is set below the retail price, allowing consumers to purchase electricity at a cheaper price [13,14].Likewise, prosumers are encouraged to share their surplus through a local market, thus being able to sell at prices above the nominal tariff normally paid during exchange with the distribution company [13,14].
Energy as a trade commodity, in addition to matching supply and demand among peers, should also consider balancing the multiple market levels of the energy system [11].Starting from wholesale market price signals and DER energy conditions, it is possible to strategize energy exchanges to achieve different benefits according to set goals.However, P2P exchanges can affect the state of energy systems by placing additional stress on the operational constraints of power grids.Additional tools are needed to ensure security of electricity supply within a P2P network.By managing consumption loads according to external changes, energy flexibility can benefit the condition of energy systems by increasing their reliability.To unlock the energy flexibility offered by DERs, the implementation of demand-side management (DSM), through demand response (DR) strategies, plays a key role in managing intermittent electric loads by fostering RES integration and improving grid congestion management [15,16].DR defines a pricing scheme established to motivate the shift in electricity consumption by end customers, either to hours of supply availability or to a non-peak hour, in response to changes in forcing signals (such as RES production, electricity price, etc.) [5,15,16].
The benefits of P2P markets for both the power grid (e.g., minimized reserve requirements [7], reduced investment and operational costs [17], reduced peak demand [18], and improved power system reliability [19]) and (pro)consumers (e.g., economic benefits and increased flexibility through shared assets [20,21]) are many, but physical and virtual challenges are also introduced [13,22].Since producers, prosumers, and consumers have control over defining the terms of transactions and the supply of goods and services [5,10,14,19], in an energy system with multiple users, it is difficult to model the decision-making process for various energy exchange parameters given the rational choices of network peers that may conflict [23].It is necessary to define a market layer for local energy exchange without compromising grid security and neglecting the demands for goods and services of different self-interested peers, while keeping losses to a minimum [13,22,24].In this context, a microgrid formed by flexible DERs provides a key tool to foster interaction among participants through a local energy exchange network [13,22].
With microgrid systems, the management of DERs, through an energy-sharing coordinator, can meet the specific needs of an entire community based on energy conditions, both at the physical and virtual levels [13,22].If virtual, microgrids operate through the existing grid reducing transmission losses, while if physical, they improve reliability in case of supply disruptions through an islanding mode or enable reduced operating costs through Energies 2023, 16, 6741 5 of 24 a traditional grid connection [17,25].Interaction is improved, and the market results in a user-centric market, which is essential to promote flexible exchange mechanisms and increase participation [11,22].
To successfully implement local P2P energy trading, it is necessary to leverage the interoperability of advanced tools to enable the participation and interaction of stakeholders (i.e., end-user to system operator) from different market levels (i.e., forward to real-time market) with security and privacy [11].P2P markets in microgrids, in addition to tools for designing an appropriate market structure and determining profitable energy prices, require a reliable information system that operates with adequate time resolution for efficient implementation [17].In addition, to involve DER flexibility providers in DR strategies, a system of stakeholder coordination and data sharing, while ensuring privacy and security, is needed [26].In this sense, the blockchain, with its characteristics as a shared and immutable digital ledger, offers a useful tool for transparent and secure P2P communication in microgrids [27].Through the shared data chain, transactions are recorded, and activities are tracked, creating a decentralized network that fosters P2P cooperation at multiple market levels [11,27].Indeed, these digital systems use cryptographically signed transactions and store data in a distributed manner.Therefore, malicious users cannot simply manipulate values, while using a distributed consensus mechanism enables the exclusion of any central data point, central authority, or middleman as each node verifies and stores the recorded transactions.Hence, once a transaction is stored within the ledger, is it assumed to be immutable, irreversible, and transparent as all users can verify each transaction within the ledger.Furthermore, anonymity remains preserved by using public wallet addresses without requiring specific usernames.Therefore, personal energy production and consumption patterns with related energy price preferences can be communicated in an anonymous manner, which mitigates the energy data communication privacy concerns.Moreover, a P2P network with a shared data chain is created and enhances cooperation between users to, e.g., minimize the total energy cost or to maximize the usage of local energy resources within a local neighborhood.Finally, blockchain-enabled microgrids unlock transactive energy through automated two-way management of energy flows that together with the P2P marketplace can pursue environmental, social, and economic benefits [5,11,27,28].

Distributed Ledger Technologies for Reliable Communication in Microgrids
The efficient operation of a microgrid requires the implementation of a reliable communication system that can ensure the decentralized management of multiple flexible DERs.In this field, blockchain and, more generally, DLTs offer a communication tool for distributed management toward better cooperation of connected DERs.The main principle of a DLT starts from a distributed ledger, also known as a distributed digital database, where any (restricted) user holds an exact copy of the database and has access to read, write, validate, and update a record.Such an approach is in contrast with the most commonly adopted databases of today, where a central authority is responsible for maintaining the database and acts as a middleman between all database users.The main reasons to switch from centralized to distributed databases are the lack of transparency and a lack of trust in the central authority from the perspective of the end-users.Due to its distributed nature, the latter avoids suffering from a single point-of-failure network architecture, while high operational costs due to the central authority can also be evaded.Figure 3 shows the concept of a centralized and distributed system on the left-and righthand side, respectively.
Within the literature, several authors mix the definitions of DLT and blockchain as blockchain is the most developed and applied DLT platform within the current literature [29].Although, other DLT platforms are reaching gradual adoption and have the potential to compete with blockchain due to their inherent characteristics.Figure 4 shows an overview of the most common DLT platforms with further details of the most commonly adopted blockchain platforms.In [30], Hrga et al. referred to blockchain and directed acyclic graph (DAG), while blockchain, DAG, Hashgraph, Holochain, and Tempo (Radix) were distinguished as the main DLT platforms according to references [5,29,31].Corda is like blockchain, though the way in which blocks are constructed is different and causes Corda to be seen as part of the blockchain DLT by one author and as a different DLT by others.In this paper, Corda is considered as a separate DLT, not belonging to the blockchain technology.As the focus of the current paper is on using blockchain within the P2P energy trading and flexible demand side management in microgrids, only the main principles of the technology will be discussed.For a thorough analysis of blockchain, DAG, Hashgraph, Holochain, and Tempo (Radix), the reader is referred to the work of Zia et al. [5].In addition, in [32], Polge et al. compared four major private permission blockchain platforms (Hyperledger Fabric, Ethereum, Quorum and MultiChain) to Corda on the level of performance, scalability, privacy, and adoption criteria.Moreover, M. J. M. Chowdhury et al. [33] performed a qualitative and quantitative analysis of the mainly adopted blockchain platforms to Corda and Tangle (via IOTA which is a DAG DLT).Within the literature, several authors mix the definitions of DLT and blockchain as blockchain is the most developed and applied DLT platform within the current literature [29].Although, other DLT platforms are reaching gradual adoption and have the potential to compete with blockchain due to their inherent characteristics.Figure 4 shows an overview of the most common DLT platforms with further details of the most commonly adopted blockchain platforms.In [30], Hrga et al. referred to blockchain and directed acyclic graph (DAG), while blockchain, DAG, Hashgraph, Holochain, and Tempo (Radix) were distinguished as the main DLT platforms according to references [5,29,31].Corda is like blockchain, though the way in which blocks are constructed is different and causes Corda to be seen as part of the blockchain DLT by one author and as a different DLT by others.In this paper, Corda is considered as a separate DLT, not belonging to the blockchain technology.As the focus of the current paper is on using blockchain within the P2P energy trading and flexible demand side management in microgrids, only the main principles of the technology will be discussed.For a thorough analysis of blockchain, DAG, Hashgraph, Holochain, and Tempo (Radix), the reader is referred to the work of Zia et al. [5].In addition, in [32], Polge et al. compared four major private permission blockchain platforms (Hyperledger Fabric, Ethereum, Quorum and MultiChain) to Corda on the level of performance, scalability, privacy, and adoption criteria.Moreover, M. J. M. Chowdhury et al. [33] performed a qualitative and quantitative analysis of the mainly adopted blockchain platforms to Corda and Tangle (via IOTA which is a DAG DLT).Within the literature, several authors mix the definitions of DLT and blockchain as blockchain is the most developed and applied DLT platform within the current literature [29].Although, other DLT platforms are reaching gradual adoption and have the potential to compete with blockchain due to their inherent characteristics.Figure 4 shows an overview of the most common DLT platforms with further details of the most commonly adopted blockchain platforms.In [30], Hrga et al. referred to blockchain and directed acyclic graph (DAG), while blockchain, DAG, Hashgraph, Holochain, and Tempo (Radix) were distinguished as the main DLT platforms according to references [5,29,31].Corda is like blockchain, though the way in which blocks are constructed is different and causes Corda to be seen as part of the blockchain DLT by one author and as a different DLT by others.In this paper, Corda is considered as a separate DLT, not belonging to the blockchain technology.As the focus of the current paper is on using blockchain within the P2P energy trading and flexible demand side management in microgrids, only the main principles of the technology will be discussed.For a thorough analysis of blockchain, DAG, Hashgraph, Holochain, and Tempo (Radix), the reader is referred to the work of Zia et al. [5].In addition, in [32], Polge et al. compared four major private permission blockchain platforms (Hyperledger Fabric, Ethereum, Quorum and MultiChain) to Corda on the level of performance, scalability, privacy, and adoption criteria.Moreover, M. J. M. Chowdhury et al. [33] performed a qualitative and quantitative analysis of the mainly adopted blockchain platforms to Corda and Tangle (via IOTA which is a DAG DLT).

Blockchain
Blockchain can be assumed as the most well-known DLT.The blockchain core principle is to group transactions together into larger blocks via an append-only approach.The first block created in the blockchain is called the genesis block as it is an empty block.Each block consists of a header and a body, in which the body holds all transaction data.The block header contains the hash of the previous block to chain the next block to the preceding one and ensures the blockchain immutability.A hash can be seen as the output of a fixed length from a function with an input of a variable length.Starting from separated transactions, each

Blockchain
Blockchain can be assumed as the most well-known DLT.The blockchain core principle is to group transactions together into larger blocks via an append-only approach.The first block created in the blockchain is called the genesis block as it is an empty block.Each block consists of a header and a body, in which the body holds all transaction data.The block header contains the hash of the previous block to chain the next block to the preceding one and ensures the blockchain immutability.A hash can be seen as the output of a fixed length from a function with an input of a variable length.Starting from separated transactions, each transaction provides a hash and block validators are combining step-by-step two hashes into a new hash to construct a so-called Merkle tree as shown in Figure 5.The main hash is also called the Merkle root and via the Merkle root its preceding hashes can be found and hence, the validity of the related transactions can be verified.transaction provides a hash and block validators are combining step-by-step two hashes into a new hash to construct a so-called Merkle tree as shown in Figure 5.The main hash is also called the Merkle root and via the Merkle root its preceding hashes can be found and hence, the validity of the related transactions can be verified.Data validators must reach consensus of the Merkle root, and several consensus mechanisms exist.In their review of 140 blockchain use cases within the energy sector, Andoni et al. [7], listed the mainly known consensus mechanisms and concluded that the main adopted consensus mechanism is proof-of-work (PoW), while the Ethereum platform is mainly used.Though, it must be noted that Ethereum has recently switched from proof-ofwork to proof-of-stake as a consensus mechanism due to the high energy consumption of PoW.Indeed, in trustless networks, the PoW principle requires large amounts of computational power to solve a cryptographical puzzle to exclude malicious transactions.As an example of a blockchain with PoW, Bitcoin uses block creation times of ten minutes, and a 256bit hash is to be found by the miners.Due to the increase in computational power within the mining networks, hashes were found faster and caused a decrease in the block creation time.Therefore, the difficulty of the cryptographic puzzle is adapted by re-evaluating the average block creation time by changing the number of leading zeros within the 256-bit hash.A higher number of leading zeros represents an increase in mining difficulty.In the case of PoS, no cryptographic puzzle is to be solved as the miner is randomly selected out of a set of stakeholders.Stakeholders are selected from its blockchain users based on their stake as it is expected that the higher the stake of a user is, the less they will be motivated to become a malicious user.
In addition to the reached consensus, it must be noted that the created block is only considered valid after some time.Indeed, several miners can produce blocks and decide which transactions they include.Therefore, the Merkle root will differ, and the chaining principle of blocks causes the existence of different possible chains.To determine which block is valid, the longest chain is considered as the main chain.Hence, several blocks must be produced to confirm preceding blocks.In general, it can be considered that blocks are valid after validation of six blocks, e.g., as the block creation time in Bitcoin is ten minutes, a block is considered valid if it is part of the main chain after one hour.
As already mentioned, in comparison to blockchain, Corda differs in the way in which transactions are chained.Where blockchain combines transactions into larger blocks and then confirms these blocks via consensus mechanisms, transactions in Corda are directly confirmed and not grouped together in blocks.Hence, the block creation waiting time is abandoned, while the scalability improves [34].Data validators must reach consensus of the Merkle root, and several consensus mechanisms exist.In their review of 140 blockchain use cases within the energy sector, Andoni et al. [7], listed the mainly known consensus mechanisms and concluded that the main adopted consensus mechanism is proof-of-work (PoW), while the Ethereum platform is mainly used.Though, it must be noted that Ethereum has recently switched from proof-of-work to proof-of-stake as a consensus mechanism due to the high energy consumption of PoW.Indeed, in trustless networks, the PoW principle requires large amounts of computational power to solve a cryptographical puzzle to exclude malicious transactions.As an example of a blockchain with PoW, Bitcoin uses block creation times of ten minutes, and a 256-bit hash is to be found by the miners.Due to the increase in computational power within the mining networks, hashes were found faster and caused a decrease in the block creation time.Therefore, the difficulty of the cryptographic puzzle is adapted by re-evaluating the average block creation time by changing the number of leading zeros within the 256-bit hash.A higher number of leading zeros represents an increase in mining difficulty.In the case of PoS, no cryptographic puzzle is to be solved as the miner is randomly selected out of a set of stakeholders.Stakeholders are selected from its blockchain users based on their stake as it is expected that the higher the stake of a user is, the less they will be motivated to become a malicious user.
In addition to the reached consensus, it must be noted that the created block is only considered valid after some time.Indeed, several miners can produce blocks and decide which transactions they include.Therefore, the Merkle root will differ, and the chaining principle of blocks causes the existence of different possible chains.To determine which block is valid, the longest chain is considered as the main chain.Hence, several blocks must be produced to confirm preceding blocks.In general, it can be considered that blocks are valid after validation of six blocks, e.g., as the block creation time in Bitcoin is ten minutes, a block is considered valid if it is part of the main chain after one hour.
As already mentioned, in comparison to blockchain, Corda differs in the way in which transactions are chained.Where blockchain combines transactions into larger blocks and then confirms these blocks via consensus mechanisms, transactions in Corda are directly confirmed and not grouped together in blocks.Hence, the block creation waiting time is abandoned, while the scalability improves [34].

Read and Write Access
While blockchain is considered as a distributed ledger, the access to its ledger can be represented by the schematical overview as shown in Figure 6.A first choice considering reading access is required.It leads to public blockchains in which everyone with an internet connection can read the state of the ledger, while with a private blockchain, only restricted users have reading access.The former approach is mainly adopted for cryptocurrencies, while in general, private blockchains are mainly used by the health sector, industry, or firms to ensure keeping information confidential.After specifying the reading access, writing access rights are determined by the choice for a permissionless or permissioned blockchain.In the former case, all reading users can also write, while only some of the reading users are allowed to write into the ledger in the latter case.

Read and Write Access
While blockchain is considered as a distributed ledger, the access to its ledger can be represented by the schematical overview as shown in Figure 6.A first choice considering reading access is required.It leads to public blockchains in which everyone with an internet connection can read the state of the ledger, while with a private blockchain, only restricted users have reading access.The former approach is mainly adopted for cryptocurrencies, while in general, private blockchains are mainly used by the health sector, industry, or firms to ensure keeping information confidential.After specifying the reading access, writing access rights are determined by the choice for a permissionless or permissioned blockchain.In the former case, all reading users can also write, while only some of the reading users are allowed to write into the ledger in the latter case.However, the differentiated possibilities are not always as straightforward as in Figure 6.Indeed, a mix between private and public blockchains can be found in the literature and causes the existence of four different types, namely public, private, hybrid and federated/consortium blockchains.As already stated, a public blockchain allows anyone with an internet connection to join and verify transactions, while no intermediary is required.Due to its open nature with trustless parties, transaction speeds are low as high security transaction confirmations are required.In contrast, a private blockchain is regulated by a single entity who controls the access of its participants.Such an approach reaches faster consensus as only a few nodes validate transactions, but at the cost of full decentralization as a single authority is responsible for the access rights and provides the final (dis)approval of a transaction.Moreover, due to its limited number of users, such an approach is also more vulnerable to security attacks as blockchains are mainly secure until 51% of its network is compromised.Hence, larger blockchain networks require more resources for reaching successful attacks as they consist of more users.A hybrid blockchain aims to combine the best of both public and private blockchains.Hence, a single entity remains responsible for the access rights, while the allowed users can verify all transactions and it prevents modifications implemented by the central entity.The hybrid approach allows to keep the security and transparency advantages of a public blockchain, while the scalability is improved due to its partially private character.The last option is a federated or consortium blockchain, which seems very similar to a hybrid blockchain as it combines both public and private blockchain features.However, the main difference between a hybrid and consortium blockchain is the central authority.In the middle of a hybrid blockchain, a single entity is used, while in a consortium blockchain, several entities are managing the blockchain together.Therefore, hybrid blockchains are considered more applicable to business-to-consumer (B2C) However, the differentiated possibilities are not always as straightforward as in Figure 6.Indeed, a mix between private and public blockchains can be found in the literature and causes the existence of four different types, namely public, private, hybrid and federated/consortium blockchains.As already stated, a public blockchain allows anyone with an internet connection to join and verify transactions, while no intermediary is required.Due to its open nature with trustless parties, transaction speeds are low as high security transaction confirmations are required.In contrast, a private blockchain is regulated by a single entity who controls the access of its participants.Such an approach reaches faster consensus as only a few nodes validate transactions, but at the cost of full decentralization as a single authority is responsible for the access rights and provides the final (dis)approval of a transaction.Moreover, due to its limited number of users, such an approach is also more vulnerable to security attacks as blockchains are mainly secure until 51% of its network is compromised.Hence, larger blockchain networks require more resources for reaching successful attacks as they consist of more users.A hybrid blockchain aims to combine the best of both public and private blockchains.Hence, a single entity remains responsible for the access rights, while the allowed users can verify all transactions and it prevents modifications implemented by the central entity.The hybrid approach allows to keep the security and transparency advantages of a public blockchain, while the scalability is improved due to its partially private character.The last option is a federated or consortium blockchain, which seems very similar to a hybrid blockchain as it combines both public and private blockchain features.However, the main difference between a hybrid and consortium blockchain is the central authority.In the middle of a hybrid blockchain, a single entity is used, while in a consortium blockchain, several entities are managing the blockchain together.Therefore, hybrid blockchains are considered more applicable to business-to-consumer (B2C) applications, while consortium blockchains seem more appropriate for business-to-business (B2B) applications [35][36][37].

Introduction of Smart Contracts, Decentralized Applications, and Oracles
Once blockchain access rights are defined, it can already be used for transactions in, e.g., cryptocurrencies.Though, within the energy sector, a smart contract (SC) or chain code is generally required as an additional key element to the blockchain.Indeed, a SC can be seen as a self-executing algorithm with predefined rules that is running on top of Energies 2023, 16, 6741 9 of 24 the blockchain and is stored across all the blockchain nodes to ensure its integrity.SCs can monitor the current ledger state and once triggered, they are automatically executed.Leaving users to directly interact with SCs is difficult as they can become complex.Hence, DApps or decentralized applications are developed and bridge the gap between the SC and blockchain users.DApps can be seen as general applications like mobile or web applications using which users can easily interact with a limited amount of freedom [38].
Although the smart contract is able to detect changes within the ledger, it is not able to directly send outputs or even receive inputs from outside the ledger and this introduces the concept of oracles.Examples of outside world information retrievals are weather forecasts, stock exchange market prices, energy consumption, and production states, while ledger outputs could deal with supplying a trigger signal to start a heat pump due to a P2P energy trade via the blockchain.Oracles form an interface to enable data exchange between the SC on the blockchain and the outside world and this inherently leads to the oracle problem (OP).Brian Curran [39] stated the OP as: "The security, authenticity and trust conflict between third-party oracles and the trustless execution of smart contracts."Indeed, oracles are controlled by a third-party, which is potentially biased.Direct retrieval of external information via smart contract facilitates their implementation, although the integrity and security of the blockchain would suffer greatly, as data validators cannot verify the validity of external data [40].Therefore, communication with the outside world is accomplished outside the blockchain.
In his study [41], Beniiche classified blockchain oracles depending on the source (software, hardware, or human), direction of information (inbound and/or outbound), and trust (centralized or decentralized).While the two former classifications are rather clear, the latter one deserves more attention.In a centralized oracle, only a single entity acts as an information provider and therefore introduces again a single point of failure and causes a lower resilience.In the case of decentralized oracles, several data sources are consulted to judge the correctness of its information retrieval.A simple example of a decentralized oracle when determining the current traffic situation is to not only use traffic cameras, but also retrieving information from satellites, smartphones, and connected vehicles.Furthermore, oracles can also be used for computational tasks to improve blockchain scalability.Indeed, the computational power of SCs is rather limited and, they generally require an execution fee [41,42].In his work [43], Mühlberger et al. distinguished four different oracles depending on the data flow direction and its initiator, namely (i) pull-based inbound, (ii) push-based inbound, (iii) pull-based outbound, and (iv) push-based outbound oracles.The most well-known oracles are Chainlink, Witnet, Provable (formerly known as Oraclize), Paralink, Town Crier, Augur, and Ramp [40].
As already stated, blockchain data validators mainly receive fees to implement SCs and to create blocks as the data validators must put resources into the validation process.As validators optimize their revenues, they prefer to validate high-fee transactions.Therefore, low-fee transactions take longer to be validated and this introduces the concepts of onchain and off-chain transactions.On-chain transactions are traditional transactions directly executed on the blockchain and are also seen as first-layer transactions.In contrast, offchain transactions are called second-layer transactions as they are not directly executed on the blockchain.Off-chain transactions move the transfer of value outside the blockchain by setting up a channel between the related off-chain users.As long as the channel remains open, they can trade without having to pay any transaction fee.Once they decide to close the channel, the final balances of the users will be communicated to the blockchain.Hence, the amount of fees can be reduced as users now only have to pay fees to open and to close the channel, but not for each single transaction.The best known second-layer protocols are Bitcoin Lightning Network and Ethereum Plasma for Bitcoin and Ethereum, respectively [44].In Ethereum, the fees related to transactions and SCs are expressed by an amount of 'gas'.Gas is expressed by the unit 'gwei', which is a small amount of the Ethereum cryptocurrency.In this context, the term 'gas limit' refers to the maximum amount of gas a user is willing to spend on the execution of its transaction or SC.Such a gas limit is particularly useful to prevent running an infinite loop in SCs as the execution will stop as soon as the gas limit is reached.Also, due to the gas limit, large attacks on the Ethereum platform are prevented.
During our study, it was found that only few works provide sufficient detail on how the blockchain platform is exactly implemented.In general, most works mention the adoption of blockchain technology, but do not describe the communication with the external world via oracles and DApps.To reduce operational costs within real-life implementation, it is expected that off-chain P2P databases will be mainly used and that only the final trading state will be written on the chain.

Trilemma and Consequences in Blockchain-Enabled Microgrids
As a communication system for efficient microgrid operation, blockchain enables decentralized control of DERs to exchange and transfer local energy based on grid conditions.When used as a P2P communication system for automatic execution of optimized energy asset management strategies, it can ensure economical, flexible, and secure system operation.However, the trade of energy assets and P2P flexibility services within a microgrid produces large amounts of data from individual DERs.This can lead to data congestion and higher transactional costs [45], undermining the feasibility of large-scale blockchain implementation.
Greater issues related to node scalability and performance include validation latency and transaction throughput, which can compromise security and decentralization [45], which are essential to enable P2P interactions in microgrids.Integrating blockchain as a communication tool between DERs in microgrids introduces challenges of scalability, security, and decentralization (the so-called blockchain trilemma).With the current technology, only two aspects of the trilemma can be achieved [46].Multiple users manage linked nodes through a decentralized data chain, and because there is no single point of failure, a high level of security is guaranteed.A second-layer solution, on the other hand, balances the blockchain trilemma and reduces transactional costs by recording only the outcome of the transaction on the data chain [45,46].
Considering P2P energy trading within microgrids, a reliable execution of smart contracts and consensus algorithms is also required.Within this context, formal methods are used to detect security breaches or anomalies within the smart contract code before real-life implementation and prevent costly errors.Formal methods exist in two steps, in which the first stage is used to retrieve a mathematical and logical description of the system.In a second stage, the retrieved description is used to determine the correct system functioning and to specify and verify software and hardware security requirements.In addition to their extensive analysis of used consensus protocols within blockchain technology, Verma et al. [47] highlighted the importance of formal modelling when developing blockchain-based systems.Krichen et al. [48] distinguished two formal methods for smart contract verification, i.e., program level and contract level.At program level, the method analyzes how the smart contract is implemented and considers low level contract execution details.At contract level, the focus is mainly on the interaction of the smart contract between the blockchain and the outside world, such as applied by Abdellatif et al. [49].

Market Structures in Blockchain-Enabled Microgrids
With distributed generation and the rise in prosumers due to the promotion of on-site energy production and consumption, there is a change in the energy value chain and how revenues are obtained [5,50].Prosumers actively participate in the growing energy market [51] and their better integration requires a reorganization of the electricity market in which stakeholders work together for distributed energy management.Blockchain offers the possibility of implementing decentralized local microgrid markets, allowing consumers to choose the source of energy supply [17].By leveraging blockchain technology, energy exchanges are brokered, and a connected network of P2P databases is created, which is useful for creating local markets centered on participants with equal power.
Participants coordinated through the blockchain initiate two-way energy transactions within their community in near real time, depending on production conditions and network reliability [5,17].
To better integrate multiple DERs into microgrids, one must define the market structure according to which the exchange of energy goods and flexibility services will be regulated.For this reason, it is useful to understand peer organization possibilities and electric market mechanisms best suited for P2P trading and flexible energy demand management enabled by blockchain.Figure 7 shows an overview of blockchain adoption for P2P energy trading within the changing energy landscape.It indicates several levels of application as will be further discussed within this paper.
energy production and consumption, there is a change in the energy value chain and how revenues are obtained [5,50].Prosumers actively participate in the growing energy market [51] and their better integration requires a reorganization of the electricity market in which stakeholders work together for distributed energy management.Blockchain offers the possibility of implementing decentralized local microgrid markets, allowing consumers to choose the source of energy supply [17].By leveraging blockchain technology, energy exchanges are brokered, and a connected network of P2P databases is created, which is useful for creating local markets centered on participants with equal power.Participants coordinated through the blockchain initiate two-way energy transactions within their community in near real time, depending on production conditions and network reliability [5,17].
To better integrate multiple DERs into microgrids, one must define the market structure according to which the exchange of energy goods and flexibility services will be regulated.For this reason, it is useful to understand peer organization possibilities and electric market mechanisms best suited for P2P trading and flexible energy demand management enabled by blockchain.Figure 7 shows an overview of blockchain adoption for P2P energy trading within the changing energy landscape.It indicates several levels of application as will be further discussed within this paper.

Peer Organization
Energy markets in microgrids can be operated exclusively or largely by self-interested and rational peers who, depending on their organization, define market objectives [17,22,52].Peer organization can be defined according to a fully decentralized, communitybased, or composite approach [22].In a fully decentralized P2P energy market, participants can trade directly with each other independently.Such fully decentralization relies on bilateral contracts [22] in which both parties involved enter into mutual agreements and exchange commitments.Bilateral contracts allow buyers to diversify the commodity from energy suppliers by configuring the trading system according to economic, social, or environmental preferences, such as defining desired savings or increased green energy consumption or source choice, and the level of acceptable risk in buying and selling [14,53,54].In addition, peers are encouraged to participate by deciding the attributes of the energy they wish to directly exchange based on the source of generation, location, and reputation of the counterparts [55].The fully decentralized market thus involves the direct buying and selling of electricity, where the seller delivers the product to the buyer over the counter (OTC).In this electricity market structure, transactions take place outside of auction processes, without brokers, or clearing markets [56].To facilitate energy transactions, the use of a platform

Peer Organization
Energy markets in microgrids can be operated exclusively or largely by self-interested and rational peers who, depending on their organization, define market objectives [17,22,52].Peer organization can be defined according to a fully decentralized, community-based, or composite approach [22].In a fully decentralized P2P energy market, participants can trade directly with each other independently.Such fully decentralization relies on bilateral contracts [22] in which both parties involved enter into mutual agreements and exchange commitments.Bilateral contracts allow buyers to diversify the commodity from energy suppliers by configuring the trading system according to economic, social, or environmental preferences, such as defining desired savings or increased green energy consumption or source choice, and the level of acceptable risk in buying and selling [14,53,54].In addition, peers are encouraged to participate by deciding the attributes of the energy they wish to directly exchange based on the source of generation, location, and reputation of the counterparts [55].The fully decentralized market thus involves the direct buying and selling of electricity, where the seller delivers the product to the buyer over the counter (OTC).In this electricity market structure, transactions take place outside of auction processes, without brokers, or clearing markets [56].To facilitate energy transactions, the use of a platform for exchanges provides a digital database of production, consumption, and contractual relationship information among stakeholders [13].However, this is validated by a central authority on which the trust and security of transactions is placed [13], affecting complete decentralization.In contrast, in community-based P2P energy trading, exchange and sharing take place through a community manager in which stakeholders can participate collaboratively [57] or competitively [58].Energy sharing occurs through common goals, such as decarbonization [5] (as in positive energy districts [59]).A similar market structure for P2P exchange refers to energy exchange in which the community manager can be an auctioneer.As the central controller, by receiving consumer bids and requests for energy volumes to be exchanged, the community manager determines the price of energy and proceeds to allocate DERs according to market objectives.
Typically, the main purpose is to minimize the cost of production by ensuring the greatest number of energy exchanges.However, the manager can also act as an aggregator in case energy flexibility services are offered [26], for better balancing of the power grid, or in the case of coalition, for energy exchange between microgrids (microgrid-to-microgrid energy trading).Through the adoption of a community manager, the preferences, and strategic models of each party within the community remain private [57], despite complete decentralization.Finally, with a combination of fully decentralized and community-based markets, stakeholders are free to interact with each other in a composite market while maintaining their own properties [22].If a composite market is created from a community-based P2P market in which a peer interacts with other markets, the manager acts as an intermediary.
Regardless of the choice of peer organization, the blockchain platform offers P2P microgrid decentralization by enabling data management and storage without a central authority [11,13].In addition, blockchain microgrids automate real-time assessment of DER energy levels and matching of their interactions between different market entities, including system operators, DERs, and energy consumers [11,27].These are independent and profitable entities that aim to maximize their interests through the process of transaction matching [60].To facilitate the matching of transaction processes, through the predefining of rules in smart contracts, consensus can be established among microgrid entities for profitable pricing and reliable energy supply.In a fully decentralized P2P market, blockchain enables automated bilateral negotiation between parties.While in a community-based market, auction process management through direct communication of supply and demand is supported by enabling users to track processes in a clear and transparent way.To support microgrid balancing, demand response strategies can be implemented that are useful for managing DERs according to system energy conditions.According to external condition variations, consumption loads can be shifted according to desired profiles (e.g., generation profiles).With blockchain, traceability of reliable data useful for flexible energy scheduling of microgrids is enhanced.

Electric Market Mechanisms
In P2P markets, electricity represents a commodity, and its value is strongly influenced by its physical characteristics.There are currently no effective methods for storing large volumes of energy, and its flow must be guaranteed within safe limits, resulting in fluctuations in the value of energy and its transmission [61].Moreover, to ensure continuous supply through DER, demand must necessarily meet production, and real-time energy flexibility provides additional value.Therefore, electricity, its transmission, and load transfer capacity are traded in various electricity market mechanisms toward real-time end use [61].
In general, P2P agreements for energy trading, transmission and balancing values can be made from short to long term.Long-term energy markets (i.e., forward energy markets) can begin months to years before final dispatch [61].These can take place within a fully decentralized organization by entering bilateral contracts (OTC trades) or in a community-based one by opening auction processes (electricity trading).Subsequently, contracts will be settled close to delivery in day-ahead and intraday short-term markets [61].In the day-ahead market, along with energy allocations in the market, hourly scheduling strategies for the next day can be defined for DERs based on weather forecasts [5,62].In the intraday market, on the other hand, energy volumes are balanced by changing the schedules defined the previous day by submitting new demand and supply offers [5,62].After the intraday market closes, a balancing market is held to ensure that supply equals demand in real time [61].The transmission system operator (TSO) of the control area, which organizes the market to procure the necessary flexible resources such as load shifting and peak reduction, is responsible for real-time balancing.
In electricity markets, blockchain technologies provide a communication system that automates interactions between entities involved in the various processes of selling, transmitting, and flexibly managing electricity [5,17,63].In addition, blockchain combined with sensors or smart equipment enables automated verification and storage of energy assets and flexibility services offered.In a balancing market, the system operator through the blockchain can send request signals for the provision of energy flexibility services to DERs, enter contracts, and later verify the actual provision of the service [26].If based on smart contracts, the blockchain can automatically determine market clearing by allocating flexible DERs for control area balancing.Finally, by coupling with predictive controls or artificial intelligence for self-learning, optimal predictions can be made, and scheduling strategies can be managed to enable efficient P2P energy trading in a smart grid.

Economical Operation in Blockchain-Enabled Microgrids
Together with the implementation of the reliable communication system and definition of the market structure, electricity pricing provides a tool for the effective operation of a microgrid.Through electricity pricing, the energy condition of the microgrid is described, and stakeholders can establish energy trading strategies that improve economic, environmental, and social benefits.In addition, by describing the condition of the microgrid, electricity pricing influences demand, especially through forced consumption loads according to price signal fluctuations (i.e., demand side management).Electricity pricing is a tool through which consumers and buyers interact to find a match as result of a strategic discussion for DER allocation.In a fully decentralized P2P energy trade, an electricity sales event is allowed through direct OTC trading [22,56].Through an asynchronous pricing process, independent P2P bilateral contracts are executed until a match is reached among participants [64].In this bid-ask mechanism, participants choose their counterparties, and the energy information of individual stakeholders is shared exclusively with the chosen counterparty.However, reaching an agreement is not always guaranteed [64].If blockchain-based, direct exchange benefits from the validation and authorization processes of transactions through smart contracts.There are also more competitive auction-based mechanisms suitable for community-based P2P markets.In a mechanism such as a double auction, sealed supply and purchase bids are sent in a forward market in synchronous time for a given volume of energy to an auctioneer.From the meeting of supply and demand curves, a uniform price for energy can be established (Vickrey mechanism), considering the common interests and goals of market participants (such as maximizing social welfare) [64].Double auction mechanisms can also enable discriminatory energy pricing, in which prices are set based on customer segmentation based on important characteristics, such as matching to increase the self-sufficiency capacity of the microgrid [65].When integrated, blockchain can facilitate the auction process by collecting and recording bid data (it acts as an auctioneer).It also allows peers to follow the auction processes clearly and transparently through access to validated information.However, depending on the implementation of the technology, different degrees of decentralization can be achieved in the dual auction mechanism [66].
To ensure balanced market clearing and DER allocation, the electricity pricing process can be improved with strategic mathematical models (e.g., game theory).Cooperative and noncooperative games, are useful in analyzing the mutual influence of decisions made by peers and achieving equilibrium among the parties involved.In the noncooperative game, the allocation of DERs is the result of independent players making decisions based on their own profit interests against the benefits of others [22,67].Instead, in cooperative play, social dynamics are evaluated for the achievement of common benefits.For example, it is possible to define a coalitional strategy for autonomous and self-managed cooperation of distribution microgrids serving a group of consumers [68].Game theory can be used to initiate negotiations and resolve P2P conflicts in microgrids by improving social welfare [69] and, when implemented in smart contracts in the blockchain layer, can be executed automatically.
To maximize the objectives of pricing processes, through constrained optimization, optimized trading strategies can be defined by considering the operational constraints of energy systems, operating costs, and production costs.Constraints due to grid utilization and market rules affecting participants' utilities can be considered [64].Examples are the maximum amount of energy, physical restrictions on prosumer generators [70] and physical restrictions on the microgrid system.In addition, considering in the minimum trade price the average cost of electric generation over the life of the system and the utility costs set by the system operator [64,71] provides potential profitability.There are several scheme optimization tools that can be used, such as linear programming, in which requirements are formulated in linear form, and the alternate direction multiplier method (ADMM), for distributed optimization.With ADMM, the collective economic distribution is decomposed by defining local problems for each participant.In addition, information exchange between the participants and the manager is supervised, making the ADMM suitable for community-based trading [72].In a modified non-cooperative double auction game, through the distributed optimization implemented in the smart contract, it is possible to determine the most suitable uniform clearing price in the interval between the winning auction and Vickrey's price, considering market objectives (e.g., social welfare maximization) and participants' needs [66,73].

Flexible and Safe Energy Management in Blockchain-Enabled Microgrids
With the rapid growth of DERs and the spread of electrification toward decarbonization, challenges arise in terms of grid management and reliability.Microgrid distribution systems enable better management of DERs by meeting the specific needs of an entire community, and by unlocking energy flexibility, microgrid reliability is increased.Energy flexibility can be described as the ability of an energy system to shift its consumption loads in response to changes in external conditions, such as generation from RES, microgrid energy conditions, and energy prices.To unlock energy flexibility in a microgrid, several tools are available, such as storage systems (e.g., electric vehicles can act as mobile energy storage devices [74]), application of efficient technologies (e.g., variable-capacity heat pumps and optimal control systems [16]), and demand-side management.By introducing demand response (DR) programs, power generation meets demand for more efficient use of electricity [75].Initiating a DR program involves several steps, and blockchain technology can provide a useful tool for fostering cooperation and defining operational boundaries between the parties involved through information sharing.In addition, considering the management challenges, technology used as a decentralized flexible energy demand control system offers ancillary services for grid balancing, better integration of RES, and economic benefits for the development of more sustainable energy system structures [16,75,76].
To initialize a DR program, the distribution system operator (DSO) sends a signal to the energy flexibility provider specifying the shifting of consumption loads according to a desired profile and associated economic incentives [76].This energy flexibility requirement is published within a dedicated platform or in a bilateral contract that specifies the magnitude and duration of the event [26].The consumer, community manager or aggregator (for aggregated energy flexibility providers), checks the availability of energy flexibility offered by their assets and submits a bid [26].After a load balancing check, the DSO accepts the offer and the energy flexibility provider sets its loads according to the desired consumption profile allowed by the electricity grid [26,76].Finally, the DSO verifies that the DR service has been provided to find the corresponding clearing price [26].To enable DR services, registration and sharing of structural information (such as location and connection points) related to available energy flexibility resources are required to regulate flexible demand management services [26,77].
With blockchain, operators have coordinated access to DERs that can support grid needs with automated processes for verification and activation of payments, reducing transactional costs and settlement times [26,78].On the other hand, aggregation of flexible DERs is supported and P2P interactions are improved, providing greater individual user privacy by sharing aggregated data.DR strategies, integrated with incentives and penalties in smart contracts, define the expected levels of energy flexibility for near-real-time balancing of the microgrid [76].In addition to desired consumption profiles, technical constraints that characterize the operation of energy systems (e.g., energy balancing, charging/discharging of batteries and electric vehicles, thermostatically and electrically controllable equipment) can be defined [76,79,80].In this field, monitoring consumption profiles for load balancing through reliable smart meters is critical for efficient DR scheduling in microgrids.Blockchain facilitates the secure integration of these efficient IoT systems useful for the digitalization of energy processes by supporting the establishment of user trust [11].Like energy pricing strategies, the definition of DR programs can be improved through decentralized optimization tools formulated through game theory.For example, through a noncooperative game between consumers, optimized energy scheduling strategies can be defined to increase benefits based on constraints and objectives [79].

Blockchain-Enabled P2P Flexible Energy Markets in Microgrids
After providing a general overview of market structures and useful tools for convenient, sustainable, and reliable energy dispatch in blockchain-enabled microgrids, the potential of the technology is further explored through a review of active P2P exchange projects and platforms.To date, several active projects implementing blockchain technology are available [81].The reviewed projects were selected using (i) P2P exchange, (ii) verification of MG conditions, (iii) definition of pricing mechanisms, and (iv) implementation of DR strategies in the energy sector as research parameters.Next, a verification of the results obtained was carried out, and the platforms that simultaneously meet the four research parameters are listed in Table A1 in Appendix A. Table A1 describes the name of the company, the main categories and subcategories of platform application, general information about the applied blockchain, the main office, and finally the year of creation.Below, some projects are also described to better understand the application potential of blockchain.
FlexiDAO [82] is project that promotes aggregation and control of flexible DERs to provide grid operators with transparent, secure, reliable, and timely energy flexibility for more efficient grid operation, increasing the integration of DERs into the system.Blockchain enables distributed management of energy resources and execution of automated DR events in near real time.Participants are incentivized to collaborate actively and with commitment through retention strategies.Collaboration among actors involved in distributed flexibility is simplified by shared access to data.With the software, it is possible to simplify access and aggregation of energy data for matching energy consumption with clean energy purchases on an hourly basis (e.g., Google project [83]).In addition, FlexiDAO can issue, transfer, and match time-based energy attribution certificates (T-EAC [84]) to the hourly load profile of data centers and eventually redeem them on behalf of Google, according to EnergyTag [85] standards.
Spectral [86] is a company that offers solutions to facilitate energy trading activities, such as integration of market platforms and automation of bidding and data reporting processes.Several tools are vertically integrated and enable optimization of behind-themeter energy assets, virtual power plants, and multi-commodity smart grids.Energy control and integration of various assets (e.g., solar, wind, batteries, cogeneration, chargers, etc.) are enabled, including through the implementation of predictive control algorithms.In addition, a comprehensive solution for congestion reduction and microgrid optimization is offered.Using configurable parameters, trading strategies are optimized, including through integrated forecasting of generation, demand, and price.Application examples include generation optimization based on dynamic pricing [87] and the implementation of a comprehensive strategy for renewable energy assets that combines specialized operational technologies and accurate energy price forecasts [88].
Electron [89] is a start-up that provides a flexible market infrastructure for interaction among grid operators, DERs, and to other parties.A shared registration platform and common trading venue is provided for all demand response, collaborative actions in the current hierarchical, P2P, and microgrid system.The platform enables DERs to resolve their combined imbalance position through mutual negotiation and to respond to intra-day variations in consumption and generation forecasts (e.g., Project Groupe-Bilan Flex [90]).Through the provision of multi-market services, the implementation and operation of multiple markets, such as peak shaving and local consumption, on the same infrastructure enables better integration of distributed resources on the grid into markets that optimize their use (e.g., Project London2London [90]).Finally, with real-time operation at the distribution level, the platform connects renewable energy generators, subject to curtailments, with local flexibility providers to absorb energy surpluses (e.g., Project TraDER [90]).
EVShare Foundation [91] is a technology partnership between leaders in electric vehicle manufacturing (Bravo Motor Company [92]), blockchain (Rootstock Labs [93]), artificial intelligence (Space AI [94]), DERs (Community Electricity [95]), and energy-dense batteries (California Lithium Battery [96]).Through energy management they create autonomous, sustainable, affordable, and comfortable ridesharing powered by clean, renewable energy.The blockchain enables the platform to securely engage multiple participants (e.g., vehicles, charging stations, energy producers, cyclists, and communities) through a series of distributed applications and a public application programming interface.The first pilot program in California includes the Los Angeles metropolitan area, the Central Valley, and the San Francisco Bay Area.
LO3 Energy [97] is a technology consulting firm committed to finding solutions for the development of innovative P2P distributed energy, computing, and distributed consensus networks.Working with multiple participants (such as utilities, energy wholesalers, DSOs, TSOs, and communities), it develops customized energy innovations.The key project is the Brooklyn Microgrid [98] enabled by the EXERGY [99] energy market platform.Specifically, the EXERGY platform, using DLT and a token system to enable transactive energy services, enables P2P transactions by strengthening data exchange for sending price signals.Connected to technologies for remote monitoring and scheduling of electric vehicle charging (e.g., JuiceNet [100]), the EXERGY platform enables energy exchange by identifying the most convenient times of day (presence of an energy surplus by a DER or availability of high levels of renewable energy production in the electricity system's generation mix), achieving economic rewards in exchange for services, either at the local optimization level or through energy markets [101].
Leap [102] is a solution platform for rapid, automated access to high-value revenue streams for flexible grid services.Acting as an aggregator of DER flexibility providers, the platform provides virtual microgrids to balance the grid.The platform can ensure the construction and scalability of grid service operations, enabling real-time energy trading, advanced smart meter synchronization and management, automated dispatch, and configuration of bidding strategies.An example of a case study is the implementation, together with a proprietary Nuvve [103] vehicle-to-grid technology, of a DR project to coordinate resources within a microgrid at the University of California [104].

Discussion
This paper reviewed the current literature on the application of blockchain technology for peer-to-peer (P2P) energy trading purposes within microgrids, with a specific focus on flexible energy demand management.Moreover, several projects which adopted blockchain technology for P2P energy trading purposes were investigated.Based on the analysis, this section aims to discuss the key challenges and directions for future work in the context of P2P energy trading via blockchain technology.Prior to presenting these findings, Figure 8 presents a research status overview on the current literature on P2P energy trading and energy flexibility by using blockchain technology.Herein, well established research topics were indicated in green, while red was used for unknown or very limited knowledge aspects.Orange areas indicate moving progress for which future work is still required to draw a general conclusion.section aims to discuss the key challenges and directions for future work in the context of P2P energy trading via blockchain technology.Prior to presenting these findings, Figure 8 presents a research status overview on the current literature on P2P energy trading and energy flexibility by using blockchain technology.Herein, well established research topics were indicated in green, while red was used for unknown or very limited knowledge aspects.Orange areas indicate moving progress for which future work is still required to draw a general conclusion.Firstly, detailed analysis revealed that the current literature lacks a sufficient description on the actual implementation level of blockchain technology within P2P energy trading.Herein, a majority of the studies mention the adoption of blockchain technology, but do not clearly describe which part of the trading process is achieved via blockchain technology and what exactly is implemented outside the blockchain.For instance, smart contracts are mainly mentioned to execute the transaction, but the connection to the outside world via decentralized applications and oracles is rarely to be found.However, these connections are of crucial importance to incorporate energy states such as the current or predicted energy production/consumption, weather conditions, energy pricing strategies in case of energy flexible control, grid conditions, etc.Hence, the current literature tends to see blockchain technology as the overall solution in which all information and states can be stored on the chain without any connection to the outside world.Therefore, the current literature complicates an in-depth understanding of the real requirements for setting up experiments or field trials on P2P energy trading via blockchain.The authors recommend future works to clarify more in depth the adopted communication and trading processes.
A second missing aspect in the current literature is a clear division of the information stored and processes executed on or off the chain.Indeed, storing all the required states for the energy trading process directly on the chain would cause a tremendous increase in the chain size and potentially also in the transaction costs.Within this context, producers/consumers in a P2P energy trading microgrid may want to change their energy states with changing electricity prices.For instance, consumers with heat pumps are likely to increase their heat pump operation with lower electricity prices, which will mainly cause a decrease in their system efficiency and an optimal balance between electricity price and system efficiency must be found.Herein, pricing strategies or algorithms such as game theory require Firstly, detailed analysis revealed that the current literature lacks a sufficient description on the actual implementation level of blockchain technology within P2P energy trading.Herein, a majority of the studies mention the adoption of blockchain technology, but do not clearly describe which part of the trading process is achieved via blockchain technology and what exactly is implemented outside the blockchain.For instance, smart contracts are mainly mentioned to execute the transaction, but the connection to the outside world via decentralized applications and oracles is rarely to be found.However, these connections are of crucial importance to incorporate energy states such as the current or predicted energy production/consumption, weather conditions, energy pricing strategies in case of energy flexible control, grid conditions, etc.Hence, the current literature tends to see blockchain technology as the overall solution in which all information and states can be stored on the chain without any connection to the outside world.Therefore, the current literature complicates an in-depth understanding of the real requirements for setting up experiments or field trials on P2P energy trading via blockchain.The authors recommend future works to clarify more in depth the adopted communication and trading processes.
A second missing aspect in the current literature is a clear division of the information stored and processes executed on or off the chain.Indeed, storing all the required states for the energy trading process directly on the chain would cause a tremendous increase in the chain size and potentially also in the transaction costs.Within this context, producers/consumers in a P2P energy trading microgrid may want to change their energy states with changing electricity prices.For instance, consumers with heat pumps are likely to increase their heat pump operation with lower electricity prices, which will mainly cause a decrease in their system efficiency and an optimal balance between electricity price and system efficiency must be found.Herein, pricing strategies or algorithms such as game theory require several iterations to find an optimal balance with potentially high iteration costs when executed on-chain.Hence, the authors believe that cost-effective real-life implementation will only store the final and agreed state (price and energy production/consumption) on the chain, while the entire trading process will be kept off the chain via a classical P2P database.Herein, the blockchain trilemma or making a balanced choice on the levels of security, scalability, and decentralization will be of crucial importance.While several works highlighted the importance of decentralization, it should also be noted that reaching a fully decentralized P2P energy trading framework is highly unlikely due to the security-of-energy supply responsibilities on transformer loading, cable loading, energy supply-demand balance, etc.Hence, the authors believe that (1) P2P energy trading between users over large physical distances will be difficult to justify and (2) the local distribution system operator should be allowed to restrict the energy transactions in case of grid issues.Hence, the authors recommend the incorporation of these hybrid or consortium blockchain network aspects within future works.In addition, future work on the application of alternating direction method of multipliers (ADMM) to achieve optimal and secure grid operation on the level of the local microgrid and microgrid-to-microgrid operation is required.Finally, the operational costs of using the blockchain technology for P2P trading processes should be compared to the loss in decentralization when using classical P2P databases via third parties.Therefore, societal questions can be expected on the balance between operational costs and trusted parties.
Moreover, the aspect of a potential mismatch between the expected and effective energy production or consumption level is mainly neglected.Therefore, most works expect that once a trade is settled, the users are fully able to meet their commitment.However, the unpredictability and weather-dependency of renewable energy resources and the stochasticity of end-user behavior can cause non-negligible differences.Within this context, further development of back-up measures and rules should be investigated on how to re-balance the energy states and which parties should cover these additional costs.Hence, the added value of the blockchain technology can come from safely storing the traded and thus expected energy levels, which can then be compared to smart meter readings.

Conclusions
Electrification toward decarbonization offers the possibility of introducing flexible distributed energy sources.Their widespread installation has great implications in terms of decentralized management and reliability of electricity supply.With microgrid systems, the management of DERs improves by meeting the needs of an entire community.In addition, enabling peer-to-peer energy exchange and demand-side management improves interaction among users, creating new value and flexibly managing consumption loads while considering power system conditions.However, efficient allocation of flexible DERs in a microgrid requires a reliable communication system, which can be met through the features of blockchain technology.By providing an overview of the basic components for the design of a flexible P2P marketplace in microgrids and the features of blockchain, it is evident how the technology offers a decentralized data management and communication system that is useful for transactional interactions between participants, ensuring security, privacy, and immutability.Thanks to the features of blockchain, decentralization is ensured regardless of the peer organization and, by offering adequate time resolution, it provides a tool for balancing electrical loads in a near-real-time market.In addition, when based on smart contracts, the blockchain can automatically determine market clearing by assigning flexible DERs for control area balancing.However, it was found that few works provide a detailed description on the adopted approach when integrating blockchain technology.In general, most works do not describe how exactly energy trading is implemented and which part of the trading process is accomplished on the blockchain, and which part is kept outside the chain by adoption of P2P databases or blockchain oracles.Finally, by investigating active blockchain-based projects, it is evident how by coupling the technology with predictive controls or artificial intelligence, it is possible to forecast and manage electric load scheduling strategies to enable flexible P2P power trading on a smart grid.

Figure 2 .
Figure 2. Overview of keywords weighted according to their frequency in the analyzed papers.

Figure 2 .
Figure 2. Overview of keywords weighted according to their frequency in the analyzed papers.

Figure 6 .
Figure 6.Distributed ledger technology access rights for reading and writing.

Figure 6 .
Figure 6.Distributed ledger technology access rights for reading and writing.

Figure 7 .
Figure 7. Overview of blockchain adoption for P2P energy trading purposes.

Figure 7 .
Figure 7. Overview of blockchain adoption for P2P energy trading purposes.