Automatic generation method and device of intelligent contract

Through knowledge graphs and deep learning technology, smart contract codes are automatically generated, solving the problems of complexity of smart contract programming and incomplete code generation, and achieving efficient and reliable smart contract development.

CN119248276APending Publication Date: 2025-01-03HUNAN DATA IND GRP CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202411220490.6
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2024-09-02
Publication Date
2025-01-03

AI Technical Summary

Technical Problem

Smart contract programming is complex and time-consuming, making it difficult for ordinary users to write the correct contract code. The existing code base reuse method depends on the existence of similar code snippets, resulting in incomplete or inapplicable code generation code.

Method used

Using knowledge graph and deep learning technology, input rules through a graphical interface, convert them to JSON format, build knowledge graphs, train models to generate smart contract codes, and automate testing and deployment.

Benefits of technology

It improves the efficiency and quality of smart contract generation, reduces manual errors, realizes automated testing and deployment, and improves the reliability and security of contracts.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN119248276A_ABST
    Figure CN119248276A_ABST
Patent Text Reader

Abstract

The invention discloses an automatic generation method and device of a smart contract, and relates to the technical field of blockchains, and the method comprises the steps: inputting a rule of a blockchain smart contract through a graphical interface, converting the rule into data in a JSON format, analyzing the data in the JSON format, constructing a knowledge graph, and generating a knowledge graph; the method comprises the following steps: modeling attributes and relationships in a rule, training a model, and according to the model, mapping nodes and edges in a knowledge graph to different parts and functions of a contract, converting the attributes and relationships in the knowledge graph into codes of a block chain smart contract, compiling the codes into byte codes, and deploying the byte codes to a block chain network. And creating an executable smart contract instance. Through the method, automatic generation of the smart contract can be realized, manpower, material resources and time cost are saved, the development efficiency and quality of the smart contract are improved, semantic analysis and reasoning are performed by using the knowledge graph, and the smart contract code more in line with the intention and scene of the user is generated.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention relates to the field of blockchain technology, and in particular to a method and device for automatically generating a smart contract. Background Art

[0002] Smart contracts are an automatically executed transaction protocol based on blockchain technology. They can realize the exchange of various assets and services without the intervention and trust of a third party. Smart contracts are written in computer code and need to follow certain specifications and formats. However, smart contract programming is a challenging and complex task for ordinary users. It requires a certain programming foundation and blockchain knowledge, otherwise it may cause errors, loopholes in the contract code or fail to meet the user's intentions and needs. In addition, smart contract programming also requires a lot of manpower, material resources and time costs, especially when it comes to complex contracts with multiple participants, multiple scenarios and multiple conditions.

[0003] In order to solve the above problems, some researchers have proposed to generate smart contract code by extracting and reusing code snippets from existing contract code libraries. These methods can simplify the process of smart contract programming to a certain extent, reduce the difficulty and threshold of programming, and improve programming efficiency and quality. However, these methods also have some limitations and shortcomings. The method of extracting and reusing code snippets from existing contract code libraries relies on the existence of contract code snippets in the code library that match or are similar to user needs. If there is a lack of relevant contract code snippets in the code library, the generated smart contract code may be incomplete or inapplicable.

[0004] Therefore, there is a need for an automated generation method for smart contracts that can automatically generate smart contract codes that meet user needs based on rules input or selected by the user. Summary of the invention

[0005] A method for automatically generating smart contracts, which solves the technical problem of how to use knowledge graphs and deep learning technology to automatically generate blockchain smart contracts based on rules input or selected by users. The method includes the following steps:

[0006] Provide a graphical interface for users to enter or select the rules of blockchain smart contracts;

[0007] Convert the rules entered or selected by the user into data in JSON format;

[0008] Parse the data in JSON format to obtain JSON rules, build a knowledge graph based on the JSON rules, and model the attributes and relationships in the rules;

[0009] Training a model, wherein the model is used to generate smart contract code based on rule inference;

[0010] According to the trained model, the attributes and relationships in the knowledge graph are converted into the code of the blockchain smart contract by mapping the nodes and edges in the knowledge graph to the different parts and functions of the smart contract;

[0011] The generated code is compiled into bytecode and deployed to the blockchain network to create an executable smart contract instance.

[0012] This method produces the following beneficial effects: it improves the efficiency and quality of smart contract generation and reduces errors and risks in manual writing; it utilizes knowledge graphs and deep learning technologies to realize the automatic generation of smart contracts and improve the intelligence and flexibility of smart contracts; it realizes the automatic testing and deployment of smart contracts and improves the reliability and security of smart contracts.

[0013] In a preferred embodiment, the method further includes performing automated testing on the generated code. This step includes:

[0014] Generate a set of test cases based on the rule set, each test case contains an input and an expected output;

[0015] For each test case, send input to the smart contract address and get output;

[0016] Compare the output with the expected output and calculate the accuracy and coverage of the contract code;

[0017] If any output that does not meet the rules and requirements is found, a corresponding error prompt or modification suggestion will be given; otherwise, the result of the contract code test passing will be output.

[0018] This step produces the following beneficial effects: it improves the correctness and coverage of smart contracts and reduces potential vulnerabilities and risks; it utilizes test case and test framework technology to realize automated testing of smart contracts and improves the testability and maintainability of smart contracts; it realizes automated error prompts or modification suggestions for smart contracts and improves the improvability and optimizability of smart contracts.

[0019] In a preferred implementation, the converting of the rules input or selected by the user into data in JSON format specifically includes:

