bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 16쪽
an event ring's
shared memory segments -- `monad_event_ring_mmap` -- only takes a file
descriptor, and does not know or care where this descriptor comes from. The
only constraints on it are those placed by the `mmap(2)` system call itself.
These conventions are about adding a reasonable default for how the mount
point is set up, and helper functions for finding event ring files in that
location. You should try to use them because they provide a performance
benefit, but you are free to come up with a file descriptor in any way you
wish and it will work with `monad_event_ring_mmap`.
</Note>
### Convention 1: libhugetlbfs in the node setup guide
The
[official guide](https://validator-docs.vercel.app/docs/full_node/events-and-websockets)
for setting up a local Monad node for execution events recommends the use
of `libhugetlbfs`.
`libhugetlbfs` is both a C library and a set of admin tools using that
library that follow a particular configuration convention. The idea is to
standardize some rules for how mount points and permissions are managed for
hugetlbfs filesystems. There are three parts to the basic idea:
1. Each user (or group if you want to do it that way) gets its own
separately-mounted hugetlbfs filesystem. The mount point is located in a
well-defined place under `/var/lib/hugetlbfs/user/<user-name>`[^1]
2. `hugeadm`, a program that a system administrator runs, is a configuration
front-end for tasks like listing hugetlbfs mounts, creating new mounts, etc.
3. The C library, `libhugetlbfs`, helps client programs "find" hugetlbfs mounts
that the current user has permission to access
The setup guide for the Monad node tells the user to install the `libhugetlbfs`
command line tools and to set up a "user mount" for the `monad` user. The guide
also recommends that all users be given access to enter this directory, so that
data consumer applications that run as non-`monad` users can open the file.
[^1]: Other configuration schemes are possible too, see
[`man hugeadm`](https://linux.die.net/man/8/hugeadm)
### Convention 2: "default" event ring directory
The event ring library introduces the concept of a "default event ring
directory." This is the default directory where event ring files should be
created, and thus where reader applications should look for them. This default
can come from one of two places:
1. You can provide it manually OR
2. If you don't provide it, the library will use a conventional location
The conventional location is a subdirectory called `event-rings`, created
directly under whatever hugetlbfs mount point is returned by `libhugeltbfs`[^2],
i.e., it is:
```
<libhugeltbfs-computed-mount-point>/event-rings
```
If you follow the setup guide to the letter, this should be:
```
/var/lib/hugetlbfs/user/monad/pagesize-2MB/event-rings
```
But depending on how your system is setup, `libhugetlbfs` could return a
different path. For example, you might see something like this:
```
/dev/hugepages/event-rings
```
This is because `libhugeltbfs` scrapes the contents of `/proc/mounts` and
returns only one path that the current user has
[access](https://man7.org/linux/man-pages/man2/access.2.html)
to. What if the user has access to multiple hugetlbfs mounts? There is no
logic to prefer one flavor of path over another, it only depends on their
relative ordering in the `/proc/mounts` file.
[^2]: The exact path might be user-dependent, and is determined by the
function `hugetlbfs_find_path_for_size`
#### Providing the default event ring directory manually
You may wish to use this "open from the default directory" configuration idiom
while by-passing libhugetlbfs. The two reasons to do that are:
1. If you don't want the event ring file to be present on a hugetlbfs file
system at all; this is usually when you want to create an event ring file
larger than the hugetlbfs mount point (or the system's underlying pool of
huge pages) would allow
2. If you do not want to use libhugetlbfs as a library dependency of your
project, in which case you will want to set the CMake
`MONAD_EVENT_USE_LIBHUGETLBFS` option to `OFF`
### Convention 3: event ring filename resolution
The "default directory" concept is used in the final convention, which is a
"convenience" API call for turning user input for an event ring file into
the path where your program will attempt to open that file.
It allows users to specify a filename such as `xyz` and have it be translated
to a full (and ugly) path like this:
```
/var/lib/hugetlbfs/user/monad/pagesize-2MB/event-rings/xyz
```
while still allowing the user to be able to specify *any* file, including one
not in the default directory, if they wish.
Here is how event ring file inputs are resolved by the the C function
`monad_event_ring_resolve_file` and the Rust function `EventRingPath::resolve`:
* If a "pure" filename is provided (i.e., a filename with no `/` character),
it is resolved relative to a provided `default_path` directory
* Otherwise (i.e., if the file contains any `/` character), it is resolved
relative to the current working directory; if `/` is the first character,
it is resolved as an absolute path
This is similar to how a UNIX shell resolves a command name. A "pure" name
with no path characters is resolved relative to the entries in the `$PATH`
environment variable (i.e., it searches the default command directories). The
presence of a path-separator character causes the input to be treated like a
specific path relative to the current directory, which disables this "search".
This familiar principal applies here.
Furthermore:
* In C you usually pass the sentinel value `MONAD_EVENT_DEFAULT_HUGETLBFS`
(which is just an alias for `nullptr`) as the `default_path` parameter; this
causes `libhugetlbfs` to figure out what the default hugetlbfs root path
should be[^3]; in Rust this is just `EventRingPath::resolve`
* You can provide your own `default_path` value, which can be on any path on
any filesystem; this is required if you don't want `libhugetlbfs` as a
dependency; in Rust this is `EventRingPath::resolve_with_default_path`
<Note title="Resolution is only about _generating_ path names">
Resolution does not try to open a file: it just standardizes the convention for
how to build a path string from the two inputs. Namely, it does not check
whether the computed file path exists or not.
Remember that the event ring library itself only cares about file descriptors,
and none of its APIs (even the "helper" APIs) attempt to
[open(2)](https://man7.org/linux/man-pages/man2/open.2.html) a file. They just
provide "reasonable default" ways of locating files that programs can opt into.
If your host needs to set up your filesystem mounts differently, you are free to
do that.
</Note>
#### Examples
The table below shows how the C function `monad_event_ring_resolve_file`
behaves. `<cwd>` is the process' current working directory and `<htlbfs>`
is the mount point returned by `libhugetlbfs`.
| `default_path` value | `input` value | resolve file returns... | Notes |
| - | - | - | - |
| `MONAD_EVENT_DEFAULT_HUGETLBFS` | `"xyz"` | `"<htlbfs>/event-rings/xyz"` | |
| `MONAD_EVENT_DEFAULT_HUGETLBFS` | `"a/b/c"` | `"<cwd>/a/b/c"` | `default_path` only affects "pure" file names |
| `MONAD_EVENT_DEFAULT_HUGETLBFS ` | `"/d/e/f"` | `"/d/e/f"` | absolute paths always remain absolute |
| `MONAD_EVENT_DEFAULT_HUGETLBFS` | `"monad-exec-events"` | `"<htlbfs>/event-rings/monad-exec-events"` | the default event ring file name used by the execution daemon |
| `"/tmp/my-event-ring-path"` | `"xyz"` | `"/tmp/my-event-ring-path/xyz"` | intermediate directories will be created if not existing |
| `"/tmp/my-event-ring-path"` | `"a/b/c"` | `"<cwd>/a/b/c"` | |
| `"/tmp/my-event-ring-path"` | `"/d/e/f"` | `"/d/e/f"` | |
In Rust, `EventRingPath::resolve` behaves like the `MONAD_EVENT_DEFAULT_HUGETLBFS`
rows, and `EventRingPath::resolve_with_default_path` takes an explicit
`basepath` argument and behaves like the bottom three rows.
[^3]: The actual function used is the event ring library's utility function
`monad_event_open_hugetlbfs_dir_fd`, which adds in the `event-rings`
subdirectory path component and creates it if it does not already exist
# C API
Source: https://docs.monad.xyz/execution-events/c-api
## Core concepts
There are two central objects in the event ring C API. They are:
1. **struct `monad_event_ring`** - represents an event ring whose shared memory
segments have been mapped into the address space of the current process;
the primary thing the client does with this object is use it to initialize
iterators that point into the event ring, using the
`monad_event_ring_init_iterator` function
2. **struct `monad_event_iterator`** - the star of the show: this iterator
object is used to read sequential events. The iterator's `try_next`
operation copies the current event descriptor (if it is available) and
if successful, advances the iterator. Conceptually, it behaves like the
expression `descriptor = *i++`, if an event descriptor is ready immediately
(it does nothing otherwise)
The easiest way to understand the API is to compile and run the included
`eventwatch` example program. This program dumps ASCII representations of
execution events to `stdout`, as they are written by a execution daemon
running on the same host.
In `eventwatch`, the event descriptors are fully decoded, but the event
payloads are only shown in hexdump form, because this simple program that does
not include pretty-printing logic for all event payload types. The program is
only 250 lines of code, and reading through it should explain how the various
API calls fit together.
The SDK also includes C++20
[`std::formatter`](https://en.cppreference.com/w/cpp/utility/format/formatter.html)
specializations which can fully decode event payloads into human-readable form.
These are used by the `monad-event-cli` utility program.
## Using the API in your project
`libmonad_event` is designed for third party integration, so it does not have
any library dependencies aside from a recent version of glibc. This also means
it has no dependency on the rest of the monad repository or on its build
system: the sole requirement is a C compiler supporting C23.
The "Getting start" guide to building the C example program
[discusses several ways](/execution-events/getting-started/c#how-can-my-code-use-libmonad_event-a)
to use the SDK library as a third-party dependency in your code. Alternatively,
the source files that make up the library target can be copied into your own
codebase. A Rust client library is [also available](/execution-events/rust-api).
## API overview
### Event ring APIs
| API | Purpose |
| - | - |
| `monad_event_ring_mmap` | Given a file descriptor to an open event ring file, map its shared memory segments into the current process, initializing a `struct monad_event_ring` |
| `monad_event_ring_init_iterator` | Given a pointer to a `struct monad_event_ring`, initialize an iterator that can read from the event ring |
| `monad_event_ring_try_copy` | Given a specific sequence number, try to copy the event descriptor for it, if it hasn't been overwritten |
| `monad_event_ring_payload_peek` | Get a zero-copy pointer to an event payload |
| `monad_event_ring_payload_check` | Check if an event payload referred to by a zero-copy pointer has been overwritten |
| `monad_event_ring_memcpy` | `memcpy` the event payload to a buffer, succeeding only if the payload is not expired |
| `monad_event_ring_get_last_error` | Return a human-readable string describing the last error that occurred on this thread |
All functions which can fail will return an `errno(3)` domain error code
diagnosing the reason for failure. The function
`monad_event_ring_get_last_error` can be called to provide a human-readable
string explanation of what failed.
### Event iterator APIs
| API | Purpose |
| - | - |
| `monad_event_iterator_try_next` | If an event descriptor if is available, copy it and advance the iterator; behaves like `*i++`, but only if `*i` is ready |
| `monad_event_iterator_try_copy` | Copy the event descriptor at the current iteration point, without advancing the iterator |
| `monad_event_iterator_reset` | Reset the iterator to point to the most recently produced event descriptor; used for gap recovery |
| `monad_exec_iter_consensus_prev` | Rewinds an iterator to the previous consensus event (`BLOCK_START`, `BLOCK_QC`, `BLOCK_FINALIZED`, or `BLOCK_VERIFIED`) |
| `monad_exec_iter_block_number_prev` | Rewinds an iterator to the previous consensus event for the given block number |
| `monad_exec_iter_block_id_prev` | Rewinds an iterator to the previous consensus event for the given block ID |
| `monad_exec_iter_rewind_for_simple_replay` | Rewinds an iterator to replay events you may have missed, based on the last finalized block you saw |
### Event ring utility APIs
| API | Purpose |
| - | - |
| `monad_event_ring_check_content_type` | Check if the binary layouts of event definitions used by the library match what is recorded in a mapped event ring |
| `monad_event_ring_find_writer_pids` | Find processes that have opened an event ring file descriptor for writing; used for detecting publisher exit |
| `monad_check_path_supports_map_hugetlb` | Check if a path is on a filesystem that allows its files to be mmap'ed with `MAP_HUGETLB` |
| `monad_event_open_hugetlbfs_dir_fd` | Open the default hugetlbfs directory where event ring files are created[^1] |
| `monad_event_resolve_ring_file` | If a path contains no `/` character (i.e., if it is a "pure" filename), resolve it relative to some default event ring directory[^2] |
| `monad_event_is_snapshot_file` | Check if a path refers to an event ring snapshot file |
| `monad_event_decompress_snapshot_fd` | Decompress the event ring snapshot contained in the given file descriptor |
| `monad_event_decompress_snapshot_mem` | Decompress the event ring snapshot contained in the given memory buffer |
[^1]: By default, this returns the a path on a hugetlbfs mount, as computed by
libhugetlbfs
[^2]: If compiling with `MONAD_EVENT_USE_LIBHUGETLBFS=OFF`, a default event
ring directory must be specified; see
[here](/execution-events/advanced#location-of-event-ring-files) for details
## Library organization
Event ring files in `libmonad_event`:
| File | Contains |
| - | - |
| `event_ring.{h,c}` | Definitions of core shared memory structures for event rings, and the API that initializes and mmaps event ring files |
| `event_iterator.h` | Defines the basic event iterator object and its API |
| `event_iterator_inline.h` | Definitions of the `event_iterator.h` functions, all of which are inlined for performance reasons |
| `event_metadata.h` | Structures that describe event metadata (string names of events, descriptions of events, etc.) |
| `exec_iter_help.h` | API for rewinding the the iterator to point to block executions or consensus events |
Execution event files in `libmonad_event`:
| File | Contains |
| - | - |
| `base_ctypes.h` | Definitions of basic vocabulary types common in Ethereum data (e.g., 256 bit integer types, etc). |
| `eth_ctypes.h` | Definitions of structures used in the Ethereum virtual machine |
| `exec_event_ctypes.h` | Definition of execution event payload structures, and the event type enumeration `enum monad_exec_event_type` |
| `exec_event_ctypes_metadata.c` | Defines static metadata about execution events, and the schema hash value array |
| `monad_ctypes.h` | Definitions of Monad blockchain extensions to Ethereum |
Supporting files in `libmonad_event`:
| File | Contains |
| - | - |
| `event_ring_util.{h,c}` | Convenience functions that are useful in most event ring programs, but which are not part of the core API |
| `format_err.{h,c}` | Helper utility from the execution codebase used to implement the `monad_event_ring_get_last_error()` function |
| `srcloc.h` | Helper utility used with the `format_err.h` API, for capturing source code locations in C |
Other files in the SDK:
| File | Contents |
| - | - |
| `eventwatch.c` | A sample program that shows how to use the API |
| `*_fmt.hpp` files | Files ending in `_fmt.hpp` are used with C++ `<format>` and contain `std::formatter` specializations for SDK types |
| `hex.hpp` | `<format>` hexdump utility used by the `_fmt.hpp` files to dump `uint8_t[]` values |
# Consensus events
Source: https://docs.monad.xyz/execution-events/consensus-events
As explained [here](/monad-arch/consensus/asynchronous-execution),
Monad's consensus and execution services are decoupled, and execution is
asynchronous with the respect to consensus: the two don't have to move in
lock step, and can working on different blocks. Also, execution can
[speculatively execute](/monad-arch/consensus/asynchronous-execution#speculative-execution)
blocks whose consensus outcome is not yet known.
Execution events are "trace" information reported directly from the EVM during
execution, so they report real-time data on *speculative* basis: the event data
may relate to a block that is never finalized.
Dealing with real-time data on a speculative basis is discussed in detail on
[this page](/monad-arch/realtime-data/spec-realtime). The "takeaway"
from that part of the documentation is the following: if you consume
speculative real-time data, then you need to understand
[block commit states](/monad-arch/consensus/block-states) and how the
real-time data protocol you're using communicates the changes in block states.
For example, for the Monad WebSocket extension feeds,
[this section](/reference/json-rpc/overview#speculative-subscription-behavior)
explains how the block IDs and commit states are announced for the
`monadNewHeads` subscription. This documentation page explains how it
is done with execution events.
## Block tags
As explained
[here](/monad-arch/realtime-data/spec-realtime#block-numbers-and-block-ids),
blocks must be identified by their unique ID prior to finalization. Even so,
it is often useful to know what the proposed block number is, even before we
know if the block will committed with that number or not. The following
structure -- called a "block tag" -- appears as a field in several execution
event payload types, to communicate the block ID and the (proposed) block
number together.
```
struct monad_exec_block_tag
{
monad_c_bytes32 id; ///< Monad consensus unique ID for block
uint64_t block_number; ///< Proposal is to become this block
};
```
## The four consensus events
The four [block commit states](/monad-arch/consensus/block-states)
correspond to four execution event types. Events of these types are published
to announce that a particular block is moving to a new commit state.
### First consensus event: **`BLOCK_START`** (*proposed* state)
```c theme={null}
/// Event recorded at the start of block execution
struct monad_exec_block_start
{
struct monad_exec_block_tag
block_tag; ///< Execution is for this block
uint64_t block_round; ///< Round when block was proposed
uint64_t epoch; ///< Epoch when block was proposed
monad_c_bytes32 parent_eth_hash; ///< Hash of Ethereum parent block
monad_c_uint256_ne chain_id; ///< Block chain we're associated with
struct monad_c_eth_block_exec_input
exec_input; ///< Ethereum execution inputs
};
```
The first event recorded by the EVM is a `BLOCK_START` event, whose event
payload contains a `block_tag` field that introduces the unique ID for the
block and the block number it will eventually have, if it gets finalized.
Almost all execution events (transaction logs, call frames, receipts, etc.)
occur between the `BLOCK_START` and `BLOCK_END` events. In the current
implementation, block execution is never pipelined, so all events between
`BLOCK_START` and `BLOCK_END` pertain to a single block, and there will not
be another `BLOCK_START` until the current block is ended.
Unlike the other events in this list, `BLOCK_START` is both a "consensus
event" (it means the프로젝트로 돌아가기