A survey on blockchain ‐ enabled smart grids: Advances, applications and challenges

Electric power grid infrastructure has revolutionized our world and changed the way of living. So has blockchain technology. The hierarchical electric power grid has been shifting from a centralized structure to a decentralized structure to achieve higher flexibility and stability, and blockchain technology has been widely adopted in the energy sector to deal with grid management, billing, metering, and so on, because of its nature of decentralization. Here, the aim is to provide a multi ‐ dimensional review on the technological advances of the blockchain in smart grids. Its corresponding applications based on these advances, including company projects and use cases, are summarized. Furthermore, the security threat issues in smart grids, Ethereum Virtual Machine (i.e. the operating environment of consensus mechanisms), and smart contracts are analysed, with a brief conclusion to manifest the prior tasks in building secure blockchain ‐ based infrastructures in smart grids. As such, the challenges and features of different protocols and their applicability in each use case are identified to provide an insightful guide for future research studies.


| INTRODUCTION
Traditional power grids are generally used to carry power from central generators to a large number of customers. According to some literature studies, the characteristics of this power network mode are summarized as follows [1,2]. Firstly, the high distribution loss is caused by long distance transmission. Secondly, distribution stations must be built, and there are high civil and installation costs. The risk rate of large-scale power supply accidents is high due to the use of integrated power supply. It is difficult to control and monitor regional power quality and performance. At present, thermal power generation is still widely used, which brings more environmental problems. In addition, its information services are lagging behind the needs of our times. The traditional power network is a rigid system. The access and exit of power supply and the transmission of electric energy are inelastic, which leads to the lack of dynamic flexibility and grouping of the power network. The vertical multilevel control mechanism is slow to respond and cannot build real-time, configurable and reconfigurable systems. The self-healing and self-recovery capability of the system is completely dependent on entity redundancy. There are many information islands in the system which lack information sharing. Although the degree of local automation is constantly improving, due to the imperfection of information and due to weak sharing ability, the multiple automation systems in the system are fragmented, local and isolated, and unable to form a real-time organic unified whole, so the intelligence degree of the entire power grid is low.
In contrast, Smart Grid (SG) uses two-way flows of electricity and information to create an automated and distributed advanced energy delivery network, which is expected to be the next-generation power grid [3]. SG utilizes modern information technologies and computational intelligence in an integrated version to deliver power, which is characterized by selfmonitoring, adaptive recovery and distributed generation. The new features of smart grid technology can be concluded as follows: � Two-way flow: Through the use of electromechanical components, conventional grid transfers electricity and the information goes from power generating units and utilities to consumers in a single direction way. In a smart grid, it adopts Information and Communication Technology (ICT) to allow two-way communication flow, and the electricity can be delivered bidirectionally [3]. � Distributed energy resources: Smart grid utilizes microsources such as renewable energy to form a microgrid to support distributed energy systems; however, the traditional grid system is centralized where generation and distribution are hierarchical.
By utilizing micro-sources, SG can control and optimize electricity demands of local areas in a more economical and reliable way. The distributed generation promotes the development of new grid paradigms, which benefits from smart energy subsystem technologies. Storage systems can be used in virtual power plants or nearby loads. The storage system comprises the distributed electricity generators (including renewable energy from the wind, sun, tide and so on) and fast response devices including batteries and EVs, which add flexibility to the control of the microgrid. By storing energy at times of excess power and generating electricity at times of low generation, the microgrid system is capable of accommodating the power demand profile fluctuation. Furthermore, the characteristics of different storage devices can be utilized to tune the frequent and rapid power changes in renewable resources, which brings economic advantages for the microgrid as well as improves the power quality. The technological advances in the smart grid can be categorized into four groups including power and energy technologies, power system capacity, power system performance, and end-user integration [4].
In the process of energy decentralization and digitalization from a traditional hierarchical grid network to a smart grid, the main challenge is to explore the most suitable control paradigm and distributed technologies. Blockchain is a shared decentralized ledger that can support permissioned or permissionless user participation, which provides scalability, security, redundancy and adaptable applications [5]. The inherent nature and recent development of blockchain technology have made it a promising solution for energy grid advancement. Furthermore, compared with conventional SG that fully depends on the redundancy of each entity to ensure system reliability, blockchain can utilize distributed ledger technology (DLT) and consensus mechanisms that can be continuously replicated on all or at least a group of nodes in a blockchain network to avoid a single point of failure. Despite the assistance from blockchain technology, the transformation from the traditional grid structure to the smart grid still faces huge workloads from the infrastructure design, installation and requirements from various stakeholders. The challenges of the smart grid system based on the analysis of current applications are addressed as follows: 1. Integration: The massive distributed energy resources such as solar panels and wind turbines need to be integrated into the smart grid system where power generation is intermediate and unpredictable. The interactions between the distributed resources and grid operators are highly random with different control standards and protocols so that an automated control system is required to accommodate more types of decentralized participants. 2. Scalability: As mentioned above, the rise in the number of participants will increase the number of transactions. The latency will increase with higher user participation. And there is inherent latency of the system response time for communication, power delivery and settlement, which serves the system's scalability [6]. 3. Security: Security concern has two aspects, data privacy and the vulnerabilities and mitigations in both blockchain and smart grids. The transaction data in a traditional grid system is exposed to various attacks which can be inferred from a user's identity and activity patterns [7]. Moreover, smart grid systems that utilize advanced ICT protocols can be compromised or eavesdropped due to fake or malicious data attacks in the network [8].
In this regard, this paper presents a comprehensive review of the blockchain technology solution to smart grid transformation from the point of technological advances in its industrial applications and, finally, the challenges and opportunities. Various use cases of blockchain applications in the energy sector demonstrate that blockchain technology will be a game changer in the future. Furthermore, the discussed challenges involve not only the security concerns in blockchain itself but also the threats and safeguards to smart grids that will act as holistic lessons for advancing the combination of blockchain and smart grids in future. Compared with the surveys [9,10] that do not involve the security concerns related to blockchain-enabled smart grids or only show some highlevel security concepts, the strength of our survey is to provide in depth security discussions on both blockchain and smart grids. Meanwhile, compared with two other surveys [11,12] that only focus on the security and privacy of blockchain, this work also presents the challenges and countermeasures from the perspective of smart grids to offer a broader view of security and privacy for different researchers in the fields of blockchain and smart grids. Our contributions focus on technological insight to evaluate the novelty and feasibility of blockchain technology: 1. This work provides an in-depth understanding of the advances in blockchain technology in the smart grid. We present a comprehensive state-of-the-art solution from a technical perspective which includes consensus mechanisms and smart contracts, and SG operational side, including energy infrastructure and markets. 2. Based on the technological advances, the blockchainenabled energy sector applications with prospective fields are identified from current pilot projects and trials. A systematic review of the current use cases is provided according to the consensus mechanism type, which emphasizes on the energy system infrastructure design for different scenarios. LIU ET AL.
3. By analysing the security issues in the smart contract and Ethereum Virtual Machine (EVM), which are two fundamental entities for storing and running consensus mechanisms applied in the energy sector, we conclude the primary missions to develop a more secure running environment for consensus mechanisms in future.
The rest of the paper is organized as follows: Section 2 provides an overview of blockchain technology including terminologies and technologies. In Section 3, blockchain technology in smart grids is presented with key elements and advances. Section 4 reviews state-of-the-art real use cases from pilot projects based on consensus mechanism applications. Section 5 presents a security threat analysis and the challenges exposed in the smart grid and blockchains, and Section 6 provides the conclusion and the scope of future work. A list of abbreviations is also included in Table 1.