[0020] Perform grammatical analysis on the rules input or selected by the user to extract the subject, predicate and object components in the rules;

[0021] Encode the extracted components in JSON format to form a key-value pair data structure;

[0022] Store the encoded data structure in a JSON file.

[0023] This step produces the following beneficial effects: it improves the efficiency and accuracy of rule conversion and reduces the possibility of data loss and errors; it utilizes syntax analysis technology and JSON format technology to achieve automation and standardization of rule conversion and improve the versatility and compatibility of rule conversion; it achieves clarity and conciseness of the data structure after rule conversion and improves the readability and scalability of the data structure after rule conversion.

[0024] In a preferred implementation, the data in JSON format is parsed to obtain JSON rules, and a knowledge graph is constructed based on the JSON rules to model the attributes and relationships in the rules, specifically including:

[0025] Read rule data from JSON file;

[0026] The subject and object in the rule data are used as entity nodes in the knowledge graph, and the predicate in the rule data is used as the relationship edge in the knowledge graph;

[0027] According to the attribute values ​​and conditional restrictions in the rule data, add corresponding labels and weights to the nodes and edges in the knowledge graph;

[0028] Store the constructed knowledge graph in the graph database.

[0029] This step produces the following beneficial effects: it improves the efficiency and accuracy of rule parsing and modeling, and reduces the possibility of data redundancy and errors; it utilizes knowledge graph technology to realize the automation and standardization of rule parsing and modeling, and improves the versatility and compatibility of rule parsing and modeling; it achieves the clarity and completeness of the knowledge graph after rule parsing and modeling, and improves the visualization and queryability of the knowledge graph after rule parsing and modeling.

[0030] In a preferred implementation, the training model specifically includes:

[0031] Extract code snippets from existing contract code bases and smart contracts and convert them into abstract syntax trees;

[0032] Construct a code generation network, which consists of an encoder and a decoder. The encoder encodes the abstract syntax tree into a vector representation, and the decoder decodes the vector representation into a contract code.

[0033] Using the rule set as training data, the code generation network is trained through deep learning, so that it can generate contract code based on rule inference;

[0034] Output the trained code generation network model.

[0035] This step produces the following beneficial effects: it improves the efficiency and quality of smart contract code generation, reduces errors and risks of manual coding; utilizes deep learning technology to realize the automation and intelligence of smart contract code generation, improves the flexibility and innovation of smart contract code generation; realizes the adaptability and optimization of smart contract code generation, improves the scalability and maintainability of smart contract code generation.

[0036] In a preferred implementation, the mapping of nodes and edges in the knowledge graph to different parts and functions of the smart contract and the conversion of attributes and relationships in the knowledge graph into the code of the blockchain smart contract specifically include:

[0037] Read knowledge graph data;

[0038] According to the trained code generation network model, a corresponding contract code snippet is generated for each knowledge graph node and edge. The generation process of the contract code snippet is expressed by the following formula:

[0039]

[0040] f(v i , e i )=DEC(ENC(v i )+ENC(e i ))

[0041] Among them, C represents the set of generated smart contract code snippets, m represents the number of nodes in the knowledge graph, and v i Indicates the attribute corresponding to the i-th node, e i represents the combination of the edges connected to the i-th node, f represents the mapping function of the code generation network model, DEC represents the decoder function, and ENC represents the encoder function;

[0042] Assign priorities and orders to contract code snippets based on tags and weights in the knowledge graph;

[0043] Concatenate contract code snippets into a complete smart contract code file according to priority and sequence.

[0044] This step produces the following beneficial effects: it improves the efficiency and accuracy of smart contract code mapping and reduces the possibility of data loss and errors; it utilizes code mapping technology to realize the automation and standardization of smart contract code mapping and improves the versatility and compatibility of smart contract code mapping; it realizes the clarity and completeness of the code files after smart contract code mapping and improves the readability and executableness of the code files after smart contract code mapping.

[0045] In a preferred implementation, the contract code fragments are assigned priorities and orders according to the labels and weights in the knowledge graph, and the contract code fragments are spliced ​​into a complete contract code file according to the priorities and orders, specifically including:

[0046] For each contract code snippet, the sum of the label and weight of the corresponding node in the knowledge graph is calculated as the priority score of the contract code snippet. The priority score is calculated using the following formula:

[0047]

[0048] Where P represents the set of priority scores, n represents the number of smart contract code snippets, and p i represents the priority score of the i-th smart contract code snippet, k represents the number of nodes corresponding to the i-th smart contract code snippet, l j represents the label value of the jth node, w j Represents the weight value of the jth node;

[0049] Sort all contract code snippets by priority score from high to low to get an ordered list of contract code snippets;

[0050] Traverse the ordered list of contract code snippets, and insert them into the appropriate position of the contract code file according to the type and function of the contract code snippet to form a complete contract code file.

[0051] This step produces the following beneficial effects: it improves the efficiency and accuracy of smart contract code splicing and reduces the possibility of data loss and errors; it utilizes priority and sequence allocation technology to achieve automation and standardization of smart contract code splicing and improve the versatility and compatibility of smart contract code splicing; it achieves clarity and completeness of the code files after smart contract code splicing and improves the readability and executableness of the code files after smart contract code splicing.

[0052] In a preferred implementation, the generated code is compiled into bytecode and deployed on the blockchain network to create an executable smart contract instance, specifically including:

[0053] Call the smart contract compiler to compile the contract code file into a bytecode file;

