A blockchain underlying data structure formal verification method and system
Patent Information
- Application Number
- CN202611399030.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-09-10
- Publication Date
- 2026-10-13
AI Technical Summary
[0005]本发明旨在提供一种区块链底层数据结构形式化验证方法及系统,以解决现有测试验证覆盖范围有限,难以系统验证MPT在键值操作过程中的结构约束、数据语义及根哈希映射正确性,导致潜在边界缺陷难以及时发现、底层数据可靠性不足的技术问题
1.消除语义歧义:通过函数式建模精确重构了底层存储结构复杂的操作语义,消除了传统自然语言规范中的歧义,从根源上保障了不同客户端实现状态演化的一致性;
Smart Images

Figure CN122909045A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of blockchain data structure verification technology, specifically to a formal verification method and system for the underlying data structure of a blockchain. Background Technology
[0002] A Merkle Patricia Trie (MPT) is an authentication key-value data structure that combines a Patricia prefix tree with a Merkle hash verification mechanism. In blockchain systems like Ethereum that employ this data structure, MPTs can be used to organize data such as account status, transaction records, or transaction receipts, and the root hash represents changes in the data and node structure within the tree. To improve key path query efficiency and storage space utilization, MPTs typically employ hexadecimal key paths, hexadecimal prefix encoding, and path compression mechanisms, and set different types of nodes such as empty nodes, leaf nodes, extended nodes, and branch nodes. When performing key-value data lookup, insertion, and deletion operations, processes such as common prefix matching, node splitting, path merging, and node type conversion may also be involved.
[0003] Blockchain clients typically implement MPT node processing, serialization encoding, and hash calculation logic according to relevant technical specifications. Because these specifications may be described using natural language, pseudocode, or distributed rules, different client implementations may exhibit misunderstandings or implementation defects regarding complex situations such as path matching boundaries, recursion termination conditions, node splitting or compression conditions, and encoding methods for different node types. These defects are not easily apparent during normal operation, but when performing a large number of continuous, deep, or interleaved key-value operations, they may lead to incorrect search results, tree structures that do not meet predetermined constraints, abnormal recursion processes, node processing failures, or inconsistent root hashes corresponding to the same business state.
[0004] Existing blockchain clients typically rely on software testing methods such as unit testing, integration testing, fuzz testing, or differential testing to verify the implementation logic of MPT (Multi-Level Transmission). While these tests can verify the execution path corresponding to selected test cases, the state space of MPT is influenced by various factors including key path combinations, node topology, data content, and operation order. It's difficult to cover all boundary states and operation sequences with a limited number of test cases, making it challenging to directly verify the correctness of maintaining tree structure constraints, key-value set semantics, and the serialization and root hash mapping relationship under different legitimate inputs. Under abnormal or maliciously constructed input conditions, undetected boundary defects may cause abnormal recursion depth or computational / storage resource consumption, even leading to denial-of-service, client state inconsistencies, or data synchronization anomalies, thereby affecting the data reliability and consensus consistency of the blockchain system. Therefore, existing verification methods still fall short in providing systematic and verifiable verification of the complex state evolution process and hash mapping mechanism of MPT. Summary of the Invention
[0005] This invention aims to provide a formal verification method and system for the underlying data structure of a blockchain, in order to solve the technical problems of limited coverage of existing testing and verification, difficulty in systematically verifying the structural constraints, data semantics and root hash mapping correctness of MPT in the key-value operation process, resulting in the difficulty in timely detection of potential boundary defects and insufficient reliability of underlying data.
[0006] To achieve the above objectives, this invention provides a formal verification method for the underlying data structure of a blockchain, comprising: Using recursive algebraic data types, Merkel-Patricia tree (MPT) nodes are modeled as empty nodes, leaf nodes, extended nodes, and branch nodes. Blockchain business data is carried by type variables to obtain the node model. Based on the node model, a basic operation model for key-value data in the MPT tree is constructed, and a serialization and hash mapping model of the MPT logical structure to the root hash is established through an algebraic structure with node type field isolation markers. Based on the basic operation model, generate structural invariance proofs and element invariance proofs; based on the serialization and hash mapping model, generate serialization distinguishability proofs and root hash distinguishability proofs; call the theorem proof auxiliary tool to perform mechanical verification of each proof, and obtain the model verification results. When the model verification result indicates that all proofs have passed mechanical verification, the type variable in the node model is instantiated as the target blockchain business data type to form a business tree. Based on the basic operation model, the business data corresponding to the target blockchain business data type is processed to obtain the business data processing result. Based on the preset business rules corresponding to the target blockchain business data type, the consistency verification of the business data processing result is performed, and the existence proof of the business data corresponding to the target key is verified using the trusted root hash of the business tree as the verification benchmark, and the business verification result is output.
[0007] As a further improvement to the above technical solution, the key path in the node model is composed of a hexadecimal character sequence; the empty node represents the empty state of the MPT tree or the termination of the key path; the leaf node includes the remaining key path fragment and the data value corresponding to the type variable; the extended node includes a non-empty common prefix and points to a unique child node; the branch node includes 16 optional child node positions corresponding to hexadecimal characters 0 to F and optional value fields corresponding to the type variable.
[0008] As a further improvement to the above technical solution, the basic operation model includes a search operation model, an insertion operation model, and a deletion operation model; The search operation model receives an MPT tree and a key to be searched, performs pattern matching based on node type, performs prefix consumption and recursive search segment by segment along the key path corresponding to the key to be searched, and outputs optional type search results containing corresponding data values or null values. The insertion operation model receives an MPT tree, a key to be inserted, and a data value to be inserted. It deterministically maps the input MPT tree state to the MPT tree state after insertion. When the key path corresponding to the key to be inserted conflicts with an existing key path, it determines the common prefix of the two and generates a fork structure. The deletion operation model receives an MPT tree and a key to be deleted, performs a depth-first traversal along the key path corresponding to the key to be deleted, removes the data corresponding to the key to be deleted, adjusts the parent nodes on the key path during the recursive return process, and outputs the state of the MPT tree after deletion.
[0009] As a further improvement to the above technical solution, when the key path corresponding to the key to be inserted is different from the existing key path, the insertion operation model calls the longest common prefix function to calculate the overlapping segment of the two; when the two branch after the overlapping segment, the node corresponding to the existing key path is split, a new branch node is constructed, and the branched key paths are associated with the corresponding child nodes respectively; when the key path corresponding to the key to be inserted matches the path segment of the existing node, the insertion is recursively performed along the child node pointed to by the existing node, and the path segments of adjacent extended nodes are merged during the recursive return process to obtain the MPT tree state after insertion without consecutive nested extended nodes. After removing the data corresponding to the key to be deleted, the deletion operation model calls a counting function during the recursive return process to determine the number of valid surviving sub-branches of the branch node. When the number of valid surviving sub-branches indicates that the branch node has lost its branching function, the branch compression function is called to perform path merging and branch degradation on the branch node, reducing the branch node to a compact node structure, and obtaining the MPT tree state after deletion.
[0010] As a further improvement to the above technical solution, the establishment of the serialization and hash mapping model includes: defining an intermediate algebraic data type including atomic string constructors and recursive list constructors, and configuring different node type domain isolation markers for leaf nodes, extension nodes, and branch nodes respectively; recursively mapping the MPT logical structure to the intermediate algebraic data type according to the node type, mapping empty nodes to empty atomic strings, mapping leaf nodes to a recursive list including the corresponding node type domain isolation marker, remaining key path fragments, and serialized representation of data values, mapping extension nodes to a recursive list including the corresponding node type domain isolation marker, common prefix, and child node hash values, and mapping branch nodes to a recursive list including the corresponding node type domain isolation marker, recursive encoding results of child node sequences, and serialized representation of optional value fields, thus obtaining a serialized algebraic structure; performing bottom-up hash calculation on the serialized algebraic structure using a preset hash function, and determining the hash value corresponding to the root node as the root hash of the MPT tree.
[0011] As a further improvement to the above technical solution, the mechanized verification includes: taking as a premise that the MPT tree before the insertion or deletion operation satisfies the structural constraints that the common prefix of the extended nodes is non-empty, there are no consecutive nested extended nodes, and the branch nodes include 16 optional child node positions, verifying that the MPT tree after the corresponding operation still satisfies the structural constraints, and generating the structural invariance proof; mapping the MPT tree to a valid key set, verifying that the search, insertion, and deletion operations correspond to set membership, union, and difference operations respectively, and generating the element invariance proof; based on the node type domain isolation marker and the injectivity assumption of the preset hash function set in the formal model, verifying that the serialized algebra structures corresponding to different node types are different, generating the serialization distinguishability proof, and verifying that the root hashes corresponding to different MPT tree structures are different, generating the root hash distinguishability proof; when all proofs pass the mechanized verification, the model verification result is determined to be passed.
[0012] As a further improvement to the above technical solution, the consistency verification includes: determining the target blockchain business data type as a transaction record type, instantiating the type variable as the transaction record type to form a transaction tree, and performing batch insertion on multiple transaction records based on the basic operation model to obtain the business data processing result; constructing corresponding business type determination predicates according to the respective business type determination conditions of ordinary transfers, message calls, and contract creation, and determining that the same transaction record cannot be determined as two or more of the aforementioned business types simultaneously as the preset business rule; calling the theorem proof auxiliary tool to verify that there are no transaction records in the business data processing result that simultaneously satisfy two or more of the aforementioned business type determination predicates; when the verification passes, determining that the transaction type determination in the business data processing result is consistent with the preset business rule.
[0013] As a further improvement to the above technical solution, the generation of the business data existence proof includes: modeling the business data existence proof as an ordered evidence chain composed of recursive length prefix encoded (RLP) serialization nodes, wherein the RLP serialization nodes are obtained by RLP encoding the serialization algebra structure corresponding to the MPT nodes; recursively traversing the business tree according to the target key by all nodes, sequentially extracting each MPT node along the key path corresponding to the target key from the root node to the target data node, wherein the target data node stores the business data corresponding to the target key; converting each extracted MPT node into a corresponding RLP serialization node, and arranging them according to the traversal order to generate the business data existence proof.
[0014] As a further improvement to the above technical solution, the verification of the existence proof of the business data corresponding to the target key includes: the light client takes the root hash of the business tree, the target key, the business data value to be verified, and the existence proof of the business data as input, performs hash link verification along the key path corresponding to the target key on the ordered evidence chain, and performs data value matching verification on the business data value at the end of the chain and the business data value to be verified; calls the theorem proof auxiliary tool to verify that, under the condition that the basic operation model performs a lookup operation on the target key and outputs the business data value to be verified, the existence proof of the business data generated by the full node can pass the hash link verification and data value matching verification performed by the light client, and obtains the validity verification result of the proof mechanism; when the validity verification result of the proof mechanism is passed, and both the hash link verification and the data value matching verification are passed, outputs the business verification result indicating that the business data corresponding to the target key exists in the business tree.
[0015] This invention also provides a formal verification system for the underlying data structure of a blockchain, comprising: The node modeling module is used to model Merkel-Patricia tree (MPT) nodes as empty nodes, leaf nodes, extended nodes, and branch nodes using recursive algebraic data types, and to carry blockchain business data with type variables to obtain the node model. The basic operation and hash mapping modeling module is used to construct a basic operation model for key-value data in the MPT tree based on the node model, and to establish a serialization and hash mapping model of the MPT logical structure through an algebraic structure with node type field isolation markers to the root hash. The mechanized verification module is used to generate structural invariance proofs and element invariance proofs based on the basic operation model, generate serialization distinguishability proofs and root hash distinguishability proofs based on the serialization and hash mapping model, and call the theorem proof auxiliary tool to perform mechanized verification of each proof to obtain the model verification results. The business verification module is used to instantiate the type variables in the node model into the target blockchain business data type when the model verification result is passed, forming a business tree; process the business data corresponding to the target blockchain business data type based on the basic operation model to obtain the business data processing result; perform consistency verification on the business data processing result according to the preset business rules corresponding to the target blockchain business data type; and verify the existence proof of the business data corresponding to the target key using the trusted root hash of the business tree as the verification benchmark, and output the business verification result.
[0016] The beneficial effects of the formal verification method and system for the underlying data structure of blockchain provided by this invention are as follows: 1. Eliminate semantic ambiguity: The complex operational semantics of the underlying storage structure are accurately reconstructed through functional modeling, eliminating ambiguity in traditional natural language specifications and ensuring consistency of state evolution across different clients from the root. 2. Reduce proof noise: The structured serialization abstraction isolates the underlying physical coding details, effectively reducing noise interference in the formal proof process; 3. Improve the automation and accuracy of verification: The theorem proof auxiliary tool completes the machine proof of the basic operation boundary and hash property, replacing the tedious and flawed manual derivation and traditional exhaustive testing, which greatly improves the automation and accuracy of verification. 4. Highly reliable scenario reuse capability: The abstract theory has been successfully extended to real Ethereum business and light client verification scenarios, providing highly reliable and reusable mathematical security for the underlying authentication data structure of the blockchain. Attached Figure Description
[0017] Figure 1 This is a schematic diagram of the formal verification method for the underlying data structure of the blockchain in an embodiment of the present invention; Figure 2 This is an example diagram of the node structure evolution triggered by the insertion operation in an embodiment of the present invention; Figure 3 This is a formal mapping architecture diagram of the logical domain to the cryptographic domain for hash computation in an embodiment of the present invention; Figure 4 This is a schematic diagram of the lemma dependency relationship for invariance verification based on the theorem proving tool in an embodiment of the present invention. Figure 5 This is a schematic diagram of the interaction scenario between the light client and the full node Merkle proof in an embodiment of the present invention; Figure 6 This is a structural diagram of the formal verification system module for the underlying data structure of the blockchain in this embodiment of the invention. Detailed Implementation
[0018] The technical solutions of the embodiments of this application will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of this application, not all embodiments. Based on the embodiments of this application, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of this application.
[0019] The term "embodiment" as used herein means that a particular feature, structure, or characteristic described in connection with an embodiment may be included in at least one embodiment of this application. The phrase appearing in various places in the specification does not necessarily refer to the same embodiment, nor is it a separate or alternative embodiment that is mutually exclusive with other embodiments. It will be explicitly and implicitly understood by those skilled in the art that the embodiments described herein can be combined with other embodiments.
[0020] Example 1 The method described in this embodiment can run on computer devices containing memory and processors, distributed consensus node clusters, or light client devices, and can complete model construction and mechanized verification within the logical framework of theorem proof aids. The following explanation uses the Merkle Patricia Trie (MPT) as the underlying implementation and Isabelle / HOL as an example of a theorem proof aid.
[0021] In the aforementioned operating environment, by reducing node topology, state evolution, serialization, and hash mapping within the logical framework of the theorem proof aid tool, and transforming them into machine-verifiable definitions, predicates, and theorems, semantic ambiguities caused by natural language specifications in terms of path boundaries, node transformations, and encoding rules can be reduced. Compared to verifying a predetermined execution path based solely on a limited number of test cases, mechanized proof can verify the corresponding proof objective against symbolic inputs that meet formal preconditions, thereby providing a formal basis for consistency, tamper-proof verification, and reuse across different business trees in MPT's underlying data processing.
[0022] like Figure 1 As shown, this embodiment provides a formal verification method for the underlying data structure of a blockchain. Figure 1 The process flow, presented sequentially from S01 to S05, includes node modeling, basic operations and hash mapping modeling, mechanized verification, business tree formation and business data processing, as well as the verification of business rule consistency and business data existence. Specifically, it includes: S01: Using recursive algebraic data types, MPT nodes are modeled as empty nodes, leaf nodes, extended nodes, and branch nodes. Blockchain business data is carried by type variables to obtain the node model. S02: Based on the node model, construct a basic operation model for key-value data in the MPT tree, and establish a serialization and hash mapping model from the MPT logical structure to the root hash via an algebraic structure with node type field isolation markers. S03: Generate structural invariance proof and element invariance proof based on the basic operation model, generate serialization distinguishability proof and root hash distinguishability proof based on the serialization and hash mapping model, call the theorem proof auxiliary tool to perform mechanical verification of each proof, and obtain the model verification result; S04: When the model verification result indicates that all proofs have passed mechanical verification, the type variable in the node model is instantiated into the target blockchain business data type to form a business tree, and the corresponding business data is processed based on the basic operation model to obtain the business data processing result. S05: Based on the preset business rules corresponding to the target blockchain business data type, perform consistency verification on the business data processing result, and use the trusted root hash of the business tree as the verification benchmark to verify the existence proof of the business data corresponding to the target key, and output the business verification result.
[0023] In the above process, the node model obtained in S01 and the basic operation and hash mapping model obtained in S02 together constitute the proof object of S03; only after all the proofs corresponding to S03 have passed mechanical verification will the business instantiation and business verification processes described in S04 and S05 begin. The following is combined with... Figures 2 to 5Further explanation of each step is provided.
[0024] S01: Detailed Implementation of the Node Model In one specific embodiment, the key path in the node model consists of a sequence of hexadecimal characters. An empty node represents the empty state of the MPT tree or the termination of the key path; a leaf node includes the remaining key path fragments and the data values corresponding to the type variables; an extension node includes a non-empty common prefix and points to a unique child node; a branch node includes 16 optional child node positions corresponding to the hexadecimal characters 0 to F and optional value fields corresponding to the type variables.
[0025] In the theorem proof aids, the static topological state of the MPT node is defined using the Recursive Algebraic Datatype, and the functional modeling is as follows: type_synonym key = "char list" datatype 'v MPT = Empty | Leaf key 'v | Extension key "'v MPT" | Branch "('v MPT option) list" "'v option" Here, `type_synonym` is the keyword for defining type synonyms, defining `char list` (character list type) as an alias for the key type, used to uniformly represent key paths composed of hexadecimal character sequences in MPT; `datatype` is the keyword for defining algebraic data types, used to declare a recursive data type `'v MPT` with a type variable `'v`. The type variable `'v` is used to carry blockchain business data, enabling the same node model to be instantiated as needed into data types such as account status, transaction records, or transaction receipts. This recursive data type includes the following four constructors: Empty (empty node): indicates the empty state of the MPT tree or the termination of the key path, and corresponds to the empty set in set semantics.
[0026] Leaf (leaf node): Indicates the end of the key path, used to compactly store the remaining key path fragments and the data values corresponding to the type variable 'v'.
[0027] Extension (Extension Node): Used to collapse and store a non-empty common prefix shared by multiple keys, pointing to a unique child node, in order to achieve key path compression.
[0028] Branch (branch node): Used to provide multiple routes, maintain 16 optional child node positions corresponding to hexadecimal characters 0 to F, and set an optional value field corresponding to a type variable 'v'.
[0029] The aforementioned Recursive Algebraic Datatype defines node forms using four types of constructors: Empty, Leaf, Extension, and Branch. It also clarifies parent-child relationships and termination states through recursive references, enabling subsequent searches, insertions, deletions, and invariance proofs to be performed within a unified model. Specifically, the extended node folds and stores common prefixes, reducing duplicate path segments and suppressing unnecessary tree depth growth. This structurally mitigates the risk of Denial of Service (DoS) attacks caused by abnormally deep paths.
[0030] In the actual operating environment of blockchains such as Ethereum, the key of the state tree (usually a 32-byte Keccak-256 hash value) or account address (20 bytes) exists in the form of a raw byte stream. Before being accessed by the MPT, the raw byte stream is split into nibbles (4 bits each). Each nibble corresponds precisely to a hexadecimal character (i.e., 0-9 and af). Therefore, in this application, the key type is defined as `type_synonym key="char list"` in functional modeling. This character list is used to equivalently represent the split hexadecimal character sequence, thus constructing an accurate mapping from the physical storage key to the formal model key path. Based on the above mapping rules, the effective input range of the auxiliary function `hex_val` is strictly limited to a set of hexadecimal characters, i.e., input characters `c∈{0,1,…,9,a,b,…,f}`. This function is responsible for injecting the above characters into the natural number index range [0,15].
[0031] In the Ethereum physical implementation, the hex-prefix encoding of leaf nodes and extension nodes distinguishes node types (leaf or extension) and handles path parity by appending specific nibble flags. However, directly introducing bit-level parity checking and bit shifting operations into formal proofs leads to significant proof noise and logical ambiguity in path parsing. To address this issue, the system directly utilizes the constructors `Leaf` and `Extension` of recursive algebraic data types to naturally and absolutely distinguish node types. The internally stored `key` field (i.e., the char list) stores only pure, valid path fragments, logically stripping away the physical prefix bits used for parity checking and extracting the essence of path compression from the complex physical encoding.
[0032] S02-1: Detailed Implementation of the Basic Operation Model In one specific embodiment, the basic operation model includes a search operation model, an insertion operation model, and a deletion operation model. All three operations use the node model as the processing object: the search operation outputs optional type search results containing corresponding data values or null values, while the insertion and deletion operations deterministically map the input MPT tree state to the MPT tree state after the corresponding operation.
[0033] The three basic operations described above are all reduced to pure functional state transitions, producing deterministic outputs for the same input tree state, target key, and data value. Therefore, each state change can be incorporated into the theorem proof as a deterministic mapping from the old tree state to the new tree state, reducing the possibility of unexpected states caused by undefined processing branches or external side effects.
[0034] Lookup operation: The lookup operation model receives an MPT tree and the key to be retrieved, performs pattern matching based on node type, and performs prefix consumption and recursive search segment by segment along the key path corresponding to the key to be retrieved. Its functional modeling is as follows: fun lookup :: "'v MPT key 'v option" where "lookup Empty _ = None" | "lookup (Leaf kv) k' = (if k = k' then Some v else None)" | "lookup (Extension pt) k = (if take (length p) k = p then lookup t(drop (length p) k) else None)" | "lookup (Branch children v_opt) k = (case k of [] v_opt | x # xs (case nth children (hex_val x) of Some t' lookup t' xs| None None))" The keyword 'fun' defines the lookup function, whose type signature is 'v MPT'. key The 'v option' option indicates that the function takes an MPT tree and a search key, and returns an optional result, which is used to implement the key-based exact value retrieval function in MPT.
[0035] The function uses a pattern matching mechanism to traverse the four types of nodes in the MPT tree: for empty nodes (Empty), it directly returns None to indicate that the search failed; for leaf nodes (Leaf), it determines whether to return the corresponding stored value through key-value matching; for extension nodes (Extension), it first verifies whether the search key prefix is consistent with the node's common prefix. If they match, it recursively searches the remaining path; otherwise, it returns a search failure; for branch nodes (Branch), if the search path is empty, it returns the node's own stored value. Otherwise, it converts the first character of the key into an index to locate the child node and recursively searches the remaining path of the child node, ultimately implementing the complete MPT key-value search logic.
[0036] The step-by-step prefix consumption, also known as prefix exhaustion, involves the following steps: Expanding nodes remove matched path segments during prefix matching; branch nodes consume the first hexadecimal character of the key path; and leaf nodes or unmatched branches terminate the recursion. This process continuously shortens the search segment along the target key path, providing a basis for verifying recursion termination and limiting the path resolution range, while also reducing the risk of timeouts due to abnormal paths.
[0037] Insertion operation: The insertion operation model receives an MPT tree, a key to be inserted, and a data value to be inserted. It deterministically maps the input tree state to the tree state after insertion. When a conflict occurs between the key path corresponding to the key to be inserted and an existing key path, it determines the common prefix of both and generates a branch structure. Its functional modeling is as follows: fun insert :: "'v MPT key 'v 'v MPT" where "insert Empty kv = Leaf kv" | "insert (Leaf k' v') kv = (if k = k' thenLeaf kv else let p = lcp k k';suffix1 = drop (length p) k;suffix2 = drop(length p) k' in case (suffix1, suffix2) of ([], y#ys) let b = Branch (update_nth (hex_val y) (Some (Leaf ysv')) (replicate 16 None)) (Some v) in if p = [] then b else Extension p b | (x#xs, []) let b = Branch (update_nth (hex_val x) (Some (Leaf xs v))(replicate 16 None)) (Some v') in if p = [] then b else Extension p b | (x#xs, y#ys) let children1 = update_nth (hex_val x) (Some (Leaf xsv)) (replicate 16 None);children2 = update_nth (hex_val y) (Some (Leaf ysv')) children1; b = Branch children2 None in if p = [] then b else Extensionp b )" | "insert (Extension p t) k v = (let common = lcp p k in if common = p then (case insert t (drop (length p) k) v of Extension p' t' Extension (p @ p') t' | result Extension p result) else (case (drop (length common) p, drop (length common) k) of (i#suffix, j#js) let child1 = (if suffix = [] then t else Extension suffix t); child2 = (if js = [] then Leaf []v else Leaf js v); em = replicate 16 None; ch1 = update_nth (hex_val i) (Some child1) em; ch2 = update_nth (hex_val j) (Some child2) ch1; b = Branch ch2 None in if common = [] then b else Extension common b | (i#suffix, []) let child1 = (if suffix = [] then t else Extension suffix t); em = replicate 16 None; ch1 = update_nth (hex_val i) (Some child1) em; b = Branch ch1 (Some v) in if common = [] then b else Extension common b | _ Branch (replicate 16 None) None))" | "insert (Branch children vo) k v =(case k of [] Branch children(Some v)| x#xs let idx = hex_val x; new_child = (case nth children idx ofSome t' insert t' xs v | None Leaf xs v) in Branch (update_nth idx (Somenew_child) children) vo)" The `fun` keyword defines the `insert` function, whose type signature is 'v MPT'. key 'v 'v MPT' indicates that the function takes an old MPT tree, an insertion key, and an insertion value, and returns a new MPT tree state.
[0038] The function uses a pattern matching mechanism to traverse the four types of nodes in the MPT tree: For empty nodes, it directly constructs and returns a new leaf node, Leaf, to expand the tree structure; for leaf nodes, it handles path conflicts by calculating the longest common prefix between the new key and the original key. If the two keys are completely identical, the existing value is updated. If there is a difference, a new branch node is constructed to isolate the path, and when the common prefix is not empty, it is further encapsulated in the extension node; for extension nodes, it compares the shared path between the new key and the node. If they match completely, it recursively enters the child node to perform insertion and performs structural normalization to prevent continuously nested extension nodes. If they partially match, the original node is split into a composite structure of "common prefix + branch node + remaining suffix" to maintain the prefix compression property; for branch nodes, if the key sequence is empty, it updates the node's own value. Otherwise, it calculates the hexadecimal slot index using the first character of the key, recursively calls the subtree insertion logic and updates the child node list, ultimately ensuring that the insertion of any key-value pair sequence can converge to a uniquely normalized MPT tree structure.
[0039] In a further specific embodiment, when the key path corresponding to the key to be inserted is different from the existing key path, the longest common prefix function is called to calculate the overlapping segment of the two; when the two branch after the overlapping segment, the node corresponding to the existing key path is split, a new branch node is constructed, and the branched key paths are associated with the corresponding child nodes respectively; when the key path corresponding to the key to be inserted matches the path segment of the existing node, the key is recursively inserted along the child node pointed to by the existing node, and the path segments of adjacent extended nodes are merged during the recursive return process, thereby obtaining the MPT tree state after insertion without consecutive nested extended nodes.
[0040] The situation where key paths conflict is also called path collision. By uniformly performing longest common prefix identification, node splitting, branch construction, and backtracking merging on such collisions, the inserted node structure can maintain a predetermined standard form, and provide a structural basis for generating consistent serialization structures and root hashes for the same business states.
[0041] like Figure 2 As shown, the insertion operation example writes four sets of illustrated key-value pairs consecutively starting from an empty node: the first insertion forms a leaf node; during the second insertion, the two key paths have a common prefix, thus forming an extended node that records the shared path, and a branch node is constructed at the fork position to associate the two leaf nodes; the third insertion adds the corresponding child node to the existing branch node; the fourth insertion further shares the local path with the existing key path, thus performing node splitting and path compression again in the corresponding subtree. Figure 2 Each stage shown retains extended nodes along the common prefix and uses the hexadecimal child node positions of branch nodes to distinguish subsequent paths.
[0042] Delete operation: The delete operation model receives an MPT tree and the key to be deleted. It performs a depth-first traversal along the key path corresponding to the key to be deleted, removes the data corresponding to the key, adjusts the parent nodes on the key path during the recursive return process, and outputs the state of the MPT tree after deletion. Its functional modeling is as follows: fun delete :: "'v MPT key 'v MPT" where "delete Empty _ = Empty" | "delete (Leaf kv) k' = (if k = k' then Empty else Leaf kv)" | "delete (Extension pt) k = (if take (length p) k = p then (casedelete t (drop (length p) k) of Empty Empty | Extension qu Extension (p @ q) u (* Path merging: prevents consecutive node expansion *) | t' Extension p t') else Extension pt)" | "delete (Branch children v_opt) k = (case k of [] Branch children None (* Remove current node value*) | x#xs let idx = hex_val x; children' = update_nth idx (case nthchildren idx of Some t' (let res = delete t' xs in if res = Empty then Noneelse Some res)| None None) children in (* Core of structural contraction: If only one child node remains, then perform branch contraction*) if v_opt = None ∧ count_nonempty children' = 1 then compress_branchchildren' v_opt else Branch children' v_opt)" The `fun` keyword defines the `delete` function, whose type signature is 'v MPT'. key 'v MPT' indicates that the function takes an MPT tree state and a key to be deleted, and returns the new MPT tree state after the operation.
[0043] The function uses a pattern matching mechanism to traverse the four types of nodes in the MPT tree: for empty nodes (Empty), the empty state is left unchanged; for leaf nodes (Leaf), the target key is compared with the node's storage path, and an empty node is returned only when there is a complete match to perform deletion, otherwise the original node is left unchanged; for extension nodes (Extension), the subtree is recursively deleted after verifying the search key prefix. If the result returned by backtracking is also an extension node, a critical path concatenation operation is performed to merge the current shared path with the path of the child node, thereby eliminating redundant levels; for branch nodes (Branch), after recursively removing the current node value or a certain sub-branch, the number of remaining valid child nodes is monitored in real time. Once it is detected that the node has lost its branching function (i.e., only a single child node remains and it has no value of itself), the branch compression logic is immediately triggered. The original hexadecimal branch index is remapped to a character and concatenated before the path of the remaining child node, degenerating it into a more compact extension or leaf node. Finally, through a bottom-up dynamic reconstruction mechanism, it is ensured that no matter how many deletion operations are performed, the tree structure always satisfies the structural invariance of "no redundant branches" and "no continuous extension".
[0044] In a further specific embodiment, after removing the data corresponding to the key to be deleted, the deletion operation model calls a counting function during the recursive return process to determine the number of valid surviving sub-branches of the branch node; when the number indicates that the branch node has lost its routing function, the branch compression function compress_branch is called to perform path merging and branch degradation on the branch node, reducing it to a more compact node structure, so as to avoid leaving a sparse structure with no effective routing function after the deletion operation.
[0045] S02-2: Detailed Implementation of Serialization and Hash Mapping Model In one specific embodiment, the serialization and hash mapping model first defines an intermediate algebraic data type including atomic string constructors and recursive list constructors, and configures different node type domain isolation tags for leaf nodes, extension nodes, and branch nodes respectively; then, according to the node type, the MPT logical structure is recursively mapped to the intermediate algebraic data type to obtain the serialized algebraic structure, and then a bottom-up hash calculation is performed on the serialized algebraic structure using a preset hash function to determine the hash value corresponding to the root node as the root hash of the MPT tree.
[0046] Hash Computation: such as Figure 3 As shown, the mapping comprises three stages. Stage 1 is located in the logical domain, using MPT nodes as source nodes; Stage 2 is located in the algebraic domain, where the source nodes are converted into an abstract RLP structure composed of RString and RList using the `mpt_to_rlp` function, and a node type domain isolation flag is injected; Stage 3 is located in the cryptographic domain, where the algebraic structure is converted into a fixed-length hash value using the `compute_hash` function. In this embodiment, the preset hash function is Keccak256; its injectivity is only used as an axiomatic assumption in the formal model for subsequent mechanized proof.
[0047] The recursive mapping from the intermediate algebraic data type and the MPT logical structure to this data type is modeled functionally as follows: datatype rlp_element = RString "char list" | RList "rlp_element list" fun mpt_to_rlp :: "char list MPT rlp_element" where "mpt_to_rlp Empty = RString []" (* Explicitly introduce type markers 'L', 'E', 'B' to achieve domain isolation *) | "mpt_to_rlp (Leaf kv) = RList [RString ''L'', str_to_rlp k, str_to_rlp v]" | "mpt_to_rlp (Extension pt) = RList [RString ''E'', str_to_rlp p, RString (compute_hash t)]" | "mpt_to_rlp (Branch children vo) = (let child_hashes = map (λopt. case opt of None RString [] | Some t RString (compute_hash t)) children; val_rlp = (case vo of None RString [] | Some v RList [str_to_rlp v]) in RList (RString ''B'' # child_hashes @ [val_rlp]))" The `datatype` keyword defines the recursive algebraic data type `rlp_element`, with `RString` and `RList` being the atomic string constructor and recursive list constructor, respectively. The `fun` keyword defines the recursive mapping function `mpt_to_rlp`. Empty nodes are mapped to empty atomic strings `RString[]`; leaf nodes are mapped to `RList` containing the tag 'L', remaining key path fragments, and serialized data values; extension nodes are mapped to `RList` containing the tag 'E', common prefixes, and child node hash values; and branch nodes are mapped to `RList` containing the tag 'B', the recursively encoded child node sequence, and serialized optional value fields. Thus, different node types have distinct type markers in the algebraic structure, and extension and branch nodes can recursively participate in bottom-up root hash calculations through child node hash values.
[0048] The aforementioned node type domain separation is also known as domain separation. Explicitly configuring different markers for different node types in the algebraic representation ensures that leaf nodes, extension nodes, and branch nodes remain distinguishable before entering hash calculations. This reduces the possibility of identical algebraic representations due to node type encoding confusion and lowers the dependence of mechanized proofs on underlying physical bit-level encoding details. The 'L', 'E', and 'B' markers introduced in this application for algebraic domain transformation are not physically existing RLP bytes or hexadecimal prefixes in the actual Ethereum protocol, but rather "Formal Domain Separators" specifically designed for mechanized verification in this model.
[0049] consts keccak256 :: "rlp_element char list" axiomatization where keccak_injective: "keccak256 x = keccak256 y x = y" and keccak_non_empty: "keccak256 x ≠ []" (* Hash value is never empty *) definition str_to_rlp :: "char list rlp_element" where "str_to_rlp s = RString s" fun compute_hash :: "char list MPT char list" where "compute_hash t = keccak256 (mpt_to_rlp t)" definition root_hash :: "char list MPT char list" where "root_hash t = compute_hash t" This application introduces the core injective axiom through axiomatization in the theorem prover: keccak_injective: "keccak256 x = keccak256 y The assumption "x = y" is strictly confined to the "logic-mathematical level": the system does not simulate the bit-level hash permutation algorithm of the underlying Keccak-256 in Ethereum, but instead elevates the engineering-considered "computational collision resistance" to an "ideal strict injective hypothesis" in the logical domain. That is, within the mathematical proof space, it is assumed that any two different serialized algebraic structures will necessarily map to different hash values. This boundary setting effectively isolates irrelevant physical computation noise, allowing the verification target to focus on the topological uniqueness of the tree structure.
[0050] The `mpt_to_rlp` function in this application maps logical nodes to an algebraic structure `rlp_element`, preserving both atomic strings (`RString`) and recursive lists (`RList`) to accurately capture the logical skeleton of RLP. The model utilizes the explicit first character marker (L / E / B) of the list to replace bit-level parity checks and implicit length rules in the actual encoding. Physically, the algebraic structure output by this model differs from the actual byte stream; however, in terms of mathematical logic and cryptographic commitment, they are equivalent.
[0051] The underlying Ethereum protocol performs complex Keccak-256 bitwise permutation operations, mapping sequences of arbitrary length to fixed-length 256-bit digests. Its security is guaranteed by computational collision resistance. This application introduces the abstract function keccak256 and axiomatizes its injectivity assumption, rigorously corresponding to and elevating the engineering-level "computational collision resistance" to the logical "strict injectivity assumption." As long as the front-end serialization algebraic structure mapping is unique, this model can logically derive the unique commitment of the root hash to the MPT structure. This ensures that the final state root calculated by this model is completely consistent with the root hash calculated by the actual MPT in terms of tamper-proof mathematical security properties.
[0052] S03: Specific Implementation Methods of Mechanized Verification In one specific embodiment, mechanized verification is divided into four proof tasks: the first task verifies the tree structure constraints before and after insertion or deletion; the second task verifies the consistency between the lookup, insertion, and deletion and the semantics of the valid key set; the third task verifies whether the algebraic representations of different node types are distinguishable; and the fourth task, under the hash injectivity assumption of the formal model, verifies whether the root hashes of different tree structures are distinguishable. The theorem proof aid returns the verification status of each of the four tasks and forms the model verification result accordingly.
[0053] Step 1: Construct a proof of structural invariance. Assuming that the MPT tree before the insertion or deletion operation satisfies the following conditions: the common prefix of the expanded nodes is non-empty, there are no consecutive nested expanded nodes, and the branch nodes include 16 optional child node positions, verify that the MPT tree after the corresponding operation still satisfies the above structural constraints. The structural invariance predicate is defined as follows: fun invar_MPT :: "'v MPT bool" where "invar_MPT Empty = True" | "invar_MPT (Leaf kv) = True" | "invar_MPT (Extension pt) = (p ≠ [] ∧ (case t of Extension _ _ False | _ True) ∧ invar_MPT t)" | "invar_MPT (Branch children vo) = (length children = 16 ∧ ( opt ∈ set children. case opt of None True | Some t invar_MPT t))" The `fun` keyword defines the invar_MPT structure invariance predicate, whose type signature is 'v MPT'. The function takes 'v MPT' as input and determines whether an MPT tree satisfies the legal structure constraints, returning a boolean verification result.
[0054] The function applies normative constraints to four types of nodes in the MPT tree based on pattern matching: Empty nodes and Leaf nodes naturally satisfy structural invariance; Extension nodes require that the prefix path is not empty, the child nodes cannot be nested extension nodes, and the subtree itself satisfies invariance; Branch nodes force the length of the child node list to be 16, and all child nodes must satisfy structural invariance.
[0055] Taking the insertion operation structure invariance theorem as an example, Theorem 1 is defined functionally as theorem invar_MPT_insert:"invar_MPT t "invar_MPT (insert tkv)" means that for any tree t that satisfies invar_MPT, the tree t′ generated after executing insert will still satisfy the constraint.
[0056] Here, `theorem` is the keyword for the theorem declaration, `invar_MPT_insert` is the theorem name, the premise is `invar_MPTt`, which means that the original MPT tree `t` satisfies the MPT structure invariance constraint; the conclusion is `invar_MPT(insert tkv)`, which means that after performing the key-value (k,v) insertion operation on a valid MPT tree, the generated new MPT tree still satisfies the structure invariance; the lemma dependency graph is as follows. Figure 4 As shown.
[0057] like Figure 4 As shown, Theorem 1, `invar_MPT_insert`, is supported by insertion invariance lemmas corresponding to leaf nodes, expanded nodes, and branch nodes. Specifically, the proof related to expanded nodes relies on the lemmas concerning the non-emptiness, commutation, and prefix consistency of the longest common prefix, while the proof related to branch nodes relies on the lemmas concerning the hexadecimal index range, the preservation of list length after update, and the preservation of subtree invariance. Through these lemma dependencies, the insertion branches under different node types are summarized into a conclusion on the overall structural invariance after the insertion operation.
[0058] Theorem 2 is defined functionally as the theorem invar_MPT_delete: "invar_MPT t "invar_MPT(delete tk)" means that for any tree t that satisfies invar_MPT, the tree t′ generated after executing delete will still satisfy the constraint.
[0059] Here, `theorem` is the keyword for the theorem declaration, `invar_MPT_delete` is the theorem name, the premise is `invar_MPTt`, which means that the original MPT tree `t` satisfies the MPT structure invariance constraint; the conclusion is `invar_MPT(delete tk)`, which means that after performing the key deletion operation `k` on a valid MPT tree, the generated new MPT tree still satisfies the structure invariance; the lemma dependency graph is as follows. Figure 4 As shown.
[0060] Theorem 2, `invar_MPT_delete`, is supported by lemmas on the deletion invariance of both the expanded node and the branch node. The proof related to the expanded node relies on the lemma of path concatenation and safe merging after recursive subtree deletion. The proof related to the branch node not only relies on the structural preservation of sublist updates but also heavily depends on the lemma of branch compression validity and the lemma of preventing hexadecimal index out-of-bounds errors. Through these lemma dependencies, complex deletion branches such as node merging, branch sparsity degradation, and path folding are summarized into a conclusion on the overall structural invariance after the deletion operation.
[0061] Step Two: Construct a theorem proving element invariance. Project the physical tree structure as a set of mathematical keys and use set algebra rules to verify the correctness of the core evolutionary function. For example, rigorously prove through inductive lemmas that the insertion operation is logically completely equivalent to the set union operation, and the deletion operation is completely equivalent to the set difference operation, eliminating data errors or omissions. Taking the element invariance theorem of the insertion operation as an example, theorem set_insert: "invar_MPT t mpt_set(insert tkv) = mpt_set t ∪ {k}”, the insert operation of MPT is strictly equivalent to the element insertion operation in set theory in abstract semantics. The key set after the insert operation is equal to the union of the original set and the new key.
[0062] Here, `theorem` is the keyword for theorem declaration, `set_insert` is the theorem name, the premise is `invar_MPT t`, indicating that the original MPT tree `t` satisfies the MPT structure invariance constraint; the conclusion is `mpt_set (insert tkv) = mpt_set t ∪{k}`, meaning that after performing the operation of inserting key `k` and value `v` on a valid MPT tree `t`, the set of keys contained in the new tree is equal to the union of the original tree's set of keys and the single-element set `{k}`. In addition to the insertion operation mentioned above, the element invariance verification will also correspond the search operation to the membership relation in the valid key set and the deletion operation to the difference operation of the valid key set. In this way, it will be verified whether the search result, the key set after insertion, and the key set after deletion are consistent with the semantics of the expected set.
[0063] Theorems 3 and 4 are defined functionally as follows: theorem lookup_eq_Some: "invar_MPT t lookup tk = Some v k ∈ mpt_set t" with theorem lookup_eq_None: "invar_MPT t lookup tk = None k "mpt_set t" means that for any tree t that satisfies invar_MPT, the success or failure of the lookup operation strictly corresponds to the membership relation of the abstract set.
[0064] Here, `theorem` is the keyword for theorem declaration, `lookup_eq_Some` and `lookup_eq_None` are theorem names, with the premise being `invar_MPT t`, indicating that the original MPT tree `t` satisfies the MPT structure invariance constraint; the conclusions respectively represent that if the lookup is successful and returns `Some v`, then the key `k` must exist in the abstract set `mpt_set`, and if the lookup fails and returns `None`, then the key `k` exists if and only if it does not exist in the abstract set; Theorem 5 is defined functionally as the theorem set_delete: "invar_MPT t mpt_set (delete k) = mpt_set t - {k}" means that for any tree t that satisfies invar_MPT, performing the delete operation is strictly equivalent in abstract semantics to the difference operation in set theory.
[0065] Here, `theorem` is the keyword for theorem declaration, `set_delete` is the theorem name, the premise is `invar_MPT t`, which means that the original MPT tree `t` satisfies the MPT structure invariance constraint; the conclusion is `mpt_set (delete tk) = mpt_set t - {k}`, which means that after performing the deletion operation on the key `k` on a valid MPT tree, its corresponding logical set is equal to the original set minus the target key `k`.
[0066] Theorem 5, `set_delete`, is supported by the lookup-delete equivalence lemma. The proof of this lemma heavily relies on the compress-branch-lookup-constancy lemma to demonstrate that even if the physical structure undergoes drastic changes such as the degeneration of branch nodes into extended nodes, the logical key-value mapping remains constant. Through this lemma dependency, and combined with the conclusions of successful lookups (Theorem 3) and failed lookups (Theorem 4), the complex underlying structure is shrunk and summarized into the conclusion of overall element invariance after the deletion operation.
[0067] Step 3: Construct a serialization distinguishability proof. Based on the different node type domain isolation markers of leaf nodes, extension nodes, and branch nodes, verify that the serialization algebraic structures corresponding to different node types are different, so as to exclude the situation where different types of nodes produce the same structural representation in the intermediate algebraic representation layer.
[0068] Step 4: Construct a proof of root hash distinctiveness. Based on the hash injective axiom and the aforementioned algebraic field isolation rule, verify in the formal model that the root hashes corresponding to different MPT tree structures are distinct. Construct the theorem root_hash_unique: "t ≠ t' The expression `root_hash t ≠ root_hash t'"` means that the two MPT trees have different structures, and `root_hash t ≠ root_hash t'` means that the root hash values of the two MPT trees are not equal.
[0069] The theorem proof aid returns the verification status of the above proof targets in sequence; the model verification result is determined to be passed only when the structural invariance, element invariance, serialization distinguishability and root hash distinguishability proofs are all passed, and is used as the entry condition for subsequent business instantiation.
[0070] In the formal model, the aforementioned root hash distinguishability conclusion is based on the premise that the serialized algebraic structure is distinguishable and that the pre-defined hash function satisfies the injectivity assumption. Within this premise, changes in the tree structure or the data it carries will be reflected in changes to the root hash. Therefore, trusted root hashes can be used to detect inconsistencies in state or data modifications, providing a formal basis for tamper-proof verification.
[0071] S04: Detailed Implementation of Business Tree Instantiation and Business Data Processing In one specific embodiment, the target blockchain business data type is determined as a transaction record type, and the type variable 'v' in the node model is instantiated as this transaction record type to form a transaction tree. Subsequently, based on the basic operation model, batch insertion is performed on multiple transaction records to obtain the business data processing results. Through this instantiation process, the node structure, basic operations, and hash mapping model, which have been mechanically verified, are applied to the storage and processing of transaction records.
[0072] In addition to the transaction tree, the type variable 'v' can also be instantiated into an account status type or a transaction receipt type based on the target business data type, thereby forming a status tree or a receipt tree respectively. Different business trees share the aforementioned node structure, basic operations, and hash mapping model, but their business data processing results are verified according to the preset business rules corresponding to the corresponding business type.
[0073] Specifically, the state tree can carry account status data such as account balance and contract code, the transaction tree can carry transaction records within a block, and the receipt tree can carry transaction execution results; polymorphic type variables enable these business data to reuse the same node model, basic operation model, and hash mapping model without having to rebuild the underlying tree structure definition separately.
[0074] S05-1: Specific Implementation Methods for Business Rule Consistency Verification In one specific embodiment, corresponding business type determination predicates are constructed based on the respective business type determination conditions for ordinary transfers, message calls, and contract creation. A preset business rule is established that the same transaction record cannot be simultaneously determined as two or more business types. A theorem proof auxiliary tool is invoked to verify that no transaction record in the processed business data after batch insertion simultaneously satisfies two or more business type determination predicates. When the verification passes, it is determined that the transaction type determination in the processed business data is consistent with the preset business rule. Thus, mutual exclusion checks can be performed on the Ethereum Virtual Machine (EVM) execution paths corresponding to ordinary transfers, message calls, and contract creation.
[0075] By performing mutual exclusion proofs on the three types of transaction judgment predicates, the situation where the same transaction meets multiple type conditions can be excluded before entering the corresponding EVM business processing branch. This avoids ambiguity in the execution path caused by overlapping transaction classifications and provides a verification basis for the consistency of business rules in batch transaction processing results.
[0076] record Transaction = transaction_from :: "char list"(* sender address*) transaction_nonce :: nat(* Transaction sequence number, to prevent replay attacks*) transaction_gasPrice :: nat(*Gas Price*) transaction_gasLimit::nat(*Gas upper limit*) transaction_to :: "char list option"(* Receive address, None indicates contract creation *) transaction_value :: nat(*transfer amount*) transaction_data :: "char list"(* Transaction input data*) Contract Creation Determination: Definition is_contract_creation :: "Transaction bool" where "is_contract_creation tx = (transaction_to tx = None)" Boundary condition: This predicate returns true only if the transaction's receiving address, transaction_to, is strictly equal to None, indicating that this transaction is used to initialize and deploy a new contract on the blockchain.
[0077] Message call (contract call) determination: definition is_contract_call :: "Transaction bool" where "is_contract_call tx = (transaction_to tx ≠ None ∧ transaction_data tx ≠ [])" Boundary conditions: Two conditions must be met simultaneously: the receiving address transaction_to exists (not equal to None), and the transaction data transaction_data is not empty (not equal to []). In this case, the predicate returns true, indicating that a specific function of an existing contract is called.
[0078] Normal Transfer Detection: definition is_transfer :: "Transaction" bool" where "is_transfer tx = (transaction_to tx ≠ None ∧ transaction_data tx = [])" Boundary conditions: The receiving address must exist and the data attached to the transaction must be strictly empty (equal to []). In this case, the predicate returns true, indicating that this is just a simple state balance transfer.
[0079] The mutual exclusion theorem is expressed as: theorem transaction_types_exclusive: shows "is_transfer transaction ¬ is_contract_creation transaction" and "is_transfer transaction ¬ is_contract_call transaction" and "is_contract_creation transaction - is_transfer transaction and "is_contract_creation transaction ¬ is_contract_calltransaction" This theorem rigorously establishes that any legally inserted Ethereum transaction into the transaction tree can never simultaneously satisfy two conflicting type predicates. By mathematically proving this mutually exclusive property of "definition as specification," the system fundamentally eliminates the security risk of smart contract execution state machine disorder caused by ambiguity in the construction of underlying business data, thus achieving reproducibility of business logic verification.
[0080] S05-2: Specific Implementation Methods for Generating Business Data Existence Proof In one specific embodiment, the proof of the existence of business data is modeled as an ordered chain of evidence consisting of recursive length prefix encoded RLP serialization nodes, wherein each RLP serialization node is obtained by RLP encoding of the serialization algebra structure corresponding to the corresponding MPT node.
[0081] In this embodiment, the existence proof of the aforementioned business data adopts Merkle Proof; Recursive Length Prefix (RLP) stands for Recursive Length Prefix. This proof mechanism is suitable for scenarios where the light client does not need to synchronize the complete business tree: the full node only provides the necessary serialized nodes on the target key path, and the light client completes the existence verification based on the trusted root hash, thereby reducing the need for full state synchronization and local storage.
[0082] The proof of the existence of business data is generated by full nodes. The full node recursively traverses the business tree with the target key as the retrieval condition, and sequentially extracts each MPT node along the key path corresponding to the target key from the root node to the target data node. The target data node stores the business data corresponding to the target key. Then, each extracted MPT node is converted into a corresponding RLP serialization node and arranged in the traversal order from the root node to the target data node to generate an ordered chain of evidence for the proof of the existence of business data.
[0083] S05-3: Specific Implementation Methods for Business Data Existence Proof Verification In a further specific embodiment, the light client takes the trusted root hash of the business tree, the target key, the business data value to be verified, and the proof of the existence of the business data as input, performs hash link verification on the ordered evidence chain along the key path corresponding to the target key, and performs data value matching verification on the business data value at the end of the chain and the business data value to be verified.
[0084] like Figure 5 As shown, the full node acts as the prover, recursively traversing the MPT tree with the search key k and generating a proof list including RLP_Root, RLP_Node1 to RLP_Leaf. The light client acts as the verifier, receiving the trusted root hash, the key-value pair to be verified (key, value), and the proof list. It first calculates the hash of the first node and compares it with the trusted root hash. If the hashes of the first node are equal, it recursively verifies subsequent nodes along the target key path. If the hash chain is valid and the values at the end of the chain are consistent, the verification is successful; if the hash of the first node is not equal to the trusted root hash, the evidence chain is broken, or the values at the end of the chain do not match, the corresponding verification failure result is output.
[0085] In the above interaction, the full node acts as the Prover, and the light client acts as the Verifier. The Verifier does not directly trust the business data provided by the Prover. Instead, it checks the evidence chain step by step by utilizing the correspondence between the head node of the proof chain and the root hash, the hash reference relationship between adjacent nodes, and the consistency of the data value at the end of the chain. When the preset hash assumption is true, any change to the content of any node or the chain relationship will cause the corresponding verification to fail, thereby identifying proofs that are inconsistent with the root hash.
[0086] To verify the correspondence between the proof generation logic and the verification logic, the core theorem *theoremmerkle_proof_valid* is constructed: "lookup tk = Some v The theorem states that, given the basic operational model that performs a lookup on the target key k and outputs the data value v, the evidence chain generated by the full node through generate_proof can be verified by the light client based on root_hash using verify_proof.
[0087] The above theorem is used to verify the effectiveness of the mechanism between the full node proof generation logic and the light client verification logic. During the actual existence verification, if the proof mechanism passes the validity verification, and both the hash link verification and data value matching verification performed by the light client pass, a business verification result indicating that the business data corresponding to the target key exists in the business tree is output; otherwise, the existence conclusion is not output.
[0088] The functional modeling of the `generate_proof` function, which generates an ordered RLP node evidence chain for full nodes, and the `verify_proof` function, which recursively verifies the evidence chain based on the trusted root hash, is as follows: fun generate_proof :: "char list MPT key merkle_proof" where "generate_proof Empty k = [mpt_to_rlp Empty]" | "generate_proof (Leaf k' v) k = [mpt_to_rlp (Leaf k' v)]" | "generate_proof (Extension pt) k = (mpt_to_rlp (Extension pt)) #generate_proof t (drop (length p) k)" | "generate_proof (Branch children vo) k = (let current_rlp = mpt_to_rlp (Branch children vo) in case k of [] [current_rlp] | x # xs (case children ! hex_val x of None [current_rlp] | Some t current_rlp # generate_proof t xs))" fun verify_proof :: "char list key char list merkle_proof bool"where "verify_proof root kv [] = False" | "verify_proof root kv [node_rlp] = (keccak256 node_rlp = root ∧check_value node_rlp kv)" | "verify_proof root kv (node_rlp # rest) = (if keccak256 node_rlp =root then case extract_next_hash node_rlp k of None False | Some (next_root, remaining_k) verify_proof next_root remaining_k vrest else False)" To ensure that the lightweight client can securely and completely verify the data sent by the full node, this model defines the core rules of the interaction protocol as follows: The trusted root hash is obtained as follows: The trusted root hash (State Root) used by light clients is directly taken from the block header that is synchronized locally and verified through consensus. This root hash serves as the absolute anchor of trust and is updated synchronously with the block header with each block update, without needing to download the complete tree structure data.
[0089] Evidence chain node order: The evidence chain (merkle_proof) generated by generate_proof is an ordered list of RLP elements. The node order of this list strictly follows a top-down topological feature, that is, the first element must correspond to the root node of the tree, the last element must correspond to the leaf node containing the target data, and the middle elements are extension or branch nodes on the path in turn.
[0090] Hash reference and path matching: In the recursive verification of verify_proof, the light client does not trust any node content. It first calculates the hash value of the current node node_rlp and compares it with the root that it absolutely trusts. If a match is successful, the helper function extract_next_hash is used to extract the hash pointer to the next hop child node from the internal structure of the current node as the new trusted root (next_root), and the matched key prefix is truncated to obtain the remaining key path (remaining_k), and so on recursively downwards.
[0091] Value matching mechanism: When the recursive parsing reaches the tail element (i.e. leaf node) of the evidence chain, the check_value helper function is called to check whether the data stored in the underlying layer of the node is completely consistent with the target key-value pair (k, v) to be verified.
[0092] Failure Branch (Defense Mechanism): If any anomaly occurs during the verification process, the system will immediately enter the failure branch and return False, rejecting the data. These failure branches include, but are not limited to: the hash calculated by the node does not match the root of trust (i.e., root hash mismatch), the hash link breaks when parsing the next hop (i.e., data forgery), or the value of the final leaf node does not match the target value.
[0093] Preconditions for the theorem to hold: This application constructs the core completeness theorem, merkle_proof_valid:"lookup tk = Some v The theorem, "verify_proof (root_hash t) kv (generate_proof tk)," holds only under the condition that lookup tk = Some v, meaning the target key-value pair must legally exist in the original tree t. The theorem mathematically proves that, provided this condition is met, the evidence chain generated by honest full nodes will always pass 100% verification by the light client, thus establishing the protocol's completeness.
[0094] Example 2: Formal Verification System for Blockchain Underlying Data Structure like Figure 6 As shown, this embodiment provides a formal verification system for the underlying data structure of a blockchain. Figure 6 The system shown is configured according to the data processing and verification relationships, including a node modeling module, a basic operation and hash mapping modeling module, a mechanized verification module, and a business verification module. The functions and coordination relationships of each module are as follows: The node modeling module generates MPT node models that are shared by subsequent models. This module uses a recursive algebraic data type to define four types of node constructors: empty nodes, leaf nodes, extended nodes, and branch nodes. It also sets the blockchain business data as node data carried by type variables, so that the resulting node model can be used as input for the next module.
[0095] The basic operation and hash mapping modeling module is used to take the node model as input. On the one hand, it forms a model for searching, inserting and deleting key-value data in the MPT tree. On the other hand, it converts the MPT logical structure into an algebraic structure containing node type field isolation tags, and calculates the root node hash layer by layer from the algebraic structure, thereby forming the basic operation model and the serialization and hash mapping model.
[0096] Specifically, the basic operation and hash mapping modeling module includes a basic operation modeling unit and a hash mapping modeling unit. The basic operation modeling unit sets up search, insertion, and deletion functions, which are used to perform recursive retrieval, node splitting and branch construction, path merging, and branch degradation, respectively. The hash mapping modeling unit sets up a serialization abstraction subunit and a hash value calculation subunit. The former converts the node topology into an algebraic representation composed of atomic strings and recursive lists and injects a node type field isolation marker. The latter performs bottom-up hash calculation on this algebraic representation and outputs the root hash.
[0097] The mechanized verification module receives two types of models output by the previous module and sets four types of proof objectives. The basic operation model corresponds to two types of proof objectives: structural constraint preservation and semantics of valid key sets. The serialization and hash mapping model corresponds to two types of proof objectives: node algebra representation differentiation and tree structure root hash differentiation. After the theorem proof auxiliary tool performs mechanized proofs on each objective, this module summarizes and generates the model verification results.
[0098] Specifically, the mechanized verification module includes a structure invariance verification unit, an element invariance verification unit, a serialization distinguishability verification unit, and a root hash distinguishability verification unit. The structure invariance verification unit checks the node structure constraints before and after insertion or deletion operations; the element invariance verification unit checks the consistency between search, insertion, and deletion operations and set membership relations, union operations, and difference operations; the serialization distinguishability verification unit checks whether the algebraic structures corresponding to different node types are mutually distinguishable; and the root hash distinguishability verification unit, under the hash injectivity assumption of the formal model, checks whether the root hashes corresponding to different MPT tree structures are mutually distinguishable.
[0099] The business verification module is used to instantiate the type variables in the node model into the target blockchain business data type when the model verification result is passed, forming a business tree. It processes the corresponding business data based on the basic operation model and obtains the business data processing result. It performs consistency verification on the result according to the corresponding preset business rules, and verifies the existence proof of the business data corresponding to the target key using the trusted root hash of the business tree as the verification benchmark, and outputs the business verification result.
[0100] Specifically, the business verification module includes a business tree instantiation and consistency verification unit, an existence proof generation unit, and an existence proof verification unit. The business tree instantiation and consistency verification unit is used to form a state tree, transaction tree, or receipt tree, and to perform rule consistency verification on the corresponding business data processing results; the existence proof generation unit is used by full nodes to generate an ordered RLP serialized node evidence chain from the root node to the target data node; the existence proof verification unit is used by the light client to perform hash link verification and data value matching verification based on the trusted root hash.
[0101] In the above system, the output of the node modeling module is passed to the basic operation and hash mapping modeling module. The model formed by the two modeling modules is then passed to the mechanized verification module. The mechanized verification module outputs the model verification result representing whether each proof passes. The business verification module only performs business instantiation, consistency verification, and business data existence verification when the result is passed, thereby forming a system with... Figure 6 The four modules shown have a consistent functional relationship.
[0102] The embodiments of this application have been described above with reference to the accompanying drawings. However, this application is not limited to the specific embodiments described above. The specific embodiments described above are merely illustrative and not restrictive. Those skilled in the art can make many other forms under the guidance of this application without departing from the spirit and scope of the claims, and all of these forms are within the protection scope of this application.
Claims
1. A formal verification method for the underlying data structure of a blockchain, characterized in that, include: Using recursive algebraic data types, Merkel-Patricia tree (MPT) nodes are modeled as empty nodes, leaf nodes, extended nodes, and branch nodes. Blockchain business data is carried by type variables to obtain the node model. Based on the node model, a basic operation model for key-value data in the MPT tree is constructed, and a serialization and hash mapping model of the MPT logical structure to the root hash is established through an algebraic structure with node type field isolation markers. Based on the basic operation model, generate structural invariance proofs and element invariance proofs; based on the serialization and hash mapping model, generate serialization distinguishability proofs and root hash distinguishability proofs; call the theorem proof auxiliary tool to perform mechanical verification of each proof, and obtain the model verification results. When the model verification result indicates that all proofs have passed mechanical verification, the type variable in the node model is instantiated as the target blockchain business data type to form a business tree. Based on the basic operation model, the business data corresponding to the target blockchain business data type is processed to obtain the business data processing result. Based on the preset business rules corresponding to the target blockchain business data type, the consistency verification of the business data processing result is performed, and the existence proof of the business data corresponding to the target key is verified using the trusted root hash of the business tree as the verification benchmark, and the business verification result is output.
2. The formal verification method for the underlying data structure of a blockchain according to claim 1, characterized in that, The key path in the node model is composed of a hexadecimal character sequence; the empty node represents the empty state of the MPT tree or the termination of the key path; the leaf node includes the remaining key path fragment and the data value corresponding to the type variable; the extended node includes a non-empty common prefix and points to a unique child node; the branch node includes 16 optional child node positions corresponding to hexadecimal characters 0 to F and optional value fields corresponding to the type variable.
3. The formal verification method for the underlying data structure of a blockchain according to claim 1, characterized in that, The basic operation model includes a search operation model, an insertion operation model, and a deletion operation model; The search operation model receives an MPT tree and a key to be searched, performs pattern matching based on node type, performs prefix consumption and recursive search segment by segment along the key path corresponding to the key to be searched, and outputs optional type search results containing corresponding data values or null values. The insertion operation model receives an MPT tree, a key to be inserted, and a data value to be inserted. It deterministically maps the input MPT tree state to the MPT tree state after insertion. When the key path corresponding to the key to be inserted conflicts with an existing key path, it determines the common prefix of the two and generates a fork structure. The deletion operation model receives an MPT tree and a key to be deleted, performs a depth-first traversal along the key path corresponding to the key to be deleted, removes the data corresponding to the key to be deleted, adjusts the parent nodes on the key path during the recursive return process, and outputs the state of the MPT tree after deletion.
4. The formal verification method for the underlying data structure of a blockchain according to claim 3, characterized in that, When the key path corresponding to the key to be inserted is different from the existing key path, the insertion operation model calls the longest common prefix function to calculate the overlapping segment of the two; when the two fork after the overlapping segment, the node corresponding to the existing key path is split, a new branch node is constructed, and the forked key paths are associated with the corresponding child nodes respectively. When the key path corresponding to the key to be inserted matches the path segment of an existing node, the key is recursively inserted along the child node pointed to by the existing node, and the path segments of adjacent extended nodes are merged during the recursive return process to obtain the MPT tree state after insertion without consecutive nested extended nodes. After removing the data corresponding to the key to be deleted, the deletion operation model calls a counting function during the recursive return process to determine the number of valid surviving sub-branches of the branch node; When the number of valid surviving sub-branches indicates that the branch node has lost its branching function, the branch compression function is called to perform path merging and branch degradation on the branch node, reducing the branch node to a compact node structure, and obtaining the MPT tree state after deletion.
5. The formal verification method for the underlying data structure of a blockchain according to claim 1, characterized in that, The establishment of the serialization and hash mapping model includes: defining an intermediate algebraic data type including atomic string constructors and recursive list constructors, and configuring different node type domain isolation markers for leaf nodes, extension nodes, and branch nodes respectively; recursively mapping the MPT logical structure to the intermediate algebraic data type according to the node type, mapping empty nodes to empty atomic strings, mapping leaf nodes to a recursive list including the corresponding node type domain isolation marker, remaining key path fragments, and serialized representation of data values, mapping extension nodes to a recursive list including the corresponding node type domain isolation marker, common prefix, and child node hash values, and mapping branch nodes to a recursive list including the corresponding node type domain isolation marker, recursive encoding results of child node sequences, and serialized representation of optional value fields, thus obtaining a serialized algebraic structure; performing bottom-up hash calculation on the serialized algebraic structure using a preset hash function, and determining the hash value corresponding to the root node as the root hash of the MPT tree.
6. The formal verification method for the underlying data structure of a blockchain according to claim 5, characterized in that, The mechanized verification includes: First, assuming the MPT tree before insertion or deletion operations satisfies the structural constraints that the common prefix of the extended nodes is non-empty, there are no consecutive nested extended nodes, and the branch nodes include 16 optional child node positions, verify that the MPT tree after the corresponding operation still satisfies the structural constraints, generating the structural invariance proof; second, mapping the MPT tree to a valid key set, verifying that the search, insertion, and deletion operations correspond to set membership, union, and difference operations respectively, generating the element invariance proof; third, based on the node type domain isolation marker and the injectivity assumption of the preset hash function set in the formal model, verifying that the serialized algebra structures corresponding to different node types are different, generating the serialization distinguishability proof, and verifying that the root hashes corresponding to different MPT tree structures are different, generating the root hash distinguishability proof; fourth, when all proofs pass the mechanized verification, the model verification result is determined to be passed.
7. The formal verification method for the underlying data structure of a blockchain according to claim 6, characterized in that, The consistency verification includes: determining the target blockchain business data type as a transaction record type, instantiating the type variable as the transaction record type to form a transaction tree, and performing batch insertion on multiple transaction records based on the basic operation model to obtain the business data processing result; constructing corresponding business type determination predicates according to the respective business type determination conditions of ordinary transfer, message call, and contract creation, and determining that the same transaction record cannot be determined as two or more of the aforementioned business types simultaneously as the preset business rule; calling the theorem proof auxiliary tool to verify that there are no transaction records in the business data processing result that simultaneously satisfy two or more of the aforementioned business type determination predicates; when the verification passes, determining that the transaction type determination in the business data processing result is consistent with the preset business rule.
8. The formal verification method for the underlying data structure of a blockchain according to claim 6, characterized in that, The generation of the business data existence proof includes: modeling the business data existence proof as an ordered evidence chain composed of recursive length prefix encoded (RLP) serialization nodes, wherein the RLP serialization nodes are obtained by RLP encoding the serialization algebra structure corresponding to the MPT nodes; recursively traversing the business tree according to the target key by all nodes, sequentially extracting each MPT node along the key path corresponding to the target key from the root node to the target data node, wherein the target data node stores the business data corresponding to the target key; converting each extracted MPT node into a corresponding RLP serialization node, and arranging them according to the traversal order to generate the business data existence proof.
9. The formal verification method for the underlying data structure of a blockchain according to claim 8, characterized in that, The verification of the existence proof of the business data corresponding to the target key includes: the light client takes the root hash of the business tree, the target key, the business data value to be verified, and the existence proof of the business data as input, performs hash link verification along the key path corresponding to the target key on the ordered evidence chain, and performs data value matching verification on the business data value at the end of the chain and the business data value to be verified; calls the theorem proof auxiliary tool to verify that, under the condition that the basic operation model performs a lookup operation on the target key and outputs the business data value to be verified, the existence proof of the business data generated by the full node can pass the hash link verification and data value matching verification performed by the light client, and obtains the validity verification result of the proof mechanism; when the validity verification result of the proof mechanism is passed, and both the hash link verification and the data value matching verification are passed, the business verification result indicating that the business data corresponding to the target key exists in the business tree is output.
10. A formal verification system for the underlying data structure of a blockchain, characterized in that, include: The node modeling module is used to model Merkel-Patricia tree (MPT) nodes as empty nodes, leaf nodes, extended nodes, and branch nodes using recursive algebraic data types, and to carry blockchain business data with type variables to obtain the node model. The basic operation and hash mapping modeling module is used to construct a basic operation model for key-value data in the MPT tree based on the node model, and to establish a serialization and hash mapping model of the MPT logical structure through an algebraic structure with node type field isolation markers to the root hash. The mechanized verification module is used to generate structural invariance proofs and element invariance proofs based on the basic operation model, generate serialization distinguishability proofs and root hash distinguishability proofs based on the serialization and hash mapping model, and call the theorem proof auxiliary tool to perform mechanized verification of each proof to obtain the model verification results. The business verification module is used to instantiate the type variables in the node model into the target blockchain business data type when the model verification result is passed, forming a business tree, and processing the business data corresponding to the target blockchain business data type based on the basic operation model to obtain the business data processing result. Based on the preset business rules corresponding to the target blockchain business data type, the consistency verification of the business data processing result is performed, and the existence proof of the business data corresponding to the target key is verified using the trusted root hash of the business tree as the verification benchmark, and the business verification result is output.