Blockchain-Based Energy Trading in Electric Vehicles using an Auctioning and Reputation Scheme

The massive adoption of electric vehicles (EVs) has caused an increasing demand for electric energy to charge the vehicles. Efficiently managing energy trading between energy providers and energy consumers can lead to meet the high demand for charging EVs while reducing its cost compared to traditional power provided by the utility company. However, a large portion of the existing systems leveraged for trading energy between EVs are centralized and fall short in providing transparency, reliability, audit, security, and trustworthy features. In this paper, we propose blockchain-based energy trading using an auctioning and reputation scheme. We develop Ethereum smart contracts which enable owners of EVs to automatically request electricity to charge their vehicles in a reliable, cost-effective, secure, and trustworthy manner. The proposed approach ensures the lowest rate available by implementing a reverse auctioning scheme for fair competition between providers to provide the requested service at the lowest cost. The proposed solution enforces high quality of service through a reputation-based approach that quantifies the performance of the service providers and gives an advantage to more reputable providers. We present the implementation details of the deployed system on a test Ethereum blockchain platform. We perform system testing and evaluation to validate and assess the functionality and performance of the proposed solution. Furthermore, we present security and cost analyses to show the affordability, robustness, and practicality of the proposed approach.


I. INTRODUCTION
The traditional electric power supply is based on consumers purchasing electricity from the utility or the producer and getting billed based on the amount of energy consumed. In such a model, residential units and commercial consumers are required to be equipped with power sources that generate electricity. However, in the case that they are in the possession of such type of renewable energy sources, the utility can buy back excessive electricity that is governed by purchase agreements [1]. In general, the buyback rates differ from that of the utility and are generally much lower. Solar power is one of the most popular renewable energy sources that such consumers tend to use to generate excess electricity and reduce their expenses. Since the cost of installing and operating these systems are less than the utility company, the rate difference is justifiable. This scheme, while long-established, suffers from several drawbacks. The centralization of electric power production and distribution results in major overhead in administrating the delivery of power to customers. It was reported that about 39.5% of the cost of your electricity bill is a result of the management of wires that deliver your power from the generators as well as their maintenance [2]. This model is visualized in Fig. 1, where consumers buy power from utilities and can sell back any excessive electricity. A major consumer of electric power, as noted by this figure, is electric vehicles (EVs). A huge increase has been noted in the number of EVs from under 250,000 vehicles in 2013 to over 7 million vehicles deployed in 2019 [3], [4]. This rapid increase was witnessed because of the world's efforts towards a sustainable future from an environmental point of view. Economically, the growing competition and technological advancements in this industry yielded competitive prices on VOLUME 4, 2016 newly deployed EVs, which aided in the ubiquity of such vehicles.
FIGURE 1: Trading model of residential and commercial consumers possessing renewable energy sources and EVs with a utility company.
A new model based on energy trading between consumers has recently been gained popularity as it eliminates the dependency on a centralized entity to supply power. This peer-to-peer (P2P) business model relies on trading energy between residents and small commercial entities that can provide energy to their peers without the intervention of a utility [5]. This is compliant with the requirements of smallscale energy consumers, such as EVs, in terms of the required energy, purchase rate, and availability. Since homeowners do not require high installation costs for their energy sources, such as rooftop solar panels, their rates tend to be much lower. These entities require a marketplace to trade electricity within themselves. Such an online platform typically connects buyers and sellers, where buyers can navigate and choose their preferred supplier based on their rate and location. This decentralized approach alleviates the restriction of the tasks of buyers and sellers, as each of them can switch between either role freely. Fig. 2 showcases this approach and how it can eradicate the need for an intermediary. Moreover, such a structure supports the utilization of renewable energy resources and enhances the accessibility of power energy for customer consumption in mini-grid arrangements. As is the case with most P2P networks, a central operator is required to overlook the entities that lead to resolve disputes, enforce some constraints, and generally manage the network. With the increased interest in energy trading and the great recognition that EVs have received as an environmentally friendly transportation system, a solution is required to surpass the need for a central authority in order to support P2P energy trading in a decentralized, transparent, trustful, and secure manner. The blockchain would eliminate the need for a trusted central entity and the restrictions that are associated with centralization. [6].

