zebra_chain/work/
equihash.rs1use 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#[non_exhaustive]
21#[derive(Debug, thiserror::Error)]
22#[error("invalid equihash solution for BlockHeader")]
23pub struct Error(#[from] equihash::Error);
24
25#[derive(Copy, Clone, Debug, Eq, PartialEq, thiserror::Error)]
27#[error("solver was cancelled")]
28pub struct SolverCancelled;
29
30pub(crate) const SOLUTION_SIZE: usize = 1344;
32
33pub(crate) const REGTEST_SOLUTION_SIZE: usize = 36;
35
36#[derive(Deserialize, Serialize)]
45#[allow(clippy::large_enum_variant)]
47pub enum Solution {
48 Common(#[serde(with = "BigArray")] [u8; SOLUTION_SIZE]),
50 Regtest(#[serde(with = "BigArray")] [u8; REGTEST_SOLUTION_SIZE]),
52}
53
54impl Solution {
55 pub const INPUT_LENGTH: usize = 4 + 32 * 3 + 4 * 2;
61
62 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 #[allow(clippy::unwrap_in_result)]
72 pub fn check(&self, header: &Header) -> Result<(), Error> {
73 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 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 pub fn from_bytes(solution: &[u8]) -> Result<Self, SerializationError> {
97 match solution.len() {
98 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 pub fn for_proposal() -> Self {
117 Self::Common([0; SOLUTION_SIZE])
119 }
120
121 #[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 let input = &input[0..Solution::INPUT_LENGTH];
150
151 while !is_shutting_down() {
152 cancel_fn()?;
154
155 let solutions = equihash::tromp::solve_200_9(input, || {
156 if cancel_fn().is_err() {
158 return None;
159 }
160
161 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 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 #[cfg(feature = "internal-miner")]
201 fn difficulty_is_valid(header: &Header) -> bool {
202 let difficulty_threshold = header
204 .difficulty_threshold
205 .to_expanded()
206 .expect("unexpected invalid header template: invalid difficulty threshold");
207
208 let hash = header.hash();
210
211 hash <= difficulty_threshold
214 }
215
216 #[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
238impl 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}