zcash_protocol 0.8.0

Zcash protocol network constants and value types.
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
//! Consensus logic and parameters.

use core::cmp::{Ord, Ordering};
use core::convert::TryFrom;
use core::fmt;
use core::num::TryFromIntError;
use core::ops::{Add, Bound, RangeBounds, Sub};

#[cfg(feature = "std")]
use memuse::DynamicUsage;

use crate::constants::{mainnet, regtest, testnet};

/// A wrapper type representing blockchain heights.
///
/// Safe conversion from various integer types, as well as addition and subtraction, are provided.
/// Subtraction of block heights, and of deltas to block heights, are always saturating.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct BlockHeight(u32);

#[cfg(feature = "std")]
memuse::impl_no_dynamic_usage!(BlockHeight);

/// The height of the genesis block on a network.
pub const H0: BlockHeight = BlockHeight(0);

impl BlockHeight {
    pub const fn from_u32(v: u32) -> BlockHeight {
        BlockHeight(v)
    }

    /// Subtracts the provided value from this height, returning [`H0`] if this would result in
    /// underflow of the wrapped `u32`.
    pub fn saturating_sub(self, v: u32) -> BlockHeight {
        BlockHeight(self.0.saturating_sub(v))
    }
}

impl fmt::Display for BlockHeight {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(formatter)
    }
}

impl Ord for BlockHeight {
    fn cmp(&self, other: &Self) -> Ordering {
        self.0.cmp(&other.0)
    }
}

impl PartialOrd for BlockHeight {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl From<u32> for BlockHeight {
    fn from(value: u32) -> Self {
        BlockHeight(value)
    }
}

impl From<BlockHeight> for u32 {
    fn from(value: BlockHeight) -> u32 {
        value.0
    }
}

impl TryFrom<u64> for BlockHeight {
    type Error = core::num::TryFromIntError;

    fn try_from(value: u64) -> Result<Self, Self::Error> {
        u32::try_from(value).map(BlockHeight)
    }
}

impl From<BlockHeight> for u64 {
    fn from(value: BlockHeight) -> u64 {
        value.0 as u64
    }
}

impl TryFrom<i32> for BlockHeight {
    type Error = core::num::TryFromIntError;

    fn try_from(value: i32) -> Result<Self, Self::Error> {
        u32::try_from(value).map(BlockHeight)
    }
}

impl TryFrom<i64> for BlockHeight {
    type Error = core::num::TryFromIntError;

    fn try_from(value: i64) -> Result<Self, Self::Error> {
        u32::try_from(value).map(BlockHeight)
    }
}

impl From<BlockHeight> for i64 {
    fn from(value: BlockHeight) -> i64 {
        value.0 as i64
    }
}

impl Add<u32> for BlockHeight {
    type Output = Self;

    fn add(self, other: u32) -> Self {
        BlockHeight(self.0.saturating_add(other))
    }
}

impl Sub<u32> for BlockHeight {
    type Output = Self;

    fn sub(self, other: u32) -> Self {
        BlockHeight(self.0.saturating_sub(other))
    }
}

impl Sub<BlockHeight> for BlockHeight {
    type Output = u32;

    fn sub(self, other: BlockHeight) -> u32 {
        self.0.saturating_sub(other.0)
    }
}

/// A wrapper type the index of a transaction within a block.
///
/// Safe conversion from various integer types are provided.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TxIndex(u16);

impl From<TxIndex> for u16 {
    fn from(value: TxIndex) -> Self {
        value.0
    }
}

impl From<TxIndex> for u32 {
    fn from(value: TxIndex) -> Self {
        value.0.into()
    }
}

impl From<TxIndex> for u64 {
    fn from(value: TxIndex) -> Self {
        value.0.into()
    }
}

impl From<u16> for TxIndex {
    fn from(value: u16) -> Self {
        TxIndex(value)
    }
}

impl TryFrom<u32> for TxIndex {
    type Error = TryFromIntError;

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        Ok(TxIndex(u16::try_from(value)?))
    }
}

impl TryFrom<u64> for TxIndex {
    type Error = TryFromIntError;

    fn try_from(value: u64) -> Result<Self, Self::Error> {
        Ok(TxIndex(u16::try_from(value)?))
    }
}

impl TryFrom<usize> for TxIndex {
    type Error = TryFromIntError;

    fn try_from(value: usize) -> Result<Self, Self::Error> {
        Ok(TxIndex(u16::try_from(value)?))
    }
}

#[cfg(feature = "std")]
memuse::impl_no_dynamic_usage!(TxIndex);

/// The enumeration of known Zcash network types.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NetworkType {
    /// Zcash Mainnet.
    Main,
    /// Zcash Testnet.
    Test,
    /// Private integration / regression testing, used in `zcashd`.
    ///
    /// For some address types there is no distinction between test and regtest encodings;
    /// those will always be parsed as `Network::Test`.
    Regtest,
}

