ScaleBit

Oct 27, 2023

Focusing on Solidity, DeFi, and Cross-Chain Bridges, Ensuring the Secure Development of the opBNB Ecosystem

This technical research report was authored by Polaris from the ScaleBit Research Group

1 Introduction to opBNB

1.1 What is opBNB?

The opBNB network is the Layer 2 scaling solution for the BNB Smart Chain powered by bedrock version[1] of Optimism OP Stack. It works by offloading transaction processing and resource usage from the BNB Smart Chain, while still posting data to the underlying mainnet. Users interact with the opBNB network by depositing funds from BSC and using applications and contracts on opBNB. Sequencers then aggregate transactions, compute state transitions and submit them to the rollup contract on BSC. Provers generate cryptographic proofs that prove the validity of these state transitions, and Verifiers check the proofs to verify the opBNB state is correct. At its core, opBNB allows users to deposit and withdraw funds, use smart contracts, and view network data with high throughput and low fees. By leveraging Layer 2, opBNB is able to scale beyond the constraints of the BNB Smart Chain and provide an improved experience for users.

OB

  • Capacity can reach to > 100m gas per second, which is mucher higher than other layer 2 solutions on the Ethereum.
  • Gas fee of transfer can reach as low as $0.005 on average.
  • block time is 1 second.

1.2 Why BSC Requires opBNB

Layer 1 networks are the base networks that provide the infrastructure for data transmission and validation, such as BSC and Ethereum. These networks face the challenge of network congestion during peak periods, which usually happens when any popular application runs a promotion campaign or experiences a spike in traffic. Network congestion can lead to high transaction fees, slow transactions, and poor user experience.

To overcome these challenges, layer 1 networks need to improve their scalability, which is the ability to handle more transactions per second without compromising security. For example, BSC had a web3 game on BNB Smart Chain (BSC) in 2021 which generated over 8 million transactions per day[2].

OB

BSC’s throughput capacity would presumably be vastly exceeded, resulting in slowed transaction speeds, delayed transaction finality, and a poor user experience both for game players and users of other dApps.

Daily gas fees could potentially rise to over 6,800 BNB ($3M USD) at that level of usage, posing a substantial barrier to usability and sustainability of this game.

The immense transaction loads from a dApp on such a large scale seem infeasible for BSC to handle efficiently in its current form. Significant optimizations and scaling solutions would likely be required for BSC to support such a dApp without network-wide performance degradation and unreasonably high costs.

2 Comparison between opBNB and Other Networks

2.1 opBNB VS Other Layer1 Networks

The goal of opBNB is to provide a scaling solution for network congestion problems for highly active applications on the BSC, such as DeFi, NFTs and gaming. opBNB is based on OP Stack and with optimizations of the mining process and the cache data access to achieve a capacity of 100M gas per second, which is much higher than BSC.

OB

2.2 opBNB VS other Layer2 Networks

Compared with other L2 solutions on the Ethereum, like OP Mainnet and Arbitrum, opBNB has lower gas fee, and higher block gas limit, which means the gas fee will be more stable when traffic of Layer 2 increases. The Ethereum EIP-1559 parameters are provided below for reference.

2.2.1 Gas Parameter Differences

OB

2.2.2 Metrics Differences

OB

3 opBNB Security Best Practices

3.1 Solidity Best Security Practice

Developing on opBNB is nearly the same as building directly on the BNB Smart Chain. opBNB uses the EVM execution engine, which means decentralized applications can migrate from Ethereum, BNB Smart Chain, Polygon, and other EVM-compatible chains with minimal code changes. Following the security guidelines below significantly enhances contract security.

OB

3.1.1 Prepare for Failures and Risks

All significant contracts are susceptible to errors. Particularly in the early stages of opBNB, issues may still arise. Thus, you must be ready to address them, and your contracts must have the capability to respond. You can achieve this in the following ways:

  • Pause the contract or “cut the circuit” when issues occur.
  • Develop an effective upgrade strategy, including methods for improvement and bug fixes.
  • Manage funds at risk effectively by limiting the maximum usage and total amount.

