Ethereum is Too Slow and Expensive? ETH Layer2 Scaling Solution and Audit Guide

Intermediate9/24/2024, 1:08:33 PM
ETH Layer2 uses Rollups to package hundreds of transactions into one submission to the Ethereum mainnet, thereby the transaction fees will be divided to all Rollup users, reducing fees per user. Transaction data in the Rollups is submitted to Layer1, but executions are carried out independently by the Rollups. By submitting transaction data to Layer1, Rollups can inherit the security of Ethereum because once the data is uploaded to Layer1, rolling back Rollups transactions requires the data to be rolled back on Layer1.

The three core attributes of blockchain are decentralization, security, and scalability. According to a blockchain trilemma theory, a blockchain architecture can only implement two of these. Ethereum was designed with decentralization and security in mind and therefore performs poorly in terms of scalability. Currently, Ethereum processes more than 1 million transactions per day, which can lead to high transaction fees and increases the need for Ethereum’s scaling solutions.

There are several different types of Ethereum scaling solutions, each with its own trade-offs and security models, including Layer 1 sharding, Layer 2 state channels, Plasma, sidechains, Rollups and Validium. Because sharding technology is slow to evolve and complex to implement and sidechains and Validium can’t inherit security and data availability from Ethereum. In summary, the Ethereum ecosystem now mainly uses the Rollups scaling solution.

So far Beosin has become a security partner of ETH Layer2 such as Manta Netowork and StarkNet. In the past audit, a number of well-known blockchains have passed Beosin’s chain security audit, including Ronin Network, Manta Network, Merlin Chain, Clover, Self Chain, Crust Network, etc. Beosin now releases an audit solution for ETH Layer2 to provide comprehensive security audit services for ETH Layer2 ecosystem.

ETH Layer2 uses Rollups to package hundreds of transactions into one submission to the Ethereum mainnet, thereby the transaction fees will be divided to all Rollup users, reducing fees per user. Transaction data in the Rollups is submitted to Layer1, but executions are carried out independently by the Rollups. By submitting transaction data to Layer1, Rollups can inherit the security of Ethereum because once the data is uploaded to Layer1, rolling back Rollups transactions requires the data to be rolled back on Layer1.

Currently, Rollups can be implemented in two main ways:

Optimistic Rollups: Use economic incentives and game theory to verify transactions, such as Arbitrum, Base, OP, Blast, etc.

Zero-Knowledge Rollups: Use zero-knowledge proofs for security and privacy, such as Scroll, Linea, zkSync, StarkNet, etc.

Optimistic Rollups

Intro

Optimistic Rollups is a way to scale Ethereum by moving computation and state storage off-chain. It executes transactions off-chain, but publish the transaction data to the mainnet as calldata or blob.

Optimistic Rollups deploy a smart contract on Ethereum, called the Rollup contract, which manages the Rollup’s status, tracks user balances, and handles deposits, withdrawals, and dispute resolution. Transactions are collected and summarized off-chain by a sequencer and multiple transactions are bundled into a Rollup block that contains a summary and cryptographic proof of the new account state (Merkle root). The sequencer then commits the Rollup block to the main chain by providing Merkle roots and calldata.

Optimistic Rollups are considered “optimistic” because they assume that off-chain transactions are valid and do not publish proof of the validity of the transaction batches pushed on-chain. Optimistic Rollups, by contrast, relies on fraud proof schemes to detect cases where transactions are incorrectly calculated. After submitting a Rollup batch on Ethereum, there is a window of time (called the challenge period) during which anyone can challenge the results of a Rollup transaction by calculating proof of fraud. The proof of fraud contains details of a particular transaction that the verifier believes to be fraudulent.

As shown in the figure below, the challenge period of most Optimistic Rollups at present is 7 days, and the shortest one is 1 day.

During the challenge period, anyone can challenge the transaction results by calculating proof of fraud. If the transaction is invalid, the Rollup block is revoked, the challenger is rewarded, and the sequencer is punished.

If the Rollup batch remains unchallenged after the challenge period (i.e. all transactions have been executed correctly), it is considered valid and accepted on Ethereum. Others can continue to expand unconfirmed Rollup blocks, but note that the transaction results will be reversed if the transaction is executed based on a previously published error.

Finally, the user must submit a withdrawal request to the Rollup contract to withdraw funds from Layer 2 to Layer 1. The contract will verify that the user has sufficient funds on the Rollup and update their balance on the mainchain accordingly.

Leading Layer2 Networks

  1. Arbitrum

With ecological construction and airdrops, Arbitrum quickly became the most active network in ETH Layer2, with TVL exceeding $2.7 billion. After the grand airdrop, the Arbitrum team launched the Arbitrum Orbit program: encouraging developers to build Layer3 using Arbitrum related technologies. Beosin has completed the security audit of ArbSwap, Arbipad to help the security development of Arbitrum ecosystem.

  1. Optimism

Although Optimism is less ecologically active than Arbitrum, OP Stack, launched by Optimism in 2023, has gained widespread industry recognition as a complete and viable solution for building modular Layer2. More than 25 Layer2 networks have been built using OP Stack, including star projects such as Base, Mantle, Manta, OP BNB, and Celo. DIPX Finance and Starnet built on Optimism have passed the security audit of Beosin.

  1. Base

Base is a Layer2 network based on OP Stack, which is second only to Arbitrum in terms of ecological activity and TVL. Previously, Beosin has analyzed Base’s architecture and security risks in detail, and audited Surf Protocol and EDA to help project owners and users avoid security risks.

  1. Blast

Blast, at the end of its “Big Bang” developer competition, has seen its TVL soar to over $2 billion, taking its place on the Layer2 circuit. Beosin analyzed Blast’s network security prior to its mainnet launch. Because Blast does not implement fraud proof, assets are held in a multi-signature wallet, not a Rollup bridge, which has a high degree of centralization risk. Beosin has audited several Blast ecological projects such as Wand Protocol, Zest, Kalax.

