Blockchain and Internet of Things for Electrical Energy Decentralization: A Review and System Architecture

The decentralization in the electrical power grids has gained increasing importance, especially in the last two decades, since transmission system operators (TSO), distribution system operators (DSO) and consumers are more aware of energy efficiency and energy sustainability issues. Therefore, globally, due to the introduction of energy production technologies near the consumers, in residential and industrial sectors, new scenarios of distributed energy resources (DER) are emerging. In order to guarantee an adequate power management in the electrical power grids, incorporating producers, consumers and producers-consumers (prosumers) together, it is important to adopt intelligent systems and platforms that allow the provision of information on energy consumption and production in real time, as well as for obtaining a fair price for the sale and purchase of energy. In this paper, we analyze the literature to identify the appropriate solutions to implement a decentralized electrical power grid based on sensors, blockchain and smart contracts, evaluating the current state of the art and pilot projects already in place. We also discuss a proposal for a power grid model, with renewable energy production, combining Internet of Things, blockchain and smart contracts.


Introduction
In traditional markets, energy transactions are carried out through a centralized model with several intermediaries, which corresponds to the old-century architecture of the electrical power grid, and is still presented nowadays. However, with the growth of energy consumption and population, there is a need to adopt new models that better respond to the needs of new cities, since the centralized model has higher financing costs and security of supply issues [1]. Decentralized models can achieve an improvement in performance and scalability of approximately 40% when compared to traditional centralized systems [2]; therefore, it is important to analyze how electricity markets work, as well as its regulations and actors, and to evaluate if there are conditions to promote decentralized solutions at a smaller scale.
Electricity markets are complex, with a variety of actors, ranging from the production, transportation, distribution and commercialization of energy. In most countries, it is necessary for a company or organization to establish itself as a trader to be able to sell energy, which in the case of decentralization constitutes a barrier for small prosumers [3] (the term prosumer represents entities or people that both produce and consume energy) [4]. At the European level, the European Commission published the European directives 2018/2201 [5] and 2019/944 [6] in order to foster the implementation of energy communities and promote the adoption of decentralized energy production systems. These directives energy management systems (EMS) and a sensor network, which, together with blockchain technologies, allow the creation of a reliable, safe, fast and robust decentralized system. This paper is structured into four more sections. The second section provides theoretical background with the main goal to give to the reader preliminary information about the main concepts of the paper. The third section presents the methodology used to perform the PRISMA review and the respective results and analysis, followed by the discussion where a decentralized electrical power grid constituted of prosumers and consumers is analyzed, followed by the presentation of a proposal for a trading platform with the goal of managing energy transactions in the aforementioned electrical power grid. We also propose a blockchain consensus mechanism that allows the safe exchange of information, as well as the signing of smart contracts that permit formalizing the relationship between the various market players, thus ensuring the transparency of the entire process. The fifth section presents the conclusions regarding the proposed solutions and limitations to the review.

Main Related Concepts
In order to promote energy decentralization, it is necessary to adopt several concepts that, working together, allow the implementation of a system that works as an aggregator of producers and consumers, with well-defined rules and a clear market operation. Local energy production aims to create more flexible and resilient systems with new ways to produce energy from different sources (e.g., solar, wind and biomass), which allow better results for everyone involved, whether through cost reduction or greater environmental sustainability. Despite this recent commitment to decentralization, it remains important that the current participants in the system are an integral part of the new solution, due to the existing complexity, namely the need for electrical power grid connections, so the distribution system operator (DSO) is an integral part of the process, as well as the energy traders [14].
Blockchain networks allow to support the integrity and transparency of an entire process, ensuring transactions, since to make changes an attacker needs to have the support of a high percentage of the network, which depends on the type of mechanism chosen [15]. Besides security concerns, blockchain adoption can have many other uses to help in the implementation of a local energy production system. In the following sections, we present information about the main concepts that support this review.

Local Energy Production
Nowadays, industries, small and medium enterprises and citizens rely on the current centralized markets and infrastructures for the provision of energy. All these key actors in the system face challenges related to increased energy costs, protection of energy provision to ensure power supply access and CO 2 emissions. In this sense, it is necessary to assure that the electrical system has the necessary characteristics and conditions to guarantee its robustness and give the necessary confidence to all involved agents. As companies develop, new services emerge, as well as new installations, creating challenges in terms of energy consumption and production. Many consumers, with the development and maturation of new energy production technologies, with considerable increases in system efficiency, became producers in order to have greater autonomy. These challenges force the system to have greater flexibility in order to accommodate new consumption and production points. With new energy and IoT technologies, it is possible to tackle these problems and promote the adoption of decentralized systems that can contribute to enhance energy efficiency, since they have the capacity to allow the safe exchange of data and information and ensure the transparency of the process, enabling a broader participation by consumers, thus leading to new possibilities for business models. Energy decentralization can bring solutions to increased energy demand, resource usage and energy poverty because it allows to create renewable energy communities, introducing social neighborhoods with low-income people, so that any production peaks can be used to bring energy to these homes, thus reducing their energy needs from the electrical power grid [16].
Peer-to-peer (P2P) transactions and decentralized energy production allow everyone who produces energy, for example, through solar photovoltaic systems, to sell their energy to other facilities for use in the vicinity, safely. This transaction system can be a turning point on the market. However, there are regulatory issues that have to be obeyed and that vary according to the country where they are inserted. If there is not a dedicated energy distribution electrical power grid between producer and consumer, it will be necessary to inject into the main distribution electrical power grid, requiring the authorization of the distributor, and a set of legislation procedures. The alternative is also for traders to buy this energy directly and then sell it at "normal" prices on the market; however, the involvement of a third party causes prices to increase [17].
With the increased number of decentralized installations introduced in the systems, intermittency issues arise. The distribution networks currently implemented were designed to supply energy to consumption points, not to receive an eventual excess of production. This paradigm shift causes disruptions in the network that impose additional management costs on the part of the competent entities [18]. It is important to mention that these entities have to maintain the balance of the network and for this they may have to overprovision their grid capacity, thus increasing costs. This is why it is so important to have demand/response mitigation strategies and incentives for consumers to adhere to these mechanisms [19]. There is also the need to control power systems because weather conditions affect solar and wind energy production. Based on these conditions the energy produced by photovoltaic units can have a variation, causing in certain conditions an energy production surplus for local grids, especially households [20].
By adding a larger number of installations at the community and neighborhood level, the complexity is increased; however, it also allows the management to be carried out with a greater number of equipment, thus allowing a more complex electrical power grid management. More installations in the electrical power grid have the advantage of reducing losses in the electrical power grid, since production is local and does not need to use the transmission electrical power grid. One of the proposals made to solve some of these problems is to convert the generated energy into a virtual currency, thus allowing the settlement between the various actors [13]. The Ethereum framework, for example, uses the concept of "gas" payments for smart contracts and transactions, where "gas" corresponds to a metric of the computational effort for the operations. The virtual coin used in this case is the Ethereum token ether, and all smart contracts work based on this [16]. One ether corresponded to 1964.32 € according to Coinbase as of 7 July 2021.
Blockchain can be a powerful tool to help to implement microgrid solutions to provide robust and secure transactions and data exchange between all actors of the process, in order to promote energy decentralization [21]. Table 1 presents the main differences between the centralized trading approach used with energy companies and the proposed peer-to-peer trading approach [17]. Table 1. Differences between centralized and decentralized trading.