| OVERVIEW OF BLOCKCHAIN TECHNOLOGY
Blockchain technology is primarily known from cryptocurrency applications which are viewed as the first stage blockchain. However, blockchain technology is envisaged to have the capacity to reform financial markets, supply chains and business-to-business services [21]: • Digital securities trading: proof of ownership for asset registries and title transfer of hard assets to secure recording of intangible assets [22]. • Foreign exchange: executes currency exchange and conversions such as Coinbase (wallet) and Kraken [23]. • Digital identity: protects the privacy of consumers by providing an immutable digital identity for users. • Supply chain: improves transparency in supply chain records with the certification of manufactured products or diamonds certification [24].
The variety of proposed applications expect blockchain technology to bring significant process optimization and novel business models. The potential lies in the DLT which can redefine digital trust and remove intermediaries which disrupt traditional forms of hierarchical governance. The disruptive nature of blockchain technology is able to use consensus within the network to enable an open-source and transparent community to support decision-making and system running.

| Blockchain deployment
Blockchain is a shared and trusted DLT that permits the recording of any digital asset transaction between parties over a decentralized network, which is initially developed as a mechanism to record financial transaction [25]. Bitcoin is known as the first blockchain application, and the technology is continuously evolving [26]. The advanced features of blockchain are a genuine combination of several techniques including distributed computing, cryptography, peer-to-peer (P2P) communication and game theory, where technological and economic primitives are elegantly considered [27]. Data integrity is guaranteed via the nature of the distributed feature, and the encryption system that uses public and private keys offers users the ability to sign transactions [28].
Blockchain can also be classified as the parent chain and side chain according to the relationship between chains. The comparison between different types of blockchain is demonstrated in the Table 2.
• In a public blockchain, there are no access restrictions for any participant. The transactions on the blockchain are available for checking and all peers are allowed to make transactions. Typical applications include Bitcoin and Ethereum. A public blockchain is used in cryptocurrency, e-commerce, Internet banking, etc. [29].
• In a consortium blockchain, update operations are only allowed for its consortium members. Only the selected set of nodes are responsible for executing the consensus mechanism in the network. It is generally suitable for making payments, accounting and auditing between banks where one block can be globally confirmed after confirmation from two-thirds of the nodes. • A private blockchain is applied in private organizations for database management and auditing. The value of private blockchain is that it provides a secure, trackable, immutable and automated platform [28].

| Blockchain operations
A complete blockchain system is composed of complex technologies, for example, digital signature and time stamps for data storage, consensus mechanisms in the P2P network, mining and PoW, bitcoin wallet for an anonymous transaction technique, Merkle tree for data structure, and so on [30]. It is because of the aforementioned technologies that the blockchain system is constantly transacting, validating and expanding. The fundamental components of blockchain technology are shown below: • Data block: Transactions are stored in the data block where the block generation rate is roughly 10 min for each block, and each data block contains a header and body. The header encapsulates the version, previous block address, timestamp, nonce, Merkel root, etc., and the body contains the transaction counts and details [31]. Each transaction is permanently stored in the data block and available for checking by anyone. And the Merkle tree in the block body applies a digital signature to each transaction so as to ensure that the transactions are not repeated or forged [32]. • Mining and forks: Mining is the process of searching a random number (nonce) which makes the hash value satisfy the requirement for gaining the right block selection [33]. The newly generated block will be broadcast immediately for validation in case of fraud, and the blocks can be traced back through the hash value. However, there will be forks when two miners successfully mine two blocks at almost the same time. After forking, the system will continue mining and choose the parent chain by calculating the maximum proof-of-work where the fork chain will be abandoned [34]. It has also been noted that some mining techniques require huge energy consumption to compute, which can have significant social and economic impacts [35]. • Timestamps: In the blockchain system, the node needs to add the time stamp when generating a new block to record the block write time. The following block will add an approved time stamp to certify the previous block, which forms a long-term increasing time chain. The timestamp is a significant parameter for the proof of existence, which ensures the immutability of the blockchain system [36]. • Unspent Transaction Outputs (UTXO) [37]: UTXO is the basic unit in the bitcoin transaction process. Except for the genesis block, all transactions (Tx) in the block contain the origin of the funds (TX_in) and the output of the funds (Tx_out). Only the UTXO stored in the network nodes with the digital signature can be transacted. In this way, the system does not need to check its complete transaction history to confirm its legitimacy. • Hash function: The hash function codes the original transaction data into a fixed-length string, which is composed of numbers and alphabets [38]. This process is single directed so that the coded hash value cannot be interpreted [39]. SHA 256 is the most commonly applied hash function using the Merkle-Damgard function to generate a 256-bit hash value [40]. • P2P network [41]: P2P network is a distributed application framework that is used to assign tasks and workloads between peers. A blockchain system is established upon IP communication protocols and distributed networks. Each node in the peer network has equal rights which do not exist in any centre point or hierarchical structure.

| Blockchain smart contracts
With the complex design of smart contracts, it can be applied to many areas such as database systems, financial derivative services, etc. [42]. Generally speaking, a smart contract cannot be intervened by human activities once it is successfully  deployed. The Ethereum is a blockchain platform supporting smart contracts, and the advantages of smart contracts can be concluded as follows: • Real-time updates: A smart contract supported system responds in almost real-time as it does not need an intermediary or third-party authentication, which largely increases transaction efficiency.
• Accuracy: The execution of each contract term is predefined and under the program's control, where all outputs are accurate and predictable [43].
• Low human intervention: Once a smart contract is deployed, the content of its contract cannot be revised by any parties so that any fraud or dishonest behaviour is punishable by the contract [44].
• Low operation cost: The system can achieve low-cost transactions by removing human involvement in transaction, enforcement and compliance costs [45].
Smart contracts are user-defined programs that determine the rules of writing on the ledger [46]. It is a computer protocol that is capable of self-executing and self-verifying without human intervention once it is deployed on the network [47]. In the technological aspect, smart contracts are executable programs that make changes on the ledger and are automatically triggered when being called or when a specific requirement needs to be met.
Before deploying a smart contract, the contract terms and logic flows are made with relevant standards. Then they are recorded in computer language encoding legal constraints and terms of agreements. A smart contract usually provides an interface for human-contract interaction which complies with the recorded logic and rules [48]. With the integration of cryptographic technology, the interaction activities can be authenticated to ensure that the contract is executed without any collisions or fraudulent activities in the process [49]. For example, the management of bank accounts can be viewed as a set of smart contract applications. In the traditional banking system, operations such as withdrawal and deposit need authentication from a centralized bank, and the system cannot run without the bank's supervision. With the aid of smart contracts, any operation can be programmed with strict logic flows and the system runs by calling the smart contract. In Figure 1, it depicts the logical workflow for the smart contracts on the Ethereum platform. Users can define the smart contracts using programming languages such as Solidity, Serpent and Lisp Like Language, which need to be translated into the EVM bytecodes [42]. Then the code is deployed on the Ethereum nodes with the cost of GAS using the Ethereum cryptocurrency for miners' confirmation. After it is successfully deployed, users can obtain an address for the contract and the interface. The Javascript API interface provided from web3.js can be used for calling contracts and making interactions [50].
As a complex combination of various technologies, blockchain is an elegant design of computer science, telecommunication, cryptography and economy. The core technologies includes consensus mechanism, unlocking script [51], Merkel proof [52], transaction rules [38], Recursive Length Prefix [53], etc. In particular, this thesis focuses on the following technologies: 1. A smart contract that resides on blockchain and allows the automation of multi-step processes to self-execute the distributed heavy workflows is envisaged in the energy industry and the Internet of things [54]. The use of a smart contract in blockchain technology is driven by open-source agreements, which also provide the potential to balance supply and demand in the transactional energy market. A smart contract also provides insight into allowing the automation of multi-step processes to self-execute the distributed heavy workflows, which is envisaged in the energy industry and the Internet of things. 2. The consensus mechanism guarantees its robustness against misbehaviour and against malicious participants and incentivizes participants to validate transactions [36]. Hence, blockchain is a promising technology for broad business sectors where transparency, trust and efficiency are needed as it can help design and deploy a proper consensus mechanism.

