Starknet Foundation
Token Distributor

The Starknet Foundation distributes tokens using Merkle proofs: roots are published on-chain and users claim with proofs from an off-chain service. We reviewed the distributor contract that checks those claims.
report id
0194
category
Token & RWA
language
Cairo
final report
February 22, 2024
lines of code
108
Content

Download audit report

1

Executive Summary

This document outlines the security review conducted by Nethermind Security for the StarkNet Foundation on the Token Distributor Contract containing 108 lines of code. The distributor contract is designed to distribute tokens utilizing Merkle tree verification. A Merkle tree is a binary tree where leaf nodes represent data, internal nodes represent hashed pairs of child nodes, and the root node represents the total hash of the data set. The tree is managed off-chain, with only the root hash being published to the contract by the owner. Multiple roots can be published, each representing the tree’s state at a different point in time.

When users wish to make a claim, they need to query the off-chain service for their claim data, including the amount and proofs for onchain validation then submit it to the distributor contract. The contract uses this data to calculate the Merkle tree root and then compares it with the published roots in storage. If any one of the roots matches, the claim is valid, and the contract sends the token to the user.

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

Audit assessment
Audit TypeSecurity Review
Initial ReportFeb 19, 2024
Final ReportFeb 22, 2024
MethodsManual Review, Automated analysis
Repositorydefispring
Commit Hash5ca2536c6c
Final Commit Hashbe3ca1f2b5
DocumentationREADME.md
Documentation AssessmentHigh
Test Suite AssessmentHigh
Total findings
6
Fixed
4
Acknowledged
2
Mitigated
0
Unresolved
0

Findings by severity

  • Critical0
  • High0
  • Medium0
  • Low0
  • Informational3
  • Best Practices3

2

Audited Files

#ContractLoCCommentsRatioBlankTotal
1src/contract.cairo106109.4%22138
2src/lib.cairo200.0%02
Total108109.3%22140

The class hash of the Distributor contract is 0x006a54af2934978ac59b27b91291d3da634f161fd5f22a2993da425893c44c64.

4

System Overview

The Distributor contract facilitates the distribution of the STRK token to eligible participants through the use of a Merkle tree.

A Merkle tree is a binary tree where leaf nodes represent data, internal nodes represent hashed pairs of child nodes, and the root node represents the total hash of the data set. The tree is managed off-chain, with only the root hash being published to the contract by the owner. Multiple roots can be published, each representing the tree’s state at a different point in time.

When users wish to make a claim, they need to query the off-chain service for their claim data, including the amount and proofs for onchain validation then submit it to the distributor contract. The contract uses this data to calculate the Merkle tree root and then compares it with the published roots in storage. If any one of the roots matches, the claim is valid, and the contract sends the token to the user.

This contract comprises a concise set of functions:

1. claim(amount: u128, proof: Span::<felt252>): This enables users to claim a specified amount of tokens by providing a valid Merkle proof.

2. add_root(new_root: felt252): This is reserved for the contract owner to add a new Merkle root, thereby specifying eligibility for token claims.

3. get_root_for(claimee: ContractAddress, amount: u128, proof: Span::<felt252>): This retrieves the Merkle root associated with a particular user’s claim, along with the specified amount and corresponding Merkle proof.

4. amount_already_claimed(claimee: ContractAddress): This returns the amount of tokens already claimed by a specific user.

5. roots(): This returns the list of all Merkle roots currently registered in the contract.

The contract owner is responsible for adding Merkle roots by calling the add_root(...) function, with each root representing eligibility for token claims for individual users.

Users can claim their tokens using the claim(...) function along with valid Merkle proofs. Upon a successful claim, the allocation_claimed mapping is updated to prevent duplicate claims, ensuring each user can claim tokens only once per Merkle root.

4.1 Assumptions

The prepared security review is based on the following assumptions:

  • The off-chain code generating the root of the Merkle tree is correctly implemented.
  • The Alexandria library accurately implements the Merkle tree.
  • The contract owner always provides enough tokens and doesn’t act maliciously. In other words, the owner is trusted.
  • The STRK token to be distributed is compliant with and conforms to the ERC20 token standard.
  • The amount that users can claim in each round increases monotonically.

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 Hardcoded token address

FileFix commitTypeStatus
contract.cairo—InfoAcknowledged

The $STRK address is currently hardcoded to its address on the Sepolia testnet. This address may differ on the mainnet, which would require manual checks and code changes before deployment.

Recommendation

Consider injecting the $STRK address via the constructor.

Resolution

We have verified that the mainnet address will not differ from the testnet addresses. We want to avoid complicating the constructor to minimize room for error during deployment of the contract.

6.2 Low trust on Alexandria Merkle Tree library

FileFix commitTypeStatus
contract.cairo—InfoAcknowledged

In the current setup, there exists an external dependency originating from the Alexandria library. This particular external dependency has not undergone an audit, which raises concerns about the overall integrity and reliability of the system.

The following code snippet is where the concern arises:

