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
use std::sync::RwLock;

use eyre::Context;
use zksync_basic_types::{H256, U256};
use zksync_types::api::Transaction;
use zksync_web3_decl::{
    jsonrpsee::http_client::{HttpClient, HttpClientBuilder},
    namespaces::{EthNamespaceClient, ZksNamespaceClient},
    types::Index,
};

use crate::{
    cache::{Cache, CacheConfig},
    fork::{block_on, ForkSource},
};

#[derive(Debug)]
/// Fork source that gets the data via HTTP requests.
pub struct HttpForkSource {
    /// URL for the network to fork.
    pub fork_url: String,
    /// Cache for network data.
    pub(crate) cache: RwLock<Cache>,
}

impl HttpForkSource {
    pub fn new(fork_url: String, cache_config: CacheConfig) -> Self {
        Self {
            fork_url,
            cache: RwLock::new(Cache::new(cache_config)),
        }
    }

    pub fn create_client(&self) -> HttpClient {
        HttpClientBuilder::default()
            .build(self.fork_url.clone())
            .unwrap_or_else(|_| panic!("Unable to create a client for fork: {}", self.fork_url))
    }
}

impl ForkSource for HttpForkSource {
    fn get_storage_at(
        &self,
        address: zksync_basic_types::Address,
        idx: zksync_basic_types::U256,
        block: Option<zksync_types::api::BlockIdVariant>,
    ) -> eyre::Result<zksync_basic_types::H256> {
        let client = self.create_client();
        block_on(async move { client.get_storage_at(address, idx, block).await })
            .wrap_err("fork http client failed")
    }

    fn get_bytecode_by_hash(
        &self,
        hash: zksync_basic_types::H256,
    ) -> eyre::Result<Option<Vec<u8>>> {
        let client = self.create_client();
        block_on(async move { client.get_bytecode_by_hash(hash).await })
            .wrap_err("fork http client failed")
    }

    fn get_transaction_by_hash(
        &self,
        hash: zksync_basic_types::H256,
    ) -> eyre::Result<Option<zksync_types::api::Transaction>> {
        if let Ok(Some(transaction)) = self
            .cache
            .read()
            .map(|guard| guard.get_transaction(&hash).cloned())
        {
            log::debug!("using cached transaction for {hash}");
            return Ok(Some(transaction));
        }

        let client = self.create_client();
        block_on(async move { client.get_transaction_by_hash(hash).await })
            .map(|maybe_transaction| {
                if let Some(transaction) = &maybe_transaction {
                    self.cache
                        .write()
                        .map(|mut guard| guard.insert_transaction(hash, transaction.clone()))
                        .unwrap_or_else(|err| {
                            log::warn!(
                                "failed writing to cache for 'get_transaction_by_hash': {:?}",
                                err
                            )
                        });
                }
                maybe_transaction
            })
            .wrap_err("fork http client failed")
    }

    fn get_raw_block_transactions(
        &self,
        block_number: zksync_basic_types::MiniblockNumber,
    ) -> eyre::Result<Vec<zksync_types::Transaction>> {
        let number = block_number.0 as u64;
        if let Ok(Some(transaction)) = self
            .cache
            .read()
            .map(|guard| guard.get_block_raw_transactions(&number).cloned())
        {
            log::debug!("using cached raw transactions for block {block_number}");
            return Ok(transaction);
        }

        let client = self.create_client();
        block_on(async move { client.get_raw_block_transactions(block_number).await })
            .wrap_err("fork http client failed")
            .map(|transactions| {
                if !transactions.is_empty() {
                    self.cache
                        .write()
                        .map(|mut guard| {
                            guard.insert_block_raw_transactions(number, transactions.clone())
                        })
                        .unwrap_or_else(|err| {
                            log::warn!(
                                "failed writing to cache for 'get_raw_block_transactions': {:?}",
                                err
                            )
                        });
                }
                transactions
            })
    }

    fn get_block_by_hash(
        &self,
        hash: zksync_basic_types::H256,
        full_transactions: bool,
    ) -> eyre::Result<Option<zksync_types::api::Block<zksync_types::api::TransactionVariant>>> {
        if let Ok(Some(block)) = self
            .cache
            .read()
            .map(|guard| guard.get_block(&hash, full_transactions).cloned())
        {
            log::debug!("using cached block for {hash}");
            return Ok(Some(block));
        }

        let client = self.create_client();
        block_on(async move { client.get_block_by_hash(hash, full_transactions).await })
            .map(|block| {
                if let Some(block) = &block {
                    self.cache
                        .write()
                        .map(|mut guard| guard.insert_block(hash, full_transactions, block.clone()))
                        .unwrap_or_else(|err| {
                            log::warn!("failed writing to cache for 'get_block_by_hash': {:?}", err)
                        });
                }
                block
            })
            .wrap_err("fork http client failed")
    }