| Consensus mechanisms
In a distributed system, multiple peers form a network cluster through asynchronous communication where states need to be replicated between different hosts to ensure consistency in all the peers [55]. However, if any of the peers in the cluster encounters attacks or failure, it might cause network congestion and broadcast tampered messages in the network. Hence, a fault-tolerant protocol is needed in the unreliable asynchronous network to ensure a consistent consensus among all the peers. As for the blockchain-based distributed ledger, the primary concern is to realize the correctness and consistency of the transaction data from different ledger nodes [56]. The consensus mechanisms in blockchain are the mechanisms or set of rules that enable all the full nodes to reach an agreement or consensus over the order of transactions [57]. There are many types of consensus mechanisms in different blockchain applications or scenarios such as Proof of Work (PoW), Practical Byzantine Fault Tolerance (PBFT), Proof of Stake (PoS), RAFT, Proof of Authority (PoA), etc. After converging of the blockchain consensus process, the final confirmed block/order of transactions is referred to as the consensus finality [58]. It is worth noting that Directed Acyclic Graphs (DAG) could be an alternative to the traditional blockchain technology and can be categorized as a DLT [59]. It differs from blockchain in how transactions are added to a network, and it aims to improve the existing speed, scalability and cost issues of blockchain technology. Furthermore, by addressing the energy consumption issue generated from resource-intensive designed mining protocols, more studies have also explored the benefits of renewable resources to mitigate those negative environmental externalities [60].

| Proof of Work
Bitcoin is one of the most widely used blockchain systems that use PoW to solve the critical challenge of reaching consensus among participants [18]. PoW requires participants to dedicate computation time and energy towards work (mining), where the processes of initiating this consensus mechanism are called miners. Miners are required to solve a hash code crypto puzzle before encapsulating the transactions into a new block [61]. The miners repeatedly select a nonce, which is the difficulty in solving the puzzle to obtain a result lower than the threshold, whereas the network peers fight using their computation source. In this way, it is nearly impossible for a single attacker to jeopardize the system by modifying the block and solving the puzzle due to extensive computation. So the system can only be controlled or attacked if someone gains 51% of the total network hash power [62].
Undoubtedly, there is a huge waste of energy and it requires a constant global effort. It is claimed that Bitcoin and Ethereum burn over $1 million worth of electricity and hardware costs per day for running the consensus mechanisms [63]. Moreover, in order to reduce the number of forks in the chain, Bitcoin's PoW is designed to produce a new block in an average of 10 min and the difficulty of mining a new block is increasing. The PoW protocol has proved that it scales to a large number of users for public use. However, transaction rates and finality are comparatively low [64]. The recommended waiting frame is six blocks before accepting a transaction, which makes it impossible for many applications such as electricity trading [65].

| Byzantine Fault Tolerance
The origin of BFT algorithms is their work on Byzantine faults which deal with unpredictable actions in computer networks when encountering hardware breakdown, network congestion or malicious attacks [15]. The problem concerns a set of Byzantine generals to agree on a joint plan of action during the war. Generals need to perform a joint action in coordination with the different parts of an army to attack simultaneously; however, the message can only be delivered by senders due to the huge territory. The challenge is to ensure that loyal generals reach a consensus on the plan of attack such that traitors cannot disrupt the attack plan. It is proved that the attack plan can be guaranteed if there are no more than one-third traitors in the system [57].
In the blockchain system, the PBFT algorithm enables a system to reach consensus with a low overhead and proceed transaction within a few network information exchanges that work against up to one-third of the attacks from participants [66]. The PBFT algorithm uses primary and secondary replicas where the secondary replicas check the correctness and liveness of the primary ones so that the complexity decreases from exponential to polynomial [36]. PBFT enables instant consensus finality as blocks are globally verified. The problem of consensus is that participants of the distributed system must agree on and accept a single shared state [67]. It requires the network to have global knowledge of the participants and does not scale the number of participants.

| Proof of Stake
To address the energy consumption waste in the PoW consensus mechanism, various alternative consensus mechanisms have been proposed, such as the PoS mechanism [68]. The approach aims to replace the useless work of solving puzzles by selecting a leader for deciding the next block according to their stake shares. The probability of generating a block depends on the stake of the nodes in the system, which can result in less electricity consumption and a decreased 51% attack probability [17]. In the case of the few rich stake owners performing malicious attacks, PoS can make use of game theory mechanisms to prevent collusions and centralization by penalizing dishonest behaviours.
Moreover, the maximum transaction rate is a few hundred transactions per second, which is low compared with other consensus mechanisms or visa system [29]. The PoS protocol results in a lack of consensus finality and leads to frequent blockchain forks. Even though it is making energy consumption less wasteful, it still requires a fair amount of available computation resources. However, PoS-based algorithms can be used in public blockchains and the validators can be unknown when performing the consensus process without knowing the identity ahead of time compared with PBFT [57].

| Proof of Authority
The PoA is designed based on PoS, which is adopted for some private blockchains [69]. The protocol predetermines the authority parities in the network, and each authority is assigned to be the leader within a fixed time slot. Network members trust the authorities and a block is accepted if it receives a majority of approvals from authorized nodes. In this mechanism, it needs to perform KYC to identify the authority ID and background instead of the stake from PoS, where misconduct or manipulation will be publicly revealed [70]. As PoA relies on trusted authorities, it is only suitable for permissioned networks.

| ADVANCES IN BLOCKCHAIN-ENABLED SMART GRIDS
Along with use cases and pilot projects in various sectors, the potential of blockchain technology in the energy industry is enormous, which is why it is deemed as a game changer. Blockchain technology enables a trustless network to eliminate the operational cost of participation of the intermediary network and creates a means that is quicker, safer and cheaper in the transactional energy market. According to commercial reports from Deloitte [71] and PWC [72], blockchain has the capability to disrupt energy-related products and commodities which can be traded interoperably as digital assets.

| System upgrades overview
In Figure 2, it demonstrates the cornerstones of a blockchainbased energy system. Energy trading transactions are recorded on a blockchain in a tamper-proof way, and the energy is delivered via the network (power grid). In general design, transactions (consumer-producer matching) can be affected by smart contracts automatically or by operators in the system manually. With the integration of digital and communication technology, a full energy system with residential use can be achieved along with smart metres, smart devices, sensors and end interfaces. As depicted in the figure, there are some key points with respect to blockchain technology: 1. Energy networks: The supply and demand are balanced via smart contracts with the aid of balancing the market, microgrids, virtual power plants, storage and so on [73]. 2. Energy transactions: Transactions data is stored on the blockchain using a decentralized mechanism, with parties identifying themselves through their digital identities, for example, in the context of energy storage, renewable energy, electric mobility and energy trading [32]. 3. Record storage: The storage for the ownership records, including emission allowances, renewable energy certificates and asset management, can be securely stored on the blockchain [62]. 4. Payment: The payment for transactional energy in the blockchain-enabled energy system does not limit to the fiat currency but also cryptocurrencies, which increases the efficiency and security of the trading process [14].