A. MOTIVATION
The ubiquity of small-scale distributed energy resources(DERs) has caused a notable shift in the power distribution system. The widespread adoption of energy resources such as solar panels and small wind turbines that are easily attainable by individual homeowners and small commercial units supported this change from consumers only to contributors. These entities produce energy that is now available for other customers to purchase. Producers and consumers of energy need a marketplace to trade power [7]. Platforms such as Ethereum blockchain smart contracts are suitable for a P2P power trading scheme as they provide customized functionality based on the market requirements in a decentralized and immutable fashion.
In this paper, we propose a blockchain-based system that hosts a marketplace for entities to sell and buy energy on a reliable and secure platform. As compared to the traditional centralized approach as well as the P2P approach, blockchain does not rely on a central authority but rather supports a completely decentralized system. Any entity that is part of the system can assume the role of an energy provider (EP) or a consumer. However, this paper will focus mainly on EVs as energy consumers. This is done in order to tailor the solution to this specific use case due to the increased interest in EVs over the past decade. These vehicles require frequent charging to operate. Therefore, the P2P energy trading scheme is well suited for EVs, especially with EPs employing Renewable Energy Sources (RES) that further reduces the energy generation cost [8], [9]. However, there is a privacy risk upon the interaction between EVs and EPs in contrast to the traditional energy trading mechanism. The blockchain offers anonymous and secure interactions between its participants, in comparison to other approaches where a central entity keeps track of every user and stores their details. Therefore, a blockchain-based methodology is proposed for energy trading between EPs and EVs while preserving their privacy and maintaining the traceability of transactions. The chosen blockchain for this solution is the Ethereum blockchain, which is a public blockchain that supports custom business logic via smart contracts. Both EVs and EPs are considered Ethereum clients that have full access to the blockchain. These include transactions between them and other Ethereum clients as well as function calls to Ethereum smart contracts. EVs submit a request for a certain amount of energy in a unit, such as Kilowatt-hour (kWh), to the smart contract. The smart contract then acts as a marketplace as it forwards these requests to the appropriate providers to fulfill the needs of the EVs.
An appropriate selection algorithm is needed to connect EVs to suitable EPs that are able to provide their power needs at a rate that both entities agree on. A bidding algorithm is fit for this purpose where EVs start auctions with their FIGURE 2: Peer-to-peer decentralized trading model between buyers and sellers of electricity. requested energy quantity, preferred price, and any other auction parameters. EPs can thereon place their competing bids for the EV to pick from. To maintain a high quality of service, several studies have investigated implementing a reputation-based algorithm to hold service providers accountable for their service levels that can be influenced by their clients' opinions on the interaction [10], [11]. As EVs continuously request energy from EPs and interact with them on a regular basis, a rating-based method can enhance the experience of EVs upon their interaction with the system and their providers.

B. CONTRIBUTIONS
This paper presents a decentralized blockchain-based marketplace for EVs to choose appropriate EPs, trade energy, and negotiate prices. This approach enables the interaction between EVs and EPs without the need for a central entity to regulate it or enforce rules. The proposed approach is developed and deployed on the Ethereum blockchain and utilizes its smart contracts. These smart contracts are public and can be accessed by all Ethereum clients in real-time. In brief, the main contributions of this paper are: • We propose a blockchain-based approach for trading energy between EPs and energy consumers, i.e., EVs. This proposed approach implements a reverse bidding mechanism for EVs to choose providers based on their rates. This auctioning technique ensures fair competition between EPs and automates selection and payments by clients. • We develop a reputation-based scheme and integrate it with the proposed solution to encourage and reward 1 https://github.com/MazenDB/EnergyTrading/ honest EPs which can lead to ensure high quality of service and penalize selfish behavior. • We design and develop Ethereum-based smart contracts to automate the functionality of the proposed approach. We present algorithms to explain the selection and auctioning mechanism, manage payments between buyers and sellers, record feedback, and update user information. • We perform the functionality testing of the smart contracts, evaluate the response, and validate the outputs of the system. In addition, we perform cost and security analyses to further establish confidence in the developed solution. We make our smart contracts code publicly available on Github 1 .
The rest of the paper is organized as follows. Section II presents the related work. Section III explains our proposed blockchain-based energy trading marketplace approach. Section IV presents the implementation details. Section V provides the details of testing, outputs obtained, and results of testing the Ethereum smart contracts. Section VI presents the security and cost analyses. Finally, section VII provides the concluding remarks.

II. RELATED WORK
This section summarizes some important and relevant works focused on energy trading between EPs and energy consumers (i.e., EVs). P2P energy trading schemes have been explored in the literature because of their notable advantages over the traditional power supply mechanism [12]- [15]. This work explores P2P energy trading, where peers sell their excess energy typically generated by small-scale DERs. The popularity of this approach was due to its financial VOLUME 4, 2016 advantage as costs are dramatically reduced for the power consumers. Moreover, local energy producers greatly benefit from this source of income using their DERs. Several different business models were investigated by those solutions to implement their P2P energy marketplace and to incentivize cooperation within a large number of energy producers and consumers. Their impact was noticed on boosting the local balance between energy consumption and energy generation. All of these solutions focus on removing the central authority that distributes the energy to the consumers. However, some sort of operator is needed to manage the system and establish a fair electricity trading market. Although such an entity is vital in administrating the system, it defies the approach of decentralization by introducing a central authority. Utilizing blockchain technology relieves the network from the needs of an administrator.
Several efforts have been made to integrate the blockchain with the P2P networks to create a completely decentralized marketplace. The authors in [16] preserved the privacy of energy traders and consumers in the Internet of Electric Vehicles (IoEV) environment using blockchain smart contracts. An account generation mechanism is introduced to mask trading trends, as exposing those trends could lead to data linkage attacks. An account mapping technique is devised to ensure the data privacy of the buyers and sellers. Payments are controlled by the smart contract by assigning tokens corresponding to the volume of energy being sold. These tokens dictate if a new account is needed to transfer the payment depending on a pre-set threshold value. A dynamic threshold is used to protect against data mining attacks.
Another solution was proposed in [17] that also uses the decentralized blockchain technology along with its smart contracts to manage the trading of power between charging systems and EVs. Using a permissioned blockchain, this solution focuses mainly on scheduling the energy exchange between them and the charging behaviors of EVs. The authors present a consensus algorithm for efficient trading of energy through smart contracts and maximizing operator utility. Another solution was proposed to model a trading platform in a parking lot setting [18]. These parking lots provide charging services for EVs. In addition to being a consumer only, this solution enables EVs to be energy traders.
The proposed solution provides an infrastructure for EVs that want to buy and sell energy to other EVs. Choosing the time of purchase and sale could generate a profit for those entities via this approach. The solution utilizes the blockchain to track and trace the energy transactions between peers. The energy requests are transmitted through a local controller in the same parking lot. EVs can therefore choose to buy or sell their energy depending on their needs. The controller itself can also assume the role of buyer and seller depending on the participants benefit. This balances the distribution of electricity among the members of the community.
The authors in [19] proposed a blockchain-based solution to ensure the transparent and fair market for energy trading. The proposed mechanism manages the integration between distributed Renewable Energy Sources (RES) and energy consumers such as EVs. The security and privacy of participating entities is maintained by the developed permissioned blockchain smart contracts. These smart contracts orchestrate the distribution of renewable energy to EVs. A study is conducted in [20] regarding the charging schemes for EVs and the potential impact of a decentralized marketplace for energy trading using the blockchain. Moreover, a blockchainpowered solution is proposed based on this study that enables trading between the grid participants managed by a decentralized controller to maintain the autonomy of the system. A similar approach was presented in [21] to better manage electricity trading between energy consumers. The blockchain technology was used to match energy traders to satisfy their power needs according to supply and demand. The entire network is managed by a central entity, called the aggregator, that establishes a fair trading scheme and deploys an optimization model to maximize the efficiency of energy supply. The introduction of P2P energy trading has paved the way for the aforementioned blockchain-based power trading solutions. However, the solution presented in this paper employs an auction-based technique on top of the decentralized blockchain for EP selection. This auction involves EV owners putting in a request in the smart contract for charging their EV. EPs are then allowed to place decreasing bids until the EV chooses an appropriate price and provider. Using this proposed mechanism, EVs can choose the EP to buy their energy from securely. The competition between EPs is made transparent and fair by implementing it on a public blockchain network. The selection of providers by the buyers is based on the history of successful interactions with other buyers. Honest and reputable EPs are identified by a high reputation score that would make them favorable for future charging requests by EVs. This reputation value is affected directly by the customer review about the quality of service provided following an interaction with a provider. Therefore, EVs can ensure a safe and satisfying interaction using this approach.