    fn get_block_by_number(
        &self,
        block_number: zksync_types::api::BlockNumber,
        full_transactions: bool,
    ) -> eyre::Result<Option<zksync_types::api::Block<zksync_types::api::TransactionVariant>>> {
        let maybe_number = match block_number {
            zksync_types::api::BlockNumber::Number(block_number) => Some(block_number),
            _ => None,
        };

        if let Some(block) = maybe_number.and_then(|number| {
            self.cache.read().ok().and_then(|guard| {
                guard
                    .get_block_hash(&number.as_u64())
                    .and_then(|hash| guard.get_block(hash, full_transactions).cloned())
            })
        }) {
            log::debug!("using cached block for {block_number}");
            return Ok(Some(block));
        }

        let client = self.create_client();
        block_on(async move {
            client
                .get_block_by_number(block_number, full_transactions)
                .await
        })
        .map(|block| {
            if let Some(block) = &block {
                self.cache
                    .write()
                    .map(|mut guard| {
                        guard.insert_block(block.hash, full_transactions, block.clone())
                    })
                    .unwrap_or_else(|err| {
                        log::warn!(
                            "failed writing to cache for 'get_block_by_number': {:?}",
                            err
                        )
                    });
            }
            block
        })
        .wrap_err("fork http client failed")
    }

    /// Returns the  transaction count for a given block hash.
    fn get_block_transaction_count_by_hash(&self, block_hash: H256) -> eyre::Result<Option<U256>> {
        let client = self.create_client();
        block_on(async move { client.get_block_transaction_count_by_hash(block_hash).await })
            .wrap_err("fork http client failed")
    }

    /// Returns the transaction count for a given block number.
    fn get_block_transaction_count_by_number(
        &self,
        block_number: zksync_types::api::BlockNumber,
    ) -> eyre::Result<Option<U256>> {
        let client = self.create_client();
        block_on(async move {
            client
                .get_block_transaction_count_by_number(block_number)
                .await
        })
        .wrap_err("fork http client failed")
    }

    /// Returns information about a transaction by block hash and transaction index position.
    fn get_transaction_by_block_hash_and_index(
        &self,
        block_hash: H256,
        index: Index,
    ) -> eyre::Result<Option<Transaction>> {
        let client = self.create_client();
        block_on(async move {
            client
                .get_transaction_by_block_hash_and_index(block_hash, index)
                .await
        })
        .wrap_err("fork http client failed")
    }

    /// Returns information about a transaction by block number and transaction index position.
    fn get_transaction_by_block_number_and_index(
        &self,
        block_number: zksync_types::api::BlockNumber,
        index: Index,
    ) -> eyre::Result<Option<Transaction>> {
        let client = self.create_client();
        block_on(async move {
            client
                .get_transaction_by_block_number_and_index(block_number, index)
                .await
        })
        .wrap_err("fork http client failed")
    }
}

#[cfg(test)]
mod tests {
    use zksync_basic_types::{MiniblockNumber, H256, U64};
    use zksync_types::api::BlockNumber;

    use crate::testing;

    use super::*;