| Power sources
The energy system is undergoing a revolutionary reform which is advanced by the ICT and distributed energy resources. One of the main challenges is to decentralize and digitalize the current grid system, where the nature of decentralization in blockchain can be utilized in structures and operations of smart grids. In [74], the transactional energy system refers to a series of energy transactions for the delivery of a certain F I G U R E 2 Cornerstones of a decentralized energy transaction and supply system 62amount of energy commodities within a specified time frame and location which can support the business of all parties including generators and distributed system operators. The concept of transactional energy provides an insight into the treatment of electricity as a commodity in the market. In the market, control mechanism can be applied to achieve various objectives. Besides providing the wholesale market in the conventional grid system, transactional energy provides a vision to aid the coordination of retail customers by automating a large number of frequent batch transactions using a blockchain-enabled platform, therefore reducing the centralized features of the next-generation grid system [75]. The information exchange is the same for a large generator, distributed energy resource, renewable energy generators such as wind and solar energy resources, EV, microgrid, energy trader, broker, exchange, aggregator or system operator. Transactions can be executed between retail and wholesale markets, which equalizes the opportunity for all components. Furthermore, the transactions must also account for the transmission and distribution limits and other physical constraints on the grid. The power source is undergoing tremendous improvement to transition into a more decentralized one, where smart, local energy systems (SLES) are also well noted as forms of local energy projects to provide solutions to system integration and management [76]. The Prospering from the Energy Revolution (PFER) program seeks to develop, test and scale up SLES to deliver cleaner, cheaper and more resilient energy, and the four selection criteria for PFER demonstration projects could define SLES by outcomes rather than by constituent elements [77].

| Blockchain infrastructure
With increasing interactions between the power grid and electricity users, traditional blockchain infrastructure is no longer sufficient to support a large transaction throughput or a low response time. Consensus mechanism, one of the core parts in the blockchain system, is responsible for the coordination and connection of its stakeholders. In order to build an advanced smart grid application, it should be able to process the electricity and information distribution in order to be more efficient, decentralized, flexible, reliable and secure. In this regard, the consensus mechanism's advances in the blockchain infrastructure are presented in this subsection.

| Proof of Burn
In the Proof of Burn (PoBr) protocol, instead of providing proof of the work, the miner sends the coins to 'burn' in order to gain the right to mine a new block [78]. The miner which burns a larger amount of coin will get a greater chance of being selected by the random selection process. In this way, PoBr protocol does not require the huge hardware cost as PoW does; however, the validation process depends on the willingness to burn coins, which will cause unnecessary waste of resources [13].

| Proof of Elapsed Time
Proof of Elapsed Time (PoET) is designed to address the high power consumption (waste) and latency for transaction confirmation in PoW-based consensus mechanisms. It was first developed by Intel's Sawtooth project [79]. The protocol aims to replicate a random block generation process without spending valuable resources as PoBr or computation power as Bitcoin. By requesting a waiting time from a trusted function in a general-purpose processor, the miner node with the least waiting time is selected to mine the next block. It randomly distributes leadership election across the entire population of validators; however, this approach is dependent on the environment developed by Intel, where trust can only be guaranteed with a single authority [58].

| Enhanced Proof of Benefit
The Enhanced Proof of Benefit (ePoB) consensus mechanism is designed to choose the winning block leadership in the EV charging and discharging scenario [80]. The participants (EV) in the consensus process are a tuple of 〈U, G, P, A〉, where U is a set of public nodes to submit buy/sell electricity orders; G is a set of gateway nodes, and P is a set of decentralized network peers to execute the consensus process. All routines with charging and discharging requirements execute the verification algorithm of the ePoB consensus mechanism, which maintains and expands the blockchain. A benefit generating algorithm is proposed to calculate the maximum benefit number for the overall grid, where the benefit can be defined by the objective function. Table 3 presents the comparison between some mainstream consensus mechanisms including PoW, BFT-based, PoS and ePoB. They are compared based on various characteristics such as consensus finality, computation cost, vulnerabilities and so on. As inferred from the table, all consensus mechanisms have their pros and cons. For example, the PoW consensus mechanism performs excellently in the aspects of security and fairness with high scalability; however, the energy consumption with increasing industrialscale mining process is critical. It is also notable that the scalability of BFT-based consensus mechanisms is low because they require quite high communication overhead between permissioned nodes such as Hyperledger Fabric, which is based on PBFT [82]. On the other hand, the new consensus mechanism PoS is more environmentally friendly; however, it is less secure and fair compared with PoW. Furthermore, different consensus mechanisms adapt to different blockchain types, and the types of blockchain applications depend on use case scenarios. In order to adapt to the frequent trading demands and consider the global power network delivery quality in the energy sector, an adaptable consensus mechanism is required. The advances on consensus protocols support a more dynamic and robust energy grid infrastructure to further innovate the whole industry including electricity pricing, billing, planning and so on. LIU ET AL.

| Customer interface
Blockchain technology has the potential to be applied to various business processes and operations in the energy system, where it can bring novel business models or applications in the following areas: • Tariff: A smart contract based energy system can enhance the automation process in billing for both consumers and distributed generators, where utility companies may change their tariff and billing plan according to the consumer energy profile, real-time cost or individual preferences [83,84]. • Trading: A blockchain-enabled grid system can trade with distributed energy producers, which is completely different from traditional wholesale market management [85]. Commodity trading transactions, risk management and energy trading strategies are being explored to accommodate the new system [86,87]. • Automation: By enabling P2P energy trading, blockchain technology can integrate locally produced energy, which increases energy self-production and self-consumption [88]. The automation process also significantly improves electricity trading and delivery efficiency, thus generating more revenues [89].
• Smart grid management: The integrated energy system in smart devices utilizes advanced communication and machine learning technologies to provide monitoring, controlling and management services. Grid management can not only offer additional services to end users but also improve network performance [83,90,91].
• Security and authentication: The protection of transactions and security is guaranteed via cryptographic techniques, which safeguard user privacy and data confidentiality and improves the auditing and regulatory compliance [92].
According to the features of transactional energy, blockchain technology matches the requirements of frequent and large-scale transactions, thus being widely adopted. By utilizing a distributed ledger with smart contracts, locally generated energy can be managed in a compliant way with PFER demonstrations. In [93], a novel energy trading mechanism based on blockchain technology is proposed to adopt the decentralized and competitive environment of locally generated electricity, but the blockchain here is only used as a database to record transactions. In [94], the authors further evaluate the economic features of market mechanism for local energy trading. A comprehensive Internet of thing business model is designed in [95] to enable P2P trade for paid data using blockchain and smart contract. However, the trading model does not perfectly adapt to energy sector trading to address frequent transaction needs and consider the overall system performance. In [96], a dynamic price incentive market mechanism is proposed to balance the local renewable energy production and support flexible demand. In [97], a blockchainbased trading platform is proposed to support the decentralized energy market with distributed optimization and control. In [98], a more sophisticated dynamic power network infrastructure is proposed, which can advance the performance of small-scale generators and the overall capacity resilience of grids.
A blockchain-based energy trading model is proposed to allow prosumers to trade energy in the grid, enabling production companies to achieve autonomy in the blockchain power trading platform, which can inject and draw energy into the smart grid public blockchain trading platform [51]. Henceforth, blockchain has generated broad interests in the