#[cfg(feature = "std")]
memuse::impl_no_dynamic_usage!(NetworkType);

pub(crate) mod private {
    pub trait Sealed {}
}

/// Constants associated with a given Zcash network.
pub trait NetworkConstants: private::Sealed + Clone {
    /// The coin type for ZEC, as defined by [SLIP 44].
    ///
    /// [SLIP 44]: https://github.com/satoshilabs/slips/blob/master/slip-0044.md
    fn coin_type(&self) -> u32;

    /// Returns the human-readable prefix for Bech32-encoded Sapling extended spending keys
    /// for the network to which this NetworkConstants value applies.
    ///
    /// Defined in [ZIP 32].
    ///
    /// [ZIP 32]: https://github.com/zcash/zips/blob/main/zips/zip-0032.rst
    fn hrp_sapling_extended_spending_key(&self) -> &'static str;

    /// Returns the human-readable prefix for Bech32-encoded Sapling extended full
    /// viewing keys for the network to which this NetworkConstants value applies.
    ///
    /// Defined in [ZIP 32].
    ///
    /// [ZIP 32]: https://github.com/zcash/zips/blob/master/zip-0032.rst
    fn hrp_sapling_extended_full_viewing_key(&self) -> &'static str;

    /// Returns the Bech32-encoded human-readable prefix for Sapling payment addresses
    /// for the network to which this NetworkConstants value applies.
    ///
    /// Defined in section 5.6.4 of the [Zcash Protocol Specification].
    ///
    /// [Zcash Protocol Specification]: https://github.com/zcash/zips/blob/main/rendered/protocol/protocol.pdf
    fn hrp_sapling_payment_address(&self) -> &'static str;

    /// Returns the human-readable prefix for Base58Check-encoded Sprout
    /// payment addresses for the network to which this NetworkConstants value
    /// applies.
    ///
    /// Defined in the [Zcash Protocol Specification section 5.6.3][sproutpaymentaddrencoding].
    ///
    /// [sproutpaymentaddrencoding]: https://zips.z.cash/protocol/protocol.pdf#sproutpaymentaddrencoding
    fn b58_sprout_address_prefix(&self) -> [u8; 2];

    /// Returns the human-readable prefix for Base58Check-encoded transparent
    /// pay-to-public-key-hash payment addresses for the network to which this NetworkConstants value
    /// applies.
    fn b58_pubkey_address_prefix(&self) -> [u8; 2];

    /// Returns the human-readable prefix for Base58Check-encoded transparent secret key for the
    /// network to which this NetworkConstants value applies.
    fn b58_secret_key_prefix(&self) -> [u8; 1];

    /// Returns the human-readable prefix for Base58Check-encoded transparent pay-to-script-hash
    /// payment addresses for the network to which this NetworkConstants value applies.
    fn b58_script_address_prefix(&self) -> [u8; 2];

    /// Returns the Bech32-encoded human-readable prefix for TEX addresses, for the
    /// network to which this `NetworkConstants` value applies.
    ///
    /// Defined in [ZIP 320].
    ///
    /// [ZIP 320]: https://zips.z.cash/zip-0320
    fn hrp_tex_address(&self) -> &'static str;

    /// The HRP for a Bech32m-encoded mainnet Unified Address.
    ///
    /// Defined in [ZIP 316][zip-0316].
    ///
    /// [zip-0316]: https://zips.z.cash/zip-0316
    fn hrp_unified_address(&self) -> &'static str;

    /// The HRP for a Bech32m-encoded mainnet Unified FVK.
    ///
    /// Defined in [ZIP 316][zip-0316].
    ///
    /// [zip-0316]: https://zips.z.cash/zip-0316
    fn hrp_unified_fvk(&self) -> &'static str;

    /// The HRP for a Bech32m-encoded mainnet Unified IVK.
    ///
    /// Defined in [ZIP 316][zip-0316].
    ///
    /// [zip-0316]: https://zips.z.cash/zip-0316
    fn hrp_unified_ivk(&self) -> &'static str;
}

impl private::Sealed for NetworkType {}

impl NetworkConstants for NetworkType {
    fn coin_type(&self) -> u32 {
        match self {
            NetworkType::Main => mainnet::COIN_TYPE,
            NetworkType::Test => testnet::COIN_TYPE,
            NetworkType::Regtest => regtest::COIN_TYPE,
        }
    }

