Pepper


Prepared by:

Halborn Logo

HALBORN

Last Updated 10/01/2024

Date of Engagement: September 9th, 2024 - September 20th, 2024

Summary

100% of all REPORTED Findings have been addressed

All findings

10

Critical

0

High

1

Medium

0

Low

4

Informational

5


1. Introduction

Pepper Team engaged Halborn to conduct a security assessment on their smart contracts beginning on September 9th, 2024, and ending on September 20th, 2024. The security assessments were scoped to the smart contracts provided in the pepper-token GitHub repository. Commit hashes and further details can be found in the Scope section of this report.

2. Assessment Summary

Halborn was provided 11 (eleven) days for the engagement, and assigned 1 (one) full-time security engineers 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 security issues, that were mostly addressed by the Pepper team. The main security issues were:

    • Allowing the airdrop contract to mint tokens to the users without reverting.

    • Input validations for critical setter functions.

    • Gas saving suggestions.

3. Test Approach and Methodology

Halborn performed a combination of manual, semi-automated and automated security testing to balance efficiency, timeliness, practicality, and accuracy regarding 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 the code 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 and purpose.

    • Smart contract manual code review and walk-through.

    • Manual assessment of use and safety for the critical Solidity variables and functions in scope to identify any vulnerability classes

    • Manual testing by custom scripts.

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

    • Local deployment and testing ( Foundry)

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:
EXPLOITABILITY 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: pepper-token
(b) Assessed Commit ID: e4a7f79
(c) Items in scope:
  • src/Pepper.sol
  • src/PepperAirdrop.sol
  • src/interfaces/IPepper.sol
↓ Expand ↓
Out-of-Scope:
Remediation Commit ID:
  • bccbd7a
Out-of-Scope: New features/implementations after the remediation commit IDs.

6. Assessment Summary & Findings Overview

Critical

0

High

1

Medium

0

Low

4

Informational

5

Security analysisRisk levelRemediation Date
Minting Limit Calculation May Prevent Legitimate ClaimsHighSolved - 09/20/2024
Missing Zero-Value Check in changeEpochLength FunctionLowSolved - 09/20/2024
Insufficient Validation of Claim Start BlockLowSolved - 09/20/2024
Modification of Claim Start Block After Claiming BeginsLowSolved - 09/20/2024
Modification of Epoch Length After Claiming BeginsLowSolved - 09/20/2024
Lack of two-step ownership transfer patternInformationalAcknowledged - 09/20/2024
Lack of Null Value ValidationInformationalSolved - 09/20/2024
Suboptimal Gas Usage in removeValidator FunctionInformationalSolved - 09/20/2024
Code Duplication in getPendingClaim and claim FunctionsInformationalSolved - 09/20/2024
Minor Reward Discrepancy Between calculateRewards and calculateRewards2InformationalAcknowledged - 09/27/2024

7. Findings & Tech Details

7.1 Minting Limit Calculation May Prevent Legitimate Claims

//

High

Description

In the Pepper contract, the mint function implements a cap on minting that is intended to limit mints to 40% of the total supply.

function mint(address to, uint256 amount) public {
    require(hasRole(MINTER_ROLE, msg.sender), "Must have minter role to mint");
    uint256 _amount = totalSupply() + amount;
    require(_amount <= MINT_LIMIT, "Minting exceeds 40% of total supply");
    require(_amount <= MAX_SUPPLY, "Max supply reached");

    _mint(to, amount);
}

The issue lies in using the total supply to calculate the minting limit. This approach doesn't distinguish between tokens minted through the mint function and those minted through other means, such as claims. As a result, once the total supply reaches 40% of MAX_SUPPLY, the minting operations through mint function will revert.

This can lead to a scenario where the PepperAirdrop::mintPepper function, which relies on this mint function, starts to revert unexpectedly. This could disrupt planned airdrops and prevent users from receiving their entitled tokens.

Proof of Concept

Add the following function to Pepper.t.sol

 function test_ClaimRevert_PoC() public {
        uint256 amount = pepper.MINT_LIMIT() / 250;
        address user1 = vm.addr(1);
        // give 3000 CHZ to user
        vm.deal(user1, amount);

        // user stakes on validator 2
        vm.prank(user1);
        stakingPool.stake{value: amount}(vm.addr(6));

        //claim
        vm.prank(user1);
        pepper.claim();

        //Mocking a call from PepperAirdrop to mint 500 Pepper to a user
        vm.expectRevert("Minting exceeds 40% of total supply");
        pepper.mint(user1, 500e18);
    }

Run with forge test --mt "test_ClaimRevert_PoC" -vvvv

BVSS
Recommendation

