-
Notifications
You must be signed in to change notification settings - Fork 681
/
Copy pathmod.rs
1676 lines (1479 loc) · 56.8 KB
/
mod.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 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;
use std::convert::TryFrom;
use std::default::Default;
use std::error;
use std::fmt;
use std::io;
use std::marker::PhantomData;
use rusqlite::Error as sqlite_error;
use crate::chainstate::burn::distribution::BurnSamplePoint;
use crate::chainstate::burn::operations::leader_block_commit::OUTPUTS_PER_COMMIT;
use crate::chainstate::burn::operations::BlockstackOperationType;
use crate::chainstate::burn::operations::Error as op_error;
use crate::chainstate::burn::operations::LeaderKeyRegisterOp;
use crate::chainstate::burn::ConsensusHash;
use crate::chainstate::stacks::StacksPublicKey;
use crate::core::*;
use crate::net::neighbors::MAX_NEIGHBOR_BLOCK_DELAY;
use crate::util_lib::db::Error as db_error;
use stacks_common::address::AddressHashMode;
use stacks_common::util::hash::Hash160;
use stacks_common::util::secp256k1::MessageSignature;
use crate::types::chainstate::BurnchainHeaderHash;
use crate::types::chainstate::PoxId;
use crate::types::chainstate::StacksAddress;
use crate::types::chainstate::TrieHash;
use self::bitcoin::indexer::{
BITCOIN_MAINNET as BITCOIN_NETWORK_ID_MAINNET, BITCOIN_MAINNET_NAME,
BITCOIN_REGTEST as BITCOIN_NETWORK_ID_REGTEST, BITCOIN_REGTEST_NAME,
BITCOIN_TESTNET as BITCOIN_NETWORK_ID_TESTNET, BITCOIN_TESTNET_NAME,
};
use self::bitcoin::Error as btc_error;
use self::bitcoin::{
BitcoinBlock, BitcoinInputType, BitcoinTransaction, BitcoinTxInput, BitcoinTxOutput,
};
pub use stacks_common::types::{Address, PrivateKey, PublicKey};
/// This module contains drivers and types for all burn chains we support.
pub mod bitcoin;
pub mod burnchain;
pub mod db;
pub mod indexer;
#[derive(Serialize, Deserialize)]
pub struct Txid(pub [u8; 32]);
impl_array_newtype!(Txid, u8, 32);
impl_array_hexstring_fmt!(Txid);
impl_byte_array_newtype!(Txid, u8, 32);
pub const TXID_ENCODED_SIZE: u32 = 32;
pub const MAGIC_BYTES_LENGTH: usize = 2;
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct MagicBytes([u8; MAGIC_BYTES_LENGTH]);
impl_array_newtype!(MagicBytes, u8, MAGIC_BYTES_LENGTH);
impl MagicBytes {
pub fn default() -> MagicBytes {
BLOCKSTACK_MAGIC_MAINNET
}
}
pub const BLOCKSTACK_MAGIC_MAINNET: MagicBytes = MagicBytes([105, 100]); // 'id'
#[derive(Debug, PartialEq, Clone)]
pub struct BurnchainParameters {
chain_name: String,
network_name: String,
network_id: u32,
stable_confirmations: u32,
consensus_hash_lifetime: u32,
pub first_block_height: u64,
pub first_block_hash: BurnchainHeaderHash,
pub first_block_timestamp: u32,
pub initial_reward_start_block: u64,
}
impl BurnchainParameters {
pub fn from_params(chain: &str, network: &str) -> Option<BurnchainParameters> {
match (chain, network) {
("bitcoin", "mainnet") => Some(BurnchainParameters::bitcoin_mainnet()),
("bitcoin", "testnet") => Some(BurnchainParameters::bitcoin_testnet()),
("bitcoin", "regtest") => Some(BurnchainParameters::bitcoin_regtest()),
_ => None,
}
}
pub fn bitcoin_mainnet() -> BurnchainParameters {
BurnchainParameters {
chain_name: "bitcoin".to_string(),
network_name: BITCOIN_MAINNET_NAME.to_string(),
network_id: BITCOIN_NETWORK_ID_MAINNET,
stable_confirmations: 7,
consensus_hash_lifetime: 24,
first_block_height: BITCOIN_MAINNET_FIRST_BLOCK_HEIGHT,
first_block_hash: BurnchainHeaderHash::from_hex(BITCOIN_MAINNET_FIRST_BLOCK_HASH)
.unwrap(),
first_block_timestamp: BITCOIN_MAINNET_FIRST_BLOCK_TIMESTAMP,
initial_reward_start_block: BITCOIN_MAINNET_INITIAL_REWARD_START_BLOCK,
}
}
pub fn bitcoin_testnet() -> BurnchainParameters {
BurnchainParameters {
chain_name: "bitcoin".to_string(),
network_name: BITCOIN_TESTNET_NAME.to_string(),
network_id: BITCOIN_NETWORK_ID_TESTNET,
stable_confirmations: 7,
consensus_hash_lifetime: 24,
first_block_height: BITCOIN_TESTNET_FIRST_BLOCK_HEIGHT,
first_block_hash: BurnchainHeaderHash::from_hex(BITCOIN_TESTNET_FIRST_BLOCK_HASH)
.unwrap(),
first_block_timestamp: BITCOIN_TESTNET_FIRST_BLOCK_TIMESTAMP,
initial_reward_start_block: BITCOIN_TESTNET_FIRST_BLOCK_HEIGHT - 10_000,
}
}
pub fn bitcoin_regtest() -> BurnchainParameters {
BurnchainParameters {
chain_name: "bitcoin".to_string(),
network_name: BITCOIN_REGTEST_NAME.to_string(),
network_id: BITCOIN_NETWORK_ID_REGTEST,
stable_confirmations: 1,
consensus_hash_lifetime: 24,
first_block_height: BITCOIN_REGTEST_FIRST_BLOCK_HEIGHT,
first_block_hash: BurnchainHeaderHash::from_hex(BITCOIN_REGTEST_FIRST_BLOCK_HASH)
.unwrap(),
first_block_timestamp: BITCOIN_REGTEST_FIRST_BLOCK_TIMESTAMP,
initial_reward_start_block: BITCOIN_REGTEST_FIRST_BLOCK_HEIGHT,
}
}
pub fn is_testnet(network_id: u32) -> bool {
match network_id {
BITCOIN_NETWORK_ID_TESTNET | BITCOIN_NETWORK_ID_REGTEST => true,
_ => false,
}
}
}
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct BurnchainSigner {
pub hash_mode: AddressHashMode,
pub num_sigs: usize,
pub public_keys: Vec<StacksPublicKey>,
}
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct BurnchainRecipient {
pub address: StacksAddress,
pub amount: u64,
}
#[derive(Debug, PartialEq, Clone)]
pub enum BurnchainTransaction {
Bitcoin(BitcoinTransaction),
// TODO: fill in more types as we support them
}
impl BurnchainTransaction {
pub fn txid(&self) -> Txid {
match *self {
BurnchainTransaction::Bitcoin(ref btc) => btc.txid.clone(),
}
}
pub fn vtxindex(&self) -> u32 {
match *self {
BurnchainTransaction::Bitcoin(ref btc) => btc.vtxindex,
}
}
pub fn opcode(&self) -> u8 {
match *self {
BurnchainTransaction::Bitcoin(ref btc) => btc.opcode,
}
}
pub fn data(&self) -> Vec<u8> {
match *self {
BurnchainTransaction::Bitcoin(ref btc) => btc.data.clone(),
}
}
pub fn num_signers(&self) -> usize {
match *self {
BurnchainTransaction::Bitcoin(ref btc) => btc.inputs.len(),
}
}
pub fn get_signers(&self) -> Vec<BurnchainSigner> {
match *self {
BurnchainTransaction::Bitcoin(ref btc) => btc
.inputs
.iter()
.map(|ref i| BurnchainSigner::from_bitcoin_input(i))
.collect(),
}
}
pub fn get_signer(&self, input: usize) -> Option<BurnchainSigner> {
match *self {
BurnchainTransaction::Bitcoin(ref btc) => btc
.inputs
.get(input)
.map(|ref i| BurnchainSigner::from_bitcoin_input(i)),
}
}
pub fn get_input_tx_ref(&self, input: usize) -> Option<&(Txid, u32)> {
match self {
BurnchainTransaction::Bitcoin(ref btc) => {
btc.inputs.get(input).map(|txin| &txin.tx_ref)
}
}
}
pub fn get_recipients(&self) -> Vec<BurnchainRecipient> {
match *self {
BurnchainTransaction::Bitcoin(ref btc) => btc
.outputs
.iter()
.map(|ref o| BurnchainRecipient::from_bitcoin_output(o))
.collect(),
}
}
pub fn get_burn_amount(&self) -> u64 {
match *self {
BurnchainTransaction::Bitcoin(ref btc) => btc.data_amt,
}
}
}
#[derive(Debug, PartialEq, Clone)]
pub enum BurnchainBlock {
Bitcoin(BitcoinBlock),
// TODO: fill in some more types as we support them
}
#[derive(Debug, PartialEq, Clone)]
pub struct BurnchainBlockHeader {
pub block_height: u64,
pub block_hash: BurnchainHeaderHash,
pub parent_block_hash: BurnchainHeaderHash,
pub num_txs: u64,
pub timestamp: u64,
}
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct Burnchain {
pub peer_version: u32,
pub network_id: u32,
pub chain_name: String,
pub network_name: String,
pub working_dir: String,
pub consensus_hash_lifetime: u32,
pub stable_confirmations: u32,
pub first_block_height: u64,
pub first_block_hash: BurnchainHeaderHash,
pub first_block_timestamp: u32,
pub pox_constants: PoxConstants,
pub initial_reward_start_block: u64,
}
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct PoxConstants {
/// the length (in burn blocks) of the reward cycle
pub reward_cycle_length: u32,
/// the length (in burn blocks) of the prepare phase
pub prepare_length: u32,
/// the number of confirmations a PoX anchor block must
/// receive in order to become the anchor. must be at least > prepare_length/2
pub anchor_threshold: u32,
/// fraction of liquid STX that must vote to reject PoX for
/// it to revert to PoB in the next reward cycle
pub pox_rejection_fraction: u64,
/// percentage of liquid STX that must participate for PoX
/// to occur
pub pox_participation_threshold_pct: u64,
/// last+1 block height of sunset phase
pub sunset_end: u64,
/// first block height of sunset phase
pub sunset_start: u64,
_shadow: PhantomData<()>,
}
impl PoxConstants {
pub fn new(
reward_cycle_length: u32,
prepare_length: u32,
anchor_threshold: u32,
pox_rejection_fraction: u64,
pox_participation_threshold_pct: u64,
sunset_start: u64,
sunset_end: u64,
) -> PoxConstants {
assert!(anchor_threshold > (prepare_length / 2));
assert!(prepare_length < reward_cycle_length);
assert!(sunset_start <= sunset_end);
PoxConstants {
reward_cycle_length,
prepare_length,
anchor_threshold,
pox_rejection_fraction,
pox_participation_threshold_pct,
sunset_start,
sunset_end,
_shadow: PhantomData,
}
}
#[cfg(test)]
pub fn test_default() -> PoxConstants {
// 20 reward slots; 10 prepare-phase slots
PoxConstants::new(10, 5, 3, 25, 5, 5000, 10000)
}
pub fn reward_slots(&self) -> u32 {
(self.reward_cycle_length - self.prepare_length) * (OUTPUTS_PER_COMMIT as u32)
}
/// is participating_ustx enough to engage in PoX in the next reward cycle?
pub fn enough_participation(&self, participating_ustx: u128, liquid_ustx: u128) -> bool {
participating_ustx
.checked_mul(100)
.expect("OVERFLOW: uSTX overflowed u128")
> liquid_ustx
.checked_mul(self.pox_participation_threshold_pct as u128)
.expect("OVERFLOW: uSTX overflowed u128")
}
pub fn mainnet_default() -> PoxConstants {
PoxConstants::new(
POX_REWARD_CYCLE_LENGTH,
POX_PREPARE_WINDOW_LENGTH,
80,
25,
5,
BITCOIN_MAINNET_FIRST_BLOCK_HEIGHT + POX_SUNSET_START,
BITCOIN_MAINNET_FIRST_BLOCK_HEIGHT + POX_SUNSET_END,
)
}
pub fn testnet_default() -> PoxConstants {
PoxConstants::new(
POX_REWARD_CYCLE_LENGTH / 2, // 1050
POX_PREPARE_WINDOW_LENGTH / 2, // 50
40,
12,
2,
BITCOIN_TESTNET_FIRST_BLOCK_HEIGHT + POX_SUNSET_START,
BITCOIN_TESTNET_FIRST_BLOCK_HEIGHT + POX_SUNSET_END,
) // total liquid supply is 40000000000000000 µSTX
}
pub fn regtest_default() -> PoxConstants {
PoxConstants::new(
5,
1,
1,
3333333333333333,
1,
BITCOIN_REGTEST_FIRST_BLOCK_HEIGHT + POX_SUNSET_START,
BITCOIN_REGTEST_FIRST_BLOCK_HEIGHT + POX_SUNSET_END,
)
}
}
/// Structure for encoding our view of the network
#[derive(Debug, PartialEq, Clone)]
pub struct BurnchainView {
pub burn_block_height: u64, // last-seen block height (at chain tip)
pub burn_block_hash: BurnchainHeaderHash, // last-seen burn block hash
pub burn_stable_block_height: u64, // latest stable block height (e.g. chain tip minus 7)
pub burn_stable_block_hash: BurnchainHeaderHash, // latest stable burn block hash
pub last_burn_block_hashes: HashMap<u64, BurnchainHeaderHash>, // map all block heights from burn_block_height back to the oldest one we'll take for considering the peer a neighbor
}
/// The burnchain block's encoded state transition:
/// -- the new burn distribution
/// -- the sequence of valid blockstack operations that went into it
/// -- the set of previously-accepted leader VRF keys consumed
#[derive(Debug, Clone)]
pub struct BurnchainStateTransition {
pub burn_dist: Vec<BurnSamplePoint>,
pub accepted_ops: Vec<BlockstackOperationType>,
pub consumed_leader_keys: Vec<LeaderKeyRegisterOp>,
}
/// The burnchain block's state transition's ops:
/// -- the new burn distribution
/// -- the sequence of valid blockstack operations that went into it
/// -- the set of previously-accepted leader VRF keys consumed
#[derive(Debug, Clone)]
pub struct BurnchainStateTransitionOps {
pub accepted_ops: Vec<BlockstackOperationType>,
pub consumed_leader_keys: Vec<LeaderKeyRegisterOp>,
}
#[derive(Debug)]
pub enum Error {
/// Unsupported burn chain
UnsupportedBurnchain,
/// Bitcoin-related error
Bitcoin(btc_error),
/// burn database error
DBError(db_error),
/// Download error
DownloadError(btc_error),
/// Parse error
ParseError,
/// Thread channel error
ThreadChannelError,
/// Missing headers
MissingHeaders,
/// Missing parent block
MissingParentBlock,
/// Remote burnchain peer has misbehaved
BurnchainPeerBroken,
/// filesystem error
FSError(io::Error),
/// Operation processing error
OpError(op_error),
/// Try again error
TrySyncAgain,
UnknownBlock(BurnchainHeaderHash),
NonCanonicalPoxId(PoxId, PoxId),
CoordinatorClosed,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::UnsupportedBurnchain => write!(f, "Unsupported burnchain"),
Error::Bitcoin(ref btce) => fmt::Display::fmt(btce, f),
Error::DBError(ref dbe) => fmt::Display::fmt(dbe, f),
Error::DownloadError(ref btce) => fmt::Display::fmt(btce, f),
Error::ParseError => write!(f, "Parse error"),
Error::MissingHeaders => write!(f, "Missing block headers"),
Error::MissingParentBlock => write!(f, "Missing parent block"),
Error::ThreadChannelError => write!(f, "Error in thread channel"),
Error::BurnchainPeerBroken => write!(f, "Remote burnchain peer has misbehaved"),
Error::FSError(ref e) => fmt::Display::fmt(e, f),
Error::OpError(ref e) => fmt::Display::fmt(e, f),
Error::TrySyncAgain => write!(f, "Try synchronizing again"),
Error::UnknownBlock(block) => write!(f, "Unknown burnchain block {}", block),
Error::NonCanonicalPoxId(parent, child) => write!(
f,
"{} is not a descendant of the canonical parent PoXId: {}",
parent, child
),
Error::CoordinatorClosed => write!(f, "ChainsCoordinator channel hung up"),
}
}
}
impl error::Error for Error {
fn cause(&self) -> Option<&dyn error::Error> {
match *self {
Error::UnsupportedBurnchain => None,
Error::Bitcoin(ref e) => Some(e),
Error::DBError(ref e) => Some(e),
Error::DownloadError(ref e) => Some(e),
Error::ParseError => None,
Error::MissingHeaders => None,
Error::MissingParentBlock => None,
Error::ThreadChannelError => None,
Error::BurnchainPeerBroken => None,
Error::FSError(ref e) => Some(e),
Error::OpError(ref e) => Some(e),
Error::TrySyncAgain => None,
Error::UnknownBlock(_) => None,
Error::NonCanonicalPoxId(_, _) => None,
Error::CoordinatorClosed => None,
}
}
}
impl From<db_error> for Error {
fn from(e: db_error) -> Error {
Error::DBError(e)
}
}
impl From<sqlite_error> for Error {
fn from(e: sqlite_error) -> Error {
Error::DBError(db_error::SqliteError(e))
}
}
impl From<btc_error> for Error {
fn from(e: btc_error) -> Error {
Error::Bitcoin(e)
}
}
impl BurnchainView {
#[cfg(test)]
pub fn make_test_data(&mut self) {
let oldest_height = if self.burn_stable_block_height < MAX_NEIGHBOR_BLOCK_DELAY {
0
} else {
self.burn_stable_block_height - MAX_NEIGHBOR_BLOCK_DELAY
};
let mut ret = HashMap::new();
for i in oldest_height..self.burn_block_height + 1 {
if i == self.burn_stable_block_height {
ret.insert(i, self.burn_stable_block_hash.clone());
} else if i == self.burn_block_height {
ret.insert(i, self.burn_block_hash.clone());
} else {
let data = {
use sha2::Digest;
use sha2::Sha256;
let mut hasher = Sha256::new();
hasher.update(&i.to_le_bytes());
hasher.finalize()
};
let mut data_32 = [0x00; 32];
data_32.copy_from_slice(&data[0..32]);
ret.insert(i, BurnchainHeaderHash(data_32));
}
}
self.last_burn_block_hashes = ret;
}
}
#[cfg(test)]
pub mod test {
use std::collections::HashMap;
use crate::burnchains::db::*;
use crate::burnchains::Burnchain;
use crate::burnchains::*;
use crate::chainstate::burn::db::sortdb::*;
use crate::chainstate::burn::operations::BlockstackOperationType;
use crate::chainstate::burn::operations::*;
use crate::chainstate::burn::*;
use crate::chainstate::coordinator::comm::*;
use crate::chainstate::coordinator::*;
use crate::chainstate::stacks::*;
use crate::util_lib::db::*;
use stacks_common::address::*;
use stacks_common::util::get_epoch_time_secs;
use stacks_common::util::hash::*;
use stacks_common::util::secp256k1::*;
use stacks_common::util::vrf::*;
use crate::types::chainstate::{BlockHeaderHash, SortitionId, VRFSeed};
use super::*;
impl Txid {
pub fn from_test_data(
block_height: u64,
vtxindex: u32,
burn_header_hash: &BurnchainHeaderHash,
noise: u64,
) -> Txid {
let mut bytes = vec![];
bytes.extend_from_slice(&block_height.to_be_bytes());
bytes.extend_from_slice(&vtxindex.to_be_bytes());
bytes.extend_from_slice(burn_header_hash.as_bytes());
bytes.extend_from_slice(&noise.to_be_bytes());
let h = DoubleSha256::from_data(&bytes[..]);
let mut hb = [0u8; 32];
hb.copy_from_slice(h.as_bytes());
Txid(hb)
}
}
pub fn BurnchainHeaderHash_from_test_data(
block_height: u64,
index_root: &TrieHash,
noise: u64,
) -> BurnchainHeaderHash {
let mut bytes = vec![];
bytes.extend_from_slice(&block_height.to_be_bytes());
bytes.extend_from_slice(index_root.as_bytes());
bytes.extend_from_slice(&noise.to_be_bytes());
let h = DoubleSha256::from_data(&bytes[..]);
let mut hb = [0u8; 32];
hb.copy_from_slice(h.as_bytes());
BurnchainHeaderHash(hb)
}
impl BurnchainBlockHeader {
pub fn from_parent_snapshot(
parent_sn: &BlockSnapshot,
block_hash: BurnchainHeaderHash,
num_txs: u64,
) -> BurnchainBlockHeader {
BurnchainBlockHeader {
block_height: parent_sn.block_height + 1,
block_hash: block_hash,
parent_block_hash: parent_sn.burn_header_hash.clone(),
num_txs: num_txs,
timestamp: get_epoch_time_secs(),
}
}
}
#[derive(Debug, Clone)]
pub struct TestBurnchainBlock {
pub block_height: u64,
pub parent_snapshot: BlockSnapshot,
pub txs: Vec<BlockstackOperationType>,
pub fork_id: u64,
pub timestamp: u64,
}
#[derive(Debug, Clone)]
pub struct TestBurnchainFork {
pub start_height: u64,
pub mined: u64,
pub tip_index_root: TrieHash,
pub tip_header_hash: BurnchainHeaderHash,
pub tip_sortition_id: SortitionId,
pub pending_blocks: Vec<TestBurnchainBlock>,
pub blocks: Vec<TestBurnchainBlock>,
pub fork_id: u64,
}
pub struct TestBurnchainNode {
pub sortdb: SortitionDB,
pub dirty: bool,
pub burnchain: Burnchain,
}
#[derive(Debug, Clone)]
pub struct TestMiner {
pub burnchain: Burnchain,
pub privks: Vec<StacksPrivateKey>,
pub num_sigs: u16,
pub hash_mode: AddressHashMode,
pub microblock_privks: Vec<StacksPrivateKey>,
pub vrf_keys: Vec<VRFPrivateKey>,
pub vrf_key_map: HashMap<VRFPublicKey, VRFPrivateKey>,
pub block_commits: Vec<LeaderBlockCommitOp>,
pub id: usize,
pub nonce: u64,
pub spent_at_nonce: HashMap<u64, u128>, // how much uSTX this miner paid in a given tx's nonce
pub test_with_tx_fees: bool, // set to true to make certain helper methods attach a pre-defined tx fee
}
pub struct TestMinerFactory {
pub key_seed: [u8; 32],
pub next_miner_id: usize,
}
impl TestMiner {
pub fn new(
burnchain: &Burnchain,
privks: &Vec<StacksPrivateKey>,
num_sigs: u16,
hash_mode: &AddressHashMode,
) -> TestMiner {
TestMiner {
burnchain: burnchain.clone(),
privks: privks.clone(),
num_sigs,
hash_mode: hash_mode.clone(),
microblock_privks: vec![],
vrf_keys: vec![],
vrf_key_map: HashMap::new(),
block_commits: vec![],
id: 0,
nonce: 0,
spent_at_nonce: HashMap::new(),
test_with_tx_fees: true,
}
}
pub fn last_VRF_public_key(&self) -> Option<VRFPublicKey> {
match self.vrf_keys.len() {
0 => None,
x => Some(VRFPublicKey::from_private(&self.vrf_keys[x - 1])),
}
}
pub fn last_block_commit(&self) -> Option<LeaderBlockCommitOp> {
match self.block_commits.len() {
0 => None,
x => Some(self.block_commits[x - 1].clone()),
}
}
pub fn next_VRF_key(&mut self) -> VRFPrivateKey {
let pk = if self.vrf_keys.len() == 0 {
// first key is simply the 32-byte hash of the secret state
let mut buf: Vec<u8> = vec![];
for i in 0..self.privks.len() {
buf.extend_from_slice(&self.privks[i].to_bytes()[..]);
}
buf.extend_from_slice(&[
(self.num_sigs >> 8) as u8,
(self.num_sigs & 0xff) as u8,
self.hash_mode as u8,
]);
let h = Sha256Sum::from_data(&buf[..]);
VRFPrivateKey::from_bytes(h.as_bytes()).unwrap()
} else {
// next key is just the hash of the last
let h = Sha256Sum::from_data(self.vrf_keys[self.vrf_keys.len() - 1].as_bytes());
VRFPrivateKey::from_bytes(h.as_bytes()).unwrap()
};
self.vrf_keys.push(pk.clone());
self.vrf_key_map
.insert(VRFPublicKey::from_private(&pk), pk.clone());
pk
}
pub fn next_microblock_privkey(&mut self) -> StacksPrivateKey {
let pk = if self.microblock_privks.len() == 0 {
// first key is simply the 32-byte hash of the secret state
let mut buf: Vec<u8> = vec![];
for i in 0..self.privks.len() {
buf.extend_from_slice(&self.privks[i].to_bytes()[..]);
}
buf.extend_from_slice(&[
(self.num_sigs >> 8) as u8,
(self.num_sigs & 0xff) as u8,
self.hash_mode as u8,
]);
let h = Sha256Sum::from_data(&buf[..]);
StacksPrivateKey::from_slice(h.as_bytes()).unwrap()
} else {
// next key is the hash of the last
let h = Sha256Sum::from_data(
&self.microblock_privks[self.microblock_privks.len() - 1].to_bytes(),
);
StacksPrivateKey::from_slice(h.as_bytes()).unwrap()
};
self.microblock_privks.push(pk.clone());
pk
}
pub fn make_proof(
&self,
vrf_pubkey: &VRFPublicKey,
last_sortition_hash: &SortitionHash,
) -> Option<VRFProof> {
test_debug!(
"Make proof from {} over {}",
vrf_pubkey.to_hex(),
last_sortition_hash
);
match self.vrf_key_map.get(vrf_pubkey) {
Some(ref prover_key) => {
let proof = VRF::prove(prover_key, &last_sortition_hash.as_bytes().to_vec());
let valid = match VRF::verify(
vrf_pubkey,
&proof,
&last_sortition_hash.as_bytes().to_vec(),
) {
Ok(v) => v,
Err(e) => false,
};
assert!(valid);
Some(proof)
}
None => None,
}
}
pub fn as_transaction_auth(&self) -> Option<TransactionAuth> {
match self.hash_mode {
AddressHashMode::SerializeP2PKH => TransactionAuth::from_p2pkh(&self.privks[0]),
AddressHashMode::SerializeP2SH => {
TransactionAuth::from_p2sh(&self.privks, self.num_sigs)
}
AddressHashMode::SerializeP2WPKH => TransactionAuth::from_p2wpkh(&self.privks[0]),
AddressHashMode::SerializeP2WSH => {
TransactionAuth::from_p2wsh(&self.privks, self.num_sigs)
}
}
}
pub fn origin_address(&self) -> Option<StacksAddress> {
match self.as_transaction_auth() {
Some(auth) => Some(auth.origin().address_testnet()),
None => None,
}
}
pub fn get_nonce(&self) -> u64 {
self.nonce
}
pub fn set_nonce(&mut self, n: u64) -> () {
self.nonce = n;
}
pub fn sign_as_origin(&mut self, tx_signer: &mut StacksTransactionSigner) -> () {
let num_keys = if self.privks.len() < self.num_sigs as usize {
self.privks.len()
} else {
self.num_sigs as usize
};
for i in 0..num_keys {
tx_signer.sign_origin(&self.privks[i]).unwrap();
}
self.nonce += 1
}
pub fn sign_as_sponsor(&mut self, tx_signer: &mut StacksTransactionSigner) -> () {
let num_keys = if self.privks.len() < self.num_sigs as usize {
self.privks.len()
} else {
self.num_sigs as usize
};
for i in 0..num_keys {
tx_signer.sign_sponsor(&self.privks[i]).unwrap();
}
self.nonce += 1
}
}
// creates miners deterministically
impl TestMinerFactory {
pub fn new() -> TestMinerFactory {
TestMinerFactory {
key_seed: [0u8; 32],
next_miner_id: 1,
}
}
pub fn from_u16(seed: u16) -> TestMinerFactory {
let mut bytes = [0u8; 32];
(&mut bytes[0..2]).copy_from_slice(&seed.to_be_bytes());
TestMinerFactory {
key_seed: bytes,
next_miner_id: seed as usize,
}
}
pub fn next_private_key(&mut self) -> StacksPrivateKey {
let h = Sha256Sum::from_data(&self.key_seed);
self.key_seed.copy_from_slice(h.as_bytes());
StacksPrivateKey::from_slice(h.as_bytes()).unwrap()
}
pub fn next_miner(
&mut self,
burnchain: &Burnchain,
num_keys: u16,
num_sigs: u16,
hash_mode: AddressHashMode,
) -> TestMiner {
let mut keys = vec![];
for i in 0..num_keys {
keys.push(self.next_private_key());
}
test_debug!("New miner: {:?} {}:{:?}", &hash_mode, num_sigs, &keys);
let mut m = TestMiner::new(burnchain, &keys, num_sigs, &hash_mode);
m.id = self.next_miner_id;
self.next_miner_id += 1;
m
}
}
impl TestBurnchainBlock {
pub fn new(parent_snapshot: &BlockSnapshot, fork_id: u64) -> TestBurnchainBlock {
TestBurnchainBlock {
parent_snapshot: parent_snapshot.clone(),
block_height: parent_snapshot.block_height + 1,
txs: vec![],
fork_id: fork_id,
timestamp: get_epoch_time_secs(),
}
}
pub fn add_leader_key_register(&mut self, miner: &mut TestMiner) -> LeaderKeyRegisterOp {
let next_vrf_key = miner.next_VRF_key();
let mut txop = LeaderKeyRegisterOp::new_from_secrets(
&miner.privks,
miner.num_sigs,
&miner.hash_mode,
&next_vrf_key,
)
.unwrap();
txop.vtxindex = self.txs.len() as u32;
txop.block_height = self.block_height;
txop.burn_header_hash = BurnchainHeaderHash_from_test_data(
txop.block_height,
&self.parent_snapshot.index_root,
self.fork_id,
);
txop.txid =
Txid::from_test_data(txop.block_height, txop.vtxindex, &txop.burn_header_hash, 0);
txop.consensus_hash = self.parent_snapshot.consensus_hash.clone();
self.txs
.push(BlockstackOperationType::LeaderKeyRegister(txop.clone()));
txop
}
pub fn add_leader_block_commit(
&mut self,
ic: &SortitionDBConn,
miner: &mut TestMiner,
block_hash: &BlockHeaderHash,
burn_fee: u64,
leader_key: &LeaderKeyRegisterOp,
fork_snapshot: Option<&BlockSnapshot>,
parent_block_snapshot: Option<&BlockSnapshot>,
) -> LeaderBlockCommitOp {
let input = (Txid([0; 32]), 0);
let pubks = miner
.privks
.iter()
.map(|ref pk| StacksPublicKey::from_private(pk))
.collect();
let apparent_sender = BurnchainSigner {
hash_mode: miner.hash_mode.clone(),
num_sigs: miner.num_sigs as usize,
public_keys: pubks,
};
let last_snapshot = match fork_snapshot {
Some(sn) => sn.clone(),
None => SortitionDB::get_canonical_burn_chain_tip(ic).unwrap(),
};
let last_snapshot_with_sortition = match parent_block_snapshot {
Some(sn) => sn.clone(),
None => SortitionDB::get_first_block_snapshot(ic).unwrap(),
};
// prove on the last-ever sortition's hash to produce the new seed
let proof = miner
.make_proof(&leader_key.public_key, &last_snapshot.sortition_hash)
.expect(&format!(
"FATAL: no private key for {}",
leader_key.public_key.to_hex()
));
let new_seed = VRFSeed::from_proof(&proof);
let get_commit_res = SortitionDB::get_block_commit(
ic.conn(),
&last_snapshot_with_sortition.winning_block_txid,
&last_snapshot_with_sortition.sortition_id,
)
.expect("FATAL: failed to read block commit");
let mut txop = match get_commit_res {
Some(parent) => {
let txop = LeaderBlockCommitOp::new(
block_hash,
self.block_height,
&new_seed,
&parent,
leader_key.block_height as u32,
leader_key.vtxindex as u16,
burn_fee,
&input,
&apparent_sender,
);
txop
}
None => {
// initial
let txop = LeaderBlockCommitOp::initial(
block_hash,
self.block_height,
&new_seed,
leader_key,