channels_sv2 5.0.0

Sv2 Channel Primitives
Documentation
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
//! Sv2 Standard Channel - Mining Client Abstraction.
//!
//! This module provides the [`StandardChannel`] struct, which models the state of a mining
//! client's Sv2 Standard Channel. It tracks channel-level job management, share accounting,
//! and chain tip state, enabling share validation and mining job lifecycle management.

extern crate alloc;
use super::HashMap;
use crate::{
    chain_tip::ChainTip,
    client::{
        error::StandardChannelError,
        share_accounting::{ShareAccounting, ShareValidationError, ShareValidationResult},
    },
    extranonce_manager::ExtranoncePrefix,
    merkle_root::merkle_root_from_path,
    target::{bytes_to_hex, u256_to_block_hash},
    MAX_EXTRANONCE_LEN,
};
use alloc::{format, string::String};
use binary_sv2::{self, Sv2Option};
use bitcoin::{
    blockdata::block::{Header, Version},
    hashes::sha256d::Hash,
    CompactTarget, Target,
};
use mining_sv2::{
    NewExtendedMiningJob, NewMiningJob, SetNewPrevHash as SetNewPrevHashMp, SubmitSharesStandard,
};
use tracing::debug;

/// A type alias representing a standard mining job tied to a specific `target`.
pub type StandardJob<'a> = (NewMiningJob<'a>, Target);

/// Mining Client abstraction over the state of a Sv2 Standard Channel.
///
/// Tracks:
/// - unique channel ID
/// - user identity string
/// - unique extranonce prefix
/// - channel target
/// - nominal hashrate in h/s
/// - future mining jobs (indexed by job_id, activated upon [`NewMiningJob`] receipt)
/// - active mining job
/// - past jobs (active jobs under current chain tip, indexed by job_id)
/// - stale jobs (jobs from previous chain tip, indexed by job_id)
/// - share accounting state
/// - chain tip state
#[derive(Debug)]
pub struct StandardChannel<'a> {
    channel_id: u32,
    user_identity: String,
    extranonce_prefix: ExtranoncePrefix,
    target: Target,
    nominal_hashrate: f32,
    future_jobs: HashMap<u32, StandardJob<'a>>,
    active_job: Option<StandardJob<'a>>,
    past_jobs: HashMap<u32, StandardJob<'a>>,
    stale_jobs: HashMap<u32, StandardJob<'a>>,
    share_accounting: ShareAccounting,
    chain_tip: Option<ChainTip>,
}

impl<'a> StandardChannel<'a> {
    /// Creates a new [`StandardChannel`] instance with provided channel parameters.
    pub fn new(
        channel_id: u32,
        user_identity: String,
        extranonce_prefix: ExtranoncePrefix,
        target: Target,
        nominal_hashrate: f32,
    ) -> Self {
        Self {
            channel_id,
            user_identity,
            extranonce_prefix,
            target,
            nominal_hashrate,
            future_jobs: HashMap::new(),
            active_job: None,
            past_jobs: HashMap::new(),
            stale_jobs: HashMap::new(),
            share_accounting: ShareAccounting::new(),
            chain_tip: None,
        }
    }

    /// Returns the channel ID.
    pub fn get_channel_id(&self) -> u32 {
        self.channel_id
    }

    /// Returns the user identity string associated with this channel.
    pub fn get_user_identity(&self) -> &String {
        &self.user_identity
    }

    /// Returns the latest chain tip information, if any.
    pub fn get_chain_tip(&self) -> Option<&ChainTip> {
        self.chain_tip.as_ref()
    }

    /// Sets the [`ChainTip`]
    pub fn set_chain_tip(&mut self, chain_tip: ChainTip) {
        self.chain_tip = Some(chain_tip);
    }

    /// Sets the extranonce prefix for the channel.
    ///
    /// All new jobs will use the new extranonce prefix. Jobs created before
    /// this call will continue using their previous prefix for share validation.
    /// Returns an error if the prefix is too large.
    pub fn set_extranonce_prefix(
        &mut self,
        extranonce_prefix: ExtranoncePrefix,
    ) -> Result<(), StandardChannelError> {
        if extranonce_prefix.len() > MAX_EXTRANONCE_LEN as usize {
            return Err(StandardChannelError::NewExtranoncePrefixTooLarge);
        }

        self.extranonce_prefix = extranonce_prefix;
        Ok(())
    }