Architecture Analysis

OP Stack, a mature framework for Optimistic Rollups, basically breaks down the complex process of building optimistic Rollups chains into a simplified process by providing a complete set of software components, tools, and frameworks. Here we take the Op stack framework as an example to analyze the typical architecture of Optimism Rollups.

● Execution node: Op-geth is an extended execution client for Ethereum that handles Layer2-specific functions, such as receiving token deposits from Layer1. This layer defines all the functions responsible for performing state variations. Here, state transitions are triggered based on input received from the summary nodes (sequences and validators) through the engine API.

● Rollup node: includes sequencer and validator. The collator is responsible for batching the processed transactions from layer 2 and publishing them to Layer1. The sequencer defines how transactions on the Layer2 chain are collected and published. The validator/validator checks the validity of the batch transaction and submits evidence if any fraud is detected.

● Fraud Proof: Cannon is an upgraded version of Geth and is responsible for running EVM during the fraud detection and proof phase. It is essentially an on-chain dispute engine that coordinates with sequentiers and validators via apis to prove false transactions.

● Batch commit: Sequencers batch process all processed transactions at once, verified by the verifiers, and Sequencers submit the batch processed transactions to Layer1.

● Bridge contracts: Deployed on Ethereum and Layer2, allowing users to pass messages and transfer assets between Layer1 and Layer2.

Under Optimistic Rollup’s technical architecture, it is essential to ensure the security of user assets as they move between L1 and L2. The following details how users can access assets between the two layers and how the system maintains the integrity and security of these transactions.

● Asset bridging into Rollup: Users deposit funds into Rollup’s chain bridge contract on Layer1. The chain bridge contract relays the transaction to Layer2, where an equal amount of assets is minted and sent to an address selected by the user in the Optimistic Rollup.

User-generated transactions, such as deposits from Layer1 to Layer2, are typically queued until the sequester resubmits them to the Rollup contract. However, in order to maintain censorship resistance, Optimistic Rollup allows users to submit transactions directly to on-chain Rollup contracts if transaction delays exceed the maximum allowed time.

● Withdrawing assets from Rollup: Due to the fraud proof mechanism, withdrawing money from Optimistic Rollup to Ethereum is more complicated. If a user initiates a Layer2 to Layer1 transaction to withdraw funds managed on Layer1, they need to wait for the end of the challenge period, which typically lasts about 7 days.

When the user initiates a withdrawal request on Rollup, the transaction is included in the next batch and the user’s assets on Rollup are destroyed. Once the batch is published on Ethereum, users can calculate a Merkle proof to verify that their exit transaction is included in the block. The next step is to wait for the delay period to end to complete the transaction on Layer1 and withdraw the funds to the mainnet.

To avoid waiting a week before withdrawing money from Ethereum, Optimistic Rollup’s users can request an advance from a liquidity provider (LP), which assumes ownership of pending withdrawals and pays the user funds on Layer1 in exchange for a fee. Liquidity providers can verify the validity of user withdrawal requests by checking on-chain data themselves before releasing funds. In this way, they can ensure that the transaction will eventually be confirmed, achieving the certainty of trust.

Audit Items

Layer2 is a complete blockchain system, so the common audit of public chains also applies to Optimistic Rollup, as detailed in the appendix at the end of this article.

In addition, due to its special nature, Optimistic Rollup requires a number of additional audits:

● Proof of data availability: Ensure that Layer2 transaction data is available on Layer1 to prevent data loss.

● Data synchronization mechanism: Check whether the data synchronization mechanism between Layer1 and Layer2 is sound and can handle abnormal situations such as network partitioning.

● Fraud Proof Contract: Verify that the fraud proof contract is implemented correctly.

● Challenge period mechanism: Check whether the length of the challenge period is reasonable and whether the fraud proof can be completed within the specified time.

● Proof of fraud submission process: Check that the process for submitting proof of fraud is secure.

● Deposit and withdrawal process: Check the deposit and withdrawal process from Layer1 to Layer2 and from Layer2 to Layer1 to ensure the process is safe.

● Asset minting and burning: Check the casting and destruction logic of the asset on Layer2 to ensure the correct correspondence with the Layer1 asset.

● Liquidity provider mechanism: If there is a liquidity provider (LP) mechanism, it is necessary to examine the operating process of the LP and its security.

Zero-Knowledge Rollups

Intro

Zero-Knowledge (ZK) Rollup is Layer2 based on zero-knowledge proof. It mainly performs complex calculation and generation of proof off-chain, verifies proof on-chain and stores part of data to ensure data availability.

ZK Rollup is a “hybrid scaling solution” that is an off-chain protocol that runs independently but gets security from Ethereum. Specifically, the Ethereum network enforces the validity of status updates on the ZK Rollups and guarantees the availability of background data each time the Rollup status is updated. The state of Rollup is maintained by smart contracts deployed on the Ethereum network. In order to update this status, the ZK Rollups node must submit a proof of validity for verification. A proof of validity is a cryptographic guarantee that a proposed change in state is indeed the result of executing a given batch of transactions. This means that ZK Rollups only needs to provide proof of validity to finalize transactions on Ethereum, without having to publish all transaction data.

There is no delay in transferring funds from ZK Rollups to Ethereum, as the exit transaction is executed once the ZK Rollups contract has verified the proof of validity. In contrast, withdrawing funds from Optimistic Rollups creates delays because anyone can use proof of fraud to challenge an exit transaction.

Leading Layer2 Networks

  1. zkSync

zkSync, an L2 solution launched five years ago by the Matter Labs team, uses zero-knowledge proof technology to enable efficient transaction verification and has raised more than $200 million. zkSync is one of the most ecologically active Layer2 networks using ZK Rollups, and zkSync is also controversial. Beosin previously conducted an audit of its leading DeFi project, SyncSwap, covering code quality, contract logic and security, operational model, and more.

  1. StarkNet

