Skip to content

Commit 2848551

Browse files
committed
update feynman compression
1 parent c1f6bb2 commit 2848551

File tree

9 files changed

+234
-89
lines changed

9 files changed

+234
-89
lines changed

Cargo.lock

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,7 @@ revm-context = { git = "https://github.com/scroll-tech/revm", branch = "feat/ret
476476
revm-context-interface = { git = "https://github.com/scroll-tech/revm", branch = "feat/reth-v74", default-features = false }
477477
revm-database-interface = { git = "https://github.com/scroll-tech/revm", branch = "feat/reth-v74", default-features = false }
478478
op-revm = { git = "https://github.com/scroll-tech/revm", branch = "feat/reth-v74", default-features = false }
479-
revm-scroll = { path = "../scroll-revm", default-features = false }
479+
revm-scroll = { git = "https://github.com/scroll-tech/scroll-revm", branch = "feat/feynman-compression", default-features = false }
480480
revm-inspectors = "0.23.0"
481481

482482
# eth

crates/scroll/alloy/evm/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ scroll-alloy-hardforks = { workspace = true, default-features = false }
3131
# misc
3232
auto_impl = { workspace = true, default-features = false }
3333
serde = { workspace = true, default-features = false, features = ["derive"], optional = true }
34+
zstd = { version = "0.13", features = ["experimental"] }
3435

3536
[dev-dependencies]
3637
alloy-hardforks.workspace = true

crates/scroll/alloy/evm/src/block/mod.rs

Lines changed: 17 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@ mod receipt_builder;
66
use crate::{
77
block::curie::{apply_curie_hard_fork, L1_GAS_PRICE_ORACLE_ADDRESS},
88
system_caller::ScrollSystemCaller,
9-
IntoCompressed, ScrollEvm, ScrollEvmFactory, ScrollTransactionIntoTxEnv,
10-
ScrollTxCompressionFactorCache, WithCompression,
9+
FromTxWithCompression, IntoCompressed, ScrollEvm, ScrollEvmFactory, ScrollTransactionIntoTxEnv,
1110
};
1211
use alloc::{boxed::Box, format, vec::Vec};
1312

@@ -18,7 +17,7 @@ use alloy_evm::{
1817
BlockExecutionError, BlockExecutionResult, BlockExecutor, BlockExecutorFactory,
1918
BlockExecutorFor, BlockValidationError, CommitChanges, ExecutableTx, OnStateHook,
2019
},
21-
Database, Evm, EvmFactory, FromRecoveredTx, FromTxWithEncoded, IntoTxEnv, RecoveredTx,
20+
Database, Evm, EvmFactory, FromRecoveredTx, FromTxWithEncoded,
2221
};
2322
use alloy_primitives::{B256, U256};
2423
use revm::{
@@ -35,6 +34,10 @@ use revm_scroll::builder::ScrollContext;
3534
use scroll_alloy_consensus::L1_MESSAGE_TRANSACTION_TYPE;
3635
use scroll_alloy_hardforks::{ScrollHardfork, ScrollHardforks};
3736

37+
/// A cache for transaction compression factors, mapping transaction hashes to their compression
38+
/// factors.
39+
pub type ScrollTxCompressionFactors = Vec<U256>;
40+
3841
/// Context for Scroll Block Execution.
3942
#[derive(Debug, Default, Clone)]
4043
pub struct ScrollBlockExecutionCtx {
@@ -93,68 +96,31 @@ where
9396
DB: Database + 'db,
9497
E: EvmExt<
9598
DB = &'db mut State<DB>,
96-
Tx: FromRecoveredTx<R::Transaction> + FromTxWithEncoded<R::Transaction>,
97-
>,
98-
R: ScrollReceiptBuilder<
99-
Transaction: Transaction + Encodable2718 + RecoveredTx<R::Transaction>,
100-
Receipt: TxReceipt,
101-
>,
102-
Spec: ScrollHardforks,
103-
for<'a> &'a WithCompression<<R as ScrollReceiptBuilder>::Transaction>:
104-
IntoTxEnv<<E as alloy_evm::Evm>::Tx>,
105-
{
106-
/// Executes all transactions in a block, applying pre and post execution changes.
107-
pub fn execute_block_with_compression_cache(
108-
mut self,
109-
transactions: impl IntoIterator<
110-
Item = impl ExecutableTx<Self> + IntoCompressed<<Self as BlockExecutor>::Transaction>,
111-
>,
112-
mut compression_cache: ScrollTxCompressionFactorCache,
113-
) -> Result<BlockExecutionResult<R::Receipt>, BlockExecutionError>
114-
where
115-
Self: Sized,
116-
{
117-
self.apply_pre_execution_changes()?;
118-
119-
for tx in transactions {
120-
let tx = tx.into_compressed(Some(&mut compression_cache));
121-
self.execute_transaction(&tx)?;
122-
}
123-
124-
self.apply_post_execution_changes()
125-
}
126-
}
127-
128-
impl<'db, DB, E, R, Spec> ScrollBlockExecutor<E, R, Spec>
129-
where
130-
DB: Database + 'db,
131-
E: EvmExt<
132-
DB = &'db mut State<DB>,
133-
Tx: FromRecoveredTx<R::Transaction> + FromTxWithEncoded<R::Transaction>,
134-
>,
135-
R: ScrollReceiptBuilder<
136-
Transaction: Transaction + Encodable2718 + RecoveredTx<R::Transaction>,
137-
Receipt: TxReceipt,
99+
Tx: FromRecoveredTx<R::Transaction>
100+
+ FromTxWithEncoded<R::Transaction>
101+
+ FromTxWithCompression<R::Transaction>,
138102
>,
103+
R: ScrollReceiptBuilder<Transaction: Transaction + Encodable2718, Receipt: TxReceipt>,
139104
Spec: ScrollHardforks,
140-
for<'a> &'a WithCompression<<R as ScrollReceiptBuilder>::Transaction>:
141-
IntoTxEnv<<E as alloy_evm::Evm>::Tx>,
142105
{
143-
/// Executes all transactions in a block, applying pre and post execution changes.
106+
/// Executes all transactions in a block, applying pre and post execution changes. The provided
107+
/// transaction compression factors are expected to be in the same order as the
108+
/// transactions.
144109
pub fn execute_block_with_compression_cache(
145110
mut self,
146111
transactions: impl IntoIterator<
147112
Item = impl ExecutableTx<Self> + IntoCompressed<<Self as BlockExecutor>::Transaction>,
148113
>,
149-
mut compression_cache: ScrollTxCompressionFactorCache,
114+
compression_cache: ScrollTxCompressionFactors,
150115
) -> Result<BlockExecutionResult<R::Receipt>, BlockExecutionError>
151116
where
152117
Self: Sized,
153118
{
154119
self.apply_pre_execution_changes()?;
155120

156-
for tx in transactions {
157-
let tx = tx.into_compressed(Some(&mut compression_cache));
121+
for (tx, compression_factor) in transactions.into_iter().zip(compression_cache.into_iter())
122+
{
123+
let tx = tx.into_compressed(compression_factor);
158124
self.execute_transaction(&tx)?;
159125
}
160126

crates/scroll/alloy/evm/src/lib.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,13 @@
77
mod block;
88
pub use block::{
99
curie, EvmExt, ReceiptBuilderCtx, ScrollBlockExecutionCtx, ScrollBlockExecutor,
10-
ScrollBlockExecutorFactory, ScrollReceiptBuilder,
10+
ScrollBlockExecutorFactory, ScrollReceiptBuilder, ScrollTxCompressionFactors,
1111
};
1212

1313
mod tx;
1414
pub use tx::{
1515
compute_compression_factor, FromTxWithCompression, IntoCompressed, ScrollTransactionIntoTxEnv,
16-
ScrollTxCompressionFactorCache, WithCompression,
16+
WithCompression,
1717
};
1818

1919
mod system_caller;
@@ -38,6 +38,7 @@ use revm::{
3838
use revm_scroll::{
3939
builder::{DefaultScrollContext, MaybeWithEip7702, ScrollBuilder, ScrollContext},
4040
instructions::ScrollInstructions,
41+
l1block::TX_L1_FEE_PRECISION_U256,
4142
precompile::ScrollPrecompileProvider,
4243
ScrollSpecId, ScrollTransaction,
4344
};
@@ -149,7 +150,7 @@ where
149150
},
150151
rlp_bytes: Some(Default::default()),
151152
// TODO: What makes sense in the context of a system call?
152-
compression_factor: Some(U256::ONE),
153+
compression_factor: Some(TX_L1_FEE_PRECISION_U256),
153154
};
154155

155156
let mut gas_limit = tx.base.gas_limit;

crates/scroll/alloy/evm/src/tx/compression.rs

Lines changed: 61 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,63 @@
1-
use std::collections::HashMap;
1+
use std::io::Write;
22

3-
use alloy_consensus::transaction::Recovered;
4-
use alloy_eips::Typed2718;
5-
use alloy_evm::{IntoTxEnv, RecoveredTx};
6-
// use alloy_consensus::transaction::Recovered;
7-
// use alloy_evm::IntoTxEnv;
83
use super::FromRecoveredTx;
94
use crate::ScrollTransactionIntoTxEnv;
10-
use alloy_primitives::{Address, Bytes, TxKind, B256, U256};
5+
use alloy_consensus::transaction::Recovered;
6+
use alloy_eips::{Encodable2718, Typed2718};
7+
use alloy_evm::{IntoTxEnv, RecoveredTx};
8+
use alloy_primitives::{Address, Bytes, TxKind, U256};
119
use revm::context::TxEnv;
10+
use revm_scroll::l1block::TX_L1_FEE_PRECISION;
1211
use scroll_alloy_consensus::{ScrollTxEnvelope, TxL1Message};
13-
14-
/// A cache for transaction compression factors, mapping transaction hashes to their compression
15-
/// factors.
16-
pub type ScrollTxCompressionFactorCache = HashMap<B256, U256>;
17-
18-
const TX_L1_FEE_PRECISION: U256 = U256::from_limbs([1_000_000_000u64, 0, 0, 0]);
12+
use zstd::{
13+
stream::Encoder,
14+
zstd_safe::{CParameter, ParamSwitch},
15+
};
16+
17+
/// The maximum size of the compression window in bytes (2^CL_WINDOW_LIMIT).
18+
const CL_WINDOW_LIMIT: u32 = 22;
19+
20+
fn compressor(target_block_size: u32) -> Encoder<'static, Vec<u8>> {
21+
let mut encoder = Encoder::new(Vec::new(), 0).expect("Failed to create zstd encoder");
22+
encoder
23+
.set_parameter(CParameter::LiteralCompressionMode(ParamSwitch::Disable))
24+
.expect("Failed to set literal compression mode");
25+
encoder
26+
.set_parameter(CParameter::WindowLog(CL_WINDOW_LIMIT))
27+
.expect("Failed to set window log");
28+
encoder
29+
.set_parameter(CParameter::TargetCBlockSize(target_block_size))
30+
.expect("Failed to set target block size");
31+
encoder.include_checksum(false).expect("Failed to disable checksum");
32+
encoder.include_magicbytes(false).expect("Failed to disable magic bytes");
33+
encoder.include_dictid(false).expect("Failed to disable dictid");
34+
encoder.include_contentsize(true).expect("Failed to include content size");
35+
encoder
36+
}
1937

2038
/// Computes the compression factor for a given RLP-encoded transaction.
21-
pub fn compute_compression_factor<T: AsRef<[u8]>>(_rlp_bytes: &T) -> U256 {
22-
U256::from(10).saturating_mul(TX_L1_FEE_PRECISION)
39+
pub fn compute_compression_factor<T: AsRef<[u8]>>(rlp_bytes: &T) -> U256 {
40+
// Instantiate the compressor
41+
let mut compressor = compressor(CL_WINDOW_LIMIT);
42+
let rlp_bytes_len = rlp_bytes.as_ref().len();
43+
44+
// Set the pledged source size to the length of the RLP bytes and write the bytes to the
45+
// compressor.
46+
// TODO: Is it possible this is fallible?
47+
compressor
48+
.set_pledged_src_size(Some(rlp_bytes_len as u64))
49+
.expect("failed to set pledged source size");
50+
// TODO: Is it possible this is fallible?
51+
compressor.write_all(rlp_bytes.as_ref()).expect("failed to write RLP bytes to compressor");
52+
53+
// Finish the compression and get the result.
54+
let result = compressor.finish().expect("failed to finish compression");
55+
56+
// compute the compression ratio
57+
let compression_ratio =
58+
((rlp_bytes_len as f64 * TX_L1_FEE_PRECISION as f64) / result.len() as f64).floor() as u64;
59+
60+
U256::from(compression_ratio)
2361
}
2462

2563
/// A generic wrrapper for a type that includes a compression factor and encoded bytes.
@@ -139,10 +177,14 @@ impl FromTxWithCompression<ScrollTxEnvelope> for ScrollTransactionIntoTxEnv<TxEn
139177
pub trait IntoCompressed<T> {
140178
/// Converts the type into a [`WithCompression`] instance, optionally using a
141179
/// [`ScrollTxCompressor`] to calculate the compression factor.
142-
fn into_compressed(
143-
self,
144-
compression_provider: Option<&mut ScrollTxCompressionFactorCache>,
145-
) -> WithCompression<T>;
180+
fn into_compressed(&self, compression_factor: U256) -> WithCompression<Recovered<&T>>;
181+
}
182+
183+
impl<T: Encodable2718> IntoCompressed<T> for Recovered<&T> {
184+
fn into_compressed(&self, compression_factor: U256) -> WithCompression<Recovered<&T>> {
185+
let encoded_bytes = self.inner().encoded_2718();
186+
WithCompression { value: *self, compression_factor, encoded_bytes: encoded_bytes.into() }
187+
}
146188
}
147189

148190
impl<Tx, T: RecoveredTx<Tx>> RecoveredTx<Tx> for WithCompression<T> {

crates/scroll/alloy/evm/src/tx/mod.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,7 @@ use scroll_alloy_consensus::{ScrollTxEnvelope, TxL1Message, L1_MESSAGE_TRANSACTI
1313

1414
mod compression;
1515
pub use compression::{
16-
compute_compression_factor, FromTxWithCompression, IntoCompressed,
17-
ScrollTxCompressionFactorCache, WithCompression,
16+
compute_compression_factor, FromTxWithCompression, IntoCompressed, WithCompression,
1817
};
1918

2019
/// This structure wraps around a [`ScrollTransaction`] and allows us to implement the [`IntoTxEnv`]

0 commit comments

Comments
 (0)