1//! Equihash Solution and related items.
23use std::{fmt, io};
45use hex::{FromHex, FromHexError, ToHex};
6use serde_big_array::BigArray;
78use crate::{
9 block::Header,
10 serialization::{
11 zcash_serialize_bytes, SerializationError, ZcashDeserialize, ZcashDeserializeInto,
12 ZcashSerialize,
13 },
14};
1516#[cfg(feature = "internal-miner")]
17use crate::serialization::AtLeastOne;
1819/// 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);
2425/// The error type for Equihash solving.
26#[derive(Copy, Clone, Debug, Eq, PartialEq, thiserror::Error)]
27#[error("solver was cancelled")]
28pub struct SolverCancelled;
2930/// The size of an Equihash solution in bytes (always 1344).
31pub(crate) const SOLUTION_SIZE: usize = 1344;
3233/// The size of an Equihash solution in bytes on Regtest (always 36).
34pub(crate) const REGTEST_SOLUTION_SIZE: usize = 36;
3536/// 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
49Common(#[serde(with = "BigArray")] [u8; SOLUTION_SIZE]),
50/// Equihash solution on Regtest
51Regtest(#[serde(with = "BigArray")] [u8; REGTEST_SOLUTION_SIZE]),
52}
5354impl 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.
60pub const INPUT_LENGTH: usize = 4 + 32 * 3 + 4 * 2;
6162/// Returns the inner value of the [`Solution`] as a byte slice.
63fn value(&self) -> &[u8] {
64match self {
65 Solution::Common(solution) => solution.as_slice(),
66 Solution::Regtest(solution) => solution.as_slice(),
67 }
68 }
6970/// Returns `Ok(())` if `EquihashSolution` is valid for `header`
71#[allow(clippy::unwrap_in_result)]
72pub 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`
76let n = 200;
77let k = 9;
78let nonce = &header.nonce;
7980let mut input = Vec::new();
81 header
82 .zcash_serialize(&mut input)
83 .expect("serialization into a vec can't fail");
8485// 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.
87let input = &input[0..Solution::INPUT_LENGTH];
8889 equihash::is_valid_solution(n, k, input, nonce.as_ref(), self.value())?;
9091Ok(())
92 }
9394/// Returns a [`Solution`] containing the bytes from `solution`.
95 /// Returns an error if `solution` is the wrong length.
96pub fn from_bytes(solution: &[u8]) -> Result<Self, SerializationError> {
97match solution.len() {
98// Won't panic, because we just checked the length.
99SOLUTION_SIZE => {
100let mut bytes = [0; SOLUTION_SIZE];
101 bytes.copy_from_slice(solution);
102Ok(Self::Common(bytes))
103 }
104 REGTEST_SOLUTION_SIZE => {
105let mut bytes = [0; REGTEST_SOLUTION_SIZE];
106 bytes.copy_from_slice(solution);
107Ok(Self::Regtest(bytes))
108 }
109 _unexpected_len => Err(SerializationError::Parse(
110"incorrect equihash solution size",
111 )),
112 }
113 }
114115/// Returns a [`Solution`] of `[0; SOLUTION_SIZE]` to be used in block proposals.
116pub fn for_proposal() -> Self {
117// TODO: Accept network as an argument, and if it's Regtest, return the shorter null solution.
118Self::Common([0; SOLUTION_SIZE])
119 }
120121/// 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)]
134pub fn solve<F>(
135mut header: Header,
136mut cancel_fn: F,
137 ) -> Result<AtLeastOne<Header>, SolverCancelled>
138where
139F: FnMut() -> Result<(), SolverCancelled>,
140 {
141use crate::shutdown::is_shutting_down;
142143let 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.
149let input = &input[0..Solution::INPUT_LENGTH];
150151while !is_shutting_down() {
152// Don't run the solver if we'd just cancel it anyway.
153cancel_fn()?;
154155let solutions = equihash::tromp::solve_200_9(input, || {
156// Cancel the solver if we have a new template.
157if cancel_fn().is_err() {
158return None;
159 }
160161// This skips the first nonce, which doesn't matter in practice.
162Self::next_nonce(&mut header.nonce);
163Some(*header.nonce)
164 });
165166let mut valid_solutions = Vec::new();
167168for solution in &solutions {
169 header.solution = Self::from_bytes(solution)
170 .expect("unexpected invalid solution: incorrect length");
171172// TODO: work out why we sometimes get invalid solutions here
173if let Err(error) = header.solution.check(&header) {
174info!(?error, "found invalid solution for header");
175continue;
176 }
177178if Self::difficulty_is_valid(&header) {
179 valid_solutions.push(header);
180 }
181 }
182183match valid_solutions.try_into() {
184Ok(at_least_one_solution) => return Ok(at_least_one_solution),
185Err(_is_empty_error) => debug!(
186 solutions = ?solutions.len(),
187"found valid solutions which did not pass the validity or difficulty checks"
188),
189 }
190 }
191192Err(SolverCancelled)
193 }
194195/// 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")]
201fn difficulty_is_valid(header: &Header) -> bool {
202// Simplified from zebra_consensus::block::check::difficulty_is_valid().
203let difficulty_threshold = header
204 .difficulty_threshold
205 .to_expanded()
206 .expect("unexpected invalid header template: invalid difficulty threshold");
207208// TODO: avoid calculating this hash multiple times
209let hash = header.hash();
210211// Note: this comparison is a u256 integer comparison, like zcashd and bitcoin. Greater
212 // values represent *less* work.
213hash <= difficulty_threshold
214 }
215216/// 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")]
219fn next_nonce(nonce: &mut [u8; 32]) {
220let _ignore_overflow = crate::primitives::byte_array::increment_big_endian(&mut nonce[..]);
221 }
222}
223224impl PartialEq<Solution> for Solution {
225fn eq(&self, other: &Solution) -> bool {
226self.value() == other.value()
227 }
228}
229230impl fmt::Debug for Solution {
231fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
232 f.debug_tuple("EquihashSolution")
233 .field(&hex::encode(self.value()))
234 .finish()
235 }
236}
237238// These impls all only exist because of array length restrictions.
239240impl Copy for Solution {}
241242impl Clone for Solution {
243fn clone(&self) -> Self {
244*self
245}
246}
247248impl Eq for Solution {}
249250#[cfg(any(test, feature = "proptest-impl"))]
251impl Default for Solution {
252fn default() -> Self {
253Self::Common([0; SOLUTION_SIZE])
254 }
255}
256257impl ZcashSerialize for Solution {
258fn zcash_serialize<W: io::Write>(&self, writer: W) -> Result<(), io::Error> {
259 zcash_serialize_bytes(&self.value().to_vec(), writer)
260 }
261}
262263impl ZcashDeserialize for Solution {
264fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
265let solution: Vec<u8> = (&mut reader).zcash_deserialize_into()?;
266Self::from_bytes(&solution)
267 }
268}
269270impl ToHex for &Solution {
271fn encode_hex<T: FromIterator<char>>(&self) -> T {
272self.value().encode_hex()
273 }
274275fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
276self.value().encode_hex_upper()
277 }
278}
279280impl ToHex for Solution {
281fn encode_hex<T: FromIterator<char>>(&self) -> T {
282 (&self).encode_hex()
283 }
284285fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
286 (&self).encode_hex_upper()
287 }
288}
289290impl FromHex for Solution {
291type Error = FromHexError;
292293fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
294let bytes = Vec::from_hex(hex)?;
295 Solution::from_bytes(&bytes).map_err(|_| FromHexError::InvalidStringLength)
296 }
297}