[0054] Call the smart contract deployer to deploy the bytecode file to the blockchain network and return a smart contract address;

[0055] Output smart contract address.

[0056] This step produces the following beneficial effects: it improves the execution efficiency and security of smart contracts and reduces runtime errors and risks; it utilizes compiler and deployer technologies to achieve automated compilation and deployment of smart contracts and improves the deployability and interactivity of smart contracts; it achieves automated output and return of smart contracts and improves the accessibility and traceability of smart contracts.

[0057] An automatic generation device for smart contracts solves the technical problem of how to use knowledge graphs and deep learning technology to automatically generate blockchain smart contracts according to rules input or selected by users. The device includes:

[0058] The rule input module is used to provide a graphical interface for users to input or select the rules of blockchain smart contracts;

[0059] A rule conversion module is used to convert the rules input or selected by the user into data in JSON format;

[0060] A knowledge graph construction module is used to parse the data in the JSON format to obtain JSON rules, and to construct a knowledge graph based on the JSON rules to model the attributes and relationships in the rules;

[0061] A model training module, used to train a module for generating smart contract code based on rule inference;

[0062] Smart contract code mapping module, which is used to convert the attributes and relationships in the knowledge graph into the code of the blockchain smart contract by mapping the nodes and edges in the knowledge graph to the different parts and functions of the contract according to the trained model;

[0063] The smart contract code compilation module is used to compile the generated code into bytecode and deploy it to the blockchain network to create an executable smart contract instance. BRIEF DESCRIPTION OF THE DRAWINGS

[0064] Figure 1 is a flow chart of a method for automatically generating a smart contract according to an embodiment of the present invention;

[0065] Figure 2 is a flow chart of a training code generation network model according to an embodiment of the present invention;

[0066] Figure 3 is a flowchart of a smart contract code mapping process according to an embodiment of the present invention;

[0067] Figure 4 It is a schematic diagram of an automatic generation device of a smart contract according to an embodiment of the present invention. DETAILED DESCRIPTION

[0068] In order to enable those skilled in the art to better understand the technical solution, the technical solution is described in detail below in conjunction with the embodiments. The description in this section is only exemplary and explanatory and should not have any limiting effect on the scope of protection of the present invention.

[0069] Figure 1 is a flow chart of a method for automatically generating a smart contract according to an embodiment of the present invention. Figure 1 As shown, the method comprises the following steps:

[0070] Step S1, providing a graphical interface for users to input or select the rules of the blockchain smart contract.

[0071] The purpose of this step is to allow users to easily define the business logic and contract terms of the smart contract they want to implement without having to understand the programming language and details of the smart contract. The graphical interface can be a web page or an application with some options and input boxes for users to select or enter some rules, such as factors such as the customer's credit record, income level, loan amount, and calculate the customer's score, whether to lend, interest rate, and repayment period based on these factors. These rules can be some natural language sentences or some mathematical formulas or logical expressions. For example, users can enter or select the following rules:

[0072] Customers’ credit records are divided into three categories: excellent, fair, and poor, corresponding to credit coefficients of 0.8, 0.6, and 0.4, respectively;

[0073] The income levels of customers are divided into three categories: high, medium, and low, corresponding to income coefficients of 0.8, 0.6, and 0.4, respectively;

[0074] The customer's loan amount is divided into three categories: large, medium and small, corresponding to loan coefficients of 0.4, 0.6 and 0.8 respectively;

[0075] The customer's score calculation formula is: score = credit coefficient × income coefficient × loan coefficient × 100;

[0076] If the customer's score is greater than or equal to 60, the loan can be granted, otherwise the loan will be rejected;

[0077] If the customer is eligible for a loan, the interest rate and repayment period will be dynamically adjusted based on the score. The specific formula is: interest rate = [(100-score) / 10]%, repayment period = (score / 10)×12 months.

[0078] Step S2: converting the rules input or selected by the user into data in JSON format.

[0079] The rules entered or selected by the user are conditions expressed in natural language, which are used to determine whether the customer meets the loan requirements. In order for the computer to understand and execute these rules, they need to be converted into a standardized data format, namely JSON format. JSON format data can use key-value pairs to represent the various components in the rules, such as subject, predicate, object, etc., as well as the attributes of the object, such as type, value, etc. In this way, the computer can obtain and process the information in the rules based on the key-value pairs, thereby realizing the evaluation and screening of customers. Specifically, the following steps are included:

[0080] Step S21: Perform grammatical analysis on the rule input or selected by the user to extract the subject, predicate and object components in the rule.

[0081] Syntax analysis is a process of converting natural language into structured data that can be understood by computers. It can identify the components in a sentence and the relationship between them. For example, for the rule "the customer has a credit record", syntax analysis can extract the following components:

[0082] Subject: Customer

[0083] Predicate: Yes

[0084] Object: credit record.

[0085] Step S22: Encode the extracted components according to the JSON format to form a key-value pair data structure.

[0086] JSON format is a lightweight data exchange format based on a subset of the JavaScript language, which uses key-value pairs to store and represent data. For example, after encoding the extracted components into JSON format, the following data structure can be obtained:

[0087] {

[0088] "subject":"Customer",

[0089] "predicate":"yes",

[0090] "object":"Credit Record",

[0091] "attribute":{

[0092] "type":["Excellent","General","Poor"],

[0093] "value":[0.8,0.6,0.4]

[0094] }

[0095] }

[0096] Step S23: Store the encoded data structure in a JSON file.

