zebra-chain 14.0.0

Core Zcash data structures
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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
//! Calculations for Block Subsidy and Funding Streams
//!
//! This module contains the consensus parameters which are required for
//! verification.
//!
//! Some consensus parameters change based on network upgrades. Each network
//! upgrade happens at a particular block height. Some parameters have a value
//! (or function) before the upgrade height, at the upgrade height, and after
//! the upgrade height. (For example, the value of the reserved field in the
//! block header during the Heartwood upgrade.)
//!
//! Typically, consensus parameters are accessed via a function that takes a
//! `Network` and `block::Height`.

pub(crate) mod constants;

mod check;
#[cfg(test)]
mod tests;

use std::{collections::HashMap, sync::LazyLock};

use crate::{
    amount::{self, Amount, NegativeAllowed, NonNegative, MAX_MONEY},
    block::{Height, HeightDiff},
    parameters::{Network, NetworkUpgrade},
    transparent,
    value_balance::ValueBalance,
};

pub use check::{miner_fees_are_valid, subsidy_is_valid, CoinbaseTransactionError};

use constants::{
    BLOSSOM_POW_TARGET_SPACING_RATIO, FUNDING_STREAM_RECEIVER_DENOMINATOR,
    FUNDING_STREAM_SPECIFICATION, LOCKBOX_SPECIFICATION, MAX_BLOCK_SUBSIDY,
    NU7_POW_TARGET_SPACING_RATIO, POST_BLOSSOM_HALVING_INTERVAL, POST_NU7_HALVING_INTERVAL,
    PRE_BLOSSOM_HALVING_INTERVAL,
};

/// The funding stream receiver categories.
#[derive(Serialize, Deserialize, Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum FundingStreamReceiver {
    /// The Electric Coin Company (Bootstrap Foundation) funding stream.
    #[serde(rename = "ECC")]
    Ecc,

    /// The Zcash Foundation funding stream.
    ZcashFoundation,

    /// The Major Grants (Zcash Community Grants) funding stream.
    MajorGrants,

    /// The deferred pool contribution, see [ZIP-1015](https://zips.z.cash/zip-1015) for more details.
    Deferred,
}

impl FundingStreamReceiver {
    /// Returns a human-readable name and a specification URL for the receiver, as described in
    /// [ZIP-1014] and [`zcashd`] before NU6. After NU6, the specification is in the [ZIP-1015].
    ///
    /// [ZIP-1014]: https://zips.z.cash/zip-1014#abstract
    /// [`zcashd`]: https://github.com/zcash/zcash/blob/3f09cfa00a3c90336580a127e0096d99e25a38d6/src/consensus/funding.cpp#L13-L32
    /// [ZIP-1015]: https://zips.z.cash/zip-1015
    pub fn info(&self, is_post_nu6: bool) -> (&'static str, &'static str) {
        if is_post_nu6 {
            (
                match self {
                    FundingStreamReceiver::Ecc => "Electric Coin Company",
                    FundingStreamReceiver::ZcashFoundation => "Zcash Foundation",
                    FundingStreamReceiver::MajorGrants => "Zcash Community Grants NU6",
                    FundingStreamReceiver::Deferred => "Lockbox NU6",
                },
                LOCKBOX_SPECIFICATION,
            )
        } else {
            (
                match self {
                    FundingStreamReceiver::Ecc => "Electric Coin Company",
                    FundingStreamReceiver::ZcashFoundation => "Zcash Foundation",
                    FundingStreamReceiver::MajorGrants => "Major Grants",
                    FundingStreamReceiver::Deferred => "Lockbox NU6",
                },
                FUNDING_STREAM_SPECIFICATION,
            )
        }
    }

    /// Returns true if this [`FundingStreamReceiver`] is [`FundingStreamReceiver::Deferred`].
    pub fn is_deferred(&self) -> bool {
        matches!(self, Self::Deferred)
    }
}

/// Funding stream recipients and height ranges.
#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct FundingStreams {
    /// Start and end Heights for funding streams
    /// as described in [protocol specification §7.10.1][7.10.1].
    ///
    /// [7.10.1]: https://zips.z.cash/protocol/protocol.pdf#zip214fundingstreams
    height_range: std::ops::Range<Height>,
    /// Funding stream recipients by [`FundingStreamReceiver`].
    recipients: HashMap<FundingStreamReceiver, FundingStreamRecipient>,
}

impl FundingStreams {
    /// Creates a new [`FundingStreams`].
    pub fn new(
        height_range: std::ops::Range<Height>,
        recipients: HashMap<FundingStreamReceiver, FundingStreamRecipient>,
    ) -> Self {
        Self {
            height_range,
            recipients,
        }
    }

    /// Creates a new empty [`FundingStreams`] representing no funding streams.
    pub fn empty() -> Self {
        Self::new(Height::MAX..Height::MAX, HashMap::new())
    }

    /// Returns height range where these [`FundingStreams`] should apply.
    pub fn height_range(&self) -> &std::ops::Range<Height> {
        &self.height_range
    }

    /// Updates the exclusive end height of a canonical funding stream.
    pub(super) fn set_end_height(&mut self, end: Height) {
        self.height_range.end = end;
    }

    /// Returns recipients of these [`FundingStreams`].
    pub fn recipients(&self) -> &HashMap<FundingStreamReceiver, FundingStreamRecipient> {
        &self.recipients
    }

    /// Returns a recipient with the provided receiver.
    pub fn recipient(&self, receiver: FundingStreamReceiver) -> Option<&FundingStreamRecipient> {
        self.recipients.get(&receiver)
    }

