use std::{fmt, io};
use hex::{FromHex, FromHexError, ToHex};
use serde_big_array::BigArray;
use crate::{
block::Header,
serialization::{
zcash_serialize_bytes, SerializationError, ZcashDeserialize, ZcashDeserializeInto,
ZcashSerialize,
},
};
#[cfg(feature = "internal-miner")]
use crate::serialization::AtLeastOne;
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
#[error("invalid equihash solution for BlockHeader")]
pub struct Error(#[from] equihash::Error);
#[derive(Copy, Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[error("solver was cancelled")]
pub struct SolverCancelled;
pub(crate) const SOLUTION_SIZE: usize = 1344;
pub(crate) const REGTEST_SOLUTION_SIZE: usize = 36;
#[derive(Deserialize, Serialize)]
#[allow(clippy::large_enum_variant)]
pub enum Solution {
Common(#[serde(with = "BigArray")] [u8; SOLUTION_SIZE]),
Regtest(#[serde(with = "BigArray")] [u8; REGTEST_SOLUTION_SIZE]),
}
impl Solution {
pub const INPUT_LENGTH: usize = 4 + 32 * 3 + 4 * 2;
fn value(&self) -> &[u8] {
match self {
Solution::Common(solution) => solution.as_slice(),
Solution::Regtest(solution) => solution.as_slice(),
}
}
#[allow(clippy::unwrap_in_result)]
pub fn check(&self, header: &Header) -> Result<(), Error> {
let n = 200;
let k = 9;
let nonce = &header.nonce;
let mut input = Vec::new();
header
.zcash_serialize(&mut input)
.expect("serialization into a vec can't fail");
let input = &input[0..Solution::INPUT_LENGTH];
equihash::is_valid_solution(n, k, input, nonce.as_ref(), self.value())?;
Ok(())
}
pub fn from_bytes(solution: &[u8]) -> Result<Self, SerializationError> {
match solution.len() {
SOLUTION_SIZE => {
let mut bytes = [0; SOLUTION_SIZE];
bytes.copy_from_slice(solution);
Ok(Self::Common(bytes))
}
REGTEST_SOLUTION_SIZE => {
let mut bytes = [0; REGTEST_SOLUTION_SIZE];
bytes.copy_from_slice(solution);
Ok(Self::Regtest(bytes))
}
_unexpected_len => Err(SerializationError::Parse(
"incorrect equihash solution size",
)),
}
}
pub fn for_proposal() -> Self {
Self::Common([0; SOLUTION_SIZE])
}
#[cfg(feature = "internal-miner")]
#[allow(clippy::unwrap_in_result)]
pub fn solve<F>(
mut header: Header,
mut cancel_fn: F,
) -> Result<AtLeastOne<Header>, SolverCancelled>
where
F: FnMut() -> Result<(), SolverCancelled>,
{
use crate::shutdown::is_shutting_down;
let mut input = Vec::new();
header
.zcash_serialize(&mut input)
.expect("serialization into a vec can't fail");
let input = &input[0..Solution::INPUT_LENGTH];
while !is_shutting_down() {
cancel_fn()?;
let solutions = equihash::tromp::solve_200_9(input, || {
if cancel_fn().is_err() {
return None;
}
Self::next_nonce(&mut header.nonce);
Some(*header.nonce)
});
let mut valid_solutions = Vec::new();
for solution in &solutions {
header.solution = Self::from_bytes(solution)
.expect("unexpected invalid solution: incorrect length");
if let Err(error) = header.solution.check(&header) {
info!(?error, "found invalid solution for header");
continue;
}
if Self::difficulty_is_valid(&header) {
valid_solutions.push(header);
}
}
match valid_solutions.try_into() {
Ok(at_least_one_solution) => return Ok(at_least_one_solution),
Err(_is_empty_error) => debug!(
solutions = ?solutions.len(),
"found valid solutions which did not pass the validity or difficulty checks"
),
}
}
Err(SolverCancelled)
}
#[cfg(feature = "internal-miner")]
fn difficulty_is_valid(header: &Header) -> bool {
let difficulty_threshold = header
.difficulty_threshold
.to_expanded()
.expect("unexpected invalid header template: invalid difficulty threshold");
let hash = header.hash();
hash <= difficulty_threshold
}
#[cfg(feature = "internal-miner")]
fn next_nonce(nonce: &mut [u8; 32]) {
let _ignore_overflow = crate::primitives::byte_array::increment_big_endian(&mut nonce[..]);
}
}
impl PartialEq<Solution> for Solution {
fn eq(&self, other: &Solution) -> bool {
self.value() == other.value()
}
}
impl fmt::Debug for Solution {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("EquihashSolution")
.field(&hex::encode(self.value()))
.finish()
}
}
impl Copy for Solution {}
impl Clone for Solution {
fn clone(&self) -> Self {
*self
}
}
impl Eq for Solution {}
#[cfg(any(test, feature = "proptest-impl"))]
impl Default for Solution {
fn default() -> Self {
Self::Common([0; SOLUTION_SIZE])
}
}
impl ZcashSerialize for Solution {
fn zcash_serialize<W: io::Write>(&self, writer: W) -> Result<(), io::Error> {
zcash_serialize_bytes(&self.value().to_vec(), writer)
}
}
impl ZcashDeserialize for Solution {
fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
let solution: Vec<u8> = (&mut reader).zcash_deserialize_into()?;
Self::from_bytes(&solution)
}
}
impl ToHex for &Solution {
fn encode_hex<T: FromIterator<char>>(&self) -> T {
self.value().encode_hex()
}
fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
self.value().encode_hex_upper()
}
}
impl ToHex for Solution {
fn encode_hex<T: FromIterator<char>>(&self) -> T {
(&self).encode_hex()
}
fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
(&self).encode_hex_upper()
}
}
impl FromHex for Solution {
type Error = FromHexError;
fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
let bytes = Vec::from_hex(hex)?;
Solution::from_bytes(&bytes).map_err(|_| FromHexError::InvalidStringLength)
}
}