Halborn Logo

BitsCrunch Protocol - bitsCrunch


Prepared by:

Halborn Logo

HALBORN

Last Updated 08/28/2024

Date of Engagement by: August 7th, 2024 - August 21st, 2024

Summary

100% of all REPORTED Findings have been addressed

All findings

11

Critical

0

High

0

Medium

0

Low

1

Informational

10


1. Introduction

BitsCrunch engaged Halborn to conduct a security assessment on their smart contracts beginning on 08-07-2024 and ending on 08-21-2024. The security assessment was scoped to the smart contracts provided in the https://github.com/bitscrunch-protocol/smartcontracts GitHub repository. Commit hashes and further details can be found in the Scope section of this report. The BitsCrunch Protocol codebase in scope is a set of smart contracts on the Polygon network focused on decentralized data analytics & forensics.

2. Assessment Summary

Halborn was provided 2 weeks for the engagement and assigned 1 full-time security engineer to review the security of the smart contracts in scope. The engineer is a blockchain and smart contract security expert with advanced penetration testing and smart contract hacking skills, and deep knowledge of multiple blockchain protocols.

The purpose of the assessment is to:

    • Identify potential security issues within the smart contracts.

    • Ensure that smart contract functionality operates as intended.

In summary, Halborn identified some improvements to reduce the likelihood and impact of risks, which were mostly addressed by the BitsCrunch team. The main identified issues were:

    • Outdated compiler version.

    • Misleading NATSPEC comments.

    • Non-reentrant modifier ordering.

3. Test Approach and Methodology

Halborn performed a combination of manual review of the code and automated security testing to balance efficiency, timeliness, practicality, and accuracy in regard to the scope of this assessment. While manual testing is recommended to uncover flaws in logic, process, and implementation; automated testing techniques help enhance coverage of smart contracts and can quickly identify items that do not follow security best practices.

The following phases and associated tools were used throughout the term of the assessment:

    • Research into architecture, purpose and use of the platform.

    • Smart contract manual code review and walkthrough to identify any logic issue.

    • Thorough assessment of safety and usage of critical Solidity variables and functions in scope that could led to arithmetic related vulnerabilities.

    • Local testing with custom scripts (Foundry).

    • Fork testing against main networks (Foundry).

    • Static analysis of security for scoped contract, and imported functions (Slither).

3.1 Out-of-scope

    • External libraries and financial-related attacks.

    • New features/implementations after/within the remediation commit IDs.

    • Changes that occur outside of the scope of PRs.

4. RISK METHODOLOGY

Every vulnerability and issue observed by Halborn is ranked based on two sets of Metrics and a Severity Coefficient. This system is inspired by the industry standard Common Vulnerability Scoring System.
The two Metric sets are: Exploitability and Impact. Exploitability captures the ease and technical means by which vulnerabilities can be exploited and Impact describes the consequences of a successful exploit.
The Severity Coefficients is designed to further refine the accuracy of the ranking with two factors: Reversibility and Scope. These capture the impact of the vulnerability on the environment as well as the number of users and smart contracts affected.
The final score is a value between 0-10 rounded up to 1 decimal place and 10 corresponding to the highest security risk. This provides an objective and accurate rating of the severity of security vulnerabilities in smart contracts.
The system is designed to assist in identifying and prioritizing vulnerabilities based on their level of risk to address the most critical issues in a timely manner.

4.1 EXPLOITABILITY

Attack Origin (AO):
Captures whether the attack requires compromising a specific account.
Attack Cost (AC):
Captures the cost of exploiting the vulnerability incurred by the attacker relative to sending a single transaction on the relevant blockchain. Includes but is not limited to financial and computational cost.
Attack Complexity (AX):
Describes the conditions beyond the attacker’s control that must exist in order to exploit the vulnerability. Includes but is not limited to macro situation, available third-party liquidity and regulatory challenges.
Metrics:
EXPLOITABILIY METRIC (mem_e)METRIC VALUENUMERICAL VALUE
Attack Origin (AO)Arbitrary (AO:A)
Specific (AO:S)
1
0.2
Attack Cost (AC)Low (AC:L)
Medium (AC:M)
High (AC:H)
1
0.67
0.33
Attack Complexity (AX)Low (AX:L)
Medium (AX:M)
High (AX:H)
1
0.67
0.33
Exploitability EE is calculated using the following formula:

