World
State Bridge Upgrade

World changed how identity roots reach other chains: each chain now gets its own update on its own schedule. We reviewed the upgraded state bridge contracts.
report id
0131
category
Identity & Cryptography
language
Solidity
final report
September 8, 2023
lines of code
344
Content

Download audit report

1

Executive Summary

This document presents the security review performed by Nethermind on the State Bridge Contracts Upgrade containing 344 lines of code. The Worldcoin team implemented a significant change in the state bridge mechanism. Instead of pushing the root hash atomically to all chains when inserting identity commitments, they have reorganized the process. Now, distinct tasks handle the data transfer to each supported blockchain independently, without involving the identity manager smart contract, and they do it at various time intervals. Along the audit of this contract, we report 11 points of attention, where 1 is classified as Medium, 1 is classified as Info, and 9 are classified as Best Practices.

Audit assessment
Audit TypeSecurity Review
Initial ReportSep. 6, 2023
Response from ClientSep. 7, 2023
Final ReportSep. 8, 2023
MethodsManual Review, Automated Analysis
Repositoryworld-id-state-bridge
Commit Hash (Audit)9edc22a94d
DocumentationREADME.md
Documentation AssessmentHigh
Test Suite AssessmentHigh
Total findings
11
Fixed
10
Acknowledged
1
Mitigated
0
Unresolved
0

Findings by severity

  • Critical0
  • High0
  • Medium1
  • Low0
  • Informational1
  • Best Practices9

2

Audited Files

#ContractLoCCommentsRatioBlankTotal
1src/PolygonStateBridge.sol3858152.6%22118
2src/OpStateBridge.sol8283101.2%38203
3src/OpWorldID.sol1437264.3%859
4src/PolygonWorldID.sol4569153.3%17131
5src/abstract/WorldIDBridge.sol77104135.1%43224
6src/utils/BytesUtils.sol726995.8%19160
7src/interfaces/IOpStateBridgeTransferOwnership.sol48200.0%113
8src/interfaces/IWorldIDIdentityManager.sol45125.0%110
9src/interfaces/IPolygonWorldID.sol415375.0%221
10src/interfaces/IOpWorldID.sol419475.0%225
Total344467135.8%153964

4

System Overview

No system overview is included in this report.

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 Wrong state variable is set in the function setGasLimitSendRoot(...)

FileFix commitTypeStatus
OpStateBridge.sol—MediumFixed

The OpStateBridge contract allows the owner to customize the gas limit for different methods. The value of _gasLimitSendRoot can be set by calling the function setGasLimitSendRoot(...). However, the current codebase instead sets the value for the wrong variable _gasLimitSetRootHistoryExpiry.

function setGasLimitSendRoot(uint32 _opGasLimit) external onlyOwner {
// @audit Should set _gasLimitSendRoot instead of _gasLimitSetRootHistoryExpiry
_gasLimitSetRootHistoryExpiry = _opGasLimit;

emit SetGasLimitSendRoot(_opGasLimit);
}

Recommendation

In the function setGasLimitSendRoot(...), set the value for _gasLimitSendRoot instead of _gasLimitSetRootHistoryExpiry.

Resolution

Fixed, current state.

6.2 Transaction ordering in L2 may leave _latestRoot in the wrong state after root hash expiration

FileFix commitTypeStatus
WorldIDBridge.sol—InfoAcknowledged

The propagation of latestRoot between L1 and L2 is done via messaging. The message data contains the new root hash but does not include the timestamp indicating the emission time from L1. Depending on the different L1-L2 messaging mechanisms, the ordering of transactions cannot be ensured, and it could be possible that two messages sent from L1 to L2 to propagate root get validated in the reverse order on L2.

This scenario has a limited impact since the user on L2 would just need to specify the root hash that contains its identity. However, there is an edge case when the root hash is not updated and expiration time (ROOT_HISTORY_EXPIRY) is reached for all root hashes. The only valid root hash is the latest one (_latestRoot), which could be the second to last one sent from L1.