Description Centralized Trading Decentralized Trading
Regulator [22] Centralized regulator (one entity) with common rules.
Possible to implement specific regulations for an energy renewable community.
Energy Distribution [23] Centralized, managed by one entity.
Possible to decentralize, building an internal distribution electrical power grid, maintained by the entity that manages de community.
Primary Energy Supplier [17] Large scale generators. Prosumers with renewable energy systems.
Trading [17] Central markets, fixed price tariffs. Bidding prices or prices according to usage factor.
Contract type [24] General contract for low voltage clients based on legislation. National regulators provide standard contractual clauses that must be complied with by all suppliers.
Standardized smart contract with rules defined by the entity that manages the community.
Management [25] Third party, smart meter. Operations are carried out by network, transmission and distribution operators.
Smart meter and smart contract, energy management system. All this information is stored on the network for all actors to analyze.
Policy and network changes [17] Policy maker, national action plans, legislation. Consensus of network participants.

Blockchain Technology
The concept of blockchain was introduced back in 2009 with Bitcoin [26]. Blockchain technologies bring several advantages regarding the energy sector, allowing trading and energy exchange between energy producers and consumers without the control of a central entity [27]. Blockchain can be used for management, trading, security, transparency, awareness, communication and certification.
For management purposes, the invoice and billing system using smart meters and smart contracts makes it possible to settle accounts and invoices automatically for consumers and distributed generators. For trading, market management is an important point, since distributors and traders need to carry out their energy consumption forecasts. With blockchain, together with other technologies, it is possible to make an intelligent management of it. Improved data transfer using smart devices makes it possible, through data transmission, to cross information. Note that these technologies are also being used to improve automatic connections, allowing control systems and networks to correct tariffs in real time, promoting P2P transactions.
For trading using smart contracts, there are contractual transaction protocols based on programming languages suited for each usage domain that are automatically executed when all parties provide the required data. Using protocols and user interfaces, these contracts must comply with legal procedures, all data must be securely stored and available for consultation during the execution period, and all contracts must be fully recorded for future verification. The smart contract itself must also be able to prevent security breaches and external interactions if possible, as well as control data accessibility for all parties involved on a contract [28].
For security and transparency purposes, ensuring safety transactions using programming verification techniques, guaranteeing the confidentiality of data, user and transparency with standardized processes that cannot be changed during time [13].
To add value for consumers, advertising and communication with customers is made in a direct way, almost individually, according to their preferences, using for that purpose the information collected through energy management systems. Improved sharing of resources supported by the electrical power grid management makes it possible to offer other services, such as energy storage, as well as charging stations for electric vehicles, because currently most projects located for power generation have to ensure consumption at the same time as production, due to the lack of storage. The blockchain network can, thus, contribute to the management of the electrical power grid, helping to minimize the intermittency generated by the introduction of renewable energy into the electrical power grid [29]. Increased competition with smart contracts that can streamline the process of changing energy suppliers, which allows for a reduction in energy tariffs [30].
One of the advantages of blockchain is the fact that it is able to certify the origin of the energy produced, thus being important for green certificates and to assure consumers that the energy they are purchasing is actually from renewable energies, something very important in social terms, so it has this most advantageous benefit as well [31].
The various areas of blockchain usage have already been explored in some way in previous studies, with application cases. In the revised literature, it was possible to identify some projects that intend to implement models to promote energy decentralization. Some platforms that have already been developed, such as PONTON Gridchain and Enerchain, are used for electrical power grid management and energy P2P direct trading. Electron is an Ethereum based platform that allows real-time switching of energy suppliers and provides P2P trading. SolarCoin rewards prosumers per each MWh generated. Energo focuses on machine-machine connections and the possibility of making transactions between them, as is the case with electric vehicles and charging stations that can interact with each other, thus making transactions through a digital wallet.
B.S. Lee et al. proposed a platform based on Ethereum for the creation of a relationship between consumers and prosumers through smart contracts [32]. A scheme with energy routers is also being implemented, where in each microgrid there is an energy router that is a node of blockchain which is operated by the blockchain-based multi-factor electricity transaction match mechanism. In this scheme, a set of transactions, records and fund settlement are recorded. It includes a node application module, an electricity transaction acquisition module, a blockchain nodes module and a smart contract module [22]. A double chained model of blockchain can be implemented to facilitate and expedite transactions between prosumer and consumers and establish smart contracts and then form coalitions for negotiation and energy exchange [4].
A cooperative approach for P2P transactions and improved privacy concerns in a secure environment is also possible. Cooperatives may have energy to sell, but selling energy to energy companies is currently not profitable due to the low prices they practice for local producers. A P2P approach between cooperatives is proposed in [3]. An example of possible parties involved in a cooperative P2P approach are solar PV panels, smart appliances, smart HVAC systems, electric vehicles, energy storage systems and smart meters that can measure the energy and share data in a bidirectional way, where DSO can obtain information from the equipment and also send information, e.g., to change the type of electricity tariff. Once each of the elements has an identification, it is possible through blockchain technology to identify the energy consumed and produced by each of the systems and distribute energy between them, that is, when equipment is able to consume the energy, it is distributed to them and when surplus exists it is stored [13].
Ali et al. present a system to group prosumers using blockchain to manage the possibility of scaling the infrastructure and the respective decentralization in a P2P trading scheme [11]. It proposes a scheme called SynergyChain to promote the scalability of the solution, as well as the decentralization of the prosumer grouping mechanism in a P2P context. It includes a learning module that improves the system's adaptability [2]. A financial platform to facilitate investments in renewable energy sources based on the Ethereum blockchain is also a solution. It implements a P2P Marketplace, based on price, thus bringing together investors and prosumers. The traded energy and its value are represented by "tokens", which are exchanged between participants automatically through pre-established conditions in smart contracts [33].
Another proposed system, called ETSE and developed under the PETRAS BlockIT project, facilitates the energy transaction between prosumers. Management is carried out through smart contracts in a blockchain network associated with smart meters. The system analyzes the various types of attacks that can then be promoted, bearing in mind the prevention of attacks [15].