    #[test]
    fn test_get_block_by_hash_full_is_cached() {
        let input_block_hash = H256::repeat_byte(0x01);
        let input_block_number = 8;

        let mock_server = testing::MockServer::run();
        mock_server.expect(
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 0,
                "method": "eth_getBlockByHash",
                "params": [
                    format!("{input_block_hash:#x}"),
                    true
                ],
            }),
            testing::BlockResponseBuilder::new()
                .set_hash(input_block_hash)
                .set_number(input_block_number)
                .build(),
        );

        let fork_source = HttpForkSource::new(mock_server.url(), CacheConfig::Memory);

        let actual_block = fork_source
            .get_block_by_hash(input_block_hash, true)
            .expect("failed fetching block by hash")
            .expect("no block");

        assert_eq!(input_block_hash, actual_block.hash);
        assert_eq!(U64::from(input_block_number), actual_block.number);

        let actual_block = fork_source
            .get_block_by_hash(input_block_hash, true)
            .expect("failed fetching cached block by hash")
            .expect("no block");

        assert_eq!(input_block_hash, actual_block.hash);
        assert_eq!(U64::from(input_block_number), actual_block.number);
    }

    #[test]
    fn test_get_block_by_hash_minimal_is_cached() {
        let input_block_hash = H256::repeat_byte(0x01);
        let input_block_number = 8;

        let mock_server = testing::MockServer::run();
        mock_server.expect(
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 0,
                "method": "eth_getBlockByHash",
                "params": [
                    format!("{input_block_hash:#x}"),
                    false
                ],
            }),
            testing::BlockResponseBuilder::new()
                .set_hash(input_block_hash)
                .set_number(input_block_number)
                .build(),
        );

        let fork_source = HttpForkSource::new(mock_server.url(), CacheConfig::Memory);

        let actual_block = fork_source
            .get_block_by_hash(input_block_hash, false)
            .expect("failed fetching block by hash")
            .expect("no block");

        assert_eq!(input_block_hash, actual_block.hash);
        assert_eq!(U64::from(input_block_number), actual_block.number);

        let actual_block = fork_source
            .get_block_by_hash(input_block_hash, false)
            .expect("failed fetching cached block by hash")
            .expect("no block");

        assert_eq!(input_block_hash, actual_block.hash);
        assert_eq!(U64::from(input_block_number), actual_block.number);
    }

    #[test]
    fn test_get_block_by_number_full_is_cached() {
        let input_block_hash = H256::repeat_byte(0x01);
        let input_block_number = 8;

        let mock_server = testing::MockServer::run();
        mock_server.expect(
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 0,
                "method": "eth_getBlockByNumber",
                "params": [
                    format!("{input_block_number:#x}"),
                    true
                ],
            }),
            testing::BlockResponseBuilder::new()
                .set_hash(input_block_hash)
                .set_number(input_block_number)
                .build(),
        );

        let fork_source = HttpForkSource::new(mock_server.url(), CacheConfig::Memory);

        let actual_block = fork_source
            .get_block_by_number(
                zksync_types::api::BlockNumber::Number(U64::from(input_block_number)),
                true,
            )
            .expect("failed fetching block by number")
            .expect("no block");

        assert_eq!(input_block_hash, actual_block.hash);
        assert_eq!(U64::from(input_block_number), actual_block.number);

        let actual_block = fork_source
            .get_block_by_number(
                zksync_types::api::BlockNumber::Number(U64::from(input_block_number)),
                true,
            )
            .expect("failed fetching cached block by number")
            .expect("no block");

        assert_eq!(input_block_hash, actual_block.hash);
        assert_eq!(U64::from(input_block_number), actual_block.number);
    }

    #[test]
    fn test_get_block_by_number_minimal_is_cached() {
        let input_block_hash = H256::repeat_byte(0x01);
        let input_block_number = 8;

        let mock_server = testing::MockServer::run();
        mock_server.expect(
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 0,
                "method": "eth_getBlockByNumber",
                "params": [
                    format!("{input_block_number:#x}"),
                    false
                ],
            }),
            testing::BlockResponseBuilder::new()
                .set_hash(input_block_hash)
                .set_number(input_block_number)
                .build(),
        );

        let fork_source = HttpForkSource::new(mock_server.url(), CacheConfig::Memory);

        let actual_block = fork_source
            .get_block_by_number(BlockNumber::Number(U64::from(input_block_number)), false)
            .expect("failed fetching block by number")
            .expect("no block");

        assert_eq!(input_block_hash, actual_block.hash);
        assert_eq!(U64::from(input_block_number), actual_block.number);

        let actual_block = fork_source
            .get_block_by_number(BlockNumber::Number(U64::from(input_block_number)), false)
            .expect("failed fetching cached block by number")
            .expect("no block");

        assert_eq!(input_block_hash, actual_block.hash);
        assert_eq!(U64::from(input_block_number), actual_block.number);
    }

    #[test]
    fn test_get_raw_block_transactions_is_cached() {
        let input_block_number = 8u32;

        let mock_server = testing::MockServer::run();
        mock_server.expect(
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 0,
                "method": "zks_getRawBlockTransactions",
                "params": [
                    input_block_number,
                ],
            }),
            testing::RawTransactionsResponseBuilder::new()
                .add(1)
                .build(),
        );

        let fork_source = HttpForkSource::new(mock_server.url(), CacheConfig::Memory);

        let actual_raw_transactions = fork_source
            .get_raw_block_transactions(MiniblockNumber(input_block_number))
            .expect("failed fetching block raw transactions");
        assert_eq!(1, actual_raw_transactions.len());

        let actual_raw_transactions = fork_source
            .get_raw_block_transactions(MiniblockNumber(input_block_number))
            .expect("failed fetching cached block raw transactions");
        assert_eq!(1, actual_raw_transactions.len());
    }

    #[test]
    fn test_get_transactions_is_cached() {
        let input_tx_hash = H256::repeat_byte(0x01);

        let mock_server = testing::MockServer::run();
        mock_server.expect(
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 0,
                "method": "eth_getTransactionByHash",
                "params": [
                    input_tx_hash,
                ],
            }),
            testing::TransactionResponseBuilder::new()
                .set_hash(input_tx_hash)
                .build(),
        );

        let fork_source = HttpForkSource::new(mock_server.url(), CacheConfig::Memory);

        let actual_transaction = fork_source
            .get_transaction_by_hash(input_tx_hash)
            .expect("failed fetching transaction")
            .expect("no transaction");
        assert_eq!(input_tx_hash, actual_transaction.hash);

        let actual_transaction = fork_source
            .get_transaction_by_hash(input_tx_hash)
            .expect("failed fetching cached transaction")
            .expect("no transaction");
        assert_eq!(input_tx_hash, actual_transaction.hash);
    }
}