III. PROPOSED APPROACH
A high-level architecture model is shown in Fig. 3 to represent the functionality of the proposed system. This model explains how different entities of the network communicate in the devised marketplace to satisfy the needs of EVs and benefit EPs. Decentralized P2P trading has been gaining a lot of interest due to its ability to more efficiently meet the need for energy and utilize local renewable energy sources. Adding a layer of blockchain to manage the network is favorable over a classic operator as it alleviates the risk of having a central single-point-of-failure in the system. Blockchain improves the traceability and transparency of the system as it records all transactions in an immutable and permanent ledger available for the members of the blockchain. Several blockchain networks support customizable smart con- tracts, which are essential to implement the business logic of the proposed system. This limits the number of potential blockchain frameworks to use for our approach. Some of the possible options include Ethereum, Hyperledger, and Multichain. We opt for using the public Ethereum blockchain to be available for public usage. This does not compromise the privacy of the participants as each Ethereum client is identified by an Ethereum Address (EA), preserving their identity.
EVs initiate the interaction with EPs by submitting a request via the relevant Ethereum smart contract. Through this request, the EVs present their requirements, such as the requested amount of energy. The smart contract generates an order number to link the request details. All future communications related to this request are identified by this number. In contrast to the solutions presented previously in section II, we present an auction-based mechanism for EVs to select their preferred provider. EVs include in their energy request the highest rate they are willing to pay for the requested service. Moreover, each EP is recognized by a reputation score linked to its performance. This reputation value is modified based on the quality of service provided by the EP. Hence, an EV can guarantee a high quality of service by requiring a minimum reputation score by EPs that communicate with it. All the data related to the request, including the order number, requested rate, requested energy, and minimum reputation, is advertised to the available EPs. Moreover, a deposit by the EV is requested to confirm their intention to pay the service providers. This deposit ensures a level of confidence in the system by the registered EPs and serves as collateral in case of any misbehavior by the EV. This deposit is dynamic and is not fixed for every client and not even for every request. The EV is requested to transfer to the smart contract the maximum amount it is willing to pay for the requested service. In a worst-case scenario where an EP offers the maximum service charge, the payment is still secured through this approach.
Announcing the request submitted by the EV starts an auction for EPs to participate in. The smart contract accepts bids for open auctions from registered EPs. Submitted offers by EPs should satisfy a set of requirements before they are accepted by the smart contract. Our solution requires a reverse auction to be utilized to select the cheapest possible fee for the service requested. As opposed to a regular forward auction, service VOLUME 4, 2016 providers make reducing bids to compete in winning the auction. Therefore, a bid placed by the EP should obviously offer a lower rate than the previous bid. An offer that is equal to or higher than the latest bid will be directly discarded. Similar to the EV, the EP is also required to pay a fee as collateral when submitting an offer. This fee should be equal to the rate proposed to guarantee that the EP will commit to providing the required energy at the proposed rate. Moreover, the EV submits a minimum reputation score along with the energy request as it does not accept services by any EP with a lower reputation than that. Hence, the smart contract does not accept bids from such EPs even if their offer is lower than the previous one. If all of the requirements are met, the bid is accepted and the Ethereum address of the bidder is recorded. Subsequently, the other bidders must now meet a lower bidding rate for their offers to be accepted.
EPs can submit their offers as long as the auction is open. Whenever the EV is satisfied by the current offer, it can close the auction. The smart contract receives the closing request, confirms the ownership of this EV to the auction, and flags the auction as closed. At this point, the EP gets paid the fee that was agreed upon by both entities. This is deducted from the amount previously deposited by the EV in earlier stages. The final details of the auction are announced, including the order number, Ethereum address of the EP, and the final rate offered. Generally, EPs cannot offer new bids to an auction that has already been closed. The final step is completed after the physical charging process is completed. Once the amount of energy is provided to the EV, the EP ends the procedure through the smart contract. The smart contract verifies the identity of the EP and finalizes the process. Considering the charging process was successful, the remaining deposit is returned to both parties, and the charging process is settled. Prior to an interaction between the EV and the EP, the client chooses the service provider based on its reputation score. This reputation score is affected by the feedback by EVs on the service level provided by the EP. Therefore, EVs can provide this feedback following the charging process. Positive feedback by clients improves the reputation of the EP, and likewise, negative feedback reduces the reputation score of the EP.
The new proposed decentralized P2P charging scheme consists of several entities that are elaborated below.
• EPs: These entities are the ones who own the Renewable Energy Sources (RES) and provide the surplus in energy that is available for sale. In addition to providing energy to EVs, their responsibilities include participating in the auctions of EVs. To sell energy to their clients, they need to actively propose reasonable and affordable rates to be able to compete with other providers. More importantly, EPs are required to meet the standard of quality and provide good service to maintain their reputation among EVs. During the charging process, EPs are also responsible for confirming the termination of the procedure in the final stages. • EVs: These are the designated clients whose needs are served by this designed solution. By utilizing the proposed solution, EVs can conveniently start an auction with all of their preferred parameters, including the preferred quality of service and the requested energy.
EVs are able to terminate the auction only when satisfied with the proposed rate. EVs can provide their feedback on the provided service as well. This affects the reputation of the EP greatly and hence enforces a high quality of service. • Smart contracts: All energy trading agreements between the EVs and EPs that involve registering both entities, submitting energy requests, negotiating price, and finalizing the contract are all governed by smart contracts that are based on the Eteherum blockchain. This set of smart contracts are deployed to accommodate the trading of electricity in a community. Several smart contracts are utilized to establish the energy marketplace, each with a separate concern. All participating entities are required to register their Ethereum addresses in a designated smart contract. This smart contract also handles depositing money and deducting from those deposits upon a confirmed purchase. The rest of the trading is handled in another smart contract that manages the energy requests and matches them to appropriate service providers. This smart contract ensures that all the EV requirements are satisfied by validating the offers from each EP. Furthermore, all remaining transactions until concluding the charging process are processed by this smart contract. Finally, a dedicated smart contract is deployed to record the reputation scores for each EP, receive client feedback, and update the reputation score accordingly.

