Polygon ID
On-chain Identities

Polygon ID added a feature that lets Ethereum accounts, both wallets and smart contracts, own identities. We reviewed the State contract changes and the new contracts for on-chain identities.
report id
0113
category
Identity & Cryptography
language
Solidity
final report
September 13, 2023
lines of code
693
Content

Download audit report

1

Executive Summary

This document outlines the security review conducted by Nethermind for the Polygon ID protocol. Polygon ID is a blockchain-native identity system. It gives the power to build trusted and secure relationships between users and dApps, following the principles of self-sovereign identity and privacy by default.

This assessment focuses on a newly added feature allowing users to create identities managed by Ethereum accounts (EOA and smart contracts). It comprehends changes to the State contract to allow transitions from these identities and a set of contracts that will act as a base for users who want to create on-chain identities.

The audited code comprises 693 lines of code in Solidity with 83.79% of test coverage. The PolygonID team has provided detailed documentation explaining the protocol summary and the newly added feature. It has also communicated to clarify existing doubts and validate our understanding of the technology.

The audit was performed using: (a) manual analysis of the codebase, (b) automated analysis tools, and (c) simulation of the smart contracts.

Audit assessment
Audit TypeSecurity Review
Initial ReportAugust 7, 2023
Final ReportSeptember 13, 2023
MethodsManual Review, Automated Analysis
Repositoryiden3
Commit Hashc62afb0720
Final Hash45eaace3de
DocumentationPolygonID tutorials, iden3 documentation
Documentation AssessmentHigh
Test Suite AssessmentHigh
Total findings
15
Fixed
11
Acknowledged
4
Mitigated
0
Unresolved
0

Findings by severity

  • Critical0
  • High0
  • Medium1
  • Low8
  • Informational1
  • Best Practices5

2

Audited Files

#ContractLoCCommentsRatioBlankTotal
1contracts/state/StateV2.sol24017070.8%47457
2contracts/lib/IdentityBase.sol11110191.0%26238
3contracts/lib/GenesisUtils.sol814049.4%26147
4contracts/lib/OnChainIdentity.sol17911363.1%31323
5contracts/interfaces/IOnchainCredentialStatusResolver.sol2730111.1%461
6contracts/interfaces/IState.sol5570127.3%10135
Total69352475.6%1441361

4

System Overview

This audit consists of two contracts, two interfaces, and two libraries:

4.1 Key Concepts

The protocol defines several key concepts, including Identity Types and Identity State. This subsection provides a summary of these concepts to facilitate the comprehension of the contracts and libraries.

Identity Types - There are two types of Identities:

  • Regular Identity - It is created from roots of three merkle trees (Claim Tree, Revocation Tree, and Roots Tree).
  • Ethereum-controlled Identity - This type of identity uses Ethereum accounts to authenticate and perform state transitions.

Identity State - An Identity State consists of three SMT (Sparse Merkle Trees):

  • Claims Tree - It contains the claims issued by an identity.
  • Revocations Tree - It contains revocation nonces of the submitted claims that were revoked by an identity.
  • Roots Tree - It contains the history of the tree roots from the Claims tree.

When an identity issues a claim, it is added to the Claims Tree. If the Claims Tree Root is changed, it is also added to the Roots Tree. The Revocation Tree is changed when an identity invalidates a claim. The revocation is done by adding the claim revocation nonce to the Revocation Tree. The action of changing Claims and Revocations Trees modifies the identity state, and it must be updated on-chain by executing a state transition. The identity state represents the status of an identity at a specific point in time. The initial state of an identity is known as the Genesis State.

4.2 Audited Contracts

Fig. 2 presents the structural diagram of the contracts. The contract StateV2, which is a part of the Polygon ID’s core component and its main goal is to store information about identities. The contract saves the state for each identity. Basically, it has a SMT and a state variable to store identities with their respective state in a mapping. This SMT works as a GIST (Global Identities State Tree) that register the state of all identities using the protocol. The GIST is stored in the StateV2 contract, and every time a user executes one state transition function, the new state of an identity is added to the GIST. This feature allows users to prove ownership of an Identity by validating that it is included in the GIST without revealing their Genesis ID.