    fn hrp_sapling_extended_spending_key(&self) -> &'static str {
        match self {
            NetworkType::Main => mainnet::HRP_SAPLING_EXTENDED_SPENDING_KEY,
            NetworkType::Test => testnet::HRP_SAPLING_EXTENDED_SPENDING_KEY,
            NetworkType::Regtest => regtest::HRP_SAPLING_EXTENDED_SPENDING_KEY,
        }
    }

    fn hrp_sapling_extended_full_viewing_key(&self) -> &'static str {
        match self {
            NetworkType::Main => mainnet::HRP_SAPLING_EXTENDED_FULL_VIEWING_KEY,
            NetworkType::Test => testnet::HRP_SAPLING_EXTENDED_FULL_VIEWING_KEY,
            NetworkType::Regtest => regtest::HRP_SAPLING_EXTENDED_FULL_VIEWING_KEY,
        }
    }

    fn hrp_sapling_payment_address(&self) -> &'static str {
        match self {
            NetworkType::Main => mainnet::HRP_SAPLING_PAYMENT_ADDRESS,
            NetworkType::Test => testnet::HRP_SAPLING_PAYMENT_ADDRESS,
            NetworkType::Regtest => regtest::HRP_SAPLING_PAYMENT_ADDRESS,
        }
    }

    fn b58_sprout_address_prefix(&self) -> [u8; 2] {
        match self {
            NetworkType::Main => mainnet::B58_SPROUT_ADDRESS_PREFIX,
            NetworkType::Test => testnet::B58_SPROUT_ADDRESS_PREFIX,
            NetworkType::Regtest => regtest::B58_SPROUT_ADDRESS_PREFIX,
        }
    }

    fn b58_pubkey_address_prefix(&self) -> [u8; 2] {
        match self {
            NetworkType::Main => mainnet::B58_PUBKEY_ADDRESS_PREFIX,
            NetworkType::Test => testnet::B58_PUBKEY_ADDRESS_PREFIX,
            NetworkType::Regtest => regtest::B58_PUBKEY_ADDRESS_PREFIX,
        }
    }

    fn b58_secret_key_prefix(&self) -> [u8; 1] {
        match self {
            NetworkType::Main => mainnet::B58_SECRET_KEY_PREFIX,
            NetworkType::Test => testnet::B58_SECRET_KEY_PREFIX,
            NetworkType::Regtest => regtest::B58_SECRET_KEY_PREFIX,
        }
    }

    fn b58_script_address_prefix(&self) -> [u8; 2] {
        match self {
            NetworkType::Main => mainnet::B58_SCRIPT_ADDRESS_PREFIX,
            NetworkType::Test => testnet::B58_SCRIPT_ADDRESS_PREFIX,
            NetworkType::Regtest => regtest::B58_SCRIPT_ADDRESS_PREFIX,
        }
    }

    fn hrp_tex_address(&self) -> &'static str {
        match self {
            NetworkType::Main => mainnet::HRP_TEX_ADDRESS,
            NetworkType::Test => testnet::HRP_TEX_ADDRESS,
            NetworkType::Regtest => regtest::HRP_TEX_ADDRESS,
        }
    }

    fn hrp_unified_address(&self) -> &'static str {
        match self {
            NetworkType::Main => mainnet::HRP_UNIFIED_ADDRESS,
            NetworkType::Test => testnet::HRP_UNIFIED_ADDRESS,
            NetworkType::Regtest => regtest::HRP_UNIFIED_ADDRESS,
        }
    }

    fn hrp_unified_fvk(&self) -> &'static str {
        match self {
            NetworkType::Main => mainnet::HRP_UNIFIED_FVK,
            NetworkType::Test => testnet::HRP_UNIFIED_FVK,
            NetworkType::Regtest => regtest::HRP_UNIFIED_FVK,
        }
    }

    fn hrp_unified_ivk(&self) -> &'static str {
        match self {
            NetworkType::Main => mainnet::HRP_UNIFIED_IVK,
            NetworkType::Test => testnet::HRP_UNIFIED_IVK,
            NetworkType::Regtest => regtest::HRP_UNIFIED_IVK,
        }
    }
}

/// Zcash consensus parameters.
pub trait Parameters: Clone {
    /// Returns the type of network configured by this set of consensus parameters.
    fn network_type(&self) -> NetworkType;

    /// Returns the activation height for a particular network upgrade,
    /// if an activation height has been set.
    fn activation_height(&self, nu: NetworkUpgrade) -> Option<BlockHeight>;

    /// Determines whether the specified network upgrade is active as of the
    /// provided block height on the network to which this Parameters value applies.
    fn is_nu_active(&self, nu: NetworkUpgrade, height: BlockHeight) -> bool {
        self.activation_height(nu).is_some_and(|h| h <= height)
    }
}

impl<P: Parameters> Parameters for &P {
    fn network_type(&self) -> NetworkType {
        (*self).network_type()
    }

    fn activation_height(&self, nu: NetworkUpgrade) -> Option<BlockHeight> {
        (*self).activation_height(nu)
    }
}

impl<P: Parameters> private::Sealed for P {}

impl<P: Parameters> NetworkConstants for P {
    fn coin_type(&self) -> u32 {
        self.network_type().coin_type()
    }

