-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmining.rs
More file actions
2107 lines (1976 loc) · 75.5 KB
/
Copy pathmining.rs
File metadata and controls
2107 lines (1976 loc) · 75.5 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
//! Node-owned mining candidate lifecycle coordinator.
//!
//! Generation is keyed by `(applied_tip_hash, mempool_sequence)`. Template
//! assembly is single-flight per key, cached by [`TemplateId`], and woken by
//! explicit generation publication. Proposal mode dry-runs the ordinary apply
//! validation path without persistence; solved-block submission returns only
//! after validation, persistence, and chain-state application complete.
use alloc::collections::VecDeque;
use alloc::sync::Arc;
use core::time::Duration;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
use arc_swap::ArcSwapOption;
use bitcoin_rs_chain::{
BlockTree, ChainError, NodeId, NodeStatus, TipSnapshot, accept_headers, current_unix_seconds,
};
use bitcoin_rs_consensus::ConsensusError;
use bitcoin_rs_mempool::{
Mempool, MempoolMiningSnapshot, MempoolObserver, MutationEnvelope, SnapshotEntry,
};
use bitcoin_rs_mining::{
AvailableMiningRule, BlockTemplate, BlockTemplateMode, BlockTemplateRequest,
BlockTemplateResult, BlockValidationResult, Candidate, CandidateContext, GenerateRequest,
GenerateSelection, GenerateTx, GeneratedBlock, LastCandidateInfo, MiningCapability,
MiningChainContext, MiningControl, MiningControlError, MiningInfo, MiningRule,
SignetMiningInfo, TemplateId, TemplateMutation, assemble_candidate, assemble_ordered_candidate,
difficulty_for_bits, update_uncommitted_block_structures,
};
use bitcoin_rs_primitives::{Block, Hash256, Header, Network, Tx, consensus_bytes};
use compact_str::CompactString;
use hashbrown::HashMap;
use parking_lot::{Condvar, Mutex, RwLock};
use crate::ApplyError;
use crate::apply::{self, Chainstate};
use crate::chain_effects::ChainFollowers;
/// Default number of cached candidates retained by template id.
const CANDIDATE_CACHE_LIMIT: usize = 8;
/// Finite bound on generation-key races during candidate assembly.
const CANDIDATE_GENERATION_RETRIES: usize = 8;
const GENERATION_RACE: &str = "generation key changed during candidate assembly";
/// Bitcoin Core's mempool-only long-poll cooldown before returning a new template.
const DEFAULT_MEMPOOL_UPDATE_WAIT: Duration = Duration::from_secs(10);
/// Upper bound for a single long-poll wait slice while rechecking predicates.
const LONG_POLL_SLICE: Duration = Duration::from_secs(1);
/// Consensus maximum block weight / serialized size.
const MAX_BLOCK_WEIGHT: u64 = 4_000_000;
const MAX_BLOCK_SIZE: u64 = 4_000_000;
/// Applied-tip hash plus mempool sequence that identify one candidate generation.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct GenerationKey {
/// Applied tip hash in consensus little-endian storage order.
pub tip_hash: Hash256,
/// Mempool sequence captured with the tip.
pub mempool_sequence: u64,
}
impl GenerationKey {
/// Opaque BIP22/BIP23 long-poll identity for this generation.
#[must_use]
pub fn template_id(self) -> TemplateId {
TemplateId::new(&self.tip_hash, self.mempool_sequence)
}
}
#[derive(Debug)]
struct InFlight {
key: GenerationKey,
result: Option<Result<Arc<Candidate>, MiningControlError>>,
}
struct CoordinatorState {
/// Last generation published to long-poll waiters.
published: Option<GenerationKey>,
/// Bounded LRU of assembled candidates keyed by template id.
cache: HashMap<TemplateId, Arc<Candidate>>,
/// Insertion order for deterministic eviction of the oldest entry.
cache_order: VecDeque<TemplateId>,
/// Single in-flight assembly, if any.
in_flight: Option<InFlight>,
/// Facts from the most recently assembled candidate.
last_candidate: Option<LastCandidateInfo>,
}
impl CoordinatorState {
fn new() -> Self {
Self {
published: None,
cache: HashMap::new(),
cache_order: VecDeque::new(),
in_flight: None,
last_candidate: None,
}
}
fn cache_get(&self, id: &TemplateId) -> Option<Arc<Candidate>> {
self.cache.get(id).cloned()
}
fn cache_insert(&mut self, id: TemplateId, candidate: Arc<Candidate>) {
if self.cache.contains_key(&id) {
self.cache.insert(id, candidate);
return;
}
while self.cache.len() >= CANDIDATE_CACHE_LIMIT {
let Some(oldest) = self.cache_order.pop_front() else {
break;
};
self.cache.remove(&oldest);
}
self.cache_order.push_back(id.clone());
self.cache.insert(id, candidate);
}
fn invalidate_key(&mut self, key: GenerationKey) {
let id = key.template_id();
if self.cache.remove(&id).is_some() {
self.cache_order.retain(|cached| cached != &id);
}
if self
.in_flight
.as_ref()
.is_some_and(|flight| flight.key == key)
{
self.in_flight = None;
}
}
}
/// Mempool-sequence wake that avoids the mempool read lock.
///
/// The mempool observer fires under the gateway's publish mutex; taking the
/// pool read lock from that path can deadlock or contend with an in-flight
/// writer. Implementations build the generation key from `applied_tip` plus
/// the caller-supplied sequence instead.
pub trait MempoolSequenceWake: Send + Sync {
/// Publishes a generation key built from `applied_tip` and `sequence`
/// without taking the mempool read lock, then wakes all waiters.
fn publish_generation_from(&self, sequence: u64);
}
/// Wake seam between authoritative mutations and the template coordinator.
///
/// [`MiningCoordinator::publish_generation`] documents that every long-poll
/// waiter must observe each authoritative applied-tip or mempool mutation,
/// but the coordinator is built after node state, so it cannot be referenced
/// from the apply path or the mempool gateway directly. This signal is
/// created with the node state, wired into the gateway's mutation observer
/// and the apply-path tip publication points, and the coordinator attaches
/// itself at startup: [`Self::publish_generation`] then forwards to the live
/// coordinator. With nothing attached it is a no-op — there is no waiter to
/// wake before the coordinator exists.
#[derive(Default)]
pub struct MiningGenerationSignal {
coordinator: RwLock<Option<std::sync::Weak<dyn MiningControl>>>,
/// Lock-free mempool-sequence wake; set by [`Self::attach_sequence_wake`].
sequence_wake: RwLock<Option<std::sync::Weak<dyn MempoolSequenceWake>>>,
}
impl MiningGenerationSignal {
/// Creates a detached signal.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Points the signal at `coordinator` without extending its ownership.
///
/// The RPC context owns the coordinator; this wake seam must not create
/// an ownership cycle through `MiningCoordinator::apply_handles`, which
/// carries the same signal back. A weak reference keeps the seam
/// observational: the coordinator's lifetime is the context's, and a
/// wake against a torn-down coordinator is a no-op.
pub fn attach(&self, coordinator: &Arc<dyn MiningControl>) {
*self.coordinator.write() = Some(Arc::downgrade(coordinator));
}
/// Points the signal at a lock-free mempool-sequence wake.
///
/// When attached, [`Self::publish_generation_from`] forwards to `wake`
/// without taking the mempool read lock. Without it, that method falls
/// back to [`Self::publish_generation`].
pub fn attach_sequence_wake(&self, wake: &Arc<dyn MempoolSequenceWake>) {
*self.sequence_wake.write() = Some(Arc::downgrade(wake));
}
/// Forwards one authoritative-mutation wake to the attached coordinator.
pub fn publish_generation(&self) {
if let Some(coordinator) = self
.coordinator
.read()
.as_ref()
.and_then(std::sync::Weak::upgrade)
{
coordinator.publish_generation();
}
}
/// Forwards one mempool-sequence wake to the attached coordinator.
///
/// Uses the lock-free [`MempoolSequenceWake`] path when attached;
/// otherwise falls back to [`Self::publish_generation`].
pub fn publish_generation_from(&self, sequence: u64) {
if let Some(wake) = self
.sequence_wake
.read()
.as_ref()
.and_then(std::sync::Weak::upgrade)
{
wake.publish_generation_from(sequence);
} else {
self.publish_generation();
}
}
}
impl MempoolObserver for MiningGenerationSignal {
fn on_mutation(&self, envelope: &MutationEnvelope) {
let result = &envelope.result;
let wake_sequence = result
.sequence_of(result.changes.len().saturating_sub(1))
.unwrap_or(result.sequence_base);
self.publish_generation_from(wake_sequence);
}
}
/// Production mining coordinator owned by the node process.
///
/// `coinbase_script` is immutable coordinator configuration captured at
/// construction. There is no wallet coupling and no default miner address:
/// callers must pass the template coinbase `ScriptBuf` explicitly. Callers may
/// pass an empty script for transport-only GBT assembly (RPC exposes
/// `coinbasevalue` / `default_witness_commitment`, not a node-owned payout).
pub struct MiningCoordinator {
network: Network,
applied_tip: Arc<ArcSwapOption<TipSnapshot>>,
block_tree: Arc<RwLock<BlockTree>>,
mempool: Arc<RwLock<Mempool>>,
apply_handles: Chainstate,
followers: ChainFollowers,
coinbase_script: Vec<u8>,
shutdown: Arc<AtomicBool>,
/// Wall clock used for long-poll cooldowns.
clock: Arc<dyn Fn() -> Instant + Send + Sync>,
/// Controllable mempool-only long-poll cooldown (Core default: 10s).
mempool_update_wait: Duration,
state: Mutex<CoordinatorState>,
wake: Condvar,
}
impl MiningCoordinator {
/// Builds a coordinator over the shared applied-chain and mempool handles.
///
/// `coinbase_script` is required and stored immutably. Pass
/// `Vec::new()` for transport-only template assembly when the node
/// does not own a miner payout script.
#[must_use]
pub fn new(
network: Network,
applied_tip: Arc<ArcSwapOption<TipSnapshot>>,
block_tree: Arc<RwLock<BlockTree>>,
mempool: Arc<RwLock<Mempool>>,
apply_handles: Chainstate,
followers: ChainFollowers,
coinbase_script: Vec<u8>,
shutdown: Arc<AtomicBool>,
) -> Self {
Self {
network,
applied_tip,
block_tree,
mempool,
apply_handles,
followers,
coinbase_script,
shutdown,
clock: Arc::new(Instant::now),
mempool_update_wait: DEFAULT_MEMPOOL_UPDATE_WAIT,
state: Mutex::new(CoordinatorState::new()),
wake: Condvar::new(),
}
}
/// Overrides the wall clock. Intended for deterministic tests.
#[must_use]
pub fn with_clock(mut self, clock: Arc<dyn Fn() -> Instant + Send + Sync>) -> Self {
self.clock = clock;
self
}
/// Overrides the mempool-only long-poll cooldown. Tests may set this to zero.
#[must_use]
pub const fn with_mempool_update_wait(mut self, wait: Duration) -> Self {
self.mempool_update_wait = wait;
self
}
/// Publishes the live generation key and wakes every long-poll / single-flight waiter.
///
/// Callers must invoke this after every authoritative applied-tip or mempool
/// mutation and before any dependent notification. The published key is
/// captured from live applied-tip / mempool state under the coordinator lock.
pub fn publish_generation(&self) {
let key = self.live_generation_key();
let mut state = self.state.lock();
if let Some(previous) = state.published
&& previous != key
{
state.invalidate_key(previous);
}
state.published = Some(key);
self.wake.notify_all();
}
/// Publishes a generation key built from `applied_tip` and `sequence`
/// without taking the mempool read lock, then wakes all waiters.
///
/// The mempool observer calls this with the sequence the mutation already
/// produced, avoiding a reentrant pool read that can deadlock under the
/// gateway's publish mutex. Tip-move callers should use
/// [`Self::publish_generation`] instead, which captures the live sequence
/// safely (no write lock is held on that path).
pub fn publish_generation_from(&self, sequence: u64) {
let tip_hash = self
.applied_tip
.load_full()
.map_or_else(|| self.network.genesis_block_hash(), |tip| tip.hash);
let key = GenerationKey {
tip_hash,
mempool_sequence: sequence,
};
let mut state = self.state.lock();
if let Some(previous) = state.published
&& previous != key
{
state.invalidate_key(previous);
}
state.published = Some(key);
self.wake.notify_all();
}
/// Reduces shutdown latency after the caller sets the shared shutdown flag.
///
/// Correctness does not depend on this notification: every wait is bounded
/// and rechecks the shutdown predicate.
pub fn notify_shutdown(&self) {
self.wake.notify_all();
}
fn live_generation_key(&self) -> GenerationKey {
let tip_hash = self
.applied_tip
.load_full()
.map_or_else(|| self.network.genesis_block_hash(), |tip| tip.hash);
let mempool_sequence = self.mempool.read().sequence_number();
GenerationKey {
tip_hash,
mempool_sequence,
}
}
fn current_time_secs() -> u32 {
u32::try_from(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |duration| duration.as_secs()),
)
.unwrap_or(u32::MAX)
}
fn ensure_published(&self, state: &mut CoordinatorState) -> GenerationKey {
let live = self.live_generation_key();
if state.published != Some(live) {
if let Some(previous) = state.published
&& previous != live
{
state.invalidate_key(previous);
}
state.published = Some(live);
}
live
}
fn wait_for_generation_change(
&self,
waited: GenerationKey,
) -> Result<GenerationKey, MiningControlError> {
let mut state = self.state.lock();
loop {
if self.shutdown.load(Ordering::Acquire) {
return Err(MiningControlError::Unavailable(CompactString::from(
"node is shutting down",
)));
}
let live = self.ensure_published(&mut state);
if live != waited {
return Ok(live);
}
let _ = self.wake.wait_for(&mut state, LONG_POLL_SLICE);
}
}
fn live_candidate(&self) -> Result<Arc<Candidate>, MiningControlError> {
let mut last_race = None;
for attempt in 0..CANDIDATE_GENERATION_RETRIES {
if self.shutdown.load(Ordering::Acquire) {
return Err(MiningControlError::Unavailable(CompactString::from(
"node is shutting down",
)));
}
let key = {
let mut state = self.state.lock();
self.ensure_published(&mut state)
};
match self.candidate_for_key(key) {
Ok(candidate) => {
if self.live_generation_key() == key {
return Ok(candidate);
}
last_race = Some(generation_race());
}
Err(error) if is_generation_race(&error) => last_race = Some(error),
Err(error) => return Err(error),
}
let _ = attempt;
}
Err(last_race.unwrap_or_else(generation_race))
}
fn candidate_for_key(&self, key: GenerationKey) -> Result<Arc<Candidate>, MiningControlError> {
let template_id = key.template_id();
let mut state = self.state.lock();
if let Some(cached) = state.cache_get(&template_id) {
return Ok(cached);
}
loop {
if self.shutdown.load(Ordering::Acquire) {
return Err(MiningControlError::Unavailable(CompactString::from(
"node is shutting down",
)));
}
let Some(flight) = state.in_flight.as_ref() else {
break;
};
if flight.key != key {
break;
}
if let Some(result) = flight.result.clone() {
return result;
}
let _ = self.wake.wait_for(&mut state, LONG_POLL_SLICE);
}
if let Some(cached) = state.cache_get(&template_id) {
return Ok(cached);
}
state.in_flight = Some(InFlight { key, result: None });
drop(state);
let assembled = self.assemble_for_key(key);
let mut state = self.state.lock();
let returned = match &assembled {
Ok(candidate) => {
let live = self.live_generation_key();
if live == key {
state.cache_insert(template_id, Arc::clone(candidate));
state.last_candidate = Some(LastCandidateInfo {
weight: candidate.weight,
transactions: u64::try_from(candidate.transactions.len())
.unwrap_or(u64::MAX)
.saturating_add(1),
});
state.published = Some(key);
Ok(Arc::clone(candidate))
} else {
Err(generation_race())
}
}
Err(error) => Err(error.clone()),
};
if let Some(flight) = state.in_flight.as_mut()
&& flight.key == key
{
flight.result = Some(returned.clone());
}
self.wake.notify_all();
if state
.in_flight
.as_ref()
.is_some_and(|flight| flight.key == key && flight.result.is_some())
{
state.in_flight = None;
}
returned
}
fn assemble_for_key(&self, key: GenerationKey) -> Result<Arc<Candidate>, MiningControlError> {
let tip = self.applied_tip.load_full().ok_or_else(|| {
MiningControlError::Unavailable(CompactString::from("applied tip is not available"))
})?;
if tip.hash != key.tip_hash {
return Err(generation_race());
}
let snapshot = {
let mempool = self.mempool.read();
if mempool.sequence_number() != key.mempool_sequence {
return Err(generation_race());
}
mempool.mining_snapshot()
};
let current_time = Self::current_time_secs().max(1);
let chain = {
let tree = self.block_tree.read();
MiningChainContext::resolve(&tree, self.network, tip.tip_id, current_time).map_err(
|error| MiningControlError::Failed(CompactString::from(error.to_string())),
)?
};
let context = CandidateContext {
previous_block_hash: chain.previous_block_hash,
height: chain.height,
version: chain.version,
bits: chain.bits,
min_time: chain.min_time,
current_time: current_time.max(chain.min_time),
locktime_cutoff: chain.locktime_cutoff(current_time.max(chain.min_time)),
network: self.network,
csv_active: chain.csv_active,
segwit_active: chain.segwit_active,
max_weight: MAX_BLOCK_WEIGHT,
max_size: MAX_BLOCK_SIZE,
max_sigops: u64::from(bitcoin_rs_consensus::MAX_BLOCK_SIGOPS_COST),
};
let candidate = assemble_candidate(&context, &snapshot, &self.coinbase_script)
.map_err(|error| MiningControlError::Failed(CompactString::from(error.to_string())))?;
if candidate.template_id != key.template_id() {
return Err(MiningControlError::Failed(CompactString::from(
"assembled candidate template id does not match generation key",
)));
}
Ok(Arc::new(candidate))
}
fn assemble_fresh(
&self,
payout: &[u8],
selection: &GenerateSelection,
) -> Result<Candidate, MiningControlError> {
let tip = self.applied_tip.load_full().ok_or_else(|| {
MiningControlError::Unavailable(CompactString::from("applied tip is not available"))
})?;
let snapshot = {
let mempool = self.mempool.read();
snapshot_for_selection(&mempool, selection)?
};
let current_time = Self::current_time_secs().max(1);
let chain = {
let tree = self.block_tree.read();
MiningChainContext::resolve(&tree, self.network, tip.tip_id, current_time).map_err(
|error| MiningControlError::Failed(CompactString::from(error.to_string())),
)?
};
let context = CandidateContext {
previous_block_hash: chain.previous_block_hash,
height: chain.height,
version: chain.version,
bits: chain.bits,
min_time: chain.min_time,
current_time: current_time.max(chain.min_time),
locktime_cutoff: chain.locktime_cutoff(current_time.max(chain.min_time)),
network: self.network,
csv_active: chain.csv_active,
segwit_active: chain.segwit_active,
max_weight: MAX_BLOCK_WEIGHT,
max_size: MAX_BLOCK_SIZE,
max_sigops: u64::from(bitcoin_rs_consensus::MAX_BLOCK_SIGOPS_COST),
};
match selection {
GenerateSelection::Mempool => assemble_candidate(&context, &snapshot, payout),
GenerateSelection::Ordered(_) => {
assemble_ordered_candidate(&context, &snapshot, payout)
}
}
.map_err(|error| MiningControlError::Failed(CompactString::from(error.to_string())))
}
/// Assemble, solve, and optionally persist `request.count` blocks (`API-05`).
///
/// Each submitted block is applied through `apply::apply_block` before the
/// next iteration; that is the commit point (`ARCH-07`). Failure after *N*
/// accepted submissions leaves those *N* blocks durable at the applied tip.
/// `submit = false` dry-validates through `apply::validate_block` and does
/// not persist. The result vector grows one block at a time, so `count` cannot
/// force a large allocation up front. Callers own retry after inspecting the
/// tip. [`MiningControlError::InvalidRequest`] is not retriable without
/// changing the request; `Unavailable` and `Failed` may be retried.
fn generate_blocks(
&self,
request: &GenerateRequest,
) -> Result<Vec<GeneratedBlock>, MiningControlError> {
if request.count == 0 {
return Ok(Vec::new());
}
if !request.submit && request.count != 1 {
return Err(MiningControlError::InvalidRequest(CompactString::from(
"submit=false requires nblocks=1",
)));
}
let mut generated = Vec::new();
for _ in 0..request.count {
if self.shutdown.load(Ordering::Acquire) {
return Err(MiningControlError::Unavailable(CompactString::from(
"node is shutting down",
)));
}
let candidate = self.assemble_fresh(&request.payout, &request.selection)?;
let block = candidate.solve(request.max_tries).map_err(|error| {
MiningControlError::Failed(CompactString::from(error.to_string()))
})?;
if request.submit {
match self.submit(&block)? {
BlockValidationResult::Accepted => {}
other => {
return Err(MiningControlError::Failed(CompactString::from(format!(
"generated block was not accepted: {other:?}"
))));
}
}
} else {
let validation = self.propose(&block);
if validation != BlockValidationResult::Accepted {
return Err(MiningControlError::Failed(CompactString::from(format!(
"generated block failed validation: {validation:?}"
))));
}
}
generated.push(GeneratedBlock {
hash: block.block_hash(),
hex: hex_encode(&consensus_bytes(&block)),
});
}
Ok(generated)
}
fn template_from_candidate(
network: Network,
candidate: Arc<Candidate>,
submit_old: Option<bool>,
version_bits_available: Vec<AvailableMiningRule>,
version_bits_required: u32,
) -> BlockTemplate {
let mut rules = Vec::new();
if candidate.segwit_active {
rules.push(MiningRule::new("segwit"));
}
if candidate.csv_active {
rules.push(MiningRule::new("csv"));
}
if network.is_taproot_active(candidate.height) {
rules.push(MiningRule::new("taproot"));
}
let signet = signet_info(network);
if signet.is_some() {
rules.push(MiningRule::new("signet"));
}
BlockTemplate {
candidate,
rules,
version_bits_available,
version_bits_required,
capabilities: vec![
MiningCapability::new("proposal"),
MiningCapability::new("longpoll"),
],
mutable: vec![
TemplateMutation::Time,
TemplateMutation::Transactions,
TemplateMutation::PreviousBlock,
],
submit_old,
signet,
}
}
fn version_bits_for(&self, candidate: &Candidate) -> (Vec<AvailableMiningRule>, u32) {
let Some(tip) = self.applied_tip.load_full() else {
return (Vec::new(), 0);
};
if tip.hash != candidate.previous_block_hash {
return (Vec::new(), 0);
}
let tree = self.block_tree.read();
let signalling = bitcoin_rs_chain::signalling_deployments(
&tree,
self.network,
tip.tip_id,
candidate.height,
);
let available = signalling
.into_iter()
.map(|deployment| AvailableMiningRule {
rule: MiningRule::new(deployment.name),
bit: deployment.bit,
})
.collect();
// Core v31 `getblocktemplate` hardcodes `vbrequired` to 0.
(available, 0)
}
fn propose(&self, block: &Block) -> BlockValidationResult {
// Core GBT proposal looks the hash up before TestBlockValidity.
if let Some(known) = self.known_block_result(block.block_hash().into()) {
return known;
}
match apply::validate_block(&self.apply_handles, block) {
Ok(()) => BlockValidationResult::Accepted,
Err(error) => map_apply_error(error),
}
}
/// Core `LookupBlockIndex` / BIP22 proposal vocabulary.
///
/// CONTRACT: docs/contracts/external-api.md#API-21
fn known_block_result(&self, block_hash: Hash256) -> Option<BlockValidationResult> {
let tree = self.block_tree.read();
let node_id = tree.lookup(block_hash)?;
let node = tree.node(node_id).ok()?;
if node.status == NodeStatus::Invalid {
return Some(BlockValidationResult::DuplicateInvalid);
}
if self.scripts_valid(&tree, node_id, node.height, node.chain_tx_count) {
return Some(BlockValidationResult::Duplicate);
}
Some(BlockValidationResult::DuplicateInconclusive)
}
/// In-process apply leaves `chain_tx_count`; checkpoint restore writes it
/// only on the applied tip, so applied-chain membership covers ancestors.
fn scripts_valid(
&self,
tree: &BlockTree,
node_id: NodeId,
height: u32,
chain_tx_count: u64,
) -> bool {
if chain_tx_count != 0 {
return true;
}
self.applied_tip
.load_full()
.is_some_and(|tip| tree.node_at_height_from(tip.tip_id, height) == Some(node_id))
}
/// Admits `header` through [`accept_headers`], the same gate inbound P2P uses.
fn accept_submitted_header(&self, header: Header) -> Result<(), MiningControlError> {
let mut tree = self.block_tree.write();
if tree.lookup(header.prev_blockhash.into()).is_none() {
return Err(MiningControlError::Rejected(CompactString::from(format!(
"Must submit previous header ({}) first",
header.prev_blockhash
))));
}
accept_headers(
&mut tree,
std::slice::from_ref(&header),
self.network,
current_unix_seconds(),
)
.map(|_| ())
.map_err(header_reject_reason)
}
/// Core `submitblock` fills the coinbase reserved nonce when the block
/// already has a BIP141 commitment but no coinbase witness. Proposal skips this.
fn fill_uncommitted_witness(&self, block: &mut Block) {
let tree = self.block_tree.read();
let Some(prev_id) = tree.lookup(block.header.prev_blockhash.into()) else {
return;
};
let Ok(prev) = tree.node(prev_id) else {
return;
};
let height = prev.height.saturating_add(1);
let segwit_active = self.network.is_segwit_active(height);
drop(tree);
update_uncommitted_block_structures(block, segwit_active);
}
fn submit(&self, block: &Block) -> Result<BlockValidationResult, MiningControlError> {
let block_hash: Hash256 = block.block_hash().into();
// CONTRACT: docs/contracts/external-api.md#API-21
// Header-only tree entries are DuplicateInconclusive and still receive
// the body so `submitheader` then `submitblock` works.
if matches!(
self.known_block_result(block_hash),
Some(BlockValidationResult::Duplicate)
) {
return Ok(BlockValidationResult::Duplicate);
}
match self.followers.apply_connect(&self.apply_handles, block) {
Ok(outcome) => {
let tip = outcome.tip;
let visible = self.applied_tip.load_full().ok_or_else(|| {
MiningControlError::Failed(CompactString::from(
"applied tip missing after accepted submission",
))
})?;
if visible.hash != tip.hash {
return Err(MiningControlError::Failed(CompactString::from(
"applied tip was not published before submit_block returned",
)));
}
Ok(BlockValidationResult::Accepted)
}
Err(error) => Ok(map_apply_error(error)),
}
}
fn mining_info_snapshot(&self) -> Result<MiningInfo, MiningControlError> {
let tip = self.applied_tip.load_full();
let blocks = tip.as_ref().map_or(0, |tip| tip.height);
let (bits, difficulty, next_bits, next_difficulty) = match tip.as_ref() {
Some(tip) => {
let tree = self.block_tree.read();
let tip_bits =
tree.node(tip.tip_id)
.map(|node| node.header.bits)
.map_err(|error| {
MiningControlError::Failed(CompactString::from(error.to_string()))
})?;
let current_time = Self::current_time_secs().max(1);
let next =
MiningChainContext::resolve(&tree, self.network, tip.tip_id, current_time)
.map_err(|error| {
MiningControlError::Failed(CompactString::from(error.to_string()))
})?;
(
tip_bits,
difficulty_for_bits(tip_bits),
next.bits,
difficulty_for_bits(next.bits),
)
}
None => (0, 0.0, 0, 0.0),
};
let pooled_transactions = u64::try_from(self.mempool.read().len()).unwrap_or(u64::MAX);
let minimum_fee_rate = self.mempool.read().min_relay_fee_sat_per_kvb();
let last_candidate = self.state.lock().last_candidate;
let network_hashes_per_second = {
let tree = self.block_tree.read();
estimate_network_hashps(
&tree,
tip.as_ref().map(|snapshot| snapshot.tip_id),
120,
self.network,
)
};
Ok(MiningInfo {
blocks,
last_candidate,
bits,
difficulty,
network_hashes_per_second,
pooled_transactions,
network: self.network,
next_bits,
next_difficulty,
minimum_fee_rate,
signet: signet_info(self.network),
warnings: crate::metrics::node_warnings()
.messages()
.into_iter()
.map(CompactString::from)
.collect(),
})
}
}
impl MiningControl for MiningCoordinator {
fn get_block_template(
&self,
request: BlockTemplateRequest,
) -> Result<BlockTemplateResult, MiningControlError> {
match request.mode {
BlockTemplateMode::Proposal(block) => {
Ok(BlockTemplateResult::Proposal(self.propose(&block)))
}
BlockTemplateMode::Template => {
let waited = if let Some(long_poll_id) = request.long_poll_id.as_deref() {
let waited = parse_long_poll_id(long_poll_id).ok_or_else(|| {
MiningControlError::InvalidRequest(CompactString::from(
"longpollid is malformed",
))
})?;
let live = {
let mut state = self.state.lock();
self.ensure_published(&mut state)
};
if live == waited {
self.wait_for_generation_change(waited)?;
}
Some(waited)
} else {
None
};
if self.applied_tip.load_full().is_none() {
return Err(MiningControlError::Unavailable(CompactString::from(
"applied tip is not available",
)));
}
let candidate = self.live_candidate()?;
let submit_old =
waited.map(|waited| candidate.previous_block_hash == waited.tip_hash);
let (version_bits_available, version_bits_required) =
self.version_bits_for(&candidate);
let template = Self::template_from_candidate(
self.network,
candidate,
submit_old,
version_bits_available,
version_bits_required,
);
Ok(BlockTemplateResult::Template(template))
}
}
}
fn mining_info(&self) -> Result<MiningInfo, MiningControlError> {
self.mining_info_snapshot()
}
fn network_hash_ps(&self, lookup: i64, height: i64) -> Result<f64, MiningControlError> {
if lookup < -1 || lookup == 0 {
return Err(MiningControlError::InvalidRequest(CompactString::from(
"Invalid nblocks. Must be a positive number or -1.",
)));
}
let tree = self.block_tree.read();
let tip = self.applied_tip.load_full();
hash_ps_at(&tree, tip.as_deref(), lookup, height, self.network)
}
fn submit_block(&self, mut block: Block) -> Result<BlockValidationResult, MiningControlError> {
self.fill_uncommitted_witness(&mut block);
self.submit(&block)
}
fn submit_header(&self, header: Header) -> Result<(), MiningControlError> {
self.accept_submitted_header(header)
}
fn publish_generation(&self) {
Self::publish_generation(self);
}
fn generate(
&self,
request: GenerateRequest,
) -> Result<Vec<GeneratedBlock>, MiningControlError> {
self.generate_blocks(&request)
}
}
impl MempoolSequenceWake for MiningCoordinator {
fn publish_generation_from(&self, sequence: u64) {
Self::publish_generation_from(self, sequence);
}
}
fn parse_long_poll_id(id: &str) -> Option<GenerationKey> {
if id.len() < 65 {
return None;
}
let (hash_hex, sequence) = id.split_at(64);
let tip_hash = Hash256::from_str_be(hash_hex).ok()?;
let mempool_sequence = sequence.parse().ok()?;
Some(GenerationKey {
tip_hash,
mempool_sequence,
})
}
fn map_apply_error(error: ApplyError) -> BlockValidationResult {
match error {
ApplyError::Shutdown | ApplyError::JournalBackpressure(_) => {
BlockValidationResult::Inconclusive
}
other => BlockValidationResult::Rejected(bip22_reject_reason(&other)),
}
}
/// Core `GetRejectReason` strings used by `BIP22ValidationResult`.
fn bip22_reject_reason(error: &ApplyError) -> CompactString {
match error {
ApplyError::ProofOfWork { .. } => CompactString::from("high-hash"),
ApplyError::PrevHashMismatch { .. } => CompactString::from("inconclusive-not-best-prevblk"),