The contract implements 23 public / external functions, and the main functions are presented below:

  • transitState(...) - Changes the state of an identity (i.e., transits to the new state) with ZKP ownership check.
  • transitStateGeneric(...) - Changes the state of an identity under a specific method id ownership check.
  • setDefaultIdType(...) - Only the owner can call this function to set the defaultIdType external wrapper.
  • setVerifier(...) - Only the owner can call it to set ZKP verifier contract address.

The getter functions retrieve several distinct pieces of information, such as the last state info for a given identity, state info for a particular identity, GIST latest root, GIST root history, and GIST inclusion or non-inclusion proof for a given identity by the block number or timestamp.

The contract IdentityBase is a base contract to build OnChain Identity or Issuer Contracts with required public interfaces implemented. OnChainIdentity is a library used by IdentityBase to create identity, manage the three trees (Claims Tree, Revocations Tree, and Roots Tree), add / revoke claims, and execute state transitions by calling the State Contract. It consists of 16 external / public functions, and the main functions are:

  • addClaim(...) and addClaimHash(...) - These functions are used to add a claim.
  • revokeClaim(...) - Revokes a claim using its revocation nonce.
  • transitState(...) - Do the state transition. If at least one of the Identity trees has changed, it updates the Roots Tree if needed, performs the function transitStateGeneric in State Contract, and updates the internal variables.
  • calcIdentityState(...) - Calculates IdentityState by computing the hash of the roots (Claims Tree Root, Revocations Tree Root, and Roots Tree Root).

Finally, the GenesisUtils is a library used to generate ID from an Ethereum address or identity state and also verify it. The library contains functions to calculate on chain ID from an address and to check if an ID is Genesis State.

4.3 Assumptions

The prepared security review basis on the following assumptions:

  • The off-chain code which interacts with the on-chain contracts is safe;
  • The Poseidon hash library is implemented correctly, and it holds properties of hashing function;
  • Circuits used to generate the zero-knowledge proof are correct;
  • The verifier of zero-knowledge proof is responsible for checking the validity of the genesis state for a regular identity;
  • The 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 regular identity;

4.4 Analysis of the Probability of Collision for Identities

This section discusses the collision probability between two Identities. The newly added feature introduces two possible scenarios to discuss: i) Collisions between two On-chain Identities and ii) Collisions between an On-chain Identity and a Regular Identity.

Collisions between two On-chain Identities - On-chain identities are generated in the following way:

genesisState = zeroPadding + ethAddress

genesisId = idType + genesisState + checksum

where, idType - consists of 2 bytes. It represents the identifier of DID method and blockchain network; zeroPadding - 7 zero bytes; ethAddress - This is the Ethereum address of controlling Ethereum account, 20 bytes; checksum - consists of 2 bytes. It represents the control checksum of idType + zeroPadding + ethAddress.

All components presented above (idType, zeroPadding, and checksum) except for ethAddress can have collisions. For this scenario, the mentioned exception makes it impossible to have two identical Identities derived from different Ethereum Addresses.

Collision between an On-chain Identity and a Regular Identity - Identity generation for both, Regular and Ethereum controlled identities, can be specified as:

genesisId = idType + genesisStateTransformation + checksum

The differences arise on the genesisStateTransformation value. For Regular identities, it is generated as: the first 27 bytes of the genesis state, where: genesisState = Hash(ClaimsTreeRoot∣∣RevocationsTreeRoot∣∣RootsTreeRoot)

For Ethereum controlled identities, the genesisStateTransformation value is the concatenation of 7 zero bytes with the 20 bytes of a valid Ethereum Address:

genesisStateTransformation = 7BytesOfZeroPadding + 20BytesOfAValidEthereumAddress

For this analysis, let’s assume that we are able to control the preimage of the hash for the genesisState of Regular identities at will (which is not true). A collision for the bytes of a given Ethereum ID happens with probability 2−8×20 = 2−160. If you have N Ethereum IDs already in the system, this probability scales linearly, i.e. N × 2−160.

This is without accounting for the proof-of-work that has to happen to make the first 7 bytes equal to zero, i.e. 2−7×8 = 2−56. All in all, we get a probability of N × 2−216 for a single of the regular IDs to collide with one of the Ethereum IDs.

From that, we get a binomial distribution for whether one out of M GenesisIDs can collide with one out of N EthereumIDs:

N