    fn hrp_sapling_extended_spending_key(&self) -> &'static str {
        self.network_type().hrp_sapling_extended_spending_key()
    }

    fn hrp_sapling_extended_full_viewing_key(&self) -> &'static str {
        self.network_type().hrp_sapling_extended_full_viewing_key()
    }

    fn hrp_sapling_payment_address(&self) -> &'static str {
        self.network_type().hrp_sapling_payment_address()
    }

    fn b58_sprout_address_prefix(&self) -> [u8; 2] {
        self.network_type().b58_sprout_address_prefix()
    }

    fn b58_pubkey_address_prefix(&self) -> [u8; 2] {
        self.network_type().b58_pubkey_address_prefix()
    }

    fn b58_secret_key_prefix(&self) -> [u8; 1] {
        self.network_type().b58_secret_key_prefix()
    }

    fn b58_script_address_prefix(&self) -> [u8; 2] {
        self.network_type().b58_script_address_prefix()
    }

    fn hrp_tex_address(&self) -> &'static str {
        self.network_type().hrp_tex_address()
    }

    fn hrp_unified_address(&self) -> &'static str {
        self.network_type().hrp_unified_address()
    }

    fn hrp_unified_fvk(&self) -> &'static str {
        self.network_type().hrp_unified_fvk()
    }

    fn hrp_unified_ivk(&self) -> &'static str {
        self.network_type().hrp_unified_ivk()
    }
}

/// Marker struct for the production network.
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub struct MainNetwork;

#[cfg(feature = "std")]
memuse::impl_no_dynamic_usage!(MainNetwork);

/// The production network.
pub const MAIN_NETWORK: MainNetwork = MainNetwork;

impl Parameters for MainNetwork {
    fn network_type(&self) -> NetworkType {
        NetworkType::Main
    }

    fn activation_height(&self, nu: NetworkUpgrade) -> Option<BlockHeight> {
        match nu {
            NetworkUpgrade::Overwinter => Some(BlockHeight(347_500)),
            NetworkUpgrade::Sapling => Some(BlockHeight(419_200)),
            NetworkUpgrade::Blossom => Some(BlockHeight(653_600)),
            NetworkUpgrade::Heartwood => Some(BlockHeight(903_000)),
            NetworkUpgrade::Canopy => Some(BlockHeight(1_046_400)),
            NetworkUpgrade::Nu5 => Some(BlockHeight(1_687_104)),
            NetworkUpgrade::Nu6 => Some(BlockHeight(2_726_400)),
            NetworkUpgrade::Nu6_1 => Some(BlockHeight(3_146_400)),
            #[cfg(zcash_unstable = "nu7")]
            NetworkUpgrade::Nu7 => None,
            #[cfg(zcash_unstable = "zfuture")]
            NetworkUpgrade::ZFuture => None,
        }
    }
}

/// Marker struct for the test network.
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub struct TestNetwork;

#[cfg(feature = "std")]
memuse::impl_no_dynamic_usage!(TestNetwork);

/// The test network.
pub const TEST_NETWORK: TestNetwork = TestNetwork;

impl Parameters for TestNetwork {
    fn network_type(&self) -> NetworkType {
        NetworkType::Test
    }

    fn activation_height(&self, nu: NetworkUpgrade) -> Option<BlockHeight> {
        match nu {
            NetworkUpgrade::Overwinter => Some(BlockHeight(207_500)),
            NetworkUpgrade::Sapling => Some(BlockHeight(280_000)),
            NetworkUpgrade::Blossom => Some(BlockHeight(584_000)),
            NetworkUpgrade::Heartwood => Some(BlockHeight(903_800)),
            NetworkUpgrade::Canopy => Some(BlockHeight(1_028_500)),
            NetworkUpgrade::Nu5 => Some(BlockHeight(1_842_420)),
            NetworkUpgrade::Nu6 => Some(BlockHeight(2_976_000)),
            NetworkUpgrade::Nu6_1 => Some(BlockHeight(3_536_500)),
            #[cfg(zcash_unstable = "nu7")]
            NetworkUpgrade::Nu7 => None,
            #[cfg(zcash_unstable = "zfuture")]
            NetworkUpgrade::ZFuture => None,
        }
    }
}

/// The enumeration of known Zcash networks.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Network {
    /// Zcash Mainnet.
    MainNetwork,
    /// Zcash Testnet.
    TestNetwork,
}

#[cfg(feature = "std")]
memuse::impl_no_dynamic_usage!(Network);

impl Parameters for Network {
    fn network_type(&self) -> NetworkType {
        match self {
            Network::MainNetwork => NetworkType::Main,
            Network::TestNetwork => NetworkType::Test,
        }
    }

    fn activation_height(&self, nu: NetworkUpgrade) -> Option<BlockHeight> {
        match self {
            Network::MainNetwork => MAIN_NETWORK.activation_height(nu),
            Network::TestNetwork => TEST_NETWORK.activation_height(nu),
        }
    }
}