E=meE = \prod m_e

4.2 IMPACT

Confidentiality (C):
Measures the impact to the confidentiality of the information resources managed by the contract due to a successfully exploited vulnerability. Confidentiality refers to limiting access to authorized users only.
Integrity (I):
Measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of data stored and/or processed on-chain. Integrity impact directly affecting Deposit or Yield records is excluded.
Availability (A):
Measures the impact to the availability of the impacted component resulting from a successfully exploited vulnerability. This metric refers to smart contract features and functionality, not state. Availability impact directly affecting Deposit or Yield is excluded.
Deposit (D):
Measures the impact to the deposits made to the contract by either users or owners.
Yield (Y):
Measures the impact to the yield generated by the contract for either users or owners.
Metrics:
IMPACT METRIC (mIm_I)METRIC VALUENUMERICAL VALUE
Confidentiality (C)None (I:N)
Low (I:L)
Medium (I:M)
High (I:H)
Critical (I:C)
0
0.25
0.5
0.75
1
Integrity (I)None (I:N)
Low (I:L)
Medium (I:M)
High (I:H)
Critical (I:C)
0
0.25
0.5
0.75
1
Availability (A)None (A:N)
Low (A:L)
Medium (A:M)
High (A:H)
Critical (A:C)
0
0.25
0.5
0.75
1
Deposit (D)None (D:N)
Low (D:L)
Medium (D:M)
High (D:H)
Critical (D:C)
0
0.25
0.5
0.75
1
Yield (Y)None (Y:N)
Low (Y:L)
Medium (Y:M)
High (Y:H)
Critical (Y:C)
0
0.25
0.5
0.75
1
Impact II is calculated using the following formula:

I=max(mI)+mImax(mI)4I = max(m_I) + \frac{\sum{m_I} - max(m_I)}{4}

4.3 SEVERITY COEFFICIENT

Reversibility (R):
Describes the share of the exploited vulnerability effects that can be reversed. For upgradeable contracts, assume the contract private key is available.
Scope (S):
Captures whether a vulnerability in one vulnerable contract impacts resources in other contracts.
Metrics:
SEVERITY COEFFICIENT (CC)COEFFICIENT VALUENUMERICAL VALUE
Reversibility (rr)None (R:N)
Partial (R:P)
Full (R:F)
1
0.5
0.25
Scope (ss)Changed (S:C)
Unchanged (S:U)
1.25
1
Severity Coefficient CC is obtained by the following product:

C=rsC = rs

The Vulnerability Severity Score SS is obtained by:

S=min(10,EIC10)S = min(10, EIC * 10)

The score is rounded up to 1 decimal places.
SeverityScore Value Range
Critical9 - 10
High7 - 8.9
Medium4.5 - 6.9
Low2 - 4.4
Informational0 - 1.9

5. SCOPE

Files and Repository
(a) Repository: smartcontracts
(b) Assessed Commit ID: 962e400
(c) Items in scope:
  • contracts/Contributor/MultiTierStaking/ContributorMultiTierStaking.sol
  • contracts/Bitscrunch/Customer/Billing.sol
  • contracts/Operator/Staking/Staking.sol
Out-of-Scope:
Remediation Commit ID:
Out-of-Scope: New features/implementations after the remediation commit IDs.

6. Assessment Summary & Findings Overview

Critical

0

High

0

Medium

0

Low

1

Informational

10

