Skip to content

feat: added get_blob_by_hash #10987

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions crates/anvil/core/src/eth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,14 @@ pub enum EthRequest {
#[serde(rename = "eth_getTransactionByHash", with = "sequence")]
EthGetTransactionByHash(TxHash),

/// Returns the blob for a given blob versioned hash.
#[serde(rename = "anvil_getBlobByHash", with = "sequence")]
GetBlobByHash(B256),

/// Returns the blobs for a given transaction hash.
#[serde(rename = "anvil_getBlobsByTransactionHash", with = "sequence")]
GetBlobByTransactionHash(TxHash),

#[serde(rename = "eth_getTransactionByBlockHashAndIndex")]
EthGetTransactionByBlockHashAndIndex(TxHash, Index),

Expand Down
10 changes: 10 additions & 0 deletions crates/anvil/core/src/eth/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -723,6 +723,16 @@ impl TypedTransaction {
}
}

pub fn sidecar(&self) -> Option<&TxEip4844WithSidecar> {
match self {
Self::EIP4844(signed_variant) => match signed_variant.tx() {
TxEip4844Variant::TxEip4844WithSidecar(with_sidecar) => Some(with_sidecar),
_ => None,
},
_ => None,
}
}

pub fn max_fee_per_blob_gas(&self) -> Option<u128> {
match self {
Self::EIP4844(tx) => Some(tx.tx().tx().max_fee_per_blob_gas),
Expand Down
24 changes: 24 additions & 0 deletions crates/anvil/src/eth/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,12 @@ impl EthApi {
EthRequest::EthGetRawTransactionByHash(hash) => {
self.raw_transaction(hash).await.to_rpc_result()
}
EthRequest::GetBlobByHash(hash) => {
self.anvil_get_blob_by_versioned_hash(hash).to_rpc_result()
}
EthRequest::GetBlobByTransactionHash(hash) => {
self.anvil_get_blob_by_tx_hash(hash).to_rpc_result()
}
EthRequest::EthGetRawTransactionByBlockHashAndIndex(hash, index) => {
self.raw_transaction_by_block_hash_and_index(hash, index).await.to_rpc_result()
}
Expand Down Expand Up @@ -1312,6 +1318,24 @@ impl EthApi {
.map(U256::from)
}

/// Handler for RPC call: `anvil_getBlobByHash`
pub fn anvil_get_blob_by_versioned_hash(
&self,
hash: B256,
) -> Result<Option<alloy_consensus::TxEip4844WithSidecar>> {
node_info!("anvil_getBlobByHash");
Ok(self.backend.get_blob_by_versioned_hash(hash)?)
}

/// Handler for RPC call: `anvil_getBlobByTransactionHash`
pub fn anvil_get_blob_by_tx_hash(
Comment on lines +1330 to +1331
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should be getBlobs

&self,
hash: B256,
) -> Result<Option<alloy_consensus::TxEip4844WithSidecar>> {
node_info!("anvil_getBlobByTransactionHash");
Ok(self.backend.get_blob_by_tx_hash(hash)?)
}

/// Get transaction by its hash.
///
/// This will check the storage for a matching transaction, if no transaction exists in storage
Expand Down
29 changes: 28 additions & 1 deletion crates/anvil/src/eth/backend/mem/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use crate::{
use alloy_chains::NamedChain;
use alloy_consensus::{
Account, BlockHeader, EnvKzgSettings, Header, Receipt, ReceiptWithBloom, Signed,
Transaction as TransactionTrait, TxEnvelope,
Transaction as TransactionTrait, TxEip4844WithSidecar, TxEnvelope,
proofs::{calculate_receipt_root, calculate_transaction_root},
transaction::Recovered,
};
Expand Down Expand Up @@ -2918,6 +2918,33 @@ impl Backend {
))
}

pub fn get_blob_by_tx_hash(&self, hash: B256) -> Result<Option<TxEip4844WithSidecar>> {
let tx = self.mined_transaction_by_hash(hash).unwrap();
let typed_tx = TypedTransaction::try_from(tx).unwrap();
if let Some(sidecar) = typed_tx.sidecar() {
return Ok(Some(sidecar.clone()));
}
Ok(None)
Comment on lines +2922 to +2927
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this can fail, so we should handle this gracefully and only return the blobs Vec here

}

pub fn get_blob_by_versioned_hash(&self, hash: B256) -> Result<Option<TxEip4844WithSidecar>> {
let storage = self.blockchain.storage.read();
for block in storage.blocks.values() {
for tx in &block.transactions {
let typed_tx = tx.as_ref();
if let Some(sidecar) = typed_tx.sidecar() {
for blob in sidecar.sidecar.clone() {
let versioned_hash = B256::from(blob.to_kzg_versioned_hash());
if versioned_hash == hash {
return Ok(Some(sidecar.clone()));
}
}
Comment on lines +2935 to +2941
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can simplify this a bit with:

https://github.com/alloy-rs/alloy/blob/d9ec782cc1e3a7850f44f72884aea8f6b9b11ca8/crates/eips/src/eip4844/sidecar.rs#L289-L289

because we want to avoid cloning all sidecars for this since this is a bit expensive

we also want a new helper blob_by_versioned_hash on the sidecar types in alloy, do you want to upstream this?

}
}
}
Ok(None)
}

/// Prove an account's existence or nonexistence in the state trie.
///
/// Returns a merkle proof of the account's trie node, `account_key` == keccak(address)
Expand Down
75 changes: 75 additions & 0 deletions crates/anvil/tests/it/eip4844.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,3 +346,78 @@ async fn can_bypass_sidecar_requirement() {

assert_eq!(tx.inner.ty(), 3);
}

#[tokio::test(flavor = "multi_thread")]
async fn can_get_blobs_by_versioned_hash() {
let node_config = NodeConfig::test().with_hardfork(Some(EthereumHardfork::Prague.into()));
let (api, handle) = spawn(node_config).await;

let wallets = handle.dev_wallets().collect::<Vec<_>>();
let from = wallets[0].address();
let to = wallets[1].address();
let provider = http_provider(&handle.http_endpoint());

let eip1559_est = provider.estimate_eip1559_fees().await.unwrap();
let gas_price = provider.get_gas_price().await.unwrap();

let sidecar: SidecarBuilder<SimpleCoder> = SidecarBuilder::from_slice(b"Hello World");

let sidecar = sidecar.build().unwrap();
let tx = TransactionRequest::default()
.with_from(from)
.with_to(to)
.with_nonce(0)
.with_max_fee_per_blob_gas(gas_price + 1)
.with_max_fee_per_gas(eip1559_est.max_fee_per_gas)
.with_max_priority_fee_per_gas(eip1559_est.max_priority_fee_per_gas)
.with_blob_sidecar(sidecar.clone())
.value(U256::from(5));

let mut tx = WithOtherFields::new(tx);

tx.populate_blob_hashes();

let _receipt = provider.send_transaction(tx).await.unwrap().get_receipt().await.unwrap();

let hash = sidecar.versioned_hash_for_blob(0).unwrap();
// api.anvil_set_auto_mine(true).await.unwrap();
let blob = api.anvil_get_blob_by_versioned_hash(hash).unwrap().unwrap();
assert_eq!(blob.sidecar, sidecar);
}

#[tokio::test(flavor = "multi_thread")]
async fn can_get_blobs_by_tx_hash() {
let node_config = NodeConfig::test().with_hardfork(Some(EthereumHardfork::Prague.into()));
let (api, handle) = spawn(node_config).await;

let wallets = handle.dev_wallets().collect::<Vec<_>>();
let from = wallets[0].address();
let to = wallets[1].address();
let provider = http_provider(&handle.http_endpoint());

let eip1559_est = provider.estimate_eip1559_fees().await.unwrap();
let gas_price = provider.get_gas_price().await.unwrap();

let sidecar: SidecarBuilder<SimpleCoder> = SidecarBuilder::from_slice(b"Hello World");

let sidecar = sidecar.build().unwrap();
let tx = TransactionRequest::default()
.with_from(from)
.with_to(to)
.with_nonce(0)
.with_max_fee_per_blob_gas(gas_price + 1)
.with_max_fee_per_gas(eip1559_est.max_fee_per_gas)
.with_max_priority_fee_per_gas(eip1559_est.max_priority_fee_per_gas)
.with_blob_sidecar(sidecar.clone())
.value(U256::from(5));

let mut tx = WithOtherFields::new(tx);

tx.populate_blob_hashes();

let receipt = provider.send_transaction(tx).await.unwrap().get_receipt().await.unwrap();
let hash = receipt.transaction_hash;
api.anvil_set_auto_mine(true).await.unwrap();
let blob = api.anvil_get_blob_by_tx_hash(hash).unwrap().unwrap();
assert_eq!(blob.sidecar, sidecar);
}