Fail closed on pool and HAL faults and bind release evidence to CI run
next-build / build (push) Canceled after 0s
next-build / build (push) Canceled after 0s
This commit is contained in:
@@ -22,6 +22,8 @@ jobs:
|
||||
run: python3 ci/test-last-attempt-badge.py
|
||||
- name: Benchmark history checks
|
||||
run: python3 ci/test-bench-history.py
|
||||
- name: Release evidence gate checks
|
||||
run: python3 ci/test-conformance.py
|
||||
- name: Quality
|
||||
run: cargo clippy --all-targets --locked -- -D warnings
|
||||
- name: Build
|
||||
|
||||
@@ -43,9 +43,11 @@ returned nonce. From this repository, run it with
|
||||
the SDK server. It is a simulator check and sends work to the named socket.
|
||||
The first BM1366 mining session sequences fan, temperature, PSU, reset,
|
||||
work submission, and nonce polling through the HAL. It rejects stale work IDs,
|
||||
malformed reports, and hashes below the caller's pool target. Sensor or HAL
|
||||
failure stops the PSU. The caller must provide a board-validated temperature
|
||||
limit.
|
||||
malformed reports, and hashes below the caller's pool target. A sensor fault
|
||||
requests PSU shutdown. A transport fault closes the HAL socket; the backend
|
||||
must end its power lease on disconnect and have an independent hardware
|
||||
watchdog. No production board backend meets that gate yet. The caller must
|
||||
provide a board-validated temperature limit.
|
||||
The library now formats verified shares as Stratum V1 `mining.submit` requests.
|
||||
For negotiated BIP310 version rolling, it includes the sixth version-bits
|
||||
parameter and rejects ASIC versions that the current pool mask cannot
|
||||
@@ -60,7 +62,9 @@ separately. Continuous scheduling and live pool acceptance remain unverified.
|
||||
Its cycle helper reads one pool event, polls one ASIC report, and sends a
|
||||
verified share when present. A share reply unanswered for 30 seconds closes
|
||||
the connection so a caller can reconnect instead of filling the pending
|
||||
queue indefinitely. The executable still lacks a board adapter and run loop.
|
||||
queue indefinitely. Terminal pool errors request miner shutdown, and pool
|
||||
reads are capped at 500 ms after the handshake so ASIC polling continues.
|
||||
The executable still lacks a board adapter and run loop.
|
||||
The Stratum V1 decoder bounds and validates `mining.subscribe` responses,
|
||||
nine-field Bitcoin `mining.notify` jobs, difficulty and extranonce changes,
|
||||
and negotiated BIP310 version-mask updates. Exact decimal difficulty values
|
||||
@@ -91,8 +95,11 @@ python3 ci/check-conformance.py
|
||||
|
||||
The last command currently fails because simulator and device evidence are
|
||||
still pending. It cross-checks the evidence matrix against the built binary's
|
||||
targets and validates artifact digest fields. It is a release gate, not a
|
||||
unit test.
|
||||
targets and requires per-cell reports from the current CI run, bound to the
|
||||
source commit and binary digest. Referenced artifacts are opened and hashed;
|
||||
captured shares must satisfy a difficulty-one-or-harder target and carry a
|
||||
matching pool ACCEPT. It is a release gate, not a unit test. The simulator
|
||||
runner that produces this evidence has not yet been implemented.
|
||||
|
||||
The badges record measured host-side checks for this initial core. They do
|
||||
not imply that any board image or mining target has passed conformance.
|
||||
|
||||
+129
-2
@@ -2,6 +2,7 @@
|
||||
"""Require the binary target matrix and traceable per-cell release evidence."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
@@ -29,6 +30,115 @@ REQUIRED_CHIPS = {
|
||||
)},
|
||||
}
|
||||
DIGEST = re.compile(r"[0-9a-f]{64}\Z")
|
||||
COMMIT = re.compile(r"[0-9a-f]{40}\Z")
|
||||
DIFF_ONE_TARGET = 0xffff << (8 * (0x1d - 3))
|
||||
MAX_REPORT_BYTES = 1_048_576
|
||||
|
||||
|
||||
def sha256_file(path: pathlib.Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as source:
|
||||
for chunk in iter(lambda: source.read(1_048_576), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def load_report(path: pathlib.Path) -> dict:
|
||||
if path.stat().st_size > MAX_REPORT_BYTES:
|
||||
raise ValueError("evidence report exceeds 1 MiB")
|
||||
value = json.loads(path.read_text())
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError("evidence report is not an object")
|
||||
return value
|
||||
|
||||
|
||||
def artifact(root: pathlib.Path, value: object) -> pathlib.Path:
|
||||
if not isinstance(value, dict) or not isinstance(value.get("path"), str):
|
||||
raise ValueError("artifact reference is missing")
|
||||
digest = value.get("sha256")
|
||||
if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
|
||||
raise ValueError("artifact digest is invalid")
|
||||
path = (root / value["path"]).resolve()
|
||||
if not path.is_relative_to(root.resolve()) or not path.is_file():
|
||||
raise ValueError("artifact is missing or outside evidence directory")
|
||||
if sha256_file(path) != digest:
|
||||
raise ValueError("artifact digest mismatch")
|
||||
return path
|
||||
|
||||
|
||||
def verify_accept(capture: dict) -> None:
|
||||
if capture.get("nonce_source") != "real_silicon_capture":
|
||||
raise ValueError("share was not sourced from captured silicon")
|
||||
header_hex = capture.get("header80")
|
||||
target_hex = capture.get("pool_target_le")
|
||||
nonce = capture.get("nonce")
|
||||
if (not isinstance(header_hex, str) or len(header_hex) != 160
|
||||
or not isinstance(target_hex, str) or not DIGEST.fullmatch(target_hex)
|
||||
or type(nonce) is not int or not 0 <= nonce <= 0xffffffff):
|
||||
raise ValueError("invalid accepted share work")
|
||||
try:
|
||||
header = bytearray.fromhex(header_hex)
|
||||
except ValueError as error:
|
||||
raise ValueError("invalid accepted share header") from error
|
||||
if int.from_bytes(header[76:80], "little") != nonce:
|
||||
raise ValueError("nonce differs from submitted header")
|
||||
target = int.from_bytes(bytes.fromhex(target_hex), "little")
|
||||
if not 0 < target <= DIFF_ONE_TARGET:
|
||||
raise ValueError("pool target is below difficulty one")
|
||||
hash_bytes = hashlib.sha256(hashlib.sha256(header).digest()).digest()
|
||||
if int.from_bytes(hash_bytes, "little") > target:
|
||||
raise ValueError("captured nonce misses the pool target")
|
||||
submission = capture.get("submission")
|
||||
response = capture.get("pool_response")
|
||||
if (not isinstance(submission, dict) or not isinstance(response, dict)
|
||||
or submission.get("method") != "mining.submit"
|
||||
or type(submission.get("id")) is not int
|
||||
or response.get("id") != submission["id"]
|
||||
or response.get("result") is not True
|
||||
or response.get("error") is not None):
|
||||
raise ValueError("no matching pool ACCEPT response")
|
||||
|
||||
|
||||
def verify_cell(row: dict, root: pathlib.Path, run_id: str,
|
||||
source_commit: str, binary_digest: str) -> None:
|
||||
board, chip = row["board"], row["chip"]
|
||||
report_path = (root / run_id / board / f"{chip}.json").resolve()
|
||||
if not report_path.is_relative_to(root.resolve()):
|
||||
raise ValueError("evidence report is outside evidence directory")
|
||||
report = load_report(report_path)
|
||||
identity = {"schema": 1, "run_id": run_id, "source_commit": source_commit,
|
||||
"os_binary_sha256": binary_digest, "board": board, "chip": chip,
|
||||
"stock_firmware_modified": False}
|
||||
if any(report.get(key) != value for key, value in identity.items()):
|
||||
raise ValueError("evidence belongs to a different run, source, binary, or cell")
|
||||
if report.get("stock_result") != row.get("stock_result"):
|
||||
raise ValueError("stock result differs from manifest")
|
||||
if report.get("stock_first_rejection") != row.get("stock_first_rejection"):
|
||||
raise ValueError("stock rejection differs from manifest")
|
||||
if report["stock_result"] == "rejects" and not report.get("stock_first_rejection"):
|
||||
raise ValueError("stock rejection gate is missing")
|
||||
if report.get("simulator_booted_stock") is not True:
|
||||
raise ValueError("unmodified stock boot is unverified")
|
||||
for field, digest_field in (("sdk_image", "sdk_image_sha256"),
|
||||
("stock_image", "stock_image_sha256"),
|
||||
("simulator_trace", "simulator_trace_sha256")):
|
||||
artifact(root, report.get(field))
|
||||
if report[field]["sha256"] != row.get(digest_field):
|
||||
raise ValueError(f"{field} digest differs from manifest")
|
||||
capture = load_report(artifact(root, report.get("alkane_share_accept_capture")))
|
||||
if report["alkane_share_accept_capture"]["path"] != row.get("alkane_share_accept_capture"):
|
||||
raise ValueError("accepted share artifact differs from manifest")
|
||||
if capture.get("board") != board or capture.get("chip") != chip:
|
||||
raise ValueError("accepted share belongs to another cell")
|
||||
verify_accept(capture)
|
||||
bench = load_report(artifact(root, report.get("bench_validation")))
|
||||
if report["bench_validation"]["path"] != row.get("bench_validation"):
|
||||
raise ValueError("bench artifact differs from manifest")
|
||||
if (bench.get("board") != board or bench.get("chip") != chip
|
||||
or bench.get("validated") is not True
|
||||
or not isinstance(bench.get("device_id"), str)
|
||||
or not bench["device_id"]):
|
||||
raise ValueError("bench validation is missing or belongs to another cell")
|
||||
|
||||
|
||||
def binary_targets(path: pathlib.Path) -> set[tuple[str, str]]:
|
||||
@@ -49,7 +159,10 @@ def binary_targets(path: pathlib.Path) -> set[tuple[str, str]]:
|
||||
return set(targets)
|
||||
|
||||
|
||||
def validate(manifest: dict, built_targets: set[tuple[str, str]]) -> list[str]:
|
||||
def validate(manifest: dict, built_targets: set[tuple[str, str]],
|
||||
evidence_root: pathlib.Path = pathlib.Path("ci/evidence"),
|
||||
run_id: str = "", source_commit: str = "",
|
||||
binary_digest: str = "") -> list[str]:
|
||||
errors = []
|
||||
if manifest.get("schema") != 1:
|
||||
errors.append("unsupported conformance manifest schema")
|
||||
@@ -71,6 +184,9 @@ def validate(manifest: dict, built_targets: set[tuple[str, str]]) -> list[str]:
|
||||
errors.append(f"manifest matrix mismatch: {len(actual)} present, {len(expected)} expected")
|
||||
if built_targets != expected:
|
||||
errors.append(f"binary matrix mismatch: {len(built_targets)} built, {len(expected)} expected")
|
||||
if (not run_id.isdecimal() or not COMMIT.fullmatch(source_commit)
|
||||
or not DIGEST.fullmatch(binary_digest)):
|
||||
errors.append("current run, source commit, or binary digest is unbound")
|
||||
required = ("sdk_image_sha256", "stock_image_sha256", "stock_result",
|
||||
"alkane_share_accept_capture", "simulator_trace_sha256",
|
||||
"bench_validation")
|
||||
@@ -87,6 +203,11 @@ def validate(manifest: dict, built_targets: set[tuple[str, str]]) -> list[str]:
|
||||
missing.append(f"{field} invalid")
|
||||
if missing:
|
||||
errors.append(f"{cell}: {', '.join(missing)}")
|
||||
elif run_id.isdecimal() and COMMIT.fullmatch(source_commit) and DIGEST.fullmatch(binary_digest):
|
||||
try:
|
||||
verify_cell(row, evidence_root, run_id, source_commit, binary_digest)
|
||||
except (OSError, ValueError, KeyError, TypeError, json.JSONDecodeError) as error:
|
||||
errors.append(f"{cell}: evidence invalid: {error}")
|
||||
return errors
|
||||
|
||||
|
||||
@@ -97,13 +218,19 @@ def main() -> None:
|
||||
parser.add_argument("--binary", type=pathlib.Path,
|
||||
default=pathlib.Path(os.environ.get("CARGO_TARGET_DIR", "target"))
|
||||
/ "release/alkane-os")
|
||||
parser.add_argument("--evidence-dir", type=pathlib.Path,
|
||||
default=pathlib.Path("ci/evidence"))
|
||||
parser.add_argument("--run-id", default=os.environ.get("GITHUB_RUN_ID", ""))
|
||||
args = parser.parse_args()
|
||||
manifest = json.loads(args.manifest.read_text())
|
||||
try:
|
||||
built_targets = binary_targets(args.binary.resolve())
|
||||
except (OSError, subprocess.SubprocessError, ValueError) as error:
|
||||
sys.exit(f"cannot verify Alkane OS binary target matrix: {error}")
|
||||
errors = validate(manifest, built_targets)
|
||||
source_commit = subprocess.run(["git", "rev-parse", "HEAD"], check=True,
|
||||
capture_output=True, text=True).stdout.strip()
|
||||
errors = validate(manifest, built_targets, args.evidence_dir, args.run_id,
|
||||
source_commit, sha256_file(args.binary.resolve()))
|
||||
if errors:
|
||||
print(f"Conformance pending: {len(errors)} issues across {len(manifest['targets'])} targets")
|
||||
for error in errors[:8]:
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regression checks for the fail-closed release evidence gate."""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
import unittest
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).with_name("check-conformance.py")
|
||||
spec = importlib.util.spec_from_file_location("check_conformance", SCRIPT)
|
||||
gate = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(gate)
|
||||
MANIFEST = json.loads(Path(__file__).with_name("conformance.json").read_text())
|
||||
TARGETS = {(row["board"], row["chip"]) for row in MANIFEST["targets"]}
|
||||
|
||||
|
||||
class ConformanceGateTest(unittest.TestCase):
|
||||
def test_placeholder_matrix_cannot_pass_without_current_run_artifacts(self):
|
||||
manifest = copy.deepcopy(MANIFEST)
|
||||
for row in manifest["targets"]:
|
||||
row.update(sdk_image_sha256="0" * 64,
|
||||
stock_image_sha256="0" * 64,
|
||||
simulator_trace_sha256="0" * 64,
|
||||
stock_result="mines",
|
||||
alkane_share_accept_capture="does-not-exist.json",
|
||||
bench_validation="not-run")
|
||||
with TemporaryDirectory() as directory:
|
||||
errors = gate.validate(manifest, TARGETS, Path(directory), "123",
|
||||
"a" * 40, "b" * 64)
|
||||
self.assertEqual(len(errors), 64)
|
||||
self.assertTrue(all("evidence invalid" in error for error in errors))
|
||||
|
||||
def test_stale_source_identity_is_rejected(self):
|
||||
row = copy.deepcopy(MANIFEST["targets"][0])
|
||||
row["stock_result"] = "mines"
|
||||
with TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
report = root / "123" / row["board"] / f"{row['chip']}.json"
|
||||
report.parent.mkdir(parents=True)
|
||||
report.write_text(json.dumps({"schema": 1, "run_id": "123",
|
||||
"source_commit": "f" * 40,
|
||||
"os_binary_sha256": "b" * 64,
|
||||
"board": row["board"], "chip": row["chip"],
|
||||
"stock_firmware_modified": False}))
|
||||
with self.assertRaisesRegex(ValueError, "different run, source"):
|
||||
gate.verify_cell(row, root, "123", "a" * 40, "b" * 64)
|
||||
|
||||
def test_share_accept_requires_real_difficulty_one_work(self):
|
||||
capture = {"nonce_source": "real_silicon_capture",
|
||||
"header80": "00" * 80,
|
||||
"pool_target_le": "ff" * 32, "nonce": 0,
|
||||
"submission": {"id": 4, "method": "mining.submit"},
|
||||
"pool_response": {"id": 4, "result": True, "error": None}}
|
||||
with self.assertRaisesRegex(ValueError, "below difficulty one"):
|
||||
gate.verify_accept(capture)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+11
-1
@@ -4,6 +4,7 @@
|
||||
use crate::HardwareBackend;
|
||||
use std::fmt;
|
||||
use std::io::{self, Read, Write};
|
||||
use std::net::Shutdown;
|
||||
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::os::unix::net::UnixStream;
|
||||
@@ -134,6 +135,9 @@ impl HalClient {
|
||||
if let Err(ref error) = result {
|
||||
if !matches!(error, HalError::Device(_)) {
|
||||
self.poisoned = true;
|
||||
// A backend power lease must expire on disconnect. Reusing a
|
||||
// desynchronized stream could silently discard an off request.
|
||||
let _ = self.stream.shutdown(Shutdown::Both);
|
||||
}
|
||||
}
|
||||
result
|
||||
@@ -180,6 +184,7 @@ impl HalClient {
|
||||
fn empty_reply(&mut self, opcode: u8, payload: &[u8]) -> Result<(), HalError> {
|
||||
if !self.exchange(opcode, payload)?.is_empty() {
|
||||
self.poisoned = true;
|
||||
let _ = self.stream.shutdown(Shutdown::Both);
|
||||
return Err(HalError::Protocol("unexpected response data"));
|
||||
}
|
||||
Ok(())
|
||||
@@ -388,6 +393,11 @@ impl HardwareBackend for HalClient {
|
||||
}
|
||||
|
||||
fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error> {
|
||||
self.empty_reply(SET_PSU_ENABLED, &[u8::from(enabled)])
|
||||
let result = self.empty_reply(SET_PSU_ENABLED, &[u8::from(enabled)]);
|
||||
if !enabled && result.is_err() {
|
||||
self.poisoned = true;
|
||||
let _ = self.stream.shutdown(Shutdown::Both);
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
+36
-3
@@ -13,6 +13,7 @@ use std::time::{Duration, Instant};
|
||||
|
||||
const MAX_PENDING_SHARES: usize = 32;
|
||||
const SHARE_REPLY_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const MINER_POOL_POLL_INTERVAL: Duration = Duration::from_millis(500);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ClientError<E> {
|
||||
@@ -24,6 +25,7 @@ pub enum ClientError<E> {
|
||||
TooManyPending,
|
||||
RequestIdsExhausted,
|
||||
ShareReplyTimeout,
|
||||
EmergencyShutdown(E),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -48,6 +50,7 @@ pub enum CycleError<E> {
|
||||
Pool(ClientError<E>),
|
||||
Miner(MinerError<E>),
|
||||
Submit(ClientError<()>),
|
||||
EmergencyShutdown(E),
|
||||
}
|
||||
|
||||
pub struct PoolConnection {
|
||||
@@ -82,7 +85,7 @@ impl PoolConnection {
|
||||
}
|
||||
|
||||
fn from_handshake(
|
||||
wire: StratumWire,
|
||||
mut wire: StratumWire,
|
||||
handshake: PoolHandshake,
|
||||
worker: &str,
|
||||
) -> Result<Self, SessionError> {
|
||||
@@ -91,6 +94,8 @@ impl PoolConnection {
|
||||
handshake.configure.version_mask,
|
||||
handshake.configure.subscribe_extranonce,
|
||||
)?;
|
||||
// Pool I/O must not postpone the next ASIC sensor check indefinitely.
|
||||
wire.set_timeout(MINER_POOL_POLL_INTERVAL);
|
||||
Ok(Self {
|
||||
wire,
|
||||
session,
|
||||
@@ -110,6 +115,9 @@ impl PoolConnection {
|
||||
let result = self.step_inner(miner);
|
||||
if result.is_err() {
|
||||
self.wire.close();
|
||||
if let Err(error) = miner.stop() {
|
||||
return Err(ClientError::EmergencyShutdown(error));
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -214,7 +222,15 @@ impl PoolConnection {
|
||||
let report = match miner.poll() {
|
||||
Ok(None) => ReportEvent::None,
|
||||
Ok(Some(share)) => {
|
||||
ReportEvent::Submitted(self.submit_share(share).map_err(CycleError::Submit)?)
|
||||
let id = match self.submit_share(share) {
|
||||
Ok(id) => id,
|
||||
Err(error) => {
|
||||
self.wire.close();
|
||||
miner.stop().map_err(CycleError::EmergencyShutdown)?;
|
||||
return Err(CycleError::Submit(error));
|
||||
}
|
||||
};
|
||||
ReportEvent::Submitted(id)
|
||||
}
|
||||
Err(MinerError::StaleReport) => ReportEvent::Stale,
|
||||
Err(MinerError::BelowTarget) => ReportEvent::BelowTarget,
|
||||
@@ -234,13 +250,16 @@ impl PoolConnection {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::stratum_v1::Subscription;
|
||||
use std::cell::Cell;
|
||||
use std::io::Write;
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::rc::Rc;
|
||||
use std::thread;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Backend {
|
||||
sent: Vec<Vec<u8>>,
|
||||
powered: Rc<Cell<bool>>,
|
||||
}
|
||||
|
||||
impl HardwareBackend for Backend {
|
||||
@@ -262,7 +281,8 @@ mod tests {
|
||||
fn read_temperature_mc(&mut self, _sensor: u8) -> Result<i32, Self::Error> {
|
||||
Ok(50_000)
|
||||
}
|
||||
fn set_psu_enabled(&mut self, _enabled: bool) -> Result<(), Self::Error> {
|
||||
fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error> {
|
||||
self.powered.set(enabled);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -386,4 +406,17 @@ mod tests {
|
||||
assert!(link.wire.is_closed());
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_pool_message_stops_miner_before_returning() {
|
||||
let (mut link, server) = test_link(b"{}\n");
|
||||
let mut backend = Backend::default();
|
||||
let powered = Rc::clone(&backend.powered);
|
||||
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
|
||||
miner.start().unwrap();
|
||||
assert!(powered.get());
|
||||
assert!(matches!(link.cycle(&mut miner), Err(CycleError::Pool(_))));
|
||||
assert!(!powered.get());
|
||||
server.join().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
+10
-3
@@ -56,6 +56,7 @@ pub struct PoolSession {
|
||||
active_difficulty: Option<PoolDifficulty>,
|
||||
extranonce2: [u8; 32],
|
||||
extranonce_exhausted: bool,
|
||||
zero_extranonce_headers: Vec<[u8; 80]>,
|
||||
tracked: [Option<TrackedWork>; 32],
|
||||
next_slot: usize,
|
||||
}
|
||||
@@ -77,6 +78,7 @@ impl PoolSession {
|
||||
active_difficulty: None,
|
||||
extranonce2: [0; 32],
|
||||
extranonce_exhausted: false,
|
||||
zero_extranonce_headers: Vec::new(),
|
||||
tracked: std::array::from_fn(|_| None),
|
||||
next_slot: 0,
|
||||
})
|
||||
@@ -104,6 +106,7 @@ impl PoolSession {
|
||||
self.subscription = subscription;
|
||||
self.extranonce2 = [0; 32];
|
||||
self.extranonce_exhausted = false;
|
||||
self.zero_extranonce_headers.clear();
|
||||
self.tracked = std::array::from_fn(|_| None);
|
||||
Ok(true)
|
||||
}
|
||||
@@ -136,15 +139,18 @@ impl PoolSession {
|
||||
if self.next_slot == self.tracked.len() {
|
||||
return Err(SessionError::WorkIdsExhausted);
|
||||
}
|
||||
if self.extranonce_exhausted {
|
||||
let size = self.subscription.extranonce2_size;
|
||||
if size != 0 && self.extranonce_exhausted {
|
||||
return Err(SessionError::ExtranonceExhausted);
|
||||
}
|
||||
let size = self.subscription.extranonce2_size;
|
||||
let extranonce2 = self.extranonce2[..size].to_vec();
|
||||
let header = job
|
||||
.work
|
||||
.nonce_zero_header(&extranonce2, job.work.ntime)
|
||||
.map_err(SessionError::Work)?;
|
||||
if size == 0 && self.zero_extranonce_headers.contains(&header) {
|
||||
return Err(SessionError::ExtranonceExhausted);
|
||||
}
|
||||
let target_le = difficulty.target_le();
|
||||
if job.clean_jobs {
|
||||
self.tracked = std::array::from_fn(|_| None);
|
||||
@@ -162,7 +168,7 @@ impl PoolSession {
|
||||
base_version: job.work.version,
|
||||
});
|
||||
if size == 0 {
|
||||
self.extranonce_exhausted = true;
|
||||
self.zero_extranonce_headers.push(header);
|
||||
} else {
|
||||
let mut carry = true;
|
||||
for byte in self.extranonce2[..size].iter_mut().rev() {
|
||||
@@ -250,6 +256,7 @@ impl PoolSession {
|
||||
pub fn after_hardware_reset(&mut self) {
|
||||
self.tracked = std::array::from_fn(|_| None);
|
||||
self.next_slot = 0;
|
||||
self.zero_extranonce_headers.clear();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+5
-7
@@ -184,14 +184,12 @@ pub fn parse_boolean_response(line: &[u8], request_id: u64) -> Result<bool, Pool
|
||||
if message.get("id").and_then(Value::as_u64) != Some(request_id) {
|
||||
return Err(PoolMessageError::WrongMessage);
|
||||
}
|
||||
let accepted = message
|
||||
.get("result")
|
||||
.and_then(Value::as_bool)
|
||||
.ok_or(PoolMessageError::InvalidField)?;
|
||||
if accepted && !message.get("error").is_none_or(Value::is_null) {
|
||||
return Err(PoolMessageError::InvalidField);
|
||||
match message.get("result") {
|
||||
Some(Value::Bool(true)) if message.get("error").is_none_or(Value::is_null) => Ok(true),
|
||||
Some(Value::Bool(false)) => Ok(false),
|
||||
Some(Value::Null) if !message.get("error").is_none_or(Value::is_null) => Ok(false),
|
||||
_ => Err(PoolMessageError::InvalidField),
|
||||
}
|
||||
Ok(accepted)
|
||||
}
|
||||
|
||||
/// Decode pool control notifications. The caller applies them in stream order:
|
||||
|
||||
@@ -47,6 +47,9 @@ pub struct StratumWire {
|
||||
}
|
||||
|
||||
impl StratumWire {
|
||||
pub(crate) fn set_timeout(&mut self, timeout: Duration) {
|
||||
self.timeout = timeout;
|
||||
}
|
||||
pub fn connect(address: SocketAddr, timeout: Duration) -> Result<Self, WireError> {
|
||||
if timeout.is_zero() || Instant::now().checked_add(timeout).is_none() {
|
||||
return Err(WireError::InvalidRequest);
|
||||
|
||||
@@ -77,6 +77,8 @@ fn rejects_wrong_response_sequence() {
|
||||
server.read_exact(&mut body).unwrap();
|
||||
header[8..12].copy_from_slice(&2_u32.to_le_bytes());
|
||||
reply(&mut server, &header, &[0]);
|
||||
let mut one = [0_u8; 1];
|
||||
assert_eq!(server.read(&mut one).unwrap(), 0);
|
||||
});
|
||||
let mut backend = HalClient::from_stream(client).unwrap();
|
||||
assert!(matches!(
|
||||
@@ -90,6 +92,27 @@ fn rejects_wrong_response_sequence() {
|
||||
worker.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_power_off_ends_backend_power_lease() {
|
||||
let (client, mut server) = UnixStream::pair().unwrap();
|
||||
let worker = thread::spawn(move || {
|
||||
let mut header = [0_u8; 16];
|
||||
server.read_exact(&mut header).unwrap();
|
||||
let mut body = [0_u8; 1];
|
||||
server.read_exact(&mut body).unwrap();
|
||||
assert_eq!(header[5], 6);
|
||||
assert_eq!(body, [0]);
|
||||
reply(&mut server, &header, &[3]);
|
||||
assert_eq!(server.read(&mut body).unwrap(), 0);
|
||||
});
|
||||
let mut backend = HalClient::from_stream(client).unwrap();
|
||||
assert!(matches!(
|
||||
backend.set_psu_enabled(false),
|
||||
Err(HalError::Device(3))
|
||||
));
|
||||
worker.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_malformed_error_response_and_poisoned_connection() {
|
||||
for body in [&[4_u8][..], &[3_u8, 99][..]] {
|
||||
|
||||
@@ -101,7 +101,7 @@ fn extranonce_change_invalidates_jobs_without_reusing_asic_ids() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_length_extranonce_can_be_issued_once() {
|
||||
fn zero_length_extranonce_requires_distinct_header_until_hardware_reset() {
|
||||
let mut pool = PoolSession::new(
|
||||
Subscription {
|
||||
extranonce1: vec![1],
|
||||
@@ -118,6 +118,10 @@ fn zero_length_extranonce_can_be_issued_once() {
|
||||
pool.issue_notify(notify("two", false).as_bytes()).err(),
|
||||
Some(SessionError::ExtranonceExhausted)
|
||||
);
|
||||
let distinct = notify("two", true).replace("66554433", "66554434");
|
||||
pool.issue_notify(distinct.as_bytes()).unwrap();
|
||||
pool.after_hardware_reset();
|
||||
pool.issue_notify(notify("three", true).as_bytes()).unwrap();
|
||||
}
|
||||
|
||||
struct FakeBackend {
|
||||
|
||||
@@ -136,6 +136,13 @@ fn both_bip310_extensions_and_boolean_responses_are_checked() {
|
||||
parse_boolean_response(br#"{"id":5,"result":false,"error":[23,"stale"]}"#, 5),
|
||||
Ok(false)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_boolean_response(
|
||||
br#"{"id":5,"result":null,"error":[21,"Job not found",null]}"#,
|
||||
5
|
||||
),
|
||||
Ok(false)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_boolean_response(br#"{"id":5,"result":true,"error":[23,"stale"]}"#, 5),
|
||||
Err(PoolMessageError::InvalidField)
|
||||
|
||||
Reference in New Issue
Block a user