-
Notifications
You must be signed in to change notification settings - Fork 660
/
pox_4_tests.rs
9508 lines (8579 loc) · 300 KB
/
pox_4_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 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::{STXEventType, STXLockEventData, StacksTransactionEvent};
use clarity::vm::functions::principals;
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 clarity::vm::Value::Optional;
use stacks_common::address::AddressHashMode;
use stacks_common::types::chainstate::{
BlockHeaderHash, BurnchainHeaderHash, StacksAddress, StacksBlockId, VRFSeed,
};
use stacks_common::types::{Address, PrivateKey};
use stacks_common::util::hash::{hex_bytes, to_hex, Sha256Sum, Sha512Trunc256Sum};
use stacks_common::util::secp256k1::{Secp256k1PrivateKey, Secp256k1PublicKey};
use stdext::num::integer::Integer;
use wsts::curve::point::{Compressed, Point};
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::coordinator::tests::pox_addr_from;
use crate::chainstate::nakamoto::test_signers::TestSigners;
use crate::chainstate::nakamoto::tests::node::TestStacker;
use crate::chainstate::stacks::address::{PoxAddress, PoxAddressType20, PoxAddressType32};
use crate::chainstate::stacks::boot::pox_2_tests::{
check_pox_print_event, generate_pox_clarity_value, get_partial_stacked, get_reward_cycle_total,
get_reward_set_entries_at, get_stacking_state_pox, get_stx_account_at, with_clarity_db_ro,
PoxPrintFields, StackingStateCheckData,
};
use crate::chainstate::stacks::boot::signers_tests::{
get_signer_index, prepare_signers_test, readonly_call,
};
use crate::chainstate::stacks::boot::{
PoxVersions, BOOT_CODE_COST_VOTING_TESTNET as BOOT_CODE_COST_VOTING, BOOT_CODE_POX_TESTNET,
MINERS_NAME, POX_2_NAME, POX_3_NAME,
};
use crate::chainstate::stacks::db::{
MinerPaymentSchedule, StacksChainState, StacksHeaderInfo, MINER_REWARD_MATURITY,
};
use crate::chainstate::stacks::events::{StacksTransactionReceipt, 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, TestEventObserverBlock, TestPeer, TestPeerConfig};
use crate::util_lib::boot::boot_code_id;
use crate::util_lib::db::{DBConn, FromRow};
use crate::util_lib::signed_structured_data::pox4::Pox4SignatureTopic;
use crate::util_lib::signed_structured_data::structured_data_message_hash;
const USTX_PER_HOLDER: u128 = 1_000_000;
const ERR_REUSED_SIGNER_KEY: i128 = 33;
/// Return the BlockSnapshot for the latest sortition in the provided
/// SortitionDB option-reference. Panics on any errors.
pub fn get_tip(sortdb: Option<&SortitionDB>) -> BlockSnapshot {
SortitionDB::get_canonical_burn_chain_tip(&sortdb.unwrap().conn()).unwrap()
}
fn make_simple_pox_4_lock(
key: &StacksPrivateKey,
peer: &mut TestPeer,
amount: u128,
lock_period: u128,
) -> StacksTransaction {
let addr = key_to_stacks_addr(key);
let pox_addr = PoxAddress::from_legacy(AddressHashMode::SerializeP2PKH, addr.bytes.clone());
let signer_pk = StacksPublicKey::from_private(&key);
let tip = get_tip(peer.sortdb.as_ref());
let next_reward_cycle = peer
.config
.burnchain
.block_height_to_reward_cycle(tip.block_height)
.unwrap();
let nonce = get_account(peer, &addr.into()).nonce;
let auth_id = u128::from(nonce);
let signature = make_signer_key_signature(
&pox_addr,
&key,
next_reward_cycle.into(),
&Pox4SignatureTopic::StackStx,
lock_period,
amount,
auth_id,
);
make_pox_4_lockup(
key,
nonce,
amount,
&pox_addr,
lock_period,
&signer_pk,
tip.block_height,
Some(signature),
amount,
auth_id,
)
}
pub 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_3_HEIGHT + 4; // 56
let EPOCH_2_5_HEIGHT = EPOCH_2_4_HEIGHT + 44; // 100
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: EPOCH_2_5_HEIGHT,
block_limit: ExecutionCost::max_value(),
network_epoch: PEER_VERSION_EPOCH_2_4,
},
StacksEpoch {
epoch_id: StacksEpochId::Epoch25,
start_height: EPOCH_2_5_HEIGHT,
end_height: STACKS_EPOCH_MAX,
block_limit: ExecutionCost::max_value(),
network_epoch: PEER_VERSION_EPOCH_2_5,
},
];
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 = (EPOCH_2_5_HEIGHT + 1) as u32;
pox_constants.pox_3_activation_height = (EPOCH_2_4_HEIGHT + 1) as u32;
// Activate pox4 2 cycles into epoch 2.5
// Don't use Epoch 3.0 in order to avoid nakamoto blocks
pox_constants.pox_4_activation_height =
(EPOCH_2_5_HEIGHT as u32) + 1 + (2 * pox_constants.reward_cycle_length);
(epochs, pox_constants)
}
#[test]
fn pox_extend_transition() {
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;
let first_v4_cycle = burnchain
.block_height_to_reward_cycle(burnchain.pox_constants.pox_4_activation_height as u64)
.unwrap()
+ 1;
assert_eq!(first_v2_cycle, EXPECTED_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 + 10));
let alice = keys.pop().unwrap();
let bob = keys.pop().unwrap();
let alice_address = key_to_stacks_addr(&alice);
let alice_principal = PrincipalData::from(alice_address.clone());
let bob_address = key_to_stacks_addr(&bob);
let bob_principal = PrincipalData::from(bob_address.clone());
let EXPECTED_ALICE_FIRST_REWARD_CYCLE = 6;
let mut coinbase_nonce = 0;
let INITIAL_BALANCE = 1024 * POX_THRESHOLD_STEPS_USTX;
let ALICE_LOCKUP = 1024 * POX_THRESHOLD_STEPS_USTX;
let BOB_LOCKUP = 512 * POX_THRESHOLD_STEPS_USTX;
// these checks should pass between Alice's first reward cycle,
// and the start of V2 reward cycles
let alice_rewards_to_v2_start_checks = |tip_index_block, peer: &mut TestPeer| {
let tip_burn_block_height = get_par_burn_block_height(peer.chainstate(), &tip_index_block);
let cur_reward_cycle = burnchain
.block_height_to_reward_cycle(tip_burn_block_height)
.unwrap() as u128;
let (min_ustx, reward_addrs, total_stacked) = with_sortdb(peer, |ref mut c, ref sortdb| {
(
c.get_stacking_minimum(sortdb, &tip_index_block).unwrap(),
get_reward_addresses_with_par_tip(c, &burnchain, sortdb, &tip_index_block).unwrap(),
c.test_get_total_ustx_stacked(sortdb, &tip_index_block, cur_reward_cycle)
.unwrap(),
)
});
assert!(
cur_reward_cycle >= EXPECTED_ALICE_FIRST_REWARD_CYCLE
&& cur_reward_cycle < first_v2_cycle as u128
);
// Alice is the only Stacker, so check that.
let (amount_ustx, pox_addr, lock_period, first_reward_cycle) =
get_stacker_info(peer, &key_to_stacks_addr(&alice).into()).unwrap();
eprintln!(
"\nAlice: {} uSTX stacked for {} cycle(s); addr is {:?}; first reward cycle is {}\n",
amount_ustx, lock_period, &pox_addr, first_reward_cycle
);
// one reward address, and it's Alice's
// either way, there's a single reward address
assert_eq!(reward_addrs.len(), 1);
assert_eq!(
(reward_addrs[0].0).version(),
AddressHashMode::SerializeP2PKH as u8
);
assert_eq!(
(reward_addrs[0].0).hash160(),
key_to_stacks_addr(&alice).bytes
);
assert_eq!(reward_addrs[0].1, ALICE_LOCKUP);
};
// these checks should pass after the start of V2 reward cycles
let v2_rewards_checks = |tip_index_block, peer: &mut TestPeer| {
let tip_burn_block_height = get_par_burn_block_height(peer.chainstate(), &tip_index_block);
let cur_reward_cycle = burnchain
.block_height_to_reward_cycle(tip_burn_block_height)
.unwrap() as u128;
let (min_ustx, reward_addrs, total_stacked) = with_sortdb(peer, |ref mut c, ref sortdb| {
(
c.get_stacking_minimum(sortdb, &tip_index_block).unwrap(),
get_reward_addresses_with_par_tip(c, &burnchain, sortdb, &tip_index_block).unwrap(),
c.test_get_total_ustx_stacked(sortdb, &tip_index_block, cur_reward_cycle)
.unwrap(),
)
});
eprintln!(
"reward_cycle = {}, reward_addrs = {}, total_stacked = {}",
cur_reward_cycle,
reward_addrs.len(),
total_stacked
);
assert!(cur_reward_cycle >= first_v2_cycle as u128);
// v2 reward cycles have begun, so reward addrs should be read from PoX2 which is Bob + Alice
assert_eq!(reward_addrs.len(), 2);
assert_eq!(
(reward_addrs[0].0).version(),
AddressHashMode::SerializeP2PKH as u8
);
assert_eq!(
(reward_addrs[0].0).hash160(),
key_to_stacks_addr(&bob).bytes
);
assert_eq!(reward_addrs[0].1, BOB_LOCKUP);
assert_eq!(
(reward_addrs[1].0).version(),
AddressHashMode::SerializeP2PKH as u8
);
assert_eq!(
(reward_addrs[1].0).hash160(),
key_to_stacks_addr(&alice).bytes
);
assert_eq!(reward_addrs[1].1, ALICE_LOCKUP);
};
// first tenure is empty
let mut latest_block = peer.tenure_with_txs(&[], &mut coinbase_nonce);
let alice_account = get_account(&mut peer, &key_to_stacks_addr(&alice).into());
assert_eq!(alice_account.stx_balance.amount_unlocked(), INITIAL_BALANCE);
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,
ALICE_LOCKUP,
AddressHashMode::SerializeP2PKH,
key_to_stacks_addr(&alice).bytes,
4,
tip.block_height,
);
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, |chainstate, 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, |chainstate, 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();
assert_eq!(
alice_first_reward_cycle as u128,
EXPECTED_ALICE_FIRST_REWARD_CYCLE
);
let height_target = burnchain.reward_cycle_to_block_height(alice_first_reward_cycle) + 1;
// 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);
while get_tip(peer.sortdb.as_ref()).block_height < height_target {
latest_block = peer.tenure_with_txs(&[], &mut coinbase_nonce);
}
// 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);
alice_rewards_to_v2_start_checks(latest_block, &mut peer);
}
// in the next tenure, PoX 2 should now exist.
// Lets have Bob lock up for v2
// this will lock for cycles 8, 9, 10
// the first v2 cycle will be 8
let tip = get_tip(peer.sortdb.as_ref());
let bob_lockup = make_pox_2_lockup(
&bob,
0,
BOB_LOCKUP,
PoxAddress::from_legacy(
AddressHashMode::SerializeP2PKH,
key_to_stacks_addr(&bob).bytes,
),
3,
tip.block_height,
);
// Alice _will_ auto-unlock: she can stack-extend in PoX v2
let alice_lockup = make_pox_2_extend(
&alice,
1,
PoxAddress::from_legacy(
AddressHashMode::SerializeP2PKH,
key_to_stacks_addr(&alice).bytes,
),
6,
);
latest_block = peer.tenure_with_txs(&[bob_lockup, alice_lockup], &mut coinbase_nonce);
alice_rewards_to_v2_start_checks(latest_block, &mut peer);
// Extend bob's lockup via `stack-extend` for 1 more cycle
let bob_extend = make_pox_2_extend(
&bob,
1,
PoxAddress::from_legacy(
AddressHashMode::SerializeP2PKH,
key_to_stacks_addr(&bob).bytes,
),
1,
);
latest_block = peer.tenure_with_txs(&[bob_extend], &mut coinbase_nonce);
alice_rewards_to_v2_start_checks(latest_block, &mut peer);
// produce blocks until the v2 reward cycles start
let height_target = burnchain.reward_cycle_to_block_height(first_v2_cycle) - 1;
while get_tip(peer.sortdb.as_ref()).block_height < height_target {
latest_block = 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);
alice_rewards_to_v2_start_checks(latest_block, &mut peer);
}
latest_block = peer.tenure_with_txs(&[], &mut coinbase_nonce);
v2_rewards_checks(latest_block, &mut peer);
// roll the chain forward until just before Epoch-2.2
while get_tip(peer.sortdb.as_ref()).block_height < epochs[4].start_height {
latest_block = peer.tenure_with_txs(&[], &mut coinbase_nonce);
// at this point, alice's balance should be locked, and so should bob's
let alice_balance = get_balance(&mut peer, &key_to_stacks_addr(&alice).into());
assert_eq!(alice_balance, 0);
let bob_balance = get_balance(&mut peer, &key_to_stacks_addr(&bob).into());
assert_eq!(bob_balance, 512 * POX_THRESHOLD_STEPS_USTX);
}
// this block is mined in epoch-2.2
latest_block = 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);
let bob_balance = get_balance(&mut peer, &key_to_stacks_addr(&bob).into());
assert_eq!(bob_balance, 512 * POX_THRESHOLD_STEPS_USTX);
// this block should unlock alice and bob's balance
latest_block = peer.tenure_with_txs(&[], &mut coinbase_nonce);
let alice_account = get_stx_account_at(&mut peer, &latest_block, &alice_principal);
let bob_account = get_stx_account_at(&mut peer, &latest_block, &bob_principal);
assert_eq!(alice_account.amount_locked(), 0);
assert_eq!(alice_account.amount_unlocked(), INITIAL_BALANCE);
assert_eq!(bob_account.amount_locked(), 0);
assert_eq!(bob_account.amount_unlocked(), INITIAL_BALANCE);
// Roll to pox4 activation and re-do the above stack-extend tests
while get_tip(peer.sortdb.as_ref()).block_height
< u64::from(burnchain.pox_constants.pox_4_activation_height)
{
latest_block = peer.tenure_with_txs(&[], &mut coinbase_nonce);
}
let tip = get_tip(peer.sortdb.as_ref());
let alice_signer_private = Secp256k1PrivateKey::new();
let alice_signer_key = Secp256k1PublicKey::from_private(&alice_signer_private);
let reward_cycle = get_current_reward_cycle(&peer, &burnchain);
let alice_pox_addr = PoxAddress::from_legacy(
AddressHashMode::SerializeP2PKH,
key_to_stacks_addr(&alice).bytes,
);
let auth_id = 1;
let alice_signature = make_signer_key_signature(
&alice_pox_addr,
&alice_signer_private,
reward_cycle,
&Pox4SignatureTopic::StackStx,
4_u128,
u128::MAX,
auth_id,
);
let alice_stack_signature = alice_signature.clone();
let alice_stack_signer_key = alice_signer_key.clone();
let alice_lockup = make_pox_4_lockup(
&alice,
2,
ALICE_LOCKUP,
&PoxAddress::from_legacy(
AddressHashMode::SerializeP2PKH,
key_to_stacks_addr(&alice).bytes,
),
4,
&alice_signer_key,
tip.block_height,
Some(alice_signature),
u128::MAX,
auth_id,
);
let alice_pox_4_lock_nonce = 2;
let alice_first_pox_4_unlock_height =
burnchain.reward_cycle_to_block_height(first_v4_cycle + 4) - 1;
let alice_pox_4_start_burn_height = tip.block_height;
latest_block = peer.tenure_with_txs(&[alice_lockup], &mut coinbase_nonce);
info!(
"Block height: {}",
get_tip(peer.sortdb.as_ref()).block_height
);
// check that the "raw" reward set will contain entries for alice at the cycle start
for cycle_number in first_v4_cycle..(first_v4_cycle + 4) {
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()
);
assert_eq!(reward_set_entries[0].amount_stacked, ALICE_LOCKUP,);
}
// check the first reward cycle when Alice's tokens get stacked
let tip_burn_block_height = get_par_burn_block_height(peer.chainstate(), &latest_block);
let alice_first_v4_reward_cycle = 1 + burnchain
.block_height_to_reward_cycle(tip_burn_block_height)
.unwrap();
let height_target = burnchain.reward_cycle_to_block_height(alice_first_v4_reward_cycle) + 1;
// alice locked, so balance should be 0
let alice_balance = get_balance(&mut peer, &alice_principal);
assert_eq!(alice_balance, 0);
// advance to the first v3 reward cycle
while get_tip(peer.sortdb.as_ref()).block_height < height_target {
latest_block = peer.tenure_with_txs(&[], &mut coinbase_nonce);
}
let bob_signer_private = Secp256k1PrivateKey::new();
let reward_cycle = get_current_reward_cycle(&peer, &burnchain);
let bob_pox_addr = PoxAddress::from_legacy(
AddressHashMode::SerializeP2PKH,
key_to_stacks_addr(&bob).bytes,
);
let bob_signature = make_signer_key_signature(
&bob_pox_addr,
&bob_signer_private,
reward_cycle,
&Pox4SignatureTopic::StackStx,
3_u128,
u128::MAX,
2,
);
let tip = get_tip(peer.sortdb.as_ref());
let bob_lockup = make_pox_4_lockup(
&bob,
2,
BOB_LOCKUP,
&bob_pox_addr,
3,
&StacksPublicKey::from_private(&bob_signer_private),
tip.block_height,
Some(bob_signature),
u128::MAX,
2,
);
// new signing key needed
let alice_signer_private = Secp256k1PrivateKey::default();
let alice_signer_key = StacksPublicKey::from_private(&alice_signer_private);
let alice_signature = make_signer_key_signature(
&alice_pox_addr,
&alice_signer_private,
reward_cycle,
&Pox4SignatureTopic::StackExtend,
6_u128,
u128::MAX,
3,
);
// Alice can stack-extend in PoX v2
let alice_lockup = make_pox_4_extend(
&alice,
3,
alice_pox_addr.clone(),
6,
alice_signer_key.clone(),
Some(alice_signature.clone()),
u128::MAX,
3,
);
let alice_pox_4_extend_nonce = 3;
let alice_extend_pox_4_unlock_height =
burnchain.reward_cycle_to_block_height(first_v4_cycle + 10) - 1;
latest_block = peer.tenure_with_txs(&[bob_lockup, alice_lockup], &mut coinbase_nonce);
// check that the "raw" reward set will contain entries for alice at the cycle start
for cycle_number in first_v4_cycle..(first_v4_cycle + 1) {
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()
);
assert_eq!(reward_set_entries[0].amount_stacked, ALICE_LOCKUP);
}
for cycle_number in (first_v4_cycle + 1)..(first_v4_cycle + 4) {
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[1].reward_address.bytes(),
key_to_stacks_addr(&alice).bytes.0.to_vec()
);
assert_eq!(reward_set_entries[1].amount_stacked, ALICE_LOCKUP);
assert_eq!(
reward_set_entries[0].reward_address.bytes(),
key_to_stacks_addr(&bob).bytes.0.to_vec()
);
assert_eq!(reward_set_entries[0].amount_stacked, BOB_LOCKUP);
}
for cycle_number in (first_v4_cycle + 4)..(first_v4_cycle + 10) {
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()
);
assert_eq!(reward_set_entries[0].amount_stacked, ALICE_LOCKUP);
}
// 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();
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();
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(), 4);
assert_eq!(bob_txs.len(), 3);
for tx in alice_txs.iter() {
assert!(
if let Value::Response(ref r) = tx.1.result {
r.committed
} else {
false
},
"Alice txs should all have committed okay"
);
}
for tx in bob_txs.iter() {
assert!(
if let Value::Response(ref r) = tx.1.result {
r.committed
} else {
false
},
"Bob txs should all have committed okay"
);
}
// Check that the call to `stack-stx` has a well-formed print event.
let stack_tx = &alice_txs
.get(&alice_pox_4_lock_nonce)
.unwrap()
.clone()
.events[0];
let pox_addr_val = generate_pox_clarity_value("ae1593226f85e49a7eaff5b633ff687695438cc9");
let stack_op_data = HashMap::from([
("lock-amount", Value::UInt(ALICE_LOCKUP)),
(
"unlock-burn-height",
Value::UInt(alice_first_pox_4_unlock_height.into()),
),
(
"start-burn-height",
Value::UInt(alice_pox_4_start_burn_height.into()),
),
("pox-addr", pox_addr_val.clone()),
("lock-period", Value::UInt(4)),
(
"signer-sig",
Value::some(Value::buff_from(alice_stack_signature).unwrap()).unwrap(),
),
(
"signer-key",
Value::buff_from(alice_stack_signer_key.to_bytes_compressed()).unwrap(),
),
("max-amount", Value::UInt(u128::MAX)),
("auth-id", Value::UInt(1)),
]);
let common_data = PoxPrintFields {
op_name: "stack-stx".to_string(),
stacker: Value::Principal(alice_principal.clone()),
balance: Value::UInt(10240000000000),
locked: Value::UInt(0),
burnchain_unlock_height: Value::UInt(0),
};
check_pox_print_event(stack_tx, common_data, stack_op_data);
// Check that the call to `stack-extend` has a well-formed print event.
let stack_extend_tx = &alice_txs
.get(&alice_pox_4_extend_nonce)
.unwrap()
.clone()
.events[0];
let stack_ext_op_data = HashMap::from([
("extend-count", Value::UInt(6)),
("pox-addr", pox_addr_val),
(
"unlock-burn-height",
Value::UInt(alice_extend_pox_4_unlock_height.into()),
),
]);
let common_data = PoxPrintFields {
op_name: "stack-extend".to_string(),
stacker: Value::Principal(alice_principal.clone()),
balance: Value::UInt(0),
locked: Value::UInt(ALICE_LOCKUP),
burnchain_unlock_height: Value::UInt(alice_first_pox_4_unlock_height.into()),
};
check_pox_print_event(stack_extend_tx, common_data, stack_ext_op_data);
}
fn get_burn_pox_addr_info(peer: &mut TestPeer) -> (Vec<PoxAddress>, u128) {
let tip = get_tip(peer.sortdb.as_ref());
let tip_index_block = tip.get_canonical_stacks_block_id();
let burn_height = tip.block_height - 1;
let addrs_and_payout = with_sortdb(peer, |ref mut chainstate, ref mut sortdb| {
let addrs = chainstate
.maybe_read_only_clarity_tx(
&sortdb.index_handle_at_tip(),
&tip_index_block,
|clarity_tx| {
clarity_tx
.with_readonly_clarity_env(
false,
0x80000000,
ClarityVersion::Clarity2,
PrincipalData::Standard(StandardPrincipalData::transient()),
None,
LimitedCostTracker::new_free(),
|env| {
env.eval_read_only(
&boot_code_id("pox-2", false),
&format!("(get-burn-block-info? pox-addrs u{})", &burn_height),
)
},
)
.unwrap()
},
)
.unwrap();
addrs
})
.unwrap()
.expect_optional()
.unwrap()
.unwrap()
.expect_tuple()
.unwrap();
let addrs = addrs_and_payout
.get("addrs")
.unwrap()
.to_owned()
.expect_list()
.unwrap()
.into_iter()
.map(|tuple| PoxAddress::try_from_pox_tuple(false, &tuple).unwrap())
.collect();
let payout = addrs_and_payout
.get("payout")
.unwrap()
.to_owned()
.expect_u128()
.unwrap();
(addrs, payout)
}
/// Test that we can lock STX for a couple cycles after pox4 starts,
/// and that it unlocks after the desired number of cycles
#[test]
fn pox_lock_unlock() {
// Config for this test
// We are going to try locking for 2 reward cycles (10 blocks)
let lock_period = 2;
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 (mut peer, keys) =
instantiate_pox_peer_with_epoch(&burnchain, function_name!(), Some(epochs.clone()), None);
assert_eq!(burnchain.pox_constants.reward_slots(), 6);
let mut coinbase_nonce = 0;
let mut latest_block = None;
// Advance into pox4
let target_height = burnchain.pox_constants.pox_4_activation_height;
// produce blocks until the first reward phase that everyone should be in
while get_tip(peer.sortdb.as_ref()).block_height < u64::from(target_height) {
latest_block = Some(peer.tenure_with_txs(&[], &mut coinbase_nonce));
// if we reach epoch 2.1, perform the check
if get_tip(peer.sortdb.as_ref()).block_height > epochs[3].start_height {
assert_latest_was_burn(&mut peer);
}
}
info!(
"Block height: {}",
get_tip(peer.sortdb.as_ref()).block_height
);
let mut txs = vec![];
let tip_height = get_tip(peer.sortdb.as_ref()).block_height;
let reward_cycle = burnchain.block_height_to_reward_cycle(tip_height).unwrap() as u128;
let stackers: Vec<_> = keys
.iter()
.zip([
AddressHashMode::SerializeP2PKH,
AddressHashMode::SerializeP2SH,
AddressHashMode::SerializeP2WPKH,
AddressHashMode::SerializeP2WSH,
])
.enumerate()
.map(|(ix, (key, hash_mode))| {
let pox_addr = PoxAddress::from_legacy(hash_mode, key_to_stacks_addr(key).bytes);
let lock_period = if ix == 3 { 12 } else { lock_period };
let signer_key = key;
let signature = make_signer_key_signature(
&pox_addr,
&signer_key,
reward_cycle,
&Pox4SignatureTopic::StackStx,
lock_period.into(),
u128::MAX,
1,
);
txs.push(make_pox_4_lockup(
key,
0,
1024 * POX_THRESHOLD_STEPS_USTX,
&pox_addr,
lock_period,
&StacksPublicKey::from_private(&signer_key),
tip_height,
Some(signature),
u128::MAX,
1,
));
pox_addr
})
.collect();
info!("Submitting stacking txs");
let mut latest_block = peer.tenure_with_txs(&txs, &mut coinbase_nonce);
// Advance to start of rewards cycle stackers are participating in
let target_height = burnchain.pox_constants.pox_4_activation_height + 5;
while get_tip(peer.sortdb.as_ref()).block_height < u64::from(target_height) {
latest_block = peer.tenure_with_txs(&[], &mut coinbase_nonce);
}
info!(
"Block height: {}",
get_tip(peer.sortdb.as_ref()).block_height
);
// now we should be in the reward phase, produce the reward blocks
let reward_blocks =
burnchain.pox_constants.reward_cycle_length - burnchain.pox_constants.prepare_length;
let mut rewarded = HashSet::new();
// Check that STX are locked for 2 reward cycles
for _ in 0..lock_period {
let tip = get_tip(peer.sortdb.as_ref());
let cycle = burnchain
.block_height_to_reward_cycle(tip.block_height)
.unwrap();
info!("Checking that stackers have STX locked for cycle {cycle}");
let balances = balances_from_keys(&mut peer, &latest_block, &keys);
assert!(balances[0].amount_locked() > 0);
assert!(balances[1].amount_locked() > 0);
assert!(balances[2].amount_locked() > 0);
assert!(balances[3].amount_locked() > 0);
info!("Checking we have 2 stackers for cycle {cycle}");
for i in 0..reward_blocks {
latest_block = peer.tenure_with_txs(&[], &mut coinbase_nonce);