    /// Accepts a target number of addresses that all recipients of this funding stream
    /// except the [`FundingStreamReceiver::Deferred`] receiver should have.
    ///
    /// Extends the addresses for all funding stream recipients by repeating their
    /// existing addresses until reaching the provided target number of addresses.
    pub fn extend_recipient_addresses(&mut self, target_len: usize) {
        for (receiver, recipient) in &mut self.recipients {
            if receiver.is_deferred() {
                continue;
            }

            recipient.extend_addresses(target_len);
        }
    }
}

/// A funding stream recipient as specified in [protocol specification §7.10.1][7.10.1]
///
/// [7.10.1]: https://zips.z.cash/protocol/protocol.pdf#zip214fundingstreams
#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct FundingStreamRecipient {
    /// The numerator for each funding stream receiver category
    /// as described in [protocol specification §7.10.1][7.10.1].
    ///
    /// [7.10.1]: https://zips.z.cash/protocol/protocol.pdf#zip214fundingstreams
    numerator: u64,
    /// Addresses for the funding stream recipient
    addresses: Vec<transparent::Address>,
}

impl FundingStreamRecipient {
    /// Creates a new [`FundingStreamRecipient`].
    pub fn new<I, T>(numerator: u64, addresses: I) -> Self
    where
        T: ToString,
        I: IntoIterator<Item = T>,
    {
        Self {
            numerator,
            addresses: addresses
                .into_iter()
                .map(|addr| {
                    let addr = addr.to_string();
                    addr.parse()
                        .expect("funding stream address must deserialize")
                })
                .collect(),
        }
    }

    /// Returns the numerator for this funding stream.
    pub fn numerator(&self) -> u64 {
        self.numerator
    }

    /// Returns the receiver of this funding stream.
    pub fn addresses(&self) -> &[transparent::Address] {
        &self.addresses
    }

    /// Accepts a target number of addresses that this recipient should have.
    ///
    /// Extends the addresses for this funding stream recipient by repeating
    /// existing addresses until reaching the provided target number of addresses.
    ///
    /// # Panics
    ///
    /// If a nonzero target requires extending an empty address list.
    pub fn extend_addresses(&mut self, target_len: usize) {
        assert!(
            target_len == 0 || !self.addresses.is_empty(),
            "cannot extend addresses for empty recipient"
        );

        self.addresses = self
            .addresses
            .iter()
            .cycle()
            .take(target_len)
            .cloned()
            .collect();
    }
}

/// Functionality specific to block subsidy-related consensus rules
pub trait ParameterSubsidy {
    /// Returns the minimum height after the first halving
    /// as described in [protocol specification §7.10][7.10]
    ///
    /// [7.10]: <https://zips.z.cash/protocol/protocol.pdf#fundingstreams>
    fn height_for_first_halving(&self) -> Height;

    /// Returns the halving interval after Blossom
    fn post_blossom_halving_interval(&self) -> HeightDiff;

    /// Returns the halving interval before Blossom
    fn pre_blossom_halving_interval(&self) -> HeightDiff;

    /// Returns the halving interval after NU7.
    ///
    /// `PostNU7HalvingInterval` in [ZIP 218].
    ///
    /// [ZIP 218]: https://zips.z.cash/zip-0218
    fn post_nu7_halving_interval(&self) -> HeightDiff;

    /// Returns the NU7 activation height, if it is configured.
    fn nu7_activation_height(&self) -> Option<Height>;

    /// Returns the address change interval for funding streams
    /// as described in [protocol specification §7.10][7.10].
    ///
    /// > FSRecipientChangeInterval := PostBlossomHalvingInterval / 48
    ///
    /// [7.10]: https://zips.z.cash/protocol/protocol.pdf#zip214fundingstreams
    fn funding_stream_address_change_interval(&self) -> HeightDiff;
}

/// Network methods related to Block Subsidy and Funding Streams
impl ParameterSubsidy for Network {
    fn height_for_first_halving(&self) -> Height {
        // Derived rather than hard-coded, so that ZIP 218's stretched halving schedule applies
        // here too and this can not disagree with `halving()`.
        //
        // <https://zips.z.cash/protocol/protocol.pdf#zip214fundingstreams>
        height_for_halving(1, self).expect("the first halving height is representable")
    }

    fn post_blossom_halving_interval(&self) -> HeightDiff {
        match self {
            Network::Mainnet => POST_BLOSSOM_HALVING_INTERVAL,
            Network::Testnet(params) => params.post_blossom_halving_interval(),
        }
    }

    fn pre_blossom_halving_interval(&self) -> HeightDiff {
        match self {
            Network::Mainnet => PRE_BLOSSOM_HALVING_INTERVAL,
            Network::Testnet(params) => params.pre_blossom_halving_interval(),
        }
    }

    fn post_nu7_halving_interval(&self) -> HeightDiff {
        match self {
            Network::Mainnet => POST_NU7_HALVING_INTERVAL,
            Network::Testnet(params) => {
                params.post_blossom_halving_interval()
                    * HeightDiff::from(NU7_POW_TARGET_SPACING_RATIO)
            }
        }
    }

    fn nu7_activation_height(&self) -> Option<Height> {
        NetworkUpgrade::Nu7.activation_height(self)
    }

    fn funding_stream_address_change_interval(&self) -> HeightDiff {
        self.post_blossom_halving_interval() / 48
    }
}

