-
Notifications
You must be signed in to change notification settings - Fork 667
/
v0.rs
4845 lines (4363 loc) · 186 KB
/
v0.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) 2020-2024 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};
use std::ops::Add;
use std::str::FromStr;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use std::{env, thread};
use clarity::vm::types::PrincipalData;
use clarity::vm::StacksEpoch;
use libsigner::v0::messages::{
BlockRejection, BlockResponse, MessageSlotID, MinerSlotID, RejectCode, SignerMessage,
};
use libsigner::{BlockProposal, SignerSession, StackerDBSession};
use stacks::address::AddressHashMode;
use stacks::chainstate::burn::db::sortdb::SortitionDB;
use stacks::chainstate::nakamoto::{NakamotoBlock, NakamotoBlockHeader, NakamotoChainState};
use stacks::chainstate::stacks::address::PoxAddress;
use stacks::chainstate::stacks::boot::MINERS_NAME;
use stacks::chainstate::stacks::db::{StacksBlockHeaderTypes, StacksChainState, StacksHeaderInfo};
use stacks::codec::StacksMessageCodec;
use stacks::core::{StacksEpochId, CHAIN_ID_TESTNET};
use stacks::libstackerdb::StackerDBChunkData;
use stacks::net::api::postblock_proposal::{ValidateRejectCode, TEST_VALIDATE_STALL};
use stacks::net::relay::fault_injection::set_ignore_block;
use stacks::types::chainstate::{StacksAddress, StacksBlockId, StacksPrivateKey, StacksPublicKey};
use stacks::types::PublicKey;
use stacks::util::hash::MerkleHashFunc;
use stacks::util::secp256k1::{Secp256k1PrivateKey, Secp256k1PublicKey};
use stacks::util_lib::boot::boot_code_id;
use stacks::util_lib::signed_structured_data::pox4::{
make_pox_4_signer_key_signature, Pox4SignatureTopic,
};
use stacks_common::bitvec::BitVec;
use stacks_common::types::chainstate::TrieHash;
use stacks_common::util::sleep_ms;
use stacks_signer::chainstate::{ProposalEvalConfig, SortitionsView};
use stacks_signer::client::{SignerSlotID, StackerDB};
use stacks_signer::config::{build_signer_config_tomls, GlobalConfig as SignerConfig, Network};
use stacks_signer::v0::signer::{
TEST_IGNORE_ALL_BLOCK_PROPOSALS, TEST_PAUSE_BLOCK_BROADCAST, TEST_REJECT_ALL_BLOCK_PROPOSAL,
TEST_SKIP_BLOCK_BROADCAST,
};
use stacks_signer::v0::SpawnedSigner;
use tracing_subscriber::prelude::*;
use tracing_subscriber::{fmt, EnvFilter};
use super::SignerTest;
use crate::config::{EventKeyType, EventObserverConfig};
use crate::event_dispatcher::MinedNakamotoBlockEvent;
use crate::nakamoto_node::miner::{TEST_BLOCK_ANNOUNCE_STALL, TEST_BROADCAST_STALL};
use crate::nakamoto_node::sign_coordinator::TEST_IGNORE_SIGNERS;
use crate::neon::Counters;
use crate::run_loop::boot_nakamoto;
use crate::tests::nakamoto_integrations::{
boot_to_epoch_25, boot_to_epoch_3_reward_set, next_block_and, setup_epoch_3_reward_set,
wait_for, POX_4_DEFAULT_STACKER_BALANCE, POX_4_DEFAULT_STACKER_STX_AMT,
};
use crate::tests::neon_integrations::{
get_account, get_chain_info, get_chain_info_opt, next_block_and_wait,
run_until_burnchain_height, submit_tx, submit_tx_fallible, test_observer,
};
use crate::tests::{self, make_stacks_transfer};
use crate::{nakamoto_node, BurnchainController, Config, Keychain};
impl SignerTest<SpawnedSigner> {
/// Run the test until the first epoch 2.5 reward cycle.
/// Will activate pox-4 and register signers for the first full Epoch 2.5 reward cycle.
fn boot_to_epoch_25_reward_cycle(&mut self) {
boot_to_epoch_25(
&self.running_nodes.conf,
&self.running_nodes.blocks_processed,
&mut self.running_nodes.btc_regtest_controller,
);
next_block_and_wait(
&mut self.running_nodes.btc_regtest_controller,
&self.running_nodes.blocks_processed,
);
let http_origin = format!("http://{}", &self.running_nodes.conf.node.rpc_bind);
let lock_period = 12;
let epochs = self.running_nodes.conf.burnchain.epochs.clone().unwrap();
let epoch_25 =
&epochs[StacksEpoch::find_epoch_by_id(&epochs, StacksEpochId::Epoch25).unwrap()];
let epoch_25_start_height = epoch_25.start_height;
// stack enough to activate pox-4
let block_height = self
.running_nodes
.btc_regtest_controller
.get_headers_height();
let reward_cycle = self
.running_nodes
.btc_regtest_controller
.get_burnchain()
.block_height_to_reward_cycle(block_height)
.unwrap();
for stacker_sk in self.signer_stacks_private_keys.iter() {
let pox_addr = PoxAddress::from_legacy(
AddressHashMode::SerializeP2PKH,
tests::to_addr(&stacker_sk).bytes,
);
let pox_addr_tuple: clarity::vm::Value =
pox_addr.clone().as_clarity_tuple().unwrap().into();
let signature = make_pox_4_signer_key_signature(
&pox_addr,
&stacker_sk,
reward_cycle.into(),
&Pox4SignatureTopic::StackStx,
CHAIN_ID_TESTNET,
lock_period,
u128::MAX,
1,
)
.unwrap()
.to_rsv();
let signer_pk = StacksPublicKey::from_private(stacker_sk);
let stacking_tx = tests::make_contract_call(
&stacker_sk,
0,
1000,
&StacksAddress::burn_address(false),
"pox-4",
"stack-stx",
&[
clarity::vm::Value::UInt(POX_4_DEFAULT_STACKER_STX_AMT),
pox_addr_tuple.clone(),
clarity::vm::Value::UInt(block_height as u128),
clarity::vm::Value::UInt(lock_period),
clarity::vm::Value::some(clarity::vm::Value::buff_from(signature).unwrap())
.unwrap(),
clarity::vm::Value::buff_from(signer_pk.to_bytes_compressed()).unwrap(),
clarity::vm::Value::UInt(u128::MAX),
clarity::vm::Value::UInt(1),
],
);
submit_tx(&http_origin, &stacking_tx);
}
next_block_and_wait(
&mut self.running_nodes.btc_regtest_controller,
&self.running_nodes.blocks_processed,
);
next_block_and_wait(
&mut self.running_nodes.btc_regtest_controller,
&self.running_nodes.blocks_processed,
);
let reward_cycle_len = self
.running_nodes
.conf
.get_burnchain()
.pox_constants
.reward_cycle_length as u64;
let epoch_25_reward_cycle_boundary =
epoch_25_start_height.saturating_sub(epoch_25_start_height % reward_cycle_len);
let next_reward_cycle_boundary =
epoch_25_reward_cycle_boundary.wrapping_add(reward_cycle_len);
let target_height = next_reward_cycle_boundary - 1;
info!("Advancing to burn block height {target_height}...",);
run_until_burnchain_height(
&mut self.running_nodes.btc_regtest_controller,
&self.running_nodes.blocks_processed,
target_height,
&self.running_nodes.conf,
);
debug!("Waiting for signer set calculation.");
let mut reward_set_calculated = false;
let short_timeout = Duration::from_secs(60);
let now = std::time::Instant::now();
// Make sure the signer set is calculated before continuing or signers may not
// recognize that they are registered signers in the subsequent burn block event
let reward_cycle = self.get_current_reward_cycle().wrapping_add(1);
while !reward_set_calculated {
let reward_set = self
.stacks_client
.get_reward_set_signers(reward_cycle)
.expect("Failed to check if reward set is calculated");
reward_set_calculated = reward_set.is_some();
if reward_set_calculated {
debug!("Signer set: {:?}", reward_set.unwrap());
}
std::thread::sleep(Duration::from_secs(1));
assert!(
now.elapsed() < short_timeout,
"Timed out waiting for reward set calculation"
);
}
debug!("Signer set calculated");
// Manually consume one more block to ensure signers refresh their state
debug!("Waiting for signers to initialize.");
info!("Advancing to the first full Epoch 2.5 reward cycle boundary...");
next_block_and_wait(
&mut self.running_nodes.btc_regtest_controller,
&self.running_nodes.blocks_processed,
);
self.wait_for_registered(30);
debug!("Signers initialized");
let current_burn_block_height = self
.running_nodes
.btc_regtest_controller
.get_headers_height();
info!("At burn block height {current_burn_block_height}. Ready to mine the first Epoch 2.5 reward cycle!");
}
/// Run the test until the epoch 3 boundary
fn boot_to_epoch_3(&mut self) {
boot_to_epoch_3_reward_set(
&self.running_nodes.conf,
&self.running_nodes.blocks_processed,
&self.signer_stacks_private_keys,
&self.signer_stacks_private_keys,
&mut self.running_nodes.btc_regtest_controller,
Some(self.num_stacking_cycles),
);
info!("Waiting for signer set calculation.");
let mut reward_set_calculated = false;
let short_timeout = Duration::from_secs(60);
let now = std::time::Instant::now();
// Make sure the signer set is calculated before continuing or signers may not
// recognize that they are registered signers in the subsequent burn block event
let reward_cycle = self.get_current_reward_cycle() + 1;
while !reward_set_calculated {
let reward_set = self
.stacks_client
.get_reward_set_signers(reward_cycle)
.expect("Failed to check if reward set is calculated");
reward_set_calculated = reward_set.is_some();
if reward_set_calculated {
debug!("Signer set: {:?}", reward_set.unwrap());
}
std::thread::sleep(Duration::from_secs(1));
assert!(
now.elapsed() < short_timeout,
"Timed out waiting for reward set calculation"
);
}
info!("Signer set calculated");
// Manually consume one more block to ensure signers refresh their state
info!("Waiting for signers to initialize.");
next_block_and_wait(
&mut self.running_nodes.btc_regtest_controller,
&self.running_nodes.blocks_processed,
);
self.wait_for_registered(30);
info!("Signers initialized");
self.run_until_epoch_3_boundary();
std::thread::sleep(Duration::from_secs(1));
wait_for(60, || {
Ok(get_chain_info_opt(&self.running_nodes.conf).is_some())
})
.expect("Timed out waiting for network to restart after 3.0 boundary reached");
// Wait until we see the first block of epoch 3.0.
// Note, we don't use `nakamoto_blocks_mined` counter, because there
// could be other miners mining blocks.
let height_before = get_chain_info(&self.running_nodes.conf).stacks_tip_height;
info!("Waiting for first Nakamoto block: {}", height_before + 1);
next_block_and(&mut self.running_nodes.btc_regtest_controller, 60, || {
let height = get_chain_info(&self.running_nodes.conf).stacks_tip_height;
Ok(height > height_before)
})
.unwrap();
info!("Ready to mine Nakamoto blocks!");
}
// Only call after already past the epoch 3.0 boundary
fn mine_and_verify_confirmed_naka_block(&mut self, timeout: Duration, num_signers: usize) {
info!("------------------------- Try mining one block -------------------------");
let reward_cycle = self.get_current_reward_cycle();
self.mine_nakamoto_block(timeout);
// Verify that the signers accepted the proposed block, sending back a validate ok response
let proposed_signer_signature_hash = self
.wait_for_validate_ok_response(timeout)
.signer_signature_hash;
let message = proposed_signer_signature_hash.0;
info!("------------------------- Test Block Signed -------------------------");
// Verify that the signers signed the proposed block
let signature = self.wait_for_confirmed_block_v0(&proposed_signer_signature_hash, timeout);
info!("Got {} signatures", signature.len());
// NOTE: signature.len() does not need to equal signers.len(); the stacks miner can finish the block
// whenever it has crossed the threshold.
assert!(signature.len() >= num_signers * 7 / 10);
info!(
"Verifying signatures against signers for reward cycle {:?}",
reward_cycle
);
let signers = self.get_reward_set_signers(reward_cycle);
// Verify that the signers signed the proposed block
let mut signer_index = 0;
let mut signature_index = 0;
let mut signing_keys = HashSet::new();
let start = Instant::now();
debug!(
"Validating {} signatures against {num_signers} signers",
signature.len()
);
let validated = loop {
// Since we've already checked `signature.len()`, this means we've
// validated all the signatures in this loop
let Some(signature) = signature.get(signature_index) else {
break true;
};
let Some(signer) = signers.get(signer_index) else {
error!("Failed to validate the mined nakamoto block: ran out of signers to try to validate signatures");
break false;
};
if !signing_keys.insert(signer.signing_key) {
panic!("Duplicate signing key detected: {:?}", signer.signing_key);
}
let stacks_public_key = Secp256k1PublicKey::from_slice(signer.signing_key.as_slice())
.expect("Failed to convert signing key to StacksPublicKey");
let valid = stacks_public_key
.verify(&message, signature)
.expect("Failed to verify signature");
if !valid {
info!(
"Failed to verify signature for signer, will attempt to validate without this signer";
"signer_pk" => stacks_public_key.to_hex(),
"signer_index" => signer_index,
"signature_index" => signature_index,
);
signer_index += 1;
} else {
signer_index += 1;
signature_index += 1;
}
// Shouldn't really ever timeout, but do this in case there is some sort of overflow/underflow happening.
assert!(
start.elapsed() < timeout,
"Timed out waiting to confirm block signatures"
);
};
assert!(validated);
}
// Only call after already past the epoch 3.0 boundary
fn run_until_burnchain_height_nakamoto(
&mut self,
timeout: Duration,
burnchain_height: u64,
num_signers: usize,
) {
let current_block_height = self
.running_nodes
.btc_regtest_controller
.get_headers_height();
let total_nmb_blocks_to_mine = burnchain_height.saturating_sub(current_block_height);
debug!("Mining {total_nmb_blocks_to_mine} Nakamoto block(s) to reach burnchain height {burnchain_height}");
for _ in 0..total_nmb_blocks_to_mine {
self.mine_and_verify_confirmed_naka_block(timeout, num_signers);
}
}
/// Propose an invalid block to the signers
fn propose_block(&mut self, block: NakamotoBlock, timeout: Duration) {
let miners_contract_id = boot_code_id(MINERS_NAME, false);
let mut session =
StackerDBSession::new(&self.running_nodes.conf.node.rpc_bind, miners_contract_id);
let burn_height = self
.running_nodes
.btc_regtest_controller
.get_headers_height();
let reward_cycle = self.get_current_reward_cycle();
let message = SignerMessage::BlockProposal(BlockProposal {
block,
burn_height,
reward_cycle,
});
let miner_sk = self
.running_nodes
.conf
.miner
.mining_key
.expect("No mining key");
// Submit the block proposal to the miner's slot
let mut accepted = false;
let mut version = 0;
let slot_id = MinerSlotID::BlockProposal.to_u8() as u32;
let start = Instant::now();
debug!("Proposing invalid block to signers");
while !accepted {
let mut chunk =
StackerDBChunkData::new(slot_id * 2, version, message.serialize_to_vec());
chunk.sign(&miner_sk).expect("Failed to sign message chunk");
debug!("Produced a signature: {:?}", chunk.sig);
let result = session.put_chunk(&chunk).expect("Failed to put chunk");
accepted = result.accepted;
version += 1;
debug!("Test Put Chunk ACK: {result:?}");
assert!(
start.elapsed() < timeout,
"Timed out waiting for block proposal to be accepted"
);
}
}
}
#[test]
#[ignore]
/// Test that a signer can respond to an invalid block proposal
///
/// Test Setup:
/// The test spins up five stacks signers, one miner Nakamoto node, and a corresponding bitcoind.
///
/// Test Execution:
/// The stacks node is advanced to epoch 3.0 reward set calculation to ensure the signer set is determined.
/// An invalid block proposal is forcibly written to the miner's slot to simulate the miner proposing a block.
/// The signers process the invalid block by first verifying it against the stacks node block proposal endpoint.
/// The signers then broadcast a rejection of the miner's proposed block back to the respective .signers-XXX-YYY contract.
///
/// Test Assertion:
/// Each signer successfully rejects the invalid block proposal.
fn block_proposal_rejection() {
if env::var("BITCOIND_TEST") != Ok("1".into()) {
return;
}
tracing_subscriber::registry()
.with(fmt::layer())
.with(EnvFilter::from_default_env())
.init();
info!("------------------------- Test Setup -------------------------");
let num_signers = 5;
let mut signer_test: SignerTest<SpawnedSigner> = SignerTest::new(num_signers, vec![]);
signer_test.boot_to_epoch_3();
let short_timeout = Duration::from_secs(30);
info!("------------------------- Send Block Proposal To Signers -------------------------");
let proposal_conf = ProposalEvalConfig {
first_proposal_burn_block_timing: Duration::from_secs(0),
block_proposal_timeout: Duration::from_secs(100),
};
let mut block = NakamotoBlock {
header: NakamotoBlockHeader::empty(),
txs: vec![],
};
// First propose a block to the signers that does not have the correct consensus hash or BitVec. This should be rejected BEFORE
// the block is submitted to the node for validation.
let block_signer_signature_hash_1 = block.header.signer_signature_hash();
signer_test.propose_block(block.clone(), short_timeout);
// Wait for the first block to be mined successfully so we have the most up to date sortition view
signer_test.wait_for_validate_ok_response(short_timeout);
// Propose a block to the signers that passes initial checks but will be rejected by the stacks node
let view = SortitionsView::fetch_view(proposal_conf, &signer_test.stacks_client).unwrap();
block.header.pox_treatment = BitVec::ones(1).unwrap();
block.header.consensus_hash = view.cur_sortition.consensus_hash;
block.header.chain_length = 35; // We have mined 35 blocks so far.
let block_signer_signature_hash_2 = block.header.signer_signature_hash();
signer_test.propose_block(block, short_timeout);
info!("------------------------- Test Block Proposal Rejected -------------------------");
// Verify the signers rejected the second block via the endpoint
let reject =
signer_test.wait_for_validate_reject_response(short_timeout, block_signer_signature_hash_2);
assert!(matches!(
reject.reason_code,
ValidateRejectCode::UnknownParent
));
let start_polling = Instant::now();
let mut found_signer_signature_hash_1 = false;
let mut found_signer_signature_hash_2 = false;
while !found_signer_signature_hash_1 && !found_signer_signature_hash_2 {
std::thread::sleep(Duration::from_secs(1));
let chunks = test_observer::get_stackerdb_chunks();
for chunk in chunks.into_iter().flat_map(|chunk| chunk.modified_slots) {
let Ok(message) = SignerMessage::consensus_deserialize(&mut chunk.data.as_slice())
else {
continue;
};
if let SignerMessage::BlockResponse(BlockResponse::Rejected(BlockRejection {
reason: _reason,
reason_code,
signer_signature_hash,
..
})) = message
{
if signer_signature_hash == block_signer_signature_hash_1 {
found_signer_signature_hash_1 = true;
assert!(matches!(reason_code, RejectCode::SortitionViewMismatch));
} else if signer_signature_hash == block_signer_signature_hash_2 {
found_signer_signature_hash_2 = true;
assert!(matches!(reason_code, RejectCode::ValidationFailed(_)));
} else {
continue;
}
} else {
continue;
}
}
assert!(
start_polling.elapsed() <= short_timeout,
"Timed out after waiting for response from signer"
);
}
signer_test.shutdown();
}
// Basic test to ensure that miners are able to gather block responses
// from signers and create blocks.
#[test]
#[ignore]
fn miner_gather_signatures() {
if env::var("BITCOIND_TEST") != Ok("1".into()) {
return;
}
tracing_subscriber::registry()
.with(fmt::layer())
.with(EnvFilter::from_default_env())
.init();
// Disable p2p broadcast of the nakamoto blocks, so that we rely
// on the signer's using StackerDB to get pushed blocks
*nakamoto_node::miner::TEST_SKIP_P2P_BROADCAST
.lock()
.unwrap() = Some(true);
info!("------------------------- Test Setup -------------------------");
let num_signers = 5;
let mut signer_test: SignerTest<SpawnedSigner> = SignerTest::new(num_signers, vec![]);
let timeout = Duration::from_secs(30);
let mined_blocks = signer_test.running_nodes.nakamoto_blocks_mined.clone();
let blocks_mined_before = mined_blocks.load(Ordering::SeqCst);
signer_test.boot_to_epoch_3();
// give the system a chance to reach the Nakamoto start tip
// mine a Nakamoto block
wait_for(30, || {
let blocks_mined = mined_blocks.load(Ordering::SeqCst);
Ok(blocks_mined > blocks_mined_before)
})
.unwrap();
info!("------------------------- Test Mine and Verify Confirmed Nakamoto Block -------------------------");
signer_test.mine_and_verify_confirmed_naka_block(timeout, num_signers);
// Test prometheus metrics response
#[cfg(feature = "monitoring_prom")]
{
let metrics_response = signer_test.get_signer_metrics();
// Because 5 signers are running in the same process, the prometheus metrics
// are incremented once for every signer. This is why we expect the metric to be
// `5`, even though there is only one block proposed.
let expected_result = format!("stacks_signer_block_proposals_received {}", num_signers);
assert!(metrics_response.contains(&expected_result));
let expected_result = format!(
"stacks_signer_block_responses_sent{{response_type=\"accepted\"}} {}",
num_signers
);
assert!(metrics_response.contains(&expected_result));
}
}
#[test]
#[ignore]
/// Test that signers can handle a transition between Nakamoto reward cycles
///
/// Test Setup:
/// The test spins up five stacks signers, one miner Nakamoto node, and a corresponding bitcoind.
/// The stacks node is then advanced to Epoch 3.0 boundary to allow block signing.
///
/// Test Execution:
/// The node mines 2 full Nakamoto reward cycles, sending blocks to observing signers to sign and return.
///
/// Test Assertion:
/// All signers sign all blocks successfully.
/// The chain advances 2 full reward cycles.
fn mine_2_nakamoto_reward_cycles() {
if env::var("BITCOIND_TEST") != Ok("1".into()) {
return;
}
tracing_subscriber::registry()
.with(fmt::layer())
.with(EnvFilter::from_default_env())
.init();
info!("------------------------- Test Setup -------------------------");
let nmb_reward_cycles = 2;
let num_signers = 5;
let mut signer_test: SignerTest<SpawnedSigner> = SignerTest::new(num_signers, vec![]);
let timeout = Duration::from_secs(200);
signer_test.boot_to_epoch_3();
let curr_reward_cycle = signer_test.get_current_reward_cycle();
// Mine 2 full Nakamoto reward cycles (epoch 3 starts in the middle of one, hence the + 1)
let next_reward_cycle = curr_reward_cycle.saturating_add(1);
let final_reward_cycle = next_reward_cycle.saturating_add(nmb_reward_cycles);
let final_reward_cycle_height_boundary = signer_test
.running_nodes
.btc_regtest_controller
.get_burnchain()
.reward_cycle_to_block_height(final_reward_cycle)
.saturating_sub(1);
info!("------------------------- Test Mine 2 Nakamoto Reward Cycles -------------------------");
signer_test.run_until_burnchain_height_nakamoto(
timeout,
final_reward_cycle_height_boundary,
num_signers,
);
let current_burnchain_height = signer_test
.running_nodes
.btc_regtest_controller
.get_headers_height();
assert_eq!(current_burnchain_height, final_reward_cycle_height_boundary);
signer_test.shutdown();
}
#[test]
#[ignore]
fn forked_tenure_invalid() {
if env::var("BITCOIND_TEST") != Ok("1".into()) {
return;
}
let result = forked_tenure_testing(Duration::from_secs(5), Duration::from_secs(7), false);
assert_ne!(
result.tip_b.index_block_hash(),
result.tip_a.index_block_hash()
);
assert_eq!(
result.tip_b.index_block_hash(),
result.tip_c.index_block_hash()
);
assert_ne!(result.tip_c, result.tip_a);
// Block B was built atop block A
assert_eq!(
result.tip_b.stacks_block_height,
result.tip_a.stacks_block_height + 1
);
assert_eq!(
result.mined_b.parent_block_id,
result.tip_a.index_block_hash().to_string()
);
// Block C was built AFTER Block B was built, but BEFORE it was broadcasted, so it should be built off of Block A
assert_eq!(
result.mined_c.parent_block_id,
result.tip_a.index_block_hash().to_string()
);
assert_ne!(
result
.tip_c
.anchored_header
.as_stacks_nakamoto()
.unwrap()
.signer_signature_hash(),
result.mined_c.signer_signature_hash,
"Mined block during tenure C should not have become the chain tip"
);
assert!(result.tip_c_2.is_none());
assert!(result.mined_c_2.is_none());
// Tenure D should continue progress
assert_ne!(result.tip_c, result.tip_d);
assert_ne!(
result.tip_b.index_block_hash(),
result.tip_d.index_block_hash()
);
assert_ne!(result.tip_a, result.tip_d);
// Tenure D builds off of Tenure B
assert_eq!(
result.tip_d.stacks_block_height,
result.tip_b.stacks_block_height + 1,
);
assert_eq!(
result.mined_d.parent_block_id,
result.tip_b.index_block_hash().to_string()
);
}
#[test]
#[ignore]
fn forked_tenure_okay() {
if env::var("BITCOIND_TEST") != Ok("1".into()) {
return;
}
let result = forked_tenure_testing(Duration::from_secs(360), Duration::from_secs(0), true);
assert_ne!(result.tip_b, result.tip_a);
assert_ne!(result.tip_b, result.tip_c);
assert_ne!(result.tip_c, result.tip_a);
// Block B was built atop block A
assert_eq!(
result.tip_b.stacks_block_height,
result.tip_a.stacks_block_height + 1
);
assert_eq!(
result.mined_b.parent_block_id,
result.tip_a.index_block_hash().to_string()
);
// Block C was built AFTER Block B was built, but BEFORE it was broadcasted, so it should be built off of Block A
assert_eq!(
result.tip_c.stacks_block_height,
result.tip_a.stacks_block_height + 1
);
assert_eq!(
result.mined_c.parent_block_id,
result.tip_a.index_block_hash().to_string()
);
let tenure_c_2 = result.tip_c_2.unwrap();
assert_ne!(result.tip_c, tenure_c_2);
assert_ne!(tenure_c_2, result.tip_d);
assert_ne!(result.tip_c, result.tip_d);
// Second block of tenure C builds off of block C
assert_eq!(
tenure_c_2.stacks_block_height,
result.tip_c.stacks_block_height + 1,
);
assert_eq!(
result.mined_c_2.unwrap().parent_block_id,
result.tip_c.index_block_hash().to_string()
);
// Tenure D builds off of the second block of tenure C
assert_eq!(
result.tip_d.stacks_block_height,
tenure_c_2.stacks_block_height + 1,
);
assert_eq!(
result.mined_d.parent_block_id,
tenure_c_2.index_block_hash().to_string()
);
}
struct TenureForkingResult {
tip_a: StacksHeaderInfo,
tip_b: StacksHeaderInfo,
tip_c: StacksHeaderInfo,
tip_c_2: Option<StacksHeaderInfo>,
tip_d: StacksHeaderInfo,
mined_b: MinedNakamotoBlockEvent,
mined_c: MinedNakamotoBlockEvent,
mined_c_2: Option<MinedNakamotoBlockEvent>,
mined_d: MinedNakamotoBlockEvent,
}
#[test]
#[ignore]
/// Test to make sure that the signers are capable of reloading their reward set
/// if the stacks-node doesn't have it available at the first block of a prepare phase (e.g., if there was no block)
fn reloads_signer_set_in() {
tracing_subscriber::registry()
.with(fmt::layer())
.with(EnvFilter::from_default_env())
.init();
let num_signers = 5;
let sender_sk = Secp256k1PrivateKey::new();
let sender_addr = tests::to_addr(&sender_sk);
let send_amt = 100;
let send_fee = 180;
let mut signer_test: SignerTest<SpawnedSigner> = SignerTest::new_with_config_modifications(
num_signers,
vec![(sender_addr.clone(), send_amt + send_fee)],
|_config| {},
|_| {},
None,
None,
);
setup_epoch_3_reward_set(
&signer_test.running_nodes.conf,
&signer_test.running_nodes.blocks_processed,
&signer_test.signer_stacks_private_keys,
&signer_test.signer_stacks_private_keys,
&mut signer_test.running_nodes.btc_regtest_controller,
Some(signer_test.num_stacking_cycles),
);
let naka_conf = &signer_test.running_nodes.conf;
let epochs = naka_conf.burnchain.epochs.clone().unwrap();
let epoch_3 = &epochs[StacksEpoch::find_epoch_by_id(&epochs, StacksEpochId::Epoch30).unwrap()];
let reward_cycle_len = naka_conf.get_burnchain().pox_constants.reward_cycle_length as u64;
let prepare_phase_len = naka_conf.get_burnchain().pox_constants.prepare_length as u64;
let epoch_3_start_height = epoch_3.start_height;
assert!(
epoch_3_start_height > 0,
"Epoch 3.0 start height must be greater than 0"
);
let epoch_3_reward_cycle_boundary =
epoch_3_start_height.saturating_sub(epoch_3_start_height % reward_cycle_len);
let before_epoch_3_reward_set_calculation =
epoch_3_reward_cycle_boundary.saturating_sub(prepare_phase_len);
run_until_burnchain_height(
&mut signer_test.running_nodes.btc_regtest_controller,
&signer_test.running_nodes.blocks_processed,
before_epoch_3_reward_set_calculation,
naka_conf,
);
info!("Waiting for signer set calculation.");
let short_timeout = Duration::from_secs(30);
// Make sure the signer set is calculated before continuing or signers may not
// recognize that they are registered signers in the subsequent burn block event
let reward_cycle = signer_test.get_current_reward_cycle() + 1;
signer_test
.running_nodes
.btc_regtest_controller
.build_next_block(1);
wait_for(short_timeout.as_secs(), || {
let reward_set = match signer_test
.stacks_client
.get_reward_set_signers(reward_cycle)
{
Ok(x) => x,
Err(e) => {
warn!("Failed to check if reward set is calculated yet: {e:?}. Will try again");
return Ok(false);
}
};
if let Some(ref set) = reward_set {
info!("Signer set: {:?}", set);
}
Ok(reward_set.is_some())
})
.expect("Timed out waiting for reward set to be calculated");
info!("Signer set calculated");
// Manually consume one more block to ensure signers refresh their state
info!("Waiting for signers to initialize.");
next_block_and_wait(
&mut signer_test.running_nodes.btc_regtest_controller,
&signer_test.running_nodes.blocks_processed,
);
signer_test.wait_for_registered(30);
info!("Signers initialized");
signer_test.run_until_epoch_3_boundary();
let commits_submitted = signer_test.running_nodes.commits_submitted.clone();
info!("Waiting 1 burnchain block for miner VRF key confirmation");
// Wait one block to confirm the VRF register, wait until a block commit is submitted
next_block_and(
&mut signer_test.running_nodes.btc_regtest_controller,
60,
|| {
let commits_count = commits_submitted.load(Ordering::SeqCst);
Ok(commits_count >= 1)
},
)
.unwrap();
info!("Ready to mine Nakamoto blocks!");
info!("------------------------- Reached Epoch 3.0 -------------------------");
signer_test.shutdown();
}
/// This test spins up a nakamoto-neon node.
/// It starts in Epoch 2.0, mines with `neon_node` to Epoch 3.0, and then switches
/// to Nakamoto operation (activating pox-4 by submitting a stack-stx tx). The BootLoop
/// struct handles the epoch-2/3 tear-down and spin-up.
/// Miner A mines a regular tenure, its last block being block a_x.
/// Miner B starts its tenure, Miner B produces a Stacks block b_0, but miner C submits its block commit before b_0 is broadcasted.
/// Bitcoin block C, containing Miner C's block commit, is mined BEFORE miner C has a chance to update their block commit with b_0's information.
/// This test asserts:
/// * tenure C ignores b_0, and correctly builds off of block a_x.
fn forked_tenure_testing(
proposal_limit: Duration,
post_btc_block_pause: Duration,
expect_tenure_c: bool,
) -> TenureForkingResult {
tracing_subscriber::registry()
.with(fmt::layer())
.with(EnvFilter::from_default_env())
.init();
let num_signers = 5;
let sender_sk = Secp256k1PrivateKey::new();
let sender_addr = tests::to_addr(&sender_sk);
let send_amt = 100;
let send_fee = 180;
let recipient = PrincipalData::from(StacksAddress::burn_address(false));
let mut signer_test: SignerTest<SpawnedSigner> = SignerTest::new_with_config_modifications(
num_signers,
vec![(sender_addr.clone(), send_amt + send_fee)],
|config| {
// make the duration long enough that the reorg attempt will definitely be accepted
config.first_proposal_burn_block_timing = proposal_limit;
// don't allow signers to post signed blocks (limits the amount of fault injection we
// need)
TEST_SKIP_BLOCK_BROADCAST.lock().unwrap().replace(true);
},
|_| {},
None,
None,
);
let http_origin = format!("http://{}", &signer_test.running_nodes.conf.node.rpc_bind);
signer_test.boot_to_epoch_3();
sleep_ms(1000);
info!("------------------------- Reached Epoch 3.0 -------------------------");
let naka_conf = signer_test.running_nodes.conf.clone();
let burnchain = naka_conf.get_burnchain();
let sortdb = burnchain.open_sortition_db(true).unwrap();
let (chainstate, _) = StacksChainState::open(
naka_conf.is_mainnet(),
naka_conf.burnchain.chain_id,
&naka_conf.get_chainstate_path_str(),
None,
)
.unwrap();
let commits_submitted = signer_test.running_nodes.commits_submitted.clone();
let mined_blocks = signer_test.running_nodes.nakamoto_blocks_mined.clone();
let proposed_blocks = signer_test.running_nodes.nakamoto_blocks_proposed.clone();
let rejected_blocks = signer_test.running_nodes.nakamoto_blocks_rejected.clone();
let coord_channel = signer_test.running_nodes.coord_channel.clone();
let blocks_processed_before = coord_channel
.lock()
.expect("Mutex poisoned")
.get_stacks_blocks_processed();
info!("Starting Tenure A.");
// In the next block, the miner should win the tenure and submit a stacks block
let commits_before = commits_submitted.load(Ordering::SeqCst);
let blocks_before = mined_blocks.load(Ordering::SeqCst);
next_block_and(
&mut signer_test.running_nodes.btc_regtest_controller,
60,
|| {
let commits_count = commits_submitted.load(Ordering::SeqCst);
let blocks_count = mined_blocks.load(Ordering::SeqCst);
let blocks_processed = coord_channel
.lock()
.expect("Mutex poisoned")
.get_stacks_blocks_processed();
Ok(commits_count > commits_before
&& blocks_count > blocks_before
&& blocks_processed > blocks_processed_before)
},
)
.unwrap();
sleep_ms(1000);
let tip_a = NakamotoChainState::get_canonical_block_header(chainstate.db(), &sortdb)
.unwrap()
.unwrap();
// For the next tenure, submit the commit op but do not allow any stacks blocks to be broadcasted
TEST_BROADCAST_STALL.lock().unwrap().replace(true);
TEST_BLOCK_ANNOUNCE_STALL.lock().unwrap().replace(true);
let blocks_before = mined_blocks.load(Ordering::SeqCst);
let commits_before = commits_submitted.load(Ordering::SeqCst);
info!("Starting Tenure B.");
next_block_and(
&mut signer_test.running_nodes.btc_regtest_controller,
60,
|| {