1//! Equihash Solution and related items.
23use std::{fmt, io};
45use hex::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 {
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
144header.solution = Solution::for_proposal();
145Ok(AtLeastOne::from_one(header))
146 }
147148// 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}
152153impl PartialEq<Solution> for Solution {
154fn eq(&self, other: &Solution) -> bool {
155self.value() == other.value()
156 }
157}
158159impl fmt::Debug for Solution {
160fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
161 f.debug_tuple("EquihashSolution")
162 .field(&hex::encode(self.value()))
163 .finish()
164 }
165}
166167// These impls all only exist because of array length restrictions.
168169impl Copy for Solution {}
170171impl Clone for Solution {
172fn clone(&self) -> Self {
173*self
174}
175}
176177impl Eq for Solution {}
178179#[cfg(any(test, feature = "proptest-impl"))]
180impl Default for Solution {
181fn default() -> Self {
182Self::Common([0; SOLUTION_SIZE])
183 }
184}
185186impl ZcashSerialize for Solution {
187fn zcash_serialize<W: io::Write>(&self, writer: W) -> Result<(), io::Error> {
188 zcash_serialize_bytes(&self.value().to_vec(), writer)
189 }
190}
191192impl ZcashDeserialize for Solution {
193fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
194let solution: Vec<u8> = (&mut reader).zcash_deserialize_into()?;
195Self::from_bytes(&solution)
196 }
197}
198199impl ToHex for &Solution {
200fn encode_hex<T: FromIterator<char>>(&self) -> T {
201self.value().encode_hex()
202 }
203204fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
205self.value().encode_hex_upper()
206 }
207}
208209impl ToHex for Solution {
210fn encode_hex<T: FromIterator<char>>(&self) -> T {
211 (&self).encode_hex()
212 }
213214fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
215 (&self).encode_hex_upper()
216 }
217}