/// Returns the address change period
/// as described in [protocol specification §7.10][7.10]
///
/// The result is signed, and callers only ever use the *difference* between two periods. It can
/// be negative below the first funding stream: on a configured Testnet whose upgrades are packed
/// into a few hundred blocks, ZIP 218 pushes the first halving above every height the network
/// reaches once NU7 activates before it. Clamping a negative period to zero would silently
/// collapse those differences, so the sign is preserved here and the conversion is left to the
/// callers, which know the range they are counting over.
///
/// [7.10]: https://zips.z.cash/protocol/protocol.pdf#fundingstreams
pub fn funding_stream_address_period<N: ParameterSubsidy>(
    height: Height,
    network: &N,
) -> HeightDiff {
    if let Some(nu7) = network.nu7_activation_height().filter(|&nu7| height >= nu7) {
        return nu7_funding_stream_address_period(height, nu7, network);
    }

    let height_after_first_halving = height - network.height_for_first_halving();

    (height_after_first_halving + network.post_blossom_halving_interval())
        .div_euclid(network.funding_stream_address_change_interval())
}

/// Returns the funding address period from NU7 onward, as redefined by [ZIP 207].
///
/// Pre-NU7 progress is scaled into post-NU7 blocks, preserving the partial period at activation.
/// Signed Euclidean division preserves floor rounding for accelerated custom schedules.
///
/// [ZIP 207]: https://zips.z.cash/zip-0207
fn nu7_funding_stream_address_period<N: ParameterSubsidy>(
    height: Height,
    nu7: Height,
    network: &N,
) -> HeightDiff {
    let ratio = HeightDiff::from(NU7_POW_TARGET_SPACING_RATIO);
    let pre_nu7_blocks =
        nu7 - network.height_for_first_halving() + network.post_blossom_halving_interval();
    let post_nu7_blocks = height - nu7;

    (ratio * pre_nu7_blocks + post_nu7_blocks)
        .div_euclid(ratio * network.funding_stream_address_change_interval())
}

/// Extends a canonical revision-2 funding stream to the ZIP 218 third halving.
/// A stream that expired before NU7 is not reactivated (ZIP 214 revision 3).
pub(super) fn nu7_funding_stream_end_height(original_end: Height, nu7: Option<Height>) -> Height {
    match nu7.filter(|&activation| activation < original_end) {
        Some(activation) => (activation
            + (original_end - activation) * HeightDiff::from(NU7_POW_TARGET_SPACING_RATIO))
        .expect("canonical funding stream end heights scaled by three fit in Height"),
        None => original_end,
    }
}
/// Returns the position in the address slice for each funding stream
/// as described in [protocol specification §7.10][7.10]
///
/// [7.10]: https://zips.z.cash/protocol/protocol.pdf#fundingstreams
fn funding_stream_address_index(
    height: Height,
    network: &Network,
    receiver: FundingStreamReceiver,
) -> Option<usize> {
    if receiver == FundingStreamReceiver::Deferred {
        return None;
    }

    let funding_streams = network.funding_streams(height)?;
    let num_addresses = funding_streams.recipient(receiver)?.addresses().len();

    // The two periods are only meaningful relative to each other, so the subtraction is done in
    // signed arithmetic: see `funding_stream_address_period()`.
    let index = usize::try_from(
        1 + funding_stream_address_period(height, network)
            - funding_stream_address_period(funding_streams.height_range().start, network),
    )
    .ok()?;

    assert!(index > 0 && index <= num_addresses);
    // spec formula will output an index starting at 1 but
    // Zebra indices for addresses start at zero, return converted.
    Some(index - 1)
}

/// Return the address corresponding to given height, network and funding stream receiver.
///
/// This function only returns transparent addresses, because the current Zcash funding streams
/// only use transparent addresses,
pub fn funding_stream_address(
    height: Height,
    network: &Network,
    receiver: FundingStreamReceiver,
) -> Option<&transparent::Address> {
    let index = funding_stream_address_index(height, network, receiver)?;
    let funding_streams = network.funding_streams(height)?;
    funding_streams.recipient(receiver)?.addresses().get(index)
}

/// The first block height of the halving at the provided halving index for a network.
///
/// See `Halving(height)`, as described in [protocol specification §7.8][7.8]
///
/// [7.8]: https://zips.z.cash/protocol/protocol.pdf#subsidies
pub fn height_for_halving(halving: u32, network: &Network) -> Option<Height> {
    if halving == 0 {
        return Some(Height(0));
    }

    let slow_start_shift = i64::from(network.slow_start_shift().0);
    let blossom_height = i64::from(NetworkUpgrade::Blossom.activation_height(network)?.0);
    let pre_blossom_halving_interval = network.pre_blossom_halving_interval();
    let halving_index = i64::from(halving);

    let unscaled_height = halving_index
        .checked_mul(pre_blossom_halving_interval)?
        .checked_add(slow_start_shift)?;

    let height = if unscaled_height > blossom_height {
        (unscaled_height - blossom_height)
            .checked_mul(i64::from(BLOSSOM_POW_TARGET_SPACING_RATIO))?
            .checked_add(blossom_height)?
    } else {
        unscaled_height
    };

    // ZIP 218: once NU7 is active, the blocks after its activation height are three times as
    // frequent, so the remaining blocks of this halving are stretched by the same ratio.
    let height = match NetworkUpgrade::Nu7.activation_height(network) {
        Some(nu7_height) if height > i64::from(nu7_height.0) => {
            let nu7_height = i64::from(nu7_height.0);

            (height - nu7_height)
                .checked_mul(i64::from(NU7_POW_TARGET_SPACING_RATIO))?
                .checked_add(nu7_height)?
        }
        _ => height,
    };

    let height = u32::try_from(height).ok()?;
    height.try_into().ok()
}

