-
Notifications
You must be signed in to change notification settings - Fork 663
/
pox_3_tests.rs
4395 lines (3848 loc) · 152 KB
/
pox_3_tests.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
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) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020-2023 Stacks Open Internet Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::collections::{HashMap, HashSet, VecDeque};
use std::convert::{TryFrom, TryInto};
use clarity::vm::clarity::ClarityConnection;
use clarity::vm::contexts::OwnedEnvironment;
use clarity::vm::contracts::Contract;
use clarity::vm::costs::{CostOverflowingMath, LimitedCostTracker};
use clarity::vm::database::*;
use clarity::vm::errors::{
CheckErrors, Error, IncomparableError, InterpreterError, InterpreterResult, RuntimeErrorType,
};
use clarity::vm::eval;
use clarity::vm::events::StacksTransactionEvent;
use clarity::vm::representations::SymbolicExpression;
use clarity::vm::tests::{execute, is_committed, is_err_code, symbols_from_values};
use clarity::vm::types::Value::Response;
use clarity::vm::types::{
BuffData, OptionalData, PrincipalData, QualifiedContractIdentifier, ResponseData, SequenceData,
StacksAddressExtensions, StandardPrincipalData, TupleData, TupleTypeSignature, TypeSignature,
Value, NONE,
};
use stacks_common::address::AddressHashMode;
use stacks_common::types::chainstate::{
BlockHeaderHash, BurnchainHeaderHash, StacksAddress, StacksBlockId, VRFSeed,
};
use stacks_common::types::Address;
use stacks_common::util::hash::{hex_bytes, to_hex, Sha256Sum, Sha512Trunc256Sum};
use super::test::*;
use super::RawRewardSetEntry;
use crate::burnchains::{Burnchain, PoxConstants};
use crate::chainstate::burn::db::sortdb::SortitionDB;
use crate::chainstate::burn::operations::*;
use crate::chainstate::burn::{BlockSnapshot, ConsensusHash};
use crate::chainstate::stacks::address::{PoxAddress, PoxAddressType20, PoxAddressType32};
use crate::chainstate::stacks::boot::pox_2_tests::{
check_pox_print_event, check_stacking_state_invariants, generate_pox_clarity_value,
get_partial_stacked, get_reward_cycle_total, get_reward_set_entries_at, get_stacking_state_pox,
get_stacking_state_pox_2, get_stx_account_at, PoxPrintFields, StackingStateCheckData,
};
use crate::chainstate::stacks::boot::{
BOOT_CODE_COST_VOTING_TESTNET as BOOT_CODE_COST_VOTING, BOOT_CODE_POX_TESTNET, POX_2_NAME,
POX_3_NAME,
};
use crate::chainstate::stacks::db::{
MinerPaymentSchedule, StacksChainState, StacksHeaderInfo, MINER_REWARD_MATURITY,
};
use crate::chainstate::stacks::events::TransactionOrigin;
use crate::chainstate::stacks::index::marf::MarfConnection;
use crate::chainstate::stacks::index::MarfTrieId;
use crate::chainstate::stacks::tests::make_coinbase;
use crate::chainstate::stacks::*;
use crate::clarity_vm::clarity::{ClarityBlockConnection, Error as ClarityError};
use crate::clarity_vm::database::marf::{MarfedKV, WritableMarfStore};
use crate::clarity_vm::database::HeadersDBConn;
use crate::core::*;
use crate::net::test::{TestEventObserver, TestPeer};
use crate::util_lib::boot::boot_code_id;
use crate::util_lib::db::{DBConn, FromRow};
const USTX_PER_HOLDER: u128 = 1_000_000;
/// Return the BlockSnapshot for the latest sortition in the provided
/// SortitionDB option-reference. Panics on any errors.
fn get_tip(sortdb: Option<&SortitionDB>) -> BlockSnapshot {
SortitionDB::get_canonical_burn_chain_tip(&sortdb.unwrap().conn()).unwrap()
}
fn make_test_epochs_pox() -> (Vec<StacksEpoch>, PoxConstants) {
let EMPTY_SORTITIONS = 25;
let EPOCH_2_1_HEIGHT = EMPTY_SORTITIONS + 11; // 36
let EPOCH_2_2_HEIGHT = EPOCH_2_1_HEIGHT + 14; // 50
let EPOCH_2_3_HEIGHT = EPOCH_2_2_HEIGHT + 2; // 52
// epoch-2.4 will start at the first block of cycle 11!
// this means that cycle 11 should also be treated like a "burn"
let EPOCH_2_4_HEIGHT = EPOCH_2_2_HEIGHT + 6; // 56
// cycle 11 = 60
let epochs = vec![
StacksEpoch {
epoch_id: StacksEpochId::Epoch10,
start_height: 0,
end_height: 0,
block_limit: ExecutionCost::max_value(),
network_epoch: PEER_VERSION_EPOCH_1_0,
},
StacksEpoch {
epoch_id: StacksEpochId::Epoch20,
start_height: 0,
end_height: 0,
block_limit: ExecutionCost::max_value(),
network_epoch: PEER_VERSION_EPOCH_2_0,
},
StacksEpoch {
epoch_id: StacksEpochId::Epoch2_05,
start_height: 0,
end_height: EPOCH_2_1_HEIGHT,
block_limit: ExecutionCost::max_value(),
network_epoch: PEER_VERSION_EPOCH_2_05,
},
StacksEpoch {
epoch_id: StacksEpochId::Epoch21,
start_height: EPOCH_2_1_HEIGHT,
end_height: EPOCH_2_2_HEIGHT,
block_limit: ExecutionCost::max_value(),
network_epoch: PEER_VERSION_EPOCH_2_1,
},
StacksEpoch {
epoch_id: StacksEpochId::Epoch22,
start_height: EPOCH_2_2_HEIGHT,
end_height: EPOCH_2_3_HEIGHT,
block_limit: ExecutionCost::max_value(),
network_epoch: PEER_VERSION_EPOCH_2_2,
},
StacksEpoch {
epoch_id: StacksEpochId::Epoch23,
start_height: EPOCH_2_3_HEIGHT,
end_height: EPOCH_2_4_HEIGHT,
block_limit: ExecutionCost::max_value(),
network_epoch: PEER_VERSION_EPOCH_2_3,
},
StacksEpoch {
epoch_id: StacksEpochId::Epoch24,
start_height: EPOCH_2_4_HEIGHT,
end_height: STACKS_EPOCH_MAX,
block_limit: ExecutionCost::max_value(),
network_epoch: PEER_VERSION_EPOCH_2_4,
},
];
let mut pox_constants = PoxConstants::mainnet_default();
pox_constants.reward_cycle_length = 5;
pox_constants.prepare_length = 2;
pox_constants.anchor_threshold = 1;
pox_constants.v1_unlock_height = (EPOCH_2_1_HEIGHT + 1) as u32;
pox_constants.v2_unlock_height = (EPOCH_2_2_HEIGHT + 1) as u32;
pox_constants.v3_unlock_height = u32::MAX;
pox_constants.pox_3_activation_height = (EPOCH_2_4_HEIGHT + 1) as u32;
pox_constants.pox_4_activation_height = u32::MAX;
(epochs, pox_constants)
}
/// In this test case, two Stackers, Alice and Bob stack and interact with the
/// PoX v1 contract and PoX v2 contract across the epoch transition and then
/// again with the PoX v3 contract.
///
/// Alice: stacks via PoX v1 for 4 cycles. The third of these cycles occurs after
/// the PoX v1 -> v2 transition, and so Alice gets "early unlocked".
/// After the early unlock, Alice re-stacks in PoX v2
/// Bob: stacks via PoX v2 for 6 cycles. He attempted to stack via PoX v1 as well,
/// but is forbidden because he has already placed an account lock via PoX v2.
///
/// After the PoX-3 contract is instantiated, Alice and Bob both stack via PoX v3.
///
#[test]
fn simple_pox_lockup_transition_pox_2() {
let EXPECTED_FIRST_V2_CYCLE = 8;
// the sim environment produces 25 empty sortitions before
// tenures start being tracked.
let EMPTY_SORTITIONS = 25;
let (epochs, pox_constants) = make_test_epochs_pox();
let mut burnchain = Burnchain::default_unittest(
0,
&BurnchainHeaderHash::from_hex(BITCOIN_REGTEST_FIRST_BLOCK_HASH).unwrap(),
);
burnchain.pox_constants = pox_constants.clone();
let first_v2_cycle = burnchain
.block_height_to_reward_cycle(burnchain.pox_constants.v1_unlock_height as u64)
.unwrap()
+ 1;
assert_eq!(first_v2_cycle, EXPECTED_FIRST_V2_CYCLE);
eprintln!("First v2 cycle = {}", first_v2_cycle);
let observer = TestEventObserver::new();
let (mut peer, mut keys) = instantiate_pox_peer_with_epoch(
&burnchain,
function_name!(),
Some(epochs.clone()),
Some(&observer),
);
peer.config.check_pox_invariants =
Some((EXPECTED_FIRST_V2_CYCLE, EXPECTED_FIRST_V2_CYCLE + 20));
let alice = keys.pop().unwrap();
let bob = keys.pop().unwrap();
let charlie = keys.pop().unwrap();
let EXPECTED_ALICE_FIRST_REWARD_CYCLE = 6;
let mut coinbase_nonce = 0;
// our "tenure counter" is now at 0
let tip = get_tip(peer.sortdb.as_ref());
assert_eq!(tip.block_height, 0 + EMPTY_SORTITIONS as u64);
// first tenure is empty
peer.tenure_with_txs(&[], &mut coinbase_nonce);
let alice_balance = get_balance(&mut peer, &key_to_stacks_addr(&alice).into());
assert_eq!(alice_balance, 1024 * POX_THRESHOLD_STEPS_USTX);
let alice_account = get_account(&mut peer, &key_to_stacks_addr(&alice).into());
assert_eq!(
alice_account.stx_balance.amount_unlocked(),
1024 * POX_THRESHOLD_STEPS_USTX
);
assert_eq!(alice_account.stx_balance.amount_locked(), 0);
assert_eq!(alice_account.stx_balance.unlock_height(), 0);
// next tenure include Alice's lockup
let tip = get_tip(peer.sortdb.as_ref());
let alice_lockup = make_pox_lockup(
&alice,
0,
1024 * POX_THRESHOLD_STEPS_USTX,
AddressHashMode::SerializeP2PKH,
key_to_stacks_addr(&alice).bytes,
4,
tip.block_height,
);
// our "tenure counter" is now at 1
assert_eq!(tip.block_height, 1 + EMPTY_SORTITIONS as u64);
let tip_index_block = peer.tenure_with_txs(&[alice_lockup], &mut coinbase_nonce);
// check the stacking minimum
let total_liquid_ustx = get_liquid_ustx(&mut peer);
let min_ustx = with_sortdb(&mut peer, |ref mut chainstate, ref sortdb| {
chainstate.get_stacking_minimum(sortdb, &tip_index_block)
})
.unwrap();
assert_eq!(
min_ustx,
total_liquid_ustx / POX_TESTNET_STACKING_THRESHOLD_25
);
// no reward addresses
let reward_addrs = with_sortdb(&mut peer, |ref mut chainstate, ref sortdb| {
get_reward_addresses_with_par_tip(chainstate, &burnchain, sortdb, &tip_index_block)
})
.unwrap();
assert_eq!(reward_addrs.len(), 0);
// check the first reward cycle when Alice's tokens get stacked
let tip_burn_block_height = get_par_burn_block_height(peer.chainstate(), &tip_index_block);
let alice_first_reward_cycle = 1 + burnchain
.block_height_to_reward_cycle(tip_burn_block_height)
.unwrap() as u128;
assert_eq!(alice_first_reward_cycle, EXPECTED_ALICE_FIRST_REWARD_CYCLE);
// alice locked, so balance should be 0
let alice_balance = get_balance(&mut peer, &key_to_stacks_addr(&alice).into());
assert_eq!(alice_balance, 0);
// produce blocks until immediately before the 2.1 epoch switch
while get_tip(peer.sortdb.as_ref()).block_height < epochs[3].start_height {
peer.tenure_with_txs(&[], &mut coinbase_nonce);
// alice is still locked, balance should be 0
let alice_balance = get_balance(&mut peer, &key_to_stacks_addr(&alice).into());
assert_eq!(alice_balance, 0);
}
// Have Charlie try to use the PoX2 contract. This transaction
// should be accepted (checked via the tx receipt). Also, importantly,
// the cost tracker should assign costs to Charlie's transaction.
// This is also checked by the transaction receipt.
let tip = get_tip(peer.sortdb.as_ref());
let test = make_pox_2_contract_call(
&charlie,
0,
"delegate-stx",
vec![
Value::UInt(1_000_000),
PrincipalData::from(key_to_stacks_addr(&charlie)).into(),
Value::none(),
Value::none(),
],
);
peer.tenure_with_txs(&[test], &mut coinbase_nonce);
// alice is still locked, balance should be 0
let alice_balance = get_balance(&mut peer, &key_to_stacks_addr(&alice).into());
assert_eq!(alice_balance, 0);
// in the next tenure, PoX 2 should now exist.
// Lets have Bob lock up for v2
// this will lock for cycles 8, 9, 10, and 11
// the first v2 cycle will be 8
let tip = get_tip(peer.sortdb.as_ref());
let bob_lockup = make_pox_2_lockup(
&bob,
0,
512 * POX_THRESHOLD_STEPS_USTX,
PoxAddress::from_legacy(
AddressHashMode::SerializeP2PKH,
key_to_stacks_addr(&bob).bytes,
),
6,
tip.block_height,
);
let block_id = peer.tenure_with_txs(&[bob_lockup], &mut coinbase_nonce);
assert_eq!(
get_tip(peer.sortdb.as_ref()).block_height as u32,
pox_constants.v1_unlock_height + 1,
"Test should have reached 1 + PoX-v1 unlock height"
);
// Auto unlock height is reached, Alice balance should be unlocked
let alice_balance = get_balance(&mut peer, &key_to_stacks_addr(&alice).into());
assert_eq!(alice_balance, 1024 * POX_THRESHOLD_STEPS_USTX);
// Now, Bob tries to lock in PoX v1 too, but it shouldn't work!
let tip = get_tip(peer.sortdb.as_ref());
let bob_lockup = make_pox_lockup(
&bob,
1,
512 * POX_THRESHOLD_STEPS_USTX,
AddressHashMode::SerializeP2PKH,
key_to_stacks_addr(&bob).bytes,
4,
tip.block_height,
);
let block_id = peer.tenure_with_txs(&[bob_lockup], &mut coinbase_nonce);
// At this point, the auto unlock height for v1 accounts has been reached.
// let Alice stack in PoX v2
let tip = get_tip(peer.sortdb.as_ref());
let alice_lockup = make_pox_2_lockup(
&alice,
1,
512 * POX_THRESHOLD_STEPS_USTX,
PoxAddress::from_legacy(
AddressHashMode::SerializeP2PKH,
key_to_stacks_addr(&alice).bytes,
),
12,
tip.block_height,
);
peer.tenure_with_txs(&[alice_lockup], &mut coinbase_nonce);
// Alice locked half her balance in PoX 2
let alice_balance = get_balance(&mut peer, &key_to_stacks_addr(&alice).into());
assert_eq!(alice_balance, 512 * POX_THRESHOLD_STEPS_USTX);
// now, let's roll the chain forward until just before Epoch-2.2
while get_tip(peer.sortdb.as_ref()).block_height < epochs[4].start_height {
peer.tenure_with_txs(&[], &mut coinbase_nonce);
// at this point, alice's balance should always include this half lockup
let alice_balance = get_balance(&mut peer, &key_to_stacks_addr(&alice).into());
assert_eq!(alice_balance, 512 * POX_THRESHOLD_STEPS_USTX);
}
// this block is mined in epoch-2.2
peer.tenure_with_txs(&[], &mut coinbase_nonce);
let alice_balance = get_balance(&mut peer, &key_to_stacks_addr(&alice).into());
assert_eq!(alice_balance, 512 * POX_THRESHOLD_STEPS_USTX);
// this block should unlock alice's balance
peer.tenure_with_txs(&[], &mut coinbase_nonce);
let alice_balance = get_balance(&mut peer, &key_to_stacks_addr(&alice).into());
assert_eq!(alice_balance, 1024 * POX_THRESHOLD_STEPS_USTX);
// now, roll the chain forward to Epoch-2.4
while get_tip(peer.sortdb.as_ref()).block_height <= epochs[6].start_height {
peer.tenure_with_txs(&[], &mut coinbase_nonce);
// at this point, alice's balance should always be unlocked
let alice_balance = get_balance(&mut peer, &key_to_stacks_addr(&alice).into());
assert_eq!(alice_balance, 1024 * POX_THRESHOLD_STEPS_USTX);
}
let tip = get_tip(peer.sortdb.as_ref()).block_height;
let bob_lockup = make_pox_3_lockup(
&bob,
2,
512 * POX_THRESHOLD_STEPS_USTX,
PoxAddress::from_legacy(
AddressHashMode::SerializeP2PKH,
key_to_stacks_addr(&bob).bytes,
),
6,
tip,
);
let alice_lockup = make_pox_3_lockup(
&alice,
2,
512 * POX_THRESHOLD_STEPS_USTX,
PoxAddress::from_legacy(
AddressHashMode::SerializeP2PKH,
key_to_stacks_addr(&alice).bytes,
),
6,
tip,
);
peer.tenure_with_txs(&[bob_lockup, alice_lockup], &mut coinbase_nonce);
let alice_balance = get_balance(&mut peer, &key_to_stacks_addr(&alice).into());
assert_eq!(alice_balance, 512 * POX_THRESHOLD_STEPS_USTX);
let bob_balance = get_balance(&mut peer, &key_to_stacks_addr(&bob).into());
assert_eq!(bob_balance, 512 * POX_THRESHOLD_STEPS_USTX);
// now let's check some tx receipts
let alice_address = key_to_stacks_addr(&alice);
let bob_address = key_to_stacks_addr(&bob);
let blocks = observer.get_blocks();
let mut alice_txs = HashMap::new();
let mut bob_txs = HashMap::new();
let mut charlie_txs = HashMap::new();
debug!("Alice addr: {}, Bob addr: {}", alice_address, bob_address);
let mut tested_charlie = false;
for b in blocks.into_iter() {
for r in b.receipts.into_iter() {
if let TransactionOrigin::Stacks(ref t) = r.transaction {
let addr = t.auth.origin().address_testnet();
debug!("Transaction addr: {}", addr);
if addr == alice_address {
alice_txs.insert(t.auth.get_origin_nonce(), r);
} else if addr == bob_address {
bob_txs.insert(t.auth.get_origin_nonce(), r);
} else if addr == key_to_stacks_addr(&charlie) {
assert!(
r.execution_cost != ExecutionCost::zero(),
"Execution cost is not zero!"
);
charlie_txs.insert(t.auth.get_origin_nonce(), r);
tested_charlie = true;
}
}
}
}
assert!(tested_charlie, "Charlie TX must be tested");
// Alice should have three accepted transactions:
// TX0 -> Alice's initial lockup in PoX 1
// TX1 -> Alice's PoX 2 lockup
// TX2 -> Alice's PoX 3 lockup
assert_eq!(alice_txs.len(), 3, "Alice should have 3 confirmed txs");
// Bob should have two accepted transactions:
// TX0 -> Bob's initial lockup in PoX 2
// TX1 -> Bob's attempt to lock again in PoX 1 -- this one should fail
// because PoX 1 is now defunct. Checked via the tx receipt.
// TX2 -> Bob's PoX 3 lockup
assert_eq!(bob_txs.len(), 3, "Bob should have 3 confirmed txs");
// Charlie should have one accepted transactions:
// TX0 -> Charlie's delegation in PoX 2. This tx just checks that the
// initialization code tracks costs in txs that occur after the
// initialization code (which uses a free tracker).
assert_eq!(charlie_txs.len(), 1, "Charlie should have 1 confirmed txs");
// TX0 -> Alice's initial lockup in PoX 1
assert!(
match alice_txs.get(&0).unwrap().result {
Value::Response(ref r) => r.committed,
_ => false,
},
"Alice tx0 should have committed okay"
);
// TX1 -> Alice's PoX 2 lockup
assert!(
match alice_txs.get(&1).unwrap().result {
Value::Response(ref r) => r.committed,
_ => false,
},
"Alice tx1 should have committed okay"
);
// TX2 -> Alice's PoX 3 lockup
assert!(
match alice_txs.get(&1).unwrap().result {
Value::Response(ref r) => r.committed,
_ => false,
},
"Alice tx3 should have committed okay"
);
// TX0 -> Bob's initial lockup in PoX 2
assert!(
match bob_txs.get(&0).unwrap().result {
Value::Response(ref r) => r.committed,
_ => false,
},
"Bob tx0 should have committed okay"
);
// TX1 -> Bob's attempt to lock again in PoX 1 -- this one should fail
// because PoX 1 is now defunct. Checked via the tx receipt.
assert_eq!(
bob_txs.get(&1).unwrap().result,
Value::err_none(),
"Bob tx1 should have resulted in a runtime error"
);
// TX0 -> Charlie's delegation in PoX 2. This tx just checks that the
// initialization code tracks costs in txs that occur after the
// initialization code (which uses a free tracker).
assert!(
match charlie_txs.get(&0).unwrap().result {
Value::Response(ref r) => r.committed,
_ => false,
},
"Charlie tx0 should have committed okay"
);
}
#[test]
fn pox_auto_unlock_ab() {
pox_auto_unlock(true)
}
#[test]
fn pox_auto_unlock_ba() {
pox_auto_unlock(false)
}
/// In this test case, two Stackers, Alice and Bob stack and interact with the
/// PoX v1 contract and PoX v2 contract across the epoch transition, and then again
/// in PoX v3.
///
/// Alice: stacks via PoX v1 for 4 cycles. The third of these cycles occurs after
/// the PoX v1 -> v2 transition, and so Alice gets "early unlocked".
/// After the early unlock, Alice re-stacks in PoX v2
/// Bob: stacks via PoX v2 for 6 cycles. He attempted to stack via PoX v1 as well,
/// but is forbidden because he has already placed an account lock via PoX v2.
///
/// Note: this test is symmetric over the order of alice and bob's stacking calls.
/// when alice goes first, the auto-unlock code doesn't need to perform a "move"
/// when bob goes first, the auto-unlock code does need to perform a "move"
fn pox_auto_unlock(alice_first: bool) {
let EXPECTED_FIRST_V2_CYCLE = 8;
// the sim environment produces 25 empty sortitions before
// tenures start being tracked.
let EMPTY_SORTITIONS = 25;
let (epochs, pox_constants) = make_test_epochs_pox();
let mut burnchain = Burnchain::default_unittest(
0,
&BurnchainHeaderHash::from_hex(BITCOIN_REGTEST_FIRST_BLOCK_HASH).unwrap(),
);
burnchain.pox_constants = pox_constants.clone();
let first_v2_cycle = burnchain
.block_height_to_reward_cycle(burnchain.pox_constants.v1_unlock_height as u64)
.unwrap()
+ 1;
let first_v3_cycle = burnchain
.block_height_to_reward_cycle(burnchain.pox_constants.pox_3_activation_height as u64)
.unwrap()
+ 1;
assert_eq!(first_v2_cycle, EXPECTED_FIRST_V2_CYCLE);
eprintln!("First v2 cycle = {}", first_v2_cycle);
let observer = TestEventObserver::new();
let (mut peer, mut keys) = instantiate_pox_peer_with_epoch(
&burnchain,
&format!("{}-{}", function_name!(), alice_first),
Some(epochs.clone()),
Some(&observer),
);
peer.config.check_pox_invariants =
Some((EXPECTED_FIRST_V2_CYCLE, EXPECTED_FIRST_V2_CYCLE + 10));
let alice = keys.pop().unwrap();
let bob = keys.pop().unwrap();
let mut coinbase_nonce = 0;
// produce blocks until epoch 2.1
while get_tip(peer.sortdb.as_ref()).block_height <= epochs[3].start_height {
peer.tenure_with_txs(&[], &mut coinbase_nonce);
}
// in the next tenure, PoX 2 should now exist.
// Lets have Bob lock up for v2
// this will lock for cycles 8, 9, 10, and 11
// the first v2 cycle will be 8
let tip = get_tip(peer.sortdb.as_ref());
let alice_lockup = make_pox_2_lockup(
&alice,
0,
1024 * POX_THRESHOLD_STEPS_USTX,
PoxAddress::from_legacy(
AddressHashMode::SerializeP2PKH,
key_to_stacks_addr(&alice).bytes,
),
6,
tip.block_height,
);
let bob_lockup = make_pox_2_lockup(
&bob,
0,
1 * POX_THRESHOLD_STEPS_USTX,
PoxAddress::from_legacy(
AddressHashMode::SerializeP2PKH,
key_to_stacks_addr(&bob).bytes,
),
6,
tip.block_height,
);
let txs = if alice_first {
[alice_lockup, bob_lockup]
} else {
[bob_lockup, alice_lockup]
};
let mut latest_block = peer.tenure_with_txs(&txs, &mut coinbase_nonce);
// check that the "raw" reward set will contain entries for alice and bob
// for the pox-2 cycles
for cycle_number in EXPECTED_FIRST_V2_CYCLE..first_v3_cycle {
let cycle_start = burnchain.reward_cycle_to_block_height(cycle_number);
let reward_set_entries = get_reward_set_entries_at(&mut peer, &latest_block, cycle_start);
assert_eq!(reward_set_entries.len(), 2);
assert_eq!(
reward_set_entries[0].reward_address.bytes(),
key_to_stacks_addr(&bob).bytes.0.to_vec()
);
assert_eq!(
reward_set_entries[1].reward_address.bytes(),
key_to_stacks_addr(&alice).bytes.0.to_vec()
);
}
// we'll produce blocks until the next reward cycle gets through the "handled start" code
// this is one block after the reward cycle starts
let height_target = burnchain.reward_cycle_to_block_height(EXPECTED_FIRST_V2_CYCLE) + 1;
// but first, check that bob has locked tokens at (height_target + 1)
let bob_bal = get_stx_account_at(
&mut peer,
&latest_block,
&key_to_stacks_addr(&bob).to_account_principal(),
);
assert_eq!(bob_bal.amount_locked(), POX_THRESHOLD_STEPS_USTX);
while get_tip(peer.sortdb.as_ref()).block_height < height_target {
latest_block = peer.tenure_with_txs(&[], &mut coinbase_nonce);
}
let first_auto_unlock_coinbase = height_target - 1 - EMPTY_SORTITIONS;
// check that the "raw" reward sets for all cycles just contains entries for alice
// at the cycle start
for cycle_number in EXPECTED_FIRST_V2_CYCLE..first_v3_cycle {
let cycle_start = burnchain.reward_cycle_to_block_height(cycle_number);
let reward_set_entries = get_reward_set_entries_at(&mut peer, &latest_block, cycle_start);
assert_eq!(reward_set_entries.len(), 1);
assert_eq!(
reward_set_entries[0].reward_address.bytes(),
key_to_stacks_addr(&alice).bytes.0.to_vec()
);
}
// now check that bob has an unlock height of `height_target`
let bob_bal = get_stx_account_at(
&mut peer,
&latest_block,
&key_to_stacks_addr(&bob).to_account_principal(),
);
assert_eq!(bob_bal.unlock_height(), height_target);
// but bob's still locked at (height_target): the unlock is accelerated to the "next" burn block
assert_eq!(bob_bal.amount_locked(), 10000000000);
// check that the total reward cycle amounts have decremented correctly
for cycle_number in EXPECTED_FIRST_V2_CYCLE..first_v3_cycle {
assert_eq!(
get_reward_cycle_total(&mut peer, &latest_block, cycle_number),
1024 * POX_THRESHOLD_STEPS_USTX
);
}
// check that bob is fully unlocked at next block
latest_block = peer.tenure_with_txs(&[], &mut coinbase_nonce);
let bob_bal = get_stx_account_at(
&mut peer,
&latest_block,
&key_to_stacks_addr(&bob).to_account_principal(),
);
assert_eq!(bob_bal.unlock_height(), 0);
assert_eq!(bob_bal.amount_locked(), 0);
// check that the total reward cycle amounts have decremented correctly
for cycle_number in EXPECTED_FIRST_V2_CYCLE..first_v3_cycle {
assert_eq!(
get_reward_cycle_total(&mut peer, &latest_block, cycle_number),
1024 * POX_THRESHOLD_STEPS_USTX
);
}
// check that bob's stacking-state is gone and alice's stacking-state is correct
assert!(
get_stacking_state_pox_2(
&mut peer,
&latest_block,
&key_to_stacks_addr(&bob).to_account_principal()
)
.is_none(),
"Bob should not have a stacking-state entry"
);
let alice_state = get_stacking_state_pox_2(
&mut peer,
&latest_block,
&key_to_stacks_addr(&alice).to_account_principal(),
)
.expect("Alice should have stacking-state entry")
.expect_tuple();
let reward_indexes_str = format!("{}", alice_state.get("reward-set-indexes").unwrap());
assert_eq!(reward_indexes_str, "(u0 u0 u0 u0 u0 u0)");
// now, lets check behavior in Epochs 2.2-2.4, with pox-3 auto unlock tests
// produce blocks until epoch 2.2
while get_tip(peer.sortdb.as_ref()).block_height <= epochs[4].start_height {
peer.tenure_with_txs(&[], &mut coinbase_nonce);
let alice_balance = get_balance(&mut peer, &key_to_stacks_addr(&alice).into());
assert_eq!(alice_balance, 0);
}
// check that alice is unlocked now
peer.tenure_with_txs(&[], &mut coinbase_nonce);
let alice_balance = get_balance(&mut peer, &key_to_stacks_addr(&alice).into());
assert_eq!(alice_balance, 1024 * POX_THRESHOLD_STEPS_USTX);
// produce blocks until epoch 2.4
while get_tip(peer.sortdb.as_ref()).block_height <= epochs[6].start_height {
peer.tenure_with_txs(&[], &mut coinbase_nonce);
}
// repeat the lockups as before, so we can test the pox-3 auto unlock behavior
let tip = get_tip(peer.sortdb.as_ref());
let alice_lockup = make_pox_3_lockup(
&alice,
1,
1024 * POX_THRESHOLD_STEPS_USTX,
PoxAddress::from_legacy(
AddressHashMode::SerializeP2PKH,
key_to_stacks_addr(&alice).bytes,
),
6,
tip.block_height,
);
let bob_lockup = make_pox_3_lockup(
&bob,
1,
1 * POX_THRESHOLD_STEPS_USTX,
PoxAddress::from_legacy(
AddressHashMode::SerializeP2PKH,
key_to_stacks_addr(&bob).bytes,
),
6,
tip.block_height,
);
let txs = if alice_first {
[alice_lockup, bob_lockup]
} else {
[bob_lockup, alice_lockup]
};
latest_block = peer.tenure_with_txs(&txs, &mut coinbase_nonce);
// check that the "raw" reward set will contain entries for alice and bob
// for the pox-3 cycles
for cycle_number in first_v3_cycle..(first_v3_cycle + 6) {
let cycle_start = burnchain.reward_cycle_to_block_height(cycle_number);
let reward_set_entries = get_reward_set_entries_at(&mut peer, &latest_block, cycle_start);
assert_eq!(reward_set_entries.len(), 2);
assert_eq!(
reward_set_entries[0].reward_address.bytes(),
key_to_stacks_addr(&bob).bytes.0.to_vec()
);
assert_eq!(
reward_set_entries[1].reward_address.bytes(),
key_to_stacks_addr(&alice).bytes.0.to_vec()
);
}
// we'll produce blocks until the next reward cycle gets through the "handled start" code
// this is one block after the reward cycle starts
let height_target = burnchain.reward_cycle_to_block_height(first_v3_cycle) + 1;
let second_auto_unlock_coinbase = height_target - 1 - EMPTY_SORTITIONS;
// but first, check that bob has locked tokens at (height_target + 1)
let bob_bal = get_stx_account_at(
&mut peer,
&latest_block,
&key_to_stacks_addr(&bob).to_account_principal(),
);
assert_eq!(bob_bal.amount_locked(), POX_THRESHOLD_STEPS_USTX);
while get_tip(peer.sortdb.as_ref()).block_height < height_target {
latest_block = peer.tenure_with_txs(&[], &mut coinbase_nonce);
}
// check that the "raw" reward sets for all cycles just contains entries for alice
// at the cycle start
for cycle_number in first_v3_cycle..(first_v3_cycle + 6) {
let cycle_start = burnchain.reward_cycle_to_block_height(cycle_number);
let reward_set_entries = get_reward_set_entries_at(&mut peer, &latest_block, cycle_start);
assert_eq!(reward_set_entries.len(), 1);
assert_eq!(
reward_set_entries[0].reward_address.bytes(),
key_to_stacks_addr(&alice).bytes.0.to_vec()
);
}
// now check that bob has an unlock height of `height_target`
let bob_bal = get_stx_account_at(
&mut peer,
&latest_block,
&key_to_stacks_addr(&bob).to_account_principal(),
);
assert_eq!(bob_bal.unlock_height(), height_target);
// but bob's still locked at (height_target): the unlock is accelerated to the "next" burn block
assert_eq!(bob_bal.amount_locked(), 10000000000);
// check that the total reward cycle amounts have decremented correctly
for cycle_number in first_v3_cycle..(first_v3_cycle + 6) {
assert_eq!(
get_reward_cycle_total(&mut peer, &latest_block, cycle_number),
1024 * POX_THRESHOLD_STEPS_USTX
);
}
// check that bob's stacking-state is gone and alice's stacking-state is correct
assert!(
get_stacking_state_pox(
&mut peer,
&latest_block,
&key_to_stacks_addr(&bob).to_account_principal(),
POX_3_NAME,
)
.is_none(),
"Bob should not have a stacking-state entry"
);
let alice_state = get_stacking_state_pox(
&mut peer,
&latest_block,
&key_to_stacks_addr(&alice).to_account_principal(),
POX_3_NAME,
)
.expect("Alice should have stacking-state entry")
.expect_tuple();
let reward_indexes_str = format!("{}", alice_state.get("reward-set-indexes").unwrap());
assert_eq!(reward_indexes_str, "(u0 u0 u0 u0 u0 u0)");
// check that bob is fully unlocked at next block
latest_block = peer.tenure_with_txs(&[], &mut coinbase_nonce);
let bob_bal = get_stx_account_at(
&mut peer,
&latest_block,
&key_to_stacks_addr(&bob).to_account_principal(),
);
assert_eq!(bob_bal.unlock_height(), 0);
assert_eq!(bob_bal.amount_locked(), 0);
// now let's check some tx receipts
let alice_address = key_to_stacks_addr(&alice);
let bob_address = key_to_stacks_addr(&bob);
let blocks = observer.get_blocks();
let mut alice_txs = HashMap::new();
let mut bob_txs = HashMap::new();
let mut coinbase_txs = vec![];
for b in blocks.into_iter() {
for (i, r) in b.receipts.into_iter().enumerate() {
if i == 0 {
coinbase_txs.push(r);
continue;
}
match r.transaction {
TransactionOrigin::Stacks(ref t) => {
let addr = t.auth.origin().address_testnet();
if addr == alice_address {
alice_txs.insert(t.auth.get_origin_nonce(), r);
} else if addr == bob_address {
bob_txs.insert(t.auth.get_origin_nonce(), r);
}
}
_ => {}
}
}
}
assert_eq!(alice_txs.len(), 2);
assert_eq!(bob_txs.len(), 2);
// TX0 -> Bob's initial lockup in PoX 2
assert!(
match bob_txs.get(&0).unwrap().result {
Value::Response(ref r) => r.committed,
_ => false,
},
"Bob tx0 should have committed okay"
);
assert_eq!(coinbase_txs.len(), 38);
info!(
"Expected first auto-unlock coinbase index: {}",
first_auto_unlock_coinbase
);
// Check that the event produced by "handle-unlock" has a well-formed print event
// and that this event is included as part of the coinbase tx
for unlock_coinbase_index in [first_auto_unlock_coinbase, second_auto_unlock_coinbase] {
// expect the unlock to occur 1 block after the handle-unlock method was invoked.
let expected_unlock_height = unlock_coinbase_index + EMPTY_SORTITIONS + 1;
let expected_cycle = pox_constants
.block_height_to_reward_cycle(0, expected_unlock_height)
.unwrap();
let auto_unlock_tx = coinbase_txs[unlock_coinbase_index as usize].events[0].clone();
let pox_addr_val = generate_pox_clarity_value("60c59ab11f7063ef44c16d3dc856f76bbb915eba");
let auto_unlock_op_data = HashMap::from([
("first-cycle-locked", Value::UInt(expected_cycle.into())),
("first-unlocked-cycle", Value::UInt(expected_cycle.into())),
("pox-addr", pox_addr_val),
]);
let common_data = PoxPrintFields {
op_name: "handle-unlock".to_string(),
stacker: Value::Principal(
StacksAddress::from_string("ST1GCB6NH3XR67VT4R5PKVJ2PYXNVQ4AYQATXNP4P")
.unwrap()
.to_account_principal(),
),
balance: Value::UInt(10230000000000),
locked: Value::UInt(10000000000),
burnchain_unlock_height: Value::UInt(expected_unlock_height.into()),
};
check_pox_print_event(&auto_unlock_tx, common_data, auto_unlock_op_data);
}
}
/// In this test case, Alice delegates to Bob.
/// Bob stacks Alice's funds via PoX v2 for 6 cycles. In the third cycle,
/// Bob increases Alice's stacking amount.
///
#[test]
fn delegate_stack_increase() {
let EXPECTED_FIRST_V2_CYCLE = 8;
// the sim environment produces 25 empty sortitions before
// tenures start being tracked.