Skip to main content

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    parameters::Network,
11    serialization::{
12        zcash_deserialize_bytes_external_count, zcash_serialize_bytes, CompactSizeMessage,
13        SerializationError, ZcashDeserialize, ZcashDeserializeInto, ZcashSerialize,
14    },
15};
16
17#[cfg(feature = "internal-miner")]
18use crate::serialization::AtLeastOne;
19
20/// The error type for Equihash validation.
21#[non_exhaustive]
22#[derive(Debug, thiserror::Error)]
23#[error("invalid equihash solution for BlockHeader")]
24pub struct Error(#[from] equihash::Error);
25
26/// The error type for Equihash solving.
27#[derive(Copy, Clone, Debug, Eq, PartialEq, thiserror::Error)]
28#[error("solver was cancelled")]
29pub struct SolverCancelled;
30
31/// The size of an Equihash solution in bytes (always 1344).
32pub(crate) const SOLUTION_SIZE: usize = 1344;
33
34/// The size of an Equihash solution in bytes on Regtest (always 36).
35pub(crate) const REGTEST_SOLUTION_SIZE: usize = 36;
36
37/// Equihash Solution in compressed format.
38///
39/// A wrapper around `[u8; n]` where `n` is the solution size because
40/// Rust doesn't implement common traits like `Debug`, `Clone`, etc.
41/// for collections like arrays beyond lengths 0 to 32.
42///
43/// The size of an Equihash solution in bytes is always 1344 on Mainnet and Testnet, and
44/// is always 36 on Regtest so the length of this type is fixed.
45#[derive(Deserialize, Serialize)]
46// It's okay to use the extra space on Regtest
47#[allow(clippy::large_enum_variant)]
48pub enum Solution {
49    /// Equihash solution on Mainnet or Testnet
50    Common(#[serde(with = "BigArray")] [u8; SOLUTION_SIZE]),
51    /// Equihash solution on Regtest
52    Regtest(#[serde(with = "BigArray")] [u8; REGTEST_SOLUTION_SIZE]),
53}
54
55impl Solution {
56    /// The length of the portion of the header used as input when verifying
57    /// equihash solutions, in bytes.
58    ///
59    /// Excludes the 32-byte nonce, which is passed as a separate argument
60    /// to the verification function.
61    pub const INPUT_LENGTH: usize = 4 + 32 * 3 + 4 * 2;
62
63    /// Returns the inner value of the [`Solution`] as a byte slice.
64    fn value(&self) -> &[u8] {
65        match self {
66            Solution::Common(solution) => solution.as_slice(),
67            Solution::Regtest(solution) => solution.as_slice(),
68        }
69    }
70
71    /// Returns `Ok(())` if `EquihashSolution` is valid for `header`
72    #[allow(clippy::unwrap_in_result)]
73    pub fn check(&self, header: &Header) -> Result<(), Error> {
74        // TODO:
75        // - Add Equihash parameters field to `testnet::Parameters`
76        // - Update `Solution::Regtest` variant to hold a `Vec` to support arbitrary parameters - rename to `Other`
77        let n = 200;
78        let k = 9;
79        let nonce = &header.nonce;
80
81        let mut input = Vec::new();
82        header
83            .zcash_serialize(&mut input)
84            .expect("serialization into a vec can't fail");
85
86        // The part of the header before the nonce and solution.
87        // This data is kept constant during solver runs, so the verifier API takes it separately.
88        let input = &input[0..Solution::INPUT_LENGTH];
89
90        equihash::is_valid_solution(n, k, input, nonce.as_ref(), self.value())?;
91
92        Ok(())
93    }
94
95    /// Returns a [`Solution`] containing the bytes from `solution`.
96    /// Returns an error if `solution` is the wrong length.
97    pub fn from_bytes(solution: &[u8]) -> Result<Self, SerializationError> {
98        match solution.len() {
99            // Won't panic, because we just checked the length.
100            SOLUTION_SIZE => {
101                let mut bytes = [0; SOLUTION_SIZE];
102                bytes.copy_from_slice(solution);
103                Ok(Self::Common(bytes))
104            }
105            REGTEST_SOLUTION_SIZE => {
106                let mut bytes = [0; REGTEST_SOLUTION_SIZE];
107                bytes.copy_from_slice(solution);
108                Ok(Self::Regtest(bytes))
109            }
110            _unexpected_len => Err(SerializationError::Parse(
111                "incorrect equihash solution size",
112            )),
113        }
114    }
115
116    /// The serialized size of a solution on Mainnet and Testnet (except Regtest), in bytes:
117    /// the 1344-byte solution and its 3-byte CompactSize length prefix (`0xfd` + `u16`).
118    pub const SERIALIZED_SIZE: usize = 3 + SOLUTION_SIZE;
119
120    /// The serialized size of a solution on Regtest, in bytes:
121    /// the 36-byte solution and its 1-byte CompactSize length prefix.
122    pub const REGTEST_SERIALIZED_SIZE: usize = 1 + REGTEST_SOLUTION_SIZE;
123
124    /// Returns the size of the serialized solution on `network`, in bytes,
125    /// including its CompactSize length prefix.
126    ///
127    /// The solution size is constant per network, so this is also constant per network:
128    /// [`Self::REGTEST_SERIALIZED_SIZE`] on Regtest, [`Self::SERIALIZED_SIZE`] everywhere else.
129    pub fn serialized_size(network: &Network) -> usize {
130        if network.is_regtest() {
131            Self::REGTEST_SERIALIZED_SIZE
132        } else {
133            Self::SERIALIZED_SIZE
134        }
135    }
136
137    /// Returns a [`Solution`] of `[0; SOLUTION_SIZE]` to be used in block proposals.
138    pub fn for_proposal() -> Self {
139        // TODO: Accept network as an argument, and if it's Regtest, return the shorter null solution.
140        Self::Common([0; SOLUTION_SIZE])
141    }
142
143    /// Mines and returns one or more [`Solution`]s based on a template `header`.
144    /// The returned header contains a valid `nonce` and `solution`.
145    ///
146    /// If `cancel_fn()` returns an error, returns early with `Err(SolverCancelled)`.
147    ///
148    /// The `nonce` in the header template is taken as the starting nonce. If you are running multiple
149    /// solvers at the same time, start them with different nonces.
150    /// The `solution` in the header template is ignored.
151    ///
152    /// This method is CPU and memory-intensive. It uses 144 MB of RAM and one CPU core while running.
153    /// It can run for minutes or hours if the network difficulty is high.
154    #[cfg(feature = "internal-miner")]
155    #[allow(clippy::unwrap_in_result)]
156    pub fn solve<F>(
157        mut header: Header,
158        mut cancel_fn: F,
159    ) -> Result<AtLeastOne<Header>, SolverCancelled>
160    where
161        F: FnMut() -> Result<(), SolverCancelled>,
162    {
163        use crate::shutdown::is_shutting_down;
164
165        let mut input = Vec::new();
166        header
167            .zcash_serialize(&mut input)
168            .expect("serialization into a vec can't fail");
169        // Take the part of the header before the nonce and solution.
170        // This data is kept constant for this solver run.
171        let input = &input[0..Solution::INPUT_LENGTH];
172
173        while !is_shutting_down() {
174            // Don't run the solver if we'd just cancel it anyway.
175            cancel_fn()?;
176
177            let solutions = equihash::tromp::solve_200_9(input, || {
178                // Cancel the solver if we have a new template.
179                if cancel_fn().is_err() {
180                    return None;
181                }
182
183                // This skips the first nonce, which doesn't matter in practice.
184                Self::next_nonce(&mut header.nonce);
185                Some(*header.nonce)
186            });
187
188            let mut valid_solutions = Vec::new();
189
190            for solution in &solutions {
191                header.solution = Self::from_bytes(solution)
192                    .expect("unexpected invalid solution: incorrect length");
193
194                // TODO: work out why we sometimes get invalid solutions here
195                if let Err(error) = header.solution.check(&header) {
196                    info!(?error, "found invalid solution for header");
197                    continue;
198                }
199
200                if Self::difficulty_is_valid(&header) {
201                    valid_solutions.push(header);
202                }
203            }
204
205            match valid_solutions.try_into() {
206                Ok(at_least_one_solution) => return Ok(at_least_one_solution),
207                Err(_is_empty_error) => debug!(
208                    solutions = ?solutions.len(),
209                    "found valid solutions which did not pass the validity or difficulty checks"
210                ),
211            }
212        }
213
214        Err(SolverCancelled)
215    }
216
217    /// Returns `true` if the `nonce` and `solution` in `header` meet the difficulty threshold.
218    ///
219    /// # Panics
220    ///
221    /// - If `header` contains an invalid difficulty threshold.
222    #[cfg(feature = "internal-miner")]
223    fn difficulty_is_valid(header: &Header) -> bool {
224        // Simplified from zebra_consensus::block::check::difficulty_is_valid().
225        let difficulty_threshold = header
226            .difficulty_threshold
227            .to_expanded()
228            .expect("unexpected invalid header template: invalid difficulty threshold");
229
230        // TODO: avoid calculating this hash multiple times
231        let hash = header.hash();
232
233        // Note: this comparison is a u256 integer comparison, like zcashd and bitcoin. Greater
234        // values represent *less* work.
235        hash <= difficulty_threshold
236    }
237
238    /// Modifies `nonce` to be the next integer in big-endian order.
239    /// Wraps to zero if the next nonce would overflow.
240    #[cfg(feature = "internal-miner")]
241    fn next_nonce(nonce: &mut [u8; 32]) {
242        let _ignore_overflow = crate::primitives::byte_array::increment_big_endian(&mut nonce[..]);
243    }
244}
245
246impl PartialEq<Solution> for Solution {
247    fn eq(&self, other: &Solution) -> bool {
248        self.value() == other.value()
249    }
250}
251
252impl fmt::Debug for Solution {
253    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
254        f.debug_tuple("EquihashSolution")
255            .field(&hex::encode(self.value()))
256            .finish()
257    }
258}
259
260// These impls all only exist because of array length restrictions.
261
262impl Copy for Solution {}
263
264impl Clone for Solution {
265    fn clone(&self) -> Self {
266        *self
267    }
268}
269
270impl Eq for Solution {}
271
272#[cfg(any(test, feature = "proptest-impl"))]
273impl Default for Solution {
274    fn default() -> Self {
275        Self::Common([0; SOLUTION_SIZE])
276    }
277}
278
279impl ZcashSerialize for Solution {
280    fn zcash_serialize<W: io::Write>(&self, writer: W) -> Result<(), io::Error> {
281        zcash_serialize_bytes(&self.value().to_vec(), writer)
282    }
283}
284
285impl ZcashDeserialize for Solution {
286    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
287        let len: CompactSizeMessage = (&mut reader).zcash_deserialize_into()?;
288        let len: usize = len.into();
289
290        // Validate the length against the consensus-required sizes before
291        // allocating, so an attacker-controlled CompactSize cannot force a
292        // multi-megabyte allocation.
293        if len > SOLUTION_SIZE {
294            return Err(SerializationError::Parse(
295                "incorrect equihash solution size",
296            ));
297        }
298
299        let solution = zcash_deserialize_bytes_external_count(len, &mut reader)?;
300        Self::from_bytes(&solution)
301    }
302}
303
304impl ToHex for &Solution {
305    fn encode_hex<T: FromIterator<char>>(&self) -> T {
306        self.value().encode_hex()
307    }
308
309    fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
310        self.value().encode_hex_upper()
311    }
312}
313
314impl ToHex for Solution {
315    fn encode_hex<T: FromIterator<char>>(&self) -> T {
316        (&self).encode_hex()
317    }
318
319    fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
320        (&self).encode_hex_upper()
321    }
322}
323
324impl FromHex for Solution {
325    type Error = FromHexError;
326
327    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
328        let bytes = Vec::from_hex(hex)?;
329        Solution::from_bytes(&bytes).map_err(|_| FromHexError::InvalidStringLength)
330    }
331}