IV. IMPLEMENTATION
This section presents the implementation details of the proposed solution. We deploy the Ethereum smart contracts on a virtual Ethereum testnet to verify the system functionality.
The implementation was performed using Remix IDE, an online development environment that uses Solidity language for Ethereum smart contract development. A brief summary of the smart contracts developed for this solution is shown below.
• Registration smart contract: All entities that contribute to the energy marketplace, whether by purchasing or selling energy, are required to be registered. They are recognized by their unique Ethereum Address that is mapped to the rest of their details. This is done through the Registration smart contract, as it records and manages all of the user data. Moreover, participants are often required to deposit a certain amount as a deposit or for payment. This is also captured and stored via this smart contract. • Energy Trading smart contract: This smart contract orchestrates the communication between all EVs and EPs in the same network. A unique order number is generated for each energy request by an EV. All the request parameters can be identified using this unique number. The smart contract announces the initiation of a new auction for the request, which can then accept bidding offers from EPs. The smart contract verifies that each request is tailored to fit the client's requirements. It also compares the current offer with previous offers by other EPs. At the end of the auction, the smart contract confirms the best available offer and closes the auction. Automatic payment is also enabled through this smart contract to pay EP fees. Whenever the charging process is terminated and both parties are satisfied, the agreed fee is immediately deducted from the EV account and transferred to the registered Ethereum Address of the EP. The Energy Trading smart contract then invokes the Registration smart contract to return the remaining deposit to the corresponding member. • Reputation smart contract: This smart contract is concerned with handling the reputation score of registered EPs. The goal of this smart contract is to guarantee the honesty of EPs and improve their quality of service. Feedback by EVs is submitted to this smart contract, which then adjusts the reputation scored accordingly.
Positive feedback results in increasing the reputation score and vice versa for the negative feedback. The number of raters also affects the reputation of the EP. The more the number of positive interactions that the EP has, the more the effect of the negative comments is mitigated. This is done to eliminate the outliers and maintain a fair and accurate estimation of the EP performance. Fig. 4 shows the sequence of interactions between both ends of the charging process as well as the Ethereum smart contracts. The presented interactions are required for an EV to submit a charging request and get matched with an appropriate EP. The chosen EP should satisfy the quality requirements of the EV and offer the lowest available rate on the marketplace for the requested amount of energy. Both entities should be registered on the Registration smart contract prior to price negotiation. An EV submits the energy request to the Energy Trading smart contract, which checks the credentials of the sender and then records the request details. The deposit sent from the EV is recorded in the Registration smart contract and confirmed via an event. Events are a part of the Ethereum smart contracts that allow for broadcasting messages to the entire network. The events consist of the name of the event and any arbitrary number of parameters. Ethereum clients can filter the events from a specific smart contract using the name and the arguments. Therefore, the events need a sufficient number of unique parameters for clients to be able to filter them. An event is also triggered VOLUME 4, 2016 to indicate the start of the auction after the EV deposit was confirmed. Once the auction is open, the EPs can place their bids by sending them to the Energy Trading smart contract. This smart contract validates the offers as explained earlier to match the EV request. The Reputation smart contract is consulted to validate the reputation of the EP. The reputation score is fetched to confirm the viability of the EP. If the bidding offer or the EP itself did not match the request, the transaction is reverted, which insinuates the rejection of the bid. On the other hand, a verified bid that is accepted, allows the smart contract to announce it by triggering the corresponding event.
The auction remains open until the termination is requested by the EV to the Energy Trading smart contract. Since it is a reverse auction, the EV is looking for the lowest offer that matches the presented criteria. Therefore, once the EV is satisfied with the cheapest bid, the auction is closed, and the last bidder is endorsed to provide the required energy. Fig. 5 presents the sequence of interactions that occur after closing the auction. The first step after announcing the termination of the auction and internally changing its status is to settle the payment. After deducting the cost of energy from the deposit of the EV and transferring it to the service provider, the remaining amount is sent back to the EV. Consequently, the EV can provide its feedback about the service provided by the EP to the Reputation smart contract. This requires the unique order number generated previously as well as the Ethereum Address of the EP to be rated. The feedback is recorded in the smart contract, and the new reputation score of the corresponding EP is computed.
The proposed approach can be broken down into three major processes explained in the algorithms for further clarification of the exact methodology followed. The presented algorithms provide a high-level description of the smart contracts in contrast to the Solidity code. Algorithm 1 discusses the steps and conditions of initiating a new request for energy by an EV via the smart contracts.  Record the message sender Ethereum Address. 5 Record the current timestamp. 6 Set the status of the auction to open 7 Record the deposited amount via the Registration smart contract. 8 Registration SC accepts the deposit. 9 Announce the availability of a new auction with its unique identifier and the rest of its parameters. 10 else 11 Revert transaction. 12 end Algorithm 1 is only available for pre-registered EVs in the Registration smart contract. The request submitted by the EV includes the requested amount of energy in kilowatthour (kW.h), the maximum price that the EV is willing to pay for the service, and the minimum reputation score of the service provider that the EV wants to receive offers from. This algorithm requires that the EV transfers the same amount as the maximum price announced in the parameter of the function. If the amount sent is confirmed by the smart contract, a new number is generated for the order and is linked to the rest of its data, such as the sender, time, status, and other details. The orders are tracked via their unique number in the Energy Trading smart contract. The Registration contract accepts the deposit and associates it with the Ethereum Address of the EV. Subsequently, the auction is open for bidding, which is announced by triggering an event with all the relevant information for bidders to place their offers to the EV. This algorithm is implemented as the Ethereum function newRequest, which has the computational complexity of O(1). Therefore, Algorithm 1 has a computational complexity of O(1) due to the lack of any loops or complex structures.
EPs can submit their bids to the Energy Trading smart contract as explained in algorithm 2. The auction is referred to using the unique request number. Therefore, multiple auctions can be opened simultaneously on the same smart contract but not by the same EV. EPs can also submit offers to multiple auctions as long as they are able to commit to all of them. The EP offers the rate at which it is willing to provide the requested energy. For security, the EP is asked to deposit an amount of money as collateral to guarantee service delivery. The first thing that the smart contract validates is the offered rate, as it has to be lower than the previously offered rates. The smart contract also checks the reputation score of the EP that placed the bid to maintain the quality of service. If the reputation score passes the threshold, the offer is accepted and replaces the last bid as the lowest available price. The deposit by the last bidder is returned to it, and the new bid is announced via an event. The explained functionality is implemented in the function makeBid. This function has a Big O notation of O(1), and therefore Algorithm 2 has a complexity of O(1).
The auction can be terminated by the EVs as the bidding price reaches its lowest, as explained in algorithm 3. EVs can invoke a function to close the auction and accept the lowest bid. The smart contract validates the Ethereum address of the EV and that the referred request number corresponds to it. The first step for closing a charging request is to set the status of the auction to be closed in order not to receive further bids from EPs. The fee that is agreed upon is deducted from the balance of the EV and transferred to the address of the EP. Once the payment is confirmed, the auction termination is announced to other EPs. The physical charging process now commences, which takes place off-chain. However, the smart contract is updated at the end of the charging process. This simple algorithm is implemented in the function acceptLow-estBid and has a computational complexity of O(1), similar to the previous algorithms.
Algorithm 4 shows the steps for ending the charging process in addition to recording the feedback by the Reputation smart Ether is equal to the bidding amount ∧ (the bidding amount is lower than the previous bid ∧ higher than zero) then 3 Fetch the reputation score of the EP from the Reputation smart contract. 4 if the reputation score is higher than the minimum required then 5 Accept the offer. 6 if it is not the first bid in the auction then 7 Return the deposit of the last bidder. 8 Deduct the last bidder's deposit from the Registration smart contract. Record the deposit of the new bidder.

