Blockchain smart contract generation method and system based on multi-agent cooperation
Patent Information
- Application Number
- CN202610762580.0
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-05-29
- Publication Date
- 2026-10-23
AI Technical Summary
[0002]现有的单一模型驱动的智能合约生成技术在端到端自动化生成过程中存在错误传递与累积放大问题,这一问题在复杂多方协作合约场景中较为突出;具体而言,当业务需求涉及多重权限控制、状态依赖转换和跨合约交互逻辑时,单一生成模型需要同时承担需求语义解析、代码逻辑构建、安全漏洞预防和功能正确性保障等多维度任务,这种统一建模机制在模型训练和推理过程中无法针对不同技术环节的专业特性进行差异化优化,导致在需求理解阶段产生的语义歧义会直接传递到代码生成环节,进而在安全验证阶段因缺乏专门的漏洞检测机制而被忽略,最终累积形成部署后的合约执行风险;这类问题不同于单一环节的技术缺陷,而是由于缺乏任务分解与协同机制,使得各环节间无法形成有效的错误纠正反馈回路,例如在多签名资金托管合约生成中,需求阶段对“授权阈值变更”的理解偏差可能导致代码阶段生成错误的权限校验逻辑,而单一模型在生成过程中既无法调用专门的安全审计模块验证权限边界,也无法通过测试验证模块及时发现状态转换异常;当前解决此问题的主流方法是采用串行工具链组合方案,即依次使用独立的需求分析工具、代码生成器、静态安全扫描器和测试框架进行多阶段处理;然而,这种基于工具拼接的解决方案不仅需要开发人员在各工具间手动传递和转换中间结果,各独立工具之间也缺乏统一的语义理解和协同优化机制,使其难以在生成过程中实现跨环节的动态错误定位与迭代修正,无法满足复杂合约场景对端到端自动化生成的高准确性和高可靠性要求且存在显著的人工协调成本,最终限制了智能合约自动化生成技术在企业级关键应用中的可信部署
[0017]本发明通过设置具备不同专业功能的智能体避免单一模型无法针对不同环节专业特性进行差异化优化的问题,使需求阶段能够针对权限控制与状态转换等合约领域语义进行精准拆解,代码生成阶段依据语义单元类型采用专门构建策略,降低语义歧义向代码逻辑错误传递的风险;安全审计智能体通过漏洞模式匹配识别权限路径缺陷,测试验证智能体通过状态路径遍历发现转换异常,从不同维度进行验证避免单一检测机制的遗漏,并通过协作通信通道将审计与测试结果反馈至代码生成智能体触发定向修正,形成错误纠正反馈回路,使需求理解或代码构建阶段产生的缺陷在生成过程中被拦截和修正,降低错误在各环节间传递并累积放大至部署阶段形成执行风险的概率;相较于需要手动传递中间结果的串行工具链方案,本发明通过智能体协同工作流实现从自然语言需求到可部署合约的端到端自动化,减少人工协调成本,提高复杂合约生成的准确性与可靠性。
Smart Images

