anvil_zksync_common/
cache.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
use super::{sh_err, sh_warn};
use clap::ValueEnum;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use std::fs;
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::path::Path;
use std::result::Result;
use std::str::FromStr;
use zksync_types::api::{Block, BridgeAddresses, Transaction, TransactionVariant};
use zksync_types::Transaction as RawTransaction;
use zksync_types::H256;

pub const DEFAULT_DISK_CACHE_DIR: &str = ".cache";
/// Caches full blocks by their hashes
const CACHE_TYPE_BLOCKS_FULL: &str = "blocks_full";
/// Caches minimal blocks by their hashes
const CACHE_TYPE_BLOCKS_MIN: &str = "blocks_min";
/// Caches raw transactions by their hashes
const CACHE_TYPE_BLOCK_RAW_TRANSACTIONS: &str = "block_raw_transactions";
/// Caches transactions by their hashes
const CACHE_TYPE_TRANSACTIONS: &str = "transactions";
/// Caching resolver functions by their selectors
const CACHE_TYPE_RESOLVER_SELECTORS: &str = "resolver_selectors";
/// Caches arbitrary values by their keys
const CACHE_TYPE_KEY_VALUE: &str = "key_value";

/// Caching key for bridge addresses
const CACHE_KEY_BRIDGE_ADDRESSES: &str = "bridge_addresses";

/// Cache type for the node.
#[derive(ValueEnum, Deserialize, Default, Debug, Copy, Clone)]
pub enum CacheType {
    None,
    Memory,
    #[default]
    Disk,
}

/// Cache configuration options.
#[derive(Deserialize, Debug, Clone)]
pub enum CacheConfig {
    #[serde(rename = "none")]
    None,
    #[serde(rename = "memory")]
    Memory,
    #[serde(rename = "disk")]
    Disk { dir: String, reset: bool },
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self::Disk {
            dir: String::from(DEFAULT_DISK_CACHE_DIR),
            reset: false,
        }
    }
}

/// A general purpose cache.
#[derive(Default, Debug, Clone)]
pub struct Cache {
    config: CacheConfig,
    block_hashes: FxHashMap<u64, H256>,
    blocks_full: FxHashMap<H256, Block<TransactionVariant>>,
    blocks_min: FxHashMap<H256, Block<TransactionVariant>>,
    block_raw_transactions: FxHashMap<u64, Vec<RawTransaction>>,
    transactions: FxHashMap<H256, Transaction>,
    resolver_selectors: FxHashMap<String, String>,
    bridge_addresses: Option<BridgeAddresses>,
    confirmed_tokens: FxHashMap<(u32, u8), Vec<zksync_web3_decl::types::Token>>,
}

impl Cache {
    /// Creates a new cache with the provided config.
    pub fn new(config: CacheConfig) -> Self {
        let mut cache = Cache {
            config: config.clone(),
            ..Default::default()
        };

        if let CacheConfig::Disk { dir, reset } = &config {
            if *reset {
                for cache_type in [
                    CACHE_TYPE_BLOCKS_FULL,
                    CACHE_TYPE_BLOCKS_MIN,
                    CACHE_TYPE_BLOCK_RAW_TRANSACTIONS,
                    CACHE_TYPE_TRANSACTIONS,
                    CACHE_TYPE_RESOLVER_SELECTORS,
                    CACHE_TYPE_KEY_VALUE,
                ] {
                    fs::remove_dir_all(Path::new(dir).join(cache_type)).unwrap_or_else(|err| {
                        sh_warn!(
                            "failed removing directory {:?}: {:?}",
                            Path::new(dir).join(cache_type),
                            err
                        )
                    });
                }

                fs::remove_dir(Path::new(dir))
                    .unwrap_or_else(|err| sh_warn!("failed removing cache directory: {:?}", err));
            }

            for cache_type in [
                CACHE_TYPE_BLOCKS_FULL,
                CACHE_TYPE_BLOCKS_MIN,
                CACHE_TYPE_BLOCK_RAW_TRANSACTIONS,
                CACHE_TYPE_TRANSACTIONS,
                CACHE_TYPE_RESOLVER_SELECTORS,
                CACHE_TYPE_KEY_VALUE,
            ] {
                fs::create_dir_all(Path::new(dir).join(cache_type)).unwrap_or_else(|err| {
                    panic!("failed creating directory {}: {:?}", cache_type, err)
                });
            }
            cache
                .read_all_from_disk(dir)
                .unwrap_or_else(|err| sh_err!("failed reading cache from disk: {:?}", err));
        }

        cache
    }