11
Update the record of the lowest bid and lowest bidder.

12
Broadcast the new bid to other EPs. if submitted bids > zero then 5 Transfer payment to the chosen bidder. 6 Deduct the payment from the EV deposit. contract. Once the trading has been executed successfully, the remainder of the deposit available in the EV balance is returned in addition to returning the deposit of the EP. Optionally, EVs can provide their feedback to the smart contract about the performance of the EP. The feedback is stored and processed in a designated Reputation smart contract. The interaction is recorded as a combination of the Ethereum addresses of both the EV and the EP. This is done to maintain VOLUME 4, 2016 fairness and preserve the integrity of the reputation score. Each time a new interaction occurs, EVs can rate the EP, which directly affects the reputation score as computed by the Reputation smart contract. This smart contract has an arbitrary value that the owner of the smart contract alters to control how lenient or strict the smart contract is towards the EPs. This algorithm discusses operations implemented in the Energy Trading smart contract and the Reputation smart contract. The function endCharging in the Energy Trading smart contract has a computational complexity of O(1). The reputation is computed in the Reputation smart contract. The first step is to take the input from EV via the function provideFeedback, which has the complexity of O(1). In this function, the reputation is computed by calling another function calculateRep. This function also has a complexity of O(1). Another way of implementing the last function is by recording all the feedback about this EP and computing the reputation. Although this provides a slightly more accurate approximation of the reputation score, the storage and computational requirements are not justifiable. Hence, only the total reputation score and the number of EVs that provided their feedback and stored for each EP. These two values provide an appropriate representation of the EP reputation score.

