Repository navigation
Expand file tree
/
Copy pathmain.rs
More file actions
407 lines (351 loc) · 13 KB
/
Copy pathmain.rs
File metadata and controls
407 lines (351 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! This example shows how to implement a custom [EngineTypes].
//!
//! The [EngineTypes] trait can be implemented to configure the engine to work with custom types,
//! as long as those types implement certain traits.
//!
//! Custom payload attributes can be supported by implementing two main traits:
//!
//! [PayloadAttributes] can be implemented for payload attributes types that are used as
//! arguments to the `engine_forkchoiceUpdated` method. This type should be used to define and
//! _spawn_ payload jobs.
//!
//! [PayloadBuilderAttributes] can be implemented for payload attributes types that _describe_
//! running payload jobs.
//!
//! Once traits are implemented and custom types are defined, the [EngineTypes] trait can be
//! implemented:
#![cfg_attr(not(test), warn(unused_crate_dependencies))]
use std::{convert::Infallible, sync::Arc};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use alloy_genesis::Genesis;
use alloy_primitives::{Address, B256};
use alloy_rpc_types::{
engine::{
ExecutionPayloadEnvelopeV2, ExecutionPayloadEnvelopeV3, ExecutionPayloadEnvelopeV4,
ExecutionPayloadV1, PayloadAttributes as EthPayloadAttributes, PayloadId,
},
Withdrawal,
};
use reth::{
api::PayloadTypes,
builder::{
components::{ComponentsBuilder, PayloadServiceBuilder},
node::{NodeTypes, NodeTypesWithEngine},
rpc::{EngineValidatorBuilder, RpcAddOns},
BuilderContext, FullNodeTypes, Node, NodeAdapter, NodeBuilder, NodeComponentsBuilder,
PayloadBuilderConfig,
},
network::NetworkHandle,
providers::{CanonStateSubscriptions, StateProviderFactory},
rpc::eth::EthApi,
tasks::TaskManager,
transaction_pool::TransactionPool,
};
use reth_basic_payload_builder::{
BasicPayloadJobGenerator, BasicPayloadJobGeneratorConfig, BuildArguments, BuildOutcome,
PayloadBuilder, PayloadConfig,
};
use reth_chainspec::{Chain, ChainSpec, ChainSpecProvider};
use reth_node_api::{
payload::{EngineApiMessageVersion, EngineObjectValidationError, PayloadOrAttributes},
validate_version_specific_fields, AddOnsContext, EngineTypes, EngineValidator,
FullNodeComponents, PayloadAttributes, PayloadBuilderAttributes,
};
use reth_node_core::{args::RpcServerArgs, node_config::NodeConfig};
use reth_node_ethereum::{
node::{
EthereumConsensusBuilder, EthereumExecutorBuilder, EthereumNetworkBuilder,
EthereumParliaBuilder, EthereumPoolBuilder,
},
EthEvmConfig,
};
use reth_payload_builder::{
EthBuiltPayload, EthPayloadBuilderAttributes, PayloadBuilderError, PayloadBuilderHandle,
PayloadBuilderService,
};
use reth_primitives::Withdrawals;
use reth_tracing::{RethTracer, Tracer};
use reth_trie_db::MerklePatriciaTrie;
/// A custom payload attributes type.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CustomPayloadAttributes {
/// An inner payload type
#[serde(flatten)]
pub inner: EthPayloadAttributes,
/// A custom field
pub custom: u64,
}
/// Custom error type used in payload attributes validation
#[derive(Debug, Error)]
pub enum CustomError {
#[error("Custom field is not zero")]
CustomFieldIsNotZero,
}
impl PayloadAttributes for CustomPayloadAttributes {
fn timestamp(&self) -> u64 {
self.inner.timestamp()
}
fn withdrawals(&self) -> Option<&Vec<Withdrawal>> {
self.inner.withdrawals()
}
fn parent_beacon_block_root(&self) -> Option<B256> {
self.inner.parent_beacon_block_root()
}
}
/// New type around the payload builder attributes type
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CustomPayloadBuilderAttributes(EthPayloadBuilderAttributes);
impl PayloadBuilderAttributes for CustomPayloadBuilderAttributes {
type RpcPayloadAttributes = CustomPayloadAttributes;
type Error = Infallible;
fn try_new(
parent: B256,
attributes: CustomPayloadAttributes,
_version: u8,
) -> Result<Self, Infallible> {
Ok(Self(EthPayloadBuilderAttributes::new(parent, attributes.inner)))
}
fn payload_id(&self) -> PayloadId {
self.0.id
}
fn parent(&self) -> B256 {
self.0.parent
}
fn timestamp(&self) -> u64 {
self.0.timestamp
}
fn parent_beacon_block_root(&self) -> Option<B256> {
self.0.parent_beacon_block_root
}
fn suggested_fee_recipient(&self) -> Address {
self.0.suggested_fee_recipient
}
fn prev_randao(&self) -> B256 {
self.0.prev_randao
}
fn withdrawals(&self) -> &Withdrawals {
&self.0.withdrawals
}
}
/// Custom engine types - uses a custom payload attributes RPC type, but uses the default
/// payload builder attributes type.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[non_exhaustive]
pub struct CustomEngineTypes;
impl PayloadTypes for CustomEngineTypes {
type BuiltPayload = EthBuiltPayload;
type PayloadAttributes = CustomPayloadAttributes;
type PayloadBuilderAttributes = CustomPayloadBuilderAttributes;
}
impl EngineTypes for CustomEngineTypes {
type ExecutionPayloadEnvelopeV1 = ExecutionPayloadV1;
type ExecutionPayloadEnvelopeV2 = ExecutionPayloadEnvelopeV2;
type ExecutionPayloadEnvelopeV3 = ExecutionPayloadEnvelopeV3;
type ExecutionPayloadEnvelopeV4 = ExecutionPayloadEnvelopeV4;
}
/// Custom engine validator
#[derive(Debug, Clone)]
pub struct CustomEngineValidator {
chain_spec: Arc<ChainSpec>,
}
impl<T> EngineValidator<T> for CustomEngineValidator
where
T: EngineTypes<PayloadAttributes = CustomPayloadAttributes>,
{
fn validate_version_specific_fields(
&self,
version: EngineApiMessageVersion,
payload_or_attrs: PayloadOrAttributes<'_, T::PayloadAttributes>,
) -> Result<(), EngineObjectValidationError> {
validate_version_specific_fields(&self.chain_spec, version, payload_or_attrs)
}
fn ensure_well_formed_attributes(
&self,
version: EngineApiMessageVersion,
attributes: &T::PayloadAttributes,
) -> Result<(), EngineObjectValidationError> {
validate_version_specific_fields(&self.chain_spec, version, attributes.into())?;
// custom validation logic - ensure that the custom field is not zero
if attributes.custom == 0 {
return Err(EngineObjectValidationError::invalid_params(
CustomError::CustomFieldIsNotZero,
))
}
Ok(())
}
}
/// Custom engine validator builder
#[derive(Debug, Default, Clone, Copy)]
#[non_exhaustive]
pub struct CustomEngineValidatorBuilder;
impl<N> EngineValidatorBuilder<N> for CustomEngineValidatorBuilder
where
N: FullNodeComponents<
Types: NodeTypesWithEngine<Engine = CustomEngineTypes, ChainSpec = ChainSpec>,
>,
{
type Validator = CustomEngineValidator;
async fn build(self, ctx: &AddOnsContext<'_, N>) -> eyre::Result<Self::Validator> {
Ok(CustomEngineValidator { chain_spec: ctx.config.chain.clone() })
}
}
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
struct MyCustomNode;
/// Configure the node types
impl NodeTypes for MyCustomNode {
type Primitives = ();
type ChainSpec = ChainSpec;
type StateCommitment = MerklePatriciaTrie;
}
/// Configure the node types with the custom engine types
impl NodeTypesWithEngine for MyCustomNode {
type Engine = CustomEngineTypes;
}
/// Custom addons configuring RPC types
pub type MyNodeAddOns<N> = RpcAddOns<
N,
EthApi<
<N as FullNodeTypes>::Provider,
<N as FullNodeComponents>::Pool,
NetworkHandle,
<N as FullNodeComponents>::Evm,
>,
CustomEngineValidatorBuilder,
>;
/// Implement the Node trait for the custom node
///
/// This provides a preset configuration for the node
impl<N> Node<N> for MyCustomNode
where
N: FullNodeTypes<Types: NodeTypesWithEngine<Engine = CustomEngineTypes, ChainSpec = ChainSpec>>,
{
type ComponentsBuilder = ComponentsBuilder<
N,
EthereumPoolBuilder,
CustomPayloadServiceBuilder,
EthereumNetworkBuilder,
EthereumExecutorBuilder,
EthereumConsensusBuilder,
EthereumParliaBuilder,
>;
type AddOns = MyNodeAddOns<
NodeAdapter<N, <Self::ComponentsBuilder as NodeComponentsBuilder<N>>::Components>,
>;
fn components_builder(&self) -> Self::ComponentsBuilder {
ComponentsBuilder::default()
.node_types::<N>()
.pool(EthereumPoolBuilder::default())
.payload(CustomPayloadServiceBuilder::default())
.network(EthereumNetworkBuilder::default())
.executor(EthereumExecutorBuilder::default())
.consensus(EthereumConsensusBuilder::default())
.parlia(EthereumParliaBuilder::default())
}
fn add_ons(&self) -> Self::AddOns {
MyNodeAddOns::default()
}
}
/// A custom payload service builder that supports the custom engine types
#[derive(Debug, Default, Clone)]
#[non_exhaustive]
pub struct CustomPayloadServiceBuilder;
impl<Node, Pool> PayloadServiceBuilder<Node, Pool> for CustomPayloadServiceBuilder
where
Node: FullNodeTypes<
Types: NodeTypesWithEngine<Engine = CustomEngineTypes, ChainSpec = ChainSpec>,
>,
Pool: TransactionPool + Unpin + 'static,
{
async fn spawn_payload_service(
self,
ctx: &BuilderContext<Node>,
pool: Pool,
) -> eyre::Result<PayloadBuilderHandle<<Node::Types as NodeTypesWithEngine>::Engine>> {
let payload_builder = CustomPayloadBuilder::default();
let conf = ctx.payload_builder_config();
let payload_job_config = BasicPayloadJobGeneratorConfig::default()
.interval(conf.interval())
.deadline(conf.deadline())
.max_payload_tasks(conf.max_payload_tasks())
.extradata(conf.extradata_bytes());
let payload_generator = BasicPayloadJobGenerator::with_builder(
ctx.provider().clone(),
pool,
ctx.task_executor().clone(),
payload_job_config,
payload_builder,
);
let (payload_service, payload_builder) =
PayloadBuilderService::new(payload_generator, ctx.provider().canonical_state_stream());
ctx.task_executor().spawn_critical("payload builder service", Box::pin(payload_service));
Ok(payload_builder)
}
}
/// The type responsible for building custom payloads
#[derive(Debug, Default, Clone)]
#[non_exhaustive]
pub struct CustomPayloadBuilder;
impl<Pool, Client> PayloadBuilder<Pool, Client> for CustomPayloadBuilder
where
Client: StateProviderFactory + ChainSpecProvider<ChainSpec = ChainSpec>,
Pool: TransactionPool,
{
type Attributes = CustomPayloadBuilderAttributes;
type BuiltPayload = EthBuiltPayload;
fn try_build(
&self,
args: BuildArguments<Pool, Client, Self::Attributes, Self::BuiltPayload>,
) -> Result<BuildOutcome<Self::BuiltPayload>, PayloadBuilderError> {
let BuildArguments { client, pool, cached_reads, config, cancel, best_payload } = args;
let PayloadConfig { parent_header, extra_data, attributes } = config;
let chain_spec = client.chain_spec();
// This reuses the default EthereumPayloadBuilder to build the payload
// but any custom logic can be implemented here
reth_ethereum_payload_builder::EthereumPayloadBuilder::new(EthEvmConfig::new(
chain_spec.clone(),
))
.try_build(BuildArguments {
client,
pool,
cached_reads,
config: PayloadConfig { parent_header, extra_data, attributes: attributes.0 },
cancel,
best_payload,
})
}
fn build_empty_payload(
&self,
client: &Client,
config: PayloadConfig<Self::Attributes>,
) -> Result<Self::BuiltPayload, PayloadBuilderError> {
let PayloadConfig { parent_header, extra_data, attributes } = config;
let chain_spec = client.chain_spec();
<reth_ethereum_payload_builder::EthereumPayloadBuilder as PayloadBuilder<Pool, Client>>::build_empty_payload(&reth_ethereum_payload_builder::EthereumPayloadBuilder::new(EthEvmConfig::new(chain_spec.clone())),client,
PayloadConfig { parent_header, extra_data, attributes: attributes.0})
}
}
#[tokio::main]
async fn main() -> eyre::Result<()> {
let _guard = RethTracer::new().init()?;
let tasks = TaskManager::current();
// create optimism genesis with canyon at block 2
let spec = ChainSpec::builder()
.chain(Chain::mainnet())
.genesis(Genesis::default())
.london_activated()
.paris_activated()
.shanghai_activated()
.build();
// create node config
let node_config =
NodeConfig::test().with_rpc(RpcServerArgs::default().with_http()).with_chain(spec);
let handle = NodeBuilder::new(node_config)
.testing_node(tasks.executor())
.launch_node(MyCustomNode::default())
.await
.unwrap();
println!("Node started");
handle.node_exit_future.await
}