-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapply.rs
More file actions
11295 lines (10441 loc) · 427 KB
/
Copy pathapply.rs
File metadata and controls
11295 lines (10441 loc) · 427 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
//! Authoritative chainstate mutation: connect, disconnect, and window apply.
//!
//! Ownership, admission, and the `Chainstate` / `ChainTransition` boundary
//! are specified by `ARCH-07` in `docs/contracts/architecture.md`. Apply
//! publishes the tip and returns a concrete connect or disconnect outcome.
//! [`crate::chain_effects`] consumes that outcome after the commit.
mod scratch;
use std::sync::Arc;
use arc_swap::ArcSwapOption;
use bitcoin_rs_chain::{BlockTree, ChainWork, NodeId, TipSnapshot};
use bitcoin_rs_consensus::{MAX_SCRIPT_SIZE, MEDIAN_TIME_PAST_WINDOW, rust_path::UtxoView};
use bitcoin_rs_mempool::{AdmissionOrigin, ChainChangeGuard, Mempool, MempoolGateway};
use bitcoin_rs_primitives::{
Block, ConsensusEncode as _, Hash256, Network, OutPoint, Tx, TxOut, Txid, consensus_bytes,
varint,
};
use bitcoin_rs_utxo::{
LiveOutput, LiveOutputMeta, UtxoSet,
connect::{BlockChangeError, SpentOutputLookup, build_block_changes},
is_coinbase_tx,
};
use hashbrown::{HashMap, HashSet};
use parking_lot::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
use rayon::prelude::*;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use crate::state::ApplyError;
use bitcoin_rs_storage::{
BlockFilePosition, FlatFileBlockReader, FlatFileBlockStore, InMemoryUndoStore, KvSnapshot,
KvStore, StorageError, WriteBatch, block_file_max_height_key, decode_block_file_max_height,
encode_block_file_max_height,
};
#[cfg(test)]
use bitcoin_rs_storage::DisconnectMarker;
pub(crate) use bitcoin_rs_storage::{DisconnectPhase, KvUndoStore, UndoStore};
use scratch::{ApplyScratch, ApplyScratchCapacities, SameBlockSpentSet};
/// Number of blocks after a coinbase that its outputs become spendable.
/// Consensus rule since Bitcoin v0.3.1; universal across networks.
const COINBASE_MATURITY: u32 = 100;
/// BIP68 sequence-bit masks.
const BIP68_DISABLE_FLAG: u32 = 0x8000_0000;
const BIP68_TYPE_FLAG: u32 = 0x0040_0000;
const BIP68_MASK: u32 = 0x0000_ffff;
const BIP68_TIME_GRANULARITY_SECONDS: u32 = 512;
const BIP34_IMPLIES_BIP30_LIMIT: u32 = 1_983_702;
const SERIALIZED_BLOCK_HEADER_LEN: usize = 80;
const SERIALIZED_BLOCK_METADATA_PREFIX_LEN: usize = SERIALIZED_BLOCK_HEADER_LEN + 9;
const LOCAL_OVERLAY_TXID_SET_THRESHOLD: usize = 8;
/// Double SHA256, kept next to the witness merkle reduction its only remaining
/// caller (a test fixture helper) uses.
#[cfg(test)]
fn sha256d(data: &[u8]) -> [u8; 32] {
use sha2::{Digest, Sha256};
let inner = Sha256::digest(data);
let outer = Sha256::digest(inner);
outer.into()
}
/// Merkle reduction over 32-byte leaves, duplicating the last leaf on odd
/// widths; test-fixture helper after the witness-commitment precheck moved to
/// the consensus crate.
#[cfg(test)]
fn merkle_root_bytes(leaves: &mut Vec<[u8; 32]>) -> Option<[u8; 32]> {
if leaves.is_empty() {
return None;
}
while leaves.len() > 1 {
let original_len = leaves.len();
let mut next = Vec::with_capacity(original_len.div_ceil(2));
for pos in 0..original_len.div_ceil(2) {
let left = leaves[2 * pos];
let right = leaves[(2 * pos + 1).min(original_len - 1)];
let mut pair = [0_u8; 64];
pair[..32].copy_from_slice(&left);
pair[32..].copy_from_slice(&right);
next.push(sha256d(&pair));
}
*leaves = next;
}
Some(leaves[0])
}
fn decode_block_tx_count(bytes: &[u8]) -> Option<usize> {
let cursor = bytes.get(SERIALIZED_BLOCK_HEADER_LEN..)?;
let (count, consumed) = varint::decode(cursor).ok()?;
let _ = &cursor[consumed..];
usize::try_from(count).ok()
}
pub(crate) trait PruneBodyReader {
/// Prefetches body positions in the order that they will be loaded.
///
/// Implementations must not prefetch body bytes.
fn prefetch_positions(
&mut self,
requests: &[(u32, bitcoin_rs_primitives::Hash256)],
) -> Result<(), StorageError> {
let _ = requests;
Ok(())
}
fn load_block_body(
&mut self,
height: u32,
hash: bitcoin_rs_primitives::Hash256,
) -> Result<Option<Vec<u8>>, StorageError>;
}
struct DirectPruneBodyReader<'a, S: PruneBodyStore + ?Sized> {
store: &'a S,
}
impl<S: PruneBodyStore + ?Sized> PruneBodyReader for DirectPruneBodyReader<'_, S> {
fn load_block_body(
&mut self,
height: u32,
hash: bitcoin_rs_primitives::Hash256,
) -> Result<Option<Vec<u8>>, StorageError> {
self.store.load_block_body(height, hash)
}
}
pub(crate) trait PruneBodyStore: Send + Sync {
fn persist_block_body(
&self,
height: u32,
hash: bitcoin_rs_primitives::Hash256,
body: &[u8],
) -> Result<(), StorageError>;
fn persist_block_body_value(
&self,
height: u32,
hash: bitcoin_rs_primitives::Hash256,
body: bytes::Bytes,
) -> Result<(), StorageError> {
self.persist_block_body(height, hash, &body)
}
fn load_block_body(
&self,
height: u32,
hash: bitcoin_rs_primitives::Hash256,
) -> Result<Option<Vec<u8>>, StorageError>;
fn reader(&self) -> Result<Box<dyn PruneBodyReader + '_>, StorageError> {
Ok(Box::new(DirectPruneBodyReader { store: self }))
}
/// The persisted undo record for `height`/`hash`, when this store can
/// reach one.
///
/// The default answers nothing: only stores backed by the chainstate
/// key-value index hold undo rows, and a `ScriptLive`-selecting worker
/// step fails closed on `None` rather than indexing without its spent-coin
/// anchor (#225).
fn undo_record(
&self,
height: u32,
hash: bitcoin_rs_primitives::Hash256,
) -> Result<Option<Vec<u8>>, StorageError> {
let _ = (height, hash);
Ok(None)
}
/// Loads `len` body bytes starting `offset` bytes into the serialized block.
///
/// Defaults to `Ok(None)`, meaning "this store cannot slice"; callers fall
/// back to [`Self::load_block_body`]. Never a short read.
fn load_block_body_range(
&self,
_height: u32,
_hash: bitcoin_rs_primitives::Hash256,
_offset: u32,
_len: u32,
) -> Result<Option<Vec<u8>>, StorageError> {
Ok(None)
}
fn block_body_metadata(
&self,
height: u32,
hash: bitcoin_rs_primitives::Hash256,
) -> Result<Option<(usize, usize)>, StorageError> {
let Some(body) = self.load_block_body(height, hash)? else {
return Ok(None);
};
let Some(tx_count) = decode_block_tx_count(&body) else {
return Ok(None);
};
Ok(Some((body.len(), tx_count)))
}
/// Bytes this store's block files occupy on disk, when it keeps files.
///
/// `None` from a store with nothing on disk to measure; the caller then
/// falls back to the block-record sum.
fn disk_usage(&self) -> Option<u64> {
None
}
/// Makes body bytes durable before their checkpoint can be published.
fn sync(&self) -> Result<(), StorageError>;
}
pub(crate) struct FlatFilePruneBodyStore<S: KvStore> {
index: Arc<S>,
files: Arc<FlatFileBlockStore>,
}
enum PositionLookup {
Direct,
Prefetched {
entries: Vec<(u32, Hash256, Option<BlockFilePosition>)>,
next: usize,
},
}
fn decode_body_position(
height: u32,
encoded: Option<&[u8]>,
) -> Result<Option<BlockFilePosition>, StorageError> {
encoded
.map(|bytes| {
BlockFilePosition::decode(bytes).ok_or_else(|| {
StorageError::IncompatibleData(format!(
"block-body index row for height {height} is not a 16-byte flat-file position"
))
})
})
.transpose()
}
struct FlatFilePruneBodyReader<'a> {
index: Box<dyn KvSnapshot + 'a>,
files: FlatFileBlockReader,
positions: PositionLookup,
}
impl PruneBodyReader for FlatFilePruneBodyReader<'_> {
fn prefetch_positions(&mut self, requests: &[(u32, Hash256)]) -> Result<(), StorageError> {
if let PositionLookup::Prefetched { entries, next } = &self.positions
&& *next != entries.len()
{
return Err(StorageError::InvalidOperation(
"prefetched body positions were not fully consumed",
));
}
let keys: Vec<_> = requests
.iter()
.map(|&(height, hash)| bitcoin_rs_storage::pruning::block_body_key(height, hash))
.collect();
let key_refs: Vec<_> = keys.iter().map(<[u8; 37]>::as_slice).collect();
let values = self
.index
.get_many_sorted(bitcoin_rs_storage::pruning::BLOCK_DATA_CF, &key_refs)?;
if values.len() != requests.len() {
return Err(StorageError::InvalidOperation(
"snapshot batch returned the wrong number of values",
));
}
let entries = requests
.iter()
.copied()
.zip(values)
.map(|((height, hash), value)| {
let position = decode_body_position(height, value.as_deref())?;
Ok((height, hash, position))
})
.collect::<Result<Vec<_>, StorageError>>()?;
self.positions = PositionLookup::Prefetched { entries, next: 0 };
Ok(())
}
fn load_block_body(
&mut self,
height: u32,
hash: bitcoin_rs_primitives::Hash256,
) -> Result<Option<Vec<u8>>, StorageError> {
let position = match &mut self.positions {
PositionLookup::Direct => {
let key = bitcoin_rs_storage::pruning::block_body_key(height, hash);
let encoded = self
.index
.get(bitcoin_rs_storage::pruning::BLOCK_DATA_CF, &key)?;
decode_body_position(height, encoded.as_deref())?
}
PositionLookup::Prefetched { entries, next } => {
let Some(&(expected_height, expected_hash, position)) = entries.get(*next) else {
return Err(StorageError::InvalidOperation(
"prefetched body positions are exhausted",
));
};
if expected_height != height || expected_hash != hash {
return Err(StorageError::InvalidOperation(
"prefetched body position consumed out of order",
));
}
*next += 1;
position
}
};
let Some(position) = position else {
return Ok(None);
};
self.files.load(position, height, *hash.as_byte_array())
}
}
impl<S: KvStore> FlatFilePruneBodyStore<S> {
pub(crate) fn open(index: Arc<S>, files: Arc<FlatFileBlockStore>) -> Self {
Self { index, files }
}
/// Resolves the flat-file position of a block body, or `None` when the
/// block is unknown. An index row that is not a decodable 16-byte
/// flat-file position is `IncompatibleData`, never a silent `None`: the
/// row's presence means the body must exist, so treating a decode failure
/// as absence would hide a schema mismatch behind a missing-block answer.
///
/// Every read path starts here, so it is written once rather than three
/// times: divergence between the whole-body, ranged, and metadata lookups
/// would surface as one of them silently disagreeing about which blocks
/// exist.
fn body_position(
&self,
height: u32,
hash: bitcoin_rs_primitives::Hash256,
) -> Result<Option<BlockFilePosition>, StorageError> {
let key = bitcoin_rs_storage::pruning::block_body_key(height, hash);
decode_body_position(
height,
self.index
.get(bitcoin_rs_storage::pruning::BLOCK_DATA_CF, &key)?
.as_deref(),
)
}
}
impl<S: KvStore> PruneBodyStore for FlatFilePruneBodyStore<S> {
fn undo_record(
&self,
height: u32,
hash: bitcoin_rs_primitives::Hash256,
) -> Result<Option<Vec<u8>>, StorageError> {
self.index.get(
bitcoin_rs_storage::ColumnFamily::UndoData,
&bitcoin_rs_storage::pruning::block_undo_key(height, hash),
)
}
fn disk_usage(&self) -> Option<u64> {
Some(self.files.disk_usage())
}
fn persist_block_body(
&self,
height: u32,
hash: bitcoin_rs_primitives::Hash256,
body: &[u8],
) -> Result<(), StorageError> {
let key = bitcoin_rs_storage::pruning::block_body_key(height, hash);
let existing = decode_body_position(
height,
self.index
.get(bitcoin_rs_storage::pruning::BLOCK_DATA_CF, &key)?
.as_deref(),
)?;
let position = self
.files
.persist(existing, height, *hash.as_byte_array(), body)?;
if existing == Some(position) {
return Ok(());
}
let max_height_key = block_file_max_height_key(position.file_no);
let max_height = self
.index
.get(bitcoin_rs_storage::pruning::BLOCK_DATA_CF, &max_height_key)?
.as_deref()
.and_then(decode_block_file_max_height)
.map_or(height, |previous| previous.max(height));
let mut batch = self.index.new_batch();
batch.put(
bitcoin_rs_storage::pruning::BLOCK_DATA_CF,
&key,
&position.encode(),
);
batch.put(
bitcoin_rs_storage::pruning::BLOCK_DATA_CF,
&max_height_key,
&encode_block_file_max_height(max_height),
);
self.index.write_deferred(batch)
}
fn reader(&self) -> Result<Box<dyn PruneBodyReader + '_>, StorageError> {
Ok(Box::new(FlatFilePruneBodyReader {
index: self.index.snapshot()?,
files: self.files.reader(),
positions: PositionLookup::Direct,
}))
}
fn load_block_body(
&self,
height: u32,
hash: bitcoin_rs_primitives::Hash256,
) -> Result<Option<Vec<u8>>, StorageError> {
let Some(position) = self.body_position(height, hash)? else {
return Ok(None);
};
self.files.load(position, height, *hash.as_byte_array())
}
fn load_block_body_range(
&self,
height: u32,
hash: bitcoin_rs_primitives::Hash256,
offset: u32,
len: u32,
) -> Result<Option<Vec<u8>>, StorageError> {
let Some(position) = self.body_position(height, hash)? else {
return Ok(None);
};
self.files
.load_range(position, height, *hash.as_byte_array(), offset, len)
}
fn block_body_metadata(
&self,
height: u32,
hash: bitcoin_rs_primitives::Hash256,
) -> Result<Option<(usize, usize)>, StorageError> {
let Some(position) = self.body_position(height, hash)? else {
return Ok(None);
};
let Some(prefix) = self.files.load_prefix(
position,
height,
*hash.as_byte_array(),
SERIALIZED_BLOCK_METADATA_PREFIX_LEN,
)?
else {
return Ok(None);
};
let Some(tx_count) = decode_block_tx_count(&prefix) else {
return Ok(None);
};
let body_size = usize::try_from(position.len)
.map_err(|_| StorageError::InvalidOperation("block body length does not fit usize"))?;
Ok(Some((body_size, tx_count)))
}
fn sync(&self) -> Result<(), StorageError> {
self.files.sync()?;
self.index.flush()
}
}
#[cfg(all(test, feature = "fjall"))]
mod body_position_prefetch_tests {
use super::*;
#[test]
fn prefetched_positions_stream_bodies_in_exact_request_order()
-> Result<(), Box<dyn std::error::Error>> {
let temp = tempfile::tempdir()?;
let index = Arc::new(bitcoin_rs_storage::FjallStore::open(
temp.path().join("index"),
)?);
let files = Arc::new(FlatFileBlockStore::open(temp.path())?);
let store = FlatFilePruneBodyStore::open(index, files);
let hash1 = Hash256::from_le_bytes(&[1_u8; 32]);
let hash2 = Hash256::from_le_bytes(&[2_u8; 32]);
store.persist_block_body(1, hash1, b"first body")?;
store.persist_block_body(2, hash2, b"second body")?;
let mut reader = store.reader()?;
reader.prefetch_positions(&[(1, hash1), (2, hash2)])?;
assert!(matches!(
reader.load_block_body(2, hash2),
Err(StorageError::InvalidOperation(
"prefetched body position consumed out of order"
))
));
assert_eq!(
reader.load_block_body(1, hash1)?.as_deref(),
Some(b"first body".as_slice())
);
assert_eq!(
reader.load_block_body(2, hash2)?.as_deref(),
Some(b"second body".as_slice())
);
assert!(matches!(
reader.load_block_body(2, hash2),
Err(StorageError::InvalidOperation(
"prefetched body positions are exhausted"
))
));
Ok(())
}
#[test]
fn malformed_body_row_is_incompatible_not_missing() -> Result<(), Box<dyn std::error::Error>> {
let temp = tempfile::tempdir()?;
let index = Arc::new(bitcoin_rs_storage::FjallStore::open(
temp.path().join("index"),
)?);
let files = Arc::new(FlatFileBlockStore::open(temp.path())?);
let store = FlatFilePruneBodyStore::open(index.clone(), files);
let hash = Hash256::from_le_bytes(&[9_u8; 32]);
store.persist_block_body(7, hash, b"body")?;
// Overwrite the position row with a legacy inline body: same key, not
// a decodable flat-file position.
let key = bitcoin_rs_storage::pruning::block_body_key(7, hash);
let mut batch = index.new_batch();
batch.put(
bitcoin_rs_storage::pruning::BLOCK_DATA_CF,
&key,
b"legacy-inline-body",
);
index.write(batch)?;
let Err(error) = store.load_block_body(7, hash) else {
return Err("malformed body row must fail closed".into());
};
assert!(matches!(error, StorageError::IncompatibleData(_)));
let mut reader = store.reader()?;
let Err(error) = reader.load_block_body(7, hash) else {
return Err("malformed body row must fail closed in the direct reader".into());
};
assert!(matches!(error, StorageError::IncompatibleData(_)));
Ok(())
}
#[test]
fn missing_prefetched_body_row_is_missing_not_incompatible()
-> Result<(), Box<dyn std::error::Error>> {
let temp = tempfile::tempdir()?;
let index = Arc::new(bitcoin_rs_storage::FjallStore::open(
temp.path().join("index"),
)?);
let files = Arc::new(FlatFileBlockStore::open(temp.path())?);
let store = FlatFilePruneBodyStore::open(index, files);
let hash = Hash256::from_le_bytes(&[8_u8; 32]);
let mut reader = store.reader()?;
reader.prefetch_positions(&[(7, hash)])?;
assert_eq!(reader.load_block_body(7, hash)?, None);
Ok(())
}
#[test]
fn malformed_prefetched_body_row_is_incompatible_not_missing()
-> Result<(), Box<dyn std::error::Error>> {
let temp = tempfile::tempdir()?;
let index = Arc::new(bitcoin_rs_storage::FjallStore::open(
temp.path().join("index"),
)?);
let files = Arc::new(FlatFileBlockStore::open(temp.path())?);
let store = FlatFilePruneBodyStore::open(index.clone(), files);
let hash = Hash256::from_le_bytes(&[7_u8; 32]);
let key = bitcoin_rs_storage::pruning::block_body_key(7, hash);
let mut batch = index.new_batch();
batch.put(
bitcoin_rs_storage::pruning::BLOCK_DATA_CF,
&key,
b"legacy-inline-body",
);
index.write(batch)?;
let mut reader = store.reader()?;
let Err(error) = reader.prefetch_positions(&[(7, hash)]) else {
return Err("malformed prefetched body row must fail closed".into());
};
assert!(matches!(error, StorageError::IncompatibleData(_)));
Ok(())
}
}
/// Admission barrier shared by every cloned apply handle.
pub(crate) struct ApplyAdmission {
closed: AtomicBool,
barrier: RwLock<()>,
}
impl ApplyAdmission {
pub(crate) fn new() -> Self {
Self {
closed: AtomicBool::new(false),
barrier: RwLock::new(()),
}
}
fn ensure_open(&self) -> Result<(), ApplyError> {
if self.closed.load(Ordering::Acquire) {
return Err(ApplyError::Shutdown);
}
Ok(())
}
fn enter(&self) -> Result<RwLockReadGuard<'_, ()>, ApplyError> {
self.ensure_open()?;
let permit = self.barrier.read();
if let Err(error) = self.ensure_open() {
drop(permit);
return Err(error);
}
Ok(permit)
}
pub(crate) fn close(&self) -> RwLockWriteGuard<'_, ()> {
self.closed.store(true, Ordering::Release);
self.barrier.write()
}
/// Temporarily pauses new chain transitions while the returned guard lives.
pub(crate) fn pause(&self) -> RwLockWriteGuard<'_, ()> {
self.barrier.write()
}
/// Closes admission without taking the barrier.
///
/// [`Self::close`] hands back the write guard because shutdown holds it
/// while it drains. A torn chainstate has nothing to drain and no owner to
/// hold a guard: it needs the flag set and every later `enter` refused,
/// including the one that would otherwise apply the next block.
pub(crate) fn close_permanently(&self) {
self.closed.store(true, Ordering::Release);
}
}
/// Proof that admission and the chain-transition lock are both held.
///
/// [`begin_chain_transition`] is the only constructor. Field order releases
/// the transition lock before the permit. This is the lock token only; the
/// caller-facing mutation capability is [`ChainTransition`].
pub(crate) struct TransitionLock<'a> {
_transition: MutexGuard<'a, ()>,
_admission: RwLockReadGuard<'a, ()>,
}
fn begin_chain_transition<'a>(
admission: &'a ApplyAdmission,
chain_transition: &'a Mutex<()>,
) -> core::result::Result<TransitionLock<'a>, ApplyError> {
let admission_guard = admission.enter()?;
let transition = chain_transition.lock();
admission.ensure_open()?;
Ok(TransitionLock {
_transition: transition,
_admission: admission_guard,
})
}
/// Unforgeable proof that a chain change is active: holds both the
/// admission/transition lock ([`TransitionLock`]) and the gateway's
/// [`ChainChangeGuard`] (odd generation).
///
/// Fields and constructor are private to this module. The admitted helpers
/// accept `&ChainChangeProof`, not independent `&TransitionLock` and
/// `&ChainChangeGuard` arguments, so a call without an active odd generation
/// fails to compile. Build one proof per single operation, whole window, or
/// whole reorg. Finish only at the outer success boundary.
pub(crate) struct ChainChangeProof<'a> {
#[expect(
dead_code,
reason = "carried for unforgeability: holding the proof proves both tokens were acquired"
)]
transition: TransitionLock<'a>,
guard: ChainChangeGuard,
}
impl<'a> ChainChangeProof<'a> {
/// Constructs the combined proof from its two halves.
///
/// Private to this module: only the entry-point functions that begin a
/// chain change call this.
pub(crate) fn new(transition: TransitionLock<'a>, guard: ChainChangeGuard) -> Self {
Self { transition, guard }
}
/// Returns the exact odd generation this proof reserved.
#[cfg(test)]
pub(crate) fn odd_generation(&self) -> u64 {
self.guard.odd_generation()
}
/// Returns the reserved even value.
#[cfg(test)]
pub(crate) fn reserved_even(&self) -> u64 {
self.guard.reserved_even()
}
/// Finishes the chain change, storing the reserved even value.
///
/// Consumes the proof so it cannot be used after finish.
pub(crate) fn finish(self) -> core::result::Result<(), ApplyError> {
self.guard.finish().map_err(|_| ApplyError::Shutdown)
}
}
/// Chain-mutation authority required by destructive block-body pruning.
#[derive(Clone)]
pub(crate) struct PruneAuthority {
admission: Arc<ApplyAdmission>,
chain_transition: Arc<Mutex<()>>,
applied_tip: Arc<ArcSwapOption<TipSnapshot>>,
}
impl PruneAuthority {
pub(crate) fn begin(&self) -> core::result::Result<PruneGuard<'_>, ApplyError> {
Ok(PruneGuard {
_transition: begin_chain_transition(&self.admission, &self.chain_transition)?,
applied_tip: &self.applied_tip,
})
}
}
/// Proof that pruning owns chain mutation and may read the authoritative tip.
pub(crate) struct PruneGuard<'a> {
_transition: TransitionLock<'a>,
applied_tip: &'a ArcSwapOption<TipSnapshot>,
}
impl PruneGuard<'_> {
#[must_use]
pub(crate) fn applied_tip_height(&self) -> Option<u32> {
self.applied_tip.load().as_ref().map(|tip| tip.height)
}
}
/// Hash-pinned assume-valid trust gate (Bitcoin Core `-assumevalid` semantics).
///
/// Historical script verification may be skipped only while the active header
/// chain is verified to contain the pinned anchor block. The gate starts
/// trusted when no anchor applies (no pin configured) and starts untrusted
/// when an anchor is pinned; [`AssumeValidGate::evaluate`] re-evaluates trust
/// against the block tree whenever a new inbound headers batch is accepted.
#[derive(Debug)]
pub struct AssumeValidGate {
/// Pinned `(height, hash)` anchor, or `None` when no pin applies.
anchor: Option<(u32, Hash256)>,
/// Whether the active chain is currently verified to contain the anchor.
trusted: AtomicBool,
/// Whether the diverged-chain warning has already been emitted.
warned: AtomicBool,
}
impl AssumeValidGate {
/// Builds the gate for `network` gated on `configured_height`.
///
/// The network's pinned anchor applies only when `configured_height` equals
/// the anchor height (the production default). Any other value — `0` (full
/// verification opt-in) or a custom height-only shortcut — leaves the gate
/// unpinned and therefore always trusted.
#[must_use]
pub fn new(network: Network, configured_height: u32) -> Self {
let anchor = network
.assume_valid_anchor()
.filter(|(height, _)| *height == configured_height);
Self {
trusted: AtomicBool::new(anchor.is_none()),
warned: AtomicBool::new(false),
anchor,
}
}
/// Builds a gate directly from an optional pinned anchor.
#[must_use]
pub fn with_anchor(anchor: Option<(u32, Hash256)>) -> Self {
Self {
trusted: AtomicBool::new(anchor.is_none()),
warned: AtomicBool::new(false),
anchor,
}
}
/// Returns whether historical script verification may currently be skipped.
#[must_use]
pub fn trusted(&self) -> bool {
self.trusted.load(Ordering::Relaxed)
}
/// Re-evaluates trust against `tree`'s active chain.
///
/// Trusted only when the active tip is at or above the pinned height and
/// the node at the pinned height on the active chain carries the pinned
/// hash. Emits a one-time warning when a chain at/past the anchor height
/// lacks the anchor block; such a chain is never trusted.
pub fn evaluate(&self, tree: &BlockTree) {
let Some((pinned_height, pinned_hash)) = self.anchor else {
return;
};
let Some(tip) = tree.tip() else {
self.trusted.store(false, Ordering::Relaxed);
return;
};
if tip.height < pinned_height {
self.trusted.store(false, Ordering::Relaxed);
return;
}
let trusted = tree
.node_at_height_from(tip.tip_id, pinned_height)
.is_some_and(|id| tree.lookup(pinned_hash) == Some(id));
if !trusted && !self.warned.swap(true, Ordering::Relaxed) {
tracing::warn!(
pinned_height,
pinned_hash = %pinned_hash,
"active chain lacks the assume-valid anchor block; verifying every script",
);
}
self.trusted.store(trusted, Ordering::Relaxed);
}
}
/// Where a block being applied came from. Decides whether its scripts execute.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BlockProvenance {
/// Untrusted input (peer delivery, submitblock, file import): scripts run
/// unless the assume-valid gate covers the height.
Network,
/// A body this node validated and persisted under its recovery marker
/// before the crash; its scripts already ran here.
LocalReplay,
}
/// Committed connect. Derived consumers read this after the tip is published.
#[derive(Clone, Debug)]
pub struct ConnectOutcome {
/// New applied tip.
pub tip: TipSnapshot,
/// Height of the connected block.
pub height: u32,
/// Hash of the connected block.
pub hash: Hash256,
/// Transaction ids in block order.
pub txids: Vec<Txid>,
/// Canonical block bytes when a derived consumer asked for them, else empty.
pub block_bytes: bytes::Bytes,
/// Per-transaction wire bytes when a derived consumer asked for `rawtx`.
pub raw_txs: Option<Vec<Vec<u8>>>,
}
/// Committed disconnect. Derived consumers read this after the tip is published.
#[derive(Clone, Debug)]
pub struct DisconnectOutcome {
/// Applied tip after the rollback (the parent).
pub parent_tip: TipSnapshot,
/// Hash of the disconnected block.
pub hash: Hash256,
/// Creating txids of coins the undo restored, for orphan re-evaluation.
pub restored_parents: Vec<Txid>,
}
/// Connect intent. See `ARCH-07` in `docs/contracts/architecture.md`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ApplyIntent {
Commit,
/// See `ARCH-07` in `docs/contracts/architecture.md`.
Propose,
}
/// Outcome of [`apply_block_admitted`] once intent is known.
enum ApplyFinish {
/// Commit path: the new applied tip, already published.
Committed(ConnectOutcome),
/// See `ARCH-07` in `docs/contracts/architecture.md`.
Proposed,
}
/// Coherent read of header tip, applied tip, and chain-tx count.
///
/// Produced by [`Chainstate::snapshot`]. Applied tip and `chain_tx_count` are
/// one publication. Header tip is a separate cell and may legitimately be
/// ahead of the applied chain. The snapshot cannot mutate chainstate.
#[derive(Clone, Debug)]
pub struct ChainstateSnapshot {
/// Best-work header tip, if the tree has one.
pub header: Option<TipSnapshot>,
/// Authoritative applied tip, if any block has committed.
pub applied: Option<TipSnapshot>,
/// Cumulative transaction count of the applied chain, or `0` when unknown.
///
/// Published with `applied`, never independently of it.
pub chain_tx_count: u64,
}
/// In-process facade for authoritative applied-chain mutation.
///
/// See `ARCH-07` in `docs/contracts/architecture.md`. Construction and
/// lifecycle stay in `node`. Mutation goes through [`Self::begin_transition`].
#[derive(Clone)]
pub struct Chainstate {
pub(crate) network: Network,
pub(crate) chain_tip: Arc<ArcSwapOption<TipSnapshot>>,
pub(crate) applied_tip: Arc<ArcSwapOption<TipSnapshot>>,
/// Cumulative transaction count of the applied chain, or `0` when unknown.
///
/// Bitcoin Core's `CBlockIndex::m_chain_tx_count`, including its convention
/// that zero means *unset* rather than *empty* (`HaveNumChainTxs()`). Only a
/// chain applied from genesis by a node that maintains this counter can know
/// it; a cold start before genesis or an arithmetic inconsistency leaves it
/// unknown until the chain is applied again.
///
/// Kept beside `applied_tip`. Connect and disconnect publish the pair
/// under `applied_seq` so [`Chainstate::snapshot`] copies one view.
pub(crate) chain_tx_count: Arc<AtomicU64>,
/// Seqlock for the applied-tip / chain-tx-count pair.
///
/// Odd means a writer is between the two stores; even is a stable pair.
/// Snapshot readers retry instead of taking the transition lock.
pub(crate) applied_seq: Arc<AtomicU64>,
pub(crate) block_tree: Arc<RwLock<BlockTree>>,
pub(crate) utxo: Arc<UtxoSet>,
pub(crate) coin_stats: Arc<bitcoin_rs_utxo::stats::CoinStatsListener>,
/// Read-only pool handle shared with `NodeState`. Apply mutates through
/// `mempool_gateway`. Tests inspect this cell; production apply does not.
#[allow(
dead_code,
reason = "shared with NodeState and tests; apply uses mempool_gateway"
)]
pub(crate) mempool: Arc<RwLock<Mempool>>,
/// Strong gateway handle for production mempool mutation. Apply and reorg
/// call this directly; they never call `MempoolGateway::shared` or recover
/// from the weak registry. The raw `mempool` field stays for read-only
/// node code that still needs the pool.
pub(crate) mempool_gateway: Arc<MempoolGateway>,
pub(crate) chain_events: Arc<crate::state::ChainEventPublisher>,
pub(crate) block_body_store: Option<Arc<dyn PruneBodyStore>>,
pub(crate) undo_store: Arc<dyn UndoStore>,
pub(crate) admission: Arc<ApplyAdmission>,
pub(crate) shutdown: Arc<AtomicBool>,
/// Serializes whole chain transitions against each other.
///
/// Distinct from `admission`, which is a shutdown barrier: `enter` takes a
/// READ guard, so any number of applies hold it at once and it excludes
/// nothing but a checkpoint close. A transition reads the applied tip,
/// decides what follows it, mutates chain-owned state, and publishes the
/// result. Two such operations interleaved can both validate against the
/// same tip and then invalidate each other's retention or publication
/// decisions. This lock spans connects, windows, disconnects, and pruning.
pub(crate) chain_transition: Arc<parking_lot::Mutex<()>>,
pub(crate) assume_valid_height: u32,
pub(crate) assume_valid_gate: Arc<AssumeValidGate>,
/// Chainstate-journal writer, when the journal is enabled (issue #230).
///
/// `None` = journal off: the apply path emits nothing and behaves exactly
/// as a checkpoint-only node. The writer is single-owner (the apply path);
/// the `Mutex` only makes the shared handle exclusive.
pub(crate) journal: Option<crate::chainstate_journal::SharedJournalWriter>,
/// Publishes checkpoints to settle rolled-back disconnect debt after a
/// non-fatal reorg. `None` in unit-test handle sets that never reorg.
pub(crate) checkpoint_publisher: Option<Arc<crate::checkpoint_worker::CheckpointPublisher>>,
/// Capture per-transaction wire bytes for a derived `rawtx` consumer.
pub(crate) capture_rawtx: bool,
/// Serialize the full block for a derived consumer (body store, index, rawblock).
pub(crate) capture_block_bytes: bool,
}
/// One admitted chain mutation.
///
/// Owns admission, the exclusive transition lock, and mempool generation.
/// Connect, window-connect, and disconnect run only through this type.
/// Dropping without [`Self::finish`] leaves generation odd by design.
///
/// # Persistence
///
/// Connect and replay write the block body and commit the UTXO set before
/// publishing `applied_tip`. A successful return means the new tip is visible
/// in memory. Store durability follows the journal batch cadence and the next
/// clean checkpoint (`docs/chainstate-recovery.md`). A crash before that
/// checkpoint recovers from the last authenticated checkpoint plus any
/// committed journal suffix. Permanent consensus failures must not be retried
/// with the same block; operational failures (storage, UTXO commit, shutdown)
/// stay with the caller to retry.
///
/// Disconnect arms a durable `DisconnectMarker` before the UTXO undo. The
/// commit point is the `applied_tip` rollback after a successful undo
/// (`EVT-05` in `docs/contracts/chain-events.md`). `DisconnectError::Refused`
/// means nothing was mutated. `DisconnectError::Fatal` means a partial undo:
/// do not retry, poison admission, and shut down. A crash during rollback is
/// recovered from the marker, not by retrying the disconnect. The
/// `RolledBack` marker stays until the checkpoint that publishes the
/// rolled-back state.
///
/// Window apply commits one block at a time. A failure leaves the committed
/// prefix in place. Permanent failures invalidate the failed subtree;
/// operational failures leave that block retryable.
///
/// [`Self::finish`] stores the reserved even mempool generation. It does not
/// persist chainstate. Call it only after a successful mutation. A crash or
/// drop after a successful connect but before finish leaves generation odd
/// until an external recovery path resets it.