Internet of Things
In order to implement a decentralized energy system, it is important to ensure that an adequate data exchange process is in place, because of the need to have real time information about energy consumption and production. This need requires the deployment of the "smart home" concept, supported by IoT technologies, with the introduction of sensors, smart devices and communication protocols that builds the foundation of P2P transactions, allowing consumers to trade energy with safety. Therefore, in the context of the model proposed in this paper, IoT provides local sensing to account for energy transactions without central supervision.
The growing interest on IoT technologies extends to several application areas [34]. Although there are multiple IoT architecture proposals [35], a basic IoT architecture can be divided in three layers: Objects, Network, and Application. The Objects layer collects data from the physical world using sensors that are integrated in electronic devices called sensor nodes. These devices include other components [36] that are essential for the node operation, such as a processing unit, a communication transceiver and a power source. Some devices may also act on the physical world using actuators. The Network layer connects the Objects layer to the Application layer, which is normally composed of several types of communication networks, which form the data communication infrastructure used by the different entities of the IoT. This layer also handles other IoT tasks, such as data storage and cloud computing. The Application layer provides specific services for the users based on the data collected by the Objects layer, such as automation of processes, use of data mining and control algorithms and user interface through IoT clients.
It is important to mention that the integration of equipment with sensors requires that consumers have to deal with additional technology, applications that require the collection of data and the additional interpretation of information [37]. The IoT is constantly growing, allowing to exchange huge amounts of information on a daily basis, which also raises issues related to information privacy. Blockchain can be a complementary technology to guarantee these situations, and improve the behavior in terms of storage and security [38].
Smart meters are important devices in this system, as stated in Figure 1. With smart meters, it is possible to obtain information about energy consumption and production within short time intervals (e.g., 15 min). This is important data for trading platforms. All data are encrypted and placed in the blockchain for smart contract purposes [14].

Literature Review Methodology
Using a PRISMA (Preferred Reporting Items for Systematic Reviews and Meta-Analyses) methodology, it was possible to select the articles to answer the main question raised by this paper. The methodology used is based on Moher et al. [39]. To guide the research, the key question was identified: "Can innovative blockchain technologies help prosumers

Literature Review Methodology
Using a PRISMA (Preferred Reporting Items for Systematic Reviews and Meta-Analyses) methodology, it was possible to select the articles to answer the main question raised by this paper. The methodology used is based on Moher et al. [39]. To guide the research, the key question was identified: "Can innovative blockchain technologies help prosumers on energy decentralization?". Papers were selected by using international recognized scientific articles in journals and conference proceedings using the most relevant databases. Five databases were used to search for available articles written in English, as presented in Table 2. To select the literature for this paper, five different inclusive and exclusive criteria were applied, as shown in Table 3.
The selection of articles was conducted based on the full texts and abstracts of the studies. To search the articles, we developed a query using our key question, which was based on three keywords Table 4: "Blockchain", to identify main technologies in this field; "Smart Contracts", to analyze main developments for trading on energy decentralization and, finally, "Prosumers", to identify the articles related to this concept, that is, consumers that are also producers of energy. These keywords were selected because the aim of this paper is to analyze the different processes proposed in the literature that allow energy consumers/producers to make their energy available to other owners, using blockchain technology. Journal articles and conference papers were considered in order to obtain the main recent contributions related to our search. Duplicates were removed from the inquiry.
Additional studies were identified though a backward and forward search, identifying the best practices and examples based on the reference and also on the relevant legislation at European level in order to better understand the path proposed by policy makers. Five additional articles were identified, and one study developed by the European Commission and two relevant European directives were included in this paper, for a total of fifty-nine references. Three researchers performed the screening process independently-every paper was screened by two of the researchers, and in case of disagreement, a third one would decide. Figure 2 provides a summary of the different steps of the review.
Energies 2021, 14, x FOR PEER REVIEW 9 of 28 fifty-nine references. Three researchers performed the screening process independentlyevery paper was screened by two of the researchers, and in case of disagreement, a third one would decide. Figure 2 provides a summary of the different steps of the review.     Table 4. List of keywords.

Identification of the Needs for a Review
The vast majority of energy markets start with a central entity, and then follow a flow of actors that ends at the final energy consumer. With the introduction of information and technology mechanisms properly adapted to the electrical power grid, it was possible to introduce renewable energy sources into the energy mix, thus creating paradigm shifts on the markets. As the power production from these forms of energy are intermittent, it is necessary to design the electrical power grid to accommodate these changes and maintain security of supply that allow a correct dimensioning of the electrical power grid. These changes, thus, open the door to prosumers that produce and consume energy; however, there is a needed for reliable systems that allow supply and demand to be adjusted in these cases, where trading platforms based on smart contracts can play a major role [40].
In this paper, we analyze the literature aiming the proposal of an integrated system of prosumers and trading platforms, properly adjusted with the electrical power grid operator, since it is necessary to ensure the supply of energy through the public electrical power grid, in order to guarantee the supply.