To address this issue, implement a separate tracker for mints performed by accounts with the MINTER_ROLE. This allows for proper enforcement of the 40% limit on controlled mints while allowing claims to proceed normally. Here's a revised implementation:

// Add this state variable
uint256 public minterRoleMintedAmount;

function mint(address to, uint256 amount) public {
    require(hasRole(MINTER_ROLE, msg.sender), "Must have minter role to mint");
    
    uint256 newMinterRoleMintedAmount = minterRoleMintedAmount + amount;
    require(newMinterRoleMintedAmount <= MINT_LIMIT, "Minting exceeds 40% of total supply for minter role");
    
    uint256 newTotalSupply = totalSupply() + amount;
    require(newTotalSupply <= MAX_SUPPLY, "Max supply reached");
    
    minterRoleMintedAmount = newMinterRoleMintedAmount;
    _mint(to, amount);
}
Remediation

SOLVED: The suggested mitigation was implemented by the Pepper team.

Remediation Hash
bccbd7a5747d4ef6586581ec93ac77e0d8a4de45

7.2 Missing Zero-Value Check in changeEpochLength Function

//

Low

Description

The changeEpochLength function in the Pepper contract allows the owner to set the EPOCH_LENGTH without validating that the new value is non-zero. This oversight can lead to a critical issue in the contract's functionality, specifically:

  • If EPOCH_LENGTH is set to zero, it will cause a divide-by-zero error in the getCurrentEpoch function:

    function getCurrentEpoch() public view returns (uint256 _epoch) {
        return (block.number - claimStartBlock) / EPOCH_LENGTH;
    }
  • This divide-by-zero error would cause all calls to getCurrentEpoch to revert, effectively breaking core functionalities of the contract that rely on epoch calculations, such as the claiming mechanism.

This vulnerability could potentially render the contract unusable if the epoch length is accidentally set to zero.

BVSS
Recommendation

To address this issue, implement a non-zero check in the changeEpochLength function.

function changeEpochLength(uint16 epochLength) public onlyOwner {
    require(epochLength != 0, "Epoch length cannot be zero");
    EPOCH_LENGTH = epochLength;
    emit EpochLengthChanged(epochLength);
}

This change ensures that:

  1. The EPOCH_LENGTH can never be set to zero, preventing potential divide-by-zero errors.

  2. The contract maintains its integrity and functionality, particularly in epoch-based calculations.

Remediation

SOLVED: The Pepper team decided to remove the changeEpochLength function from the Pepper contract.

Remediation Hash
bccbd7a5747d4ef6586581ec93ac77e0d8a4de45

7.3 Insufficient Validation of Claim Start Block

//

Low

Description

The constructor of the Pepper contract allows setting the claimStartBlock without proper validation. Currently, there's no check to ensure that the provided _claimStartBlock is either set to the current block number or a future block number.

  constructor(
        uint256 _claimStartBlock,
        string memory _tokenName,
        string memory _tokenSymbol,
        address[] memory initialValidators
    ) ERC20(_tokenName, _tokenSymbol) ERC20Capped(MAX_SUPPLY) {
        claimStartBlock = _claimStartBlock;

        // Set initial validators
        validators = initialValidators;

        // Grant the contract deployer the default admin role: it will be able to grant and revoke any roles
        _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
        _setupRole(MINTER_ROLE, msg.sender);
    }

This oversight could potentially lead to issues if the _claimStartBlock is mistakenly set to a past block number, which might enable premature claiming of rewards or cause other unexpected behaviors in the contract's timing-dependent functions.

A similar issue in changeClaimStartBlock function:

    function changeClaimStartBlock(uint256 newStartBlock) public onlyOwner {
        claimStartBlock = newStartBlock;
        emit ClaimStartBlockChanged(newStartBlock);
    }
BVSS
Recommendation

To address this issue, implement a check in the constructor and changeClaimStartBlock function to ensure that the _claimStartBlock is either equal to or greater than the current block number.

require(_claimStartBlock >= block.number, "Claim start block must be current or future block");
Remediation

SOLVED: The suggested check was added to changeClaimStartBlock function. It was not added in the constructor as the check exists in the deployment script for the Pepper contract.

Remediation Hash
bccbd7a5747d4ef6586581ec93ac77e0d8a4de45

7.4 Modification of Claim Start Block After Claiming Begins

//

Low

Description

The changeClaimStartBlock function in the Pepper contract allows the owner to modify the claimStartBlock at any time, even after the claiming process has begun.

   function changeClaimStartBlock(uint256 newStartBlock) public onlyOwner {
        claimStartBlock = newStartBlock;
        emit ClaimStartBlockChanged(newStartBlock);
    }