/// An event that occurs at a specified height on the Zcash chain, at which point the
/// consensus rules enforced by the network are altered.
///
/// See [ZIP 200](https://zips.z.cash/zip-0200) for more details.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NetworkUpgrade {
    /// The [Overwinter] network upgrade.
    ///
    /// [Overwinter]: https://z.cash/upgrade/overwinter/
    Overwinter,
    /// The [Sapling] network upgrade.
    ///
    /// [Sapling]: https://z.cash/upgrade/sapling/
    Sapling,
    /// The [Blossom] network upgrade.
    ///
    /// [Blossom]: https://z.cash/upgrade/blossom/
    Blossom,
    /// The [Heartwood] network upgrade.
    ///
    /// [Heartwood]: https://z.cash/upgrade/heartwood/
    Heartwood,
    /// The [Canopy] network upgrade.
    ///
    /// [Canopy]: https://z.cash/upgrade/canopy/
    Canopy,
    /// The [Nu5] network upgrade.
    ///
    /// [Nu5]: https://z.cash/upgrade/nu5/
    Nu5,
    /// The [Nu6] network upgrade.
    ///
    /// [Nu6]: https://z.cash/upgrade/nu6/
    Nu6,
    /// The [Nu6.1] network upgrade.
    ///
    /// [Nu6.1]: https://z.cash/upgrade/nu6.1/
    Nu6_1,
    /// The [Nu7 (proposed)] network upgrade.
    ///
    /// [Nu7 (proposed)]: https://z.cash/upgrade/nu7/
    #[cfg(zcash_unstable = "nu7")]
    Nu7,
    /// The ZFUTURE network upgrade.
    ///
    /// This upgrade is expected never to activate on mainnet;
    /// it is intended for use in integration testing of functionality
    /// that is a candidate for integration in a future network upgrade.
    #[cfg(zcash_unstable = "zfuture")]
    ZFuture,
}

#[cfg(feature = "std")]
memuse::impl_no_dynamic_usage!(NetworkUpgrade);

impl fmt::Display for NetworkUpgrade {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            NetworkUpgrade::Overwinter => write!(f, "Overwinter"),
            NetworkUpgrade::Sapling => write!(f, "Sapling"),
            NetworkUpgrade::Blossom => write!(f, "Blossom"),
            NetworkUpgrade::Heartwood => write!(f, "Heartwood"),
            NetworkUpgrade::Canopy => write!(f, "Canopy"),
            NetworkUpgrade::Nu5 => write!(f, "Nu5"),
            NetworkUpgrade::Nu6 => write!(f, "Nu6"),
            NetworkUpgrade::Nu6_1 => write!(f, "Nu6.1"),
            #[cfg(zcash_unstable = "nu7")]
            NetworkUpgrade::Nu7 => write!(f, "Nu7"),
            #[cfg(zcash_unstable = "zfuture")]
            NetworkUpgrade::ZFuture => write!(f, "ZFUTURE"),
        }
    }
}

impl NetworkUpgrade {
    fn branch_id(self) -> BranchId {
        match self {
            NetworkUpgrade::Overwinter => BranchId::Overwinter,
            NetworkUpgrade::Sapling => BranchId::Sapling,
            NetworkUpgrade::Blossom => BranchId::Blossom,
            NetworkUpgrade::Heartwood => BranchId::Heartwood,
            NetworkUpgrade::Canopy => BranchId::Canopy,
            NetworkUpgrade::Nu5 => BranchId::Nu5,
            NetworkUpgrade::Nu6 => BranchId::Nu6,
            NetworkUpgrade::Nu6_1 => BranchId::Nu6_1,
            #[cfg(zcash_unstable = "nu7")]
            NetworkUpgrade::Nu7 => BranchId::Nu7,
            #[cfg(zcash_unstable = "zfuture")]
            NetworkUpgrade::ZFuture => BranchId::ZFuture,
        }
    }
}

/// The network upgrades on the Zcash chain in order of activation.
///
/// This order corresponds to the activation heights, but because Rust enums are
/// full-fledged algebraic data types, we need to define it manually.
const UPGRADES_IN_ORDER: &[NetworkUpgrade] = &[
    NetworkUpgrade::Overwinter,
    NetworkUpgrade::Sapling,
    NetworkUpgrade::Blossom,
    NetworkUpgrade::Heartwood,
    NetworkUpgrade::Canopy,
    NetworkUpgrade::Nu5,
    NetworkUpgrade::Nu6,
    NetworkUpgrade::Nu6_1,
    #[cfg(zcash_unstable = "nu7")]
    NetworkUpgrade::Nu7,
];

/// The "grace period" defined in [ZIP 212].
///
/// [ZIP 212]: https://zips.z.cash/zip-0212#changes-to-the-process-of-receiving-sapling-or-orchard-notes
pub const ZIP212_GRACE_PERIOD: u32 = 32256;

