Monad 백서

Monad

원문

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

nalReward`](/reference/staking/api#externalreward) method on the staking precompile. Commission is **not** deducted from external rewards. ### Claiming and compounding Each delegation accumulates rewards over time. Delegators can either: * **Claim** rewards — withdrawn to the delegator's account immediately * **Compound** rewards — added to the delegation, increasing stake weight (follows the standard epoch timing rules described below) ## Epochs and boundaries An **epoch** uses one set of delegations and leader validators for its entire duration. Every 50,000 blocks (the `BOUNDARY_BLOCK_PERIOD`) is a **boundary block** that commits the upcoming staking changes and the validator set to be used in the next epoch. Boundary blocks happen approximately every 4 hours 12 minutes. The next epoch does not start immediately at the boundary block, but after a 5,000-round delay (`EPOCH_DELAY_ROUNDS`) to allow all nodes to update their epoch information. <img alt="timeline showing the placement of boundary blocks within an epoch" /> ### Timing of staking actions Most staking actions take effect after they are committed in a boundary block and the next epoch starts. The exceptions are `claimRewards()` and `externalReward()`, which take effect immediately. As an example, consider `delegate()` during epoch #4: * If the `delegate()` takes place before the boundary block for epoch #5, the stake will be included in epoch #5. * If the `delegate()` transaction is in the boundary block itself, it will not be included in epoch #5 (the snapshot is taken at the start of the block, before user transactions). The delegation will be picked up in the boundary block for epoch #6. * If the `delegate()` transaction is after the boundary block but before the end of epoch #4, the delegation will take effect in epoch #6. <Note> The `BOUNDARY_BLOCK_PERIOD` is denominated in **blocks**, while `EPOCH_DELAY_ROUNDS` is denominated in **rounds**. If perfect consensus is achieved, these increment at the same rate. However, upon a failed block proposal (e.g. timeout), the round increments while the block does not. </Note> ## Execution, snapshot, and consensus views The staking system maintains three views that staking state passes through: 1. **Execution view** — the real-time state. When validators are added, delegations change, or any staking transaction happens, the execution view is updated immediately. 2. **Snapshot view** — at the start of each boundary block, the current execution view is copied into the snapshot view. Any transaction changes after this point will not affect the following epoch. The snapshot now matches what the next epoch will look like. 3. **Consensus view** — after `EPOCH_DELAY_ROUNDS` (5,000 rounds) from the boundary block, the new epoch starts and the snapshot view is copied into the consensus view. The consensus view holds the validators and voting stake weights being used by the consensus system for the remainder of the epoch. ## Slashing Robust logging provides accountability for malicious, slashable offenses. However, automated in-protocol slashing is not currently implemented. ## Constants | Constant | Meaning | Value | | - | - | - | | `BOUNDARY_BLOCK_PERIOD` | Blocks from boundary block to boundary block | 50,000 blocks | | `EPOCH_DELAY_ROUNDS` | Rounds between the boundary block and the start of each epoch | 5,000 rounds | | `WITHDRAWAL_DELAY` | Number of epochs before unstaked tokens can be withdrawn | 1 epoch | | `MIN_AUTH_ADDRESS_STAKE` | Min MON self-delegated by a validator to be eligible for the active set | 100,000 MON | | `ACTIVE_VALIDATOR_STAKE` | Min total MON staked with a validator for active set eligibility | 10,000,000 MON | | `ACTIVE_VALSET_SIZE` | Number of validators in the active set | 200 | | `REWARD` | MON reward per block | 18 MON | # Statesync Source: https://docs.monad.xyz/monad-arch/consensus/statesync Mechanism for synchronizing MonadDb state ## Summary Statesync is the process for synchronizing state to a target block close to the current tip. A synchronizing node ("client") requests data from other up-to-date validators ("servers") to help it progress from its current view to its target view; the servers rely on metadata in MonadDb to efficiently respond to the request. Since the current tip is a moving target, following completion of statesync, the client makes another statesync request to get closer to the current tip, or replays queued blocks if within striking distance. ## Approach Statesync is the process of synchronizing state stored in [MonadDb](/monad-arch/execution/monaddb) to a target block close to the current tip. The current tip is a moving target, so as statesync is running, the syncing node stores new blocks beyond the target block and, upon completion of statesync, replays these additional blocks through normal execution to catch up to the current tip. The target block may be updated several times during this process. Statesync follows a client-server model, where the statesync requester is the client and the validator node servicing a statesync request is the server. ## Data included in statesync MonadDb stores a variety of data relating to the execution of blocks. However, only a subset is required for full participation in the active set and thus included in statesync: * accounts, including balances, code, and storage * the last 256 block headers (to verify correctness) In an effort to evenly distribute load, each of the aforementioned is spliced into chunks. The client assigns each chunk to a server who remains the peer for that chunk until synchronization is complete. Servers are randomly selected from the list of available peers. The client maintains a certain number of sessions up to a configured maximum. In the event that servers are unresponsive, the client’s statesync request will timeout and request from a different server. ## Versioning and verification For efficiency, the client requests state from least- to most-recently updated, converging on the tip near the end of the process. Servers serve diffs relative to the client's latest block. <img alt="statesync_requests" /> In the example above, the statesync client makes three consecutive requests to the statesync server assigned to prefix p. For each request, there are five parameters specified: * `prefix` - the prefix of the Merkle Patricia Trie * `i` - the start block number * `j` - the end block number * `target` - the target block number * `last_target` - last target block number, this is used to deduce deletions to send Because there may be multiple rounds of statesync (as statesync occurs, the chain is progressing and the target block may need to adjust), `j` is buffered by some offset B from the target block to avoid retransmitting most recently used nodes in the MPT. When `i` and `target` block are sufficiently close, as in the last round above, the statesync client will request `j = target`. At this point, if `target` is less than `statesync_threshold` (600 blocks by default) from the tip of the chain, statesync is concluded and the state root will be validated. Any remaining blocks between `target` and tip are then synced via [blocksync](/monad-arch/consensus/blocksync). If `target` is greater than `statesync_threshold` blocks from the tip of the chain, a new round of statesync will begin. During block execution, the server stores the version alongside node contents. As such, upon receipt of a statesync request, the server is able to quickly narrow down the relevant subtrie and submit read requests, which are embarrassingly parallel. ## Trust assumptions Statesync clients trust that the requested data (including state root and parent hash) from statesync servers is correct. This is currently sampled randomly from the validator set according to stakeweight, but clients can optionally whitelist specific known providers as statesync servers. The current implementation validates the data transmitted when the whole transfer is complete by comparing the state root. Because the work is split between multiple servers, a single server sending invalid data can cause a state root mismatch, without attribution to the faulty server. The only recourse in this situation is to retry the whole transfer, giving the faulty server an opportunity to fail the operation again. Changes are currently being implemented to verify the data transmitted on a per-server basis. In the event of a faulty server sending invalid data, the statesync client can discard and retry *only* the affected prefix. Further, it can identify the faulty server, log the error and potentially blacklist it from subsequent requests. # Transport Protocol Usage Source: https://docs.monad.xyz/monad-arch/consensus/transport-protocols Overview of transport protocol usage for node communication Monad nodes use both TCP and UDP protocols for different types of communication. | Traffic Type | Protocol | | - | - | | [Primary RaptorCast](/monad-arch/consensus/raptorcast) | UDP | | [Secondary RaptorCast](/monad-arch/consensus/raptorcast#secondary-raptorcast-full-node-block-propagation) | UDP | | [Peer Discovery](/monad-arch/consensus/peer-discovery) | UDP | | [Transaction Forwarding](/monad-arch/consensus/local-mempool) | UDP | | [Block Forwarding to Dedicated Full Nodes](/node-ops/full-node-block-delivery#dedicated-upstream) | UDP | | [Blocksync](/monad-arch/consensus/blocksync) | TCP | | [Statesync](/monad-arch/consensus/statesync) | TCP | # Execution Source: https://docs.monad.xyz/monad-arch/execution/index <CardGroup> <Card title="Parallel Execution" href="/monad-arch/execution/parallel-execution"> Optimistic parallel execution </Card> <Card title="MonadDb" href="/monad-arch/execution/monaddb"> Custom database for storing the Ethereum Merkle Patricia Trie natively on SSD </Card> <Card title="JIT Compilation" href="/monad-arch/execution/native-compilation"> High-performance execution of EVM bytecode by compiling to machine code </Card> </CardGroup> # MonadDb Source: https://docs.monad.xyz/monad-arch/execution/monaddb High-performance database for storing blockchain data. ## Summary MonadDb is a critical component in Monad for maintaining full Ethereum compatibility while delivering high performance. It is a custom-built key-value database designed for storing authenticated blockchain data. MonadDb, specifically, is optimized for efficiently storing Merkle Patricia Trie nodes on disk. ## Merkle Patricia Trie Structured Database Most Ethereum clients use generic key-value databases that are implemented as either B-Tree (e.g. [LMDB](https://www.symas.com/lmdb)) or LSM-Tree (e.g. [LevelDB,](https://github.com/google/leveldb) [RocksDB](https://rocksdb.org/)) data structures. However Ethereum uses the [Merkle Patricia Trie](https://ethereum.org/en/developers/docs/data-structures-and-encoding/patricia-merkle-trie/) (MPT) data structure for storing state and other authenticated fields like receipts and transactions. This results in a suboptimal solution where one data structure is embedded into another data structure. MonadDb implements a [Patricia Trie](https://en.wikipedia.org/wiki/Radix_tree) (a specific variant of radix tree) data structure natively, both on-disk and in-memory. Despite the opinionated design, MonadDb is a flexible key-value store capable of storing any type of data. For instance, MonadDb is also used to store block headers and payloads for Monad. ## Page-based storage state Under [MIP-8](https://mips.monad.xyz/MIPs/MIP-8), the storage trie commits to pages rather than to individual slots. A page is a contiguous group of 128 storage slots (4096 bytes), and each storage leaf holds a 32-byte commitment to the contents of one page, so the trie stores `{page_index, page_commitment}` pairs. The trie is otherwise unchanged: keys are hashed with keccak, and branch, extension and leaf nodes follow the standard MPT rules. Reading a single 32-byte slot already pulls a whole page off the SSD, so the commitment now covers the same unit as one disk read. A page commitment is a BLAKE3 Merkle root built over the occupied slots of the page alone. The work of computing it, and the size of a proof against it, grow with how much of the page is occupied rather than with the 4096-byte page size. See [Storage pages](/developer-essentials/opcode-pricing#storage-pages) for the resulting gas schedule, and [MIP-8 Activation and Page Storage Migration](/node-ops/upgrade-instructions/page-storage-mip-8-migration) for how existing databases are migrated. ## Asynchronous IO Monad executes multiple transactions in [parallel](/monad-arch/execution/parallel-execution). In order to enable this, reads should not block continued operation, and this goal motivates [asynchronous I/O](/monad-arch/concepts/asynchronous-io) (async I/O) for the database. The above-mentioned key-value databases lack proper async I/O support (although there are some efforts to improve in this area). MonadDb fully utilizes the latest kernel support for async I/O (on Linux this is [io\_uring](https://unixism.net/loti/index.html)). This avoids spawning a large number of kernel threads to handle pending I/O requests in an attempt to perform work asynchronously. ## Filesystem bypass Modern filesystems provide a convenient abstraction for applications, but introduce overhead when building high-throughput I/O software. These often hidden costs include block allocation, fragmentation, read/write amplification, and metadata management. The abstraction of files and a set of system calls allows applications to interact with the file data as if it were stored contiguously. The complexity of managing exact physical disk locations is abstracted away from the applications (and their developers). However, the actual content on disk might be fragmented into multiple non-contiguous pieces. Accessing or writing to such a file usually involves more than one simple I/O operation. To minimize overhead, MonadDb provides operators the option to bypass the filesystem. MonadDb implements its own indexing system based on the Patricia trie data structure, eliminating filesystem dependencies. Users have the flexibility to operate MonadDb on either regular files or block devices. For optimal performance, it is recommended to run MonadDb directly on block devices. This approach avoids all filesystem-related overhead, allowing MonadDb to fully unlock SSD performance. ## Concurrency Control The Monad blockchain consists of multiple clients, each interacting with the database as either reader or writer. To support this functionality, MonadDb must efficiently synchronize between a single writer (execution) and multiple readers (consensus and RPC). MonadDb implements a persistent (or immutable) Patricia trie. When a branch in the trie is updated, new versions of the nodes on that branch are created, and the previous version of the trie is preserved. This approach facilitates versioning within the database and significantly simplifies synchronization between readers and the writer. It ensures that all reads are accurate and consistent while guaranteeing that writes are both complete and atomic from the perspective of the readers. ## Write Performance on Modern SSD The usage of a persistent data structure also allows us to perform sequential writes, which offers better performance than random writes on modern SSDs. Modern SSD garbage collection occurs at the block level. On sequential writes, an entire block gets filled before the next one, which dramatically simplifies garbage collection. Garbage collection is much more expensive for random writes. Sequential writes also distribute data more efficiently, thereby reducing write amplification and increasing SSD longevity. ## Compaction As historical versions accumulate, the amount of data written to disk will grow. Given the limited disk capacity it operates on, it is impossible to retain complete historical records. MonadDb stores recent versions of blockchain data and state and dynamically adjusts the history length based on available disk space. As newer versions are stored and older versions are pruned, the underlying storage space becomes fragmented. To address this, MonadDb performs compaction inline with updates, consolidating active data and releasing unused storage for recycling. This reduces fragmentation while maintaining performance and data integrity. # JIT Compilation Source: https://docs.monad.xyz/monad-arch/execution/native-compilation High-performance execution of EVM bytecode by compiling to machine code. ## Summary Executing each EVM contract call to completion as quickly as possible is a key part of Monad’s overall performance. To do this, Monad uses both a highly optimized interpreter and a bespoke native-code compiler. The compiler analyzes frequently used contracts once and caches native code so subsequent calls execute more efficiently while preserving exact EVM semantics (including gas and error behavior). ## Interpreting vs. Compiling Most Ethereum clients execute smart contract code one instruction at a time, checking stack bounds and available gas before applying the instruction’s semantics. This is an *interpreter*. Interpreters are straightforward to build and maintain, have low startup latency, and can perform very well when implemented with modern techniques. An alternative is to *compile* programs. Before execution begins, code is analyzed and transformed into a representation that executes more efficiently. Compilation adds upfront latency and complexity, but it happens once per contract version. If repeated executions are faster, overall system performance improves. For simplicity and portability, many compilers target a higher-level *intermediate representation* (e.g., [LLVM IR](https://llvm.org/) or [Cranelift](https://cranelift.dev/)). Because the Monad client targets a specific hardware configuration, the compiler emits native [x86-64](https://en.wikipedia.org/wiki/X86_assembly_language) directly to maximize control and performance while still matching EVM behavior exactly. ## Eliminating Redundant Work Compilation lets us precompute behavior ahead of time. Consider this straight-line fragment: ``` JUMPDEST PUSH1 0x1 ADD PUSH0 JUMP ``` Once execution reaches the `JUMPDEST`, it must proceed through `PUSH1`, `ADD`, `PUSH0` and `JUMP`. A pure interpreter would charge gas and perform checks for each instruction as it executes. A compiler can recognize the straight-line block and perform a single upfront gas check for the combined cost of the block (subject to EVM rules), then emit code that runs the block without per-instruction bookkeeping. The result is fewer CPU instructions while preserving identical gas accounting and out-of-gas semantics. [Constant folding](https://en.wikipedia.org/wiki/Constant_folding) is another example. Given: ``` PUSH1 0x2 PUSH1 0x3 ADD ``` the compiler can determine the stack state at ADD and fold it to: ``` PUSH1 0x5 ``` internally, while still charging the same total gas as the original sequence and maintaining 256-bit modular arithmetic semantics. ## Optimizing Code Beyond removing redundant work, the compiler chooses efficient implementations based on where operands reside. It maintains a *simulated EVM stack* that maps each 256-bit stack word to a location on the machine: main memory, a set of general-purpose integer registers, or a single AVX vector register. This approach is a combination of [register allocation](https://en.wikipedia.org/wiki/Register_allocation) in a traditional optimizing compiler and [stack caching](https://dl.acm.org/doi/abs/10.1145/223428.207165) techniques for compiling stack-based languages. Each EVM instruction is then specialized to the operand locations it sees. For example, `AND` can be implemented with a single [x86 `vpand`](https://www.felixcloutier.com/x86/pand) when both arguments are already in A
프로젝트로 돌아가기