P = 1 − (1 − )M 2216

If N = 230 (roughly a trillion ETH IDs), then a probability of collision of one in a billion (roughly P = 2−20) would take roughly 2−20 × 2186 = 2166 attempts in M.

Note that this analysis assumes full control over the preimage of the hash from which the Regular ID is created. This is false for this implementation since the preimage is the hash of the three merkle tree roots, with the added requirement that at least one BJJ public key must be added to the Claims tree.

5

Risk Rating Methodology

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:

  1. High: the issue is trivial to exploit and has no specific conditions that need to be met;
  2. Medium: the issue is moderately complex and may have some conditions that need to be met;
  3. Low: the issue is very complex and requires very specific conditions to be met.

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:

  1. High: the issue can cause significant damage, such as loss of funds or the protocol entering an unrecoverable state;
  2. Medium: the issue can cause moderate damage, such as impacts that only affect a small group of users or only a particular part of the protocol;
  3. Low: the issue can cause little to no damage, such as bugs that are easily recoverable or cause unexpected interactions that cause minor inconveniences.

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 / LikelihoodLowMediumHigh
HighMediumHighCritical
MediumLowMediumHigh
LowInfo / Best PracticesLowMedium
UndeterminedUndeterminedUndeterminedUndetermined

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.

  1. Informational findings do not pose any risk to the application, but they carry some information that the audit team intends to pass to the client formally;
  2. Best Practice findings are used when some piece of code does not conform with smart contract development best practices;
  3. Undetermined findings are used when we cannot predict the impact or likelihood of the issue.

6

Issues

6.1 Unable to set version for a revocations

FileFix commitTypeStatus
OnChainIdentity.sol—MediumAcknowledged

Based on the documentation, an updatable claim can be updated by adding a leaf to the Claim Tree by incrementing the version(32 bits) and changing the claim value part.

Index:
i_0: [ 128 bits ] claim schema
[ 32 bits ] option flags
[3] Subject:
000: A.1 Self
001: invalid
010: A.2.i OtherIden Index
011: A.2.v OtherIden Value
100: B.i Object Index
101: B.v Object Value
[1] Expiration: bool
[1] Updatable: bool
[3] Merklized: data is merklized root is stored in the:
000: none
001: C.i Root Index (root located in i_2)
010: C.v Root Value (root located in v_2)
[24] 0
[ 32 bits ] version (optional?)
[ 61 bits ] 0 - reserved for future use
i_1: [ 248 bits] identity (case b) (optional)
[ 5 bits ] 0
i_2: [ 253 bits] 0
i_3: [ 253 bits] 0
Value:
v_0: [ 64 bits ] revocation nonce
[ 64 bits ] expiration date (optional)
[ 125 bits] 0 - reserved
v_1: [ 248 bits] identity (case c) (optional)
[ 5 bits ] 0
v_2: [ 253 bits] 0
v_3: [ 253 bits] 0

Then, adding a leaf to the Revocation Tree containing the revocation nonce(64 bits) and the highest invalid version(32 bits) (that is, all the claims with that nonce and version equal or lower to the one in the leaf are invalid).

Revocation Tree Leaf:
leaf: [ 64 bits ] revocation nonce
[ 32 bits ] version
[157 bits ] 0

When an updatable claim needs to be revoked completely, without the possibility of updating, the highest version and the revocation nonce should be added to the ReT. But the revokeClaim function takes only revocationNonce as an argument. No version argument is included.

/**
* @dev Revoke claim using it's revocationNonce
* @param revocationNonce - revocation nonce
*/
// @audit based on documentation, missing version argument
function revokeClaim(Identity storage self, uint64 revocationNonce) external {
self.trees.revocationsTree.addLeaf(uint256(revocationNonce), 0);
}

This creates an issue if an identity wants to update a claim:

1. add a new leaf(with increased version and new claim value) to claim tree; 2. add a new leaf(revocation nonce) to revocation tree;

This will revoke the claim completely instead of just updating and revoking the old claim.

Recommendation

Consider adding a version(32 bits) argument to the revokeClaim function as mentioned in the docs.

Resolution

The claim versioning currently exists in the documentation only. There is no version implemented either in the core Golang libraries or in the contracts. Actually, we just put zero bits in place of a version, so it looks like this approach is fine, and a version can be added later as a backward-compatible feature.