In summary, here are the issues related to smart contract upgrades:

  • Avoid using selfdestruct and delegatecall within the contract’s implementation.
  • Ensure that stored variables do not overwrite each other during upgrades.
  • Avoid calling external libraries within the contract’s implementation, as it’s unpredictable how they will affect storage access.
  • Deployers must not neglect calling the initialization function.
  • Do not include interval variables in base contracts to prevent storage conflicts when adding new variables to the base contract (this is automatically handled by the Hardhat plugin).
  • Values in immutable variables are not retained between upgrades.
  • It’s strongly discouraged to execute any operations within the constructor function, as future upgrades will need to execute the same constructor logic to maintain compatibility.

3.1.3 Pay Attention to Integer Division Rounding

Solidity doesn’t support floating-point numbers, so rounding errors are inevitable. Designers must be aware of whether rounding up or rounding down is the correct approach and who should benefit from the rounding.

// bad
uint x = 5 / 2; // Result is 2, all integer divison rounds DOWN to the nearest integer

Using a multiplier can prevent rounding, and this multiplier must be taken into account when working with x:

// good
uint multiplier = 10;
uint x = (5 * multiplier) / 2;

Storing the numerator and denominator means that the result of numerator/denominator can be calculated off-chain:

// good
uint numerator = 5;
uint denominator = 2;

3.1.4 Use Ownable2Step Instead of Ownable

Single-step ownership transfer implies that if an incorrect address is passed during the transfer of ownership or permission management, it means that the role will be permanently lost. Granting management permission to the wrong address in this function could cause irreversible damage to the contract.

Ownable2Step requires the receiver to confirm ownership, ensuring that ownership isn’t accidentally sent to the wrong address.

Reference the following implementation:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable2Step.sol

3.1.5 Use Multi-Signature Wallets

One way to implement secure access control is by using multi-signature accounts to manage contracts. Unlike regular external accounts, multi-signature accounts are owned by multiple entities and require a minimum number of account signatures (e.g., 3 out of 5) to execute transactions.

Using multi-signature for access control adds an extra layer of security because it requires consensus from multiple parties to perform actions on the target contract. This approach is particularly useful when ownership patterns are necessary, making it more challenging for attackers or malicious insiders to manipulate sensitive contract functions for malicious purposes.

3.1.6 Distinguish Between Functions and Events

To prevent confusion between functions and events, name an event in uppercase and add a prefix (we recommend LOG). For functions, always start with a lowercase letter, except for constructors.

 // bad
event Transfer() {}
function transfer() {}

// good
event LogTransfer() {}
function transfer() external {}

3.1.7 Beware of Sandwich Attacks

The price of an asset moves in response to buying and selling pressure. If a large order is sitting in the mempool, traders have an incentive to copy the order but with a higher gas price. That way, they purcase the asset, let the large order move the price up, then they sell right away. The sell order is sometimes called “backrunning.” The sell order can be done with by placing a sell order with a lower gas price so that the sequence looks like this:

  1. Frontrun buy
  2. Large buy
  3. Sell

The primary defense against this attack is to provide a “slippage” parameter. If the “frontrun buy” itself pushes the price up past a certain threshld, the “large buy” order will revert making the frontrunner fail on the trade.

It’s called a sandwhich, because the large buy is sandwhiched by the frontrun buy and the backrun sell. This attack also works with large sell orders, just in the opposite direction.

3.1.8 Remember that On-Chain Data Is Public

Many applications require data to be submitted that is private until a certain point in time. Games (e.g., on-chain games like rock-paper-scissors) and auctions (e.g., sealed-bid second-price auctions) are two typical examples. If your application deals with privacy concerns, be sure to avoid premature disclosure of user information.

