channels_sv2 3.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
//! Sv2 Group Channel - Mining Server Abstraction.
//!
//! This module defines the [`GroupChannel`] struct, which provides an abstraction of a Stratum V2
//! (SV2) group channel as maintained by a mining server.
//!
//! A group channel represents a logical grouping of standard and extended channels, allowing multiple mining
//! entities to share jobs. It manages job distribution and activation for all
//! associated channels, but delegates share validation and accounting to those channels.
//!
//! ## Responsibilities
//!
//! `GroupChannel` is responsible for managing the state associated with an SV2 group channel,
//! including:
//!
//! - **Group Channel ID**: Holds the unique `group_channel_id`.
//! - **Channel Management**: Tracks the set of associated channel IDs, allowing
//!   for dynamic addition and removal.
//! - **Job Factory and Store**: Manages creation and storage of jobs (future and active) using the
//!   job factory and job store abstractions.
//! - **Job Lifecycle Management**: Stores jobs received from new templates, including:
//!   - Future jobs (indexed by `template_id`)
//!   - Active job (currently being mined)
//! - **Chain Tip Management**: Tracks the latest known chain tip (block height, previous hash,
//!   timestamp, and target) for constructing headers and activating jobs.
//!
//! ## Notes
//!
//! - Share validation and accounting is handled at the channel level, not in the group
//!   channel.
//! - Past and stale jobs are not tracked in this abstraction.
//! - Extranonce prefix management is deferred to channels; group jobs use an empty prefix.

use crate::{
    chain_tip::ChainTip,
    server::{
        error::GroupChannelError,
        jobs::{extended::ExtendedJob, factory::JobFactory, job_store::JobStore},
    },
};
use bitcoin::transaction::TxOut;
use std::{collections::HashSet, marker::PhantomData};
use template_distribution_sv2::{NewTemplate, SetNewPrevHash as SetNewPrevHashTdp};

/// Abstraction of a Group Channel.
///
/// It keeps track of:
/// - the group channel's unique `group_channel_id`
/// - the group channel's `channels` (indexed by `channel_id`)
/// - the group channel's job factory
/// - the group channel's future jobs (indexed by `template_id`, to be activated upon receipt of a
///   `SetNewPrevHash` message)
/// - the group channel's active job
/// - the group channel's chain tip
/// - the group channel's full extranonce size
///
/// Since share validation happens at the Channel level, we don't really keep track of:
/// - the group channel's past jobs
/// - the group channel's stale jobs
/// - the group channel's share validation state
#[derive(Debug)]
pub struct GroupChannel<'a, J>
where
    J: JobStore<ExtendedJob<'a>>,
{
    group_channel_id: u32,
    channel_ids: HashSet<u32>,
    job_factory: JobFactory,
    job_store: J,
    chain_tip: Option<ChainTip>,
    full_extranonce_size: usize,
    phantom: PhantomData<&'a ()>,
}

