A static analysis-based smart contract privacy leakage detection method
By statically analyzing the comments and code of smart contracts, and utilizing the TextRank algorithm and abstract syntax tree to detect potential privacy leaks, the problem of privacy leaks in smart contracts on the blockchain is solved, achieving fast and accurate privacy leak detection.
Patent Information
- Application Number
- CN202211277073.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2022-10-18
- Publication Date
- 2026-11-27
- Estimated Expiration
- 2042-10-18
AI Technical Summary
Existing technologies are insufficient to effectively detect privacy breaches in smart contracts on the blockchain, resulting in the permanent public disclosure of user privacy information on the immutable blockchain, causing serious losses.
Using a static analysis method, this study analyzes the comments and code of smart contracts, extracts keywords using the TextRank algorithm, constructs an abstract syntax tree, and calculates similarity using a privacy-related thesaurus to automatically detect potential privacy leaks.
Rapidly detecting privacy breaches during the smart contract programming phase improves detection efficiency, reduces the inefficiency and error risks of manual analysis, and ensures the security of user privacy.
Smart Images

Figure CN115563612B_ABST
Abstract
Description
Technical Field
[0001] This invention belongs to the technical field of blockchain security, specifically relating to a method for detecting privacy leaks in smart contracts based on static analysis. Background Technology
[0002] The concept of smart contracts can be traced back to 1995, first proposed by Nick Szabo. A smart contract is a set of promises defined in digital form, including protocols by which the contract participants execute these promises. As a Turing-complete programming language, smart contracts can maximize the fulfillment of real-world development needs, eliminating the need for intermediaries in traditional business processes, improving efficiency and reducing risks caused by human error. However, contracts on permissionless blockchains are publicly displayed on the blockchain, and all nodes can execute them; permissioned blockchains achieve privacy protection through access control policies, but nodes within the channel can still access data unrelated to the transaction. The emergence of anti-anonymity technologies such as traffic analysis and cluster analysis allows attackers to analyze existing information to track transaction trajectories and extract large amounts of user identity, user addresses, and other information that users do not wish to disclose. Due to the immutability of blockchain, once user privacy information is leaked, it will be permanently exposed on the blockchain, and the resulting losses will be irreparable. Therefore, automatic detection of privacy leaks can effectively mitigate the serious consequences of privacy breaches. This paper uses static analysis to reveal potential privacy leaks in smart contracts, helping smart contract developers to better maintain their contracts and effectively prevent privacy leaks for users. This research is of significant importance in ensuring user privacy is not compromised when executing smart contracts.
[0003] Static detection methods analyze the code without running the application itself to detect potential privacy leaks, such as those related to syntax, structure, and processes. Currently, privacy leak detection methods primarily focus on mobile applications, as these applications frequently access users' private information like phone numbers and addresses, leading to serious privacy breaches. Decentralized blockchains, with their transparent nature, are also significantly hampered by privacy leaks, making them a major obstacle to widespread adoption. Therefore, static analysis of smart contracts before deployment is an effective way to mitigate privacy leaks. This work analyzes state variables, function names, and other relevant information in smart contract code, preprocesses textual comments, and extracts keywords. The extracted information is then compared with a privacy-related thesaurus; high similarity indicates a potential privacy leak in the smart contract. Summary of the Invention
[0004] To address the shortcomings of the existing technologies, the present invention aims to provide a method for detecting privacy leaks in smart contracts based on static analysis, thereby preventing such leaks. This invention fully utilizes natural language processing technology to analyze text type annotations, uses abstract syntax trees to represent code, extracts key information, and detects privacy leaks in smart contracts, thus providing security for user privacy within smart contracts.
[0005] To achieve the above objectives, the technical solution adopted by the present invention is as follows:
[0006] The present invention provides a method for detecting privacy leaks in smart contracts based on static analysis, comprising the following steps:
[0007] 1) Classification of privacy information in smart contracts: Analyze the reasons for privacy leaks in smart contracts, summarize and define the types of privacy information in smart contracts, namely user identity information, account address information and transaction content information, and construct a privacy-related thesaurus based on these three types of information;
[0008] 2) Analysis of the forms in which privacy information exists: Analyze the forms in which privacy information appears in smart contracts. Privacy information usually appears in contract names, state variable names, function names, event names, structure names, variable names in structures, enumeration type names, and contract comments;
[0009] 3) Information extraction from comments and code: Use the TextRank algorithm to extract keywords from the comments of text-based smart contracts; construct an abstract syntax tree for the smart contract code, and extract the information required in step 2) based on the node type;
[0010] 4) Similarity Threshold Determination and Privacy Leakage Detection: Calculate the similarity between the words extracted in step 3) and the words in the privacy-related lexicon constructed in step 1). Evaluate using labeled experimental data, and select an appropriate similarity threshold using three evaluation metrics: accuracy, false positive rate, and false negative rate. Smart contracts exceeding this threshold may indicate privacy leaks.
[0011] Preferably, the three types of privacy information in step 1) mainly include:
[0012] 11) User identity information involves users' personal private information, including their real name, gender, age, address, and ID number. For example, on a medical blockchain that implements personal health records, each user's health record is private data and should not be accessed by other unauthorized users through smart contracts.
[0013] 12) Account address information pertains to accounts and the transaction relationships between them. This primarily includes the account address's balance, transaction connections between accounts, and transaction records for that account address. For example, when a smart contract verifies whether a member's balance exceeds the transfer amount, that member's balance should not be visible to all members.
[0014] 13) Transaction details include information about the transaction between users, including the transaction initiator, recipient, transaction amount, and other accompanying data. For example, in a smart contract implementing a transfer transaction, the transfer amount should only be visible to the sender and recipient;
[0015] 14) Based on the above three types of information, a privacy-related thesaurus is manually constructed and expanded using a thesaurus of synonyms.
[0016] Preferably, step 3) specifically includes:
[0017] 31) Standardized smart contracts contain numerous comments, which can effectively reveal the behavioral intent of the code. Regular expressions are used to extract comments from smart contracts, and preprocessing operations such as word segmentation and stop word removal are performed on the comments. Then, the extractive text summarization algorithm TextRank is used to extract meaningful keywords from the comments.
[0018] 32) Traverse the abstract syntax tree of the smart contract code, obtain the node information of the abstract syntax tree, filter all node content according to node type, extract the information required in step 2), and decompose this information into words using camelCase and underscore splitting rules.
[0019] Preferably, step 4) specifically includes:
[0020] 41) Calculate the similarity between the words extracted in step 3) and the words in the privacy-related lexicon built in step 1). Evaluate the similarity using labeled experimental data, selecting an appropriate similarity threshold based on three metrics: accuracy, false positive rate, and false negative rate. A suitable threshold is one where accuracy is high and false positive and false negative rates are low. If the similarity between a smart contract and the privacy-related lexicon exceeds this threshold, privacy breaches may occur. Presenting similar parts of the smart contract to the developers will allow for further improvement or protection of the smart contract.
[0021] The beneficial effects of this invention are:
[0022] This invention fully utilizes the comments and code of smart contracts, extracting keywords from text-based comments and keywords representing the semantics of the code from the contract code. These constitute the key information of the smart contract, which is then compared with a privacy-related thesaurus to determine whether privacy leaks have occurred. The use of static analysis helps smart contract developers quickly correct any privacy breaches.
[0023] Specifically, it has the following main advantages:
[0024] (1) Static analysis does not rely on the Solidity language execution environment. Without actually executing the program, the semantics and behavior of smart contract code can be analyzed, which can quickly detect privacy leaks during the smart contract programming stage and help prevent privacy leaks.
[0025] (2) Research has shown that there is currently a lack of research on detecting privacy leaks in smart contracts. This invention analyzes smart contracts from both the comments and the code, analyzing the potential for privacy leaks from the code behavior, making the correction of the contract code more targeted and improving the quality of the contract code.
[0026] (3) Natural language processing technology is used to automatically extract privacy-related key information from annotations and code, replacing the traditional manual parsing method and solving the problems of low efficiency in large-scale parsing of smart contracts and easy errors in manual parsing. Attached Figure Description
[0027] Figure 1 This is a flowchart of the method of the present invention. Detailed Implementation
[0028] To facilitate understanding by those skilled in the art, the present invention will be further described below with reference to embodiments and accompanying drawings. The content mentioned in the embodiments is not intended to limit the present invention.
[0029] Example 1: Refer to Figure 1 As shown, this invention is a method for detecting privacy leaks in smart contracts based on static analysis. The method includes the following steps:
[0030] Step 1) Classification of Privacy Information in Smart Contracts: Analyze the reasons for privacy leaks in smart contracts, summarize and define the types of privacy information in smart contracts, namely user identity information, account address information, and transaction content information, and construct a privacy-related thesaurus based on these three types of information; among them,
[0031] 11) User identity information involves users' personal private information, including their real name, gender, age, address, and ID number. For example, on a medical blockchain that implements personal health records, each user's health record is private data and should not be accessed by other unauthorized users through smart contracts.
[0032] 12) Account address information pertains to accounts and the transaction relationships between them. This primarily includes the account address's balance, transaction connections between accounts, and transaction records for that account address. For example, when a smart contract verifies whether a member's balance exceeds the transfer amount, that member's balance should not be visible to all members.
[0033] 13) Transaction details include information about the transaction between users, including the transaction initiator, recipient, transaction amount, and other accompanying data. For example, in a smart contract implementing a transfer transaction, the transfer amount should only be visible to the sender and recipient;
[0034] 14) Based on the three types of privacy information defined above, this invention defines a privacy-related lexicon. The words or phrases corresponding to each type of privacy information are shown in Table 1. Synonyms from WordNet can be used to obtain synonyms for the words in the lexicon. All synonyms are added to the lexicon, and the expanded lexicon serves as a privacy-related lexicon for smart contracts, for use in subsequent steps.
[0035] Table 1. Thesaurus related to smart contract privacy (before expansion)
[0036]
[0037] Step 2) Analysis of the form of privacy information: Analyze the form in which privacy information appears in smart contracts. Privacy information usually appears in contract name, state variable name, function name, event name, structure name, variable name in structure, enumeration type name, and contract comments;
[0038] To detect the presence of privacy information in smart contracts, in addition to categorizing the privacy information, it is also necessary to study its form within the smart contract. The naming conventions of functions and variables in smart contract code typically consist of one or more words linked together to form a single name. This naming rule largely represents some of the functions and operations of the smart contract code. Nodes unrelated to privacy need to be excluded, such as nodes specifying the Solidity language version, nodes with the contract type "Library," and nodes importing external source files. Furthermore, smart contract comments explain and clarify the contract code in text form, facilitating a better understanding of the code block design methods. Analyzing comments can effectively capture the intent of the code and help detect potential privacy leaks.
[0039] Step 3) Information extraction from comments and code: Use the TextRank algorithm to extract keywords from text-based smart contract comments; construct an abstract syntax tree for the smart contract code, and extract the information needed in Step 2) based on the node type;
[0040] 31) Single-line comments begin with " / / ", while multi-line comments usually appear above the entire code block, beginning with " / / / " or enclosed in " / *" and "* / ". Multi-line comments need to be concatenated line by line to form a complete comment, such as the multi-line comments in Table 2 which need to be concatenated to form "This is a multi-line comment."
[0041] Table 2:
[0042]
[0043] This paper uses regular expressions to extract all comments from a smart contract and then uses the TextRank algorithm to extract keywords from the comment set. TextRank is a graph-based keyword extraction method, an improvement on PageRank. It constructs a graph network using co-occurrence relationships between words, where each node represents a word and edges between nodes represent the co-occurrence of two words. The importance of each word i is represented by its corresponding node V. i Weight WS(V) i The calculation method for ) is shown in formula (1):
[0044]
[0045] Where d is the damping coefficient, typically taken as 0.85, and w ji WS(V) represents the number of times words i and j co-occur. j ) represents the weight of word j from the previous iteration, link(V) j ) refers to node V j The set of all other connected nodes.
[0046] The comments in the comment set are divided into multiple sentences T = [S1, S2, ..., S...]. m For each sentence S i ∈T is used for word segmentation, stop word removal, part-of-speech tagging, and part-of-speech restoration to obtain a candidate keyword list S for each sentence. i =[t i,1 ,t i,2 ,...,t i,n Construct a graph G = (V, E) for candidate keywords, with words as nodes. Set the window size; if words co-occur within the window size, they form edges between words. Iterate and propagate the weights of each node according to formula (1) until convergence, thus obtaining the weight corresponding to each node. The greater the weight of a node, the more important the keyword of that node. If adjacent word groups are formed, they form a multi-word keyword. Finally, select the T keywords with higher weights as the keywords extracted from the smart contract annotations.
[0047] 32) An Abstract Syntax Tree (AST) is used to abstractly represent the syntactic structure of smart contract code. As the name suggests, an AST presents the syntactic structure of the source code in a tree-like format, with each node representing its type and corresponding code. This invention utilizes the solc compiler to compile and parse the smart contract code, generating an AST file in JSON format, which can intuitively present all components of the code. Taking Solidity, the programming language most suitable for smart contracts, as an example, for the smart contract shown in Table 3, the contract defines three data types: uint, bytes32, and enum. The generated JSON AST file contains 147 lines, and Table 4 shows a partial excerpt.
[0048] Table 3:
[0049]
[0050] The abstract syntax tree (AST) is traversed, and each node is analyzed based on its characteristic attribute NodeType. According to the privacy information storage methods analyzed in step 2), this invention extracts the following from the smart contract code: contract name (node type: ContractDefinition), state variable name (node type: VariableDeclaration), function name (node type: FunctionDefinition), event name (node type: EventDefinition), structure name (node type: StructDefinition), variable name within the structure (node type: VariableDeclaration), and enumeration type name (node type: EnumDefinition) for further analysis. Table 4 shows an example of the AST for the enumeration type, where NodeType is EnumDefinition, and its corresponding name is the value to be extracted, which is gender.
[0051] Table 4:
[0052]
[0053] After extracting the above information from the smart contract based on the node type, since this type of information usually strings several words together in camelCase or underscore format, camelCase and underscore splitting rules are used to segment this information into individual words. Natural language processing techniques are then used to perform part-of-speech tagging and part-of-speech reconstruction. For example, if the extracted information is "addressmixing", it needs to be split into "address" and "mixing", and "mixing" also needs to be reclassified as "mix".
[0054] Ultimately, the words extracted from the comments and code of the smart contract are the key information needed.
[0055] Step 4) Similarity Threshold Determination and Privacy Leakage Detection: Calculate the similarity between the words extracted in Step 3) and the words in the privacy-related lexicon constructed in Step 1). Evaluation is performed using labeled experimental data. A suitable similarity threshold is selected using three evaluation metrics: accuracy, false positive rate, and false negative rate. Smart contracts exceeding this threshold may indicate privacy leaks.
[0056] This invention utilizes the Jaccard coefficient to measure the similarity between two word sets. The specific calculation method is shown in formula (2), where set A is the privacy-related vocabulary from step 1), and set B is the word set extracted from the code and comments of the smart contract. The Jaccard coefficient is defined as the ratio of the size of the intersection of A and B to the size of their union, used to compare the similarity and differences between finite sample sets. The larger the Jaccard coefficient, the higher the similarity between the two sets, indicating a greater likelihood of privacy leakage in the smart contract.
[0057]
[0058] This invention selects smart contracts that have been marked as having privacy leaks and uses three evaluation metrics—precision, false positive rate, and false negative rate—to select a suitable similarity threshold. The specific calculation method is shown in formulas (3)-(5), where TP is the number of contracts that actually have privacy leaks and are detected, FP is the number of contracts that actually have no privacy leaks but are detected, and FN is the number of contracts that actually have privacy leaks but are not detected. Precision is the probability of correctly predicting a privacy leak, false positive rate is the ratio of the number of contracts that actually have no privacy leaks but are detected by this invention to the total number of contracts that have detected privacy leaks, and false negative rate is the ratio of the number of contracts that actually have privacy leaks but are not detected by this invention to the total number of contracts that have not been detected. When the precision is high and the false positive and false negative rates are relatively low, it is a suitable similarity threshold. For a smart contract, the similarity value is automatically calculated by extracting the contract's code and comments. If it is greater than the threshold, it indicates that privacy leaks have occurred to a large extent. Finally, the specific code that has privacy leaks is presented to the developers for manual evaluation in order to make further improvements.
[0059]
[0060]
[0061]
[0062] This invention has many specific applications. The above description is only a preferred embodiment of this invention. It should be noted that for those skilled in the art, several improvements can be made without departing from the principle of this invention, and these improvements should also be considered within the scope of protection of this invention.
Claims
1. A method for detecting privacy leaks in smart contracts based on static analysis, comprising the following steps: 1) Classification of privacy information in smart contracts: Analyze the reasons for privacy leaks in smart contracts, summarize and define the types of privacy information in smart contracts, namely user identity information, account address information and transaction content information, and construct a privacy-related thesaurus based on these three types of information; 2) Analysis of the forms in which privacy information exists: Analyze the forms in which privacy information appears in smart contracts. Privacy information usually appears in contract names, state variable names, function names, event names, structure names, variable names in structures, enumeration type names, and contract comments; 3) Information extraction from comments and code: Use the TextRank algorithm to extract keywords from the comments of smart contracts in text type; construct an abstract syntax tree of the smart contract code, and extract the information required in step 2) according to the node type; 4) Similarity Threshold Determination and Privacy Leakage Detection: The similarity between the words extracted in step 3) and the words in the privacy-related lexicon constructed in step 1) is calculated. Evaluation is performed using labeled experimental data, and a suitable similarity threshold is selected using three evaluation metrics: accuracy, false positive rate, and false negative rate. Smart contracts exceeding this threshold may indicate privacy leaks. The Jaccard coefficient is used to measure the similarity between two word sets. The specific calculation method is shown in formula (2), where the set... For step 1), a privacy-related thesaurus is set. The Jaccard coefficient, defined as the ratio of the intersection to the union of the two sets of words extracted from the code and comments of a smart contract, is used to compare the similarity and differences between finite sample sets. A larger Jaccard coefficient indicates a higher similarity between the two sets, suggesting a greater likelihood of privacy breaches in the smart contract. (2)。 2. The method for detecting privacy leaks in smart contracts based on static analysis according to claim 1, characterized in that, The three types of privacy information mentioned in step 1) mainly include: 11) User identity information involves users' personal privacy information, including their real name, gender, age, address, and ID number. 12) Account address information includes the account and the transaction relationship between accounts, including the account address balance, the transaction connection between accounts, and the transaction record of the account address; 13) Transaction content information includes information related to transactions between users, including the transaction initiator, transaction recipient, transaction amount, and other accompanying data; 14) Based on the above three types of information, a privacy-related thesaurus is manually constructed and expanded using a thesaurus of synonyms.
3. The method for detecting privacy leaks in smart contracts based on static analysis according to claim 1, characterized in that, Step 3) specifically includes: 31) Standardized smart contracts contain a large number of comments, which can effectively reveal the behavioral intent of the code. We use regular expressions to extract comments from smart contracts, perform word segmentation and stop word removal preprocessing on the comments, and use the extractive text summarization algorithm TextRank to extract meaningful keywords from the comments. 32) Traverse the abstract syntax tree of the smart contract code, obtain the node information of the abstract syntax tree, filter all node content according to node type, extract the information required in step 2), and decompose this information into words using camelCase and underscore splitting rules.
4. The method for detecting privacy leaks in smart contracts based on static analysis according to claim 1, characterized in that, Step 4) specifically includes: 41) Calculate the similarity between the words extracted in step 3) and the words in the privacy-related lexicon built in step 1). Evaluate the similarity by selecting labeled experimental data and select an appropriate similarity threshold using three evaluation indicators: accuracy, false positive rate, and false negative rate. When the accuracy is high and the false positive rate and false negative rate are low, it is a suitable threshold. If the similarity between a smart contract and the privacy-related lexicon exceeds the threshold, there may be a privacy leak. Present the similar parts of the smart contract to the developers to further improve or protect the smart contract.
Citation Information
Patent Citations
Code layer semantic analysis driving-based privacy data identification method
CN108171073A
Software source code privacy detection method and system based on static detection
CN114595482A
