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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
//! Abstraction of a factory for creating Sv2 Extended or Standard Jobs.
//!
//! This module provides the [`JobFactory`] struct, which enables the creation
//! of uniquely identified Extended and Standard mining jobs as required by
//! Stratum V2 (SV2) mining servers. It manages job ID assignment, construction
//! of coinbase transactions, and correct association of template and custom job
//! parameters.
//!
//! ## Responsibilities
//!
//! - **Job ID Generation**: Ensures all jobs have unique IDs per factory instance.
//! - **Job Construction**: Builds Extended and Standard jobs from SV2 templates and custom job
//! messages, assembling all required coinbase transaction data and metadata.
//! - **Coinbase Output Validation**: Verifies that coinbase outputs match SV2 template constraints
//! and protocol rules.
//! - **`scriptSig` Budget Enforcement**: Verifies that the assembled coinbase `scriptSig` fits
//! within [`MAX_SCRIPT_SIG_SIZE`]. This is the authoritative check, since the template's
//! `coinbase_prefix` is only known at job creation time.
//! - **Version Rolling**: Tracks version rolling allowance for created jobs.
//!
//! ## Usage
//!
//! Designed for mining server implementations. Use `JobFactory` to generate jobs in response to
//! incoming SV2 messages (`NewTemplate`, `SetCustomMiningJob`), ensuring protocol correctness and
//! uniqueness of job IDs.
use crate::{
bip141::try_strip_bip141,
chain_tip::ChainTip,
merkle_root::merkle_root_from_path,
outputs::deserialize_template_outputs,
server::jobs::{error::*, extended::ExtendedJob, standard::StandardJob},
};
use binary_sv2::{B0255Owned, Sv2OptionOwned};
use bitcoin::{
absolute::LockTime,
blockdata::witness::Witness,
consensus::{serialize, Decodable},
transaction::{OutPoint, Transaction, TxIn, TxOut, Version},
Amount, Sequence,
};
use mining_sv2::{NewExtendedMiningJobOwned, NewMiningJobOwned, SetCustomMiningJobOwned};
use std::convert::TryInto;
use template_distribution_sv2::NewTemplateOwned;
/// Maximum size, in bytes, of a coinbase transaction `scriptSig`, as mandated by Bitcoin
/// consensus rules.
pub const MAX_SCRIPT_SIG_SIZE: usize = 100;
/// Maximum number of bytes that [`NewTemplateOwned::coinbase_prefix`] is allowed to contribute to
/// the coinbase `scriptSig`, as mandated by the Sv2 Template Distribution Protocol spec.
///
/// The spec phrase "up to 8 bytes (not including the length byte)" refers to the `B0255` wire
/// length prefix. The BIP34 script push opcode is already part of these 8 bytes.
pub const MAX_COINBASE_PREFIX_SIZE: usize = 8;
#[derive(Debug, PartialEq, Eq, Clone)]
struct JobIdFactory {
state: u32,
}
impl JobIdFactory {
/// Creates a new [`Id`] instance initialized to `0`.
fn new() -> Self {
Self { state: 0 }
}
/// Increments then returns the internal state on a new ID.
///
/// Explicitly wraps to `0` after `u32::MAX`, restarting the sequence. This makes the
/// overflow behavior identical across build profiles (unchecked `+= 1` would panic with
/// overflow checks enabled and wrap silently without them). Reuse of an ID is safe in
/// practice: future jobs are consumed on activation and past/stale jobs are flushed on
/// every chain-tip transition, so a wrapped ID can only land on a still-tracked job (the
/// stale set retained from the previous tip) if all 2³² allocations happen within a single
/// tip epoch — orders of magnitude beyond any realistic job rate. Even then, the job store
/// drops the stale namesake in favor of the new job (see `JobStore`), so the collision only
/// changes the error code the stale job's late shares are rejected with.
fn next(&mut self) -> u32 {
self.state = self.state.wrapping_add(1);
self.state
}
}
/// A Factory for creating Extended or Standard Jobs.
///
/// Ensures unique job ids within any window of 2³² allocations: IDs are sequential and
/// explicitly wrap to `0` after `u32::MAX` (see `JobIdFactory::next` for why reuse is safe).
///
/// Enables creation of new Extended Jobs from NewTemplate and SetCustomMiningJob messages.
///
/// Enables creation of new Standard Jobs from NewTemplate messages.
#[derive(Debug, Clone)]
pub struct JobFactory {
job_id_factory: JobIdFactory,
version_rolling_allowed: bool,
pool_tag_string: Option<String>,
miner_tag_string: Option<String>,
}
impl JobFactory {
/// Creates a new [`JobFactory`] instance.
///
/// The `pool_tag_string` and `miner_tag_string` are optional and will be added to the coinbase
/// scriptSig.
///
/// Version rolling is always allowed for standard jobs, so the `version_rolling_allowed`
/// parameter is only relevant for creating extended jobs.
pub fn new(
version_rolling_allowed: bool,
pool_tag_string: Option<String>,
miner_tag_string: Option<String>,
) -> Self {
Self {
job_id_factory: JobIdFactory::new(),
version_rolling_allowed,
pool_tag_string,
miner_tag_string,
}
}
/// Returns a byte vector with the OP_PUSHBYTES opcode and `Sv2/<pool>/<miner>/` tag.
///
/// The character `/` is used as a delimiter.
///
/// If pool and/or miner tags are not provided, delimiters are still kept
/// (e.g. `Sv2///` when both are missing).
pub fn op_pushbytes_pool_miner_tag(&self) -> Result<Vec<u8>, JobFactoryError> {
let mut pool_miner_tag = vec![];
pool_miner_tag.extend_from_slice(b"Sv2/");
if let Some(pool_tag_string) = &self.pool_tag_string {
pool_miner_tag.extend_from_slice(pool_tag_string.as_bytes());
}
pool_miner_tag.extend_from_slice(b"/");
if let Some(miner_tag_string) = &self.miner_tag_string {
pool_miner_tag.extend_from_slice(miner_tag_string.as_bytes());
}
pool_miner_tag.extend_from_slice(b"/");
// Create the proper OP_PUSHBYTES opcode based on data length
let op_pushbytes = match pool_miner_tag.len() {
// OP_PUSHBYTES_N is a valid single-byte push opcode only for N in 1..=75.
// The scriptSig budget is enforced separately, see `MAX_SCRIPT_SIG_SIZE`.
len @ 1..=75 => len as u8,
_ => return Err(JobFactoryError::CoinbaseTxPrefixError),
};
let mut op_pushbytes_pool_miner_tag = vec![];
op_pushbytes_pool_miner_tag.push(op_pushbytes);
op_pushbytes_pool_miner_tag.extend_from_slice(&pool_miner_tag);
Ok(op_pushbytes_pool_miner_tag)
}
/// Returns the number of bytes that the `Sv2/<pool>/<miner>/` tag assembled by
/// [`JobFactory::op_pushbytes_pool_miner_tag`] contributes to the coinbase `scriptSig`,
/// including the `OP_PUSHBYTES` opcode.
pub fn pool_miner_tag_size(&self) -> usize {
1 // OP_PUSHBYTES opcode
+ 3 // "Sv2"
+ 3 // three `/` delimiters
+ self.pool_tag_string.as_ref().map_or(0, |s| s.len())
+ self.miner_tag_string.as_ref().map_or(0, |s| s.len())
}
/// Returns the number of bytes of the coinbase `scriptSig` assembled by this factory, for a
/// [`NewTemplateOwned::coinbase_prefix`] of `coinbase_prefix_size` bytes and a full extranonce
/// of `full_extranonce_size` bytes.
///
/// The assembled layout is:
/// `coinbase_prefix || OP_PUSHBYTES_N || Sv2/pool_tag/miner_tag/ || OP_PUSHBYTES_M ||
/// extranonce`
///
/// Callers that do not have a template at hand (such as channel constructors) should pass
/// [`MAX_COINBASE_PREFIX_SIZE`] to get the worst-case size allowed by the spec.
pub fn script_sig_size(
&self,
coinbase_prefix_size: usize,
full_extranonce_size: usize,
) -> usize {
coinbase_prefix_size
+ self.pool_miner_tag_size()
+ 1 // OP_PUSHBYTES opcode for the extranonce
+ full_extranonce_size
}
/// Returns whether the coinbase `scriptSig` assembled by this factory fits within
/// [`MAX_SCRIPT_SIG_SIZE`], for a full extranonce of `full_extranonce_size` bytes and the
/// worst-case [`NewTemplateOwned::coinbase_prefix`] allowed by the spec
/// ([`MAX_COINBASE_PREFIX_SIZE`]).
///
/// Meant for callers that do not have a template at hand, such as channel constructors and
/// extranonce setters. Since it assumes the largest in-spec prefix, a `true` here guarantees
/// that no in-spec template can overflow the budget; the exact size is still re-checked
/// against each actual template in `JobFactory::coinbase`.
pub fn fits_script_sig_budget(&self, full_extranonce_size: usize) -> bool {
self.script_sig_size(MAX_COINBASE_PREFIX_SIZE, full_extranonce_size) <= MAX_SCRIPT_SIG_SIZE
}
/// Creates a new job from a template.
///
/// This job (and related shares) is fully committed to:
/// - The template
/// - The additional coinbase outputs (added to the outputs coming from the template)
/// - The extranonce prefix of the channel at the time of job creation
///
/// The optional `ChainTip` defines whether the job will be future or not.
///
/// Version rolling is always allowed for standard jobs, so the `version_rolling_allowed`
/// parameter is ignored.
///
/// It's up to the caller to ensure that the sum of `additional_coinbase_outputs` is equal to
/// available template revenue. Returns an error otherwise.
pub fn new_standard_job(
&mut self,
channel_id: u32,
chain_tip: Option<ChainTip>,
extranonce_prefix: Vec<u8>,
template: NewTemplateOwned,
additional_coinbase_outputs: Vec<TxOut>,
) -> Result<StandardJob, JobFactoryError> {
let coinbase_outputs_sum = additional_coinbase_outputs
.iter()
.map(|o| o.value.to_sat())
.sum::<u64>();
if coinbase_outputs_sum != template.coinbase_tx_value_remaining {
return Err(JobFactoryError::InvalidCoinbaseOutputsSum);
}
let job_id = self.job_id_factory.next();
let version = template.version;
let coinbase_tx_prefix = self.coinbase_tx_prefix(
template.clone(),
additional_coinbase_outputs.clone(),
extranonce_prefix.len(),
)?;
let coinbase_tx_suffix = self.coinbase_tx_suffix(
template.clone(),
additional_coinbase_outputs.clone(),
extranonce_prefix.len(),
)?;
let merkle_path = template.merkle_path.clone();
let merkle_root = merkle_root_from_path(
&coinbase_tx_prefix,
&coinbase_tx_suffix,
&extranonce_prefix,
merkle_path.as_slice(),
)
.expect("merkle root must be valid")
.into();
let job_message = match template.future_template {
true => NewMiningJobOwned {
channel_id,
job_id,
min_ntime: Sv2OptionOwned::new(None),
version,
merkle_root,
},
false => {
let min_ntime = match chain_tip {
Some(chain_tip) => Some(chain_tip.min_ntime()),
None => return Err(JobFactoryError::ChainTipRequired),
};
NewMiningJobOwned {
channel_id,
job_id,
min_ntime: Sv2OptionOwned::new(min_ntime),
version,
merkle_root,
}
}
};
let job = StandardJob::from_template(
template,
extranonce_prefix,
additional_coinbase_outputs,
job_message,
)
.map_err(|_| JobFactoryError::DeserializeCoinbaseOutputsError)?;
Ok(job)
}
/// Creates a new job from a template.
///
/// This job (and related shares) is fully committed to:
/// - The template
/// - The additional coinbase outputs (added to the outputs coming from the template)
/// - The extranonce prefix of the channel at the time of job creation
///
/// The optional `ChainTip` defines whether the job will be future or not.
///
/// It's up to the caller to ensure that the sum of `additional_coinbase_outputs` is equal to
/// available template revenue. Returns an error otherwise.
pub fn new_extended_job(
&mut self,
channel_id: u32,
chain_tip: Option<ChainTip>,
extranonce_prefix: Vec<u8>,
template: NewTemplateOwned,
additional_coinbase_outputs: Vec<TxOut>,
full_extranonce_size: usize,
) -> Result<ExtendedJob, JobFactoryError> {
let coinbase_outputs_sum = additional_coinbase_outputs
.iter()
.map(|o| o.value.to_sat())
.sum::<u64>();
if coinbase_outputs_sum != template.coinbase_tx_value_remaining {
return Err(JobFactoryError::InvalidCoinbaseOutputsSum);
}
let job_id = self.job_id_factory.next();
let version = template.version;
let coinbase_tx_prefix = self.coinbase_tx_prefix(
template.clone(),
additional_coinbase_outputs.clone(),
full_extranonce_size,
)?;
let coinbase_tx_suffix = self.coinbase_tx_suffix(
template.clone(),
additional_coinbase_outputs.clone(),
full_extranonce_size,
)?;
// strip bip141 bytes from coinbase_tx_prefix and coinbase_tx_suffix
let (coinbase_tx_prefix_stripped_bip141, coinbase_tx_suffix_stripped_bip141) =
try_strip_bip141(&coinbase_tx_prefix, &coinbase_tx_suffix)
.map_err(|_| JobFactoryError::FailedToStripBip141)?
.ok_or(JobFactoryError::FailedToStripBip141)?;
let merkle_path = template.merkle_path.clone();
let job_message = match template.future_template {
true => NewExtendedMiningJobOwned {
channel_id,
job_id,
min_ntime: Sv2OptionOwned::new(None),
version,
version_rolling_allowed: self.version_rolling_allowed,
merkle_path,
coinbase_tx_prefix: coinbase_tx_prefix_stripped_bip141
.try_into()
.map_err(|_| JobFactoryError::CoinbaseTxPrefixError)?,
coinbase_tx_suffix: coinbase_tx_suffix_stripped_bip141
.try_into()
.map_err(|_| JobFactoryError::CoinbaseTxSuffixError)?,
},
false => {
let min_ntime = match chain_tip {
Some(chain_tip) => Some(chain_tip.min_ntime()),
None => return Err(JobFactoryError::ChainTipRequired),
};
NewExtendedMiningJobOwned {
channel_id,
job_id,
min_ntime: Sv2OptionOwned::new(min_ntime),
version,
version_rolling_allowed: self.version_rolling_allowed,
merkle_path,
coinbase_tx_prefix: coinbase_tx_prefix_stripped_bip141
.try_into()
.map_err(|_| JobFactoryError::CoinbaseTxPrefixError)?,
coinbase_tx_suffix: coinbase_tx_suffix_stripped_bip141
.try_into()
.map_err(|_| JobFactoryError::CoinbaseTxSuffixError)?,
}
}
};
let job = ExtendedJob::from_template(
template,
extranonce_prefix,
additional_coinbase_outputs,
coinbase_tx_prefix,
coinbase_tx_suffix,
job_message,
)
.map_err(|_| JobFactoryError::DeserializeCoinbaseOutputsError)?;
Ok(job)
}
/// Creates a new coinbase_tx_prefix and coinbase_tx_suffix from a template.
///
/// To be used by a Sv2 Job Declarator Client to create a `DeclareMiningJob` message.
///
/// It's up to the caller to ensure that the sum of `additional_coinbase_outputs`
/// is equal to available template revenue. Returns an error otherwise.
pub fn new_coinbase_tx_prefix_and_suffix(
&self,
template: NewTemplateOwned,
additional_coinbase_outputs: Vec<TxOut>,
full_extranonce_size: usize,
) -> Result<(Vec<u8>, Vec<u8>), JobFactoryError> {
let coinbase_outputs_sum = additional_coinbase_outputs
.iter()
.map(|o| o.value.to_sat())
.sum::<u64>();
if coinbase_outputs_sum != template.coinbase_tx_value_remaining {
return Err(JobFactoryError::InvalidCoinbaseOutputsSum);
}
let coinbase_tx_prefix = self.coinbase_tx_prefix(
template.clone(),
additional_coinbase_outputs.clone(),
full_extranonce_size,
)?;
let coinbase_tx_suffix =
self.coinbase_tx_suffix(template, additional_coinbase_outputs, full_extranonce_size)?;
Ok((coinbase_tx_prefix, coinbase_tx_suffix))
}
/// Creates a new `SetCustomMiningJob` message from a template.
///
/// To be used by a Sv2 Job Declarator Client.
///
/// It's up to the caller to ensure that the sum of the additional coinbase outputs is equal to
/// available template revenue.
///
/// Returns [`JobFactoryError::ScriptSigSizeTooLarge`] if the template's `coinbase_prefix`, the
/// pool/miner tag and the full extranonce do not fit within [`MAX_SCRIPT_SIG_SIZE`].
#[allow(clippy::too_many_arguments)]
pub fn new_custom_job(
&self,
channel_id: u32,
request_id: u32,
token: B0255Owned,
chain_tip: ChainTip,
template: NewTemplateOwned,
additional_coinbase_outputs: Vec<TxOut>,
full_extranonce_size: usize,
) -> Result<SetCustomMiningJobOwned, JobFactoryError> {
// the `coinbase_prefix` assembled below carries this factory's pool/miner tag, so the
// regular scriptSig layout applies. catching it here means the Job Declarator Client fails
// locally instead of having the pool reject the `SetCustomMiningJob` it just sent
if self.script_sig_size(template.coinbase_prefix.len(), full_extranonce_size)
> MAX_SCRIPT_SIG_SIZE
{
return Err(JobFactoryError::ScriptSigSizeTooLarge);
}
let coinbase_outputs_sum = additional_coinbase_outputs
.iter()
.map(|o| o.value.to_sat())
.sum::<u64>();
if coinbase_outputs_sum != template.coinbase_tx_value_remaining {
return Err(JobFactoryError::InvalidCoinbaseOutputsSum);
}
let template_outputs = deserialize_template_outputs(
template.coinbase_tx_outputs.to_owned_bytes(),
template.coinbase_tx_outputs_count,
)
.map_err(|_| JobFactoryError::DeserializeCoinbaseOutputsError)?;
let mut coinbase_tx_outputs = vec![];
coinbase_tx_outputs.extend_from_slice(additional_coinbase_outputs.as_slice());
coinbase_tx_outputs.extend_from_slice(template_outputs.as_slice());
let serialized_outputs = serialize(&coinbase_tx_outputs);
let mut coinbase_prefix = vec![];
coinbase_prefix.extend_from_slice(template.coinbase_prefix.as_bytes());
coinbase_prefix.extend_from_slice(&self.op_pushbytes_pool_miner_tag()?);
coinbase_prefix.push(full_extranonce_size as u8); // OP_PUSHBYTES_X (for the full extranonce)
let set_custom_mining_job = SetCustomMiningJobOwned {
channel_id,
request_id,
token,
version: template.version,
prev_hash: chain_tip.prev_hash(),
min_ntime: chain_tip.min_ntime(),
nbits: chain_tip.nbits(),
coinbase_tx_version: template.coinbase_tx_version,
coinbase_prefix: coinbase_prefix
.try_into()
.map_err(|_| JobFactoryError::FailedToSerializeCoinbasePrefix)?,
coinbase_tx_input_n_sequence: template.coinbase_tx_input_sequence,
coinbase_tx_outputs: serialized_outputs
.try_into()
.map_err(|_| JobFactoryError::FailedToSerializeCoinbaseOutputs)?,
coinbase_tx_locktime: template.coinbase_tx_locktime,
merkle_path: template.merkle_path.clone(),
};
Ok(set_custom_mining_job)
}
/// Creates a new Extended Job from a SetCustomMiningJob message.
///
/// Assumes that the SetCustomMiningJob message has already been validated, with the exception
/// of its `coinbase_prefix` length: since that arrives from a downstream Job Declarator Client,
/// it is bounded here rather than delegated to the caller.
///
/// Returns [`JobFactoryError::ScriptSigSizeTooLarge`] if the message's `coinbase_prefix` and
/// the full extranonce do not fit within [`MAX_SCRIPT_SIG_SIZE`]. Note that a custom job's
/// `coinbase_prefix` already embeds the pool/miner tag, so no tag is added on top of it.
///
/// To be used by Extended Channels on a Sv2 Pool Server.
pub fn new_extended_job_from_custom_job(
&mut self,
set_custom_mining_job: SetCustomMiningJobOwned,
extranonce_prefix: Vec<u8>,
full_extranonce_size: usize,
) -> Result<ExtendedJob, JobFactoryError> {
let serialized_outputs = set_custom_mining_job.coinbase_tx_outputs.to_owned_bytes();
let coinbase_outputs = Vec::<TxOut>::consensus_decode(&mut serialized_outputs.as_slice())
.map_err(|_| JobFactoryError::DeserializeCoinbaseOutputsError)?;
let job_id = self.job_id_factory.next();
let version = set_custom_mining_job.version;
let coinbase_tx_prefix =
self.custom_coinbase_tx_prefix(set_custom_mining_job.clone(), full_extranonce_size)?;
let coinbase_tx_suffix =
self.custom_coinbase_tx_suffix(set_custom_mining_job.clone(), full_extranonce_size)?;
// strip bip141 bytes from coinbase_tx_prefix and coinbase_tx_suffix
let (coinbase_tx_prefix_stripped_bip141, coinbase_tx_suffix_stripped_bip141) =
try_strip_bip141(&coinbase_tx_prefix, &coinbase_tx_suffix)
.map_err(|_| JobFactoryError::FailedToStripBip141)?
.ok_or(JobFactoryError::FailedToStripBip141)?;
let merkle_path = set_custom_mining_job.merkle_path.clone();
let job_message = NewExtendedMiningJobOwned {
channel_id: set_custom_mining_job.channel_id,
job_id,
min_ntime: Sv2OptionOwned::new(Some(set_custom_mining_job.min_ntime)),
version,
version_rolling_allowed: self.version_rolling_allowed,
coinbase_tx_prefix: coinbase_tx_prefix_stripped_bip141
.clone()
.try_into()
.map_err(|_| JobFactoryError::CoinbaseTxPrefixError)?,
coinbase_tx_suffix: coinbase_tx_suffix_stripped_bip141
.clone()
.try_into()
.map_err(|_| JobFactoryError::CoinbaseTxSuffixError)?,
merkle_path,
};
let job = ExtendedJob::from_custom_job(
set_custom_mining_job,
extranonce_prefix,
coinbase_outputs,
coinbase_tx_prefix,
coinbase_tx_suffix,
job_message,
);
Ok(job)
}
}
// impl block with private methods
impl JobFactory {
// build a coinbase transaction from a SetCustomMiningJob
// this is only used to extract coinbase_tx_prefix and coinbase_tx_suffix from the custom
// coinbase
fn custom_coinbase(
&self,
m: SetCustomMiningJobOwned,
full_extranonce_size: usize,
) -> Result<Transaction, JobFactoryError> {
// a custom job arrives from a downstream Job Declarator Client with the pool/miner tag
// already embedded in `coinbase_prefix`, so the assembled scriptSig is just the prefix
// followed by the extranonce, with no tag of ours to account for.
//
// this is untrusted input off the wire and nothing upstream of here bounds it, so the
// check cannot be delegated to the caller the way it is for a locally built job. an
// oversized prefix would otherwise yield a consensus-invalid coinbase, and past 252 bytes
// it would also break the one-byte CompactSize assumption the prefix/suffix split indexes
// rely on, silently mis-slicing the coinbase.
if m.coinbase_prefix.len() + full_extranonce_size > MAX_SCRIPT_SIG_SIZE {
return Err(JobFactoryError::ScriptSigSizeTooLarge);
}
let deserialized_outputs =
Vec::<TxOut>::consensus_decode(&mut m.coinbase_tx_outputs.to_owned_bytes().as_slice())
.map_err(|_| JobFactoryError::DeserializeCoinbaseOutputsError)?;
let mut script_sig = vec![];
script_sig.extend_from_slice(m.coinbase_prefix.as_bytes());
script_sig.extend_from_slice(&vec![0; full_extranonce_size]);
// Create transaction input
let tx_in = TxIn {
previous_output: OutPoint::null(),
script_sig: script_sig.into(),
sequence: Sequence(m.coinbase_tx_input_n_sequence),
witness: Witness::from(vec![vec![0; 32]]), /* note: 32 bytes of zeros is only safe to
* assume now, this could change in future
* soft forks */
};
Ok(Transaction {
version: Version::non_standard(m.coinbase_tx_version as i32),
lock_time: LockTime::from_consensus(m.coinbase_tx_locktime),
input: vec![tx_in],
output: deserialized_outputs,
})
}
fn custom_coinbase_tx_prefix(
&self,
m: SetCustomMiningJobOwned,
full_extranonce_size: usize,
) -> Result<Vec<u8>, JobFactoryError> {
let coinbase = self.custom_coinbase(m.clone(), full_extranonce_size)?;
let serialized_coinbase = serialize(&coinbase);
// the coinbase scriptSig is limited to 100 bytes by Bitcoin consensus rules, which is
// always below the 253 byte threshold where CompactSize switches from a 1-byte to a
// 3-byte encoding, so the script length prefix is unconditionally 1 byte
let index = 4 // tx version
+ 2 // segwit
+ 1 // number of inputs
+ 32 // prev OutPoint
+ 4 // index
+ 1 // bytes in script
+ m.coinbase_prefix.len();
let coinbase_tx_prefix = serialized_coinbase[0..index].to_vec();
Ok(coinbase_tx_prefix)
}
fn custom_coinbase_tx_suffix(
&self,
m: SetCustomMiningJobOwned,
full_extranonce_size: usize,
) -> Result<Vec<u8>, JobFactoryError> {
let coinbase = self.custom_coinbase(m.clone(), full_extranonce_size)?;
let serialized_coinbase = serialize(&coinbase);
// the coinbase scriptSig is limited to 100 bytes by Bitcoin consensus rules, which is
// always below the 253 byte threshold where CompactSize switches from a 1-byte to a
// 3-byte encoding, so the script length prefix is unconditionally 1 byte
let index = 4 // tx version
+ 2 // segwit
+ 1 // number of inputs
+ 32 // prev OutPoint
+ 4 // index
+ 1 // bytes in script
+ m.coinbase_prefix.len()
+ full_extranonce_size;
let coinbase_tx_suffix = serialized_coinbase[index..].to_vec();
Ok(coinbase_tx_suffix)
}
// build a coinbase transaction from some template in the JobFactory
fn coinbase(
&self,
template: NewTemplateOwned,
coinbase_reward_outputs: Vec<TxOut>,
full_extranonce_size: usize,
) -> Result<Transaction, JobFactoryError> {
// the template's coinbase_prefix is only known here, so this is the authoritative
// scriptSig budget check; channel constructors can only check against the spec's
// worst-case MAX_COINBASE_PREFIX_SIZE
if self.script_sig_size(template.coinbase_prefix.len(), full_extranonce_size)
> MAX_SCRIPT_SIG_SIZE
{
return Err(JobFactoryError::ScriptSigSizeTooLarge);
}
// check that the sum of the additional coinbase outputs is equal to the value remaining in
// the active template
let mut coinbase_reward_outputs_sum = Amount::from_sat(0);
for output in coinbase_reward_outputs.iter() {
coinbase_reward_outputs_sum = coinbase_reward_outputs_sum
.checked_add(output.value)
.ok_or(JobFactoryError::CoinbaseOutputsSumOverflow)?;
}
if template.coinbase_tx_value_remaining < coinbase_reward_outputs_sum.to_sat() {
return Err(JobFactoryError::InvalidCoinbaseOutputsSum);
}
let mut outputs = vec![];
for output in coinbase_reward_outputs.iter() {
outputs.push(output.clone());
}
let mut template_outputs = deserialize_template_outputs(
template.coinbase_tx_outputs.to_owned_bytes(),
template.coinbase_tx_outputs_count,
)
.map_err(|_| JobFactoryError::DeserializeCoinbaseOutputsError)?;
outputs.append(&mut template_outputs);
let op_pushbytes_pool_miner_tag = self.op_pushbytes_pool_miner_tag()?;
let mut script_sig = vec![];
script_sig.extend_from_slice(template.coinbase_prefix.as_bytes());
script_sig.extend_from_slice(&op_pushbytes_pool_miner_tag);
script_sig.push(full_extranonce_size as u8); // OP_PUSHBYTES_X (for the full extranonce)
script_sig.extend_from_slice(&vec![0; full_extranonce_size]);
let tx_in = TxIn {
previous_output: OutPoint::null(),
script_sig: script_sig.into(),
sequence: Sequence(template.coinbase_tx_input_sequence),
witness: Witness::from(vec![vec![0; 32]]), /* note: 32 bytes of zeros is only safe to
* assume now, this could change in future
* soft forks */
};
Ok(Transaction {
version: Version::non_standard(template.coinbase_tx_version as i32),
lock_time: LockTime::from_consensus(template.coinbase_tx_locktime),
input: vec![tx_in],
output: outputs,
})
}
fn coinbase_tx_prefix(
&self,
template: NewTemplateOwned,
coinbase_reward_outputs: Vec<TxOut>,
full_extranonce_size: usize,
) -> Result<Vec<u8>, JobFactoryError> {
let coinbase = self.coinbase(
template.clone(),
coinbase_reward_outputs,
full_extranonce_size,
)?;
let serialized_coinbase = serialize(&coinbase);
// the full pool/miner tag length, including delimiters and OP_PUSHBYTES opcode
let pool_miner_tag_len = self.pool_miner_tag_size();
// the coinbase scriptSig is limited to 100 bytes by Bitcoin consensus rules, which is
// always below the 253 byte threshold where CompactSize switches from a 1-byte to a
// 3-byte encoding, so the script length prefix is unconditionally 1 byte
let index = 4 // tx version
+ 2 // segwit bytes
+ 1 // number of inputs
+ 32 // prev OutPoint
+ 4 // index
+ 1 // bytes in script
+ template.coinbase_prefix.len()
+ pool_miner_tag_len
+ 1; // OP_PUSHBYTES_X (for the extranonce)
let coinbase_tx_prefix = serialized_coinbase[0..index].to_vec();
Ok(coinbase_tx_prefix)
}
fn coinbase_tx_suffix(
&self,
template: NewTemplateOwned,
coinbase_reward_outputs: Vec<TxOut>,
full_extranonce_size: usize,
) -> Result<Vec<u8>, JobFactoryError> {
let coinbase = self.coinbase(
template.clone(),
coinbase_reward_outputs,
full_extranonce_size,
)?;
let serialized_coinbase = serialize(&coinbase);
// the full pool/miner tag length, including delimiters and OP_PUSHBYTES opcode
let pool_miner_tag_len = self.pool_miner_tag_size();
// the coinbase scriptSig is limited to 100 bytes by Bitcoin consensus rules, which is
// always below the 253 byte threshold where CompactSize switches from a 1-byte to a
// 3-byte encoding, so the script length prefix is unconditionally 1 byte
let coinbase_tx_suffix = serialized_coinbase[4 // tx version
+ 2 // segwit bytes
+ 1 // number of inputs
+ 32 // prev OutPoint
+ 4 // index
+ 1 // bytes in script
+ template.coinbase_prefix.len()
+ pool_miner_tag_len
+ 1 // OP_PUSHBYTES_X (for the full extranonce)
+ full_extranonce_size..]
.to_vec();
Ok(coinbase_tx_suffix)
}
}
#[cfg(test)]
mod tests {
use super::*;
use bitcoin::ScriptBuf;
use mining_sv2::NewExtendedMiningJobOwned as NewExtendedMiningJob;
use template_distribution_sv2::NewTemplateOwned as NewTemplate;
#[test]
fn test_new_pool_job() {
let mut job_factory = JobFactory::new(true, Some("Stratum V2 SRI Pool".to_string()), None);
// note:
// the messages on this test were collected from a sane message flow
// we use them as test vectors to assert correct behavior of job creation
let template = NewTemplate {
template_id: 1,
future_template: true,
version: 536870912,
coinbase_tx_version: 2,
coinbase_prefix: vec![82, 0].try_into().unwrap(),
coinbase_tx_input_sequence: 4294967295,
coinbase_tx_value_remaining: 5000000000,
coinbase_tx_outputs_count: 1,
coinbase_tx_outputs: vec![
0, 0, 0, 0, 0, 0, 0, 0, 38, 106, 36, 170, 33, 169, 237, 226, 246, 28, 63, 113, 209,
222, 253, 63, 169, 153, 223, 163, 105, 83, 117, 92, 105, 6, 137, 121, 153, 98, 180,
139, 235, 216, 54, 151, 78, 140, 249,
]
.try_into()
.unwrap(),
coinbase_tx_locktime: 0,
merkle_path: vec![].try_into().unwrap(),
};
// match the original script format used to generate the coinbase_reward_outputs for the
// expected job
let pubkey_hash = [
235, 225, 183, 220, 194, 147, 204, 170, 14, 231, 67, 168, 111, 137, 223, 130, 88, 194,
8, 252,
];
let mut script_bytes = vec![0]; // SegWit version 0
script_bytes.push(20); // Push 20 bytes (length of pubkey hash)
script_bytes.extend_from_slice(&pubkey_hash);
let script = ScriptBuf::from(script_bytes);
let coinbase_reward_outputs = vec![TxOut {
value: Amount::from_sat(5000000000),
script_pubkey: script,
}];
// match the original extranonce_prefix used to generate the expected job
let extranonce_prefix = [
83, 116, 114, 97, 116, 117, 109, 32, 86, 50, 32, 83, 82, 73, 32, 80, 111, 111, 108, 0,
0, 0, 0, 0, 0, 0, 1,
]
.to_vec();
let job = job_factory
.new_extended_job(
1,
None,
extranonce_prefix,
template,
coinbase_reward_outputs,
32,
)
.unwrap();
// we know that the provided template should generate this job
let expected_job = NewExtendedMiningJob {
channel_id: 1,
job_id: 1,
min_ntime: Sv2OptionOwned::new(None),
version: 536870912,
version_rolling_allowed: true,
// contains scriptSig with Sv2/Stratum V2 SRI Pool//
coinbase_tx_prefix: vec![
2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 61, 82, 0, 25, 83, 118, 50, 47, 83,
116, 114, 97, 116, 117, 109, 32, 86, 50, 32, 83, 82, 73, 32, 80, 111, 111, 108, 47,
47, 32,
]
.try_into()
.unwrap(),
coinbase_tx_suffix: vec![
255, 255, 255, 255, 2, 0, 242, 5, 42, 1, 0, 0, 0, 22, 0, 20, 235, 225, 183, 220,
194, 147, 204, 170, 14, 231, 67, 168, 111, 137, 223, 130, 88, 194, 8, 252, 0, 0, 0,
0, 0, 0, 0, 0, 38, 106, 36, 170, 33, 169, 237, 226, 246, 28, 63, 113, 209, 222,
253, 63, 169, 153, 223, 163, 105, 83, 117, 92, 105, 6, 137, 121, 153, 98, 180, 139,
235, 216, 54, 151, 78, 140, 249, 0, 0, 0, 0,
]
.try_into()
.unwrap(),
merkle_path: vec![].try_into().unwrap(),
};
assert_eq!(job.get_job_message(), &expected_job);
}
// builds a template with the provided `coinbase_prefix`, reusing the same vectors as
// `test_new_pool_job` for everything else
fn template_with_coinbase_prefix(coinbase_prefix: Vec<u8>) -> NewTemplate {
NewTemplate {
template_id: 1,
future_template: true,
version: 536870912,
coinbase_tx_version: 2,
coinbase_prefix: coinbase_prefix.try_into().unwrap(),
coinbase_tx_input_sequence: 4294967295,
coinbase_tx_value_remaining: 5000000000,
coinbase_tx_outputs_count: 1,
coinbase_tx_outputs: vec![
0, 0, 0, 0, 0, 0, 0, 0, 38, 106, 36, 170, 33, 169, 237, 226, 246, 28, 63, 113, 209,
222, 253, 63, 169, 153, 223, 163, 105, 83, 117, 92, 105, 6, 137, 121, 153, 98, 180,
139, 235, 216, 54, 151, 78, 140, 249,
]
.try_into()
.unwrap(),
coinbase_tx_locktime: 0,
merkle_path: vec![].try_into().unwrap(),
}
}
fn coinbase_reward_outputs() -> Vec<TxOut> {
let pubkey_hash = [
235, 225, 183, 220, 194, 147, 204, 170, 14, 231, 67, 168, 111, 137, 223, 130, 88, 194,
8, 252,
];
let mut script_bytes = vec![0]; // SegWit version 0
script_bytes.push(20); // Push 20 bytes (length of pubkey hash)
script_bytes.extend_from_slice(&pubkey_hash);
vec![TxOut {
value: Amount::from_sat(5000000000),
script_pubkey: ScriptBuf::from(script_bytes),
}]
}
#[test]
fn test_coinbase_rejects_oversized_script_sig() {
// a 52 char pool tag places the worst-case scriptSig exactly on the budget:
// 8 (MAX_COINBASE_PREFIX_SIZE) + 1 + 3 ("Sv2") + 3 + 52 (tag) + 1 + 32 (extranonce) = 100
let pool_tag_string = "x".repeat(52);
let mut job_factory = JobFactory::new(true, Some(pool_tag_string), None);
assert_eq!(
job_factory.script_sig_size(MAX_COINBASE_PREFIX_SIZE, 32),
MAX_SCRIPT_SIG_SIZE
);
// a spec-compliant 8 byte coinbase_prefix fits exactly
let job = job_factory.new_extended_job(
1,
None,
vec![0; 32],
template_with_coinbase_prefix(vec![0xab; MAX_COINBASE_PREFIX_SIZE]),
coinbase_reward_outputs(),
32,
);
assert!(job.is_ok());
// an out-of-spec Template Provider sending 9 bytes overflows the budget, and must be
// rejected instead of yielding a consensus-invalid coinbase
let job = job_factory.new_extended_job(
1,
None,
vec![0; 32],
template_with_coinbase_prefix(vec![0xab; MAX_COINBASE_PREFIX_SIZE + 1]),
coinbase_reward_outputs(),
32,
);
assert!(matches!(
job.unwrap_err(),
JobFactoryError::ScriptSigSizeTooLarge
));
}
#[test]
fn test_new_extended_job_from_custom_job() {
let jdc_job_factory = JobFactory::new(
true,
Some("Stratum V2 SRI Pool".to_string()),
Some("Stratum V2 SRI Miner".to_string()),
);
let extranonce_prefix = [
83, 116, 114, 97, 116, 117, 109, 32, 86, 50, 32, 83, 82, 73, 32, 80, 111, 111, 108, 0,
0, 0, 0, 0, 0, 0, 1,
]
.to_vec();
let template = NewTemplate {
template_id: 1,
future_template: false,
version: 536870912,
coinbase_tx_version: 2,
coinbase_prefix: vec![82, 0].try_into().unwrap(),
coinbase_tx_input_sequence: 4294967295,
coinbase_tx_value_remaining: 5000000000,
coinbase_tx_outputs_count: 1,
coinbase_tx_outputs: vec![
0, 0, 0, 0, 0, 0, 0, 0, 38, 106, 36, 170, 33, 169, 237, 226, 246, 28, 63, 113, 209,
222, 253, 63, 169, 153, 223, 163, 105, 83, 117, 92, 105, 6, 137, 121, 153, 98, 180,
139, 235, 216, 54, 151, 78, 140, 249,
]
.try_into()
.unwrap(),
coinbase_tx_locktime: 0,
merkle_path: vec![].try_into().unwrap(),
};
// match the original script format used to generate the coinbase_reward_outputs for the
// expected job
let pubkey_hash = [
235, 225, 183, 220, 194, 147, 204, 170, 14, 231, 67, 168, 111, 137, 223, 130, 88, 194,
8, 252,
];
let mut script_bytes = vec![0]; // SegWit version 0
script_bytes.push(20); // Push 20 bytes (length of pubkey hash)
script_bytes.extend_from_slice(&pubkey_hash);
let script = ScriptBuf::from(script_bytes);
let coinbase_reward_outputs = vec![TxOut {
value: Amount::from_sat(5000000000),
script_pubkey: script,
}];
let chain_tip = ChainTip::new(
[
200, 53, 253, 129, 214, 31, 43, 84, 179, 58, 58, 76, 128, 213, 24, 53, 38, 144,
205, 88, 172, 20, 251, 22, 217, 141, 21, 221, 21, 0, 0, 0,
]
.into(),
503543726,
1746839905,
);
let set_custom_mining_job = jdc_job_factory
.new_custom_job(
1,
1,
vec![0].try_into().unwrap(),
chain_tip,
template,
coinbase_reward_outputs,
32,
)
.unwrap();
let mut pool_job_factory =
JobFactory::new(true, Some("Stratum V2 SRI Pool".to_string()), None);
let custom_job = pool_job_factory
.new_extended_job_from_custom_job(set_custom_mining_job, extranonce_prefix, 32)
.unwrap();
let expected_job = NewExtendedMiningJob {
channel_id: 1,
job_id: 1,
min_ntime: Sv2OptionOwned::new(Some(1746839905)),
version: 536870912,
version_rolling_allowed: true,
// contains scriptSig with Sv2/Stratum V2 SRI Pool/Stratum V2 SRI Miner/
coinbase_tx_prefix: vec![
2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 81, 82, 0, 45, 83, 118, 50, 47, 83,
116, 114, 97, 116, 117, 109, 32, 86, 50, 32, 83, 82, 73, 32, 80, 111, 111, 108, 47,
83, 116, 114, 97, 116, 117, 109, 32, 86, 50, 32, 83, 82, 73, 32, 77, 105, 110, 101,
114, 47, 32,
]
.try_into()
.unwrap(),
coinbase_tx_suffix: vec![
255, 255, 255, 255, 2, 0, 242, 5, 42, 1, 0, 0, 0, 22, 0, 20, 235, 225, 183, 220,
194, 147, 204, 170, 14, 231, 67, 168, 111, 137, 223, 130, 88, 194, 8, 252, 0, 0, 0,
0, 0, 0, 0, 0, 38, 106, 36, 170, 33, 169, 237, 226, 246, 28, 63, 113, 209, 222,
253, 63, 169, 153, 223, 163, 105, 83, 117, 92, 105, 6, 137, 121, 153, 98, 180, 139,
235, 216, 54, 151, 78, 140, 249, 0, 0, 0, 0,
]
.try_into()
.unwrap(),
merkle_path: vec![].try_into().unwrap(),
};
assert_eq!(custom_job.get_job_message(), &expected_job);
}
// builds a `SetCustomMiningJob` with the given `coinbase_prefix`, bypassing `new_custom_job`
// so the receiving side can be exercised with prefixes a well-behaved JDC would never send
fn custom_job_with_coinbase_prefix(coinbase_prefix: Vec<u8>) -> SetCustomMiningJobOwned {
SetCustomMiningJobOwned {
channel_id: 1,
request_id: 1,
token: vec![0].try_into().unwrap(),
version: 536870912,
prev_hash: [0u8; 32].into(),
min_ntime: 1746839905,
nbits: 503543726,
coinbase_tx_version: 2,
coinbase_prefix: coinbase_prefix.try_into().unwrap(),
coinbase_tx_input_n_sequence: 4294967295,
coinbase_tx_outputs: serialize(&coinbase_reward_outputs()).try_into().unwrap(),
coinbase_tx_locktime: 0,
merkle_path: vec![].try_into().unwrap(),
}
}
#[test]
fn test_new_custom_job_rejects_oversized_script_sig() {
// same boundary as `test_coinbase_rejects_oversized_script_sig`: a 52 char pool tag places
// the worst-case scriptSig exactly on the budget
let job_factory = JobFactory::new(true, Some("x".repeat(52)), None);
let chain_tip = ChainTip::new([0u8; 32].into(), 503543726, 1746839905);
let new_custom_job = |coinbase_prefix_len: usize| {
job_factory.new_custom_job(
1,
1,
vec![0].try_into().unwrap(),
chain_tip.clone(),
template_with_coinbase_prefix(vec![0xab; coinbase_prefix_len]),
coinbase_reward_outputs(),
32,
)
};
// a spec-compliant 8 byte coinbase_prefix fits exactly
assert!(new_custom_job(MAX_COINBASE_PREFIX_SIZE).is_ok());
// one byte over must be rejected here, so the Job Declarator Client fails locally rather
// than having the pool reject the `SetCustomMiningJob` it just sent
assert!(matches!(
new_custom_job(MAX_COINBASE_PREFIX_SIZE + 1).unwrap_err(),
JobFactoryError::ScriptSigSizeTooLarge
));
}
#[test]
fn test_job_id_wraps_to_zero_after_u32_max() {
let mut job_factory = JobFactory::new(true, None, None);
let new_job = |job_factory: &mut JobFactory| {
job_factory
.new_extended_job(
1,
None,
vec![0; 32],
template_with_coinbase_prefix(vec![82, 0]),
coinbase_reward_outputs(),
32,
)
.unwrap()
};
// place the private counter one below the last u32 ID
job_factory.job_id_factory.state = u32::MAX - 1;
assert_eq!(new_job(&mut job_factory).get_job_message().job_id, u32::MAX);
// the next allocation must wrap to 0 and restart the sequence, identically across
// build profiles (this test panics on overflow-checked builds without the explicit
// wrapping arithmetic)
assert_eq!(new_job(&mut job_factory).get_job_message().job_id, 0);
assert_eq!(new_job(&mut job_factory).get_job_message().job_id, 1);
}
#[test]
fn test_custom_job_rejects_oversized_script_sig() {
// a custom job's coinbase_prefix already embeds the pool/miner tag, so the assembled
// scriptSig is just the prefix plus the full extranonce: 68 + 32 = 100
let mut job_factory = JobFactory::new(true, None, None);
let job = job_factory.new_extended_job_from_custom_job(
custom_job_with_coinbase_prefix(vec![0xab; MAX_SCRIPT_SIG_SIZE - 32]),
vec![0; 32],
32,
);
assert!(job.is_ok());
// one byte over the budget yields a consensus-invalid coinbase
let job = job_factory.new_extended_job_from_custom_job(
custom_job_with_coinbase_prefix(vec![0xab; MAX_SCRIPT_SIG_SIZE - 32 + 1]),
vec![0; 32],
32,
);
assert!(matches!(
job.unwrap_err(),
JobFactoryError::ScriptSigSizeTooLarge
));
// a hostile downstream can otherwise push the scriptSig past the 252 byte CompactSize
// threshold, which would also mis-slice the prefix/suffix split
let job = job_factory.new_extended_job_from_custom_job(
custom_job_with_coinbase_prefix(vec![0xab; 250]),
vec![0; 32],
32,
);
assert!(matches!(
job.unwrap_err(),
JobFactoryError::ScriptSigSizeTooLarge
));
}
}