Cross-Chain Security with LayerZero Labs

Overview

This article is a written breakdown of Ryan Zarick’s, CTO of LayerZero labs, seminar delivered at Spearbit. Ryan dives into building cross-chain with a security-first mindset.

LayerZero seeks to provide a solution to one of the most pressing issues that blockchain technology is facing today – interoperability. It is an interoperability protocol that uses a novel technique to make it easier for different blockchain networks to connect with each other. LayerZero is a user application (UA) configurable on-chain endpoint that runs a ULN and relies on two parties to transfer messages between on-chain endpoints: the oracle and the relayer.

Spearbit is an industry-leading distributed blockchain security services firm pairing protocols with top security researchers having deep subject matter expertise to identify vulnerabilities in an ever-evolving landscape and scale web3 security.

Video Seminar Link: https://youtu.be/ZR3y-aUyJNA

Understanding the Need for Cross-Chain Infrastructure

Cross-chain, Omni-chain, Multi-chain — no matter what term is used, they all refer to the same core concept: a method of communication and interoperability between different blockchain networks. But why is this necessary and how does it impact the overall functioning and evolution of blockchain-based applications? The answers lie in the very nature and dynamics of blockchain technology itself.

Importance of Composability in Blockchain

In the realm of smart contract-based applications on blockchains, composability is the most valuable asset. Composability allows applications to be built on each other, adding value to each other, a phenomenon often referred to as "All boats rise together". This implies that applications improve and become more powerful when they can interact and work in harmony with each other.

The Need for Diversity and Specialization

Over the past few years, it has become increasingly clear that a single blockchain cannot cater to the needs of every application. Various applications have differing requirements:

  • Some applications demand high throughput and low transaction costs.

  • Others prioritize high security and can afford to be indifferent to speed.

  • Some require a high degree of uptime.

These varying requirements result in applications and their respective user bases becoming fragmented across different blockchains.

Challenges with Fragmentation

With the fragmentation of applications across different blockchains, the value of composability often gets lost. This is because the applications are no longer able to interact with each other seamlessly, given the lack of intercommunication and interoperability between distinct blockchains.

Role of Cross-Chain Messaging

In this complex landscape, cross-chain messaging comes to the fore. It enables the reunification of these fragmented blockchains through a mechanism known as asynchronous composability. This process helps to counteract the fragmentation, bringing different ecosystems closer to each other.

Choosing the Right Cross-Chain Messaging Protocol

The Necessity of Caution

While the concept of cross-chain messaging provides promising solutions to many issues faced by blockchain ecosystems, it's crucial to proceed with caution. One may argue that any cross-chain messaging protocol could be selected, but this is far from the truth. The reality is that not all cross-chain messaging protocols are created equal, and making an uninformed decision could lead to substantial risks.

Stolen Funds and Security Breaches

A worrying statistic sheds light on this issue — in the past year alone, over two billion dollars, which accounts for sixty percent of all stolen funds, have been lost due to cross-chain bridge hacks. Some of these bridges have been compromised multiple times. This highlights the gravity of the risk associated with choosing the wrong cross-chain messaging protocol.

The Importance of Due Diligence

Selecting a cross-chain messaging protocol isn't a decision that should be made lightly. It entails a certain level of due diligence and understanding of the risk profiles associated with different protocols. As a developer building applications on blockchain, the task becomes even more complex when you consider the sheer number of protocols available — over 40 at the last count.

Key Considerations

When choosing a cross-chain messaging protocol, several important factors must be taken into consideration:

  • Security: Understand the security measures in place and the history of any potential breaches or vulnerabilities.

  • Reliability: Evaluate the protocol’s track record in terms of uptime and reliability.

  • Compatibility: Ensure that the protocol is compatible with your particular blockchain network and use case.

  • Community Support: A strong developer and user community can often signal a well-maintained and reliable protocol.

  • Performance: Consider the protocol's throughput, latency, and other performance metrics relevant to your application.

Considering Security in Cross-Chain Messaging

When deliberating on the security aspects of cross-chain messaging, there are three key risk factors that need to be taken into account. These are the diversity of clients, the risk associated with smart contract protocol upgrades, and the user application risk.

Client Diversity Risk

The first major risk stems from the diversity of clients. This refers to the different pieces of software that various networks use to move messages between chains. If all networks are running the same piece of software, it could pose a significant risk. If a vulnerability is found in this software, it could be exploited across all chains running that software, resulting in widespread damage. A diversity of clients can help mitigate this risk as it reduces the chances of a single point of failure.

Smart Contract Protocol Upgrade Risk