This unrestricted ability to change the start block can lead to significant issues in the contract's accounting and fairness mechanisms. Specifically:

  1. It can disrupt the epoch calculation, potentially causing inconsistencies in reward distributions.

  2. It may invalidate previous claims or allow double-claiming if the new start block is set to a past value.

  3. It could unfairly advantage or disadvantage users depending on how the start block is changed.

This undermines the integrity and predictability of the claiming process, which is crucial for user trust and proper contract functionality.

BVSS
Recommendation

To address this issue, implement a check in the changeClaimStartBlock function to prevent modifications after the claiming process has started.

function changeClaimStartBlock(uint256 newStartBlock) public onlyOwner {
    require(block.number < claimStartBlock, "Claiming has already begun, cannot change start block");
    require(newStartBlock > block.number, "New claim start block must be a future block");
    claimStartBlock = newStartBlock;
    emit ClaimStartBlockChanged(newStartBlock);
}
Remediation

SOLVED: The suggested mitigation was implemented along with adding a new variable, claimEnabled, which when set to true will prevent modification to claimStartBlock.

require(!claimEnabled, "Claim currently active");
Remediation Hash
bccbd7a5747d4ef6586581ec93ac77e0d8a4de45

7.5 Modification of Epoch Length After Claiming Begins

//

Low

Description

The changeEpochLength function in the Pepper contract allows the owner to modify the EPOCH_LENGTH at any time, even after the claiming process has begun. This unrestricted ability to change the epoch length can lead to significant issues in the contract's accounting and fairness mechanisms, as pointed out in the issue "Modification of Claim Start Block After Claiming Begins".

  function changeEpochLength(uint16 epochLength) public onlyOwner {
        EPOCH_LENGTH = epochLength;
        emit EpochLengthChanged(epochLength);
    }
BVSS
Recommendation

To address this issue, implement a check in the changeEpochLength function to prevent modifications after the claiming process has started.

Remediation

SOLVED: The Pepper team decided to remove the changeEpochLength function from the Pepper contract.

Remediation Hash
bccbd7a5747d4ef6586581ec93ac77e0d8a4de45

7.6 Lack of two-step ownership transfer pattern

//

Informational

Description

Pepper.soland Pepperairdrop.sol implements the Ownable pattern. However, the assessment revealed that the solution does not support the two-step-ownership-transfer pattern. The ownership transfer might be accidentally set to an inactive EOA account. In the case of account hijacking, all functionalities get under permanent control of the attacker.

BVSS
Recommendation