[0097] A JSON file is a text file with a .json extension that can store and transmit data in JSON format. Storing the encoded data structure in a JSON file can facilitate subsequent reading and processing, and can also save storage space and network bandwidth.

[0098] Step S3, parse the data in JSON format to obtain JSON rules, build a knowledge graph based on the JSON rules, and model the attributes and relationships in the rules.

[0099] In order for computers to reason and generate these rules, they need to be converted into a graphical data structure, namely a knowledge graph. A knowledge graph is a graphical data model used to represent and store knowledge. It consists of entities, attributes, and relationships, where entities are nodes in the knowledge graph, attributes are the characteristics of entities, and relationships are the connections between entities. The knowledge graph can be easily displayed and queried graphically, and can also support complex logical reasoning and knowledge generation. Specifically, it includes the following steps:

[0100] Step S31: Read rule data from the JSON file.

[0101] Step S32: Use the subject and object in the rule data as entity nodes in the knowledge graph, and use the predicate in the rule data as the relationship edge in the knowledge graph.

[0102] An entity node is the basic unit in a knowledge graph, which represents a concrete or abstract thing, such as a customer, a rating, an interest rate, etc. A relationship edge is a line segment connecting entity nodes in a knowledge graph, which represents a certain connection between entity nodes, such as influence, equal, greater than, etc. Converting rule data into a knowledge graph can present the information in the rules in an intuitive and clear way.

[0103] Step S33: Add corresponding labels and weights to the nodes and edges in the knowledge graph according to the attribute values ​​and conditional restrictions in the rule data.

[0104] Labels are texts used to describe the characteristics or categories of entity nodes or relationship edges in the knowledge graph, such as credit records, credit coefficients, interest rate values, etc. Weights are numerical values ​​used to represent the importance or credibility of entity nodes or relationship edges in the knowledge graph, such as 0.5, 0.8, 0.4, etc. According to the attribute values ​​and conditional restrictions in the rule data, corresponding labels and weights can be added to the nodes and edges in the knowledge graph, thereby increasing the amount of information and accuracy in the knowledge graph. Storing the constructed knowledge graph in the graph database can facilitate subsequent retrieval and updates, and can also improve data security and efficiency.

[0105] For example, the first rule entered or selected by the user can be converted into a knowledge graph. In this knowledge graph, there are three entity nodes and two relationship edges, namely:

[0106] Entity Node 1: Customer (attribute: credit record; label value: 0.6; weight: 0.7)

[0107] Entity node 2: score (attribute: credit factor; label value: 0.7; weight: 0.7)

[0108] Entity node 3: interest rate (attribute: interest rate value; label value: 0.4; weight: 0.5)

[0109] Relationship edge 1: Influence (condition: credit record = excellent; then credit coefficient = 0.8; label value: 0.7; weight: 0.6)

[0110] Relationship edge 2: Influence (condition: score = 80, then interest rate value = 2%; label value: 0.5; weight: 0.6)

[0111] The above label values ​​are used to reflect the obviousness of the characteristics or categories of entity nodes or relationship edges. The higher the label value, the more obvious or clear the characteristics or categories of the entity or relationship are. The lower the label value, the more vague or uncertain the characteristics or categories of the entity or relationship are.

[0112] Step S34, storing the constructed knowledge graph in the graph database.

[0113] Step S4: training a model, wherein the model is used to generate smart contract code based on rule inference.

[0114] In order to enable computers to automatically generate smart contract codes according to these rules, it is necessary to use deep learning technology to train an artificial intelligence model that can automatically generate smart contract codes according to user-defined rules. Deep learning is a machine learning method based on artificial neural networks, which can learn abstract and complex features and rules from large amounts of data. Specifically, Figure 2 As shown, the following steps are included:

[0115] Step S41: extract code snippets from existing contract code libraries and smart contracts, and convert them into an abstract syntax tree, which is a tree data structure used to represent program code structure and semantics.

[0116] A contract code base is a software repository that stores and manages contract codes. It can provide functions such as version control, collaborative development, testing and deployment of contract codes. A smart contract is an automatically executed contract based on blockchain technology. It can perform transactions and operations according to preset conditions and logic without the intervention of a third party. An abstract syntax tree is a tree data structure used to represent the structure and semantics of program code. It consists of nodes and edges, where nodes represent various elements in the code, such as variables, functions, operators, etc., and edges represent grammatical relationships in the code, such as assignments, calls, loops, etc. Extracting code snippets from existing contract code bases and smart contracts and converting them into abstract syntax trees can easily obtain grammatical and semantic information in the code, and can also provide input and output for subsequent encoding and decoding.

[0117] Step S42: construct a code generation network, which consists of an encoder and a decoder. The encoder encodes the abstract syntax tree into a vector representation, and the decoder decodes the vector representation into a contract code.

[0118] The code generation network is an artificial intelligence model based on deep learning technology, which can automatically generate corresponding program codes according to the input rules or requirements; the encoder is a component in the code generation network, which can convert the input abstract syntax tree into a fixed-length vector representation, which can capture the grammatical and semantic features in the abstract syntax tree; the decoder is another component in the code generation network, which can convert the vector representation output by the encoder into the output contract code, which can meet the input rules or requirements. Building a code generation network can realize the automatic conversion from rules to code, and can also improve the efficiency and quality of code generation.

[0119] Step S43: Use the rule set as training data to perform deep learning training on the code generation network so that it can generate contract code based on rule inference.

