-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathbasic.rs
More file actions
1910 lines (1698 loc) · 69.5 KB
/
Copy pathbasic.rs
File metadata and controls
1910 lines (1698 loc) · 69.5 KB
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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2024 RBB S.r.l
// opensource@mintlayer.org
// SPDX-License-Identifier: MIT
// Licensed under the MIT License;
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://github.com/mintlayer/mintlayer-core/blob/master/LICENSE
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use chainstate_test_framework::helpers::split_utxo;
use mempool_types::tx_origin::LocalTxOrigin;
use test_utils::BasicTestTimeGetter;
use crate::pool::tx_pool::store::{StoreHashSet, TxMempoolEntryWithAncestors};
use super::*;
#[test]
fn dummy_size() {
log::debug!("1, 1: {}", estimate_tx_size(1, 1));
log::debug!("1, 2: {}", estimate_tx_size(1, 2));
log::debug!("1, 400: {}", estimate_tx_size(1, 400));
}
#[rstest]
#[trace]
#[case(Seed::from_entropy())]
#[test]
fn real_size(#[case] seed: Seed) -> anyhow::Result<()> {
let mut rng = make_seedable_rng(seed);
let tf = TestFramework::builder(&mut rng).build();
let genesis = tf.genesis();
let mut tx_builder = TransactionBuilder::new().add_input(
TxInput::from_utxo(OutPointSourceId::BlockReward(genesis.get_id().into()), 0),
empty_witness(&mut rng),
);
for _ in 0..400 {
tx_builder = tx_builder.add_output(TxOutput::Transfer(
OutputValue::Coin(Amount::from_atoms(1)),
anyonecanspend_address(),
));
}
let tx = tx_builder.build();
log::debug!("real size of tx {}", tx.encoded_size());
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn add_single_tx() -> anyhow::Result<()> {
let mut mempool = setup();
let outpoint_source_id = mempool.chain_config.genesis_block_id().into();
let flags = 0;
let input = TxInput::from_utxo(outpoint_source_id, 0);
let relay_fee: Fee = get_relay_fee_from_tx_size(TX_SPEND_INPUT_SIZE).into();
let tx = tx_spend_input(
&mempool,
input,
InputWitness::NoSignature(Some(DUMMY_WITNESS_MSG.to_vec())),
relay_fee,
flags,
)
.await?;
let tx_clone = tx.clone();
let tx_id = tx.transaction().get_id();
mempool.add_transaction_test(tx)?.assert_in_mempool();
assert!(mempool.contains_transaction(&tx_id));
let all_txs = mempool.get_all_by_descendant_score();
assert_eq!(all_txs, vec![tx_clone]);
mempool.store.remove_tx(&tx_id, MempoolRemovalReason::Block);
assert!(!mempool.contains_transaction(&tx_id));
let all_txs = mempool.get_all_by_descendant_score();
assert_eq!(all_txs, Vec::<SignedTransaction>::new());
mempool.store.assert_valid();
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn add_tx_with_fee_rate_below_minimum() {
let min_relay_fee_rate = FeeRate::from_amount_per_kb(Amount::from_atoms(123));
let mut mempool = setup_with_min_tx_relay_fee_rate(min_relay_fee_rate);
async fn make_tx(
tx_pool: &TxPool<StoreMemoryUsageEstimator>,
relay_fee: Fee,
) -> SignedTransaction {
let outpoint_source_id = tx_pool.chain_config.genesis_block_id().into();
let flags = 0;
let input = TxInput::from_utxo(outpoint_source_id, 0);
tx_spend_input(
tx_pool,
input,
InputWitness::NoSignature(Some(DUMMY_WITNESS_MSG.to_vec())),
relay_fee,
flags,
)
.await
.unwrap()
}
let estimated_tx_size = make_tx(&mempool, Amount::ZERO.into()).await.encoded_size();
let min_relay_fee = min_relay_fee_rate.compute_fee(estimated_tx_size).unwrap();
// Tx1's fee is below the minimum, so it must be rejected.
let tx1_relay_fee = (min_relay_fee - Amount::from_atoms(1).into()).unwrap();
let tx1 = make_tx(&mempool, tx1_relay_fee).await;
let err = mempool.add_transaction_test(tx1).unwrap_err();
assert!(matches!(
err,
Error::Policy(MempoolPolicyError::InsufficientFeesToRelay {
tx_fee: _,
min_relay_fee: _
})
));
// Tx2's fee is exactly the minimum, so it must be accepted.
let tx2 = make_tx(&mempool, min_relay_fee).await;
let tx_status = mempool.add_transaction_test(tx2).unwrap();
assert_eq!(tx_status, TxStatus::InMempool);
}
#[rstest]
#[trace]
#[case(Seed::from_entropy())]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn txs_sorted(#[case] seed: Seed) -> anyhow::Result<()> {
let mut rng = make_seedable_rng(seed);
let tf = TestFramework::builder(&mut rng).build();
let genesis = tf.genesis();
let mut mempool = setup_with_chainstate(tf.chainstate());
let target_txs = 10;
let mut tx_builder = TransactionBuilder::new().add_input(
TxInput::from_utxo(OutPointSourceId::BlockReward(genesis.get_id().into()), 0),
empty_witness(&mut rng),
);
for i in 0..target_txs {
tx_builder = tx_builder.add_output(TxOutput::Transfer(
OutputValue::Coin(Amount::from_atoms(1000 * (target_txs + 1 - i))),
Destination::AnyoneCanSpend,
))
}
let initial_tx = tx_builder.build();
let initial_tx_id = initial_tx.transaction().get_id();
mempool.add_transaction_test(initial_tx)?.assert_in_mempool();
for i in 0..target_txs {
let tx = TransactionBuilder::new()
.add_input(
TxInput::from_utxo(OutPointSourceId::Transaction(initial_tx_id), i as u32),
empty_witness(&mut rng),
)
.add_output(TxOutput::Transfer(
OutputValue::Coin(Amount::from_atoms(0)),
Destination::AnyoneCanSpend,
))
.build();
mempool.add_transaction_test(tx.clone())?.assert_in_mempool();
}
let mut fees = Vec::new();
for tx in mempool.get_all_by_descendant_score() {
fees.push(try_get_fee(&mempool, &tx).await)
}
let mut fees_sorted = fees.clone();
fees_sorted.sort();
assert_eq!(fees, fees_sorted);
mempool.store.assert_valid();
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn tx_no_inputs() {
let mut mempool = setup();
let tx = TransactionBuilder::new().build();
let res = mempool.add_transaction_test(tx);
assert_eq!(
res,
Err(MempoolPolicyError::NoInputs.into()),
"Should have failed with no inputs, got {res:?} instead"
);
mempool.store.assert_valid();
}
#[rstest]
#[trace]
#[case(Seed::from_entropy())]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn tx_no_outputs(#[case] seed: Seed) -> anyhow::Result<()> {
let mut rng = make_seedable_rng(seed);
let tf = TestFramework::builder(&mut rng).build();
let genesis = tf.genesis();
let tx = TransactionBuilder::new()
.add_input(
TxInput::from_utxo(OutPointSourceId::BlockReward(genesis.get_id().into()), 0),
empty_witness(&mut rng),
)
.build();
let mut mempool = setup_with_chainstate(tf.chainstate());
assert_eq!(
mempool.add_transaction_test(tx),
Err(MempoolPolicyError::NoOutputs.into())
);
mempool.store.assert_valid();
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn tx_duplicate_inputs() -> anyhow::Result<()> {
let mut mempool = setup();
let outpoint_source_id = OutPointSourceId::from(mempool.chain_config.genesis_block_id());
let input = TxInput::from_utxo(outpoint_source_id.clone(), 0);
let witness = b"attempted_double_spend".to_vec();
let duplicate_input = TxInput::from_utxo(outpoint_source_id, 0);
let flags = 0;
let outputs = tx_spend_input(
&mempool,
input.clone(),
InputWitness::NoSignature(Some(DUMMY_WITNESS_MSG.to_vec())),
None,
flags,
)
.await?
.transaction()
.outputs()
.to_owned();
let inputs = vec![input, duplicate_input];
let tx = SignedTransaction::new(
Transaction::new(flags, inputs, outputs)?,
vec![
InputWitness::NoSignature(Some(DUMMY_WITNESS_MSG.to_vec())),
InputWitness::NoSignature(Some(witness)),
],
)
.expect("invalid witness count");
assert!(matches!(
mempool.add_transaction_test(tx),
Err(Error::Validity(_)),
));
mempool.store.assert_valid();
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn tx_already_in_mempool() -> anyhow::Result<()> {
let mut mempool = setup();
let outpoint_source_id = OutPointSourceId::from(mempool.chain_config.genesis_block_id());
let input = TxInput::from_utxo(outpoint_source_id, 0);
let flags = 0;
let tx = tx_spend_input(
&mempool,
input,
InputWitness::NoSignature(Some(DUMMY_WITNESS_MSG.to_vec())),
None,
flags,
)
.await?;
mempool.add_transaction_test(tx.clone())?.assert_in_mempool();
assert_eq!(
mempool.add_transaction_test(tx),
Ok(TxStatus::InMempoolDuplicate),
);
mempool.store.assert_valid();
Ok(())
}
#[rstest]
#[trace]
#[case(Seed::from_entropy())]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn outpoint_not_found(#[case] seed: Seed) -> anyhow::Result<()> {
let mut rng = make_seedable_rng(seed);
let tf = TestFramework::builder(&mut rng).build();
let chainstate = tf.chainstate();
let mut mempool = setup_with_chainstate(chainstate);
let outpoint_source_id = OutPointSourceId::from(mempool.chain_config.genesis_block_id());
let good_input = TxInput::from_utxo(outpoint_source_id.clone(), 0);
let flags = 0;
let outputs = tx_spend_input(
&mempool,
good_input,
InputWitness::NoSignature(Some(DUMMY_WITNESS_MSG.to_vec())),
None,
flags,
)
.await?
.transaction()
.outputs()
.to_owned();
let bad_outpoint_index = 1;
let bad_input = TxInput::from_utxo(outpoint_source_id, bad_outpoint_index);
let inputs = vec![bad_input];
let tx = SignedTransaction::new(
Transaction::new(flags, inputs, outputs)?,
vec![InputWitness::NoSignature(Some(DUMMY_WITNESS_MSG.to_vec()))],
)
.expect("invalid witness count");
let error = match mempool.add_transaction_test(tx) {
Err(Error::Validity(TxValidationError::TxValidation(e))) => e,
res => panic!("Unexpected result {res:?}"),
};
assert_eq!(OrphanType::from_error(error), Ok(OrphanType::MissingUtxo));
mempool.store.assert_valid();
Ok(())
}
// Create a tx bigger than `ChainConfig::max_tx_size_for_mempool`.
#[rstest]
#[trace]
#[case(Seed::from_entropy())]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn tx_bigger_than_block_size(#[case] seed: Seed) -> anyhow::Result<()> {
let mut rng = make_seedable_rng(seed);
let tf = TestFramework::builder(&mut rng).build();
let genesis = tf.genesis();
let output = TxOutput::Transfer(
OutputValue::Coin(Amount::from_atoms(100)),
Destination::AnyoneCanSpend,
);
let output_size = output.encoded_size();
let outputs_count =
tf.chainstate.get_chain_config().max_tx_size_for_mempool() / output_size + 1;
let tx = TransactionBuilder::new()
.add_input(
TxInput::from_utxo(OutPointSourceId::BlockReward(genesis.get_id().into()), 0),
empty_witness(&mut rng),
)
.add_output_n_times(outputs_count, &output)
.build();
let mut mempool = setup_with_chainstate(tf.chainstate());
assert_eq!(
mempool.add_transaction_test(tx),
Err(MempoolPolicyError::TxSizeExceedsMaxBlockSize.into())
);
mempool.store.assert_valid();
Ok(())
}
// Create a tx bigger than the cluster size specified in the mempool config.
#[rstest]
#[trace]
#[case(Seed::from_entropy())]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn tx_bigger_than_cluster_size(#[case] seed: Seed) -> anyhow::Result<()> {
let mut rng = make_seedable_rng(seed);
let tf = TestFramework::builder(&mut rng).build();
let genesis = tf.genesis();
let max_cluster_size = rng.random_range(10_000..500_000);
let output = TxOutput::Transfer(
OutputValue::Coin(Amount::from_atoms(100)),
Destination::AnyoneCanSpend,
);
let output_size = output.encoded_size();
let outputs_count = max_cluster_size / output_size + 1;
let tx = TransactionBuilder::new()
.add_input(
TxInput::from_utxo(OutPointSourceId::BlockReward(genesis.get_id().into()), 0),
empty_witness(&mut rng),
)
.add_output_n_times(outputs_count, &output)
.build();
let tx_size = tx.encoded_size();
let mempool_config = MempoolConfig {
min_tx_relay_fee_rate: TEST_MIN_TX_RELAY_FEE_RATE.into(),
max_cluster_size_bytes: max_cluster_size.into(),
max_cluster_tx_count: Default::default(),
};
let mut mempool =
setup_with_chainstate_generic(tf.chainstate(), mempool_config, Default::default());
assert_eq!(
mempool.add_transaction_test(tx),
Err(MempoolPolicyError::TxSizeExceedsMaxClusterSize {
tx_size,
limit: max_cluster_size
}
.into())
);
mempool.store.assert_valid();
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn tx_mempool_entry() -> anyhow::Result<()> {
use common::primitives::time;
let mut mempool = setup();
// Input different flag values just to make the hashes of these dummy transactions
// different
let txs = (1..=6)
.map(|i| {
SignedTransaction::new(
Transaction::new(i, vec![], vec![]).unwrap_or_else(|_| panic!("tx {i}")),
vec![],
)
.expect("invalid witness count")
})
.collect::<Vec<_>>();
let fee = Amount::from_atoms(1).into();
// Generation 1
let tx1_parents = StoreHashSet::default();
let entry_1_ancestors = BTreeSet::default();
let entry1 = TxMempoolEntry::new_from_data(
txs.first().unwrap().clone(),
fee,
tx1_parents,
entry_1_ancestors,
time::get_time(),
)
.unwrap();
let tx2_parents = StoreHashSet::default();
let entry_2_ancestors = BTreeSet::default();
let entry2 = TxMempoolEntry::new_from_data(
txs.get(1).unwrap().clone(),
fee,
tx2_parents,
entry_2_ancestors,
time::get_time(),
)
.unwrap();
// Generation 2
let tx3_parents = vec![*entry1.tx_id(), *entry2.tx_id()].into_iter().collect();
let tx3_ancestors = vec![entry1.clone(), entry2.clone()].into_iter().collect();
let entry3 = TxMempoolEntry::new_from_data(
txs.get(2).unwrap().clone(),
fee,
tx3_parents,
tx3_ancestors,
time::get_time(),
)
.unwrap();
// Generation 3
let tx4_parents = vec![*entry3.tx_id()].into_iter().collect();
let tx4_ancestors = vec![entry1.clone(), entry2.clone(), entry3.clone()].into_iter().collect();
let tx5_parents = vec![*entry3.tx_id()].into_iter().collect();
let tx5_ancestors = vec![entry1.clone(), entry2.clone(), entry3.clone()].into_iter().collect();
let entry4 = TxMempoolEntry::new_from_data(
txs.get(3).unwrap().clone(),
fee,
tx4_parents,
tx4_ancestors,
time::get_time(),
)
.unwrap();
let entry5 = TxMempoolEntry::new_from_data(
txs.get(4).unwrap().clone(),
fee,
tx5_parents,
tx5_ancestors,
time::get_time(),
)
.unwrap();
// Generation 4
let tx6_parents = vec![*entry3.tx_id(), *entry4.tx_id(), *entry5.tx_id()].into_iter().collect();
let tx6_ancestors =
vec![entry1.clone(), entry2.clone(), entry3.clone(), entry4.clone(), entry5.clone()]
.into_iter()
.collect();
let entry6 = TxMempoolEntry::new_from_data(
txs.get(5).unwrap().clone(),
fee,
tx6_parents,
tx6_ancestors,
time::get_time(),
)
.unwrap();
let entries = vec![entry1, entry2, entry3, entry4, entry5, entry6];
let ids = entries.iter().map(|entry| *entry.tx_id()).collect::<Vec<_>>();
for entry in entries.into_iter() {
let entry_with_ancestors =
TxMempoolEntryWithAncestors::new_from_existing_entry(&mempool.store, entry);
mempool.store.add_tx_entry(entry_with_ancestors)?;
}
#[allow(clippy::get_first)]
let entry1 = mempool.store.get_entry(ids.get(0).expect("index")).expect("entry");
let entry2 = mempool.store.get_entry(ids.get(1).expect("index")).expect("entry");
let entry3 = mempool.store.get_entry(ids.get(2).expect("index")).expect("entry");
let entry4 = mempool.store.get_entry(ids.get(3).expect("index")).expect("entry");
let entry5 = mempool.store.get_entry(ids.get(4).expect("index")).expect("entry");
let entry6 = mempool.store.get_entry(ids.get(5).expect("index")).expect("entry");
assert_eq!(entry1.collect_ancestors(&mempool.store).len(), 0);
assert_eq!(entry2.collect_ancestors(&mempool.store).len(), 0);
assert_eq!(entry3.collect_ancestors(&mempool.store).len(), 2);
assert_eq!(entry4.collect_ancestors(&mempool.store).len(), 3);
assert_eq!(entry5.collect_ancestors(&mempool.store).len(), 3);
assert_eq!(entry6.collect_ancestors(&mempool.store).len(), 5);
assert_eq!(entry1.fees_with_ancestors(), Amount::from_atoms(1).into());
assert_eq!(entry2.fees_with_ancestors(), Amount::from_atoms(1).into());
assert_eq!(entry3.fees_with_ancestors(), Amount::from_atoms(3).into());
assert_eq!(entry4.fees_with_ancestors(), Amount::from_atoms(4).into());
assert_eq!(entry5.fees_with_ancestors(), Amount::from_atoms(4).into());
assert_eq!(entry6.fees_with_ancestors(), Amount::from_atoms(6).into());
assert_eq!(entry1.count_with_descendants(), 5);
assert_eq!(entry2.count_with_descendants(), 5);
assert_eq!(entry3.count_with_descendants(), 4);
assert_eq!(entry4.count_with_descendants(), 2);
assert_eq!(entry5.count_with_descendants(), 2);
assert_eq!(entry6.count_with_descendants(), 1);
assert_eq!(entry1.fees_with_descendants(), Amount::from_atoms(5).into());
assert_eq!(entry2.fees_with_descendants(), Amount::from_atoms(5).into());
assert_eq!(entry3.fees_with_descendants(), Amount::from_atoms(4).into());
assert_eq!(entry4.fees_with_descendants(), Amount::from_atoms(2).into());
assert_eq!(entry5.fees_with_descendants(), Amount::from_atoms(2).into());
assert_eq!(entry6.fees_with_descendants(), Amount::from_atoms(1).into());
Ok(())
}
async fn test_bip125_max_replacements(
seed: Seed,
num_potential_replacements: usize,
) -> anyhow::Result<()> {
let mut rng = make_seedable_rng(seed);
let tf = TestFramework::builder(&mut rng).build();
let genesis = tf.genesis();
let mut tx_builder = TransactionBuilder::new()
.add_input(
TxInput::from_utxo(OutPointSourceId::BlockReward(genesis.get_id().into()), 0),
empty_witness(&mut rng),
)
.with_flags(1);
for _ in 0..(num_potential_replacements - 1) {
tx_builder = tx_builder.add_output(TxOutput::Transfer(
OutputValue::Coin(Amount::from_atoms(999_999_999_000_000_000)),
anyonecanspend_address(),
));
}
let tx = tx_builder.build();
let mut mempool = setup_with_chainstate(tf.chainstate());
let input = tx.transaction().inputs().first().expect("one input").clone();
let outputs = tx.transaction().outputs().to_owned();
let tx_id = tx.transaction().get_id();
mempool.add_transaction_test(tx)?.assert_in_mempool();
let flags = 0;
let outpoint_source_id = OutPointSourceId::Transaction(tx_id);
let fee = 2_000;
for (index, _) in outputs.iter().enumerate() {
let input = TxInput::from_utxo(outpoint_source_id.clone(), index.try_into().unwrap());
let tx = tx_spend_input(
&mempool,
input,
InputWitness::NoSignature(Some(DUMMY_WITNESS_MSG.to_vec())),
Fee::new(Amount::from_atoms(fee)),
flags,
)
.await?;
mempool.add_transaction_test(tx)?.assert_in_mempool();
}
let mempool_size_before_replacement = mempool.store.txs_by_id().len();
let replacement_fee = (Amount::from_atoms(1_000_000_000_000_000) * fee).map(Fee::from);
let replacement_tx = tx_spend_input(
&mempool,
input,
InputWitness::NoSignature(Some(DUMMY_WITNESS_MSG.to_vec())),
replacement_fee,
flags,
)
.await?;
mempool.add_transaction_test(replacement_tx)?.assert_in_mempool();
let mempool_size_after_replacement = mempool.store.txs_by_id().len();
assert_eq!(
mempool_size_after_replacement,
mempool_size_before_replacement - num_potential_replacements + 1
);
Ok(())
}
#[rstest]
#[trace]
#[case(Seed::from_entropy())]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "RBF not implemented"]
async fn too_many_conflicts(#[case] seed: Seed) -> anyhow::Result<()> {
let num_potential_replacements = MAX_BIP125_REPLACEMENT_CANDIDATES + 1;
let err: Error = test_bip125_max_replacements(seed, num_potential_replacements)
.await
.expect_err("expected error TooManyPotentialReplacements")
.downcast()
.expect("failed to downcast");
assert_eq!(
err,
MempoolPolicyError::from(MempoolConflictError::TooManyReplacements).into(),
);
Ok(())
}
#[rstest]
#[trace]
#[case(Seed::from_entropy())]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "RBF not implemented"]
async fn not_too_many_conflicts(#[case] seed: Seed) -> anyhow::Result<()> {
let num_potential_replacements = MAX_BIP125_REPLACEMENT_CANDIDATES;
test_bip125_max_replacements(seed, num_potential_replacements).await
}
#[rstest]
#[trace]
#[case(Seed::from_entropy())]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn rolling_fee(#[case] seed: Seed) -> anyhow::Result<()> {
let mock_time = Arc::new(SeqCstAtomicU64::new(0));
let mock_clock = mocked_time_getter_seconds(Arc::clone(&mock_time));
let mut mock_usage = MockMemoryUsageEstimator::new();
// Add parent
// Add first child
mock_usage.expect_estimate_memory_usage().times(2).return_const(0usize);
// Add second child, triggering the trimming process
mock_usage
.expect_estimate_memory_usage()
.times(1)
.return_const(MAX_MEMPOOL_SIZE_BYTES + 1);
// After removing one entry, cause the code to exit the loop by showing a small usage
mock_usage.expect_estimate_memory_usage().return_const(0usize);
let mut rng = make_seedable_rng(seed);
let tf = TestFramework::builder(&mut rng).build();
let genesis = tf.genesis();
let mut tx_builder = TransactionBuilder::new()
.add_input(
TxInput::from_utxo(OutPointSourceId::BlockReward(genesis.get_id().into()), 0),
empty_witness(&mut rng),
)
.with_flags(1);
let num_outputs = 3;
for _ in 0..num_outputs {
tx_builder = tx_builder.add_output(TxOutput::Transfer(
OutputValue::Coin(Amount::from_atoms(999_999_999_000)),
anyonecanspend_address(),
));
}
let parent = tx_builder.build();
let parent_id = parent.transaction().get_id();
let chainstate = tf.chainstate();
let chain_config = Arc::clone(chainstate.get_chain_config());
let chainstate_interface = start_chainstate(chainstate);
let num_inputs = 1;
// Use a higher than default fee because we don't want this transaction to be evicted during
// the trimming process
log::debug!("parent_id: {}", parent_id.to_hash());
log::debug!("before adding parent");
let mut tx_pool = TxPool::new(
Arc::clone(&chain_config),
create_mempool_config(),
chainstate_interface,
mock_clock,
mock_usage,
);
tx_pool.add_transaction_test(parent.clone())?.assert_in_mempool();
log::debug!("after adding parent");
let flags = 0;
let outpoint_source_id = OutPointSourceId::Transaction(parent_id);
// child_0 has the lower fee so it will be evicted when memory usage is too high
let child_0 = tx_spend_input(
&tx_pool,
TxInput::from_utxo(outpoint_source_id.clone(), 0),
InputWitness::NoSignature(Some(DUMMY_WITNESS_MSG.to_vec())),
None,
flags,
)
.await?;
let child_0_id = child_0.transaction().get_id();
log::debug!("child_0_id {}", child_0_id.to_hash());
let big_fee: Fee = (get_relay_fee_from_tx_size(estimate_tx_size(num_inputs, num_outputs))
+ Amount::from_atoms(100))
.unwrap()
.into();
let child_1 = tx_spend_input(
&tx_pool,
TxInput::from_utxo(outpoint_source_id.clone(), 1),
InputWitness::NoSignature(Some(DUMMY_WITNESS_MSG.to_vec())),
big_fee,
flags,
)
.await?;
let child_1_id = child_1.transaction().get_id();
log::debug!("child_1_id {}", child_1_id.to_hash());
tx_pool.add_transaction_test(child_0.clone())?.assert_in_mempool();
log::debug!("added child_0");
tx_pool.add_transaction_test(child_1)?.assert_in_mempool();
log::debug!("added child_1");
assert_eq!(tx_pool.store.txs_by_id().len(), 2);
assert!(tx_pool.contains_transaction(&child_1_id));
assert!(!tx_pool.contains_transaction(&child_0_id));
let rolling_fee = tx_pool.get_minimum_rolling_fee();
let child_0_fee = try_get_fee(&tx_pool, &child_0).await;
log::debug!("FeeRate of child_0 {:?}", child_0_fee);
assert_eq!(
rolling_fee,
(INCREMENTAL_RELAY_FEE_RATE
+ FeeRate::from_total_tx_fee(
child_0_fee,
NonZeroUsize::new(child_0.encoded_size()).unwrap()
)?)
.unwrap()
);
assert_eq!(
rolling_fee,
FeeRate::from_amount_per_kb(Amount::from_atoms(3629))
);
log::debug!(
"minimum rolling fee after child_0's eviction {:?}",
rolling_fee
);
assert_eq!(
rolling_fee,
(FeeRate::from_total_tx_fee(
try_get_fee(&tx_pool, &child_0).await,
NonZeroUsize::new(child_0.encoded_size()).unwrap()
)? + INCREMENTAL_RELAY_FEE_RATE)
.unwrap()
);
// Now that the minimum rolling fee has been bumped up, a low-fee tx will not pass
// validation
let child_2 = tx_spend_input(
&tx_pool,
TxInput::from_utxo(outpoint_source_id.clone(), 2),
InputWitness::NoSignature(Some(DUMMY_WITNESS_MSG.to_vec())),
None,
flags,
)
.await?;
log::debug!(
"before child2: fee = {:?}, size = {}, minimum fee rate = {:?}",
try_get_fee(&tx_pool, &child_2).await,
child_2.encoded_size(),
tx_pool.get_minimum_rolling_fee()
);
let res = tx_pool.add_transaction_test(child_2);
log::debug!("result of adding child2 {:?}", res);
assert!(matches!(
res,
Err(Error::Policy(
MempoolPolicyError::RollingFeeThresholdNotMet { .. }
))
));
// We provide a sufficient fee for the tx to pass the minimum rolling fee requirement
let child_2_high_fee = tx_spend_input(
&tx_pool,
TxInput::from_utxo(outpoint_source_id, 2),
InputWitness::NoSignature(Some(DUMMY_WITNESS_MSG.to_vec())),
tx_pool.get_minimum_rolling_fee().compute_fee(estimate_tx_size(1, 1)).unwrap(),
flags,
)
.await?;
let child_2_high_fee_id = child_2_high_fee.transaction().get_id();
let child_2_high_fee_outpt =
UtxoOutPoint::new(OutPointSourceId::Transaction(child_2_high_fee_id), 0);
log::debug!("before child2_high_fee");
tx_pool.add_transaction_test(child_2_high_fee.clone())?.assert_in_mempool();
assert!(tx_pool.contains_transaction(&child_2_high_fee_id));
assert!(
tx_pool
.chainstate_handle()
.call({
let outpt = child_2_high_fee_outpt.clone();
move |c| c.utxo(&outpt).unwrap().is_none()
})
.await
.unwrap()
);
// TODO The commented out part only applies if RBF is active
// We simulate a block being accepted so the rolling fee will begin to decay
let block = Block::new(
vec![parent, child_2_high_fee],
genesis.get_id().into(),
BlockTimestamp::from_int_seconds(1639975461),
ConsensusData::None,
BlockReward::new(vec![]),
)
.map_err(|_| anyhow::Error::msg("block creation error"))?;
let block_id = block.get_id();
tx_pool
.chainstate_handle
.call_mut(|this| this.process_block(block, BlockSource::Local))
.await??;
tx_pool.on_new_tip(block_id, BlockHeight::new(1)).unwrap();
assert!(!tx_pool.contains_transaction(&child_2_high_fee_id));
assert!(
tx_pool
.chainstate_handle()
.call(move |c| c.utxo(&child_2_high_fee_outpt).unwrap().is_some())
.await
.unwrap()
);
// Because the rolling fee is only updated when we attempt to add a tx to the mempool we need
// to submit a "dummy" tx to trigger these updates.
// Since memory usage is now zero, it is less than 1/4 of the max size
// and ROLLING_FEE_BASE_HALFLIFE / 4 is the time it will take for the fee to halve
// We are going to submit dummy txs to the mempool incrementing time by this halflife
// between txs. Finally, when the fee rate falls under INCREMENTAL_RELAY_THRESHOLD, we
// observer that it is set to zero
let halflife = ROLLING_FEE_BASE_HALFLIFE / 4;
mock_time.store(mock_time.load() + halflife.as_secs());
let dummy_tx = TransactionBuilder::new()
.add_input(
TxInput::from_utxo(OutPointSourceId::Transaction(child_2_high_fee_id), 0),
InputWitness::NoSignature(Some(DUMMY_WITNESS_MSG.to_vec())),
)
.add_output(TxOutput::Transfer(
OutputValue::Coin(Amount::from_atoms(499999999105 - 84)),
Destination::AnyoneCanSpend,
))
.build();
log::debug!(
"First attempt to add dummy which pays a fee of {:?}",
try_get_fee(&tx_pool, &dummy_tx).await
);
let res = tx_pool.add_transaction_test(dummy_tx.clone());
log::debug!("Result of first attempt to add dummy: {res:?}");
assert!(matches!(
res,
Err(Error::Policy(
MempoolPolicyError::RollingFeeThresholdNotMet { .. }
)),
));
log::debug!(
"minimum rolling fee after first attempt to add dummy: {:?}",
tx_pool.get_minimum_rolling_fee()
);
assert_eq!(
tx_pool.get_minimum_rolling_fee(),
rolling_fee / NonZeroUsize::new(2).expect("nonzero")
);
mock_time.store(mock_time.load() + halflife.as_secs());
log::debug!("Second attempt to add dummy");
tx_pool.add_transaction_test(dummy_tx)?.assert_in_mempool();
log::debug!(
"minimum rolling fee after first second to add dummy: {:?}",
tx_pool.get_minimum_rolling_fee()
);
assert_eq!(
tx_pool.get_minimum_rolling_fee(),
rolling_fee / NonZeroUsize::new(4).expect("nonzero")
);
log::debug!(
"After successful addition of dummy, rolling fee rate is {:?}",
tx_pool.get_minimum_rolling_fee()
);
// Add another dummy until rolling feerate drops to zero
mock_time.store(mock_time.load() + halflife.as_secs());
let another_dummy = TransactionBuilder::new()
.add_input(
TxInput::from_utxo(OutPointSourceId::Transaction(child_1_id), 0),
InputWitness::NoSignature(Some(DUMMY_WITNESS_MSG.to_vec())),
)
.add_output(TxOutput::Transfer(
OutputValue::Coin(Amount::from_atoms(499999999105 - 77)),
Destination::AnyoneCanSpend,
))
.build();
tx_pool.add_transaction_test(another_dummy)?.assert_in_mempool();
assert_eq!(
tx_pool.get_minimum_rolling_fee(),
FeeRate::from_amount_per_kb(Amount::from_atoms(0))
);
tx_pool.store.assert_valid();
Ok(())
}
#[rstest]
#[trace]
#[case(Seed::from_entropy())]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn different_size_txs(#[case] seed: Seed) -> anyhow::Result<()> {
use std::time::Instant;
let mut rng = make_seedable_rng(seed);
let mut tf = TestFramework::builder(&mut rng).build();
let genesis = tf.genesis();
let mut tx_builder = TransactionBuilder::new().add_input(
TxInput::from_utxo(OutPointSourceId::BlockReward(genesis.get_id().into()), 0),
empty_witness(&mut rng),
);
for _ in 0..10_000 {
tx_builder = tx_builder.add_output(TxOutput::Transfer(
OutputValue::Coin(Amount::from_atoms(1_000)),
Destination::AnyoneCanSpend,
))
}
let initial_tx = tx_builder.build();
let block = tf.make_block_builder().add_transaction(initial_tx.clone()).build(&mut rng);
tf.process_block(block, BlockSource::Local).expect("process_block");
let chainstate = tf.chainstate();
let mut mempool = setup_with_chainstate(chainstate);
let target_txs = 10;
for i in 0..target_txs {
let tx_i_start = Instant::now();
let num_inputs = 10 * (i + 1);
let num_outputs = 10 * (i + 1);
let mut tx_builder = TransactionBuilder::new();
for j in 0..num_inputs {
tx_builder = tx_builder.add_input(
TxInput::from_utxo(
OutPointSourceId::Transaction(initial_tx.transaction().get_id()),
100 * i + j,
),
empty_witness(&mut rng),
);
}
log::debug!(
"time spent building inputs of tx {} {:?}",
i,
tx_i_start.elapsed()
);
let before_outputs = Instant::now();
for _ in 0..num_outputs {
tx_builder = tx_builder.add_output(TxOutput::Transfer(
OutputValue::Coin(Amount::from_atoms(100)),
Destination::AnyoneCanSpend,
))
}
log::debug!(
"time spent building outputs of tx {} {:?}",
i,
before_outputs.elapsed()
);
let tx = tx_builder.build();
let before_adding_tx_i = Instant::now();
mempool.add_transaction_test(tx)?.assert_in_mempool();
log::debug!(
"time spent adding tx {}: {:?}",
i,
before_adding_tx_i.elapsed()
);
log::debug!("Added tx {}", i);
}
mempool.store.assert_valid();
Ok(())
}
#[rstest]