/// Returns the `fs.Value(height)` for each stream receiver
/// as described in [protocol specification §7.8][7.8]
///
/// [7.8]: https://zips.z.cash/protocol/protocol.pdf#subsidies
pub fn funding_stream_values(
    height: Height,
    network: &Network,
    expected_block_subsidy: Amount<NonNegative>,
) -> Result<HashMap<FundingStreamReceiver, Amount<NonNegative>>, amount::Error> {
    let mut results = HashMap::new();

    if expected_block_subsidy.is_zero() {
        return Ok(results);
    }

    if NetworkUpgrade::current(network, height) >= NetworkUpgrade::Canopy {
        let funding_streams = network.funding_streams(height);
        if let Some(funding_streams) = funding_streams {
            for (&receiver, recipient) in funding_streams.recipients() {
                // - Spec equation: `fs.value = floor(block_subsidy(height)*(fs.numerator/fs.denominator))`:
                //   https://zips.z.cash/protocol/protocol.pdf#subsidies
                // - In Rust, "integer division rounds towards zero":
                //   https://doc.rust-lang.org/stable/reference/expressions/operator-expr.html#arithmetic-and-logical-binary-operators
                //   This is the same as `floor()`, because these numbers are all positive.
                let amount_value = ((expected_block_subsidy * recipient.numerator())?
                    / FUNDING_STREAM_RECEIVER_DENOMINATOR)?;

                results.insert(receiver, amount_value);
            }
        }
    }

    Ok(results)
}

/// Block subsidy errors.
#[derive(thiserror::Error, Clone, Debug, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum SubsidyError {
    #[error("no coinbase transaction in block")]
    NoCoinbase,

    #[error("funding stream expected output not found")]
    FundingStreamNotFound,

    #[error("founders reward output not found")]
    FoundersRewardNotFound,

    #[error("one-time lockbox disbursement output not found")]
    OneTimeLockboxDisbursementNotFound,

    #[error("miner fees are invalid")]
    InvalidMinerFees,

    #[error("addition of amounts overflowed")]
    Overflow,

    #[error("subtraction of amounts underflowed")]
    Underflow,

    #[error("unsupported height")]
    UnsupportedHeight,

    #[error("{0}")]
    Other(String),

    #[error("invalid amount")]
    InvalidAmount(#[from] amount::Error),

    #[error(
        "the block subsidy at height {0:?} depends on the chain value pools after its parent block"
    )]
    ParentChainValuePoolsRequired(Height),
}

/// `INITIAL_NSM_VALUE_BALANCE` on Mainnet: the block subsidy and fees left unclaimed by coinbase
/// transactions before NU6, which seeds the NSM value balance at NU7 activation under the
/// [halving-preserving issuance ZIP][zip].
///
/// Since [ZIP 236] made claiming the full coinbase value a consensus rule, this is the fixed amount
/// `sum(ScheduledBlockSubsidy(0..=H)) - IssuedSupply(H)` for any `H` from the last pre-NU6 height
/// (2,726,399) up to NU7 activation.
///
/// Measured from the historical chain value pools at height 2,726,399.
///
/// [zip]: https://zips.z.cash/zip-0237
/// [ZIP 236]: https://zips.z.cash/zip-0236
pub const MAINNET_INITIAL_NSM_VALUE_BALANCE: u64 = 36_858_445_520;

/// The unclaimed pre-NU6 subsidy and fees on public Testnet, measured at height 2,975,999.
pub const TESTNET_INITIAL_NSM_VALUE_BALANCE: u64 = 55_768_414_957;

impl Network {
    /// `INITIAL_NSM_VALUE_BALANCE`: the NSM value balance seeded at NU7 activation under the
    /// [halving-preserving issuance ZIP][zip].
    ///
    /// Mainnet and public Testnet use their measured pre-NU6 shortfalls. Configured Testnets
    /// and Regtest can set their own value, and default to zero.
    ///
    /// [zip]: https://zips.z.cash/zip-0237
    pub fn initial_nsm_value_balance(&self) -> Amount<NonNegative> {
        match self {
            Network::Mainnet => Amount::try_from(MAINNET_INITIAL_NSM_VALUE_BALANCE)
                .expect("hard-coded initial NSM value balance should be valid"),
            Network::Testnet(params) => params.initial_nsm_value_balance(),
        }
    }

    /// The ZIP 237 reissuance height calculated from the scheduled-issuance crossover.
    ///
    /// Configured networks may explicitly override it for accelerated testing. An unscheduled
    /// NU7, or a custom schedule with no crossing before the fourth halving, returns `None`.
    pub fn nsm_reissuance_height(&self) -> Option<Height> {
        match self {
            Network::Mainnet => {
                static HEIGHT: LazyLock<Option<Height>> = LazyLock::new(|| {
                    nsm_reissuance_crossing_height(&Network::Mainnet)
                        .expect("the hard-coded Mainnet subsidy schedule is valid")
                });
                *HEIGHT
            }
            Network::Testnet(params) => params.nsm_reissuance_height(),
        }
    }
}

