Automatic detection method, system and computing device for malicious code in smart contracts
By combining the generation of an abstract syntax tree and a symbolic execution engine, combined with conditional statement analysis and a support vector machine model, the problems of incomplete coverage and missed reports in malicious code detection in blockchain smart contracts are solved, achieving efficient and accurate malicious contract detection.
Patent Information
- Application Number
- CN202510999345.0
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-07-21
- Publication Date
- 2025-09-12
- Estimated Expiration
- 2045-07-21
AI Technical Summary
Existing technologies for detecting malicious code in blockchain smart contracts have problems such as detection capabilities being limited by the scope of known attack samples and incomplete status coverage, resulting in a high risk of missed reports.
By generating an abstract syntax tree, extracting the storage status and address mapping relationship of the contract constructor, using the symbolic execution engine and cache pool to build a result deviation table, combining the conditional statement analyzer and symbol permutator, iteratively analyzing the address variable set, and using the support vector machine model to judge the maliciousness of the contract.
It achieves comprehensive detection of unknown malicious contracts, reduces the false alarm rate, improves detection coverage and accuracy, and can determine the maliciousness of contracts within milliseconds.
Smart Images

Figure CN120509033B_ABST
Abstract
Description
Technical Field
[0001] The present invention belongs to the field of security analysis and relates to smart contract technology, specifically to a method, system and computing device for automatically detecting malicious code in smart contracts. Background Art
[0002] Malicious code in blockchain smart contracts can severely harm the interests of contract users, causing them to lose trust in the smart contract and even the entire blockchain service. Therefore, automated and precise detection of malicious code in blockchain smart contracts is essential. There are two main approaches to automated detection of malicious code in smart contracts: code pattern-based and permission comparison-based. Code pattern-based methods analyze smart contract code to determine the execution path or control dependencies of the smart contract, then determine whether the path or dependency conforms to a pre-set pattern to determine whether the contract contains malicious code. Permission comparison-based methods identify privileged accounts with higher permissions than ordinary accounts among contract users, thereby uncovering malicious fragments within the contract associated with such accounts.
[0003] Existing technologies face significant application boundary constraints in the malicious signature detection layer. Methods based on code pattern matching rely heavily on the completeness of predefined malicious code signature libraries, limiting their detection capabilities to the scope of known attack samples. Permission comparison-based methods are only effective in smart contract scenarios where privileged accounts can be clearly identified. This results in fundamental technical flaws in existing methods for detecting new, unknown malicious contracts.
[0004] At the same time, at the state space analysis level, existing technologies generally face the challenge of incomplete state coverage; specifically, the method using fuzz testing technology can only explore part of the contract's execution state due to its random sampling characteristics, and the method using symbolic execution technology can theoretically achieve full state coverage, but in order to avoid the path explosion problem, it has to adopt a state space pruning strategy, which leads to the risk of missing key execution states in existing technologies. This incomplete state coverage will directly lead to the technical problem of missed detection of malicious code.
[0005] The present invention provides a method, system and computing device for automatically detecting malicious code in smart contracts to solve the above technical problems. Summary of the Invention
[0006] The present invention aims to solve at least one of the technical problems existing in the prior art; to this end, the present invention proposes a method, system and computing device for automatically detecting malicious code for smart contracts, which are used to solve the technical problem of the risk of missing key execution states, thereby causing underreporting of malicious code detection.
[0007] To achieve the above objectives, the first aspect of the present invention provides a method for automatically detecting malicious code in smart contracts, comprising:
[0008] S100: Receive the source code of the smart contract and parse the source code to generate an abstract syntax tree; wherein the abstract syntax tree includes: contract function definitions and global variables; contract function definitions include: contract constructors and non-contract constructors;
[0009] S200: Extract the contract constructor and use the storage state, address mapping relationship and initial variable values after the execution of the contract constructor as the initial state;
[0010] S300: traverse and identify all types of address variables in the abstract syntax tree as address variable sets, and classify the address variable sets into classification sets;
[0011] S400: calling the initial state and building a symbolic execution engine with a buffer pool, taking the initial state as input and outputting a matrix through the symbolic execution engine; building and initializing a result deviation table based on the output matrix; building a symbol permutator, updating the result deviation table according to the symbol permutator and generating a deviation function queue;
[0012] S500: Based on the deviation function queue, the result deviation is iteratively analyzed to obtain a final deviation variable set; based on the final deviation variable set, it is determined whether the corresponding smart contract is malicious; if so, an early warning signal is issued; if not, the malicious code automatic detection of the smart contract is completed.
[0013] Preferably, the classifying the address variable set into a classification set includes:
[0014] S310: Retrieve an address variable set, and classify each address variable in the address variable set through a conditional statement analyzer; wherein the classification types include: explicit conditional class and implicit external class;
[0015] S320: All explicit conditional classes and implicit external classes are combined to form a classification set C.
[0016] It should be noted that the implicit external class initially contains a variable EA for the external account.
[0017] By performing classification operations on address variables, the present invention helps to distinguish the importance of different address type variables to the contract function execution process. When an address belongs to the explicit conditional class, it means that at least one function must be called by this address to complete execution; at the same time, explicit and implicit classification avoids misjudging non-sensitive addresses (such as logging addresses) as high-risk targets, thereby reducing the false alarm rate.
[0018] Preferably, the classifying each address variable in the address variable set by the conditional statement analyzer includes:
[0019] Determine whether each address variable in the address variable set A exists in a conditional judgment statement of any function in the source code; if yes, mark the corresponding address content as being included in the explicit conditional class; if not, mark the corresponding address content as being included in the implicit external class.
[0020] Preferably, the step of using the initial state as input to output a matrix through a symbolic execution engine includes:
[0021] S411: Retrieve the initial state, transform the initial state into a row matrix, a function code, and a representative address of each category in the classification set, and use the row matrix, function code, and representative address of each category as input to the symbolic execution engine; wherein the function code includes: statements of numerical constraint type and statements of non-numerical constraint type;
[0022] S412: Build a conditional statement analyzer using third-party programming software; determine whether the input of the symbolic execution engine is a statement of a numerical constraint type; if so, place the statement of the numerical constraint type in a buffer pool through the symbolic execution engine and perform a symbolic value assignment operation; if not, directly execute the statement to obtain the subsequent state of the corresponding statement;
[0023] S413: The symbolic execution engine ultimately outputs a 2×n matrix, where n is the number of global variables in the smart contract. Each column of the matrix corresponds to a global variable, the first row represents the symbolic representation of the corresponding global variable, and the second row represents the numerical constraints associated with the corresponding global variable in the cache pool.
[0024] It should be noted that the symbolic execution engine is used to perform symbolic execution of contract function definitions with numerical decoupling.
[0025] The present invention uses matrix storage of global variable symbols and constraints to facilitate cross-function and cross-path state comparison, thereby supporting global state dependency analysis of complex contracts. The conditional statement analyzer distinguishes between numerical constraint statements and non-numerical constraint statements, which helps reduce the symbolic engine's analysis load on non-critical statements and concentrates resources on high-risk constraint logic.
[0026] Preferably, constructing and initializing a result deviation table based on the output matrix includes:
[0027] S421: Retrieve the representative addresses of each category in the classification set, randomly select one of the representative addresses and mark it as an anchor address, and mark the category to which the anchor address belongs as the anchor category;
[0028] S422: Call the non-contract constructor, use the non-contract constructor and the anchor address as input to the symbolic execution engine, and mark the first output matrix of the symbolic execution engine as the first-round anchor matrix corresponding to the non-contract constructor;
[0029] S423: Use the non-contract constructor and the non-anchor address as the input of the symbolic execution engine to obtain the secondary output matrix of the symbolic execution engine; determine whether the difference between the matrix subtraction of the secondary output matrix and the first-round anchor matrix is a non-zero matrix; if so, multiply the matrix subtraction difference by a 1×n all-one matrix to obtain the deviation value between the secondary output matrix and the first-round anchor matrix, and construct a result deviation table based on the deviation value and the secondary output matrix; if not, mark the symbolic execution result as no deviation; wherein, the symbolic execution result is the output matrix of the symbolic execution engine.
[0030] It should be noted that if the output result is marked as non-deviation, there is no need to construct a result deviation table and execute the operation of discarding the corresponding anchor address.
[0031] The present invention generates differentiated symbolic execution results for different address categories, which is conducive to quickly capturing malicious logic that depends on the caller identity; by constructing a result deviation table only when there is a difference between the secondary output matrix and the benchmark, it ensures that subsequent analysis resources are concentrated in high-risk areas.
[0032] Preferably, the updating of the result deviation table according to the symbol permutator and generating the deviation function queue comprises:
[0033] S431: Build a symbolic extractor and retrieve the result deviation table, build a mapping value between the deviation value and the symbolic execution result, and use the mapping value as the input of the symbolic extractor. The output is the symbolic representation of the global variable corresponding to the non-zero item in the quadratic output matrix in the corresponding row output matrix.
[0034] S432: Calling a symbol replacer, obtaining a symbolic representation of the required global variable for each row in the result deviation table based on the mapping value and the deviation value, and using the symbolic representation as input to the symbol replacer to obtain a replaced symbolic representation; updating the replaced symbolic representation to the secondary output matrix of the symbolic execution engine for the corresponding row; replacing the secondary output matrix in the result deviation table with the updated secondary output matrix to obtain an updated result deviation table;
[0035] S433: Obtain all functions in the first column of the updated result deviation table to generate a deviation function queue.
[0036] It should be noted that the symbol permutator is used to take the symbolic representation of any variable as the permutator input, and the permutator transforms the symbolic quantity in the symbolic representation into a new symbolic quantity that is different from the existing symbolic quantity.
[0037] The present invention generates a unique new symbol for each variable through a symbol replacer, ensuring symbol independence in multiple executions, thereby avoiding state misjudgment due to symbol overlap; through the symbolic representation of global variables, state changes can be tracked across functions and malicious cross-function collaboration can be captured; when updating the result deviation table, only the secondary output matrix is replaced instead of full reconstruction, reducing computational redundancy.
[0038] Preferably, the iterative analysis of the result deviation based on the deviation function queue to obtain the final deviation variable set includes:
[0039] S511: Calling the deviation function queue, traversing the deviation function queue, querying the corresponding row of each function in the deviation function queue in the result deviation table, and taking the output of the symbolic execution engine corresponding to the corresponding row, and using the first row of the submatrix in the output of the symbolic execution engine as input one;
[0040] S512: Retrieve the representative address of each category in the classification set C as input 2;
[0041] S513: Input 1 and input 2 are input to the symbolic execution engine, and the symbolic execution engine obtains an output matrix; the output matrix is subtracted from the first-round anchor matrix to obtain a calculation result; and a determination is made as to whether the calculation result is a non-zero matrix; if so, the calculation result is multiplied by a 1×n all-ones matrix to obtain a deviation value between the two outputs; if not, the symbolic execution result is marked as no deviation;
[0042] S514: Retrieve the global variables corresponding to the items whose deviation values are non-zero matrices and whose corresponding deviation values are not zero, and determine whether the corresponding global variables are not equal to the deviation values in the current row of the result deviation table. If so, update the deviation values of the current row and the symbolic execution engine output matrix; if not, mark the global variables corresponding to the items whose deviation values are not zero in the current row as the final deviation variable set, delete the current row from the result deviation table, and delete the current function from the deviation function queue.
[0043] S515: Determine whether the result deviation table is empty. If yes, mark it as end of determination. If not, repeat steps S511-S515.
[0044] By dynamically binding the deviation function queue with the result deviation table and introducing the representative address of the classification set C as an input variable, the present invention can simulate contract interactions in multiple roles and scenarios; thus, the present invention covers a wider range of malicious smart contracts than the existing technology.
[0045] Preferably, judging whether the corresponding smart contract is malicious based on the final deviation variable set includes:
[0046] Load the trained support vector machine model; retrieve the source code of the smart contract and input each i-th variable in the final deviation variable set into the support vector machine model; where i = 1, 2, 3, ..., m, and m is a positive integer;
[0047] Output m sensitive labels through the support vector machine model; where sensitive labels include: 0 and 1; sensitive label 0 indicates that each i-th variable currently input into the support vector machine model is not related to the preset sensitive operation, and sensitive label 1 indicates that each i-th variable currently input into the support vector machine model is related to the preset sensitive operation;
[0048] Determine whether there are variables related to preset sensitive operations in the final deviation variable set; if yes, mark the corresponding smart contract as malicious; if not, mark the corresponding smart contract as safe; among which, the preset sensitive operations include: transfer, contract destruction, and permission transfer.
[0049] It should be noted that the support vector machine model is trained using known malicious contract data.
[0050] The present invention trains a support vector machine model with known malicious contract data, and can accurately learn the variable characteristics of sensitive operations. Even if the malicious code is obfuscated or disguised, it can trigger the classification boundary by deviating from the key parameters in the variable set; the linear classification complexity of the support vector machine model is low, and the deviating variable set generated by symbolic execution can achieve millisecond-level single-sample judgment.
[0051] To achieve the above-mentioned object, a second aspect of the present invention provides an automatic malicious code detection system for smart contracts, comprising: a data input module, a result deviation analysis module, and a maliciousness determination module;
[0052] Data input module: receives the source code of the smart contract and parses the source code to generate an abstract syntax tree; the abstract syntax tree contains: contract function definitions and global variables; contract function definitions include: contract constructors and non-contract constructors;
[0053] Result deviation analysis module: Extracts the contract constructor and uses the storage state, address mapping relationship, and initial variable values after the execution of the contract constructor as the initial state; traverses and identifies all types of address variables in the abstract syntax tree and marks them as address variable sets, and classifies the address variable sets into classification sets;
[0054] Furthermore, the initial state is called and a symbolic execution engine with a buffer pool is constructed, the initial state is used as input and the symbolic execution engine outputs a matrix; a result deviation table is constructed and initialized based on the output matrix; a symbol permutator is constructed, the result deviation table is updated according to the symbol permutator, and a deviation function queue is generated;
[0055] Maliciousness determination module: Based on the deviation function queue, the result deviation is iteratively analyzed to obtain the final deviation variable set; based on the final deviation variable set, it is determined whether the corresponding smart contract is malicious; if so, an early warning signal is issued; if not, the malicious code of the smart contract is automatically detected.
[0056] A computing device for automatically detecting malicious code for smart contracts, characterized in that it includes: a memory and a processor, wherein the memory stores executable instructions of the processor; wherein the processor is configured to execute the method for automatically detecting malicious code for smart contracts provided by the first aspect by executing the executable instructions.
[0057] Compared with the prior art, the present invention has the following beneficial effects:
[0058] 1. The present invention can discover arithmetic vulnerabilities in advance through symbolic analysis of numerical constraints; identify hidden malicious logic by decoupling constraints; and aggregate deviations into a set form for analysis through iterative operations using deviation matrices. This approach is not limited to a specific type or types of malicious code patterns and does not require clear identification of which accounts are privileged. Therefore, it is also applicable to smart contracts with unclear account identities. This allows the present invention to cover a wider range of malicious smart contracts than existing technologies and discover more types of malicious smart contracts.
[0059] 2. The present invention uses a conditional statement analyzer to distinguish between numerical constraint statements and non-numerical constraint statements, which is beneficial to reducing the analysis load of the symbolic engine on non-critical statements and concentrating resources on high-risk constraint logic; when analyzing the source code, the deviation information between the streamlined state and other states is retained by constructing a deviation matrix and symbol substitution, and the deviation information is continuously propagated during the analysis process, ensuring that the valid information of the streamlined state is not discarded; thereby, the present invention retains the information of the streamlined nodes while streamlining the state space, avoiding the omission of malicious contracts due to streamlining. BRIEF DESCRIPTION OF THE DRAWINGS
[0060] In order to more clearly illustrate the embodiments of the present invention or the technical solutions in the prior art, the following briefly introduces the drawings required for use in the embodiments or the description of the prior art. Obviously, the drawings described below are only some embodiments of the present invention. For ordinary technicians in this field, other drawings can be obtained based on these drawings without paying any creative work.
[0061] Figure 1 A schematic diagram of the process of automatic malicious code detection of the present invention;
[0062] Figure 2 Schematic diagram of the specific steps of variable analysis of the present invention;
[0063] Figure 3 Schematic diagram of the specific steps of maliciousness determination in the present invention;
[0064] Figure 4 This is a schematic diagram of the relationship between the modules included in the present invention. DETAILED DESCRIPTION
[0065] The technical solutions of the present invention will be clearly and completely described below in conjunction with the embodiments. Obviously, the embodiments described are only some embodiments of the present invention, not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without making creative efforts are within the scope of protection of the present invention.
[0066] See also Figure 1 The first embodiment of the present invention provides a method for automatically detecting malicious code in smart contracts, including:
[0067] S100: Receive the source code of the smart contract and parse the source code to generate an abstract syntax tree; wherein the abstract syntax tree includes: contract function definitions and global variables; contract function definitions include: contract constructors and non-contract constructors;
[0068] S200: Extract the contract constructor and use the storage state, address mapping relationship and initial variable values after the execution of the contract constructor as the initial state;
[0069] S300: traverse and identify all types of address variables in the abstract syntax tree as address variable sets, and classify the address variable sets into classification sets;
[0070] S400: calling the initial state and building a symbolic execution engine with a buffer pool, taking the initial state as input and outputting a matrix through the symbolic execution engine; building and initializing a result deviation table based on the output matrix; building a symbol permutator, updating the result deviation table according to the symbol permutator and generating a deviation function queue;
[0071] S500: Based on the deviation function queue, the result deviation is iteratively analyzed to obtain a final deviation variable set; based on the final deviation variable set, it is determined whether the corresponding smart contract is malicious; if so, an early warning signal is issued; if not, the malicious code automatic detection of the smart contract is completed.
[0072] See also Figure 2 , the specific steps of result deviation analysis:
[0073] S310: Retrieve an address variable set, and classify each address variable in the address variable set through a conditional statement analyzer;
[0074] Determine whether each address variable in the address variable set A exists in a conditional judgment statement of any function in the source code; if yes, mark the corresponding address content as being classified into an explicit conditional class; if not, mark the corresponding address content as being classified into an implicit external class; wherein the classification types include: explicit conditional class and implicit external class;
[0075] S320: Merge all explicit conditional classes and implicit external classes to form a classification set C;
[0076] S411: Retrieve the initial state, transform the initial state into a row matrix, a function code, and a representative address of each category in the classification set, and use the row matrix, function code, and representative address of each category as input to the symbolic execution engine; wherein the function code includes: statements of numerical constraint type and statements of non-numerical constraint type;
[0077] S412: Build a conditional statement analyzer using third-party programming software; determine whether the input of the symbolic execution engine is a statement of a numerical constraint type; if so, place the statement of the numerical constraint type in a buffer pool through the symbolic execution engine and perform a symbolic value assignment operation; if not, directly execute the statement to obtain the subsequent state of the corresponding statement;
[0078] S413: The symbolic execution engine ultimately outputs a 2×n matrix, where n is the number of global variables in the smart contract. Each column of the matrix corresponds to a global variable, the first row represents the symbolic representation of the corresponding global variable, and the second row represents the numerical constraints associated with the corresponding global variable in the cache pool.
[0079] S421: Retrieve the representative addresses of each category in the classification set, randomly select one of the representative addresses and mark it as an anchor address, and mark the category to which the anchor address belongs as the anchor category;
[0080] S422: Call the non-contract constructor, use the non-contract constructor and the anchor address as input to the symbolic execution engine, and mark the first output matrix of the symbolic execution engine as the first-round anchor matrix corresponding to the non-contract constructor;
[0081] S423: Use the non-contract constructor and the non-anchor address as input to the symbolic execution engine to obtain the secondary output matrix of the symbolic execution engine; determine whether the difference between the secondary output matrix and the first-round anchor matrix is a non-zero matrix; if so, multiply the difference between the matrix subtraction and the 1×n all-ones matrix to obtain the deviation value between the secondary output matrix and the first-round anchor matrix, and construct a result deviation table based on the deviation value and the secondary output matrix; if not, mark the symbolic execution result as no deviation; the symbolic execution result is the output matrix of the symbolic execution engine;
[0082] S431: Build a symbolic extractor and retrieve the result deviation table, build a mapping value between the deviation value and the symbolic execution result, and use the mapping value as the input of the symbolic extractor. The output is the symbolic representation of the global variable corresponding to the non-zero item in the quadratic output matrix in the corresponding row output matrix.
[0083] S432: Calling a symbol replacer, obtaining a symbolic representation of the required global variable for each row in the result deviation table based on the mapping value and the deviation value, and using the symbolic representation as input to the symbol replacer to obtain a replaced symbolic representation; updating the replaced symbolic representation to the secondary output matrix of the symbolic execution engine for the corresponding row; replacing the secondary output matrix in the result deviation table with the updated secondary output matrix to obtain an updated result deviation table;
[0084] S433: Obtain all functions in the first column of the updated result deviation table to generate a deviation function queue.
[0085] For example, the source code of the BOBCHAIN contract is received as input, the source code is parsed, and an abstract syntax tree (AST) is generated. The AST contains the contract functions: ransfer and updateFee, as well as global variables: balances, txFee, and FeeAddress.
[0086] Since there is no explicit constructor in the BOBCHAIN contract, the initial state includes the default symbolic storage state and variable initial values, that is, _balances is {FeeAddress: _balances[FeeAddress], ExtAddress: _balances[ExtAddress]}, where the initial values of variables are all symbolic values; the value of txFee is represented by a symbolic quantity named txFee; and the initial value of FeeAddress is represented by a symbolic quantity named FeeAddress.
[0087] Traverse the AST and identify all global variables of address type. In the BOBCHAIN contract, FeeAddress is the only global variable of address type.
[0088] Write code to insert a conditional statement analyzer. In the _transfer function, FeeAddress is used for conditional judgment (sender!=FeeAddress), so it is classified into the explicit condition class C_f;
[0089] Output classification set C, including explicit conditional class C_f and implicit external class C_imp (containing only one symbolic address representing an external account);
[0090] Now take updateFee as an example to build the result deviation table;
[0091] Take a representative address from each category in the classification set C, namely: FeeAddress and ExtAddress;
[0092] Build a symbolic execution engine with a cache pool and perform two numerically decoupled symbolic executions on the function. The first engine input is the row matrix obtained from the starting state transition, the code of the updateFee function, and FeeAddress. The second engine input is the row matrix obtained from the starting state transition, the code of the updateFee function, and ExtAddress.
[0093] The output of the first execution is matrix J1 (as shown in Table 1)
[0094] Table 1 Matrix J1
[0095]
[0096] Here, txFee1 is a symbolic amount not equal to the initial txFee, and FeeAddress1 is a symbolic amount not equal to the initial FeeAddress;
[0097] The output of the second execution is matrix J2 (see Table 2);
[0098] Table 2 Matrix J2
[0099]
[0100] Assuming that FeeAddress is selected as the anchor address, the output matrix of the first execution is the first-round anchor matrix of the updateFee function;
[0101] The above matrices are subtracted to obtain a non-zero matrix, which is multiplied by the 1×4 all-one matrix to obtain the matrix J3 (as shown in Table 3);
[0102] Table 3 Matrix J3
[0103]
[0104] Then create a result deviation table (such as Table 4);
[0105] Table 4 Result deviation table
[0106]
[0107] Construct a symbolic permutator, the input of which is a symbolic representation of any variable, and the permutator transforms the symbolic quantity in the symbolic representation into a newly created symbolic quantity, which is different from the existing symbolic quantity;
[0108] For each row in the result deviation table, construct a mapping f between the deviation value and the output result, such that the input of f is the deviation value, and the output is the symbolic representation of the global variable corresponding to the non-zero entry in the deviation matrix in the output result of that row. Input the deviation value in the above table, and the output of mapping f is {txFee, FeeAddress};
[0109] For each row in the result deviation table, the symbolic representation of the required global variable is obtained according to the mapping f and the deviation value, and the symbol permutator is applied to it. The permuted symbolic representation is updated to the symbolic execution engine output matrix of the row. The symbolic execution engine output matrix in the above table is updated to matrix J4 (as shown in Table 5);
[0110] Table 5 Matrix J4
[0111]
[0112] Get all functions whose results deviate from the first column in the table and generate a deviation function queue {updateFee}.
[0113] See also Figure 3 ,Specific steps for maliciousness determination: S511: call the deviation function queue, traverse the deviation function queue, query the corresponding row of each function in the deviation function queue in the result deviation table, and take out the output of the corresponding symbolic execution engine in the corresponding row, and use the first row sub-matrix in the output of the symbolic execution engine as input one;
[0114] S512: Retrieve the representative address of each category in the classification set C as input 2;
[0115] S513: Input 1 and input 2 are input to the symbolic execution engine, and the symbolic execution engine obtains an output matrix; the output matrix is subtracted from the first-round anchor matrix to obtain a calculation result; and a determination is made as to whether the calculation result is a non-zero matrix; if so, the calculation result is multiplied by a 1×n all-ones matrix to obtain a deviation value between the two outputs; if not, the symbolic execution result is marked as no deviation;
[0116] S514: Retrieve the global variables corresponding to the items whose deviation values are non-zero matrices and whose corresponding deviation values are not zero, and determine whether the corresponding global variables are not equal to the deviation values in the current row of the result deviation table. If so, update the deviation values of the current row and the symbolic execution engine output matrix; if not, mark the global variables corresponding to the items whose deviation values are not zero in the current row as the final deviation variable set, delete the current row from the result deviation table, and delete the current function from the deviation function queue.
[0117] S515: Determine whether the result deviation table is empty. If yes, mark it as end of determination. If no, repeat steps S511-S515.
[0118] Load the trained support vector machine model; retrieve the source code of the smart contract and input each i-th variable in the final deviation variable set into the support vector machine model; where i = 1, 2, 3, ..., m, and m is a positive integer;
[0119] Output m sensitive labels through the support vector machine model; where sensitive labels include: 0 and 1; sensitive label 0 indicates that each i-th variable currently input into the support vector machine model is not related to the preset sensitive operation, and sensitive label 1 indicates that each i-th variable currently input into the support vector machine model is related to the preset sensitive operation;
[0120] Determine whether there are variables related to preset sensitive operations in the final deviation variable set; if yes, mark the corresponding smart contract as malicious; if not, mark the corresponding smart contract as safe; among which, the preset sensitive operations include: transfer, contract destruction, and permission transfer.
[0121] For example, call the deviation function queue {updateFee}, traverse the deviation function queue, query the corresponding row in the result deviation table for each function, and extract the symbolic execution engine output. Use the first row of the submatrix in the output as input, and take a representative address from each category in the set C to perform another round of symbolic execution. The input submatrix is: matrix J5 (as shown in Table 6);
[0122] Table 6 Matrix J5
[0123]
[0124] Take FeeAddress and ExtAddress as representative addresses respectively and execute twice. The first engine input is the above sub-matrix, the code of the updateFee function, and FeeAddress. The second engine input is the above sub-matrix, the code of the updateFee function, and ExtAddress. The output of the first execution is: matrix J6 (as shown in Table 7).
[0125] Table 7 Matrix J6
[0126]
[0127] Here, txFee2 is a symbolic amount not equal to the initial txFee, txFee1, and newtxFee; here, FeeAddress2 is a symbolic amount not equal to the initial FeeAddress, FeeAddress1, and newFeeAddress;
[0128] The output of the second execution is: matrix J7 (as shown in Table 8);
[0129] Table 8 Matrix J7
[0130]
[0131] Then, the output matrix is subtracted from the first-round anchor matrix. The matrix subtraction results in a non-zero matrix, which is multiplied with the 1×4 all-one matrix to obtain the matrix J8 (see Table 9).
[0132] Table 9 Matrix J8
[0133]
[0134] The global variable corresponding to this deviation value is {txFee, FeeAddress}. The deviation value for the current row in the resulting deviation table also corresponds to {txFee, FeeAddress}. Therefore, {txFee, FeeAddress} is stored in the final deviation variable set, the current row is deleted from the deviation table, and the current function is removed from the deviation function queue. If the resulting deviation table is empty, a pre-trained vector machine model (trained with known malicious contract data) is loaded. This model takes as input the source code of the smart contract to be analyzed and an item from the final deviation value set. Its output is whether the item is related to a sensitive operation in the contract (transfer, contract destruction, permission transfer). Model evaluation indicates that both txFee and FeeAddress have a high probability (greater than 0.9) of being related to transaction fees in financial operations, making them sensitive variables. Therefore, the input contract is determined to be malicious.
[0135] It should be noted that the steps for loading the pre-trained support vector machine model are: collect 1,000 smart contracts, manually determine and label each variable in them as being related to sensitive operations; use the labeled data to train the support vector machine model, with a maximum training round of 3,000, and calculate the cross-entropy loss every 100 rounds. The training is completed when the preset maximum number of rounds is reached, or when the loss of two consecutive calculations does not decrease.
[0136] See also Figure 4 , a second aspect of the present invention provides an automatic malicious code detection system for smart contracts, including: a data input module, a result deviation analysis module, and a maliciousness determination module;
[0137] Data input module: receives the source code of the smart contract and parses the source code to generate an abstract syntax tree; the abstract syntax tree contains: contract function definitions and global variables; contract function definitions include: contract constructors and non-contract constructors;
[0138] Result deviation analysis module: Extracts the contract constructor and uses the storage state, address mapping relationship, and initial variable values after the execution of the contract constructor as the initial state; traverses and identifies all types of address variables in the abstract syntax tree and marks them as address variable sets, and classifies the address variable sets into classification sets;
[0139] Furthermore, the initial state is called and a symbolic execution engine with a buffer pool is constructed, the initial state is used as input and the symbolic execution engine outputs a matrix; a result deviation table is constructed and initialized based on the output matrix; a symbol permutator is constructed, the result deviation table is updated according to the symbol permutator, and a deviation function queue is generated;
[0140] Maliciousness determination module: Based on the deviation function queue, the result deviation is iteratively analyzed to obtain the final deviation variable set; based on the final deviation variable set, it is determined whether the corresponding smart contract is malicious; if so, an early warning signal is issued; if not, the malicious code of the smart contract is automatically detected.
[0141] An embodiment of the third aspect of the present invention provides a computing device for automatically detecting malicious code for smart contracts, comprising: a memory and a processor, wherein the memory stores executable instructions of the processor; wherein the processor is configured to execute the method for automatically detecting malicious code for smart contracts provided in the first aspect by executing the executable instructions.
[0142] Some of the data in the above formula are calculated by removing the dimensions and taking their numerical values. The formula is a formula that is closest to the actual situation obtained by software simulation of a large amount of collected data; the preset parameters and preset thresholds in the formula are set by technical personnel in this field according to actual conditions or obtained through simulation of a large amount of data.
[0143] The working principle of the present invention is as follows: receiving the source code of the smart contract, parsing the source code to generate an abstract syntax tree; the result deviation analysis module: extracting the contract constructor, taking the storage state, address mapping relationship and initial variable value after the execution of the contract constructor as the initial state; traversing and identifying all types of address variables in the abstract syntax tree and marking them as address variable sets, classifying the address variable sets into classification sets; calling the initial state and building a symbolic execution engine with a buffer pool, taking the initial state as input and outputting a matrix through the symbolic execution engine; building and initializing a result deviation table based on the output matrix; building a symbol replacer, updating the result deviation table according to the symbol replacer and generating a deviation function queue; iteratively analyzing the result deviation based on the deviation function queue to obtain a final deviation variable set; judging whether the corresponding smart contract is malicious based on the final deviation variable set; if yes, issuing a warning signal; if not, completing the automatic detection of malicious code in the smart contract.
[0144] The above embodiments are only used to illustrate the technical method of the present invention and are not intended to limit the present invention. Although the present invention has been described in detail with reference to the preferred embodiments, those skilled in the art should understand that the technical method of the present invention may be modified or replaced by equivalents without departing from the spirit and scope of the technical method of the present invention.
Claims
1. Automatic detection method for malicious code in smart contracts, characterized by: include: S100: Receive the source code of the smart contract and parse the source code to generate an abstract syntax tree; wherein the abstract syntax tree includes: contract function definitions and global variables; contract function definitions include: contract constructors and non-contract constructors; S200: Extract the contract constructor and use the storage state, address mapping relationship and initial variable values after the execution of the contract constructor as the initial state; S300: traverse and identify all types of address variables in the abstract syntax tree as address variable sets, and classify the address variable sets into classification sets; S400: calling an initial state and building a symbolic execution engine with a buffer pool, taking the initial state as input and outputting a matrix through the symbolic execution engine; building and initializing a result deviation table based on the output matrix; building a symbol permutator, updating the result deviation table according to the symbol permutator, and generating a deviation function queue; wherein the symbol permutator is used to take a symbolic representation of any variable as input to the permutator, and the permutator transforms the symbolic quantity in the symbolic representation into a new symbolic quantity that is different from the existing symbolic quantity; S500: Iteratively analyzing the result deviation based on the deviation function queue to obtain a final deviation variable set; judging whether the corresponding smart contract is malicious based on the final deviation variable set; if so, issuing a warning signal; The step of constructing and initializing a result deviation table based on the output matrix includes: S421: Retrieve the representative addresses of each category in the classification set, randomly select one of the representative addresses and mark it as an anchor address, and mark the category to which the anchor address belongs as the anchor category; S422: Call the non-contract constructor, use the non-contract constructor and the anchor address as input to the symbolic execution engine, and mark the first output matrix of the symbolic execution engine as the first-round anchor matrix corresponding to the non-contract constructor; S423: Use the non-contract constructor and the non-anchor address as the input of the symbolic execution engine to obtain the secondary output matrix of the symbolic execution engine; determine whether the difference between the matrix subtraction of the secondary output matrix and the first-round anchor matrix is a non-zero matrix; if so, multiply the difference between the matrix subtraction and the 1×n all-one matrix to obtain the deviation value between the secondary output matrix and the first-round anchor matrix, and construct a result deviation table based on the deviation value and the secondary output matrix; if not, mark the symbolic execution result as no deviation; wherein, the symbolic execution result is the output matrix of the symbolic execution engine, and n is the number of global variables in the smart contract.
2. The method for automatically detecting malicious code in smart contracts according to claim 1, wherein: The classifying the address variable set into a classification set includes: S310: Retrieve an address variable set, and classify each address variable in the address variable set through a conditional statement analyzer; wherein the classification types include: explicit conditional class and implicit external class; S320: All explicit conditional classes and implicit external classes are combined to form a classification set.
3. The method for automatically detecting malicious code in smart contracts according to claim 2, wherein: The process of classifying each address variable in the address variable set by the conditional statement analyzer includes: Determine whether each address variable in the address variable set A exists in a conditional judgment statement of any function in the source code; if yes, mark the corresponding address content as being included in the explicit conditional class; if not, mark the corresponding address content as being included in the implicit external class.
4. The method for automatically detecting malicious code in smart contracts according to claim 1, wherein: The method of using the initial state as input and outputting a matrix through a symbolic execution engine includes: S411: Retrieve the initial state, transform the initial state into a row matrix, a function code, and a representative address of each category in the classification set, and use the row matrix, function code, and representative address of each category as input to the symbolic execution engine; wherein the function code includes: statements of numerical constraint type and statements of non-numerical constraint type; S412: Build a conditional statement analyzer; determine whether the input of the symbolic execution engine is a statement of a numerical constraint type; if so, place the statement of the numerical constraint type in a cache pool through the symbolic execution engine and perform symbolic value assignment; if not, directly execute the statement to obtain the subsequent state of the corresponding statement; S413: The symbolic execution engine finally outputs a 2×n matrix; each column of the matrix corresponds to a global variable, the first row represents the symbolic representation of the corresponding global variable, and the second row represents the numerical constraints related to the corresponding global variable in the cache pool.
5. The method for automatically detecting malicious code in smart contracts according to claim 1, wherein: The updating of the result deviation table according to the symbol permutator and generating the deviation function queue include: S431: Build a symbolic extractor and retrieve the result deviation table, build a mapping value between the deviation value and the symbolic execution result, and use the mapping value as the input of the symbolic extractor. The output is the symbolic representation of the global variable corresponding to the non-zero item in the quadratic output matrix in the corresponding row output matrix. S432: Calling a symbol replacer, obtaining a symbolic representation of the required global variable for each row in the result deviation table based on the mapping value and the deviation value, and using the symbolic representation as input to the symbol replacer to obtain a replaced symbolic representation; updating the replaced symbolic representation to the secondary output matrix of the symbolic execution engine for the corresponding row; replacing the secondary output matrix in the result deviation table with the updated secondary output matrix to obtain an updated result deviation table; S433: Obtain all functions in the first column of the updated result deviation table to generate a deviation function queue.
6. The method for automatically detecting malicious code in smart contracts according to claim 4, wherein: The iterative analysis of the result deviation based on the deviation function queue to obtain the final deviation variable set includes: S511: Calling the deviation function queue, traversing the deviation function queue, querying the corresponding row of each function in the deviation function queue in the result deviation table, and taking the output of the symbolic execution engine corresponding to the corresponding row, and using the first row of the submatrix in the output of the symbolic execution engine as input one; S512: Retrieve the representative address of each category in the classification set as input 2; S513: Input 1 and input 2 are input to the symbolic execution engine, and the output matrix is obtained through the symbolic execution engine; the output matrix is subtracted from the first-round anchor matrix to obtain the operation result; and it is determined whether the operation result is a non-zero matrix; if so, the operation result is multiplied by the all-ones matrix to obtain the deviation value of the two outputs; if not, the symbolic execution result is marked as no deviation; S514: Retrieve the global variables corresponding to the items whose deviation values are non-zero matrices and whose corresponding deviation values are not zero, and determine whether the corresponding global variables are not equal to the deviation values in the current row of the result deviation table. If so, update the deviation values of the current row and the symbolic execution engine output matrix; if not, mark the global variables corresponding to the items whose deviation values are not zero in the current row as the final deviation variable set, delete the current row from the result deviation table, and delete the current function from the deviation function queue. S515: Determine whether the result deviation table is empty. If yes, mark it as end of determination. If not, repeat steps S511-S515.
7. The method for automatically detecting malicious code in smart contracts according to claim 1, wherein: The determining whether the corresponding smart contract is malicious based on the final deviation variable set includes: Load the trained support vector machine model; retrieve the source code of the smart contract and input each i-th variable in the final deviation variable set into the support vector machine model; where i = 1, 2, 3, ..., m, and m is a positive integer; Output m sensitive labels through the support vector machine model; wherein the sensitive labels include: labels of variables related to sensitive operations, and labels of variables unrelated to sensitive operations; Determine whether there are variables related to preset sensitive operations in the final deviation variable set; if yes, mark the corresponding smart contract as malicious; if not, mark the corresponding smart contract as safe; among which, the preset sensitive operations include: transfer, contract destruction, and permission transfer.
8. An automatic malicious code detection system for smart contracts, adapted to the automatic malicious code detection method for smart contracts according to any one of claims 1 to 7, characterized in that: include: Data input module, result deviation analysis module, and maliciousness determination module; Data input module: receives the source code of the smart contract and parses the source code to generate an abstract syntax tree; the abstract syntax tree contains: contract function definitions and global variables; contract function definitions include: contract constructors and non-contract constructors; Result deviation analysis module: Extracts the contract constructor and uses the storage state, address mapping relationship, and initial variable values after the execution of the contract constructor as the initial state; traverses and identifies all types of address variables in the abstract syntax tree and marks them as address variable sets, and classifies the address variable sets into classification sets; Furthermore, the initial state is called and a symbolic execution engine with a buffer pool is constructed, the initial state is used as input and the symbolic execution engine outputs a matrix; a result deviation table is constructed and initialized based on the output matrix; a symbol permutator is constructed, the result deviation table is updated according to the symbol permutator, and a deviation function queue is generated; Maliciousness determination module: Based on the deviation function queue, the result deviation is iteratively analyzed to obtain the final deviation variable set; based on the final deviation variable set, it is determined whether the corresponding smart contract is malicious; if so, an early warning signal is issued; if not, the malicious code of the smart contract is automatically detected.
9. Automatic detection of malicious code in smart contracts by computing devices, characterized by: The method comprises a memory and a processor, wherein the memory stores executable instructions of the processor; wherein the processor is configured to execute the method for automatically detecting malicious code for smart contracts according to any one of claims 1 to 7 by executing the executable instructions.
Citation Information
Patent Citations
Dynamic iteration multi-engine fusion malicious code detection method and device and medium
CN114386034A
Smart contract detection method and apparatus, and electronic device
CN116841906A