-
Notifications
You must be signed in to change notification settings - Fork 647
/
signer.rs
1431 lines (1370 loc) · 62.8 KB
/
signer.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-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::VecDeque;
use std::path::PathBuf;
use std::sync::mpsc::Sender;
use std::time::Instant;
use blockstack_lib::chainstate::burn::ConsensusHashExtensions;
use blockstack_lib::chainstate::nakamoto::signer_set::NakamotoSigners;
use blockstack_lib::chainstate::nakamoto::{NakamotoBlock, NakamotoBlockVote};
use blockstack_lib::chainstate::stacks::StacksTransaction;
use blockstack_lib::net::api::postblock_proposal::BlockValidateResponse;
use hashbrown::HashSet;
use libsigner::{
BlockProposalSigners, BlockRejection, BlockResponse, MessageSlotID, RejectCode, SignerEvent,
SignerMessage,
};
use serde_derive::{Deserialize, Serialize};
use slog::{slog_debug, slog_error, slog_info, slog_warn};
use stacks_common::codec::{read_next, StacksMessageCodec};
use stacks_common::types::chainstate::{ConsensusHash, StacksAddress};
use stacks_common::types::StacksEpochId;
use stacks_common::util::hash::Sha512Trunc256Sum;
use stacks_common::{debug, error, info, warn};
use wsts::common::{MerkleRoot, Signature};
use wsts::curve::keys::PublicKey;
use wsts::curve::point::Point;
use wsts::net::{Message, NonceRequest, Packet, SignatureShareRequest};
use wsts::state_machine::coordinator::fire::Coordinator as FireCoordinator;
use wsts::state_machine::coordinator::{
Config as CoordinatorConfig, Coordinator, State as CoordinatorState,
};
use wsts::state_machine::signer::Signer as SignerStateMachine;
use wsts::state_machine::{OperationResult, SignError};
use wsts::traits::Signer as _;
use wsts::v2;
use crate::client::{retry_with_exponential_backoff, ClientError, StackerDB, StacksClient};
use crate::config::SignerConfig;
use crate::coordinator::CoordinatorSelector;
use crate::signerdb::SignerDb;
/// The signer StackerDB slot ID, purposefully wrapped to prevent conflation with SignerID
#[derive(Debug, Clone, PartialEq, Eq, Hash, Copy, PartialOrd, Ord)]
pub struct SignerSlotID(pub u32);
impl std::fmt::Display for SignerSlotID {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
/// Additional Info about a proposed block
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct BlockInfo {
/// The block we are considering
pub block: NakamotoBlock,
/// Our vote on the block if we have one yet
pub vote: Option<NakamotoBlockVote>,
/// Whether the block contents are valid
valid: Option<bool>,
/// The associated packet nonce request if we have one
nonce_request: Option<NonceRequest>,
/// Whether this block is already being signed over
pub signed_over: bool,
}
impl BlockInfo {
/// Create a new BlockInfo
pub const fn new(block: NakamotoBlock) -> Self {
Self {
block,
vote: None,
valid: None,
nonce_request: None,
signed_over: false,
}
}
/// Create a new BlockInfo with an associated nonce request packet
pub const fn new_with_request(block: NakamotoBlock, nonce_request: NonceRequest) -> Self {
Self {
block,
vote: None,
valid: None,
nonce_request: Some(nonce_request),
signed_over: true,
}
}
/// Return the block's signer signature hash
pub fn signer_signature_hash(&self) -> Sha512Trunc256Sum {
self.block.header.signer_signature_hash()
}
}
/// Which signer operation to perform
#[derive(PartialEq, Clone, Debug)]
pub enum Command {
/// Generate a DKG aggregate public key
Dkg,
/// Sign a message
Sign {
/// The block to sign over
block: NakamotoBlock,
/// Whether to make a taproot signature
is_taproot: bool,
/// Taproot merkle root
merkle_root: Option<MerkleRoot>,
},
}
/// The Signer state
#[derive(PartialEq, Eq, Debug, Clone)]
pub enum State {
/// The signer is idle, waiting for messages and commands
Idle,
/// The signer is executing a DKG or Sign round
OperationInProgress,
}
/// The stacks signer registered for the reward cycle
pub struct Signer {
/// The coordinator for inbound messages for a specific reward cycle
pub coordinator: FireCoordinator<v2::Aggregator>,
/// The signing round used to sign messages for a specific reward cycle
pub state_machine: SignerStateMachine<v2::Signer>,
/// the state of the signer
pub state: State,
/// Received Commands that need to be processed
pub commands: VecDeque<Command>,
/// The stackerdb client
pub stackerdb: StackerDB,
/// Whether the signer is a mainnet signer or not
pub mainnet: bool,
/// The signer id
pub signer_id: u32,
/// The signer slot ids for the signers in the reward cycle
pub signer_slot_ids: Vec<SignerSlotID>,
/// The addresses of other signers
pub signer_addresses: Vec<StacksAddress>,
/// The signer slot ids for the signers in the NEXT reward cycle
pub next_signer_slot_ids: Vec<SignerSlotID>,
/// The addresses of the signers for the NEXT reward cycle
pub next_signer_addresses: Vec<StacksAddress>,
/// The reward cycle this signer belongs to
pub reward_cycle: u64,
/// The tx fee in uSTX to use if the epoch is pre Nakamoto (Epoch 3.0)
pub tx_fee_ustx: u64,
/// The coordinator info for the signer
pub coordinator_selector: CoordinatorSelector,
/// The approved key registered to the contract
pub approved_aggregate_public_key: Option<Point>,
/// The current active miner's key (if we know it!)
pub miner_key: Option<PublicKey>,
/// Signer DB path
pub db_path: PathBuf,
/// SignerDB for state management
pub signer_db: SignerDb,
}
impl std::fmt::Display for Signer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Cycle #{} Signer #{}(C:{})",
self.reward_cycle,
self.signer_id,
self.coordinator_selector.get_coordinator().0,
)
}
}
impl Signer {
/// Return the current coordinator.
/// If the current reward cycle is the active reward cycle, this is the miner,
/// so the first element of the tuple will be None (because the miner does not have a signer index).
/// Otherwise, the coordinator is the signer with the index returned by the coordinator selector.
fn get_coordinator_sign(&self, current_reward_cycle: u64) -> (Option<u32>, PublicKey) {
if self.reward_cycle == current_reward_cycle {
let Some(ref cur_miner) = self.miner_key else {
error!(
"Signer #{}: Could not lookup current miner while in active reward cycle",
self.signer_id
);
let selected = self.coordinator_selector.get_coordinator();
return (Some(selected.0), selected.1);
};
// coordinator is the current miner.
(None, *cur_miner)
} else {
let selected = self.coordinator_selector.get_coordinator();
(Some(selected.0), selected.1)
}
}
/// Get the current coordinator for executing DKG
/// This will always use the coordinator selector to determine the coordinator
fn get_coordinator_dkg(&self) -> (u32, PublicKey) {
self.coordinator_selector.get_coordinator()
}
}
impl From<SignerConfig> for Signer {
fn from(signer_config: SignerConfig) -> Self {
let stackerdb = StackerDB::from(&signer_config);
let num_signers = signer_config
.signer_entries
.count_signers()
.expect("FATAL: Too many registered signers to fit in a u32");
let num_keys = signer_config
.signer_entries
.count_keys()
.expect("FATAL: Too many key ids to fit in a u32");
let threshold = signer_config
.signer_entries
.get_signing_threshold()
.expect("FATAL: Too many key ids to fit in a u32");
let dkg_threshold = signer_config
.signer_entries
.get_dkg_threshold()
.expect("FATAL: Too many key ids to fit in a u32");
let coordinator_config = CoordinatorConfig {
threshold,
dkg_threshold,
num_signers,
num_keys,
message_private_key: signer_config.ecdsa_private_key,
dkg_public_timeout: signer_config.dkg_public_timeout,
dkg_private_timeout: signer_config.dkg_private_timeout,
dkg_end_timeout: signer_config.dkg_end_timeout,
nonce_timeout: signer_config.nonce_timeout,
sign_timeout: signer_config.sign_timeout,
signer_key_ids: signer_config.signer_entries.coordinator_key_ids,
signer_public_keys: signer_config.signer_entries.signer_public_keys,
};
let coordinator = FireCoordinator::new(coordinator_config);
let coordinator_selector =
CoordinatorSelector::from(signer_config.signer_entries.public_keys.clone());
debug!(
"Reward cycle #{} Signer #{}: initial coordinator is signer {}",
signer_config.reward_cycle,
signer_config.signer_id,
coordinator_selector.get_coordinator().0
);
let signer_db =
SignerDb::new(&signer_config.db_path).expect("Failed to connect to signer Db");
let mut state_machine = SignerStateMachine::new(
threshold,
num_signers,
num_keys,
signer_config.signer_id,
signer_config.key_ids,
signer_config.ecdsa_private_key,
signer_config.signer_entries.public_keys,
);
if let Some(state) = signer_db
.get_signer_state(signer_config.reward_cycle)
.expect("Failed to load signer state")
{
debug!(
"Reward cycle #{} Signer #{}: Loading signer",
signer_config.reward_cycle, signer_config.signer_id
);
state_machine.signer = v2::Signer::load(&state);
}
Self {
coordinator,
state_machine,
state: State::Idle,
commands: VecDeque::new(),
stackerdb,
mainnet: signer_config.mainnet,
signer_id: signer_config.signer_id,
signer_addresses: signer_config
.signer_entries
.signer_ids
.into_keys()
.collect(),
signer_slot_ids: signer_config.signer_slot_ids.clone(),
next_signer_slot_ids: vec![],
next_signer_addresses: vec![],
reward_cycle: signer_config.reward_cycle,
tx_fee_ustx: signer_config.tx_fee_ustx,
coordinator_selector,
approved_aggregate_public_key: None,
miner_key: None,
db_path: signer_config.db_path,
signer_db,
}
}
}
impl Signer {
/// Refresh the coordinator selector
pub fn refresh_coordinator(&mut self) {
// TODO: do not use an empty consensus hash
let pox_consensus_hash = ConsensusHash::empty();
let old_coordinator_id = self.coordinator_selector.get_coordinator().0;
let updated_coordinator_id = self
.coordinator_selector
.refresh_coordinator(&pox_consensus_hash);
if old_coordinator_id != updated_coordinator_id {
debug!(
"{self}: Coordinator updated. Resetting state to Idle.";
"old_coordinator_id" => {old_coordinator_id},
"updated_coordinator_id" => {updated_coordinator_id},
"pox_consensus_hash" => %pox_consensus_hash
);
self.coordinator.state = CoordinatorState::Idle;
self.state = State::Idle;
}
}
/// Finish an operation and update the coordinator selector accordingly
fn finish_operation(&mut self) {
self.state = State::Idle;
self.coordinator_selector.last_message_time = None;
}
/// Update operation
fn update_operation(&mut self) {
self.state = State::OperationInProgress;
self.coordinator_selector.last_message_time = Some(Instant::now());
}
/// Execute the given command and update state accordingly
fn execute_command(&mut self, stacks_client: &StacksClient, command: &Command) {
match command {
Command::Dkg => {
if self.approved_aggregate_public_key.is_some() {
debug!("Reward cycle #{} Signer #{}: Already have an aggregate key. Ignoring DKG command.", self.reward_cycle, self.signer_id);
return;
}
let vote_round = match retry_with_exponential_backoff(|| {
stacks_client
.get_last_round(self.reward_cycle)
.map_err(backoff::Error::transient)
}) {
Ok(last_round) => last_round,
Err(e) => {
error!("{self}: Unable to perform DKG. Failed to get last round from stacks node: {e:?}");
return;
}
};
// The dkg id will increment internally following "start_dkg_round" so do not increment it here
self.coordinator.current_dkg_id = vote_round.unwrap_or(0);
info!(
"{self}: Starting DKG vote";
"round" => self.coordinator.current_dkg_id.wrapping_add(1),
"cycle" => self.reward_cycle,
);
match self.coordinator.start_dkg_round() {
Ok(msg) => {
let ack = self.stackerdb.send_message_with_retry(msg.into());
debug!("{self}: ACK: {ack:?}",);
}
Err(e) => {
error!("{self}: Failed to start DKG: {e:?}",);
return;
}
}
}
Command::Sign {
block,
is_taproot,
merkle_root,
} => {
if self.approved_aggregate_public_key.is_none() {
debug!("{self}: Cannot sign a block without an approved aggregate public key. Ignore it.");
return;
}
let signer_signature_hash = block.header.signer_signature_hash();
let mut block_info = self
.signer_db
.block_lookup(self.reward_cycle, &signer_signature_hash)
.unwrap_or_else(|_| Some(BlockInfo::new(block.clone())))
.unwrap_or_else(|| BlockInfo::new(block.clone()));
if block_info.signed_over {
debug!("{self}: Received a sign command for a block we are already signing over. Ignore it.");
return;
}
info!("{self}: Signing block";
"block_consensus_hash" => %block.header.consensus_hash,
"block_height" => block.header.chain_length,
"pre_sign_block_id" => %block.block_id(),
);
match self.coordinator.start_signing_round(
&block.serialize_to_vec(),
*is_taproot,
*merkle_root,
) {
Ok(msg) => {
let ack = self.stackerdb.send_message_with_retry(msg.into());
debug!("{self}: ACK: {ack:?}",);
block_info.signed_over = true;
self.signer_db
.insert_block(self.reward_cycle, &block_info)
.unwrap_or_else(|e| {
error!("{self}: Failed to insert block in DB: {e:?}");
});
}
Err(e) => {
error!("{self}: Failed to start signing block: {e:?}",);
return;
}
}
}
}
self.update_operation();
}
/// Attempt to process the next command in the queue, and update state accordingly
pub fn process_next_command(
&mut self,
stacks_client: &StacksClient,
current_reward_cycle: u64,
) {
match &self.state {
State::Idle => {
let Some(command) = self.commands.front() else {
debug!("{self}: Nothing to process. Waiting for command...");
return;
};
let coordinator_id = if matches!(command, Command::Dkg) {
// We cannot execute a DKG command if we are not the coordinator
Some(self.get_coordinator_dkg().0)
} else {
self.get_coordinator_sign(current_reward_cycle).0
};
if coordinator_id != Some(self.signer_id) {
debug!(
"{self}: Coordinator is {coordinator_id:?}. Will not process any commands...",
);
return;
}
let command = self
.commands
.pop_front()
.expect("BUG: Already asserted that the command queue was not empty");
self.execute_command(stacks_client, &command);
}
State::OperationInProgress => {
// We cannot execute the next command until the current one is finished...
debug!(
"{self}: Waiting for operation to finish. Coordinator state = {:?}",
self.coordinator.state
);
}
}
}
/// Handle the block validate response returned from our prior calls to submit a block for validation
fn handle_block_validate_response(
&mut self,
stacks_client: &StacksClient,
block_validate_response: &BlockValidateResponse,
res: Sender<Vec<OperationResult>>,
current_reward_cycle: u64,
) {
let mut block_info = match block_validate_response {
BlockValidateResponse::Ok(block_validate_ok) => {
let signer_signature_hash = block_validate_ok.signer_signature_hash;
// For mutability reasons, we need to take the block_info out of the map and add it back after processing
let mut block_info = match self
.signer_db
.block_lookup(self.reward_cycle, &signer_signature_hash)
{
Ok(Some(block_info)) => block_info,
Ok(None) => {
// We have not seen this block before. Why are we getting a response for it?
debug!("{self}: Received a block validate response for a block we have not seen before. Ignoring...");
return;
}
Err(e) => {
error!("{self}: Failed to lookup block in signer db: {e:?}",);
return;
}
};
let is_valid = self.verify_block_transactions(stacks_client, &block_info.block);
block_info.valid = Some(is_valid);
self.signer_db
.insert_block(self.reward_cycle, &block_info)
.unwrap_or_else(|_| panic!("{self}: Failed to insert block in DB"));
info!(
"{self}: Treating block validation for block {} as valid: {:?}",
&block_info.block.block_id(),
block_info.valid
);
block_info
}
BlockValidateResponse::Reject(block_validate_reject) => {
let signer_signature_hash = block_validate_reject.signer_signature_hash;
let mut block_info = match self
.signer_db
.block_lookup(self.reward_cycle, &signer_signature_hash)
{
Ok(Some(block_info)) => block_info,
Ok(None) => {
// We have not seen this block before. Why are we getting a response for it?
debug!("{self}: Received a block validate response for a block we have not seen before. Ignoring...");
return;
}
Err(e) => {
error!("{self}: Failed to lookup block in signer db: {e:?}");
return;
}
};
block_info.valid = Some(false);
// Submit a rejection response to the .signers contract for miners
// to observe so they know to send another block and to prove signers are doing work);
warn!("{self}: Broadcasting a block rejection due to stacks node validation failure...");
if let Err(e) = self
.stackerdb
.send_message_with_retry(block_validate_reject.clone().into())
{
warn!("{self}: Failed to send block rejection to stacker-db: {e:?}",);
}
block_info
}
};
if let Some(mut nonce_request) = block_info.nonce_request.take() {
debug!("{self}: Received a block validate response from the stacks node for a block we already received a nonce request for. Responding to the nonce request...");
// We have received validation from the stacks node. Determine our vote and update the request message
self.determine_vote(&mut block_info, &mut nonce_request);
// Send the nonce request through with our vote
let packet = Packet {
msg: Message::NonceRequest(nonce_request),
sig: vec![],
};
self.handle_packets(stacks_client, res, &[packet], current_reward_cycle);
}
debug!(
"{self}: Received a block validate response";
"block_hash" => block_info.block.header.block_hash(),
"valid" => block_info.valid,
"signed_over" => block_info.signed_over,
);
self.signer_db
.insert_block(self.reward_cycle, &block_info)
.unwrap_or_else(|_| panic!("{self}: Failed to insert block in DB"));
}
/// Handle signer messages submitted to signers stackerdb
fn handle_signer_messages(
&mut self,
stacks_client: &StacksClient,
res: Sender<Vec<OperationResult>>,
messages: &[SignerMessage],
current_reward_cycle: u64,
) {
let packets: Vec<Packet> = messages
.iter()
.filter_map(|msg| match msg {
SignerMessage::DkgResults { .. }
| SignerMessage::BlockResponse(_)
| SignerMessage::Transactions(_) => None,
// TODO: if a signer tries to trigger DKG and we already have one set in the contract, ignore the request.
SignerMessage::Packet(packet) => {
let coordinator_pubkey = if Self::is_dkg_message(&packet.msg) {
self.get_coordinator_dkg().1
} else {
self.get_coordinator_sign(current_reward_cycle).1
};
self.verify_packet(stacks_client, packet.clone(), &coordinator_pubkey)
}
})
.collect();
self.handle_packets(stacks_client, res, &packets, current_reward_cycle);
}
/// Handle proposed blocks submitted by the miners to stackerdb
fn handle_proposed_blocks(
&mut self,
stacks_client: &StacksClient,
proposals: &[BlockProposalSigners],
) {
for proposal in proposals {
if proposal.reward_cycle != self.reward_cycle {
debug!(
"{self}: Received proposal for block outside of my reward cycle, ignoring.";
"proposal_reward_cycle" => proposal.reward_cycle,
"proposal_burn_height" => proposal.burn_height,
);
continue;
}
let sig_hash = proposal.block.header.signer_signature_hash();
match self.signer_db.block_lookup(self.reward_cycle, &sig_hash) {
Ok(Some(block)) => {
debug!(
"{self}: Received proposal for block already known, ignoring new proposal.";
"signer_sighash" => %sig_hash,
"proposal_burn_height" => proposal.burn_height,
"vote" => ?block.vote.as_ref().map(|v| {
if v.rejected {
"REJECT"
} else {
"ACCEPT"
}
}),
"signed_over" => block.signed_over,
);
continue;
}
Ok(None) => {
// Store the block in our cache
self.signer_db
.insert_block(self.reward_cycle, &BlockInfo::new(proposal.block.clone()))
.unwrap_or_else(|e| {
error!("{self}: Failed to insert block in DB: {e:?}");
});
// Submit the block for validation
stacks_client
.submit_block_for_validation_with_retry(proposal.block.clone())
.unwrap_or_else(|e| {
warn!("{self}: Failed to submit block for validation: {e:?}");
});
}
Err(e) => {
error!(
"{self}: Failed to lookup block in DB: {e:?}. Dropping proposal request."
);
continue;
}
}
}
}
/// Helper function for determining if the provided message is a DKG specific message
fn is_dkg_message(msg: &Message) -> bool {
matches!(
msg,
Message::DkgBegin(_)
| Message::DkgEnd(_)
| Message::DkgEndBegin(_)
| Message::DkgPrivateBegin(_)
| Message::DkgPrivateShares(_)
| Message::DkgPublicShares(_)
)
}
/// Process inbound packets as both a signer and a coordinator
/// Will send outbound packets and operation results as appropriate
fn handle_packets(
&mut self,
stacks_client: &StacksClient,
res: Sender<Vec<OperationResult>>,
packets: &[Packet],
current_reward_cycle: u64,
) {
let signer_outbound_messages = self
.state_machine
.process_inbound_messages(packets)
.unwrap_or_else(|e| {
error!("{self}: Failed to process inbound messages as a signer: {e:?}",);
vec![]
});
// Next process the message as the coordinator
let (coordinator_outbound_messages, operation_results) = if self.reward_cycle
!= current_reward_cycle
{
self.coordinator
.process_inbound_messages(packets)
.unwrap_or_else(|e| {
error!("{self}: Failed to process inbound messages as a coordinator: {e:?}");
(vec![], vec![])
})
} else {
(vec![], vec![])
};
if !operation_results.is_empty() {
// We have finished a signing or DKG round, either successfully or due to error.
// Regardless of the why, update our state to Idle as we should not expect the operation to continue.
self.process_operation_results(stacks_client, &operation_results);
self.send_operation_results(res, operation_results);
self.finish_operation();
} else if !packets.is_empty() && self.coordinator.state != CoordinatorState::Idle {
// We have received a message and are in the middle of an operation. Update our state accordingly
self.update_operation();
}
debug!("{self}: Saving signer state");
self.save_signer_state();
self.send_outbound_messages(signer_outbound_messages);
self.send_outbound_messages(coordinator_outbound_messages);
}
/// Validate a signature share request, updating its message where appropriate.
/// If the request is for a block it has already agreed to sign, it will overwrite the message with the agreed upon value
/// Returns whether the request is valid or not.
fn validate_signature_share_request(&self, request: &mut SignatureShareRequest) -> bool {
let Some(block_vote): Option<NakamotoBlockVote> = read_next(&mut &request.message[..]).ok()
else {
// We currently reject anything that is not a block vote
debug!(
"{self}: Received a signature share request for an unknown message stream. Reject it.",
);
return false;
};
match self
.signer_db
.block_lookup(self.reward_cycle, &block_vote.signer_signature_hash)
.unwrap_or_else(|_| panic!("{self}: Failed to connect to DB"))
.map(|b| b.vote)
{
Some(Some(vote)) => {
// Overwrite with our agreed upon value in case another message won majority or the coordinator is trying to cheat...
debug!(
"{self}: Set vote (rejected = {}) to {vote:?}", block_vote.rejected;
"requested_sighash" => %block_vote.signer_signature_hash,
);
request.message = vote.serialize_to_vec();
true
}
Some(None) => {
// We never agreed to sign this block. Reject it.
// This can happen if the coordinator received enough votes to sign yes
// or no on a block before we received validation from the stacks node.
debug!(
"{self}: Received a signature share request for a block we never agreed to sign. Ignore it.";
"requested_sighash" => %block_vote.signer_signature_hash,
);
false
}
None => {
// We will only sign across block hashes or block hashes + b'n' byte for
// blocks we have seen a Nonce Request for (and subsequent validation)
// We are missing the context here necessary to make a decision. Reject the block
debug!(
"{self}: Received a signature share request from an unknown block. Reject it.";
"requested_sighash" => %block_vote.signer_signature_hash,
);
false
}
}
}
/// Validate a nonce request, updating its message appropriately.
/// If the request is for a block, we will update the request message
/// as either a hash indicating a vote no or the signature hash indicating a vote yes
/// Returns whether the request is valid or not
fn validate_nonce_request(
&mut self,
stacks_client: &StacksClient,
nonce_request: &mut NonceRequest,
) -> Option<BlockInfo> {
let Some(block) =
NakamotoBlock::consensus_deserialize(&mut nonce_request.message.as_slice()).ok()
else {
// We currently reject anything that is not a block
warn!("{self}: Received a nonce request for an unknown message stream. Reject it.",);
return None;
};
let signer_signature_hash = block.header.signer_signature_hash();
let Some(mut block_info) = self
.signer_db
.block_lookup(self.reward_cycle, &signer_signature_hash)
.expect("Failed to connect to signer DB")
else {
debug!(
"{self}: We have received a block sign request for a block we have not seen before. Cache the nonce request and submit the block for validation...";
"signer_sighash" => %block.header.signer_signature_hash(),
);
let block_info = BlockInfo::new_with_request(block.clone(), nonce_request.clone());
stacks_client
.submit_block_for_validation_with_retry(block)
.unwrap_or_else(|e| {
warn!("{self}: Failed to submit block for validation: {e:?}",);
});
return Some(block_info);
};
if block_info.valid.is_none() {
// We have not yet received validation from the stacks node. Cache the request and wait for validation
debug!("{self}: We have yet to receive validation from the stacks node for a nonce request. Cache the nonce request and wait for block validation...");
block_info.nonce_request = Some(nonce_request.clone());
return Some(block_info);
}
self.determine_vote(&mut block_info, nonce_request);
Some(block_info)
}
/// Verify the transactions in a block are as expected
fn verify_block_transactions(
&mut self,
stacks_client: &StacksClient,
block: &NakamotoBlock,
) -> bool {
if self.approved_aggregate_public_key.is_some() {
// We do not enforce a block contain any transactions except the aggregate votes when it is NOT already set
// TODO: should be only allow special cased transactions during prepare phase before a key is set?
debug!("{self}: Already have an aggregate key. Skipping transaction verification...");
return true;
}
if let Ok(expected_transactions) = self.get_expected_transactions(stacks_client) {
//It might be worth building a hashset of the blocks' txids and checking that against the expected transaction's txid.
let block_tx_hashset = block.txs.iter().map(|tx| tx.txid()).collect::<HashSet<_>>();
// Ensure the block contains the transactions we expect
let missing_transactions = expected_transactions
.into_iter()
.filter_map(|tx| {
if !block_tx_hashset.contains(&tx.txid()) {
debug!("{self}: expected txid {} is in the block", &tx.txid());
Some(tx)
} else {
debug!("{self}: missing expected txid {}", &tx.txid());
None
}
})
.collect::<Vec<_>>();
let is_valid = missing_transactions.is_empty();
if !is_valid {
debug!("{self}: Broadcasting a block rejection due to missing expected transactions...");
let block_rejection = BlockRejection::new(
block.header.signer_signature_hash(),
RejectCode::MissingTransactions(missing_transactions),
);
// Submit signature result to miners to observe
if let Err(e) = self
.stackerdb
.send_message_with_retry(block_rejection.into())
{
warn!("{self}: Failed to send block rejection to stacker-db: {e:?}",);
}
}
is_valid
} else {
// Failed to connect to the stacks node to get transactions. Cannot validate the block. Reject it.
debug!("{self}: Broadcasting a block rejection due to signer connectivity issues...",);
let block_rejection = BlockRejection::new(
block.header.signer_signature_hash(),
RejectCode::ConnectivityIssues,
);
// Submit signature result to miners to observe
if let Err(e) = self
.stackerdb
.send_message_with_retry(block_rejection.into())
{
warn!("{self}: Failed to send block submission to stacker-db: {e:?}",);
}
false
}
}
/// Get transactions from stackerdb for the given addresses and account nonces, filtering out any malformed transactions
fn get_signer_transactions(
&mut self,
nonces: &std::collections::HashMap<StacksAddress, u64>,
) -> Result<Vec<StacksTransaction>, ClientError> {
let transactions: Vec<_> = self
.stackerdb
.get_current_transactions_with_retry()?
.into_iter()
.filter_map(|tx| {
if !NakamotoSigners::valid_vote_transaction(nonces, &tx, self.mainnet) {
return None;
}
Some(tx)
})
.collect();
Ok(transactions)
}
/// Get the transactions that should be included in the block, filtering out any invalid transactions
fn get_expected_transactions(
&mut self,
stacks_client: &StacksClient,
) -> Result<Vec<StacksTransaction>, ClientError> {
if self.next_signer_slot_ids.is_empty() {
debug!("{self}: No next signers. Skipping transaction retrieval.",);
return Ok(vec![]);
}
// Get all the account nonces for the next signers
let account_nonces = self.get_account_nonces(stacks_client, &self.next_signer_addresses);
let transactions: Vec<_> = self
.stackerdb
.get_next_transactions_with_retry(&self.next_signer_slot_ids)?;
let mut filtered_transactions = std::collections::HashMap::new();
NakamotoSigners::update_filtered_transactions(
&mut filtered_transactions,
&account_nonces,
self.mainnet,
transactions,
);
// We only allow enforcement of one special cased transaction per signer address per block
Ok(filtered_transactions.into_values().collect())
}
/// Determine the vote for a block and update the block info and nonce request accordingly
fn determine_vote(&self, block_info: &mut BlockInfo, nonce_request: &mut NonceRequest) {
let rejected = !block_info.valid.unwrap_or(false);
if rejected {
debug!("{self}: Rejecting block {}", block_info.block.block_id());
} else {
debug!("{self}: Accepting block {}", block_info.block.block_id());
}
let block_vote = NakamotoBlockVote {
signer_signature_hash: block_info.block.header.signer_signature_hash(),
rejected: !block_info.valid.unwrap_or(false),
};
let block_vote_bytes = block_vote.serialize_to_vec();
// Cache our vote
block_info.vote = Some(block_vote);
nonce_request.message = block_vote_bytes;
}
/// Verify a chunk is a valid wsts packet. Returns the packet if it is valid, else None.
/// NOTE: The packet will be updated if the signer wishes to respond to NonceRequest
/// and SignatureShareRequests with a different message than what the coordinator originally sent.
/// This is done to prevent a malicious coordinator from sending a different message than what was
/// agreed upon and to support the case where the signer wishes to reject a block by voting no
fn verify_packet(
&mut self,
stacks_client: &StacksClient,
mut packet: Packet,
coordinator_public_key: &PublicKey,
) -> Option<Packet> {
// We only care about verified wsts packets. Ignore anything else.
if packet.verify(&self.state_machine.public_keys, coordinator_public_key) {
match &mut packet.msg {
Message::SignatureShareRequest(request) => {
if !self.validate_signature_share_request(request) {
return None;
}
}
Message::NonceRequest(request) => {
let Some(updated_block_info) =
self.validate_nonce_request(stacks_client, request)
else {
warn!("Failed to validate and parse nonce request");
return None;
};
self.signer_db
.insert_block(self.reward_cycle, &updated_block_info)
.unwrap_or_else(|_| panic!("{self}: Failed to insert block in DB"));
let process_request = updated_block_info.vote.is_some();
if !process_request {
debug!("Failed to validate nonce request");
return None;
}
}
_ => {
// Nothing to do for other message types
}
}
Some(packet)
} else {
debug!(
"{self}: Failed to verify wsts packet with {}: {packet:?}",
coordinator_public_key
);
None
}
}
/// Processes the operation results, broadcasting block acceptance or rejection messages
/// and DKG vote results accordingly
fn process_operation_results(
&mut self,
stacks_client: &StacksClient,
operation_results: &[OperationResult],
) {
for operation_result in operation_results {
// Signers only every trigger non-taproot signing rounds over blocks. Ignore SignTaproot results
match operation_result {
OperationResult::Sign(signature) => {
debug!("{self}: Received signature result");
self.process_signature(signature);
}
OperationResult::SignTaproot(_) => {
debug!("{self}: Received a signature result for a taproot signature. Nothing to broadcast as we currently sign blocks with a FROST signature.");
}
OperationResult::Dkg(aggregate_key) => {
self.process_dkg(stacks_client, aggregate_key);
}
OperationResult::SignError(e) => {