Objective of the Review and Review Protocol
The objective of this PRISMA literature review is to define the best model for a P2P energy trading system using an innovative blockchain approach based on IoT sensor devices that will enable smart contracts. The main steps of the review protocol are identifying the keywords, identifying the main databases and applying filters to obtain the final articles for the review.

Results and Data Extraction
After the application of the filter of the review protocol and removal of duplicates, a total of 54 articles were obtained, as shown in Table 5. With the data that were extracted from the different databases, it was possible to evaluate the years, citations and journal and conference rankings of each article. There was an almost equal distribution of papers from conference proceedings and articles from journals (52% journals). The h-index for the journals has a mean value of 130 points, based on Scimago. The majority of articles are very recent (from 2020), as shown in Figure 3, followed by 2019 and 2021, which shows the recent nature of the topic.

Literature Review Analysis
The revision of the different articles was made reviewing abstract and conclusio first, and the full text after. With the analysis of these articles, it was possible to identif five different concepts that must be a part of a decentralized system. Table 6 classifies th articles according to the adoption of each concept for microgrid and decentralization im plementation. Table 6. Classification of the reviewed articles according to energy decentralization concepts.

Grid Architecture Smart Devices and IoT
Trading Platform

Blockchain Technology
Smart Contract Design

Literature Review Analysis
The revision of the different articles was made reviewing abstract and conclusion first, and the full text after. With the analysis of these articles, it was possible to identify five different concepts that must be a part of a decentralized system. Table 6 classifies the articles according to the adoption of each concept for microgrid and decentralization implementation.
In Table 7, we describe these five concepts in terms of type of energy decentralization adoption. All the concepts must be a part of the energy decentralization network in order to ensure the correct functioning of the system and to unsure transparency and security of all the process. Grid Architecture refers to the design and constitution of the distribution power gird between the various market actors, Smart Devices and IoT describe the implementation scheme and description of used solutions and details of equipment, sensors, systems and smart meters, Trading Platform describes the solution, architecture and scheme and implementation proposal, Blockchain Technology includes the details of technologies, solutions, consensus mechanisms and proposal of implementation and Smart Contract Design presents the solution proposal, details of used code and relationship between actors and entities.

Concepts Type of Adoption
Grid Architecture • To provide the connections between producers, consumers, DSO (Distribution System Operators) and suppliers.

•
Renewable energy systems, energy storage and electric vehicle can be part of a decentralized system that may help to manage energy grids. • A properly dimensioned and designed electrical power grid allows for adequate management and for the best adjustment of demand and supply, bringing together various elements of the infrastructure, charging points, storage and energy production system.

Smart Devices and IoT
• Solutions such as smart metering, real-time monitoring, asset tracking and management. • Demand-response management is extremely important for the success of the implemented solution.

•
Smart meters need to be tamper-proof devices.
Trading Platform • Allows to make a match between offer and demand at the best pricing offer. • Users can use the system to have personalized advice and control energy tariffs.

Blockchain Technology
• Used to improve transparency of the process and provide a consensus mechanism. • Information can be stored in a chronologically order and all blocks are duly protected with cryptography. • Blockchain networks can be Public, Consortium or Private.

Smart Contract Design
• Smart contract design solves an economic dispatch problem of distributed energy resource to reach a consensus between producers and consumers and provide the best offer for each part.

System Architecture and Discussion
Based on the findings, we propose a community concept of renewable energy sources, grounded on IoT technologies to help to facilitate energy trading and transactions between prosumers and consumers. Current proposals and projects on the majority of cases only focus on one of these concepts. Pop et al. [29] implemented a similar concept but used a non-tested consensus mechanism, which, in our opinion, is not the preferred solution to implement. The renewable energy community concept, despite the social benefits and advantages to be open to all participants, must have a closed and controlled environment to work properly. Ideally, in this concept it will be helpful to have a mix of consumers, residential and non-residential buildings, public lighting and also electric vehicle charging stations, in order to better adjust offer and demand.

Electrical Power Grid Architecture
In this system architecture, each locale of production and consumption is considered to be a node in the electrical power grid. Each node has a smart meter and all nodes are connected to an electrical power grid and share data with the central trading platform. The interaction between actors occurs when conditions pre-determined by a smart contract are triggered [15]. In order for smart contracts to be initiated, each user of the electrical power grid, whether producer or consumer, must be duly registered in the network and have a unique identification. It is necessary to have an account that has the balance of energy sold and purchased and for a transaction to take place, each user must have the necessary funds for this to occur. As soon as there is a match between demand and supply, then there is an exchange of assets [21].
Theoretically, the electrical power grid concept proposed in this paper can be internal, that is, an electrical power grid owned by these prosumers, or it can be a central system electrical power grid managed by a distributor that has to approve all electrical connections that are made, as well as new connections to manage production and consumption.
This management of production and consumption is the central point of the whole process, since the production and consumption units may not match, so it is necessary to develop mechanisms that allow to adjust the production, store, connect equipment remotely in the consumer units or alternatively make the injection in the electrical power grid so that the surplus can be drained [61]. Figure 4 shows a proposed architecture, composed of an electrical power grid and a data network. Each building, as well as public lighting and public charging station, is a node on the network. They are all connected to the trading platform, sending information collected through smart meters, such as energy consumption and production, in kWh, for each period of the day, and the identification of the production system and consumption point. tem electrical power grid managed by a distributor that has to approve all electrical connections that are made, as well as new connections to manage production and consumption. This management of production and consumption is the central point of the whole process, since the production and consumption units may not match, so it is necessary to develop mechanisms that allow to adjust the production, store, connect equipment remotely in the consumer units or alternatively make the injection in the electrical power grid so that the surplus can be drained [61].Error! Reference source not found. Figure 4 shows a proposed architecture, composed of an electrical power grid and a data network. Each building, as well as public lighting and public charging station, is a node on the network. They are all connected to the trading platform, sending information collected through smart meters, such as energy consumption and production, in kWh, for each period of the day, and the identification of the production system and consumption point.    Each equipment can be triggered by the central management system for load balancing in order to bring supply and demand closer together. For the purpose of this paper, we do not consider an energy storage system because of the cost that this still represents, with high investment and maintenance [43]. Each equipment can be triggered by the central management system for load balancing in order to bring supply and demand closer together. For the purpose of this paper, we do not consider an energy storage system because of the cost that this still represents, with high investment and maintenance [43].

