Smart contract test method and device, equipment, storage medium and program product
By constructing a business knowledge graph and generating test scenarios and test cases, the problem of low automation and accuracy in smart contract testing was solved, achieving comprehensive coverage of the business logic of smart contracts and improving the accuracy and efficiency of testing.
Patent Information
- Application Number
- CN202511617509.5
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-11-06
- Publication Date
- 2026-02-10
AI Technical Summary
Existing smart contract testing has low levels of automation and accuracy, failing to fully cover complex business logic and regulatory rules, resulting in inaccurate test results and low efficiency.
By analyzing the development documentation, code comments, and business rules of smart contracts, a business knowledge graph is constructed to generate test scenarios and test cases covering interface interactions, code branches, business rules, and regulatory compliance. Entities and relationships between entities are extracted using a large language model, test strategies are optimized, test cases are executed, and accurate test results are generated.
It improves the automation and accuracy of smart contract testing, comprehensively covers the complete business logic of smart contracts, saves labor costs, generates real and accurate test results, and improves testing efficiency.
Smart Images

Figure CN121501657A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the fields of financial technology, blockchain technology, and artificial intelligence technology, and in particular to a smart contract testing method, apparatus, device, storage medium, and program product. Background Technology
[0002] Smart contracts are a core component of blockchain platforms, widely used in high-reliability scenarios such as financial transactions, supply chain management, digital identity verification, and asset custody. Smart contracts automatically execute pre-defined business logic and transaction rules, ensuring the immutability and transparency of contract terms. The complexity of smart contract code and the diversity of business logic necessitate rigorous testing and verification before deployment.
[0003] The automation level and accuracy of smart contract testing for related technologies are low. Summary of the Invention
[0004] This application provides a smart contract testing method, apparatus, device, storage medium, and program product to improve the automation level and accuracy of smart contract testing.
[0005] Firstly, this application provides a smart contract testing method, comprising: parsing the smart contract's development documentation, code comments, and business rules to obtain entities and relationships between entities; constructing a business knowledge graph based on the entities and relationships between entities, wherein the business knowledge graph represents the relationships between interfaces, code branches, business scenarios, business rules, and regulatory rules; generating test scenarios and corresponding test cases based on the business knowledge graph, wherein the test scenarios cover interface interactions, code branches, business rules, and regulatory compliance; and executing the test cases to obtain test results.
[0006] In one possible embodiment, the relationships between entities in the business knowledge graph have weights. The weights of the relationships between entities are calculated based on rule frequency, logical dependency, and business impact. Rule frequency represents the number of times the relationship between entities is declared in the development document. Logical dependency represents the pre-constraint relationship between entities. Business impact represents the impact of the relationship between entities on the business objective.
[0007] In one possible embodiment, generating test scenarios and corresponding test cases based on a business knowledge graph includes: extracting test elements based on the weights of relationships between entities in the business knowledge graph, wherein the test elements include relationships between entities with weights greater than a first threshold and their corresponding entities; determining test modes that match the test elements and determining corresponding test strategies based on the test modes, wherein the test modes are reusable test templates and the test modes are mapped to the test strategies, and the test strategies include interface compatibility strategies, full branch coverage strategies, business rule verification strategies, and regulatory compliance strategies; generating test scenarios based on the business knowledge graph and the test strategies; and generating test cases corresponding to the test scenarios.
[0008] In one possible embodiment, generating test scenarios based on the business knowledge graph and the test strategy includes: selecting features from the business knowledge graph that correspond to the interface compatibility strategy, the full branch coverage strategy, the business rule verification strategy, and the regulatory compliance strategy respectively through the dimension combination method, and combining them to generate the corresponding test scenarios.
[0009] In one possible embodiment, after generating test cases corresponding to the test scenario, the smart contract testing method further includes: determining the execution priority of the test cases according to priority rules. The execution priority order indicated by the priority rules from high to low is: test cases with prerequisite dependencies, test cases covering the target area, test cases covering the target process, and test cases not covering code branches. The target area includes exception handling logic indicated by business rules and regulatory rule constraints indicated by regulatory rules. The target process is determined according to the weight of the relationships between entities in the business knowledge graph.
[0010] In one possible embodiment, executing test cases and obtaining test results includes: generating input parameter types and boundary values for the interface based on the input parameter constraints of the interface and the relationships between business rules in the business knowledge graph, wherein the input parameter types include dependent and associated input parameter types, abnormal input parameter types, and normal and compliant input parameter types, and the boundary values include numerical boundaries, time boundaries, and business rule boundaries; and executing test cases according to their priority based on the input parameter types and boundary values of the interface to obtain test results.
[0011] In one possible embodiment, after executing test cases and obtaining test results, the smart contract testing method further includes: comparing the test results with the expected results to determine smart contract defects, which include at least one of the following: missing code branches, violation of business rules, violation of regulatory rules, or abnormal execution paths; generating a test report based on the smart contract defects; and adjusting and updating the test strategy and / or priority rules based on the test report.
[0012] In one possible embodiment, adjusting and updating the test strategy based on the test report includes: adjusting and updating the test strategy through reinforcement learning based on the test report.
[0013] Secondly, this application provides a smart contract testing device, comprising: a parsing module, a business knowledge graph construction module, a test case generation module, and a test case execution module. The parsing module is used to parse the smart contract's development documentation, code comments, and business rules to obtain entities and relationships between them. The business knowledge graph construction module is used to construct a business knowledge graph based on the entities and their relationships, representing the relationships between interfaces, code branches, business scenarios, business rules, and regulatory rules. The test case generation module is used to generate test scenarios and corresponding test cases based on the business knowledge graph, with the test scenarios covering interface interactions, code branches, business rules, and regulatory compliance. The test case execution module is used to execute the test cases and obtain test results.
[0014] Thirdly, this application provides an electronic device, including: a processor and a memory communicatively connected to the processor; the memory stores computer-executable instructions; the processor executes the computer-executable instructions stored in the memory to implement the method as described in any of the first aspects.
[0015] Fourthly, this application provides a computer-readable storage medium storing computer-executable instructions, which, when executed by a processor, are used to implement the method as described in any of the first aspects.
[0016] Fifthly, this application provides a computer program product, including a computer program that, when executed by a processor, implements the method of any one of the first aspects.
[0017] In this embodiment, the smart contract's development documentation, code comments, and business rules constitute the original development data of the smart contract, accurately reflecting its business logic. By parsing the smart contract's development documentation, code comments, and business rules, the server can extract valid information from the smart contract and thereby construct a business knowledge graph that closely reflects the business logic of the real smart contract. That is, the smart contract testing method in this embodiment can parse the complex business logic of the smart contract and, based on the correlation of the business logic, set the complex business logic of the smart contract into a business knowledge graph that reflects the correlation of the business logic, thus accurately representing the complex business logic of the smart contract.
[0018] In this embodiment, the server generates test scenarios and corresponding test cases based on a business knowledge graph. The test scenarios cover interface interaction, code branches, business scenarios, and regulatory compliance; these four dimensions together constitute the complete business logic of the smart contract. Therefore, test scenarios covering these four dimensions closely match the complete business logic of the smart contract. Consequently, the test cases can also accurately test the complete business logic of the smart contract, thereby improving the test completeness of the smart contract.
[0019] By executing test cases, the server can more realistically and accurately simulate the interface calls and code execution of smart contracts based on actual business logic. The generated test results can realistically and accurately reflect the actual performance of the smart contract. This improves the accuracy and efficiency of smart contract testing.
[0020] In addition, the smart contract testing method in this application embodiment is a fully automated smart contract testing process, from understanding requirements by analyzing development documents, code comments and business rules, to generating test cases and executing test cases, which can save manpower costs. Attached Figure Description
[0021] The accompanying drawings, which are incorporated in and form part of this specification, illustrate embodiments consistent with this application and, together with the description, serve to explain the principles of this application.
[0022] Figure 1 This is a schematic diagram illustrating the application of the smart contract testing method, apparatus, device, storage medium, and program product of this application in a financial scenario;
[0023] Figure 2 This is a flowchart of a smart contract testing method according to an embodiment of this application;
[0024] Figure 3 This is a flowchart of a smart contract testing method according to another embodiment of this application;
[0025] Figure 4 This is a schematic diagram of a smart contract testing device according to an embodiment of this application;
[0026] Figure 5 This is a schematic diagram of the structure of an electronic device according to an embodiment of this application.
[0027] The accompanying drawings have illustrated specific embodiments of this application, which will be described in more detail below. These drawings and descriptions are not intended to limit the scope of the concept in any way, but rather to illustrate the concept of this application to those skilled in the art through reference to specific embodiments. Detailed Implementation
[0028] Exemplary embodiments will now be described in detail, examples of which are illustrated in the accompanying drawings. When the following description relates to the drawings, unless otherwise indicated, the same numbers in different drawings denote the same or similar elements. The embodiments described in the following exemplary embodiments do not represent all embodiments consistent with this application. Rather, they are merely examples of apparatuses and methods consistent with some aspects of this application as detailed in the appended claims.
[0029] It should be noted that the user information (including but not limited to user device information, user personal information, etc.) and data (including but not limited to data used for analysis, data stored, data displayed, etc.) involved in this application are all information and data authorized by the user or fully authorized by all parties. Furthermore, the collection, storage, use, processing, transmission, provision, disclosure, and application of the relevant data all comply with the relevant laws, regulations, and standards of the relevant countries and regions, have taken necessary confidentiality measures, do not violate public order and good morals, and provide corresponding operation access points for users to choose to authorize or refuse.
[0030] It should be noted that the smart contract testing methods, devices, equipment, storage media, and program products provided in this application can be used in the fields of financial technology, blockchain technology, and artificial intelligence technology, as well as in any field other than financial technology, blockchain technology, and artificial intelligence technology. The application fields of the smart contract testing methods, devices, equipment, storage media, and program products in this application are not limited.
[0031] Figure 1 This is a schematic diagram illustrating the application of the smart contract testing method, apparatus, device, storage medium, and program product of this application in a financial scenario.
[0032] like Figure 1 As shown, a blockchain network in a financial scenario includes multiple server nodes ( Figure 3In the example (e.g., server node 1, server node 2, etc.), when a user initiates a transaction through the financial application 2 on terminal device 1, transaction information is generated. Terminal device 1 sends the transaction information to the blockchain network. If the transaction information invokes a smart contract, it is broadcast to the entire blockchain network. Each validator node in the blockchain network independently executes the smart contract code and calculates the transaction result. After each validator node completes its calculation, it votes or verifies its calculated result through the blockchain network's consensus mechanism. If the transaction results of more than a certain percentage of validator server nodes are consistent, the transaction result is considered valid and is packaged and written into a new block. After the transaction result is written into a new block, it is synchronized to the local ledgers of all server nodes in the blockchain network. The data in the local ledgers of each server node is consistent. Because the transaction result has been jointly verified by multiple validator nodes and synchronized to the local ledgers of all server nodes, the immutability and transparency of the transaction result are ensured.
[0033] Smart contracts are highly complex, involving multiple layers of business logic, exception handling, and regulatory compliance requirements. Any code defects or logical vulnerabilities could lead to huge financial losses or systemic risks. For example, in financial scenarios, smart contracts need to handle complex processes such as high-frequency trading, cross-border settlement, and risk control verification. Insufficient testing may lead to problems such as abnormal on-chain fund flows, permission bypassing, or contract freezes.
[0034] Therefore, smart contracts need to be tested and verified before deployment.
[0035] The following are some specific methods for testing smart contracts using related technologies, and their limitations:
[0036] (1) Script-based testing framework: simulates interface calls and parameter inputs through preset scripts, and relies on manual writing of test cases for smart contracts.
[0037] (2) Static analysis tools: These tools analyze the code logic of smart contracts through methods such as symbolic execution and model checking, but they cannot cover the behavior of smart contracts during dynamic runtime.
[0038] (3) Formal verification: Using mathematical methods to prove the correctness of smart contract code, but due to computational complexity, it is only applicable to simple smart contracts.
[0039] (4) Templated test case generation: Test scenarios are generated based on fixed templates, which are difficult to adapt to dynamic changes in interface parameters.
[0040] (5) Coverage-driven testing: It guides the supplementation of test cases by statistical code coverage, but it cannot actively identify uncovered deep branches (such as exception handling logic).
[0041] (6) Continuous Integration (CI) / Continuous Delivery (CD) Integration Regression Testing: Pre-set test suites are executed in the continuous integration process, but there is a lack of proactive detection capabilities for new vulnerabilities.
[0042] (7) Machine learning vulnerability detection: It identifies code defects based on historical vulnerability feature library, but has a low recognition rate for new attack patterns (such as reentrancy attack variants).
[0043] (8) Deep learning code auditing: It analyzes the code structure through neural networks, but cannot analyze the relationship between business logic and regulatory rules.
[0044] (9) Natural Language Processing-Assisted Testing: The requirements document is transformed into test cases, but it relies on manually annotated rule templates, which lacks flexibility.
[0045] In summary, the relevant technologies have at least one of the following drawbacks:
[0046] (1) Lack of business understanding: unable to parse the business rules and regulatory rules in the development documents, resulting in test cases being out of touch with actual requirements.
[0047] (2) Lack of autonomous evolution capability: It is unable to learn optimization strategies from historical tests and requires manual continuous maintenance of test cases.
[0048] (3) Fixed mode limitation: The test process is rigid and cannot adapt to the dynamic changes of interface parameters.
[0049] (4) Low efficiency of human-machine collaboration: Test results need to be interpreted manually and cannot provide intelligent improvement suggestions.
[0050] (5) Insufficient test coverage: Limited coverage of new consensus mechanisms and complex boundary conditions (such as multi-level nested exception handling).
[0051] The smart contract testing methods, apparatus, equipment, storage media, and program products provided in this application are intended to solve the above-mentioned technical problems of the prior art.
[0052] The technical solution of this application and how the technical solution of this application solves the above-mentioned technical problems are described in detail below with specific embodiments. These specific embodiments can be combined with each other, and the same or similar concepts or processes may not be described again in some embodiments. The embodiments of this application will now be described with reference to the accompanying drawings.
[0053] Figure 2This is a flowchart illustrating a smart contract testing method according to an embodiment of this application. The smart contract testing method can be executed by a server, specifically by a smart agent deployed on the server. The smart contract testing method includes steps S110 to S140.
[0054] S110. Analyze the smart contract's development documentation, code comments, and business rules to obtain the entities and the relationships between them.
[0055] For example, before step S110, the smart contract tester submits a smart contract testing task through a human-machine interface, indicating the identifier of the smart contract to be tested. The server requests the smart contract's development documentation, code comments, and business rules based on the smart contract's identifier, and then executes step S110.
[0056] The development documentation can be understood as a systematic description of the overall design, functionality, interaction methods, and deployment requirements of smart contracts. It includes the business scenarios supported by the smart contract, the triggering conditions for each scenario, and related process steps. The development documentation also includes regulatory rules.
[0057] Code comments, embedded within the smart contract's code, explain the specific implementation details of the smart contract, improving its readability and maintainability. Code branches are accessible through code comments and development documentation.
[0058] Business rules can be understood as the business logic and rules carried by smart contracts. They are the core basis for code implementation and determine how smart contracts process data, respond to interactions, and update states.
[0059] For example, since development documentation, code comments, and business rules are in text format, natural language processing (such as large language models) can be used to parse these documents. Specifically, the named entity recognition and entity linking technologies of large language models can be used to parse the entities in the development documentation, code comments, and business rules. The relation extraction capabilities of large language models can then be used to parse the relationships between entities.
[0060] Large language models have advantages such as being able to process large amounts of text and accurately capture explicit and implicit information in the text. Therefore, large language models can be used to deeply analyze development documents, code comments and business rules, and accurately and quickly extract entities and relationships between entities.
[0061] Understandably, the development documentation includes text indicating interface definitions and business scenarios. Code comments indicate code branches, etc. Business rules include text indicating regulatory rules under the business scenarios. Parsing the smart contract's development documentation, code comments, and business rules yields the entities and relationships between them.
[0062] The following will specifically illustrate some entities: entities related to interfaces (such as interfaces, input parameters, and output parameters), entities related to code branches (such as code branches, functions, and database operations), entities related to business scenarios (such as transfer scenarios and recharge scenarios), entities related to business rules (such as transaction amount verification rules and whitelist matching rules), and entities related to regulatory rules (such as audit log retention requirements and single transaction limit requirements).
[0063] The following will illustrate some relationships between entities: the interface contains input parameters; the output parameters trigger code branches, the code branches call functions, the function execution triggers database operations, business scenarios must follow business rules, and business scenarios must comply with regulatory rules.
[0064] S120. Construct a business knowledge graph based on entities and the relationships between entities.
[0065] A business knowledge graph represents the relationships between interfaces, code branches, business scenarios, business rules, and regulatory rules.
[0066] Entities can serve as nodes in a knowledge graph, and relationships between entities can serve as directed edges in the knowledge graph, thereby constructing a business knowledge graph. A business knowledge graph represents the relationships between interfaces, code branches, business scenarios, business rules, and regulatory rules.
[0067] S130. Generate test scenarios and corresponding test cases based on business knowledge graphs.
[0068] The test scenarios cover interface interaction, code branching, business rules, and regulatory compliance.
[0069] Interface interaction, code branches, business scenarios, and regulatory compliance—these four dimensions together constitute the complete business logic of a smart contract. Therefore, in this embodiment, generating test scenarios covering these four dimensions based on a business knowledge graph aligns well with the complete business logic of the smart contract. Furthermore, by generating test cases corresponding to the test scenarios based on the business knowledge graph, these test cases can also accurately test the complete business logic of the smart contract, thereby improving the testing completeness of the smart contract.
[0070] S140. Execute the test cases and obtain the test results.
[0071] The test cases obtained in step S130 are matched with the actual business logic. By executing the test cases, the interface calls and code execution of the smart contract can be simulated based on the actual business logic. The test results obtained by executing the test cases can be used to determine whether the functionality of the smart contract meets expectations, and whether there are any vulnerabilities or anomalies.
[0072] For example, executing test cases and obtaining test results may include: sending the input parameters of the interface defined in the test cases to the server where the smart contract is deployed according to the interface format through an interface invocation tool, triggering the execution of the smart contract; simultaneously, obtaining the database operations after the smart contract execution in real time through a database connection tool, and integrating the database operation records and the smart contract execution log to obtain the test results. The interface invocation tool includes a Software Development Kit (SDK), and the interface format is, for example, a message format or JSON (JavaScript Object Notation) format. JSON is a lightweight data exchange format that can be used for interface data transmission.
[0073] In this embodiment, the smart contract's development documentation, code comments, and business rules constitute the original development data of the smart contract, accurately reflecting its business logic. By parsing the smart contract's development documentation, code comments, and business rules, the server can extract valid information from the smart contract and thereby construct a business knowledge graph that closely reflects the business logic of the real smart contract. That is, the smart contract testing method in this embodiment can parse the complex business logic of the smart contract and, based on the correlation of the business logic, set the complex business logic of the smart contract into a business knowledge graph that reflects the correlation of the business logic, thus accurately representing the complex business logic of the smart contract.
[0074] In this embodiment, the server generates test scenarios and corresponding test cases based on a business knowledge graph. The test scenarios cover interface interaction, code branches, business scenarios, and regulatory compliance; these four dimensions together constitute the complete business logic of the smart contract. Therefore, test scenarios covering these four dimensions closely match the complete business logic of the smart contract. Consequently, the test cases can also accurately test the complete business logic of the smart contract, thereby improving the test completeness of the smart contract.
[0075] In this embodiment, the server, by executing test cases, can more realistically and accurately simulate the interface calls and code execution of smart contracts based on actual business logic. The generated test results can realistically and accurately reflect the actual performance of the smart contract. This improves the accuracy and efficiency of smart contract testing.
[0076] In addition, the smart contract testing method in this application embodiment is a fully automated smart contract testing process, from understanding requirements by analyzing development documents, code comments and business rules, to generating test cases and executing test cases, which can save manpower costs.
[0077] In real-world scenarios, the relationships between entities in a business knowledge graph vary in strength. In one embodiment of this application, the weights of the relationships between entities in the business knowledge graph can represent the differences in the strength of these relationships, thereby enabling accurate modeling of the complex relationships within smart contracts using the business knowledge graph.
[0078] Specifically, the relationships between entities in the business knowledge graph have weights, which are calculated based on rule frequency, logical dependencies, and business impact.
[0079] Rule frequency represents the number of times an entity relationship is declared in the development documentation. The number of declarations can be understood as the number of times the entity relationship is mentioned in the documentation. Rule frequency reflects the standardization of entity relationships within the development documentation. A first weight can be calculated from the rule frequency. The first weight is determined based on the mapping relationship between rule frequency and weight, which can be pre-set and maintained.
[0080] Logical dependency indicates that the relationship between entities has a pre-existing constraint. Logical dependency reflects the necessity of the technical link in the relationship between entities. A second weight can be calculated from logical dependency. For example, the weights of logically dependent and non-logically dependent relationships between entities can be preset.
[0081] Business impact represents the influence of inter-entity relationships on business objectives. It reflects the risks associated with these relationships and the resulting business objectives. A third weight can be calculated based on business impact. Business objectives include: financial security, compliance, and business process integrity. For example, the third weight can be determined based on the risk level of the business objective; higher risk levels for financial security and compliance result in a higher third weight than the third weight corresponding to business process integrity.
[0082] For example, the first weight, the second weight, and the third weight are normalized, and the weighted sum of the normalized first weight, second weight, and third weight can be used as the weight of the relationship between entities. The weight allocation used in the weighted sum of the first weight, second weight, and third weight can be preset as needed.
[0083] In one possible embodiment, the server can also perform consistency checks and corrections on the business knowledge graph. For example, if the server performs a consistency check on the business knowledge graph and finds contradictory entity relationships, it can re-extract the entity relationships and recalculate their weights. Alternatively, the server can derive entity relationships from the business knowledge graph. If the server derives new entity relationships, it can also calculate the weights of the new relationships and add them to the business knowledge graph to update it.
[0084] Figure 3 This is a flowchart illustrating a smart contract testing method according to another embodiment of this application. Figure 3 As shown, step S130, which generates test scenarios and corresponding test cases based on business knowledge graphs, may include steps S131 to S134.
[0085] S131. Extract test elements based on the weights of relationships between entities in the business knowledge graph.
[0086] The test elements include the relationships between entities with weights greater than the first threshold and the corresponding entities.
[0087] Step S131 involves extracting entity relationships with weights greater than the first threshold and their corresponding entities from the business knowledge graph as test elements.
[0088] The weights of relationships between entities in the business knowledge graph indicate their importance for testing smart contracts. By leveraging these weights, more critical test elements can be extracted. For example, test elements might include: the transfer interface contains an "amount" field; the conversion interface can trigger a risk control code branch; and executing the risk control code branch requires performing an abnormal transaction compliance check.
[0089] For example, after extracting the test elements, the following steps can be performed sequentially: matching test objectives to the test elements, planning test steps, and allocating test resources. Taking the test elements as follows: the transfer interface contains an `amount` field, the `amount` field can trigger a risk control code branch, and executing the risk control code branch requires performing abnormal transaction compliance verification. The corresponding test objectives include: verifying that the `amount` field triggers all code branches, and verifying that abnormal transaction compliance is effective in cross-border scenarios. Planning test steps breaks down the test objectives into test steps, which may include, for example: preparation before calling the transfer interface, constructing the input parameters of the transfer interface, calling the transfer interface, and result verification. Allocating test resources may include, for example, specifying a test environment (such as a server node for testing smart contracts) and test tools (such as a software development kit for interface calls).
[0090] S132. Determine the test mode that matches the test elements based on the test elements, and determine the corresponding test strategy based on the test mode.
[0091] The test mode is a reusable test template, and the test mode is mapped to the test strategy. The test strategy includes interface compatibility strategy, full branch coverage strategy, business rule verification strategy, and regulatory compliance strategy.
[0092] Test modes include code branch coverage mode, interface interaction mode, boundary test mode, and exception injection mode.
[0093] The code branch coverage mode is a template for designing test cases for different code branches.
[0094] The interface interaction mode is a test case design template adapted to different interface types.
[0095] Boundary testing mode is a template for designing test cases for various boundary scenarios.
[0096] The exception injection pattern is a test case design template that simulates abnormal input parameters.
[0097] For example, test patterns can be stored in a knowledge base, which is maintained by relevant personnel.
[0098] For example, a test pattern has function labels that indicate the object and relationship type. The function labels are matched against the object and relationship type of the test element, and the corresponding test pattern is matched based on the degree of match.
[0099] For example, the functional label indicators for the branch coverage mode include code branches and interface fields, and the relationship types include condition triggering; the functional label indicators for the interface interaction mode include interface fields and parameter formats, and the relationship types include format constraints; the functional label indicators for the boundary test mode include numerical fields, time fields, and threshold rules, and the relationship types include critical value triggering; the functional label indicators for the exception injection mode include interface parameters and business dependencies, and the relationship types include exception conditions.
[0100] The interface compatibility strategy instructs the generation of test cases to verify the interface's compatibility with diverse input parameter formats, taking into account the dynamic characteristics of the interface's input and output parameters. For example, the interface's input parameters may include scenarios with missing non-required fields or fields of abnormal types.
[0101] The full branch coverage strategy instructs the generation of test cases that cover all code branches based on the association between code branches and input parameter fields. For example, code branches include normal branches, exception branches, nested branches, loop branches, boundary branches, etc.
[0102] The business rule validation strategy instructs the generation of test cases to verify the validity of business rules, based on the interaction logic between business rules and interfaces.
[0103] The regulatory compliance strategy instructs on generating test cases to verify compliance with regulatory rules relevant to business scenarios.
[0104] To illustrate with a concrete example: both code branch coverage mode and full branch coverage strategy aim to cover code branches, therefore code branch coverage mode matches full branch coverage strategy; by simulating calls to different interfaces through interface interaction mode, the compatibility of interfaces with diverse input parameter formats can be verified, therefore interface interaction mode matches interface compatibility strategy; boundary testing mode indicates testing various boundary scenarios, while full branch coverage strategy indicates covering all code branches, including boundary branches, therefore boundary testing mode matches full branch coverage strategy; in addition, regulatory compliance strategy indicates verifying compliance, and in boundary scenarios, compliance is constrained by threshold values, therefore boundary testing mode also matches regulatory compliance strategy.
[0105] S133. Generate test scenarios based on the business knowledge graph and test strategy.
[0106] For example, step S133 may include: selecting features from the business knowledge graph that correspond to the interface compatibility strategy, full branch coverage strategy, business rule verification strategy, and regulatory compliance strategy respectively through the dimension combination method, and combining them to generate corresponding test scenarios.
[0107] When features are selected from the business knowledge graph and combined to generate corresponding test scenarios using the dimensional combination method, the test scenarios also satisfy the constraints of the business knowledge graph.
[0108] It is understandable that the business knowledge graph includes multi-dimensional entities and relationships corresponding to interface compatibility strategies, full branch coverage strategies, business rule verification strategies, and regulatory compliance strategies. Specifically, it may include entities and relationships related to the interface interaction dimension, entities and relationships related to the code branch dimension, entities and relationships related to the business rule dimension, and entities and relationships related to the regulatory rule dimension.
[0109] Entities and relationships between entities related to the interface interaction dimension can be used as features of the interface interaction dimension; entities and relationships between entities related to the code branch dimension can be used as features of the code branch dimension; entities and relationships between entities related to the business rule dimension can be used as features of the business rule dimension; and entities and relationships between entities related to the regulatory rule dimension can be used as features of the regulatory compliance dimension.
[0110] The interface interaction dimension corresponds to the interface compatibility strategy, which can focus on the characteristics of the interface's input and output parameters, such as features including standard JSON format, dynamic fields, abnormal field types, and missing non-required fields.
[0111] The code branch dimension corresponds to the full branch coverage strategy, and can focus on code branch coverage, such as normal branches, abnormal branches (such as parameter out of bounds), nested branches (such as nested if-else statements), and loop branches (such as batch transfers).
[0112] The business rule dimensions correspond to the business rule verification strategies, which can focus on actual business processes, such as features including ordinary transfers, cross-border transfers, pledge financing, and redemption operations.
[0113] Regulatory compliance dimensions correspond to regulatory compliance strategies and can focus on compliance verification, such as characteristics including compliance with regulatory rules, compliance with thresholds, and violations of regulatory rules.
[0114] The dimensional combination method can be understood as a method of obtaining a feature for each dimension and combining them based on the features of each dimension.
[0115] The dimensional combination method involves iterating through features from each of the four dimensions—interface interaction, code branching, business rules, and regulatory compliance—to generate test scenarios covering all four dimensions. Within each test scenario, complete test cases are formed based on the combination of features from each dimension. The completeness of the test cases is reflected in their coverage of the business logic related to the corresponding interface interaction, code branching, business rules, and regulatory rules for that test scenario.
[0116] For example, test scenarios generated by the dimension combination method may include: the input parameters of the interface contain dynamic fields, which will trigger the risk control code branch, which belongs to cross-border transfer and complies with the abnormal transaction compliance rules.
[0117] In this embodiment, the entities and relationships between entities in the business knowledge graph provide business logic that closely aligns with real-world smart contracts. Based on real-world application scenarios, issues such as dynamic interface parameters, incomplete code branch coverage, deviation from business rules, and neglect of regulatory rules in smart contracts are addressed. The design specifically focuses on four dimensions within the business knowledge graph: interface interaction, code branches, business rules, and regulatory rules. A dimensional combination method is used to generate test scenarios covering these four dimensions. This method can traverse every feature within each dimension, resulting in test scenarios that cover all dimensions. These combinations form complete test cases.
[0118] S134. Generate test cases corresponding to the test scenario.
[0119] For example, for any test scenario, corresponding test cases are generated based on the interface's input parameters, execution steps, and expected results.
[0120] In this embodiment, by extracting test elements based on the weights of relationships between entities in the business knowledge graph, the more important test parts of the smart contract can be filtered by weight, ensuring that subsequent test resources are prioritized for the core logic that has the greatest impact on business objectives, security risks, and compliance, and avoiding wasting test resources in low-weight edge scenarios (such as the format of the remarks field).
[0121] In this embodiment, test elements provide the testing focus for the smart contract. By determining test modes that match the test elements and corresponding test strategies based on the test modes, the testing focus of the smart contract can be accurately matched with the corresponding test modes and strategies. By generating test scenarios that cover interface interactions, code branches, business rules, and regulatory compliance based on the business knowledge graph and test strategies, it can be ensured that the test scenarios closely match the complete business logic of the smart contract. Subsequently, test cases corresponding to the test scenarios can be generated for comprehensive testing of the smart contract.
[0122] like Figure 3 As shown, in one possible embodiment, after generating test cases corresponding to the test scenario in step S134, the smart contract testing method may further include: determining the priority of the test cases according to priority rules.
[0123] Priority rules are associated with at least one of the following: the weight of relationships between entities in the business knowledge graph, the exception handling logic indicated by business rules, and the regulatory rule constraints indicated by regulatory rules.
[0124] The priority rules indicate the following order of priority from highest to lowest: test cases with prerequisite dependencies, test cases covering the target area, test cases covering the target process, and test cases not covering code branches.
[0125] The target area includes the exception handling logic indicated by business rules and the regulatory rule constraints indicated by regulatory rules. The target process is determined based on the weight of the relationships between entities in the business knowledge graph.
[0126] For example, if test case A and test case B have a prerequisite dependency that test case B's execution requires test case A to complete, then test case A has a higher priority than test case B. This ensures the correct execution of test cases and avoids invalid tests caused by incorrect execution order.
[0127] Test cases without prerequisite dependencies are executed in the following order of priority: test cases covering the target area, test cases covering the target process, and test cases not covering the code branch.
[0128] The target area includes the exception handling logic indicated by business rules and the regulatory constraints indicated by regulatory rules. Test cases covering the target area can be understood as high-risk test cases. Due to the on-chain characteristics of smart contracts (such as irreversibility and asset-related characteristics), high-risk smart contracts can cause serious losses. In this embodiment, the execution priority of test cases covering the target area is set higher. This allows high-risk test cases to be executed first when testing resources are limited, enabling timely detection and repair of high risks in smart contracts.
[0129] For test cases covering the target process, the target process is determined based on the weights of relationships between entities in the business knowledge graph. For example, the target process is determined by relationships between entities in the business knowledge graph whose weights are greater than a second threshold, making the target process the core business process of the smart contract. In this embodiment, by setting a higher execution priority for test cases covering the target process, test cases covering the target process can be executed first when test resources are limited, ensuring that the smart contract achieves its business objectives.
[0130] Smart contracts have complex business logic, typically involving multiple and intricate code branches, including deeply nested branches. Uncovered code branches may harbor hidden vulnerabilities (such as a non-nested branch lacking permission checks, allowing for malicious calls), and these vulnerabilities are easily overlooked in conventional testing. In this embodiment, based on the requirement of full branch coverage, by setting a higher execution priority for test cases on uncovered code branches, test cases on uncovered code branches can be executed first when testing resources are limited, thereby reducing code branch blind spots.
[0131] In one possible implementation, the priority rule may also indicate that the execution priority of test cases with historical failures follows that of test cases that do not cover code branches.
[0132] Historical failures of smart contracts are often recurring. In this embodiment, by setting the execution priority of test cases with historical failures, the testing of historical failures can be strengthened in a targeted manner, reducing the probability of the same historical failures recurring.
[0133] In one possible embodiment, the execution of test cases in step S140 to obtain test results may include: generating input parameter types and boundary values for the interface based on the input parameter constraints of the interface and the relationships between business rules in the business knowledge graph, wherein the input parameter types include dependent and associated input parameter types, abnormal input parameter types, and normal and compliant input parameter types, and the boundary values include numerical boundaries, time boundaries, and business rule boundaries; and executing test cases according to the input parameter types and boundary values of the interface and the priority of the test cases to obtain test results.
[0134] Test cases are used to simulate smart contract interface calls, where the interface includes input parameters. The input parameters of the interface are the most basic entry point for smart contract interaction. In this embodiment, the interface's input parameters and boundary values can be dynamically generated, and real input parameters can be simulated based on the interface's input parameter types and boundary values.
[0135] For example, based on the numerical constraints, format rules, and dependency relationships of interface-related entities in the business knowledge graph, the numerical range, correct format, and dependency relationships of the interface's input parameters can be obtained. The numerical range determines the numerical boundaries, and the correct format determines the date boundaries. Based on the business rule-related entities in the business knowledge graph, the business rule boundaries of the interface's input parameters can be obtained.
[0136] The input parameter types of an interface can be categorized into dependent and related input parameter types, abnormal format input parameter types, and normal and compliant input parameter types.
[0137] Dependency-related input parameter types can be understood as input parameters with dependent relationships. For example, dependency-related input parameter types include input parameter types that need to be associated with historical data (such as "cumulative transfers of 490,000 today, current transfer of 20,000", triggering daily limit verification) and input parameter types that need to be associated with the current state (such as "the contract has expired, but a transaction is still initiated", testing the interface response in the expired state).
[0138] Normal and compliant input parameter types can be understood as input parameters that conform to regulations. For example, the specific value of a numeric input parameter conforms to the normal value range. For instance, for a numeric input parameter of a single transaction, if the value of a single transaction is within the range of a single transaction, then it is a normal and compliant input parameter type. Similarly, the specific time of a time-type input parameter conforms to time requirements, and the specific format of a format-type input parameter conforms to format requirements.
[0139] For example, normal and compliant input parameters can be generated based on the interface definitions and corresponding business rule constraints in the business knowledge graph.
[0140] Abnormal format input parameter types can be understood as input parameters that do not conform to the regulations, such as input parameters with abnormal time formats or input parameters with abnormal numerical formats.
[0141] Boundary values can be understood as the criteria for determining whether an input parameter is a normal, compliant input parameter type or an abnormal format input parameter type. Boundary values can include boundary values for normal, compliant input parameter types and boundary values for abnormal format input parameter types.
[0142] For example, if the input parameter of the interface is the cumulative transfer value for the day, and the normal and compliant range of the cumulative transfer value for the day is less than or equal to 500,000, and the transfer value is in units of 1, the boundary values may include 500,000 and 500,001. In this case, the boundary value of 500,000 is a normal and compliant input parameter type, and the boundary value of 500,001 is an abnormal format input parameter type.
[0143] Table 1 below will illustrate some input parameter types and boundary values, as well as the impact of executing test cases based on these input parameter types and boundary values on the test execution process and on the test results.
[0144] Table 1
[0145] Input conditions / boundary cases Impact on the execution process Impact on test results Normal and compliant input (single transfer of 50,000, time: 2025-09-10) Perform a normal transfer branch, skipping limit verification and expiration checks. The API returned "success", the database added a new transaction record (status = success), and the balance was reduced by 50,000. Input with incorrect format (time is 2025 / 09 / 10, separated by " / ") Trigger the parameter format validation branch and terminate subsequent business logic. The API returned "incorrect time format", the database has no record, and the balance remains unchanged. Numerical boundary (just met the limit) (single transfer of 100,000, not exceeding the limit) Normal transfer branch executed, limit verification passed. The API returned "success," the database recorded the transaction amount as 100,000, and the balance was correctly deducted. Numerical boundary (exceeding the limit) (single transfer of 101,000) Triggering the limit verification branch, the transfer is refused. The API returned "Exceeded single transaction limit", the database has no record, and the balance remains unchanged. Time Boundary (Last moment of validity) (2025-09-30 23:59:59) Once the validity period check is passed, proceed with the normal transfer process. The API returned "success", and the database recorded the transaction time as the threshold. Time Boundary (First Moment After Expiration) (2025-10-01 00:00:00) Triggering a branch indicating expiration verification failure terminates the transaction. The API returned "Contract expired", and there was no record in the database. Business rule boundaries (frequency limit) (3rd transaction per second) The normal transaction process was executed, and the frequency verification passed. The API returned "success", and the transaction record was generated normally. Business rule boundary (frequency exceeded) (4 transactions per second) Triggering rate limiting branch, refusing to process. The API returned "Transaction frequency exceeded, please try again later," and there was no database record.
[0146] In this embodiment, corresponding input parameter types and boundary values are generated for the normal range, abnormal values, and boundary values of the interface's input parameters. Test cases are then executed based on the input parameter types and boundary values. This ensures that the test cases cover normal, abnormal, and boundary scenarios for the interface's input parameters, avoiding omissions or incomplete boundary coverage. In particular, boundary scenarios often contain logical vulnerabilities; this embodiment verifies boundary scenarios to ensure higher accuracy and stability of smart contracts when handling them.
[0147] like Figure 2 As shown, in one possible embodiment, after executing the test case in step S140 and obtaining the test result, the smart contract testing method may further include steps S150 to S170.
[0148] S150. Compare the test results with the expected results to identify smart contract defects. Smart contract defects include at least one of the following: missing code branch, violation of business rules, violation of regulatory rules, or abnormal execution path.
[0149] The expected result can be understood as a predefined standard used to determine whether the smart contract's functionality meets requirements before the test cases are executed. For example, development documentation and other data may include text indicating the logic of the expected result. Therefore, a business knowledge graph built based on this data also indicates the expected result. The expected result can be obtained by extracting the relevant entities and relationships between them from the business knowledge graph. Alternatively, the expected result can be designed by relevant personnel.
[0150] The following will illustrate the flaws of smart contracts and provide some specific examples:
[0151] Missing code branches, such as a code block under an if condition that is never executed.
[0152] Errors in parameter processing, such as incorrect balance deduction calculations, resulting in over- or under-deduction.
[0153] Error handling is missing; for example, no error message is displayed when the input is empty.
[0154] Violations of business rules may include: failure of limit verification, incorrect process sequence, and abnormal status synchronization.
[0155] The limit verification failed; transfers exceeding 100,000 yuan are still allowed.
[0156] The process sequence is incorrect; for example, the transfer is executed directly in the contract signing instance.
[0157] The state synchronization is abnormal. For example, when multiple tables are involved, table A is updated but table B is not updated.
[0158] Violations of regulatory rules may include: missing audit logs and failure to perform identity verification.
[0159] Audit logs are missing, such as the lack of records on the source of funds for transfers.
[0160] Identity verification was not performed, such as upgrading the wallet type from anonymous wallet to real-name wallet without real-name authentication.
[0161] The aforementioned smart contract defects can be categorized into two types: Category 1 smart contract defects, which are inherent flaws in the smart contract's functionality, business rules, or compliance. Category 2 smart contract defects are further illustrated below. Category 2 defects are recurring anomalies or patterns exhibited by the smart contract in specific scenarios, typically related to scenario characteristics such as input, execution path, timing, or resources.
[0162] Input parameter association anomalies include: failure of input parameters in a specific format, and boundary value triggering inconsistency errors.
[0163] Input parameters in specific formats, such as address formats containing "-", will cause the interface to report an error.
[0164] Boundary values trigger consistency errors; for example, if a transaction of 99,999 yuan is successful, a transaction of 100,000 yuan will definitely return a timeout.
[0165] Execution path anomalies include disordered branch jumps and missing service function calls.
[0166] The code branch jumps are disordered. For example, an input that should trigger code branch 1 may randomly jump to code branch 2 or code branch 3.
[0167] Timing / frequency anomalies include inconsistent data during high-frequency calls and abnormal behavior at expired time points.
[0168] Inconsistent data from frequent calls, such as more than 5 calls per second, will inevitably lead to errors in balance calculation.
[0169] Abnormal behavior at the expiration date, such as allowing transactions after the contract has expired.
[0170] Resource association anomalies include database operation failures and functional degradation under high resource consumption.
[0171] Database operations may fail, such as a successful transfer that is not recorded in the database, resulting in an inflated balance.
[0172] Functional degradation under high resource consumption, such as when CPU utilization exceeds 80%, the quota verification function fails.
[0173] In one possible embodiment, the above-mentioned comparison of test results with expected results to determine smart contract defects may include: comparing the execution results of test cases (such as parameter changes, error messages) with expected results and marking inconsistencies; combining the execution path records of test cases to determine whether inconsistencies are triggered by abnormal code branches; identifying recurring failure scenarios through clustering algorithms to determine a second category of smart contract defects; and verifying whether the test results violate business rules or regulatory rules to determine a first category of smart contract defects.
[0174] In one possible embodiment, the server can also integrate the test results and smart contract defects into a test report and output the test report.
[0175] S160. Generate a test report based on smart contract defects.
[0176] For example, the server can perform statistical processing on smart contract defects to generate a test report.
[0177] S170. Adjust and update the test strategy and / or priority rules based on the test report.
[0178] For example, if the test case coverage for a particular smart contract defect is low, the testing strategy can be adjusted to generate more test cases for variations of that particular smart contract defect.
[0179] For example, if a test report shows that the cost of fixing a particular smart contract defect is high, the priority rules can be adjusted so that test cases covering that particular smart contract have a higher execution priority.
[0180] For example, if test cases for a particular smart contract defect repeatedly fail, the priority rules are adjusted so that test cases covering that particular smart contract have a higher execution priority.
[0181] In one possible embodiment, when the test report is viewed manually and feedback is obtained manually, step S170, which involves adjusting and updating the test strategy and / or priority rules based on the test report, may include: adjusting and updating the test strategy and / or priority rules based on the test report and the feedback results.
[0182] Among these, adjusting and updating test strategies and / or priority rules based on human feedback has higher priority. In the event of a conflict between the human feedback and the test report's adjustments and updates to test strategies and / or priority rules, the human feedback shall prevail.
[0183] It should be noted that in the embodiments of this application, the test strategy and / or priority rules can be dynamically updated, and the test strategy and / or priority rules used by the currently executed smart contract test method are all the latest updated test strategies and / or priority rules.
[0184] In this embodiment, smart contract defects are identified by comparing test results with expected results, thus enabling precise identification of smart contract defects. Generating test reports based on these defects quantifies the risks of the smart contract, providing a traceable basis for subsequent decision-making. Adjusting and updating test strategies and / or priority rules based on the test reports allows for dynamic adjustment of the smart contract's testing strategies and / or priority rules, thereby improving testing effectiveness.
[0185] In one possible embodiment, step S170, adjusting and updating the test strategy based on the test report, may include: adjusting and updating the test strategy through reinforcement learning based on the test report.
[0186] Reinforcement learning (RL) is a self-learning strategy optimization method. In this embodiment, the testing strategy can be adjusted and updated using reinforcement learning.
[0187] Reinforcement learning optimizes strategies through interactions between agents, the environment, and rewards. Specifically, agents generate test strategies, and the environment includes the current state of the smart contract (e.g., code branches, business rules, regulatory rules) and historical test reports. Actions include adjustments to interface compatibility strategies, full branch coverage strategies, non-business rule verification strategies, and regulatory compliance strategies. For interface compatibility strategies, actions include increasing the proportion of test cases for "special character input" and "field length exceeding limits." For full branch compatibility strategies, actions include prioritizing the generation of test cases for nested branches and loop branches. For business rule verification strategies, actions include supplementing test cases for multi-account joint transfers to address timeliness of limit verification. For regulatory compliance strategies, actions include supplementing test cases covering audit log integrity and identity verification. Rewards measure the effectiveness of test strategy adjustments. Positive rewards may include the decrease in the number of smart contract defects after implementing the adjusted test strategy. Negative rewards may include the number of newly added smart contract defects after implementing the adjusted test strategy.
[0188] The agent generates test cases based on an initial test policy (with default values for the relevant parameters of the test policy), and generates a test report after executing the test cases. Rewards are calculated based on the test reports, and the test policy is adjusted and updated using a reinforcement learning algorithm (such as Q-learning) until the test policy converges.
[0189] In this embodiment of the application, reinforcement learning is used to achieve adaptive evolution of the testing strategy. Specifically, it can automatically perform smart contract defect analysis and test strategy adjustment, which is suitable for scenarios such as smart contracts with large code volume, complex code branches and changing rules.
[0190] In one possible embodiment, the server may store relevant data for smart contract testing through a knowledge base. For example, the knowledge in the knowledge base may include at least one of the following: historical business rules, interface definition templates, historical test patterns, historical smart contract defects, historical interface call cases, boundary value parameter examples, historical test reports, and historical test strategies.
[0191] The knowledge in the knowledge base can be updated, and the knowledge in the knowledge base can be used to provide experience for smart contract testing.
[0192] For example, historical business rules and interface definition templates can be used to assist in parsing development documentation and code comments. Historical test patterns and smart contract defects can be used to assist in adjusting priority rules and test strategies to generate test cases. Historical interface call examples and boundary value parameter examples can be used to assist in generating boundary values. Historical test reports and historical test strategies can be used to assist in reinforcement learning.
[0193] For example, knowledge retrieval from the knowledge base can be used to access interface definition templates, aiding in the identification of interface fields in development documentation and deriving their business meaning. Knowledge retrieval can also be used to access historical test patterns and, combined with the current business scenario, generate appropriate test strategies. Furthermore, knowledge retrieval can be used to access historical smart contract defects and deduce key test cases that need to be covered. Finally, knowledge retrieval can be used to perform feature matching between current and historical smart contract defects to determine whether they are known or novel smart contract defects.
[0194] In this embodiment of the application, by storing and updating relevant data for smart contract testing through a knowledge base, reusable experience can be provided for new smart contract testing, which can accurately assist in test strategy generation, boundary value generation, reinforcement learning feedback, etc., thereby improving the testing efficiency of smart contracts.
[0195] In one possible embodiment, the server can provide a human-computer interaction interface to support human participation in the smart contract testing process, thereby solving problems that arise during automated smart contract testing and improving the accuracy of smart contract testing.
[0196] For example, through a human-computer interaction interface, the server can receive test requirements input by the user, and then perform subsequent smart contract testing based on these requirements. Test requirements are user-defined requirements, which may include, for example, expected output requirements, such as generating a detailed database change report. Test requirements may also include test scope requirements, such as testing only the core process or covering all branches.
[0197] For example, users can handle smart contract defects through a human-computer interaction interface. Specifically, they can intervene in non-reproducible smart contract defects, smart contract defects that conflict with business rules, novel smart contract defects, smart contract defects involving compliance risks, and resource-dependent smart contract defects.
[0198] Non-reproducible smart contract defects include, for example, smart contract defects that fail once in 10 tests under the same input conditions and are unpredictable. The smart contract testing method in the embodiments of this application cannot pinpoint the root cause (which may involve network fluctuations, occasional inconsistencies in the smart contract state, etc.), and manual intervention is required to analyze the environment logs.
[0199] Defects in smart contracts that conflict with business rules include, for example, test results showing that a single transaction exceeding 100,000 can be transferred normally, but the business rules clearly limit the amount to 100,000. In this case, manual intervention can be used to confirm the accuracy of the business rules.
[0200] New types of smart contract defects include, for example, the state variables of a smart contract being abnormally reset after a nested branch is triggered, and the knowledge base cannot match this new type of smart contract defect.
[0201] Smart contract defects involving compliance risks include, for example, the failure to record audit logs for cross-border transfers, which may violate regulatory rules. The smart contract testing method used in this application's embodiments cannot determine whether a smart contract defect involving compliance risks is due to a test environment configuration issue or a code defect; manual intervention is required to verify the compliance boundaries.
[0202] Resource-dependent defects in smart contracts include, for example, frequent database connection interruptions during test case execution. The smart contract testing method in this application cannot independently repair resource problems and requires manual intervention to investigate environmental factors such as network and database configuration.
[0203] In summary, the smart contract testing method according to the embodiments of this application has at least one of the following technical effects:
[0204] (1) From understanding the requirements through development documents, code comments and business rules, to generating test cases and executing test cases, the entire process of smart contract testing is automated, which can save manpower costs.
[0205] (2) By parsing the development documents, code comments and business rules of smart contracts, entities and relationships between entities are obtained, and a business knowledge graph is constructed based on the entities and relationships between entities. This enables the business knowledge graph to accurately reflect the complex business logic of smart contracts, and the test cases generated based on the business knowledge graph are more accurate.
[0206] (3) By using dynamic testing strategies and generating test scenarios covering multiple dimensions based on the testing strategies, the fixed pattern of test case generation can be broken, and real and diverse test scenarios can be simulated to improve the accuracy of test cases and reduce the limitations of the test scope.
[0207] (4) By adjusting and updating the testing strategy through reinforcement learning, the testing strategy can be optimized flexibly and autonomously.
[0208] Figure 4 This is a schematic diagram of a smart contract testing device provided in an embodiment of this application. Figure 4 As shown, the smart contract testing device provided in this application embodiment includes: a parsing module 210, a business knowledge graph construction module 220, a test case generation module 230, and a test case execution module 240.
[0209] The parsing module 210 is used to parse the smart contract's development documentation, code comments, and business rules to obtain the entities and the relationships between them.
[0210] The business knowledge graph construction module 220 is used to construct a business knowledge graph based on entities and the relationships between entities. The business knowledge graph represents the association between interfaces, code branches, business scenarios, business rules, and regulatory rules.
[0211] The test case generation module 230 is used to generate test scenarios and corresponding test cases based on the business knowledge graph. The test scenarios cover interface interaction, code branching, business rules and regulatory compliance.
[0212] Test case execution module 240 is used to execute test cases and obtain test results.
[0213] In one possible embodiment, the relationships between entities in the business knowledge graph have weights. The weights of the relationships between entities are calculated based on rule frequency, logical dependency, and business impact. Rule frequency represents the number of times the relationship between entities is declared in the development document. Logical dependency represents the pre-constraint relationship between entities. Business impact represents the impact of the relationship between entities on the business objective.
[0214] In one possible embodiment, the test case generation module includes: a test element extraction submodule, used to extract test elements based on the weights of relationships between entities in a business knowledge graph, wherein the test elements include relationships between entities with weights greater than a first threshold and their corresponding entities; a test strategy determination submodule, used to determine test modes matching the test elements and determine corresponding test strategies based on the test modes, wherein the test modes are reusable test templates and the test modes are mapped to the test strategies, and the test strategies include interface compatibility strategies, full branch coverage strategies, business rule verification strategies, and regulatory compliance strategies; a test scenario generation submodule, used to generate test scenarios based on the business knowledge graph and the test strategies; and a test case generation submodule, used to generate test cases corresponding to the test scenarios.
[0215] In one possible embodiment, the test scenario generation submodule includes: a test scenario generation unit, used to select features corresponding to interface compatibility strategy, full branch coverage strategy, business rule verification strategy and regulatory compliance strategy from the business knowledge graph through the dimension combination method and combine them to generate corresponding test scenarios.
[0216] In one possible embodiment, the smart contract testing device further includes: an execution priority determination module, used to determine the execution priority of test cases according to priority rules, wherein the execution priority order indicated by the priority rules from high to low is: test cases with prerequisite dependencies, test cases covering target areas, test cases covering target processes, and test cases not covering code branches. The target areas include exception handling logic indicated by business rules and regulatory rule constraints indicated by regulatory rules. The target processes are determined according to the weights of relationships between entities in the business knowledge graph.
[0217] In one possible embodiment, the test case execution module includes: an input parameter type and boundary value generation submodule, used to generate the input parameter types and boundary values of the interface based on the input parameter constraints of the interface and the association relationships between business rules in the business knowledge graph, wherein the input parameter types include dependent association input parameter types, abnormal input parameter types, and normal compliant input parameter types, and the boundary values include numerical boundaries, time boundaries, and business rule boundaries; and a test case execution submodule, used to execute test cases according to the input parameter types and boundary values of the interface and according to the priority of the test cases to obtain test results.
[0218] In one possible embodiment, the smart contract testing apparatus further includes: a comparison processing module for comparing test results with expected results to determine smart contract defects, wherein smart contract defects include at least one of the following: missing code branches, violation of business rules, violation of regulatory rules, and abnormal execution paths; a test report generation module for generating a test report based on the smart contract defects; and an update module for adjusting and updating test strategies and / or priority rules based on the test report.
[0219] In one possible embodiment, the update module includes an update submodule for adjusting and updating the test strategy based on the test report using reinforcement learning.
[0220] Figure 5 This is a schematic diagram of the structure of an electronic device provided in an embodiment of this application. Figure 5 As shown, this application embodiment provides an electronic device including a processor 301 and a memory 302. Optionally, the device further includes a communication component 303. The processor 301, memory 302, and communication component 303 are connected via a bus 304.
[0221] In the specific implementation process, the memory 302 stores code, and the processor 301 runs the code stored in the memory 302 to execute the method of the above method embodiment.
[0222] The specific implementation process of processor 301 can be found in the above method embodiments, and its implementation principle and technical effect are similar. It will not be repeated here.
[0223] In the above Figure 5In the illustrated embodiments, it should be understood that the processor 301 can be a Central Processing Unit (CPU), or other general-purpose processors, digital signal processors (DSPs), application-specific integrated circuits (ASICs), etc. The general-purpose processor can be a microprocessor or any conventional processor. The steps of the method disclosed in this invention can be directly implemented by a hardware processor, or implemented by a combination of hardware and software modules within the processor.
[0224] The memory 302 may include high-speed RAM memory, and may also include non-volatile memory (NVM), such as at least one disk storage.
[0225] Bus 304 can be an Industry Standard Architecture (ISA) bus, a Peripheral Component Interconnect (PCI) bus, or an Extended Industry Standard Architecture (EISA) bus, etc. Bus 304 can be divided into address bus, data bus, control bus, etc. For ease of illustration, the bus 304 in the accompanying drawings of this application is not limited to only one bus or one type of bus.
[0226] This application provides a computer-readable storage medium storing computer-executable instructions, which, when executed by a processor, are used to implement the methods described in the above-described method embodiments.
[0227] The aforementioned computer-readable storage medium can be implemented by any type of volatile or non-volatile storage device or a combination thereof, such as static random access memory (SRAM), electrically erasable programmable read-only memory (EEPROM), erasable programmable read-only memory (EPROM), programmable read-only memory (PROM), read-only memory (ROM), magnetic storage, flash memory, magnetic disk, or optical disk. The readable storage medium can be any available medium accessible to a general-purpose or special-purpose computer.
[0228] An exemplary readable storage medium is coupled to a processor, enabling the processor to read information from and write information to the readable storage medium. Of course, the readable storage medium can also be a component of the processor. The processor and the readable storage medium can reside in an Application Specific Integrated Circuit (ASIC). Alternatively, the processor and the readable storage medium can exist as discrete components in the device.
[0229] This application provides a computer program product, including a computer program that, when executed by a processor, implements the methods provided in any of the embodiments described above.
[0230] It should be noted that, for the sake of simplicity, the foregoing method embodiments are all described as a series of actions. However, those skilled in the art should understand that this application is not limited to the described order of actions, as some steps may be performed in other orders or simultaneously according to this application. Furthermore, those skilled in the art should also understand that the embodiments described in the specification are all optional embodiments, and the actions and modules involved are not necessarily essential to this application.
[0231] It should be further noted that although the steps in the flowchart are shown sequentially according to the arrows, these steps are not necessarily executed in the order indicated by the arrows. Unless explicitly stated herein, there is no strict order restriction on the execution of these steps, and they can be executed in other orders. Moreover, at least some steps in the flowchart may include multiple sub-steps or multiple stages. These sub-steps or stages are not necessarily completed at the same time, but can be executed at different times. The execution order of these sub-steps or stages is not necessarily sequential, but can be performed alternately or in turn with other steps or at least some of the sub-steps or stages of other steps.
[0232] It should be understood that the above-described device embodiments are merely illustrative, and the device of this application can also be implemented in other ways. For example, the division of units / modules in the above embodiments is only a logical functional division, and there may be other division methods in actual implementation. For example, multiple units, modules, or components may be combined, or integrated into another system, or some features may be ignored or not executed.
[0233] Furthermore, unless otherwise specified, the functional units / modules in the various embodiments of this application can be integrated into one unit / module, or each unit / module can exist physically separately, or two or more units / modules can be integrated together. The integrated units / modules described above can be implemented in hardware or as software program modules.
[0234] When integrated units / modules are implemented in hardware, the hardware can be digital circuits, analog circuits, etc. The physical implementation of the hardware structure includes, but is not limited to, transistors, memristors, etc. Unless otherwise specified, the processor can be any suitable hardware processor, such as a CPU, GPU, FPGA, DSP, and ASIC, etc. Unless otherwise specified, the storage unit can be any suitable magnetic or magneto-optical storage medium, such as Resistive Random Access Memory (RRAM), Dynamic Random Access Memory (DRAM), Static Random Access Memory (SRAM), Enhanced Dynamic Random Access Memory (EDRAM), High-Bandwidth Memory (HBM), Hybrid Memory Cube (HMC), etc.
[0235] If the integrated unit / module is implemented as a software program module and sold or used as an independent product, it can be stored in a computer-readable storage device (CMD). Based on this understanding, the technical solution of this application, in essence, or the part that contributes to the prior art, or all or part of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a memory and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute all or part of the steps of the methods of the various embodiments of this application. The aforementioned memory includes various media capable of storing program code, such as a USB flash drive, read-only memory (ROM), random access memory (RAM), portable hard drive, magnetic disk, or optical disk.
[0236] In the above embodiments, the descriptions of each embodiment have their own emphasis. For parts not described in detail in a certain embodiment, please refer to the relevant descriptions of other embodiments. The technical features of the above embodiments can be combined arbitrarily. For the sake of brevity, not all possible combinations of the technical features in the above embodiments are described. However, as long as the combination of these technical features does not contradict each other, it should be considered within the scope of this specification.
[0237] Other embodiments of this application will readily occur to those skilled in the art upon consideration of the specification and practice of the invention disclosed herein. This application is intended to cover any variations, uses, or adaptations of this application that follow the general principles of this application and include common knowledge or customary techniques in the art not disclosed herein. The specification and examples are to be considered exemplary only, and the true scope and spirit of this application are indicated by the following claims.
[0238] It should be understood that this application is not limited to the precise structure described above and shown in the accompanying drawings, and various modifications and changes can be made without departing from its scope. The scope of this application is limited only by the appended claims.
Claims
1. A smart contract testing method, characterized in that, include: Analyze the development documentation, code comments, and business rules of smart contracts to obtain the entities and the relationships between them; A business knowledge graph is constructed based on the entities and the relationships between them. The business knowledge graph represents the relationships between interfaces, code branches, business scenarios, business rules, and regulatory rules. Test scenarios and corresponding test cases are generated based on the business knowledge graph. The test scenarios cover interface interaction, code branching, business rules, and regulatory compliance. Execute the test cases to obtain the test results.
2. The method according to claim 1, characterized in that, The relationships between entities in the business knowledge graph have weights, which are calculated based on rule frequency, logical dependency, and business impact. Rule frequency indicates the number of times the relationship between entities is declared in the development document, logical dependency indicates that the relationship between entities has a pre-constraint relationship, and business impact indicates the influence of the relationship between entities on business objectives.
3. The method according to claim 2, characterized in that, The generation of test scenarios and corresponding test cases based on the business knowledge graph includes: Test elements are extracted based on the weights of the relationships between entities in the business knowledge graph. The test elements include the relationships between entities with weights greater than a first threshold and the corresponding entities. Based on the test elements, a test mode matching the test elements is determined, and a corresponding test strategy is determined based on the test mode. The test mode is a reusable test template, and the test mode is mapped to the test strategy. The test strategy includes interface compatibility strategy, full branch coverage strategy, business rule verification strategy, and regulatory compliance strategy. The test scenario is generated based on the business knowledge graph and the test strategy; Generate test cases corresponding to the test scenario.
4. The method according to claim 3, characterized in that, The step of generating the test scenario based on the business knowledge graph and the test strategy includes: The feature corresponding to the interface compatibility strategy, the full branch coverage strategy, the business rule verification strategy, and the regulatory compliance strategy is selected from the business knowledge graph by the dimension combination method and combined to generate the corresponding test scenario.
5. The method according to claim 4, characterized in that, After generating test cases corresponding to the test scenario, the method further includes: The execution priority of the test cases is determined according to priority rules. The execution priority order indicated by the priority rules from high to low is: test cases with prerequisite dependencies, test cases covering the target area, test cases covering the target process, and test cases not covering code branches. The target area includes the exception handling logic indicated by the business rules and the regulatory rule constraints indicated by the regulatory rules. The target process is determined according to the weight of the relationships between entities in the business knowledge graph.
6. The method according to claim 5, characterized in that, The test results obtained from executing the test cases include: Based on the input parameter constraints of the interface in the business knowledge graph and the association between the business rules, the input parameter types and boundary values of the interface are generated. The input parameter types include dependent and associated input parameter types, abnormal input parameter types, and normal and compliant input parameter types. The boundary values include numerical boundaries, time boundaries, and business rule boundaries. Based on the input parameter types and boundary values of the interface, the test cases are executed according to their priority to obtain the test results.
7. The method according to claim 5 or 6, characterized in that, After executing the test cases and obtaining the test results, the method further includes: The test results are compared with the expected results to identify smart contract defects, which include at least one of the following: missing code branches, violation of business rules, violation of regulatory rules, and abnormal execution path. Based on the aforementioned smart contract defects, a test report is generated; The test strategy and / or priority rules are adjusted and updated based on the test report.
8. The method according to claim 7, characterized in that, The step of adjusting and updating the test strategy based on the test report includes: adjusting and updating the test strategy through reinforcement learning based on the test report.
9. A smart contract testing device, comprising: The parsing module is used to parse the smart contract's development documentation, code comments, and business rules to obtain the entities and the relationships between them; The business knowledge graph construction module is used to construct a business knowledge graph based on the entities and the relationships between entities. The business knowledge graph represents the association between interfaces, code branches, business scenarios, business rules, and regulatory rules. The test case generation module is used to generate test scenarios and corresponding test cases based on the business knowledge graph. The test scenarios cover interface interaction, code branching, business rules, and regulatory compliance. The test case execution module is used to execute the test cases and obtain the test results.
10. An electronic device, characterized in that, include: A processor, and a memory communicatively connected to the processor; The memory stores computer-executed instructions; The processor executes computer execution instructions stored in the memory to implement the method as described in any one of claims 1 to 8.
11. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores computer-executable instructions, which, when executed by a processor, are used to implement the method as described in any one of claims 1 to 8.
12. A computer program product, characterized in that, Includes a computer program that, when executed by a processor, implements the method of any one of claims 1 to 8.