Security analysisRisk levelRemediation Date
Outdated compiler versionLowNot Applicable - 08/27/2024
Misleading NATSPEC commentsInformationalSolved - 08/27/2024
Non-reentrant modifier orderingInformationalSolved - 08/27/2024
Dispensable gas fees from use of revert strings over custom errorsInformationalAcknowledged - 08/27/2024
Dispensable gas fees from unoptimized loopsInformationalAcknowledged - 08/27/2024
Missing checks for address(0) on initializationInformationalSolved - 08/27/2024
Unused importsInformationalSolved - 08/27/2024
Missing lock period threshold verificationInformationalAcknowledged - 08/27/2024
Inconsistent use of uint alias instead of uint256InformationalSolved - 08/27/2024
Single step ownership transfer risks DOS for privileged functionsInformationalAcknowledged - 08/27/2024
Check-effects-interactions pattern not followedInformationalAcknowledged - 08/27/2024

7. Findings & Tech Details

7.1 Outdated compiler version

// Low

Description

It was identified that the contracts under scope are using solidity compiler version 0.8.18, hence, outdated, considering the current Solidity compiler version is 0.8.26. Known issues with the compiler version 0.8.18 include:

  • VerbatimInvalidDeduplication

  • FullInlinerNonExpressionSplitArgumentEvaluationOrder

  • MissingSideEffectsOnSelectorAccess

For more reference, see https://docs.soliditylang.org/en/latest/bugs.html

BVSS
Recommendation

Whenever possible, it is recommended to use the latest released version of Solidity, as specified in the official Solidity documentation: https://docs.soliditylang.org/en/latest/installing-solidity.html#versioning

Remediation

NOT APPLICABLE: Since files in scope are an upgraded version of previous contracts deployed with the compiler 0.8.18, these finding is not applicable as new deployments for upgradeable contracts are recommended to keep the compiler version from the original deployment.

7.2 Misleading NATSPEC comments

// Informational

Description

In the updatePlan function of the ContributorMultiTierStaking contract, the NATSPEC comment is misleading. The comment states that the function is for deactivating a plan, but the function actually updates the plan, from an active to an inactive state and vice versa.

/**
* @dev Deactivate the plan.
* @param _planId is the id of the plan to deactivate.
*/
Score
Impact:
Likelihood:
Recommendation

Update the NATSPEC comment to reflect the actual functionality of the function.

Remediation

SOLVED: The BitsCrunch team solved this finding in commit 64e161677096dedd26cf25b65f4fa2ce166c8c6d by following the mentioned recommendation.

Remediation Hash
References

7.3 Non-reentrant modifier ordering

// Informational

Description

In Solidity, if a function has multiple modifiers, they are executed in the order specified. If checks or logic of modifiers depend on other modifiers, this has to be considered in their ordering.

Several functions of the contracts in scope have multiple modifiers, with one of them being nonReentrant which prevents reentrancy behavior on the functions. Ideally, the nonReentrant modifier should be the first one to prevent even the execution of other modifiers in case of reentrancy behavior.

While there is currently no obvious vulnerability with nonReentrant being the last modifier in the list, placing it first ensures that all other modifiers are executed only if the call is non-reentrant. This is a safer practice and can prevent potential issues in future updates or unforeseen scenarios.

BVSS
Recommendation

Switch modifier order to consistently place the nonReentrant modifier as the first one to run so that all other modifiers are executed only if the call is non-reentrant.

Remediation

SOLVED: The BitsCrunch team solved this finding in commit fa7db913cc3a9d01e535e5e3c530d7b8848b9ab9 by following the mentioned recommendation.

Remediation Hash
References

7.4 Dispensable gas fees from use of revert strings over custom errors

// Informational

Description

Throughout the files in scope, there are several instances of use of revert strings over custom errors.

In Solidity development, replacing hard-coded revert message strings with the Error() syntax is an optimization strategy that can significantly reduce gas costs. Hard-coded strings, stored on the blockchain, increase the size and cost of deploying and executing contracts.

The Error() syntax allows for the definition of reusable, parameterized custom errors, leading to a more efficient use of storage and reduced gas consumption. This approach not only optimizes gas usage during deployment and interaction with the contract but also enhances code maintainability and readability by providing clearer, context-specific error information.

Score
Impact:
Likelihood:
Recommendation

Consider replacing all revert strings with custom errors. For example:

error ConditionNotMet();

