CEP18 - Casper Association


Prepared by:

Halborn Logo

HALBORN

Last Updated 07/21/2025

Date of Engagement: June 23rd, 2025 - July 7th, 2025

Summary

100% of all REPORTED Findings have been addressed

All findings

7

Critical

0

High

0

Medium

0

Low

4

Informational

3


1. Introduction

Casper engaged Halborn to conduct a security assessment of the CEP18 contract, beginning June 23rd, 2024 and ending July 7th, 2024.


The CEP18 contract is the standard token contract within the Casper ecosystem, and the engagement aimed to verify that the Casper network Conder upgrade did not create security vulnerabilities in the updated contract.

2. Assessment Summary

The team at Halborn assigned a full-time security engineer to verify the security of the smart contract. The security engineer is a blockchain and smart-contract security expert with advanced penetration testing, smart-contract hacking, and deep knowledge of multiple blockchain protocols.

The purpose of this assessment is to:

    • Ensure that smart contract functions operate as intended.

    • Identify potential security issues with the smart contracts.


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

    • Support the AddressableEntities feature.

    • Synchronize the SDK with the added entry points.

    • Fix the SDK entry point parameters.

    • Fix the SDK events support.

3. Test Approach and Methodology

Halborn performed a combination of the manual view of the code and automated security testing to balance efficiency, timeliness, practicality, and accuracy regarding the scope of the smart contract assessment. While manual testing is recommended to uncover flaws in logic, process, and implementation, automated testing techniques help enhance the coverage of smart contracts. They 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.

    • Manual code read and walk through.

    • Manual Assessment of use and safety for the critical Rust variables and functions in scope to identify any arithmetic related vulnerability classes.

    • Cross contract call controls.

    • Architecture related logical controls.

    • Test complex scenarios with unit tests.


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

REPOSITORY
(a) Repository: cep18
(b) Assessed Commit ID: eae0263
(c) Items in scope:
  • cep18/contracts/contract/allowances.rs
  • cep18/contracts/contract/balances.rs
  • cep18/contracts/contract/constants.rs
↓ Expand ↓
Out-of-Scope: Economic attacks and external dependencies.
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

4

Informational

3

Security analysisRisk levelRemediation Date
Addressable entities feature activation leads to total loss of fundsLowRisk Accepted - 07/13/2025
SDK is missing eventsLowSolved - 07/13/2025
Missing ChangeEventsModeParams declaration in SDKLowSolved - 07/13/2025
Deprecated BurnerList argument in ChangeSecurityArgsLowSolved - 07/13/2025
Unreachable caller kinds in get_immediate_callerInformationalSolved - 07/13/2025
Redundant sender recipient checkInformationalAcknowledged - 07/13/2025
Unused ENTRY_POINT_UPGRADE constantInformationalSolved - 07/13/2025

7. Findings & Tech Details

7.1 Addressable entities feature activation leads to total loss of funds

//

Low

Description

In casper, the caller could be externally owned accounts, represented by an AccountHash, or a contract, represented by ContractPackageHash, two enums of the Key type, wrapping a hash, and the access control and balances recording are done using Key::to_bytes.


In the new Casper network upgrade, Casper introduce a new enum inside the Key, the AddressableEntity. It is a new enum of Key that can carry both Account and Package hashes, present in AccountHash and ContractPackageHash in the older version.


Therefore Casper Network is preparing to replace through a simple switch in the node codebase, that will replace in the call context:

  • Key::AccountHash, by Key::AddressableEntity::Account

  • Key::ContractPackageHash, by Key::AddressableEntity::Package


The critical point of that upgrade is that the transition to AddressableEntity does not maintain the same byte value behind a Key holding the hash for an Account and the previous AccountHash. This has the effect of treating differently the same actors before and after the upgrade, meaning that:

  • Access control will cease to work on the last configuration.

  • Balances will immediately be lost.