Smart Devices and IoT Framework
To have a successful system in place, there is a need to develop smart homes, that is, houses that provide innovative IoT systems, integrating sensor devices and other smart appliances that promote comfort, user convenience, improved security and above all, energy efficiency. Nevertheless, smart homes may also have negative aspects and challenges, such as the complexity of facilities and connections, initial learning curve by homeowners, connection to other systems and products, as well as issues related to privacy and security due to the traffic and data that are generated [44]. It should be noted that, in the scope of the IoT, the fact that there are more connected devices increases the security problem, as these devices (e.g., motion sensors, light switches, window sensors, weather sensors/stations and smart plugs) tend to use more lightweight and less secure protocols, which can lead to compromising situations. This problem happens because, with the massification of the IoT, it is intended that this equipment is above all inexpensive, but also small and with low complexity. Another problem is the high number of parties involved in the process, that is, as there are many accesses, information passes through the equipment and the attack can go through the sensor devices with the goal of attacking another party [15].
In the proposed scheme, it is important that all connected sensor devices have security protocols to address data and privacy concerns. An energy management system must be available for every house and installation in order for the process to be successful. This system will be connected to the dynamic pricing mechanism for trading purposes [8]. One of the key elements of our proposal is the incorporation of and energy management system that can help consumers to better understand their behavior, thus adjusting the consumption profile based on machine learning.
To be possible to use the appliances for load balancing, there is a need to evaluate the hours and functioning type of each equipment. Table 8 presents an example with a start time and end time for each appliance, the ability to participate in the flexibility of the network, the power rating and also the number of working hours. These values can be set in the beginning of the process, but, based on the energy management system of the different houses and installation, may be adapted for better management of the grid. This system must be installed in every house. The control of the appliances must be done with the help of energy management systems, which can control devices using automatic scheduling techniques, production and consumption of energy and help with energy prediction, management of smart contracts and energy trading, as represented in Figure 6 [41]. and consumption of energy and help with energy prediction, management of smart contracts and energy trading, as represented in Figure 6 [41]. Using a current clamp system, which is a non-intrusive way of measuring an existing electric circuit, embracing the live wire with the current clamp, it is possible to monitor power usage of high power-demanding appliances, such as air conditioners or battery chargers of electric vehicles. In Figure 7, it is possible to observe the power usage of a battery charger of electric vehicle, and calculate the amount of consumed energy, together with the charging schedule of the vehicle.
For regular appliances, smart plugs that measure energy consumption can be used to schedule the appliance or calculate the daily power usage. Using a current clamp system, which is a non-intrusive way of measuring an existing electric circuit, embracing the live wire with the current clamp, it is possible to monitor power usage of high power-demanding appliances, such as air conditioners or battery chargers of electric vehicles. In Figure 7, it is possible to observe the power usage of a battery charger of electric vehicle, and calculate the amount of consumed energy, together with the charging schedule of the vehicle.
For regular appliances, smart plugs that measure energy consumption can be used to schedule the appliance or calculate the daily power usage. electric circuit, embracing the live wire with the current clamp, it is possible to monitor power usage of high power-demanding appliances, such as air conditioners or battery chargers of electric vehicles. In Figure 7, it is possible to observe the power usage of a battery charger of electric vehicle, and calculate the amount of consumed energy, together with the charging schedule of the vehicle.
For regular appliances, smart plugs that measure energy consumption can be used to schedule the appliance or calculate the daily power usage. The goal of the centralized management system is to help the management of energy demand and reduce peaks of consumption, as illustrated on Figure 8. In this way, it is possible to reduce peaks and adapt consumption, thus making a better management of the grid [48]. Using smart relays to toggle appliances on and off when there is a need to adjust the electrical power grid load allows the system to intervene and, for instance, to start the charging of electric vehicles at night or change the charging schedule. It is important to evaluate possible peak hours using data from Table 9 and adjust the schedule accordingly.
When the energy load within a neighborhood is not balanced, the system evaluates each household individually to determine where the smart balancing measures should be applied. The goal of the centralized management system is to help the management of energy demand and reduce peaks of consumption, as illustrated on Figure 8. In this way, it is possible to reduce peaks and adapt consumption, thus making a better management of the grid [48]. Using smart relays to toggle appliances on and off when there is a need to adjust the electrical power grid load allows the system to intervene and, for instance, to start the charging of electric vehicles at night or change the charging schedule. It is important to evaluate possible peak hours using data from Table 9 and adjust the schedule accordingly.
When the energy load within a neighborhood is not balanced, the system evaluates each household individually to determine where the smart balancing measures should be applied.

