-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathvector.rs
720 lines (622 loc) · 23.4 KB
/
vector.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
//! Fixed test vectors for the mempool.
use std::{collections::HashSet, sync::Arc};
use color_eyre::Report;
use tokio::time;
use tower::{ServiceBuilder, ServiceExt};
use zebra_chain::{block::Block, parameters::Network, serialization::ZcashDeserializeInto};
use zebra_consensus::transaction as tx;
use zebra_state::Config as StateConfig;
use zebra_test::mock_service::{MockService, PanicAssertion};
use crate::components::{
mempool::{self, storage::tests::unmined_transactions_in_blocks, *},
sync::RecentSyncLengths,
};
/// A [`MockService`] representing the network service.
type MockPeerSet = MockService<zn::Request, zn::Response, PanicAssertion>;
/// The unmocked Zebra state service's type.
type StateService = Buffer<BoxService<zs::Request, zs::Response, zs::BoxError>, zs::Request>;
/// A [`MockService`] representing the Zebra transaction verifier service.
type MockTxVerifier = MockService<tx::Request, tx::Response, PanicAssertion, TransactionError>;
#[tokio::test]
async fn mempool_service_basic() -> Result<(), Report> {
// Test multiple times to catch intermittent bugs since eviction is randomized
for _ in 0..10 {
mempool_service_basic_single().await?;
}
Ok(())
}
async fn mempool_service_basic_single() -> Result<(), Report> {
// Using the mainnet for now
let network = Network::Mainnet;
// get the genesis block transactions from the Zcash blockchain.
let mut unmined_transactions = unmined_transactions_in_blocks(..=10, network);
let genesis_transaction = unmined_transactions
.next()
.expect("Missing genesis transaction");
let last_transaction = unmined_transactions.next_back().unwrap();
let more_transactions = unmined_transactions.collect::<Vec<_>>();
// Use as cost limit the costs of all transactions that will be
// inserted except one (the genesis block transaction).
let cost_limit = more_transactions.iter().map(|tx| tx.cost()).sum();
let (mut service, _peer_set, _state_service, _tx_verifier, mut recent_syncs) =
setup(network, cost_limit).await;
// Enable the mempool
let _ = service.enable(&mut recent_syncs).await;
// Insert the genesis block coinbase transaction into the mempool storage.
let mut inserted_ids = HashSet::new();
service.storage().insert(genesis_transaction.clone())?;
inserted_ids.insert(genesis_transaction.transaction.id);
// Test `Request::TransactionIds`
let response = service
.ready()
.await
.unwrap()
.call(Request::TransactionIds)
.await
.unwrap();
let genesis_transaction_ids = match response {
Response::TransactionIds(ids) => ids,
_ => unreachable!("will never happen in this test"),
};
// Test `Request::TransactionsById`
let genesis_transactions_hash_set = genesis_transaction_ids
.iter()
.copied()
.collect::<HashSet<_>>();
let response = service
.ready()
.await
.unwrap()
.call(Request::TransactionsById(
genesis_transactions_hash_set.clone(),
))
.await
.unwrap();
let transactions = match response {
Response::Transactions(transactions) => transactions,
_ => unreachable!("will never happen in this test"),
};
// Make sure the transaction from the blockchain test vector is the same as the
// response of `Request::TransactionsById`
assert_eq!(genesis_transaction.transaction, transactions[0]);
// Insert more transactions into the mempool storage.
// This will cause the genesis transaction to be moved into rejected.
// Skip the last (will be used later)
for tx in more_transactions {
inserted_ids.insert(tx.transaction.id);
// Error must be ignored because a insert can trigger an eviction and
// an error is returned if the transaction being inserted in chosen.
let _ = service.storage().insert(tx.clone());
}
// Test `Request::RejectedTransactionIds`
let response = service
.ready()
.await
.unwrap()
.call(Request::RejectedTransactionIds(
genesis_transactions_hash_set,
))
.await
.unwrap();
let rejected_ids = match response {
Response::RejectedTransactionIds(ids) => ids,
_ => unreachable!("will never happen in this test"),
};
assert!(rejected_ids.is_subset(&inserted_ids));
// Test `Request::Queue`
// Use the ID of the last transaction in the list
let response = service
.ready()
.await
.unwrap()
.call(Request::Queue(vec![last_transaction.transaction.id.into()]))
.await
.unwrap();
let queued_responses = match response {
Response::Queued(queue_responses) => queue_responses,
_ => unreachable!("will never happen in this test"),
};
assert_eq!(queued_responses.len(), 1);
assert!(queued_responses[0].is_ok());
assert_eq!(service.tx_downloads().in_flight(), 1);
Ok(())
}
#[tokio::test]
async fn mempool_queue() -> Result<(), Report> {
// Test multiple times to catch intermittent bugs since eviction is randomized
for _ in 0..10 {
mempool_queue_single().await?;
}
Ok(())
}
async fn mempool_queue_single() -> Result<(), Report> {
// Using the mainnet for now
let network = Network::Mainnet;
// Get transactions to use in the test
let unmined_transactions = unmined_transactions_in_blocks(..=10, network);
let mut transactions = unmined_transactions.collect::<Vec<_>>();
// Split unmined_transactions into:
// [transactions..., new_tx]
// A transaction not in the mempool that will be Queued
let new_tx = transactions.pop().unwrap();
// Use as cost limit the costs of all transactions that will be
// inserted except the last.
let cost_limit = transactions
.iter()
.take(transactions.len() - 1)
.map(|tx| tx.cost())
.sum();
let (mut service, _peer_set, _state_service, _tx_verifier, mut recent_syncs) =
setup(network, cost_limit).await;
// Enable the mempool
let _ = service.enable(&mut recent_syncs).await;
// Insert [transactions...] into the mempool storage.
// This will cause the at least one transaction to be rejected, since
// the cost limit is the sum of all costs except of the last transaction.
for tx in transactions.iter() {
// Error must be ignored because a insert can trigger an eviction and
// an error is returned if the transaction being inserted in chosen.
let _ = service.storage().insert(tx.clone());
}
// Test `Request::Queue` for a new transaction
let response = service
.ready()
.await
.unwrap()
.call(Request::Queue(vec![new_tx.transaction.id.into()]))
.await
.unwrap();
let queued_responses = match response {
Response::Queued(queue_responses) => queue_responses,
_ => unreachable!("will never happen in this test"),
};
assert_eq!(queued_responses.len(), 1);
assert!(queued_responses[0].is_ok());
// Test `Request::Queue` with all previously inserted transactions.
// They should all be rejected; either because they are already in the mempool,
// or because they are in the recently evicted list.
let response = service
.ready()
.await
.unwrap()
.call(Request::Queue(
transactions
.iter()
.map(|tx| tx.transaction.id.into())
.collect(),
))
.await
.unwrap();
let queued_responses = match response {
Response::Queued(queue_responses) => queue_responses,
_ => unreachable!("will never happen in this test"),
};
assert_eq!(queued_responses.len(), transactions.len());
// Check if the responses are consistent
let mut in_mempool_count = 0;
let mut evicted_count = 0;
for response in queued_responses {
match response {
Ok(_) => panic!("all transactions should have been rejected"),
Err(e) => match e {
MempoolError::StorageEffectsChain(
SameEffectsChainRejectionError::RandomlyEvicted,
) => evicted_count += 1,
MempoolError::InMempool => in_mempool_count += 1,
_ => panic!("transaction should not be rejected with reason {:?}", e),
},
}
}
assert_eq!(in_mempool_count, transactions.len() - 1);
assert_eq!(evicted_count, 1);
Ok(())
}
#[tokio::test]
async fn mempool_service_disabled() -> Result<(), Report> {
// Using the mainnet for now
let network = Network::Mainnet;
let (mut service, _peer_set, _state_service, _tx_verifier, mut recent_syncs) =
setup(network, u64::MAX).await;
// get the genesis block transactions from the Zcash blockchain.
let mut unmined_transactions = unmined_transactions_in_blocks(..=10, network);
let genesis_transaction = unmined_transactions
.next()
.expect("Missing genesis transaction");
let more_transactions = unmined_transactions;
// Test if mempool is disabled (it should start disabled)
assert!(!service.is_enabled());
// Enable the mempool
let _ = service.enable(&mut recent_syncs).await;
assert!(service.is_enabled());
// Insert the genesis block coinbase transaction into the mempool storage.
service.storage().insert(genesis_transaction.clone())?;
// Test if the mempool answers correctly (i.e. is enabled)
let response = service
.ready()
.await
.unwrap()
.call(Request::TransactionIds)
.await
.unwrap();
let _genesis_transaction_ids = match response {
Response::TransactionIds(ids) => ids,
_ => unreachable!("will never happen in this test"),
};
// Queue a transaction for download
// Use the ID of the last transaction in the list
let txid = more_transactions.last().unwrap().transaction.id;
let response = service
.ready()
.await
.unwrap()
.call(Request::Queue(vec![txid.into()]))
.await
.unwrap();
let queued_responses = match response {
Response::Queued(queue_responses) => queue_responses,
_ => unreachable!("will never happen in this test"),
};
assert_eq!(queued_responses.len(), 1);
assert!(queued_responses[0].is_ok());
assert_eq!(service.tx_downloads().in_flight(), 1);
// Disable the mempool
let _ = service.disable(&mut recent_syncs).await;
// Test if mempool is disabled again
assert!(!service.is_enabled());
// Test if the mempool returns no transactions when disabled
let response = service
.ready()
.await
.unwrap()
.call(Request::TransactionIds)
.await
.unwrap();
match response {
Response::TransactionIds(ids) => {
assert_eq!(
ids.len(),
0,
"mempool should return no transactions when disabled"
)
}
_ => unreachable!("will never happen in this test"),
};
// Test if the mempool returns to Queue requests correctly when disabled
let response = service
.ready()
.await
.unwrap()
.call(Request::Queue(vec![txid.into()]))
.await
.unwrap();
let queued_responses = match response {
Response::Queued(queue_responses) => queue_responses,
_ => unreachable!("will never happen in this test"),
};
assert_eq!(queued_responses.len(), 1);
assert_eq!(queued_responses[0], Err(MempoolError::Disabled));
Ok(())
}
#[tokio::test]
async fn mempool_cancel_mined() -> Result<(), Report> {
let block1: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_1_BYTES
.zcash_deserialize_into()
.unwrap();
let block2: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_2_BYTES
.zcash_deserialize_into()
.unwrap();
// Using the mainnet for now
let network = Network::Mainnet;
let (mut mempool, _peer_set, mut state_service, _tx_verifier, mut recent_syncs) =
setup(network, u64::MAX).await;
time::pause();
// Enable the mempool
let _ = mempool.enable(&mut recent_syncs).await;
assert!(mempool.is_enabled());
// Push the genesis block to the state
let genesis_block: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES
.zcash_deserialize_into()
.unwrap();
state_service
.ready()
.await
.unwrap()
.call(zebra_state::Request::CommitFinalizedBlock(
genesis_block.clone().into(),
))
.await
.unwrap();
// Query the mempool to make it poll chain_tip_change
mempool.dummy_call().await;
// Push block 1 to the state
state_service
.ready()
.await
.unwrap()
.call(zebra_state::Request::CommitFinalizedBlock(
block1.clone().into(),
))
.await
.unwrap();
// Query the mempool to make it poll chain_tip_change
mempool.dummy_call().await;
// Queue transaction from block 2 for download.
// It can't be queued before because block 1 triggers a network upgrade,
// which cancels all downloads.
let txid = block2.transactions[0].unmined_id();
let response = mempool
.ready()
.await
.unwrap()
.call(Request::Queue(vec![txid.into()]))
.await
.unwrap();
let queued_responses = match response {
Response::Queued(queue_responses) => queue_responses,
_ => unreachable!("will never happen in this test"),
};
assert_eq!(queued_responses.len(), 1);
assert!(queued_responses[0].is_ok());
assert_eq!(mempool.tx_downloads().in_flight(), 1);
// Push block 2 to the state
state_service
.oneshot(zebra_state::Request::CommitFinalizedBlock(
block2.clone().into(),
))
.await
.unwrap();
// This is done twice because after the first query the cancellation
// is picked up by select!, and after the second the mempool gets the
// result and the download future is removed.
for _ in 0..2 {
// Query the mempool just to poll it and make it cancel the download.
mempool.dummy_call().await;
// Sleep to avoid starvation and make sure the cancellation is picked up.
time::sleep(time::Duration::from_millis(100)).await;
}
// Check if download was cancelled.
assert_eq!(mempool.tx_downloads().in_flight(), 0);
Ok(())
}
#[tokio::test]
async fn mempool_cancel_downloads_after_network_upgrade() -> Result<(), Report> {
let block1: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_1_BYTES
.zcash_deserialize_into()
.unwrap();
let block2: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_2_BYTES
.zcash_deserialize_into()
.unwrap();
// Using the mainnet for now
let network = Network::Mainnet;
let (mut mempool, _peer_set, mut state_service, _tx_verifier, mut recent_syncs) =
setup(network, u64::MAX).await;
// Enable the mempool
let _ = mempool.enable(&mut recent_syncs).await;
assert!(mempool.is_enabled());
// Push the genesis block to the state
let genesis_block: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES
.zcash_deserialize_into()
.unwrap();
state_service
.ready()
.await
.unwrap()
.call(zebra_state::Request::CommitFinalizedBlock(
genesis_block.clone().into(),
))
.await
.unwrap();
// Queue transaction from block 2 for download
let txid = block2.transactions[0].unmined_id();
let response = mempool
.ready()
.await
.unwrap()
.call(Request::Queue(vec![txid.into()]))
.await
.unwrap();
let queued_responses = match response {
Response::Queued(queue_responses) => queue_responses,
_ => unreachable!("will never happen in this test"),
};
assert_eq!(queued_responses.len(), 1);
assert!(queued_responses[0].is_ok());
assert_eq!(mempool.tx_downloads().in_flight(), 1);
// Query the mempool to make it poll chain_tip_change
mempool.dummy_call().await;
// Push block 1 to the state. This is considered a network upgrade,
// and thus must cancel all pending transaction downloads.
state_service
.ready()
.await
.unwrap()
.call(zebra_state::Request::CommitFinalizedBlock(
block1.clone().into(),
))
.await
.unwrap();
// Query the mempool to make it poll chain_tip_change
mempool.dummy_call().await;
// Check if download was cancelled.
assert_eq!(mempool.tx_downloads().in_flight(), 0);
Ok(())
}
/// Check if a transaction that fails verification is rejected by the mempool.
#[tokio::test]
async fn mempool_failed_verification_is_rejected() -> Result<(), Report> {
// Using the mainnet for now
let network = Network::Mainnet;
let (mut mempool, _peer_set, mut state_service, mut tx_verifier, mut recent_syncs) =
setup(network, u64::MAX).await;
// Get transactions to use in the test
let mut unmined_transactions = unmined_transactions_in_blocks(1..=2, network);
let rejected_tx = unmined_transactions.next().unwrap().clone();
time::pause();
// Enable the mempool
let _ = mempool.enable(&mut recent_syncs).await;
// Push the genesis block to the state, since downloader needs a valid tip.
let genesis_block: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES
.zcash_deserialize_into()
.unwrap();
state_service
.ready()
.await
.unwrap()
.call(zebra_state::Request::CommitFinalizedBlock(
genesis_block.clone().into(),
))
.await
.unwrap();
// Queue first transaction for verification
// (queue the transaction itself to avoid a download).
let request = mempool
.ready()
.await
.unwrap()
.call(Request::Queue(vec![rejected_tx.transaction.clone().into()]));
// Make the mock verifier return that the transaction is invalid.
let verification = tx_verifier.expect_request_that(|_| true).map(|responder| {
responder.respond(Err(TransactionError::BadBalance));
});
let (response, _) = futures::join!(request, verification);
let queued_responses = match response.unwrap() {
Response::Queued(queue_responses) => queue_responses,
_ => unreachable!("will never happen in this test"),
};
// Check that the request was enqueued successfully.
assert_eq!(queued_responses.len(), 1);
assert!(queued_responses[0].is_ok());
for _ in 0..2 {
// Query the mempool just to poll it and make get the downloader/verifier result.
mempool.dummy_call().await;
// Sleep to avoid starvation and make sure the verification failure is picked up.
time::sleep(time::Duration::from_millis(100)).await;
}
// Try to queue the same transaction by its ID and check if it's correctly
// rejected.
let response = mempool
.ready()
.await
.unwrap()
.call(Request::Queue(vec![rejected_tx.transaction.id.into()]))
.await
.unwrap();
let queued_responses = match response {
Response::Queued(queue_responses) => queue_responses,
_ => unreachable!("will never happen in this test"),
};
assert_eq!(queued_responses.len(), 1);
assert!(matches!(
queued_responses[0],
Err(MempoolError::StorageExactTip(
ExactTipRejectionError::FailedVerification(_)
))
));
Ok(())
}
/// Check if a transaction that fails download is _not_ rejected.
#[tokio::test]
async fn mempool_failed_download_is_not_rejected() -> Result<(), Report> {
// Using the mainnet for now
let network = Network::Mainnet;
let (mut mempool, mut peer_set, mut state_service, _tx_verifier, mut recent_syncs) =
setup(network, u64::MAX).await;
// Get transactions to use in the test
let mut unmined_transactions = unmined_transactions_in_blocks(1..=2, network);
let rejected_valid_tx = unmined_transactions.next().unwrap().clone();
time::pause();
// Enable the mempool
let _ = mempool.enable(&mut recent_syncs).await;
// Push the genesis block to the state, since downloader needs a valid tip.
let genesis_block: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES
.zcash_deserialize_into()
.unwrap();
state_service
.ready()
.await
.unwrap()
.call(zebra_state::Request::CommitFinalizedBlock(
genesis_block.clone().into(),
))
.await
.unwrap();
// Queue second transaction for download and verification.
let request = mempool
.ready()
.await
.unwrap()
.call(Request::Queue(vec![rejected_valid_tx
.transaction
.id
.into()]));
// Make the mock peer set return that the download failed.
let verification = peer_set
.expect_request_that(|r| matches!(r, zn::Request::TransactionsById(_)))
.map(|responder| {
responder.respond(zn::Response::Transactions(vec![]));
});
let (response, _) = futures::join!(request, verification);
let queued_responses = match response.unwrap() {
Response::Queued(queue_responses) => queue_responses,
_ => unreachable!("will never happen in this test"),
};
// Check that the request was enqueued successfully.
assert_eq!(queued_responses.len(), 1);
assert!(queued_responses[0].is_ok());
for _ in 0..2 {
// Query the mempool just to poll it and make get the downloader/verifier result.
mempool.dummy_call().await;
// Sleep to avoid starvation and make sure the download failure is picked up.
time::sleep(time::Duration::from_millis(100)).await;
}
// Try to queue the same transaction by its ID and check if it's not being
// rejected.
let response = mempool
.ready()
.await
.unwrap()
.call(Request::Queue(vec![rejected_valid_tx
.transaction
.id
.into()]))
.await
.unwrap();
let queued_responses = match response {
Response::Queued(queue_responses) => queue_responses,
_ => unreachable!("will never happen in this test"),
};
assert_eq!(queued_responses.len(), 1);
assert!(queued_responses[0].is_ok());
Ok(())
}
/// Create a new [`Mempool`] instance using mocked services.
async fn setup(
network: Network,
tx_cost_limit: u64,
) -> (
Mempool,
MockPeerSet,
StateService,
MockTxVerifier,
RecentSyncLengths,
) {
let peer_set = MockService::build().for_unit_tests();
let state_config = StateConfig::ephemeral();
let (state, latest_chain_tip, chain_tip_change) = zebra_state::init(state_config, network);
let state_service = ServiceBuilder::new().buffer(1).service(state);
let tx_verifier = MockService::build().for_unit_tests();
let (sync_status, recent_syncs) = SyncStatus::new();
let (mempool, _mempool_transaction_receiver) = Mempool::new(
&mempool::Config {
tx_cost_limit,
..Default::default()
},
Buffer::new(BoxService::new(peer_set.clone()), 1),
state_service.clone(),
Buffer::new(BoxService::new(tx_verifier.clone()), 1),
sync_status,
latest_chain_tip,
chain_tip_change,
);
(mempool, peer_set, state_service, tx_verifier, recent_syncs)
}