The network still did not introduce the feature, but a future release with this feature activated would cause irrecoverable loss of funds for all the users in the protocol, because the getImmediateCaller would not return the same data before and after the feature release.


Code Location

The following snippets illustrates that balances will not be recognized under the same accounts. In balances.rs, the Key is used to create the dictionary key:

pub fn read_balance_from(address: Key) -> U256 {
    let dictionary_item_key = make_dictionary_item_key(address);
    get_dictionary_value_from_key(DICT_BALANCES, &dictionary_item_key).unwrap_or_default()
}

The dicitonary key is created using the Key::to_bytes, which gives a different result before and after the AddressableEntities upgrade.

fn make_dictionary_item_key(owner: Key) -> String {
    let preimage = owner
        .to_bytes()
        .unwrap_or_revert_with(Cep18Error::FailedToConvertBytes);
    base64_encode(preimage)
}

Proof of Concept

The following unit test shows inequality of the keys but equality of the values:

#[test]
fn test_mint_to_account_and_check_balance_with_entity_addr() {
    let mint_amount = U256::from(1000);

    let (
        mut builder,
        TestContext {
            cep18_contract_hash,
            ..
        },
    ) = setup_with_args(runtime_args! {
        ARG_NAME => TOKEN_NAME,
        ARG_SYMBOL => TOKEN_SYMBOL,
        ARG_DECIMALS => TOKEN_DECIMALS,
        ARG_TOTAL_SUPPLY => U256::from(TOKEN_TOTAL_SUPPLY),
        ARG_ENABLE_MINT_BURN => true,
    });

    // Create a 32-byte array for our test address starting with `0xbeef...`.
    let mut addr_bytes: HashAddr = [0u8; 32];
    addr_bytes[0] = 0xbe;
    addr_bytes[1] = 0xef;

    // Create the keys
    let account_hash = AccountHash::new(addr_bytes);
    let key_as_account = Key::Account(account_hash);
    let entity_addr = EntityAddr::Account(addr_bytes);
    let key_as_entity_addr = Key::AddressableEntity(entity_addr.into());

    let addressable_cep18_contract_hash = AddressableEntityHash::new(cep18_contract_hash.value());
    let mint_request = ExecuteRequestBuilder::contract_call_by_hash(
        *DEFAULT_ACCOUNT_ADDR,
        addressable_cep18_contract_hash,
        ENTRY_POINT_MINT,
        runtime_args! {
            ARG_OWNER => key_as_account,
            ARG_AMOUNT => mint_amount,
        },
    )
    .build();

    builder.exec(mint_request).expect_success().commit();

    let balance_from_account_key = cep18_check_balance_of(
        &mut builder,
        &cep18_contract_hash,
        key_as_account,
    );
    assert_eq!(balance_from_account_key, mint_amount);

    let balance_from_entity_addr_key = cep18_check_balance_of(
        &mut builder,
        &cep18_contract_hash,
        key_as_entity_addr,
    );

    // This one passes because the balance is not the same even though the address hash is the same
    assert_ne!(balance_from_account_key, balance_from_entity_addr_key);
}

The test is successful and proves that keys are not equal, leading to different balances for the AccountHash and the AddressableEntity:



BVSS
Recommendation

Implement a canonical serialization within Key::to_bytes (or inside make_dictionary_item_key) that maps AddressableEntity::Account to the legacy AccountHash byte sequence and AddressableEntity::Package to the legacy ContractPackageHash sequence. This ensures that dictionary keys and access controls established before the upgrade remain valid.

Remediation Comment

RISK ACCEPTED: The Casper team accepted the risk behind this finding, also mentioning that:

  1. Current CEP-18 implementation still derives the dictionary keys straight from Key::to_bytes().

  2. There is no logic anywhere in the crate that recognizes the new Key::AddressableEntity::{Account,Package} variants or normalizes them back to the old byte layout.

    1. No occurrence of AddressableEntity in the codebase.

    2. No conversion helper that strips the leading variant-tag byte before storing / reading.

  3. utils::get_immediate_caller_address() still returns a plain Key produced with Key::from(...). When the upstream Casper libraries switch that constructor to emit the new Key::AddressableEntity variants, the bytes returned by to_bytes() will differ from the ones that were stored previously