Trading Platform
To promote P2P transactions, it is necessary a platform that acts similarly to what currently happens in traditional markets, a multi-settlement pool market. Based on that, we propose the following: First, use a futures market to forecast future transactions, as well as ensure a balanced supply and demand in real time; Second, use tools that allow prosumers to understand the state of the market and, thus, maximize their profits; Third, all information transactions are carried out based on smart contracts on a blockchain network and authentication using consensus mechanisms [40]. Figure 9 presents a concept for a trading platform using P2P and blockchain. It considers that, despite the importance of the decentralized model, it is still relevant the participation of the DSO in order to maintain the balance of the network and manage the electrical power grid connections [24]. Each node of the electrical power grid must publish information about its demand or generation of energy needs in the future market. This situation must be carried out based on the EMS mentioned before, which will at a given moment make the forecast of future consumption, as well as transmit this information to the electrical power grid; in this case, the period works with time intervals of one hour. With this information energy producers can adapt the systems for the needs of the electrical power grid. This information flows through smart contracts, threading the information to each of the parties and being duly registered for later consultation if necessary. It should be noted that immutability is one of the advantages of using blockchain mechanisms and respective consensus algorithms. Therefore, for this purpose, each consumption node must submit its demand profile for Each node of the electrical power grid must publish information about its demand or generation of energy needs in the future market. This situation must be carried out based on the EMS mentioned before, which will at a given moment make the forecast of future consumption, as well as transmit this information to the electrical power grid; in this case, the period works with time intervals of one hour. With this information energy producers can adapt the systems for the needs of the electrical power grid. This information flows through smart contracts, threading the information to each of the parties and being duly registered for later consultation if necessary. It should be noted that immutability is one of the advantages of using blockchain mechanisms and respective consensus algorithms. Therefore, for this purpose, each consumption node must submit its demand profile for each corresponding time interval, and each production node must submit its generation capacity with selling price for the same period. This information is used by the trading platform for market clearing and energy trading [40]. IoT devices can be used to define the profile of consumers and also producers, and also to make adjustments in real time. It is important to state that, in some situations, offer and demand could not match, and in these cases, utilities must also be part of the process, in order to ensure that energy is always available. Feed-in tariffs are also an important part of the process. In Figure 10, it is possible to see the flow of the operation and the interaction between all actors. For trading, a trading system can be used based on tokens and cryptocurrencies, such as Bitcoin, Ethereum and Ripple [26]. For each prosumer, the availability would be displayed through energy tokens that illustrates the energy account of each of them. This represents the tradable energy unit. Prosumers can buy or sell tokens using blockchain to ensure that a token is used only once. This information is stored in a trading platform to control the account of all users. Data are then shared through control messages on the network to smart meters and based on smart contracts. A trading platform using artificial intelligence (AI) and machine learning (ML) would provide personalized advice based on consumer profiles, consumption, energy prices and other relevant information, such as detailed energy consumption from different types of appliances [26].
In Figure 11, it is possible to view the electrical power grid in orange, where each smart meter is a node that exchanges data with the blockchain network. When a prosumer produces a unit of energy, the smart meter shares this information to the blockchain. Through smart contracts, this information is stored on the account of the prosumer to balance available energy tokens. These energy tokens can be bought by consumers and, by exchange through blockchain transactions, the amount of each token is passed from the buyer to the producer. In order to manage this process, the trading platform must have an AI algorithm to help consumers and producers to maximize gains or minimize costs and guarantee that the produced energy is all consumed inside the community [26]. For trading, a trading system can be used based on tokens and cryptocurrencies, such as Bitcoin, Ethereum and Ripple [26]. For each prosumer, the availability would be displayed through energy tokens that illustrates the energy account of each of them. This represents the tradable energy unit. Prosumers can buy or sell tokens using blockchain to ensure that a token is used only once. This information is stored in a trading platform to control the account of all users. Data are then shared through control messages on the network to smart meters and based on smart contracts. A trading platform using artificial intelligence (AI) and machine learning (ML) would provide personalized advice based on consumer profiles, consumption, energy prices and other relevant information, such as detailed energy consumption from different types of appliances [26].
In Figure 11, it is possible to view the electrical power grid in orange, where each smart meter is a node that exchanges data with the blockchain network. When a prosumer produces a unit of energy, the smart meter shares this information to the blockchain. Through smart contracts, this information is stored on the account of the prosumer to balance available energy tokens. These energy tokens can be bought by consumers and, by exchange through blockchain transactions, the amount of each token is passed from the buyer to the producer. In order to manage this process, the trading platform must have an AI algorithm to help consumers and producers to maximize gains or minimize costs and guarantee that the produced energy is all consumed inside the community [26]. In order to establish the structure and information contained in the smart contracts, it is possible to define a transaction structure using information about participants, assets and transactions. In Table 9, a list of information to complete a transaction is proposed. Information about consumer and producer is also presented containing personal information, an identifier that can be an email address or an IDgrid. The introduction of this ID is one of the advantages of our proposal, making possible to build an identifier of each participant. The "Balance" represents the digital currency, the token used for the transaction. When the transaction happens, the number of tokens is updated on the digital wallets of the participants. Regarding the assets, two are proposed, 'RES' and 'kWhlisting'. 'RES' represents all registered renewable energy systems, which have the identifiers 'RESid' and 'ownerid' ID, the e-mail address of the producer. 'kWhoffer' is automatically presented by the system and updated every hour with the following information: 'listingid', with date and time of RES electricity exchange; and 'state', which can have two options, 'AU-THORIZE_OFFERS', that represents that offers are accepted from producers and buyers, or 'BIDS_CLOSED', representing that offers and bids are no longer accepted. 'RESOffer' and 'BuyOffer' are other fields with the values that producers and buyers are offering [27].
Transactions have four main attributes. 'AuthorizeOfferCom' represents the beginning of the bidding phase. Each hour, a message is automatically sent to all participants inviting to participate in the bid. 'RESoffer' represents the amount of energy in kWh and token price per kWh. 'BUYOffer' allow consumers to send bids, identifying the amount of energy needed and the price they are willing to pay. With 'Bid_Closed', the process is closed, the smart contract processes the information and the trading is processed [27].
Within the smart contract processing, we have the clearing price of the market, as represented in Figure 12. After this process, the 'CloseBidding' is initiated to close the process. Using RESOffers and BUYOffers, the global amount of kWh available for sale, (kWhavailable), and kWh to be purchased, (kWhwanted), are calculated. The market clearing price, (MCP), as token/kWh, can be determined in each hour by the average bid price offered by all buyers, as proposed by Pipattanasomporn et al. [27]. The principle to match buying and selling offers is based on the FIFO (First-In First-Out) algorithm, and the highest offer to buy energy is the one that wins the auction.
In order to guarantee the proper functioning of this entire process, it is necessary that the network where the system is based has a performance capacity duly established; otherwise, it will not be possible to carry out transactions every hour. Thus, the selected Power grid Figure 11. Trading system representation.
In order to establish the structure and information contained in the smart contracts, it is possible to define a transaction structure using information about participants, assets and transactions. In Table 9, a list of information to complete a transaction is proposed. Information about consumer and producer is also presented containing personal information, an identifier that can be an email address or an IDgrid. The introduction of this ID is one of the advantages of our proposal, making possible to build an identifier of each participant. The "Balance" represents the digital currency, the token used for the transaction. When the transaction happens, the number of tokens is updated on the digital wallets of the participants. Regarding the assets, two are proposed, 'RES' and 'kWhlisting'. 'RES' represents all registered renewable energy systems, which have the identifiers 'RESid' and 'ownerid' ID, the e-mail address of the producer. 'kWhoffer' is automatically presented by the system and updated every hour with the following information: 'listingid', with date and time of RES electricity exchange; and 'state', which can have two options, 'AUTHORIZE_OFFERS', that represents that offers are accepted from producers and buyers, or 'BIDS_CLOSED', representing that offers and bids are no longer accepted. 'RESOffer' and 'BuyOffer' are other fields with the values that producers and buyers are offering [27].
Transactions have four main attributes. 'AuthorizeOfferCom' represents the beginning of the bidding phase. Each hour, a message is automatically sent to all participants inviting to participate in the bid. 'RESoffer' represents the amount of energy in kWh and token price per kWh. 'BUYOffer' allow consumers to send bids, identifying the amount of energy needed and the price they are willing to pay. With 'Bid_Closed', the process is closed, the smart contract processes the information and the trading is processed [27].
Within the smart contract processing, we have the clearing price of the market, as represented in Figure 12. After this process, the 'CloseBidding' is initiated to close the process. Using RESOffers and BUYOffers, the global amount of kWh available for sale, (kWhavailable), and kWh to be purchased, (kWhwanted), are calculated. The market clearing price, (MCP), as token/kWh, can be determined in each hour by the average bid price offered by all buyers, as proposed by Pipattanasomporn et al. [27]. The principle to match buying and selling offers is based on the FIFO (First-In First-Out) algorithm, and the highest offer to buy energy is the one that wins the auction. mechanism must address, in addition to security-related issues, the performance and possible scalability of the solution. The solution now proposed may only consider residential buildings, but in order to better adapt to demand and supply, the ideal would be to insert into the network other types of buildings that can absorb any peak of energy consumption during the day [45]. Based on offer and demand, it is possible to set the clearing price of each auction [38], which represents the balance between producers and consumers and which results from the auction that is held every hour, as stated in Figure 12. This price is determined automatically through the trading mechanism and consider an average price for selling energy of 0.039 €/kWh and a buying price of 0.095 €/kWh on the peak period between 13 to 23 h [54].

