-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate.rs
More file actions
2790 lines (2583 loc) · 107 KB
/
Copy pathstate.rs
File metadata and controls
2790 lines (2583 loc) · 107 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
//! Shared node state aggregating subsystem handles.
//!
//! V1 keeps this deliberately minimal: it owns the resolved [`Config`], the
//! data-directory path, the open chainstate storage backend, and the replay log
//! used by [`crate::crash_recovery`]. Subsystem wiring (chain / utxo / mempool
//! / index / p2p / rpc / electrum) parks here as the integration point matures.
use arc_swap::{ArcSwap, ArcSwapOption};
use bitcoin::consensus::encode::deserialize;
use bitcoin::hex::FromHex as _;
use bitcoin::{Transaction, Txid};
use bitcoin_rs_chain::TipSnapshot;
use bitcoin_rs_rpc::{
BlockBodyMetadata, BlockBodySource, BlockRecord, NetworkState, PruneResult, PruneService,
PruneServiceError, PruneStatus, ZmqNotification,
};
use compact_str::CompactString;
use core::fmt;
use core::mem::size_of;
use crossbeam_channel::{Receiver, Sender};
use hashbrown::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use anyhow::{Context as _, Result, bail};
use bitcoin_rs_mempool::{Mempool, MempoolLimits};
use bitcoin_rs_pruning::policy::CORE_REORG_SAFETY_MARGIN;
use bitcoin_rs_pruning::{
PrunePolicy, reclaim_staged_flat_block_files, stage_block_and_undo_prune,
};
use bitcoin_rs_storage::{ColumnFamily, FlatFileBlockStore, KvStore, WriteBatch};
use bitcoin_rs_utxo::UtxoSet;
use parking_lot::{Mutex, RwLock};
use crate::Config;
type FilterIndexHandle = Arc<Box<dyn bitcoin_rs_filters::FilterIndexLike>>;
struct DisabledFilterIndex;
impl bitcoin_rs_filters::FilterIndexLike for DisabledFilterIndex {
fn wants_filters(&self) -> bool {
false
}
fn put_filter(
&self,
_block_hash: bitcoin_rs_primitives::Hash256,
_prev_header: bitcoin_rs_primitives::Hash256,
_filter_bytes: &[u8],
) -> std::result::Result<bitcoin_rs_primitives::Hash256, bitcoin_rs_filters::FilterIndexError>
{
Ok(bitcoin_rs_primitives::Hash256::default())
}
fn filter_header(
&self,
_block_hash: bitcoin_rs_primitives::Hash256,
) -> std::result::Result<
Option<bitcoin_rs_primitives::Hash256>,
bitcoin_rs_filters::FilterIndexError,
> {
Ok(None)
}
}
// One active generation of outbound requests is enough to keep the drain fed;
// extra backlog is overload and must fail fast at producers.
pub(crate) const P2P_OUTBOUND_QUEUE_LIMIT: usize = 8;
// Bounds transient inbound-block buffering between the per-peer listener
// threads and the single-threaded `BlockSync::tick` drain. Decoded inbound
// blocks carry the full `Block` plus preserved wire bytes (up to ~4 MiB each),
// so an unbounded channel lets a fast or flooding peer accumulate blocks faster
// than they drain — an OOM vector. A full channel applies TCP backpressure to
// the sending peer's listener thread; `tick` drains independently and holds no
// lock a listener needs, so the bound cannot deadlock. Sized well above the
// in-flight request window (`PENDING_BUDGET` = 128) so honest delivery, which
// wakes the drain on every block, is never throttled.
pub(crate) const INBOUND_BLOCK_CHANNEL_LIMIT: usize = 256;
/// Errors produced when applying a block to the node state.
#[derive(Debug, thiserror::Error)]
pub enum ApplyError {
/// Clean shutdown has closed block-apply admission.
#[error("block apply rejected because clean shutdown has begun")]
Shutdown,
/// The block's previous header hash does not match the current tip's hash.
#[error("prev hash mismatch: tip {tip}, block prev {prev}")]
PrevHashMismatch {
/// Current tip header hash, big-endian hex.
tip: bitcoin_rs_primitives::Hash256,
/// Block's previous header hash, big-endian hex.
prev: bitcoin_rs_primitives::Hash256,
},
/// Height arithmetic overflowed `u32::MAX`.
#[error("height overflow at tip {0}")]
HeightOverflow(u32),
/// The block header hash does not satisfy its declared proof-of-work target.
#[error("proof-of-work: header hash {hash} exceeds declared target")]
ProofOfWork {
/// Block header hash, big-endian display.
hash: bitcoin_rs_primitives::Hash256,
},
/// Declared target exceeds the network's proof-of-work limit.
#[error("declared target exceeds network max_target")]
TargetAboveLimit,
/// Declared `nBits` does not match the parent block's `nBits` at a non-retarget height.
#[error(
"nBits {actual:08x} does not match parent {expected:08x} at non-retarget height {height}"
)]
NbitsNonRetargetMismatch {
/// This block's `nBits`.
actual: u32,
/// Parent block's `nBits`.
expected: u32,
/// Block height.
height: u32,
},
/// Consensus validation rejected the block.
#[error("consensus: {0}")]
Consensus(#[from] bitcoin_rs_consensus::ConsensusError),
/// Block-tree insertion rejected the header.
#[error("chain: {0}")]
Chain(#[from] bitcoin_rs_chain::ChainError),
/// UTXO commit failed during block apply.
#[error("utxo commit: {0}")]
UtxoCommit(#[from] bitcoin_rs_utxo::UtxoError),
/// Persisting the canonical prunable block body failed.
#[error("block body persistence: {0}")]
BlockBodyPersistence(#[from] bitcoin_rs_storage::StorageError),
/// Persisting the UTXO undo record failed.
///
/// Fatal for the block: without a recoverable undo record the node could
/// not disconnect it, so the block must not be applied.
#[error("undo persistence: {0}")]
UndoPersistence(#[source] bitcoin_rs_storage::StorageError),
/// A spent output had no resolved prevout, so the undo record would be
/// unable to restore it.
#[error("undo record cannot restore spent output {txid}:{vout}")]
UndoPrevoutMissing {
/// Transaction id of the unresolvable spend.
txid: bitcoin_rs_primitives::Hash256,
/// Output index of the unresolvable spend.
vout: u32,
},
/// The undo record for a block being disconnected is absent.
///
/// Fatal: without it the UTXO set cannot be restored, and guessing would
/// silently corrupt the chainstate.
#[error("no undo record for block {hash} at height {height}")]
UndoRecordMissing {
/// Block whose record is absent.
hash: bitcoin_rs_primitives::Hash256,
/// Height the block was applied at.
height: u32,
},
/// A stored undo record could not be decoded.
#[error("undo record for block {hash} is unreadable: {reason}")]
UndoRecordUnreadable {
/// Block whose record is unreadable.
hash: bitcoin_rs_primitives::Hash256,
/// Why the codec rejected it.
reason: String,
},
/// Reading a stored undo record failed.
#[error("undo record read: {0}")]
UndoRead(#[source] bitcoin_rs_storage::StorageError),
/// The block asked to be disconnected is not the applied tip.
///
/// Blocks must be disconnected tip-first. Taking one from the middle would
/// restore outputs that its descendants have already spent.
#[error("block {hash} is not the applied tip {tip}")]
DisconnectNotTip {
/// Block the caller asked to disconnect.
hash: bitcoin_rs_primitives::Hash256,
/// Block that is actually applied.
tip: bitcoin_rs_primitives::Hash256,
},
/// The supplied block body does not match its own header.
///
/// The header hash commits to the merkle root, not to the transactions the
/// caller handed over. A body swapped under a matching header would roll
/// the index back over the wrong rows.
#[error("block {hash} body does not match its header merkle root")]
DisconnectBodyMismatch {
/// Block whose body was rejected.
hash: bitcoin_rs_primitives::Hash256,
},
/// Reading a BIP157 filter header failed.
///
/// A broken backend, not a missing row: an absent header is answered by
/// skipping the filter write, which keeps the chain moving.
#[error("filter header lookup: {0}")]
FilterHeaderLookup(#[source] bitcoin_rs_filters::FilterIndexError),
/// Rewinding the block-level coinstats failed.
///
/// The per-coin fields ride the UTXO change listener and are already
/// reversed by the undo; only height and transaction count are set
/// directly, and a refusal here means they do not describe the block being
/// disconnected.
#[error("coinstats rewind: {0}")]
CoinStatsRewind(#[source] bitcoin_rs_coinstats::CoinStatsRewindError),
}
/// The outcome of a refused or failed block disconnect.
///
/// Two variants because the caller must act differently, and a single error
/// type let that distinction live in prose where it can be missed. Every
/// disconnect failure is one or the other; there is no third case.
#[derive(Debug, thiserror::Error)]
pub enum DisconnectError {
/// Refused before anything was touched. The chain is exactly as it was.
///
/// Safe to report and carry on: no rollback started, so no state is half
/// applied. Every check that can produce this runs in the planning step
/// precisely so that refusing stays free.
#[error("disconnect refused: {0}")]
Refused(#[source] Box<ApplyError>),
/// Failed after the rollback began. Some state is rolled back and some is
/// not, and which is which depends on where it stopped.
///
/// Fatal. Do not retry: the UTXO commit fires the set's change listener and
/// coinstats is registered as one, so a second pass double-counts even
/// where the set itself converges. Stop applying blocks and report the
/// block named here, which is why the hash and height are carried rather
/// than left for the caller to reconstruct.
#[error(
"disconnect of block {hash} at height {height} failed after mutation began, chain state is partial: {source}"
)]
Fatal {
/// Block whose disconnect wedged.
hash: bitcoin_rs_primitives::Hash256,
/// Height it was applied at.
height: u32,
/// What failed.
#[source]
source: Box<ApplyError>,
},
/// Rolled back cleanly, but the in-flight marker could not be cleared.
///
/// The chain is consistent and no data is lost. What is broken is the
/// interlock: the marker still says a disconnect was in flight, so the next
/// start refuses until it is cleared. Reported rather than folded into
/// success because a caller that heard "done" would restart into a refusal
/// it had no warning of.
#[error(
"disconnect of block {hash} at height {height} completed but the in-flight marker remains set: {source}"
)]
MarkerStuck {
/// Block that was disconnected.
hash: bitcoin_rs_primitives::Hash256,
/// Height it was applied at.
height: u32,
/// Why the marker could not be cleared.
#[source]
source: Box<ApplyError>,
},
}
enum NodeStorage {
#[cfg(feature = "rocksdb")]
RocksDb(Arc<bitcoin_rs_storage::RocksDbStore>),
#[cfg(feature = "fjall")]
Fjall(Arc<bitcoin_rs_storage::FjallStore>),
#[cfg(feature = "redb")]
Redb(Arc<bitcoin_rs_storage::RedbStore>),
#[cfg(feature = "mdbx")]
Mdbx(Arc<bitcoin_rs_storage::MdbxStore>),
}
impl NodeStorage {
fn open(config: &Config) -> Result<Self> {
let chainstate_dir = config.data_dir.join("chainstate");
std::fs::create_dir_all(&chainstate_dir)
.with_context(|| format!("create chainstate_dir {}", chainstate_dir.display()))?;
match config.storage_backend.as_str() {
#[cfg(feature = "rocksdb")]
"rocksdb" => Ok(Self::RocksDb(Arc::new(
bitcoin_rs_storage::RocksDbStore::open(&chainstate_dir)
.map_err(anyhow::Error::new)?,
))),
#[cfg(feature = "fjall")]
"fjall" => Ok(Self::Fjall(Arc::new(
bitcoin_rs_storage::FjallStore::open(&chainstate_dir)
.map_err(anyhow::Error::new)?,
))),
#[cfg(feature = "redb")]
"redb" => Ok(Self::Redb(Arc::new(
bitcoin_rs_storage::RedbStore::open(&chainstate_dir).map_err(anyhow::Error::new)?,
))),
#[cfg(feature = "mdbx")]
"mdbx" => Ok(Self::Mdbx(Arc::new(
bitcoin_rs_storage::MdbxStore::open(&chainstate_dir).map_err(anyhow::Error::new)?,
))),
other => bail!(
"unsupported storage backend: {other} (compiled features = {CompiledStorageFeatures})"
),
}
}
const fn kind(&self) -> &'static str {
match self {
#[cfg(feature = "rocksdb")]
Self::RocksDb(store) => {
let _ = store;
"rocksdb"
}
#[cfg(feature = "fjall")]
Self::Fjall(store) => {
let _ = store;
"fjall"
}
#[cfg(feature = "redb")]
Self::Redb(store) => {
let _ = store;
"redb"
}
#[cfg(feature = "mdbx")]
Self::Mdbx(store) => {
let _ = store;
"mdbx"
}
}
}
fn prune_service(
&self,
block_files: &Arc<FlatFileBlockStore>,
block_body_store: &Arc<dyn crate::apply::PruneBodyStore>,
blocks: Arc<RwLock<Vec<BlockRecord>>>,
transactions: Arc<RwLock<HashMap<Txid, Transaction>>>,
durable_tip_height: &Arc<AtomicU32>,
) -> Result<Arc<dyn PruneService>> {
match self {
#[cfg(feature = "rocksdb")]
Self::RocksDb(store) => Ok(Arc::new(NodePruneService::new(
Arc::clone(store),
Arc::clone(block_files),
Arc::clone(block_body_store),
blocks,
transactions,
Arc::clone(durable_tip_height),
)?)),
#[cfg(feature = "fjall")]
Self::Fjall(store) => Ok(Arc::new(NodePruneService::new(
Arc::clone(store),
Arc::clone(block_files),
Arc::clone(block_body_store),
blocks,
transactions,
Arc::clone(durable_tip_height),
)?)),
#[cfg(feature = "redb")]
Self::Redb(store) => Ok(Arc::new(NodePruneService::new(
Arc::clone(store),
Arc::clone(block_files),
Arc::clone(block_body_store),
blocks,
transactions,
Arc::clone(durable_tip_height),
)?)),
#[cfg(feature = "mdbx")]
Self::Mdbx(store) => Ok(Arc::new(NodePruneService::new(
Arc::clone(store),
Arc::clone(block_files),
Arc::clone(block_body_store),
blocks,
transactions,
Arc::clone(durable_tip_height),
)?)),
}
}
fn block_body_store(
&self,
files: Arc<FlatFileBlockStore>,
data_dir: &Path,
) -> Result<Arc<dyn crate::apply::PruneBodyStore>> {
match self {
#[cfg(feature = "rocksdb")]
Self::RocksDb(store) => Ok(Arc::new(crate::apply::FlatFilePruneBodyStore::open(
Arc::clone(store),
files,
data_dir,
)?)),
#[cfg(feature = "fjall")]
Self::Fjall(store) => Ok(Arc::new(crate::apply::FlatFilePruneBodyStore::open(
Arc::clone(store),
files,
data_dir,
)?)),
#[cfg(feature = "redb")]
Self::Redb(store) => Ok(Arc::new(crate::apply::FlatFilePruneBodyStore::open(
Arc::clone(store),
files,
data_dir,
)?)),
#[cfg(feature = "mdbx")]
Self::Mdbx(store) => Ok(Arc::new(crate::apply::FlatFilePruneBodyStore::open(
Arc::clone(store),
files,
data_dir,
)?)),
}
}
/// Builds the undo store for the configured backend.
///
/// Mandatory rather than optional: without undo records the node cannot
/// disconnect a block, so it could advance its tip into a chain it is
/// unable to leave.
fn undo_store(&self) -> Arc<dyn crate::apply::UndoStore> {
match self {
#[cfg(feature = "rocksdb")]
Self::RocksDb(store) => Arc::new(crate::apply::KvUndoStore::new(Arc::clone(store))),
#[cfg(feature = "fjall")]
Self::Fjall(store) => Arc::new(crate::apply::KvUndoStore::new(Arc::clone(store))),
#[cfg(feature = "redb")]
Self::Redb(store) => Arc::new(crate::apply::KvUndoStore::new(Arc::clone(store))),
#[cfg(feature = "mdbx")]
Self::Mdbx(store) => Arc::new(crate::apply::KvUndoStore::new(Arc::clone(store))),
}
}
#[cfg(test)]
fn stored_prune_body(
&self,
height: u32,
hash: bitcoin_rs_primitives::Hash256,
) -> Result<Option<Vec<u8>>> {
let key = bitcoin_rs_pruning::block_body_key(height, hash);
match self {
#[cfg(feature = "rocksdb")]
Self::RocksDb(store) => Ok(store.get(bitcoin_rs_pruning::BLOCK_DATA_CF, &key)?),
#[cfg(feature = "fjall")]
Self::Fjall(store) => Ok(store.get(bitcoin_rs_pruning::BLOCK_DATA_CF, &key)?),
#[cfg(feature = "redb")]
Self::Redb(store) => Ok(store.get(bitcoin_rs_pruning::BLOCK_DATA_CF, &key)?),
#[cfg(feature = "mdbx")]
Self::Mdbx(store) => Ok(store.get(bitcoin_rs_pruning::BLOCK_DATA_CF, &key)?),
}
}
#[cfg(test)]
fn stored_prune_undo(
&self,
height: u32,
hash: bitcoin_rs_primitives::Hash256,
) -> Result<Option<Vec<u8>>> {
let key = bitcoin_rs_pruning::block_undo_key(height, hash);
match self {
#[cfg(feature = "rocksdb")]
Self::RocksDb(store) => Ok(store.get(ColumnFamily::UndoData, &key)?),
#[cfg(feature = "fjall")]
Self::Fjall(store) => Ok(store.get(ColumnFamily::UndoData, &key)?),
#[cfg(feature = "redb")]
Self::Redb(store) => Ok(store.get(ColumnFamily::UndoData, &key)?),
#[cfg(feature = "mdbx")]
Self::Mdbx(store) => Ok(store.get(ColumnFamily::UndoData, &key)?),
}
}
}
struct StoredBlockBodySource {
store: Arc<dyn crate::apply::PruneBodyStore>,
}
impl StoredBlockBodySource {
fn new(store: Arc<dyn crate::apply::PruneBodyStore>) -> Self {
Self { store }
}
}
impl BlockBodySource for StoredBlockBodySource {
fn block_body(&self, height: u32, hash: bitcoin_rs_primitives::Hash256) -> Option<Vec<u8>> {
self.store.load_block_body(height, hash).ok().flatten()
}
fn block_body_range(
&self,
height: u32,
hash: bitcoin_rs_primitives::Hash256,
offset: u32,
len: u32,
) -> Option<Vec<u8>> {
// `None` is overloaded here: it means both "this store cannot slice"
// and "the read failed". Callers must treat either as a reason to fall
// back to the whole body, so the return type stays — but this is the
// hot path for every Electrum history call now, and an I/O error that
// silently degrades into a full block scan is exactly the failure that
// would otherwise show up only as unexplained latency.
match self.store.load_block_body_range(height, hash, offset, len) {
Ok(bytes) => bytes,
Err(error) => {
tracing::debug!(
%error,
height,
offset,
len,
"ranged block body read failed; falling back to the whole body"
);
None
}
}
}
fn block_body_metadata(
&self,
height: u32,
hash: bitcoin_rs_primitives::Hash256,
) -> Option<BlockBodyMetadata> {
self.store
.block_body_metadata(height, hash)
.ok()
.flatten()
.map(|(body_size, tx_count)| BlockBodyMetadata {
body_size,
tx_count,
})
}
}
const PRUNEHEIGHT_METADATA_KEY: &[u8] = b"node:pruneheight";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ResumeSource {
Cold,
HeadersOnly,
Checkpoint,
}
fn load_pruneheight<S: KvStore>(store: &S) -> Result<Option<u32>> {
let Some(bytes) = store.get(ColumnFamily::UtxoMeta, PRUNEHEIGHT_METADATA_KEY)? else {
return Ok(None);
};
if bytes.len() != size_of::<u32>() {
bail!("invalid persisted pruneheight length {}", bytes.len());
}
let mut encoded = [0_u8; size_of::<u32>()];
encoded.copy_from_slice(&bytes);
Ok(Some(u32::from_be_bytes(encoded)))
}
/// Storage-backed implementation of RPC manual pruning.
pub struct NodePruneService<S: KvStore> {
store: Arc<S>,
block_files: Arc<FlatFileBlockStore>,
block_body_store: Arc<dyn crate::apply::PruneBodyStore>,
blocks: Arc<RwLock<Vec<BlockRecord>>>,
transactions: Arc<RwLock<HashMap<Txid, Transaction>>>,
pruneheight: Mutex<Option<u32>>,
/// Height the last clean checkpoint would restore to, 0 when none exists.
///
/// Undo pruning is bounded by this, not by the in-memory applied tip, which
/// can run far ahead of it.
durable_tip_height: Arc<AtomicU32>,
}
impl<S: KvStore> NodePruneService<S> {
/// Creates a manual pruning service over the chainstate store and RPC block cache.
pub(crate) fn new(
store: Arc<S>,
block_files: Arc<FlatFileBlockStore>,
block_body_store: Arc<dyn crate::apply::PruneBodyStore>,
blocks: Arc<RwLock<Vec<BlockRecord>>>,
transactions: Arc<RwLock<HashMap<Txid, Transaction>>>,
durable_tip_height: Arc<AtomicU32>,
) -> Result<Self> {
let pruneheight = load_pruneheight(&*store)?;
Ok(Self {
store,
block_files,
block_body_store,
blocks,
transactions,
pruneheight: Mutex::new(pruneheight),
durable_tip_height,
})
}
}
impl<S: KvStore> PruneService for NodePruneService<S> {
fn prune_to_height(
&self,
requested_height: u32,
) -> core::result::Result<PruneResult, PruneServiceError> {
let mut blocks = self.blocks.write();
let mut pruneheight = self.pruneheight.lock();
let policy = PrunePolicy {
target_size_mb: 0,
keep_below_tip: CORE_REORG_SAFETY_MARGIN,
};
let updated_pruneheight =
pruneheight.map_or(requested_height, |height| height.max(requested_height));
let pruner_tip = updated_pruneheight
.checked_add(policy.retention_depth())
.ok_or_else(|| PruneServiceError::failed("prune height overflow"))?;
let mut pruned_txids = Vec::new();
for record in blocks
.iter()
.filter(|record| record.height < updated_pruneheight)
{
if record.tx_count == 0 {
continue;
}
let bytes = if record.block_hex.is_empty() {
self.block_body_store
.load_block_body(record.height, record.hash)
.map_err(|error| PruneServiceError::failed(error.to_string()))?
.unwrap_or_default()
} else {
Vec::<u8>::from_hex(&record.block_hex).map_err(|error| {
PruneServiceError::failed(format!(
"cached block body at height {} is not valid hex: {error}",
record.height
))
})?
};
if bytes.is_empty() {
continue;
}
let block = deserialize::<bitcoin::Block>(&bytes).map_err(|error| {
PruneServiceError::failed(format!(
"cached block body at height {} failed decode: {error}",
record.height
))
})?;
pruned_txids.extend(block.txdata.iter().map(Transaction::compute_txid));
}
let mut batch = self.store.new_batch();
let (block_outcome, undo_outcome, prunable_files) = stage_block_and_undo_prune(
&*self.store,
&mut batch,
&self.block_files,
pruner_tip,
self.durable_tip_height.load(Ordering::Acquire),
policy,
)
.map_err(|err| PruneServiceError::failed(err.to_string()))?;
batch.put(
ColumnFamily::UtxoMeta,
PRUNEHEIGHT_METADATA_KEY,
&updated_pruneheight.to_be_bytes(),
);
self.store
.write(batch)
.map_err(|err| PruneServiceError::failed(err.to_string()))?;
reclaim_staged_flat_block_files(&*self.store, &self.block_files, &prunable_files)
.map_err(|err| PruneServiceError::failed(err.to_string()))?;
if !pruned_txids.is_empty() {
let mut transactions = self.transactions.write();
for txid in pruned_txids {
transactions.remove(&txid);
}
}
for record in blocks.iter_mut() {
if record.height < updated_pruneheight {
record.block_hex = String::new();
}
}
*pruneheight = Some(updated_pruneheight);
Ok(PruneResult {
requested_height,
pruneheight: updated_pruneheight,
block_rows_removed: block_outcome.blocks_removed,
undo_rows_removed: undo_outcome.blocks_removed,
bytes_freed: block_outcome
.bytes_freed
.saturating_add(undo_outcome.bytes_freed),
})
}
fn status(&self) -> PruneStatus {
PruneStatus {
pruned: true,
pruneheight: *self.pruneheight.lock(),
}
}
}
const COMPILED_STORAGE_FEATURES: &[&str] = &[
#[cfg(feature = "rocksdb")]
"rocksdb",
#[cfg(feature = "fjall")]
"fjall",
#[cfg(feature = "redb")]
"redb",
#[cfg(feature = "mdbx")]
"mdbx",
];
struct CompiledStorageFeatures;
impl fmt::Display for CompiledStorageFeatures {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Some((first, rest)) = COMPILED_STORAGE_FEATURES.split_first() else {
return f.write_str("none");
};
f.write_str(first)?;
for feature in rest {
f.write_str(",")?;
f.write_str(feature)?;
}
Ok(())
}
}
struct OpenTxIndex {
writer: Arc<dyn crate::txindex_worker::TxIndexWriter>,
reader: Arc<dyn bitcoin_rs_index::IndexReader>,
batch_limits: bitcoin_rs_index::PreparedBatchLimits,
}
fn open_writer<S>(
store: &Arc<S>,
) -> Result<bitcoin_rs_index::IndexWriter<S>, bitcoin_rs_index::IndexError>
where
S: bitcoin_rs_storage::KvStore,
{
match bitcoin_rs_index::IndexWriter::open(Arc::clone(store)) {
Ok(writer) => Ok(writer),
Err(bitcoin_rs_index::IndexError::LegacyCursorlessIndex) => {
bitcoin_rs_index::IndexWriter::reset_legacy(store.as_ref())?;
bitcoin_rs_index::IndexWriter::open(Arc::clone(store))
}
Err(error) => Err(error),
}
}
fn open_tx_index_store<S>(
store: Arc<S>,
batch_limits: bitcoin_rs_index::PreparedBatchLimits,
) -> Result<OpenTxIndex>
where
S: bitcoin_rs_storage::KvStore + Send + Sync + 'static,
{
let writer = open_writer(&store)?;
let writer: Arc<dyn crate::txindex_worker::TxIndexWriter> =
Arc::new(parking_lot::Mutex::new(writer));
let reader: Arc<dyn bitcoin_rs_index::IndexReader> =
Arc::new(bitcoin_rs_index::Indexer::new(store));
Ok(OpenTxIndex {
writer,
reader,
batch_limits,
})
}
fn open_tx_index(config: &Config) -> Result<Option<OpenTxIndex>> {
if !config.txindex {
return Ok(None);
}
if config.prune_target_mb > 0 {
bail!("-txindex is not compatible with -prune");
}
let txindex_dir = config.data_dir.join("txindex");
std::fs::create_dir_all(&txindex_dir)
.with_context(|| format!("create txindex_dir {}", txindex_dir.display()))?;
match config.storage_backend.as_str() {
#[cfg(feature = "rocksdb")]
"rocksdb" => {
let store = Arc::new(
bitcoin_rs_storage::RocksDbStore::open(&txindex_dir).map_err(anyhow::Error::new)?,
);
Ok(Some(open_tx_index_store(
store,
crate::txindex_worker::ROCKSDB_BATCH_LIMITS,
)?))
}
#[cfg(feature = "fjall")]
"fjall" => {
let store = Arc::new(
bitcoin_rs_storage::FjallStore::open(&txindex_dir).map_err(anyhow::Error::new)?,
);
Ok(Some(open_tx_index_store(
store,
crate::txindex_worker::DEFAULT_BATCH_LIMITS,
)?))
}
#[cfg(feature = "redb")]
"redb" => {
let store = Arc::new(
bitcoin_rs_storage::RedbTxIndexStore::open(&txindex_dir)
.map_err(anyhow::Error::new)?,
);
Ok(Some(open_tx_index_store(
store,
crate::txindex_worker::REDB_BATCH_LIMITS,
)?))
}
#[cfg(feature = "mdbx")]
"mdbx" => {
let store = Arc::new(
bitcoin_rs_storage::MdbxStore::open(&txindex_dir).map_err(anyhow::Error::new)?,
);
Ok(Some(open_tx_index_store(
store,
crate::txindex_worker::DEFAULT_BATCH_LIMITS,
)?))
}
other => bail!("unsupported storage backend for txindex: {other}"),
}
}
fn open_filter_index(config: &Config) -> Result<FilterIndexHandle> {
if !config.blockfilterindex {
let filter_index: Box<dyn bitcoin_rs_filters::FilterIndexLike> =
Box::new(DisabledFilterIndex);
return Ok(Arc::new(filter_index));
}
let filters_dir = config.data_dir.join("filters");
std::fs::create_dir_all(&filters_dir)
.with_context(|| format!("create filters_dir {}", filters_dir.display()))?;
let filter_index: Box<dyn bitcoin_rs_filters::FilterIndexLike> =
match config.storage_backend.as_str() {
#[cfg(feature = "rocksdb")]
"rocksdb" => Box::new(bitcoin_rs_filters::FilterIndex::new(
bitcoin_rs_storage::RocksDbStore::open(&filters_dir).map_err(anyhow::Error::new)?,
)),
#[cfg(feature = "fjall")]
"fjall" => Box::new(bitcoin_rs_filters::FilterIndex::new(
bitcoin_rs_storage::FjallStore::open(&filters_dir).map_err(anyhow::Error::new)?,
)),
#[cfg(feature = "redb")]
"redb" => Box::new(bitcoin_rs_filters::FilterIndex::new(
bitcoin_rs_storage::RedbStore::open(&filters_dir).map_err(anyhow::Error::new)?,
)),
#[cfg(feature = "mdbx")]
"mdbx" => Box::new(bitcoin_rs_filters::FilterIndex::new(
bitcoin_rs_storage::MdbxStore::open(&filters_dir).map_err(anyhow::Error::new)?,
)),
other => bail!("unsupported storage backend for filter index: {other}"),
};
Ok(Arc::new(filter_index))
}
/// Aggregate handle to a running node.
pub struct NodeState {
/// Height the last clean checkpoint would restore to, 0 when none exists.
///
/// Published by `write_clean_checkpoint` and read by the pruner, which must
/// not delete an undo record a crash-restore would still need.
durable_tip_height: Arc<AtomicU32>,
config: Config,
data_dir: PathBuf,
checkpoint_data_dir: cap_std::fs::Dir,
resume_source: ResumeSource,
storage: NodeStorage,
block_body_store: Arc<dyn crate::apply::PruneBodyStore>,
utxo: Arc<UtxoSet>,
coin_stats: Arc<bitcoin_rs_coinstats::CoinStatsListener>,
tx_index_runtime: Option<Arc<crate::txindex_worker::TxIndexRuntime>>,
tx_index_worker: Option<crate::txindex_worker::TxIndexWorker>,
tx_index_query: Option<Arc<crate::txindex_worker::TxIndexQueryEngine>>,
filter_index: FilterIndexHandle,
prune_service: Option<Arc<dyn PruneService>>,
zmq_publisher: Arc<dyn crate::ZmqPublisher>,
active_zmq_notifications: Vec<ZmqNotification>,
mempool: Arc<RwLock<Mempool>>,
chain_tip: Arc<ArcSwapOption<TipSnapshot>>,
applied_tip: Arc<ArcSwapOption<TipSnapshot>>,
block_tree: Arc<RwLock<bitcoin_rs_chain::BlockTree>>,
blocks: Arc<RwLock<Vec<BlockRecord>>>,
transactions: Arc<RwLock<HashMap<Txid, Transaction>>>,
network: Arc<RwLock<NetworkState>>,
peers: Arc<RwLock<Vec<bitcoin_rs_p2p::PeerInfo>>>,
/// Per-peer outbound message senders, keyed by remote socket address.
/// External code pushes messages here; the per-connection thread drains
/// and writes them to the peer's TCP stream.
peer_outbound: Arc<RwLock<HashMap<std::net::SocketAddr, bitcoin_rs_p2p::PeerLease>>>,
banned: Arc<RwLock<Vec<bitcoin_rs_p2p::BannedSubnet>>>,
p2p_outbound_tx: crossbeam_channel::Sender<std::net::SocketAddr>,
p2p_outbound_rx: Arc<Mutex<crossbeam_channel::Receiver<std::net::SocketAddr>>>,
inbound_headers_tx: Sender<bitcoin_rs_p2p::InboundHeaders>,
inbound_headers_rx: Arc<Mutex<Receiver<bitcoin_rs_p2p::InboundHeaders>>>,
inbound_blocks_tx: Sender<bitcoin_rs_p2p::InboundBlock>,
inbound_blocks_rx: Arc<Mutex<Receiver<bitcoin_rs_p2p::InboundBlock>>>,
apply_handles: crate::apply::ApplyHandles,
sync: Arc<crate::BlockSync>,
mining_template_id: Arc<ArcSwap<CompactString>>,
replayed: Mutex<Vec<u32>>,
}
impl NodeState {
/// Opens (or creates) the node's data directory and configured storage
/// backend.
#[allow(clippy::arc_with_non_send_sync)]
#[allow(clippy::too_many_lines)]
pub fn open(config: Config) -> Result<Self> {
config.validate()?;
std::fs::create_dir_all(&config.data_dir)
.with_context(|| format!("create data_dir {}", config.data_dir.display()))?;
let checkpoint_data_dir = crate::checkpoint_fs::open_data_dir(&config.data_dir)
.with_context(|| format!("open data_dir {}", config.data_dir.display()))?;
let checkpoint_config = crate::checkpoint::HeaderCheckpointConfig {
network: config.network,
genesis: config.network.genesis_block_hash(),
};
let checkpoint_load =
crate::checkpoint::load_checkpoint_from_dir(&checkpoint_data_dir, checkpoint_config)?;
let g2_muhash_sampler = config
.g2_muhash_samples
.clone()
.map(|path| crate::g2_muhash::G2MuhashSampler::open(path, config.g2_muhash_tip_height))
.transpose()
.context("open G2 MuHash sample writer")?
.map(Arc::new);
let g14_utxo_commit_sampler = match (
config.g14_utxo_commit_samples.as_ref(),
config.g14_utxo_commit_ibd_start_height,
config.g14_utxo_commit_ibd_stop_height,
config.g14_utxo_commit_ibd_start_hash.as_ref(),
config.g14_utxo_commit_ibd_stop_hash.as_ref(),
) {
(None, None, None, None, None) => None,
(
Some(path),
Some(start_height),
Some(stop_height),
Some(start_hash),
Some(stop_hash),
) => Some(Arc::new(
crate::g14_utxo_commit::G14UtxoCommitSampler::open(
path.clone(),
start_height,
stop_height,
start_hash.clone(),
stop_hash.clone(),
)
.context("open G14 UTXO commit sample writer")?,
)),
_ => {
bail!("g14_utxo_commit_samples requires complete G14 UTXO commit IBD window fields")
}
};
let storage = NodeStorage::open(&config)?;
let undo_store = storage.undo_store();
// Before anything reads the chainstate, let alone serves or syncs it.
// A node that starts on a torn chainstate builds on it, and every block
// it adds makes the damage harder to find.
if let Some(marker) = undo_store
.load_disconnect_marker()
.map_err(anyhow::Error::new)?
{
// Names directories rather than a `-reindex` option, because this
// node has no reindex. An instruction the operator cannot follow is
// worse than none.
//
// Remove the authoritative views. The marker covers a disconnect
// that did not reach a clean UTXO-and-tip checkpoint. TxIndex and
// filter rows are derived state outside this marker, but a retained
// TxIndex watermark can stall rollback because wiping the chainstate
// removes the body positions the index refers to. Include the txindex
// path so the operator action is complete.
bail!(
"refusing to start: a disconnect of block {hash} at height {height} did not \
reach a clean checkpoint, so the UTXO set and chain tip cannot be trusted \
together. The node cannot repair this in place. Remove or quarantine \
{chainstate}, {checkpoints}, and {txindex}, then resync.",
hash = marker.hash,
height = marker.height,
chainstate = config.data_dir.join("chainstate").display(),
checkpoints = config.data_dir.join("chainstate-checkpoints").display(),
txindex = config.data_dir.join("txindex").display(),
);
}
let block_files =
Arc::new(FlatFileBlockStore::open(&config.data_dir).map_err(anyhow::Error::new)?);
let block_body_store =
storage.block_body_store(Arc::clone(&block_files), &config.data_dir)?;
let filter_index = open_filter_index(&config)?;
let zmq_publications = config.zmq_publications();
let active_zmq_notifications: Vec<_> = zmq_publications
.iter()
.map(|publication| {
ZmqNotification::new(
publication.topic.notifier_type(),
publication.endpoint.clone(),
publication.hwm,
)
})
.collect();
let zmq_publisher: Arc<dyn crate::ZmqPublisher> = if zmq_publications.is_empty() {
Arc::new(crate::NoOpZmqPublisher)
} else {
Arc::new(crate::SocketZmqPublisher::bind(&zmq_publications)?)
};
let (
mut utxo_set,