Algorithm 4: Ending the charging process and Updating Reputation
Input : request number, Ethereum Address of EP, status of interaction with EP Output: Updated EP reputation score 1 if the auction is closed ∧ the referred request belongs to the request sender then 2 Transfer the remaining deposit to EV and deduct it from the EV balance in the Registration smart contract. 3 Return deposit to the EP.

4
Broadcast an event announcing the end of the charging process. 5 else 6 Revert transaction. 7 end / * Feedback by the EV * / 8 Record feedback by the Ethereum Addresses of the EV and the EP. 9 Compute the new reputation score of the EP. 10 Return the updated score.
Developing smart contracts to be deployed on the blockchain network enforces some limitations on the developer, in contrast to developing a traditional centralized server. Great emphasis is placed on minimizing the cost of operation and simplifying the functions. As it can be seen in the smart code shown in the Github repository, the use of loops is avoided due to its high computational costs. The use of data types such as arrays is also not favorable as they typically require loops to fetch data with an unknown index in addition to removing elements from the array. Alternatively, Solidity offers more efficient reference data types called mappings that can map two different data types in a key-value manner. For instance, mappings are used to record the EVs and EPs that are registered. The key used in this case is the Ethereum address of the member. The value in this mapping, as well as other mappings throughout the smart contract, are complex objects or structures. Another example of mappings is the objects that are created for the charging requests. In this case, the request number is mapped to all the details of the request, including the requested amount of energy, requester EA, timestamp, current bidding value, and other relevant details that will be elaborated on later in the testing section. The use of mapping for charging requests is especially useful as it significantly reduces the complexity compared to arrays.
The storage of data in smart contracts is minimized to reduce the cost. Information that is not crucial can be retrieved via the events triggered as they are stored permanently on the blockchain ledger. For example, the time of each bid can be very costly to record and can be rather retrieved from the event triggered upon the bid submission. The use of events undoubtedly reduces the storage of data in the smart contract. In addition to cost consideration, the privacy and integrity of data are preserved by checking for the Ethereum client's address before allowing them to call a function. This is done via structures called modifiers that are appended to function headers. Unauthorized members will cause these modifiers to generate an error and revert the transaction.