StarkNet uses ZK-STARK to build Layer2 to increase transaction speed and reduce transaction fees. StarkNet has a native virtual machine (Cairo VM) and development language Cairo to help developers write smart contracts more securely and easily. Beosin has become an official security partner of StarkNet, completing security audits for Option Dance and Reddio. On August 13, 2024, Reddio closed a seed funding round led by Paradigm to build a high-performance parallel EVM Layer2 network.

  1. Scroll

Scroll is scaled by zero-knowledge proof technology, and hardware accelerates the generation and verification of zero-knowledge proofs, aiming to achieve bytecode level EVM compatibility. This means that developers can directly use Solidity and Ethereum related development tools to build smart contracts.

Architecture Analysis

Common frameworks for ZK Rollups include Rollup and Bridge contracts, collators, aggregators, Repeaters, and Roller networks that generate zero-knowledge proofs. The specific architecture is shown in the following figure:

● Rollup Contract and Bridge contract:

The Rollup contract is responsible for providing data availability for Rollup transactions, verifying zkEVM proof of validity, and allowing users to transfer assets between Ethereum and Rollup. It receives the Layer 2 state root and block from the collator, the state root is stored in the Ethereum state, and the layer 2 block data is saved as the calldata of Ethereum.

Bridge contracts are deployed on Ethereum and Layer2, allowing users to pass messages and transfer assets between Layer1 and Layer2.

● Sequencer: The sequencer provides the JSON-RPC interface and accepts Layer2 transactions, periodically retrieves a batch of transactions from the memory pool for execution, generating new Layer2 blocks and state roots. Its implementation is usually based on Go-Ethereum (Geth), ensuring the best compatibility and highest security.

● Coordinator: The coordinator is notified when the collator generates a new block and receives an execution trace of that block from the collator. The execution trace is then dispatched to a randomly selected Roller in the Roller network, which generates a proof of validity.

● Relayer: The repeater monitors Rollup contracts and bridge contracts deployed on Ethereum and Layer2. The main responsibilities are :1) Tracking data availability and validation of Layer2 blocks by monitoring Rollup contracts; 2) Monitor deposit and withdrawal events of Ethereum and Layer2 bridge engagement and relay messages to the other end.

● Roller Network: Roller in the Roller network acts as the prover and is responsible for generating proof of validity for ZK Rollup. A block execution trace is first received from the coordinator, converted to a circuit witness, then a proof is generated for each zkevm using hardware acceleration, and finally a proof aggregation is used to aggregate multiple proofs into a single proof.

Under the technical architecture of ZK Rollups, it is essential to ensure the security of user assets during the transfer between L1 and L2. The following details how users can access assets between the two layers and how the system maintains the integrity and security of these transactions.

● Asset bridging into Rollup: Users enter the Rollup by deposting tokens into a ZK Rollups contract deployed on a layer of network chain. This transaction needs to be submitted to the Rollup contract by the project side.

If the pending deposit queue starts to fill up, the ZK Rollups operator will accept these deposit transactions and submit them to the Rollup contract. Once the funds are deposited in Rollup, the user can begin transaction processing.

Users can verify the balance on Rollup by hashing their account, sending the hash value to the Rollup contract and providing a Merkle proof that verifies against the current state root.

● Assets withdrawal from Rollup: The user initiates an exit transaction, sending the assets on their Rollup to the specified account for destruction. If the operator adds the transaction to the next batch, the user can submit a withdrawal request to the on-chain contract. Withdrawal requests include:

  1. Merkle proof, which proves that the user’s transaction is added to the destroyed account in the transaction batch

  2. Transaction data

  3. Batch the root

  4. Layer1 network address for receiving deposited funds

The Rollup contract hashes the transaction data, checks if the batch root exists, and uses Merkle proof to check if the transaction hash is part of the batch root. The contract executes the exit transaction and sends funds to an address on the Layer1 network selected by the user.

Audit Items

Layer 2 is a complete blockchain system, so common audit items for blockchains also apply to ZK Rollup, as detailed in the appendix at the end of this article.

In addition, due to its special nature, ZK Rollup is required to perform some additional audits:

● Proof of system security: Check the safety and correctness of the zero-knowledge proof schemes used (e.g. Groth16, Plonk, Halo2, zk-STARK, etc.).

● Circuit safety: Check for possible vulnerabilities in circuit design and implementation, mainly including the following:

  1. Under-constrained Circuits

  2. Over-constrained Circuits

  3. Nondeterministic Circuits

  4. Arithmetic Over/Under Flows Arithmetic over/under flows

  5. Mismatching Bit Lengths

  6. Unused Public Inputs Optimized Out

  7. Frozen Heart: Forging of Zero Knowledge Proofs

  8. Trusted Setup Leak

  9. Assigned but not Constrained

  10. Unsafe Component Usage

  11. Variable Precision

● Proof generation and validation: Review the process for proof generation and validation to ensure it is efficient and secure.

● Proof of data availability: Ensure that Layer2 transaction data is available on Layer1 to prevent data loss.

● Data synchronization mechanism: Check whether the data synchronization mechanism between Layer1 and Layer2 is sound and can handle abnormal situations such as network partitioning.

● Deposit and withdrawal process: Check the deposit and withdrawal process from Layer1 to Layer2 and from Layer2 to Layer1 to ensure the process is safe.

● Asset minting and burning: Check the casting and destruction logic of the asset on Layer2 to ensure the correct correspondence with the Layer1 asset.

● Scanning for external dependencies and known vulnerabilities: ZK Rollup often relies heavily on cryptographic and mathematical repositories or tools of third parties and should thoroughly check their dependency security for scanning and validation of known vulnerabilities.