| APPLICATIONS IN SMART GRIDS
Driven by the advances in blockchain technology, utility companies and blockchain teams have explored the feasibility of applying blockchain technology in the energy industry. The authors in [99] concluded eight types of use cases and wholesale, retail and P2P energy trading and cryptocurrencies, tokens and investment accounting take the largest shares among the eight types, accounting for 33% and 19% of the total share, respectively. Mature consensus mechanisms such as PoW and PoS have been applied in many blockchain projects; however, traditional consensus mechanisms might not meet the requirement of the system when combined with energy generation and trading [100]. So the choice of consensus mechanisms is highly correlated with use case which has different requirements for throughput, scalability, latency, security and so on. In this section, we focus on consensus mechanism uses in different energy grid projects and present them according to the types of blockchain-based applications for different purposes.

| PoW-based
PoW consensus mechanism has proven to be highly scalable for public blockchain, where it is the most commonly used consensus mechanism in applications [62]. The Bankymoon project works with banks to provide blockchain services for cryptocurrencies integrating into smart metres [101]. The project uses smart contracts to execute regulation or policy terms according to the application requirements, thereby effectively reducing transaction latency. A smart metre is used in water and electricity installation, where low-latency transaction is essential and the automated transaction process can achieve an approximate real-time settlement for payments. Bankymoon utilizes a smart contract feature on the Ethereum platform to ensure scalability and latency at the same time.
Another PoW-based project named PowerLedger aims at trading P2P renewable energy resources with customers [102]. Blockchain is used to trace the authenticity of green energy, where the trading transparency on the origins can be promised. The solution eliminates the customers' concern about the energy sources, and all transactions are securely recorded on the blockchain. The Australian startup Divvi also focuses on renewable energy trading and ownership, which is also based up Ethereum's smart contracts [103]. However, P2P trading emphasizes more than the origin proof. Another important aspect is matching the customer with renewable energy suppliers or the commodity being traded in this process [87]. The Alliander group from the Netherlands uses a smart metre on the blockchain platform to enable real-time electricity exchange between energy markets (retail and wholesale) and residents [104]. Also, it is developing an EV charging and discharging platform to support dynamic customer contracts. In this way, the EV user can choose the energy supplier and trade with potential renewable energy providers whose electricity sources and prices are transparent to customers [88]. Due to the different application scenarios, Alliander uses multi-chain solutions in different use cases, such as a private blockchain solution which is used for P2P energy sharing platform, and a public blockchain which is adopted for smart metre transaction recordings. The e-mobility application is extremely popular as the EV is a highly dynamic energy source that can charge and discharge electricity to the grid network. PowerLedger and another startup named Everty are also working on the construction of an electric vehicle charging infrastructure. The purpose is to establish an electric vehicle charging platform, giving electric vehicle users more autonomy [102,105]. As we can see from the PoW-based energy use cases, scalability and transaction settlement time are the two major considerations for accommodating more users. However, the incentive mechanisms in the project (used to promote users to contribute to and behave well in the project community) should also be considered equally as the aforementioned scalability and latency.

| PBFT-based
If a certain amount of signatures is collected from the network peers, a PBFT-based consensus mechanism can provide instant finality. However, the message overhead limits the scalability of the network; hence it is mostly applied in the consortium blockchain to deal with a limited number of participants. SunChain from France aims to build an energy management system to track, secure and certify energy exchanges on blockchain-based applications [106]. It uses consortium blockchain to eliminate the mining process and perform authentication between consumers and energy producers. The Dutch company TenneT and the German blockchain company Sonnen use residential battery to provide ancillary grid services [107]. It is implemented through Hyperledger, an open-source platform for enterprise-scale blockchain solutions [108], to provide information to the grid network operator regarding the current power availability and reservoir. TenneT is the first power grid operator to launch a blockchain project on the operator level, where the PBFT algorithm is suitable in an application with fewer stakeholders [109].
PONTON is dedicated to the whole energy market with blockchain technology [110]. PONTON works with energy trading companies and utilities to develop a P2P wholesale trading platform in the regional market's Tendermin platform. Moreover, it applies strategies to enable smart trading and provide additional energy services such as power load balancing [111]. The BFT-based blockchain project in BTL works with the largest utility company in Austria to trade energy on the blockchain platform, which approves a huge reduction in operation cost and improves the efficiency of the trading process [112]. The automation process executed by the blockchain contracts reduces the time in the wholesale LIU ET AL.
-65 transaction, such as confirmation, authorization, audit, etc. [113]. Now, the projects mentioned here, that are based on the PBFT consensus mechanism, are working with large stakeholders where the number of participants is limited. Also, the identity of the network peers is known and visible to all participants, thus the system's security is ensured, whereas scalability is still the biggest drawback for PBFT-based consensus mechanism.
Ripple is an open-source payment PBT-based agreement on the Internet to achieve decentralized currency exchange, payment and liquidation [14]. In the Ripple network, the transaction is made by the application and broadcast via tracking nodes or validating nodes. The consensus process of Ripple is run between validating nodes where each node has a pre-configured copy of the Unique Node List (UNL), and only the nodes from the UNL are capable of voting for the approved transactions. The validating nodes will store the approved transaction with 80% votes from UNL nodes to the local ledger, which is referred to as the last closed ledger [114]. In the Ripple consensus algorithm, the identities of the voting nodes from the UNL are known, so the transaction confirmation time is around several seconds, which is more efficient than permissionless consensus mechanisms such as PoW. Hence, the Ripple consensus mechanism is only suitable for permissioned blockchain applications [28]. And the BFT capability is n−1 5 , which guarantees a secure consensus process withstanding 20% nodes performing Byzantine faults [115] (n denotes the number of nodes in the network).

| PoA-based
A PoA-based consensus mechanism highly relies on KYC techniques, since identity is the authentication proof and participants only trust authorized nodes. The use case of PoA is usually characterized by a high security-oriented scenario where it cannot put integrity and security at risk [58]. Grid Singularity is a highly active member of a blockchain organization promoting green energy generation and certification [101]. It aims to provide smart grid management solutions to improve power load balancing, automated transaction and audition, and grid network reliability. Grid singularity is also a member of the Energy Web Foundation (EWF), an open-source platform, and works with large corporations to launch and accelerate blockchain use cases in the energy sector [116]. EWF is an Ethereum-based platform that uses a PoA consensus algorithm to generate blocks, where the finality can be generated by 51% of the validators' signatures. Another blockchain company named Wirepas works with the EWF and serves as an IoT provider to connect the IoT devices to the blockchain platform [117].
StromDAO is a German company that has established an investment platform for renewable projects, through which consumers can invest directly [118]. It focusses on energy grid stakeholders at all levels and provides blockchain solutions that conform to the traditional grid structure. The British startup Green Running is currently developing a decentralized platform to make P2P energy trading possible [119]. It proposes a market model to serve as a broker between the energy producers and local aggregators, and customers can conduct energy transactions on the platform. Artificial intelligence is used to predict power consumption and electricity price and then help the P2P market price for its participants. PoA-based blockchain applications have a clear tendency for large-scale corporation use cases. However, the authority judgement exposes the centralized governing body, which is opposed to the decentralized idea behind blockchain technology.