Blockchain Implementation
This paper considers a P2P private network with blockchain nodes and distributed ledgers containing information about smart contracts that deal with transactions and share data between all actors. It is important to ensure data security and privacy of all processes. Each customer must have an exclusive identity with an identifier that distributes and replicates the copy of the transaction to all the peers in the network for validation [8]. For this purpose, a consensus mechanism must be in place. Several mechanisms can be adopted. Proof of Work (PoW) can be used in order to ensure the immutability of the information [8]; however, PoW is a consensus mechanism that is energy intensive; therefore, it is not the most adequate option for energy-efficiency purposes [29]. The Ethereum platform is one of the most used algorithms in the energy area and it is based on the Proof of Stake (PoS) concept, which does not need large amount of computational power in order to solve the problem to make a new block and in terms of rewards is better for investment in the network. In terms of security, an attack can be very difficult, as it needs the majority of support [20]. In the PoS consensus mechanism, a node that has the right to create a new block is elected, and for that, it must have an interest in the transaction, called "stake", such as the virtual currency itself. This process, however, may have some limitations, as the node that demonstrates that it has more in stake may be the one that most often will have the right to create new blocks. In order to democratize this process, there are platforms that require authentication and permissions, as well as making it difficult to In order to guarantee the proper functioning of this entire process, it is necessary that the network where the system is based has a performance capacity duly established; otherwise, it will not be possible to carry out transactions every hour. Thus, the selected mechanism must address, in addition to security-related issues, the performance and possible scalability of the solution. The solution now proposed may only consider residential buildings, but in order to better adapt to demand and supply, the ideal would be to insert into the network other types of buildings that can absorb any peak of energy consumption during the day [45].
Based on offer and demand, it is possible to set the clearing price of each auction [38], which represents the balance between producers and consumers and which results from the auction that is held every hour, as stated in Figure 12. This price is determined automatically through the trading mechanism and consider an average price for selling energy of 0.039 €/kWh and a buying price of 0.095 €/kWh on the peak period between 13 to 23 h [54].