Appendix

Blockchain & Layer2 General Audit items:

● Integer overflow: Check integer overflows and integer underflows

● Loop: Check the loop of the program to see if the condition is reasonable

● Infinite recursive call: Check whether the exit condition of the program recursive call is reasonable

● Race condition: Checks the access to shared resources in concurrent state

● Exception crash: Check for exception throwing code that causes the program to actively exit

● Divide by 0 vulnerability: Check whether there is a case of dividing by 0

● Type conversion: Check whether the type conversion is correct and whether important information is lost during the conversion

● Array out of bounds: Checks for access to elements outside the array bounds

● Deserialization vulnerability: Check for problems during deserialization

● Function implementation security: Check whether the implementation of RPC interfaces has security risks and is consistent with the functional design of RPC interfaces

● Whether the permission Settings of the sensitive RPC interface are reasonable: Check the access permission Settings of the sensitive RPC interface

● Encrypted transmission mechanism: Check whether an encrypted transmission protocol, such as TLS, is used

● Request data format parsing: Checks the format parsing process for request data

● Wallet unlock attack: When a node unlocks its wallet, it is asked by RPC to steal funds

● Traditional Web security: Check for the following vulnerabilities: Cross-site scripting (XSS)/template injection/third-party component vulnerability/HTTP parameter contamination/SQL injection/XXE entity injection/deserialization vulnerability/SSRF vulnerability/Code injection/local file inclusion/Remote file inclusion/command execution injection and other traditional vulnerabilities

● Network node identity authentication and identification mechanism: check whether there is a node identity identification mechanism, node identity identification mechanism can be circumvented

● Routing table contamination: Check whether the routing table can be inserted or overwritten arbitrarily

● Node discovery algorithm: Check whether the node discovery algorithm is balanced and unpredictable, for example, the distance algorithm is unbalanced

● Connection Usage audit: Check whether the limit and management of the number of nodes connected to the p2p network are reasonable

● Solar Eclipse Attacks: Assess the costs and hazards of solar eclipse attacks, providing quantitative analysis if necessary

● Sybil Attack: Evaluating voting consensus mechanisms and analyzing voting eligibility check strategies

● Eavesdropping attack: Check whether the communication protocol discloses privacy

● Alien attack: Evaluates whether the node can recognize the same type of chain node

● Time hijacking: Check the network time calculation mechanism of a node

● Memory exhaustion attack: Check for large memory consumption

● Hard drive exhaustion attack: Check where large files are stored

● socket pressure attack: Check the limit policy on the number of links

● Kernel handle exhaustion attack: Check for limitations on kernel handle creation, such as file handles

● Persistent memory leaks: Check for memory leaks

● Hash algorithm security: Check the collision resistance of the hash algorithm

● Digital signature algorithm security: Check the security of the signature algorithm and algorithm implementation

● Encryption algorithm security: Check the security of the encryption algorithm and algorithm implementation

● Random number generator security: Check whether the key random number generation algorithm is reasonable

● BFT implementation security: Evaluate the implementation security of BFT algorithms

● Fork selection rules: Check fork selection rules to ensure security

● Centralization degree test: Identify whether there is an overly centralized design in the system design

● Incentive audit: Assess the impact of incentives on security

● Double-spending attacks: Check whether consensus can defend against double-spending attacks

● MEV Attack audit: Examine the impact of the MEV of the block package node on chain fairness

● Block synchronization process audit: Checks for security issues during synchronization

● Block format parsing process audit: Checks for security issues during format parsing, such as parsing errors that cause crashes

● Block generation Process audit: Check security issues in the block generation process, including whether the Merkle tree root is built in a reasonable way

● Block verification process audit: Check whether block signature items and verification logic are sufficient

● Block validation logic audit: Check whether the block validation algorithm and implementation are reasonable

● Block hash collision: Check how the block hash collision is constructed and whether the collision is handled reasonably

● Block processing resource limits: Check whether orphan block pools, verification computing, hard disk addressing, and other resource limits are reasonable

● Transaction synchronization process audit: Checks for security issues in the synchronization process

● Transaction hash collisions: Examine how transaction hash collisions are constructed and how they are handled

● Transaction format parsing: Check for security issues during format parsing, such as parsing errors that cause crashes

● Transaction validity check: Check whether the signature items of each type of transaction and the verification logic are sufficient

● Transaction processing resource limits: Check whether resource limits such as transaction pools, verification computing, and hard disk addressing are reasonable

● Transaction malleability attack: Whether a transaction can change internal fields (such as ScriptSig) to change the transaction hash without affecting the validity of the transaction

● Transaction replay attack audit: Checks the system’s detection of transaction replay

● Contract bytecode check: Check the security of the contract verification process of the virtual machine, such as integer overflow and dead loops

● Contract bytecode execution: Check the security of the bytecode execution process of the virtual machine, such as integer overflow, dead loops, and so on

● Gas model: Check that the fees for each atomic operation of the transaction processing/contract execution are proportional to the resource consumption

● Log integrity: Check whether key information is logged

● Log security: Check whether improper handling of logs causes security problems, such as integer overflow

● Logs contain privacy information: Check whether logs contain privacy information such as keys

● Log storage: Check whether excessive content is recorded in logs, which consumes node resources

● Node code Supply chain security: Check all third-party libraries, components, and versions of public chain frameworks for known issues

Disclaimer:

  1. This article is reprinted from [beosin]. All copyrights belong to the original author [beosin]. If there are objections to this reprint, please contact the Gate Learn team, and they will handle it promptly.
  2. Liability Disclaimer: The views and opinions expressed in this article are solely those of the author and do not constitute any investment advice.
  3. Translations of the article into other languages are done by the Gate Learn team. Unless mentioned, copying, distributing, or plagiarizing the translated articles is prohibited.

