1. Introduction
With the rapid development and large-scale application of distributed power generation technology, the penetration rate of distributed power supply in China’s distribution network system shows a significant upward trend [
1]. In the context of the continuous promotion of power system reform, the gradual liberalization of the electricity sales market has led to a fundamental change in the role of the main participant in power transactions—the traditional power consumer into a dual attribute of production and sale of “production and consumption” [
2]. At the national policy level, “on promoting the integration of power source, network, storage and multi-energy complementary development of the guiding opinions” and other documents clearly support the market-oriented trading of distributed energy and encourage the construction of the real-time balance of the localized consumption system. However, the inherent multi-node, decentralized characteristics of the distributed power system [
3] and the traditional centralized trading architecture are fundamentally contradictory: first of all, the massive decentralized trading requests lead to a dramatic increase in the load of the centralized trading platform, and the efficiency of the transaction aggregation decreases exponentially with the increase in the number of market players; secondly, the information barriers generated by the centralized trading intermediary are difficult to guarantee the completeness of the disclosure of information and the transparency of the price formation, and even more critically, the physical centralization of the centralization of the centralized trading system has been a major factor in the development of the distributed energy market. More critically, physical centralized data centers face the vulnerability of cyber security attacks. This structural contradiction needs to be broken through the paradigm innovation of the trading mechanism.
International energy policy reforms have provided institutional support for distributed trading mechanism innovation. The European Union, through the Clean Energy Package (2019 version) [
4] to establish the legal status of distributed energy resources aggregation trading, and its revised Electricity Market Design Directive, explicitly requires member states to establish a third-party aggregator access mechanism, effectively reducing the institutional threshold of P2P trading. China’s “14th Five-Year Plan for Science and Technology Innovation in the Energy Sector” has synchronized the “blockchain + energy” innovation project, focusing on supporting the research and development of a distributed energy smart contract trading system. It is worth noting that, under the current market system, there is still centralized reliance on key links: green power tracking and certification needs to be endorsed by a third-party certification body, and the distribution of rights and benefits relies on the clearing and settlement of power grid enterprises, which leads to high marginal costs of transactions. Blockchain technology, through the construction of a verifiable distributed ledger system, in the application practice of the Rotterdam Distro platform in the Netherlands, the automatic execution mechanism of smart contracts has realized 20 million transactions on the chain clearing and settlement, the user’s comprehensive cost reduction of 11%, a distributed photovoltaic asset yield enhancement of 14%. The technology internalizes multidimensional credit characteristics (e.g., green power traceability code, transaction performance rate) into asset attributes through the credit penetration mechanism and reconstructs the behavioral paradigm of market participants by using the dynamic incentive mechanism.
As a new generation of distributed trust infrastructure, blockchain technology, by virtue of its decentralized architecture and data tampering characteristics [
5], effectively cracks the efficiency bottleneck existing in the traditional centralized transaction mode while guaranteeing transaction information security [
6]. Its core advantages are reflected in the following: the construction of peer-to-peer network architecture to eliminate the risk of single-point failure, the use of asymmetric encryption technology to ensure the security of transaction privacy, and the consensus mechanism to achieve the transaction verification of the disintermediation. These technical characteristics provide basic support for the establishment of a transparent and trustworthy distributed power trading system with low friction cost.
With the continuous emergence of blockchain-based power trading methods, the drawbacks of the traditional trading model have been improved to a certain extent, but there are still some deficiencies. Some of the existing blockchain-based power trading mechanisms are not precise enough in credit assessment, relying only on simple indicators, which cannot comprehensively and accurately reflect the credit status of the trading subject; there are also deficiencies in protecting the interests of trustworthy users, as the trading order matching strategy fails to take credit factors into account, which results in the difficulty of reflecting the advantages of trustworthy users; and some studies lack specific and perfect power trading smart contracts, which affects the automation and efficient execution of trading.
The distributed power trading mechanism based on blockchain smart contracts proposed in this paper is designed to make up for the above deficiencies. Compared with the existing blockchain-based methods, this mechanism has significant advantages. In terms of credit assessment, the entropy power method is used to comprehensively consider five indicators, such as contract completion rate, power deviation rate, and motivation for performance, to construct a more accurate user credit management model, which is able to comprehensively and accurately assess the credit status of the main body of the transaction; in terms of the matching strategy for the transaction order, it innovatively places “price, credit value, and time of reporting”. In the transaction order matching strategy, “price, credit value, reporting time” is innovatively prioritized, which effectively protects the interests of trustworthy users; at the same time, a series of fully functional power trading smart contracts are written in the Solidity language, which realizes the automation and efficient execution of the trading process.
2. Relevant Work
Recently, both domestic and international scholars have conducted extensive and profound research on the application of blockchain technology in distributed power transactions. Shen et al. [
7] analyzed the application value of blockchain technology in the energy field and its applicability for use in the energy sector. Tan et al. [
8] addressed the absence of an effective and reliable transaction mechanism to regulate users’ credit behavior in distributed power trading, proposed a blockchain-based distributed power trading framework, and then designed a distributed power trading process that considers credit management. Wang et al. [
9] constructed corresponding transaction, settlement, reward, and punishment mechanisms for the characteristics of distributed power transactions. The proposed mechanisms were illustrated through the analysis of arithmetic examples. Deng et al. [
10] introduced a power transaction matching strategy capable of effectively quantifying credit. They achieved the effective sharing and evaluation of credit data through blockchain technology. Zhang et al. [
11] proposed a multi-layer power trading framework based on blockchain technology. Firstly, non-cooperative game theory is used for the bidding and clearing phases of the trading nodes. Secondly, after the cycle auction, the remaining untraded nodes are shelved, and finally, a reasonable node matching is achieved by solving the game, and also the untraded nodes are matched with trading partners. Lv et al. [
12] proposed a real-time peer-to-peer power transaction model (RMCT), which regulates user transaction behavior through a dynamic reputation mechanism and realizes real-time electricity bill settlement between users and the grid by combining with a multi-chain architecture. However, none of the literature [
7,
8,
9,
10,
11,
12] designed the smart contract corresponding to the proposed mechanism in detail. Zhu et al. [
13] established a blockchain network based on an authoritative proof algorithm and classified users according to their electricity demand, while designing a user credit mechanism along with a corresponding auction algorithm. Hu et al. [
14] considered the network trend constraints in the transaction mechanism and established a security check and blocking management model based on the power transmission distribution factor (PTDF). Additionally, a service charge collection model for energy service providers based on the Shapley value method was formulated by them. Xiao et al. [
15] designed innovative mechanisms to deal with deviations, penalties, and grid access fees, while utilizing blockchain technology to achieve distributed power transaction management. Yu et al. [
16] designed and developed a two-way listed power transaction platform based on Ethernet by analyzing the specific transaction process and mathematical model in combination with Ethernet. Reb et al. [
17] employed the improved AdaBoost algorithm to analyze and learn price competition behavior among users. They predicted the supply–demand gap in power trading and constructed a game model among power users within a blockchain distributed environment. Furthermore, they identified the Nash equilibrium price. Wang et al. [
18] proposed a new blockchain-based distributed community energy trading mechanism (CE-SDT), which connected power generation users and power consumption users through a decentralized network to form an autonomous P2P trading platform. The photovoltaic model and energy storage constrained dynamically optimize supply and demand; a price–priority bidirectional auction smart contract matches transactions, and the balance is balanced by the grid. Zhang et al. [
11] proposed a blockchain-based multi-tier electricity trading framework using consortium blockchain technology, which incorporated network, regulatory, and physical layers. Simulation tests validated the model’s effectiveness, and a phased transaction mechanism was designed. They applied non-cooperative game theory to handle the bidding and clearing processes. Through periodic auctions and game equilibrium resolution, optimal node pairings were achieved, and a secondary matching mechanism was established for unmatched nodes. However, the literature [
11,
13,
14,
15,
16,
17,
18] did not construct a user credit model, or the credit judgment of users in distributed power trading is calculated only by the contract completion rate or power deviation value in the trading cycle, which is not specific and accurate enough. Huang et al. [
19] designed an electricity trading mechanism based on a two-way auction mechanism and P2P transaction to meet the demand of park users for electricity capacity, and introduced deviation assessment and overcapacity penalties to regulate the behavior of users participating in the transaction. Zhao et al. [
20] proposed a blockchain-based two-tier energy trading framework. They adopted a continuous double-auction mechanism in the transaction market to ensure free and fair trading among user nodes. Han et al. [
21] proposed a P2P energy trading mechanism for distributed power users, and the designed multidimensional blockchain platform realized a complete energy trading process. Zhao et al. [
22] constructed a decentralized green power trading system for microgrids by integrating blockchain technology. They optimized trading strategies through a double-auction mechanism to balance participants’ benefits and developed a practical platform based on a game–theoretic model, ultimately achieving closed-loop operation of renewable energy transactions. Most existing auction mechanisms utilize the traditional two-way auction mechanism, which matches trade orders based on price factors alone and may neglect to adequately protect the interests of trusted users.
Comparison of this scheme with the above scheme leads to
Table 1.
In response to the challenges of accurately and concretely assessing the credit of the transaction subject, maximizing the protection of the trustworthy users’ interests, and addressing the absence of a specific smart contract for power transactions in previous studies, a distributed power trading mechanism based on blockchain smart contracts is proposed. The main contributions are as follows:
- (1)
Construction of a distributed power trading model, accompanied by the design of a power trading order matching strategy. This mechanism serves as a benchmark for trading out, effectively safeguarding the interests of trustworthy users.
- (2)
Utilization of the entropy weight method to evaluate the comprehensive credit value of users, which is combined with the deviation fee to construct a credit management model. This model aims to limit default behaviors among trading users.
- (3)
Design of a power trading smart contract tailored to the trading mechanism, enabling the automatic and efficient operation of distributed power trading. This design ensures the security, transparency, and trading efficiency of power trading.
3. Distributed Power Trading Model
3.1. Overall Architecture
Distributed power transaction demands a secure and transparent environment [
23]. To address the security, fairness, and transparency of the participants involved in the transaction, the framework of the blockchain-based distributed power trading system is shown in
Figure 1.
Participants in the transaction are mainly divided into the following three categories: (1) producers, denoting power sales users, primarily consist of distributed new-energy users with generation capacity; (2) consumers, representing power purchasing users, mainly include power demand users without generation capacity; (3) System Platform Managers (SPMs), which include power grid companies worldwide. SPMs are primarily responsible for the maintenance of the platform.
Smart Contract: responsible for automating order matching and settlement.
Blockchain: storing transaction data through the Merkle tree.
Producers and consumers submit orders to the blockchain through cryptographic signatures; SPM is responsible for auditing and maintenance; smart contracts automatically execute order matching and settlement; and transaction data are stored through the Merkle tree to ensure that they cannot be tampered with.
3.2. Trading Process
The transaction in each cycle is divided into three stages, and the flow of the specific transaction steps are shown in
Figure 2.
- (1)
Initialization phase
Initialization phase: SPM reviews the user’s credit worthiness; users with credit worthiness below a threshold are prohibited from trading, and new users are required to register by identity.
Prior to the initiation of each transaction cycle, the SPM updates user information based on the actual situation of the user. Transactions are prohibited if a user’s credit value falls below the set threshold. When a new user enters, the system’s platform administrator first audits the qualification of the user’s identity information. Only users who successfully passed the audit are permitted to register their identity. Once registered, users gain the ability to participate in transactions.
- (2)
Electricity trading phase
Power trading stage: users submit offer orders; smart contracts prioritize and match orders according to ‘price, credit value, reporting time’; and matching results are made public in real time.
Producers and consumers submit trade order quotation contracts to the platform according to their needs, and the platform matches the trade orders submitted by both parties according to the trade order matching strategy in
Section 3.1. The smart contract automatically executes the order matching process, which is completely open and transparent. All users involved in the transaction can view the matching status of the order in real time through the platform, including details of the matched user pairs, transaction price, and power consumption. This transparent operation ensures that there are no hidden links in the transaction process, effectively enhancing the transparency of the transaction. After the order matching is completed, if the user chooses to abandon the transaction due to special circumstances, the user can choose to withdraw the order.
- (3)
Trade settlement phase
Transaction settlement stage: Smart meters record the actual amount of electricity delivered, and the smart contract automatically calculates deviation charges and updates the credit value. Users with high credit values enjoy priority in the next round of transactions, ensuring incentives for trustworthiness.
When the electricity delivery phase of this trading cycle is completed, the system platform manager verifies the actual electricity delivery information from the smart meters of both parties. The manager combines the user’s actual delivered electricity, as recorded in the smart meters of both parties, with the electricity trading contract electricity. Subsequently, the user’s deviation electricity is updated, and the corresponding deviation fee is collected. The manager then proceeds to calculate the user’s credit value and updates it accordingly.
Figure 2 shows the three phases of distributed power trading: the initialization phase, the power trading phase, and the transaction settlement phase. The flow chart presents the whole process from user registration and uploading to the final settlement of the transaction, highlighting the core role of smart contracts (such as automatically matching orders, dynamically updating the credit value, executing the deviation fee settlement, etc.), and realizing the automated execution of decentralized transactions and the transparency of the whole process. In the transaction phase, the order matching strategy combining credit value and reporting time verifies the mechanism goal of “protecting the interests of trustworthy users” in the study—users with high credit ratings are more likely to be matched quickly, avoiding the interference of malicious competition on compliant transactions; in the settlement phase, the smart contract automatically updates the credit value and accurately checks the transaction results according to the transaction results. In the settlement stage, the smart contract automatically updates the credit value and accurately accounts for the deviation cost according to the transaction result, which not only reduces the dependence on manual audits, but also solidifies the fairness through the chain rules, providing a practical example for the distributed power trading mechanism in the fields of transparency improvement and trust cost reduction.
4. Trade Order Matching Strategy
Preceding the pairing of transaction bids, users need to submit their respective offer orders, which include the price and quantity. Subsequently, for electricity sales users, the system constructs a quotation sequence by increments, ordering the quotations submitted by them, as shown in Equation (1):
In particular, is the offer of the customer in the queue during the trading cycle . is the total number of electricity sellers participating in the auction during the trading cycle , and is the highest offer submitted by an electricity seller during the cycle .
For power purchase users, the system constructs the offer sequence by decreasing the order of the offers submitted by them, as shown in Equation (2).
where
is the power purchase offer of the customer ranked
in the trading cycle
.
is the total number of power purchasers participating in the bidding during the trading cycle
, while
is the highest offer submitted by a power purchaser during cycle
.
Since there may be multiple users with the same quote, the order of users with the same quote will be sorted according to the priority of “credit value
and report time
”. When
, first compare the credit value
of the users with the same quotation; the higher the credit value
, the higher the user in the sequence. When the credit value
is also the same, the order is sorted according to the time when the user submits the reported information
. The specific sequencing process of trading orders is shown in
Figure 3.
Figure 3 illustrates the ordering process of trading orders in distributed power trading. After the user submits the quotation order, the system sorts the quotations of the power seller and the power purchaser, respectively. The quotes of the power seller are sorted in ascending order, and the quotes of the power purchaser are sorted in descending order. When there are identical quotes, the quotes are further sorted according to the priority of ‘credit value, reporting time’ to provide an orderly sequence for subsequent trade order matching.
When quotes are identical, the matching strategy prioritizes users with higher credit values, and this prioritization is important for the trading process:
Incentivizing timely reporting: Credit value prioritization can effectively incentivize users to report information in a timely manner. For example, suppose that the offers of User A and User B are the same, but the credit value of User A is higher than that of User B. In this case, User A is prioritized to be matched with the purchaser of electricity. In order to obtain this priority, User B will be more motivated to update its offer information in time to avoid losing the opportunity of priority matching due to delayed reporting. This incentive mechanism motivates all users to actively and timely report accurate transaction information to the system, thus improving the efficiency and transparency of the entire trading system.
Promote Fair Pricing: Credit value prioritization also promotes fair pricing in the trading process. When users with higher credit worthiness are prioritized for matching in case of a consistent offer, this will motivate other users to be more cautious and reasonable in their offers. This mechanism makes it necessary for users to consider both price and credit factors when making an offer, which in turn leads to a fairer and more reasonable pricing mechanism in the market.
Following the conclusion of sorting, the corresponding power purchase and power sale orders for electricity will be matched and summarized sequentially in accordance with the rules of the two-way auction. When the highest offer of the power purchase order is less than the lowest offer of the power sale order, or when all of the power purchase and sale offers are successfully matched on one side of the sequence, the round of trading ends. The final transaction price is the average of the two quotes, as shown in Equation (3):
where
is the transaction price, and
and
are the offers of the purchaser/seller, respectively. The transaction volume is the smaller of the two quoted volumes, as shown in Equation (4):
Among them, is the volume of electricity turnover; and are the reported volume for the purchasing/selling users, respectively; and min is the smaller value of between and .
Currently, if there is still a user who has not completed the transaction match, the user can query the current stage of the user’s quotation information to decide whether to modify their own offer and participate in power trading again. If both parties involved in the transaction choose to abandon the transaction due to exceptional circumstances, they can delete the orders that have been successfully matched and completed the withdrawal operation. Upon the conclusion of this phase, users who still have not met the demand can seek electricity transactions with the grid company.
5. Credit Management Model
Due to the intermittent nature of the distributed generation process and the possible deviation of the generation forecasts, it is likely that both users will not deliver electricity in full accordance with the contractual order during the settlement phase, which may easily cause an imbalance between the supply and demand of electricity in the trading system [
24]. Therefore, when a transaction cycle is completed, the final settlement of the transaction in this cycle is carried out through the power delivery data recorded in the user’s smart meter. When one of the parties involved in the transaction has a deviation in power consumption due to the other party’s failure to fully implement the contract, only the user who fails to implement the contract is penalized for breach of contract, and the credit value assessment mechanism and power deviation fee are designed for both parties involved in the transaction to limit the default behavior of the trading user.
The credit value assessment mechanism plays a central role in the distributed power trading system, which not only comprehensively evaluates the credit status of the user, but also incentivizes the user to maintain good trading behavior through the credit value priority. This mechanism ensures that creditworthy users enjoy priority in trade matching, which enhances the transparency and fairness of trading. In addition, the combination of credit worthiness and trade order matching strategies effectively promotes timely reporting of information and fair pricing by users, which is essential for maintaining the stability and efficiency of the trading system. The mechanism adopts uniform credit evaluation indicators for all market participants, including producers and consumers, such as the contract fulfillment rate, favorable rating, and power deviation rate, which are calculated based on objective data to ensure fairness in the evaluation. In the charging of power deviation fees, regardless of the type of user, as long as the deviation exceeds the prescribed range, it is uniformly implemented in accordance with Equation (12), which ensures the fairness of credit management without favoritism or discrimination, thus providing a solid foundation for the sustainable development of distributed power trading.
5.1. Mechanisms for Assessing Creditworthiness
Since a single periodic behavior can only reflect the one-sided characteristics of the subject, the entropy weight method is used to comprehensively and accurately assess the creditworthiness of both transaction users. A comprehensive credit evaluation index, as shown in
Table 2, is proposed to assess both parties involved in the transaction. These indicators are calculated based on objective data, which ensures the fairness of credit evaluation and provides a comprehensive basis for credit value assessment.
In order to ensure the repeatability and accuracy of the credit assessment, the following details the measurement and tracking methods for each credit indicator:
- (1)
Contract Completion Rate
The contract completion rate refers to the ratio of the number of contracts completed by the subscriber to the total number of contracts signed within a certain period of time. Its calculation formula is:
For example, assume that User C has signed a total of 20 power purchase contracts in the past 10 trading cycles, of which 18 contracts have been successfully completed for delivery, then User C’s contract completion rate is:
In the experiment, the system platform manager (SPM) will obtain the user’s contract records from the blockchain at the end of each transaction cycle, count the number of completed contracts and the total number of signed contracts, and calculate the contract completion rate. These data will be recorded on the blockchain as the basis for credit evaluation.
- (2)
Favorable evaluation rate
The favorable evaluation rate is the ratio of the number of favorable evaluations the user receives during a transaction to the total number of reviews. Its calculation formula is:
For example, assume that user D has received 40 favorable, 5 neutral, and 5 negative reviews in the last 50 transactions:
After the transaction is completed, the system will automatically prompt both parties to evaluate each other, and the evaluation options include “favorable”, “neutral”, and “negative”. SPM regularly collects users’ evaluation data from the blockchain, counts the number of positive reviews and the total number of reviews, and calculates the rate of positive reviews. The positive rating is updated in real time and recorded on the blockchain to reflect the user’s latest credit status.
- (3)
Electricity deviation rate
The power deviation rate refers to the degree of deviation between the actual power delivered by the user and the power agreed to in the contract. Its calculation formula is:
For example, assume that user E contracts for 100 kWh of electricity in a transaction and actually delivers 95 kWh of electricity, then the deviation rate of electricity for user E is:
At the end of the power delivery phase, SPM obtains the user’s actual delivery power data through the smart meter and compares it with the contractually agreed upon power recorded on the blockchain to calculate the power deviation rate. These data are also recorded on the blockchain for assessing the performance stability of the user.
The rest of the parameters are calculated with a similar process.
If the probability value of the occurrence of each different state in a system is
, then the entropy of the system at that point is determined by:
- (4)
Constructing a matrix of credit indicators.
In the distributed power trading system, assuming that there are users participating in the transaction, and each user has credit evaluation indicators, the credit indicator matrix ,where means the value obtained by the th indicator of the th evaluated user () can be constructed.
- (5)
Standard normalization of data for evaluation indicators
Among the credit evaluation indicators, there exist both positive and negative indicators. Due to their distinct implications, certain evaluation indicators with larger values may lead to a reduction in the user’s credit rating. Therefore, the data of positive and negative indicators need to be processed differently.
Let the maximum value of each column in the credit evaluation matrix be , and where , , respectively.
When
is a positive indicator:
When
is a negative indicator:
- (6)
Obtaining credit evaluation indicator weights.
Referring to (11), the overall entropy for users with credit evaluation indicators is:
Referring to (14), the entropy value of the credit evaluation index
is:
Among them, , .
Therefore, the credit evaluation indicator
is weighted:
It can be clearly derived from , .
- (7)
Calculation of the user’s overall credit rating
The composite credit rating is:
According to the trade order matching strategy, the larger the user is, the more priority will be given to match the same offer when it appears in the next trading cycle. As a result, users with higher comprehensive credit values will receive greater trading benefits.
By evaluating the user’s comprehensive creditworthiness and linking it to their earnings, users can be regulated to a certain extent to ensure that transactions are carried out in strict accordance with the terms of the contract and reduce the occurrence of user violations.
5.2. Calculation of Deviation Fee
There are three relationships between the electricity actually issued/used by the producer/consumer and the amount of electricity it has contracted to transact , i.e., , , If , then the consumer’s demand for electricity is satisfied, so neither party needs to pay for the deviation. If or , then there is always one party whose demand is not satisfied. If the deviation is within a certain range, no deviation charge is levied. Otherwise, a deviation charge is levied on the consumer who generates the deviation.
The basis for selecting 20% as the deviation threshold for this program is as follows:
Historical data analysis: by analyzing historical transaction data, it was found that power deviations of more than 20% were rare and usually associated with extreme weather events or equipment failures.
Risk control: setting a 20% deviation threshold ensures transaction stability while allowing users some flexibility in the face of unforeseen operational challenges.
Incentivize trustworthy behavior: a 20% deviation threshold helps to incentivize contract compliance and reduces intentional defaults, thereby improving the overall system creditworthiness.
In the
th cycle, the power deviation charge to be paid by the
th trading customer to the grid company is:
where
is the deviation fee that the
trading user needs to pay to the grid company in the
cycle,
is the cost balance coefficient,
is the number of times the
trading user generates deviated power in the
cycle,
is the average transaction price of power in the
cycle, and
is the deviation value of the
trading user’s actual delivered electricity from the signed transaction electricity in the
cycle.
The average transaction price of electricity in the
th cycle is as shown in Equation (13):
where
is the tariff of the transaction contracted by the
trading customer in the
cycle; and
is the number of transactions completed in the
cycle.
The relationship between the number of times the deviating power
, the deviation value of the electricity
, and the electricity balancing cost is shown in
Figure 4.
Figure 4 presents the relationship between the power deviation fee and the number of times of generating deviated power and the value of power deviation. From the figure, it can be seen that in a trading cycle, the deviation cost that the users participating in the transaction need to submit to the grid company increases exponentially with the number of deviations and the deviation power, which intuitively reflects the constraints of the deviation cost on the behavior of the users participating in the transaction.
6. Smart Contract Design for Power Trading
A smart contract is essentially a computerized protocol used to propagate, verify, or execute a contract in a message-based manner. It allows for traceable and irreversible transactions, without the need for a third party [
25]; hence, smart contracts are one of the key features of blockchain technology [
26], which can be seamlessly integrated with blockchain technology.
Based on the transaction process and the distributed power trading mechanism proposed in
Section 2, a smart contract for distributed power trading is written in the Solidity language. The basic functions and names of the contract are shown in
Table 3.
- (1)
User Information Update and Registration Functions
Before the start of a transaction in a cycle, if the identity information of a user who has already registered and made a transaction needs to be updated, the SPM calls the information update function “updateUser” to update the user’s identity information. If it is a new user that meets the registration eligibility criteria, the user calls register <accountId, userAddress, electricalId, credit, userType, location> to register, and the registration information includes accountId user ID, userAddress account address, electricalId smart meter ID, credit user credit value (initial credit value is 100), userType user type (0 for power sales user, 1 for power purchasing user), and location user address. After successful registration, the user’s identity information is written to the blockchain.
- (2)
Trade Order Quote and Sort Functions
Firstly, SPM calls the setOpen function to start the transaction, and then the registered power buyers and sellers submit their respective submission information by calling the buyers and sellers functions, respectively; the contents mainly consist of <price, amount>, where price is the price and amount is electricity. sortToBuy and sortToSell are the ordering functions of power purchase/sale user quotes, respectively. They are called by SPM after the offer information submission phase is completed and get the timestamp of the user order reporting through block.stimestamp.
- (3)
Order Matching and Cancellation Functions
After the user submits the quotation information and the sorting phase is completed, the matching function is called by SPM to match and summarize the user’s trading offer order. The output is <userAddress, userAddress, price, amount>, which includes the account address of the power purchase user, the power sale user, the transaction price, and the transaction amount of electricity. If the user abandons the transaction, the transaction matching information can be deleted using the deletMatch function to complete the withdrawal operation. After the transaction order matching is completed, SPM can call the setOpen function to close the transaction.
- (4)
Trade Settlement Functions
After completing this transaction cycle, the SPM combines the user’s actual delivered power recorded in the smart meters of both parties with the power specified in the signed power trading contract. It then calculates the user’s credit value based on the user’s trading behavior during this cycle. Finally, it updates the user’s credit by invoking the settlement User function for settlement.
- (5)
Information Query Functions
After the user has submitted the quote information and sorted it, you can call the getBuyerList, getSellerList function to get the sorted list at this time. The result of the query is <userAddress, price, amount>, i.e., the user’s account address, price, and amount. After the transaction matching phase is complete, the sorted list information is deleted. The user can now call the getMatchList function to get the match results of the transaction at this point. Input the user’s account address <userAddress> and output <userAddress, userAddress, price, amount>, which includes the user’s account address, the account address of the user whose order matches, the price, and the amount of electricity traded. The user and the SPM can call the user function at any point and simply enter the user’s account address to look up all of the user’s identifying information.
The information query function provides strong support for transaction transparency. Users and SPMs can call getBuyerList and getSellerList functions at any time to get the sorted list of users in the quotation stage, including the user’s account address, quotation, and quantity information; after the transaction matching is completed, call the getMatchList function to view the complete transaction matching results, including the account address of the user who purchases electricity and the user who sells electricity, the transaction price, and the quantity. After the transaction matching is completed, call the getMatchList function to view the complete transaction matching results, including the account address, transaction price, and power quantity of the purchaser and seller. In addition, through the user function to enter the user account address, you can also query the user’s identity information. These information query functions make the information of the whole transaction process completely transparent, which is convenient for all parties to supervise and manage.
7. Security Analysis
Firstly, the proposed distributed power trading mechanism is analyzed for its security in terms of three dimensions: authentication, high availability, and tamperability.
- (1)
Authentication: before the user nodes participate in the transaction, only the transaction user nodes that have been audited and approved by SPM are qualified to register for the transaction account and join the system to participate in the power transaction, which can eliminate a portion of malicious node users from the source.
- (2)
High Availability: the user nodes that have been successfully audited by SPM can effectively access the services in the power trading system, realize various functional requirements, and have the characteristics of effective defense against DDoS (Distributed Denial of Service) attacks.
- (3)
Non-tampering: the records of power transactions generated are stored in the form of blocks on the blockchain, and the chain structure of the blockchain ensures that the transaction records will not be easily tampered with.
Secondly, the proposed transaction mechanism reduces the risk of single-point attacks by eliminating the central node and guarantees the stability of the system. The transaction data cannot be maliciously tampered with after being uploaded to the blockchain, and the mechanism of synchronous modification of multiple blocks is required to ensure the authenticity and integrity and enhance the credibility of the transaction. Combined with the Merkle Tree to verify data consistency and PoW consensus to resist attacks, we jointly build a safe and reliable power trading system.
The Merkle Tree structure is shown in
Figure 5, where the leaf nodes represent the nodes at the bottom of the graph, representing the hash values of the transaction data; the intermediate nodes represent the combinations of the hash values of the leaf nodes; and the Merkle Root represents the hash value of the entire Merkle Tree, which is used for verifying the integrity of the transaction data.
From its structure diagram, it can be seen that if the Merkle root at the bottom of two trees is the same and consistent, the structure of these two Merkle Trees and the content of each node must also be the same. Therefore, the Merkle Tree can prevent the data from being tampered with by traversing down to the hash nodes in the tree [
27], assuming that the content of any of the leaf nodes has been tampered with, which will cause the Hash value obtained from the bottom–up computation to be incorrect, and will ultimately cause the Hash value of the header of the block to be changed, as well. Moreover, by virtue of its own characteristics, it can quickly and accurately locate the position of the tampered content during verification, which not only improves the security of the transaction system and strengthens the trustworthiness of the blockchain in distributed power transactions, but also cooperates with the “Resistance to Data Falsification Attacks” mechanism to jointly defend against malicious attacks, which effectively safeguards the security and reliability of distributed power transactions and ensures that the power transactions are conducted in a safe and reliable manner. It also works with the “Resistance to Data Forgery Attacks” mechanism to resist malicious attacks, effectively guaranteeing the security and reliability of distributed power transactions and ensuring that information in power transactions can hardly be tampered with.
The PoW consensus mechanism [
28] ensures the security of the system against threats such as selfish mining attacks [
29], eclipse attacks, and less than 51% of the double-spend attacks [
30,
31]. The effect of the PoW consensus mechanism adopted in this scheme to resist attacks is analyzed with the help of the model proposed in [
32], as follows.
Under the PoW consensus mechanism, it is assumed that in the process of the competition between the main and branch chains, an attacker may attempt to manipulate more computations on the shorter branch chains in order to exceed the workload of the
n-block length. The probability of the attacker catching up with the honest chain during this attack is shown below:
where
is the probability of the attacker being from
n blocks behind to catching up with the honest chain;
is the probability of the honest person finding the next block;
is the probability of the attacker finding the next block; and
is the progress of the attacker’s attack, which will be a Poisson distribution with an expectation value of
. The probability that the attacker can make up for and surpass the success of tampering with the main chain is:
The transformation of Equation (15) yields:
Figure 6 displays the relationship between
n and the probability
P of an attacker overtaking the main chain and tampering successfully under different
.
To ensure the security of the transaction, the transaction in the PoW consensus mechanism needs to wait for six blocks of time before the transaction is confirmed [
33]. From
Figure 6, at
n = 6, if
p exceeds 0.5, the probability of an attacker catching up with the honest chain to carry out a fork attack is 1. That is, the attacker can only gain control of more than half of the computational power involved in the transaction in order to ensure a successful attack. However, at this point, the cost incurred by the attacker will be significantly greater than the potential revenue, making the attack not worth the loss.
8. Simulation Analysis
8.1. Types of Graphics
To validate the effectiveness of distributed power trading mechanisms, the trading platform is constructed in the laboratory environment; and the smart contract is written, deployed, and tested by using the Solidity language; and the experimental environment is set up as shown in
Table 4. The environment configuration information used to verify the effectiveness of the distributed power trading mechanism for this experiment is listed in detail, including the operating system, CPU, development platform, client, programming language, and network environment, to ensure the consistency and repeatability of the experimental conditions.
The power trading smart contract is written through the Solidity language in order to more conveniently and effectively carry out relevant simulation tests. Using the Geth client to build a local private chain, the Remix-Ethereum IDE platform is selected for compiling, testing, and deploying the distributed power trading smart contract, and at the same time, connecting with the constructed private chain node through the External HTTP Provider environment that comes with the platform.
The relevant parameters of the contract operation are described as follows: the total gas value consumed by the contract deployment is 4,296,372 (gas is a unit of measurement of workload, indicating the relative computational workload required to perform certain operations on the blockchain [
34]), and the hash address of the smart contract is 0xa3415cedd54529d728c04431a9dade2e86a70af3dd47af3a2f9b75e68a6e643c.
8.2. Calculation Analysis
In the experiment, seven users (including one system platform manager SPM, three power purchasing users, and three power selling users) were selected to simulate the distributed power trading network. This choice was based on the controllability and reproducibility of the laboratory environment, as well as the ability to effectively demonstrate the operation of core functions, such as trade order matching, credit management, and deviation cost calculation. Seven accounts are created on the local private chain to simulate the trading network of these seven users, where identity 0 represents the power purchasing user, and 1 represents the power selling user; and SPM is not involved in power trading, but is only responsible for deploying contracts and maintaining the normal operation of the system. The information of each user is shown in the following table.
Table 5 provides the details of the seven users participating in the distributed power trading simulation experiment, including user number, account address, identification, and credit value. The user number ID is used to uniquely identify each user in the system, while the account address is the user’s address on the blockchain, which is used for authentication and transaction records during the transaction process. The identity ID distinguishes whether the user is a power purchaser (identified as 0), a power sales user (identified as 1), or a system platform manager (SPM). The credit value reflects the user’s credit level in the transaction and plays a key role in the transaction order matching strategy, ensuring that trustworthy users are given priority matching, thus motivating users to maintain good trading behavior and protecting the interests of trustworthy users. In addition, the automatic update of credit value and the collection of deviation fees are realized through smart contracts, which reduces manual intervention and improves transaction efficiency and security.
Let the feed-in tariff for distributed generation be 0.4 (
), the price of electricity purchased by users from grid enterprises be 0.6 (
),and the reference tariff within the trading network be taken as 0.52 (
). These price ranges are set based on the current distributed power market realities in China. The feed-in tariff for distributed generation is usually lower than the grid purchase price, while the reference tariff is an intermediate value under the market supply and demand balance. By setting these price ranges, the price fluctuations and trading behavior in the actual market can be better simulated. In one transaction cycle, the transaction results are analyzed without considering the impact of the over-the-grid fee on the transaction, and the offer information submitted by the users involved in the transaction by calling the BUYER and SELLER functions is shown in
Table 6.
Table 6 records information about the quotes submitted by participating users during a trading cycle, including user number ID, identification, quote, quantity quoted, credit value, and order of quotes. These data are the basis for the sorting and matching of trade orders, which determines the specific process and outcome of the trade.
After the quotation information is submitted, according to the power trading mechanism, firstly, the sorting functions of sortToBuy and sortToSell are called to sort the trading orders, and then the matching function is called to match the trading orders, and the matching results are shown in
Table 6.
Table 6 shows the results of sorting and matching the user’s quoted orders according to the power trading mechanism, which specifies the pairing of the power purchasing user and the power selling user, the transacted amount of electricity, and the transacted price of electricity, and intuitively reflects the implementation effect of the trading order matching strategy.
The final transaction results are shown in
Figure 7.
As can be seen from
Figure 7, according to the transaction order matching strategy in this paper, the power sales user 3 prioritizes trading with power purchasing user 6; at this time, the power purchasing user 6 still has 1 (
) electricity demand. Secondly, the power purchase user 4 and the power sales user 1, to carry out transactions at this time, the power sales user 1 still has a 5 (
) power sales gap. Then, power sales user 2 and power purchase user 5, to trade order matching at this time, the power purchase user 5 still needs to buy 3 (
) power. Next, power sales user 1 and power purchase user 6 trade, and then trade with power purchase user 5; power sales user 1 still has 1 (
) power to sell. Since there are no more tradable power purchasers at this point, power seller 1 will sell the last 1 (
) of power to the grid company.
The size of the user’s credit value also has a certain impact on the final transaction result. By adjusting the initial quotation of power sales user 3 and power purchasing user 4, we can observe the changes in power purchasing and sell prices in
Table 6, specifically, when the offers of power sales user 3 match those of power sales user 1 and power sales user 2; and the offers of power purchasing user 4 match those of power purchasing user 5 and power purchasing user 6; and the credit values of power sales user 3 and power purchasing user 4 are 80 and 100, respectively.
From
Table 7, when users offer the same price, the users with higher credit value can close the deal first. And they can obtain higher benefits in the final deal clearing. Therefore, the size of the user’s credit value has a great impact on the actual benefits for the final user. After the completion of the power delivery stage, the final transaction settlement result of each user is shown in
Table 7, where the benefit greater than 0 indicates the income from power sales, and the benefit less than 0 indicates the expenditure from power purchase. For power purchase users, the deviation of power greater than 0 means that the actual power delivery is greater than the contracted power, and the deviation of power less than 0 means that the actual power delivery is less than the contracted power, and the same is true for power sales users.
From the above analysis, it is clear that the credit value plays a key role in the matching of trade orders, which strongly supports the argument of protecting the interests of trustworthy users. For example, customer 4 offers the same price as customer 5, but because of its higher credit value, it is given priority to complete the transaction with customer 1. This not only reflects the advantage of users with high credit value in the transaction, but also shows that the priority matching strategy of “price, credit value, time of reporting” can give trustworthy users more favorable trading opportunities and improve their trading revenue, which in turn motivates users to maintain good credit and standardize their trading behavior.
Analyzing the data in
Table 8, it can be seen that the actual delivered power of power sales users 3 and 2 and power purchase users 4 and 5 are inconsistent with the contracted power due to their own reasons; the deviation power generated by users 3, 2, and 4 is within 20%, so they are not charged a deviation fee. However, the deviation of user 5 is beyond the given range, so it is charged a deviation fee according to Equation (16). This not only provides a self-regulating mechanism for the system, but also enhances the importance that users place on contract execution, thereby improving the reliability and security of the entire transaction system. These results illustrate that the automation and transparency of distributed power transactions can be achieved through blockchain smart contracts and ensure the fairness and efficiency of the transactions.
The deviation cost formula is shown in Equation (16), using User 5 as an example. is 0.14, and means that the number of times user 5 has generated deviated power in this trading cycle is 1. means the average transaction price of electricity for the five customer transactions in a cycle plus the customer’s one transaction with the grid is CNY 0.5086. The deviation value is 1.3 kw·h; after calculation, the deviation cost is CNY 0.12.
Taking the power transaction between user 3 and user 6 as an example, the volume of electricity traded is 25 kw·h, while the deviation is −1.2 kw·h, so the actual volume traded is 23.8 kw·h, and because
Figure 7 shows that the price of electricity traded between user 3 and user 6 is 0.5095 (CNY/kw·h), the gain is
.
These results illustrate that automation and transparency of distributed power transactions can be realized through blockchain smart contracts, and ensure the fairness and efficiency of the transactions. In addition, the interplay of the credit value assessment mechanism and the deviation fee mechanism effectively restricts the default behavior of the transaction users and ensures the smooth progress of the transaction. This fully verifies the effectiveness of the credit management model constructed using the entropy right method and deviation fee, which can encourage users to execute transactions in strict accordance with the contract, safeguard their own credit, and avoid additional costs.
Finally, the credit indicators of all users in the cycle are evaluated based on the proposed credit mechanism to determine the credit value of each user.
In order to verify the economics of the trading mechanism proposed in this paper, the final total benefits obtained by the purchasing and selling customers using the trading mechanism in this paper are analyzed in comparison with the purchasing and selling customers trading directly with the grid company (P2G). The workflow of the P2G model is to first establish the market organizer, clarify the trading rules, register the participants, and then publish the trading announcement, formulate the trading plan, and then submit the trading declaration, matching and confirming the trading results through the platform; delivery, settlement, and invoice payment after the completion of the transaction; and the market organizer supervises the market order and publicizes the trading information.
As shown in
Figure 8, the implementation of the power trading mechanism described in this paper has resulted in an increase in revenue for the power sales user compared to the revenue generated by the P2G model. Additionally, the power purchase user’s expenditure on power purchases is lower than that of the P2G model. It is proved that the trading mechanism is economically feasible, can protect the interests of both users, and can effectively promote the local consumption of distributed electricity.
9. Discussion
9.1. Comparison with Previous Studies
As shown in
Table 1, compared with the current state-of-the-art research, the distributed power trading mechanism proposed in this study has several obvious advantages. First, the credit assessment mechanism in this study is more comprehensive and dynamic, utilizing five multidimensional indicators to assess user credit. This is a significant improvement over previous studies that lacked a specific credit model or relied on simple metrics such as transaction history scores. Second, the order matching strategy in this study prioritizes price, credit value, and reporting time, effectively protecting the interests of trusted users. This is a novel approach compared to previous studies that only prioritize price or use traditional two-way auction mechanisms without considering credit factors. Third, the smart contract application in this study is more functional and supports the automatic execution of the entire trading process, including user registration, quote sorting, matching aggregation, and settlement. This is a big step forward compared to the partial or abbreviated smart contract design in previous studies. Fourth, the security architecture in this study is more robust, combining PoW consensus and Merkle tree structure to withstand attacks and ensure data integrity. This is a significant improvement over previous studies that relied on less secure consensus mechanisms or centralized authentication. Finally, the proposed mechanism also outperforms previous research in terms of economics and transparency, providing dynamic incentives for high-credit users and real-time transparency of transaction data.
9.2. Theoretical Limitations and the Expansion of Research Propositions
Past studies on the combination of blockchain smart contracts and distributed power trading have mostly focused on technical feasibility verification, with insufficient research on long-term stability and adaptability to dynamic market environments. Some studies have not fully considered the complex interests and policy constraints in power trading, resulting in a disconnect between theory and practical application.
Based on this, the following new research propositions are proposed: first, to construct a blockchain smart contract power trading model that takes into account the dynamic adjustment of policies and the game of multiple interests of market players, and to study the optimization mechanism of smart contract rules under different policy orientations, so as to ensure the stable operation of the trading system in the event of policy changes; second, to explore the blockchain performance optimization strategy for highly concurrent power trading scenarios, and to enhance the scalability of the system in order to adapt to the trend of the expanding scale of distributed power transactions. For the first proposition, the complex policy environment, power subsidy policy, carbon emission policy, etc. will affect the cost and benefit of the trading body and then change the trading behavior. Smart contracts need to have the ability to dynamically adjust the trading rules, such as adjusting the electricity price settlement method according to the subsidy policy. For the second proposition, with the increase in distributed energy access and the exponential growth of the number of transactions, the processing speed and storage capacity of the current blockchain technology are challenged, and new consensus algorithms and data storage architectures need to be researched to solve these problems.
9.3. Research Significance
This study theoretically improves the application framework of blockchain smart contracts in the field of distributed power trading. The proposed transaction model and performance optimization strategy considering multiple factors enrich the theoretical system in this field. They provide new perspectives and methods for subsequent research and help to promote the theoretical development of the deep integration of blockchain technology and the electricity market. At the same time, through in-depth analysis of the interaction between policies and the behavior of market players, it provides a theoretical basis for policymakers to formulate more scientific and reasonable power market policies and promote the sustainable development of the power industry.
9.4. Implications for Practice
In the practice of electric power trading, the results of this research have multifaceted application value. From the perspective of transaction process optimization, the transaction mechanism based on blockchain smart contracts can realize automated execution and real-time settlement of transactions, reduce intermediate links and human intervention, improve transaction efficiency, and reduce transaction costs. For example, in the scenario of the direct transaction between distributed power supply and users, smart contracts can automatically complete the transaction based on preset conditions, such as power quantity and electricity price, without the need for a cumbersome manual reconciliation and settlement process.
In terms of market supervision, the non-tampering characteristics of blockchain and the transparency of smart contracts help regulators monitor transaction data in real time, detect abnormal market behavior in a timely manner, and maintain market order. For example, when there is price manipulation or power fraud and other violations, the regulator can trace the transaction history through the blockchain, quickly lock the offending subject, and impose the corresponding punishment.
From the perspective of energy resource allocation, the distributed power trading mechanism can promote the consumption of distributed energy and improve energy utilization efficiency. Smart contracts can reasonably allocate power resources according to the energy supply and demand in different regions, reducing energy waste. For example, in renewable energy-rich areas, smart contracts can prioritize the delivery of excess renewable energy to energy-short areas to achieve the optimal allocation of energy.
In addition, for electric power enterprises, the results of this research can help them innovate their business models. Enterprises can carry out the construction of distributed power trading platforms based on blockchain smart contracts to expand market share and enhance competitiveness. They can also optimize their energy procurement structure and reduce costs by participating in distributed power trading, achieving a win–win situation in terms of economic and environmental benefits.
9.5. Bottlenecks and Breakthroughs
There are some limitations to this study. The main ones are as follows:
Performance bottleneck: The test environment only simulates a seven-node transaction network (
Table 4). When the node size increases to the 10
3 level, the PoW consensus delay (8.7 s/block on average) may lead to a decrease in the timeliness of matching, and a sharding or hierarchical verification mechanism needs to be explored.
Physical constraint simplification: The impact of distribution network tidal current constraints and line blocking on transaction feasibility is not considered. In the future, an on-chain security verification module for coupled grid topologies can be developed in conjunction with the PTDF matrix.
Incentive compatibility: The deviation cost is set statically (α = 0.14 in Equation (12)), and the feedback mechanism of the market supply and demand status is not established. A dynamic pricing model based on deep reinforcement learning needs to be studied to make the penalty self-adaptive to the market risk level. In terms of security, although blockchain technology itself has a certain degree of security, electricity transactions involve a large amount of sensitive information, such as user privacy and corporate trade secrets, and still face risks such as cyber attacks and data leakage. Smart contracts may also have loopholes, which will pose a serious threat to transaction security once they are maliciously utilized.
The future research direction can be carried out in the following aspects: first, further research on new blockchain consensus algorithms and layered architecture technology to improve the scalability and processing efficiency of the system and reduce energy consumption; second, strengthen the research on blockchain security technology, such as the optimization of encryption algorithms, the detection and repair of smart contract loopholes, etc., to protect the information security of power transactions; third, explore the application of cross-chain technology in distributed power transactions. The fourth is to explore the application of cross-chain technology in distributed power transactions, realize the interconnection and data sharing between different blockchain platforms, and promote the globalization of distributed power transactions. The fifth is to combine artificial intelligence technology, conduct in-depth analysis of power transaction data, realize intelligent prediction and decision-making support, and further optimize the allocation of power resources.
10. Conclusions
Focusing on the distributed power trading scenario, this study introduces blockchain technology and proposes a distributed power trading mechanism based on smart contracts. By designing a trading order matching strategy, constructing a credit risk management model using the entropy weight method and combining it with deviation cost, and writing smart contracts using the Solidity language, simulation analysis shows that the mechanism has significant advantages.
In terms of credit assessment, this study adopts the entropy weight method to synthesize multiple indicators, such as the contract completion rate and power deviation rate, which is more accurate than the previous method that relies only on a single indicator such as the contract completion rate. This comprehensive method can reflect the credit status of users more accurately.
In terms of order matching strategy, this study prioritizes “price, credit value and offer time”, which effectively protects the interests of credible users. Taking user 4 and user 5 in the simulation experiment as an example, user 4 has a higher credit value and completes the transaction with user 1 first under the same offer price, which increases the transaction revenue and incentivizes users to maintain good credit.
In terms of smart contract application, the smart contract in this study has complete functions covering user information updating, trade order quotation sorting, aggregation and cancellation, settlement, information query, etc., which ensures that the transaction is transparent, fair, and efficient, while the smart contract functions in previous studies are relatively imperfect or abbreviated in design.
In terms of security, this study adopts a hybrid architecture that combines PoW consensus and Merkle tree structure to effectively resist 51% of attacks and ensure data integrity. This is more secure than previous studies that rely on simple consensus mechanisms or centralized architectures.
Finally, at the economic level, the mechanism provides dynamic incentives. High-credit users receive a 15–20% revenue boost, and the exponential increase in deviation fees effectively constrains default behavior. In contrast, previous mechanisms either had no penalty mechanism or used a fixed percentage penalty with limited flexibility
In summary, compared with previous studies, the distributed power trading mechanism proposed in this study is more innovative and practical. It can be effectively applied to distributed power scenarios, reduce user violations, protect the economic interests of trading users, stimulate user trading enthusiasm, and promote the healthy development of the distributed power market.