Blockchain Implementation
This paper considers a P2P private network with blockchain nodes and distributed ledgers containing information about smart contracts that deal with transactions and share data between all actors. It is important to ensure data security and privacy of all processes. Each customer must have an exclusive identity with an identifier that distributes and replicates the copy of the transaction to all the peers in the network for validation [8]. For this purpose, a consensus mechanism must be in place. Several mechanisms can be adopted. Proof of Work (PoW) can be used in order to ensure the immutability of the information [8]; however, PoW is a consensus mechanism that is energy intensive; therefore, it is not the most adequate option for energy-efficiency purposes [29]. The Ethereum platform is one of the most used algorithms in the energy area and it is based on the Proof of Stake (PoS) concept, which does not need large amount of computational power in order to solve the problem to make a new block and in terms of rewards is better for investment in the network. In terms of security, an attack can be very difficult, as it needs the majority of support [20]. In the PoS consensus mechanism, a node that has the right to create a new block is elected, and for that, it must have an interest in the transaction, called "stake", such as the virtual currency itself. This process, however, may have some limitations, as the node that demonstrates that it has more in stake may be the one that most often will have the right to create new blocks. In order to democratize this process, there are platforms that require authentication and permissions, as well as making it difficult to change their stake values. The proposal we present in Section 4 has these last two points in line [41]. Another consensus mechanism, the Hyperledger Fabric, uses byzantine fault tolerance (BFT) consensus, which is suitable for enterprises and private networks and guarantees added control over transactions, better performance and scalability [32].
To implement the process referred in Table 9, we proposed the use of the Hyperledger Fabric framework, an open source platform that can be used for P2P trading. It has a modular architecture and is considered to have good performance with high capacity to incorporate different modules that increase privacy and encryption [51]. Hyperledger Fabric is considered to be more flexible and more suitable to develop private networks and adapted for specific needs than Ethereum based systems, as presented in Table 10, namely, the number of transactions per second (TPS) allowed on Hyperledger Fabric is much higher, up to 3500 TPS. Another important aspect is the framework used to implement smart contracts. On Hyperledger fabric, several languages can be used and on Ethereum Solidity, which is a specific object-oriented language for implementing smart contracts. In Figure 13, it is possible to see a simplified example of a blockchain framework for decentralized purposes. The blockchain would be used as ledger, a database of energy transactions, and as a management system using information from smart meters [26]. Based on blockchain solutions, it is possible to have an adequate demand-response system in place that offer a fair platform for prosumers to trade energy. It is important to mention that blockchain networks can be placed in three categories: Public, Consortium and Private. In public networks, all participants can read or write on the blockchain and also participate in the consensus procedure, in consortium networks, the consensus procedure is controlled by pre-selected nodes, and in private networks, authorizations are made by one entity. These different approaches have different security degrees maintained by cryptographic tokens to guarantee data quality and validation on the blockchain network [31]. The information that flows on the blockchain will trigger the conditions set on the smart contracts and each node will have a copy of the ledger. This will help to improve trust and transparency on the process with information available on different locations and guarantee that energy is not sold in duplicate [26]. There are also some constraints The information that flows on the blockchain will trigger the conditions set on the smart contracts and each node will have a copy of the ledger. This will help to improve trust and transparency on the process with information available on different locations and guarantee that energy is not sold in duplicate [26]. There are also some constraints that must be observed, namely data storage and scalability. The size of the chain is always increasing, as due to the immutability, transactions related to smart contracts cannot be eliminated. In this sense, it is necessary to be aware of the storage dimension [37]. IoT needs communications and also produces a big amount of real time data. With the increase of the network in different areas, more resources are needed, and the system must have the characteristics to incorporate more data and yet be able to perform. Another important aspect is anonymity and data privacy. It is important that authentication and authorization mechanisms are in place. Hyperledger Fabric guarantees this aspect where information is managed according to different levels of permission. Reliability is also important; transactions rely on data from sensors and the EMS system and traceability of the information must be made possible. If users do not trust the information, then it is impossible to implement such a system. Sensors of each appliance and equipment communicate to EMS, and smart meters also communicate with the management system. Every hour, based on forecast algorithms, such as Prophet, it is possible to send previsions for the bids at production and consumption levels. This information is then stored on smart contracts.
Smart contracts are self-executable code and contain a set of rules that must be followed in order for a transaction to take place. They contain automatic setup conditions for demand and response and also information about energy profiles and operation of each house and production system. They also contain information about bids, price components, traded and available quantities, market information and prosumers systems [23]. They also contain other relevant information, such as contract duration, capacity limits, number of allowed transactions, incentives and suspension mechanisms [24]. Smart contracts are a part of the blockchain code, contribute for the transparency of all the process and do not need a central entity to operate [62]. Each entity has an identifier and each installation is a node on the network. Smart contracts are performed on each node automatically, based on previous set conditions, and operate through a virtual machine with blockchain as the distributed virtual machine [30]. The main operations of a smart contract are performing parts of the blockchain algorithm, exchanging information within the blockchain with other nodes and allowing other nodes to perform the next operation [47].
Smart contracts allow to buy or sell energy and monitor a control of all transactions. All payment processes between producers, consumers and the main grid happen through these contracts. It is important to promote the interaction and participation of prosumers and consumers [12], in order to have the maximum number of offers, and therefore, maximize gains for producers and consumers.

Conclusions
Electricity supply requires compliance with rules that depend on each country, so it is difficult to find a model that can be implemented without observing certain specificities, even knowing that the intention is to move from a centralized model of electrical energy production and consumption to a decentralized model. In an electrical power grid with industrial or non-residential consumers with larger installations, a backup in the energy supply must be ensured by the public electrical power grid. Additionally, in most electricity markets, the installed production of the electrical power grid must also be duly authorized by the licensing entity, and in close collaboration with the distribution system operator (DSO), in order to ensure that the public electrical power grid is able to absorb any excess of energy production, but also guaranteeing the energy supply for the consumers, at all times.
With the publication of new legislation across Europe based on the recent energy European directives, it is possible across the majority of member states to implement pilot projects for renewable energy communities, and several are already underway in order to test and evaluate different methodologies. Based on the reviewed articles, it was also possible to verify that across the world, many projects are being implemented with successful results, with increased gains in reducing energy costs. With this information, it is possible to verify that the technologies are ready, but there are still legal barriers in some countries that must be addressed in order to be able to implement these types of electrical power systems. Consumer awareness must also be a part of this process; if homeowners are not willing to participate, it will not be possible to implement these models.
In that regard, this paper proposes a model of an electrical power grid and blockchain network, which responds to the majority of self-consumption installations with relevant dimensions, allowing to record up to 3500 transactions per second, and requires the existence of a trading mechanism that allows the integration of producers, consumers and prosumers, thus matching the electrical energy supply and demand. The blockchain solution also provides for the existence of smart meters in all installations, sensors in the equipment and even energy management systems, which can transmit information on consumption and production to the trading system in real time. The formalization of the relationship between the various actors must be carried out through smart contracts that must be duly authorized by the owners of each energy production system, as well as by the consumers. Blockchain operating conditions, such as the mandatory "IDgrid", which allows users to be identified, provides the system with credibility and security. The match between energy supply and demand should be done at all hours during the day, thus ensuring a proper optimization of the electrical power grid operation. Thus, it is possible to guarantee a balance between electrical systems, promote transparency and ensure the proper functioning of the entire process. Management and operational costs are also reduced due to the absence of the central entity, allowing producers, consumers and prosumers to obtain a fairer tariff offer.
The scalability of blockchain can be overtaken by applying this approach to local communities in a size that current blockchain consensus mechanisms can be handled efficiently in an appropriate time.