Ethereum is Too Slow and Expensive? ETH Layer2 Scaling Solution and Audit Guide

Intermediate9/24/2024, 1:08:33 PM
ETH Layer2 uses Rollups to package hundreds of transactions into one submission to the Ethereum mainnet, thereby the transaction fees will be divided to all Rollup users, reducing fees per user. Transaction data in the Rollups is submitted to Layer1, but executions are carried out independently by the Rollups. By submitting transaction data to Layer1, Rollups can inherit the security of Ethereum because once the data is uploaded to Layer1, rolling back Rollups transactions requires the data to be rolled back on Layer1.

The three core attributes of blockchain are decentralization, security, and scalability. According to a blockchain trilemma theory, a blockchain architecture can only implement two of these. Ethereum was designed with decentralization and security in mind and therefore performs poorly in terms of scalability. Currently, Ethereum processes more than 1 million transactions per day, which can lead to high transaction fees and increases the need for Ethereum’s scaling solutions.

There are several different types of Ethereum scaling solutions, each with its own trade-offs and security models, including Layer 1 sharding, Layer 2 state channels, Plasma, sidechains, Rollups and Validium. Because sharding technology is slow to evolve and complex to implement and sidechains and Validium can’t inherit security and data availability from Ethereum. In summary, the Ethereum ecosystem now mainly uses the Rollups scaling solution.

So far Beosin has become a security partner of ETH Layer2 such as Manta Netowork and StarkNet. In the past audit, a number of well-known blockchains have passed Beosin’s chain security audit, including Ronin Network, Manta Network, Merlin Chain, Clover, Self Chain, Crust Network, etc. Beosin now releases an audit solution for ETH Layer2 to provide comprehensive security audit services for ETH Layer2 ecosystem.

ETH Layer2 uses Rollups to package hundreds of transactions into one submission to the Ethereum mainnet, thereby the transaction fees will be divided to all Rollup users, reducing fees per user. Transaction data in the Rollups is submitted to Layer1, but executions are carried out independently by the Rollups. By submitting transaction data to Layer1, Rollups can inherit the security of Ethereum because once the data is uploaded to Layer1, rolling back Rollups transactions requires the data to be rolled back on Layer1.

Currently, Rollups can be implemented in two main ways:

Optimistic Rollups: Use economic incentives and game theory to verify transactions, such as Arbitrum, Base, OP, Blast, etc.

Zero-Knowledge Rollups: Use zero-knowledge proofs for security and privacy, such as Scroll, Linea, zkSync, StarkNet, etc.

Optimistic Rollups

Intro

Optimistic Rollups is a way to scale Ethereum by moving computation and state storage off-chain. It executes transactions off-chain, but publish the transaction data to the mainnet as calldata or blob.

Optimistic Rollups deploy a smart contract on Ethereum, called the Rollup contract, which manages the Rollup’s status, tracks user balances, and handles deposits, withdrawals, and dispute resolution. Transactions are collected and summarized off-chain by a sequencer and multiple transactions are bundled into a Rollup block that contains a summary and cryptographic proof of the new account state (Merkle root). The sequencer then commits the Rollup block to the main chain by providing Merkle roots and calldata.

Optimistic Rollups are considered “optimistic” because they assume that off-chain transactions are valid and do not publish proof of the validity of the transaction batches pushed on-chain. Optimistic Rollups, by contrast, relies on fraud proof schemes to detect cases where transactions are incorrectly calculated. After submitting a Rollup batch on Ethereum, there is a window of time (called the challenge period) during which anyone can challenge the results of a Rollup transaction by calculating proof of fraud. The proof of fraud contains details of a particular transaction that the verifier believes to be fraudulent.

As shown in the figure below, the challenge period of most Optimistic Rollups at present is 7 days, and the shortest one is 1 day.

During the challenge period, anyone can challenge the transaction results by calculating proof of fraud. If the transaction is invalid, the Rollup block is revoked, the challenger is rewarded, and the sequencer is punished.

If the Rollup batch remains unchallenged after the challenge period (i.e. all transactions have been executed correctly), it is considered valid and accepted on Ethereum. Others can continue to expand unconfirmed Rollup blocks, but note that the transaction results will be reversed if the transaction is executed based on a previously published error.

Finally, the user must submit a withdrawal request to the Rollup contract to withdraw funds from Layer 2 to Layer 1. The contract will verify that the user has sufficient funds on the Rollup and update their balance on the mainchain accordingly.

Leading Layer2 Networks

  1. Arbitrum

With ecological construction and airdrops, Arbitrum quickly became the most active network in ETH Layer2, with TVL exceeding $2.7 billion. After the grand airdrop, the Arbitrum team launched the Arbitrum Orbit program: encouraging developers to build Layer3 using Arbitrum related technologies. Beosin has completed the security audit of ArbSwap, Arbipad to help the security development of Arbitrum ecosystem.

  1. Optimism

Although Optimism is less ecologically active than Arbitrum, OP Stack, launched by Optimism in 2023, has gained widespread industry recognition as a complete and viable solution for building modular Layer2. More than 25 Layer2 networks have been built using OP Stack, including star projects such as Base, Mantle, Manta, OP BNB, and Celo. DIPX Finance and Starnet built on Optimism have passed the security audit of Beosin.

  1. Base

Base is a Layer2 network based on OP Stack, which is second only to Arbitrum in terms of ecological activity and TVL. Previously, Beosin has analyzed Base’s architecture and security risks in detail, and audited Surf Protocol and EDA to help project owners and users avoid security risks.

  1. Blast

Blast, at the end of its “Big Bang” developer competition, has seen its TVL soar to over $2 billion, taking its place on the Layer2 circuit. Beosin analyzed Blast’s network security prior to its mainnet launch. Because Blast does not implement fraud proof, assets are held in a multi-signature wallet, not a Rollup bridge, which has a high degree of centralization risk. Beosin has audited several Blast ecological projects such as Wand Protocol, Zest, Kalax.