/// Finds ZIP 237's first strict reference-subsidy crossing after the third halving.
///
/// This depends only on the issuance schedule, never the actual reserve or transaction fees.
/// Within this halving era the reference reserve decreases and the scheduled subsidy is
/// constant (or increases during a custom slow start), so the predicate is monotonic.
pub(super) fn nsm_reissuance_crossing_height(
    network: &Network,
) -> Result<Option<Height>, SubsidyError> {
    let Some(activation) = NetworkUpgrade::Nu7.activation_height(network) else {
        return Ok(None);
    };
    let Some(third_halving) = height_for_halving(3, network) else {
        return Ok(None);
    };
    let mut low = activation.0.max(third_halving.0 + 1);
    let mut high =
        height_for_halving(4, network).map_or(Height::MAX.0, |height| height.0.saturating_sub(1));
    if low > high {
        return Ok(None);
    }
    let crossed = |height| -> Result<bool, SubsidyError> {
        let issued = cumulative_scheduled_issuance_zatoshis(Height(height - 1), network)?;
        let reserve = u64::try_from(MAX_MONEY)
            .expect("MAX_MONEY is positive")
            .saturating_sub(issued);
        let reference =
            (u128::from(reserve) * 1_375).div_ceil(u128::from(BLOCK_SUBSIDY_FRACTION_DENOMINATOR));
        Ok(reference < u128::from(u64::from(scheduled_block_subsidy(Height(height), network)?)))
    };
    if !crossed(high)? {
        return Ok(None);
    }
    while low < high {
        let middle = low + (high - low) / 2;
        if crossed(middle)? {
            high = middle;
        } else {
            low = middle + 1;
        }
    }
    Ok(Some(Height(low)))
}

/// The divisor used for halvings.
///
/// `1 << Halving(height)`, as described in [protocol specification §7.8][7.8]
///
/// [7.8]: https://zips.z.cash/protocol/protocol.pdf#subsidies
///
/// Returns `None` if the divisor would overflow a `u64`.
pub fn halving_divisor(height: Height, network: &Network) -> Option<u64> {
    // Some far-future shifts can be more than 63 bits
    1u64.checked_shl(halving(height, network))
}

/// The halving index for a block height and network.
///
/// `Halving(height)`, as described in [protocol specification §7.8][7.8]
///
/// [7.8]: https://zips.z.cash/protocol/protocol.pdf#subsidies
pub fn halving(height: Height, network: &Network) -> u32 {
    let slow_start_shift = network.slow_start_shift();
    let blossom_height = NetworkUpgrade::Blossom
        .activation_height(network)
        .expect("blossom activation height should be available");

    // `NetworkUpgrade::activation_height()` falls back to the next upgrade's height, so this is
    // `None` exactly when no upgrade from NU7 onward is scheduled on `network`.
    let nu7_height = NetworkUpgrade::Nu7.activation_height(network);

    let halving_index = if height < slow_start_shift {
        0
    } else if height < blossom_height {
        let pre_blossom_height = height - slow_start_shift;
        pre_blossom_height / network.pre_blossom_halving_interval()
    } else if nu7_height.is_none_or(|nu7_height| height < nu7_height) {
        let pre_blossom_height = blossom_height - slow_start_shift;
        let scaled_pre_blossom_height =
            pre_blossom_height * HeightDiff::from(BLOSSOM_POW_TARGET_SPACING_RATIO);

        let post_blossom_height = height - blossom_height;

        (scaled_pre_blossom_height + post_blossom_height) / network.post_blossom_halving_interval()
    } else {
        // ZIP 218 adds a third era to `Halving()`. Each era is scaled into post-NU7 blocks: a
        // pre-Blossom block is worth `BlossomPoWTargetSpacingRatio * NU7PoWTargetSpacingRatio`
        // of them, and a post-Blossom pre-NU7 block is worth `NU7PoWTargetSpacingRatio`.
        let nu7_height = nu7_height.expect("checked by the branch condition above");

        let scaled_pre_blossom_height = (blossom_height - slow_start_shift)
            * HeightDiff::from(BLOSSOM_POW_TARGET_SPACING_RATIO)
            * HeightDiff::from(NU7_POW_TARGET_SPACING_RATIO);

        let scaled_post_blossom_height =
            (nu7_height - blossom_height) * HeightDiff::from(NU7_POW_TARGET_SPACING_RATIO);

        let post_nu7_height = height - nu7_height;

        (scaled_pre_blossom_height + scaled_post_blossom_height + post_nu7_height)
            / network.post_nu7_halving_interval()
    };

    halving_index
        .try_into()
        .expect("already checked for negatives")
}

/// `10^10 * ln 2`, rounded so that Mainnet's `PostBlossomHalvingInterval` of 1,680,000 blocks
/// gives a `BLOCK_SUBSIDY_FRACTION` numerator of exactly 4126.
///
/// The [halving-preserving issuance ZIP][zip] states `BLOCK_SUBSIDY_FRACTION` as a function of the
/// halving schedule, so that the NSM value balance's half-life is one halving period whatever the
/// target spacing is. With ZIP 218's `PostNU7HalvingInterval` of 5,040,000 blocks the numerator is
/// 1375, with no separate constant.
///
/// [zip]: https://zips.z.cash/zip-0237
pub const LN2_SCALED: u64 = 6_931_680_000;

/// The denominator of `BLOCK_SUBSIDY_FRACTION` in the [halving-preserving issuance ZIP][zip].
///
/// [zip]: https://zips.z.cash/zip-0237
pub const BLOCK_SUBSIDY_FRACTION_DENOMINATOR: u64 = 10_000_000_000;

/// `HalvingInterval(height)`: the number of blocks in the halving period containing `height`.
///
/// The [halving-preserving issuance ZIP][zip] defines this as `PostNU7HalvingInterval` where
/// ZIP 218's 25-second blocks are active, and `PostBlossomHalvingInterval` otherwise.
///
/// [zip]: https://zips.z.cash/zip-0237
pub fn halving_interval(height: Height, network: &Network) -> HeightDiff {
    if NetworkUpgrade::current(network, height) >= NetworkUpgrade::Nu7 {
        network.post_nu7_halving_interval()
    } else {
        network.post_blossom_halving_interval()
    }
}