The second major risk factor is associated with upgrades to the smart contract protocol. If a cross-chain messaging protocol employs upgradable contracts, it could pose a substantial risk to the applications built on top of them. Any upgrade to the protocol could unintentionally introduce bugs or vulnerabilities, leading to potential losses or exploits. It's important to consider the protocol's approach to upgrades and how these might impact security.

User Application Risk

The final risk category relates to the applications that developers build on top of the messaging protocol. If these applications contain bugs, it could lead to potential issues or vulnerabilities. As such, thorough testing and validation are critical during the development process to ensure the security of these applications.

Client Diversity Risk

Let’s delve into the nuances of client diversity in the context of cross-chain messaging and highlight its crucial role in maintaining the security and integrity of cross-chain systems.

Pre-Proof of Stake Era

Prior to its shift to a Proof of Stake (PoS) mechanism, Ethereum was largely dependent on Geth (Go Ethereum) as the primary software run by its validators. This created a monoculture scenario where a majority of the network's nodes operated on the same software.

  • The Geth Monopoly: With Geth becoming the predominant choice of software, it was updated frequently, with validators regularly installing the newest versions. This consistent updating cycle presented a vulnerability; if a rogue developer managed to infiltrate malicious code into a Geth update, the validators, upon updating, would inadvertently integrate this code into their systems, potentially triggering a network-wide attack.

  • Recovery Mechanism: Despite this potential security threat, Ethereum had a safety net. Since Ethereum's state is not 'final', it could revert to a previous state and essentially negate the effects of the malicious blocks. This rollback mechanism allowed Ethereum to circumvent the aftermath of the attack and continue operation from a 'clean' state, hence ensuring its survival.

Client Diversity in Cross-Chain Messaging

  • Validator Variety: Unlike the earlier Ethereum scenario, cross-chain messaging protocols could feature a wide array of validators. However, a common thread remains — these validators often run the same software provided by the protocol's parent company.

  • The Hidden Risks: The similar adoption pattern to Ethereum's Geth scenario unfolds here, with validators routinely accepting and implementing updates from the parent company without regular source code checks. This leaves the door open for the integration of malicious or faulty code into the system if it were introduced into an update. The consequences of such an event could be dire, leading to theft of funds or forgery of messages.

The Issue of Finality: Why Rolling Back Is Not an Option

A crucial difference between the earlier Ethereum case and current cross-chain messaging systems is the question of finality. Unlike Ethereum, actions in cross-chain messaging protocols are irreversible

  • Inability to Undo Actions: If a message is forged and relayed to another layer (e.g., layer 1 or layer 2), the bridge lacks the authority to retract or modify that message. Bridges do not possess control over the blockchains they interact with, eliminating the possibility of a rollback.

  • The Importance of Client Diversity: Given the irreversibility of actions in cross-chain messaging, the need for client diversity becomes increasingly paramount. It's important to note that the security of a cross-chain messaging protocol does not lie in the quantity of its validators, but in the diversity of the software they run. Even a protocol with a large number of validators becomes essentially equivalent to a single-validator scenario if all the validators run the same software. Hence, client diversity should be a core consideration in cross-chain messaging security assessments.

Smart Contract Protocol Upgrade Risk

When considering smart contracts, the perception of security often grows over time. A smart contract's 'perceived security' can be thought of as the level of trust it garners due to its operational history and the amount of funds it has securely managed.

  • Time and Security: A smart contract that has been in operation for an extended period and successfully managed vast sums of money naturally earns a reputation for being secure. This sense of security is rooted in its proven track record.

  • Proven Track Record: If a smart contract has been functioning effectively, securing millions or billions of dollars over a period, without any significant issues or modifications to its code, it is seen as hardened and robust. For instance, it's improbable that a bug exists in Uniswap V2 or even V3 due to their prolonged operation without significant issues.

Smart Contract Upgradeability: A Double-Edged Sword

An interesting facet of smart contract perceived security lies in its upgradeability.

  • Unchangeable Contracts: Smart contracts that cannot be upgraded gain perceived security with time. This is because they have a set code that doesn't change, and the longer this code operates without issues, the more secure the contract is perceived to be.

  • Trade-Offs of Upgradeability: On the one hand, upgradeable contracts offer the advantage of being able to introduce new features and fix potential issues. On the other hand, every upgrade essentially restarts the 'trust clock'. It creates an opportunity for new bugs to be introduced, thereby potentially reducing the perceived security.

In summary, the longer a smart contract operates without alterations or issues, the more secure it's deemed to be. Therefore, upgradeability, while allowing for improvements and fixes, could potentially diminish the perceived security of a smart contract.

Upgradeability Solution: Library Upgrades in Cross-Chain