It is recommended to implement a two-step process (Openzeppelin's Ownable2Step.sol) where the owner nominates an account and the nominated account needs to call an acceptOwnership() function for the transfer of the ownership to fully succeed. This ensures the nominated EOA account is a valid and active account.

Remediation

ACKNOWLEDGED: The Pepper team acknowledged the above finding.

7.7 Lack of Null Value Validation

//

Informational

Description

Here are the functions that lack these checks:

  1. In the constructor:

    • _claimStartBlock: While this is a uint256 and not an address, it's still important to validate that it's not 0.

  2. In the changeStakingContract function:

    • newStakingContract: This should be checked to ensure it's not address(0).

  3. In the changeStakingPoolContract function:

    • newStakingPoolContract: This should be checked to ensure it's not address(0).

  4. In the addValidator function:

    • validator: This should be checked to ensure it's not address(0).

  5. In the removeValidator function:

    • validator: While less critical here, it's still good practice to check that it's not address(0).

BVSS
Recommendation

Every input address should be checked not to be zero, especially the ones that could lead to rendering the contract unusable, lock tokens, etc. This is considered a best practice.

Remediation

SOLVED: All the necessary null value checks were added to the Pepper contract.

Remediation Hash
bccbd7a5747d4ef6586581ec93ac77e0d8a4de45

7.8 Suboptimal Gas Usage in removeValidator Function

//

Informational

Description

The removeValidator function in the Pepper contract iterates through the validators array to find and remove a specific validator. While the function correctly implements the removal process, it does not optimize for gas efficiency. The current implementation accesses the validators.length property in each iteration of the loop, which can be costly in terms of gas, especially for larger arrays.

function removeValidator(address validator) external onlyOwner {
    for (uint256 i = 0; i < validators.length; i++) {
        if (validators[i] == validator) {
            validators[i] = validators[validators.length - 1];
            validators.pop();
            break;
        }
    }
}

In Solidity, accessing an array's length in each iteration of a loop is considered inefficient, as it requires an extra storage read operation each time. This inefficiency becomes more pronounced as the array grows larger.

BVSS
Recommendation

To improve gas efficiency, it's recommended to cache the array length before entering the loop. This reduces the number of storage reads and can lead to noticeable gas savings, especially for larger validator sets.

Here's an optimized version of the function:

function removeValidator(address validator) external onlyOwner {
    uint256 validatorCount = validators.length;
    for (uint256 i = 0; i < validatorCount; i++) {
        if (validators[i] == validator) {
            validators[i] = validators[validatorCount - 1];
            validators.pop();
            break;
        }
    }
}
Remediation

SOLVED: The suggested mitigation was implemented by the Pepper team.

Remediation Hash
bccbd7a5747d4ef6586581ec93ac77e0d8a4de45

7.9 Code Duplication in getPendingClaim and claim Functions

//

Informational

Description

The Pepper contract contains two functions, getPendingClaim and claim, which share significant portions of identical logic.

    function getPendingClaim() external view returns (uint256 pendingHarvest) {
        require(block.number >= claimStartBlock, "Claim is not enabled");
        uint256 currentEpoch = getCurrentEpoch();

        require(claims[msg.sender][currentEpoch].blockNumber == 0, "Already claimed for this epoch");

        (uint256 rewardStakingPool, uint256 rewardStaking) = calculateRewards(msg.sender);

        uint256 totalReward = rewardStakingPool + rewardStaking;
        return totalReward;
    }

    function claim() external nonReentrant {
        require(block.number >= claimStartBlock, "Claim is not enabled");
        uint256 currentEpoch = getCurrentEpoch();
        require(claims[msg.sender][currentEpoch].blockNumber == 0, "Already claimed for this epoch");

        (uint256 rewardStakingPool, uint256 rewardStaking) = calculateRewards(msg.sender);

        uint256 totalReward = rewardStakingPool + rewardStaking;

        claims[msg.sender][currentEpoch] = Claim({
            amountStakingPoolClaimed: rewardStakingPool,
            amountStakingClaimed: rewardStaking,
            blockNumber: block.number
        });

        emit Claimed(msg.sender, rewardStakingPool, rewardStaking);
        _mint(msg.sender, totalReward);
    }

The duplicated logic includes:

  1. Checking if claiming is enabled

  2. Calculating the current epoch

  3. Verifying if a claim has already been made for the current epoch

  4. Calculating rewards

This duplication increases the contract's complexity and the potential for errors during future modifications.

BVSS
Recommendation

To address this issue, refactor the common logic.

Here's an example of how to implement this:

function getPendingClaim(address user) public view returns (uint256 pendingHarvest) {
    require(block.number >= claimStartBlock, "Claim is not enabled");
    uint256 currentEpoch = getCurrentEpoch();

    require(claims[user][currentEpoch].blockNumber == 0, "Already claimed for this epoch");

    (uint256 rewardStakingPool, uint256 rewardStaking) = _calculatePendingClaim(user);

    return rewardStakingPool + rewardStaking;
}

function claim() external nonReentrant {
    uint256 totalReward = getPendingClaim(msg.sender);

    uint256 currentEpoch = getCurrentEpoch();
    claims[msg.sender][currentEpoch] = Claim({
        amountStakingPoolClaimed: rewardStakingPool,
        amountStakingClaimed: rewardStaking,
        blockNumber: block.number
    });

    emit Claimed(msg.sender, rewardStakingPool, rewardStaking);
    _mint(msg.sender, totalReward);
}
Remediation

SOLVED: A new internal function was added which contains the common logic between both functions:

function _calculateRewards(
        address account
    ) private view returns (uint256 rewardStakingPoolAmount, uint256 rewardStakingAmount) {
        require(getClaimStatus(), "Claim is not enabled");
        uint256 currentEpoch = getCurrentEpoch();

        require(claims[account][currentEpoch].blockNumber == 0, "Already claimed for this epoch");
        return calculateRewards(account);
    }
Remediation Hash
bccbd7a5747d4ef6586581ec93ac77e0d8a4de45

7.10 Minor Reward Discrepancy Between calculateRewards and calculateRewards2

//

Informational

Description

The calculateRewards2 function does not account for the amountToStake returned by _calcUnclaimedDelegatorFee, which results in a slightly lower totalStakedInPool and consequently reduces the stakingPoolStakes for a user. In contrast, users who use calculateRewards might receive slightly higher rewards, causing a small discrepancy in reward distribution.

BVSS
Recommendation

This behavior should be documented to inform users about the potential difference in reward calculations between the two functions.

Remediation

ACKNOWLEDGED: The Pepper team acknowledged this finding with the following comment: "We decided to make this compromise to reduce the transaction fee. so basically user may get less (just slightly less) Peppers but they will pay 10x less in transaction fee."

8. Automated Testing

Introduction

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.

Most of the issues found were false positives, including the reentrancy. One suggestion related to caching the array length to save gas was included in the final report.

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 2025. All rights reserved.