    /// Returns the cached full/minimal block for the provided hash.
    pub fn get_block(
        &self,
        hash: &H256,
        full_transactions: bool,
    ) -> Option<&Block<TransactionVariant>> {
        if matches!(self.config, CacheConfig::None) {
            return None;
        }

        if full_transactions {
            self.blocks_full.get(hash)
        } else {
            self.blocks_min.get(hash)
        }
    }

    /// Cache a full/minimal block for the provided hash.
    pub fn insert_block(
        &mut self,
        hash: H256,
        full_transactions: bool,
        block: Block<TransactionVariant>,
    ) {
        if matches!(self.config, CacheConfig::None) {
            return;
        }

        self.block_hashes.insert(block.number.as_u64(), block.hash);
        if full_transactions {
            self.write_to_disk(CACHE_TYPE_BLOCKS_FULL, format!("{:#x}", hash), &block);
            self.blocks_full.insert(hash, block);
        } else {
            self.write_to_disk(CACHE_TYPE_BLOCKS_MIN, format!("{:#x}", hash), &block);
            self.blocks_min.insert(hash, block);
        }
    }

    /// Returns the cached full/minimal block for the provided hash.
    pub fn get_block_hash(&self, number: &u64) -> Option<&H256> {
        if matches!(self.config, CacheConfig::None) {
            return None;
        }

        self.block_hashes.get(number)
    }

    /// Returns the cached raw transactions for the provided block number.
    pub fn get_block_raw_transactions(&self, number: &u64) -> Option<&Vec<RawTransaction>> {
        if matches!(self.config, CacheConfig::None) {
            return None;
        }

        self.block_raw_transactions.get(number)
    }

    /// Returns the cached confirmed tokens.
    pub fn get_confirmed_tokens(
        &self,
        from: u32,
        limit: u8,
    ) -> Option<&Vec<zksync_web3_decl::types::Token>> {
        if matches!(self.config, CacheConfig::None) {
            return None;
        }
        self.confirmed_tokens.get(&(from, limit))
    }

    /// Cache confirmed tokens
    pub fn set_confirmed_tokens(
        &mut self,
        from: u32,
        limit: u8,
        confirmed_tokens: Vec<zksync_web3_decl::types::Token>,
    ) {
        if matches!(self.config, CacheConfig::None) {
            return;
        }
        self.confirmed_tokens
            .insert((from, limit), confirmed_tokens);
    }

    /// Cache the raw transactions for the provided block number.
    pub fn insert_block_raw_transactions(
        &mut self,
        number: u64,
        transactions: Vec<RawTransaction>,
    ) {
        if matches!(self.config, CacheConfig::None) {
            return;
        }

        self.write_to_disk(
            CACHE_TYPE_BLOCK_RAW_TRANSACTIONS,
            format!("{}", number),
            &transactions,
        );
        self.block_raw_transactions.insert(number, transactions);
    }

    /// Returns the cached transaction for the provided hash.
    pub fn get_transaction(&self, hash: &H256) -> Option<&Transaction> {
        if matches!(self.config, CacheConfig::None) {
            return None;
        }

        self.transactions.get(hash)
    }