Layer0 Labs has designed a system that balances contract immutability with the need for improvement through the use of 'Library Upgrades'.

  • Immutable Smart Contracts: Layer0 ensures that every smart contract validation library it releases remains unchangeable, thereby not granting any entity the ability to alter it. This immutability instills a strong sense of trust in the protocol.

  • Appended Libraries: However, Layer0 retains the capability to append new libraries to existing smart contracts. These additional libraries offer improvements, such as better gas efficiency or the incorporation of advanced tech like ZK (Zero-Knowledge) clients.

  • Application Opt-In: Crucially, applications are not forced to accept these new libraries. They have the freedom to continue using an existing, proven library, or they can opt to adopt the new, cutting-edge libraries as they see fit.

The Implications of Library Upgrades for Cross-Chain Messaging Protocol

Layer0's implementation of Library Upgrades has profound implications for the security and trustworthiness of cross-chain messaging protocols.

  • No Forced Changes: Layer0 doesn't impose changes or control over the messaging protocols used by an application. This eliminates the risk of 'resetting the clock' and maintains a high level of protocol stability.

  • Trust in the Developer and the Chain: Applications should be able to trust the security properties of the chain they're building on and the code they've written. Introducing an upgradable cross-chain messaging protocol adds a third party to this trust equation.

  • Mitigation of Upgrade Risk: If Layer0 were to retain the ability to upgrade smart contracts, they could potentially forge messages or even attack protocols. By not allowing such upgrades, Layer0 effectively mitigates these risks.

  • Reduced Dependency on Protocol Team: Relying on an upgradable protocol implies placing trust in a small group of people. If the protocol team becomes unsuccessful or their security measures falter, a rogue developer could potentially harm users or steal assets. By not granting upgrade capabilities, Layer0 minimizes this risk.

User Application Smart Contract Risk

Smart contract risks arise from vulnerabilities that exist in the smart contracts of user applications built on top of the cross-chain messaging protocols.

  • Case Study: The Wormhole Hack: Approximately a year and a half ago, a bug in a bridge on top of the Wormhole protocol allowed for the execution of an incorrect message. This unauthorized message led to the unlocking of funds on a different chain. Although this bug was not an issue with the off-chain infrastructure, it still resulted in a major security breach.

  • Potential Impact: Any application built on a cross-chain messaging protocol is susceptible to this kind of risk. A bug in their smart contract could end up sending a rogue message to another chain, thereby jeopardizing their application.

Leveraging Asynchrony for Enhanced Security

In light of these security risks, the asynchronous nature of cross-chain messaging protocols can serve as a safety net.

  • Asynchronous Messaging: Unlike atomic transactions, asynchronous cross-chain messages don't happen instantly. Instead, there's a time window between when the message is sent and when it is executed on the other chain.

  • Time Window Advantage: This delay can be used as a 'grace period' to perform necessary checks. If an anomaly or a suspicious message is detected during this time, necessary actions can be taken to ensure that the erroneous message does not result in a successful hack.

Solution: Pre-Crime

To address the inherent risks in cross-chain messaging, LayerZero has developed an innovative solution named Pre-Crime" By leveraging the asynchronous nature of these protocols and implementing thorough testing methodologies, LayerZero aims to proactively prevent potential hacks and offer enhanced security for its users.

Pre-Crime: Defining Invariants

Pre-Crime allows smart applications built on LayerZero to define a set of 'invariants'.

  • Invariants: These are conditions that must hold true at all times. For instance, an invariant could be a condition stipulating that the total supply of a token can never exceed a predefined limit. If a cross-chain message would lead to a violation of this invariant, the message would not be delivered.

  • Preventing Errors: Pre-Crime can essentially protect user applications from their own bugs. As messages aren't delivered instantly due to the asynchronous nature of cross-chain protocols, there's a window of opportunity to conduct these checks and prevent potential issues.

Rigorous Testing and Deployment Procedure

LayerZero goes above and beyond when it comes to testing and deploying new libraries to ensure security.

  • Forking Blockchains: As part of the process, LayerZero forks all the blockchains involved with an application. The message is delivered to these forks and checked against the defined invariants, which return a true or false value indicating if the message passes the checks or not.

  • Repetitive Dry Runs: The team at LayerZero also conducts rigorous testing, called 'dry runs', for months before going live. They create multiple potential scenarios and strive to anticipate and rectify any issues that could arise. This meticulous approach involves deploying across multiple chains, trying to find potential vulnerabilities, and automating protection against possible threats.

Ensuring Absolute Security