| Others
SolarCoin is an open community project, which was registered as a public benefit corporation in the USA in 2014 [120]. SolarCoin uses a reward mechanism for solar energy producers. Energy producer use blockchain-based digital tokens as rewards to produce one SunCoin per million watt-hours of solar energy. This project aims to enable verifiably produced solar energy with SolarCoin issued cryptocurrency and reduce carbon emission globally [121]. It uses a free economic incentive to increase the production and consumption of solar energy, and rewards the production of solar energy through additional electricity stimulus. SolarCoin's blockchain uses PoS consensus mechanism on the public blockchain platform to verify blocks which are claimed to be more environmentally friendly. As opposed to Bitcoin, SolarCoin is granted for the proof of energy production from the solar installation, rather than the mining reward for contributing to computation power. And the PoS in the SolarCoin project is designed to use less than 0.001% of the power of bitcoin on a similar scale [122]. Another PoS-based project is called Energo Labs, which works on decentralized autonomous energy exchange [123]. It utilizes the Quantum blockchain, a decentralized application platform, to integrate smart metres and EV charging stations, thus reducing energy waste compared to PoW [39].
Bouygues Immobilier & Stratumn developed a blockchain project, which is used for the direct exchange of electricity between renewable energy producers and customers, where renewable energy is authenticated and verified through a blockchain platform [124]. The proof of the process is the consensus mechanism for the verification process of zeroknowledge proof. Due to the hierarchical order of trust to be executed in this process, an obvious centralized organization is exposed [125]. Another startup named Pylon Network developed a decentralized electricity trading platform for distributed energy resources and customers, using Pylon coins to reward green energy generation. The consensus mechanism is the Proof of Capacity, which is based on LiteCoin that supports a lower energy cost than the PoW with a larger throughput [126].
We can see that majority of the applications are still based on traditional consensus mechanisms. The most common distributed ledger platforms include Ethereum, Quantum, Corda and Hyperledger Fabric, which feature in different functionalities that can be applied in more diverse scenarios.
However, more and more applications are adopting or designing novel consensus mechanisms to accommodate their application requirements. In summary, a general comparison of the consensus mechanisms used by applications in the recent times is shown in Table 4.

| SECURITY THREATS AND CHALLENGES
It is claimed that blockchain technology is capable of accelerating the smart grid transformation process for decentralized energy generation and trading [131]. The overall security of a smart grid in the context of a smart city covers multiple factors such as data, connectivity, physical hazards, etc., where a comprehensive security framework was proposed in [132]. As for the process of energy decentralization and digitalization, the main challenge is to explore the most suitable control paradigm and distributed technologies. In this subsection, it explores the challenges imposed by the aforementioned projects and use cases.
According to the interoperability standard of smart grids proposed by the National Institute of Standards and Technology (NIST) [133], a conceptual model of smart grids is shown in Figure 3. It is noticeable that the market domain and the operation domain have the highest interoperability, as these two domains can be connected to all the other six domains in Figure 3. Therefore, the security threats in the market domain may affect the normal operation of the smart grids and vice versa. When the stakeholders plan to build up the blockchain-enabled electricity trading market in the smart grids, they should consider the security threats in both the blockchainenabled markets and the entire smart grids.
Hence, our analysis of the blockchain-enabled smart grids' security threats is twofold in this section. The first part shows the common security threats in smart grids. Then, the security threats in consensus mechanisms, EVM and smart contracts are analysed in the second part. Finally, in the last part of this section, we present the lessons learnt from our analysis as well as some suggestions for future blockchain-enabled smart grid security enhancements.

| Smart grids
Current smart grids are usually controlled and operated using ICT. Therefore, security is still one of the most important considerations to protect the devices, communications and services in smart grids. Next, we conclude eight prevalent security threats from [134][135][136][137][138][139] in smart grids.

| Central controller compromise
The central controller (the operations domain in Figure 3) usually has the most sound security safeguard in a smart grid since it is the brain that controls all the facilities and devices of the whole smart grid to provide varied services to the users. However, social engineering attacks can invade the central controller and make it vulnerable. Social engineering attacks can help an attacker obtain access to the central controller from certain nodes with weak security settings or from the staff. For instance, the central computers of the power grid in the United States and Ukrain were invaded and malwares were implanted by external attackers using social engineering attacks [140,141]. These malwares can allow attackers to manipulate the servers, databases, billing systems and so on, resulting in severe corruption and privacy leakage.

| Intermediation compromise
In smart grids, all the communication between different devices needs to pass through multiple intermediate nodes (multihop communications), for example, a user uploads the bills to the central controller via several collector nodes. Meanwhile, some service facilities (e.g. charging piles) should use router nodes to communicate with their controllers. If the intermediate nodes are compromised in a smart grid, plenty of sensitive information can be leaked, including control commands, event and device identifiers, users' power consumption (usage) and so on, which will infringe user privacy and even support other potential attacks indirectly. For example, users' behaviours and life patterns can be analysed from their power usage [142]. Malicious code can be injected into metres through modified software update by attackers [143]. In addition, legal identifiers can be utilized to forge authorized devices or even credentials but smart grid networks cannot discover them. Another example is a weak backhaul network. Backhaul network is an IP-based intermediate component for data (e.g. bills and bidding price) aggregation and collection. In a backhaul network, misconfigurations may lead to weak authentication. Furthermore, IP packets can be easily eavesdropped and even tampered, since packet encryption is not mandatory in the configuration. Therefore, the attacker can use methods like sniffing, replaying, spoofing and tampering to gather sensitive information and interfere users' actions [136]. For example, the attacker can modify the packet destination to make the user send bills to him/her. On the other hand, the attacker can change the packet sequence to delay the user's bidding [144,145]. It is clear that a weak backhaul network may lead to fatal service failure, financial loss and cause harm to users' privacy.

| Intrusion by unknown nodes
This attack means that an attacker can implant several nodes (e.g. forwarding nodes) in the multi-hop network where the smart grid is constructed. If the multi-hop network lacks access authentication, these unknown nodes can be invisible and utilized to perform the following three kinds of man-in-the-middle (MITM) attacks: • Packet analysis: The attacker can use the implanted nodes to intercept the transported data and perform an attack similar to the compromise analysis of the multi-hop network.
• Service disorder: The attacker can block the connections between nodes or publish fake commands (to ending nodes) to disrupt the normal services in the smart grid. • Operational failure: The attacker intercepts electronic infrastructure commands and then deliberately sends (tampered) incorrect commands to these infrastructures to trigger their fault alarms and even shut them down [146]. Such threats may lead to severe damage to the smart grid's availability.
Compared with the threat of intermediation compromise, this threat is much more practical (lower cost) and concealed, and if there is no well-structured authentication strategy in the smart grid, the attacker does not need to attack the nodes. F I G U R E 3 A conceptual model of smart grids defined in the smart grid standard of NIST [133] 68 -LIU ET AL.

| Denial of Service
Denial of Service (DoS) threat means that the attacker can exploit vulnerabilities in different network layers to generate a tremendous number of fake connections in a short period of time, thereby reducing the operating performance of the entire smart grid. DoS can be further categorized as follows: • Processor or memory exhaust: The attacker can utilize buffer overflow or malicious resource-exhausted applications to crash the device's operating system, thus causing a DoS in the device [147]. • Ending device compromise: If certain legal ending devices are compromised, the attacker can exploit these devices to repeatedly send useless packets (e.g. fake control signals) to other nodes (like zombie network) in the smart grid, thus realizing flooding attacks. This kind of DoS can decrease communication performance and drain the devices' energy in the smart grid [146]. • Forwarding and routing compromise: This attack is kind of a further exploitation of the intermediation compromise. When an attacker controls some forwarding nodes, he/she can continuously forward the same packets to degrade the data transmitting capability of the smart grid or clogg packet confirmation through a large number of trash packets, causing the data transmission to lose synchronization. For example, if the attacker manipulates certain routing nodes, he/she can find a non-existent address by broadcasting an address lookup message, thus crashing the routing service and clogging the network [148]. On the other hand, if the trusted third party that the smart grid relies on is attacked, it may cause a DoS in the smart grid since certain essential security functions such as key distribution, identity validation, etc. can be clogged. It implies that reliance on a fully trusted third party in a smart grid environment reduces the robustness of the smart grid and increases the maintenance cost [149].