Architecture Analysis

OP Stack, a mature framework for Optimistic Rollups, basically breaks down the complex process of building optimistic Rollups chains into a simplified process by providing a complete set of software components, tools, and frameworks. Here we take the Op stack framework as an example to analyze the typical architecture of Optimism Rollups.

● Execution node: Op-geth is an extended execution client for Ethereum that handles Layer2-specific functions, such as receiving token deposits from Layer1. This layer defines all the functions responsible for performing state variations. Here, state transitions are triggered based on input received from the summary nodes (sequences and validators) through the engine API.

● Rollup node: includes sequencer and validator. The collator is responsible for batching the processed transactions from layer 2 and publishing them to Layer1. The sequencer defines how transactions on the Layer2 chain are collected and published. The validator/validator checks the validity of the batch transaction and submits evidence if any fraud is detected.

● Fraud Proof: Cannon is an upgraded version of Geth and is responsible for running EVM during the fraud detection and proof phase. It is essentially an on-chain dispute engine that coordinates with sequentiers and validators via apis to prove false transactions.

● Batch commit: Sequencers batch process all processed transactions at once, verified by the verifiers, and Sequencers submit the batch processed transactions to Layer1.

● Bridge contracts: Deployed on Ethereum and Layer2, allowing users to pass messages and transfer assets between Layer1 and Layer2.

Under Optimistic Rollup’s technical architecture, it is essential to ensure the security of user assets as they move between L1 and L2. The following details how users can access assets between the two layers and how the system maintains the integrity and security of these transactions.

● Asset bridging into Rollup: Users deposit funds into Rollup’s chain bridge contract on Layer1. The chain bridge contract relays the transaction to Layer2, where an equal amount of assets is minted and sent to an address selected by the user in the Optimistic Rollup.

User-generated transactions, such as deposits from Layer1 to Layer2, are typically queued until the sequester resubmits them to the Rollup contract. However, in order to maintain censorship resistance, Optimistic Rollup allows users to submit transactions directly to on-chain Rollup contracts if transaction delays exceed the maximum allowed time.

● Withdrawing assets from Rollup: Due to the fraud proof mechanism, withdrawing money from Optimistic Rollup to Ethereum is more complicated. If a user initiates a Layer2 to Layer1 transaction to withdraw funds managed on Layer1, they need to wait for the end of the challenge period, which typically lasts about 7 days.

When the user initiates a withdrawal request on Rollup, the transaction is included in the next batch and the user’s assets on Rollup are destroyed. Once the batch is published on Ethereum, users can calculate a Merkle proof to verify that their exit transaction is included in the block. The next step is to wait for the delay period to end to complete the transaction on Layer1 and withdraw the funds to the mainnet.

To avoid waiting a week before withdrawing money from Ethereum, Optimistic Rollup’s users can request an advance from a liquidity provider (LP), which assumes ownership of pending withdrawals and pays the user funds on Layer1 in exchange for a fee. Liquidity providers can verify the validity of user withdrawal requests by checking on-chain data themselves before releasing funds. In this way, they can ensure that the transaction will eventually be confirmed, achieving the certainty of trust.

Audit Items

Layer2 is a complete blockchain system, so the common audit of public chains also applies to Optimistic Rollup, as detailed in the appendix at the end of this article.

In addition, due to its special nature, Optimistic Rollup requires a number of additional audits:

● Proof of data availability: Ensure that Layer2 transaction data is available on Layer1 to prevent data loss.

● Data synchronization mechanism: Check whether the data synchronization mechanism between Layer1 and Layer2 is sound and can handle abnormal situations such as network partitioning.

● Fraud Proof Contract: Verify that the fraud proof contract is implemented correctly.

● Challenge period mechanism: Check whether the length of the challenge period is reasonable and whether the fraud proof can be completed within the specified time.

● Proof of fraud submission process: Check that the process for submitting proof of fraud is secure.

● Deposit and withdrawal process: Check the deposit and withdrawal process from Layer1 to Layer2 and from Layer2 to Layer1 to ensure the process is safe.

● Asset minting and burning: Check the casting and destruction logic of the asset on Layer2 to ensure the correct correspondence with the Layer1 asset.

● Liquidity provider mechanism: If there is a liquidity provider (LP) mechanism, it is necessary to examine the operating process of the LP and its security.

Zero-Knowledge Rollups

Intro

Zero-Knowledge (ZK) Rollup is Layer2 based on zero-knowledge proof. It mainly performs complex calculation and generation of proof off-chain, verifies proof on-chain and stores part of data to ensure data availability.

ZK Rollup is a “hybrid scaling solution” that is an off-chain protocol that runs independently but gets security from Ethereum. Specifically, the Ethereum network enforces the validity of status updates on the ZK Rollups and guarantees the availability of background data each time the Rollup status is updated. The state of Rollup is maintained by smart contracts deployed on the Ethereum network. In order to update this status, the ZK Rollups node must submit a proof of validity for verification. A proof of validity is a cryptographic guarantee that a proposed change in state is indeed the result of executing a given batch of transactions. This means that ZK Rollups only needs to provide proof of validity to finalize transactions on Ethereum, without having to publish all transaction data.

There is no delay in transferring funds from ZK Rollups to Ethereum, as the exit transaction is executed once the ZK Rollups contract has verified the proof of validity. In contrast, withdrawing funds from Optimistic Rollups creates delays because anyone can use proof of fraud to challenge an exit transaction.

Leading Layer2 Networks

  1. zkSync

zkSync, an L2 solution launched five years ago by the Matter Labs team, uses zero-knowledge proof technology to enable efficient transaction verification and has raised more than $200 million. zkSync is one of the most ecologically active Layer2 networks using ZK Rollups, and zkSync is also controversial. Beosin previously conducted an audit of its leading DeFi project, SyncSwap, covering code quality, contract logic and security, operational model, and more.

  1. StarkNet