/// The numerator of `BLOCK_SUBSIDY_FRACTION(height)` on `network`:
/// `LN2_SCALED / HalvingInterval(height)`.
///
/// Over one halving period this reissues about half the NSM value balance, because
/// `(1 - ln 2 / n)^n` approaches `1/2` for large `n`.
///
/// The result is non-zero for any halving interval up to `Height::MAX`.
pub fn block_subsidy_fraction_numerator(height: Height, network: &Network) -> u64 {
    let halving_interval =
        u64::try_from(halving_interval(height, network)).expect("halving intervals are positive");

    LN2_SCALED / halving_interval
}

/// `NSMFeeContribution(height)`: the transaction fees the block at `height` removes from
/// circulation, `floor(block_miner_fees * 6 / 10)` from NU7 activation, and zero before it. This
/// is the fraction from [ZIP 235], applied the way the [NU7 deployment ZIP][nu7] specifies.
///
/// The fraction applies to the total fees in the block, so rounding favors the miner. The
/// coinbase transaction can only claim the remaining fees, and the contribution needs no
/// transaction field.
///
/// [ZIP 235]: https://zips.z.cash/zip-0235
/// [nu7]: https://github.com/zcash/zips/pull/1363
pub fn nsm_fee_contribution(
    height: Height,
    network: &Network,
    block_miner_fees: Amount<NonNegative>,
) -> Amount<NonNegative> {
    if !nsm_value_balance_is_tracked(height, network) {
        return Amount::zero();
    }

    let fees = u64::from(block_miner_fees);

    // Splitting at the divisor keeps the exact floor without overflowing `fees * 6`.
    (fees / 10 * 6 + fees % 10 * 6 / 10)
        .try_into()
        .expect("the contribution is at most the fees, which are a valid amount")
}

/// Returns `true` if the NSM value balance is tracked at `height`: from NU7 activation, per the
/// [halving-preserving issuance ZIP][zip].
///
/// [zip]: https://zips.z.cash/zip-0237
pub fn nsm_value_balance_is_tracked(height: Height, network: &Network) -> bool {
    NetworkUpgrade::Nu7
        .activation_height(network)
        .is_some_and(|activation_height| height >= activation_height)
}

/// Returns `true` if the [halving-preserving issuance ZIP][zip] reissues the NSM value balance at
/// `height`: from `DEPLOYMENT_BLOCK_HEIGHT`, which is at or after NU7 activation.
///
/// [zip]: https://zips.z.cash/zip-0237
pub fn nsm_reissuance_is_active(height: Height, network: &Network) -> bool {
    network
        .nsm_reissuance_height()
        .is_some_and(|deployment_height| height >= deployment_height)
}

/// The value the block at `height` seeds into the NSM value balance: `INITIAL_NSM_VALUE_BALANCE`
/// at the NU7 activation block, and zero otherwise.
fn nsm_seed(height: Height, network: &Network) -> Amount<NonNegative> {
    if Some(height) == NetworkUpgrade::Nu7.activation_height(network) {
        network.initial_nsm_value_balance()
    } else {
        Amount::zero()
    }
}

/// `NSMValueBalance(height - 1)`: the Network Sustainability Mechanism value balance the block at
/// `height` reissues from, where `parent_nsm_value_balance` is the balance after its parent block.
///
/// The [halving-preserving issuance ZIP][zip] defines
/// `NSMValueBalance(NU7ActivationHeight - 1)` as `INITIAL_NSM_VALUE_BALANCE`, the subsidy and fees
/// left unclaimed before NU6, so the NU7 activation block reissues from that seed.
///
/// [zip]: https://zips.z.cash/zip-0237
pub fn nsm_value_balance_before(
    height: Height,
    network: &Network,
    parent_nsm_value_balance: Amount<NonNegative>,
) -> Amount<NonNegative> {
    (parent_nsm_value_balance + nsm_seed(height, network))
        .expect("the balance is zero before NU7 activation, and the seed is zero after it")
}

/// The change the block at `height` makes to the Network Sustainability Mechanism value balance,
/// where `parent_chain_value_pools` are the chain value pools after its parent block.
///
/// The balance is credited at the NU7 activation block with `INITIAL_NSM_VALUE_BALANCE`, and
/// debited by the additional block subsidy, which is zero before `DEPLOYMENT_BLOCK_HEIGHT`. Before
/// NU7 activation the change is zero.
///
/// It is also credited with [`nsm_fee_contribution`], the part of `block_miner_fees` that ZIP 235
/// removes from circulation.
pub fn nsm_value_balance_change(
    height: Height,
    network: &Network,
    parent_chain_value_pools: ValueBalance<NonNegative>,
    block_miner_fees: Amount<NonNegative>,
) -> Result<Amount<NegativeAllowed>, amount::Error> {
    if !nsm_value_balance_is_tracked(height, network) {
        return Ok(Amount::zero());
    }

    let seed = nsm_seed(height, network).constrain::<NegativeAllowed>()?;
    let contributed =
        nsm_fee_contribution(height, network, block_miner_fees).constrain::<NegativeAllowed>()?;
    let reissued = additional_block_subsidy(
        height,
        network,
        nsm_value_balance_before(height, network, parent_chain_value_pools.nsm_amount()),
    )
    .constrain::<NegativeAllowed>()?;

    // The seed and the contribution can each be up to `MAX_MONEY`, so subtract first.
    (seed - reissued)? + contributed
}