function requireValidRoot(uint256 root) internal view {
// The latest root is always valid.
if (root == _latestRoot) {
return;
}

All users registered between these two root hash propagations cannot create valid proofs on L2 until a new root hash is propagated.

Recommendation

Consider sending the timestamp from L1 to ensure the latest root hash is correctly updated.

Resolution

Acknowledged. Transaction ordering doesn’t impact the correct functioning of bridged World IDs. The signup-sequencer is the one that takes care of providing roots against the latest root on the L2, which solves the edge case mentioned above.

6.3 Avoid using magic numbers

FileFix commitTypeStatus
OpStateBridge.sol
PolygonWorldID.sol
PR #106
PR #106
Best PracticesFixed

Enhancing code readability can be achieved by replacing magic numbers with meaningful constants. The code snippet below shows an example:

constructor(
address _worldIDIdentityManager,
address _opWorldIDAddress,
address _crossDomainMessenger
) {
opWorldIDAddress = _opWorldIDAddress;
worldIDAddress = _worldIDIdentityManager;
crossDomainMessengerAddress = _crossDomainMessenger;
// @audit Avoid using magic number
_gasLimitSendRoot = 100000;
_gasLimitSetRootHistoryExpiry = 100000;
_gasLimitTransferOwnership = 100000;
}

Recommendation

Consider replacing these magic numbers with named constants or variables that provide meaningful names and context for these values.

Resolution

Fixed in commits 364826209, 33df6b53

6.4 Inconsistent usage of custom errors

FileFix commitTypeStatus
PolygonStateBridge.sol
PolygonWorldID.sol
PR #108Best PracticesFixed

Within these contract, both require()/revert() and custom errors are employed. Adopting a consistent approach and using only one error-handling method within each file is recommended.

Recommendation

Consider adopting a uniform error-handling method throughout the codebase.

Resolution

Fixed in commit 52f2c77

6.5 Incorrect NatSpec description in _receiveRoot(...) function

FileFix commitTypeStatus
WorldIDBridge.solPR #106Best PracticesFixed

The _receiveRoot(...) function contains incorrect custom NatSpec. It specifies that the function may revert if the caller is not the owner. However, the function does not have this logic.

/// @custom: reverts string If the caller is not the owner.
function _receiveRoot(uint256 newRoot) internal {
[...]
}

Recommendation

Consider correcting the NatSpec documentation to reflect the function’s implementation.

Resolution

Fixed in commit 844da90

6.6 Lack of event emission when updating state variables

FileFix commitTypeStatus
PolygonStateBridge.sol
PolygonWorldID.sol
PR #106
PR #106
Best PracticesFixed

It is best practice to emit an event when changing important state variables. The code snippet below shows an example where the function sets the address for fxRootTunnel, but does not emit an event.

function setFxRootTunnel(address _fxRootTunnel) external virtual override onlyOwner {
require(fxRootTunnel == address(0x0), "FxBaseChildTunnel: ROOT_TUNNEL_ALREADY_SET");
// @audit Should emit event
fxRootTunnel = _fxRootTunnel;
}

Recommendation

Consider emitting a suitable event when updating state variables.

Resolution

Fixed in commits 33df6b53, c3c25679

6.7 Missing input validation in some functions

Some functions do not check for the validity of their input before utilizing them:

  • OpStateBridge.transferOwnershipOp(...) does not check if _owner is different than address(0). Note that a check is implemented in transferOwnership function of CrossDomainOwnable3 contract, but it can be endorsed at the protocol contract level;
  • gas limit setters (setGasLimitSendRoot(...), setGasLimitSetRootHistoryExpiry(...), setGasLimitTransferOwnershipOp(...).. ) does not check for the validity of the gas limit (i.e., whether it differs from 0);
  • PolygonStateBridge constructor function lacks validation for inputs _checkpointManager _fxRoot and _worldIDIdentityManager, allowing them to be set as address(0);
  • PolygonWorldID contract constructor lacks validation of _fxChild address;

Including input validation to enhance code robustness and prevent unexpected errors is a good practice.

Recommendation

We recommend implementing a check for inputs in different functions.

Resolution

Fixed in commits c3c25679, 0c08228

6.8 Optimization of WorldIdBridge

FileFix commitTypeStatus
WorldIDBridge.solPR #106
PR #106
Best PracticesFixed

The treeDepth state variable from the WorldIDBridge abstract contract is never updated. This value is only set within the constructor.

/// @notice Constructs a new instance of the state bridge.
///
/// @param _treeDepth The depth of the identities Merkle tree.
constructor(uint8 _treeDepth) {
if (!SemaphoreTreeDepthValidator.validate(_treeDepth)) {
revert UnsupportedTreeDepth(_treeDepth);
}

treeDepth = _treeDepth;
}

Recommendation

Gas optimization can be done following these steps:

  • change treedepth to an immutable variable (initialization in constructor);
  • change type of getTreeDepth() function to pure;

Resolution

getTreeDepth() needs to remain a view function for the contract to compile. The solidity compiler considers immutable variables to be non-pure because it is possible to initialize them with some state link. Fixed in commits 12d09df, 8e0e5b4

6.9 Remove the testing library from the code base

FileFix commitTypeStatus
WorldIDBridge.solPR #106Best PracticesFixed

The WorldIdBridge abstract contract imports the forge-std console library.

import "forge-std/console.sol";

Recommendation

Consider removing the testing library in the production code base.

Resolution

Fixed in commit 88beb2e

6.10 Remove unused imports

FileFix commitTypeStatus
PolygonWorldID.solPR #106Best PracticesFixed

PolygonWorldID contract has the following imports that are not being used.

import {SemaphoreTreeDepthValidator} from "./utils/SemaphoreTreeDepthValidator.sol";
import {SemaphoreVerifier} from "semaphore/base/SemaphoreVerifier.sol";

Recommendation

Consider removing unused imports from the contract.

Resolution

Fixed in commit 33df6b5

6.11 Typos in the code base

FileFix commitTypeStatus
WorldIDBridge.sol
OpStateBridge.sol
PR #106
PR #106
PR #107
Best PracticesFixed

The code base contains the following typos:

  • The NatSpec documentation from the verifyProof(...) function of the WorldIDBridge contract;
/// @param root The of the Merkle tree
  • The NatSpec documentation from the OpStateBridge contract:;
/// @notice Emitted when the the StateBridge sets the gas limit for SetRootHistoryExpiryt
/// @param _opGasLimit The new opGasLimit for SetRootHistoryExpirytimism

Recommendation

Consider correcting the typos to improve code quality.

Resolution

Fixed in commits d89e337, 399dec2, e986574

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 documentation is presented in README.md. The documentation is sufficient for this audit.

7.3 Code Coverage

The relevant output is presented below.

Test suite
44Tests 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.