foundry_fork_db/
backend.rs

1//! Smart caching and deduplication of requests when using a forking provider.
2
3use crate::{
4    cache::{BlockchainDb, FlushJsonBlockCacheDB, MemDb, StorageInfo},
5    error::{DatabaseError, DatabaseResult},
6};
7use alloy_primitives::{keccak256, Address, Bytes, B256, U256};
8use alloy_provider::{
9    network::{AnyNetwork, AnyRpcBlock, AnyRpcTransaction},
10    DynProvider, Provider,
11};
12use alloy_rpc_types::BlockId;
13use eyre::WrapErr;
14use futures::{
15    channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
16    pin_mut,
17    stream::Stream,
18    task::{Context, Poll},
19    Future, FutureExt,
20};
21use revm::{
22    database::DatabaseRef,
23    primitives::{
24        map::{hash_map::Entry, AddressHashMap, HashMap},
25        KECCAK_EMPTY,
26    },
27    state::{AccountInfo, Bytecode},
28};
29use std::{
30    collections::VecDeque,
31    fmt,
32    future::IntoFuture,
33    path::Path,
34    pin::Pin,
35    sync::{
36        atomic::{AtomicU8, Ordering},
37        mpsc::{channel as oneshot_channel, Sender as OneshotSender},
38        Arc,
39    },
40};
41use tokio::select;
42
43/// Logged when an error is indicative that the user is trying to fork from a non-archive node.
44pub const NON_ARCHIVE_NODE_WARNING: &str = "\
45It looks like you're trying to fork from an older block with a non-archive node which is not \
46supported. Please try to change your RPC url to an archive node if the issue persists.";
47
48// Various future/request type aliases
49
50type AccountFuture<Err> =
51    Pin<Box<dyn Future<Output = (Result<(U256, u64, Bytes), Err>, Address)> + Send>>;
52type StorageFuture<Err> = Pin<Box<dyn Future<Output = (Result<U256, Err>, Address, U256)> + Send>>;
53type BlockHashFuture<Err> = Pin<Box<dyn Future<Output = (Result<B256, Err>, u64)> + Send>>;
54type FullBlockFuture<Err> = Pin<
55    Box<dyn Future<Output = (FullBlockSender, Result<Option<AnyRpcBlock>, Err>, BlockId)> + Send>,
56>;
57type TransactionFuture<Err> =
58    Pin<Box<dyn Future<Output = (TransactionSender, Result<AnyRpcTransaction, Err>, B256)> + Send>>;
59
60type AccountInfoSender = OneshotSender<DatabaseResult<AccountInfo>>;
61type StorageSender = OneshotSender<DatabaseResult<U256>>;
62type BlockHashSender = OneshotSender<DatabaseResult<B256>>;
63type FullBlockSender = OneshotSender<DatabaseResult<AnyRpcBlock>>;
64type TransactionSender = OneshotSender<DatabaseResult<AnyRpcTransaction>>;
65
66type AddressData = AddressHashMap<AccountInfo>;
67type StorageData = AddressHashMap<StorageInfo>;
68type BlockHashData = HashMap<U256, B256>;
69
70/// States for tracking which account endpoints should be used when account info
71const ACCOUNT_FETCH_UNCHECKED: u8 = 0;
72/// Endpoints supports the non standard eth_getAccountInfo which is more efficient than sending 3
73/// separate requests
74const ACCOUNT_FETCH_SUPPORTS_ACC_INFO: u8 = 1;
75/// Use regular individual getCode, getNonce, getBalance calls
76const ACCOUNT_FETCH_SEPARATE_REQUESTS: u8 = 2;
77
78struct AnyRequestFuture<T, Err> {
79    sender: OneshotSender<Result<T, Err>>,
80    future: Pin<Box<dyn Future<Output = Result<T, Err>> + Send>>,
81}
82
83impl<T, Err> fmt::Debug for AnyRequestFuture<T, Err> {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        f.debug_tuple("AnyRequestFuture").field(&self.sender).finish()
86    }
87}
88
89trait WrappedAnyRequest: Unpin + Send + fmt::Debug {
90    fn poll_inner(&mut self, cx: &mut Context<'_>) -> Poll<()>;
91}
92
93/// @dev Implements `WrappedAnyRequest` for `AnyRequestFuture`.
94///
95/// - `poll_inner` is similar to `Future` polling but intentionally consumes the Future<Output=T>
96///   and return Future<Output=()>
97/// - This design avoids storing `Future<Output = T>` directly, as its type may not be known at
98///   compile time.
99/// - Instead, the result (`Result<T, Err>`) is sent via the `sender` channel, which enforces type
100///   safety.
101impl<T, Err> WrappedAnyRequest for AnyRequestFuture<T, Err>
102where
103    T: fmt::Debug + Send + 'static,
104    Err: fmt::Debug + Send + 'static,
105{
106    fn poll_inner(&mut self, cx: &mut Context<'_>) -> Poll<()> {
107        match self.future.poll_unpin(cx) {
108            Poll::Ready(result) => {
109                let _ = self.sender.send(result);
110                Poll::Ready(())
111            }
112            Poll::Pending => Poll::Pending,
113        }
114    }
115}
116
117/// Request variants that are executed by the provider
118enum ProviderRequest<Err> {
119    Account(AccountFuture<Err>),
120    Storage(StorageFuture<Err>),
121    BlockHash(BlockHashFuture<Err>),
122    FullBlock(FullBlockFuture<Err>),
123    Transaction(TransactionFuture<Err>),
124    AnyRequest(Box<dyn WrappedAnyRequest>),
125}
126
127/// The Request type the Backend listens for
128#[derive(Debug)]
129enum BackendRequest {
130    /// Fetch the account info
131    Basic(Address, AccountInfoSender),
132    /// Fetch a storage slot
133    Storage(Address, U256, StorageSender),
134    /// Fetch a block hash
135    BlockHash(u64, BlockHashSender),
136    /// Fetch an entire block with transactions
137    FullBlock(BlockId, FullBlockSender),
138    /// Fetch a transaction
139    Transaction(B256, TransactionSender),
140    /// Sets the pinned block to fetch data from
141    SetPinnedBlock(BlockId),
142
143    /// Update Address data
144    UpdateAddress(AddressData),
145    /// Update Storage data
146    UpdateStorage(StorageData),
147    /// Update Block Hashes
148    UpdateBlockHash(BlockHashData),
149    /// Any other request
150    AnyRequest(Box<dyn WrappedAnyRequest>),
151}
152
153/// Handles an internal provider and listens for requests.
154///
155/// This handler will remain active as long as it is reachable (request channel still open) and
156/// requests are in progress.
157#[must_use = "futures do nothing unless polled"]
158pub struct BackendHandler {
159    provider: DynProvider<AnyNetwork>,
160    /// Stores all the data.
161    db: BlockchainDb,
162    /// Requests currently in progress
163    pending_requests: Vec<ProviderRequest<eyre::Report>>,
164    /// Listeners that wait for a `get_account` related response
165    account_requests: HashMap<Address, Vec<AccountInfoSender>>,
166    /// Listeners that wait for a `get_storage_at` response
167    storage_requests: HashMap<(Address, U256), Vec<StorageSender>>,
168    /// Listeners that wait for a `get_block` response
169    block_requests: HashMap<u64, Vec<BlockHashSender>>,
170    /// Incoming commands.
171    incoming: UnboundedReceiver<BackendRequest>,
172    /// unprocessed queued requests
173    queued_requests: VecDeque<BackendRequest>,
174    /// The block to fetch data from.
175    // This is an `Option` so that we can have less code churn in the functions below
176    block_id: Option<BlockId>,
177    /// The mode for fetching account data
178    account_fetch_mode: Arc<AtomicU8>,
179}
180
181impl BackendHandler {
182    fn new(
183        provider: DynProvider<AnyNetwork>,
184        db: BlockchainDb,
185        rx: UnboundedReceiver<BackendRequest>,
186        block_id: Option<BlockId>,
187    ) -> Self {
188        Self {
189            provider,
190            db,
191            pending_requests: Default::default(),
192            account_requests: Default::default(),
193            storage_requests: Default::default(),
194            block_requests: Default::default(),
195            queued_requests: Default::default(),
196            incoming: rx,
197            block_id,
198            account_fetch_mode: Arc::new(AtomicU8::new(ACCOUNT_FETCH_UNCHECKED)),
199        }
200    }
201
202    /// handle the request in queue in the future.
203    ///
204    /// We always check:
205    ///  1. if the requested value is already stored in the cache, then answer the sender
206    ///  2. otherwise, fetch it via the provider but check if a request for that value is already in
207    ///     progress (e.g. another Sender just requested the same account)
208    fn on_request(&mut self, req: BackendRequest) {
209        match req {
210            BackendRequest::Basic(addr, sender) => {
211                trace!(target: "backendhandler", "received request basic address={:?}", addr);
212                let acc = self.db.accounts().read().get(&addr).cloned();
213                if let Some(basic) = acc {
214                    let _ = sender.send(Ok(basic));
215                } else {
216                    self.request_account(addr, sender);
217                }
218            }
219            BackendRequest::BlockHash(number, sender) => {
220                let hash = self.db.block_hashes().read().get(&U256::from(number)).cloned();
221                if let Some(hash) = hash {
222                    let _ = sender.send(Ok(hash));
223                } else {
224                    self.request_hash(number, sender);
225                }
226            }
227            BackendRequest::FullBlock(number, sender) => {
228                self.request_full_block(number, sender);
229            }
230            BackendRequest::Transaction(tx, sender) => {
231                self.request_transaction(tx, sender);
232            }
233            BackendRequest::Storage(addr, idx, sender) => {
234                // account is already stored in the cache
235                let value =
236                    self.db.storage().read().get(&addr).and_then(|acc| acc.get(&idx).copied());
237                if let Some(value) = value {
238                    let _ = sender.send(Ok(value));
239                } else {
240                    // account present but not storage -> fetch storage
241                    self.request_account_storage(addr, idx, sender);
242                }
243            }
244            BackendRequest::SetPinnedBlock(block_id) => {
245                self.block_id = Some(block_id);
246            }
247            BackendRequest::UpdateAddress(address_data) => {
248                for (address, data) in address_data {
249                    self.db.accounts().write().insert(address, data);
250                }
251            }
252            BackendRequest::UpdateStorage(storage_data) => {
253                for (address, data) in storage_data {
254                    self.db.storage().write().insert(address, data);
255                }
256            }
257            BackendRequest::UpdateBlockHash(block_hash_data) => {
258                for (block, hash) in block_hash_data {
259                    self.db.block_hashes().write().insert(block, hash);
260                }
261            }
262            BackendRequest::AnyRequest(fut) => {
263                self.pending_requests.push(ProviderRequest::AnyRequest(fut));
264            }
265        }
266    }
267
268    /// process a request for account's storage
269    fn request_account_storage(&mut self, address: Address, idx: U256, listener: StorageSender) {
270        match self.storage_requests.entry((address, idx)) {
271            Entry::Occupied(mut entry) => {
272                entry.get_mut().push(listener);
273            }
274            Entry::Vacant(entry) => {
275                trace!(target: "backendhandler", %address, %idx, "preparing storage request");
276                entry.insert(vec![listener]);
277                let provider = self.provider.clone();
278                let block_id = self.block_id.unwrap_or_default();
279                let fut = Box::pin(async move {
280                    let storage = provider
281                        .get_storage_at(address, idx)
282                        .block_id(block_id)
283                        .await
284                        .map_err(Into::into);
285                    (storage, address, idx)
286                });
287                self.pending_requests.push(ProviderRequest::Storage(fut));
288            }
289        }
290    }
291
292    /// returns the future that fetches the account data
293    fn get_account_req(&self, address: Address) -> ProviderRequest<eyre::Report> {
294        trace!(target: "backendhandler", "preparing account request, address={:?}", address);
295
296        let provider = self.provider.clone();
297        let block_id = self.block_id.unwrap_or_default();
298        let mode = Arc::clone(&self.account_fetch_mode);
299        let fut = async move {
300            // depending on the tracked mode we can dispatch requests.
301            let initial_mode = mode.load(Ordering::Relaxed);
302            match initial_mode {
303                ACCOUNT_FETCH_UNCHECKED => {
304                    // single request for accountinfo object
305                    let acc_info_fut =
306                        provider.get_account_info(address).block_id(block_id).into_future();
307
308                    // tri request for account info
309                    let balance_fut =
310                        provider.get_balance(address).block_id(block_id).into_future();
311                    let nonce_fut =
312                        provider.get_transaction_count(address).block_id(block_id).into_future();
313                    let code_fut = provider.get_code_at(address).block_id(block_id).into_future();
314                    let triple_fut = futures::future::try_join3(balance_fut, nonce_fut, code_fut);
315                    pin_mut!(acc_info_fut, triple_fut);
316
317                    select! {
318                        acc_info = &mut acc_info_fut => {
319                            match acc_info {
320                                Ok(info) => {
321                                 trace!(target: "backendhandler", "endpoint supports eth_getAccountInfo");
322                                    mode.store(ACCOUNT_FETCH_SUPPORTS_ACC_INFO, Ordering::Relaxed);
323                                    Ok((info.balance, info.nonce, info.code))
324                                }
325                                Err(err) => {
326                                    trace!(target: "backendhandler", ?err, "failed initial eth_getAccountInfo call");
327                                    mode.store(ACCOUNT_FETCH_SEPARATE_REQUESTS, Ordering::Relaxed);
328                                    Ok(triple_fut.await?)
329                                }
330                            }
331                        }
332                        triple = &mut triple_fut => {
333                            match triple {
334                                Ok((balance, nonce, code)) => {
335                                    mode.store(ACCOUNT_FETCH_SEPARATE_REQUESTS, Ordering::Relaxed);
336                                    Ok((balance, nonce, code))
337                                }
338                                Err(err) => Err(err.into())
339                            }
340                        }
341                    }
342                }
343
344                ACCOUNT_FETCH_SUPPORTS_ACC_INFO => {
345                    let mut res = provider
346                        .get_account_info(address)
347                        .block_id(block_id)
348                        .into_future()
349                        .await
350                        .map(|info| (info.balance, info.nonce, info.code));
351
352                    // it's possible that the configured endpoint load balances requests to multiple
353                    // instances and not all support that endpoint so we should reset here
354                    if res.is_err() {
355                        mode.store(ACCOUNT_FETCH_SEPARATE_REQUESTS, Ordering::Relaxed);
356
357                        let balance_fut =
358                            provider.get_balance(address).block_id(block_id).into_future();
359                        let nonce_fut = provider
360                            .get_transaction_count(address)
361                            .block_id(block_id)
362                            .into_future();
363                        let code_fut =
364                            provider.get_code_at(address).block_id(block_id).into_future();
365                        res = futures::future::try_join3(balance_fut, nonce_fut, code_fut).await;
366                    }
367
368                    Ok(res?)
369                }
370
371                ACCOUNT_FETCH_SEPARATE_REQUESTS => {
372                    let balance_fut =
373                        provider.get_balance(address).block_id(block_id).into_future();
374                    let nonce_fut =
375                        provider.get_transaction_count(address).block_id(block_id).into_future();
376                    let code_fut = provider.get_code_at(address).block_id(block_id).into_future();
377
378                    Ok(futures::future::try_join3(balance_fut, nonce_fut, code_fut).await?)
379                }
380
381                _ => unreachable!("Invalid account fetch mode"),
382            }
383        };
384
385        ProviderRequest::Account(Box::pin(async move {
386            let result = fut.await;
387            (result, address)
388        }))
389    }
390
391    /// process a request for an account
392    fn request_account(&mut self, address: Address, listener: AccountInfoSender) {
393        match self.account_requests.entry(address) {
394            Entry::Occupied(mut entry) => {
395                entry.get_mut().push(listener);
396            }
397            Entry::Vacant(entry) => {
398                entry.insert(vec![listener]);
399                self.pending_requests.push(self.get_account_req(address));
400            }
401        }
402    }
403
404    /// process a request for an entire block
405    fn request_full_block(&mut self, number: BlockId, sender: FullBlockSender) {
406        let provider = self.provider.clone();
407        let fut = Box::pin(async move {
408            let block = provider
409                .get_block(number)
410                .full()
411                .await
412                .wrap_err(format!("could not fetch block {number:?}"));
413            (sender, block, number)
414        });
415
416        self.pending_requests.push(ProviderRequest::FullBlock(fut));
417    }
418
419    /// process a request for a transactions
420    fn request_transaction(&mut self, tx: B256, sender: TransactionSender) {
421        let provider = self.provider.clone();
422        let fut = Box::pin(async move {
423            let block = provider
424                .get_transaction_by_hash(tx)
425                .await
426                .wrap_err_with(|| format!("could not get transaction {tx}"))
427                .and_then(|maybe| {
428                    maybe.ok_or_else(|| eyre::eyre!("could not get transaction {tx}"))
429                });
430            (sender, block, tx)
431        });
432
433        self.pending_requests.push(ProviderRequest::Transaction(fut));
434    }
435
436    /// process a request for a block hash
437    fn request_hash(&mut self, number: u64, listener: BlockHashSender) {
438        match self.block_requests.entry(number) {
439            Entry::Occupied(mut entry) => {
440                entry.get_mut().push(listener);
441            }
442            Entry::Vacant(entry) => {
443                trace!(target: "backendhandler", number, "preparing block hash request");
444                entry.insert(vec![listener]);
445                let provider = self.provider.clone();
446                let fut = Box::pin(async move {
447                    let block = provider
448                        .get_block_by_number(number.into())
449                        .hashes()
450                        .await
451                        .wrap_err("failed to get block");
452
453                    let block_hash = match block {
454                        Ok(Some(block)) => Ok(block.header.hash),
455                        Ok(None) => {
456                            warn!(target: "backendhandler", ?number, "block not found");
457                            // if no block was returned then the block does not exist, in which case
458                            // we return empty hash
459                            Ok(KECCAK_EMPTY)
460                        }
461                        Err(err) => {
462                            error!(target: "backendhandler", %err, ?number, "failed to get block");
463                            Err(err)
464                        }
465                    };
466                    (block_hash, number)
467                });
468                self.pending_requests.push(ProviderRequest::BlockHash(fut));
469            }
470        }
471    }
472}
473
474impl Future for BackendHandler {
475    type Output = ();
476
477    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
478        let pin = self.get_mut();
479        loop {
480            // Drain queued requests first.
481            while let Some(req) = pin.queued_requests.pop_front() {
482                pin.on_request(req)
483            }
484
485            // receive new requests to delegate to the underlying provider
486            loop {
487                match Pin::new(&mut pin.incoming).poll_next(cx) {
488                    Poll::Ready(Some(req)) => {
489                        pin.queued_requests.push_back(req);
490                    }
491                    Poll::Ready(None) => {
492                        trace!(target: "backendhandler", "last sender dropped, ready to drop (&flush cache)");
493                        return Poll::Ready(());
494                    }
495                    Poll::Pending => break,
496                }
497            }
498
499            // poll all requests in progress
500            for n in (0..pin.pending_requests.len()).rev() {
501                let mut request = pin.pending_requests.swap_remove(n);
502                match &mut request {
503                    ProviderRequest::Account(fut) => {
504                        if let Poll::Ready((resp, addr)) = fut.poll_unpin(cx) {
505                            // get the response
506                            let (balance, nonce, code) = match resp {
507                                Ok(res) => res,
508                                Err(err) => {
509                                    let err = Arc::new(err);
510                                    if let Some(listeners) = pin.account_requests.remove(&addr) {
511                                        listeners.into_iter().for_each(|l| {
512                                            let _ = l.send(Err(DatabaseError::GetAccount(
513                                                addr,
514                                                Arc::clone(&err),
515                                            )));
516                                        })
517                                    }
518                                    continue;
519                                }
520                            };
521
522                            // convert it to revm-style types
523                            let (code, code_hash) = if !code.is_empty() {
524                                (code.clone(), keccak256(&code))
525                            } else {
526                                (Bytes::default(), KECCAK_EMPTY)
527                            };
528
529                            // update the cache
530                            let acc = AccountInfo {
531                                nonce,
532                                balance,
533                                code: Some(Bytecode::new_raw(code)),
534                                code_hash,
535                            };
536                            pin.db.accounts().write().insert(addr, acc.clone());
537
538                            // notify all listeners
539                            if let Some(listeners) = pin.account_requests.remove(&addr) {
540                                listeners.into_iter().for_each(|l| {
541                                    let _ = l.send(Ok(acc.clone()));
542                                })
543                            }
544                            continue;
545                        }
546                    }
547                    ProviderRequest::Storage(fut) => {
548                        if let Poll::Ready((resp, addr, idx)) = fut.poll_unpin(cx) {
549                            let value = match resp {
550                                Ok(value) => value,
551                                Err(err) => {
552                                    // notify all listeners
553                                    let err = Arc::new(err);
554                                    if let Some(listeners) =
555                                        pin.storage_requests.remove(&(addr, idx))
556                                    {
557                                        listeners.into_iter().for_each(|l| {
558                                            let _ = l.send(Err(DatabaseError::GetStorage(
559                                                addr,
560                                                idx,
561                                                Arc::clone(&err),
562                                            )));
563                                        })
564                                    }
565                                    continue;
566                                }
567                            };
568
569                            // update the cache
570                            pin.db.storage().write().entry(addr).or_default().insert(idx, value);
571
572                            // notify all listeners
573                            if let Some(listeners) = pin.storage_requests.remove(&(addr, idx)) {
574                                listeners.into_iter().for_each(|l| {
575                                    let _ = l.send(Ok(value));
576                                })
577                            }
578                            continue;
579                        }
580                    }
581                    ProviderRequest::BlockHash(fut) => {
582                        if let Poll::Ready((block_hash, number)) = fut.poll_unpin(cx) {
583                            let value = match block_hash {
584                                Ok(value) => value,
585                                Err(err) => {
586                                    let err = Arc::new(err);
587                                    // notify all listeners
588                                    if let Some(listeners) = pin.block_requests.remove(&number) {
589                                        listeners.into_iter().for_each(|l| {
590                                            let _ = l.send(Err(DatabaseError::GetBlockHash(
591                                                number,
592                                                Arc::clone(&err),
593                                            )));
594                                        })
595                                    }
596                                    continue;
597                                }
598                            };
599
600                            // update the cache
601                            pin.db.block_hashes().write().insert(U256::from(number), value);
602
603                            // notify all listeners
604                            if let Some(listeners) = pin.block_requests.remove(&number) {
605                                listeners.into_iter().for_each(|l| {
606                                    let _ = l.send(Ok(value));
607                                })
608                            }
609                            continue;
610                        }
611                    }
612                    ProviderRequest::FullBlock(fut) => {
613                        if let Poll::Ready((sender, resp, number)) = fut.poll_unpin(cx) {
614                            let msg = match resp {
615                                Ok(Some(block)) => Ok(block),
616                                Ok(None) => Err(DatabaseError::BlockNotFound(number)),
617                                Err(err) => {
618                                    let err = Arc::new(err);
619                                    Err(DatabaseError::GetFullBlock(number, err))
620                                }
621                            };
622                            let _ = sender.send(msg);
623                            continue;
624                        }
625                    }
626                    ProviderRequest::Transaction(fut) => {
627                        if let Poll::Ready((sender, tx, tx_hash)) = fut.poll_unpin(cx) {
628                            let msg = match tx {
629                                Ok(tx) => Ok(tx),
630                                Err(err) => {
631                                    let err = Arc::new(err);
632                                    Err(DatabaseError::GetTransaction(tx_hash, err))
633                                }
634                            };
635                            let _ = sender.send(msg);
636                            continue;
637                        }
638                    }
639                    ProviderRequest::AnyRequest(fut) => {
640                        if fut.poll_inner(cx).is_ready() {
641                            continue;
642                        }
643                    }
644                }
645                // not ready, insert and poll again
646                pin.pending_requests.push(request);
647            }
648
649            // If no new requests have been queued, break to
650            // be polled again later.
651            if pin.queued_requests.is_empty() {
652                return Poll::Pending;
653            }
654        }
655    }
656}
657
658/// Mode for the `SharedBackend` how to block in the non-async [`DatabaseRef`] when interacting with
659/// [`BackendHandler`].
660#[derive(Default, Clone, Debug, PartialEq)]
661pub enum BlockingMode {
662    /// This mode use `tokio::task::block_in_place()` to block in place.
663    ///
664    /// This should be used when blocking on the call site is disallowed.
665    #[default]
666    BlockInPlace,
667    /// The mode blocks the current task
668    ///
669    /// This can be used if blocking on the call site is allowed, e.g. on a tokio blocking task.
670    Block,
671}
672
673impl BlockingMode {
674    /// run process logic with the blocking mode
675    pub fn run<F, R>(&self, f: F) -> R
676    where
677        F: FnOnce() -> R,
678    {
679        match self {
680            Self::BlockInPlace => tokio::task::block_in_place(f),
681            Self::Block => f(),
682        }
683    }
684}
685
686/// A cloneable backend type that shares access to the backend data with all its clones.
687///
688/// This backend type is connected to the `BackendHandler` via a mpsc unbounded channel. The
689/// `BackendHandler` is spawned on a tokio task and listens for incoming commands on the receiver
690/// half of the channel. A `SharedBackend` holds a sender for that channel, which is `Clone`, so
691/// there can be multiple `SharedBackend`s communicating with the same `BackendHandler`, hence this
692/// `Backend` type is thread safe.
693///
694/// All `Backend` trait functions are delegated as a `BackendRequest` via the channel to the
695/// `BackendHandler`. All `BackendRequest` variants include a sender half of an additional channel
696/// that is used by the `BackendHandler` to send the result of an executed `BackendRequest` back to
697/// `SharedBackend`.
698///
699/// The `BackendHandler` holds a `Provider` to look up missing accounts or storage slots
700/// from remote (e.g. infura). It detects duplicate requests from multiple `SharedBackend`s and
701/// bundles them together, so that always only one provider request is executed. For example, there
702/// are two `SharedBackend`s, `A` and `B`, both request the basic account info of account
703/// `0xasd9sa7d...` at the same time. After the `BackendHandler` receives the request from `A`, it
704/// sends a new provider request to the provider's endpoint, then it reads the identical request
705/// from `B` and simply adds it as an additional listener for the request already in progress,
706/// instead of sending another one. So that after the provider returns the response all listeners
707/// (`A` and `B`) get notified.
708// **Note**: the implementation makes use of [tokio::task::block_in_place()] when interacting with
709// the underlying [BackendHandler] which runs on a separate spawned tokio task.
710// [tokio::task::block_in_place()]
711// > Runs the provided blocking function on the current thread without blocking the executor.
712// This prevents issues (hangs) we ran into were the [SharedBackend] itself is called from a spawned
713// task.
714#[derive(Clone, Debug)]
715pub struct SharedBackend {
716    /// channel used for sending commands related to database operations
717    backend: UnboundedSender<BackendRequest>,
718    /// Ensures that the underlying cache gets flushed once the last `SharedBackend` is dropped.
719    ///
720    /// There is only one instance of the type, so as soon as the last `SharedBackend` is deleted,
721    /// `FlushJsonBlockCacheDB` is also deleted and the cache is flushed.
722    cache: Arc<FlushJsonBlockCacheDB>,
723
724    /// The mode for the `SharedBackend` to block in place or not
725    blocking_mode: BlockingMode,
726}
727
728impl SharedBackend {
729    /// _Spawns_ a new `BackendHandler` on a `tokio::task` that listens for requests from any
730    /// `SharedBackend`. Missing values get inserted in the `db`.
731    ///
732    /// The spawned `BackendHandler` finishes once the last `SharedBackend` connected to it is
733    /// dropped.
734    pub async fn spawn_backend<P: Provider<AnyNetwork> + 'static>(
735        provider: P,
736        db: BlockchainDb,
737        pin_block: Option<BlockId>,
738    ) -> Self {
739        let (shared, handler) = Self::new(provider, db, pin_block);
740        // spawn the provider handler to a task
741        trace!(target: "backendhandler", "spawning Backendhandler task");
742        tokio::spawn(handler);
743        shared
744    }
745
746    /// Same as `Self::spawn_backend` but spawns the `BackendHandler` on a separate `std::thread` in
747    /// its own `tokio::Runtime`
748    pub fn spawn_backend_thread<P: Provider<AnyNetwork> + 'static>(
749        provider: P,
750        db: BlockchainDb,
751        pin_block: Option<BlockId>,
752    ) -> Self {
753        let (shared, handler) = Self::new(provider, db, pin_block);
754
755        // spawn a light-weight thread with a thread-local async runtime just for
756        // sending and receiving data from the remote client
757        std::thread::Builder::new()
758            .name("fork-backend".into())
759            .spawn(move || {
760                let rt = tokio::runtime::Builder::new_current_thread()
761                    .enable_all()
762                    .build()
763                    .expect("failed to build tokio runtime");
764
765                rt.block_on(handler);
766            })
767            .expect("failed to spawn thread");
768        trace!(target: "backendhandler", "spawned Backendhandler thread");
769
770        shared
771    }
772
773    /// Returns a new `SharedBackend` and the `BackendHandler`
774    pub fn new<P: Provider<AnyNetwork> + 'static>(
775        provider: P,
776        db: BlockchainDb,
777        pin_block: Option<BlockId>,
778    ) -> (Self, BackendHandler) {
779        let (backend, backend_rx) = unbounded();
780        let cache = Arc::new(FlushJsonBlockCacheDB(Arc::clone(db.cache())));
781        let handler = BackendHandler::new(provider.erased(), db, backend_rx, pin_block);
782        (Self { backend, cache, blocking_mode: Default::default() }, handler)
783    }
784
785    /// Returns a new `SharedBackend` and the `BackendHandler` with a specific blocking mode
786    pub fn with_blocking_mode(&self, mode: BlockingMode) -> Self {
787        Self { backend: self.backend.clone(), cache: self.cache.clone(), blocking_mode: mode }
788    }
789
790    /// Updates the pinned block to fetch data from
791    pub fn set_pinned_block(&self, block: impl Into<BlockId>) -> eyre::Result<()> {
792        let req = BackendRequest::SetPinnedBlock(block.into());
793        self.backend.unbounded_send(req).map_err(|e| eyre::eyre!("{:?}", e))
794    }
795
796    /// Returns the full block for the given block identifier
797    pub fn get_full_block(&self, block: impl Into<BlockId>) -> DatabaseResult<AnyRpcBlock> {
798        self.blocking_mode.run(|| {
799            let (sender, rx) = oneshot_channel();
800            let req = BackendRequest::FullBlock(block.into(), sender);
801            self.backend.unbounded_send(req)?;
802            rx.recv()?
803        })
804    }
805
806    /// Returns the transaction for the hash
807    pub fn get_transaction(&self, tx: B256) -> DatabaseResult<AnyRpcTransaction> {
808        self.blocking_mode.run(|| {
809            let (sender, rx) = oneshot_channel();
810            let req = BackendRequest::Transaction(tx, sender);
811            self.backend.unbounded_send(req)?;
812            rx.recv()?
813        })
814    }
815
816    fn do_get_basic(&self, address: Address) -> DatabaseResult<Option<AccountInfo>> {
817        self.blocking_mode.run(|| {
818            let (sender, rx) = oneshot_channel();
819            let req = BackendRequest::Basic(address, sender);
820            self.backend.unbounded_send(req)?;
821            rx.recv()?.map(Some)
822        })
823    }
824
825    fn do_get_storage(&self, address: Address, index: U256) -> DatabaseResult<U256> {
826        self.blocking_mode.run(|| {
827            let (sender, rx) = oneshot_channel();
828            let req = BackendRequest::Storage(address, index, sender);
829            self.backend.unbounded_send(req)?;
830            rx.recv()?
831        })
832    }
833
834    fn do_get_block_hash(&self, number: u64) -> DatabaseResult<B256> {
835        self.blocking_mode.run(|| {
836            let (sender, rx) = oneshot_channel();
837            let req = BackendRequest::BlockHash(number, sender);
838            self.backend.unbounded_send(req)?;
839            rx.recv()?
840        })
841    }
842
843    /// Inserts or updates data for multiple addresses
844    pub fn insert_or_update_address(&self, address_data: AddressData) {
845        let req = BackendRequest::UpdateAddress(address_data);
846        let err = self.backend.unbounded_send(req);
847        match err {
848            Ok(_) => (),
849            Err(e) => {
850                error!(target: "sharedbackend", "Failed to send update address request: {:?}", e)
851            }
852        }
853    }
854
855    /// Inserts or updates data for multiple storage slots
856    pub fn insert_or_update_storage(&self, storage_data: StorageData) {
857        let req = BackendRequest::UpdateStorage(storage_data);
858        let err = self.backend.unbounded_send(req);
859        match err {
860            Ok(_) => (),
861            Err(e) => {
862                error!(target: "sharedbackend", "Failed to send update address request: {:?}", e)
863            }
864        }
865    }
866
867    /// Inserts or updates data for multiple block hashes
868    pub fn insert_or_update_block_hashes(&self, block_hash_data: BlockHashData) {
869        let req = BackendRequest::UpdateBlockHash(block_hash_data);
870        let err = self.backend.unbounded_send(req);
871        match err {
872            Ok(_) => (),
873            Err(e) => {
874                error!(target: "sharedbackend", "Failed to send update address request: {:?}", e)
875            }
876        }
877    }
878
879    /// Returns any arbitrary request on the provider
880    pub fn do_any_request<T, F>(&mut self, fut: F) -> DatabaseResult<T>
881    where
882        F: Future<Output = Result<T, eyre::Report>> + Send + 'static,
883        T: fmt::Debug + Send + 'static,
884    {
885        self.blocking_mode.run(|| {
886            let (sender, rx) = oneshot_channel::<Result<T, eyre::Report>>();
887            let req = BackendRequest::AnyRequest(Box::new(AnyRequestFuture {
888                sender,
889                future: Box::pin(fut),
890            }));
891            self.backend.unbounded_send(req)?;
892            rx.recv()?.map_err(|err| DatabaseError::AnyRequest(Arc::new(err)))
893        })
894    }
895
896    /// Flushes the DB to disk if caching is enabled
897    pub fn flush_cache(&self) {
898        self.cache.0.flush();
899    }
900
901    /// Flushes the DB to a specific file
902    pub fn flush_cache_to(&self, cache_path: &Path) {
903        self.cache.0.flush_to(cache_path);
904    }
905
906    /// Returns the DB
907    pub fn data(&self) -> Arc<MemDb> {
908        self.cache.0.db().clone()
909    }
910
911    /// Returns the DB accounts
912    pub fn accounts(&self) -> AddressData {
913        self.cache.0.db().accounts.read().clone()
914    }
915
916    /// Returns the DB accounts length
917    pub fn accounts_len(&self) -> usize {
918        self.cache.0.db().accounts.read().len()
919    }
920
921    /// Returns the DB storage
922    pub fn storage(&self) -> StorageData {
923        self.cache.0.db().storage.read().clone()
924    }
925
926    /// Returns the DB storage length
927    pub fn storage_len(&self) -> usize {
928        self.cache.0.db().storage.read().len()
929    }
930
931    /// Returns the DB block_hashes
932    pub fn block_hashes(&self) -> BlockHashData {
933        self.cache.0.db().block_hashes.read().clone()
934    }
935
936    /// Returns the DB block_hashes length
937    pub fn block_hashes_len(&self) -> usize {
938        self.cache.0.db().block_hashes.read().len()
939    }
940}
941
942impl DatabaseRef for SharedBackend {
943    type Error = DatabaseError;
944
945    fn basic_ref(&self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
946        trace!(target: "sharedbackend", %address, "request basic");
947        self.do_get_basic(address).inspect_err(|err| {
948            error!(target: "sharedbackend", %err, %address, "Failed to send/recv `basic`");
949            if err.is_possibly_non_archive_node_error() {
950                error!(target: "sharedbackend", "{NON_ARCHIVE_NODE_WARNING}");
951            }
952        })
953    }
954
955    fn code_by_hash_ref(&self, hash: B256) -> Result<Bytecode, Self::Error> {
956        Err(DatabaseError::MissingCode(hash))
957    }
958
959    fn storage_ref(&self, address: Address, index: U256) -> Result<U256, Self::Error> {
960        trace!(target: "sharedbackend", "request storage {:?} at {:?}", address, index);
961        self.do_get_storage(address, index).inspect_err(|err| {
962            error!(target: "sharedbackend", %err, %address, %index, "Failed to send/recv `storage`");
963            if err.is_possibly_non_archive_node_error() {
964                error!(target: "sharedbackend", "{NON_ARCHIVE_NODE_WARNING}");
965            }
966        })
967    }
968
969    fn block_hash_ref(&self, number: u64) -> Result<B256, Self::Error> {
970        trace!(target: "sharedbackend", "request block hash for number {:?}", number);
971        self.do_get_block_hash(number).inspect_err(|err| {
972            error!(target: "sharedbackend", %err, %number, "Failed to send/recv `block_hash`");
973            if err.is_possibly_non_archive_node_error() {
974                error!(target: "sharedbackend", "{NON_ARCHIVE_NODE_WARNING}");
975            }
976        })
977    }
978}
979
980#[cfg(test)]
981mod tests {
982    use super::*;
983    use crate::cache::{BlockchainDbMeta, JsonBlockCacheDB};
984    use alloy_consensus::BlockHeader;
985    use alloy_provider::ProviderBuilder;
986    use alloy_rpc_client::ClientBuilder;
987    use serde::Deserialize;
988    use std::{fs, path::PathBuf};
989    use tiny_http::{Response, Server};
990
991    pub fn get_http_provider(endpoint: &str) -> impl Provider<AnyNetwork> + Clone {
992        ProviderBuilder::new()
993            .network::<AnyNetwork>()
994            .connect_client(ClientBuilder::default().http(endpoint.parse().unwrap()))
995    }
996
997    const ENDPOINT: Option<&str> = option_env!("ETH_RPC_URL");
998
999    #[tokio::test(flavor = "multi_thread")]
1000    async fn test_builder() {
1001        let Some(endpoint) = ENDPOINT else { return };
1002        let provider = get_http_provider(endpoint);
1003
1004        let any_rpc_block = provider.get_block(BlockId::latest()).hashes().await.unwrap().unwrap();
1005        let meta = BlockchainDbMeta::default().with_block(&any_rpc_block.inner);
1006
1007        assert_eq!(meta.block_env.number, U256::from(any_rpc_block.header.number()));
1008    }
1009
1010    #[tokio::test(flavor = "multi_thread")]
1011    async fn shared_backend() {
1012        let Some(endpoint) = ENDPOINT else { return };
1013
1014        let provider = get_http_provider(endpoint);
1015        let meta = BlockchainDbMeta::new(Default::default(), endpoint.to_string());
1016
1017        let db = BlockchainDb::new(meta, None);
1018        let backend = SharedBackend::spawn_backend(Arc::new(provider), db.clone(), None).await;
1019
1020        // some rng contract from etherscan
1021        let address: Address = "63091244180ae240c87d1f528f5f269134cb07b3".parse().unwrap();
1022
1023        let idx = U256::from(0u64);
1024        let value = backend.storage_ref(address, idx).unwrap();
1025        let account = backend.basic_ref(address).unwrap().unwrap();
1026
1027        let mem_acc = db.accounts().read().get(&address).unwrap().clone();
1028        assert_eq!(account.balance, mem_acc.balance);
1029        assert_eq!(account.nonce, mem_acc.nonce);
1030        let slots = db.storage().read().get(&address).unwrap().clone();
1031        assert_eq!(slots.len(), 1);
1032        assert_eq!(slots.get(&idx).copied().unwrap(), value);
1033
1034        let num = 10u64;
1035        let hash = backend.block_hash_ref(num).unwrap();
1036        let mem_hash = *db.block_hashes().read().get(&U256::from(num)).unwrap();
1037        assert_eq!(hash, mem_hash);
1038
1039        let max_slots = 5;
1040        let handle = std::thread::spawn(move || {
1041            for i in 1..max_slots {
1042                let idx = U256::from(i);
1043                let _ = backend.storage_ref(address, idx);
1044            }
1045        });
1046        handle.join().unwrap();
1047        let slots = db.storage().read().get(&address).unwrap().clone();
1048        assert_eq!(slots.len() as u64, max_slots);
1049    }
1050
1051    #[test]
1052    fn can_read_cache() {
1053        let cache_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("test-data/storage.json");
1054        let json = JsonBlockCacheDB::load(cache_path).unwrap();
1055        assert!(!json.db().accounts.read().is_empty());
1056    }
1057
1058    #[tokio::test(flavor = "multi_thread")]
1059    async fn can_modify_address() {
1060        let Some(endpoint) = ENDPOINT else { return };
1061
1062        let provider = get_http_provider(endpoint);
1063        let meta = BlockchainDbMeta::new(Default::default(), endpoint.to_string());
1064
1065        let db = BlockchainDb::new(meta, None);
1066        let backend = SharedBackend::spawn_backend(Arc::new(provider), db.clone(), None).await;
1067
1068        // some rng contract from etherscan
1069        let address: Address = "63091244180ae240c87d1f528f5f269134cb07b3".parse().unwrap();
1070
1071        let new_acc = AccountInfo {
1072            nonce: 1000u64,
1073            balance: U256::from(2000),
1074            code: None,
1075            code_hash: KECCAK_EMPTY,
1076        };
1077        let mut account_data = AddressData::default();
1078        account_data.insert(address, new_acc.clone());
1079
1080        backend.insert_or_update_address(account_data);
1081
1082        let max_slots = 5;
1083        let handle = std::thread::spawn(move || {
1084            for i in 1..max_slots {
1085                let idx = U256::from(i);
1086                let result_address = backend.basic_ref(address).unwrap();
1087                match result_address {
1088                    Some(acc) => {
1089                        assert_eq!(
1090                            acc.nonce, new_acc.nonce,
1091                            "The nonce was not changed in instance of index {idx}"
1092                        );
1093                        assert_eq!(
1094                            acc.balance, new_acc.balance,
1095                            "The balance was not changed in instance of index {idx}"
1096                        );
1097
1098                        // comparing with db
1099                        let db_address = {
1100                            let accounts = db.accounts().read();
1101                            accounts.get(&address).unwrap().clone()
1102                        };
1103
1104                        assert_eq!(
1105                            db_address.nonce, new_acc.nonce,
1106                            "The nonce was not changed in instance of index {idx}"
1107                        );
1108                        assert_eq!(
1109                            db_address.balance, new_acc.balance,
1110                            "The balance was not changed in instance of index {idx}"
1111                        );
1112                    }
1113                    None => panic!("Account not found"),
1114                }
1115            }
1116        });
1117        handle.join().unwrap();
1118    }
1119
1120    #[tokio::test(flavor = "multi_thread")]
1121    async fn can_modify_storage() {
1122        let Some(endpoint) = ENDPOINT else { return };
1123
1124        let provider = get_http_provider(endpoint);
1125        let meta = BlockchainDbMeta::new(Default::default(), endpoint.to_string());
1126
1127        let db = BlockchainDb::new(meta, None);
1128        let backend = SharedBackend::spawn_backend(Arc::new(provider), db.clone(), None).await;
1129
1130        // some rng contract from etherscan
1131        let address: Address = "63091244180ae240c87d1f528f5f269134cb07b3".parse().unwrap();
1132
1133        let mut storage_data = StorageData::default();
1134        let mut storage_info = StorageInfo::default();
1135        storage_info.insert(U256::from(20), U256::from(10));
1136        storage_info.insert(U256::from(30), U256::from(15));
1137        storage_info.insert(U256::from(40), U256::from(20));
1138
1139        storage_data.insert(address, storage_info);
1140
1141        backend.insert_or_update_storage(storage_data.clone());
1142
1143        let max_slots = 5;
1144        let handle = std::thread::spawn(move || {
1145            for _ in 1..max_slots {
1146                for (address, info) in &storage_data {
1147                    for (index, value) in info {
1148                        let result_storage = backend.do_get_storage(*address, *index);
1149                        match result_storage {
1150                            Ok(stg_db) => {
1151                                assert_eq!(
1152                                    stg_db, *value,
1153                                    "Storage in slot number {index} in address {address} do not have the same value"
1154                                );
1155
1156                                let db_result = {
1157                                    let storage = db.storage().read();
1158                                    let address_storage = storage.get(address).unwrap();
1159                                    *address_storage.get(index).unwrap()
1160                                };
1161
1162                                assert_eq!(
1163                                    stg_db, db_result,
1164                                    "Storage in slot number {index} in address {address} do not have the same value"
1165                                )
1166                            }
1167
1168                            Err(err) => {
1169                                panic!("There was a database error: {err}")
1170                            }
1171                        }
1172                    }
1173                }
1174            }
1175        });
1176        handle.join().unwrap();
1177    }
1178
1179    #[tokio::test(flavor = "multi_thread")]
1180    async fn can_modify_block_hashes() {
1181        let Some(endpoint) = ENDPOINT else { return };
1182
1183        let provider = get_http_provider(endpoint);
1184        let meta = BlockchainDbMeta::new(Default::default(), endpoint.to_string());
1185
1186        let db = BlockchainDb::new(meta, None);
1187        let backend = SharedBackend::spawn_backend(Arc::new(provider), db.clone(), None).await;
1188
1189        // some rng contract from etherscan
1190        // let address: Address = "63091244180ae240c87d1f528f5f269134cb07b3".parse().unwrap();
1191
1192        let mut block_hash_data = BlockHashData::default();
1193        block_hash_data.insert(U256::from(1), B256::from(U256::from(1)));
1194        block_hash_data.insert(U256::from(2), B256::from(U256::from(2)));
1195        block_hash_data.insert(U256::from(3), B256::from(U256::from(3)));
1196        block_hash_data.insert(U256::from(4), B256::from(U256::from(4)));
1197        block_hash_data.insert(U256::from(5), B256::from(U256::from(5)));
1198
1199        backend.insert_or_update_block_hashes(block_hash_data.clone());
1200
1201        let max_slots: u64 = 5;
1202        let handle = std::thread::spawn(move || {
1203            for i in 1..max_slots {
1204                let key = U256::from(i);
1205                let result_hash = backend.do_get_block_hash(i);
1206                match result_hash {
1207                    Ok(hash) => {
1208                        assert_eq!(
1209                            hash,
1210                            *block_hash_data.get(&key).unwrap(),
1211                            "The hash in block {key} did not match"
1212                        );
1213
1214                        let db_result = {
1215                            let hashes = db.block_hashes().read();
1216                            *hashes.get(&key).unwrap()
1217                        };
1218
1219                        assert_eq!(hash, db_result, "The hash in block {key} did not match");
1220                    }
1221                    Err(err) => panic!("Hash not found, error: {err}"),
1222                }
1223            }
1224        });
1225        handle.join().unwrap();
1226    }
1227
1228    #[tokio::test(flavor = "multi_thread")]
1229    async fn can_modify_storage_with_cache() {
1230        let Some(endpoint) = ENDPOINT else { return };
1231
1232        let provider = get_http_provider(endpoint);
1233        let meta = BlockchainDbMeta::new(Default::default(), endpoint.to_string());
1234
1235        // create a temporary file
1236        fs::copy("test-data/storage.json", "test-data/storage-tmp.json").unwrap();
1237
1238        let cache_path =
1239            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("test-data/storage-tmp.json");
1240
1241        let db = BlockchainDb::new(meta.clone(), Some(cache_path));
1242        let backend =
1243            SharedBackend::spawn_backend(Arc::new(provider.clone()), db.clone(), None).await;
1244
1245        // some rng contract from etherscan
1246        let address: Address = "63091244180ae240c87d1f528f5f269134cb07b3".parse().unwrap();
1247
1248        let mut storage_data = StorageData::default();
1249        let mut storage_info = StorageInfo::default();
1250        storage_info.insert(U256::from(1), U256::from(10));
1251        storage_info.insert(U256::from(2), U256::from(15));
1252        storage_info.insert(U256::from(3), U256::from(20));
1253        storage_info.insert(U256::from(4), U256::from(20));
1254        storage_info.insert(U256::from(5), U256::from(15));
1255        storage_info.insert(U256::from(6), U256::from(10));
1256
1257        let mut address_data = backend.basic_ref(address).unwrap().unwrap();
1258        address_data.code = None;
1259
1260        storage_data.insert(address, storage_info);
1261
1262        backend.insert_or_update_storage(storage_data.clone());
1263
1264        let mut new_acc = backend.basic_ref(address).unwrap().unwrap();
1265        // nullify the code
1266        new_acc.code = Some(Bytecode::new_raw(([10, 20, 30, 40]).into()));
1267
1268        let mut account_data = AddressData::default();
1269        account_data.insert(address, new_acc.clone());
1270
1271        backend.insert_or_update_address(account_data);
1272
1273        let backend_clone = backend.clone();
1274
1275        let max_slots = 5;
1276        let handle = std::thread::spawn(move || {
1277            for _ in 1..max_slots {
1278                for (address, info) in &storage_data {
1279                    for (index, value) in info {
1280                        let result_storage = backend.do_get_storage(*address, *index);
1281                        match result_storage {
1282                            Ok(stg_db) => {
1283                                assert_eq!(
1284                                    stg_db, *value,
1285                                    "Storage in slot number {index} in address {address} doesn't have the same value"
1286                                );
1287
1288                                let db_result = {
1289                                    let storage = db.storage().read();
1290                                    let address_storage = storage.get(address).unwrap();
1291                                    *address_storage.get(index).unwrap()
1292                                };
1293
1294                                assert_eq!(
1295                                    stg_db, db_result,
1296                                    "Storage in slot number {index} in address {address} doesn't have the same value"
1297                                );
1298                            }
1299
1300                            Err(err) => {
1301                                panic!("There was a database error: {err}")
1302                            }
1303                        }
1304                    }
1305                }
1306            }
1307
1308            backend_clone.flush_cache();
1309        });
1310        handle.join().unwrap();
1311
1312        // read json and confirm the changes to the data
1313
1314        let cache_path =
1315            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("test-data/storage-tmp.json");
1316
1317        let json_db = BlockchainDb::new(meta, Some(cache_path));
1318
1319        let mut storage_data = StorageData::default();
1320        let mut storage_info = StorageInfo::default();
1321        storage_info.insert(U256::from(1), U256::from(10));
1322        storage_info.insert(U256::from(2), U256::from(15));
1323        storage_info.insert(U256::from(3), U256::from(20));
1324        storage_info.insert(U256::from(4), U256::from(20));
1325        storage_info.insert(U256::from(5), U256::from(15));
1326        storage_info.insert(U256::from(6), U256::from(10));
1327
1328        storage_data.insert(address, storage_info);
1329
1330        // redo the checks with the data extracted from the json file
1331        let max_slots = 5;
1332        let handle = std::thread::spawn(move || {
1333            for _ in 1..max_slots {
1334                for (address, info) in &storage_data {
1335                    for (index, value) in info {
1336                        let result_storage = {
1337                            let storage = json_db.storage().read();
1338                            let address_storage = storage.get(address).unwrap().clone();
1339                            *address_storage.get(index).unwrap()
1340                        };
1341
1342                        assert_eq!(
1343                            result_storage, *value,
1344                            "Storage in slot number {index} in address {address} doesn't have the same value"
1345                        );
1346                    }
1347                }
1348            }
1349        });
1350
1351        handle.join().unwrap();
1352
1353        // erase the temporary file
1354        fs::remove_file("test-data/storage-tmp.json").unwrap();
1355    }
1356
1357    #[tokio::test(flavor = "multi_thread")]
1358    async fn shared_backend_any_request() {
1359        let expected_response_bytes: Bytes = vec![0xff, 0xee].into();
1360        let server = Server::http("0.0.0.0:0").expect("failed starting in-memory http server");
1361        let endpoint = format!("http://{}", server.server_addr());
1362
1363        // Spin an in-memory server that responds to "foo_callCustomMethod" rpc call.
1364        let expected_bytes_innner = expected_response_bytes.clone();
1365        let server_handle = std::thread::spawn(move || {
1366            #[derive(Debug, Deserialize)]
1367            struct Request {
1368                method: String,
1369            }
1370            let mut request = server.recv().unwrap();
1371            let rpc_request: Request =
1372                serde_json::from_reader(request.as_reader()).expect("failed parsing request");
1373
1374            match rpc_request.method.as_str() {
1375                "foo_callCustomMethod" => request
1376                    .respond(Response::from_string(format!(
1377                        r#"{{"result": "{}"}}"#,
1378                        alloy_primitives::hex::encode_prefixed(expected_bytes_innner),
1379                    )))
1380                    .unwrap(),
1381                _ => request
1382                    .respond(Response::from_string(r#"{"error": "invalid request"}"#))
1383                    .unwrap(),
1384            };
1385        });
1386
1387        let provider = get_http_provider(&endpoint);
1388        let meta = BlockchainDbMeta::new(Default::default(), endpoint.to_string());
1389
1390        let db = BlockchainDb::new(meta, None);
1391        let provider_inner = provider.clone();
1392        let mut backend = SharedBackend::spawn_backend(Arc::new(provider), db.clone(), None).await;
1393
1394        let actual_response_bytes = backend
1395            .do_any_request(async move {
1396                let bytes: alloy_primitives::Bytes =
1397                    provider_inner.raw_request("foo_callCustomMethod".into(), vec!["0001"]).await?;
1398                Ok(bytes)
1399            })
1400            .expect("failed performing any request");
1401
1402        assert_eq!(actual_response_bytes, expected_response_bytes);
1403
1404        server_handle.join().unwrap();
1405    }
1406}