93 lines
2.9 KiB
Rust
93 lines
2.9 KiB
Rust
// SPDX-License-Identifier: MIT
|
|
//! Format one verified share for Stratum V1 and negotiated BIP310 submission.
|
|
//! Pool I/O and request tracking are owned by the caller.
|
|
|
|
use crate::pow::VersionMask;
|
|
use std::fmt::Write;
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
pub enum SubmitError {
|
|
EmptyWorker,
|
|
EmptyJobId,
|
|
FieldTooLong,
|
|
ExtranonceTooLong,
|
|
UnrepresentableVersion,
|
|
}
|
|
|
|
pub struct Submission<'a> {
|
|
pub request_id: u64,
|
|
pub worker: &'a str,
|
|
pub job_id: &'a str,
|
|
pub extranonce2: &'a [u8],
|
|
pub ntime: u32,
|
|
pub nonce: u32,
|
|
pub base_version: u32,
|
|
pub rolled_version: u32,
|
|
/// The last pool mask, only after version rolling was accepted.
|
|
pub version_mask: Option<VersionMask>,
|
|
}
|
|
|
|
fn json_string(out: &mut String, value: &str) {
|
|
out.push('"');
|
|
for ch in value.chars() {
|
|
match ch {
|
|
'"' => out.push_str("\\\""),
|
|
'\\' => out.push_str("\\\\"),
|
|
'\n' => out.push_str("\\n"),
|
|
'\r' => out.push_str("\\r"),
|
|
'\t' => out.push_str("\\t"),
|
|
c if c <= '\u{001f}' => {
|
|
write!(out, "\\u{:04x}", c as u32).expect("write to String");
|
|
}
|
|
c => out.push(c),
|
|
}
|
|
}
|
|
out.push('"');
|
|
}
|
|
|
|
/// Emit one newline-terminated JSON request. The caller must have checked the
|
|
/// ASIC report against the pool target and retained the original job metadata.
|
|
pub fn format_submission(share: &Submission<'_>) -> Result<String, SubmitError> {
|
|
if share.worker.is_empty() {
|
|
return Err(SubmitError::EmptyWorker);
|
|
}
|
|
if share.job_id.is_empty() {
|
|
return Err(SubmitError::EmptyJobId);
|
|
}
|
|
if share.worker.len() > 128 || share.job_id.len() > 128 {
|
|
return Err(SubmitError::FieldTooLong);
|
|
}
|
|
if share.extranonce2.len() > 32 {
|
|
return Err(SubmitError::ExtranonceTooLong);
|
|
}
|
|
let version_bits = match share.version_mask {
|
|
Some(mask) => {
|
|
let bits = share.rolled_version & mask.bits();
|
|
if mask.apply_submission_bits(share.base_version, bits) != Some(share.rolled_version) {
|
|
return Err(SubmitError::UnrepresentableVersion);
|
|
}
|
|
Some(bits)
|
|
}
|
|
None if share.rolled_version == share.base_version => None,
|
|
None => return Err(SubmitError::UnrepresentableVersion),
|
|
};
|
|
|
|
let mut out = format!(
|
|
"{{\"id\":{},\"method\":\"mining.submit\",\"params\":[",
|
|
share.request_id
|
|
);
|
|
json_string(&mut out, share.worker);
|
|
out.push(',');
|
|
json_string(&mut out, share.job_id);
|
|
out.push_str(",\"");
|
|
for byte in share.extranonce2 {
|
|
write!(out, "{byte:02x}").expect("write to String");
|
|
}
|
|
write!(out, "\",\"{:08x}\",\"{:08x}\"", share.ntime, share.nonce).expect("write to String");
|
|
if let Some(bits) = version_bits {
|
|
write!(out, ",\"{bits:08x}\"").expect("write to String");
|
|
}
|
|
out.push_str("]}\n");
|
|
Ok(out)
|
|
}
|