    /// Returns the bytes representing the first part of the extranonce.
    pub fn get_extranonce_prefix(&self) -> &[u8] {
        self.extranonce_prefix.as_bytes()
    }

    /// Returns the length of the `upstream_prefix` region of this channel's
    /// extranonce prefix, if known.
    ///
    /// See [`ExtranoncePrefix::upstream_prefix_len`](crate::extranonce_manager::ExtranoncePrefix::upstream_prefix_len)
    /// for the full semantics. In particular, this is `None` for channels
    /// opened from a wire-sourced prefix (the common case on a client),
    /// and `Some(n)` when the application minted the prefix locally from
    /// an [`ExtranonceAllocator`](crate::extranonce_manager::ExtranonceAllocator) — e.g. a proxy that
    /// sub-allocates an upstream-assigned extranonce space and hands one
    /// slot to each downstream channel.
    pub fn upstream_prefix_len(&self) -> Option<u8> {
        self.extranonce_prefix.upstream_prefix_len()
    }

    /// Returns the current target for the channel.
    pub fn get_target(&self) -> &Target {
        &self.target
    }

    /// Sets a new target for the channel.
    pub fn set_target(&mut self, target: Target) {
        self.target = target;
    }

    /// Returns the nominal hashrate of the channel in h/s.
    pub fn get_nominal_hashrate(&self) -> f32 {
        self.nominal_hashrate
    }

