Monad 백서

Monad

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 64쪽

VX registers. Much of the compiler’s effectiveness comes from emitting specialized sequences for common operand-location combinations. ## Compilation Performance Compiling every contract ahead of time is impractical. Instead, the compiler tracks contracts by cumulative gas consumed over all executions and caches native code for the “hottest” ones. As blocks execute, newly hot contracts enter a compile queue. Compilation runs asynchronously, and contracts that are not yet compiled (or never become hot) continue to run on the highly optimized interpreter. The cache ensures repeated calls to popular contracts benefit from compilation without blocking execution on compile latency. # Parallel Execution Source: https://docs.monad.xyz/monad-arch/execution/parallel-execution ## Summary Monad executes transactions in parallel. While at first it might seem like this implies different execution semantics than exist in Ethereum, it actually does not. Monad blocks are the same as Ethereum blocks - a linearly ordered set of transactions. The result of executing the transactions in a block is identical between Monad and Ethereum. ## Optimistic Execution At a base level, Monad uses optimistic execution. This means that Monad will start executing transactions before earlier transactions in the block have completed. Sometimes (but not always) this results in incorrect execution. Consider two transactions (in this order in the block): 1. Transaction 1 reads and updates the balance of account A (for example, it receives a transfer from account B). 2. Transaction 2 also reads and updates the balance of account A (for example, it makes a transfer to account C). If these transactions are run in parallel and transaction 2 starts running before transaction 1 has completed, then the balance it reads for account A may be different than if they were run sequentially. This could result in incorrect execution. The way optimistic execution solves this is by tracking the inputs used while executing transaction 2 and comparing them to the outputs of transaction 1. If they differ, we have detected that transaction 2 used incorrect data while executing and it needs to be executed again with the correct data. While Monad executes transactions in parallel, the updated state for each transaction is "merged" sequentially in order to check the condition mentioned above. Related computer science topics are [optimistic concurrency control](https://en.wikipedia.org/wiki/Optimistic_concurrency_control) (OCC) and [software transactional memory](https://en.wikipedia.org/wiki/Software_transactional_memory) (STM). ## Optimistic Execution Implications In a naïve implementation of optimistic execution, one doesn't detect that a transaction needs to be executed again until earlier transactions in the block have completed. At that time, the state updates for all the earlier transactions have been merged so it's not possible for the transaction to fail due to optimistic execution a second time. There are steps in executing a transaction that do not depend on state. An example is signature recovery, which is an expensive computation. This work does not need to be repeated when executing the transaction again. Furthermore, when executing a transaction again due to failure to merge, often the account(s) and storage accessed will not change. This state is still be cached in memory, so again this is expensive work that does not need to be repeated. ## Further Work There are other opportunities to avoid re-executing transactions which are still being explored. # Monad Architecture Source: https://docs.monad.xyz/monad-arch/index This section surveys Monad's major architectural innovations. <CardGroup> <Card title="Concepts" href="/monad-arch/concepts"> Explaining high level themes (async io and pipelining) that recur in Monad </Card> <Card title="Consensus" href="/monad-arch/consensus"> Algorithms for maintaining a globally distributed, decentralized validator set </Card> <Card title="Execution" href="/monad-arch/execution"> Algorithms for executing EVM transactions efficiently </Card> <Card title="Real-time Data" href="/monad-arch/realtime-data"> Consuming recent blockchain data as quickly as possible </Card> <Card title="Transaction Lifecycle" href="/monad-arch/transaction-lifecycle"> Mapping the path of a transaction in Monad </Card> </CardGroup> The first Monad client is built by [Category Labs](https://www.category.xyz/) and is written from scratch in C++ and Rust. Check out the codebase: * [`monad-bft`](https://github.com/category-labs/monad-bft) (consensus client) * [`monad`](https://github.com/category-labs/monad) (execution client) # Real-Time Data Sources Source: https://docs.monad.xyz/monad-arch/realtime-data/data-sources For many use cases, developers and users can access current and historical data for the Monad blockchain via the JSON-RPC interface. This is not the most efficient way to receive data about the latest blocks, however. The traditional JSON-RPC access methods use a request/response model (which requires polling) instead of a notification model, where new updates are pushed to you as soon as they happen. <Warning> Because the Monad blockchain is much faster than other EVM-compatible L1 blockchains, the traditional JSON-RPC methods may not provide enough performance if you consume a *lot* of data, even if they've worked for you on other EVM ecosystems. The next section explains why in detail. </Warning> ## Why might I need real-time data, even if I didn't before? Monad is a fast blockchain capable of thousands of transactions per second: when the Monad ecosystem runs at peak rates there is much more data per second than in other L1 EVM-compatible blockchains such as mainnet Ethereum. The data ecosystem of original Ethereum evolved around a network that ran at less than 100 TPS, so certain data query patterns that work there might not perform well enough when the amount of data is almost 100 times larger. A classic example is an indexer workflow of fetching data about every transaction and every log in a block, using JSON-RPC methods like [`eth_getLogs`](/reference/json-rpc/api#eth_getlogs). A typical Ethereum block will have hundreds of transactions in it, and there will be one new block every 12 seconds or so. For Monad, there are 2.5 blocks every second, and each block can contain thousands of transactions. The number of `eth_getLogs` requests would be almost 100 times greater, putting a strain on the JSON-RPC service provider. Using real-time data services can help. Such services exist on other EVM blockchains too, but they're essential in more situations for Monad. ## How do I receive real-time data? Monad currently offers three sources of real-time data, which offer different trade-offs in latency vs. complexity. ### Source #1: Geth-compatible real-time events This is a [WebSocket-based protocol](https://geth.ethereum.org/docs/interacting-with-geth/rpc/pubsub) that originated in the Geth Ethereum client but is widely supported by other EVM-compatible blockchains. Monad implements the `eth_subscribe` method and the `newHeads` and `logs` subscription types. The `syncing` and `newPendingTransactions` subscription types are not supported. This real-time data feed is published by the Monad RPC server component. ### Source #2: Monad extensions to Geth real-time events The Monad RPC server also offers an extension to the Geth protocol; it provides `eth_subscribe` subscriptions called `monadNewHeads` and `monadLogs`. These publish almost the same data as the Geth real-time events protocol, but include extra data for tracking each block's progression through consensus. This requires the user to understand speculative execution and [how it affects real-time data](/monad-arch/realtime-data/spec-realtime). You can read more about these subscriptions in the [WebSocket subscriptions](/reference/json-rpc/overview#speculative-subscription-behavior). ### Source #3: Execution events SDK This is the fastest way to consume real-time data. It requires you to write your own real-time data processing software using the Monad client SDK in C, C++, or Rust -- and then run it alongside your own Monad node. This is the source of data that powers the other two access methods: it is what the RPC server itself is listening to, to create the WebSocket feeds. It has its own [documentation](/execution-events). ## Comparison of data offerings | Data offering | How to consume | Published by | Granularity | Transaction-level info | When data is published | | - | - | - | - | - | - | | Geth real-time events | [WebSocket](/reference/json-rpc/overview#websocket-subscriptions) | RPC server | Block commit | Logs only | When a block reaches `Proposed` state | | Geth real-time events (with Monad extensions) | [WebSocket](/reference/json-rpc/overview#websocket-subscriptions) | RPC server | Block commit | Logs only | When a block reaches `Proposed` state, with subsequent commitment-state updates also available | | Execution event SDK | C/C++ or Rust SDK | Execution daemon | Tx commit | Logs, call frames, state reads/writes | As soon as proposal is received | The first two offerings are consumed using `eth_subscribe` method over a WebSocket. They are available from third-party data providers if you don't wish to run your own Monad node. The SDK offering requires you to write your own third-party program using the C/C++ or Rust SDK. These programs are not plugins that run inside the node software -- they are free-standing programs written entirely by you. As events occur inside the EVM (in the execution daemon), they are recorded to shared memory. Your program also is reading this same shared memory. Therefore, your program must run on the same host as a Monad node. # Real-time Data Source: https://docs.monad.xyz/monad-arch/realtime-data/index <CardGroup> <Card title="Real-Time Data Sources" href="/monad-arch/realtime-data/data-sources"> How Monad reports real-time blockchain data </Card> <Card title="Speculative Real-Time Data" href="/monad-arch/realtime-data/spec-realtime"> An optimization for reporting real-time data with very low latency </Card> </CardGroup> # Speculative Real-Time Data Source: https://docs.monad.xyz/monad-arch/realtime-data/spec-realtime The Monad architectural overview explains the [asynchronous execution](/monad-arch/consensus/asynchronous-execution) feature. It is essential to have a basic understanding of how this feature works before you consume Monad's fastest real-time data feeds, especially the [speculative execution](/monad-arch/consensus/asynchronous-execution#speculative-execution) and [block states](/monad-arch/consensus/block-states) sections. ## Why do I need to understand speculative execution? Monad's design has considerably more parallelism than a typical EVM-compatible blockchain. This includes nodes speculatively executing the transactions in a newly-received block before being certain that that block will finalize. The real-time data feeds are created during speculative execution, so if you consume them, you might see data about transactions and their effects (e.g., logs and balance changes), but *those transactions may never really happen!* To avoid reacting to blockchain data that is not "real", you need to know how Monad real-time data feeds express speculative execution, and how they inform you later whether blocks (and their transactions and state effects) were ultimately added to the blockchain (or not). Given this additional complexity, why would you consume these real-time feeds? The answer is so that *your* software can get the same performance benefits from speculative execution that Monad itself gets [(explained below)](#what-benefits-do-i-get-from-speculative-execution). The cost you pay for this benefit is that you need to understand more about how Monad works, so that you can write your data processing code correctly. ## Can I consume real-time data without dealing with speculative execution? Yes. Monad's JSON-RPC interface supports the `"safe"` and `"finalized"` block tags, which return data only from blocks that have reached stronger commitment levels (`Voted` and `Finalized` respectively). See [block states](/monad-arch/consensus/block-states) for details on what each commitment level guarantees. <Info> Geth-style reorganizations don't occur in the `monadNewHeads` or `monadLogs` subscriptions. Instead, you are explicitly told what the consensus algorithm is doing with the blocks you have already seen, so you know what blockchain data gets committed or not. The purpose of this document is to explain exactly what this information means, so you know how to react to it. </Info> ## What benefits do I get from speculative execution? Realtime data generated by speculative execution is valuable to a consumer for two reasons: 1. It allows you to use the same pipelining tricks that Monad itself uses 2. Sometimes it's valuable to react as soon as possible, even when the data you're seeing is not a sure thing ### Advantage #1: pipelining Monad's pipelining tricks are explained [here](/monad-arch/concepts/pipelining) and [here](/introduction/monad-for-users#what%E2%80%99s-different-about-monad). You may recall the below illustration of the laundry analogy, which helps explain the concept in both places: <img alt="Pipelining, Laundry Day" /> <p>Pipelining laundry day. Top: Naive; Bottom: Pipelined. Credit: <a href="https://www.cs.fsu.edu/~hawkes/cda3101lects/chap6/index.html?$$$F6.1.html$$$">Prof. Lois Hawkes, FSU</a></p> Here's a concrete example of how you can use pipelining yourself: Suppose you are writing a automated trading application. Further suppose that when a certain contract (e.g., a CLOB contract) emits a particular log event, your trading algorithm uses data from that log event as a signal to buy or sell. Before actually trading, you may need to perform additional actions first. Some of the things you might do are: * Check your risk limits, to see if increasing the position will give you too much exposure, or bring you too close to a potential liquidation * Run a more complex mathematical model, if your strategy needs to perform complex computations based on the input in the trading signal * Create and cryptographically sign the transaction for your buy/sell order All these things take time, and you can do them *in preparation* for your eventual trade, while you wait to find out if the block containing the market signal was actually finalized. If the block *is* finalized, you've already completed the essential work and can just "pull the trigger" (i.e., send the presigned trade transaction message). If the block is *not* finalized, you just throw the preparatory work away and never do the trade. ### Advantage #2: reacting before we know it's "real" Consider a UI component which wants to keep users informed about the progress of their transaction. When the transaction is speculatively executed, it can be marked as `Pending` in the UI, so that the user knows it has been seen and there's a very good chance it will go through. Even if it fails to progress to a later commit state, seeing a bit of instant feedback tends to be a superior user experience. Also, consider again the example of our automated trading application. Timing is very important in financial markets. When prices are changing rapidly, a trade *right now* could be much more valuable than a trade a few seconds later. It might make sense to initiate a trade *immediately* off of speculative data, even knowing that some tiny percentage of the time, the trade is based on a false premise. You may lose money sometimes, i.e., when your strategy reacts to "not real" market data in a block that fails to finalize. But *usually* this does not happen, and the gains from being early most of the time could outweigh the occasional losses when you react to "false" data. There are also other kinds of applications, e.g., on-chain games, where being more interactive is better than being perfectly accurate all the time. # Block commit states Elsewhere in the [documentation](/monad-arch/consensus/block-states), we learned that a block can be in one of four states: `Proposed`, `Voted`, `Finalized`, and `Verified`. These are sometimes called "commit states" or "consensus states" in the documentation. In speculative real-time data feeds, whenever you are given blockchain data, you will also be told: * What commit state the associated block is in * If the initial state was not *verified*, you will be notified at some point later when the block transitions to a different state Later in this article, we'll walk through exactly how the process happens in the current version of the software. ## Block numbers and block ids Once a block is canonically appended to the blockchain, it becomes uniquely identified by a (sequentially increasing) block number, also called a "block height." The inclusion of a block on the blockchain is the goal of the consensus algorithm, and is called "finalization." When a block is first constructed, it is constructed assuming it will become the next block number, `N`. But prior to finalization, consensus nodes are still trying to agree whether or not this candidate block will actually become block `N`. In consensus terminology, a leader constructs a block and *proposes* it to the Monad network. Consensus nodes vote on the proposal of a particular candidate block `B` to become the finalized block with number `N`. We call this candidate block a "proposed block." It's not part of the blockchain yet, but it probably will be soon. It's possible for the proposal to fail for many reasons. In the most common case, the proposed block does not reach enough other nodes before the timeout period expires, due to network issues. In that case, you would see another candidate to become the same block number `N` later on. Because the real-time data feeds are fed by speculative execution, you might see blockchain data for *both* of the block `N` candidates, and will be told later which one was correct. The critical thing to understand is that this blockchain data may claim to be for "block number `N`", but it's not be the "real" block `N` yet: it's just a *proposal* to become block `N`. Consequently, when you see real-time data for a block *before* it finalizes, the block number alone is not enough to uniquely identify it. This is only the block number that the block *will* have, if it eventually gets finalized. Instead, consensus uses a "block id" to uniquely identify proposed blocks. The id can be used to track a specific block through its commit state lifecycle. Consider the following situation: ``` ■ ║ ┌─────────────┐ ┌─────────────┐ ║ │ │ │ │ ┌─────────╬──┤ Block 102 ◀───┤ Block 103 │ │ ║ │ id: 79c25 │ │ id: 13a33 │ ┌─────────────┐ ┌──────▼──────┐ ║ │ │ │ │ │ │ │ │ ║ └─────────────┘ └─────────────┘ │ Block 100 ◀───┤ Block 101 │ ║ │ id: 5b3a6 │ │ id: 6d585 │ ║ │ │ │ │ ║ └─────────────┘ └──────▲──────┘ ║ ┌─────────────┐ │ ║ │ │ └─────────╬──┤ Block 102 │ ║ │ id: 3ed4d │ ║ │ │ ║ └─────────────┘ ║ ║ ◀ ║ ▶ Finalized blocks ║ Proposed blocks (committed to ║ (may not become blockchain) ║ committed to ║ blockchain) ║ ■ ``` In this diagram: * Block 101 is the latest block to be finalized * There are two competing proposed blocks vying to become block 102; they can be distinguished by their block ids * One of the proposed blocks (`13a33`) is the parent of another proposed block * You might see real-time data for *all* of these blocks; for those which are not finalized, you can start your pipeline processing right away, but you *may* want to wait until they reach a better commitment state before acting <Info> The above situation is very rare in practice, but you should be aware that it is possible. </Info> # Consensus, execution, and c
프로젝트로 돌아가기