[0120] Deep learning training is a process of optimizing the parameters of artificial intelligence models using large amounts of data, which can make artificial intelligence models more generalizable and adaptable. A rule set is a data set consisting of rules input or selected by the user, which can be used as input data for deep learning training. For each rule, a correct or expected contract code needs to be provided as the output data for deep learning training. Using the rule set as training data, deep learning training of the code generation network can enable it to generate contract code based on rule inference, and can also enable it to adapt to rules of different types and fields.

[0121] Step S44: output the trained code generation network model.

[0122] The trained code generation network model is an artificial intelligence model trained through deep learning, which can automatically generate smart contract code according to user-defined rules. Outputting the trained code generation network model can facilitate user use and can also be used for further testing and evaluation.

[0123] In step S5, according to the trained model, the attributes and relationships in the knowledge graph are converted into the code of the blockchain smart contract by mapping the nodes and edges in the knowledge graph to the different parts and functions of the smart contract.

[0124] The purpose of this step is to use the trained artificial intelligence model to convert the user-defined rules into executable smart contract code. Blockchain is a distributed, decentralized, tamper-proof, consensus mechanism, encrypted security, programmable, traceable, trustworthy, efficient, low-cost, open and transparent system.

[0125] Specifically, Figure 3 As shown, the following steps are included:

[0126] Step S51, reading knowledge graph data from the graph database;

[0127] Step S52: Generate a corresponding contract code snippet for each knowledge graph node and edge based on the trained code generation network model. The generation process of the smart contract code snippet is expressed by the following formula:

[0128]

[0129] f(v i , e i )=DEC(ENC(v i )+ENC(e i ))

[0130] Among them, C represents the set of generated smart contract code snippets, m represents the number of nodes in the knowledge graph, and vi Indicates the attribute corresponding to the i-th node, e i represents the combination of the edges connected to the i-th node, f represents the mapping function of the code generation network model, DEC represents the decoder function, and ENC represents the encoder function;

[0131] Step S53: assign priorities and orders to smart contract code snippets according to the tags and weights in the knowledge graph;

[0132] Step S54: splice the generated contract code fragments into a complete contract code file according to a certain priority and order.

[0133] Preferably, for each smart contract code snippet, the sum of the label and weight of the corresponding node in the knowledge graph is calculated as the priority score of the smart contract code snippet, and the priority score is calculated using the following formula:

[0134]

[0135] Where P represents the set of priority scores, n represents the number of smart contract code snippets, and p i represents the priority score of the i-th smart contract code snippet, k represents the number of nodes corresponding to the i-th smart contract code snippet, l j represents the label value of the jth node, w j Represents the weight value of the jth node;

[0136] Sort all smart contract code snippets according to their priority scores from high to low to obtain an ordered list of smart contract code snippets;

[0137] Traverse the ordered list of smart contract code snippets, and insert them into the appropriate position of the smart contract code file according to the type and function of the smart contract code snippet to form a complete smart contract code file.

[0138] Specifically, the following methods are used:

[0139] For each knowledge graph node and edge, convert its corresponding attributes and conditions into an abstract syntax tree;

[0140] For each abstract syntax tree, it is passed as input to the encoder of the code generation network model. The encoder encodes the abstract syntax tree into a vector representation. For example, the encoder function is used to convert the three nodes and two edges in the knowledge graph obtained in step S3 into the vector representation shown below:

[0141] ENC(client) = [0.1, 0.2, 0.3, 0.4]

[0142] ENC(score) = 90.5, 0.6, 0.7, 0.8]

[0143] ENC(interest rate) = [0.9, 1.0, 1.1, 1.2]

[0144] ENC(impact) = [1.3, 1.4, 1.5, 1.6]

[0145] For each vector representation, it is passed as input to the decoder of the code generation network model. The decoder decodes the vector representation into a contract code snippet. The contract code snippet is a text string used to represent the functions and logic of the smart contract. For example, the three nodes and two edges are converted into contract code snippets using a mapping function:

[0146] f(customer, impact) = DEC(ENC(customer) + ENC(impact)) = DEC([1.4, 1.6, 1.8, 2.0])

[0147] ="if(customer.incomeLevel=='high')customer.incomeFactor=0.8;"

[0148] f(score, impact) = DEC(ENC(score) + ENC(impact)) = DEC([1.8, 2.0, 2.2, 2.4])

[0149] ="if(customer.score==80)customer.interestRate=0.02;"

