zebra_chain/work/
equihash.rs

1//! Equihash Solution and related items.
2
3use std::{fmt, io};
4
5use hex::{FromHex, FromHexError, 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        use crate::shutdown::is_shutting_down;
142
143        let mut input = Vec::new();
144        header
145            .zcash_serialize(&mut input)
146            .expect("serialization into a vec can't fail");
147        // Take the part of the header before the nonce and solution.
148        // This data is kept constant for this solver run.
149        let input = &input[0..Solution::INPUT_LENGTH];
150
151        while !is_shutting_down() {
152            // Don't run the solver if we'd just cancel it anyway.
153            cancel_fn()?;
154
155            let solutions = equihash::tromp::solve_200_9(input, || {
156                // Cancel the solver if we have a new template.
157                if cancel_fn().is_err() {
158                    return None;
159                }
160
161                // This skips the first nonce, which doesn't matter in practice.
162                Self::next_nonce(&mut header.nonce);
163                Some(*header.nonce)
164            });
165
166            let mut valid_solutions = Vec::new();
167
168            for solution in &solutions {
169                header.solution = Self::from_bytes(solution)
170                    .expect("unexpected invalid solution: incorrect length");
171
172                // TODO: work out why we sometimes get invalid solutions here
173                if let Err(error) = header.solution.check(&header) {
174                    info!(?error, "found invalid solution for header");
175                    continue;
176                }
177
178                if Self::difficulty_is_valid(&header) {
179                    valid_solutions.push(header);
180                }
181            }
182
183            match valid_solutions.try_into() {
184                Ok(at_least_one_solution) => return Ok(at_least_one_solution),
185                Err(_is_empty_error) => debug!(
186                    solutions = ?solutions.len(),
187                    "found valid solutions which did not pass the validity or difficulty checks"
188                ),
189            }
190        }
191
192        Err(SolverCancelled)
193    }
194
195    /// Returns `true` if the `nonce` and `solution` in `header` meet the difficulty threshold.
196    ///
197    /// # Panics
198    ///
199    /// - If `header` contains an invalid difficulty threshold.  
200    #[cfg(feature = "internal-miner")]
201    fn difficulty_is_valid(header: &Header) -> bool {
202        // Simplified from zebra_consensus::block::check::difficulty_is_valid().
203        let difficulty_threshold = header
204            .difficulty_threshold
205            .to_expanded()
206            .expect("unexpected invalid header template: invalid difficulty threshold");
207
208        // TODO: avoid calculating this hash multiple times
209        let hash = header.hash();
210
211        // Note: this comparison is a u256 integer comparison, like zcashd and bitcoin. Greater
212        // values represent *less* work.
213        hash <= difficulty_threshold
214    }
215
216    /// Modifies `nonce` to be the next integer in big-endian order.
217    /// Wraps to zero if the next nonce would overflow.
218    #[cfg(feature = "internal-miner")]
219    fn next_nonce(nonce: &mut [u8; 32]) {
220        let _ignore_overflow = crate::primitives::byte_array::increment_big_endian(&mut nonce[..]);
221    }
222}
223
224impl PartialEq<Solution> for Solution {
225    fn eq(&self, other: &Solution) -> bool {
226        self.value() == other.value()
227    }
228}
229
230impl fmt::Debug for Solution {
231    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
232        f.debug_tuple("EquihashSolution")
233            .field(&hex::encode(self.value()))
234            .finish()
235    }
236}
237
238// These impls all only exist because of array length restrictions.
239
240impl Copy for Solution {}
241
242impl Clone for Solution {
243    fn clone(&self) -> Self {
244        *self
245    }
246}
247
248impl Eq for Solution {}
249
250#[cfg(any(test, feature = "proptest-impl"))]
251impl Default for Solution {
252    fn default() -> Self {
253        Self::Common([0; SOLUTION_SIZE])
254    }
255}
256
257impl ZcashSerialize for Solution {
258    fn zcash_serialize<W: io::Write>(&self, writer: W) -> Result<(), io::Error> {
259        zcash_serialize_bytes(&self.value().to_vec(), writer)
260    }
261}
262
263impl ZcashDeserialize for Solution {
264    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
265        let solution: Vec<u8> = (&mut reader).zcash_deserialize_into()?;
266        Self::from_bytes(&solution)
267    }
268}
269
270impl ToHex for &Solution {
271    fn encode_hex<T: FromIterator<char>>(&self) -> T {
272        self.value().encode_hex()
273    }
274
275    fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
276        self.value().encode_hex_upper()
277    }
278}
279
280impl ToHex for Solution {
281    fn encode_hex<T: FromIterator<char>>(&self) -> T {
282        (&self).encode_hex()
283    }
284
285    fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
286        (&self).encode_hex_upper()
287    }
288}
289
290impl FromHex for Solution {
291    type Error = FromHexError;
292
293    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
294        let bytes = Vec::from_hex(hex)?;
295        Solution::from_bytes(&bytes).map_err(|_| FromHexError::InvalidStringLength)
296    }
297}