    /// Returns the cached resolved function/event selector for the provided selector.
    pub fn get_resolver_selector(&self, selector: &String) -> Option<&String> {
        if matches!(self.config, CacheConfig::None) {
            return None;
        }

        self.resolver_selectors.get(selector)
    }

    /// Cache a transaction for the provided hash.
    pub fn insert_transaction(&mut self, hash: H256, transaction: Transaction) {
        if matches!(self.config, CacheConfig::None) {
            return;
        }

        self.write_to_disk(
            CACHE_TYPE_TRANSACTIONS,
            format!("{:#x}", hash),
            &transaction,
        );
        self.transactions.insert(hash, transaction);
    }

    /// Cache a resolver function for the provided selector.
    pub fn insert_resolver_selector(&mut self, selector: String, selector_value: String) {
        if matches!(self.config, CacheConfig::None) {
            return;
        }

        self.write_to_disk(
            CACHE_TYPE_RESOLVER_SELECTORS,
            selector.clone(),
            &selector_value,
        );
        self.resolver_selectors.insert(selector, selector_value);
    }

    /// Returns the cached bridge addresses for the provided hash.
    pub fn get_bridge_addresses(&self) -> Option<&BridgeAddresses> {
        if matches!(self.config, CacheConfig::None) {
            return None;
        }

        self.bridge_addresses.as_ref()
    }

    /// Cache default bridge addresses.
    pub fn set_bridge_addresses(&mut self, bridge_addresses: BridgeAddresses) {
        if matches!(self.config, CacheConfig::None) {
            return;
        }

        self.write_to_disk(
            CACHE_TYPE_KEY_VALUE,
            String::from(CACHE_KEY_BRIDGE_ADDRESSES),
            &bridge_addresses,
        );
        self.bridge_addresses = Some(bridge_addresses);
    }

    /// Reads the cache contents from the disk, if available.
    fn read_all_from_disk(&mut self, dir: &str) -> Result<(), String> {
        for cache_type in [
            CACHE_TYPE_BLOCKS_FULL,
            CACHE_TYPE_BLOCKS_MIN,
            CACHE_TYPE_BLOCK_RAW_TRANSACTIONS,
            CACHE_TYPE_TRANSACTIONS,
            CACHE_TYPE_RESOLVER_SELECTORS,
            CACHE_TYPE_KEY_VALUE,
        ] {
            let cache_dir = Path::new(dir).join(cache_type);
            let dir_listing = fs::read_dir(cache_dir.clone())
                .map_err(|err| format!("failed reading dir '{:?}': {:?}", cache_dir, err))?
                .flatten();
            for file in dir_listing {
                let key = file
                    .file_name()
                    .to_str()
                    .ok_or_else(|| String::from("failed converting filename to string"))?
                    .to_string();

                let cache_file = File::open(file.path()).map_err(|err| {
                    format!("failed reading file: '{:?}': {:?}", file.path(), err)
                })?;
                let reader = BufReader::new(cache_file);
                match cache_type {
                    CACHE_TYPE_BLOCKS_FULL => {
                        let key = H256::from_str(&key).map_err(|err| {
                            format!("invalid key for cache file '{:?}': {:?}", key, err)
                        })?;
                        let block: Block<TransactionVariant> = serde_json::from_reader(reader)
                            .map_err(|err| {
                                format!("failed parsing json for cache file '{:?}': {:?}", key, err)
                            })?;
                        self.block_hashes.insert(block.number.as_u64(), block.hash);
                        self.blocks_full.insert(key, block);
                    }
                    CACHE_TYPE_BLOCKS_MIN => {
                        let key = H256::from_str(&key).map_err(|err| {
                            format!("invalid key for cache file '{:?}': {:?}", key, err)
                        })?;
                        let block: Block<TransactionVariant> = serde_json::from_reader(reader)
                            .map_err(|err| {
                                format!("failed parsing json for cache file '{:?}': {:?}", key, err)
                            })?;
                        self.block_hashes.insert(block.number.as_u64(), block.hash);
                        self.blocks_min.insert(key, block);
                    }
                    CACHE_TYPE_BLOCK_RAW_TRANSACTIONS => {
                        let key = key.parse::<u64>().map_err(|err| {
                            format!("invalid key for cache file '{:?}': {:?}", key, err)
                        })?;
                        let transactions: Vec<RawTransaction> = serde_json::from_reader(reader)
                            .map_err(|err| {
                                format!("failed parsing json for cache file '{:?}': {:?}", key, err)
                            })?;
                        self.block_raw_transactions.insert(key, transactions);
                    }
                    CACHE_TYPE_TRANSACTIONS => {
                        let key = H256::from_str(&key).map_err(|err| {
                            format!("invalid key for cache file '{:?}': {:?}", key, err)
                        })?;
                        let transaction: Transaction =
                            serde_json::from_reader(reader).map_err(|err| {
                                format!("failed parsing json for cache file '{:?}': {:?}", key, err)
                            })?;
                        self.transactions.insert(key, transaction);
                    }
                    CACHE_TYPE_RESOLVER_SELECTORS => {
                        let selector: String = serde_json::from_reader(reader).map_err(|err| {
                            format!("failed parsing json for cache file '{:?}': {:?}", key, err)
                        })?;
                        self.resolver_selectors.insert(key, selector);
                    }
                    CACHE_TYPE_KEY_VALUE => match key.as_str() {
                        CACHE_KEY_BRIDGE_ADDRESSES => {
                            self.bridge_addresses =
                                Some(serde_json::from_reader(reader).map_err(|err| {
                                    format!(
                                        "failed parsing json for cache file '{:?}': {:?}",
                                        key, err
                                    )
                                })?);
                        }
                        _ => return Err(format!("invalid cache_type_value key {}", cache_type)),
                    },
                    _ => return Err(format!("invalid cache_type {}", cache_type)),
                }
            }
        }

        Ok(())
    }