/// `AdditionalBlockSubsidy(height)`: the block subsidy added to the scheduled block subsidy by the
/// [halving-preserving issuance ZIP][zip], `ceiling(BLOCK_SUBSIDY_FRACTION * nsm_value_balance)`
/// from `DEPLOYMENT_BLOCK_HEIGHT`, and zero before it.
///
/// [zip]: https://zips.z.cash/zip-0237
pub fn additional_block_subsidy(
    height: Height,
    network: &Network,
    nsm_value_balance: Amount<NonNegative>,
) -> Amount<NonNegative> {
    if !nsm_reissuance_is_active(height, network) {
        return Amount::zero();
    }

    let additional_block_subsidy = (u128::from(u64::from(nsm_value_balance))
        * u128::from(block_subsidy_fraction_numerator(height, network)))
    .div_ceil(u128::from(BLOCK_SUBSIDY_FRACTION_DENOMINATOR));

    u64::try_from(additional_block_subsidy)
        .ok()
        .and_then(|additional_block_subsidy| Amount::try_from(additional_block_subsidy).ok())
        .expect("BLOCK_SUBSIDY_FRACTION is less than 1, so the result is at most the balance")
}

/// `BlockSubsidy(height)` for a block whose parent block leaves `parent_chain_value_pools` in the
/// chain value pools.
///
/// From `DEPLOYMENT_BLOCK_HEIGHT`, this is
/// `ScheduledBlockSubsidy(height) + ceiling(BLOCK_SUBSIDY_FRACTION * NSMValueBalance(height - 1))`.
/// Before that, `parent_chain_value_pools` is unused and this is [`scheduled_block_subsidy`].
///
/// [zip]: https://zips.z.cash/zip-0237
pub fn block_subsidy_with_parent_pools(
    height: Height,
    net: &Network,
    parent_chain_value_pools: ValueBalance<NonNegative>,
) -> Result<Amount<NonNegative>, SubsidyError> {
    block_subsidy_with_parent_nsm_value_balance(height, net, parent_chain_value_pools.nsm_amount())
}

/// `BlockSubsidy(height)` for a block whose parent block leaves `parent_nsm_value_balance` in the
/// NSM value balance. See [`block_subsidy_with_parent_pools`].
pub fn block_subsidy_with_parent_nsm_value_balance(
    height: Height,
    net: &Network,
    parent_nsm_value_balance: Amount<NonNegative>,
) -> Result<Amount<NonNegative>, SubsidyError> {
    let scheduled_block_subsidy = scheduled_block_subsidy(height, net)?;

    if !nsm_reissuance_is_active(height, net) {
        return Ok(scheduled_block_subsidy);
    }

    let nsm_value_balance = nsm_value_balance_before(height, net, parent_nsm_value_balance);

    Ok((scheduled_block_subsidy + additional_block_subsidy(height, net, nsm_value_balance))?)
}

/// `BlockSubsidy(height)` as described in [protocol specification §7.8][7.8]
///
/// This returns [`SubsidyError::ParentChainValuePoolsRequired`] once the
/// [halving-preserving issuance ZIP][zip] reissues, because the subsidy then depends on
/// the parent block's NSM value balance. Use [`block_subsidy_with_parent_pools`] there.
///
/// [7.8]: https://zips.z.cash/protocol/protocol.pdf#subsidies
/// [zip]: https://zips.z.cash/zip-0237
pub fn block_subsidy(height: Height, net: &Network) -> Result<Amount<NonNegative>, SubsidyError> {
    if nsm_reissuance_is_active(height, net) {
        return Err(SubsidyError::ParentChainValuePoolsRequired(height));
    }

    scheduled_block_subsidy(height, net)
}

/// `ScheduledBlockSubsidy(height)`: the block subsidy under the halving schedule, as described in
/// [protocol specification §7.8][7.8] for `BlockSubsidy(height)`.
///
/// [7.8]: https://zips.z.cash/protocol/protocol.pdf#subsidies
pub fn scheduled_block_subsidy(
    height: Height,
    net: &Network,
) -> Result<Amount<NonNegative>, SubsidyError> {
    let Some(halving_div) = halving_divisor(height, net) else {
        return Ok(Amount::zero());
    };

    let slow_start_interval = net.slow_start_interval();

    // The `floor` fn used in the spec is implicit in Rust's division of primitive integer types.

    let amount = if height < slow_start_interval {
        let slow_start_rate = MAX_BLOCK_SUBSIDY / u64::from(slow_start_interval);

        if height < net.slow_start_shift() {
            slow_start_rate * u64::from(height)
        } else {
            slow_start_rate * (u64::from(height) + 1)
        }
    } else {
        // Nested integer divisions by `base_subsidy` then `halving_div` give the same result as
        // the spec's single `floor()` over their product, because both divisors are positive.
        let nu = NetworkUpgrade::current(net, height);
        let base_subsidy = if nu < NetworkUpgrade::Blossom {
            MAX_BLOCK_SUBSIDY
        } else if nu < NetworkUpgrade::Nu7 {
            MAX_BLOCK_SUBSIDY / u64::from(BLOSSOM_POW_TARGET_SPACING_RATIO)
        } else {
            // ZIP 218 divides the subsidy by a further `NU7PoWTargetSpacingRatio`, so that the
            // issuance per unit of wall clock time is unchanged by the faster block spacing.
            MAX_BLOCK_SUBSIDY
                / u64::from(BLOSSOM_POW_TARGET_SPACING_RATIO)
                / u64::from(NU7_POW_TARGET_SPACING_RATIO)
        };

        base_subsidy / halving_div
    };

    Ok(Amount::try_from(amount)?)
}

