Skip to content

Commit

Permalink
payload built
Browse files Browse the repository at this point in the history
  • Loading branch information
Brechtpd committed Aug 17, 2024
1 parent 6451b5d commit 738d9ea
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 27 deletions.
48 changes: 32 additions & 16 deletions bin/reth/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ use transaction::TransactionTestContext;
use wallet::Wallet;
use std::{future::Future, marker::PhantomData, pin::Pin, sync::Arc};

use alloy_rlp::Decodable;

//use alloy_primitives::{Address, B256};
use reth::rpc::types::engine::PayloadAttributes;
//use reth_e2e_test_utils::NodeHelperType;
Expand All @@ -81,15 +83,15 @@ mod traits;
//pub(crate) type EthNode = NodeHelperType<EthereumNode, EthereumAddOns>;

/// Helper function to create a new eth payload attributes
pub(crate) fn eth_payload_attributes(timestamp: u64) -> EthPayloadBuilderAttributes {
pub(crate) fn eth_payload_attributes(timestamp: u64, transactions: Vec<TransactionSigned>) -> EthPayloadBuilderAttributes {
let attributes = PayloadAttributes {
timestamp,
prev_randao: B256::ZERO,
suggested_fee_recipient: Address::ZERO,
withdrawals: Some(vec![]),
parent_beacon_block_root: Some(B256::ZERO),
};
EthPayloadBuilderAttributes::new(B256::ZERO, attributes)
EthPayloadBuilderAttributes::new(B256::ZERO, attributes, Some(transactions))
}


Expand All @@ -110,6 +112,15 @@ static CHAIN_SPEC: Lazy<Arc<ChainSpec>> = Lazy::new(|| {
)
});

pub fn decode_transactions(tx_list: &[u8]) -> Vec<TransactionSigned> {
#[allow(clippy::useless_asref)]
Vec::<TransactionSigned>::decode(&mut tx_list.as_ref()).unwrap_or_else(|e| {
// If decoding fails we need to make an empty block
println!("decode_transactions not successful: {e:?}, use empty tx_list");
vec![]
})
}

struct Rollup<Node: reth_node_api::FullNodeComponents> {
ctx: ExExContext<Node>,
node: TestNodeContext,
Expand Down Expand Up @@ -174,22 +185,27 @@ impl<Node: reth_node_api::FullNodeComponents> Rollup<Node> {
println!("tx_list: {:?}", tx_list);
let _call = RollupContractCalls::abi_decode(tx.input(), true)?;

let wallet = Wallet::default();
let raw_tx = TransactionTestContext::transfer_tx_bytes(1, wallet.inner).await;
let transactions: Vec<TransactionSigned> = decode_transactions(&tx_list);
self.node.payload.transactions = transactions.clone();

println!("transactions: {:?}", transactions);

// let wallet = Wallet::default();
// let raw_tx = TransactionTestContext::transfer_tx_bytes(1, wallet.inner).await;

// make the node advance
//let tx_hash = self.node.rpc.inject_tx(raw_tx).await?;
// // make the node advance
// //let tx_hash = self.node.rpc.inject_tx(raw_tx).await?;


println!("tx_hash start");
// println!("tx_hash start");

let tx_hash = tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on({
self.node.rpc.inject_tx(raw_tx)
})
}).unwrap();
// let tx_hash = tokio::task::block_in_place(|| {
// tokio::runtime::Handle::current().block_on({
// self.node.rpc.inject_tx(raw_tx)
// })
// }).unwrap();

println!("tx_hash start");
// println!("tx_hash start");

// make the node advance
//let (payload, _): (EthBuiltPayload, _) = self.node.advance_block(vec![], eth_payload_attributes).await?;
Expand Down Expand Up @@ -226,7 +242,7 @@ impl<Node: reth_node_api::FullNodeComponents> Rollup<Node> {
tokio::runtime::Handle::current().block_on({
// do something async
println!("assert_new_block");
self.node.assert_new_block(tx_hash, block_hash, block_number)
self.node.assert_new_block(transactions[0].hash(), block_hash, block_number)
})
});