For example:

  • In on-chain games like rock-paper-scissors, both parties participating in the game need to submit the hash value of their “action plans,” and they subsequently need to reveal their action plans. If the action plans don’t match the previously submitted hash value, an exception is raised.
  • In auctions, players are required to submit the hash value of their initial price offer (along with a deposit exceeding their bid) in the first stage and then submit funds for their price offer in the second stage.
  • When developing an application that relies on a random number generator, the correct sequence should be: (1) players submit action plans, (2) generate a random number, (3) players make payments.
  • If you’re implementing frequent batch auctions, the hash-commit mechanism is also a good choice.

3.2 DeFi Protocol Security Practice

Adopting several security practices in DeFi protocols can significantly enhance their security.

OB

3.2.1 Smart Contract Audits

A smart contract audit is a detailed methodical examination of the code used to interact with the blockchain. Smart contract security audits are essential to eliminating security vulnerabilities that could have arisen during the development process and could cause potential exploits, putting user funds at risk. Regular security audits are essential to eradicate vulnerabilities during the product life cycle. A security audit must be performed post-development and before the main net deployment of a new version of the smart contract. Ex- V1, V2 and V3.

As a blockchain security team that provides security solutions for Mass Adoption of Web3, ScaleBit leverages its expertise in blockchain cross-chain and zero-knowledge proof technologies and specializes in delivering detailed and cutting-edge security audits for ZKP (Zero-Knowledge Proof), Layer 2, and cross-chain applications. The commitment of ScaleBit lies in ensuring the security of large-scale applications within the scalable blockchain ecosystem.

3.2.2 On-chain Suspicious Activity Tracking

On-chain activity tracking bots are used to detect mission critical actions, or state changes (malicious transactions) in smart contracts, such as external function call, re-entrancy calls and alert teams through custom notifications to take necessary action on time.

3.2.3 Formal Verification

Formal verification is a method used to prove the correctness of a design and demonstrate the root cause of an error by rigorous mathematical procedures. Formal verification can help verify the correctness of systems such as cryptographic protocols. It is performed mathematically to avoid any cryptographic vulnerabilities from the source code. In formal verification, one writes a specification (you define what is right in terms of context and what’s wrong) to expose a bug.

It is different from a security audit as it focuses on the mathematical logic of the smart contract code and can reliably find complex bugs that auditing firms tend to miss.

3.2.4 Economic Security

Maximum capital efficiency, reduced risk solution. Economic security is a solution that focuses on the financial model of the DeFi projects. It ensures protocols are tested extensively on financial security and help developers to understand how decisions about security, governance, and consensus mechanisms are likely to affect network activity and asset value.

3.2.5 Lessons Learned

  • It is imperative to follow multiple security practices in DeFi protocols to protect user-locked funds from hacks and exploits.
  • Relying on a single security practice can cause a single point of failure in case of a security incident. Multiple security practices should be followed to hedge one’s bets against potential exploits.
  • It is worth noting that most of the exploited smart contracts are either not audited or do not have etiquette security practices in place to safeguard assets.

3.3 Cross-Chain Bridges Security Practice

Cross-chain bridges play a critical role in Layer 2 solutions, and opBNB is no exception. Before building or deploying any applications on the opBNB network, it’s essential to deposit BNB (tBNB) as your gas token from the BNB Smart Chain to opBNB, which is facilitated through cross-chain bridges. However, there has been a noticeable increase in cross-chain bridge attacks, making these bridges a target for malicious activities and a potential source of vulnerabilities, sometimes leading to severe consequences.

OB

3.3.1 Common Cross-Chain Bridge Vulnerabilities

The Custodian

  • Incorrect asset amount released with respect to the burnt tokens
  • Assets released despite the debt token has not been burnt
  • Asset transaction replay for a single burn transaction

The Debt Issuer

  • Incorrect amount of debt issued with respect to the deposited assets
  • Debt token issued although the actual verification did not take place
  • Anybody can issue debt tokens

The Communicator

  • Issues debt tokens although no assets have been deposited
  • Issues no debt tokens although assets have been deposited
  • Accepts fraudulent messages from a fake custodian or a debt issuer
  • Does not relay messages
  • The source contract does not emit events upon deposit/withdrawal