/// The number of blocks after which a coinbase output is considered mature and spendable.
///
/// From [§ 7.1.2 of the Zcash Protocol Specification][txnconsensus]:
/// > A transaction MUST NOT spend a transparent output of a coinbase transaction from a
/// > block less than 100 blocks prior to the spend.
///
/// [txnconsensus]: https://zips.z.cash/protocol/protocol.pdf#txnconsensus
pub const COINBASE_MATURITY_BLOCKS: u32 = 100;

/// A globally-unique identifier for a set of consensus rules within the Zcash chain.
///
/// Each branch ID in this enum corresponds to one of the epochs between a pair of Zcash
/// network upgrades. For example, `BranchId::Overwinter` corresponds to the blocks
/// starting at Overwinter activation, and ending the block before Sapling activation.
///
/// The main use of the branch ID is in signature generation: transactions commit to a
/// specific branch ID by including it as part of [`signature_hash`]. This ensures
/// two-way replay protection for transactions across network upgrades.
///
/// See [ZIP 200](https://zips.z.cash/zip-0200) for more details.
///
/// [`signature_hash`]: https://docs.rs/zcash_primitives/latest/zcash_primitives/transaction/sighash/fn.signature_hash.html
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BranchId {
    /// The consensus rules at the launch of Zcash.
    Sprout,
    /// The consensus rules deployed by [`NetworkUpgrade::Overwinter`].
    Overwinter,
    /// The consensus rules deployed by [`NetworkUpgrade::Sapling`].
    Sapling,
    /// The consensus rules deployed by [`NetworkUpgrade::Blossom`].
    Blossom,
    /// The consensus rules deployed by [`NetworkUpgrade::Heartwood`].
    Heartwood,
    /// The consensus rules deployed by [`NetworkUpgrade::Canopy`].
    Canopy,
    /// The consensus rules deployed by [`NetworkUpgrade::Nu5`].
    Nu5,
    /// The consensus rules deployed by [`NetworkUpgrade::Nu6`].
    Nu6,
    /// The consensus rules deployed by [`NetworkUpgrade::Nu6_1`].
    Nu6_1,
    /// The consensus rules to be deployed by [`NetworkUpgrade::Nu7`].
    #[cfg(zcash_unstable = "nu7")]
    Nu7,
    /// Candidates for future consensus rules; this branch will never
    /// activate on mainnet.
    #[cfg(zcash_unstable = "zfuture")]
    ZFuture,
}

#[cfg(feature = "std")]
memuse::impl_no_dynamic_usage!(BranchId);

impl TryFrom<u32> for BranchId {
    type Error = &'static str;

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(BranchId::Sprout),
            0x5ba8_1b19 => Ok(BranchId::Overwinter),
            0x76b8_09bb => Ok(BranchId::Sapling),
            0x2bb4_0e60 => Ok(BranchId::Blossom),
            0xf5b9_230b => Ok(BranchId::Heartwood),
            0xe9ff_75a6 => Ok(BranchId::Canopy),
            0xc2d6_d0b4 => Ok(BranchId::Nu5),
            0xc8e7_1055 => Ok(BranchId::Nu6),
            0x4dec_4df0 => Ok(BranchId::Nu6_1),
            #[cfg(zcash_unstable = "nu7")]
            0xffff_ffff => Ok(BranchId::Nu7),
            #[cfg(zcash_unstable = "zfuture")]
            0xffff_ffff => Ok(BranchId::ZFuture),
            _ => Err("Unknown consensus branch ID"),
        }
    }
}

impl From<BranchId> for u32 {
    fn from(consensus_branch_id: BranchId) -> u32 {
        match consensus_branch_id {
            BranchId::Sprout => 0,
            BranchId::Overwinter => 0x5ba8_1b19,
            BranchId::Sapling => 0x76b8_09bb,
            BranchId::Blossom => 0x2bb4_0e60,
            BranchId::Heartwood => 0xf5b9_230b,
            BranchId::Canopy => 0xe9ff_75a6,
            BranchId::Nu5 => 0xc2d6_d0b4,
            BranchId::Nu6 => 0xc8e7_1055,
            BranchId::Nu6_1 => 0x4dec_4df0,
            #[cfg(zcash_unstable = "nu7")]
            BranchId::Nu7 => 0xffff_ffff,
            #[cfg(zcash_unstable = "zfuture")]
            BranchId::ZFuture => 0xffff_ffff,
        }
    }
}

impl BranchId {
    /// Returns the branch ID corresponding to the consensus rule set that is active at
    /// the given height.
    ///
    /// This is the branch ID that should be used when creating transactions.
    pub fn for_height<P: Parameters>(parameters: &P, height: BlockHeight) -> Self {
        for nu in UPGRADES_IN_ORDER.iter().rev() {
            if parameters.is_nu_active(*nu, height) {
                return nu.branch_id();
            }
        }

        // Sprout rules apply before any network upgrade
        BranchId::Sprout
    }