/// Cumulative scheduled issuance through `height`, including the scheduled genesis subsidy.
///
/// Slow start is summed arithmetically; later constant-subsidy ranges are bounded by spacing
/// changes and halvings. The inverse halving-height calculation is deliberately not required.
pub fn cumulative_scheduled_issuance(
    height: Height,
    network: &Network,
) -> Result<Amount<NonNegative>, SubsidyError> {
    Ok(Amount::try_from(cumulative_scheduled_issuance_zatoshis(
        height, network,
    )?)?)
}

/// Sums the schedule before applying the monetary cap, so builder validation can exclude the
/// unspendable genesis subsidy.
pub(super) fn cumulative_scheduled_issuance_zatoshis(
    height: Height,
    network: &Network,
) -> Result<u64, SubsidyError> {
    let end = u64::from(height) + 1;
    let mut slow_end = u64::from(network.slow_start_interval()).min(end);
    // The schedule stops after 64 halvings, even during slow start on custom networks.
    if slow_end > 0
        && halving_divisor(
            Height(u32::try_from(slow_end - 1).map_err(|_| SubsidyError::Overflow)?),
            network,
        )
        .is_none()
    {
        let mut low = 0;
        while low < slow_end {
            let mid = low + (slow_end - low) / 2;
            if halving_divisor(
                Height(u32::try_from(mid).map_err(|_| SubsidyError::Overflow)?),
                network,
            )
            .is_some()
            {
                low = mid + 1;
            } else {
                slow_end = mid;
            }
        }
    }
    let mut total = 0u64;
    if slow_end > 0 {
        let last = slow_end - 1;
        let shift = u64::from(network.slow_start_shift());
        total = (MAX_BLOCK_SUBSIDY / u64::from(network.slow_start_interval()))
            * (last * (last + 1) / 2 + slow_end.saturating_sub(shift));
    }

    let mut start = slow_end;
    while start < end {
        let height = Height(u32::try_from(start).map_err(|_| SubsidyError::Overflow)?);
        let subsidy = u64::from(scheduled_block_subsidy(height, network)?);
        if subsidy == 0 {
            break;
        }
        let era_end = [NetworkUpgrade::Blossom, NetworkUpgrade::Nu7]
            .into_iter()
            .filter_map(|upgrade| upgrade.activation_height(network))
            .map(u64::from)
            .filter(|&boundary| boundary > start)
            .min()
            .unwrap_or(end)
            .min(end);
        let index = halving(height, network);
        let (mut low, mut high) = (start + 1, era_end);
        while low < high {
            let mid = low + (high - low) / 2;
            if halving(
                Height(u32::try_from(mid).map_err(|_| SubsidyError::Overflow)?),
                network,
            ) == index
            {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        total = total
            .checked_add(subsidy * (low - start))
            .ok_or(SubsidyError::Overflow)?;
        start = low;
    }
    Ok(total)
}

/// `MinerSubsidy(height)` as described in [protocol specification §7.8][7.8]
///
/// [7.8]: https://zips.z.cash/protocol/protocol.pdf#subsidies
pub fn miner_subsidy(
    height: Height,
    network: &Network,
    expected_block_subsidy: Amount<NonNegative>,
) -> Result<Amount<NonNegative>, amount::Error> {
    let founders_reward = founders_reward(network, height);

    let funding_streams_sum = funding_stream_values(height, network, expected_block_subsidy)?
        .values()
        .sum::<Result<Amount<NonNegative>, _>>()?;

    expected_block_subsidy - founders_reward - funding_streams_sum
}

/// Returns the founders reward address for a given height and network as described in [§7.9].
///
/// [§7.9]: <https://zips.z.cash/protocol/protocol.pdf#foundersreward>
pub fn founders_reward_address(net: &Network, height: Height) -> Option<transparent::Address> {
    let founders_address_list = net.founder_address_list();
    let num_founder_addresses = u32::try_from(founders_address_list.len()).ok()?;
    let slow_start_shift = u32::from(net.slow_start_shift());
    let pre_blossom_halving_interval = u32::try_from(net.pre_blossom_halving_interval()).ok()?;

    let founder_address_change_interval = slow_start_shift
        .checked_add(pre_blossom_halving_interval)?
        .div_ceil(num_founder_addresses);

    let founder_address_adjusted_height =
        if NetworkUpgrade::current(net, height) < NetworkUpgrade::Blossom {
            u32::from(height)
        } else {
            NetworkUpgrade::Blossom
                .activation_height(net)
                .and_then(|h| {
                    let blossom_activation_height = u32::from(h);
                    let height = u32::from(height);

                    blossom_activation_height.checked_add(
                        height.checked_sub(blossom_activation_height)?
                            / BLOSSOM_POW_TARGET_SPACING_RATIO,
                    )
                })?
        };

    let founder_address_index =
        usize::try_from(founder_address_adjusted_height / founder_address_change_interval).ok()?;

    founders_address_list
        .get(founder_address_index)
        .and_then(|a| a.parse().ok())
}

/// `FoundersReward(height)` as described in [§7.8].
///
/// [§7.8]: <https://zips.z.cash/protocol/protocol.pdf#subsidies>
pub fn founders_reward(net: &Network, height: Height) -> Amount<NonNegative> {
    // The founders reward is 20% of the block subsidy before the first halving, and 0 afterwards.
    //
    // On custom testnets, the first halving can occur later than Canopy, which causes an
    // inconsistency in the definition of the founders reward, which should occur only before
    // Canopy, so we check if Canopy is active as well.
    if halving(height, net) < 1 && NetworkUpgrade::current(net, height) < NetworkUpgrade::Canopy {
        scheduled_block_subsidy(height, net)
            .map(|subsidy| subsidy.div_exact(5))
            .expect("block subsidy must be valid for founders rewards")
    } else {
        Amount::zero()
    }
}