StarkNet uses ZK-STARK to build Layer2 to increase transaction speed and reduce transaction fees. StarkNet has a native virtual machine (Cairo VM) and development language Cairo to help developers write smart contracts more securely and easily. Beosin has become an official security partner of StarkNet, completing security audits for Option Dance and Reddio. On August 13, 2024, Reddio closed a seed funding round led by Paradigm to build a high-performance parallel EVM Layer2 network.

  1. Scroll

Scroll is scaled by zero-knowledge proof technology, and hardware accelerates the generation and verification of zero-knowledge proofs, aiming to achieve bytecode level EVM compatibility. This means that developers can directly use Solidity and Ethereum related development tools to build smart contracts.

Architecture Analysis

Common frameworks for ZK Rollups include Rollup and Bridge contracts, collators, aggregators, Repeaters, and Roller networks that generate zero-knowledge proofs. The specific architecture is shown in the following figure:

● Rollup Contract and Bridge contract:

The Rollup contract is responsible for providing data availability for Rollup transactions, verifying zkEVM proof of validity, and allowing users to transfer assets between Ethereum and Rollup. It receives the Layer 2 state root and block from the collator, the state root is stored in the Ethereum state, and the layer 2 block data is saved as the calldata of Ethereum.

Bridge contracts are deployed on Ethereum and Layer2, allowing users to pass messages and transfer assets between Layer1 and Layer2.

● Sequencer: The sequencer provides the JSON-RPC interface and accepts Layer2 transactions, periodically retrieves a batch of transactions from the memory pool for execution, generating new Layer2 blocks and state roots. Its implementation is usually based on Go-Ethereum (Geth), ensuring the best compatibility and highest security.

● Coordinator: The coordinator is notified when the collator generates a new block and receives an execution trace of that block from the collator. The execution trace is then dispatched to a randomly selected Roller in the Roller network, which generates a proof of validity.

● Relayer: The repeater monitors Rollup contracts and bridge contracts deployed on Ethereum and Layer2. The main responsibilities are :1) Tracking data availability and validation of Layer2 blocks by monitoring Rollup contracts; 2) Monitor deposit and withdrawal events of Ethereum and Layer2 bridge engagement and relay messages to the other end.

● Roller Network: Roller in the Roller network acts as the prover and is responsible for generating proof of validity for ZK Rollup. A block execution trace is first received from the coordinator, converted to a circuit witness, then a proof is generated for each zkevm using hardware acceleration, and finally a proof aggregation is used to aggregate multiple proofs into a single proof.

Under the technical architecture of ZK Rollups, it is essential to ensure the security of user assets during the transfer between L1 and L2. The following details how users can access assets between the two layers and how the system maintains the integrity and security of these transactions.

● Asset bridging into Rollup: Users enter the Rollup by deposting tokens into a ZK Rollups contract deployed on a layer of network chain. This transaction needs to be submitted to the Rollup contract by the project side.

If the pending deposit queue starts to fill up, the ZK Rollups operator will accept these deposit transactions and submit them to the Rollup contract. Once the funds are deposited in Rollup, the user can begin transaction processing.

Users can verify the balance on Rollup by hashing their account, sending the hash value to the Rollup contract and providing a Merkle proof that verifies against the current state root.

● Assets withdrawal from Rollup: The user initiates an exit transaction, sending the assets on their Rollup to the specified account for destruction. If the operator adds the transaction to the next batch, the user can submit a withdrawal request to the on-chain contract. Withdrawal requests include:

  1. Merkle proof, which proves that the user’s transaction is added to the destroyed account in the transaction batch

  2. Transaction data

  3. Batch the root

  4. Layer1 network address for receiving deposited funds

The Rollup contract hashes the transaction data, checks if the batch root exists, and uses Merkle proof to check if the transaction hash is part of the batch root. The contract executes the exit transaction and sends funds to an address on the Layer1 network selected by the user.

Audit Items

Layer 2 is a complete blockchain system, so common audit items for blockchains also apply to ZK Rollup, as detailed in the appendix at the end of this article.

In addition, due to its special nature, ZK Rollup is required to perform some additional audits:

● Proof of system security: Check the safety and correctness of the zero-knowledge proof schemes used (e.g. Groth16, Plonk, Halo2, zk-STARK, etc.).

● Circuit safety: Check for possible vulnerabilities in circuit design and implementation, mainly including the following:

  1. Under-constrained Circuits

  2. Over-constrained Circuits

  3. Nondeterministic Circuits

  4. Arithmetic Over/Under Flows Arithmetic over/under flows

  5. Mismatching Bit Lengths

  6. Unused Public Inputs Optimized Out

  7. Frozen Heart: Forging of Zero Knowledge Proofs

  8. Trusted Setup Leak

  9. Assigned but not Constrained

  10. Unsafe Component Usage

  11. Variable Precision

● Proof generation and validation: Review the process for proof generation and validation to ensure it is efficient and secure.

● Proof of data availability: Ensure that Layer2 transaction data is available on Layer1 to prevent data loss.

● Data synchronization mechanism: Check whether the data synchronization mechanism between Layer1 and Layer2 is sound and can handle abnormal situations such as network partitioning.

● Deposit and withdrawal process: Check the deposit and withdrawal process from Layer1 to Layer2 and from Layer2 to Layer1 to ensure the process is safe.

● Asset minting and burning: Check the casting and destruction logic of the asset on Layer2 to ensure the correct correspondence with the Layer1 asset.

● Scanning for external dependencies and known vulnerabilities: ZK Rollup often relies heavily on cryptographic and mathematical repositories or tools of third parties and should thoroughly check their dependency security for scanning and validation of known vulnerabilities.

Appendix