    /// Writes the cache contents to disk, if supported.
    fn write_to_disk<T: Serialize>(&self, cache_type: &'static str, key: String, data: &T) {
        if let CacheConfig::Disk { dir, .. } = &self.config {
            let file = Path::new(&dir).join(cache_type).join(key);

            tracing::debug!("writing cache {:?}", file);
            match File::create(file.clone()) {
                Ok(cache_file) => {
                    let writer = BufWriter::new(cache_file);
                    if let Err(err) = serde_json::to_writer(writer, data) {
                        sh_err!("failed writing to cache '{:?}': {:?}", file, err);
                    }
                }
                Err(err) => sh_err!("failed creating file: '{:?}': {:?}", file, err),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use zksync_types::{Execute, ExecuteTransactionCommon};
    use zksync_types::{H160, U64};

    // use crate::testing;

    use super::*;

    #[test]
    fn test_cache_config_none_disables_cache() {
        let mut cache = Cache::new(CacheConfig::None);

        cache.insert_block(H256::zero(), true, Default::default());
        assert_eq!(None, cache.get_block(&H256::zero(), true));
        assert_eq!(None, cache.get_block_hash(&0));

        cache.insert_block(H256::zero(), false, Default::default());
        assert_eq!(None, cache.get_block(&H256::zero(), false));
        assert_eq!(None, cache.get_block_hash(&0));

        cache.insert_block_raw_transactions(0, Default::default());
        assert_eq!(None, cache.get_block_raw_transactions(&0));

        cache.insert_transaction(H256::zero(), Default::default());
        assert_eq!(None, cache.get_transaction(&H256::zero()));
    }

    #[test]
    fn test_cache_config_memory_enables_cache() {
        let block_full = Block::<TransactionVariant> {
            hash: H256::repeat_byte(0x1),
            number: U64::from(1),
            ..Default::default()
        };
        let block_min = Block::<TransactionVariant> {
            hash: H256::repeat_byte(0x2),
            number: U64::from(2),
            ..Default::default()
        };
        let transaction = Transaction::default();
        let raw_transactions = vec![RawTransaction {
            common_data: ExecuteTransactionCommon::L1(Default::default()),
            execute: Execute {
                calldata: Default::default(),
                contract_address: Default::default(),
                factory_deps: vec![],
                value: Default::default(),
            },
            received_timestamp_ms: 0,
            raw_bytes: None,
        }];
        let bridge_addresses = BridgeAddresses {
            l1_shared_default_bridge: Some(H160::repeat_byte(0x5)),
            l2_shared_default_bridge: Some(H160::repeat_byte(0x6)),
            l1_erc20_default_bridge: Some(H160::repeat_byte(0x1)),
            l2_erc20_default_bridge: Some(H160::repeat_byte(0x2)),
            l1_weth_bridge: Some(H160::repeat_byte(0x3)),
            l2_weth_bridge: Some(H160::repeat_byte(0x4)),
            l2_legacy_shared_bridge: Some(H160::repeat_byte(0x6)),
        };

        let mut cache = Cache::new(CacheConfig::Memory);

        cache.insert_block(block_full.hash, true, block_full.clone());
        assert_eq!(
            Some(&block_full),
            cache.get_block(&H256::repeat_byte(0x1), true)
        );
        assert_eq!(Some(&H256::repeat_byte(0x1)), cache.get_block_hash(&1));

        cache.insert_block(block_min.hash, false, block_min.clone());
        assert_eq!(
            Some(&block_min),
            cache.get_block(&H256::repeat_byte(0x2), false)
        );
        assert_eq!(Some(&H256::repeat_byte(0x2)), cache.get_block_hash(&2));

        cache.insert_block_raw_transactions(0, raw_transactions.clone());
        assert_eq!(
            Some(&raw_transactions),
            cache.get_block_raw_transactions(&0)
        );

        cache.insert_transaction(H256::zero(), transaction.clone());
        assert_eq!(Some(&transaction), cache.get_transaction(&H256::zero()));

        cache.set_bridge_addresses(bridge_addresses.clone());
        assert_bridge_addresses_eq(
            &bridge_addresses,
            cache.get_bridge_addresses().expect("expected addresses"),
        );
    }

    #[test]
    fn test_cache_config_disk_enables_cache_and_preserves_it_to_disk() {
        let block_full = Block::<TransactionVariant> {
            hash: H256::repeat_byte(0x1),
            number: U64::from(1),
            ..Default::default()
        };
        let block_min = Block::<TransactionVariant> {
            hash: H256::repeat_byte(0x2),
            number: U64::from(2),
            ..Default::default()
        };
        let transaction = Transaction::default();
        let raw_transactions = vec![RawTransaction {
            common_data: ExecuteTransactionCommon::L1(Default::default()),
            execute: Execute {
                calldata: Default::default(),
                contract_address: Default::default(),
                factory_deps: vec![],
                value: Default::default(),
            },
            received_timestamp_ms: 0,
            raw_bytes: None,
        }];
        let bridge_addresses = BridgeAddresses {
            l1_shared_default_bridge: Some(H160::repeat_byte(0x5)),
            l2_shared_default_bridge: Some(H160::repeat_byte(0x6)),
            l1_erc20_default_bridge: Some(H160::repeat_byte(0x1)),
            l2_erc20_default_bridge: Some(H160::repeat_byte(0x2)),
            l1_weth_bridge: Some(H160::repeat_byte(0x3)),
            l2_weth_bridge: Some(H160::repeat_byte(0x4)),
            l2_legacy_shared_bridge: Some(H160::repeat_byte(0x6)),
        };

        let cache_dir = tempfile::Builder::new()
            .prefix("cache-test")
            .tempdir()
            .expect("failed creating temporary dir");
        let cache_dir_path = cache_dir
            .path()
            .to_str()
            .expect("invalid dir name")
            .to_string();
        let mut cache = Cache::new(CacheConfig::Disk {
            dir: cache_dir_path.clone(),
            reset: true,
        });

        cache.insert_block(block_full.hash, true, block_full.clone());
        assert_eq!(
            Some(&block_full),
            cache.get_block(&H256::repeat_byte(0x1), true)
        );
        assert_eq!(Some(&H256::repeat_byte(0x1)), cache.get_block_hash(&1));

        cache.insert_block(block_min.hash, false, block_min.clone());
        assert_eq!(
            Some(&block_min),
            cache.get_block(&H256::repeat_byte(0x2), false)
        );
        assert_eq!(Some(&H256::repeat_byte(0x2)), cache.get_block_hash(&2));

        cache.insert_block_raw_transactions(0, raw_transactions.clone());
        assert_eq!(
            Some(&raw_transactions),
            cache.get_block_raw_transactions(&0)
        );

        cache.insert_transaction(H256::zero(), transaction.clone());
        assert_eq!(Some(&transaction), cache.get_transaction(&H256::zero()));

        cache.set_bridge_addresses(bridge_addresses.clone());
        assert_bridge_addresses_eq(
            &bridge_addresses,
            cache.get_bridge_addresses().expect("expected addresses"),
        );

        let new_cache = Cache::new(CacheConfig::Disk {
            dir: cache_dir_path,
            reset: false,
        });
        assert_eq!(
            Some(&block_full),
            new_cache.get_block(&H256::repeat_byte(0x1), true)
        );
        assert_eq!(Some(&H256::repeat_byte(0x1)), new_cache.get_block_hash(&1));
        assert_eq!(
            Some(&block_min),
            new_cache.get_block(&H256::repeat_byte(0x2), false)
        );
        assert_eq!(Some(&H256::repeat_byte(0x2)), new_cache.get_block_hash(&2));
        assert_eq!(
            Some(&raw_transactions),
            new_cache.get_block_raw_transactions(&0)
        );
        assert_eq!(Some(&transaction), new_cache.get_transaction(&H256::zero()));
        assert_bridge_addresses_eq(
            &bridge_addresses,
            new_cache
                .get_bridge_addresses()
                .expect("expected addresses"),
        );
    }

    #[test]
    fn test_cache_config_disk_enables_cache_and_can_reset_data_on_disk() {
        let block_full = Block::<TransactionVariant> {
            hash: H256::repeat_byte(0x1),
            number: U64::from(1),
            ..Default::default()
        };
        let block_min = Block::<TransactionVariant> {
            hash: H256::repeat_byte(0x2),
            number: U64::from(2),
            ..Default::default()
        };
        let transaction = Transaction::default();
        let raw_transactions = vec![RawTransaction {
            common_data: ExecuteTransactionCommon::L1(Default::default()),
            execute: Execute {
                calldata: Default::default(),
                contract_address: Default::default(),
                factory_deps: vec![],
                value: Default::default(),
            },
            received_timestamp_ms: 0,
            raw_bytes: None,
        }];
        let bridge_addresses = BridgeAddresses {
            l1_shared_default_bridge: Some(H160::repeat_byte(0x5)),
            l2_shared_default_bridge: Some(H160::repeat_byte(0x6)),
            l2_erc20_default_bridge: Some(H160::repeat_byte(0x2)),
            l1_erc20_default_bridge: Some(H160::repeat_byte(0x1)),
            l1_weth_bridge: Some(H160::repeat_byte(0x3)),
            l2_weth_bridge: Some(H160::repeat_byte(0x4)),
            l2_legacy_shared_bridge: Some(H160::repeat_byte(0x6)),
        };

        let cache_dir = tempfile::Builder::new()
            .prefix("cache-test")
            .tempdir()
            .expect("failed creating temporary dir");
        let cache_dir_path = cache_dir
            .path()
            .to_str()
            .expect("invalid dir name")
            .to_string();
        let mut cache = Cache::new(CacheConfig::Disk {
            dir: cache_dir_path.clone(),
            reset: true,
        });

        cache.insert_block(block_full.hash, true, block_full.clone());
        assert_eq!(
            Some(&block_full),
            cache.get_block(&H256::repeat_byte(0x1), true)
        );
        assert_eq!(Some(&H256::repeat_byte(0x1)), cache.get_block_hash(&1));

        cache.insert_block(block_min.hash, false, block_min.clone());
        assert_eq!(
            Some(&block_min),
            cache.get_block(&H256::repeat_byte(0x2), false)
        );
        assert_eq!(Some(&H256::repeat_byte(0x2)), cache.get_block_hash(&2));

        cache.insert_block_raw_transactions(0, raw_transactions.clone());
        assert_eq!(
            Some(&raw_transactions),
            cache.get_block_raw_transactions(&0)
        );

        cache.insert_transaction(H256::zero(), transaction.clone());
        assert_eq!(Some(&transaction), cache.get_transaction(&H256::zero()));

        cache.set_bridge_addresses(bridge_addresses.clone());
        assert_bridge_addresses_eq(
            &bridge_addresses,
            cache.get_bridge_addresses().expect("expected addresses"),
        );

        let new_cache = Cache::new(CacheConfig::Disk {
            dir: cache_dir_path,
            reset: true,
        });
        assert_eq!(None, new_cache.get_block(&H256::zero(), true));
        assert_eq!(None, new_cache.get_block_hash(&1));
        assert_eq!(None, new_cache.get_block(&H256::zero(), false));
        assert_eq!(None, new_cache.get_block_hash(&2));
        assert_eq!(None, new_cache.get_block_raw_transactions(&0));
        assert_eq!(None, new_cache.get_transaction(&H256::zero()));
        assert!(new_cache.get_bridge_addresses().is_none());
    }

    #[test]
    fn test_cache_config_disk_only_resets_created_data_on_disk() {
        let cache_dir = tempfile::Builder::new()
            .prefix("cache-test")
            .tempdir()
            .expect("failed creating temporary dir");
        let cache_dir_path = cache_dir
            .path()
            .to_str()
            .expect("invalid dir name")
            .to_string();
        let mut cache = Cache::new(CacheConfig::Disk {
            dir: cache_dir_path.clone(),
            reset: true,
        });

        cache.insert_transaction(H256::zero(), Default::default());
        let cached_tx_file = cache_dir
            .path()
            .join(CACHE_TYPE_TRANSACTIONS)
            .join(format!("{:#x}", H256::zero()));
        assert!(
            cached_tx_file.exists(),
            "cached transaction did not exist on disk"
        );

        let random_file_path = cache_dir.path().join("foobar.txt");
        _ = File::create(&random_file_path).expect("failed creating random file");

        Cache::new(CacheConfig::Disk {
            dir: cache_dir_path,
            reset: true,
        });

        assert!(
            !cached_tx_file.exists(),
            "cached transaction was not reset on disk"
        );
        assert!(random_file_path.exists(), "random file was reset from disk");
    }

    /// Asserts that two instances of [BridgeAddresses] are equal
    pub fn assert_bridge_addresses_eq(
        expected_bridge_addresses: &BridgeAddresses,
        actual_bridge_addresses: &BridgeAddresses,
    ) {
        assert_eq!(
            expected_bridge_addresses.l1_erc20_default_bridge,
            actual_bridge_addresses.l1_erc20_default_bridge
        );
        assert_eq!(
            expected_bridge_addresses.l2_erc20_default_bridge,
            actual_bridge_addresses.l2_erc20_default_bridge
        );
        assert_eq!(
            expected_bridge_addresses.l1_weth_bridge,
            actual_bridge_addresses.l1_weth_bridge
        );
        assert_eq!(
            expected_bridge_addresses.l2_weth_bridge,
            actual_bridge_addresses.l2_weth_bridge
        );
    }
}