V. TESTING AND VALIDATION
This section presents the outcome and results after deploying the proposed solution along with the testing details. Comparing these results with the expected outcome is essential to validate the proposed approach. Remix IDE was utilized to deploy the developed smart contracts in addition to testing them on the virtual test environment offered by the IDE. Debugging the smart contract code and testing each function separately as well as testing the entire smart contract are made easy using this IDE. All transactions are logged and can be retrieved along with relevant information such as function parameters, transaction cost, and events, similar to an Ethereum transaction. In addition to successful transactions, erroneous function calls are also recorded, with sufficient details of the errors for developers to investigate the source of the error. The error messages are either built-in or added in the smart contract. To evaluate the functionality of our smart contracts, we deployed the Registration smart contract at 0xd9145CCE52D386f254917e481eB44e9943F39138, the Energy Trading smart contract at the address 0xf8e81D47203A594245E36C48e151709F0C19fBe8, and the Reputation smart contract at the address 0xd8b934580fc E35a11B58C6D73aDeE468a2833fa8. All EVs and local EPs that trade energy among each other utilize the same instances of the smart contracts. In addition, we simulated a complete energy trading scenario between an EV and multiple EPs to validate and test our proposed approach. The Registration smart contract was deployed first, followed by the Reputation smart contract. Lastly, the Energy Trading smart contract was deployed as it requires the Ethereum Addresses of the other two smart contracts to refer to them. Several EVs and EPs were registered using the virtual accounts provided by the Remix IDE.
The EV puts in a request to buy electricity from an available provider through the Energy Trading smart contract of the area it is located in. The EV specifies the relevant parameters which are recorded by the smart contract. The smart contract generates a unique request number and broadcasts it through an event, as shown in Fig. 6. The figure also shows the deposit confirmation by the EV to guarantee the automatic payment to the selected EP.  The auction that is open for bidding accepts offers from EPs as long as they meet the criteria of the requester. When an EP submits a bid, the smart contract verifies it against these criteria and records it after the validation. Subsequently, the bid is announced via the corresponding event for other EPs to match it in their following offers. Fig. 7 shows the event trigerred by the smart contract when an EV accepts a bid by an EP. This event includes the details of the accepted bid with the new offered rate by the EP. Other EPs need to offer a lower rate than the previous one for it to be accepted by the EV. The request details are continuously updated and linked to the unique request number generated by the smart contract. Fig. 8 shows the getter function to fetch details of the request by its unique number. These include the requester Ethereum Address, the requested amount of energy, the request timestamp automatically generated by the smart contract, the latest bid, the address of the bidder, and the minimum required reputation score of a future bidder. These details are helpful for EPs to decide if they are eligible to submit a new bid for the auction. The Reputation smart contract is dedicated to receiving feedback from EVs about their experience with their providers. With every new feedback by an EV, the reputation score of the EP is updated. The feedback is recorded as a pair of two Ethereum addresses, the EP and the EV. This is done so that each interaction affects the reputation score of the EP with the same amount. As the reputation score is updated, it is logged in an event containing the Ethereum address of the EP in addition to the newly updated reputation score, as shown in Fig. 9. The Remix IDE helps with debugging as it offers logs for error handling as well. Developers have the option to customize an error message relating to a specific exception. For instance, Fig. 10 shows a customized error in the Reputation smart contract. When an Ethereum account tries to register as an EP in this smart contract, it checks if the Ethereum address exists in the Registration smart contract as an EP. In addition, the Ethereum address should not be already registered in the Reputation smart contract. This is crucial as new EPs get assigned an initial reputation score. Therefore, overwriting EPs can mislead EVs.

VI. EVALUATION AND ANALYSIS
This section discusses the cost estimation for the proposed blockchain-based solution in addition to the security analysis VOLUME 4, 2016 of the smart contracts. Also, we compare our solution with the existing solutions, present smart contract code vulnerability analysis, and outline limitations along with future work in this section.

A. COST ANALYSIS
The cost of calling a function on an Ethereum smart contract is affected by its complexity, function parameters, and outputs, which make up the execution gas cost of the function call [22]. Gas is a unit of measurement used in the Ethereum network that measures the computational power needed to execute a function. The total transaction gas cost consists of the aforementioned execution cost in addition to the cost of sending the transaction to the blockchain. The gas fee paid by Ethereum clients is in Ether and depends on the gas price set by the client. This means that the same transaction can cost different amounts for two different Ethereum clients depending on the gas price. However, transactions with higher gas prices are more attractive to miners. This is because miners collect and execute transactions, form blocks from those transactions, and participate in a computationally heavy task as denoted by the proof-of-work (PoW) algorithm. In addition to Ethers awarded by the Ethereum blockchain, miners get rewards from Ethereum clients depending on the gas prices. Hence, transactions with higher gas prices are more likely to be executed faster as they offer a higher reward for miners. Therefore, Ethreum clients face a tradeoff between cost and speed of transaction execution. The first step towards estimating the gas fee required is to determine the execution gas cost, which is done through the transaction logs on Remix IDE. The execution and transaction costs are recorded in the gas unit as well as in the US dollar in Table 1. Since there is no direct conversion rate between gas and an interpretable fiat currency, we present three commonly used conversion rates that are selected by Ethereum clients. These conversion rates correspond to a cheap but slow execution, average, and expensive but fast transaction execution, as suggested by ETH Gas Station as of April 12th, 2020 [23]. The different types of execution require 0.9, 1.1, and 1.6 Gwei per gas, respectively. The cost of 1 Ether equals 3,467.32 USD at the time of writing this paper. However, a more realistic conversion rate to USD to be used as of May 2020, due to the current temporary spike in Ether prices. The cost of all methods is $0.03 or lower for each method for slow execution, $0.05 or lower for average execution, and $0.07 or lower for fast execution. The low cost of executing these transactions is due to programming the smart contracts in an efficient manner, which can be noted in the computational complexity column. All functions have a big O notation of O(1), insinuating that loops and arrays were avoided in the smart contract to reduce the cost of operation. This proves the feasibility of utilizing smart contracts for energy trading between EVs and EPs. Moreover, another solution to reduce the cost is to use a private Ethereum blockchain which waives the transaction fee for public networks. Ethereum clients can also opt for emerging cheaper alternatives such as zkSync, which is a protocol for low fees on the Ethereum.

B. SECURITY ANALYSIS
Herein, we present the security analysis to show that our proposed solution is secure enough against well-known attacks, threats, and vulnerabilities.
• Availability: The decentralized nature of the blockchain technology guarantees that all transactions are processed despite the downtime of some of the nodes in the network. Hence, smart contracts that are deployed on the blockchain are expected to be responsive always to function calls from the Ethereum clients. This is because the same smart contract is duplicated on thousands of mining nodes. Hence, the block time is ensured regardless of the unavailability of some of those nodes. This also applies to the access of data stored in smart contracts. Fetching this data is also always guaranteed since they are stored in a decentralized manner. • Accountability: The energy trading marketplace includes several buyers and sellers of electricity. Placing bids by buyers and accepting them by sellers requires trust in those entities to abide by those contracts. Both sides of the energy trading contract are expected to deliver their end of the deal. Since this trading is managed on the blockchain network, the transactions and function calls are permanent and cannot be altered. Therefore, all actions by both entities are recorded, and the corresponding member is liable for breaching this agreement. • Authorization: Several restrictions are implemented to ensure that only eligible members can access specific function calls and alter the data in the smart contracts. Therefore, we employ function modifiers that allow access for specific functions according to the Ethereum address of the sender. Hence, members are given limited accessibility based on their role as an EV or an EP. • Data Integrity: All transactions on the Ethereum blockchain are tamper-proof. Therefore, these transactions cannot be modified or removed from the immutable decentralized ledger. This qualifies the blockchain to be a secure marketplace for EPs and EVs