if (!condition) revert ConditionNotMet();

For more reference, see here.

Remediation

ACKNOWLEDGED: The BitsCrunch team made a business decision to acknowledge this finding and not alter the contracts. It will be planned for future upgrades.

7.5 Dispensable gas fees from unoptimized loops

// Informational

Description

Throughout the code in scope, there are several instances of unoptimized for loop declarations that may incur in higher gas costs than necessary.

Score
Impact:
Likelihood:
Recommendation

Optimize the for loop declarations to reduce gas costs. Best practices include:

  • The non-redundant initialization of the iterator with a default value (declaring simply i is equivalent to i = 0 but more gas efficient),

  • The use of the pre-increment operator (inside an unchecked block if using Solidity >=0.8.0 and <= 0.8.21 :unchecked {++i} , or simply ++i if compiling with Solidity >=0.8.22).

Additionally, when reading from storage variables, it is recommended to reduce gas costs significantly by caching the array to read locally and iterate over it to avoid reading from storage on every iteration. Moreover, if there are several loops in the same function, the i variable can be re-used, to be able to set the value from non-zero to zero and reduce gas costs without additional variable declaration. For example:

uint256[] memory arrayInMemory = arrayInStorage;

uint256 i;
for (; i < arrayInMemory.length ;) {
  // code logic
  unchecked { ++i; }
}

delete i;

uint256[] memory arrayInMemory2 = arrayInStorage2;

for (; i < arrayInMemory2.length ;) {
  // code logic
  unchecked { ++i; }
}
Remediation

ACKNOWLEDGED: The BitsCrunch team made a business decision to acknowledge this finding and not alter the contracts.

References

7.6 Missing checks for address(0) on initialization

// Informational

Description

Throughout the code in scope, there are several instances where the contracts do not check for the address(0) when initializing the upgradeable contracts in scope. This can lead to an incorrect deployment state of contracts, where an improper initialization may require redeployment of the contracts.

Score
Impact:
Likelihood:
Recommendation

Add a check for the address(0) when initializing variables to ensure proper deployment and initialization of the contracts.

Remediation

SOLVED: The BitsCrunch team solved this finding in commit 64e161677096dedd26cf25b65f4fa2ce166c8c6d by following the mentioned recommendation.

Remediation Hash
References

7.7 Unused imports

// Informational

Description

Throughout the code in scope, there are several instances of unused imports that can be removed to improve code readability and maintainability. The following unused imports were identified:

import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; (src/Bitscrunch/Payments/Storage.sol#4)
import {MathUtils} from "../../Utils/MathUtils.sol"; (src/Contributor/RewardManager/RewardManager.sol#8)
import { IOperator } from "../../Operator/IOperator.sol"; (src/Operator/RewardManager/Storage.sol#4)
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; (src/Operator/RewardManager/Storage.sol#3)
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; (src/Operator/Staking/Staking.sol#4)
import {IEpochManager} from "../../Epochs/EpochManager.sol"; (src/Operator/Staking/Staking.sol#6)
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; (src/Operator/Staking/Storage.sol#3)
Score
Impact:
Likelihood:
Recommendation

Remove the unused imports from the contract.

Remediation

SOLVED: The BitsCrunch team solved this finding in commit 64e161677096dedd26cf25b65f4fa2ce166c8c6d by following the mentioned recommendation.

Remediation Hash

7.8 Missing lock period threshold verification

// Informational

Description

In ContributorMultiTierStaking contract, the addPlan() and updatePlanLockPeriod() functions do not have a check for the _lockPeriod input parameter. This can lead to a situation where the _lockPeriod is set to an excessively high value, which can affect the functionality of the contract.


BVSS
Recommendation

Add a check for the _lockPeriod input parameter in the addPlan() and updatePlanLockPeriod() functions to ensure that the lock period is within a reasonable threshold.

Remediation

ACKNOWLEDGED: The BitsCrunch team made a business decision to acknowledge this finding and not alter the contracts. It will be planned for future upgrades.

References

7.9 Inconsistent use of uint alias instead of uint256

// Informational

Description

Throughout the code in scope, it has been noted that there is inconsistent use of uint and uint256 variable declarations, where some variables are declared as uint and others as uint256. While this does not affect the functionality of the code, it is recommended to use explicit size declaration for integers to ensure consistency and readability.

Score
Impact:
Likelihood:
Recommendation

Use explicit size declaration for integers. For example, use uint256 instead of uint.


Remediation

SOLVED: The BitsCrunch team solved this finding in commit 64e161677096dedd26cf25b65f4fa2ce166c8c6d by following the mentioned recommendation.

Remediation Hash

7.10 Single step ownership transfer risks DOS for privileged functions

// Informational

Description

The EpochManager contracts inherit from OpenZeppelin's OwnableUpgradeable contract and allows for single-step ownership transfer via the transferOwnership() function. In this aspect, it is crucial that the address to which ownership is transferred is verified to be active and willing to assume ownership responsibilities. Otherwise, the contract could be locked in a situation where it is no longer possible to make administrative changes to it.

Additionally, it is worth mentioning that in the OwnableUpgradeable contract, the renounceOwnership() function allows renouncing to the owner permission. Renouncing ownership before transferring it would result in the contract having no owner, eliminating the ability to call privileged functions.

Score
Impact:
Likelihood:
Recommendation

Consider using OpenZeppelin's Ownable2StepUpgradeable contract over the Ownable contract, or implementing similar two-step ownership transfer logic into the contracts, so that rather than directly transferring to the new owner, the transfer only completes when the new owner accepts ownership.

Additionally, it is recommended that the owner cannot call the renounceOwnership() function without first transferring ownership to another address. In addition, if a multi-signature wallet is used, the call to the renounceOwnership() function should be confirmed by most signers.

Remediation

ACKNOWLEDGED: The BitsCrunch team made a business decision to acknowledge this finding and not alter the contracts. It will be planned for future upgrades.

References

7.11 Check-effects-interactions pattern not followed

// Informational

Description

The claimReward function in the RewardManager contract is responsible for claiming rewards for a specific operator. However, the function does not follow the CEI pattern, which is a common pattern in Solidity development to prevent reentrancy attacks.

According to this pattern, any modifications to the contract's state should precede calls to external contracts or addresses. While the current usage of the ERC20 transfer method is not expected to make additional external calls, it is important to adhere to this pattern to ensure that the contract is secure against potential reentrancy behavior.

Score
Impact:
Likelihood:
Recommendation

Follow the checks-effects-interactions pattern to execute the state modifications prior to making external calls .

Remediation

ACKNOWLEDGED: The BitsCrunch team made a business decision to acknowledge this finding and not alter the contracts. It will be planned for future upgrades.

References

8. Automated Testing

Static Analysis Report

Description

Halborn used automated testing techniques to enhance the coverage of certain areas of the smart contracts in scope. Among the tools used was Slither, a Solidity static analysis framework. After Halborn verified the smart contracts in the repository and was able to compile them correctly into their abis and binary format, Slither was run against the contracts. This tool can statically verify mathematical relationships between Solidity variables to detect invalid or inconsistent usage of the contracts' APIs across the entire code-base.

The security team assessed all findings identified by the Slither software, however, findings with related to external dependencies are not included in the below results for the sake of report readability.

Output

The findings obtained as a result of the Slither scan were reviewed, and most of them were not included in the report because they were determined as false positives.

Slither results (1)Slither results (2)Slither results (3)Slither results (4)

Unit tests and fuzzing

The original repository used the Hardhat environment to develop and test the smart contracts. All tests were executed successfully. Additionally, the test codebase was duplicated in a Foundry environment to generate additional fuzz tests. These additional tests were run successfully covering ~1.000.000 runs per test.

Test results

Halborn strongly recommends conducting a follow-up assessment of the project either within six months or immediately following any material changes to the codebase, whichever comes first. This approach is crucial for maintaining the project’s integrity and addressing potential vulnerabilities introduced by code modifications.

© Halborn 2024. All rights reserved.