    /// Returns the range of heights for the consensus epoch associated with this branch id.
    ///
    /// The resulting tuple implements the [`RangeBounds<BlockHeight>`] trait.
    pub fn height_range<P: Parameters>(&self, params: &P) -> Option<impl RangeBounds<BlockHeight>> {
        self.height_bounds(params).map(|(lower, upper)| {
            (
                Bound::Included(lower),
                upper.map_or(Bound::Unbounded, Bound::Excluded),
            )
        })
    }

    /// Returns the range of heights for the consensus epoch associated with this branch id.
    ///
    /// The return type of this value is slightly more precise than [`Self::height_range`]:
    /// - `Some((x, Some(y)))` means that the consensus rules corresponding to this branch id
    ///   are in effect for the range `x..y`
    /// - `Some((x, None))` means that the consensus rules corresponding to this branch id are
    ///   in effect for the range `x..`
    /// - `None` means that the consensus rules corresponding to this branch id are never in effect.
    pub fn height_bounds<P: Parameters>(
        &self,
        params: &P,
    ) -> Option<(BlockHeight, Option<BlockHeight>)> {
        match self {
            BranchId::Sprout => params
                .activation_height(NetworkUpgrade::Overwinter)
                .map(|upper| (BlockHeight(0), Some(upper))),
            BranchId::Overwinter => params
                .activation_height(NetworkUpgrade::Overwinter)
                .map(|lower| (lower, params.activation_height(NetworkUpgrade::Sapling))),
            BranchId::Sapling => params
                .activation_height(NetworkUpgrade::Sapling)
                .map(|lower| (lower, params.activation_height(NetworkUpgrade::Blossom))),
            BranchId::Blossom => params
                .activation_height(NetworkUpgrade::Blossom)
                .map(|lower| (lower, params.activation_height(NetworkUpgrade::Heartwood))),
            BranchId::Heartwood => params
                .activation_height(NetworkUpgrade::Heartwood)
                .map(|lower| (lower, params.activation_height(NetworkUpgrade::Canopy))),
            BranchId::Canopy => params
                .activation_height(NetworkUpgrade::Canopy)
                .map(|lower| (lower, params.activation_height(NetworkUpgrade::Nu5))),
            BranchId::Nu5 => params
                .activation_height(NetworkUpgrade::Nu5)
                .map(|lower| (lower, params.activation_height(NetworkUpgrade::Nu6))),
            BranchId::Nu6 => params
                .activation_height(NetworkUpgrade::Nu6)
                .map(|lower| (lower, params.activation_height(NetworkUpgrade::Nu6_1))),
            BranchId::Nu6_1 => params
                .activation_height(NetworkUpgrade::Nu6_1)
                .map(|lower| {
                    #[cfg(zcash_unstable = "nu7")]
                    let upper = params.activation_height(NetworkUpgrade::Nu7);
                    #[cfg(zcash_unstable = "zfuture")]
                    let upper = params.activation_height(NetworkUpgrade::ZFuture);
                    #[cfg(not(any(zcash_unstable = "nu7", zcash_unstable = "zfuture")))]
                    let upper = None;
                    (lower, upper)
                }),
            #[cfg(zcash_unstable = "nu7")]
            BranchId::Nu7 => params
                .activation_height(NetworkUpgrade::Nu7)
                .map(|lower| (lower, None)),
            #[cfg(zcash_unstable = "zfuture")]
            BranchId::ZFuture => params
                .activation_height(NetworkUpgrade::ZFuture)
                .map(|lower| (lower, None)),
        }
    }

    pub fn sprout_uses_groth_proofs(&self) -> bool {
        !matches!(self, BranchId::Sprout | BranchId::Overwinter)
    }

    // Returns `true` for consensus branches that support the Sprout protocol, `false` otherwise..
    pub fn has_sprout(&self) -> bool {
        use BranchId::*;
        match self {
            Sprout | Overwinter | Sapling | Blossom | Heartwood | Canopy | Nu5 | Nu6 | Nu6_1 => {
                true
            }
            #[cfg(zcash_unstable = "nu7")]
            BranchId::Nu7 => false,
            #[cfg(zcash_unstable = "zfuture")]
            BranchId::ZFuture => false,
        }
    }

    // Returns `true` for consensus branches that support the Sapling protocol, `false` otherwise..
    pub fn has_sapling(&self) -> bool {
        use BranchId::*;
        match self {
            Sprout | Overwinter => false,
            Sapling | Blossom | Heartwood | Canopy | Nu5 | Nu6 | Nu6_1 => true,
            #[cfg(zcash_unstable = "nu7")]
            BranchId::Nu7 => true,
            #[cfg(zcash_unstable = "zfuture")]
            BranchId::ZFuture => true,
        }
    }