6.2 Collision of claims’ indices

FileFix commitTypeStatus
OnChainIdentity.sol—LowAcknowledged

Claims are added to the claims tree in the OnChainIdentity contract. The trees can be initialized with a depth up to a maximum of 40. Depending on the number of claims an issuer needs to publish, this depth may be insufficient, leading to a probability of index collision in the Sparse Merkle Trees (SMTs). For example, if the number of claims inserted in the tree is around 1 million, a tree with a depth 40 has a collision probability of around 60%. If the number of claims rises to approximately 10 million, the collision probability effectively becomes 100%.

Recommendation

Consider raising the maximum permissible tree depth. Also, it would be beneficial to inform users about the necessary tree depth for their specific use case when setting up an on-chain identity contract. This information should be prominently featured in user guides or any related documentation.

Resolution

We are limiting the depth of the trees to 40 as the optimal depth, which balances the collision / ZK-proofgeneration-performance ratio. We’ll consider including it in the documentation.

6.3 IdentityBase may return data based on non-published state

FileFix commitTypeStatus
IdentityBase.sol
OnChainIdentity.sol
—LowFixed

The getter functions in the IdentityBase contract may return data not synchronized with the StateV2 contract. The functions getClaimProof(...), getClaimsTreeRoot(...), getRevocationProof(...), and getRevocationsTreeRoot(...) return data using the newest root of a claim/revocation tree. However, those roots may refer to changes to the tree that were not yet committed to the StateV2 contract with the state transition. This may result in, e.g., generating proof for a claim that was not yet confirmed on the StateV2 contract.

Recommendation

Consider using the self.lastTreeRoots.claimsRoot and self.lastTreeRoots.revocationRoot in the OnChainIdentity library instead of the latest root for returning roots and generating proofs for claims and revocations

Resolution

getClaimProof(...) and getRevocationProof(...) return proofs based on the latest published roots but not the current tree roots. If there is a need to get proof for non-published roots or any roots in the history, users can use getClaimProofByRoot(...) and getRevocationProofByRoot(...) functions. The getClaimsTreeRoot(...) and getRevocationsTreeRoot(...) didn’t change. They return current roots, which may not be published yet.

6.4 IdentityBase may return data not synchronized with StateV2 contract

FileFix commitTypeStatus
IdentityBase.sol
OnChainIdentity.sol
—LowAcknowledged

The getter functions in the IdentityBase contract may return data not synchronized with the StateV2 contract. The getRevocationStatus(...) function in IdentityBase.sol checks if a particular nonce has been revoked, returning an inclusion or non-inclusion proof of the specified nonce in the revocationTree. However, this function does not verify if the data stored in the Identity struct is consistent with the data in the State contract. As indicated in the documentation, state transitions can be executed through Zero-Knowledge Proofs (ZKP) if a Baby Jubjub (BJJ) key has been added to the identity. If a state transition occurs this way, the change may not be reflected in the information stored in the contract using the OnChainIdentity library, leading to stale data being used by getRevocationStatus(...).

Recommendation

Consider ensuring that the latest state saved in the contract using the OnChainIdentity library matches the data in the StateV2 contract to avoid potential data inconsistencies

Resolution

We decided not to introduce any restriction from the Onchain Identity side or the State contract side (at least for now). Yes, this may result in the Onchain Identity state being stale. However, the risk of that is close to zero and still can’t even impact more than one identity, which harmed itself on purpose in this case. The warning of the data inconsistency was added to the documentation here.

6.5 Incorrect documentation about ID creation

FileFix commitTypeStatus
StateV2.sol—LowFixed

There is a misalignment between the documentation and the actual implementation regarding creating an ID for Ethereumcontrolled Identity. According to the documentation, the process for ID creation should be as follows:

idType + zeroPadding + ethAddress + checksum

The documentation gives an example:

idType:         0212 // DID method: PolygonID; Network: Polygon Mumbai
ethAddress: 0x0dcd1bf9a1b36ce34237eeafef220932846bcd82

The corresponding ID creation is presented as:

id: 0212000000000000000dcd1bf9a1b36ce34237eeafef220932846bcd82450a (bytes)
id: 2qCU58EJgrELSJT6EzT27Rw9DhvwamAdbMLpePztYq (base58)