Blockchain & Layer2 General Audit items:

● Integer overflow: Check integer overflows and integer underflows

● Loop: Check the loop of the program to see if the condition is reasonable

● Infinite recursive call: Check whether the exit condition of the program recursive call is reasonable

● Race condition: Checks the access to shared resources in concurrent state

● Exception crash: Check for exception throwing code that causes the program to actively exit

● Divide by 0 vulnerability: Check whether there is a case of dividing by 0

● Type conversion: Check whether the type conversion is correct and whether important information is lost during the conversion

● Array out of bounds: Checks for access to elements outside the array bounds

● Deserialization vulnerability: Check for problems during deserialization

● Function implementation security: Check whether the implementation of RPC interfaces has security risks and is consistent with the functional design of RPC interfaces

● Whether the permission Settings of the sensitive RPC interface are reasonable: Check the access permission Settings of the sensitive RPC interface

● Encrypted transmission mechanism: Check whether an encrypted transmission protocol, such as TLS, is used

● Request data format parsing: Checks the format parsing process for request data

● Wallet unlock attack: When a node unlocks its wallet, it is asked by RPC to steal funds

● Traditional Web security: Check for the following vulnerabilities: Cross-site scripting (XSS)/template injection/third-party component vulnerability/HTTP parameter contamination/SQL injection/XXE entity injection/deserialization vulnerability/SSRF vulnerability/Code injection/local file inclusion/Remote file inclusion/command execution injection and other traditional vulnerabilities

● Network node identity authentication and identification mechanism: check whether there is a node identity identification mechanism, node identity identification mechanism can be circumvented

● Routing table contamination: Check whether the routing table can be inserted or overwritten arbitrarily

● Node discovery algorithm: Check whether the node discovery algorithm is balanced and unpredictable, for example, the distance algorithm is unbalanced

● Connection Usage audit: Check whether the limit and management of the number of nodes connected to the p2p network are reasonable

● Solar Eclipse Attacks: Assess the costs and hazards of solar eclipse attacks, providing quantitative analysis if necessary

● Sybil Attack: Evaluating voting consensus mechanisms and analyzing voting eligibility check strategies

● Eavesdropping attack: Check whether the communication protocol discloses privacy

● Alien attack: Evaluates whether the node can recognize the same type of chain node

● Time hijacking: Check the network time calculation mechanism of a node

● Memory exhaustion attack: Check for large memory consumption

● Hard drive exhaustion attack: Check where large files are stored

● socket pressure attack: Check the limit policy on the number of links

● Kernel handle exhaustion attack: Check for limitations on kernel handle creation, such as file handles

● Persistent memory leaks: Check for memory leaks

● Hash algorithm security: Check the collision resistance of the hash algorithm

● Digital signature algorithm security: Check the security of the signature algorithm and algorithm implementation

● Encryption algorithm security: Check the security of the encryption algorithm and algorithm implementation

● Random number generator security: Check whether the key random number generation algorithm is reasonable

● BFT implementation security: Evaluate the implementation security of BFT algorithms

● Fork selection rules: Check fork selection rules to ensure security

● Centralization degree test: Identify whether there is an overly centralized design in the system design

● Incentive audit: Assess the impact of incentives on security

● Double-spending attacks: Check whether consensus can defend against double-spending attacks

● MEV Attack audit: Examine the impact of the MEV of the block package node on chain fairness

● Block synchronization process audit: Checks for security issues during synchronization

● Block format parsing process audit: Checks for security issues during format parsing, such as parsing errors that cause crashes

● Block generation Process audit: Check security issues in the block generation process, including whether the Merkle tree root is built in a reasonable way

● Block verification process audit: Check whether block signature items and verification logic are sufficient

● Block validation logic audit: Check whether the block validation algorithm and implementation are reasonable

● Block hash collision: Check how the block hash collision is constructed and whether the collision is handled reasonably

● Block processing resource limits: Check whether orphan block pools, verification computing, hard disk addressing, and other resource limits are reasonable

● Transaction synchronization process audit: Checks for security issues in the synchronization process

● Transaction hash collisions: Examine how transaction hash collisions are constructed and how they are handled

● Transaction format parsing: Check for security issues during format parsing, such as parsing errors that cause crashes

● Transaction validity check: Check whether the signature items of each type of transaction and the verification logic are sufficient

● Transaction processing resource limits: Check whether resource limits such as transaction pools, verification computing, and hard disk addressing are reasonable

● Transaction malleability attack: Whether a transaction can change internal fields (such as ScriptSig) to change the transaction hash without affecting the validity of the transaction

● Transaction replay attack audit: Checks the system’s detection of transaction replay

● Contract bytecode check: Check the security of the contract verification process of the virtual machine, such as integer overflow and dead loops

● Contract bytecode execution: Check the security of the bytecode execution process of the virtual machine, such as integer overflow, dead loops, and so on

● Gas model: Check that the fees for each atomic operation of the transaction processing/contract execution are proportional to the resource consumption

● Log integrity: Check whether key information is logged

● Log security: Check whether improper handling of logs causes security problems, such as integer overflow

● Logs contain privacy information: Check whether logs contain privacy information such as keys

● Log storage: Check whether excessive content is recorded in logs, which consumes node resources

● Node code Supply chain security: Check all third-party libraries, components, and versions of public chain frameworks for known issues

Disclaimer:

  1. This article is reprinted from [beosin]. All copyrights belong to the original author [beosin]. If there are objections to this reprint, please contact the Gate Learn team, and they will handle it promptly.
  2. Liability Disclaimer: The views and opinions expressed in this article are solely those of the author and do not constitute any investment advice.
  3. Translations of the article into other languages are done by the Gate Learn team. Unless mentioned, copying, distributing, or plagiarizing the translated articles is prohibited.
Start Now
Sign up and get a
$100
Voucher!