[0150] f(rate,null)=DEC(ENCrate))=DEC([0.9,1.0,1.1,1.2D="customer.paybackAmount

[0151] =customer.loanAmount*(1+customer.interestRate);”

[0152] For each contract code snippet, calculate the sum of the label and weight of the corresponding node or edge in the knowledge graph as the priority score of the contract code snippet. The priority score is a number used to represent the importance and order of contract code snippets when splicing. For example, the priority scores of the three contract code snippets are calculated using the above priority score function:

[0153] p 1 =0.6+0.7+0.7+0.6=2.6

[0154] p 2=0.7+0.7+0.5+0.6=2.5

[0155] p 3 =0.4+0.5=0.9;

[0156] Sort all contract code snippets by priority score from high to low to get an ordered list of contract code snippets, as shown below:

[0157] "if(customer.incomeLevel=='high'){customer.incomeFactor=0.8;}"

[0158] "if(customer.score==80){customer.interestRate=0.02;}"

[0159] "customer.paybackAmount=customer.loanAmoutnt*(1+customer.interestRate);"

[0160] Traverse the ordered list of contract code snippets, and insert them into the appropriate position of the contract code file according to the type and function of the contract code snippet to form a complete contract code file.

[0161] Step S6, compile the generated code into bytecode and deploy it on the blockchain network to create an executable smart contract instance.

[0162] The purpose of this step is to convert the generated smart contract code into a format that can be recognized and executed by the blockchain network, and publish it to the blockchain network so that it can be called and used by other users.

[0163] Specifically, the following steps are included:

[0164] Step S61: Call the smart contract compiler to compile the contract code file into a bytecode file.

[0165] The purpose of this operation is to convert the generated smart contract code into an intermediate code that can be interpreted or compiled by a specific virtual machine. Bytecode is an intermediate code that consists of a series of simple and compact instructions. It can run on different platforms and improve the efficiency and security of code execution. A smart contract compiler is a software tool that can convert smart contract codes written in different languages ​​into bytecode. For example, you can write smart contract code in Solidity and use the online compiler Remix to compile it into bytecode.

[0166] Step S62: Call the smart contract deployer to deploy the bytecode file to the blockchain network and return a smart contract address.

[0167] The purpose of this operation is to publish the generated bytecode file to the blockchain network and obtain an address that uniquely identifies the smart contract instance. The blockchain network is a distributed system composed of multiple nodes. It maintains an immutable transaction ledger through a consensus mechanism. Each node can run a virtual machine to execute the instructions in the bytecode file and record the results in the transaction ledger. The smart contract address is a string of numbers and letters that can be used to locate and access a specific smart contract instance. The smart contract deployer is a software tool that can send the bytecode file to the blockchain network and wait for it to be confirmed and executed. For example, if Ethereum is used as the blockchain network, the browser plug-in MetaMask can be used to deploy the bytecode file and obtain the smart contract address.

[0168] Step S63: Output the smart contract address.

[0169] Preferably, the method further comprises step S7, performing automated testing on the generated code.

[0170] The purpose of this step is to verify whether the generated smart contract code complies with the rules and requirements defined by the user and whether there are any errors or vulnerabilities.Automated testing is a process that uses software tools to execute pre-defined test cases and compare the actual output with the expected output.

[0171] Specifically, the following steps are included:

[0172] Step S71: Generate a set of test cases according to the rule set, each test case including an input and an expected output.

[0173] The purpose of this operation is to simulate customer behavior and results in different scenarios, and to verify whether the generated smart contract code can handle these scenarios correctly. A test case is a data set used to verify software functionality and performance. It consists of an input and an expected output. The input is data or instructions that simulate user operations or environmental changes, such as a customer applying for a loan, a change in a customer's credit record, etc. The expected output is an expected result or feedback, such as whether the loan is approved, the score, and the interest rate.

[0174] Step S72: For each test case, send input to the smart contract address and obtain output.

[0175] The purpose of this operation is to execute the generated smart contract code and observe its running results. Sending input to the smart contract address is the process of sending a transaction or query request to a specific smart contract instance through the blockchain network, which can trigger the corresponding function or logic in the smart contract. Getting output is the process of getting the result or event returned by a specific smart contract instance from the blockchain network, which can reflect the status or operation in the smart contract. For each test case, you can use the smart contract testing tool to send input to the smart contract address and get output.

[0176] Step S73: Compare the output with the expected output, and calculate the accuracy and coverage of the contract code.

[0177] The purpose of this operation is to evaluate whether the generated smart contract code meets all rules and requirements and whether there are any omissions or redundancies.

[0178] Step S74: If any output that does not meet the rules and requirements is found, a corresponding error prompt or modification suggestion is given; otherwise, the result that the contract code test passed is output.

[0179] From the above content, we can see that this method realizes the automatic generation of smart contracts, saves manpower, material resources and time costs, improves the development efficiency and quality of smart contracts, and uses knowledge graphs for semantic analysis and reasoning to generate smart contract codes that are more in line with user intentions and scenarios. At the same time, deep learning technology is used to realize the automatic generation of smart contracts, improve the intelligence and flexibility of smart contracts, realize the automatic testing and deployment of smart contracts, and improve the reliability and security of smart contracts.

[0180] Embodiment 2:

[0181] This embodiment provides an automatic generation device for smart contracts, which includes a rule input module, a rule conversion module, a knowledge graph construction module, a model training module, a contract code mapping module and a contract code compilation module. Figure 4 shown.

[0182] Specifically, the working process of the device is as follows:

[0183] Rule input module 801: This module is responsible for providing a graphical interface for users to input or select the rules of the blockchain smart contract, and passing the rules to the rule conversion module;

[0184] This module can be implemented in the following ways:

[0185] Rule input interface generation submodule: This submodule is responsible for designing a webpage or application, providing a form or drop-down menu for users to enter or select relevant information of the smart contract, such as contract type, platform, function, parameters, etc.

[0186] Rule string generation submodule: This submodule is responsible for generating a rule string based on the information input or selected by the user to represent the user's needs;

[0187] Rule string sending submodule: This submodule is responsible for sending the rule string to the rule conversion module.

[0188] Rule conversion module 802: This module is responsible for converting the rules input or selected by the user into data in JSON format and passing the data to the knowledge graph construction module;

[0189] This module can be implemented in the following ways:

[0190] Rule string receiving submodule: This submodule is responsible for receiving the rule string from the rule input module;

[0191] Rule string analysis submodule: This submodule is responsible for parsing the rule string and extracting the subject, predicate and object components in the rule;

[0192] JSON data encoding submodule: This submodule is responsible for encoding the extracted components in JSON format to form a key-value pair data structure;

[0193] JSON data sending submodule: This submodule is responsible for storing the encoded data structure in a JSON file and sending it to the knowledge graph construction module.

[0194] Knowledge graph construction module 803: This module is responsible for parsing the data in JSON format to obtain JSON rules, and constructing a knowledge graph based on the JSON rules, modeling the attributes and relationships in the rules, and passing the knowledge graph to the model training module;

[0195] This module can be implemented in the following ways:

[0196] JSON data receiving submodule: This submodule is responsible for receiving the JSON file from the rule conversion module;

[0197] JSON data parsing submodule: This submodule is responsible for reading rule data from JSON files;

[0198] Knowledge graph construction submodule: This submodule is responsible for taking the subject and object in the rule data as entity nodes in the knowledge graph, and taking the predicate in the rule data as the relationship edge in the knowledge graph; according to the attribute values ​​and conditional restrictions in the rule data, adding corresponding labels and weights to the nodes and edges in the knowledge graph;

[0199] Knowledge graph sending submodule: This submodule is responsible for storing the constructed knowledge graph in the graph database and sending it to the model training module.

[0200] Model training module 804: This module is responsible for training a model for generating smart contract code based on rule inference, and passing the trained model to the contract code mapping module;

[0201] This module can be implemented in the following ways:

[0202] Code snippet extraction submodule: This submodule is responsible for extracting code snippets from existing contract code bases and smart contracts and converting them into abstract syntax trees;

[0203] Code generation network construction submodule: This submodule is responsible for building a code generation network, which consists of an encoder and a decoder. The encoder encodes the abstract syntax tree into a vector representation, and the decoder decodes the vector representation into a contract code.

[0204] Code generation network training submodule: This submodule is responsible for using the rule set as training data to perform deep learning training on the code generation network, so that it can generate contract code based on rule inference;

[0205] Code generation network output submodule: This submodule is responsible for outputting the trained code generation network model and sending it to the contract code mapping module.

[0206] Smart contract code mapping module 805: This module is responsible for converting the attributes and relationships in the knowledge graph into the code of the blockchain smart contract by mapping the nodes and edges in the knowledge graph to the different parts and functions of the contract according to the trained model, and passing the code to the contract code compilation module;

[0207] This module can be implemented in the following ways:

[0208] Code generation network receiving submodule: This submodule is responsible for receiving the code generation network model from the model training module;

[0209] Knowledge graph receiving submodule: This submodule is responsible for receiving knowledge graph data from the knowledge graph building module;

[0210] Contract code snippet generation submodule: This submodule is responsible for generating corresponding contract code snippets for each knowledge graph node and edge based on the code generation network model. The generation process of the contract code snippet is expressed by the following formula:

[0211]

[0212] Among them, C represents the set of generated smart contract code snippets, m represents the number of nodes in the knowledge graph, and v i Indicates the attribute corresponding to the i-th node, e i represents the combination of the edges connected to the i-th node, f represents the mapping function of the code generation network model, DEC represents the decoder function, and ENC represents the encoder function;

[0213] Contract code snippet sorting submodule: This submodule is responsible for assigning priorities and orders to contract code snippets based on the tags and weights in the knowledge graph;

[0214] Contract code file splicing submodule: This submodule is responsible for splicing contract code fragments into a complete contract code file according to priority and sequence, and sending it to the contract code compilation module.

[0215] Smart contract code compilation module 806: This module is responsible for compiling the generated code into bytecode, deploying it to the blockchain network, creating an executable smart contract instance, and outputting the smart contract address;

[0216] This module can be implemented in the following ways:

[0217] Contract code file receiving submodule: This submodule is responsible for receiving the contract code file from the contract code mapping module;

[0218] Contract code compilation submodule: This submodule is responsible for calling the smart contract compiler to compile the contract code file into a bytecode file;

[0219] Contract code deployment submodule: This submodule is responsible for calling the smart contract deployer, deploying the bytecode file to the blockchain network, and returning a smart contract address;

[0220] Contract address output submodule: This submodule is responsible for outputting the smart contract address.

[0221] Preferably, the automatic generation device of the smart contract in this embodiment also includes a smart contract code testing module 807, which is responsible for automatically testing the generated contract code.

[0222] It should be noted that, in this article, the terms "include", "comprises" or any other variants thereof are intended to cover non-exclusive inclusion, so that a process, method, article or device including a series of elements includes not only those elements, but also other elements not explicitly listed, or also includes elements inherent to such process, method, article or device. Specific examples are used in this article to illustrate the principle and implementation of the technical solution of the present invention. The above examples are only used to help understand the method of the present invention and its core idea. The above is only a preferred implementation of the present invention. It should be pointed out that due to the limitations of textual expression and the objective existence of infinite specific structures, for ordinary technicians in this technical field, without departing from the principle of the present invention, several improvements, modifications or changes can be made, and the above technical features can also be combined in an appropriate manner; these improvements, modifications, changes or combinations, or the direct application of the concept and technical solution of the invention to other occasions without improvement, should be regarded as the protection scope of the present invention.

Claims

1. A method for automatically generating a smart contract, characterized in that: The following steps are involved: Provide a graphical interface for users to enter or select the rules of blockchain smart contracts; Convert the rules entered or selected by the user into data in JSON format; Parse the data in JSON format to obtain JSON rules, build a knowledge graph based on the JSON rules, and model the attributes and relationships in the rules; Training a model, wherein the model is used to generate smart contract code based on rule inference; According to the trained model, the attributes and relationships in the knowledge graph are converted into the code of the blockchain smart contract by mapping the nodes and edges in the knowledge graph to the different parts and functions of the smart contract; The generated code is compiled into bytecode and deployed to the blockchain network to create an executable smart contract instance.

2. The method for automatically generating a smart contract according to claim 1, characterized in that: The method also includes performing automated testing on the generated code.

3. The method for automatically generating a smart contract according to claim 1, characterized in that: The conversion of the rules input or selected by the user into data in JSON format specifically includes: Perform grammatical analysis on the rules input or selected by the user to extract the subject, predicate and object components in the rules; Encode the extracted components in JSON format to form a key-value pair data structure; Store the encoded data structure in a JSON file.

4. The method for automatically generating a smart contract according to claim 3, characterized in that: The JSON formatted data is parsed to obtain JSON rules, and a knowledge graph is constructed based on the JSON rules to model the attributes and relationships in the rules, specifically including: Read rule data from JSON file; The subject and object in the rule data are used as entity nodes in the knowledge graph, and the predicate in the rule data is used as the relationship edge in the knowledge graph; According to the attribute values ​​and conditional restrictions in the rule data, add corresponding labels and weights to the nodes and edges in the knowledge graph; Store the constructed knowledge graph in the graph database.

5. The method for automatically generating a smart contract according to claim 1, characterized in that: The training model specifically includes: Extract code snippets from existing smart contract code bases and smart contracts and convert them into abstract syntax trees; Construct a code generation network consisting of an encoder that encodes the abstract syntax tree into a vector representation and a decoder that decodes the vector representation into smart contract code; Using the rule set as training data, the code generation network is trained through deep learning, so that it can generate smart contract code based on rule inference; Output the trained code generation network model.

6. The method for automatically generating a smart contract according to claim 5, characterized in that: According to the trained model, the attributes and relationships in the knowledge graph are converted into the code of the blockchain smart contract by mapping the nodes and edges in the knowledge graph to different parts and functions of the smart contract, including: Read knowledge graph data; According to the trained code generation network model, a corresponding smart contract code snippet is generated for each knowledge graph node and edge. The generation process of the smart contract code snippet is expressed by the following formula: f(v i , yes i )=DEC(ENC(in i )+ENC(e i )) Among them, C represents the set of generated smart contract code snippets, m represents the number of nodes in the knowledge graph, and v i Indicates the attribute corresponding to the i-th node, e i represents the combination of the edges connected to the i-th node, f represents the mapping function of the code generation network model, DEC represents the decoder function, and ENC represents the encoder function; Assign priorities and orders to smart contract code snippets based on tags and weights in the knowledge graph; Concatenate smart contract code snippets into a complete smart contract code file according to priority and sequence.

7. The method for automatically generating a smart contract according to claim 6, characterized in that: The above-mentioned method assigns priorities and sequences to smart contract code snippets according to the labels and weights in the knowledge graph, and splices the smart contract code snippets into a complete smart contract code file according to the priorities and sequences, specifically including: For each smart contract code snippet, the sum of the label and weight of the corresponding node in the knowledge graph is calculated as the priority score of the smart contract code snippet. The priority score is calculated using the following formula: Where P represents the set of priority scores, n represents the number of smart contract code snippets, and p i represents the priority score of the i-th smart contract code snippet, k represents the number of nodes corresponding to the i-th smart contract code snippet, l j represents the label value of the jth node, w j Represents the weight value of the jth node; Sort all smart contract code snippets according to their priority scores from high to low to obtain an ordered list of smart contract code snippets; Traverse the ordered list of smart contract code snippets, and insert them into the appropriate position of the smart contract code file according to the type and function of the smart contract code snippet to form a complete smart contract code file.

8. The method for automatically generating a smart contract according to claim 2, characterized in that: The generated code is compiled into bytecode and deployed on the blockchain network to create an executable smart contract instance, including: Call the smart contract compiler to compile the smart contract code file into a bytecode file; Call the smart contract deployer to deploy the bytecode file to the blockchain network and return a smart contract address; Output smart contract address.

9. The method for automatically generating a smart contract according to claim 8, characterized in that: The automated testing of the generated code specifically includes: Generate a set of test cases based on the rule set, each test case contains an input and an expected output; For each test case, send input to the smart contract address and get output; Compare the output with the expected output and calculate the accuracy and coverage of the smart contract code; If any output that does not meet the rules and requirements is found, a corresponding error prompt or modification suggestion will be given; otherwise, the result of the smart contract code test passing will be output.

10. An automatic generation device for smart contracts, characterized in that: include: The rule input module is used to provide a graphical interface for users to input or select the rules of blockchain smart contracts; A rule conversion module is used to convert the rules input or selected by the user into data in JSON format; A knowledge graph construction module is used to parse the data in the JSON format to obtain JSON rules, and to construct a knowledge graph based on the JSON rules to model the attributes and relationships in the rules; A model training module, used to train a module for generating smart contract code based on rule inference; Smart contract code mapping module, which is used to convert the attributes and relationships in the knowledge graph into the code of the blockchain smart contract by mapping the nodes and edges in the knowledge graph to the different parts and functions of the smart contract according to the trained model; The smart contract code compilation module is used to compile the generated code into bytecode and deploy it to the blockchain network to create an executable smart contract instance.