bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 61쪽
c<RollupConfig>,
/// The PayloadId being sealed.
pub payload_id: PayloadId,
/// The OpAttributesWithParent to instruct the execution layer to build.
pub attributes: OpAttributesWithParent,
/// Whether or not the payload was derived, or created by the sequencer.
pub is_attributes_derived: bool,
/// An optional sender for the built OpExecutionPayloadEnvelope or the
/// SealTaskError that occurred during processing.
pub result_tx: Option<mpsc::Sender<Result<OpExecutionPayloadEnvelope, SealTaskError>>>,
}
```
#### InsertTask
Inserts payloads (for example unsafe blocks received from gossip) into the execution engine:
```rust theme={null}
pub struct InsertTask<EngineClient_: EngineClient> {
/// The engine client.
client: Arc<EngineClient_>,
/// The rollup config.
rollup_config: Arc<RollupConfig>,
/// The network payload envelope.
envelope: OpExecutionPayloadEnvelope,
/// If the payload is safe this is true.
is_payload_safe: bool,
}
```
#### ConsolidateTask
Advances the safe chain through derivation:
```rust theme={null}
pub struct ConsolidateTask<EngineClient_: EngineClient> {
/// The engine client.
pub client: Arc<EngineClient_>,
/// The RollupConfig.
pub cfg: Arc<RollupConfig>,
/// The input for consolidation (either attributes or block info).
pub input: ConsolidateInput,
}
```
If consolidation fails, the task reverts to payload attribute processing via the `BuildTask`.
#### FinalizeTask
Finalizes L2 blocks:
```rust theme={null}
pub struct FinalizeTask<EngineClient_: EngineClient> {
/// The engine client.
pub client: Arc<EngineClient_>,
/// The rollup config.
pub cfg: Arc<RollupConfig>,
/// Identifier of the L2 block to finalize.
pub block_id: FinalizeBlockId,
}
```
## Engine State Management
The `EngineState` tracks the current state of the execution engine:
```rust theme={null}
pub struct EngineState {
/// The sync state of the engine.
pub sync_state: EngineSyncState,
/// Whether or not the EL has finished syncing.
pub el_sync_finished: bool,
/// Tracks when the rollup node changes the forkchoice to restore a
/// previously known unsafe chain (e.g. an unsafe reorg caused by an
/// invalid span batch).
pub need_fcu_call_backup_unsafe_reorg: bool,
}
```
The unsafe, safe, and finalized heads live in the nested `EngineSyncState`. State updates are communicated through watch channels, enabling reactive programming patterns across the system.
## Integration with kona-node
The `kona-node` service layer integrates the engine through the `EngineActor`:
### Actor Pattern
The `EngineActor` implements the `NodeActor` trait:
```rust theme={null}
#[async_trait]
pub trait NodeActor: Send + 'static {
/// The error type for the actor.
type Error: std::fmt::Debug;
/// Handle the next inbound request, event, or scheduled tick.
async fn step(&mut self) -> Result<(), Self::Error>;
}
```
### Communication Channels
The `EngineActor` receives all state-mutating input through a single inbound request channel of `EngineActorRequest` messages: payload attributes from derivation, unsafe blocks from gossip, reset requests, finalization requests, and block building requests (sequencer mode only). A separate read-only `EngineRpcActor` runs as an independent peer and serves engine queries; it shares the engine client and a watch over the engine state and queue length, but is constrained to a read-only subset of the engine client so it cannot reach Engine API mutation methods.
### Engine Queries
The engine supports queries for:
```rust theme={null}
pub enum EngineQueries {
/// Request the current rollup configuration.
Config(Sender<RollupConfig>),
/// Request the current EngineState snapshot.
State(Sender<EngineState>),
/// Request the L2 output root for a specific block.
OutputAtBlock { block: BlockNumberOrTag, sender: Sender<(L2BlockInfo, OutputRoot, EngineState)> },
/// Subscribe to engine state updates via a watch channel receiver.
StateReceiver(Sender<tokio::sync::watch::Receiver<EngineState>>),
/// Development API: Subscribe to task queue length updates.
QueueLengthReceiver(Sender<tokio::sync::watch::Receiver<usize>>),
/// Development API: Get the current number of pending tasks in the queue.
TaskQueueLength(Sender<usize>),
}
```
## Usage Patterns
### Basic Engine Setup
```rust theme={null}
// Create an engine client. The `EngineClient` trait is implemented by
// `OpEngineClient`, constructed through the `EngineClientBuilder`.
let client = EngineClientBuilder {
l2: l2_engine_url,
l2_jwt: jwt_secret,
l1_rpc: l1_rpc_url,
cfg: rollup_config,
}
.build();
// Initialize engine state
let state = EngineState::default();
let (state_sender, state_receiver) = watch::channel(state);
let (queue_length_sender, queue_length_receiver) = watch::channel(0);
// Create engine with task queue
let engine = Engine::new(state, state_sender, queue_length_sender);
```
### Adding Tasks
```rust theme={null}
// Add a consolidate task
let task = EngineTask::Consolidate(Box::new(ConsolidateTask::new(
client.clone(),
rollup_config.clone(),
input,
)));
engine.enqueue(task);
```
### Draining the Queue
```rust theme={null}
// Process all pending tasks
match engine.drain().await {
Ok(()) => info!("Tasks completed successfully"),
Err(e) => match e.severity() {
EngineTaskErrorSeverity::Reset => {
// Request derivation reset
},
EngineTaskErrorSeverity::Critical => {
// Handle critical error
},
_ => {
// Handle other error types
}
}
}
```
## Error Handling and Recovery
The engine provides robust error handling through:
### Severity-Based Recovery
* **Temporary errors**: Automatically retried
* **Critical errors**: Propagated to the actor
* **Reset errors**: Trigger derivation pipeline reset
* **Flush errors**: Trigger derivation pipeline flush
### State Consistency
Tasks operate atomically on the `EngineState`, ensuring consistency even during error conditions.
## Version Support
The engine automatically selects appropriate Engine API versions based on hardfork activation:
* **Pre-Ecotone (Bedrock, Canyon, Delta)**: Uses `engine_newPayloadV2` and `engine_getPayloadV2`
* **Post-Ecotone**: Uses `engine_newPayloadV3` and `engine_getPayloadV3`
* **Post-Isthmus**: Uses `engine_newPayloadV4` and `engine_getPayloadV4`
* **Post-Karst (Osaka)**: Uses `engine_getPayloadV5` (`engine_newPayload` and `engine_forkchoiceUpdated` stay at their V4/V3 versions)
## Metrics and Observability
When the `metrics` feature is enabled, the engine provides comprehensive metrics for:
* Task execution times
* Error rates by task type
* Engine state transitions
* API call latencies
## Extensibility
The trait-based architecture allows for:
* **Custom task implementations** via `EngineTaskExt`
* **Custom error handling** via `EngineTaskError`
* **Custom state management** extensions
* **Testing and mocking** support
This modular design ensures the engine can adapt to future OP Stack protocol changes while maintaining backward compatibility.
# Node Design Overview
Source: https://docs.optimism.io/node-operators/kona-node/design/intro
The entry-point for the `kona-node` is the [`RollupNode`][node] service,
which encapsulates the core wiring for the node. A `RollupNode` is
constructed through the [`RollupNodeBuilder`][builder], and its
[`start` method][start] handles connecting all the different components
of the node, running each in a spawned task. As such, each node
component is considered an actor.
The `RollupNode` abstracts individual actors through the
[`NodeActor` trait][actor], a minimal interface with a single `step`
method that the service drives in a loop until the actor reports a
fatal error or the node shuts down.
Kona provides implementations for all `NodeActor`s required to run a
`RollupNode`. Actors are defined in the [actors][actors] module of the
`kona-node-service` crate, and the `RollupNode` wiring lives in the
[service][service] module.
### Actors
The architecture of `kona-node` is a web of actors that share
state through message passing, using channels, rather than using
shared memory.
The [`RollupNode`][node] builds and starts the following actors.
* **Derivation Actor**: Orchestrates the derivation pipeline,
deriving L2 payload attributes from L1 blocks. Payload
attributes prepared this way are forwarded to the Engine
Actor to be executed. The [derivation][derivation] docs
dive deeper into how the derivation actor works.
* **Engine Actor**: Brokers the connection to the execution
layer client (or "execution engine"). The engine actor
turns messages from other actors into engine "tasks"
that are executed in priority order against the EL client.
A companion engine RPC actor serves read-only engine
queries. The [engine][engine] docs expand on this.
* **L1 Watcher Actor**: Watches the L1 chain for new
head and finalized blocks and relays them to the
derivation actor. It also keeps the unsafe block
signer current from the `SystemConfig` contract, for
gossip validation and the signer actor.
* **Network Actor**: Manages the P2P Network for the rollup
node. The P2P stack consists of `discv5` peer discovery
and block gossip through libp2p. Visit the [network][p2p]
docs for more detail.
* **Sequencer Actor**: The sequencer actor extends the
`kona-node` to be run as a sequencer. Sequencing is
periphery to the basic rollup node operation. See
the [sequencer][sequencer] docs.
* **Signer Actor**: Runs alongside the sequencer actor.
It signs each block the sequencer builds, in order,
and passes it to the network actor to gossip.
* **RPC Actor**: The RPC actor spins up and serves an
RPC server that exposes the rpc methods required by
the [OP Stack Specs][specs].
[p2p]: ./p2p
[engine]: ./engine
[derivation]: ./derivation
[sequencer]: ./sequencer
[specs]: https://specs.optimism.io/protocol/rollup-node.html
[service]: https://github.com/ethereum-optimism/optimism/tree/develop/rust/kona/crates/node/service/src/service
[actors]: https://github.com/ethereum-optimism/optimism/tree/develop/rust/kona/crates/node/service/src/actors
[actor]: https://github.com/ethereum-optimism/optimism/blob/develop/rust/kona/crates/node/service/src/actors/traits.rs
[start]: https://github.com/ethereum-optimism/optimism/blob/develop/rust/kona/crates/node/service/src/service/node.rs
[node]: https://github.com/ethereum-optimism/optimism/blob/develop/rust/kona/crates/node/service/src/service/node.rs
[builder]: https://github.com/ethereum-optimism/optimism/blob/develop/rust/kona/crates/node/service/src/service/builder.rs
# P2P Networking
Source: https://docs.optimism.io/node-operators/kona-node/design/p2p
<Info>
Partly adapted from the [OP Stack P2P Specs][p2p-specs].
Please reference the specs for up-to-date OP Stack requirements.
</Info>
The OP Stack uses P2P networking on the consensus layer to share
the sequencer's view of the L2 chain with other nodes on the
network. L2 blocks shared via P2P are considered "unsafe", and
will be reorganized to match the canonical chain, prioritizing L1.
This means that behavior on the P2P layer does not affect the
rollup security. As such, rules around banning and scoring peers
based on their P2P gossip is policy - it is up to the user to
ultimately choose a configuration best for them.
To understand how the P2P is hooked up to the `kona-node`, jump
to the [P2P Actor](#p2p-actor) section below. Otherwise, read
on to learn more about the details of the P2P stack.
### Topography
The P2P stack topography consists of the following.
* Discovery of peers via [discv5][discv5].
* Gossip and peer connection management through [libp2p][libp2p].
* Publishing and validation of gossip by the node.
In the `kona-node`, these layers are split up into modular
components either as modules or distinct crates.
#### Discovery
Kona's discovery layer is encapsulated in a "driver" called
the [`Discv5Driver`][driver]. When started, the driver spawns a
new thread to handle [`discv5::Discv5`][discv5-service] events
from its event stream as well as metrics requests from the
`kona-node`. A "handler" is returned by the consumed
[`Discv5Driver`][driver] which allows other components of
the `kona-node` to communicate through channels to the
spawned [`discv5::Discv5`][discv5-service] service.
When peers are discovered by kona's discovery service, their
"ENR"s need to be validated to ensure those peers are
participating in the right network gossip. Ethereum Node
Records (ENRs) and how they are validated is discussed in a
[later section](#node-identification). After their ENRs are
validated, they are forwarded to the consumer (in kona's case
libp2p) which establishes and manages the connection to the
node.
There are also a few more notable functions of Kona's discovery
driver.
* Every X seconds it attempts to discover random ENRs. This is
configurable using `Discv5Builder::with_interval`
* Every Y seconds it evicts a random ENR from the discovery
table to keep peer discovery fresh. This is configurable
using `Discv5Builder::with_discovery_randomize`.
* Every Z seconds it stores its ENR table at a configurable
location so if the service is restarted, it doesn't need to
rediscover peers, it can just use the stored peers. The
interval is configurable using
`Discv5Builder::with_store_interval`.
#### Gossip
L2 blocks on the OP Stack not otherwise derived from L1 are
shared over TCP in the P2P network of nodes. Unsafe L2 blocks
shared this way originate from the sequencer.
In the `kona-node`, L2 block gossip is handled through the
[libp2p Swarm][swarm]. The `GossipDriver` is the component
in the `kona-node` that manages the libp2p swarm, including
any interfacing with the swarm like dialing peers, publishing
payloads (L2 blocks), handling events from the swarm, and more.
<Info>
The libp2p swarm must be polled via Swarm as Stream
in order to make progress.
Through kona's `GossipDriver`, this can be done by looping
over and consuming events from `GossipDriver::next`.
</Info>
The `GossipDriver` provides the methods to handle events
from the [libp2p Swarm][swarm]. Events should be consumed
this way in order to use the connection gater as well as peer
store and fields on the `GossipDriver`.
The [libp2p Swarm][swarm] listens on a specified
[`Multiaddr`][multiaddr].
#### L2 Block Publishing
As mentioned in [the previous section](#gossip), L2 blocks
are published as payloads through the [libp2p Swarm][swarm],
which is done using the `GossipDriver`. The `GossipDriver` accepts an `OpExecutionPayloadEnvelope` and its
signature, then privately encodes them in the wire format documented
in the [OP Stack P2P Specs][p2p-specs].
L2 blocks published through the `GossipDriver` are published on
a "topic". The topic is used by the gossipsub protocol to publish
the message on that given topic, allowing peers to choose which
topics they wish to subscribe to.
#### L2 Block Validation
L2 blocks are validated in kona through a trait-abstracted
"block handler". Since messages in the libp2p mesh network are
snappy compressed, they need to be decompressed and then decoded
for the correct [block topic][block-topic] those messages are
published on.
After decompression, kona separates the signature from the exact encoded
envelope bytes. It authenticates those bytes before decoding the envelope
according to the corresponding block topic and validating the block contents.
<Info>
Block validity in kona follows the [OP Stack block validation specs][validation].
</Info>
As of writing these docs, block validation follows a few rules.
* The timestamp is between 60 seconds in the past and at most 5 seconds in the future.
* The block signature authenticates the exact encoded envelope bytes.
* The block hash is valid. This is checked by computing the transaction trie root directly from
the encoded transaction bytes and hashing the reconstructed header. Transaction decoding and
execution remain the execution layer's responsibility.
* The contents of the payload envelope are correct for its version. Since different
versions introduce new contents to the payload from hardforks, the
forwards-compatible payload envelope cannot have fields with content that don't exist
for previous versions.
### Node Identification
TODO
### P2P Actor
TODO
[validation]: https://specs.optimism.io/protocol/rollup-node-p2p.html#block-validation
[block-topic]: https://specs.optimism.io/protocol/rollup-node-p2p.html#gossip-topics
[multiaddr]: https://docs.rs/libp2p/0.56.0/libp2p/struct.Multiaddr.html
[swarm]: https://docs.rs/libp2p/latest/libp2p/struct.Swarm.html
[discv5-service]: https://docs.rs/discv5/latest/discv5/struct.Discv5.html
[driver]: https://github.com/ethereum-optimism/optimism/blob/develop/rust/kona/crates/node/disc/src/driver.rs
[discv5]: https://github.com/ethereum/devp2p/blob/master/discv5/discv5.md
[libp2p]: https://libp2p.io/
[p2p-specs]: https://specs.optimism.io/protocol/rollup-node-p2p.html
# Sequencer Mode
Source: https://docs.optimism.io/node-operators/kona-node/design/sequencer
Understand how the kona-node sequencer actor builds L2 blocks, and the trait abstractions and programmatic configuration behind sequencer mode.
The Kona node can operate in **sequencer mode** to build and produce new L2 blocks. In this mode, the node acts as the sequencer for an OP Stack rollup, building L2 blocks on top of the current unsafe head and extending the L2 chain.
This page explains the design of sequencer mode and how to configure it programmatically through the Node SDK. To run `kona-node` as a sequencer from the command line, follow the [run a sequencer node](/node-operators/kona-node/run/sequencer) guide.
## Overview
When running in sequencer mode, the Kona node:
* **Builds L2 blocks** by collecting transactions from the mempool and constructing new blocks
* **Selects L1 origins** for new L2 blocks based on finalized L1 data
* **Manages block production timing** and ensures proper sequencing constraints
* **Integrates with conductor services** for leader election in multi-sequencer setups
* **Handles recovery scenarios** when the sequencer needs to catch up with L1
The sequencer uses the same core derivation pipeline as validator nodes but operates in reverse - instead of deriving L2 blocks from L1 data, it produces L2 blocks that will later be derivable from L1.
## Core Components
### `NodeMode`
The node's operational mode is expressed by the `NodeMode` enum, carried on the node's `EngineConfig`:
```rust theme={null}
pub enum NodeMode {
/// Validator mode.
Validator,
/// Sequencer mode.
Sequencer,
}
```
### `SequencerActor`
The core actor responsible for block production. Like every node component, it implements the `NodeActor` trait:
* Builds L2 blocks using the attributes builder
* Manages timing and L1 origin selection
* Handles admin RPC commands for sequencer control
* Coordinates with conductor services for leader election
### `SequencerConfig`
Sequencer behavior is configured through the `SequencerConfig` struct:
```rust theme={null}
pub struct SequencerConfig {
/// Whether or not the sequencer is enabled at startup.
pub sequencer_stopped: bool,
/// Whether or not the sequencer is in recovery mode.
pub sequencer_recovery_mode: bool,
/// The Url for the conductor RPC endpoint. If Some, enables the conductor service.
pub conductor_rpc_url: Option<Url>,
/// The confirmation delay for the sequencer.
pub l1_conf_delay: u64,
}
```
## Programmatic Configuration
### Using the RollupNodeBuilder
To configure a Kona node programmatically for sequencer mode, set `NodeMode::Sequencer` on the `EngineConfig` and pass a `SequencerConfig` to the `RollupNodeBuilder`:
```rust theme={null}
use kona_node_service::{NodeMode, RollupNodeBuilder, SequencerConfig};
// Configure sequencer settings
let sequencer_config = SequencerConfig {
sequencer_stopped: false, // Start sequencer immediately
sequencer_recovery_mode: false, // Normal operation mode
conduct프로젝트로 돌아가기