Skip to main content

zebra_network/protocol/external/
types.rs

1use std::{cmp::max, fmt};
2
3use zebra_chain::{
4    block,
5    parameters::{
6        Network::{self, *},
7        NetworkUpgrade::{self, *},
8    },
9};
10
11use crate::constants::{self, CURRENT_NETWORK_PROTOCOL_VERSION};
12
13#[cfg(any(test, feature = "proptest-impl"))]
14use proptest_derive::Arbitrary;
15
16/// A protocol version number.
17#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
18pub struct Version(pub u32);
19
20impl fmt::Display for Version {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22        f.write_str(&self.0.to_string())
23    }
24}
25
26impl Version {
27    /// Returns the version as a metric label if Zebra defines it, or `other` otherwise.
28    pub(crate) fn metric_label(&self) -> &'static str {
29        // Keep these labels in sync with min_specified_for_upgrade and the current version.
30        match self.0 {
31            170_002 => "170002",
32            170_003 => "170003",
33            170_005 => "170005",
34            170_006 => "170006",
35            170_007 => "170007",
36            170_008 => "170008",
37            170_009 => "170009",
38            170_010 => "170010",
39            170_011 => "170011",
40            170_012 => "170012",
41            170_013 => "170013",
42            170_050 => "170050",
43            170_100 => "170100",
44            170_110 => "170110",
45            170_120 => "170120",
46            170_130 => "170130",
47            170_140 => "170140",
48            170_150 => "170150",
49            170_160 => "170160",
50            170_180 => "170180",
51            170_190 => "170190",
52            _ => "other",
53        }
54    }
55
56    /// Returns the minimum remote node network protocol version for `network` and
57    /// `height`. Zebra disconnects from peers with lower versions.
58    ///
59    /// # Panics
60    ///
61    /// If we are incompatible with our own minimum remote protocol version.
62    pub fn min_remote_for_height(
63        network: &Network,
64        height: impl Into<Option<block::Height>>,
65    ) -> Version {
66        let height = height.into().unwrap_or(block::Height(0));
67        let min_spec = Version::min_specified_for_height(network, height);
68
69        // shut down if our own version is too old
70        assert!(
71            constants::CURRENT_NETWORK_PROTOCOL_VERSION >= min_spec,
72            "Zebra does not implement the minimum specified {:?} protocol version for {:?} at {:?}",
73            NetworkUpgrade::current(network, height),
74            network,
75            height,
76        );
77
78        max(min_spec, Version::initial_min_for_network(network))
79    }
80
81    /// Returns the minimum supported network protocol version for `network`.
82    ///
83    /// This is the minimum peer version when Zebra is significantly behind current tip:
84    /// - during the initial block download,
85    /// - after Zebra restarts, and
86    /// - after Zebra's local network is slow or shut down.
87    fn initial_min_for_network(network: &Network) -> Version {
88        *constants::INITIAL_MIN_NETWORK_PROTOCOL_VERSION
89            .get(&network.kind())
90            .expect("We always have a value for testnet or mainnet")
91    }
92
93    /// Returns the minimum specified network protocol version for `network` and
94    /// `height`.
95    ///
96    /// This is the minimum peer version when Zebra is close to the current tip.
97    fn min_specified_for_height(network: &Network, height: block::Height) -> Version {
98        let network_upgrade = NetworkUpgrade::current(network, height);
99        Version::min_specified_for_upgrade(network, network_upgrade)
100    }
101
102    /// Returns the minimum specified network protocol version for `network` and
103    /// `network_upgrade`.
104    ///
105    /// ## ZIP-253
106    ///
107    /// > Nodes compatible with a network upgrade activation MUST advertise a network protocol
108    /// > version that is greater than or equal to the MIN_NETWORK_PROTOCOL_VERSION for that
109    /// > activation.
110    ///
111    /// <https://zips.z.cash/zip-0253>
112    ///
113    /// ### Notes
114    ///
115    /// - The citation above is a generalization of a statement in ZIP-253 since that ZIP is
116    ///   concerned only with NU6 on Mainnet and Testnet.
117    pub(crate) fn min_specified_for_upgrade(
118        network: &Network,
119        network_upgrade: NetworkUpgrade,
120    ) -> Version {
121        Version(match (network, network_upgrade) {
122            (_, Genesis) | (_, BeforeOverwinter) => 170_002,
123            (Testnet(params), Overwinter) if params.is_default_testnet() => 170_003,
124            (Mainnet, Overwinter) => 170_005,
125            (Testnet(params), Sapling) if params.is_default_testnet() => 170_007,
126            (Testnet(params), Sapling) if params.is_regtest() => 170_006,
127            (Mainnet, Sapling) => 170_007,
128            (Testnet(params), Blossom) if params.is_default_testnet() || params.is_regtest() => {
129                170_008
130            }
131            (Mainnet, Blossom) => 170_009,
132            (Testnet(params), Heartwood) if params.is_default_testnet() || params.is_regtest() => {
133                170_010
134            }
135            (Mainnet, Heartwood) => 170_011,
136            (Testnet(params), Canopy) if params.is_default_testnet() || params.is_regtest() => {
137                170_012
138            }
139            (Mainnet, Canopy) => 170_013,
140            (Testnet(params), Nu5) if params.is_default_testnet() || params.is_regtest() => 170_050,
141            (Mainnet, Nu5) => 170_100,
142            (Testnet(params), Nu6) if params.is_default_testnet() || params.is_regtest() => 170_110,
143            (Mainnet, Nu6) => 170_120,
144            (Testnet(params), Nu6_1) if params.is_default_testnet() || params.is_regtest() => {
145                170_130
146            }
147            (Mainnet, Nu6_1) => 170_140,
148            (Testnet(params), Nu6_2) if params.is_default_testnet() || params.is_regtest() => {
149                170_150
150            }
151            (Mainnet, Nu6_2) => 170_150,
152            (Testnet(params), Nu6_3) if params.is_default_testnet() || params.is_regtest() => {
153                170_160
154            }
155            (Mainnet, Nu6_3) => 170_160,
156            // ZIP 204 assigns distinct Testnet and Mainnet versions from NU7 onward.
157            (Testnet(params), Nu7) if params.is_default_testnet() || params.is_regtest() => 170_180,
158            (Mainnet, Nu7) => 170_190,
159
160            // It should be fine to reject peers with earlier network protocol versions on custom testnets for now.
161            (Testnet(_), _) => CURRENT_NETWORK_PROTOCOL_VERSION.0,
162
163            #[cfg(zcash_unstable = "zfuture")]
164            (Mainnet, ZFuture) => {
165                panic!("ZFuture network upgrade should not be active on Mainnet")
166            }
167        })
168    }
169}
170
171bitflags! {
172    /// A bitflag describing services advertised by a node in the network.
173    ///
174    /// Note that bits 24-31 are reserved for temporary experiments; other
175    /// service bits should be allocated via the ZIP process.
176    #[derive(Copy, Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
177    pub struct PeerServices: u64 {
178        /// NODE_NETWORK means that the node is a full node capable of serving
179        /// blocks, as opposed to a light client that makes network requests but
180        /// does not provide network services.
181        const NODE_NETWORK = 1;
182
183        /// NODE_PRUNED means the node may have deleted historic block bodies.
184        ///
185        /// Zakura pruned nodes advertise it alongside `NODE_NETWORK` (experimental bit 25).
186        /// They don't answer `getblocks` for heights below what they keep.
187        const NODE_PRUNED = 1 << 25;
188
189        /// Support compact block relay.
190        ///
191        /// Both ends must advertise this bit, assigned by the [draft Compact Block Relay ZIP].
192        ///
193        /// [draft Compact Block Relay ZIP]: https://github.com/zcash/zips/pull/1429
194        const NODE_COMPACT_BLOCKS = 1 << 16;
195    }
196}
197
198impl PeerServices {
199    /// Returns true if these services say the peer can serve every historic block.
200    pub fn serves_full_history(&self) -> bool {
201        self.contains(PeerServices::NODE_NETWORK) && !self.contains(PeerServices::NODE_PRUNED)
202    }
203}
204
205/// A nonce used in the networking layer to identify messages.
206#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
207#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
208pub struct Nonce(pub u64);
209
210impl Default for Nonce {
211    fn default() -> Self {
212        Self(rand::random())
213    }
214}
215
216/// A random value to add to the seed value in a hash function.
217#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
218#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
219pub struct Tweak(pub u32);
220
221impl Default for Tweak {
222    fn default() -> Self {
223        Self(rand::random())
224    }
225}
226
227/// A Bloom filter consisting of a bit field of arbitrary byte-aligned
228/// size, maximum size is 36,000 bytes.
229#[derive(Clone, Debug, Eq, PartialEq)]
230#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
231pub struct Filter(pub Vec<u8>);
232
233#[cfg(test)]
234mod test;