forked from empeje/core-eng
-
Notifications
You must be signed in to change notification settings - Fork 1
/
signing_round.rs
1796 lines (1593 loc) · 67.4 KB
/
signing_round.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
use bdk::miniscript::psbt::SighashError;
use chrono::Local;
use bitcoin::blockdata::opcodes::all;
use bitcoin::blockdata::script::Builder;
use bitcoin::consensus::serialize;
use bitcoin::hashes::Hash;
use bitcoin::psbt::{PartiallySignedTransaction, Prevouts};
use bitcoin::secp256k1::{All, Secp256k1, SecretKey};
use bitcoin::util::sighash::SighashCache;
use bitcoin::util::{base58, taproot};
use bitcoin::{Transaction, Txid};
use bitcoin::{
hashes::hex::FromHex,
EcdsaSighashType, KeyPair, Network, OutPoint, PrivateKey, PublicKey, SchnorrSighashType,
Script, TxOut, Witness, XOnlyPublicKey,
};
use stackslib::burnchains::bitcoin::address::{BitcoinAddress, SegwitBitcoinAddress};
use stackslib::burnchains::bitcoin::{
BitcoinNetworkType, BitcoinTransaction, BitcoinTxOutput,
};
use stackslib::burnchains::{
BurnchainBlockHeader, BurnchainTransaction, PrivateKey as PrivateKeyTrait,
};
use stackslib::chainstate::burn::operations::PegOutRequestOp;
use stackslib::chainstate::burn::Opcodes;
use stackslib::chainstate::stacks::address::PoxAddress;
use bitcoin::util::address::Address;
use stackslib::chainstate::stacks::{StacksPrivateKey, StacksTransaction, TransactionVersion};
use stackslib::types::chainstate::{BurnchainHeaderHash, StacksAddress};
use stackslib::util::hash::{Hash160, Sha256Sum};
use stackslib::vm::ContractName;
use hashbrown::{HashMap, HashSet};
use p256k1::{
ecdsa,
point::{Compressed, Point},
scalar::Scalar,
};
use rand::{random, Rng};
use rand_core::{CryptoRng, OsRng, RngCore};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::str::FromStr;
use std::thread;
use std::thread::sleep;
use std::time::Duration;
use bdk::miniscript::ToPublicKey;
use bitcoin::psbt::serialize::Serialize as TransactionSerializer;
use bitcoin::util::taproot::{TapBranchHash, TaprootSpendInfo, TapSighashHash};
use itertools::Itertools;
use tracing::{debug, info, warn};
use url::Url;
use wsts::{
common::{PolyCommitment, PublicNonce, SignatureShare},
traits::Signer as SignerTrait,
v1,
};
use std::io::Write;
use std::sync::{Arc, Mutex};
use crate::bitcoin_node::{BitcoinNode, LocalhostBitcoinNode, UTXO};
use crate::bitcoin_scripting::{create_refund_tx, create_script_refund, create_script_unspendable, create_tree, create_tx_from_user_to_script, get_current_block_height, sign_tx_script_refund, sign_tx_user_to_script};
use crate::bitcoin_wallet::BitcoinWallet;
use crate::peg_wallet::{BitcoinWallet as BitcoinWalletTrait, StacksWallet as PegWallet};
use crate::stacks_node::client::NodeClient;
use crate::stacks_wallet::StacksWallet;
use crate::{
config::PublicKeys,
signer::Signer as FrostSigner,
state_machine::{Error as StateMachineError, StateMachine, States},
util::{decrypt, encrypt, make_shared_secret},
};
use crate::signing_round::UtxoError::{InvalidUTXO, UTXOAmount};
use crate::stacks_node::StacksNode;
use stackslib::burnchains::Address as BitcoinAddressTrait;
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("InvalidPartyID")]
InvalidPartyID,
#[error("InvalidDkgPublicShare")]
InvalidDkgPublicShare,
#[error("InvalidDkgPrivateShares")]
InvalidDkgPrivateShares(Vec<u32>),
#[error("InvalidNonceResponse")]
InvalidNonceResponse,
#[error("InvalidSignatureShare")]
InvalidSignatureShare,
#[error("State Machine Error: {0}")]
StateMachineError(#[from] StateMachineError),
#[error("Error occured during signing: {0}")]
SigningError(#[from] SighashError),
#[error("The amount you're sending is smaller than the fee")]
FeeError,
}
#[derive(thiserror::Error, Debug, Clone, Serialize, Deserialize)]
pub enum UtxoError {
#[error("Invalid UTXO.")]
InvalidUTXO,
#[error("UTXO amount too low")]
UTXOAmount,
}
pub trait Signable {
fn hash(&self, hasher: &mut Sha256);
fn sign(&self, private_key: &Scalar) -> Result<Vec<u8>, ecdsa::Error> {
let mut hasher = Sha256::new();
self.hash(&mut hasher);
let hash = hasher.finalize();
match ecdsa::Signature::new(hash.as_slice(), private_key) {
Ok(sig) => Ok(sig.to_bytes().to_vec()),
Err(e) => Err(e),
}
}
fn verify(&self, signature: &[u8], public_key: &ecdsa::PublicKey) -> bool {
let mut hasher = Sha256::new();
self.hash(&mut hasher);
let hash = hasher.finalize();
let sig = match ecdsa::Signature::try_from(signature) {
Ok(sig) => sig,
Err(_) => return false,
};
sig.verify(hash.as_slice(), public_key)
}
}
pub struct SigningRound {
pub dkg_id: u64,
pub dkg_public_id: u64,
pub sign_id: u64,
pub sign_nonce_id: u64,
pub threshold: u32,
pub total_signers: u32,
pub total_keys: u32,
pub signer: Signer,
pub state: States,
pub commitments: BTreeMap<u32, PolyCommitment>,
pub shares: HashMap<u32, HashMap<u32, Vec<u8>>>,
pub public_nonces: Vec<PublicNonce>,
pub network_private_key: Scalar,
pub public_keys: PublicKeys,
// TODO: should be encrypted, i guess?
pub contract_name: ContractName,
pub contract_address: StacksAddress,
pub aggregate_public_key: Point,
pub stacks_private_key: StacksPrivateKey,
pub stacks_address: StacksAddress,
pub stacks_node_rpc_url: Url,
pub local_stacks_node: NodeClient,
pub stacks_wallet: StacksWallet,
pub stacks_version: TransactionVersion,
pub bitcoin_private_key: SecretKey,
pub bitcoin_xonly_public_key: XOnlyPublicKey,
pub bitcoin_node_rpc_url: Url,
pub local_bitcoin_node: LocalhostBitcoinNode,
pub bitcoin_wallet: BitcoinWallet,
pub transaction_fee: u64,
pub amount_to_script: u64,
pub fee_to_script: u64,
pub bitcoin_network: Network,
pub previous_transactions: Vec<(u64, Txid, Vec<Address>, u64)>,
pub amount_back_to_script: Vec<(u64, u64)>,
pub script_addresses: BTreeMap<PublicKey, BitcoinAddress>,
pub pox_transactions_block_heights: Arc<Mutex<Vec<u64>>>,
pub fund_each_block: bool,
}
pub struct Signer {
pub frost_signer: v1::Signer,
pub signer_id: u32,
}
impl StateMachine for SigningRound {
fn move_to(&mut self, state: States) -> Result<(), StateMachineError> {
self.can_move_to(&state)?;
self.state = state;
Ok(())
}
fn can_move_to(&self, state: &States) -> Result<(), StateMachineError> {
let prev_state = &self.state;
let accepted = match state {
States::Idle => true,
States::DkgPublicDistribute => {
prev_state == &States::Idle
|| prev_state == &States::DkgPublicGather
|| prev_state == &States::DkgPrivateDistribute
}
States::DkgPublicGather => prev_state == &States::DkgPublicDistribute,
States::DkgPrivateDistribute => prev_state == &States::DkgPublicGather,
States::DkgPrivateGather => prev_state == &States::DkgPrivateDistribute,
States::SignGather => prev_state == &States::Idle,
States::Signed => prev_state == &States::SignGather,
States::DegensScriptDistribute => prev_state == &States::Idle,
States::DegensScriptGather => prev_state == &States::DegensScriptDistribute,
// TODO degens: add states for scripts
};
if accepted {
info!("state change from {:?} to {:?}", prev_state, state);
Ok(())
} else {
Err(StateMachineError::BadStateChange(format!(
"{:?} to {:?}",
prev_state, state
)))
}
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub enum DkgStatus {
Success,
Failure(String),
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub enum MessageTypes {
DkgBegin(DkgBegin),
DkgPrivateBegin(DkgBegin),
DkgEnd(DkgEnd),
DkgPublicEnd(DkgEnd),
DkgPublicShare(DkgPublicShare),
DkgPrivateShares(DkgPrivateShares),
NonceRequest(NonceRequest),
NonceResponse(NonceResponse),
SignShareRequest(SignatureShareRequest),
SignShareResponse(SignatureShareResponse),
SigShareRequestPox(SigShareRequestPox),
SigShareResponsePox(SigShareResponsePox),
VoteOutActorRequest(VoteOutActorRequest),
POXTxidResponse(POXTxidResponse),
DegensCreateScriptsRequest(DegensScriptRequest),
DegensCreateScriptsResponse(DegensScriptResponse),
DegensSpendScripts(DegensSpendScript),
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct DkgPublicShare {
pub dkg_id: u64,
pub dkg_public_id: u64,
pub party_id: u32,
pub public_share: PolyCommitment,
}
impl Signable for DkgPublicShare {
fn hash(&self, hasher: &mut Sha256) {
hasher.update("DKG_PUBLIC_SHARE".as_bytes());
hasher.update(self.dkg_id.to_be_bytes());
hasher.update(self.dkg_public_id.to_be_bytes());
hasher.update(self.party_id.to_be_bytes());
for a in &self.public_share.A {
hasher.update(a.compress().as_bytes());
}
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct DkgPrivateShares {
pub dkg_id: u64,
pub key_id: u32,
/// Encrypt the shares using AES-GCM with a key derived from ECDH
pub private_shares: HashMap<u32, Vec<u8>>,
}
impl Signable for DkgPrivateShares {
fn hash(&self, hasher: &mut Sha256) {
hasher.update("DKG_PRIVATE_SHARES".as_bytes());
hasher.update(self.dkg_id.to_be_bytes());
hasher.update(self.key_id.to_be_bytes());
// make sure we iterate sequentially
// TODO: change this once WSTS goes to 1 based indexing for key_ids, or change to BTreeMap
for id in 0..self.private_shares.len() as u32 {
hasher.update(id.to_be_bytes());
hasher.update(&self.private_shares[&id]);
}
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct DkgBegin {
pub dkg_id: u64, //TODO: Strong typing for this, alternatively introduce a type alias
}
impl Signable for DkgBegin {
fn hash(&self, hasher: &mut Sha256) {
hasher.update("DKG_BEGIN".as_bytes());
hasher.update(self.dkg_id.to_be_bytes());
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct DkgEnd {
pub dkg_id: u64,
pub signer_id: u32,
pub status: DkgStatus,
}
impl Signable for DkgEnd {
fn hash(&self, hasher: &mut Sha256) {
hasher.update("DKG_END".as_bytes());
hasher.update(self.dkg_id.to_be_bytes());
hasher.update(self.signer_id.to_be_bytes());
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct NonceRequest {
pub dkg_id: u64,
pub sign_id: u64,
pub sign_nonce_id: u64,
}
impl Signable for NonceRequest {
fn hash(&self, hasher: &mut Sha256) {
hasher.update("NONCE_REQUEST".as_bytes());
hasher.update(self.dkg_id.to_be_bytes());
hasher.update(self.sign_id.to_be_bytes());
hasher.update(self.sign_nonce_id.to_be_bytes());
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct NonceResponse {
pub dkg_id: u64,
pub sign_id: u64,
pub sign_nonce_id: u64,
pub signer_id: u32,
pub key_ids: Vec<u32>,
pub nonces: Vec<PublicNonce>,
}
impl Signable for NonceResponse {
fn hash(&self, hasher: &mut Sha256) {
hasher.update("NONCE_RESPONSE".as_bytes());
hasher.update(self.dkg_id.to_be_bytes());
hasher.update(self.sign_id.to_be_bytes());
hasher.update(self.sign_nonce_id.to_be_bytes());
hasher.update(self.signer_id.to_be_bytes());
for key_id in &self.key_ids {
hasher.update(key_id.to_be_bytes());
}
for nonce in &self.nonces {
hasher.update(nonce.D.compress().as_bytes());
hasher.update(nonce.E.compress().as_bytes());
}
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct SignatureShareRequest {
pub dkg_id: u64,
pub sign_id: u64,
pub correlation_id: u64,
pub nonce_responses: Vec<NonceResponse>,
pub message: Vec<u8>,
}
impl Signable for SignatureShareRequest {
fn hash(&self, hasher: &mut Sha256) {
hasher.update("SIGNATURE_SHARE_REQUEST".as_bytes());
hasher.update(self.dkg_id.to_be_bytes());
hasher.update(self.sign_id.to_be_bytes());
hasher.update(self.correlation_id.to_be_bytes());
for nonce_response in &self.nonce_responses {
nonce_response.hash(hasher);
}
hasher.update(self.message.as_slice());
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct SignatureShareResponse {
pub dkg_id: u64,
pub sign_id: u64,
pub correlation_id: u64,
pub signer_id: u32,
pub signature_shares: Vec<SignatureShare>,
}
impl Signable for SignatureShareResponse {
fn hash(&self, hasher: &mut Sha256) {
hasher.update("SIGNATURE_SHARE_RESPONSE".as_bytes());
hasher.update(self.dkg_id.to_be_bytes());
hasher.update(self.sign_id.to_be_bytes());
hasher.update(self.correlation_id.to_be_bytes());
hasher.update(self.signer_id.to_be_bytes());
for signature_share in &self.signature_shares {
hasher.update(signature_share.id.to_be_bytes());
hasher.update(signature_share.z_i.to_bytes());
}
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct SigShareRequestPox {
pub dkg_id: u64,
pub sign_id: u64,
pub correlation_id: u64,
pub nonce_responses: Vec<NonceResponse>,
pub message: Vec<u8>,
pub transaction: Transaction,
}
impl Signable for SigShareRequestPox {
fn hash(&self, hasher: &mut Sha256) {
hasher.update("SIGSHARE_REQUEST_POX".as_bytes());
hasher.update(self.dkg_id.to_be_bytes());
hasher.update(self.sign_id.to_be_bytes());
hasher.update(self.correlation_id.to_be_bytes());
for nonce_response in &self.nonce_responses {
nonce_response.hash(hasher);
}
hasher.update(self.message.as_slice());
hasher.update(bitcoin::psbt::serialize::Serialize::serialize(&self.transaction).as_slice());
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct SigShareResponsePox {
pub dkg_id: u64,
pub sign_id: u64,
pub correlation_id: u64,
pub signer_id: u32,
pub signature_shares: Vec<SignatureShare>,
}
impl Signable for SigShareResponsePox {
fn hash(&self, hasher: &mut Sha256) {
hasher.update("SIGSHARE_RESPONSE_POX".as_bytes());
hasher.update(self.dkg_id.to_be_bytes());
hasher.update(self.sign_id.to_be_bytes());
hasher.update(self.correlation_id.to_be_bytes());
hasher.update(self.signer_id.to_be_bytes());
for signature_share in &self.signature_shares {
hasher.update(signature_share.id.to_be_bytes());
hasher.update(signature_share.z_i.to_bytes());
}
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct VoteOutActorRequest {
pub dkg_id: u64,
pub aggregate_public_key: Point,
pub actors_to_be_voted_out: Vec<StacksAddress>,
}
impl Signable for VoteOutActorRequest {
fn hash(&self, hasher: &mut Sha256) {
hasher.update("DEGENS_CREATE_SCRIPT_REQUEST".as_bytes());
hasher.update(self.dkg_id.to_be_bytes());
hasher.update(self.aggregate_public_key.to_string().as_bytes());
for actor in &self.actors_to_be_voted_out {
hasher.update(actor.to_string().as_bytes());
}
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct POXTxidResponse {
pub dkg_id: u64,
pub txid: Txid,
}
impl Signable for POXTxidResponse {
fn hash(&self, hasher: &mut Sha256) {
hasher.update("DEGENS_CREATE_SCRIPT_REQUEST".as_bytes());
hasher.update(self.dkg_id.to_be_bytes());
hasher.update(self.txid.to_vec().as_slice());
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct DegensScriptRequest {
pub dkg_id: u64,
pub fee_to_pox: u64,
pub aggregate_public_key: Point,
}
impl Signable for DegensScriptRequest {
fn hash(&self, hasher: &mut Sha256) {
hasher.update("DEGENS_CREATE_SCRIPT_REQUEST".as_bytes());
hasher.update(self.dkg_id.to_be_bytes());
hasher.update(self.fee_to_pox.to_be_bytes());
hasher.update(self.aggregate_public_key.to_string().as_bytes());
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct DegensScriptResponse {
pub signer_id: u32,
pub stacks_address: StacksAddress,
pub merkle_root: TapBranchHash,
pub utxo: Result<UTXO, UtxoError>,
}
impl Signable for DegensScriptResponse {
fn hash(&self, hasher: &mut Sha256) {
hasher.update("DEGENS_CREATE_SCRIPT_RESPONSE".as_bytes());
hasher.update(self.signer_id.to_be_bytes());
hasher.update(self.stacks_address.bytes.as_bytes());
hasher.update(self.stacks_address.version.to_be_bytes());
hasher.update(self.merkle_root.to_vec().as_slice());
match &self.utxo {
Ok(utxo) => {
hasher.update(utxo.address.as_bytes());
hasher.update(utxo.txid.as_bytes());
hasher.update(utxo.amount.to_be_bytes());
hasher.update(utxo.desc.as_bytes());
hasher.update(utxo.confirmations.to_be_bytes());
hasher.update(utxo.label.as_bytes());
hasher.update(utxo.redeemScript.as_bytes());
hasher.update(utxo.reused.to_string().as_bytes());
hasher.update(utxo.safe.to_string().as_bytes());
hasher.update(utxo.scriptPubKey.as_bytes());
hasher.update(utxo.solvable.to_string().as_bytes());
hasher.update(utxo.spendable.to_string().as_bytes());
hasher.update(utxo.vout.to_be_bytes());
hasher.update(utxo.witnessScript.as_bytes());
}
Err(_) => {
hasher.update("No good UTXO in the list.".as_bytes());
}
}
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct DegensSpendScript {
pub dkg_id: u64,
pub addresses: Vec<String>, // TODO degens: update to address type/alias
}
impl Signable for DegensSpendScript {
fn hash(&self, hasher: &mut Sha256) {
hasher.update("DEGENS_SPEND_SCRIPT".as_bytes());
hasher.update(self.dkg_id.to_be_bytes());
for address in &self.addresses {
hasher.update(address.as_bytes());
}
}
}
impl SigningRound {
pub fn new(
threshold: u32,
total_signers: u32,
total_keys: u32,
signer_id: u32,
key_ids: Vec<u32>,
network_private_key: Scalar,
public_keys: PublicKeys,
network: Network,
) -> SigningRound {
assert!(threshold <= total_keys);
let mut rng = OsRng;
let frost_signer = v1::Signer::new(signer_id, &key_ids, total_keys, threshold, &mut rng);
let signer = Signer {
frost_signer,
signer_id,
};
SigningRound {
dkg_id: 0,
dkg_public_id: 0,
sign_id: 1,
sign_nonce_id: 1,
threshold,
total_signers,
total_keys,
signer,
state: States::Idle,
commitments: BTreeMap::new(),
shares: HashMap::new(),
public_nonces: vec![],
network_private_key,
public_keys,
contract_name: ContractName::from(""),
contract_address: StacksAddress::new(26, Hash160([0; 20])),
aggregate_public_key: Point::new(),
stacks_private_key: StacksPrivateKey::new(),
stacks_address: StacksAddress::new(26, Hash160([0; 20])),
stacks_node_rpc_url: Url::from_str("").unwrap(),
local_stacks_node: NodeClient::new(
Url::from_str("").unwrap(),
ContractName::from(""),
StacksAddress::new(26, Hash160([0; 20])),
),
stacks_wallet: StacksWallet::new(
ContractName::from(""),
StacksAddress::from_string("").unwrap(),
StacksPrivateKey::new(),
StacksAddress::new(26, Hash160([0; 20])),
TransactionVersion::Testnet,
0,
),
stacks_version: TransactionVersion::Testnet,
bitcoin_private_key: SecretKey::new(&mut rng),
bitcoin_xonly_public_key: SecretKey::new(&mut rng)
.x_only_public_key(&Secp256k1::new())
.0,
bitcoin_node_rpc_url: Url::from_str("").unwrap(),
local_bitcoin_node: LocalhostBitcoinNode::new(Url::from_str("").unwrap()),
bitcoin_wallet: BitcoinWallet::new(
XOnlyPublicKey::from_str(
"cc8a4bc64d897bddc5fbc2f670f7a8ba0b386779106cf1223c6fc5d7cd6fc115",
)
.unwrap(),
network,
),
transaction_fee: 0,
amount_to_script: 0,
bitcoin_network: network,
previous_transactions: vec![],
amount_back_to_script: vec![],
fee_to_script: 0,
script_addresses: BTreeMap::new(),
pox_transactions_block_heights: Arc::new(Mutex::new(vec![])),
fund_each_block: true,
}
}
fn reset<T: RngCore + CryptoRng>(&mut self, dkg_id: u64, rng: &mut T) {
self.dkg_id = dkg_id;
self.dkg_public_id = 0;
self.commitments.clear();
self.shares.clear();
self.public_nonces.clear();
self.signer.frost_signer.reset_polys(rng);
}
pub fn process(&mut self, message: MessageTypes) -> Result<Vec<MessageTypes>, Error> {
let out_msgs = match message {
MessageTypes::DkgBegin(dkg_begin) => self.dkg_begin(dkg_begin),
MessageTypes::DkgPrivateBegin(_) => self.dkg_private_begin(),
MessageTypes::DkgPublicShare(dkg_public_shares) => {
self.dkg_public_share(dkg_public_shares)
}
MessageTypes::DkgPrivateShares(dkg_private_shares) => {
self.dkg_private_shares(dkg_private_shares)
}
MessageTypes::SignShareRequest(sign_share_request) => {
self.sign_share_request(sign_share_request)
}
MessageTypes::SigShareRequestPox(sigshare_request_pox) => {
self.sigshare_request_pox(sigshare_request_pox)
}
MessageTypes::NonceRequest(nonce_request) => {
self.nonce_request(nonce_request)
},
MessageTypes::VoteOutActorRequest(vote_out_request) => {
self.vote_miners_out_of_pool(vote_out_request)
}
MessageTypes::POXTxidResponse(txid_response) => {
self.add_txid_to_list(txid_response)
}
MessageTypes::DegensCreateScriptsRequest(degens_create_script) => {
self.degen_create_script(degens_create_script)
}
_ => Ok(vec![]), // TODO
};
match out_msgs {
Ok(mut out) => {
if self.public_shares_done() {
debug!(
"public_shares_done==true. commitments {}",
self.commitments.len()
);
let dkg_end_msgs = self.dkg_public_ended()?;
out.push(dkg_end_msgs);
self.move_to(States::DkgPrivateDistribute)?;
} else if self.can_dkg_end() {
debug!(
"can_dkg_end==true. shares {} commitments {}",
self.shares.len(),
self.commitments.len()
);
let dkg_end_msgs = self.dkg_ended()?;
out.push(dkg_end_msgs);
self.move_to(States::Idle)?;
}
Ok(out)
}
Err(e) => Err(e),
}
}
fn dkg_public_ended(&mut self) -> Result<MessageTypes, Error> {
let dkg_end = DkgEnd {
dkg_id: self.dkg_id,
signer_id: self.signer.signer_id,
status: DkgStatus::Success,
};
let dkg_end = MessageTypes::DkgPublicEnd(dkg_end);
info!(
"DKG_END round #{} signer_id {}",
self.dkg_id, self.signer.signer_id
);
Ok(dkg_end)
}
fn dkg_ended(&mut self) -> Result<MessageTypes, Error> {
let polys: Vec<PolyCommitment> = self.commitments.clone().into_values().collect();
let mut decrypted_shares = HashMap::new();
// go through private shares, and decrypt any for owned keys, leaving the rest as zero scalars
let key_ids: HashSet<u32> = self.signer.frost_signer.get_key_ids().into_iter().collect();
let mut invalid_dkg_private_shares = Vec::new();
for (src_key_id, encrypted_shares) in &self.shares {
let mut decrypted_key_shares = HashMap::new();
for (dst_key_id, private_share) in encrypted_shares {
if key_ids.contains(dst_key_id) {
debug!(
"decrypting dkg private share for key_id #{}",
dst_key_id + 1
);
let compressed =
Compressed::from(self.public_keys.key_ids[&(src_key_id + 1)].to_bytes());
let src_public_key = Point::try_from(&compressed).unwrap();
let shared_secret =
make_shared_secret(&self.network_private_key, &src_public_key);
match decrypt(&shared_secret, private_share) {
Ok(plain) => match Scalar::try_from(&plain[..]) {
Ok(s) => {
decrypted_key_shares.insert(*dst_key_id, s);
}
Err(e) => {
warn!("Failed to parse Scalar for dkg private share from key_id {} to key_id {}: {:?}", src_key_id, dst_key_id, e);
invalid_dkg_private_shares.push(*src_key_id);
}
},
Err(e) => {
warn!("Failed to decrypt dkg private share from key_id {} to key_id {}: {:?}", src_key_id, dst_key_id, e);
invalid_dkg_private_shares.push(*src_key_id);
}
}
} else {
decrypted_key_shares.insert(*dst_key_id, Scalar::new());
}
}
decrypted_shares.insert(*src_key_id, decrypted_key_shares);
}
let dkg_end = if invalid_dkg_private_shares.is_empty() {
match self
.signer
.frost_signer
.compute_secrets(&decrypted_shares, &polys)
{
Ok(()) => DkgEnd {
dkg_id: self.dkg_id,
signer_id: self.signer.signer_id,
status: DkgStatus::Success,
},
Err(dkg_error_map) => DkgEnd {
dkg_id: self.dkg_id,
signer_id: self.signer.signer_id,
status: DkgStatus::Failure(format!("{:?}", dkg_error_map)),
},
}
} else {
DkgEnd {
dkg_id: self.dkg_id,
signer_id: self.signer.signer_id,
status: DkgStatus::Failure(format!("{:?}", invalid_dkg_private_shares)),
}
};
let dkg_end = MessageTypes::DkgEnd(dkg_end);
info!(
"DKG_END round #{} signer_id {}",
self.dkg_id, self.signer.signer_id
);
Ok(dkg_end)
}
fn public_shares_done(&self) -> bool {
debug!(
"public_shares_done state {:?} commitments {}",
self.state,
self.commitments.len(),
);
self.state == States::DkgPublicGather
&& self.commitments.len() == usize::try_from(self.total_keys).unwrap()
}
fn can_dkg_end(&self) -> bool {
debug!(
"can_dkg_end state {:?} commitments {} shares {}",
self.state,
self.commitments.len(),
self.shares.len()
);
self.state == States::DkgPrivateGather
&& self.commitments.len() == usize::try_from(self.total_keys).unwrap()
&& self.shares.len() == usize::try_from(self.total_keys).unwrap()
}
fn nonce_request(&mut self, nonce_request: NonceRequest) -> Result<Vec<MessageTypes>, Error> {
let mut rng = OsRng;
let mut msgs = vec![];
let signer_id = self.signer.signer_id;
let key_ids = self.signer.frost_signer.get_key_ids();
let nonces = self.signer.frost_signer.gen_nonces(&mut rng);
let response = NonceResponse {
dkg_id: nonce_request.dkg_id,
sign_id: nonce_request.sign_id,
sign_nonce_id: nonce_request.sign_nonce_id,
signer_id,
key_ids,
nonces,
};
let response = MessageTypes::NonceResponse(response);
info!(
"nonce request with dkg_id {:?}. response sent from signer_id {}",
nonce_request.dkg_id, signer_id
);
msgs.push(response);
Ok(msgs)
}
fn sign_share_request(
&mut self,
sign_request: SignatureShareRequest,
) -> Result<Vec<MessageTypes>, Error> {
let mut msgs = vec![];
let signer_ids = sign_request
.nonce_responses
.iter()
.map(|nr| nr.signer_id)
.collect::<Vec<u32>>();
info!("Got SignatureShareRequest for signer_ids {:?}", signer_ids);
for signer_id in &signer_ids {
if *signer_id == self.signer.signer_id {
let key_ids: Vec<u32> = sign_request
.nonce_responses
.iter()
.flat_map(|nr| nr.key_ids.iter().copied())
.collect::<Vec<u32>>();
let nonces = sign_request
.nonce_responses
.iter()
.flat_map(|nr| nr.nonces.clone())
.collect::<Vec<PublicNonce>>();
let signature_shares = self.signer.frost_signer.sign(
&sign_request.message,
&signer_ids,
&key_ids,
&nonces,
);
let response = SignatureShareResponse {
dkg_id: sign_request.dkg_id,
sign_id: sign_request.sign_id,
correlation_id: sign_request.correlation_id,
signer_id: *signer_id,
signature_shares,
};
info!(
"Sending SignatureShareResponse for signer_id {:?}",
signer_id
);
let response = MessageTypes::SignShareResponse(response);
msgs.push(response);
} else {
debug!("SignShareRequest for {} dropped.", signer_id);
}
}
Ok(msgs)
}
fn sigshare_request_pox(
&mut self,
sign_request: SigShareRequestPox,
) -> Result<Vec<MessageTypes>, Error> {
let mut msgs = vec![];
let secp = Secp256k1::new();
let keypair = KeyPair::from_secret_key(&secp, &self.bitcoin_private_key);
// let aggregate_compressed = degens_create_script.aggregate_public_key.compress();
// let aggregate_x_only = PublicKey::from_slice(aggregate_compressed.as_bytes()).unwrap().to_x_only_pubkey();
let script_1 = create_script_refund(&self.bitcoin_xonly_public_key, 100);
let script_2 = create_script_unspendable();
// TODO: degens - change keypair xonly back to aggregate_x_only after done with testing
let (_, script_address) = create_tree(&secp, keypair.x_only_public_key().0, self.bitcoin_network, &script_1, &script_2);
let transaction_clone = sign_request.transaction;
let transaction_outputs = &transaction_clone.output;
let transaction_inputs = &transaction_clone.input;
let mut pox_addresses = vec![
Address::from_str("bcrt1phvt5tfz4hlkth0k7ls9djweuv9rwv5a0s5sa9085umupftnyalxq0zx28d").unwrap(),
Address::from_str("bcrt1pdsavc4yrdq0sdmjcmf7967eeem2ny6vzr4f8m7dyemcvncs0xtwsc85zdq").unwrap()
];
let mut pox_total_amount: u64 = 0;
let pox_sc_amount = self.local_stacks_node.get_pool_total_spend_per_block(self.stacks_wallet.address()).unwrap_or(0) as u64;
transaction_outputs.iter().for_each(|output| {
match Address::from_script(&output.script_pubkey, self.bitcoin_network) {
Ok(address) => {
if pox_addresses.contains(&address) {
pox_addresses.retain(|user| user != &address);
pox_total_amount = pox_total_amount + output.value;
}
}
Err(e) => {
info!("Couldn't retreive address from UTXO: {:?}", e);
}
}
});
let script_utxos = self.local_bitcoin_node.list_unspent(&script_address).unwrap_or(vec![]);
let number_of_signers = transaction_inputs.len() as u64;
let total_amount = self.local_stacks_node.get_pool_total_spend_per_block(self.stacks_wallet.address()).unwrap_or(0) as u64;
let fee = 1000;
let mut found_utxo_in_inputs = false;
let mut found_correct_output = self.fund_each_block;
for utxo in script_utxos {
for input in transaction_inputs {
if input.previous_output.txid.to_string() == utxo.txid && input.previous_output.vout == utxo.vout {
found_utxo_in_inputs = true;
break
}
}
if utxo.amount > (total_amount + fee) / number_of_signers {
let amount_back = utxo.amount - ((total_amount + fee) / number_of_signers);
for output in transaction_outputs {
if Script::from_str(&utxo.scriptPubKey).unwrap_or(Script::new()).eq(&output.script_pubkey) && amount_back == output.value {
found_correct_output = true;
break
}
}
}
if found_correct_output && found_utxo_in_inputs {
break
}
}
if pox_addresses.len() == 0 && pox_total_amount == pox_sc_amount && found_correct_output && found_utxo_in_inputs {
let signer_ids = sign_request
.nonce_responses
.iter()
.map(|nr| nr.signer_id)
.collect::<Vec<u32>>();
info!("Got SigShareRequestPox for signer_ids {:?}", signer_ids);
for signer_id in &signer_ids {
if *signer_id == self.signer.signer_id {
let key_ids: Vec<u32> = sign_request
.nonce_responses
.iter()
.flat_map(|nr| nr.key_ids.iter().copied())
.collect::<Vec<u32>>();
let nonces = sign_request
.nonce_responses
.iter()
.flat_map(|nr| nr.nonces.clone())