zebra_chain/work/
equihash.rs

1//! Equihash Solution and related items.
2
3use std::{fmt, io};
4
5use hex::ToHex;
6use serde_big_array::BigArray;
7
8use crate::{
9    block::Header,
10    serialization::{
11        zcash_serialize_bytes, SerializationError, ZcashDeserialize, ZcashDeserializeInto,
12        ZcashSerialize,
13    },
14};
15
16#[cfg(feature = "internal-miner")]
17use crate::serialization::AtLeastOne;
18
19/// The error type for Equihash validation.
20#[non_exhaustive]
21#[derive(Debug, thiserror::Error)]
22#[error("invalid equihash solution for BlockHeader")]
23pub struct Error(#[from] equihash::Error);
24
25/// The error type for Equihash solving.
26#[derive(Copy, Clone, Debug, Eq, PartialEq, thiserror::Error)]
27#[error("solver was cancelled")]
28pub struct SolverCancelled;
29
30/// The size of an Equihash solution in bytes (always 1344).
31pub(crate) const SOLUTION_SIZE: usize = 1344;
32
33/// The size of an Equihash solution in bytes on Regtest (always 36).
34pub(crate) const REGTEST_SOLUTION_SIZE: usize = 36;
35
36/// Equihash Solution in compressed format.
37///
38/// A wrapper around `[u8; n]` where `n` is the solution size because
39/// Rust doesn't implement common traits like `Debug`, `Clone`, etc.
40/// for collections like arrays beyond lengths 0 to 32.
41///
42/// The size of an Equihash solution in bytes is always 1344 on Mainnet and Testnet, and
43/// is always 36 on Regtest so the length of this type is fixed.
44#[derive(Deserialize, Serialize)]
45// It's okay to use the extra space on Regtest
46#[allow(clippy::large_enum_variant)]
47pub enum Solution {
48    /// Equihash solution on Mainnet or Testnet
49    Common(#[serde(with = "BigArray")] [u8; SOLUTION_SIZE]),
50    /// Equihash solution on Regtest
51    Regtest(#[serde(with = "BigArray")] [u8; REGTEST_SOLUTION_SIZE]),
52}
53
54impl Solution {
55    /// The length of the portion of the header used as input when verifying
56    /// equihash solutions, in bytes.
57    ///
58    /// Excludes the 32-byte nonce, which is passed as a separate argument
59    /// to the verification function.
60    pub const INPUT_LENGTH: usize = 4 + 32 * 3 + 4 * 2;
61
62    /// Returns the inner value of the [`Solution`] as a byte slice.
63    fn value(&self) -> &[u8] {
64        match self {
65            Solution::Common(solution) => solution.as_slice(),
66            Solution::Regtest(solution) => solution.as_slice(),
67        }
68    }
69
70    /// Returns `Ok(())` if `EquihashSolution` is valid for `header`
71    #[allow(clippy::unwrap_in_result)]
72    pub fn check(&self, header: &Header) -> Result<(), Error> {
73        // TODO:
74        // - Add Equihash parameters field to `testnet::Parameters`
75        // - Update `Solution::Regtest` variant to hold a `Vec` to support arbitrary parameters - rename to `Other`
76        let n = 200;
77        let k = 9;
78        let nonce = &header.nonce;
79
80        let mut input = Vec::new();
81        header
82            .zcash_serialize(&mut input)
83            .expect("serialization into a vec can't fail");
84
85        // The part of the header before the nonce and solution.
86        // This data is kept constant during solver runs, so the verifier API takes it separately.
87        let input = &input[0..Solution::INPUT_LENGTH];
88
89        equihash::is_valid_solution(n, k, input, nonce.as_ref(), self.value())?;
90
91        Ok(())
92    }
93
94    /// Returns a [`Solution`] containing the bytes from `solution`.
95    /// Returns an error if `solution` is the wrong length.
96    pub fn from_bytes(solution: &[u8]) -> Result<Self, SerializationError> {
97        match solution.len() {
98            // Won't panic, because we just checked the length.
99            SOLUTION_SIZE => {
100                let mut bytes = [0; SOLUTION_SIZE];
101                bytes.copy_from_slice(solution);
102                Ok(Self::Common(bytes))
103            }
104            REGTEST_SOLUTION_SIZE => {
105                let mut bytes = [0; REGTEST_SOLUTION_SIZE];
106                bytes.copy_from_slice(solution);
107                Ok(Self::Regtest(bytes))
108            }
109            _unexpected_len => Err(SerializationError::Parse(
110                "incorrect equihash solution size",
111            )),
112        }
113    }
114
115    /// Returns a [`Solution`] of `[0; SOLUTION_SIZE]` to be used in block proposals.
116    pub fn for_proposal() -> Self {
117        // TODO: Accept network as an argument, and if it's Regtest, return the shorter null solution.
118        Self::Common([0; SOLUTION_SIZE])
119    }
120
121    /// Mines and returns one or more [`Solution`]s based on a template `header`.
122    /// The returned header contains a valid `nonce` and `solution`.
123    ///
124    /// If `cancel_fn()` returns an error, returns early with `Err(SolverCancelled)`.
125    ///
126    /// The `nonce` in the header template is taken as the starting nonce. If you are running multiple
127    /// solvers at the same time, start them with different nonces.
128    /// The `solution` in the header template is ignored.
129    ///
130    /// This method is CPU and memory-intensive. It uses 144 MB of RAM and one CPU core while running.
131    /// It can run for minutes or hours if the network difficulty is high.
132    #[cfg(feature = "internal-miner")]
133    #[allow(clippy::unwrap_in_result)]
134    pub fn solve<F>(
135        mut header: Header,
136        mut _cancel_fn: F,
137    ) -> Result<AtLeastOne<Header>, SolverCancelled>
138    where
139        F: FnMut() -> Result<(), SolverCancelled>,
140    {
141        // TODO: Function code was removed as part of https://github.com/ZcashFoundation/zebra/issues/8180
142        // Find the removed code at https://github.com/ZcashFoundation/zebra/blob/v1.5.1/zebra-chain/src/work/equihash.rs#L115-L166
143        // Restore the code when conditions are met. https://github.com/ZcashFoundation/zebra/issues/8183
144        header.solution = Solution::for_proposal();
145        Ok(AtLeastOne::from_one(header))
146    }
147
148    // TODO: Some methods were removed as part of https://github.com/ZcashFoundation/zebra/issues/8180
149    // Find the removed code at https://github.com/ZcashFoundation/zebra/blob/v1.5.1/zebra-chain/src/work/equihash.rs#L171-L196
150    // Restore the code when conditions are met. https://github.com/ZcashFoundation/zebra/issues/8183
151}
152
153impl PartialEq<Solution> for Solution {
154    fn eq(&self, other: &Solution) -> bool {
155        self.value() == other.value()
156    }
157}
158
159impl fmt::Debug for Solution {
160    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
161        f.debug_tuple("EquihashSolution")
162            .field(&hex::encode(self.value()))
163            .finish()
164    }
165}
166
167// These impls all only exist because of array length restrictions.
168
169impl Copy for Solution {}
170
171impl Clone for Solution {
172    fn clone(&self) -> Self {
173        *self
174    }
175}
176
177impl Eq for Solution {}
178
179#[cfg(any(test, feature = "proptest-impl"))]
180impl Default for Solution {
181    fn default() -> Self {
182        Self::Common([0; SOLUTION_SIZE])
183    }
184}
185
186impl ZcashSerialize for Solution {
187    fn zcash_serialize<W: io::Write>(&self, writer: W) -> Result<(), io::Error> {
188        zcash_serialize_bytes(&self.value().to_vec(), writer)
189    }
190}
191
192impl ZcashDeserialize for Solution {
193    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
194        let solution: Vec<u8> = (&mut reader).zcash_deserialize_into()?;
195        Self::from_bytes(&solution)
196    }
197}
198
199impl ToHex for &Solution {
200    fn encode_hex<T: FromIterator<char>>(&self) -> T {
201        self.value().encode_hex()
202    }
203
204    fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
205        self.value().encode_hex_upper()
206    }
207}
208
209impl ToHex for Solution {
210    fn encode_hex<T: FromIterator<char>>(&self) -> T {
211        (&self).encode_hex()
212    }
213
214    fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
215        (&self).encode_hex_upper()
216    }
217}