C. SMART CONTRACT CODE VULNERABILITY ANALYSIS
Despite the ability to develop, debug, and test our smart contracts in the Remix IDE, it cannot detect more than syntax errors in addition to the functionality testing, unlike the other security analysis tools. The Oyente security analysis tool was used for this purpose as it offers more insight into the robustness of our solution and how it can be exploited. Figures 11,12, and 13 present the security report generated by Oyente for the Registration smart contract, Energy Trading smart contract, and the Reputation smart contract, respectively. As can be seen in the figures, this tool analyzes the code coverage of the smart contract in addition to checking for several possible vulnerabilities. In the early development stages, many issues were found in the code, such as Integer overflow and underflow possibilities. The code was modified to avoid these issues to generate smart contracts that are free of the shown bugs, as reported by those figures. Hence, the developed smart contracts are considered safe for deployment in order to test for real-time performance.    Table 2 presents the different features offered by our proposed blockchain-based approach to implement a decentralized marketplace for trading energy in contrast to the existing solutions. Some of the previous solutions do not employ the blockchain but rather use a centralized approach such as [12]- [15]. Other blockchain-based solutions do not implement a selection mechanism, such as an auctioning scheme to choose appropriate EPs, such as in [16], and others are made using permissioned blockchain networks which gives it limited accessibility, such as in [17] and [19]. In contrast, the proposed solution in this paper employs the public Ethereum network to implement a decentralized public marketplace for energy trading. Moreover, a reverse auctioning mechanism is utilized for a fair selection of EPs along with a reputation score that evaluates the energy seller performance. Nevertheless, this solution lacks a user-friendly interface for a better user experience. A front-end application is part of the possible enhancements to this approach.

E. LIMITATIONS AND FUTURE WORK
The benefits of employing the decentralized blockchain technology are evident across various fields and applications. Nonetheless, certain compromises are observed when utiliz-VOLUME 4, 2016 ing this technology, as is the case in our blockchain-based approach. For instance, special consideration is required for the complexity of the deployed smart contracts in contrast to typical centralized systems that have higher computational power at a lower cost. Complex algorithms increase the cost of operation significantly in blockchain-based solutions, and therefore, the gas consumption needs to be minimized for the solution to be feasible. In addition, large data such as images cannot be stored on the blockchain itself as it requires large storage space that is quite expensive. Hence, third-party decentralized storage systems are typically required, which add extra overhead to the system.
The current version of the Ethereum blockchain can process about 15 transactions per second, which is considered low in contrast to centralized servers. Hence, scalability issues arise as the number of members and operations increases in the network. The hardware and software of a central server, on the other hand, can be improved to accommodate large traffic and increased throughput requirements. Time delays also tend to be an issue with blockchain-based solutions. Therefore, the blockchain is not a suitable backend for a real-time application, as transactions take relatively longer to be processed depending on the consensus protocol implemented. In the case of Ethereum, the time delay of a transaction includes the time it spends in the pool of transactions to be picked by a miner as well as the time taken by the miner to form the block, compute the hash, and append the block to the blockchain. Finally, additional time delay should be considered for the transaction to be confirmed. A transaction is confirmed when there are enough blocks ahead of it to avoid double-spending problems.
In the next phase of this project, we aim to deploy this solution on the real Ethereum network. This allows for further testing and a real-time analysis of the system. A decentralized application (DApp) is also required for the full deployment, as this solution is expected to be user-friendly. Developing a frontend DApp improves the usability of the system as it makes it more intuitive as compared to accessing the smart contracts directly. Special consideration is required when developing DApp because, unlike other applications, they are decentralized in order to be compatible with the blockchain.

VII. CONCLUSION
In this paper, we have proposed a blockchain-based solution to enable energy trading using an auctioning and reputation scheme between EVs in a manner that is reliable, secure, and trustworthy. The proposed solution ensures costeffectiveness through a reverse auctioning scheme for fair competition between EPs to offer the requested service at the lowest cost. We proposed a reputation-based scheme that assists in selecting reputable EPs based on their reputation scores. The communication between different entities involved in the energy trading is enabled using Ethereum smart contracts. We employed Remix IDE to deploy and test the functionality of the developed smart contracts. The smart contracts were proven to generate the expected outputs for all the documented functions in contrast to the functional requirements. Non-functional requirements were also validated by performing the cost and security analysis. For the cost estimation, all functions were shown to cost less than $0.05 for average execution according to the aforementioned conversion rates, which further proves the solution feasibility. The security analysis revealed that the proposed solution is secure enough against common attacks and vulnerabilities. For future work, the solution can be deployed and tested on the real Ethereum network, in addition to the development of DApps for better usability as well as expanding the back-end functionality.