impl<'a, J> GroupChannel<'a, J>
where
    J: JobStore<ExtendedJob<'a>>,
{
    /// Constructor of `GroupChannel` for a Sv2 Pool Server.
    /// Not meant for usage on a Sv2 Job Declaration Client.
    ///
    /// Initializes the group channel state with the provided group channel ID and job store.
    /// The job factory is initialized with version rolling enabled.
    ///
    /// For non-JD jobs, `pool_tag_string` is added to the coinbase scriptSig in between `/`
    /// and `//` delimiters: `/pool_tag_string//`
    pub fn new_for_pool(
        group_channel_id: u32,
        job_store: J,
        full_extranonce_size: usize,
        pool_tag_string: String,
    ) -> Result<Self, GroupChannelError> {
        let group_channel = Self::new(
            group_channel_id,
            job_store,
            full_extranonce_size,
            Some(pool_tag_string),
            None,
        )?;
        Ok(group_channel)
    }

    /// Constructor of `GroupChannel` for a Sv2 Job Declaration Client.
    /// Not meant for usage on a Sv2 Pool Server.
    ///
    /// Initializes the extended channel state with the provided parameters, including channel
    /// identifiers, difficulty targets, share accounting, and job management.
    /// Returns an error if target/difficulty parameters are invalid or extranonce prefix
    /// requirements are not met.
    ///
    /// The `pool_tag_string` and `miner_tag_string` are added to the coinbase scriptSig in between
    /// `/` delimiters: `/pool_tag_string/miner_tag_string/`
    pub fn new_for_job_declaration_client(
        group_channel_id: u32,
        job_store: J,
        full_extranonce_size: usize,
        pool_tag_string: Option<String>,
        miner_tag_string: String,
    ) -> Result<Self, GroupChannelError> {
        let group_channel = Self::new(
            group_channel_id,
            job_store,
            full_extranonce_size,
            pool_tag_string,
            Some(miner_tag_string),
        )?;
        Ok(group_channel)
    }

    // private constructor
    fn new(
        group_channel_id: u32,
        job_store: J,
        full_extranonce_size: usize,
        pool_tag: Option<String>,
        miner_tag: Option<String>,
    ) -> Result<Self, GroupChannelError> {
        let script_sig_size = 5 + // BIP34
            1 + // OP_PUSHBYTES
            3 + // `/` delimiters
            pool_tag.as_ref().map_or(0, |s| s.len()) +
            miner_tag.as_ref().map_or(0, |s| s.len()) +
            1 + // OP_PUSHBYTES
            full_extranonce_size;

        if script_sig_size > 100 {
            return Err(GroupChannelError::ScriptSigSizeTooLarge);
        }

        Ok(Self {
            group_channel_id,
            channel_ids: HashSet::new(),
            job_factory: JobFactory::new(true, pool_tag, miner_tag),
            job_store,
            chain_tip: None,
            full_extranonce_size,
            phantom: PhantomData,
        })
    }

    /// Adds a channel ID to this group channel. Also takes the `full_extranonce_size` of the channel to be added.
    ///
    /// Returns an error if the provided `full_extranonce_size` doesn't match the group channel's `full_extranonce_size`.
    pub fn add_channel_id(
        &mut self,
        channel_id: u32,
        full_extranonce_size: usize,
    ) -> Result<(), GroupChannelError> {
        self.channel_ids.insert(channel_id);

        if self.full_extranonce_size != full_extranonce_size {
            return Err(GroupChannelError::FullExtranonceSizeMismatch);
        }

        Ok(())
    }

    /// Removes a channel ID from this group channel.
    pub fn remove_channel_id(&mut self, channel_id: u32) {
        self.channel_ids.remove(&channel_id);
    }

    /// Returns the unique group channel ID for this group channel.
    pub fn get_group_channel_id(&self) -> u32 {
        self.group_channel_id
    }

    /// Set the full extranonce size for this group channel.
    /// Also clears all channel IDs, as no channels can belong to the same group while having different `full_extranonce_size`s.
    pub fn set_full_extranonce_size(&mut self, full_extranonce_size: usize) {
        if self.full_extranonce_size != full_extranonce_size {
            self.channel_ids.clear();
        }

        self.full_extranonce_size = full_extranonce_size;
    }

    pub fn get_full_extranonce_size(&self) -> usize {
        self.full_extranonce_size
    }

    /// Returns a reference to the set of channel IDs associated with this group channel.
    pub fn get_channel_ids(&self) -> &HashSet<u32> {
        &self.channel_ids
    }

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

    /// Only for testing purposes, not meant to be used in real apps.
    #[cfg(test)]
    pub fn set_chain_tip(&mut self, chain_tip: ChainTip) {
        self.chain_tip = Some(chain_tip);
    }

    /// Returns an owned copy of the currently active job, if any.
    pub fn get_active_job(&self) -> Option<ExtendedJob<'a>> {
        // cloning happens inside the job store
        self.job_store.get_active_job()
    }

    /// Returns the job ID for a future job from a template ID, if any.
    pub fn get_future_job_id_from_template_id(&self, template_id: u64) -> Option<u32> {
        self.job_store
            .get_future_job_id_from_template_id(template_id)
    }

    /// Returns an owned copy of a future job from its job ID, if any.
    pub fn get_future_job(&self, job_id: u32) -> Option<ExtendedJob<'a>> {
        // cloning happens inside the job store
        self.job_store.get_future_job(job_id)
    }

    /// Updates the group channel state with a new template.
    ///
    /// If the template is a future template, the chain tip is not used.
    /// If the template is not a future template, the chain tip must be set.
    /// Returns an error if a non-future job cannot be created due to missing chain tip.
    pub fn on_new_template(
        &mut self,
        template: NewTemplate<'a>,
        coinbase_reward_outputs: Vec<TxOut>,
    ) -> Result<(), GroupChannelError> {
        match template.future_template {
            true => {
                let new_job = self
                    .job_factory
                    .new_extended_job(
                        self.group_channel_id,
                        None,
                        vec![], /* empty extranonce prefix, as it will be replaced by the
                                 * channel's extranonce prefix */
                        template.clone(),
                        coinbase_reward_outputs,
                        self.full_extranonce_size,
                    )
                    .map_err(GroupChannelError::JobFactoryError)?;
                self.job_store.add_future_job(template.template_id, new_job);
            }
            false => {
                match self.chain_tip.clone() {
                    // we can only create non-future jobs if we have a chain tip
                    None => return Err(GroupChannelError::ChainTipNotSet),
                    Some(chain_tip) => {
                        let new_job = self
                            .job_factory
                            .new_extended_job(
                                self.group_channel_id,
                                Some(chain_tip),
                                vec![], /* empty extranonce prefix, as it will be replaced by
                                         * the channel's extranonce prefix */
                                template.clone(),
                                coinbase_reward_outputs,
                                self.full_extranonce_size,
                            )
                            .map_err(GroupChannelError::JobFactoryError)?;
                        self.job_store.add_active_job(new_job);
                    }
                }
            }
        }
        Ok(())
    }

    /// Updates the group channel state with a new [`SetNewPrevHash`](SetNewPrevHashTdp) message
    /// (Template Distribution Protocol variant).
    ///
    /// If there is a future job matching the `template_id` specified in `SetNewPrevHash`,
    /// this future job is "activated" and set as the active job.
    ///
    /// Updates the chain tip for the group channel.
    /// Returns an error if no matching future job is found.
    pub fn on_set_new_prev_hash(
        &mut self,
        set_new_prev_hash: SetNewPrevHashTdp<'a>,
    ) -> Result<(), GroupChannelError> {
        match self.job_store.has_future_jobs() {
            false => {
                return Err(GroupChannelError::TemplateIdNotFound);
            }
            true => {
                self.job_store.activate_future_job(
                    set_new_prev_hash.template_id,
                    set_new_prev_hash.header_timestamp,
                );
            }
        }

        // update the chain tip
        self.chain_tip = Some(set_new_prev_hash.into());

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        chain_tip::ChainTip,
        server::{
            group::GroupChannel,
            jobs::job_store::{DefaultJobStore, JobStore},
        },
    };
    use binary_sv2::Sv2Option;
    use bitcoin::{transaction::TxOut, Amount, ScriptBuf};
    use mining_sv2::NewExtendedMiningJob;
    use std::{collections::HashSet, convert::TryInto};
    use template_distribution_sv2::{NewTemplate, SetNewPrevHash};

    const SATS_AVAILABLE_IN_TEMPLATE: u64 = 5000000000;

    #[test]
    fn test_future_job_activation_flow() {
        // 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 group_channel_id = 1;
        let job_store = DefaultJobStore::new();
        let full_extranonce_size = 32;
        let mut group_channel = GroupChannel::new(
            group_channel_id,
            job_store,
            full_extranonce_size,
            None,
            None,
        )
        .unwrap();

        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: SATS_AVAILABLE_IN_TEMPLATE,
            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(SATS_AVAILABLE_IN_TEMPLATE),
            script_pubkey: script,
        }];

        assert!(!group_channel.job_store.has_future_jobs());
        group_channel
            .on_new_template(template.clone(), coinbase_reward_outputs)
            .unwrap();
        assert!(group_channel.get_active_job().is_none());

        let future_job_id = group_channel
            .get_future_job_id_from_template_id(template.template_id)
            .unwrap();

        let future_job = group_channel.get_future_job(future_job_id).unwrap();

        // we know that the provided template + coinbase_reward_outputs should generate this future
        // job
        let expected_job = NewExtendedMiningJob {
            channel_id: 1,
            job_id: 1,
            min_ntime: Sv2Option::new(None),
            version: 536870912,
            version_rolling_allowed: true,
            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, 39, 82, 0, 3, 47, 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!(future_job.get_job_message(), &expected_job);

        let ntime = 1746839905;

        let set_new_prev_hash = SetNewPrevHash {
            template_id: 1,
            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(),
            header_timestamp: ntime,
            n_bits: 503543726,
            target: [
                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,
                174, 119, 3, 0, 0,
            ]
            .into(),
        };

        group_channel
            .on_set_new_prev_hash(set_new_prev_hash)
            .unwrap();

        // we just activated the only future job
        assert!(group_channel.get_active_job().is_some());

        let mut previously_future_job = future_job.clone();
        previously_future_job.activate(ntime);

        let activated_job = group_channel.get_active_job().unwrap();

        // assert that the activated job is the same as the previously future job
        assert_eq!(
            activated_job.get_job_message(),
            previously_future_job.get_job_message()
        );
    }

    #[test]
    fn test_non_future_job_creation_flow() {
        // 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 group_channel_id = 1;

        let job_store = DefaultJobStore::new();
        let full_extranonce_size = 32;
        let mut group_channel = GroupChannel::new(
            group_channel_id,
            job_store,
            full_extranonce_size,
            None,
            None,
        )
        .unwrap();

        let ntime = 1746839905;
        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,
        ]
        .into();
        let n_bits = 503543726;

        let chain_tip = ChainTip::new(prev_hash, n_bits, ntime);
        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: SATS_AVAILABLE_IN_TEMPLATE,
            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(SATS_AVAILABLE_IN_TEMPLATE),
            script_pubkey: script,
        }];

        group_channel.set_chain_tip(chain_tip);
        group_channel
            .on_new_template(template.clone(), coinbase_reward_outputs)
            .unwrap();

        let active_job = group_channel.get_active_job().unwrap();

        // we know that the provided template + coinbase_reward_outputs should generate this
        // non-future job
        let expected_job = NewExtendedMiningJob {
            channel_id: 1,
            job_id: 1,
            min_ntime: Sv2Option::new(Some(ntime)),
            version: 536870912,
            version_rolling_allowed: true,
            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, 39, 82, 0, 3, 47, 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!(active_job.get_job_message(), &expected_job);
    }

    #[test]
    fn test_coinbase_reward_outputs_sum_above_template_value() {
        // 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 group_channel_id = 1;

        let job_store = DefaultJobStore::new();
        let full_extranonce_size = 32;
        let mut group_channel = GroupChannel::new(
            group_channel_id,
            job_store,
            full_extranonce_size,
            None,
            None,
        )
        .unwrap();

        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: SATS_AVAILABLE_IN_TEMPLATE,
            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(),
        };

        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 invalid_coinbase_reward_outputs = vec![TxOut {
            value: Amount::from_sat(SATS_AVAILABLE_IN_TEMPLATE + 1), /* oops: one too many extra
                                                                      * sats */
            script_pubkey: script,
        }];

        assert!(group_channel
            .on_new_template(template.clone(), invalid_coinbase_reward_outputs)
            .is_err());

        assert!(!group_channel.job_store.has_future_jobs());
    }

    #[test]
    fn test_add_channel_id() {
        let group_channel_id = 1;
        let job_store = DefaultJobStore::new();
        let full_extranonce_size = 32;
        let mut group_channel = GroupChannel::new(
            group_channel_id,
            job_store,
            full_extranonce_size,
            None,
            None,
        )
        .unwrap();

        // add a first channel with the correct full extranonce size
        group_channel
            .add_channel_id(1, full_extranonce_size)
            .unwrap();
        assert_eq!(group_channel.get_channel_ids(), &HashSet::from([1]));
        assert_eq!(
            group_channel.get_full_extranonce_size(),
            full_extranonce_size
        );

        // add a second channel with the correct full extranonce size
        group_channel
            .add_channel_id(2, full_extranonce_size)
            .unwrap();
        assert_eq!(group_channel.get_channel_ids(), &HashSet::from([1, 2]));
        assert_eq!(
            group_channel.get_full_extranonce_size(),
            full_extranonce_size
        );

        // add a third channel with a different full extranonce size
        // this should return an error
        let new_full_extranonce_size = 24;
        assert!(group_channel
            .add_channel_id(3, new_full_extranonce_size)
            .is_err());

        // set the full extranonce size to a new value
        group_channel.set_full_extranonce_size(new_full_extranonce_size);
        assert_eq!(
            group_channel.get_full_extranonce_size(),
            new_full_extranonce_size
        );
        // all channel IDs should be cleared
        assert_eq!(group_channel.get_channel_ids(), &HashSet::new());

        // add a fourth channel with the correct full extranonce size
        group_channel
            .add_channel_id(4, new_full_extranonce_size)
            .unwrap();
        assert_eq!(group_channel.get_channel_ids(), &HashSet::from([4]));

        // add a fifth channel with the old full extranonce size
        // this should return an error because the full extranonce size is now set to 24
        assert!(group_channel.add_channel_id(5, 32).is_err());
    }
}