LayerZero is dedicated to maintaining the highest standards of security, making sure not to rush any processes even after multiple successful audits.

  • Asynchronous Deployment: As LayerZero simultaneously deploys on multiple chains such as Ethereum, BSC, Avalanche, etc., a level of asynchronous activity is inherent. The team continuously works to consider all potential challenges and ensures robust automated defense mechanisms.

  • Opting into Upgrades: LayerZero's approach ensures that no existing users can be negatively affected as they have to actively opt into any upgrades.

The "Pre-Crime" strategy and the painstaking attention to detail underpin LayerZero's dedication to perfecting their protocol. The goal is to minimize any risk of forged messaging or negative impacts on user applications, ensuring the highest level of security and trust in their protocol.

LayerZero Architecture Overview

LayerZero aims to put user applications in control of their own security properties while enabling communication across different blockchains. Reviewing the architecture we have:

User Applications and Endpoints

  • User applications directly interact with endpoints, sending and receiving messages.

  • Developers find this approach easy to use as they only pay gas on the source chain.

  • The destination chain automatically executes the necessary operations.

Ultralight Node Validation Libraries

  • User applications select their own ultralight node validation libraries.

  • The original ultralight node includes the selection of an Oracle and relayer.

Oracle & Relayer

  • The Oracle and relayer are responsible for moving different pieces of information between chains. This can be a transaction hash and the transaction itself, or a block header and a transaction proof.

Selection and Control of Off-Chain Infrastructure

  • Applications send messages through the validation library they've selected, to the Oracle and relayer set they've chosen.

  • Applications have the flexibility to choose multiple Oracles and relayers, giving them complete control over their off-chain infrastructure.

  • Oracles and relayers are paid by the ultralight node based on a quote provided on-chain.

Block Confirmations and Message Delivery

  • Once the application-defined block confirmations are completed, the Oracle submits the block header or transaction hash.

  • The relayer moves the transaction proof or transaction itself.

  • The same validation library verifies these on the destination chain and delivers the information directly to the user application.

Application Control and Trustless Communication

  • LayerZero ensures that user applications maintain control over their security properties.

  • The protocol operates on the belief that in a trustless communication system, users are always dependent on someone or something. Therefore, applications should be able to trust themselves and control their own infrastructure.

  • LayerZero adopts a "developer-first" standpoint, ensuring applications are not susceptible to unwanted upgrades by allowing them to select their own off-chain infrastructure and validation libraries.

Summary

To summarize, LayerZero emphasizes once again the importance of the following three risks:

Client Diversity

  • It is crucial to consider not just the number of validators, but also the software clients they utilize.

  • This protocol promotes diversity among clients, reducing dependence on a single software. If all validators use the same software, the entire system is only as strong as the software's weakest link.

Protocol and Upgrade Risks

The risk related to smart contract protocols and upgrades is another aspect that LayerZero takes into account.

  • This protocol highlights the dangers of being overly dependent on a messaging protocol, especially when upgrades can be forcibly pushed onto you, irrespective of whether you agree with them or not.

  • Negative outcomes can occur from such situations, with bugs being unintentionally introduced, leading to serious consequences such as fund thefts or forged messages.

Application-Specific Risks

LayerZero enables the writing of individual invariances to protect against critical failures for cross-chain messaging.

  • This is necessary due to the distinct nature of building cross-chain compared to single-chain; the former lacks atomicity and is more asynchronous.

  • Leveraging a system like "Pre-crime" helps in managing these risks by serving as an emergency brake when certain conditions are met.

Q&A Summary

The LayerZero team took questions from the community and provided clarifications on some key areas:

Can applications create and choose their own validation library?

Currently, applications can select their own validation library but cannot create one. This might change in the future as LayerZero Labs looks at options to allow more flexibility and control for applications over their validation libraries.

What are the most common coding errors seen in LayerZero implementations?

The most common mistakes usually stem from setup issues, particularly in defining gas usage for cross-chain messaging. Other common errors relate to interaction with other smart contracts and overlooking potential problems such as re-entrancy issues and excessive gas usage.

Who sets the invariants in the Pre-crime system?

Currently, LayerZero provides on-chain invariants, which are then defined by applications on-chain. LayerZero is testing its documentations and instructions with applications that reach out directly before releasing these resources to the public. The aim is to ensure that they are perfect and user-friendly.

Looking for a Security Review?

Please contact us below via our submission form:

You may also reach out to us via our Twitter: https://twitter.com/SpearbitDAO[:](https://twitter.com/SpearbitDAO:)

For a brief overview of what Spearbit is and what we have to offer please see: https://twitter.com/SpearbitDAO/status/1656786350601846787?s=20

Subscribe to Spearbit
Receive the latest updates directly to your inbox.
Mint this entry as an NFT to add it to your collection.
Verification
This entry has been permanently stored onchain and signed by its creator.