| Weak credential
Weak credential is a threat not only to the smart grid but also to most of the information systems. In smart grids, weak credentials involve not only fake or weak credentials and weak passwords but also vulnerable authentications (e.g. unsafe PPTP VPN links), lose authorization policies and so on that can be used to enter devices and facility systems. Weak credentials enable the attacker to learn the network structure, collect information, find the vulnerabilities of different nodes, and plan the attack targets in the smart grid when they are compromised. For example, in the attack on the Ukrainian power grids, the perpetrators broke the weak VPN credentials to access the industrial control system and then remotely shut down the partial power plants via human machine interface [141].

| Eavesdropping
Eavesdropping is the most common threat to an individuals' privacy and the system security in smart grids. As discussed in Intermediation compromise and Intrusion by unknown nodes, the attacker can intercept communication channels to gather power usage, household power load, peak time period, geolocation and other personal sensitive information, and analyse users' daily routine and behaviours [150]. On the other hand, eavesdropping is an effective approach for an attacker to obtain useful information from the target smart grid. Moreover, the attacker can exploit the information to learn about the smart grid, and find potential vulnerabilities to organize targeted and perilous attacks.

| Privacy analysis
When we consider privacy leakage and analysis, one type of privacy analysis is conducted by the external attacker, which is what we discussed in the intermediation compromise. However, there is another potential threat of privacy analysis from the internal nodes. Even though a user's power usage and bills are aggregated with certain privacy-preserving aggregation schemes before they are transmitted to the power supplier (central controller), the aggregation nodes can still reveal the user's private data to the power supplier and other stakeholders such as electric companies [151] because these aggregation nodes are essentially managed by the central controller [143]. For example, a user's private data can be utilized for repair, maintenance, price adjustment or even precise advertisement, but the user actually knows nothing.

| Blockchain
Since blockchain and different consensus mechanisms were proposed, the security discussions about blockchain and consensus mechanisms have never stopped. Meanwhile, more and more consensus mechanisms are being implemented based on Ethereum; thus the security of EVM is being considered to ensure that consensus mechanisms and smart contracts can be executed correctly. Furthermore, as the carrier of trade strategy and the applied consensus mechanism, a smart contract has security vulnerabilities that may lead to transaction chaos or even real-world economic loss (manipulated by attackers).

Collusion attack
The collision attack is the most common method which can be used by attackers to attack different consensus mechanisms. To be specific, if the attacker has more than 50% of the computing power in the PoW-based context, the attacker can manipulate all the results of the consensus requests, thereby causing fatal problems to the PoW network (e.g. selfish mining, cancelled LIU ET AL. transactions and double-spending) [152]. On the other hand, if the attacker can control over 50% of the validation nodes selected by the consensus leader, the collusion attack may occur in the PBFT-related context. Compared with the PoWbased context, the PBFT-based context can be more easily affected by the collusion attack because the quantity of the used validation nodes defined by different consensus mechanisms that process each consensus request is much less than 50% of all the nodes in the PBFT-based context. The simulation result is shown in Figure 4, which is consistent with this view as the consensus mechanisms PBFT and Ripple cannot reach 100% consensus accuracy in handling a different number of concurrent transactions. Note that we utilize OPNET to conduct our simulations based on the idea and source code from [153]. The number of the consensus nodes for validation increases from 2000 to 18,000 with a step of 4000. In the PoW (ePoB) network and the PBFT (Ripple) network, the proportion of the unfaithful nodes is 1 3 and 1 5 , respectively. Meanwhile, incorrect concurrent transactions are generated randomly during the simulation.

Sybil attack
Sybil attack means that one attacker claims a large number of fake identities (nodes) and then attempts to influence the voting result of the consensus mechanism in the consensus network. If the identity authentication is not robust enough, the Sybil attack will be widespread in peer-to-peer networks. For the PoW consensus mechanism operating in the anonymous network, the method used to ensure whether each node is valid involves checking whether the node owns a considerable amount of computing power. Meanwhile, PoW consensus mechanism provides miners with an incentive to work honestly but not to work in a way that will help avoid a Sybil attack. However, if enough fake nodes are selected in the validator group, the PBFT-related consensus mechanism may be affected by a Sybil attack, resulting in a higher probability.

Eclipse attack
In an eclipse attack, the attacker monopolizes all incoming and outgoing connections of the victim, thus isolating the victim from the rest of his or her peers in the network [154]. To be specific, a node depends on n number of nodes selected by the peer selection strategy to view its distributed ledger in a decentralized network. However, if an attacker can force this victim node to choose all the n number of nodes from the malicious nodes manipulated by him, the attacker can eclipse the original ledger of the victim node and replace the original ledger with a tampered ledger. Figure 5 shows an example of the eclipse attack, where the victim node cannot send/receive correct ledgers to the decentralized network since the victim can only choose the malicious nodes as peers. Compared with a Sybil attack that affects the entire blockchain network, an eclipse attack only attacks certain nodes more precisely, so the attack cost of an eclipse attack is much lower. It indicates that an eclipse attack is much easier to be performed in real-world blockchain-enabled systems [155]. In order to detect an eclipse attack, Xu et al. [156] proposed to utilize random forest classification algorithms to separate the attack data packets in terms of certain packet features (e.g. packet size, access frequency, access time and so on). Furthermore, two major countermeasures are proposed to mitigate an eclipse attack. The first countermeasure is partial randomness, giving priority to the old nodes with fresh outgoing connections in the peer selection. The other countermeasure is to establish some known and verified nodes' outgoing connections to test the neighbour nodes before they are selected as peers [154].

| EVM
EVM is a transaction-based state machine that runs on a 256bit stack to execute all the functions in a smart contract and then implements the consensus mechanism [48]. Compared with the VMs used for general computation like Java Virtual Machine (JVM), Dalvik and ART in Android, the complexity of EVM is relatively low as it only needs to execute smart contracts deterministically and supports certain cryptographic primitives [157]. Nevertheless, security is still a primary concern in EVM since it is the last barrier to prevent malicious smart contracts and flaw consensus mechanisms. On the other hand, Ethereum is the most mainstream platform (or framework) serving numerous cryptocurrency and noncryptocurrency applications. If EVM itself has severe vulnerabilities, attackers may endanger all Ethereum-based platforms to cause irreversible financial loss. Meanwhile, there are four versions of EVM that are used base on different programming languages: py-evm (Python), js-evm (JavaScript), geth (Golang) and aleth (C++). This diversity increases the potential attack range for attackers and the workload of security analysis for security researchers. In the current research, the major methods for discovering EVM vulnerabilities are symbolic execution and fuzzing [158], and the explored vulnerabilities in EVM are mainly related to memory management (e.g. stack overflow and illegal memory access) and opcode [48,159].
Apart from detecting vulnerabilities in EVM, some researchers try to reinforce EVM via bytecode verification and semantics analysis [44,50,160,161]. The target of these two methods is to eliminate unsafe bytecodes generated in different smart contracts. Since EVM is now continuously maintained and updated, new vulnerabilities in EVM may threaten all consensus mechanisms and smart contracts implemented on Ethereum. Therefore, the blockchain community should pay close attention to EVM security. In addition, many other studies are discussing the use of cryptographic methods (e.g. zero-knowledge proof, ring signature and multi-party computation) to design more secure consensus mechanisms running in EVM [51,162].