Figure CN122969768A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the fields of artificial intelligence and blockchain technology, and more specifically, to a method and system for generating blockchain smart contracts based on multi-agent collaboration. Background Technology
[0002] Existing single-model-driven smart contract generation technologies suffer from error propagation and amplification issues during end-to-end automated generation, a problem particularly pronounced in complex multi-party collaborative contract scenarios. Specifically, when business requirements involve multiple access controls, state dependency transitions, and cross-contract interaction logic, a single generation model must simultaneously handle multiple tasks, including requirement semantic parsing, code logic construction, security vulnerability prevention, and functional correctness assurance. This unified modeling mechanism cannot differentiate and optimize for the specific characteristics of different technical stages during model training and inference. Consequently, semantic ambiguities arising in the requirement understanding phase are directly propagated to the code generation stage and subsequently overlooked during the security verification stage due to the lack of a dedicated vulnerability detection mechanism, ultimately accumulating into post-deployment contract execution risks. This type of problem differs from the technical defects of a single stage; rather, it stems from a lack of task decomposition and collaboration mechanisms, preventing the formation of an effective error correction feedback loop between stages. For example, in multi-signature fund custody contract generation... In the process of development, misunderstandings about "authorization threshold changes" during the requirements phase may lead to incorrect permission verification logic generated during the code phase. A single model cannot call a dedicated security audit module to verify permission boundaries during the generation process, nor can it detect abnormal state transitions in a timely manner through a test verification module. The current mainstream approach to solving this problem is to adopt a serial toolchain combination scheme, that is, to use independent requirements analysis tools, code generators, static security scanners, and testing frameworks in sequence for multi-stage processing. However, this tool-based solution not only requires developers to manually transfer and transform intermediate results between tools, but also lacks a unified semantic understanding and collaborative optimization mechanism among the independent tools. This makes it difficult to achieve dynamic error location and iterative correction across stages during the generation process, and it cannot meet the high accuracy and high reliability requirements of end-to-end automated generation in complex contract scenarios. It also has significant manual coordination costs, ultimately limiting the reliable deployment of smart contract automated generation technology in enterprise-level critical applications.
[0003] In view of this, the present invention proposes a blockchain smart contract generation method and system based on multi-agent collaboration to solve the above problems. Summary of the Invention
[0004] To overcome the aforementioned shortcomings of the prior art and to achieve the above objectives, the present invention provides the following technical solution: a blockchain smart contract generation method based on multi-agent collaboration, comprising:
[0005] Step S1: Receive the contract business requirement text described in natural language, and perform multi-level semantic decomposition processing on the contract business requirement text through the requirement parsing intelligent agent to obtain contract intent description data. The contract intent description data includes permission control semantic units, state transition semantic units, and cross-contract interaction semantic units.
[0006] Step S2: The contract intent description data is distributed to the code generation agent through the agent collaboration communication channel. The code generation agent constructs the corresponding contract code logic fragments unit by unit according to the type label and dependency topology relationship of each semantic unit in the contract intent description data, and assembles and connects each contract code logic fragment according to the dependency topology relationship to generate contract candidate code data.
[0007] Step S3: The contract candidate code data is transmitted to the security audit agent through the agent collaboration communication channel. The security audit agent performs vulnerability pattern matching scan on the permission verification path and state change operation in the contract candidate code data, and generates security audit report data with vulnerability location annotations.
[0008] Step S4: The contract candidate code data is transmitted to the test and verification agent. The test and verification agent constructs a multi-condition combination contract execution test sequence based on the contract intent description data, performs state path traversal verification on the contract candidate code data, and generates test and verification result data containing abnormal path markers.
[0009] Step S5: Based on the vulnerability location markers in the security audit report data and the abnormal path markers in the test verification result data, trigger the code generation agent through the agent collaboration communication channel to perform targeted correction on the corresponding code logic fragments in the contract candidate code data, and generate deployable contract data.
[0010] A blockchain smart contract generation system based on multi-agent collaboration, used to implement the aforementioned blockchain smart contract generation method based on multi-agent collaboration, includes:
[0011] Requirement decomposition module: Receives contract business requirement text described in natural language, performs multi-level semantic decomposition processing on the contract business requirement text through the requirement parsing intelligent agent, and obtains contract intent description data. The contract intent description data includes permission control semantic units, state transition semantic units, and cross-contract interaction semantic units.
[0012] The logic assembly module distributes the contract intent description data to the code generation agent through the agent collaboration communication channel. The code generation agent constructs the corresponding contract code logic fragments unit by unit according to the type label and dependency topology relationship of each semantic unit in the contract intent description data, and assembles and connects the contract code logic fragments according to the dependency topology relationship to generate contract candidate code data.
[0013] Vulnerability scanning module: Transmits contract candidate code data to security audit agent via intelligent agent collaborative communication channel. Security audit agent performs vulnerability pattern matching scan on permission verification paths and state change operations in contract candidate code data, and generates security audit report data with vulnerability location annotations.
[0014] State verification module: transmits contract candidate code data to test verification agent. Test verification agent constructs a contract execution test sequence with multiple conditions based on contract intent description data, performs state path traversal verification on contract candidate code data, and generates test verification result data containing abnormal path markers.
[0015] Targeted Correction Module: Based on the vulnerability location markers in the security audit report data and the abnormal path markers in the test verification result data, the module triggers the code generation agent through the agent collaboration communication channel to perform targeted correction on the corresponding code logic fragments in the contract candidate code data, thereby generating deployable contract data.
[0016] The technical effects and advantages of the blockchain smart contract generation method and system based on multi-agent collaboration of this invention are as follows:
[0017] This invention avoids the problem of a single model being unable to perform differentiated optimization for the professional characteristics of different stages by setting up intelligent agents with different professional functions. It enables the requirement stage to accurately decompose the semantics of the contract domain, such as permission control and state transition. In the code generation stage, a special construction strategy is adopted according to the semantic unit type, reducing the risk of semantic ambiguity being transmitted to code logic errors. The security audit intelligent agent identifies permission path defects through vulnerability pattern matching, and the testing and verification intelligent agent discovers transition anomalies through state path traversal. Verification from different dimensions avoids the omissions of a single detection mechanism. The audit and test results are fed back to the code generation intelligent agent through a collaborative communication channel to trigger targeted correction, forming an error correction feedback loop. This ensures that defects generated in the requirement understanding or code building stage are intercepted and corrected during the generation process, reducing the probability of errors being transmitted between stages and accumulating and amplifying to the deployment stage, thus creating execution risks. Compared with serial toolchain solutions that require manual transmission of intermediate results, this invention achieves end-to-end automation from natural language requirements to deployable contracts through intelligent agent collaborative workflow, reducing manual coordination costs and improving the accuracy and reliability of complex contract generation. Attached Figure Description
[0018] Figure 1 This is a schematic diagram of the blockchain smart contract generation method based on multi-agent collaboration of the present invention;
[0019] Figure 2 This is a schematic diagram of the blockchain smart contract generation system based on multi-agent collaboration of the present invention. Detailed Implementation
[0020] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0021] Example 1
[0022] Please see Figure 1 As shown, this embodiment of the blockchain smart contract generation method based on multi-agent collaboration includes:
[0023] Step S1: Receive the contract business requirement text described in natural language, and perform multi-level semantic decomposition processing on the contract business requirement text through the requirement parsing intelligent agent to obtain contract intent description data. The contract intent description data includes permission control semantic units, state transition semantic units, and cross-contract interaction semantic units.
[0024] Existing single-model solutions need to simultaneously handle multiple tasks such as semantic parsing, code building, and security verification. When dealing with complex requirements involving multiple access controls, state dependency transitions, and cross-contract interaction logic, ambiguities generated during the semantic understanding stage are directly transmitted to the code generation stage and gradually accumulate and amplify, ultimately leading to contract execution risks after deployment. To address this problem at its root, this invention introduces a dedicated requirement parsing agent responsible for deep semantic decomposition of contract business requirement text. By separating the semantic parsing task from the overall generation process, this agent can perform in-depth optimization of the requirement understanding stage, significantly improving the accuracy of requirement semantic parsing.
[0025] In some possible implementations of this invention, the method for obtaining contract intent description data includes the following processing steps:
[0026] Segment Boundary Recognition and Initial Semantic Triple Generation: The requirement parsing agent first performs segment boundary recognition processing on the received contract business requirement text. Natural language requirement text is usually composed of multiple semantically independent business description segments, which are connected by action predicates and conditional adverbs. The specific processing method for segment boundary recognition is as follows: scan the contract business requirement text, and use action predicates (such as words that represent specific operational behaviors, such as transfer, signature, call, change, etc.) and conditional adverbs (such as sentence structures that represent triggering conditions, such as when, if, under certain circumstances, etc.) as segmentation anchors. At the above segmentation anchors, the contract business requirement text is segmented into several mutually independent business semantic segments.
[0027] For each business semantic segment, part-of-speech (POS) level grammatical component tagging is performed. Specifically, each word in the segment is tagged with its part-of-speech category, which includes nouns, verbs, adjectives, adverbs, and prepositions. After POS tagging, noun phrases that act as the executor of actions are identified and extracted as candidate subject role identifiers; predicate phrases that act as the core action are identified and extracted as candidate operation behavior identifiers; and subordinate structural components that act as limiting conditions (including conditional clauses, quantity-limiting phrases, and scope-limiting phrases) are identified and extracted as candidate constraint condition identifiers.
[0028] After extracting candidate identifiers, a contract domain role dictionary matching process is performed on the candidate entity role identifiers. The contract domain role dictionary pre-defines common role type entries in smart contract scenarios, including contract owner, authorized signer, beneficiary, and external caller. Each role type entry is associated with a set of synonym expressions; for example, the set of synonym expressions for the beneficiary role type entry includes various natural language expressions such as payee, fund recipient, and designated beneficiary. When a candidate entity role identifier matches any item in the set of synonym expressions for a role type entry in the contract domain role dictionary, the candidate entity role identifier is normalized and replaced with the standard role identifier for that role type entry to eliminate semantic ambiguity caused by synonym differences and ensure consistency in the expression of role entities during subsequent processing. Candidate operation behavior identifiers undergo contract operation semantic classification processing, and are categorized into one of the following four types based on their execution effect: if the operation behavior involves the transfer of tokens or assets between accounts, it is classified as an asset transfer operation; if the operation behavior involves reading, writing, or modifying internal contract variables, it is classified as a status modification operation; if the operation behavior involves granting or revoking account permissions, it is classified as a permission change operation; and if the operation behavior only involves reading or querying data, it is classified as an information query operation. The standardized role identifier, the classified operation identifier, and the corresponding candidate constraint condition identifier are combined and encapsulated to generate corresponding semantic triple data. The structure of the semantic triple data is an ordered triple of (subject role identifier, operation behavior identifier, constraint condition identifier).
[0029] Cross-segment role referencing resolution: In natural language requirement descriptions, the same role entity may appear repeatedly in different sentence segments as pronouns (such as "he" or "the user") or abbreviations. Without resolution, semantic triples corresponding to different sentence segments will contain subject role identifiers with different expressions but pointing to the same entity, leading to a break in the semantic association across sentence segments and affecting the accuracy of subsequent dependency topology construction. To address this, the requirement parsing agent performs cross-segment role referencing resolution on the semantic triple data corresponding to each business semantic segment. The specific process is as follows: Iterate through the subject role identifiers in all semantic triple data, and for referential role descriptions existing between adjacent semantic triples, determine the role entity they point to based on the context semantics, and establish an equivalence mapping table of subject role identifiers between different semantic triple data. The data structure of the equivalence mapping table is in key-value pair form, where the key is the referential role description (such as "the user"), and the value is the unified role entity identifier it points to (such as the authorized signer). After the equivalence mapping table is established, all semantic triples are traversed, and the referential role descriptions in them are replaced with the corresponding unified role entity identifiers according to the equivalence mapping table. This results in a set of resolved semantic triples, ensuring that the same role entity is expressed with the same standard role identifier in all semantic triples during subsequent processing.
[0030] Dependency Topology Construction and Semantic Unit Classification: Based on the logical implication between the operation behavior identifiers and constraint condition identifiers of each semantic triple in the resolved semantic triple set, dependency topology relationships between semantic units are constructed. These dependency topology relationships are expressed in the form of a directed graph, where nodes represent the semantic triple data, and directed edges represent the dependencies between semantic triples. The rule for determining logical implication relationships is as follows: if the constraint condition identifier of semantic triple A references the operation result described by the operation behavior identifier of semantic triple B (i.e., the execution prerequisite of semantic triple A includes the completion of semantic triple B), then semantic triple A is determined to depend on semantic triple B, and a directed edge from semantic triple B to semantic triple A is added to the directed graph. For example, if a contract transfers funds to a designated beneficiary relying on at least two authorized signatories to complete signature confirmation, then a directed edge is added to the directed graph from the signature confirmation semantic triple to the transfer semantic triple.
[0031] After the directed graph relying on topological relationships is constructed, semantic unit classification processing is performed on the resolved set of semantic triples. The classification rules are as follows: semantic triples whose operation behavior identifiers belong to the permission change category, or whose constraint identifiers contain role authentication logic (such as verifying whether the caller belongs to the authorized role set), are classified as permission control semantic units; semantic triples whose operation behavior identifiers belong to the state modification category (i.e., the operation behavior involves changes to internal contract variables) are classified as state transition semantic units; and semantic triples whose operation behavior identifiers belong to the asset transfer category and require calling external contract interfaces are classified as cross-contract interaction semantic units. Finally, the directed graph relying on topological relationships, each semantic triple data, and its corresponding type label (permission control semantic unit, state transition semantic unit, or cross-contract interaction semantic unit) are jointly encapsulated and assembled to generate contract intent description data, providing structured and semantically clear task input for subsequent code generation of intelligent agents.
[0032] Step S2: Distribute the contract intent description data to the code generation agent through the agent collaboration communication channel. The code generation agent constructs the corresponding contract code logic fragments unit by unit according to the type label and dependency topology relationship of each semantic unit in the contract intent description data, and assembles and connects each contract code logic fragment according to the dependency topology relationship to generate contract candidate code data.
[0033] The contract intent description data is transmitted to the code generation agent via the agent collaboration communication channel. It should be noted that the agent collaboration communication channel is responsible for reliable business data transmission between agents. Its specific working mechanism is as follows: The sending agent encapsulates the business data to be transmitted into a communication message packet. The communication message packet contains four fields: the sending agent identifier (identifying the agent that sent the message packet), the receiving agent identifier (identifying the agent that should receive the message packet), a message type flag (distinguishing between three communication categories: task distribution messages, result feedback messages, and correction instruction messages; task distribution messages are used to distribute the processing results of the upstream agent to the downstream agent, result feedback messages are used to return the processing results of the downstream agent to the upstream agent, and correction instruction messages are used to trigger the code generation agent to perform targeted corrections), and a business data payload field (carrying the actual business data content to be transmitted).
[0034] The agent collaborative communication channel has a built-in message routing scheduler, which maintains a task status register for each agent. The task status register is a mapping table with the agent identifier as the key and the agent's current working stage identifier and the version identifier of completed task data as values. The working stage identifier records the agent's current processing stage (e.g., waiting for input, processing, processing completed), and the version identifier records the batch number of the task data processed by the agent. Upon receiving a communication message packet, the message routing scheduler queries the task status register based on the receiver agent identifier in the message packet to confirm whether the receiver agent's current working stage identifier meets the message reception preconditions corresponding to the communication message packet. The message reception precondition is that the receiver agent's current working stage identifier is in the waiting for input state. When the message reception preconditions are met, the message routing scheduler injects the business data payload field from the communication message packet into the task input buffer of the receiving agent (i.e., writes the business data into the data storage area that the receiving agent can read). Simultaneously, it updates the receiving agent's working stage identifier to "processing" and updates the data version identifier in the task status register. When the message reception preconditions are not met (i.e., the receiving agent is still in the "processing" state), the message routing scheduler temporarily stores the communication message packet in the message waiting queue and continuously queries the task status register according to a preset status polling period until the receiving agent's working stage identifier is updated to "waiting for input," at which point the injection operation is performed. The preset status polling period is an empirical value of 500 milliseconds, which implementers can adjust to a range of 100 to 2000 milliseconds based on actual network latency and task processing time. This communication channel mechanism ensures that each agent receives the corresponding business data when it is in the correct working stage, avoiding data overwriting and processing status confusion caused by concurrent message injection.
[0035] After the contract intent description data is successfully injected into the task input buffer of the code generation agent, the code generation agent begins the code construction process. Due to the dependency topology between semantic units, improper code construction order can lead to undefined reference errors when downstream code logic fragments reference upstream variables. This invention introduces a topology sorting mechanism in the code construction phase to ensure that the construction order of code logic fragments strictly follows the dependencies between semantic units.
[0036] In some possible implementations of this invention, the method for obtaining contract candidate code data includes the following processing steps:
[0037] Topological sorting and code construction priority determination: After receiving the contract intent description data, the code generation agent performs topological sorting on the directed graph in the contract intent description data that depends on topological relationships. Topological sorting is an algorithm that linearly sorts the nodes in a directed acyclic graph. The sorting result guarantees that for each directed edge from node A to node B in the directed graph, node A is always ranked before node B in the sorting result. The specific execution process of topological sorting is as follows: First, the in-degree value of each semantic unit node in the directed graph is counted. The in-degree value refers to the number of directed edges pointing to that node, representing the number of semantic units that the semantic unit depends on. Semantic unit nodes with an in-degree value of zero (i.e., nodes that do not depend on any other semantic units) are marked as root semantic units and added to the code building queue first. The code generation agent sequentially retrieves semantic unit nodes from the code building queue and performs code building. Whenever a semantic unit node completes code building, all outgoing edges of that node are removed from the directed graph, and the in-degree values of the successor semantic unit nodes pointed to by the outgoing edges are decreased by 1. When the in-degree value of a successor semantic unit node decreases to 0, that successor semantic unit node is added to the code building queue. The above process is repeated until the code building queue is empty and all semantic unit nodes have completed code building. Through the above topological sorting process, a code building priority sequence for each semantic unit is generated, ensuring that the code logic fragments of upstream semantic units in the dependency relationship are always built before the code logic fragments of downstream semantic units.
[0038] Type-based code building strategy execution: For each semantic unit in the code building queue, the code generation agent selects the corresponding code building strategy based on its type label, and adopts differentiated code building methods for different types of semantic units:
[0039] For the access control semantic unit, a role-based access control assertion nesting construction strategy is adopted. The specific processing steps of this strategy are as follows: Read the constraint identifier of the access control semantic unit, and parse out the signature count threshold (e.g., a threshold of 2 for at least two signatures) and the set of participating roles (e.g., a set of 3 authorized roles for three authorized signers); generate mapping data structure code to store the list of authorized role addresses, establishing a correspondence between role addresses and their authorization status (authorized or unauthorized); generate code to declare a counter variable to record the number of valid signatures, with the initial value of the counter variable set to 0; construct a loop structure code to traverse the current transaction signer list, nesting within the loop body. The following two layers of verification logic are used: The first layer is a signature validity verification assertion, which verifies whether the currently traversed signer address exists in the mapping data structure of the authorized role set. If it exists, the count variable value is incremented by 1. The second layer inserts a signature count threshold judgment assertion after the loop structure is executed, comparing whether the count variable value is greater than or equal to the signature count threshold. If it is less than the threshold, an instruction code to trigger execution rollback is generated with a descriptive error message (such as insufficient signature count, unable to execute the operation). Executing the rollback will terminate the current transaction and undo all executed state changes, ensuring that the contract does not produce any side effects when the permission verification fails.
[0040] For state transition semantic units, a state machine transition path construction strategy is adopted. The specific processing steps of this strategy are as follows: First, read the constraint identifier of the state transition semantic unit. Then, parse the preceding state description (i.e., the state the contract should be in before executing the current operation) and the following state description (i.e., the state the contract should transition to after executing the current operation) from the constraint identifier. Next, generate contract state enumeration type declaration code, which lists all possible state values of the contract. Then, generate contract state variable declaration code, which stores the current state enumeration value of the contract. At the beginning of the function code body, generate preceding state value check assertion code. This assertion code compares the current value of the contract state variable with the enumeration value corresponding to the preceding state description. If they are not equal, it triggers execution rollback and outputs a descriptive error message (e.g., the current contract state does not meet the operation's preceding conditions), ensuring that the contract is in the correct preceding state when the function is called. After the preceding state check assertion, generate state change assignment code, updating the contract state variable to the enumeration value corresponding to the following state description. Finally, after the state assignment code, generate blockchain event trigger code. This event trigger code records the operation log of state transitions, allowing external listeners to track the history of contract state changes.
[0041] For cross-contract interaction semantic units, an external call encapsulation construction strategy is adopted. The specific processing steps of this strategy are as follows: Read the operation behavior identifier and constraint condition identifier of the cross-contract interaction semantic unit; parse the target contract's interface address parameters and the target function signature to be called from the operation behavior identifier (the function signature consists of the function name and a list of parameter types, used to uniquely identify a function in the target contract); generate the target contract interface declaration code, which defines the function call specifications exposed by the target contract for the current contract to follow when calling; generate return value receiving variable declaration code after the external call statement, declaring variables used to store the return result of the external call; generate return value success flag assertion code, read the execution success flag (a boolean success / failure flag returned after the external call execution) from the return value receiving variable; when the flag value is false (i.e., the external call execution failed), trigger execution rollback with a descriptive error message (e.g., external contract call failed, transaction rolled back), ensuring that the contract can correctly handle exceptions and undo all state changes of the current transaction when the external call fails.
[0042] Code logic fragment assembly and connection: After all code logic fragments are constructed, parameter passing interface code and execution order control code are inserted between each code logic fragment according to the directed edge relationship between each semantic unit in the directed graph of dependency topology, so as to realize the data flow connection and call timing constraints between each code logic fragment.
[0043] The parameter passing interface code generation process is as follows: For each directed edge in the directed graph of dependent topology, read the post-state description of the semantic unit of the source node (upstream semantic unit) of the directed edge, and determine the state variables or operation return values involved in the post-state description as the data passing source; read the constraint condition identifier of the semantic unit of the target node (downstream semantic unit) of the directed edge, and determine the parameters referencing the upstream operation results in the constraint condition identifier as the data passing target; generate parameter mapping assignment code that assigns the data passing source to the data passing target, and insert the parameter mapping assignment code at the position after the upstream code logic segment is executed and before the downstream code logic segment is executed.
[0044] The process of generating execution order control code is as follows: The call sequence of each code logic segment is determined according to the topological sorting result. Order control code is generated so that the downstream code logic segment's corresponding function call is triggered only after the upstream code logic segment's corresponding function has completed execution (i.e., the function returns). The order control code implements call sequence constraints through function call chains or status flag checks. All code logic segments, along with the parameter passing interface code and execution order control code, are assembled according to the topological sorting order to form complete contract candidate code data.
[0045] Step S3: The contract candidate code data is transmitted to the security audit agent via the agent collaboration communication channel. The security audit agent performs vulnerability pattern matching scans on the permission verification path and state change operation in the contract candidate code data, and generates security audit report data with vulnerability location annotations.
[0046] Contract candidate code data is transmitted to the security audit agent via a collaborative communication channel. While the code generation phase focuses on the correct implementation of functional logic, the security of the contract code requires verification through a dedicated vulnerability detection mechanism. In a single model-driven approach, security vulnerability prevention and code generation share the same model parameters, preventing the model from being deeply optimized for vulnerability detection and easily overlooking typical vulnerability patterns such as reentrant calls and unauthorized state tampering. This invention introduces an independent security audit agent specifically responsible for vulnerability scanning of the contract candidate code data, decoupling the security verification and code generation phases, thereby significantly improving the coverage and accuracy of vulnerability detection.
[0047] In some possible implementations of this invention, the method for obtaining security audit report data includes the following processing steps:
[0048] Control Flow Path Extraction and Permission Verification Node Labeling: The security audit agent performs control flow path extraction processing on the contract candidate code data. A control flow path refers to a complete execution path formed by the contract code from the moment the entry function is called, through various branching structures (conditional branches, loop structures, and function call jumps) until it reaches a state change operation (such as assigning a state variable or calling an asset transfer). The specific processing steps for control flow path extraction are as follows: using the entry function of the contract candidate code data as the starting point for path extraction, recursively traverse each code statement in the entry function body; when encountering a conditional branch, continue path extraction along the two branches where the condition is true and false, forming two independent sub-paths; when encountering a function call jump, expand the function body of the called function and insert it into the current path, continuing extraction along the expanded path; when reaching a state change operation (including contract state variable assignment statements and external call statements triggering asset transfers), record the entire sequence of operation nodes traversed from the entry function's starting point to the current state change operation as a complete reachable execution path; summarize all extracted reachable execution paths to generate a control flow path set.
[0049] For each reachable execution path in the control flow path set, all operation nodes on the path are traversed one by one. Operation nodes that perform role authentication (such as verifying whether the caller address belongs to the authorized role set) and signature quantity threshold judgment are marked as permission verification nodes. Operation nodes that perform contract state variable assignment and asset transfer calls are marked as state change operation nodes. It is also marked whether there is a permission verification node before the state change operation node in each reachable execution path, so as to provide path security feature information for subsequent vulnerability pattern matching scanning.
[0050] Vulnerability Pattern Matching Scan: Loads a pre-built contract vulnerability feature pattern library. This library pre-stores operational characteristic descriptions of typical contract security vulnerabilities, manually compiled by the attacker. It includes the following four vulnerability patterns: Reentrant Call Pattern (describes an attacker repeatedly withdrawing funds before the state variables are updated by recursively calling the current contract), Unauthorized State Tampering Pattern (describes a vulnerability where critical contract state variables are modified without authorization), Integer Overflow Operation Pattern (describes a vulnerability where arithmetic operations result in values exceeding the data type's storage range, leading to numerical anomalies), and External Call Return Value Ignore Pattern (describes a vulnerability where subsequent logic continues execution without checking the success of an external contract call).
[0051] For each vulnerability pattern in the contract vulnerability feature pattern library, its operation node type sequence template is extracted. The operation node type sequence template describes the code operation characteristics of the vulnerability in the form of an ordered combination of operation node type tags. The operation node type sequence template for the reentrant call pattern is: a continuous arrangement in which the external call node type tag appears first and the state change node type tag appears last, that is, the code operation sequence of executing the external call first and then the state variable update; the operation node type sequence template for the unauthorized state tampering pattern is: a missing arrangement in the sequence interval before the state change node type tag, that is, the code operation sequence of directly executing the state variable update without any authorization verification; the operation node type sequence template for the integer overflow operation pattern is: a missing arrangement in which the arithmetic operation node type tag appears but there are no overflow check assertion node type tags before or after it; the operation node type sequence template for the external call return value ignoring pattern is: a missing arrangement in which the external call node type tag appears first but there are no return value verification node type tags after it.
[0052] For each reachable execution path sequence in the control flow path set, a subsequence matching operation is performed. The specific process of subsequence matching is as follows: a sliding window is set, the length of which is the same as the total number of operation node type markers in the current operation node type sequence template to be matched; the sliding window position is moved sequentially backward from the first operation node in the sequence along the operation node sequence direction of the reachable execution path, and an operation node subsequence window of the corresponding length is taken out for each sliding window position; the node type marker of each operation node in the operation node subsequence window is compared with the corresponding operation node type marker in the operation node type sequence template, and it is determined whether the two are the same. For missing permutation type operation node type sequence templates (i.e., templates describing the absence of a certain type of operation node), the following retrieval method is used: Locate all sequence positions where the target operation node type marker (such as the state change node type marker) appears in the operation node sequence of the reachable execution path. For each located target operation node type marker position, search for the existence of a specified preceding operation node type marker (such as the permission verification node type marker) in the sequence interval before that position (i.e., the interval from the start of the path to the target operation node position). When the position-by-position comparison results of a certain operation node sub-sequence window are all consistent, or the missing permutation search results confirm that the specified preceding operation node type marker does not exist, it is determined that the current reachable execution path successfully matches the corresponding vulnerability pattern at the position of the sub-sequence window. Record the first operation node of the sub-sequence window as the starting operation node of the vulnerability hit interval and the last operation node as the ending operation node of the vulnerability hit interval to obtain the vulnerability hit interval.
[0053] Vulnerability Location Annotation Summary: For all successfully matched vulnerability hit intervals, extract the line numbers of the start and end operation nodes in the contract candidate code data source code file for each vulnerability hit interval. The line range from the start operation node to the end operation node is used as the vulnerability location annotation, and the corresponding vulnerability pattern category identifier is associated and stored with this vulnerability location annotation. All vulnerability location annotations and their associated vulnerability pattern category identifiers are summarized and assembled to generate security audit report data. The security audit report data is organized in a structured list format. Each audit entry in the list contains two fields: vulnerability location annotation (line range) and vulnerability pattern category identifier, providing precise vulnerability location and type basis for subsequent targeted code correction.
[0054] Step S4: The contract candidate code data is transmitted to the test verification agent. The test verification agent constructs a multi-condition combination contract execution test sequence based on the contract intent description data, performs state path traversal verification on the contract candidate code data, and generates test verification result data containing abnormal path markers.
[0055] Contract candidate code data is simultaneously transmitted to the test and verification agent via the agent collaboration communication channel. After the contract candidate code data passes security vulnerability scanning, it is also necessary to verify whether its functional behavior is consistent with the description of each semantic unit in the contract intent description data. Especially in complex multi-condition combination scenarios, the code logic may produce state transition anomalies on specific execution paths. Existing single-model solutions lack a dedicated test and verification module, making it impossible to detect state transition anomalies in a timely manner, leading to execution risks after contract deployment. This invention introduces an independent test and verification agent, which automatically constructs test sequences with multiple conditions based on the contract intent description data, and performs state path traversal verification in an isolated sandbox environment, achieving comprehensive coverage verification of the contract's functional correctness. The contract execution sandbox environment is an independently running virtual blockchain execution environment that provides on-chain state storage and contract virtual machine execution capabilities completely isolated from the production blockchain network. All read and write operations on the contract state during testing are performed within the sandbox environment, without affecting any production environment data.
[0056] In some possible implementations of this invention, the method for obtaining test verification result data includes the following processing steps:
[0057] Contract State Transition Directed Graph Construction: The test verification agent extracts all state transition semantic units from the contract intent description data. For each state transition semantic unit, it parses its preceding state identifier (i.e., the state the contract should be in before the transition) and following state identifier (i.e., the state the contract will be in after the transition). Using the preceding and following state identifiers involved in all state transition semantic units as nodes, and the state transition conditions described by the state transition semantic units (i.e., the role conditions and constraints required to trigger the state transition) as the edge weights of directed edges, a contract state transition directed graph is constructed. The initial state node of the contract state transition directed graph corresponds to the default state of the contract after deployment without any operation. Each directed edge represents the state of the contract changing from the state represented by the source node to the state represented by the target node under the condition of satisfying the corresponding state transition conditions. Through the contract state transition directed graph, all possible state transition paths of the contract are explicitly expressed in directed graph form, providing a structured basis for the systematic construction of subsequent test sequences.
[0058] Construction of Multi-Condition Combination Test Sequence: Based on the directed graph of contract state transitions, a depth-first traversal is performed on all paths starting from the initial state node. The specific process of depth-first traversal is as follows: starting from the initial state node, recursively visit successor state nodes along the directed edges. When reaching a terminal state node with no successor, record the current traversal path, backtrack to the previous branch node, and continue traversing other successor nodes until all reachable paths in the directed graph have been traversed. For the state transition conditions attached to each directed edge on each traversal path, extract the relevant role entity identifiers and constraint condition identifiers in the order of the directed edges on the path, and combine them in the path order to generate the contract execution test sequence corresponding to that path. The contract execution test sequence consists of multiple test transaction data arranged in path order. Each test transaction data carries the following three types of parameters: calling role parameter (the value is the specific role address corresponding to the role entity identifier in the current directed edge state transition condition, used to simulate the role initiating the transaction), calling function identifier (the value is the operation behavior identifier of the state transition semantic unit corresponding to the current directed edge, used to specify the contract function called in this test transaction), and input parameter value (the value is the specific value corresponding to the parameter constraint specified by the constraint condition identifier in the current directed edge state transition condition).
[0059] For each constraint identifier containing numerical constraints, two types of parameter values are constructed: normal parameter values that satisfy the constraints (used to verify whether the execution result of the contract under normal conditions meets expectations) and boundary abnormal parameter values that exceed the constraint range (used to verify whether the contract can correctly refuse execution and trigger a rollback under abnormal conditions), so as to achieve dual verification coverage of normal execution paths and abnormal execution paths.
[0060] Sandbox Environment Execution and State Consistency Verification: Contract candidate code data is deployed to the contract execution sandbox environment. The deployment process includes compiling the contract candidate code data into contract bytecode and registering the contract bytecode in the sandbox environment's contract address registry, enabling the sandbox environment to receive function call requests for that contract address. The function call structures in the contract candidate code data are parsed, and the state variable operation sequences (including read and write operations on contract state variables) arranged in execution order are extracted from each function call structure (i.e., the complete code body of each contract function). These state variable operation sequences are then associated with the state transition conditions of the corresponding directed edges in the contract state transition directed graph (based on matching the operation behavior identifiers corresponding to the function call structures with the operation behavior identifiers in the directed edge state transition conditions), generating a path coverage mapping table between function call structures and directed edges. The path coverage mapping table is stored using function call structure identifiers as keys and their corresponding directed edge identifiers as values.
[0061] In the contract execution sandbox environment, test transaction data for each contract execution test sequence is submitted sequentially. After each submission, the current values of all contract state variables in the sandbox environment are read, and the combined current values of all state variables are recorded as a snapshot of the contract state variables after the execution of that test transaction data. The directed edge identifier corresponding to the function call identifier of the current test transaction data is found based on the path coverage mapping table. The state variable values related to the post-state identifier of that directed edge in the contract state variable snapshot are extracted and compared with the target state value described by that post-state identifier. When the comparison result is inconsistent (i.e., the actual state variable value after contract execution differs from the expected target value described by the post-state identifier), the execution path position corresponding to that test transaction data (i.e., the directed edge position in the contract state transition directed graph) is marked as an abnormal path marker, and the inconsistent contract state variable snapshot is associated with and stored with this abnormal path marker. All abnormal path markers and their associated contract state variable snapshots are summarized to generate test verification result data.
[0062] Step S5: Based on the vulnerability location markers in the security audit report data and the abnormal path markers in the test verification result data, trigger the code generation agent through the agent collaboration communication channel to perform targeted correction on the corresponding code logic fragments in the contract candidate code data, and generate deployable contract data.
[0063] After obtaining security audit report data and test verification result data, the vulnerability location annotations and abnormal path markers need to be converted into precise correction operations for the contract candidate code data. Existing serial toolchain solutions require developers to manually transfer and convert intermediate results between tools at this stage, resulting in significant manual coordination costs. Furthermore, the lack of a unified semantic understanding and collaborative optimization mechanism among the independent tools makes it impossible to achieve dynamic error location and iterative correction across stages during the generation process. This invention directly transmits security audit report data and test verification result data back to the code generation agent through an intelligent agent collaborative communication channel, triggering it to execute targeted corrections and constructing a dynamic error correction feedback loop between the agents, completely eliminating manual coordination costs.
[0064] In some possible implementations of this invention, the process of triggering a code generation agent through an agent collaborative communication channel to perform targeted correction on the corresponding code logic fragments in the contract candidate code data and generate the final deployable contract data includes:
[0065] The remediation task list is generated by iterating through all audit entries in the structured list of the security audit report data, extracting the vulnerability location label (code line range) and its associated vulnerability mode category identifier for each audit entry; and by iterating through all abnormal path markers in the test verification result data, extracting each abnormal path marker and its associated contract state variable snapshot. All extracted vulnerability location labels and abnormal path markers are then aggregated. Specifically, based on the code line range in the vulnerability location label and the execution path position in the abnormal path marker, the correspondence between code logic segments and semantic units recorded in step S2's code generation stage is queried, mapping the vulnerability location labels and abnormal path markers to their respective code logic segments. Multiple vulnerability location labels and abnormal path markers mapped to the same code logic segment are merged into a single remediation task item, generating a remediation task list at the code logic segment level. Each remediation task item in the remediation task list contains three fields: target code logic segment identifier (corresponding code line range), vulnerability mode category identifier (from security audit report data), and abnormal state variable snapshot (from test verification result data). The task list is encapsulated as a correction instruction message by the security audit agent and the test verification agent through the agent collaboration communication channel, and sent to the task input buffer of the code generation agent respectively.
[0066] Local Refactoring: After receiving the list of remediation tasks, the code generation agent performs local refactoring on the code line range pointed to by the target code logic segment identifier in each remediation task item, according to the order of the remediation task items in the list. The local refactoring process determines the specific remediation operation type based on the vulnerability mode category identifier in the remediation task item, and adopts the following differentiated remediation operations for the four vulnerability modes:
[0067] For reentrant call patterns, a state change pre-emption rearrangement is performed. Specifically, the process involves: locating the line positions of the external call statement and the state change assignment statement within the target code segment; cutting the entire state change assignment statement from its original line position and inserting it before the external call statement, ensuring the state variable update is completed before the external call; and adjusting the variable reference order within the target code segment caused by statement movement to ensure that all variables referenced by the moved state change assignment statement have been declared and initialized during its execution. This rearrangement ensures that the contract state variables are updated before the external call, preventing attackers from triggering the fund withdrawal logic again even if they re-enter the current contract via recursion, as the contract state has been updated, thus eliminating the reentrant call vulnerability.
[0068] For the unauthorized state tampering mode category, an authorization verification node insertion operation is performed. The specific process is as follows: The semantic unit corresponding to the target code logic fragment identifier in the correction task item is read. Based on the authorization control semantic unit associated with this semantic unit (found through a directed graph of dependency topology relationships), the principal role identifier and constraint condition identifier in the authorization control semantic unit are extracted. Before the code line corresponding to the state change operation node within the target code logic fragment's code line range, role identity verification assertion code is inserted. The content of the role identity verification assertion code is: obtain the account address of the current transaction initiator, compare this address with the list of authorized role addresses corresponding to the principal role identifier one by one. If the account address is not in the list of authorized role addresses, a rollback is triggered and a descriptive error message is output (e.g., the caller has no right to perform this operation) to complete the missing authorization verification logic and prevent unauthorized accounts from tampering with the contract state.
[0069] For integer overflow operation patterns, a safe arithmetic operation replacement operation is performed. Specifically, the process involves locating all arithmetic operation statements (including addition, subtraction, and multiplication statements) that lack overflow checks within the target code block's line range; replacing each arithmetic operation statement with a safe arithmetic operation function call carrying overflow checking logic. When performing addition, the safe arithmetic operation function checks whether the sum of the two operands exceeds the maximum representation range of the current data type (for unsigned integers, it checks for overflow); when performing subtraction, it checks whether the minuend is less than the subtrahend (for unsigned integers, it checks for underflow); and when performing multiplication, it checks whether the product of the two operands exceeds the maximum representation range of the current data type. When the check results trigger an overflow condition, the safe arithmetic operation function triggers a rollback and outputs a descriptive error message (e.g., "arithmetic overflow, transaction rolled back") to eliminate the integer overflow vulnerability.
[0070] For the external call return value ignoring mode category, a return value assertion supplement operation is performed. The specific process is as follows: Locate the external call statement that ignores the return value within the code line range of the target code logic segment; at the code line containing the external call statement, rewrite the original call form that ignores the return value into a call form that explicitly receives the return value, i.e., insert the declaration code for the return value receiving variable (declare a boolean variable to store the success flag of the external call execution) before the external call statement and assign the return value of the external call to this variable; insert the return value success flag assertion code after the return value assignment statement. The assertion code reads the value of the return value receiving variable, and if its value is false, triggers execution rollback and outputs a descriptive error message (such as "External contract call failed, transaction rolled back"), ensuring that the contract can correctly terminate the current transaction and undo all executed state changes when the external call fails.
[0071] Replace the original code content within the corresponding code line range in the contract candidate code data with the code logic fragments that have been completely refactored. After the replacement is completed, the corrected contract code data is obtained.
[0072] Compilation and Bytecode Integrity Verification: Contract compilation is performed on the corrected contract code data. The specific process of contract compilation is as follows: The compiler corresponding to the contract programming language is called (in this embodiment, the Solidity language compiler is used as an example). The source code file of the corrected contract code data is used as the compiler input. The compiler performs compilation steps such as lexical analysis, syntax analysis, semantic checking, and bytecode generation on the source code file, and outputs the contract bytecode file and the application binary interface file. If the compiler outputs compilation failure information such as syntax error or type error during the compilation process, the compilation failure information and the corresponding corrected contract code data are re-encapsulated into a correction task item. The code generation agent is triggered again through the intelligent agent cooperative communication channel to perform the correction processing for the compilation error until the compilation is successfully completed and the contract bytecode file is output.
[0073] After successful compilation, bytecode integrity verification is performed on the generated contract bytecode file. The specific process of bytecode integrity verification is as follows: Parse the application binary interface file to extract the complete set of function selectors exposed by the contract bytecode (a function selector is the first four bytes of the hash value of a function signature, used to uniquely identify a function entry point in the contract); traverse all semantic units in the contract intent description data, extract the operation behavior identifier for each semantic unit, construct the corresponding function signature based on the operation behavior identifier, calculate the first four bytes of its hash value, and generate the expected function selector set; compare the expected function selector set with the function selector set extracted from the application binary interface file one by one to verify whether each element in the expected function selector set exists in the function selector set of the application binary interface file, thus confirming that the functions described by all semantic units in the contract intent description data are completely preserved in the generated contract bytecode. If, during the comparison process, elements not belonging to the application binary interface file function selector set are found in the expected function selector set, the corresponding semantic unit identifier is re-encapsulated as a correction task item. The code generation agent is then triggered again through the agent collaboration communication channel to supplement and build the missing functions until all bytecode integrity checks pass. If all comparison results are consistent, the compiled contract bytecode file is encapsulated as the final deployable contract data, completing the entire multi-agent collaborative blockchain smart contract generation process.
[0074] This solution utilizes the collaborative efforts of a requirements analysis agent, a code generation agent, a security audit agent, and a testing and verification agent to decompose the smart contract generation task into four specialized sub-tasks: semantic decomposition, code construction, security verification, and functional testing. Each agent focuses on task processing within its respective domain and forms a dynamic error correction feedback loop across stages through the agent collaboration communication channel. This fundamentally solves the problem of error propagation and cumulative amplification in single-model solutions, while eliminating the manual coordination costs caused by manually passing intermediate results between stages in serial toolchain solutions. This achieves high accuracy and high reliability in end-to-end automated generation of complex multi-party collaborative contracts.
[0075] Example 2
[0076] Please see Figure 2 As shown, parts not described in detail in this embodiment are described in Embodiment 1. A blockchain smart contract generation system based on multi-agent collaboration is provided, including:
[0077] Requirement decomposition module: Receives contract business requirement text described in natural language, performs multi-level semantic decomposition processing on the contract business requirement text through the requirement parsing intelligent agent, and obtains contract intent description data. The contract intent description data includes permission control semantic units, state transition semantic units, and cross-contract interaction semantic units.
[0078] The logic assembly module distributes the contract intent description data to the code generation agent through the agent collaboration communication channel. The code generation agent constructs the corresponding contract code logic fragments unit by unit according to the type label and dependency topology relationship of each semantic unit in the contract intent description data, and assembles and connects the contract code logic fragments according to the dependency topology relationship to generate contract candidate code data.
[0079] Vulnerability scanning module: Transmits contract candidate code data to security audit agent via intelligent agent collaborative communication channel. Security audit agent performs vulnerability pattern matching scan on permission verification paths and state change operations in contract candidate code data, and generates security audit report data with vulnerability location annotations.
[0080] State verification module: transmits contract candidate code data to test verification agent. Test verification agent constructs a contract execution test sequence with multiple conditions based on contract intent description data, performs state path traversal verification on contract candidate code data, and generates test verification result data containing abnormal path markers.
[0081] Targeted Correction Module: Based on the vulnerability location markers in the security audit report data and the abnormal path markers in the test verification result data, the module triggers the code generation agent through the agent collaboration communication channel to perform targeted correction on the corresponding code logic fragments in the contract candidate code data, thereby generating deployable contract data.
[0082] The above description is merely a preferred embodiment of the present invention and is not intended to limit the present invention. Although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art can still modify the technical solutions described in the foregoing embodiments or make equivalent substitutions for some of the technical features. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the protection scope of the present invention.
Claims
1. A method for generating blockchain smart contracts based on multi-agent collaboration, characterized in that, include: Step S1: Receive the contract business requirement text described in natural language, and perform multi-level semantic decomposition processing on the contract business requirement text through the requirement parsing intelligent agent to obtain contract intent description data. The contract intent description data includes permission control semantic units, state transition semantic units, and cross-contract interaction semantic units. Step S2: The contract intent description data is distributed to the code generation agent through the agent collaboration communication channel. The code generation agent constructs the corresponding contract code logic fragments unit by unit according to the type label and dependency topology relationship of each semantic unit in the contract intent description data, and assembles and connects each contract code logic fragment according to the dependency topology relationship to generate contract candidate code data. Step S3: The contract candidate code data is transmitted to the security audit agent through the agent collaboration communication channel. The security audit agent performs vulnerability pattern matching scan on the permission verification path and state change operation in the contract candidate code data, and generates security audit report data with vulnerability location annotations. Step S4: The contract candidate code data is transmitted to the test and verification agent. The test and verification agent constructs a multi-condition combination contract execution test sequence based on the contract intent description data, performs state path traversal verification on the contract candidate code data, and generates test and verification result data containing abnormal path markers. Step S5: Based on the vulnerability location markers in the security audit report data and the abnormal path markers in the test verification result data, trigger the code generation agent through the agent collaboration communication channel to perform targeted correction on the corresponding code logic fragments in the contract candidate code data, and generate deployable contract data.
2. The blockchain smart contract generation method based on multi-agent collaboration according to claim 1, characterized in that, Methods for obtaining contract intent description data include: The demand parsing agent identifies the sentence and segment boundaries of the contract business demand text. It uses action predicates and conditional adverbs as segmentation anchors to divide the contract business demand text into independent business semantic sentence segments. It extracts the subject role identifier, operation behavior identifier, and constraint condition identifier for each business semantic sentence segment and generates corresponding semantic triple data. Cross-segment role referencing resolution is performed on the semantic triple data corresponding to the business semantic segments. Role referencing resolution is performed by establishing an equivalent mapping table of subject role identifiers between different semantic triple data, replacing the referential role descriptions with unified role entity identifiers, and obtaining the resolved semantic triple set. Based on the logical implication relationship between the operation behavior identifier and constraint condition identifier of each semantic triple in the decomposed semantic triple set, the dependency topology relationship between semantic units is constructed. Semantic triple data involving role permission determination are classified as permission control semantic units, semantic triple data involving changes in internal contract variables are classified as state transition semantic units, and semantic triple data involving external contract calls are classified as cross-contract interaction semantic units. Contract intent description data is then assembled and generated.
3. The blockchain smart contract generation method based on multi-agent collaboration according to claim 2, characterized in that, The methods for obtaining contract candidate code data include: The code generation agent performs topological sorting on each semantic unit in the contract intent description data according to the dependency topology, determines the code construction priority sequence of each semantic unit, and marks the semantic unit without in-degree dependency as the root node semantic unit and enters the code construction queue first. For each semantic unit in the code building queue, the code generation agent selects the corresponding code building strategy according to its type label. Specifically, for the permission control semantic unit, the role permission assertion nested building strategy is used to generate code logic fragments containing multi-level signature verification logic. For the state transition semantic unit, the state machine transition path building strategy is used to generate code logic fragments containing precondition checks and poststate assignment. For the cross-contract interaction semantic unit, the external call encapsulation building strategy is used to generate code logic fragments containing call return value verification and exception rollback handling. Based on the directed edge relationships between semantic units in the dependency topology, parameter passing interface code and execution order control code are inserted between each contract code logic segment. The parameter passing interface code maps the output variables of the upstream code logic segment to the input parameters of the downstream code logic segment. The execution order control code sets the calling timing constraints between code logic segments according to the topology sorting result, and assembles all code logic segments into complete contract candidate code data.
4. The blockchain smart contract generation method based on multi-agent collaboration according to claim 3, characterized in that, The data transmission process of the intelligent agent cooperative communication channel includes: The sending agent encapsulates the business data to be transmitted into a communication message packet. This message packet includes a sending agent identifier, a receiving agent identifier, a message type flag, and a business data payload field. The message type flag distinguishes between three communication categories: task distribution messages, result feedback messages, and correction instruction messages. The agent collaborative communication channel has a built-in message routing scheduler. This scheduler maintains a task status register for each agent, recording the current work stage identifier and the version identifier of completed task data for each agent. Upon receiving a communication message packet, the message routing scheduler queries the task based on the receiving agent identifier. The state register table checks whether the current working stage identifier of the receiving agent meets the message reception preconditions corresponding to the communication message packet. When the message reception preconditions are met, the message routing scheduler injects the service data payload field of the communication message packet into the task input buffer of the receiving agent, and updates the working stage identifier and data version identifier of the receiving agent in the task state register table. When the message reception preconditions are not met, the message routing scheduler temporarily stores the communication message packet in the message waiting queue and continuously checks the task state register table of the receiving agent according to the preset state polling cycle until the preconditions are met and then performs the injection operation.
5. The blockchain smart contract generation method based on multi-agent collaboration according to claim 4, characterized in that, The methods for obtaining security audit report data include: The security audit agent extracts control flow paths from the contract candidate code data, expands the code branch structure layer by layer from the contract entry function, identifies all reachable execution paths from the entry function to the state change operation, generates a set of control flow paths, and marks all permission verification nodes and state change operation nodes that do not pass through permission verification nodes for each reachable execution path in the set of control flow paths. Load a pre-built contract vulnerability feature pattern library, which includes reentrant call patterns, unauthorized state tampering patterns, integer overflow operation patterns, and external call return value ignoring patterns. Perform subsequence matching operations on the operation node sequence of each reachable execution path in the control flow path set with each vulnerability pattern in the contract vulnerability feature pattern library to obtain vulnerability hit intervals. For all identified vulnerability hit intervals, extract the corresponding code line range and vulnerability pattern category identifier in the contract candidate code data for each vulnerability hit interval. Mark the code line range as a vulnerability location label and associate it with the corresponding vulnerability pattern category identifier. Summarize all vulnerability location labels to generate security audit report data.
6. The blockchain smart contract generation method based on multi-agent collaboration according to claim 5, characterized in that, The methods for obtaining test verification result data include: The test verifies that the intelligent agent extracts all state transition semantic units from the contract intent description data, parses the previous state identifier and the next state identifier in each state transition semantic unit, and constructs a directed graph of contract state transition. The nodes of the directed graph of contract state transition are contract state identifiers, and the directed edges are the state transition conditions described by the state transition semantic units. Based on the directed graph of contract state transition, a depth-first traversal is performed on all paths starting from the initial state node. For the state transition conditions attached to each directed edge on each traversal path, the role entity identifiers and constraint condition identifiers involved in the conditions are extracted and combined to generate the contract execution test sequence corresponding to the path. The contract execution test sequence contains multiple test transaction data arranged in the order of the path. Each test transaction data carries the calling role parameters, calling function identifiers and input parameter values. The contract candidate code data is deployed to the contract execution sandbox environment. The function call structure in the contract candidate code data is parsed, and the state variable operation sequence corresponding to each function call structure is extracted. The state variable operation sequence is associated and bound with the state transition conditions of the corresponding directed edges in the contract state transition directed graph, generating a path coverage mapping table between function call structures and directed edges. Test transaction data in each contract execution test sequence is submitted sequentially in the contract execution sandbox environment. A snapshot of the contract state variables after the execution of each test transaction is recorded. According to the path coverage mapping table, the contract state variable snapshot is mapped to the corresponding directed edge in the contract state transition directed graph. The consistency of the mapped contract state variable snapshot and the post-state identifier of the corresponding directed edge is compared. When the comparison result is inconsistent, the execution path position corresponding to the test transaction data is marked as an abnormal path marker. All abnormal path markers and corresponding contract state variable snapshots are summarized to generate test verification result data.
7. The blockchain smart contract generation method based on multi-agent collaboration according to claim 6, characterized in that, The code generation agent, triggered by the agent collaborative communication channel, performs targeted corrections on the corresponding code logic fragments in the contract candidate code data to generate deployable contract data, including: Extract all vulnerability location markers and their associated vulnerability mode category identifiers from the security audit report data. Extract all abnormal path markers and their associated contract state variable snapshots from the test verification result data. Collect the vulnerability location markers and abnormal path markers according to the code logic segments they point to in the contract candidate code data. Generate a remediation task list with code logic segments as the granularity. Each remediation task item in the remediation task list is associated with the target code logic segment identifier, vulnerability mode category identifier, and abnormal state variable snapshot. After receiving the list of correction tasks, the code generation agent performs partial reconstruction processing on the target code logic fragments in each correction task item. The partial reconstruction processing determines the correction operation type based on the vulnerability mode category identifier. For the reentrant call mode category, a state change pre-ordering operation is performed; for the unauthorized state tampering mode category, a permission verification node insertion operation is performed; for the integer overflow operation mode category, a secure arithmetic operation replacement operation is performed; and for the external call return value ignoring mode category, a return value assertion supplementation operation is performed. The partially reconstructed code logic fragments replace the original corresponding fragments in the contract candidate code data to generate the corrected contract code data. Contract compilation processing and bytecode integrity verification processing are performed on the corrected contract code data to confirm that the functional mapping relationship between the compiled contract bytecode and each semantic unit in the contract intent description data is completely preserved, generating deployable contract data.
8. The blockchain smart contract generation method based on multi-agent collaboration according to claim 2, characterized in that, For each business semantic segment, extract the subject role identifier, operation behavior identifier, and constraint condition identifier to generate corresponding semantic triple data, including: For each business semantic segment, perform part-of-speech level grammatical component annotation processing, identify the noun components that act as the action executor in the business semantic segment and extract them as candidate subject role identifiers, identify the predicate components that act as the core action in the business semantic segment and extract them as candidate operation behavior identifiers, and identify the subordinate structure components that act as limiting conditions in the business semantic segment and extract them as candidate constraint condition identifiers. Candidate subject role identifiers are matched using a contract domain role dictionary. When a candidate subject role identifier matches a set of synonyms for a role type entry in the contract domain role dictionary, the candidate subject role identifier is normalized to the standard role identifier for that role type entry. Candidate operation behavior identifiers are classified using contract operation semantic classification. Based on the execution effect of the operation behavior, the candidate operation behavior identifiers are classified into asset transfer operation identifiers, status modification operation identifiers, permission change operation identifiers, or information query operation identifiers. The normalized standard role identifiers, the classified operation identifiers, and the corresponding candidate constraint condition identifiers are combined and encapsulated into semantic triple data.
9. The blockchain smart contract generation method based on multi-agent collaboration according to claim 5, characterized in that, The operation node sequence of each reachable execution path in the control flow path set is matched with the vulnerability patterns in the contract vulnerability feature pattern library using a subsequence matching operation, including: For each vulnerability pattern in the contract vulnerability feature pattern library, extract its operation node type sequence template. The operation node type sequence template consists of an ordered arrangement of operation node type markers. The operation node type sequence template for the reentrant call pattern is a continuous arrangement with the external call node first and the state change node last. The operation node type sequence template for the unauthorized state tampering pattern is a missing arrangement with no permission verification node before the state change node. For each reachable execution path sequence in the control flow path set, extract sub-sequence windows of operation nodes with the same length as the operation node type sequence template along the sequence direction. Compare the node type marker of each operation node in the sub-sequence window with the corresponding operation node type marker in the operation node type sequence template. For operation node type sequence templates with missing arrangement types, search all positions where the target operation node type marker appears in the operation node sequence of the reachable execution path, and search the sequence interval before that position for whether a specified preceding operation node type marker exists. When all the comparison results of a certain operation node sub-sequence window are consistent or the specified preceding operation node type marker confirmed by the missing arrangement search results does not exist, it is determined that the current reachable execution path successfully matches the corresponding vulnerability pattern at the position of the sub-sequence window. Record the first and last operation nodes of the sub-sequence window as the starting and ending operation nodes of the vulnerability hit interval.
10. A blockchain smart contract generation system based on multi-agent collaboration, used to implement the blockchain smart contract generation method based on multi-agent collaboration as described in any one of claims 1 to 9, characterized in that, include: Requirement decomposition module: Receives contract business requirement text described in natural language, performs multi-level semantic decomposition processing on the contract business requirement text through the requirement parsing intelligent agent, and obtains contract intent description data. The contract intent description data includes permission control semantic units, state transition semantic units, and cross-contract interaction semantic units. The logic assembly module distributes the contract intent description data to the code generation agent through the agent collaboration communication channel. The code generation agent constructs the corresponding contract code logic fragments unit by unit according to the type label and dependency topology relationship of each semantic unit in the contract intent description data, and assembles and connects the contract code logic fragments according to the dependency topology relationship to generate contract candidate code data. Vulnerability scanning module: Transmits contract candidate code data to security audit agent via intelligent agent collaborative communication channel. Security audit agent performs vulnerability pattern matching scan on permission verification paths and state change operations in contract candidate code data, and generates security audit report data with vulnerability location annotations. State verification module: transmits contract candidate code data to test verification agent. Test verification agent constructs a contract execution test sequence with multiple conditions based on contract intent description data, performs state path traversal verification on contract candidate code data, and generates test verification result data containing abnormal path markers. Targeted Correction Module: Based on the vulnerability location markers in the security audit report data and the abnormal path markers in the test verification result data, the module triggers the code generation agent through the agent collaboration communication channel to perform targeted correction on the corresponding code logic fragments in the contract candidate code data, thereby generating deployable contract data.