Expand Down Expand Up @@ -514,7 +530,7 @@ fn main() -> eyre::Result<()> {
};

let chain_spec = ChainSpecBuilder::default()
.chain(MAINNET.chain)
.chain(CHAIN_ID.into())
.genesis(serde_json::from_str(include_str!("../../../crates/ethereum/node/tests/assets/genesis.json")).unwrap())
.cancun_activated()
.build();
Expand All @@ -524,7 +540,7 @@ fn main() -> eyre::Result<()> {
.with_network(network_config.clone())
.with_unused_ports()
.with_rpc(RpcServerArgs::default().with_unused_ports().with_http())
.set_dev(false);
.set_dev(true);

let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())
.testing_node(exec.clone())
Expand Down
8 changes: 4 additions & 4 deletions bin/reth/src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use reth::{
},
};
use reth_node_builder::{NodeAddOns, NodeTypes};
use reth_primitives::{BlockHash, BlockNumber, Bytes, B256};
use reth_primitives::{BlockHash, BlockNumber, Bytes, TransactionSigned, B256};
use reth_stages_types::StageId;
use tokio_stream::StreamExt;

Expand Down Expand Up @@ -78,7 +78,7 @@ where
&mut self,
length: u64,
tx_generator: impl Fn(u64) -> Pin<Box<dyn Future<Output = Bytes>>>,
attributes_generator: impl Fn(u64) -> <Node::Engine as PayloadTypes>::PayloadBuilderAttributes
attributes_generator: impl Fn(u64, Vec<TransactionSigned>) -> <Node::Engine as PayloadTypes>::PayloadBuilderAttributes
+ Copy,
) -> eyre::Result<
Vec<(
Expand Down Expand Up @@ -110,7 +110,7 @@ where
/// It triggers the resolve payload via engine api and expects the built payload event.
pub async fn new_payload(
&mut self,
attributes_generator: impl Fn(u64) -> <Node::Engine as PayloadTypes>::PayloadBuilderAttributes,
attributes_generator: impl Fn(u64, Vec<TransactionSigned>) -> <Node::Engine as PayloadTypes>::PayloadBuilderAttributes,
) -> eyre::Result<(
<<Node as NodeTypes>::Engine as PayloadTypes>::BuiltPayload,
<<Node as NodeTypes>::Engine as PayloadTypes>::PayloadBuilderAttributes,
Expand All @@ -135,7 +135,7 @@ where
pub async fn advance_block(
&mut self,
versioned_hashes: Vec<B256>,
attributes_generator: impl Fn(u64) -> <Node::Engine as PayloadTypes>::PayloadBuilderAttributes,
attributes_generator: impl Fn(u64, Vec<TransactionSigned>) -> <Node::Engine as PayloadTypes>::PayloadBuilderAttributes,
) -> eyre::Result<(
<Node::Engine as PayloadTypes>::BuiltPayload,
<<Node as NodeTypes>::Engine as PayloadTypes>::PayloadBuilderAttributes,
Expand Down
8 changes: 5 additions & 3 deletions bin/reth/src/payload.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
use futures_util::StreamExt;
use reth::api::{BuiltPayload, EngineTypes, PayloadBuilderAttributes};
use reth_payload_builder::{Events, PayloadBuilderHandle, PayloadId};
use reth_primitives::TransactionSigned;
use tokio_stream::wrappers::BroadcastStream;

/// Helper for payload operations
pub struct PayloadTestContext<E: EngineTypes> {
pub payload_event_stream: BroadcastStream<Events<E>>,
payload_builder: PayloadBuilderHandle<E>,
pub timestamp: u64,
pub transactions: Vec<TransactionSigned>,
}

impl<E: EngineTypes> PayloadTestContext<E> {
Expand All @@ -16,16 +18,16 @@ impl<E: EngineTypes> PayloadTestContext<E> {
let payload_events = payload_builder.subscribe().await?;
let payload_event_stream = payload_events.into_stream();
// Cancun timestamp
Ok(Self { payload_event_stream, payload_builder, timestamp: 1710338135 })
Ok(Self { payload_event_stream, payload_builder, timestamp: 1710338135, transactions: Vec::new() })
}

/// Creates a new payload job from static attributes
pub async fn new_payload(
&mut self,
attributes_generator: impl Fn(u64) -> E::PayloadBuilderAttributes,
attributes_generator: impl Fn(u64, Vec<TransactionSigned>) -> E::PayloadBuilderAttributes,
) -> eyre::Result<E::PayloadBuilderAttributes> {
self.timestamp += 1;
let attributes: E::PayloadBuilderAttributes = attributes_generator(self.timestamp);
let attributes: E::PayloadBuilderAttributes = attributes_generator(self.timestamp, self.transactions.clone());
self.payload_builder.new_payload(attributes.clone()).await.unwrap();
Ok(attributes)
}
Expand Down
10 changes: 6 additions & 4 deletions crates/ethereum/engine-primitives/src/payload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ use reth_chainspec::ChainSpec;
use reth_evm_ethereum::revm_spec_by_timestamp_after_merge;
use reth_payload_primitives::{BuiltPayload, PayloadBuilderAttributes};
use reth_primitives::{
constants::EIP1559_INITIAL_BASE_FEE, Address, BlobTransactionSidecar, EthereumHardfork, Header,
SealedBlock, Withdrawals, B256, U256,
constants::EIP1559_INITIAL_BASE_FEE, Address, BlobTransactionSidecar, EthereumHardfork, Header, SealedBlock, TransactionSigned, Withdrawals, B256, U256
};
use reth_rpc_types::engine::{
ExecutionPayloadEnvelopeV2, ExecutionPayloadEnvelopeV3, ExecutionPayloadEnvelopeV4,
Expand Down Expand Up @@ -168,6 +167,8 @@ pub struct EthPayloadBuilderAttributes {
pub withdrawals: Withdrawals,
/// Root of the parent beacon block
pub parent_beacon_block_root: Option<B256>,
/// Fixed transaction list
pub transactions: Option<Vec<TransactionSigned>>,
}

// === impl EthPayloadBuilderAttributes ===
Expand All @@ -181,7 +182,7 @@ impl EthPayloadBuilderAttributes {
/// Creates a new payload builder for the given parent block and the attributes.
///
/// Derives the unique [`PayloadId`] for the given parent and attributes
pub fn new(parent: B256, attributes: PayloadAttributes) -> Self {
pub fn new(parent: B256, attributes: PayloadAttributes, transactions: Option<Vec<TransactionSigned>>) -> Self {
let id = payload_id(&parent, &attributes);

Self {
Expand All @@ -192,6 +193,7 @@ impl EthPayloadBuilderAttributes {
prev_randao: attributes.prev_randao,
withdrawals: attributes.withdrawals.unwrap_or_default().into(),
parent_beacon_block_root: attributes.parent_beacon_block_root,
transactions,
}
}
}
Expand All @@ -204,7 +206,7 @@ impl PayloadBuilderAttributes for EthPayloadBuilderAttributes {
///
/// Derives the unique [`PayloadId`] for the given parent and attributes
fn try_new(parent: B256, attributes: PayloadAttributes) -> Result<Self, Infallible> {
Ok(Self::new(parent, attributes))
Ok(Self::new(parent, attributes, None))
}

fn payload_id(&self) -> PayloadId {
Expand Down
8 changes: 8 additions & 0 deletions crates/ethereum/payload/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,8 @@ where

let block_number = initialized_block_env.number.to::<u64>();

println!("brecht: payload builder: {:?}", attributes.transactions);

// apply eip-4788 pre block contract call
pre_block_beacon_root_contract_call(
&mut db,
Expand Down Expand Up @@ -435,6 +437,12 @@ where
executed_txs.push(tx.into_signed());
}

// Using fixed transaction list if it's set
if attributes.transactions.is_some() {
println!("Using fixed tx list");
executed_txs = attributes.transactions.unwrap();
}

// check if we have a better block
if !is_better_payload(best_payload.as_ref(), total_fees) {
// can skip building the block
Expand Down

0 comments on commit 738d9ea

Please sign in to comment.