| Smart contracts
A smart contract is an entity to carry the implemented consensus mechanism and transaction strategy. Therefore, the security of consensus mechanism is tightly linked to the 70security of smart contracts. In order to explore the potential vulnerabilities in smart contracts, several projects have proposed the construction of fuzzing tools based on heuristic search, symbolic execution, control flow graph and data stream analysis [46,[163][164][165][166]. The common vulnerabilities found in thousands of real-world smart contracts are summarized as follows.

Leaking and suicidal
A smart contract is considered to have a leak vulnerability if it leaks ether to attackers. Similarly, a smart contract is considered suicidal if it can be killed by attackers [167]. Both of these vulnerabilities are caused by inappropriate permission settings (especially in some smart contract tests), which allow attackers to invoke send() or selfdestruct() functions without any restrictions.

Block status dependency
If the transaction of sending ether (or other critical operations) relies on certain block status variables (e.g. timestamp, difficulty, gas limit and so on), the smart contract can be vulnerable since an attacker can construct transactions to achieve malicious behaviours by analysing the block status. Timestamp dependency is an example. Every block has a timestamp in the blockchain to record the time of the transaction. When the trigger conditions of some critical operations in a smart contract depend on timestamps, the timestamp can be exploited as a vulnerability. If an attacker can manipulate the timestamps (e.g. change the local system time), the timestamp-dependent smart contracts may be vulnerable.

Exception disorder
The reason for exception disorder is the inconsistency during exception handling. When a smart contract A tries to invoke a function f in another smart contract B, the function call may fail and generate different exceptions. Normally, all the transactions will be reverted in terms of the chain of nested calls for f ∈ B. However, if there is at least one low-level function call (e.g. address.call() and address.send()) in the chain, the transaction rollback will be terminated at the last low-level function call. Therefore, the rest of the transactions cannot be reverted, and the exceptions cannot be propagated to the caller A.

Re-entrancy
In general, the status of the contract's account can be changed after the invocation of some re-entrant functions in a smart contract is completed. However, many functions in smart contracts are not designed to be re-entrant functions. Therefore, if a malicious smart contract invokes these functions in a re-entrant manner repeatedly, it may lead to ether theft. The famous 'DAO' attack takes advantage of the re-entrancy vulnerability through the fallback function withdraw() to steal about 60 million USD [168].

Gasless send
When the sender tries to send ether >0 to the recipient, the fallback function in the recipient smart contract will be invoked with a fixed gas stipend (2300) determined by the EVM. However, if the gas consumption of the fallback function is designed to be higher than the current gas balance of the sender in the recipient contract, the sender will receive the exception 'out of gas'. Therefore, if the exception 'out of gas' is not handled and broadcast appropriately, a malicious sender can send ether to the recipient without costing gas. Frozen ether (locking) Some smart contracts are designed to invoke the functions of other smart contracts to operate ether via delegatecall(). It means that these smart contracts entirely depend on the related functions of other smart contracts to manipulate ether, as there is no actual ether manipulating function in these smart contracts. When the smart contracts that provide ether manipulating functions execute self-destructive (suicide) operation, the smart contracts with only delegated calls cannot send the ether to others, so that all the ether is frozen. In November 2017, a frozen ether bug resulted in the Parity Wallet users to permanently lose an estimated $150 million in funds [169].

Dangerous delegatecall
The delegatecall opcode is designed for a caller smart contract to invoke other library contracts. Specifically, the caller contract can load the library contract's code and execute it in the context of the caller contract. Since the parameter of delegatecall is the address of a library contract, an attacker can execute an arbitrary code in the caller contract by manipulating the parameter (i.e. the library contract's address) of delegatecall. This vulnerability has been exploited to result in $30 million loss in a multi-signature wallet. 1

| Lessons learnt
• Improving the administration of staff and facilities is an important step to enhance the security of the smart grid. There should be widespread awareness of information security and it should be learnt by every staff working for smart grids because these staff are the actual operators of all the facilities in a smart grid. If the staff are compromised by social engineering or activate certain malicious applications unconsciously, any smart grid can be broken easily, even if they are flawless. On the other hand, the physical access control of the facilities and the firmware security of the electronic devices should also be considered carefully. This is because some attackers may barge into some smart grid facilities to implant malicious devices for eavesdropping, jamming, data collection and so on. Meanwhile, the vulnerabilities in the electronic devices' firmware can be exploited by some attackers to interfere the running of these devices or execute other attacks, thereby destroying the entire smart grid. • Pragmatic testbeds should be built for a study to evaluate different security approaches with unified standards. Table 5 presents diverse countermeasures to address the threats discussed in the smart grids (Section 5.1). It is noticeable that each kind of solution has its own security goals and features. However, they have a common drawback: lack of practical evaluation. Because smart grids are critical and valuable fundamental infrastructures, it is unrealistic to test new security countermeasures (including solutions, schemes, etc.) in real smart grids. Such tests (or evaluations) may incur fatal errors, causing the smart grid to be in an unstable state (even out of service). Therefore, a realistic testbed is a wise choice, which is jointly constructed and used by researchers and stakeholders. • Code security should be strongly concerned in all blockchain-related systems. Apart from studying the security of consensus mechanisms and smart contract, researchers and software engineers should also study code security because vulnerable codes can be utilized by attackers, resulting in financial loss (e.g. DAO attack). More validating and simulating tools should be developed to test the codes in different smart contracts and can be applied to different test techniques for software security (e.g. fault injection, fuzzing, symbolic execution, sandbox, static analysis, etc). As a result, more and more severe vulnerabilities in smart contracts can be avoided before such smart contracts are released to the public.
In a nutshell, when discussing the security of consensus mechanism, we should not only consider the threats to consensus mechanisms themselves but also the threats to both the carrier (smart contract) and the running environment (EVM). In the smart grid sector and many other noncryptocurrency sectors, there are no standards (or any best practice) to guide companies to deploy secure blockchain-based systems. Even in the cryptocurrency area, the related standards and standard operation procedures (SOPs) are still unclear (in developing). Otherwise, there would not be this many cases of cryptocurrencies being stolen on different cryptocurrency trading platforms [200]. In our view, in non-cryptocurrency areas, building up security standards (e.g., PKI) and normalizing code writing (smart contracts) for blockchain-based applications should be considered as the top priority.

| CONCLUSIONS AND FUTURE WORKS
Here, we comprehensively study the consensus mechanism of blockchain technology applied in the energy sector. We first introduce the basic terms related to blockchain technology and its general applications. We pay special attention to the application of a blockchain-enabled system in the energy sector, where the overall structure and principals are presented. Next, state-of-the-art consensus mechanisms are reviewed and the corresponding use cases are presented. We can see the obvious trend of the consensus protocol design in the blockchain system, where the use case with a large number of participants chooses a consensus mechanism with high scalability, such as PoW. Moreover, the use cases that use stricter user access prefer PBFT or PoA because the user's identity is easy to be checked. The choice of consensus mechanism relies on the trade-off between transaction cost and throughput, scalability and latency, privacy and decentralization, energy waste and security. A security analysis demonstrates that collusion attack and sybil attack can influence the consensus accuracy of different consensus mechanisms, especially the consensus accuracy of Ripple. On the other hand, the numerous vulnerabilities due to man-made faults in the blockchain environment can lead to vulnerable consensus mechanisms.
This work focusses on a deeper understanding of the consensus mechanism in the energy sector to boost the development of smart grid management systems. However, the current consensus mechanism might not be able to fully implement all the requirements from its use case. A customized consensus mechanism should be designed to better adapt to more complicated and efficient energy grid operations in the future. And the customized consensus mechanism can be deployed and tested on the platform with a governance structure by giving special permissions. For blockchain-based platforms in smart grids, the development of security standards and the normalization of the smart contract's code should be given priority. Besides, the security of the system relies on secure data transmission and management, which can improve data encryption in the network layer and the authentication mechanisms for user identity validation. Combining with user identification and access priorities will further improve system security and flexibility.