    /// Returns all future jobs for this channel.
    ///
    /// The list is cleared once a [`StandardChannel::on_set_new_prev_hash`] is processed.
    pub fn get_future_jobs(&self) -> &HashMap<u32, StandardJob<'a>> {
        &self.future_jobs
    }

    /// Returns the currently active job, if any.
    pub fn get_active_job(&self) -> Option<&StandardJob<'a>> {
        self.active_job.as_ref()
    }

    /// Returns all past jobs for the channel (active jobs under current chain tip).
    pub fn get_past_jobs(&self) -> &HashMap<u32, StandardJob<'a>> {
        &self.past_jobs
    }

    /// Returns all stale jobs for the channel (jobs from previous chain tip).
    pub fn get_stale_jobs(&self) -> &HashMap<u32, StandardJob<'a>> {
        &self.stale_jobs
    }

    /// Returns the share accounting state for this channel.
    pub fn get_share_accounting(&self) -> &ShareAccounting {
        &self.share_accounting
    }

    /// Updates share accounting based on a [`SubmitSharesSuccess`] message from the
    /// upstream server. Delegates to [`ShareAccounting::on_share_acknowledgement`].
    pub fn on_share_acknowledgement(
        &mut self,
        new_submits_accepted_count: u32,
        new_shares_sum: f64,
    ) {
        self.share_accounting
            .on_share_acknowledgement(new_submits_accepted_count, new_shares_sum);
    }

    /// Updates share accounting based on a [`SubmitSharesError`] message from the upstream
    /// server. Delegates to [`ShareAccounting::on_share_rejection`].
    pub fn on_share_rejection(&mut self, error_code: String) {
        self.share_accounting.on_share_rejection(error_code);
    }

    /// Handles a new group channel job by converting it into a standard job
    /// and activating it in this channel's context.
    ///
    /// The new job is constructed using the current extranonce prefix.
    pub fn on_new_group_channel_job(&mut self, new_extended_mining_job: NewExtendedMiningJob<'a>) {
        let merkle_root = merkle_root_from_path(
            new_extended_mining_job.coinbase_tx_prefix.inner_as_ref(),
            new_extended_mining_job.coinbase_tx_suffix.inner_as_ref(),
            self.extranonce_prefix.as_bytes(),
            &new_extended_mining_job.merkle_path.inner_as_ref(),
        )
        .expect("merkle root must be valid")
        .try_into()
        .expect("merkle root must be 32 bytes");

        let new_mining_job = NewMiningJob {
            channel_id: self.channel_id,
            job_id: new_extended_mining_job.job_id,
            merkle_root,
            version: new_extended_mining_job.version,
            min_ntime: new_extended_mining_job.min_ntime,
        };

        self.on_new_mining_job(new_mining_job);
    }

    /// Handles a newly received [`NewMiningJob`] message from upstream.
    ///
    /// - If `min_ntime` is present, the job is activated and replaces the current active job.
    /// - If `min_ntime` is empty, the job is added to future jobs.
    /// - If an active job exists, it is moved to past jobs on activation.
    pub fn on_new_mining_job(&mut self, new_mining_job: NewMiningJob<'a>) {
        match new_mining_job.min_ntime.clone().into_inner() {
            Some(_min_ntime) => {
                if let Some(active_job) = self.active_job.as_ref() {
                    self.past_jobs
                        .insert(active_job.0.job_id, active_job.clone());
                }
                self.active_job = Some((new_mining_job, self.target));
            }
            None => {
                self.future_jobs
                    .insert(new_mining_job.job_id, (new_mining_job, self.target));
            }
        }
    }

    /// Handles an upstream [`SetNewPrevHash`](SetNewPrevHashMp) message.
    ///
    /// - Activates the matching future job as the new active job.
    /// - Clears all future jobs.
    /// - Marks all past jobs as stale (they are no longer valid for share propagation).
    /// - Clears past jobs and the set of seen shares (to avoid memory growth and stale share
    ///   submissions).
    /// - Updates chain tip information. Returns error if no matching future job found.
    pub fn on_set_new_prev_hash(
        &mut self,
        set_new_prev_hash: SetNewPrevHashMp<'a>,
    ) -> Result<(), StandardChannelError> {
        match self.future_jobs.remove(&set_new_prev_hash.job_id) {
            Some(mut activated_job) => {
                activated_job.0.min_ntime = Sv2Option::new(Some(set_new_prev_hash.min_ntime));
                self.active_job = Some(activated_job);
            }
            None => return Err(StandardChannelError::JobIdNotFound),
        }

        // all other future jobs are now useless
        self.future_jobs.clear();

        // mark all past jobs as stale, so that shares are not propagated
        self.stale_jobs = self.past_jobs.clone();

        // clear past jobs, as we're no longer going to propagate shares for them
        self.past_jobs.clear();

        // clear seen shares, as shares for past chain tip will be rejected as stale
        self.share_accounting.flush_seen_shares();

        self.chain_tip = Some(set_new_prev_hash.into());

        Ok(())
    }

    /// Validates a share before submission upstream.
    ///
    /// - Checks if the share refers to an active or past job; rejects stale jobs.
    /// - Verifies the share meets the channel target, is not a duplicate, and is not stale.
    /// - Updates share accounting state based on validation result.
    /// - Returns whether the share is valid or resulted in a block being found.
    /// - Returns error describing why share is not valid.
    pub fn validate_share(
        &mut self,
        share: SubmitSharesStandard,
    ) -> Result<ShareValidationResult, ShareValidationError> {
        let job_id = share.job_id;

        // check if job_id is active job
        let is_active_job = self
            .active_job
            .as_ref()
            .is_some_and(|job| job.0.job_id == job_id);

        // check if job_id is past job
        let is_past_job = self.past_jobs.contains_key(&job_id);

        // check if job_id is stale job
        let is_stale_job = self.stale_jobs.contains_key(&job_id);

        if is_stale_job {
            return Err(ShareValidationError::Stale);
        }

        let job = if is_active_job {
            self.active_job.as_ref().expect("active job must exist")
        } else if is_past_job {
            self.past_jobs.get(&job_id).expect("past job must exist")
        } else {
            return Err(ShareValidationError::InvalidJobId);
        };

        let merkle_root: [u8; 32] = job
            .0
            .merkle_root
            .inner_as_ref()
            .try_into()
            .expect("merkle root must be 32 bytes");

        let chain_tip = self
            .chain_tip
            .as_ref()
            .ok_or(ShareValidationError::NoChainTip)?;

        let prev_hash = chain_tip.prev_hash();
        let nbits = CompactTarget::from_consensus(chain_tip.nbits());

        // create the header for validation
        let header = Header {
            version: Version::from_consensus(share.version as i32),
            prev_blockhash: u256_to_block_hash(prev_hash.clone()),
            merkle_root: (*Hash::from_bytes_ref(&merkle_root)).into(),
            time: share.ntime,
            bits: nbits,
            nonce: share.nonce,
        };

        // convert the header hash to a target type for easy comparison
        let share_hash = header.block_hash();
        let raw_share_hash: [u8; 32] = *share_hash.to_raw_hash().as_ref();
        let share_hash_target = Target::from_le_bytes(raw_share_hash);
        let share_hash_as_diff = share_hash_target.difficulty_float();
        let network_target = Target::from_compact(nbits);

        let job_target = job.1;

        // print hash_as_target and self.target as human readable hex
        let share_hash_target_bytes = share_hash_target.to_be_bytes();
        let job_target_bytes = job_target.to_be_bytes();

        debug!(
            "share validation \nshare:\t\t{}\njob target:\t{}\nnetwork target:\t{}",
            bytes_to_hex(&share_hash_target_bytes),
            bytes_to_hex(&job_target_bytes),
            format!("{:x}", network_target)
        );

        // check if a block was found
        if network_target.is_met_by(share_hash) {
            if self
                .share_accounting
                .is_share_seen(share_hash.to_raw_hash())
            {
                return Err(ShareValidationError::DuplicateShare);
            }
            self.share_accounting
                .track_validated_share(share.sequence_number, share_hash.to_raw_hash());
            self.share_accounting.increment_blocks_found();
            return Ok(ShareValidationResult::BlockFound(share_hash.to_raw_hash()));
        }

        // check if the share hash meets the job target
        if share_hash_target < job_target {
            if self
                .share_accounting
                .is_share_seen(share_hash.to_raw_hash())
            {
                return Err(ShareValidationError::DuplicateShare);
            }

            self.share_accounting
                .track_validated_share(share.sequence_number, share_hash.to_raw_hash());

            // update the best diff
            self.share_accounting.update_best_diff(share_hash_as_diff);

            return Ok(ShareValidationResult::Valid(share_hash.to_raw_hash()));
        }

        Err(ShareValidationError::DoesNotMeetTarget)
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        client::{
            share_accounting::{ShareValidationError, ShareValidationResult},
            standard::StandardChannel,
        },
        extranonce_manager::ExtranoncePrefix,
    };
    use binary_sv2::Sv2Option;
    use bitcoin::Target;
    use mining_sv2::{NewMiningJob, SetNewPrevHash as SetNewPrevHashMp, SubmitSharesStandard};

    #[test]
    fn test_future_job_activation_flow() {
        let channel_id = 1;
        let user_identity = "user_identity".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 target = Target::from_le_bytes([0xff; 32]);
        let nominal_hashrate = 1.0;

        let mut channel = StandardChannel::new(
            channel_id,
            user_identity,
            ExtranoncePrefix::from_wire(extranonce_prefix).unwrap(),
            target,
            nominal_hashrate,
        );

        let future_job = NewMiningJob {
            channel_id,
            job_id: 1,
            merkle_root: [
                189, 200, 25, 246, 119, 73, 34, 42, 209, 112, 237, 50, 169, 71, 163, 192, 24, 84,
                56, 86, 147, 71, 243, 44, 18, 107, 167, 169, 169, 66, 186, 98,
            ]
            .into(),
            version: 536870912,
            min_ntime: Sv2Option::new(None),
        };

        channel.on_new_mining_job(future_job.clone());

        assert_eq!(channel.get_future_jobs().len(), 1);
        assert_eq!(channel.get_active_job(), None);
        assert_eq!(channel.get_past_jobs().len(), 0);

        let ntime: u32 = 1746839905;
        let set_new_prev_hash = SetNewPrevHashMp {
            channel_id,
            job_id: future_job.job_id,
            prev_hash: [
                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(),
            nbits: 503543726,
            min_ntime: ntime,
        };

        channel.on_set_new_prev_hash(set_new_prev_hash).unwrap();
        assert!(channel.get_future_jobs().is_empty());

        let mut previously_future_job = future_job.clone();
        previously_future_job.min_ntime = Sv2Option::new(Some(ntime));

        assert_eq!(
            channel.get_active_job(),
            Some(&(previously_future_job, channel.get_target().clone()))
        );
    }

    #[test]
    fn test_past_jobs_flow() {
        let channel_id = 1;
        let user_identity = "user_identity".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 target = Target::from_le_bytes([0xff; 32]);
        let nominal_hashrate = 1.0;

        let mut channel = StandardChannel::new(
            channel_id,
            user_identity,
            ExtranoncePrefix::from_wire(extranonce_prefix).unwrap(),
            target,
            nominal_hashrate,
        );

        let ntime: u32 = 1746839905;
        let active_job = NewMiningJob {
            channel_id,
            job_id: 1,
            merkle_root: [
                189, 200, 25, 246, 119, 73, 34, 42, 209, 112, 237, 50, 169, 71, 163, 192, 24, 84,
                56, 86, 147, 71, 243, 44, 18, 107, 167, 169, 169, 66, 186, 98,
            ]
            .into(),
            version: 536870912,
            min_ntime: Sv2Option::new(Some(ntime)),
        };

        channel.on_new_mining_job(active_job.clone());

        assert_eq!(channel.get_future_jobs().len(), 0);
        assert_eq!(
            channel.get_active_job(),
            Some(&(active_job.clone(), channel.get_target().clone()))
        );
        assert_eq!(channel.get_past_jobs().len(), 0);

        let mut new_active_job = active_job.clone();
        new_active_job.job_id = 2;
        channel.on_new_mining_job(new_active_job.clone());

        assert_eq!(channel.get_future_jobs().len(), 0);
        assert_eq!(
            channel.get_active_job(),
            Some(&(new_active_job, channel.get_target().clone()))
        );
        assert_eq!(channel.get_past_jobs().len(), 1);
    }

    #[test]
    fn test_share_validation_block_found() {
        let channel_id = 1;
        let user_identity = "user_identity".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 target = Target::from_le_bytes([0xff; 32]);
        let nominal_hashrate = 1.0;

        let mut channel = StandardChannel::new(
            channel_id,
            user_identity,
            ExtranoncePrefix::from_wire(extranonce_prefix).unwrap(),
            target,
            nominal_hashrate,
        );

        let future_job = NewMiningJob {
            channel_id,
            job_id: 1,
            merkle_root: [
                189, 200, 25, 246, 119, 73, 34, 42, 209, 112, 237, 50, 169, 71, 163, 192, 24, 84,
                56, 86, 147, 71, 243, 44, 18, 107, 167, 169, 169, 66, 186, 98,
            ]
            .into(),
            version: 536870912,
            min_ntime: Sv2Option::new(None),
        };

        channel.on_new_mining_job(future_job.clone());

        // network target: 7fffff0000000000000000000000000000000000000000000000000000000000
        let nbits = 545259519;
        let prev_hash = [
            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,
        ];
        let ntime: u32 = 1746839905;
        let set_new_prev_hash = SetNewPrevHashMp {
            channel_id,
            job_id: future_job.job_id,
            prev_hash: prev_hash.into(),
            nbits,
            min_ntime: ntime,
        };

        channel.on_set_new_prev_hash(set_new_prev_hash).unwrap();

        // this share has hash 61e8fe82487d10282fdededed636403eb2c8cb05ce792951dd410a9011a94ebb
        // which satisfied the network target
        // 7fffff0000000000000000000000000000000000000000000000000000000000
        let share_valid_block = SubmitSharesStandard {
            channel_id,
            sequence_number: 0,
            job_id: future_job.job_id,
            nonce: 3,
            ntime: 1745596932,
            version: 536870912,
        };

        let res = channel.validate_share(share_valid_block.clone());

        assert!(matches!(res, Ok(ShareValidationResult::BlockFound(_))));
        assert_eq!(channel.get_share_accounting().get_blocks_found(), 1);

        // re-submitting the same valid block must be rejected as duplicate
        let res = channel.validate_share(share_valid_block);
        assert!(matches!(
            res.unwrap_err(),
            ShareValidationError::DuplicateShare
        ));
        assert_eq!(channel.get_share_accounting().get_blocks_found(), 1);
    }

    #[test]
    fn test_share_validation_does_not_meet_target() {
        let channel_id = 1;
        let user_identity = "user_identity".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();
        // channel target: 0000ffff00000000000000000000000000000000000000000000000000000000
        let target = Target::from_le_bytes([
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0xff, 0xff, 0x00, 0x00,
        ]);
        let nominal_hashrate = 1.0;

        let mut channel = StandardChannel::new(
            channel_id,
            user_identity,
            ExtranoncePrefix::from_wire(extranonce_prefix).unwrap(),
            target,
            nominal_hashrate,
        );

        let future_job = NewMiningJob {
            channel_id,
            job_id: 1,
            merkle_root: [
                189, 200, 25, 246, 119, 73, 34, 42, 209, 112, 237, 50, 169, 71, 163, 192, 24, 84,
                56, 86, 147, 71, 243, 44, 18, 107, 167, 169, 169, 66, 186, 98,
            ]
            .into(),
            version: 536870912,
            min_ntime: Sv2Option::new(None),
        };

        channel.on_new_mining_job(future_job.clone());

        // network target: 000000000000d7c0000000000000000000000000000000000000000000000000
        let nbits = 453040064;
        let prev_hash = [
            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,
        ];
        let ntime: u32 = 1746839905;
        let set_new_prev_hash = SetNewPrevHashMp {
            channel_id,
            job_id: future_job.job_id,
            prev_hash: prev_hash.into(),
            nbits,
            min_ntime: ntime,
        };

        channel.on_set_new_prev_hash(set_new_prev_hash).unwrap();

        // this share has hash 45ec7dbd7b599599e6724ab32e6936dad033f46ccff97e743579d8c047cf3243
        // which does not meet the channel target
        // 0000ffff00000000000000000000000000000000000000000000000000000000
        let share_low_diff = SubmitSharesStandard {
            channel_id,
            sequence_number: 0,
            job_id: future_job.job_id,
            nonce: 3,
            ntime: 1745596932,
            version: 536870912,
        };

        let res = channel.validate_share(share_low_diff);

        assert!(matches!(
            res.unwrap_err(),
            ShareValidationError::DoesNotMeetTarget
        ));
    }

    #[test]
    fn test_share_validation_valid_share() {
        let channel_id = 1;
        let user_identity = "user_identity".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();
        // channel target: 0000ffff00000000000000000000000000000000000000000000000000000000
        let target = Target::from_le_bytes([
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0xff, 0xff, 0x00, 0x00,
        ]);
        let nominal_hashrate = 1.0;

        let mut channel = StandardChannel::new(
            channel_id,
            user_identity,
            ExtranoncePrefix::from_wire(extranonce_prefix).unwrap(),
            target,
            nominal_hashrate,
        );

        let future_job = NewMiningJob {
            channel_id,
            job_id: 1,
            merkle_root: [
                189, 200, 25, 246, 119, 73, 34, 42, 209, 112, 237, 50, 169, 71, 163, 192, 24, 84,
                56, 86, 147, 71, 243, 44, 18, 107, 167, 169, 169, 66, 186, 98,
            ]
            .into(),
            version: 536870912,
            min_ntime: Sv2Option::new(None),
        };

        channel.on_new_mining_job(future_job.clone());

        // network target: 000000000000d7c0000000000000000000000000000000000000000000000000
        let nbits = 453040064;
        let prev_hash = [
            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,
        ];
        let ntime: u32 = 1746839905;
        let set_new_prev_hash = SetNewPrevHashMp {
            channel_id,
            job_id: future_job.job_id,
            prev_hash: prev_hash.into(),
            nbits,
            min_ntime: ntime,
        };

        channel.on_set_new_prev_hash(set_new_prev_hash).unwrap();

        // this share has hash 0000762e88282a2ed8e7097aef06f413a962a47e32206a80ecbfc1f0b4bd1493
        // which meets the channel target
        // 0000ffff00000000000000000000000000000000000000000000000000000000
        let valid_share = SubmitSharesStandard {
            channel_id,
            sequence_number: 0,
            job_id: future_job.job_id,
            nonce: 244405,
            ntime: 1745596932,
            version: 536870912,
        };

        let res = channel.validate_share(valid_share);

        assert!(matches!(res, Ok(ShareValidationResult::Valid(_))));
    }
}