use alexandria_merkle_tree::merkle_tree::{
Hasher, MerkleTree, pedersen::PedersenHasherImpl, MerkleTreeTrait
};

Recommendation

Consider monitoring this library for potential future issues. This can be done by regularly checking updates and changes made to the library. Also, consider conducting an audit of the library to ensure its integrity and reliability.

Resolution

Acknowledged. We will continue monitoring the library for potential future issues.

6.3 Possible hash collision when calculating the hash of leaves

FileFix commitTypeStatus
contract.cairo5f06c14
be3ca1f
InfoFixed

Presently, the leaf of the Merkle tree is computed using the following code snippet:

let leaf = LegacyHash::hash(claimee.into(), amount);
merkle_tree.compute_root(leaf, proof)

The function LegacyHash::hash() preprocesses the input values into felt252 before hashing. Consequently, the output of this function represents the Pedersen hash of two felt252 values. Similarly, the middle node in the Merkle tree also corresponds to the Pedersen hash of two felt252 values. Therefore, in theory, it is conceivable that an attacker could provide claimee as the left middle node and amount as the right middle node, leading to a situation where a valid claim could be made to drain the contract. However, this attack vector is contingent upon two conditions:

  • The value of the right middle node must fit within u128, as it is provided as the input parameter amount;
  • The left middle node corresponds to the caller’s address. While practically improbable, it’s worth noting that in the future, the contract might introduce a function to allow claims on behalf of others;

Recommendation

Consider avoiding using leaf values that are two felt252 prior to hashing or using a different hashing function other than Pedersen for hashing leaves.

Resolution

Fixed in commit 5f06c147b42daf3685d3cb9a5f58c67edc757998 on branch audit-fixes by hashing leaves twice:

leaf = LegacyHash::hash(LegacyHash::hash(claimee.into(), amount), 1);

Update from Nethermind Security

Hashing has changed, but the test data has not been updated. As a result, the test cases are failing.

Update from the client

Fixed in commit be3ca1f2b55e1de94399c29da854adb30184bebc on branch audit-fixes by using Poseidon for hashing the leaves.

6.4 Maintainable imports rather single line for every imports

FileFix commitTypeStatus
contract.cairoc91d05fBest PracticesFixed

In the current coding style of the contract, individual external libraries are imported one by one, each on a single line. This approach, while functional, does not align with best coding practices. It is generally advised to consolidate these imports into a single line, where possible, to improve the readability and maintainability of the code.

To illustrate, here is a snapshot of how the external libraries are currently imported into the contract:

use openzeppelin::access::ownable::ownable::OwnableComponent::InternalTrait;
use openzeppelin::access::ownable::ownable::OwnableComponent;

Recommendation

Instead of having multiple lines for each import, it would be more advantageous and in line with best practices to group them into a single line. This would not only make the code cleaner but also easier to manage and maintain.

The following is an example of how the imports can be grouped:

use openzeppelin::access::ownable::ownable::{OwnableComponent::InternalTrait,OwnableComponent}; // @audit - Best Practice

Resolution

Fixed in commit c91d05feb3b5b7ca06bce3593144021bac2ebad9on branch audit-fixes.

6.5 Unchecked return value for token transfer

FileFix commitTypeStatus
contract.cairoa20d0beBest PracticesFixed

It is usually good to check the return value unless one is certain the given token will revert in the event of a failure. In this instance, the $STRK token is currently set to the testnet address, and the code can also be upgraded in the future.

token.transfer(claimee, u256 { high: 0, low: left_to_claim });

Recommendation

Consider checking the return value of the token transfer call.

Resolution

Fixed in commit a20d0be7dc4ab5441770c3cd9a190a9444f1bb3f on branch audit-fixes

6.6 Use of Poisedon hashing instead of Pedersen

FileFix commitTypeStatus
contract.cairo5f06c14Best PracticesFixed

The current hashing technique implemented in this contract is Pedersen hashing. Pedersen hashing, while effective in certain use cases, can be resource-intensive and may not always be the optimal choice. It is recommended to switch to Poseidon hashing, a different hashing algorithm that is known to be significantly less costly in terms of computational resources. This shift in technique can potentially improve the overall efficiency of the contract.

Recommendation

It is recommended to use Poseidon hashing as it is much more gas-efficient compared to Pedersen hashing.

Resolution

Fixed in commit 5f06c147b42daf3685d3cb9a5f58c67edc757998 on branch audit-fixes

Update from Nethermind Security

Commit 5f06c147 changed the hashing of both leaves and middle nodes to Poseidon in the backend side. However, on the contract side, only middle nodes are calculated using Poseidon, while leaves are still calculated using Pedersen (Legacy::hash() uses Pedersen as can be seen here).

Update from the client

Acknowledged. We will stick with Pedersen hashing for the tree because the backend is already stabilized, but use Poseidon for the leaves.

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 StarkNet Foundation has provided documentation about the distributor contract in the codebase comments and through the README file in the repository. The provided documentation is sufficient for the audit.

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