forked from stacks-network/stacks-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
5412 lines (4956 loc) · 217 KB
/
Copy pathmod.rs
File metadata and controls
5412 lines (4956 loc) · 217 KB
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::{HashMap, HashSet};
use std::ops::{Deref, DerefMut, Range};
use std::sync::LazyLock;
use clarity::util::secp256k1::Secp256k1PublicKey;
use clarity::vm::ast::ASTRules;
use clarity::vm::costs::ExecutionCost;
use clarity::vm::events::{STXEventType, STXMintEventData, StacksTransactionEvent};
use clarity::vm::types::PrincipalData;
use clarity::vm::{ClarityVersion, Value};
use lazy_static::lazy_static;
use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput};
use rusqlite::{params, Connection, OptionalExtension};
use sha2::{Digest as Sha2Digest, Sha512_256};
use stacks_common::bitvec::BitVec;
use stacks_common::codec::{
read_next, write_next, Error as CodecError, StacksMessageCodec, MAX_MESSAGE_LEN,
MAX_PAYLOAD_LEN,
};
use stacks_common::consts::{
FIRST_BURNCHAIN_CONSENSUS_HASH, FIRST_STACKS_BLOCK_HASH, MICROSTACKS_PER_STACKS,
};
use stacks_common::types::chainstate::{
BlockHeaderHash, BurnchainHeaderHash, ConsensusHash, SortitionId, StacksAddress, StacksBlockId,
StacksPrivateKey, StacksPublicKey, TrieHash, VRFSeed,
};
use stacks_common::types::{PrivateKey, StacksEpochId};
use stacks_common::util::hash::{to_hex, Hash160, MerkleHashFunc, MerkleTree, Sha512Trunc256Sum};
use stacks_common::util::retry::BoundReader;
use stacks_common::util::secp256k1::MessageSignature;
use stacks_common::util::vrf::{VRFProof, VRFPublicKey, VRF};
use stacks_common::util::{get_epoch_time_secs, sleep_ms};
use self::signer_set::SignerCalculation;
use super::burn::db::sortdb::{
get_ancestor_sort_id, get_block_commit_by_txid, SortitionHandle, SortitionHandleConn,
};
use super::burn::operations::{DelegateStxOp, StackStxOp, TransferStxOp, VoteForAggregateKeyOp};
use super::stacks::boot::{
RewardSet, RewardSetData, BOOT_TEST_POX_4_AGG_KEY_CONTRACT, BOOT_TEST_POX_4_AGG_KEY_FNAME,
};
use super::stacks::db::accounts::MinerReward;
use super::stacks::db::{
ChainstateTx, ClarityTx, MinerPaymentSchedule, MinerRewardInfo, StacksBlockHeaderTypes,
StacksEpochReceipt, StacksHeaderInfo,
};
use super::stacks::events::StacksTransactionReceipt;
use super::stacks::{
Error as ChainstateError, StacksBlock, StacksTransaction, TenureChangePayload,
TokenTransferMemo, TransactionPayload, TransactionVersion,
};
use crate::burnchains::{PoxConstants, Txid};
use crate::chainstate::burn::db::sortdb::SortitionDB;
use crate::chainstate::burn::operations::LeaderBlockCommitOp;
use crate::chainstate::burn::{BlockSnapshot, SortitionHash};
use crate::chainstate::coordinator::{BlockEventDispatcher, OnChainRewardSetProvider};
use crate::chainstate::nakamoto::keys as nakamoto_keys;
use crate::chainstate::nakamoto::signer_set::NakamotoSigners;
use crate::chainstate::nakamoto::staging_blocks::NakamotoBlockObtainMethod;
use crate::chainstate::nakamoto::tenure::{
NakamotoTenureEventId, NAKAMOTO_TENURES_SCHEMA_1, NAKAMOTO_TENURES_SCHEMA_2,
NAKAMOTO_TENURES_SCHEMA_3,
};
use crate::chainstate::stacks::boot::SIP_031_NAME;
use crate::chainstate::stacks::db::blocks::DummyEventDispatcher;
use crate::chainstate::stacks::db::{
DBConfig as ChainstateConfig, StacksChainState, StacksDBConn, StacksDBTx,
};
use crate::chainstate::stacks::{
TenureChangeCause, MINER_BLOCK_CONSENSUS_HASH, MINER_BLOCK_HEADER_HASH,
};
use crate::clarity::vm::clarity::TransactionConnection;
use crate::clarity_vm::clarity::{ClarityInstance, PreCommitClarityBlock};
use crate::clarity_vm::database::SortitionDBRef;
use crate::core::{
BOOT_BLOCK_HASH, BURNCHAIN_TX_SEARCH_WINDOW, NAKAMOTO_SIGNER_BLOCK_APPROVAL_THRESHOLD,
};
use crate::monitoring;
use crate::net::stackerdb::{StackerDBConfig, MINER_SLOT_COUNT};
use crate::net::Error as net_error;
use crate::util_lib::boot::{boot_code_addr, boot_code_id, boot_code_tx_auth};
use crate::util_lib::db::{
query_row, query_row_columns, query_row_panic, query_rows, u64_to_sql, Error as DBError,
FromRow,
};
pub mod coordinator;
pub mod keys;
pub mod miner;
pub mod shadow;
pub mod signer_set;
pub mod staging_blocks;
pub mod tenure;
pub mod test_signers;
#[cfg(test)]
pub mod tests;
pub use self::staging_blocks::{
NakamotoStagingBlocksConn, NakamotoStagingBlocksConnRef, NakamotoStagingBlocksTx,
};
pub const NAKAMOTO_BLOCK_VERSION: u8 = 0;
define_named_enum!(HeaderTypeNames {
Nakamoto("nakamoto"),
Epoch2("epoch2"),
});
impl ToSql for HeaderTypeNames {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
self.get_name_str().to_sql()
}
}
impl FromSql for HeaderTypeNames {
fn column_result(value: rusqlite::types::ValueRef<'_>) -> FromSqlResult<Self> {
Self::lookup_by_name(value.as_str()?).ok_or_else(|| FromSqlError::InvalidType)
}
}
lazy_static! {
pub static ref FIRST_STACKS_BLOCK_ID: StacksBlockId = StacksBlockId::new(&FIRST_BURNCHAIN_CONSENSUS_HASH, &FIRST_STACKS_BLOCK_HASH);
pub static ref NAKAMOTO_CHAINSTATE_SCHEMA_1: Vec<String> = vec![
r#"
-- Table for storing calculated reward sets. This must be in the Chainstate DB because calculation occurs
-- during block processing.
CREATE TABLE nakamoto_reward_sets (
index_block_hash TEXT NOT NULL,
reward_set TEXT NOT NULL,
PRIMARY KEY (index_block_hash)
);"#.into(),
NAKAMOTO_TENURES_SCHEMA_1.into(),
r#"
-- Table for Nakamoto block headers
CREATE TABLE nakamoto_block_headers (
-- The following fields all correspond to entries in the StacksHeaderInfo struct
block_height INTEGER NOT NULL,
-- root hash of the internal, not-consensus-critical MARF that allows us to track chainstate/fork metadata
index_root TEXT NOT NULL,
-- burn header hash corresponding to the consensus hash (NOT guaranteed to be unique, since we can
-- have 2+ blocks per burn block if there's a PoX fork)
burn_header_hash TEXT NOT NULL,
-- height of the burnchain block header that generated this consensus hash
burn_header_height INT NOT NULL,
-- timestamp from burnchain block header that generated this consensus hash
burn_header_timestamp INT NOT NULL,
-- size of this block, in bytes.
-- encoded as TEXT for compatibility
block_size TEXT NOT NULL,
-- The following fields all correspond to entries in the NakamotoBlockHeader struct
version INTEGER NOT NULL,
-- this field is the total number of blocks in the chain history (including this block)
chain_length INTEGER NOT NULL,
-- this field is the total amount of BTC spent in the chain history (including this block)
burn_spent INTEGER NOT NULL,
-- the consensus hash of the burnchain block that selected this block's miner's block-commit
consensus_hash TEXT NOT NULL,
-- the parent StacksBlockId
parent_block_id TEXT NOT NULL,
-- Merkle root of a Merkle tree constructed out of all the block's transactions
tx_merkle_root TEXT NOT NULL,
-- root hash of the Stacks chainstate MARF
state_index_root TEXT NOT NULL,
-- miner's signature over the block
miner_signature TEXT NOT NULL,
-- signers' signatures over the block
signer_signature TEXT NOT NULL,
-- bitvec capturing stacker participation in signature
signer_bitvec TEXT NOT NULL,
-- The following fields are not part of either the StacksHeaderInfo struct
-- or its contained NakamotoBlockHeader struct, but are used for querying
-- what kind of header this is (nakamoto or stacks 2.x)
header_type TEXT NOT NULL,
-- hash of the block
block_hash TEXT NOT NULL,
-- index_block_hash is the hash of the block hash and consensus hash of the burn block that selected it,
-- and is guaranteed to be globally unique (across all Stacks forks and across all PoX forks).
-- index_block_hash is the block hash fed into the MARF index.
index_block_hash TEXT NOT NULL,
-- the ExecutionCost of the block
cost TEXT NOT NULL,
-- the total cost up to and including this block in the current tenure
total_tenure_cost TEXT NOT NULL,
-- this field is true if this is the first block of a new tenure
tenure_changed INTEGER NOT NULL,
-- this field tracks the total tx fees so far in this tenure. it is a text-serialized u128
tenure_tx_fees TEXT NOT NULL,
-- nakamoto block's VRF proof, if this is a tenure-start block
vrf_proof TEXT,
PRIMARY KEY(consensus_hash,block_hash)
);
CREATE INDEX nakamoto_block_headers_by_consensus_hash ON nakamoto_block_headers(consensus_hash);
"#.into(),
format!(
r#"ALTER TABLE payments
ADD COLUMN schedule_type TEXT NOT NULL DEFAULT "{}";
"#,
HeaderTypeNames::Epoch2.get_name_str()),
r#"
UPDATE db_config SET version = "4";
"#.into(),
];
}
pub static NAKAMOTO_CHAINSTATE_SCHEMA_2: &[&str] = &[
NAKAMOTO_TENURES_SCHEMA_2,
r#"
ALTER TABLE nakamoto_block_headers
ADD COLUMN timestamp INTEGER NOT NULL;
"#,
r#"
UPDATE db_config SET version = "5";
"#,
// make burn_view NULLable. We could use a default value, but NULL should be safer (because it will error).
// there should be no entries in nakamoto_block_headers with a NULL entry when this column is added, because
// nakamoto blocks have not been produced yet.
r#"
ALTER TABLE nakamoto_block_headers
ADD COLUMN burn_view TEXT;
"#,
];
pub static NAKAMOTO_CHAINSTATE_SCHEMA_3: &[&str] = &[
NAKAMOTO_TENURES_SCHEMA_3,
r#"
UPDATE db_config SET version = "6";
"#,
// Add a `height_in_tenure` field to the block header row, so we know how high this block is
// within its tenure. This is needed to process malleablized Nakamoto blocks with the same
// height, as well as accidental forks that can arise from slow miners.
//
//
//
// No default value is needed because at the time of this writing, this table is actually empty.
r#"
ALTER TABLE nakamoto_block_headers
ADD COLUMN height_in_tenure;
"#,
];
pub static NAKAMOTO_CHAINSTATE_SCHEMA_4: &[&str] = &[
r#"
UPDATE db_config SET version = "7";
"#,
// Add a `signer_stats` table to keep track of how many blocks have been signed by each signer
r#"
-- Table for signer stats
CREATE TABLE signer_stats (
-- Signers public key
public_key TEXT NOT NULL,
-- Stacking rewards cycle ID
reward_cycle INTEGER NOT NULL,
-- Number of blocks signed during reward cycle
blocks_signed INTEGER DEFAULT 1 NOT NULL,
PRIMARY KEY(public_key,reward_cycle)
);
"#,
];
pub static NAKAMOTO_CHAINSTATE_SCHEMA_5: &[&str] = &[
r#"
UPDATE db_config SET version = "8";
"#,
// Add an index for index block hash in nakamoto block headers
"CREATE INDEX IF NOT EXISTS index_block_hash ON nakamoto_block_headers(index_block_hash);",
];
pub static NAKAMOTO_CHAINSTATE_SCHEMA_6: &[&str] = &[
// schema change is JUST a new index, but the index is on a table
// created by a migration, so don't add the index to the CHAINSTATE_INDEXES
r#"UPDATE db_config SET version = "10";"#,
"CREATE INDEX IF NOT EXISTS nakamoto_block_headers_by_ch_bv ON nakamoto_block_headers(consensus_hash, burn_view);"
];
#[cfg(test)]
mod fault_injection {
static PROCESS_BLOCK_STALL: std::sync::Mutex<bool> = std::sync::Mutex::new(false);
pub fn stall_block_processing() {
if *PROCESS_BLOCK_STALL.lock().unwrap() {
// Do an extra check just so we don't log EVERY time.
warn!("Block processing is stalled due to testing directive.");
while *PROCESS_BLOCK_STALL.lock().unwrap() {
std::thread::sleep(std::time::Duration::from_millis(10));
}
info!("Block processing is no longer stalled due to testing directive.");
}
}
pub fn enable_process_block_stall() {
*PROCESS_BLOCK_STALL.lock().unwrap() = true;
}
pub fn disable_process_block_stall() {
*PROCESS_BLOCK_STALL.lock().unwrap() = false;
}
}
/// Trait for common MARF getters between StacksDBConn and StacksDBTx
pub trait StacksDBIndexed {
fn get(&mut self, tip: &StacksBlockId, key: &str) -> Result<Option<String>, DBError>;
fn sqlite(&self) -> &Connection;
/// Get the ancestor block hash given a coinbase height
fn get_ancestor_block_id(
&mut self,
coinbase_height: u64,
tip_index_hash: &StacksBlockId,
) -> Result<Option<StacksBlockId>, DBError>;
/// Get the block ID for a specific coinbase height in the fork identified by `tip`
fn get_nakamoto_block_id_at_coinbase_height(
&mut self,
tip: &StacksBlockId,
coinbase_height: u64,
) -> Result<Option<StacksBlockId>, DBError> {
Ok(self
.get(
tip,
&nakamoto_keys::ongoing_tenure_coinbase_height(coinbase_height),
)?
.and_then(|id_str| nakamoto_keys::parse_block_id(&id_str)))
}
/// Get the first block in the tenure for a given tenure ID consensus hash in the fork
/// identified by `tip`
fn get_tenure_start_block_id(
&mut self,
tip: &StacksBlockId,
tenure_id_consensus_hash: &ConsensusHash,
) -> Result<Option<StacksBlockId>, DBError> {
Ok(self
.get(
tip,
&nakamoto_keys::tenure_start_block_id(tenure_id_consensus_hash),
)?
.and_then(|id_str| nakamoto_keys::parse_block_id(&id_str)))
}
/// Get the coinbase height of a tenure (identified by its consensus hash) in a fork identified
/// by `tip`
fn get_coinbase_height(
&mut self,
tip: &StacksBlockId,
tenure_id_consensus_hash: &ConsensusHash,
) -> Result<Option<u64>, DBError> {
Ok(self
.get(
tip,
&nakamoto_keys::coinbase_height(tenure_id_consensus_hash),
)?
.and_then(|height_str| nakamoto_keys::parse_u64(&height_str)))
}
/// Get the ongoing tenure ID in the fork identified by `tip`
fn get_ongoing_tenure_id(
&mut self,
tip: &StacksBlockId,
) -> Result<Option<NakamotoTenureEventId>, DBError> {
Ok(self
.get(tip, nakamoto_keys::ongoing_tenure_id())?
.and_then(|id_str| nakamoto_keys::parse_tenure_id_value(&id_str)))
}
/// Get the highest block ID in a tenure identified by its consensus hash in the Stacks fork
/// identified by `tip`
fn get_highest_block_id_in_tenure(
&mut self,
tip: &StacksBlockId,
tenure_id_consensus_hash: &ConsensusHash,
) -> Result<Option<StacksBlockId>, DBError> {
Ok(self
.get(
tip,
&nakamoto_keys::highest_block_in_tenure(tenure_id_consensus_hash),
)?
.and_then(|id_str| nakamoto_keys::parse_block_id(&id_str)))
}
/// Get the block-found tenure ID for a given tenure's consensus hash (if defined) in a given
/// Stacks fork identified by `tip`
fn get_block_found_tenure_id(
&mut self,
tip: &StacksBlockId,
tenure_id_consensus_hash: &ConsensusHash,
) -> Result<Option<NakamotoTenureEventId>, DBError> {
Ok(self
.get(
tip,
&nakamoto_keys::block_found_tenure_id(tenure_id_consensus_hash),
)?
.and_then(|id_str| nakamoto_keys::parse_tenure_id_value(&id_str)))
}
/// Determine if a tenure, identified by its consensus hash, has finished in a fork identified
/// by `tip`
fn is_tenure_finished(
&mut self,
tip: &StacksBlockId,
tenure_id_consensus_hash: &ConsensusHash,
) -> Result<Option<bool>, DBError> {
if self
.get_tenure_start_block_id(tip, tenure_id_consensus_hash)?
.is_none()
{
// tenure not started
debug!(
"No tenure-start block for {} off of {}",
tenure_id_consensus_hash, tip
);
return Ok(None);
}
if self
.get(
tip,
&nakamoto_keys::finished_tenure_consensus_hash(tenure_id_consensus_hash),
)?
.is_none()
{
// tenure has started, but is not done yet
debug!(
"Tenure {} not finished off of {}",
tenure_id_consensus_hash, tip
);
return Ok(Some(false));
}
// tenure started and finished
Ok(Some(true))
}
/// Get the parent tenure consensus hash of a given tenure (identified by its own consensus
/// hash) within a Stacks fork identified by `tip`
fn get_parent_tenure_consensus_hash(
&mut self,
tip: &StacksBlockId,
tenure_id_consensus_hash: &ConsensusHash,
) -> Result<Option<ConsensusHash>, DBError> {
Ok(self
.get(
tip,
&nakamoto_keys::parent_tenure_consensus_hash(tenure_id_consensus_hash),
)?
.and_then(|ch_str| nakamoto_keys::parse_consensus_hash(&ch_str)))
}
}
impl StacksDBIndexed for StacksDBConn<'_> {
fn get(&mut self, tip: &StacksBlockId, key: &str) -> Result<Option<String>, DBError> {
self.get_indexed(tip, key)
}
fn sqlite(&self) -> &Connection {
self.conn()
}
fn get_ancestor_block_id(
&mut self,
coinbase_height: u64,
tip_index_hash: &StacksBlockId,
) -> Result<Option<StacksBlockId>, DBError> {
self.get_ancestor_block_hash(coinbase_height, tip_index_hash)
}
}
impl StacksDBIndexed for StacksDBTx<'_> {
fn get(&mut self, tip: &StacksBlockId, key: &str) -> Result<Option<String>, DBError> {
self.get_indexed(tip, key)
}
fn sqlite(&self) -> &Connection {
self.tx().deref()
}
fn get_ancestor_block_id(
&mut self,
coinbase_height: u64,
tip_index_hash: &StacksBlockId,
) -> Result<Option<StacksBlockId>, DBError> {
self.get_ancestor_block_hash(coinbase_height, tip_index_hash)
}
}
impl<'a> ChainstateTx<'a> {
pub fn as_tx(&mut self) -> &mut StacksDBTx<'a> {
&mut self.tx
}
}
/// Matured miner reward schedules
#[derive(Debug, Clone)]
pub struct MaturedMinerPaymentSchedules {
/// miners whose rewards matured
pub latest_miners: Vec<MinerPaymentSchedule>,
/// parent to be paid (epoch2 only)
pub parent_miner: MinerPaymentSchedule,
}
impl MaturedMinerPaymentSchedules {
pub fn genesis(mainnet: bool) -> Self {
Self {
latest_miners: vec![],
parent_miner: MinerPaymentSchedule::genesis(mainnet),
}
}
}
/// Struct for the transaction events associated with
/// any operations handled in finish_block()
pub struct FinishBlockEvents {
pub lockup_events: Vec<StacksTransactionEvent>,
pub sip31_event: Option<StacksTransactionEvent>,
}
/// Struct containing information about the miners assigned in the
/// .miners stackerdb config
pub struct MinersDBInformation {
signer_0_sortition: ConsensusHash,
signer_1_sortition: ConsensusHash,
latest_winner: u16,
}
impl MinersDBInformation {
/// What index in the `.miners` stackerdb is the miner who won
/// `sortition`?
pub fn get_signer_index(&self, sortition: &ConsensusHash) -> Option<u16> {
if sortition == &self.signer_0_sortition {
Some(0)
} else if sortition == &self.signer_1_sortition {
Some(1)
} else {
None
}
}
/// Get all of the sortitions whose winners are included in .miners
pub fn get_sortitions(&self) -> [&ConsensusHash; 2] {
[&self.signer_0_sortition, &self.signer_1_sortition]
}
/// Get the index of the latest sortition winner in .miners
pub fn get_latest_winner_index(&self) -> u16 {
self.latest_winner
}
}
/// Calculated matured miner rewards, from scheduled rewards
#[derive(Debug, Clone)]
pub struct MaturedMinerRewards {
/// this block's reward recipient
/// NOTE: in epoch2, if a PoisonMicroblock report was successful, then the recipient is the
/// reporter, not the miner.
pub recipient: MinerReward,
/// the parent block's reward.
/// this is all of the fees they accumulated during their tenure.
pub parent_reward: MinerReward,
/// metadata about the block miner's reward
pub reward_info: MinerRewardInfo,
}
impl MaturedMinerRewards {
/// Get the list of miner rewards this struct represents
pub fn consolidate(&self) -> Vec<MinerReward> {
vec![self.recipient.clone(), self.parent_reward.clone()]
}
}
/// Struct describing the intervals in which SIP-031 emission are applied.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SIP031EmissionInterval {
/// amount of uSTX to emit
pub amount: u128,
/// height of the burn chain in which the interval starts
pub start_height: u64,
}
// From SIP-031:
//
// | Bitcoin Height | STX Emission |
// |----------------|------------ |
// | 907,740 | 475 |
// | 960,300 | 1,140 |
// | 1,012,860 | 1,705 |
// | 1,065,420 | 1,305 |
// | 1,117,980 | 1,155 |
// | 1,170,540 | 0 |
/// Mainnet sip-031 emission intervals
pub static SIP031_EMISSION_INTERVALS_MAINNET: LazyLock<[SIP031EmissionInterval; 6]> =
LazyLock::new(|| {
let emissions_schedule = [
SIP031EmissionInterval {
amount: 0,
start_height: 1_170_540,
},
SIP031EmissionInterval {
amount: 1_155 * u128::from(MICROSTACKS_PER_STACKS),
start_height: 1_117_980,
},
SIP031EmissionInterval {
amount: 1_305 * u128::from(MICROSTACKS_PER_STACKS),
start_height: 1_065_420,
},
SIP031EmissionInterval {
amount: 1_705 * u128::from(MICROSTACKS_PER_STACKS),
start_height: 1_012_860,
},
SIP031EmissionInterval {
amount: 1_140 * u128::from(MICROSTACKS_PER_STACKS),
start_height: 960_300,
},
SIP031EmissionInterval {
amount: 475 * u128::from(MICROSTACKS_PER_STACKS),
start_height: 907_740,
},
];
assert!(SIP031EmissionInterval::check_inversed_order(
&emissions_schedule
));
emissions_schedule
});
/// Testnet sip-031 emission intervals (starting from 71_525, 1 interval every 360 bitcoin blocks)
pub static SIP031_EMISSION_INTERVALS_TESTNET: LazyLock<[SIP031EmissionInterval; 6]> =
LazyLock::new(|| {
let emissions_schedule = [
SIP031EmissionInterval {
amount: 0,
start_height: 71_525 + (360 * 6),
},
SIP031EmissionInterval {
amount: 5_000,
start_height: 71_525 + (360 * 5),
},
SIP031EmissionInterval {
amount: 4_000,
start_height: 71_525 + (360 * 4),
},
SIP031EmissionInterval {
amount: 3_000,
start_height: 71_525 + (360 * 3),
},
SIP031EmissionInterval {
amount: 2_000,
start_height: 71_525 + (360 * 2),
},
SIP031EmissionInterval {
amount: 1_000,
start_height: 71_525 + 360,
},
];
assert!(SIP031EmissionInterval::check_inversed_order(
&emissions_schedule
));
emissions_schedule
});
/// Used for testing to substitute a sip-031 emission schedule
#[cfg(any(test, feature = "testing"))]
pub static SIP031_EMISSION_INTERVALS_TEST: std::sync::Mutex<Option<Vec<SIP031EmissionInterval>>> =
std::sync::Mutex::new(None);
#[cfg(any(test, feature = "testing"))]
pub fn set_test_sip_031_emission_schedule(emission_schedule: Option<Vec<SIP031EmissionInterval>>) {
if let Some(emission_schedule_vec) = &emission_schedule {
assert!(SIP031EmissionInterval::check_inversed_order(
&emission_schedule_vec
));
}
match SIP031_EMISSION_INTERVALS_TEST.lock() {
Ok(mut schedule_guard) => {
*schedule_guard = emission_schedule;
}
Err(_e) => {
panic!("SIP031_EMISSION_INTERVALS_TEST mutex poisoned");
}
}
}
#[cfg(any(test, feature = "testing"))]
fn get_sip_031_emission_schedule(_mainnet: bool) -> Vec<SIP031EmissionInterval> {
match SIP031_EMISSION_INTERVALS_TEST.lock() {
Ok(schedule_opt) => {
if let Some(schedule) = (*schedule_opt).as_ref() {
info!("Use overridden SIP-031 emission schedule {:?}", &schedule);
return schedule.clone();
} else {
return vec![];
}
}
Err(_e) => {
panic!("COINBASE_INTERVALS_TEST mutex poisoned");
}
}
}
#[cfg(not(any(test, feature = "testing")))]
fn get_sip_031_emission_schedule(mainnet: bool) -> Vec<SIP031EmissionInterval> {
if mainnet {
SIP031_EMISSION_INTERVALS_MAINNET.to_vec()
} else {
SIP031_EMISSION_INTERVALS_TESTNET.to_vec()
}
}
impl SIP031EmissionInterval {
/// Look up the amount of STX to emit at the start of the tenure at the specified height.
/// Precondition: `intervals` must be sorted in descending order by `start_height`
pub fn get_sip_031_emission_at_height(burn_height: u64, mainnet: bool) -> u128 {
let intervals = get_sip_031_emission_schedule(mainnet);
if intervals.is_empty() {
return 0;
}
for interval in intervals {
if burn_height >= interval.start_height {
return interval.amount;
}
}
// default emission (out of SIP-031 ranges)
return 0;
}
/// Verify that a list of intervals is sorted in descending order by `start_height`
pub fn check_inversed_order(intervals: &[SIP031EmissionInterval]) -> bool {
let Some(mut ht) = intervals.first().map(|x| x.start_height) else {
// if the interval list is empty, its sorted
return true;
};
for interval in intervals.iter().skip(1) {
if interval.start_height > ht {
return false;
}
ht = interval.start_height;
}
true
}
}
/// Result of preparing to produce or validate a block
pub struct SetupBlockResult<'a, 'b> {
/// Handle to the ClarityVM
pub clarity_tx: ClarityTx<'a, 'b>,
/// Transaction receipts from any Stacks-on-Bitcoin transactions and epoch transition events
pub tx_receipts: Vec<StacksTransactionReceipt>,
/// Miner rewards that can be paid now
pub matured_miner_rewards_opt: Option<MaturedMinerRewards>,
/// Epoch in which this block was set up
pub evaluated_epoch: StacksEpochId,
/// Whether or not we applied an epoch transition in this block
pub applied_epoch_transition: bool,
/// stack-stx Stacks-on-Bitcoin txs
pub burn_stack_stx_ops: Vec<StackStxOp>,
/// transfer-stx Stacks-on-Bitcoin txs
pub burn_transfer_stx_ops: Vec<TransferStxOp>,
/// delegate-stx Stacks-on-Bitcoin txs
pub burn_delegate_stx_ops: Vec<DelegateStxOp>,
/// STX auto-unlock events from PoX
pub auto_unlock_events: Vec<StacksTransactionEvent>,
/// Result of a signer set calculation if one occurred
pub signer_set_calc: Option<SignerCalculation>,
/// vote-for-aggregate-key Stacks-on-Bitcoin txs
pub burn_vote_for_aggregate_key_ops: Vec<VoteForAggregateKeyOp>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NakamotoBlockHeader {
pub version: u8,
/// The total number of StacksBlock and NakamotoBlocks preceding
/// this block in this block's history.
pub chain_length: u64,
/// Total amount of BTC spent producing the sortition that
/// selected this block's miner.
pub burn_spent: u64,
/// The consensus hash of the burnchain block that selected this tenure. The consensus hash
/// uniquely identifies this tenure, including across all Bitcoin forks.
pub consensus_hash: ConsensusHash,
/// The index block hash of the immediate parent of this block.
/// This is the hash of the parent block's hash and consensus hash.
pub parent_block_id: StacksBlockId,
/// The root of a SHA512/256 merkle tree over all this block's
/// contained transactions
pub tx_merkle_root: Sha512Trunc256Sum,
/// The MARF trie root hash after this block has been processed
pub state_index_root: TrieHash,
/// A Unix time timestamp of when this block was mined, according to the miner.
/// For the signers to consider a block valid, this timestamp must be:
/// * Greater than the timestamp of its parent block
/// * At most 15 seconds into the future
pub timestamp: u64,
/// Recoverable ECDSA signature from the tenure's miner.
pub miner_signature: MessageSignature,
/// The set of recoverable ECDSA signatures over
/// the block header from the signer set active during the tenure.
/// (ordered by reward set order)
pub signer_signature: Vec<MessageSignature>,
/// A bitvec which conveys whether reward addresses should be punished (by burning their PoX rewards)
/// or not in this block.
///
/// The maximum number of entries in the bitvec is 4000.
pub pox_treatment: BitVec<4000>,
}
impl FromRow<NakamotoBlockHeader> for NakamotoBlockHeader {
fn from_row(row: &rusqlite::Row) -> Result<NakamotoBlockHeader, DBError> {
let version = row.get("version")?;
let chain_length_i64: i64 = row.get("chain_length")?;
let chain_length = chain_length_i64
.try_into()
.map_err(|_| DBError::ParseError)?;
let burn_spent_i64: i64 = row.get("burn_spent")?;
let burn_spent = burn_spent_i64.try_into().map_err(|_| DBError::ParseError)?;
let consensus_hash = row.get("consensus_hash")?;
let parent_block_id = row.get("parent_block_id")?;
let tx_merkle_root = row.get("tx_merkle_root")?;
let state_index_root = row.get("state_index_root")?;
let timestamp_i64: i64 = row.get("timestamp")?;
let timestamp = timestamp_i64.try_into().map_err(|_| DBError::ParseError)?;
let miner_signature = row.get("miner_signature")?;
let signer_bitvec = row.get("signer_bitvec")?;
let signer_signature_json: String = row.get("signer_signature")?;
let signer_signature: Vec<MessageSignature> =
serde_json::from_str(&signer_signature_json).map_err(|_e| DBError::ParseError)?;
Ok(NakamotoBlockHeader {
version,
chain_length,
burn_spent,
consensus_hash,
parent_block_id,
tx_merkle_root,
state_index_root,
timestamp,
signer_signature,
miner_signature,
pox_treatment: signer_bitvec,
})
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NakamotoBlock {
pub header: NakamotoBlockHeader,
pub txs: Vec<StacksTransaction>,
}
pub struct NakamotoChainState;
impl StacksMessageCodec for NakamotoBlockHeader {
fn consensus_serialize<W: std::io::Write>(&self, fd: &mut W) -> Result<(), CodecError> {
write_next(fd, &self.version)?;
write_next(fd, &self.chain_length)?;
write_next(fd, &self.burn_spent)?;
write_next(fd, &self.consensus_hash)?;
write_next(fd, &self.parent_block_id)?;
write_next(fd, &self.tx_merkle_root)?;
write_next(fd, &self.state_index_root)?;
write_next(fd, &self.timestamp)?;
write_next(fd, &self.miner_signature)?;
write_next(fd, &self.signer_signature)?;
write_next(fd, &self.pox_treatment)?;
Ok(())
}
fn consensus_deserialize<R: std::io::Read>(fd: &mut R) -> Result<Self, CodecError> {
Ok(NakamotoBlockHeader {
version: read_next(fd)?,
chain_length: read_next(fd)?,
burn_spent: read_next(fd)?,
consensus_hash: read_next(fd)?,
parent_block_id: read_next(fd)?,
tx_merkle_root: read_next(fd)?,
state_index_root: read_next(fd)?,
timestamp: read_next(fd)?,
miner_signature: read_next(fd)?,
signer_signature: read_next(fd)?,
pox_treatment: read_next(fd)?,
})
}
}
impl NakamotoBlockHeader {
/// Calculate the message digest for miners to sign.
/// This includes all fields _except_ the signatures.
pub fn miner_signature_hash(&self) -> Sha512Trunc256Sum {
self.miner_signature_hash_inner()
.expect("BUG: failed to calculate miner signature hash")
}
/// Calculate the message digest for signers to sign.
/// This includes all fields _except_ the signer signature.
pub fn signer_signature_hash(&self) -> Sha512Trunc256Sum {
self.signer_signature_hash_inner()
.expect("BUG: failed to calculate signer signature hash")
}
/// Inner calculation of the message digest for miners to sign.
/// This includes all fields _except_ the signatures.
fn miner_signature_hash_inner(&self) -> Result<Sha512Trunc256Sum, CodecError> {
let mut hasher = Sha512_256::new();
let fd = &mut hasher;
write_next(fd, &self.version)?;
write_next(fd, &self.chain_length)?;
write_next(fd, &self.burn_spent)?;
write_next(fd, &self.consensus_hash)?;
write_next(fd, &self.parent_block_id)?;
write_next(fd, &self.tx_merkle_root)?;
write_next(fd, &self.state_index_root)?;
write_next(fd, &self.timestamp)?;
write_next(fd, &self.pox_treatment)?;
Ok(Sha512Trunc256Sum::from_hasher(hasher))
}
/// Inner calculation of the message digest for stackers to sign.
/// This includes all fields _except_ the stacker signature.
fn signer_signature_hash_inner(&self) -> Result<Sha512Trunc256Sum, CodecError> {
let mut hasher = Sha512_256::new();
let fd = &mut hasher;
write_next(fd, &self.version)?;
write_next(fd, &self.chain_length)?;
write_next(fd, &self.burn_spent)?;
write_next(fd, &self.consensus_hash)?;
write_next(fd, &self.parent_block_id)?;
write_next(fd, &self.tx_merkle_root)?;
write_next(fd, &self.state_index_root)?;
write_next(fd, &self.timestamp)?;
write_next(fd, &self.miner_signature)?;
write_next(fd, &self.pox_treatment)?;
Ok(Sha512Trunc256Sum::from_hasher(hasher))
}
pub fn recover_miner_pk(&self) -> Option<StacksPublicKey> {
let signed_hash = self.miner_signature_hash();
let recovered_pk =
StacksPublicKey::recover_to_pubkey(signed_hash.bits(), &self.miner_signature).ok()?;
Some(recovered_pk)
}
pub fn block_hash(&self) -> BlockHeaderHash {
// same as sighash -- we don't commit to signatures
BlockHeaderHash(
self.signer_signature_hash_inner()
.expect("BUG: failed to serialize block header hash struct")
.0,
)
}
pub fn block_id(&self) -> StacksBlockId {
StacksBlockId::new(&self.consensus_hash, &self.block_hash())
}
pub fn is_first_mined(&self) -> bool {
self.parent_block_id == StacksBlockId::first_mined()
}
/// Sign the block header by the miner
pub fn sign_miner(&mut self, privk: &StacksPrivateKey) -> Result<(), ChainstateError> {
let sighash = self.miner_signature_hash().0;
let sig = privk
.sign(&sighash)
.map_err(|se| net_error::SigningError(se.to_string()))?;
self.miner_signature = sig;
Ok(())
}
/// Verify the block header against the list of signer signatures
///
/// Validate against:
/// - Any invalid signatures (eg not recoverable or not from a signer)
/// - Any duplicate signatures
/// - At least the minimum number of signatures (based on total signer weight
/// and a 70% threshold)
/// - Order of signatures is maintained vs signer set
///
/// Returns the signing weight on success.
/// Returns ChainstateError::InvalidStacksBlock on error