-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathchannel_factory.rs
1985 lines (1903 loc) · 79.1 KB
/
channel_factory.rs
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
use super::extended_to_standard_job;
use crate::{
common_properties::StandardChannel,
job_creator::{self, JobsCreators},
parsers::Mining,
utils::{GroupId, Id, Mutex},
Error,
};
use mining_sv2::{
ExtendedExtranonce, NewExtendedMiningJob, NewMiningJob, OpenExtendedMiningChannelSuccess,
OpenMiningChannelError, OpenStandardMiningChannelSuccess, SetCustomMiningJob,
SetCustomMiningJobSuccess, SetNewPrevHash, SubmitSharesError, SubmitSharesExtended,
SubmitSharesStandard, Target,
};
use nohash_hasher::BuildNoHashHasher;
use std::{collections::HashMap, convert::TryInto, sync::Arc};
use template_distribution_sv2::{NewTemplate, SetNewPrevHash as SetNewPrevHashFromTp};
use tracing::{debug, error, info, trace, warn};
use stratum_common::{
bitcoin,
bitcoin::{
hash_types,
hashes::{hex::ToHex, sha256d::Hash, Hash as Hash_},
TxOut,
},
};
/// A stripped type of `SetCustomMiningJob` without the (`channel_id, `request_id` and `token`) fields
#[derive(Debug)]
pub struct PartialSetCustomMiningJob {
pub version: u32,
pub prev_hash: binary_sv2::U256<'static>,
pub min_ntime: u32,
pub nbits: u32,
pub coinbase_tx_version: u32,
pub coinbase_prefix: binary_sv2::B0255<'static>,
pub coinbase_tx_input_n_sequence: u32,
pub coinbase_tx_value_remaining: u64,
pub coinbase_tx_outputs: binary_sv2::B064K<'static>,
pub coinbase_tx_locktime: u32,
pub merkle_path: binary_sv2::Seq0255<'static, binary_sv2::U256<'static>>,
pub extranonce_size: u16,
pub future_job: bool,
}
/// Represent the action that needs to be done when a new share is received.
#[derive(Debug, Clone)]
pub enum OnNewShare {
/// Used when the received is malformed, is for an inexistent channel or do not meet downstream
/// target.
SendErrorDownstream(SubmitSharesError<'static>),
/// Used when an exteded channel in a proxy receive a share, and the share meet upstream
/// target, in this case a new share must be sent upstream. Also an optional template id is
/// returned, when a job declarator want to send a valid share upstream could use the
/// template for get the up job id.
SendSubmitShareUpstream((Share, Option<u64>)),
/// Used when a group channel in a proxy receive a share that is not malformed and is for a
/// valid channel in that case we relay the same exact share upstream with a new request id.
RelaySubmitShareUpstream,
/// Indicate that the share meet bitcoin target, when there is an upstream the we should send
/// the share upstream, whenever possible we should also notify the TP about it.
/// When a pool negotiate a job with downstream we do not have the template_id so we set it to
/// None
/// (share, template id, coinbase,complete extranonce)
ShareMeetBitcoinTarget((Share, Option<u64>, Vec<u8>, Vec<u8>)),
/// Indicate that the share meet downstream target, in the case we could send a success
/// response dowmstream.
ShareMeetDownstreamTarget,
}
impl OnNewShare {
/// convert standard share into extended share
pub fn into_extended(&mut self, extranonce: Vec<u8>, up_id: u32) {
match self {
OnNewShare::SendErrorDownstream(_) => (),
OnNewShare::SendSubmitShareUpstream((share, template_id)) => match share {
Share::Extended(_) => (),
Share::Standard((share, _)) => {
let share = SubmitSharesExtended {
channel_id: up_id,
sequence_number: share.sequence_number,
job_id: share.job_id,
nonce: share.nonce,
ntime: share.ntime,
version: share.version,
extranonce: extranonce.try_into().unwrap(),
};
*self = Self::SendSubmitShareUpstream((Share::Extended(share), *template_id));
}
},
OnNewShare::RelaySubmitShareUpstream => (),
OnNewShare::ShareMeetBitcoinTarget((share, t_id, coinbase, ext)) => match share {
Share::Extended(_) => (),
Share::Standard((share, _)) => {
let share = SubmitSharesExtended {
channel_id: up_id,
sequence_number: share.sequence_number,
job_id: share.job_id,
nonce: share.nonce,
ntime: share.ntime,
version: share.version,
extranonce: extranonce.try_into().unwrap(),
};
*self = Self::ShareMeetBitcoinTarget((
Share::Extended(share),
*t_id,
coinbase.clone(),
ext.to_vec(),
));
}
},
OnNewShare::ShareMeetDownstreamTarget => todo!(),
}
}
}
/// A share can be both extended or standard
#[derive(Clone, Debug)]
pub enum Share {
Extended(SubmitSharesExtended<'static>),
// share, group id
Standard((SubmitSharesStandard, u32)),
}
/// helper type used before a `SetNewPrevHash` has a channel_id
#[derive(Clone, Debug)]
pub struct StagedPhash {
job_id: u32,
prev_hash: binary_sv2::U256<'static>,
min_ntime: u32,
nbits: u32,
}
impl StagedPhash {
pub fn into_set_p_hash(
&self,
channel_id: u32,
new_job_id: Option<u32>,
) -> SetNewPrevHash<'static> {
SetNewPrevHash {
channel_id,
job_id: new_job_id.unwrap_or(self.job_id),
prev_hash: self.prev_hash.clone(),
min_ntime: self.min_ntime,
nbits: self.nbits,
}
}
}
impl Share {
pub fn get_sequence_number(&self) -> u32 {
match self {
Share::Extended(s) => s.sequence_number,
Share::Standard(s) => s.0.sequence_number,
}
}
pub fn get_channel_id(&self) -> u32 {
match self {
Share::Extended(s) => s.channel_id,
Share::Standard(s) => s.0.channel_id,
}
}
pub fn get_n_time(&self) -> u32 {
match self {
Share::Extended(s) => s.ntime,
Share::Standard(s) => s.0.ntime,
}
}
pub fn get_nonce(&self) -> u32 {
match self {
Share::Extended(s) => s.nonce,
Share::Standard(s) => s.0.nonce,
}
}
pub fn get_job_id(&self) -> u32 {
match self {
Share::Extended(s) => s.job_id,
Share::Standard(s) => s.0.job_id,
}
}
pub fn get_version(&self) -> u32 {
match self {
Share::Extended(s) => s.version,
Share::Standard(s) => s.0.version,
}
}
}
#[derive(Debug)]
/// Basic logic shared between all the channel factory.
struct ChannelFactory {
ids: Arc<Mutex<GroupId>>,
standard_channels_for_non_hom_downstreams:
HashMap<u64, StandardChannel, BuildNoHashHasher<u64>>,
standard_channels_for_hom_downstreams: HashMap<u32, StandardChannel, BuildNoHashHasher<u32>>,
extended_channels:
HashMap<u32, OpenExtendedMiningChannelSuccess<'static>, BuildNoHashHasher<u32>>,
extranonces: ExtendedExtranonce,
share_per_min: f32,
// (NewExtendedMiningJob,group ids that already received the future job)
future_jobs: Vec<(NewExtendedMiningJob<'static>, Vec<u32>)>,
// (SetNewPrevHash,group ids that already received the set prev_hash)
last_prev_hash: Option<(StagedPhash, Vec<u32>)>,
last_prev_hash_: Option<hash_types::BlockHash>,
// (NewExtendedMiningJob,group ids that already received the job)
last_valid_job: Option<(NewExtendedMiningJob<'static>, Vec<u32>)>,
kind: ExtendedChannelKind,
job_ids: Id,
channel_to_group_id: HashMap<u32, u32, BuildNoHashHasher<u32>>,
future_templates: HashMap<u32, NewTemplate<'static>, BuildNoHashHasher<u32>>,
}
impl ChannelFactory {
pub fn add_standard_channel(
&mut self,
request_id: u32,
downstream_hash_rate: f32,
is_header_only: bool,
id: u32,
) -> Result<Vec<Mining>, Error> {
match is_header_only {
true => {
self.new_standard_channel_for_hom_downstream(request_id, downstream_hash_rate, id)
}
false => self.new_standard_channel_for_non_hom_downstream(
request_id,
downstream_hash_rate,
id,
),
}
}
/// Called when a `OpenExtendedMiningChannel` message is received.
/// Here we save the downstream's target (based on hashrate) and the
/// channel's extranonce details before returning the relevant SV2 mining messages
/// to be sent downstream. For the mining messages, we will first return an `OpenExtendedMiningChannelSuccess`
/// if the channel is successfully opened. Then we add the `NewExtendedMiningJob` and `SetNewPrevHash` messages if
/// the relevant data is available. If the channel opening fails, we return `OpenExtenedMiningChannelError`.
pub fn new_extended_channel(
&mut self,
request_id: u32,
hash_rate: f32,
min_extranonce_size: u16,
) -> Result<Vec<Mining<'static>>, Error> {
let extended_channels_group = 0;
let max_extranonce_size = self.extranonces.get_range2_len() as u16;
if min_extranonce_size <= max_extranonce_size {
// SECURITY is very unlikely to finish the ids btw this unwrap could be used by an attaccher that
// want to dirsrupt the service maybe we should have a method to reuse ids that are no
// longer connected?
let channel_id = self
.ids
.safe_lock(|ids| ids.new_channel_id(extended_channels_group))
.unwrap();
self.channel_to_group_id.insert(channel_id, 0);
let target = match crate::utils::hash_rate_to_target(
hash_rate.into(),
self.share_per_min.into(),
) {
Ok(target) => target,
Err(e) => {
error!(
"Impossible to get target: {:?}. Request id: {:?}",
e, request_id
);
return Err(e);
}
};
let extranonce = self
.extranonces
.next_extended(max_extranonce_size as usize)
.unwrap();
let extranonce_prefix = extranonce
.into_prefix(self.extranonces.get_prefix_len())
.unwrap();
let success = OpenExtendedMiningChannelSuccess {
request_id,
channel_id,
target,
extranonce_size: max_extranonce_size,
extranonce_prefix,
};
self.extended_channels.insert(channel_id, success.clone());
let mut result = vec![Mining::OpenExtendedMiningChannelSuccess(success)];
if let Some((job, _)) = &self.last_valid_job {
let mut job = job.clone();
job.set_future();
let j_id = job.job_id;
result.push(Mining::NewExtendedMiningJob(job));
if let Some((new_prev_hash, _)) = &self.last_prev_hash {
let mut new_prev_hash = new_prev_hash.into_set_p_hash(channel_id, None);
new_prev_hash.job_id = j_id;
result.push(Mining::SetNewPrevHash(new_prev_hash.clone()))
};
} else if let Some((new_prev_hash, _)) = &self.last_prev_hash {
let new_prev_hash = new_prev_hash.into_set_p_hash(channel_id, None);
result.push(Mining::SetNewPrevHash(new_prev_hash.clone()))
};
for (job, _) in &self.future_jobs {
result.push(Mining::NewExtendedMiningJob(job.clone()))
}
Ok(result)
} else {
Ok(vec![Mining::OpenMiningChannelError(
OpenMiningChannelError::unsupported_extranonce_size(request_id),
)])
}
}
/// Called when we want to replicate a channel already opened by another actor.
/// is used only in the jd client from the template provider module to mock a pool.
/// Anything else should open channel with the new_extended_channel function
pub fn replicate_upstream_extended_channel_only_jd(
&mut self,
target: binary_sv2::U256<'static>,
extranonce: mining_sv2::Extranonce,
channel_id: u32,
extranonce_size: u16,
) -> Option<()> {
self.channel_to_group_id.insert(channel_id, 0);
let extranonce_prefix = extranonce.into();
let success = OpenExtendedMiningChannelSuccess {
request_id: 0,
channel_id,
target,
extranonce_size,
extranonce_prefix,
};
self.extended_channels.insert(channel_id, success.clone());
Some(())
}
/// Called when an `OpenStandardChannel` message is received for a header only mining channel.
/// Here we save the downstream's target (based on hashrate) and and the
/// channel's extranonce details before returning the relevant SV2 mining messages
/// to be sent downstream.
fn new_standard_channel_for_hom_downstream(
&mut self,
request_id: u32,
downstream_hash_rate: f32,
id: u32,
) -> Result<Vec<Mining>, Error> {
let hom_group_id = 0;
let mut result = vec![];
let channel_id = id;
let target = match crate::utils::hash_rate_to_target(
downstream_hash_rate.into(),
self.share_per_min.into(),
) {
Ok(target) => target,
Err(e) => {
error!(
"Impossible to get target: {:?}. Request id: {:?}",
e, request_id
);
return Err(e);
}
};
let extranonce = self
.extranonces
.next_standard()
.ok_or(Error::ExtranonceSpaceEnded)?;
let standard_channel = StandardChannel {
channel_id,
group_id: hom_group_id,
target: target.clone().into(),
extranonce: extranonce.clone(),
};
self.standard_channels_for_hom_downstreams
.insert(channel_id, standard_channel);
// First message to be sent is OpenStandardMiningChannelSuccess
result.push(Mining::OpenStandardMiningChannelSuccess(
OpenStandardMiningChannelSuccess {
request_id: request_id.into(),
channel_id,
target,
extranonce_prefix: extranonce.into(),
group_channel_id: hom_group_id,
},
));
self.prepare_standard_jobs_and_p_hash(&mut result, channel_id)?;
self.channel_to_group_id.insert(channel_id, hom_group_id);
Ok(result)
}
/// This function is called when downstream have a group channel
/// Shouldnt all standard channel's be non HOM??
fn new_standard_channel_for_non_hom_downstream(
&mut self,
request_id: u32,
downstream_hash_rate: f32,
group_id: u32,
) -> Result<Vec<Mining>, Error> {
let mut result = vec![];
let channel_id = self
.ids
.safe_lock(|ids| ids.new_channel_id(group_id))
.unwrap();
let complete_id = GroupId::into_complete_id(group_id, channel_id);
let target = match crate::utils::hash_rate_to_target(
downstream_hash_rate.into(),
self.share_per_min.into(),
) {
Ok(target_) => target_,
Err(e) => {
info!(
"Impossible to get target: {:?}. Request id: {:?}",
e, request_id
);
return Err(e);
}
};
let extranonce = self
.extranonces
.next_standard()
.ok_or(Error::ExtranonceSpaceEnded)?;
let standard_channel = StandardChannel {
channel_id,
group_id,
target: target.clone().into(),
extranonce: extranonce.clone(),
};
self.standard_channels_for_non_hom_downstreams
.insert(complete_id, standard_channel);
// First message to be sent is OpenStandardMiningChannelSuccess
result.push(Mining::OpenStandardMiningChannelSuccess(
OpenStandardMiningChannelSuccess {
request_id: request_id.into(),
channel_id,
target,
extranonce_prefix: extranonce.into(),
group_channel_id: group_id,
},
));
self.prepare_jobs_and_p_hash(&mut result, complete_id);
self.channel_to_group_id.insert(channel_id, group_id);
Ok(result)
}
// When a hom downstream opens a channel, we use this function to prepare all the standard jobs
// (future and not) that we need to be sent downstream
fn prepare_standard_jobs_and_p_hash(
&mut self,
result: &mut Vec<Mining>,
channel_id: u32,
) -> Result<(), Error> {
// Safe cause the function is private and we always add the channel before calling this
// funtion
let standard_channel = self
.standard_channels_for_hom_downstreams
.get(&channel_id)
.unwrap();
// OPTIMIZATION this could be memoized somewhere cause is very likely that we will receive a lot od
// OpenStandardMiningChannel requests consequtevely
let job_id = self.job_ids.next();
let future_jobs: Option<Vec<NewMiningJob<'static>>> = self
.future_jobs
.iter()
.map(|j| {
extended_to_standard_job(
&j.0,
&standard_channel.extranonce.clone().to_vec()[..],
standard_channel.channel_id,
Some(job_id),
)
})
.collect();
// OPTIMIZATION the extranonce is cloned so many time but maybe is avoidable?
let last_valid_job = match &self.last_valid_job {
Some((j, _)) => Some(
extended_to_standard_job(
j,
&standard_channel.extranonce.clone().to_vec(),
standard_channel.channel_id,
Some(self.job_ids.next()),
)
.ok_or(Error::ImpossibleToCalculateMerkleRoot)?,
),
None => None,
};
// This is the same thing of just check if there is a prev hash add it to result. If there
// is last_job add it to result and add each future job to result.
// But using the pattern match is more clear how each option is handled
match (
&self.last_prev_hash,
last_valid_job,
self.future_jobs.is_empty(),
) {
// If we do not have anything just do nothing
(None, None, true) => Ok(()),
// If we have only future jobs we need to send them all after the
// SetupConnectionSuccess message
(None, None, false) => {
// Safe unwrap cause we check that self.future_jobs is not empty
let mut future_jobs = future_jobs.unwrap();
while let Some(job) = future_jobs.pop() {
result.push(Mining::NewMiningJob(job));
}
Ok(())
}
// If we have just a prev hash we need to send it after the SetupConnectionSuccess
// message
(Some((prev_h, _)), None, true) => {
let prev_h = prev_h.into_set_p_hash(channel_id, None);
result.push(Mining::SetNewPrevHash(prev_h.clone()));
Ok(())
}
// If we have a prev hash and a last valid job we need to send new mining job before the prev hash
(Some((prev_h, _)), Some(mut job), true) => {
let prev_h = prev_h.into_set_p_hash(channel_id, Some(job.job_id));
// set future_job to true
job.set_future();
result.push(Mining::NewMiningJob(job));
result.push(Mining::SetNewPrevHash(prev_h.clone()));
Ok(())
}
// If we have everything we need, send the future jobs and the the prev hash
(Some((prev_h, _)), Some(mut job), false) => {
let prev_h = prev_h.into_set_p_hash(channel_id, Some(job.job_id));
job.set_future();
result.push(Mining::NewMiningJob(job));
result.push(Mining::SetNewPrevHash(prev_h.clone()));
// Safe unwrap cause we check that self.future_jobs is not empty
let mut future_jobs = future_jobs.unwrap();
while let Some(job) = future_jobs.pop() {
result.push(Mining::NewMiningJob(job));
}
Ok(())
}
// This can not happen because we can not have a valid job without a prev hash
(None, Some(_), true) => unreachable!(),
// This can not happen because we can not have a valid job without a prev hash
(None, Some(_), false) => unreachable!(),
// This can not happen because as soon as a prev hash is received we flush the future
// jobs
(Some(_), None, false) => unreachable!(),
}
}
// When a new non HOM downstream opens a channel, we use this function to prepare all the
// extended jobs (future and non) and the prev hash that we need to send dowmstream
fn prepare_jobs_and_p_hash(&mut self, result: &mut Vec<Mining>, complete_id: u64) {
// If group is 0 it means that we are preparing jobs and p hash for a non HOM downstream
// that want to open a new extended channel in that case we want to use the channel id
// TODO verify that this is true also for the case where the channle factory is in a proxy
// and not in a pool.
let group_id = match GroupId::into_group_id(complete_id) {
0 => GroupId::into_channel_id(complete_id),
a => a,
};
// This is the same thing of just check if there is a prev hash add it to result if there
// is last_job add it to result and add each future job to result.
// But using the pattern match is more clear how each option is handled
match (
self.last_prev_hash.as_mut(),
self.last_valid_job.as_mut(),
self.future_jobs.is_empty(),
) {
// If we do not have anything just do nothing
(None, None, true) => (),
// If we have only future jobs we need to send them all after the
// SetupConnectionSuccess message
(None, None, false) => {
for (job, group_id_job_sent) in &mut self.future_jobs {
if !group_id_job_sent.contains(&group_id) {
let mut job = job.clone();
job.channel_id = group_id;
group_id_job_sent.push(group_id);
result.push(Mining::NewExtendedMiningJob(job));
}
}
}
// If we have just a prev hash we need to send it after the SetupConnectionSuccess
// message
(Some((prev_h, group_id_p_hash_sent)), None, true) => {
if !group_id_p_hash_sent.contains(&group_id) {
let prev_h = prev_h.into_set_p_hash(group_id, None);
group_id_p_hash_sent.push(group_id);
result.push(Mining::SetNewPrevHash(prev_h.clone()));
}
}
// If we have a prev hash and a last valid job we need to send before the prev hash and
// the the valid job
(Some((prev_h, group_id_p_hash_sent)), Some((job, group_id_job_sent)), true) => {
if !group_id_p_hash_sent.contains(&group_id) {
let prev_h = prev_h.into_set_p_hash(group_id, Some(job.job_id));
group_id_p_hash_sent.push(group_id);
result.push(Mining::SetNewPrevHash(prev_h));
}
if !group_id_job_sent.contains(&group_id) {
let mut job = job.clone();
job.channel_id = group_id;
group_id_job_sent.push(group_id);
result.push(Mining::NewExtendedMiningJob(job));
}
}
// If we have everything we need, send before the prev hash and then all the jobs
(Some((prev_h, group_id_p_hash_sent)), Some((job, group_id_job_sent)), false) => {
if !group_id_p_hash_sent.contains(&group_id) {
let prev_h = prev_h.into_set_p_hash(group_id, Some(job.job_id));
group_id_p_hash_sent.push(group_id);
result.push(Mining::SetNewPrevHash(prev_h));
}
if !group_id_job_sent.contains(&group_id) {
let mut job = job.clone();
job.channel_id = group_id;
group_id_job_sent.push(group_id);
result.push(Mining::NewExtendedMiningJob(job));
}
for (job, group_id_future_j_sent) in &mut self.future_jobs {
if !group_id_future_j_sent.contains(&group_id) {
let mut job = job.clone();
job.channel_id = group_id;
group_id_future_j_sent.push(group_id);
result.push(Mining::NewExtendedMiningJob(job));
}
}
}
// This can not happen because we can not have a valid job without a prev hash
(None, Some(_), true) => unreachable!(),
// This can not happen because we can not have a valid job without a prev hash
(None, Some(_), false) => unreachable!(),
// This can not happen because as soon as a prev hash is received we flush the future
// jobs
(Some(_), None, false) => unreachable!(),
}
}
/// Called when a new prev hash is received. If the respective job is available in the future job queue,
/// we move the future job into the valid job slot and store the prev hash as the current prev hash to be referenced.
fn on_new_prev_hash(&mut self, m: StagedPhash) -> Result<(), Error> {
while let Some(mut job) = self.future_jobs.pop() {
if job.0.job_id == m.job_id {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as u32;
job.0.set_no_future(now);
self.last_valid_job = Some(job);
break;
}
self.last_valid_job = None;
}
self.future_jobs = vec![];
self.last_prev_hash_ = Some(crate::utils::u256_to_block_hash(m.prev_hash.clone()));
let mut ids = vec![];
for complete_id in self.standard_channels_for_non_hom_downstreams.keys() {
let group_id = GroupId::into_group_id(*complete_id);
if !ids.contains(&group_id) {
ids.push(group_id)
}
}
self.last_prev_hash = Some((m, ids));
Ok(())
}
/// Called when a `NewExtendedMiningJob` arrives. If the job is future, we add it to the future queue.
/// If the job is not future, we pair it with a the most recent prev hash
fn on_new_extended_mining_job(
&mut self,
m: NewExtendedMiningJob<'static>,
) -> Result<HashMap<u32, Mining<'static>, BuildNoHashHasher<u32>>, Error> {
match (m.is_future(), &self.last_prev_hash) {
(true, _) => {
let mut result = HashMap::with_hasher(BuildNoHashHasher::default());
self.prepare_jobs_for_downstream_on_new_extended(&mut result, &m)?;
let mut ids = vec![];
for complete_id in self.standard_channels_for_non_hom_downstreams.keys() {
let group_id = GroupId::into_group_id(*complete_id);
if !ids.contains(&group_id) {
ids.push(group_id)
}
}
self.future_jobs.push((m, ids));
Ok(result)
}
(false, Some(_)) => {
let mut result = HashMap::with_hasher(BuildNoHashHasher::default());
self.prepare_jobs_for_downstream_on_new_extended(&mut result, &m)?;
// If job is not future it must always be paired with the last received prev hash
let mut ids = vec![];
for complete_id in self.standard_channels_for_non_hom_downstreams.keys() {
let group_id = GroupId::into_group_id(*complete_id);
if !ids.contains(&group_id) {
ids.push(group_id)
}
}
self.last_valid_job = Some((m, ids));
if let Some((_p_hash, _)) = &self.last_prev_hash {
Ok(result)
} else {
Err(Error::JobIsNotFutureButPrevHashNotPresent)
}
}
// This should not happen when a non future job is received we always need to have a
// prev hash
(false, None) => Err(Error::JobIsNotFutureButPrevHashNotPresent),
}
}
// When a new extended job is received we use this function to prepare the jobs to be sent
// downstream (standard for hom and this job for non hom)
fn prepare_jobs_for_downstream_on_new_extended(
&mut self,
result: &mut HashMap<u32, Mining, BuildNoHashHasher<u32>>,
m: &NewExtendedMiningJob<'static>,
) -> Result<(), Error> {
for (id, channel) in &self.standard_channels_for_hom_downstreams {
let job_id = self.job_ids.next();
let mut standard_job = extended_to_standard_job(
m,
&channel.extranonce.clone().to_vec()[..],
*id,
Some(job_id),
)
.unwrap();
standard_job.channel_id = *id;
let standard_job = Mining::NewMiningJob(standard_job);
result.insert(*id, standard_job);
}
for id in self.standard_channels_for_non_hom_downstreams.keys() {
let group_id = GroupId::into_group_id(*id);
let mut extended = m.clone();
extended.channel_id = group_id;
let extended_job = Mining::NewExtendedMiningJob(extended);
result.insert(group_id, extended_job);
}
for id in self.extended_channels.keys() {
let mut extended = m.clone();
extended.channel_id = *id;
let extended_job = Mining::NewExtendedMiningJob(extended);
result.insert(*id, extended_job);
}
Ok(())
}
// If there is job creator, bitcoin_target is retrieved from there. If not, it is set to 0.
// If there is a job creator we pass the correct template id. If not, we pass `None`
// allow comparison chain because clippy wants to make job management assertion into a match clause
#[allow(clippy::comparison_chain)]
#[allow(clippy::too_many_arguments)]
fn check_target<TxHash: std::convert::AsRef<[u8]>>(
&mut self,
mut m: Share,
bitcoin_target: Target,
template_id: Option<u64>,
up_id: u32,
merkle_path: Vec<TxHash>,
coinbase_tx_prefix: &[u8],
coinbase_tx_suffix: &[u8],
prev_blockhash: hash_types::BlockHash,
bits: u32,
) -> Result<OnNewShare, Error> {
debug!("Checking target for share {:?}", m);
let upstream_target = match &self.kind {
ExtendedChannelKind::Pool => Target::new(0, 0),
ExtendedChannelKind::Proxy {
upstream_target, ..
}
| ExtendedChannelKind::ProxyJd {
upstream_target, ..
} => upstream_target.clone(),
};
let (downstream_target, extranonce) = self
.get_channel_specific_mining_info(&m)
.ok_or(Error::ShareDoNotMatchAnyChannel)?;
let extranonce_1_len = self.extranonces.get_range0_len();
let extranonce_2 = extranonce[extranonce_1_len..].to_vec();
match &mut m {
Share::Extended(extended_share) => {
extended_share.extranonce = extranonce_2.try_into()?;
}
Share::Standard(_) => (),
};
trace!(
"On checking target coinbase prefix is: {:?}",
coinbase_tx_prefix
);
trace!(
"On checking target coinbase suffix is: {:?}",
coinbase_tx_suffix
);
// Safe unwrap a sha256 can always be converted into [u8;32]
let merkle_root: [u8; 32] = crate::utils::merkle_root_from_path(
coinbase_tx_prefix,
coinbase_tx_suffix,
&extranonce[..],
&merkle_path[..],
)
.ok_or(Error::InvalidCoinbase)?
.try_into()
.unwrap();
let version = match &m {
Share::Extended(share) => share.version as i32,
Share::Standard(share) => share.0.version as i32,
};
let header = bitcoin::blockdata::block::BlockHeader {
version,
prev_blockhash,
merkle_root: Hash::from_inner(merkle_root).into(),
time: m.get_n_time(),
bits,
nonce: m.get_nonce(),
};
trace!("On checking target header is: {:?}", header);
let hash_ = header.block_hash();
let hash = hash_.as_hash().into_inner();
if tracing::level_enabled!(tracing::Level::DEBUG)
|| tracing::level_enabled!(tracing::Level::TRACE)
{
let bitcoin_target_log: binary_sv2::U256 = bitcoin_target.clone().into();
let mut bitcoin_target_log = bitcoin_target_log.to_vec();
bitcoin_target_log.reverse();
debug!("Bitcoin target : {:?}", bitcoin_target_log.to_hex());
let upstream_target: binary_sv2::U256 = upstream_target.clone().into();
let mut upstream_target = upstream_target.to_vec();
upstream_target.reverse();
debug!("Upstream target: {:?}", upstream_target.to_vec().to_hex());
let mut hash = hash;
hash.reverse();
debug!("Hash : {:?}", hash.to_vec().to_hex());
}
let hash: Target = hash.into();
if hash <= bitcoin_target {
let mut print_hash = hash_.as_hash().into_inner();
print_hash.reverse();
info!(
"Share hash meet bitcoin target: {:?}",
print_hash.to_vec().to_hex()
);
let coinbase = [coinbase_tx_prefix, &extranonce[..], coinbase_tx_suffix]
.concat()
.to_vec();
match self.kind {
ExtendedChannelKind::Proxy { .. } | ExtendedChannelKind::ProxyJd { .. } => {
let upstream_extranonce_space = self.extranonces.get_range0_len();
let extranonce_ = extranonce[upstream_extranonce_space..].to_vec();
let mut res = OnNewShare::ShareMeetBitcoinTarget((
m,
template_id,
coinbase,
extranonce.to_vec(),
));
res.into_extended(extranonce_, up_id);
Ok(res)
}
ExtendedChannelKind::Pool => Ok(OnNewShare::ShareMeetBitcoinTarget((
m,
template_id,
coinbase,
extranonce.to_vec(),
))),
}
} else if hash <= upstream_target {
match self.kind {
ExtendedChannelKind::Proxy { .. } | ExtendedChannelKind::ProxyJd { .. } => {
let upstream_extranonce_space = self.extranonces.get_range0_len();
let extranonce = extranonce[upstream_extranonce_space..].to_vec();
let mut res = OnNewShare::SendSubmitShareUpstream((m, template_id));
res.into_extended(extranonce, up_id);
Ok(res)
}
ExtendedChannelKind::Pool => {
Ok(OnNewShare::SendSubmitShareUpstream((m, template_id)))
}
}
} else if hash <= downstream_target {
Ok(OnNewShare::ShareMeetDownstreamTarget)
} else {
error!("Share does not meet any target: {:?}", m);
let error = SubmitSharesError {
channel_id: m.get_channel_id(),
sequence_number: m.get_sequence_number(),
// Infallible unwrap we already know the len of the error code (is a
// static string)
error_code: SubmitSharesError::difficulty_too_low_error_code()
.to_string()
.try_into()
.unwrap(),
};
Ok(OnNewShare::SendErrorDownstream(error))
}
}
/// Returns the downstream target and extranonce for the channel
fn get_channel_specific_mining_info(&self, m: &Share) -> Option<(mining_sv2::Target, Vec<u8>)> {
match m {
Share::Extended(share) => {
let channel = self.extended_channels.get(&m.get_channel_id())?;
let extranonce_prefix = channel.extranonce_prefix.to_vec();
let dowstream_target = channel.target.clone().into();
let extranonce = [&extranonce_prefix[..], &share.extranonce.to_vec()[..]]
.concat()
.to_vec();
if extranonce.len() != self.extranonces.get_len() {
error!(
"Extranonce is not of the right len expected {} actual {}",
self.extranonces.get_len(),
extranonce.len()
);
}
Some((dowstream_target, extranonce))
}
Share::Standard((share, group_id)) => match &self.kind {
ExtendedChannelKind::Pool => {
let complete_id = GroupId::into_complete_id(*group_id, share.channel_id);
let mut channel = self
.standard_channels_for_non_hom_downstreams
.get(&complete_id);
if channel.is_none() {
channel = self
.standard_channels_for_hom_downstreams
.get(&share.channel_id);
};
Some((
channel?.target.clone(),
channel?.extranonce.clone().to_vec(),
))
}
ExtendedChannelKind::Proxy { .. } | ExtendedChannelKind::ProxyJd { .. } => {
let complete_id = GroupId::into_complete_id(*group_id, share.channel_id);
let mut channel = self
.standard_channels_for_non_hom_downstreams
.get(&complete_id);
if channel.is_none() {
channel = self
.standard_channels_for_hom_downstreams
.get(&share.channel_id);
};
Some((
channel?.target.clone(),
channel?.extranonce.clone().to_vec(),
))
}
},
}
}
/// updates the downstream target for the given channel_id
fn update_target_for_channel(&mut self, channel_id: u32, new_target: Target) -> Option<bool> {
let channel = self.extended_channels.get_mut(&channel_id)?;
channel.target = new_target.into();
Some(true)
}
}
/// Used by a pool to in order to manage all downstream channel. It add job creation capabilities
/// to ChannelFactory.
#[derive(Debug)]
pub struct PoolChannelFactory {
inner: ChannelFactory,
job_creator: JobsCreators,
pool_coinbase_outputs: Vec<TxOut>,
pool_signature: String,
// extedned_channel_id -> SetCustomMiningJob
negotiated_jobs: HashMap<u32, SetCustomMiningJob<'static>, BuildNoHashHasher<u32>>,
}
impl PoolChannelFactory {
pub fn new(
ids: Arc<Mutex<GroupId>>,
extranonces: ExtendedExtranonce,
job_creator: JobsCreators,
share_per_min: f32,
kind: ExtendedChannelKind,
pool_coinbase_outputs: Vec<TxOut>,
pool_signature: String,
) -> Self {
let inner = ChannelFactory {
ids,
standard_channels_for_non_hom_downstreams: HashMap::with_hasher(
BuildNoHashHasher::default(),
),
standard_channels_for_hom_downstreams: HashMap::with_hasher(
BuildNoHashHasher::default(),
),
extended_channels: HashMap::with_hasher(BuildNoHashHasher::default()),
extranonces,
share_per_min,
future_jobs: Vec::new(),
last_prev_hash: None,