The Interface (could be fixed with “revoke approval”)

  • Deposit from another account
  • Execute any calls from any contract

The Network

  • 51% attack

It’s crucial to adhere to standards and create secure contracts based on lessons learned from past mistakes if your project includes bridge smart contracts. Ensure that verified contracts meet the following requirements:

  1. Conduct a contract security audit before the project goes live.
  2. Consider potential threats related to the bridge.
  3. Thoroughly validate the suitability of contract calling interfaces.
  4. When updating versions, reassess interface and signature security.
  5. Implement a rigorous review of cross-chain signers to ensure signatures aren’t controlled by malicious actors.

3.3.2 Security Verification Requirements

Following these security verification requirements can significantly enhance the security of cross-chain bridges:

  1. Verify that bridge requires all necessary values to be included in the message and signed: chain ids, receiver, amount, nonce.
  2. Verify that used signatures are invalidated to protect the bridge from replay attacks.
  3. Verify that the message hash generation algorithm is resistant to collision attacks.
  4. Verify that bridge includes source and destination chain identifiers in the signed message and correctly verifies them.
  5. Verify that bridge does not allow spoofing chain identifiers.
  6. Verify that bridge uses a nonce parameter to prevent the same operation (the same sender, receiver, and amount) to be executed multiple times.
  7. Verify that signed message cannot be used in a different context.
  8. Verify that the case of 0 being returned by ecrecover function is handled securely.
  9. Verify that privileged contracts are separated from cross-chain relay calls. Attacker should not be able to cross-call the privileged contract.
  10. Verify each supported blockchain’s finality is taken into account when settling relay calls.
  11. Verify that bridge disregards calls originating from different function than designed.
  12. Verify that bridge requires adequate amount of fees to process the message.
  13. Verify that the maximum gas consumption for relayed messages is limited or fully backed by sender (e.g., in terms of fee).

Conclusion

In the opBNB ecosystem, strict adherence to the security practices outlined above is crucial to ensure the safety of your protocol. These practices cover various key aspects, including smart contracts, DeFi protocols, and cross-chain bridges. Following these practices not only effectively reduces the risk of potential vulnerabilities and attacks but also enhances user trust, ensuring the reliable protection of their funds and data.

Furthermore, the importance of security audits cannot be emphasized enough. As a leading blockchain security team, ScaleBit possesses the expertise and practical experience to provide security audit services for ZKP, Layer 2, and cross-chain applications. Security auditing is a crucial step in ensuring the integrity of protocols and smart contracts. It helps identify and rectify potential vulnerabilities and security risks to ensure the reliable protection of user funds and data. ScaleBit is committed to providing security solutions for Web3 Mass Adoption and being a trusted partner in ensuring the security of protocols and smart contracts. Through rigorous review and testing, ScaleBit offers in-depth insights into potential threats to ensure that users in the opBNB ecosystem can confidently use this innovative ecosystem.

Reference

[1] https://community.optimism.io/docs/developers/bedrock/

[2] https://bscscan.com/address/0x39bea96e13453ed52a734b6aceed4c41f57b2271?ref=binance.ghost.io#analytics

[3] https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable2Step.sol

[4] https://docs.bnbchain.org/opbnb-docs/docs/intro

[5] https://docs.bnbchain.org/opbnb-docs/docs/core-concepts/need-for-opbnb

[6] https://github.com/arunimshukla/Best-DeFi-Security-Practices

About ScaleBit

ScaleBit is a blockchain security team that provides security solutions for Mass Adoption of Web3. With expertise in scaling technologies like blockchain interoperability and zero-knowledge proofs, we provide meticulous and cutting-edge security audits for blockchain applications. The team comprises security professionals with extensive experience in both academia and enterprise. Our mission is to provide security solutions for Web3 Mass Adoption and make security accessible for all.

OLDER > < NEWER