However, the actual implementation in the GenesisUtils.calcOnchainIdFromAddress(...) function uses a different process:

reverse(idType + zeroPadding + ethAddress + reverse(checksum))

Applying the same arguments to this process results in a different ID:

id: 0A4582CD6B84320922EFAFEE3742E36CB3A1F91BCD0D000000000000001202 (bytes)
id: A5tDcNxacVgBQ4yHRvqv1FMR7cqNG74xGDhBWMidaq (base58)

Another issue resides in the documentation’s representation of checksum calculation. The example presents the checksum as:

checksum: 450a // checksum of idType + zeroPadding + ethAddress

However, following the algorithm from the documentation, the checksum should not be reversed, resulting in:

checksum 0a45 // checksum of idType + zeroPadding + ethAddress (actual, non-reverted)

Recommendation

It is recommended to synchronize the implementation of the ID creation algorithm with its documentation. This alignment will help to ensure clarity and accuracy.

Resolution

Client smart contracts expect identifiers in little-endian byte order, so the resulting identifier is reversed, which we’ve fixed in the documentation. The same we’ve done regarding the checksum, we’ve added a note to the docs that the checksum is uint16 sum of all the bytes of idType + zero-padding + ethAddress, but the bytes of the uint16 are in reversed order, e.g., if the sum is 0x0a45 then the checksum is 0x450a. The above will be reflected in the online docs as soon as the changes are processed.

6.6 On-chain ID genesis state can’t follow the specification

FileFix commitTypeStatus
OnChainIdentity.sol—LowFixed

The documentation states that the genesis state of an Ethereum-controlled identity is:

genesisState = zeroPadding + ethAddress

However, the OnChainIdentity library does not provide an option for defining a genesis state. It isn’t possible to set it during initialization, and the first state transition, its value remains unset, defaulting to 0.

Recommendation

Consider allowing for providing a genesis state during initialization and checking if it corresponds with ID.

Resolution

Fixed docs and the code so that the genesis state of Ethereum-controlled identity is always zero, which is the desired behavior.

6.7 State transition security properties differ for ID types

FileFix commitTypeStatus
StateV2.sol—LowFixed

The StateV2 contract allows authorized users of an identity to execute state transitions through the transitState(...) and transitStateGeneric(...) functions. The former requires a zero-knowledge proof of the correctness of the provided data, while the latter validates that the caller is the identity owner. In the transitStateGeneric(...) function, two checks are properly conducted in transitState(...) but not adequately executed:

1. Verifying that the new user state (newUserState) corresponds to the hash of the new claims tree root (newClaimsTreeRoot), the revocation tree root (newRevTreeRoot), and the roots tree root (newRootsTreeRoot); 2. Ensuring that the old user state (oldUserState) and newUserState are distinct. Currently, transitStateGeneric(...) allows oldUserState to be equal to newUserState if oldUserState is the genesis state. This condition usually gets checked by confirming that the new state does not exist. However, if oldUserState is the genesis state, both states are added after the existence check, bypassing the validation;

Recommendation

To maintain the integrity of state transitions, it’s recommended to introduce the following changes to the transitStateGeneric(...) function:

  • Explicitly check that oldUserState != newUserState;
  • Verify that newUserState is the hash of the three tree roots (newClaimsTreeRoot, newRevTreeRoot, newRootsTreeRoot). To achieve this, these tree roots need to be passed as arguments to the function;

Resolution

We’ve fixed the oldUserState != newUserState, a case we missed for the unique state’s restriction for an identity. But there is no reason to check if the state is derived from tree roots. It is not State contract responsibility.

Update from Nethermind Security

Checking if the state is derived from the three roots is one of the properties ensured by the ZKP transition. Documenting the properties ensured by the onChain transitions could be helpful.

Update from the client

The onChain transition properties where documented in this page

6.8 OnChain identities can be left unusable

FileFix commitTypeStatus
OnChainIdentity.sol—LowAcknowledged

PolygonID supports several types of identities. This includes "regular" identities managed by Baby Jubjub (BJJ) keys and Ethereum-controlled identities managed by Ethereum accounts. An Ethereum-controlled identity can gain additional functionality by adding at least one BJJ key as authorized, acting as a hybrid of the two primary types. However, this can cause issues with state transitions.