Moreover, the CEP18 contract is intended for the current configuration of the Casper network, and the activation of the AddressableEntities feature would take the nodes to apply the change, which would most likely not happen if Casper Labs does not push for it.


7.2 SDK is missing events

//

Low

Description

The TypeScript client is missing two events that are defined and emitted by the Rust contract:

  • ChangeSecurity, emitted when security settings are modified.

  • ChangeEventsMode, emitted when the events mode is changed.


BVSS
Recommendation

Update the TypeScript SDK’s contract ABI to incorporate the ChangeSecurity and ChangeEventsMode event definitions. Additionally, add the corresponding event interfaces and listener logic to enable the client to emit these events.

Remediation Comment

SOLVED: The Casper team added ChangeSecurity and ChangeEventsMode event types to client-js/src/events.ts, extending the CEP-18 event union and EventsMap so the TypeScript client now recognizes and handles these contract events correctly.

Remediation Hash

7.3 Missing ChangeEventsModeParams declaration in SDK

//

Low

Description

The SDK exposes types for each entry points in the CEP18 contract, however does not declare the ChangeEventsMode params.

Code Location

For example, the ChangeSecurityArgs type in client-js/src/types.ts:

export type ChangeSecurityArgs = {
    adminList?: Entity[];
    minterList?: Entity[];
// [...]
};

Reflects the change_security function in contracts/contract/src/main.rs:

pub extern "C" fn change_security() {
    if 0 == get_stored_value::<u8>(ARG_ENABLE_MINT_BURN) {
        revert(Cep18Error::MintBurnDisabled);
    }
    sec_check(vec![SecurityBadge::Admin]);
    let admin_list: Option<Vec<Key>> =
        get_optional_named_arg_with_user_errors(ADMIN_LIST, Cep18Error::InvalidAdminList);
    let minter_list: Option<Vec<Key>> =
        get_optional_named_arg_with_user_errors(MINTER_LIST, Cep18Error::InvalidMinterList);
    let none_list: Option<Vec<Key>> =
        get_optional_named_arg_with_user_errors(NONE_LIST, Cep18Error::InvalidNoneList);

BVSS
Recommendation

Implement and export a ChangeEventsModeParams interface in the SDK’s TypeScript definitions that corresponds to the ChangeEventsMode entry point parameters of the CEP18 contract.

Remediation Comment

SOLVED: The Casper team added the missing ChangeEventsModeArgs interface so the SDK now has typed parameters for the change_events_mode entry-point.

Remediation Hash

7.4 Deprecated BurnerList argument in ChangeSecurityArgs

//

Low

Description

The SDK declares an interface that is not up to date with the latest contract version. The SDK shows burnerList and mintAndBurnList arguments that are not used in the CEP18 contract:

export type ChangeSecurityArgs = {
  adminList?: Entity[];
  minterList?: Entity[];
  burnerList?: Entity[];
  mintAndBurnList?: Entity[];
  noneList?: Entity[];
};

For reference, in the contract side:

pub extern "C" fn change_security() {
    if 0 == get_stored_value::<u8>(ARG_ENABLE_MINT_BURN) {
        revert(Cep18Error::MintBurnDisabled);
    }
    sec_check(vec![SecurityBadge::Admin]);
    let admin_list: Option<Vec<Key>> =
        get_optional_named_arg_with_user_errors(ADMIN_LIST, Cep18Error::InvalidAdminList);
    let minter_list: Option<Vec<Key>> =
        get_optional_named_arg_with_user_errors(MINTER_LIST, Cep18Error::InvalidMinterList);
    let none_list: Option<Vec<Key>> =
        get_optional_named_arg_with_user_errors(NONE_LIST, Cep18Error::InvalidNoneList);

Calling the entry point with these arguments will therefore not work as intended.

BVSS
Recommendation

Update the ChangeSecurityArgs type in the SDK to align with the latest CEP18 contract by removing the deprecated burnerList and mintAndBurnList fields, and regenerate the client bindings to include only adminList, minterList, and noneList.

Remediation Comment

SOLVED: The Casper team successfully remediated this issue.

Remediation Hash

7.5 Unreachable caller kinds in get_immediate_caller

//

Informational

Description

The get_immediate_caller function retrieves the information about the caller, that could be either an externally owned account or a contract. The function consider some items as caller_info.kind that will never be provided by the node codebase, such as: PACKAGE and CONTRACT_PACKAGE.


The node codebase only consider three branches:

  • ACCOUNT

  • ENTITY

  • CONTRACT


Therefore, the other kinds will never be reached in the get_immediate_caller implementation.

Code Location

In the get_immediate_caller function, many kinds are defined:

pub fn get_immediate_caller() -> Key {
    const ACCOUNT: u8 = 0;
    const PACKAGE: u8 = 1;
    const CONTRACT_PACKAGE: u8 = 2;
    const ENTITY: u8 = 3;
    const CONTRACT: u8 = 4;

    let caller_info = casper_get_immediate_caller().unwrap_or_revert();

    match caller_info.kind() {
        ACCOUNT => caller_info
            .get_field_by_index(ACCOUNT)
            .unwrap()
            .to_t::<Option<AccountHash>>()
            .unwrap_or_revert()
            .unwrap_or_revert_with(Cep18Error::InvalidContext)
            .into(),
        PACKAGE => caller_info
            .get_field_by_index(PACKAGE)
            .unwrap()
            .to_t::<Option<PackageHash>>()
            .unwrap_or_revert()
            .unwrap_or_revert_with(Cep18Error::InvalidContext)
            .into(),
        CONTRACT_PACKAGE | CONTRACT => caller_info
            .get_field_by_index(CONTRACT_PACKAGE)
            .unwrap()
            .to_t::<Option<ContractPackageHash>>()
            .unwrap_or_revert()
            .unwrap_or_revert_with(Cep18Error::InvalidContext)
            .into(),
        ENTITY => caller_info
            .get_field_by_index(ENTITY)
            .unwrap()
            .to_t::<Option<EntityAddr>>()
            .unwrap_or_revert()
            .unwrap_or_revert_with(Cep18Error::InvalidContext)
            .into(),
        _ => revert(Cep18Error::InvalidContext),
    }
}

In the Casper codebase (types/src/system/caller.rs), the system only branches through the three aforementioned kinds:

impl TryFrom<Caller> for CallerInfo {
    type Error = CLValueError;

    fn try_from(value: Caller) -> Result<Self, Self::Error> {
        match value {
            Caller::Initiator { account_hash } => {
                let kind = ACCOUNT;

                let mut ret = BTreeMap::new();
                ret.insert(ACCOUNT, CLValue::from_t(Some(account_hash))?);
                ret.insert(PACKAGE, CLValue::from_t(Option::<PackageHash>::None)?);
                ret.insert(
                    CONTRACT_PACKAGE,
                    CLValue::from_t(Option::<ContractPackageHash>::None)?,
                );
                ret.insert(ENTITY, CLValue::from_t(Option::<EntityAddr>::None)?);
                ret.insert(CONTRACT, CLValue::from_t(Option::<ContractHash>::None)?);
                Ok(CallerInfo { kind, fields: ret })
            }
            Caller::Entity {
                package_hash,
                entity_addr,
            } => {
                let kind = ENTITY;

                let mut ret = BTreeMap::new();
                ret.insert(ACCOUNT, CLValue::from_t(Option::<AccountHash>::None)?);
                ret.insert(PACKAGE, CLValue::from_t(Some(package_hash))?);
                ret.insert(
                    CONTRACT_PACKAGE,
                    CLValue::from_t(Option::<ContractPackageHash>::None)?,
                );
                ret.insert(ENTITY, CLValue::from_t(Some(entity_addr))?);
                ret.insert(CONTRACT, CLValue::from_t(Option::<ContractHash>::None)?);
                Ok(CallerInfo { kind, fields: ret })
            }
            Caller::SmartContract {
                contract_package_hash,
                contract_hash,
            } => {
                let kind = CONTRACT;

                let mut ret = BTreeMap::new();
                ret.insert(ACCOUNT, CLValue::from_t(Option::<AccountHash>::None)?);
                ret.insert(PACKAGE, CLValue::from_t(Option::<PackageHash>::None)?);
                ret.insert(
                    CONTRACT_PACKAGE,
                    CLValue::from_t(Some(contract_package_hash))?,
                );

                ret.insert(ENTITY, CLValue::from_t(Option::<EntityAddr>::None)?);
                ret.insert(CONTRACT, CLValue::from_t(Some(contract_hash))?);
                Ok(CallerInfo { kind, fields: ret })
            }
        }
    }
}

BVSS
Recommendation

Refactor the get_immediate_caller implementation to align with the node’s CallerInfo kinds by removing the PACKAGE and CONTRACT_PACKAGE constants and their corresponding match arms, and handle only ACCOUNT, ENTITY, and CONTRACT types to eliminate unreachable code paths.

Remediation Comment

SOLVED: The over-broad variant list (PACKAGECONTRACT_PACKAGE, …) inside get_immediate_caller is not present in this version of the contract; the helper now uses CallStackElement instead.

Remediation Hash

7.6 Redundant sender recipient check

//

Informational

Description

The codebase contains duplicate checks for recipient to caller inequality:


pub extern "C" fn transfer() {
    let caller = get_immediate_caller();
    let recipient: Key = runtime::get_named_arg(ARG_RECIPIENT);
    if caller == recipient {
        revert(Cep18Error::CannotTargetSelfUser);
    }
    let amount: U256 = runtime::get_named_arg(ARG_AMOUNT);
    transfer_balance(caller, recipient, amount).unwrap_or_revert();
    events::record_event_dictionary(Event::Transfer(Transfer {
        sender: caller,
        recipient,
        amount,
    }))
}

pub fn transfer_balance(sender: Key, recipient: Key, amount: U256) -> Result<(), Cep18Error> {
    if sender == recipient || amount.is_zero() {
        return Ok(());
    }
    let new_sender_balance = {
        let sender_balance = read_balance_from(sender);
        sender_balance
            .checked_sub(amount)
            .ok_or(Cep18Error::InsufficientBalance)?
    };

    let new_recipient_balance = {
        let recipient_balance = read_balance_from(recipient);
        recipient_balance
            .checked_add(amount)
            .ok_or(Cep18Error::Overflow)?
    };

    write_balance_to(sender, new_sender_balance);
    write_balance_to(recipient, new_recipient_balance);

    Ok(())
}

BVSS
Recommendation

Eliminate the redundant sender == recipient check from transfer() and centralize the self-transfer validation within transfer_balance by returning Err(Cep18Error::CannotTargetSelfUser) when sender == recipient. Propagate this error upstream to enforce the validation consistently in a single location.

Remediation Comment

ACKNOWLEDGED: Duplicate sender == recipient check remains in both transfer() and transfer_balance().

Remediation Hash

7.7 Unused ENTRY_POINT_UPGRADE constant

//

Informational

Description

The ENTRY_POINT_UPGRADE constant defined in constants.rs is not used in the entry points. This endpoint is not expected to be implemented because of the way Casper handles upgrades.

BVSS
Recommendation

Remove the unused ENTRY_POINT_UPGRADE constant from constants.rs to eliminate dead code and ensure alignment with Casper’s native upgrade mechanism.

Remediation Comment

SOLVED: The Casper team successfully remediated this issue.

Remediation Hash

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.