    // Returns `true` for consensus branches that support the Orchard protocol, `false` otherwise.
    pub fn has_orchard(&self) -> bool {
        use BranchId::*;
        match self {
            Sprout | Overwinter | Sapling | Blossom | Heartwood | Canopy => false,
            Nu5 | Nu6 | Nu6_1 => true,
            #[cfg(zcash_unstable = "nu7")]
            BranchId::Nu7 => true,
            #[cfg(zcash_unstable = "zfuture")]
            BranchId::ZFuture => true,
        }
    }
}

#[cfg(any(test, feature = "test-dependencies"))]
pub mod testing {
    use proptest::sample::select;
    use proptest::strategy::{Just, Strategy};

    use super::{BlockHeight, BranchId, Parameters};

    pub fn arb_branch_id() -> impl Strategy<Value = BranchId> {
        select(vec![
            BranchId::Sprout,
            BranchId::Overwinter,
            BranchId::Sapling,
            BranchId::Blossom,
            BranchId::Heartwood,
            BranchId::Canopy,
            BranchId::Nu5,
            BranchId::Nu6,
            BranchId::Nu6_1,
            #[cfg(zcash_unstable = "nu7")]
            BranchId::Nu7,
            #[cfg(zcash_unstable = "zfuture")]
            BranchId::ZFuture,
        ])
    }

    pub fn arb_height<P: Parameters>(
        branch_id: BranchId,
        params: &P,
    ) -> impl Strategy<Value = Option<BlockHeight>> {
        branch_id
            .height_bounds(params)
            .map_or(Strategy::boxed(Just(None)), |(lower, upper)| {
                Strategy::boxed(
                    (lower.0..upper.map_or(u32::MAX, |u| u.0)).prop_map(|h| Some(BlockHeight(h))),
                )
            })
    }

    #[cfg(feature = "test-dependencies")]
    impl incrementalmerkletree_testing::TestCheckpoint for BlockHeight {
        fn from_u64(value: u64) -> Self {
            BlockHeight(u32::try_from(value).expect("Test checkpoint ids do not exceed 32 bits"))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        BlockHeight, BranchId, MAIN_NETWORK, NetworkUpgrade, Parameters, UPGRADES_IN_ORDER,
    };

    #[test]
    fn nu_ordering() {
        for i in 1..UPGRADES_IN_ORDER.len() {
            let nu_a = UPGRADES_IN_ORDER[i - 1];
            let nu_b = UPGRADES_IN_ORDER[i];
            match (
                MAIN_NETWORK.activation_height(nu_a),
                MAIN_NETWORK.activation_height(nu_b),
            ) {
                (Some(a), Some(b)) if a < b => (),
                (Some(_), None) => (),
                (None, None) => (),
                _ => panic!(
                    "{} should not be before {} in UPGRADES_IN_ORDER",
                    nu_a, nu_b
                ),
            }
        }
    }

    #[test]
    fn nu_is_active() {
        assert!(!MAIN_NETWORK.is_nu_active(NetworkUpgrade::Overwinter, BlockHeight(0)));
        assert!(!MAIN_NETWORK.is_nu_active(NetworkUpgrade::Overwinter, BlockHeight(347_499)));
        assert!(MAIN_NETWORK.is_nu_active(NetworkUpgrade::Overwinter, BlockHeight(347_500)));
    }

    #[test]
    fn branch_id_from_u32() {
        assert_eq!(BranchId::try_from(0), Ok(BranchId::Sprout));
        assert!(BranchId::try_from(1).is_err());
    }

    #[test]
    fn branch_id_for_height() {
        assert_eq!(
            BranchId::for_height(&MAIN_NETWORK, BlockHeight(0)),
            BranchId::Sprout,
        );
        assert_eq!(
            BranchId::for_height(&MAIN_NETWORK, BlockHeight(419_199)),
            BranchId::Overwinter,
        );
        assert_eq!(
            BranchId::for_height(&MAIN_NETWORK, BlockHeight(419_200)),
            BranchId::Sapling,
        );
        assert_eq!(
            BranchId::for_height(&MAIN_NETWORK, BlockHeight(903_000)),
            BranchId::Heartwood,
        );
        assert_eq!(
            BranchId::for_height(&MAIN_NETWORK, BlockHeight(1_046_400)),
            BranchId::Canopy,
        );
        assert_eq!(
            BranchId::for_height(&MAIN_NETWORK, BlockHeight(1_687_104)),
            BranchId::Nu5,
        );
        assert_eq!(
            BranchId::for_height(&MAIN_NETWORK, BlockHeight(2_726_399)),
            BranchId::Nu5,
        );
        assert_eq!(
            BranchId::for_height(&MAIN_NETWORK, BlockHeight(2_726_400)),
            BranchId::Nu6,
        );
        assert_eq!(
            BranchId::for_height(&MAIN_NETWORK, BlockHeight(3_146_400)),
            BranchId::Nu6_1,
        );
        assert_eq!(
            BranchId::for_height(&MAIN_NETWORK, BlockHeight(5_000_000)),
            BranchId::Nu6_1,
        );
    }
}