When a BJJ key is used to transition the identity state, a discrepancy between the latestState in the contract using OnChainIdentity and the last state recorded in the StateV2 contract arises. This discrepancy means that the transitState(...) function in the contract using OnChainIdentity will no longer function correctly, as it relies on the on-chain recorded state being the latest one. The StateV2 contract will then revert upon attempting a state transition as the latest state recorded by the contract controller identity differs from the new state set via the BJJ key.

In summary, once a BJJ key transition has been made, the identity will no longer be able to update its state using the smart contract, leading to a partially operable identity.

Recommendation

Consider either preventing Ethereum-controlled identities from making state transitions using BJJ keys or document this issue thoroughly. It’s crucial to inform users not to perform state transitions with BJJ keys if they use the OnChainIdentity library to manage their identities.

Resolution

Yes, the scenario is feasible. However, we decided not to disable using BJJ keys for Ethereum-controlled identities but rather document this issue and recommend users avoid such scenarios. Plus, always create their onchain-identities as upgradable to handle "disasters".

6.9 bytesToAddress(...) casts to incomplete address

FileFix commitTypeStatus
GenesisUtils.sol—LowFixed

The function bytesToAddress(...) receives bytes and returns its respective address. However, the function does not return the full address.

function bytesToAddress(bytes memory bys) internal pure returns (address addr) {
assembly {
// @audit it's not returning the full address
addr := mload(add(bys, 20))
}
}

function int256ToAddress(uint256 input) internal pure returns (address) {
return bytesToAddress(int256ToBytes(reverse(input)));
}

Proof-of-Concept:

