Download audit report
This document presents the security review performed by Nethermind in the Polygon Id Smart Contracts. The Polygon Id is a decentralized and permissionless identity framework for web2 and web3 applications based on the principles of Self-Sovereign Identity (SSI) and cryptography. With the help of zero-knowledge proofs, users can prove their identity without exposing their private information. The audit focuses on Iden3 smart contracts. Iden3 is an open-source protocol that provides the foundations for Polygon Id. The protocol defines how the parties communicate and interact. Polygon Id is an abstraction layer to enable developers to build applications leveraging the Iden3 protocol. The audited code consists of 687 lines of Solidity with code coverage of 94%. The Polygon team provided two documents to assist the audit presenting an overview of the contracts and how to run the test suite. The audit was supported by the documentation accessible from the Polygon ID wiki.
The audit was conducted using (a) manual analysis of the codebase, (b) automated analysis tools, (c) simulation of the smart contracts, and (d) creation of test cases. The Nethermind Formal Verification and Cryptography Research teams also provided support for the audit. The audit was supplemented with multiple testing techniques, such as black-box testing, white-box testing, and property testing. The white-box tests were enhanced by dynamic analysis to uncover untested code branches.
In the first re-audit, we identified 16 points of attention, of which two were classified as Low severity, while the remaining 14 points of attention were classified as either Informational or Best Practices. Following the re-audit, the Polygon team addressed 12 issues, while four issues were acknowledged.
After the audit, the Polygon team decided to refactor the implementation to remove the restriction of only having one unique state per contract, which could potentially limit the future evolution of the system. Our team reviewed these changes in re-audit 2. In the second reaudit, we identified five points of attention, of which two were classified as Informational and three were classified as Best Practices. The Polygon team addressed four issues, while one issue was acknowledged. The acknowledged issue pertains to our request for the creation of a test case to evaluate the logic for updating implementations, which is a standard procedure that the Polygon team has expertise in.
| Audit assessment | |
| Audit Type | Security Review |
| Initial Report | Jan. 31, 2023 |
| Response from Client | Feb. 15, 2023 |
| Final Report Reaudit 1 | Mar. 16, 2023 |
| Final Report Reaudit 2 | Apr. 18, 2023 |
| Methods | Manual Review, Automated Analysis |
| Repository | Polygon ID |
| Commit Hash (Initial Audit) | 9c8f5d6132 |
| Commit Hashes (Reaudit) | d9be60d7c9 80398a1b46 ebe466957f c9c661ef00 347dd01048 3245a7563e a046906491 278e292d1c 6ac5bca7fc |
| Documentation | README |
| Documentation Assessment | High |
| Test Suite Assessment | Medium |
Findings by severity
| # | Contract | LoC | Comments | Ratio | Blank | Total |
| 1 | contracts/lib/Smt.sol | 427 | 127 | 29.7% | 60 | 614 |
| 2 | contracts/state/StateV2.sol | 260 | 173 | 66.5% | 44 | 477 |
| Total | 687 | 300 | 43.6% | 104 | 1091 |
The Polygon ID, with the help of zero-knowledge proofs, lets users prove their identity without exposing their private information. This section was written based on the codebase audited in audit 1, before the refactoring performed by the Polygon team. The audit is based on two contracts: a) StateV2.sol; and b) Smt.sol. The contract StateV2.sol stores meta information about identities. The contract is OwnableUpgradeable, which means that it uses the EIP-1967 proxy pattern for holding the state information, where the proxy contract store the address of the logic contract they delegate to, as well as other proxy-specific information. The contract Smt.sol implements a Sparse Merkle Tree used by the StateV2.sol for managing its data. The contracts are described below in accordance with the structural diagram presented in Fig.2.
OwnableUpgradeable BinarySearchSmtRoots
Smt addtransitState
🔍 getGISTProofByRoot 🔍 getGISTProofByBlock 🔍 getRoot 🔍 getGISTProofByTime 🔍 getRootInfoByTime
StateV2.solThe contract StateV2.sol uses three structs: StateData, StateEntry, and StateInfo. The struct StateEntry holds the metadata of each identity state. The struct is reproduced below.
struct StateEntry {
uint256 id;
uint256 timestamp;
uint256 block;
uint256 replacedBy;
}The struct StateData stores all the state data. In this struct, the field statesHistories holds the history per each identity, while the field stateEntries stores data related to the state of the identity.
struct StateData {
mapping(uint256 => uint256[]) statesHistories;
mapping(uint256 => StateEntry) stateEntries;
}The struct StateInfo is used for public interfaces to represent state information. This structure holds information about identity identifiers when the state was committed to the Blockchain, the block number when the state was committed, and the state which replaced this state for the identity. The struct is reproduced below.
struct StateInfo {
uint256 id;
uint256 state;
uint256 replacedByState;
uint256 createdAtTimestamp;
uint256 replacedAtTimestamp;
uint256 createdAtBlock;
uint256 replacedAtBlock;
}Thus, for each identity, the contract stores the identity state and its history. The contract also uses a sparse Merkle Tree to store the whole tree (and history) on-chain. This contract has the following public functions.
− setVerifier()
− transitState()
− renounceOwnership()
− transferOwnership()In addition to these functions, the contract provides several getters not described here. These getters allow to retrieve data such as the state, root information, check the existence of ids, states, retrieve the verifier address, among others. Fig. 2 lists all the functions implemented in the contract StateV2.sol.
Smt.solSmt is a library implementing a Sparse Merkle Tree (SMT). This implementation keeps the tree history as long as roots are never duplicated. Each leaf of the tree consists of a tuple (index;value), where the index represents the identity (and also the location in the tree), while value represents the value assigned to the given id. A Sparse Merkle Tree is an authenticated data structure based on a perfect Merkle tree of intractable size. It contains a distinct leaf for every possible output from a cryptographic hash function and can be simulated efficiently because the tree is sparse (i.e., most leaves are empty).
Root= h ((1,2)(3,4)…(n/2-1), (n/2)(n/2+1)…(n))
... ...
h h (1,2)(3,4) ((n-3),(n-2)),((n-1),(n))
h h h h (1)(2) (3)(4) (n-3)(n-2) (n-1)(n)
h h h h h h h h 1 2 3 4 n-3 n-2 n-1 n
v v v v v v v v 1 2 3 4 n-3 n-2 n-1 n
Given a set of values V = {v1; v2; v3; :::; vn}, the Merkle tree can be computed by generating the set of hashes H = {h1; h2; h3; :::; hn} using a cryptographic function over each element of V , where h = hash(v ) and 1 ≤ i ≤ n. After computing each h ∈ H, we must gen- i i
erate the second level of the tree (H ) by hashing siblings elements, where each element belongs to a single pair. So, h = hash(h1;h2), 1
′ ′ ′ h = hash(h3;h4), and so forth. By doing so, ∣H ∣ = ∣H∣/2, i.e., we reduce the cardinality of the set H to its half. Then, we make H = H . 2 We repeat the process until ∣H∣ = 1, i.e., only one element is left in H. That element is called the root of the Merkle tree. Whenever we have an odd number of elements in the set H, we repeat the last element to always have an even number of elements at any given level. When considering the implementation being audited, the value v is represented by the tuple (index;value). It is also important to mention that the index indicates the item’s location in the tree. To locate the key-value pair, the index is read bit-by-bit from the right-most bit to the left-most bit while traversing the tree from the root downwards. Bit zero means ”follow the edge going to the left”, while bit one means ”follow the edge going to the right”. The main goal of the SMT implementation is to provide inclusion and non-inclusion proofs of identities states into the SMT root. The Smt library contract is used for the state contract (StateV2.sol). The Sparse Merkle Tree is defined to have a maximum depth of 32 levels. Since the first depth is zero, the tree can hold up to 231 leaves.
uint256 public constant MAX_SMT_DEPTH = 32;The implementation considers three node types. The type empty represents a new node that has not been filled with any data yet. The type leaf represents a tree leaf, while the type middle represents non-leaf nodes. The definition of nodes is presented below.
enum NodeType {
EMPTY,
LEAF,
MIDDLE
}The Sparse Merkle Tree data is represented in the struct smtData having the mapping of nodes (position in the Merkle tree and nodes data) and the history of roots. The struct is reproduced below.
struct SmtData {
mapping(uint256 => Node) nodes;
uint256[] rootHistory;
mapping(uint256 => RootEntry) rootEntries;
}The struct Node holds the type of the node (empty, leaf, middle), the left and right children, the index of the node (location in the tree), and the value.
struct Node {
NodeType nodeType;
uint256 childLeft;
uint256 childRight;
uint256 index;
uint256 value;
}The struct RootEntry stores data related to the root of the Sparse Merkle Tree. This struct is used internally, and it has the following fields: replacedByRoot (indicates which root has replaced this one), createdAtTimestamp (indicates the creation time), and createdAtBlock (indicates the creation block). The struct is reproduced below.
struct RootEntry {
uint256 replacedByRoot;
uint256 createdAtTimestamp;
uint256 createdAtBlock;
}The code also has the struct RootInfo used as an interface to external calls. This struct is very similar to RootEntry, with the addition of the following fields root (indicates the root of the tree), replacedAtTimestamp (indicates the time where the tree has changed), replacedAtBlock (indicates the block where the root has changed). The struct is presented below.
struct RootInfo {
uint256 root;
uint256 replacedByRoot;
uint256 createdAtTimestamp;
uint256 replacedAtTimestamp;
uint256 createdAtBlock;
uint256 replacedAtBlock;
}Finally, the contract also uses one struct to hold proof-related data. The struct has the root, existence (indicates if the index exists in the tree), siblings (holds the siblings for the proof, index (index in the tree), value (value stored in the tree), auxExistence (indicates that the searched node does not exist in the tree but the auxiliary node was found instead), auxIndex (contains the index of an auxiliary node), auxValue (contains the value of an auxiliary node). The struct is also reproduced below.
struct Proof {
uint256 root;
bool existence;
uint256[MAX_SMT_DEPTH] siblings;
uint256 index;
uint256 value;
bool auxExistence;
uint256 auxIndex;
uint256 auxValue;
}BinarySearchSmtRootsThe code uses Binary Search to find roots of the stored Sparse Merkle Trees in O(logn). The code can execute the search based on the 2
block.timestamp or the block.number. Thus, the library BinarySearchSmtRoots is applied to the SmtData.
using BinarySearchSmtRoots for SmtData;
function binarySearchUint256( Smt.SmtData storage self, uint256 value, SearchType searchType ) ... returns (uint256) {
if (self.rootHistory.length == 0) { return 0; }
uint256 min = 0;
uint256 max = self.rootHistory.length - 1;
uint256 mid;
uint256 midRoot;
while (min <= max) {
/////////////////////////////////////////////////////////////////////////
// @audit Compute the index in the middle of the array.
/////////////////////////////////////////////////////////////////////////
mid = (max + min) / 2;
midRoot = self.rootHistory[mid];
/////////////////////////////////////////////////////////////////////////
// @audit Define if searching for "block.timestamp" or "block.number".
/////////////////////////////////////////////////////////////////////////
uint256 midValue = fieldSelector( self.rootEntries[midRoot], searchType );
if (midValue == value) {
///////////////////////////////////////////////////////////////////////
// @audit If the elements have been found, start the linear search.
///////////////////////////////////////////////////////////////////////
while (mid < self.rootHistory.length - 1) {
uint256 nextRoot = self.rootHistory[mid + 1];
uint256 nextValue = fieldSelector( self.rootEntries[nextRoot], searchType );
if (nextValue == value) {
////////////////////////////////////////////////////////////////////////////
// @audit If the next element is equal to the actual element, move forward.
////////////////////////////////////////////////////////////////////////////
mid++;
midRoot = nextRoot;
}
else {
////////////////////////////////////////////////////////////////////////////
// @audit Next element is different. Finish the search.
////////////////////////////////////////////////////////////////////////////
return midRoot;
}
}
return midRoot;
}
else if (value > midValue) { min = mid + 1; }
else if (value < midValue && mid > 0) { max = mid - 1; }
else { return 0; }
}In the contract Smt.sol, the Binary Search is called in functions getRootInfoByTime(...) and getRootInfoByBlock(...). The Binary Search is implemented using an interactive approach (instead of a recursive one) followed by a Linear Search to find the last element meeting the search criteria. In the extreme case when a large portion of the elements are added to the sparse Merkle Tree in the same block.timestamp or block.number, the Binary Search can become linear, i.e., the order of complexity can degenerate from O(logn) to 2
number of equal elements meeting the search criteria. The Binary Search with audit comments is shown above.
To reuse the same implementation, the type of the search is specified using the enum SearchType described below.
enum SearchType {
TIMESTAMP,
BLOCK
}The STATEV2_OWNER is the address that deployed the contract StateV2. The role can:
setVerifier(address newVerifierAddr);renounceOwnership(). This leaves the contract without an owner;transferOwnership().The prepared security review is based on the following assumptions:
Poseidon hash library is implemented correctly;verifier of zero-knowledge proof is responsible for checking the validity of the genesis state for a given index;verifier of the zero-knowledge proof is responsible for checking the validity of state transitions from the old state to the new one for a given index;This section was prepared by Nethermind’s Research Team for discussing the identity’s collision probability. Since identities are stored in a sparse Merkle Tree (SMT) having 32 levels, the sparse Merkle Tree can store up to 231 leaves. In this section, we approach this problem using two complementary approaches. Initially, we use formal methods to derive the equation that relates the collision probability to the number of elements stored in the sparse Merkle Tree considering the sparse Merkle Tree’s depth. This is achieved by mapping the collision problem into the classical birthday problem. After that, we approach the collision problem by instantiating sparse Merkle Trees, adding random elements, and measuring the number of collisions according to the number of elements added.
4.6.1 Approach: The birthday problem
We would like to include a note on the likelihood of seeing leaf “collisions” that impede an element being added to the Merkle tree in light of the depth limit parameter of 32. With leaves indexed by 256-bit hashes, we have 2256 different elements to consider, but a maximum of 231 elements that can fit in the last level of the tree. We, therefore, ask: what is the probability of two leaves, generated at random, occupying the same space in the last level of the SMT? (We call this a collision). And how concerning is this probability in ordinary use? Since the SMT allocates leaves in the tree according only to their least significant 31 bits, we can consider leaves ‘ to be 31-bit i
sequences, without loss of generality—thus restricting the total options down to T = 231. Then we can phrase our question as follows:
Consider a set of n leaves {‘1;‘2;:::‘n} which have been chosen uniformly at random. Compute the probability P = P(‘ = ‘ ; i ≠ j) col i j
as a function of n.
This is an instance of a well-known probability problem, the birthday problem. The solution (which can be found via combinatorics as in, for example, https://mathworld.wolfram.com/BirthdayProblem.html), is:
T!
P = 1 − (1) col (T − n)!Tn
Since the factorials above complicate visualizing the equation, the following estimate is commonly used:
P ≈ 1 − e−n(n−1)/2T (2) col
Let us graph this estimate below.

n = 216 = 65536 and P ≈ 98% when n = 217 = 131072. col
4.6.1.1 Asking the inverse question
For security purposes (and for grasping the meaning of the formula above), it might be more meaningful to frame the question inversely:
What is the value of N required in order for the probability P to rise to an appreciable number? col
Fig. 4 above answers our questions. For n = 216 leaves, seeing a collision is likely, at roughly 63% probability. For n = 217 leaves and beyond, a collision is practically guaranteed. The fact that a collision is so likely at 217 leaves may seem counterintuitive, especially since it represents only 0.006% of the maximum number of 231 entries in the SMT. This interesting phenomenon is known as the birthday paradox.
4.6.1.2 Usability concerns
There is a concern about how the application employing the Sparse Merkle Tree will handle collisions. From the contracts, we can see that a collision will cause the corresponding leaf operation to revert. It may depend on the dApp in question whether there is a way to circumvent the collision at the application level. With collisions being a virtual certainty for applications that use over 250,000 users, we believe these remarks are worth considering.
4.6.2 Approach: Study on the number of collisions expected according to the number
of identities added to the tree
In this section, we focus on simulating how the number of collisions in the sparse Merkle Tree will behave as we add new random identities. To study the collision problem, we created software to simulate the collisions whose pseudo-code is explained below.
Input: output_csv_filename;
Output: csv_file;
#define MAX_SMT_DEPTH 32
function simulate( output_csv_filename )
begin
while (true)
begin
file f = open(output_csv_filename,"a");
for expoent in {0,1,2,3, ... ,31}
begin
number_leaves_to_be_added = 1 << exponent;
smt = create_empty_smt( MAX_SMT_DEPTH );
collisions[exponent] = add_random_leaves( smt, number_leaves_to_be_added);
end for
f.append_to_csv_file(collisions);
f.close();
end while
end functionThe code receives the output_csv_filename. The simulator starts an infinite loop. Line 9 opens the csv file for appending data. Line 10 is a for-loop over the variable exponent that will run from 0 to 31. Line 12 defines the number of leaves to be added to the SMT as 2exponent or simply 1 << exponent. Line 13 creates a new SMT. Line 14 adds number_leaves_to_be_added random nodes to the SMT. After each interaction, the function returns the number of collisions, which are then stored in the array collisions. After exponent looping over all the range from 0 up to 31, line 16 appends the collision data to the csv file, and the file is closed to ensure that all data has been saved. Our team has executed 138 interactions for this report, and the most important results are presented now. Fig. 5 shows the probability of collisions as we add identities to the SMT. Even having 231 leaves (2.147 billion leaves), when we try to add 500 million leaves, more than 10% of the requests fail due to a hash clash. At this point, the SMT has less than 450 million identities and almost 1.7 billion empty leaves. When we try to add 1 billion identities, more than 20% of the requests fail due to a hash clash. Thus, the SMT ends with less than 800 million identities stored and more than 1.3 billion empty leaves. Finally, when we try to add 231 leaves, almost 37% of the requests collide.
2^0 - 2^11 2^12 2^13 2^14 2^15 2^16 2^17 2^18 2^19 2^20 2^21
Min Value 0.0000000% 0.0000000% 0.0000000% 0.0000000% 0.0000000% 0.0000000% 0.0000000% 0.0030518% 0.0089645% 0.0199318% 0.0448227% Max Value 0.0000000% 0.0244141% 0.0000000% 0.0061035% 0.0061035% 0.0076294% 0.0083923% 0.0095367% 0.0156403% 0.0294685% 0.0518322% Range 0.0000000% 0.0244141% 0.0000000% 0.0061035% 0.0061035% 0.0076294% 0.0083923% 0.0064850% 0.0066757% 0.0095367% 0.0070095% Standard Deviation 0.0000000% 0.0029177% 0.0000000% 0.0016531% 0.0012088% 0.0014888% 0.0013844% 0.0013716% 0.0013646% 0.0015728% 0.0014185% Confidence Interval (95%) 0.0000000% 0.0004868% 0.0000000% 0.0002758% 0.0002017% 0.0002484% 0.0002310% 0.0002288% 0.0002277% 0.0002624% 0.0002367%
2^22 2^23 2^24 2^25 2^26 2^27 2^28 2^29 2^30 2^31
Min Value 0.0941515% 0.1919389% 0.3855288% 0.7731050% 1.5419349% 3.0573435% 5.9935372% 11.5169361% 21.3030718% 36.7861910% Max Value 0.1018763% 0.1992464% 0.3932714% 0.7800370% 1.5500665% 3.0636482% 6.0016654% 11.5230497% 21.3085684% 36.7893524% Range 0.0077248% 0.0073075% 0.0077426% 0.0069320% 0.0081316% 0.0063047% 0.0081282% 0.0061136% 0.0054966% 0.0031614% Standard Deviation 0.0015326% 0.0014611% 0.0015172% 0.0013932% 0.0015073% 0.0012331% 0.0013214% 0.0011778% 0.0010324% 0.0006518% Confidence Interval (95%) 0.0002557% 0.0002438% 0.0002531% 0.0002324% 0.0002515% 0.0002057% 0.0002205% 0.0001965% 0.0001723% 0.0001088%
Fig. 6 characterizes the results in terms of minimum value, maximum value, range, standard deviation, and confidence interval of 95%. The standard deviation is the degree of dispersion or the scatter of the data points relative to its mean. It tells how the values are spread across the data sample, and it measures the variation of the data points from the mean. The confidence interval is the range of values that you expect your estimate to fall between a certain percentage of the time if you run your experiment again or re-sample the population similarly. The confidence level is the percentage of times you expect to reproduce an estimate between the upper and lower bounds of
the number of requests for adding new identities (leaves). We notice that we have not detected collisions when adding from 20(1) up to 211 (2:048) identities. Thus, this seems to be a safe interval, although our number of runs was not expressive (only 138 runs). So, in order to confirm this behavior, we ran another 1 million simulations considering only the interval 20(1) up to 211 (2:048), which corresponds to 12 million data points. Considering those 12 million data points, we notice only 4,487 collisions.
Figs. 7(a) to 7(n) shows the probability of collisions for different numbers of identities added to the sparse Merkle Tree. As we increase the number of identities added, we also increase the probability of collisions.
Number of collisions when adding identities 2^15 2^16 Number of collisions when adding identities 2^17 2^18 0.0090% 0.0120% 0.0080% 0.0100%
0.0070% s 0.0060% s 0.0080% n n o o i 0.0050% i s s i i 0.0060% l l l 0.0040% l o o C C 0.0030% 0.0040% 0.0020% 0.0020%
0.0010% 0.0000% 0.0000% 0 20 40 60 80 100 120 140 0 20 40 60 80 100 120 140 Simulations Simulations
(a) adding 215 and 216 identities (b) adding 217 and 218 identities
Number of collisions when adding identities 2^19 2^20 Number of collisions when adding identities 2^21 0.035% 0.053% 0.052%
0.030% 0.051%
0.025% s s 0.050% n n o 0.020% o i i 0.049% s s i i l l l l 0.048% o 0.015% o C C 0.047%
0.010% 0.046%
0.005% 0.045%
0.000% 0.044% 0 20 40 60 80 100 120 140 0 20 40 60 80 100 120 140 Simulations Simulations
(c) adding 219 and 220 identities (d) adding 221 identities
Number of collisions when adding identities 2^22 Number of collisions when adding identities 2^23 0.103% 0.200% 0.102% 0.199% 0.101% 0.198%
0.100% s s 0.197% n 0.099% n o o i i 0.196% s s i 0.098% i l l l l 0.195% o o 0.097% C C 0.194%
0.096% 0.193%
0.095% 0.094% 0.192% 0.093% 0.191% 0 20 40 60 80 100 120 140 0 20 40 60 80 100 120 140 Simulations Simulations
(e) adding 222 identities (f) adding 224 identities
Number of collisions when adding identities 2^24 Number of collisions when adding identities 2^25 0.394% 0.781% 0.393% 0.780% 0.392% 0.779% s 0.391% s 0.778% n n o o i 0.390% i 0.777% s s i i l l l 0.389% l 0.776% o o C C 0.388% 0.775% 0.387% 0.774% 0.386% 0.773% 0.385% 0.772% 0 20 40 60 80 100 120 140 0 20 40 60 80 100 120 140 Simulations Simulations
(g) adding 224 identities (h) adding 225 identities
Number of collisions when adding identities 2^26 Number of collisions when adding identities 2^27 1.551% 3.064% 1.550% 3.063%
1.549% 1.548% 3.062% s s n 1.547% n o o 3.061% i i s s i 1.546% i l l l l o o 3.060% 1.545% C C 1.544% 3.059% 1.543% 3.058%
1.542% 1.541% 3.057% 0 20 40 60 80 100 120 140 0 20 40 60 80 100 120 140 Simulations Simulations
(i) adding 226 identities (j) adding 227 identities
Number of collisions when adding identities 2^28 Number of collisions when adding identities 2^29 6.003% 11.524% 6.002% 11.523%
6.001% 11.522%
6.000% s s n n 11.521% 5.999% o o i i s s i 5.998% i 11.520% l l l l o o 5.997% C C 11.519% 5.996% 11.518%
5.995% 11.517%
5.994% 5.993% 11.516% 0 20 40 60 80 100 120 140 0 20 40 60 80 100 120 140 Simulations Simulations
(k) adding 228 identities (l) adding 229 identities
Number of collisions when adding identities 2^30 Number of collisions when adding identities 2^31 36.7900%
21.309% 36.7895%
21.308% 36.7890%
21.307% s
s 36.7885% n
n o
o 21.306% i i s s i 36.7880% i l l l l o 21.305% o C 36.7875%
C 21.304% 36.7870% 21.303% 36.7865% 36.7860%
21.302% 0 20 40 60 80 100 120 140
0 20 40 60 80 100 120 140 Simulations
Simulations
(m) adding 230 identities (n) adding 231 identities
4.6.3 Choosing an appropriate depth limit
The graphs and experiments above clearly show the risks behind setting a depth limit of 32 for the SMT. They also show how quickly we may spot collisions in this scenario. In light of this, what would be an appropriate depth limit to balance security and performance? Let us return to Eq. (2). Assume a protocol to handle n = 220 (i.e, roughly 1 million) identities. What is the probability of collision as a function of the depth limit? The graph below illustrates this.

tree. For a depth limit of 53, the highlighted point shows that the collision probability goes down to 0.0001 (0.01%). For a depth limit of 64, the probability goes down even further to 0.000006%.
Fig. 8 suggests depth limits above 50 achieve much greater security regarding collision—if the SMT is expected to hold a million leaves. There are many more permutations of this analysis, all of which can be treated with equation (2). For reference, we show an example below.
Example: Suppose the protocol has grown to n = 220 million identities (roughly the total number of Ethereum unique addresses as of January 2023). Compute the probability of collision for a depth limit of 64.
With the aforementioned depth limit, we have T = 263 different leaves. Substituting in (2), we get
6 6 63
P ≈ 1 − e−220×10 ×(220×10 −1)/2⋅2 ≈ 0:0026 = 0:26%: col
We notice that the depth limit of 64 still provides reasonable security for this greatly enhanced identity load.
In this section, we introduce a formal specification of a sparse Merkle tree and its operations.
4.7.1 Preliminaries
First, we introduce some basic sets that we will use throughout the exposition of the specification:
We can now define a basic binary tree data structure Node with two kinds of leaf nodes. We will use this data structure to abstractly model the state of a sparse Merkle tree.
Node ∶= Empty ∣ Leaf(i ∶ N;v ∶ UInt256) ∣ Middle(l ∶ Node;r ∶ Node)
Note here that child nodes are directly ’stored’ within the parent nodes, unlike in Merkle Tree implementations where parent nodes contain as members only hashes of their children. This is done both for clarity and ease of reasoning and to better model the intended structure, which Merkle Trees are but one way of implementing.
Next, we introduce several functions and predicates to assist in reasoning about these trees.
nodes ∶ Node → P(Node) nodes(Empty) = {Empty} nodes(Leaf(i;v)) = {Leaf(i;v)} nodes(Middle(l;r)) = {Middle(l;r)} ∪ nodes(l) ∪ nodes(r)
leaves ∶ Node− > P(Node) leaves(n) = {Leaf(i;v)∣Leaf(i;v) ∈ nodes(n)}
nodes returns a set containing every node reachable from the one given, including itself. Importantly reachability is defined here in the directed sense where children are reachable by parents, but not vice versa. leaves is then a filter on this that only returns reachable Leaf nodes.
distance ∶ Node × Node ⇀ N distance(Empty();Empty()) = 0 distance(Leaf(i;v);Leaf(i;v)) = 0 distance(Middle(l;r);n)
∣ n ∈ nodes(l) = 1 + distance(l;n) ∣ n ∈ nodes(r) = 1 + distance(r;n)
∣ otherwise = undefineddistance is a partial function defined if-and-only-if the second node is reachable from the first. It counts the number of edges that must be traversed to get from one to the other.
depth ∶ Node → N depth(Empty()) = 0 depth(Leaf(_;_)) = 0 depth(Middle(left;right)) = 1 + max(depth(left);depth(right))
The depth function provides the distance between a root and its most distant leaf or empty child. A single node is defined as having a depth of 0, and a such limit on depth also tells us how many bits of information from a node’s index can be utilized. It is important to note that while this lines up with the use of the depth parameter in recursive functions, it is slightly misaligned with MAX_SMT_DEPTH. Due to the condition in _pushLeaf, the maximum depth allowed by this definition of a tree is MAX_SMT_DEPTH − 1. The data structure described by Node is, by itself, far too general; no link has yet been made between indices and location in the tree. To fill this gap, we introduce the predicate pathMatchesIndex ⊆ Node × Node × N which has the following definition:
pathMatchesIndex(n;n;_) ⇐⇒ True
pathMatchesIndex(Middle(l;r);n;2x + 1) ⇐⇒ pathMatchesIndex(r;n;x) pathMatchesIndex(Middle(l;r);n;2x) ⇐⇒ pathMatchesIndex(l;n;x)
Given a tree, a Leaf or Empty node, and an index, this predicate models whether the node is in the correct place given the associated index. We can say that a Node represents a sparse Merkle tree if and only if every leaf, l, reachable from the root satisfies pathMatchesIndex(root;l;l:index). Importantly no minimum suffix length of the index is defined here, only that by following it, you will reach the intended node. However, this only works if you start at the root of the tree. Many functions used here recur through the tree, and as such, we need to be able to reason about placement with regard to any arbitrary higher node. For this purpose, we define the sparseMerkleSubtree ⊆ NodeN predicates parameterized by the depth at which it is attached to the full tree:
sparseMerkleSubtree(Empty;_) ⇐⇒ True
sparseMerkleSubtree(Leaf(_;_);_) ⇐⇒ True
sparseMerkleSubtree(left;attachmentDepth + 1) ∧ sparseMerkleSubtree(right;attachmentDepth + 1) ∧
sparseMerkleSubtree(Middle(l;r);attachmentDepth) ⇐⇒ (∀l ∈ leaves(left): l:index & 2attachmentDepth = 0) ∧ (∀l ∈ leaves(right): l:index & 2attachmentDepth ≠ 0)
An attachment depth of 0 means we are treating the given node as the root of the whole tree. Intuitively, the attachment depth determines how long of a suffix of the index to ignore, meaning that we can now reason about proper leaf positioning with regard to any intermediate parent node. In order to properly model the structures constructed by this code we need to assert that there are no extraneous nodes added to the tree. We do this using the minimumSparseMerkleSubtree ⊆ Node × N predicate:
minimumSparseMerkleSubtree(node;attachmentDepth) ⇐⇒ sparseMerkleSubtree(node;attachmentDepth) ∧
∀x ∈ Node: sparseMerkleSubtree(x;attachmentDepth) ∧
∀l ∈ leaves(node): distance(node;l) ≤ distance(x;l)
Here assert that the tree contains only those Middle nodes required to distinguish its current leaves from each other. With this in place, we can finally define a predicate, minimumSparseMerkleTree ⊆ Node, that asserts that a given binary tree describes a valid tree:
minimumSparseMerkleTree(x) ⇐⇒ minimumSparseMerkleSubtree(x;0)
Finally, to reason about the proofs of inclusion and non-inclusion produced by the various getProof::: functions, we define our hash function H and two additional helpers: H and H are two separate hash functions of type UInt256 × UInt256 → UInt256, representing l m
PoseidonUint3L:poseidon with the constant 1 for the third parameter, and PoseidonUint2L:poseidon respectively.
H ∶ Node → UInt256 H(Empty) = 0 H(Leaf(i;v)) = H (i;v) l
H(Middle(l;r)) = Hm(H(l);H(r))
From these two base hash functions, we recursively construct H to produce hashes for our Node type, in line with how the code produces hashes for its Node type. The aforementioned helpers are then defined as follows: hashChain ∶ Node × Node × N ⇀ [UInt256] hashChain(l;l; = [] )
hashChain(Middle(l;r);n;2x + 1) = H(l) ∶ hashChain(r;n;x) hashChain(Middle(l;r);n;2x) = H(r) ∶ hashChain(l;n;x)
hashChain is used to construct the Merkle proofs of inclusion or non-inclusion. Given a start node, a target node, and an index, it traverses the tree along the path defined by the index, recording the hashes of the paths not taken. As such by using the index to determine the layout and starting with the hash of the target node, one can arrive at the hash of the root by repeated application of the hash function.
pad ∶ [UInt256] × N ⇀ [UInt256] pad(xs;len) = ys ⇐⇒ length(ys) = len ∧
Since proofs in this implementation always return a list of length MAX_SMT_DEPTH, we also require the partial function pad to take a list and pad it with zeroes if necessary.
4.7.2 Introduction to Hoare triples and separation logic
Now that we have introduced the abstraction of the state of the module we will use for our specification, we will give a short introduction to the specification format we use. Our functional specification will be written using Hoare triples:
∀x ∈ X: ⊢ {P} C {Q}
Where P and Q are assertions on the machine state, in this case, the state of the EVM, and C is a solidity command, in our case, since we are writing functional specifications for the module’s operations, these will always be individual function calls. Intuitively, this specification means that, for an arbitrary assignment of the logical variable, x ∈ X, in any state satisfying the assertion P, the precondition, if we execute the command C, any terminating, non-faulting execution terminates in a state satisfying Q, the postcondition. In Hoare logic, these assertions are usually written in some flavor of first-order logic ranging over appropriate programs and logical variables. For example:
This assertion is satisfied in any state where the relation y = 2x + 7 holds between the program variables x and y and, if the program variable l has value 1, then x = 3, and consequently, y = 13. However, we will use classical separation logic, an extension of Hoare logic for reasoning about shared, mutable resources. It introduces the separation conjunction, P ∗ Q, pronounced P sep Q. Intuitively, this asserts the ownership of the disjoint resources asserted by P and Q. The separating conjunction has a unit, emp, for which the expected axioms hold: P ⇐⇒ P ∗ emp ⇐⇒ emp ∗ P
We then also introduce cell assertions, E1 ↦ E2, which, in our case, asserts that the cell at the address that E1 evaluates to in storage memory has the value that E2 evaluates to. To enforce that a cell assertion represents ownership of the assertions, the following axiom holds:
by the two cell assertions are not disjoint, they predicate over the same cell in storage memory. Note that _ represents an arbitrary value. Similarly to logical conjunction, ∧, the separating conjunction is also commutative and associative. This allows us to define an iterated separated conjunction: ⊛ P(x) x∈X
This assertion simply represents the separating conjunction of the resources asserted by P(x) for each x ∈ X. Finally, in contrast to
cell assertions recording updates to the storage memory to be "forgotten". Otherwise, if cell assertions were conjuncted together, using the consequence rule of Hoare logic:
be taken by a terminating, non-faulting execution of C to Q′, which in turn must satisfied Q, and therefore, we can infer that ⊢ {P} C {Q} holds. However, since implication does not allow us to forget separated conjuncts, this is no longer a problem. The separation logic also comes with a host of advantages, allowing local, modular, and abstract reasoning. However, an exposition of the details of these properties is outside the scope of this introduction. However, we have now introduced enough of the basics to be able to explain our separation logic specifications for the Sparse Merkle Tree in the following section.
4.7.3 Specifications
We start with a simple spec for _addNode, where we assert that if a hash is currently associated with an Empty node, it can be overwritten with a given node and that the return value is appropriate.
⊢ {self:nodes[H(node)] ↦ Empty()} ret = _addNode(self;node) {self:nodes[H(node)] ↦ node ∧ ret = H(node)}
With that done we can move onto a spec for _pushLeaf. From context within the codebase, we can add some assertions about the inputs: namely that newLeaf and oldLeaf are distinct leaves and that pathNewLeaf and pathOldLeaf are their indices. With these properties assumed we can assert that when _pushLeaf is run, the minimum sparse Merkle subtree with these two leaves and no others are created, parameterized by depth as its attachment depth. Because we need to satisfy the precondition of _addNode in order to be able to add these new nodes we need to assert in the precondition of _pushLeaf that all of the hashes to be written to currently associate with the Empty node. We assign no specific value to MAX_SMT_DEPTH in these specs, but it can be no greater than 257 due to the 256-bit index length, and no less than 2 owing to how the depth restriction in _pushLeaf is formed.
∀afterTree ∈ Node: ⊢ ⎧ self:nodes[H(oldLeaf)] ↦ oldLeaf ∗ ⎫ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⊛ self:nodes[H(n)] ↦ Empty() ∧ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ n∈nodes(afterTree)∖oldLeaf ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ minimumSparseMerkleSubtree(afterTree;depth) ∧ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ leaves(afterTree) = {oldLeaf;newLeaf} ∧ ⎪ ⎪ ⎪ ⎨ ⎬ oldLeaf ≠ newLeaf ∧ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ depth(afterTree) + depth < MAX_SMT_DEPTH ∧ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ′ ⎪ ⎪ ∃v;v : ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ oldLeaf = Leaf(pathOldLeaf;v) ∧ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ′ ⎪ ⎩ newLeaf = Leaf(pathNewLeaf;v ) ⎭ ret = _pushLeaf(self;newLeaf;oldLeaf;depth;pathNewLeaf;pathOldLeaf) ⎧ ⎫ self:nodes[H(n)] ↦ n ∧
⎪ ⊛ ⎪ ⎪ ⎪ n∈nodes(afterTree) ⎨ ⎬ ⎪ ⎪ ⎪ ⎪ ret = H(afterTree)
⎩ ⎭
Next, we introduce the specification for the _addLeaf function. Where before we went from a single leaf to a minimum sparse Merkle subtree with two leaves, we now go from one minimum sparse Merkle subtree to another attaching at the same depth. The block at the end of the precondition states two cases: either the old tree has a leaf with the same index as the new one and it gets replaced, or it does not and the new leaf can coexist alongside all the existing ones as long as doing so doesn’t violate the depth assertions:
∀beforeTree;afterTree ∈ Node: ⊢ ⎧ ⎫ ⊛ self:nodes[H(n)] ↦ n ∗
⎪ ⎪ ⎪ ⎪ ⎪ n∈nodes(beforeTree) ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⊛ self:nodes[H(n)] ↦ Empty ∧ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ n∈nodes(afterTree)∖nodes(beforeTree) ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ minimumSparseMerkleSubtree(beforeTree;depth) ∧ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ minimumSparseMerkleSubtree(afterTree;depth) ∧ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ depth(beforeTree) < MAX_SMT_DEPTH − depth ∧ ⎪ ⎨ ⎬ ⎪ depth(afterTree) < MAX_SMT_DEPTH − depth ∧ ⎪
⎪ ⎛ ∃l ∈ leaves(beforeTree): ⎞ ⎪ ⎪ ⎪ ⎪ ( ) ∨ ⎪ ⎪ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ l:index = newLeaf:index ∧ leaves(afterTree) = {newLeaf} ∪ leaves(beforeTree) ∖ {l} ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ leaves(afterTree) = {newLeaf} ∪ leaves(beforeTree) ∧ ⎟ ⎪ ⎪ ⎪ ⎪ ( ) ⎪ ⎪ ⎪ ⎪ ⎝ ⎠ ⎪ ∀l ∈ leaves(beforeTree): l:index ≠ newLeaf:index
⎩ ⎭ ret = _addLeaf(self;newLeaf;oldLeaf;nodeHash;depth) ⎧ ⎫ ⊛ self:nodes[H(n)] ↦ n ∧
⎪ ⎪ ⎪ ⎪ n∈nodes(afterTree)∪nodes(beforeTree) ⎨ ⎬ ⎪ ⎪ ⎪ ⎪ ret = H(afterTree) ⎩ ⎭
To finish this sequence, we specify the top-level function: add. Much of this will look familiar from _addLeaf with the difference that we’re now working with minimum sparse Merkle trees, not subtrees. Additionally, we specify the change to the rootHistory list and rootEntries. ∀beforeTree;afterTree ∈ Node;rootHistoryLength ∈ N;beforeTreeRootEntry ∈ RootEntry: ⊢ ⎧ ⎫ self:rootHistory:length ↦ rootHistoryLength ∗ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ (self:rootHistory[rootHistoryLength − 1] ↦ H(beforeTree) ∧ rootHistoryLength > 0) ∨ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ( ) ∗ ⎪ ⎪ ⎪ ⎪ (emp ∧ rootHistoryLength = 0) ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ self:rootEntries[H(beforeTree)] ↦ beforeTreeRootEntry ∗ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ self:rootEntries[H(afterTree)] ↦ _ ∗ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ self:nodes[H(n)] ↦ n ∗ ⎪ ⎪ ⊛ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ n∈nodes(beforeTree) ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ self:nodes[H(n)] ↦ Empty ∧ ⎪ ⎪ ⊛ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ n∈nodes(afterTree)∖nodes(beforeTree) ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ minimumSparseMerkleTree(beforeTree) ∧ ⎨ ⎬ ⎪ ⎪ ⎪ minimumSparseMerkleTree(afterTree) ∧ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ depth(beforeTree) < MAX_SMT_DEPTH ∧ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ depth(afterTree) < MAX_SMT_DEPTH ∧ ⎪
⎪ ∃l ∈ leaves(beforeTree): ⎪ ⎪ ⎛ ⎛ ⎞ ⎞ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎜ ⎜ l:index = i ∧ ⎟ ∨ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ ⎝ ⎠ ⎟ ⎪ ⎪ leaves(afterTree) = {Leaf(i;v)} ∪ leaves(beforeTree) ∖ {l} ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ leaves(afterTree) = {Leaf(i;v)} ∪ leaves(beforeTree) ∧ ⎟ ⎪ ⎪ ⎪ ⎪ ( ) ⎪ ⎪ ⎪ ⎪ ⎝ ⎠ ⎪ ∀l ∈ leaves(beforeTree): l:index ≠ i
⎩ ⎭ add(self;i;v) ⎧ ⎫ self:rootHistory:length ↦ rootHistoryLength + 1 ∗ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ (self:rootHistory[rootHistoryLength − 1] ↦ H(beforeTree) ∧ rootHistoryLength > 0) ∨ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ( ) ∗ ⎪ ⎪ ⎪ ⎪ (emp ∧ rootHistoryLength = 0) ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ self:rootHistory[rootHistoryLength] ↦ H(afterTree) ∗ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ (self:rootEntries[H(beforeTree)] ↦ beforeTreeRootEntry ∧ beforeTree = Empty) ∨ ⎪ ⎪ ⎪ ⎪ ⎪ ( ) ∗ ⎨ ⎬ (self:rootEntries[H(beforeTree)] ↦ beforeTreeRootEntryreplacedByRoot = H(afterTree) ∧ beforeTree ≠ Empty)
⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ replacedByRoot = 0; ⎪ ⎪ ⎛ ⎞ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ self:rootEntries[H(afterTree)] ↦ RootEntry ⎜ createdAtTimestamp = #block_timestamp; ⎟ ∗ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎝ ⎠ ⎪ ⎪ createdAtBlock = #block_number ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ self:nodes[H(n)] ↦ n ⎪ ⎪ ⊛ ⎪ ⎪ ⎪ ⎪ ⎪ ⎩ n∈nodes(afterTree)∪nodes(beforeTree) ⎭
Finally, we can move on to the proofs of inclusion and exclusion. Much of the actual work here is done in our definition of the hashChain function, so all that is left is to reason about relevant storage variables and the cases for the return value. We outline each in turn, separated by whether looking for the given index finds the Leaf in question, an Empty, or a different Leaf. With this done the rest of the getProof functions become relatively easy to specify by using this one as a template and bolting on additional logic as to which root is used. ∀tree ∈ Node;rootIndex ∈ N: ⊢ ⎧ ⎫ self:rootHistory[rootIndex] ↦ historicalRoot ∗ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⊛ self:nodes[H(n)] ↦ n ∧ ⎪ ⎪ ⎪ n∈nodes(tree) ⎨ ⎬ ⎪ ⎪ ⎪ ⎪ ⎪ historicalRoot = H(tree) ∧ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ depth(tree) < MAX_SMT_DEPTH ⎩ ⎭ proof = getProofByRoot(self;index;historicalRoot) ⎧ self:rootHistory[rootIndex] ↦ historicalRoot ∗ ⎫ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⊛ self:nodes[H(n)] ↦ n ∧ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ n∈nodes(tree) ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ proof:root = historicalRoot ∧ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ proof:index = index ∧ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ∃n ∈ leaves(tree): ⎪ ⎪ ⎪ ⎪ ⎛ ⎞ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ n:index = index ∧ proof:existence = 1 ∧ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ proof:siblings = pad(hashChain(tree;n;index);MAX_SMT_DEPTH) ∧ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ proof:value = n:value ∧ ∨ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ proof:auxExistence = 0 ∧ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ proof:auxIndex = 0 ∧ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎝ ⎠ ⎪ ⎪ ⎪ ⎪ proof:auxValue = 0 ⎪ ⎪ ⎪ ⎨ ⎬ (∀n ∈ leaves(tree): n:index ≠ index ∧ ¬pathMatchesIndex(tree;n;index)) ∧
⎪ ⎛ ⎞ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎜ proof:existence = 0 ∧ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ∨ ⎪ ⎪ ⎪ ⎪ ⎜ proof:siblings = pad(hashChain(tree;Empty();index);MAX_SMT_DEPTH) ∧ ⎟ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎝ ⎠ ⎪ ⎪ proof:auxExistence = 0 ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ (∀m ∈ leaves(tree): m:index ≠ index) ∧ ⎪ ⎪ ⎛ ⎞ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎜ ∃n ∈ leaves(tree): ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ pathMatchesIndex(tree;n;index) ∧ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ proof:existence = 0 ∧ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎜ proof:siblings = pad(hashChain(tree;n;index);MAX_SMT_DEPTH) ∧ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ proof:auxExistence = 1 ∧ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ ⎟ ⎪ ⎪ ⎪ ⎪ ⎜ proof:auxIndex = n:index ∧ ⎟ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎝ ⎠ ⎪ ⎩ proof:auxValue = n:value ⎭
This section describes each part of the overall audit process. The audit team was divided into groups responsible for the following:
a) Line-by-line inspection of the source code;
b) Manual execution of the algorithm on pen and paper covering all possible code branches;
c) White box testing targeting particular logic;
d) Black box testing.
4.8.1 White-box tests
White box testing involves testing an application with detailed inside information about its source code, architecture, and configuration. It can expose issues such as security vulnerabilities, broken paths, or data flow issues, which black box testing cannot test comprehensively. The white-box tests were divided into specific goals:
a) Validate if every line of code is tested at least once to add a new leaf in the SMT;
b) Improve code auditing by scanning the following functions: add(...), getRoot(...), _addLeaf(...), _pushLeaf(...), _addNode(...), and getNodeHash(...).
4.8.1.1 Methodology
Our methodology consists of two stages:
i) careful inspection of the code, line-by-line, annotating parts of the code that require deeper investigation;
ii) manual code inspection combined with dynamic code analysis during the auditing process. Dynamic analysis is a debugging technique to test and evaluate a program while running, i.e., to apply behavioral analysis on the code for a given input. We extract test case execution traces for monitoring the dynamic interaction. We generate trace files during the execution of the add(...) function and their nested functions (_addLeaf(...), _pushLeaf(...), _addNode(...), getNodeHash(...), and getRoot(...)). These files present the order of the code that is executed during the test cases, such as called functions, variables, and executed branches for a given input. Then, for each test case, we reinspect the code following the captured traces.
4.8.1.2 Statement and Branch Coverage
We applied two White Box Test design techniques: i) statement coverage that is used to verify if every line of code has been executed at least once; and, ii) branch coverage that is used to ensure that each decision condition from every branch has been tested at least once.
Branch Coverage: We executed 4 (four) test cases on the instrumented code to validate all branches when calling smt.add(...) function and to avoid no branch leading to any unexpected behavior. For example, Fig. 5 describes the existent branches in _addLeaf and _pushLeaf functions.
_pushLeaf
_addLeaf
if (depth > MAX_SMT_DEPTH - 2)
if(depth > MAX_SMT_DEPTH)
revert()
revert()
if ((pathNewLeaf >> depth) & 1 == (pathOldLeaf >> depth)
if (node.nodeType == NodeType.EMPTY) & 1)
|--- _addNode(...)
|--- _pushLeaf(...)
else if (node.nodeType == NodeType.LEAF)
|--- if ((pathNewLeaf >> depth) & 1 == 1)
|--- if(node.index == newLeaf.index)
newNodeMiddle
|--- _addNode(...)
|--- else
|--- else
newNodeMiddle
|--- _pushLeaf(...)
|--- return _addNode(newNodeMiddle)
else if (node.nodeType == NodeType.MIDDLE)
if ((pathNewLeaf >> depth) & 1 == 1)
|--- if ((newLeaf.index >> depth) & 1 == 1)
|--- newNodeMiddle
|--- _addLeaf(...)
else
|--- else
|--- newNodeMiddle
|--- _addLeaf(...)
_addNode(newLeaf);
return leafHash
return _addNode(newNodeMiddle);Table 2: Test Cases - Branch Coverage obtained by analyzing execution traces.
Index Binary Branch Coverage 25763 110010010100011 62%
9379 010010010100011 3235 110010100011 1187 010010100011 81%
25763 110010010100011 9379 010010010100011
Results: Every branch of the code to add a new leaf node was executed at least once, except one condition in _addLeaf function related to MAX_SMT_DEPTH (see Fig. 5). The above table summarizes some information about the test cases. We defined different indexes to compute statements and the branch coverage measures. Moreover, Table 2 shows the branch coverage for these test cases considering different values of node. As we can see, the test case to insert four leaf nodes reached 81% of branch coverage. However, four branches are not tested with these test cases: i) When a node already exists with the same index and value; ii) When a node already exists but with a different value; iii) In _addLeaf function when depth > MAX_SMT_DEPTH (see Fig. 5); iv) In _pushLeaf function when depth > MAX_SMT_DEPTH - 2 (see Fig. 5).
We performed the inputs described in Fig 6 to run the branches described in items (i) and (ii) mentioned above. These tests use the (index, value) pairs to run at least once the branches when adding a new leaf node.
leavesToInsert: [ leavesToInsert: [
{ i: 9379, v: 100 }, { i: 9379, v: 100 },
{ i: 9379, v: 100 }, { i: 9379, v: 222 },
] ],Next, we apply tests that fail to test branches when adding a new leaf node process is reverted. We could not test the branch when depth is greater than maximum depth in _addLeaf function. This branch is not reachable. Lastly, to test the branch in _pushLeaf function when depth > MAX_SMT_DEPTH - 2, we performed the first scenario listed in Table 3 when labeled ”Test that fails”.
Statement Coverage: We execute the same 4 (four) test cases described in Table 2 and Fig 6 on the instrumented code to ensure that there is no dead code, unused statements, or missing statements. Result: All lines of code were executed at least once.
In this work, we combine black-box testing with white-box testing. By combining black-box and white-box testing, testers can achieve a comprehensive ”inside-out” inspection of software and increase the coverage of quality aspects and security issues. The black-box tests are discussed in the following subsection.
4.8.2 Black-box tests
Black-box testing is a method of software testing that examines the functionality of an application without peering into its internal structures or workings. Test cases are built around specifications and requirements, i.e., what the application is supposed to do. Test cases derive from external software descriptions, including specifications, requirements, and design parameters. Although the tests are primarily functional, non-functional tests may also be used. The test designer selects valid and invalid inputs and determines the correct output, often with the help of a test oracle or a previous result known to be correct, without any knowledge of the test object’s internal structure.
4.8.2.1 Boundary Testing
We applied a Black Box Test design technique called Boundary Testing. This is a type of test in which tests are performed using boundary values. The goal of this test is to evaluate the maximum depth the tree reaches.
The Maximum Depth. The constant MAX_SMT_DEPTH set to n allows the depth of the tree to reach n-1 levels, i.e., the insertion of a leaf in the n-th level will fail. For this test, we run the add(...) function considering MAX_SMT_DEPTH=32 as defined in the code. Table 3 describes two scenarios: i) Test that fails - Scenario with two indexes where the tree depth reaches 32; and ii) Test that passes - Scenario with two indexes where the tree depth reaches 31.
Table 3: Test Cases for the boundary test
Scenario Index Binary 3459916963 11001110001110100010010010100011
Test that fails 1312433315 01001110001110100010010010100011 1312433315 1001110001110100010010010100011
Test that passes 238691491 0001110001110100010010010100011
4.8.3 Final Remarks
Although the provided test suite achieves 96% and 85% coverage on the Branch and Statement measures, there are some caveats that we should take into account. There is no silver bullet to define an absolute number for test coverage. This number depends on the complexity of the requirements, how critical a given implementation is, etc. Typically, achieving 100% coverage is not necessary because usually there are non-critical methods such as getters. Instead, it is recommended to carefully evaluate snippets not covered by the tests to ensure they are not relevant or hard to test. During the audit, we observed that not all branches were tested by the existent unit tests when inserting leaf nodes, even having coverage reaching 96% (Branch metric) and 85% (Statement metric). The main goal of the tests applied in this section was to ensure that all the code responsible for adding nodes was executed at least once. Consequently, avoiding undesirable behavior during its execution in the production environment. Result: During our code analysis, we observe that the branch in the function _addLeaf(...) that tests if depth > MAX_SMT_DEPTH is not reachable.
The risk rating methodology used by Nethermind Security follows the principles established by the OWASP Foundation. The severity of each finding is determined by two factors: Likelihood and Impact.
Likelihood measures how likely the finding is to be uncovered and exploited by an attacker. This factor will be one of the following values:
When defining the likelihood of a finding, other factors are also considered. These can include but are not limited to motive, opportunity, exploit accessibility, ease of discovery, and ease of exploit.
Impact is a measure of the damage that may be caused if an attacker exploits the finding. This factor will be one of the following values:
When defining the impact of a finding, other factors are also considered. These can include but are not limited to data and state integrity, loss of availability, financial loss, and reputation damage. After defining the likelihood and impact of an issue, the severity is determined according to the table below.
| Impact / Likelihood | Low | Medium | High |
| High | Medium | High | Critical |
| Medium | Low | Medium | High |
| Low | Info / Best Practices | Low | Medium |
| Undetermined | Undetermined | Undetermined | Undetermined |
To address issues that do not fit a High, Medium or Low severity, Nethermind Security also uses three more finding severities: Informational, Best Practices, and Undetermined.
| File | Fix commit | Type | Status |
contracts/StateV2.sol | — | Low | Fixed |
The StateV2 contract inherits from OpenZeppelin’s OwnableUpgradeable contract, which provides a one-step ownership transfer. Transferring ownership in a single step is error-prone and can severely harm the protocol if a mistake happens.
Recommendation
We suggest implementing a two-step process for transferring ownership, such as the propose-accept scheme. Check the Ownable2Step.sol contract from OpenZeppelin.
Resolution
We’ve inherited the StateV2 contract from Ownable2StepUpgradeable instead of OwnableUpgradeable. However, it discovered a design flaw, which may cause issues in future upgrades. The reason is that StateV2 may change or use some new parent contracts in the future, which introduce their state variables. In that way, it may shift down the storage layout. To mitigate that, we’ve introduced a uint256[500] __gap; array as the first state variable in the StateV2 contract, which can be reduced or extended in length to mitigate such cases. Please let us know if there is a better or standard solution for such a case.
Update from Nethermind Security
Fixed in commit hash d9be60d7c92d331058135f4fa124969fb02fdcf3. The private variable __gap is a good solution for ensuring the security of the storage variables’ layout in case of future updates.
Proof.siblings| File | Fix commit | Type | Status |
contracts/lib/Smt.sol | — | Low | Fixed |
The member siblings in the structure Proof allocates MAX_SMT_DEPTH slots. However, since the maximum number of siblings is MAX_SMT_DEPTH-1, the allocated space in Proof.siblings can be MAX_SMT_DEPTH-1. The current struct definition can be seen in the code snippet below.
/**
* @dev Struct of the node proof in the SMT
*/
struct Proof {
uint256 root;
bool existence;
/////////////////////////////////////////////////////////
// @audit A proof will have MAX_SMT_DEPTH - 1 maximum. //
/////////////////////////////////////////////////////////
uint256[MAX_SMT_DEPTH] siblings;
uint256 index;
uint256 value;
bool auxExistence;
uint256 auxIndex;
uint256 auxValue;
}Below we present a test case written in Foundry that proves the issue.
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import "forge-std/Test.sol";
import "forge-std/console.sol";
import "../src/Smt.sol";
/////////////////////////////////////////////////////////////////////
// TESTING ISSUE: "Unnecessary space allocation in Proof.siblings" //
/////////////////////////////////////////////////////////////////////
contract SmtTest is Test {
Smt.SmtData internal smtData;
using Smt for Smt.SmtData;
function add(uint256 i, uint256 v) public {
smtData.add(i, v);
}
function getProof(uint256 id) public view returns (Smt.Proof memory) {
return Smt.getProof(smtData, id);
}
function testMAX_DEPTHProofSiblings() public {
// We add the leaves to the last level 31
// |-----------<31 bits>---------|
// in binary 1111111111111111111111111111111 (1 and 30 ones)
uint256 index = 2147483647;
// in binary 0111111111111111111111111111111 (0 and 30 ones)
uint256 index2 = 1073741823;
add(index, 1);
add(index2, 2);
Smt.Proof memory proof = getProof(index);
// this is the last possible sibling and is non-zero (the hash of leaf at index2)
assert(proof.siblings[30] == Smt.getNodeHash(Smt.Node(Smt.NodeType.LEAF, 0, 0, index2, 2)));
// the last slot is empty, no "Out of bounds array access", which means that this space was allocated but never used
assert(proof.siblings[31] == 0);
}
function testFailMAX_DEPTH() public {
// JUST TO DEMONSTRATE THAT ERROR "Max depth reached" OCCURS CORRECTLY FOR LEVEL 32
// |-----------<32 bits>----------|
// in binary 11111111111111111111111111111111 (1 and 31 ones)
uint256 index = 4294967295;
// in binary 01111111111111111111111111111111 (0 and 31 ones)
uint256 index2 = 2147483647;
add(index, 1);
add(index2, 2);
}
}Recommendation
Review the number of siblings required.
Resolution
The logic of the MAX_SMT_DEPTH constant was changed to coincide with the number of siblings. E.g., if the number MAX_SMT_DEPTH = 32, then the number of siblings is 32 too. Note, the root tree level has zero depth number, the lowest possible level equal to MAX_SMT_DEPTH.
Update from Nethermind Security
After the client update on the MAX_SMT_DEPTH logic, this issue is Fixed since the maximum depth of the tree is MAX_SMT_DEPTH and not MAX_SMT_DEPTH - 1. Therefore the space allocated in Proof.siblings is necessary. The update includes changes in the function _pushLeaf(...) and the loop in the function getProofByRoot(...). The changes are shown below.
function _pushLeaf(...) internal returns (uint256) {
- if (depth > MAX_SMT_DEPTH - 2) {
- revert("Max depth reached");
- }
+ if (depth >= MAX_SMT_DEPTH) {
+ revert("Max depth reached");
+ }
...
}
function getProofByRoot(...)
public
view
onlyExistingRoot(self, historicalRoot)
returns (Proof memory)
{
...
- for (uint256 i = 0; i < MAX_SMT_DEPTH; i++) {...}
+ for (uint256 i = 0; i <= MAX_SMT_DEPTH; i++) {...}
...Both changes allow adding 2ˆMAX_SMT_DEPTH leaves to the tree and proof creation from MAX_SMT_DEPTH nodes.
| File | Fix commit | Type | Status |
contracts/StateV2.sol | — | Info | Fixed |
The comments for functions getGISTProofByTime(...), getGISTProofByBlock(...), getGISTRootInfoByBlock(...), and getGISTRootInfoByTime(...) state that the fetched proof "existed at some block/timestamp or later", which indicates that the proof existed for a root in block/timestamp equal or greater than the one provided. We reproduce one of these comments below.
/**
* @dev Retrieve GIST inclusion or non-inclusion proof for a given identity
* for GIST root existed in some block or later.
* @param id Identity
* @param blockNumber Blockchain block number
* @return The GIST inclusion or non-inclusion proof for the identity
*/
function getGISTProofByBlock(uint256 id, uint256 blockNumber)However, these functions use the binarySearchUint256(...) to select which root will be used. The function binarySearchUint256(...) will return a block/timestamp not greater than the one provided. For instance, if we invoke the function binarySearchUint256(...) with the input parameter 2000, and there are roots for the blocks/timestamps [1000, 1500, 1800, 2010], the function returns the information related to the root at block/timestamp 1800. Below we present a fuzzy test written in Foundry, checking that the function binarySearchUint256(...) returns roots created at a timestamp equal to or lower than the one provided.
function test_BinarySearchNeverReturnsAGreaterValue(uint256[] memory values, uint256 value) public {
// We don't want to test arrays with no values
vm.assume(values.length > 0);
// If all the roots are inserted after the time we are searching, the timestamp returned will be zero
vm.assume(value > values[0]);
// Adding nodes to the tree in different timestamps
for (uint256 i = 0; i < values.length; i++) {
// Increase timestamp before adding a root.
// Modulo operation is used for bounding the value
skip(values[i] % 10000000000);
// Add the node
smt.add(i, i*i);
}
// Avoid errNoFutureAllowed error
value = value % block.timestamp;
// If all the roots are inserted after the time we are searching, the timestamp returned will be zero
vm.assume(value > values[0] % 10000000000);
// Function to test
Smt.RootInfo memory root = smt.getRootInfoByTime(value);
// Ensure returned root has a timestamp lower or equal
assert(root.createdAtTimestamp <= value);
}Recommendation
The development team should clarify this use case and update the comments related to the functions getGISTProofByTime(...), getGISTProofByBlock(...), getGISTRootInfoByBlock(...), and getGISTRootInfoByTime(...). If those comments are correct, the team should update the function binarySearchUint256(...) to return the values stated in those comments.
Resolution
The comments were not correct.
Update from Nethermind Security
Fixed in commit hash 80398a1b46c4108ee9dcccb710486e7a3bc5ec99.
| File | Fix commit | Type | Status |
contracts/lib/Smt.sol | — | Info | Fixed |
The function _addLeaf(...) contains a check for ensuring that leaves with a depth greater than MAX_SMT_DEPTH are not added.
function _addLeaf(...) internal returns (uint256) {
if (depth > MAX_SMT_DEPTH) {
revert("Max depth reached");
}
...
}The maximum amount of levels the tree may have is MAX_SMT_DEPTH, which means that the maximum depth of a node is MAX_SMT_DEPTH 1. However, this check potentially allows nodes with a depth of MAX_SMT_DEPTH to be added. This finding is rated as Info because it is not possible to add leaves at this depth. But it still can create false assumptions. Below we present a test case written in Foundry that proves the issue.
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import "forge-std/Test.sol";
import "forge-std/console.sol";
import "../src/Smt2.sol";
import "../src/Smt.sol";
////////////////////////////////////////////////////////////
// TESTING ISSUE: Nodes with incorrect depth are allowed //
////////////////////////////////////////////////////////////
contract SmtTest2 is Test {
Smt2.SmtData internal smtData;
using Smt2 for Smt2.SmtData;
///////////////////////////////////////////////////////////////////////////////////
// NOTE: Smt2.sol is changed: _pushLeaf() has removed revert check to test this //
///////////////////////////////////////////////////////////////////////////////////
function add(uint256 i, uint256 v) public {
smtData.add(i, v);
}
function testMAX_DEPTHSmt2() public {
// |-----------<32 bits>----------|
// in binary 11111111111111111111111111111111 (1 and 31 ones)
uint256 index = 4294967295;
// in binary 01111111111111111111111111111111 (0 and 31 ones)
uint256 index2 = 2147483647;
// Added with _addLeaf(): 1st level is reached
add(index, 1);
// Added with _pushLeaf(): 32 level reached, because index and index2 share 31 bits and 32nd is different
// _pushLeaf() doesn't revert because of the removed check
add(index2, 2);
////////////////////////////////
// DEMONSTRATION OF THE ISSUE //
////////////////////////////////
// Changed with _addLeaf: this node should not be accessible by _addLeaf(...), but it is
add(index2, 3);
}
}Recommendation
This issue presents inconsistency. Consider changing the condition to be aligned with the rest of the code.
Resolution
The fix applied to the previous note also fixes this. We’ve changed the logic of the MAX_SMT_DEPTH constant, and now it is possible to add leaves at the lowest level of the tree.
Update from Nethermind Security
After the client update on the MAX_SMT_DEPTH logic, this issue is Fixed since the maximum depth of the tree is MAX_SMT_DEPTH and not MAX_SMT_DEPTH - 1. Therefore the check in the function _addLeaf(...) is correct. The update includes changes in the function _pushLeaf(...), and in the loop of the function getProofByRoot(...).
function _pushLeaf(...) internal returns (uint256) {
- if (depth > MAX_SMT_DEPTH - 2) {
- revert("Max depth reached");
- }
+ if (depth >= MAX_SMT_DEPTH) {
+ revert("Max depth reached");
+ }
...
}
function getProofByRoot(...)
public
view
onlyExistingRoot(self, historicalRoot)
returns (Proof memory)
{
...
- for (uint256 i = 0; i < MAX_SMT_DEPTH; i++) {...}
+ for (uint256 i = 0; i <= MAX_SMT_DEPTH; i++) {...}
...Both changes allow adding 2ˆMAX_SMT_DEPTH leaves to the tree and proof creation from MAX_SMT_DEPTH nodes.
| File | Fix commit | Type | Status |
contracts/StateV2.sol | — | Info | Acknowledged |
The contract StateV2 contains an initialize(...) function called during deployment time, and it takes the verifier address as an input parameter, as reproduced below.
function initialize(IVerifier verifierContractAddr) public initializer {
///////////////////////////////////////////////////////////////
// @audit Setting the address of the verifier contract //
///////////////////////////////////////////////////////////////
verifier = verifierContractAddr;
__Ownable_init();
}The verifier contract contains the zero-knowledge verification logic. The owner can change this logic after the contract has been deployed. In case the private key of the owner is compromised, an attacker will be able to alter the logic of verification of the smart contract to add illegitimate states in the sparse Merkle Tree. The function setVerifier(...) is reproduced below.
function setVerifier(address newVerifierAddr) public onlyOwner {
verifier = IVerifier(newVerifierAddr);
}Recommendation
No special action is required. This issue is just highlighting this behavior to users of the protocol.
| File | Fix commit | Type | Status |
contracts/StateV2.sol | — | Info | Acknowledged |
Smart contracts often have owner variables to designate the person with special privileges to modify the smart contract.
Recommendation
This centralization of power needs to be made clear to the users, especially depending on the level of privilege the contract allows to the owner.
| File | Fix commit | Type | Status |
contracts/StateV2.sol | — | Info | Acknowledged |
Users should be aware that the contract can be upgraded at any given time.
Recommendation
Communicate to users the reasons for upgrades beforehand.
getRootHistory(...)| File | Fix commit | Type | Status |
contracts/lib/Smt.sol | — | Best Practices | Fixed |
The function getRootHistory(...) is a view function responsible for returning the history of all the sparse Merkle tree roots stored in the protocol. It receives the startIndex and the length to be returned. The endIndex is computed by adding length to the startIndex. When the endIndex is greater than the array length, the function reverts. The reversion can be avoided by computing the endIndex considering the smallest value between startIndex + length and self.rootHistory.length as presented below.
uint256 endIndex = min(startIndex + length, self.rootHistory.length);By following this approach, this function will never revert due to input values leading to an Out of the bonds exception. The code snippet with audit comments is presented below.
function getRootHistory(SmtData storage self, uint256 startIndex, uint256 length ) ... returns (RootInfo[] memory)
{
...
/////////////////////////////////////////////////////////////////////
// @audit "endIndex" can be computed as:
// "min(startIndex + length, self.rootHistory.length)"
/////////////////////////////////////////////////////////////////////
uint256 endIndex = startIndex + length;
require(endIndex <= self.rootHistory.length, "Out of bounds of root history");
RootInfo[] memory result = new RootInfo[](length);
uint64 j = 0;
for (uint256 i = startIndex; i < endIndex; i++) {
uint256 root = self.rootHistory[i];
result[j] = getRootInfo(self, root);
j++;
}
return result;
}Recommendation
Consider computing the endIndex so that the function does not have an Out of the bonds exception, increasing the user experience. The proposed changes are presented below.
- uint256 endIndex = startIndex + length;
- require(endIndex <= self.rootHistory.length, "Out of bounds of root history");
+ uint256 endIndex = min(startIndex + length, self.rootHistory.length);Resolution
Fixed for both StateV2.getStateInfoHistoryById() and Smt.getRootHistory().
Update from Nethermind Security
Fixed in commit hash ebe466957f4d8af8e2c11ad5249e3ac219b9145d.
external visibility instead of public| File | Fix commit | Type | Status |
contracts/StateV2.sol | — | Best Practices | Fixed |
The functions listed below can have external visibility since they are never called inside the contract. Besides setting the proper visibility, external functions consume less gas than public ones. The functions are listed below.
StateV2.transitState(...)
StateV2.getStateInfoById(...)
StateV2.getStateInfoHistoryLengthById(...)
StateV2.getVerifier()
StateV2.setVerifier()Recommendation
Make the functions above external instead of public.
Update from Nethermind Security
Fixed in commit hash c9c661ef00811b8f1eb9367519d4f230aa1b2842.
| File | Fix commit | Type | Status |
contracts/lib/Smt.sol | — | Best Practices | Fixed |
The code has some variables that have not been initialized because they are expected to be zero. However, Solidity does not guarantee that memory variables are initialized as zero, as shown here.
Recommendation
Always initialize memory variables.
Update from Nethermind Security
Fixed in commit hash 31926bd130ba6494316a57427ff994816e66fefa.
address(0x0)| File | Fix commit | Type | Status |
contracts/StateV2.sol | — | Best Practices | Acknowledged |
The function setVerifier(...) does not check the newVerifierAddr for address(0x0). The code is reproduced below.
function setVerifier(address newVerifierAddr) public onlyOwner {
////////////////////////////////////////////////////////////
// @audit Not checking "newVerifierAddr" for address(0x0)
////////////////////////////////////////////////////////////
verifier = IVerifier(newVerifierAddr);
}Recommendation
Consider checking newVerifierAddr for address(0x0).
Update from Nethermind Security
The issue was fixed in commit hash 5b1d9d14db5836fc6d6d1ce4db9ad9c77b2f9e3f by checking if newVerifierAddr != 0. However, the fix was reverted in commit hash 05af5b4414fcd871972992ddc839d62f4ff37a97 because it allows the owner to prevent any new state change.
_pushLeaf(...)| File | Fix commit | Type | Status |
contracts/lib/Smt.sol | — | Best Practices | Fixed |
The index of a leaf is also the path to that leaf in the tree. The values for the arguments pathNewLeaf and pathOldLeaf in the function _pushLeaf(...) will share the same values as newLeaf.index and oldLeaf.index. These arguments can be removed from the function signature. The code snippet below shows how the same values are used for those arguments.
function _addLeaf(...) internal returns (uint256) {
...
if (node.nodeType == NodeType.EMPTY) {
leafHash = _addNode(self, newLeaf);
} else if (node.nodeType == NodeType.LEAF) {
leafHash = node.index == newLeaf.index
? _addNode(self, newLeaf)
////////////////////////////////////////////////////////////////////////////
//@audit - The values "newLeaf.index" and "node.index" were already accessible
// from the "newLeaf" and the node arguments
///////////////////////////////////////////////////////////////////////////
: _pushLeaf(
self,
newLeaf,
node,
depth,
newLeaf.index,
node.index
);
} ...Recommendation
Remove redundant arguments from the function _pushLeaf(...).
Update from Nethermind Security
Fixed in commit hash 347dd01048110f8da49069835a93a6fe0bd389c0.
| File | Fix commit | Type | Status |
contracts/StateV2.sol | — | Best Practices | Fixed |
The StateV2 contract considers some values *special* and contract behavior can change if these special values are encountered. In the function transitState(...) an user cannot submit a new identity state when it matches any other identity state that has already been submitted. The check is reproduced below.
require(!stateExists(newState), "New state should not exist")The function stateExists(...) checks whether a state exists by using the StateEntry.id value. If the id is not equal to zero, then the state exists. This means an id of zero is treated as an exceptional value. For all practical purposes, it is impossible to have an identity id of zero. However, the function transitState(...) does not prevent this. This issue also applies to the argument newState. When a state is replaced, the struct member replacedBy will contain the newState, which could be zero. This could lead to the StateEntry incorrectly indicating that the state has not been replaced. Again, for all practical purposes, it is impossible to have a newState of zero, but the function transitState(...) does not prevent this.
Recommendation
It is considered a best practice to prevent normal inputs from being treated as special values. Therefore consider sanitizing the input and checking if the newState and the id differ from 0.
Resolution
The issue is partially fixed in commit hash 3245a7563ecc3f8876682b67c965437ce888ca62. The newState is checked for 0 value, but the id is not.
Update from the client
Fixed in commit hash ede2e6b3
| File | Fix commit | Type | Status |
contracts/lib/Smt.sol | — | Best Practices | Fixed |
The Smt.sol contract imports Poseidon.sol as below, which is unnecessary considering that both files are in the same folder.
Recommendation
Update the code as shown below.
- import "../lib/Poseidon.sol";
+ import "./Poseidon.sol";Update from Nethermind Security
Fixed in commit hash a04690649188b71cceddc2ef81fcbec54926b7aa.
abicoder v2 pragma is not needed since version 0.8.0| File | Fix commit | Type | Status |
contracts/* | — | Best Practices | Fixed |
The abicoder v2 is the default version since Solidity 0.8.0, as shown in the solidity documentation.
Recommendation
Remove the abicoder v2 pragma.
Update from Nethermind Security
Fixed in commit hash 278e292d1cd7f6063f5ebeb0ef855d00f51af528.
uint256 instead of uint64| File | Fix commit | Type | Status |
contracts/lib/Smt.sol | — | Best Practices | Fixed |
In the function getRootHistory(...) the variable j is of type uint64. Since the EVM word size is 32 bytes long (aligning with uint256), working with smaller-sized integer types can incur extra operations when converting the value to the desired format.
function getRootHistory(...) public view returns (RootInfo[] memory) {
...
/////////////////////////////////////////////////////////////////
// @audit "uint64" is more expensive than "uint256"
/////////////////////////////////////////////////////////////////
uint64 j = 0;
for (uint256 i = startIndex; i < endIndex; i++) {
uint256 root = self.rootHistory[i];
result[j] = getRootInfo(self, root);
j++;
}
return result;
}Recommendation
As there appears to be no reason for j to be of type uint64, consider changing it to uint256.
Update from Nethermind Security
Fixed in commit hash 278e292d1cd7f6063f5ebeb0ef855d00f51af528.
We have conducted a re-audit on the updated implementation of the Polygon team, as they had to refactor the original implementation by changing the data model and design of the StateV2. As a result, new issues have been identified, which are listed below. The commit hash of the re-audit is b74788b3e7fb71c2b8c858f4aba0b52aa1d36eae.
| File | Fix commit | Type | Status |
contracts/lib/SmtLib.sol | 6ac5bca | Info | Fixed |
During the initialization of _gistData, the first root is assigned a value of 0. However, when retrieving the proof information, we notice inconsistent behavior between the public functions. Some functions, such as getProof(...) and getProofByRoot(...), return the proof for a root value of 0, while others, such as getProofByTime(...) and getProofByBlock(...), revert when the root value is 0. Below, we introduce the function getProofByRoot(...), which returns a proof when encountering a root of 0:
function getProofByRoot(Data storage self, uint256 index, uint256 historicalRoot) public view onlyExistingRoot(self, historicalRoot) returns (Proof memory) {
uint256[] memory siblings = new uint256[](self.maxDepth);
// Solidity does not guarantee that memory vars are zeroed out
for (uint256 i = 0; i < self.maxDepth; i++) {
siblings[i] = 0;
}
///////////////////////////////////////////////////////////
// @audit The proof is returned even on root 0
///////////////////////////////////////////////////////////
Proof memory proof = Proof({
root: historicalRoot,
existence: false,
siblings: siblings,
index: index,
value: 0,
auxExistence: false,
auxIndex: 0,
auxValue: 0
});
uint256 nextNodeHash = historicalRoot;
Node memory node;
for (uint256 i = 0; i <= self.maxDepth; i++) {
node = getNode(self, nextNodeHash);
if (node.nodeType == NodeType.EMPTY) {
break;
} else if (node.nodeType == NodeType.LEAF) {
if (node.index == proof.index) {
proof.existence = true;
proof.value = node.value;
break;
} else {
proof.auxExistence = true;
proof.auxIndex = node.index;
proof.auxValue = node.value;
proof.value = node.value;
break;
}
} else if (node.nodeType == NodeType.MIDDLE) {
if ((proof.index >> i) & 1 == 1) {
nextNodeHash = node.childRight;
proof.siblings[i] = node.childLeft;
} else {
nextNodeHash = node.childLeft;
proof.siblings[i] = node.childRight;
}
} else {
revert("Invalid node type");
}
}
return proof;
}Below we present an example of a function that reverts when encountering a root of zero.
function getProofByBlock(
Data storage self,
uint256 index,
uint256 blockNumber
) external view returns (Proof memory) {
RootEntryInfo memory rootInfo = getRootInfoByBlock(self, blockNumber);
///////////////////////////////////////////////////////////
// @audit Revert on root 0
///////////////////////////////////////////////////////////
require(rootInfo.root != 0, "historical root not found");
return getProofByRoot(self, index, rootInfo.root);
}Recommendation
Ensure consistent behavior among getter functions when providing proof for a root value of 0.
Resolution
Fixed in commit 6ac5bca7fcd2138f639bcf39722107c0b4e37b9a.
calculateBounds(...)| File | Fix commit | Type | Status |
contracts/lib/ArrayUtils.sol | 6ac5bca | Info | Fixed |
In the library ArrayUtils, the function calculateBounds(...) is lacking NatSpec comments for the input parameter limit. Below, we provide the NatSpec comment for the calculateBounds(...) function.
/**
* @dev Calculates bounds for the slice of the array.
* @param arrLength An array length.
* @param start A start index.
* @param length A length of the slice.
///////////////////////////////////////////////////////////
// @audit Missing description of "limit"
///////////////////////////////////////////////////////////
* @return The bounds for the slice of the array.
*/
function calculateBounds(
uint256 arrLength,
uint256 start,
uint256 length,
uint256 limit
) internal pure returns (uint256, uint256) {Recommendation
Please add NatSpec comments for the parameter limit.
Resolution
Fixed in commit 6ac5bca7fcd2138f639bcf39722107c0b4e37b9a.
| File | Fix commit | Type | Status |
contracts/lib/SmtLib.solcontracts/lib/StateLib.sol | 6ac5bca | Best Practices | Fixed |
The __gap field in the Data struct is used to reserve space for future upgrades. It is considered best practice to allocate a round number of slots in the __gap field for ease of memory and reasoning during upgrades. An example of a place for improvement is struct Data:
struct Data {
mapping(uint256 => Node) nodes;
RootEntry[] rootEntries;
mapping(uint256 => uint256[]) rootIndexes; // root => rootEntryIndex[]
uint256 maxDepth;
bool initialized;
///////////////////////////////////////////////////////////
// @audit Slots in __gap should be 45 not 48
///////////////////////////////////////////////////////////
uint256[48] __gap;
}In this case, it is recommended to allocate 45 slots in the __gap field so that the total number of slots used and reserved is a round number. Another example is the struct Data in StateLib, which should have allocated 48 slots.
struct Data {
mapping(uint256 => Entry[]) stateEntries;
mapping(uint256 => mapping(uint256 => uint256[])) stateIndexes;
///////////////////////////////////////////////////////////
// @audit Slots in __gap should be 48 not 50
///////////////////////////////////////////////////////////
uint256[50] __gap;
}Recommendation
Consider keeping the space allocated in __gap as a round number. Document this practice and the reasoning behind the chosen number of slots in the __gap field to ensure clarity and consistency in future upgrades.
Resolution
Fixed in commit 6ac5bca7fcd2138f639bcf39722107c0b4e37b9a.
| File | Fix commit | Type | Status |
test/state/stateV2.test.ts | — | Best Practices | Acknowledged |
The testing suite does not include a scenario where the implementation of the StateV2 is changed to a new one.
Recommendation
Consider improving the testing suite for StateV2.
| File | Fix commit | Type | Status |
contracts/state/StateV2.sol | 6ac5bca | Best Practices | Fixed |
The implementation contract StateV2 serves as the logic code for the proxy contract. However, it is possible for any address to directly initialize the implementation contract. To prevent this, it is advisable to include _disableInitializers(...) in the constructor, as recommended by OpenZeppelin.
Recommendation
Consider including _disableInitializers(...) in the constructor.
Resolution
Fixed in commit 6ac5bca7fcd2138f639bcf39722107c0b4e37b9a.
Software documentation refers to the written or visual information that describes the functionality, architecture, design, and implementation of software. It provides a comprehensive overview of the software system and helps users, developers, and stakeholders understand how the software works, how to use it, and how to maintain it. Software documentation can take different forms, such as user manuals, system manuals, technical specifications, requirements documents, design documents, and code comments. Software documentation is critical in software development, enabling effective communication between developers, testers, users, and other stakeholders. It helps to ensure that everyone involved in the development process has a shared understanding of the software system and its functionality. Moreover, software documentation can improve software maintenance by providing a clear and complete understanding of the software system, making it easier for developers to maintain, modify, and update the software over time. Smart contracts can use various types of software documentation. Some of the most common types include:
These types of documentation are essential for smart contract development and maintenance. They help ensure that the contract is properly designed, implemented, and tested, and they provide a reference for developers who need to modify or maintain the contract in the future.
The Polygon Id team provided two documents to assist the audit process, describing (a) the contract StateV2 and the SMT library; (b) instructions for running the test suite. These documents covered the most common terms used in the source code, explanations for the core business logic and functions flow and guides for running tests. Besides that, the audit team used the Polygon public documentation available at wiki.polygon.technology to gain deeper knowledge about the Polygon Id and understand the interaction between the Polygon Id and the Iden3 protocol. By reading the whole documentation suite, we could get a proper understanding of how the contract StateV2 should operate.
Along this investigation, we could notice that the implementation for leaf node hash calculations differs from the specification. According to the sparse Merkle Tree specification designed by the iden3 team, a leaf node hash is calculated as follows:
///////////////////////////////////////////////////////////////////////////////////
// @audit Code snippet 1: how the hash is defined in the iden3 documentation
///////////////////////////////////////////////////////////////////////////////////
hash(leaf_bit, key, value)However, the function getNodeHash(...) computes the hash as follows:
///////////////////////////////////////////////////////////////////////////////////
// @audit Code snippet 2: how Polygon is computing the hash
///////////////////////////////////////////////////////////////////////////////////
hash(key, value, leaf_bit)After presenting this issue to the Polygon team, we were told that the documentation of the iden3 is not reflecting the implementation and this is the reason they are adopting the code snippet 2 presented above. The Polygon Wiki is a complete source of resources for developers and auditors, and we are satisfied with the documentation provided by the Polygon team. The codebase has sufficient inline comments, helping the audit team to understand the functions flow and to detect some issues. The Polygon Id could benefit from clearly stating each use case, allowing the audit team to ensure that all use cases are perfectly implemented.
The relevant output is presented below.
| 65Tests passed | 0Failed |
The complete test output is in the full report.
As auditors, we recommend that any changes or updates made to the audited codebase undergo a re-audit or security review to address potential vulnerabilities or risks introduced by the modifications. By conducting a re-audit or security review of the modified codebase, you can significantly enhance the overall security of your system and reduce the likelihood of exploitation. However, we do not possess the authority or right to impose obligations or restrictions on our clients regarding codebase updates, modifications, or subsequent audits. Accordingly, the decision to seek a re-audit or security review lies solely with you.
This report is based on the scope of materials and documentation provided by you to Nethermind in order that Nethermind could conduct the security review outlined in 1. Executive Summary and 2. Audited Files. The results set out in this report may not be complete nor inclusive of all vulnerabilities. Nethermind has provided the review and this report on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. This report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on this report in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, Nethermind disclaims any liability in connection with this report, its content, and any related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. Nethermind does not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and Nethermind will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE.
The Leading Engineers of Blockchain Infrastructure