1. Let the address equal to 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4; 2. Now we cast to uint256 and apply reverse(...) function: output = 89045105184058068735626723095753784881446600650024375522886434599973815320576; 3. Then we call the function int256ToAddress(...) with the output value (this function uses bytesToAddress(...); 4. The returned address is 0x0000000000000000000000005b38Da6A701c5685;

Recommendation

Consider reviewing the intended use of this function and checking correctness based on that review.

Resolution

The function is not used by any other component, so it was removed from the repo.

6.10 Incorrect nat-spec documentation

FileFix commitTypeStatus
IdentityBase.sol
OnChainIdentity.sol
—InfoFixed

There are a few incorrectly commented functions:

  • getRootProof(...) and getRootProofByRoot(...) have incorrectly described the return value as "The RevocationsTree inclusion or non-inclusion proof for the claim", which does not match the returned value in both IdentityBase contract and OnChainIdentity library;
  • getLastRevocationsRoot(...) returns revocationsRoot, but the comment states "@return claimsRoot";

Recommendation

Rewrite nat-spec for listed functions.

6.11 Change names of int256ToAddress(...) and int256ToBytes(...)

FileFix commitTypeStatus
GenesisUtils.sol—Best PracticesFixed

The GenesisUtils library incorporates the functions int256ToAddress(...) and int256ToBytes(...). However, these function names can be confusing as they convert a uint256 type variable, not an int256. In Solidity, int256 and uint256 are distinct types. Consequently, the current function names may misleadingly imply that the input value should be of type int256.

Recommendation

To enhance code readability and prevent potential misunderstandings, we recommend renaming int256ToAddress(...) to uint256ToAddress(...) and int256ToBytes(...) to uint256ToBytes(...).

6.12 Checks-effects-interactions pattern is not applied on transitState(...) function

FileFix commitTypeStatus
OnChainIdentity.sol—Best PracticesFixed

The transitState(...) function computes the new state for the Identity and executes a state transition on the State contract. The function makes an external call to the State contract, made before the contract’s storage is updated.

function transitState(Identity storage self) external {
...
// @audit - Execute state transition in the State contract. This will be done through an external call.
// do state transition in State Contract
self.stateContract.transitStateGeneric(
self.id,
self.latestState,
newIdentityState,
self.isOldStateGenesis,
1, // state transition method id: 1 - using ethereum auth
new bytes(0) // empty method params
);

// @audit - Update contract's storage
// update internal state vars
self.latestState = newIdentityState;
...
}

The State contract is upgradeable, and its logic could change in the future in a way that would pass control of the call to the original caller or a different contract. This would open a possibility for a reentrancy attack vector.

Recommendation

It is recommended to apply the checks-effects-interactions pattern to mitigate potential reentrancy attack vectors. The contract’s storage should be updated before making the external call to the State contract.

6.13 Mapping variable name does not match with documentation

FileFix commitTypeStatus
StateV2.sol—Best PracticesFixed

The State contract stores identities and their respective states in _stateData.

StateLib.Data internal _stateData;

According to the documentation, the mapping that stores identities is named identities as described in the text below:

> Hereafter, this identity is represented as a mapping: ID => IdState. This gets published, together with all other identities, inside the identities mapping, which is part of the State contract.

Recommendation

Consider updating the documentation as is defined in the code to increase code comprehension.

Resolution

Fixed in the docs and will be updated once the relevant PR in the docs repo is merged and processed.

6.14 IdentityBase.sol contract can be deployed in its current state

FileFix commitTypeStatus
IdentityBase.sol—Best PracticesFixed

The IdentityBase contract, intended to be inherited by contracts that manage on-chain identities, only provides some of the basic functionalities required for such management. More complex mechanisms, such as state transitions and claim additions, are expected to be implemented by the inheriting contracts. The contract could be denoted as abstract to make this requirement more explicit and promote good programming practices.

Recommendation

Consider designating the IdentityBase contract as an abstract contract to signal that it only provides base functionality and requires further implementation.

6.15 transitStateGeneric(...) calls itself externally

FileFix commitTypeStatus
StateV2.sol—Best PracticesFixed

The function transitStateGeneric(...) currently makes an external call to this.getDefaultIdType(...). In the context of Solidity, this pattern leads to the contract calling itself externally. It’s noteworthy that in this specific instance, such an external call to getDefaultIdType(...) is unnecessary, given that the function’s visibility is set to public.

Recommendation

Avoiding external calls is a best practice. Therefore, consider calling getDefaultIdType(...) without a this keyword.

7

Documentation Evaluation

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:

  • Technical whitepaper: A technical whitepaper is a comprehensive document describing the smart contract’s design and technical details. It includes information about the purpose of the contract, its architecture, its components, and how they interact with each other;
  • User manual: A user manual is a document that provides information about how to use the smart contract. It includes step-by-step instructions on how to perform various tasks and explains the different features and functionalities of the contract;
  • Code documentation: Code documentation is a document that provides details about the code of the smart contract. It includes information about the functions, variables, and classes used in the code, as well as explanations of how they work;
  • API documentation: API documentation is a document that provides information about the API (Application Programming Interface) of the smart contract. It includes details about the methods, parameters, and responses that can be used to interact with the contract;
  • Testing documentation: Testing documentation is a document that provides information about how the smart contract was tested. It includes details about the test cases that were used, the results of the tests, and any issues that were identified during testing;
  • Audit documentation: Audit documentation includes reports, notes, and other materials related to the security audit of the smart contract. This type of documentation is critical in ensuring that the smart contract is secure and free from vulnerabilities.

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.

8

Remarks & Test Suite

The Polygon team has provided extensive documentation on Polygon ID, including developer-friendly documentation:

  • An initial tutorial describing several concepts, such as Identity holder, Issuer, Verifier, off-chain and on-chain verification. This documentation can be found in https://0xpolygonid.github.io/tutorials/.
  • The another one includes in detail core concepts, such as Identity Types, Identity State, and OnChain Identity. This documentation can be accessed in https://docs.iden3.io/getting-started/getting-started/.
  • Their README explains the StateV2 smart contract, how to run tests, and the deployment script.

Use of code comments is present in some files, explaining the goal and behavior of multiple functions. Moreover, the Polygon team was available to address any inquiries or concerns raised by the Nethermind auditors.

9.1 ID creation in the documentation is not updated

File(s): StateV2.sol

ID creation for Ethereum-controlled Identity is not implemented the same way presented in the documentation. More information about it can be found in Issue 8.4.

9.2 Mapping variable name does not match with documentation

File(s): StateV2.sol

In the contract StateV2 there is a mismatch on the state variable that stores identities and their respective state in:

StateLib.Data internal _stateData;

More information about it can be found in Issue 8.13 and the documentation.

Test suite
198Tests passed0Failed

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.