From 7689d51e630357ce0a1bfc6f89f1eb2673932dbd Mon Sep 17 00:00:00 2001 From: John Calhoun Date: Sun, 29 Nov 2026 00:02:48 -0500 Subject: [PATCH 01/12] tests: the Lean's rows of the record and the door, and of LeafRows, each under its own machine (for #47) The rows file gains the 47 #guard lines of HandedRows from "The competitor's proof goes on the record" and the 5 of Tracker.LeafRows at bsv-stack-lean a7ef91de, with one row of the crate's own (the self refusal). Each row names its group and its machine, and each input of a trace the machine the source's run P or runR passes it through. The replay runs every row under its own machine (45 under the door, 8 under the latch, LeafRows' competitor named C listed as not spelled), then replays the latch's rows a second time through the door wherever stepRecheck_eq_step's premise holds at every step: the keeper's condition for one machine with a mode. Co-Authored-By: Claude Opus 5.5 --- tests/tracker_rows.rs | 715 +++++++++++++++++----- tests/vectors/tracker/rows_of_record.json | 147 +++-- 2 files changed, 661 insertions(+), 201 deletions(-) diff --git a/tests/tracker_rows.rs b/tests/tracker_rows.rs index 88bd5a5..332f0f3 100644 --- a/tests/tracker_rows.rs +++ b/tests/tracker_rows.rs @@ -1,19 +1,24 @@ //! The tracker machine's rows of record: `tests/vectors/tracker/rows_of_record.json`, //! each row one `#guard` of bsv-stack-lean's `lean/Tracker.lean` (the file's -//! `source` names the commit and the namespace), replayed through the crate's +//! `source` names the commit and the namespaces), replayed through the crate's //! public items. No row is a journal row. //! -//! A row names the machine it runs under, a start, a trace of inputs each -//! under named headers, and what the `#guard` asserts of the state after the -//! last input: its word, its list of instances, its re-ask, its equality with -//! another trace's state, or the spend guard's answer. The tracked +//! A row names its group (the word `handed`, the record and the door, the +//! leaf rows, or the crate's own), the machine it runs under (`step`, the +//! latch, or `recheck`, the machine with the door), a start, a trace of +//! inputs each under named headers and through a named machine, and what the +//! `#guard` asserts of the state after the last input. The tracked //! transaction is a txid nobody has bytes for, so its own proof is stated //! (`common::proof`); a competitor's proof is built from the competitor's own -//! bytes (`common::competitor`), and its id is the hash of those bytes. A -//! root named in the headers is the root of the file's proof that names it. +//! bytes, and its id is the hash of those bytes. A root named in the headers +//! is the root of the file's proof that names it. +//! +//! The Lean's machine answers no error: a step's error is the crate's word +//! beside the state, and the row judges the state. A row of the word names +//! none, so there an error is a divergence. //! //! A row the crate's public items cannot spell is listed by name with its -//! reason in `UNSPELLABLE` and printed; none of the rows of the word is. +//! reason in `UNSPELLABLE` and printed. // The lint bar binds the library; a test may unwrap, and its fixtures fail loudly // (bsv-stack-lean #134). #![allow( @@ -23,26 +28,39 @@ clippy::panic )] mod common; +use bsv_rs::transaction::{MerklePath, MerklePathLeaf}; use bsv_tracker::doubts::{self, AppRule, Doubts}; use bsv_tracker::*; use common::*; use serde_json::Value; +use std::cell::Cell; use std::collections::{BTreeMap, BTreeSet}; const ROWS_OF_RECORD: &str = include_str!("vectors/tracker/rows_of_record.json"); /// The rows the crate's public items cannot spell, by name, with the reason. -/// The rows of the word hold none. -const UNSPELLABLE: [(&str, &str); 0] = []; +const UNSPELLABLE: [(&str, &str); 1] = [( + "leaf.4", + "a competitor named C offered X's proof: the crate names a competitor by its proof's own txid \ + (Evidence::Competitor(Proof)), so a proof of another leaf cannot be offered for C", +)]; -/// The sibling every proof of the file is built with: one level, so a proof's -/// root is fixed by its txid and its height. +/// The sibling every proof of the file is built with, but the two of a root +/// two leaves share: one level, so a proof's root is fixed by its txid and +/// its height. const SIBLING: u64 = 1_000; -/// The source's `P`: `ageThreshold := 10, spendDepth := 1`. -fn machine(name: &str) -> Params { +/// A machine of the file under its parameters: the source's `P` +/// (`ageThreshold := 10, spendDepth := 1`) or `LeafRows`' `⟨0, 1⟩`. +fn machine(name: &str, params: &str) -> Params { + let p = match params { + "P" => Params::new(10, 1), + "P0" => Params::new(0, 1), + other => panic!("parameters this test does not know: {other}"), + }; match name { - "step" => Params::new(10, 1), + "step" => p, + "recheck" => p.with_recheck_conflicted(true), other => panic!("a machine this test does not know: {other}"), } } @@ -59,9 +77,20 @@ fn text(value: &Value) -> &str { value.as_str().expect("a string") } -/// The file's names: the tracked transaction and the competitors. +/// A block's hash: `hash(n)`, `n` its name's bytes read big-endian. +fn block_hash(name: &str) -> String { + assert!( + name.len() <= 8, + "{name}: a block name of at most eight bytes" + ); + hash(name.bytes().fold(0u64, |n, b| (n << 8) | u64::from(b))) +} + +/// The file's names: the tracked transaction and the competitors, and the +/// roots two leaves share (`root-B`: T at offset 0, X at 1). struct Names { tracked: String, + shared: BTreeMap, } impl Names { @@ -72,6 +101,34 @@ impl Names { _ => txid_of(&tx_bytes(competitor_n(name), 191)), } } + + /// The proof of `leaf` at `height` under the root named `root`: the + /// tracked transaction's stated, a competitor's built from its bytes. + fn proof(&self, leaf: &str, height: u32, root: &str) -> Proof { + let id = self.id(leaf); + let path = match self.shared.get(root) { + Some(pair) => { + let at = pair + .iter() + .position(|n| n == leaf) + .expect("a leaf of the root") as u64; + let other = self.id(&pair[1 - at as usize]); + MerklePath::new( + height, + vec![vec![ + MerklePathLeaf::new_txid(at, id.clone()), + MerklePathLeaf::new(1 - at, other), + ]], + ) + .unwrap() + } + None => path_of(&id, height, SIBLING), + }; + match leaf { + "T" => Proof::with_stated_len(&id, STATED_LEN, path).unwrap(), + c => Proof::new(&tx_bytes(competitor_n(c), 191), path).unwrap(), + } + } } /// A competitor's bytes are `tx_bytes(n, 191)`, `n` by its name. @@ -79,44 +136,86 @@ fn competitor_n(name: &str) -> u64 { match name { "X" => 2, "Z" => 3, + "V" => 4, + "C" => 5, other => panic!("a competitor this test does not know: {other}"), } } -/// The proof a row's input names, through the tests' shared helpers: the -/// tracked transaction's own proof stated, a competitor's from its bytes. -/// `None` when its leaf is not the name it is offered for. -fn proof_of_name(names: &Names, name: &str, height: u32, leaf: &str) -> Option { - if leaf != name { - return None; +/// Every input of every trace of the file, the rows' and those they compare +/// with. +fn every_input(file: &Value) -> Vec { + fn trace(t: &Value, out: &mut Vec) { + for step in t.as_array().unwrap() { + out.push(step[1].clone()); + } + } + let mut out = vec![]; + for row in file["rows"].as_array().unwrap() { + trace(&row["trace"], &mut out); + for (k, v) in row["expect"].as_object().unwrap() { + match k.as_str() { + "state_equals" | "evidence_equals" | "view_equals" | "view_differs" => { + trace(v, &mut out); + } + "state_with_reask" => trace(&v["trace"], &mut out), + _ => {} + } + } + } + out +} + +/// The proofs the file names, `(leaf, height, root)`. +fn named_proofs(file: &Value) -> Vec<(String, u32, String)> { + every_input(file) + .iter() + .filter_map(|input| { + let a = input.as_array().unwrap(); + match text(&a[0]) { + "proof" => Some(( + text(&a[3]).to_owned(), + height(&a[1]), + text(&a[2]).to_owned(), + )), + "competitor" => Some(( + text(&a[4]).to_owned(), + height(&a[2]), + text(&a[3]).to_owned(), + )), + _ => None, + } + }) + .collect() +} + +fn names(file: &Value) -> Names { + let mut leaves: BTreeMap> = BTreeMap::new(); + for (leaf, _, root) in named_proofs(file) { + leaves.entry(root).or_default().insert(leaf); + } + let shared = leaves + .into_iter() + .filter(|(_, l)| l.len() == 2) + .map(|(root, l)| { + let mut it = l.into_iter(); + (root, [it.next().unwrap(), it.next().unwrap()]) + }) + .collect(); + Names { + tracked: hash(1), + shared, } - Some(match name { - "T" => proof(&names.tracked, height, SIBLING), - c => competitor(competitor_n(c), height, SIBLING), - }) } /// Every named root: the root of the file's proof that names it, else (a /// root no proof reduces to) a value no proof of the file computes. fn roots(file: &Value, names: &Names) -> BTreeMap { let mut roots: BTreeMap = BTreeMap::new(); - for row in file["rows"].as_array().unwrap() { - for step in row["trace"].as_array().unwrap() { - let input = step[1].as_array().unwrap(); - let (name, h, root, leaf) = match text(&input[0]) { - "proof" => ("T", &input[1], &input[2], &input[3]), - "competitor" => (text(&input[1]), &input[2], &input[3], &input[4]), - _ => continue, - }; - let Some(p) = proof_of_name(names, name, height(h), text(leaf)) else { - continue; - }; - let computed = p.root().unwrap(); - let held = roots - .entry(text(root).to_owned()) - .or_insert(computed.clone()); - assert_eq!(held, &computed, "{}: one name, two roots", text(root)); - } + for (leaf, h, root) in named_proofs(file) { + let computed = names.proof(&leaf, h, &root).root().unwrap(); + let held = roots.entry(root.clone()).or_insert(computed.clone()); + assert_eq!(held, &computed, "{root}: one name, two roots"); } for (n, name) in file["roots"].as_object().unwrap().keys().enumerate() { roots @@ -128,7 +227,6 @@ fn roots(file: &Value, names: &Names) -> BTreeMap { /// The named headers: each height's block (its name's hash) and its root. fn headers(file: &Value, roots: &BTreeMap) -> BTreeMap { - let mut blocks: BTreeMap = BTreeMap::new(); let mut out = BTreeMap::new(); for (name, spec) in file["headers"].as_object().unwrap() { let mut h = TestHeaders { @@ -136,12 +234,10 @@ fn headers(file: &Value, roots: &BTreeMap) -> BTreeMap HintStatus { height: height(payload), }, "doubleSpend" => HintStatus::DoubleSpend { - competitors: payload - .as_array() - .unwrap() - .iter() - .map(|c| names.id(text(c))) - .collect(), + competitors: ids(names, payload), }, other => panic!("a hint status this test does not know: {other}"), } } +fn ids(names: &Names, value: &Value) -> Vec { + value + .as_array() + .unwrap() + .iter() + .map(|c| names.id(text(c))) + .collect() +} + fn hint_of(names: &Names, value: &[Value]) -> Hint { let source = text(&value[0]); Hint::new(source, status(names, &value[1], source), num(&value[2])) } +/// A chain event's header of a named block at `height`. +fn block_at(name: &str, height: u32) -> EventHeader { + EventHeader { + hash: block_hash(name), + ..event_header(height, 0) + } +} + /// One input of a row, or `Err` naming why the crate cannot spell it. fn input(names: &Names, value: &Value) -> Result { let a = value.as_array().expect("an input is an array"); let host = |action| Ok(Input::Host(action)); + let chain = |event| Ok(Input::Evidence(Evidence::Chain(event))); match text(&a[0]) { "build" => host(HostAction::Build), "abandon" => host(HostAction::Abandon), @@ -207,14 +316,19 @@ fn input(names: &Names, value: &Value) -> Result { instance: text(&a[1]).to_owned(), }), "hint" => Ok(Input::Hint(hint_of(names, &a[1..]))), - "proof" => proof_of_name(names, "T", height(&a[1]), text(&a[3])) - .map(|p| Input::Evidence(Evidence::Proof(p))) - .ok_or_else(|| format!("a proof of another leaf than the tracked: {value}")), - "competitor" => proof_of_name(names, text(&a[1]), height(&a[2]), text(&a[4])) - .map(|p| Input::Evidence(Evidence::Competitor(p))) - .ok_or_else(|| { - format!("a competitor named with another leaf's proof: the crate names a competitor by its proof's own txid: {value}") - }), + "proof" => Ok(Input::Evidence(Evidence::Proof(names.proof( + text(&a[3]), + height(&a[1]), + text(&a[2]), + )))), + "competitor" if text(&a[1]) != text(&a[4]) => Err(format!( + "a competitor named with another leaf's proof: the crate names a competitor by its proof's own txid: {value}" + )), + "competitor" => Ok(Input::Evidence(Evidence::Competitor(names.proof( + text(&a[4]), + height(&a[2]), + text(&a[3]), + )))), "verdict" => { let (kind, payload) = a[1].as_object().unwrap().iter().next().unwrap(); Ok(Input::Evidence(Evidence::Verdict(match kind.as_str() { @@ -222,16 +336,48 @@ fn input(names: &Names, value: &Value) -> Result { reason: text(payload).to_owned(), }, "conflicted" => NodeVerdict::Conflicted { - competitors: payload - .as_array() - .unwrap() - .iter() - .map(|c| names.id(text(c))) - .collect(), + competitors: ids(names, payload), }, other => panic!("a verdict this test does not know: {other}"), }))) } + "reorg" => { + let fh = height(&a[1]); + chain(ChainEvent::Reorg { + fork_height: fh, + depth: u32::try_from(num(&a[2])).unwrap(), + deactivated_headers: a[3] + .as_array() + .unwrap() + .iter() + .map(|b| block_at(text(b), fh)) + .collect(), + new_tip: block_at(text(&a[4]), fh + 1), + }) + } + "tip" => { + let h = height(&a[1]); + let header = block_at(text(&a[2]), h); + chain(ChainEvent::Tip { + height: h, + hash: header.hash.clone(), + time: header.time, + header, + }) + } + "fork" => { + let h = height(&a[1]); + let tips = a[2].as_array().unwrap(); + chain(ChainEvent::Fork { + height: h, + competing_tips: [block_at(text(&tips[0]), h), block_at(text(&tips[1]), h)], + depth: u32::try_from(num(&a[3])).unwrap(), + }) + } + "invalidated" => chain(ChainEvent::Invalidated { + block_hash: block_hash(text(&a[1])), + }), + "recheck" => Ok(Input::Evidence(Evidence::Recheck)), other => panic!("an input this test does not know: {other}"), } } @@ -255,17 +401,21 @@ fn word(names: &Names, value: &Value) -> Word { reason: text(payload).to_owned(), }, "conflicted" => Word::Conflicted { - competitors: payload - .as_array() - .unwrap() - .iter() - .map(|c| names.id(text(c))) - .collect(), + competitors: ids(names, payload), }, other => panic!("a word this test does not know: {other}"), } } +/// A word of the file against the state's: `{"mined": h}` is any `Mined` +/// word at `h`, the proof's own readers judged by the rows that name it. +fn word_is(names: &Names, w: &Word, want: &Value) -> bool { + match want.get("mined") { + Some(h) => matches!(w, Word::Mined(m) if m.height() == height(h)), + None => *w == word(names, want), + } +} + fn reask(names: &Names, value: &Value) -> Option { match value { Value::Null => None, @@ -280,6 +430,15 @@ fn reask(names: &Names, value: &Value) -> Option { (k, payload) if k == "hint" => { Some(Reask::Hint(hint_of(names, payload.as_array().unwrap()))) } + (k, payload) if k == "competitorGone" => Some(Reask::CompetitorGone { + competitors: ids(names, payload), + }), + (k, payload) if k == "fork" => Some(Reask::Fork { + height: height(payload), + }), + (k, payload) if k == "proofFailed" => Some(Reask::ProofFailed { + height: height(payload), + }), (k, _) => panic!("a re-ask this test does not know: {k}"), }, other => panic!("a re-ask this test does not know: {other}"), @@ -308,76 +467,233 @@ fn rule(value: &Value) -> Option { Some(AppRule::new(text(&value["name"]), allows)) } -/// The run of a trace from the tracked transaction's birth. A step's error -/// is a divergence: no row of the word answers one. -fn run( - names: &Names, - headers: &BTreeMap, - params: &Params, - trace: &Value, -) -> Result { - let mut s = State::new(&names.tracked); - for step in trace.as_array().unwrap() { - let h = &headers[text(&step[0])]; - let i = input(names, &step[1])?; - s.step(params, h, i.clone()) - .map_err(|e| format!("the step {i:?} answered {e:?}"))?; +/// Headers that count the reads asked of them. +struct Counting<'a> { + inner: &'a TestHeaders, + reads: Cell, +} + +impl Headers for Counting<'_> { + fn header_at(&self, height: u32) -> Result, HeaderError> { + self.reads.set(self.reads.get() + 1); + self.inner.header_at(height) } - Ok(s) -} - -/// What a row expects, against the state after its trace: `Err` names the -/// divergence. -fn judge( - names: &Names, - headers: &BTreeMap, - params: &Params, - s: &State, - expect: &Value, -) -> Result<(), String> { - let expect = expect.as_object().unwrap(); - assert_eq!(expect.len(), 1, "a row asserts one thing"); - let (what, want) = expect.iter().next().unwrap(); - let ok = match what.as_str() { - "word" => *s.word() == word(names, want), - "handed_to" => { - let list: Vec = want - .as_array() - .unwrap() - .iter() - .map(|p| HandedTo::new(text(&p[0]), num(&p[1]))) - .collect(); - s.handed_to() == list.as_slice() + fn tip_height(&self) -> Result { + self.inner.tip_height() + } +} + +/// How a replay runs a row: each input through the machine the file names, +/// or every input through the door (`Door`), where the Lean's +/// `stepRecheck_eq_step` states the two machines agree. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Mode { + AsWritten, + Door, +} + +/// What the replay of one trace gives. +enum Ran { + /// The state, and the crate's errors along the trace. + State(State, Vec), + /// Under `Mode::Door`, a step outside `stepRecheck_eq_step`'s premise: + /// a `conflicted` word met a chain event or a recheck. + Uncovered(String), +} + +/// The context of a replay. +struct Ctx<'a> { + names: &'a Names, + headers: &'a BTreeMap, + roots: &'a BTreeMap, + params: &'a str, + machine: &'a str, + mode: Mode, +} + +impl Ctx<'_> { + /// The run of a trace from the tracked transaction's birth. + fn run(&self, trace: &Value) -> Result { + let mut s = State::new(&self.names.tracked); + let mut errors = vec![]; + for step in trace.as_array().unwrap() { + let h = &self.headers[text(&step[0])]; + let i = input(self.names, &step[1])?; + let m = step.get(2).map_or(self.machine, text); + let params = match self.mode { + Mode::AsWritten => machine(m, self.params), + Mode::Door => { + let door_takes = + matches!(i, Input::Evidence(Evidence::Chain(_) | Evidence::Recheck)); + if matches!(s.word(), Word::Conflicted { .. }) && door_takes { + return Ok(Ran::Uncovered(format!( + "a conflicted word meets {}", + step[1] + ))); + } + machine("recheck", self.params) + } + }; + if let Err(e) = s.step(¶ms, h, i.clone()) { + errors.push(format!("the step {} answered {e:?}", step[1])); + } } - "reask" => s.reask() == reask(names, want).as_ref(), - "state_equals" => *s == run(names, headers, params, want)?, - "spendable" => { - let h = &headers[text(&want["headers"])]; - let ds = Doubts::cold(h.tip); - let rule = rule(&want["rule"]); - let answer = doubts::spendable_eff(params, h, &ds, rule.as_ref(), s); - answer == Ok(want["answer"].as_bool().unwrap()) + Ok(Ran::State(s, errors)) + } + + /// What a row expects, against the state after its trace: `Ok(false)` + /// when a compared trace is uncovered, `Err` the divergence. + fn judge(&self, s: &State, expect: &Value) -> Result { + let names = self.names; + let expect = expect.as_object().unwrap(); + assert_eq!(expect.len(), 1, "a row asserts one thing"); + let (what, want) = expect.iter().next().unwrap(); + let other = |trace: &Value| -> Result, String> { + match self.run(trace)? { + Ran::State(t, _) => Ok(Some(t)), + Ran::Uncovered(_) => Ok(None), + } + }; + let view = |s: &State| { + ( + s.word().chain().cloned(), + s.evidence().cloned(), + s.suspect(), + ) + }; + let ok = match what.as_str() { + "word" => word_is(names, s.word(), want), + "handed_to" => { + let list: Vec = want + .as_array() + .unwrap() + .iter() + .map(|p| HandedTo::new(text(&p[0]), num(&p[1]))) + .collect(); + s.handed_to() == list.as_slice() + } + "reask" => s.reask() == reask(names, want).as_ref(), + "prior" => match want { + Value::Null => s.prior().is_none(), + w => s.prior() == Some(&word(names, w)), + }, + "suspect" => s.suspect() == want.as_bool().unwrap(), + "rivals_gone" => { + let marks: Vec = s.rivals().iter().map(Competitor::gone).collect(); + let want: Vec = want + .as_array() + .unwrap() + .iter() + .map(|b| b.as_bool().unwrap()) + .collect(); + marks == want + } + "rivals" => { + let want = want.as_array().unwrap(); + s.rivals().len() == want.len() + && s.rivals().iter().zip(want).all(|(r, w)| { + let checked = match (&w[1], r.checked()) { + (Value::Null, None) => true, + (p, Some(c)) if !p.is_null() => { + let roots = |n: &Value| self.root(text(n)); + c.height() == height(&p["height"]) + && c.root() == roots(&p["root"]) + && c.proof().txid() == names.id(text(&p["leaf"])) + && c.header().hash == block_hash(text(&p["block"])) + && c.header().merkle_root == roots(&p["header_root"]) + } + _ => false, + }; + r.txid() == names.id(text(&w[0])) && checked && r.gone() == w[2] + }) + } + "state_equals" => match other(want)? { + Some(t) => *s == t, + None => return Ok(false), + }, + "evidence_equals" => match other(want)? { + Some(t) => s.evidence() == t.evidence(), + None => return Ok(false), + }, + "view_equals" | "view_differs" => match other(want)? { + Some(t) => (view(s) == view(&t)) == (what == "view_equals"), + None => return Ok(false), + }, + "state_with_reask" => match other(&want["trace"])? { + Some(t) => { + s.reask() == reask(names, &want["reask"]).as_ref() + && s.txid() == t.txid() + && s.word() == t.word() + && s.evidence() == t.evidence() + && s.suspect() == t.suspect() + && s.hints() == t.hints() + && s.last_hint_at() == t.last_hint_at() + && s.handed_to() == t.handed_to() + && s.rivals() == t.rivals() + && s.prior() == t.prior() + && s.tx_len() == t.tx_len() + } + None => return Ok(false), + }, + "conflict_reads" => { + let h = Counting { + inner: &self.headers["h0"], + reads: Cell::new(0), + }; + let mut t = s.clone(); + let _ = t.step( + &machine("recheck", self.params), + &h, + Input::Evidence(Evidence::Recheck), + ); + u64::from(h.reads.get()) == num(want) + } + "spendable" => { + let h = &self.headers[text(&want["headers"])]; + let ds = Doubts::cold(h.tip); + let rule = rule(&want["rule"]); + let params = machine(self.machine, self.params); + let answer = doubts::spendable_eff(¶ms, h, &ds, rule.as_ref(), s); + answer == Ok(want["answer"].as_bool().unwrap()) + } + other => panic!("an assertion this test does not know: {other}"), + }; + if ok { + Ok(true) + } else { + Err(format!("{what}: expected {want}, the state {s:?}")) } - other => panic!("an assertion this test does not know: {other}"), - }; - if ok { - Ok(()) - } else { - Err(format!("{what}: expected {want}, the state {s:?}")) } + + fn root(&self, name: &str) -> String { + self.roots[name].clone() + } +} + +/// The tally of one replay. +#[derive(Default)] +struct Tally { + /// Rows run, by machine. + ran: BTreeMap, + divergences: Vec, + unspellable: Vec, + /// Under `Mode::Door`, the rows `stepRecheck_eq_step` does not cover. + uncovered: Vec, + /// The crate's errors along the rows, by row. + errors: Vec, } -/// Every row the file runs under `machine`: `(rows, divergences, unspellable)`. -fn replay(machine_name: &str) -> (usize, Vec, Vec) { +/// Every row of `groups` the file runs, each under its own machine (or, +/// under `Mode::Door`, the rows of the latch through the door). +fn replay(groups: &[&str], mode: Mode) -> Tally { let file: Value = serde_json::from_str(ROWS_OF_RECORD).unwrap(); assert_eq!(file["schema"], "bsv-tracker-rows/1"); - let names = Names { tracked: hash(1) }; + let names = names(&file); let roots = roots(&file, &names); let headers = headers(&file, &roots); - let params = machine(machine_name); let listed: BTreeMap<&str, &str> = UNSPELLABLE.into_iter().collect(); let mut seen = BTreeSet::new(); - let (mut ran, mut divergences, mut unspellable) = (0, vec![], vec![]); + let mut tally = Tally::default(); for row in file["rows"].as_array().unwrap() { let name = text(&row["name"]); assert!(seen.insert(name), "{name}: named twice"); @@ -386,44 +702,135 @@ fn replay(machine_name: &str) -> (usize, Vec, Vec) { "{name}: a start this test does not know" ); assert!(row["lean"].as_str().is_some_and(|l| !l.is_empty())); - if row["machine"] != machine_name { + let group = text(&row["group"]); + if !groups.contains(&group) { + continue; + } + let m = text(&row["machine"]); + if mode == Mode::Door && m != "step" { continue; } - ran += 1; + *tally.ran.entry(m.to_owned()).or_default() += 1; if let Some(why) = listed.get(name) { - unspellable.push(format!("{name}: {why}")); + tally.unspellable.push(format!("{name}: {why}")); continue; } - let verdict = run(&names, &headers, ¶ms, &row["trace"]) - .and_then(|s| judge(&names, &headers, ¶ms, &s, &row["expect"])); - if let Err(why) = verdict { - divergences.push(format!("{name} ({}): {why}", text(&row["lean"]))); + let ctx = Ctx { + names: &names, + headers: &headers, + roots: &roots, + params: row.get("params").map_or("P", text), + machine: m, + mode, + }; + let verdict = ctx.run(&row["trace"]).and_then(|ran| match ran { + Ran::Uncovered(why) => Ok(Some(why)), + Ran::State(s, errors) => { + if !errors.is_empty() { + if group == "handed" { + return Err(errors.join("; ")); + } + tally.errors.push(format!("{name}: {}", errors.join("; "))); + } + ctx.judge(&s, &row["expect"]) + .map(|covered| (!covered).then(|| "a compared trace is uncovered".to_owned())) + } + }); + match verdict { + Ok(None) => {} + Ok(Some(why)) => tally.uncovered.push(format!("{name}: {why}")), + Err(why) => tally + .divergences + .push(format!("{name} ({}): {why}", text(&row["lean"]))), } } - assert_eq!( - Some(ran as u64), - file["counts"][machine_name].as_u64(), - "the file's count under {machine_name}" - ); - (ran, divergences, unspellable) + if mode == Mode::AsWritten { + for group in groups { + let want: BTreeMap = + serde_json::from_value(file["counts"][group].clone()).unwrap(); + let mut got = BTreeMap::new(); + for row in file["rows"].as_array().unwrap() { + if row["group"] == *group { + *got.entry(text(&row["machine"]).to_owned()).or_default() += 1; + } + } + assert_eq!(got, want, "the file's counts of {group}"); + } + } + tally } -/// The rows of the word `handed`, under the machine without the recheck. -#[test] -fn rows_of_record_handed() { - let (ran, divergences, unspellable) = replay("step"); - for line in &unspellable { +fn print(tally: &Tally) { + for line in &tally.unspellable { println!("not spelled: {line}"); } - for line in &divergences { + for line in &tally.errors { + println!("the crate's error beside the state: {line}"); + } + for line in &tally.uncovered { + println!("not covered by stepRecheck_eq_step: {line}"); + } + for line in &tally.divergences { println!("divergence: {line}"); } +} + +/// The rows of the word `handed`, under the machine without the recheck. +#[test] +fn rows_of_record_handed() { + let tally = replay(&["handed"], Mode::AsWritten); + print(&tally); + let ran = tally.ran.get("step").copied().unwrap_or(0); println!( "rows_of_record_handed: {ran} rows under step, {} divergences, {} not spelled", - divergences.len(), - unspellable.len() + tally.divergences.len(), + tally.unspellable.len() ); assert_eq!(ran, 46, "the rows of the word hold 46 rows"); - assert!(divergences.is_empty(), "{divergences:#?}"); - assert!(unspellable.is_empty()); + assert_eq!(tally.ran.len(), 1); + assert!(tally.divergences.is_empty(), "{:#?}", tally.divergences); + assert!(tally.unspellable.is_empty()); +} + +/// The rows of the record and the door, the leaf rows and the crate's own, +/// each under its own machine; then every row of the latch in the file (the +/// word's 46 among them) a second time through the door, where the Lean's +/// `stepRecheck_eq_step` states the two machines agree: every step of the +/// row's trace, and of a trace it compares with, meets a word that is not +/// `conflicted` or an input that is neither a chain event nor a recheck. +/// +/// No row of the file starts from a state stored before the record existed +/// (each starts at `State.init "T"`), so no row is one the crate answers +/// ahead of the Lean (its named join, `docs/VERIFICATION.md`): the count of +/// such rows is printed, and is 0. +#[test] +fn rows_of_record_recheck() { + let tally = replay(&["recheck", "leaf", "crate"], Mode::AsWritten); + print(&tally); + let under = |m: &str| tally.ran.get(m).copied().unwrap_or(0); + let ran: usize = tally.ran.values().sum(); + println!( + "rows_of_record_recheck: {ran} rows, {} under recheck and {} under step, {} divergences, {} not spelled, 0 ahead of the Lean", + under("recheck"), + under("step"), + tally.divergences.len(), + tally.unspellable.len() + ); + assert_eq!((under("recheck"), under("step")), (45, 8)); + assert!(tally.divergences.is_empty(), "{:#?}", tally.divergences); + assert_eq!(tally.unspellable.len(), 1); + + let door = replay(&["handed", "recheck", "leaf", "crate"], Mode::Door); + print(&door); + let ran = door.ran.get("step").copied().unwrap_or(0); + let spelled = ran - door.unspellable.len(); + println!( + "rows_of_record_latch_through_the_door: {} of {ran} rows of the latch covered by stepRecheck_eq_step and replayed under recheck, {} not covered, {} divergences, {} not spelled", + spelled - door.uncovered.len(), + door.uncovered.len(), + door.divergences.len(), + door.unspellable.len() + ); + assert_eq!(ran, 54); + assert!(door.divergences.is_empty(), "{:#?}", door.divergences); } diff --git a/tests/vectors/tracker/rows_of_record.json b/tests/vectors/tracker/rows_of_record.json index 2b018e5..ca56d25 100644 --- a/tests/vectors/tracker/rows_of_record.json +++ b/tests/vectors/tracker/rows_of_record.json @@ -1,48 +1,101 @@ -{"schema": "bsv-tracker-rows/1", "source": "bsv-stack-lean@a7ef91de104944e3b02c920a935e8549c19dcc89 lean/Tracker.lean (blob c2a6045a), namespace Tracker.HandedRows, the rows of the word handed: from the heading \"The hand-over\" through \"The spend gate\", 46 #guard lines", "rule": "one row, one #guard: each row is one #guard of the source, in its order, its text verbatim in lean; nothing is invented and no row is a journal row. The rows of the record and the door (47, from \"The competitor's proof goes on the record\") and the 5 of Tracker.LeafRows are not in this file yet", "naming": "a row is named by its heading in the source and its place under it (hand_over.4 is the fourth #guard under \"The hand-over\"); a #guard that reads a named definition carries that definition's name (handedConflicted, dischargedAborted)", "machines": {"step": "the Lean's step, the machine without the recheck of conflicted: State::step under Params::new(10, 1), the source's P (ageThreshold 10, spendDepth 1)"}, "start": {"init": "State.init \"T\": State::new of the tracked transaction's txid"}, "names": {"T": "the tracked transaction: hash(1), a txid nobody has bytes for; its own proof is stated at STATED_LEN (tests/common/mod.rs, proof)", "X": "a competitor: the bytes tx_bytes(2, 191); its id is the hash of those bytes, and its proof is built from them (tests/common/mod.rs, competitor)"}, "headers": {"h0": {"tip": 99, "at": []}, "hX": {"tip": 100, "at": [[100, "B100", "root-X"]]}, "hT": {"tip": 102, "at": [[101, "B101b", "root-T"], [100, "B100b", "root-Y"]]}}, "roots": {"root-T": "the root of T's proof at 101", "root-X": "the root of X's proof at 100", "root-Y": "a root no proof of the file reduces to"}, "inputs": {"build": "[\"build\"] is .host .build", "abandon": "[\"abandon\"] is .host .abandon", "hand": "[\"hand\", i, t] is hand i t: .host (.handOver i t), HostAction::HandOver { instance: i, at: t }", "discharge": "[\"discharge\", i] is .host (.discharge i)", "endHold": "[\"endHold\"] is .host .endHold", "tick": "[\"tick\", t] is .host (.tick t)", "hint": "[\"hint\", src, status, t] is hint src status t: Hint::new(src, status, t); mempoolPresent carries the hint's own source as the crate's MempoolPresent { source }; a name in doubleSpend is that name's id", "proof": "[\"proof\", height, root, leaf] is .evidence (.proof ⟨height, root, leaf⟩)", "competitor": "[\"competitor\", c, height, root, leaf] is .evidence (.competitor c ⟨height, root, leaf⟩)", "verdict": "[\"verdict\", v] is .evidence (.verdict v)"}, "expect": {"word": "the word: a name, or {\"conflicted\": [names]}, {\"rejected\": reason}, {\"mined\": height}", "handed_to": "State::handed_to as [instance, at] pairs", "reask": "State::reask: null, a name, or {\"hint\": [src, status, t]}", "state_equals": "the state equals the state of this other trace from the same start", "spendable": "doubts::spendable_eff under the named headers, Doubts::cold at their tip and the rule (null for none; else a rule that allows the one word it names)"}, "counts": {"step": 46},"rows":[ -{"name": "hand_over.1", "trace": [["h0", ["build"]], ["h0", ["hand", "arc", 1]]], "expect": {"word": "handed"}, "lean": "(runH [.host .build, hand \"arc\" 1]).word == .handed", "machine": "step", "start": "init"}, -{"name": "hand_over.2", "trace": [["h0", ["build"]], ["h0", ["hand", "arc", 1]]], "expect": {"handed_to": [["arc", 1]]}, "lean": "(runH [.host .build, hand \"arc\" 1]).handedTo == [(\"arc\", 1)]", "machine": "step", "start": "init"}, -{"name": "hand_over.3", "trace": [["h0", ["hand", "arc", 1]]], "expect": {"word": "handed"}, "lean": "(runH [hand \"arc\" 1]).word == .handed", "machine": "step", "start": "init"}, -{"name": "hand_over.4", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hand", "taal", 2]], ["h0", ["hand", "arc", 5]]], "expect": {"handed_to": [["arc", 5], ["taal", 2]]}, "lean": "(runH [hand \"arc\" 1, hand \"taal\" 2, hand \"arc\" 5]).handedTo == [(\"arc\", 5), (\"taal\", 2)]", "machine": "step", "start": "init"}, -{"name": "hand_over.5", "trace": [["h0", ["build"]], ["h0", ["hint", "arc", "accepted", 1]], ["h0", ["hand", "arc", 9]]], "expect": {"word": "announced"}, "lean": "(runH [.host .build, hint \"arc\" .accepted 1, hand \"arc\" 9]).word == .announced", "machine": "step", "start": "init"}, -{"name": "hand_over.6", "trace": [["h0", ["build"]], ["h0", ["hint", "arc", "accepted", 1]], ["h0", ["hand", "arc", 9]]], "expect": {"handed_to": []}, "lean": "(runH [.host .build, hint \"arc\" .accepted 1, hand \"arc\" 9]).handedTo == []", "machine": "step", "start": "init"}, -{"name": "hand_over.7", "trace": [["h0", ["build"]], ["h0", ["abandon"]], ["h0", ["hand", "arc", 1]]], "expect": {"state_equals": [["h0", ["build"]], ["h0", ["abandon"]]]}, "lean": "(runH [.host .build, .host .abandon, hand \"arc\" 1]) == (runH [.host .build, .host .abandon])", "machine": "step", "start": "init"}, -{"name": "hints_on_handed.1", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", "accepted", 2]]], "expect": {"word": "announced"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" .accepted 2]).word == .announced", "machine": "step", "start": "init"}, -{"name": "hints_on_handed.2", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", "accepted", 2]]], "expect": {"handed_to": []}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" .accepted 2]).handedTo == []", "machine": "step", "start": "init"}, -{"name": "hints_on_handed.3", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "peer", "mempoolPresent", 2]]], "expect": {"word": "announced"}, "lean": "(runH [hand \"arc\" 1, hint \"peer\" .mempoolPresent 2]).word == .announced", "machine": "step", "start": "init"}, -{"name": "hints_on_handed.4", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", "seen", 2]]], "expect": {"word": "seen"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" .seen 2]).word == .seen", "machine": "step", "start": "init"}, -{"name": "hints_on_handed.5", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", {"rejected": "476"}, 2]]], "expect": {"word": "handed"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" (.rejected \"476\") 2]).word == .handed", "machine": "step", "start": "init"}, -{"name": "hints_on_handed.6", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", {"rejected": "476"}, 2]]], "expect": {"reask": {"hint": ["arc", {"rejected": "476"}, 2]}}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" (.rejected \"476\") 2]).reask == some (.hint ⟨\"arc\", .rejected \"476\", 2⟩)", "machine": "step", "start": "init"}, -{"name": "hints_on_handed.7", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", {"rejected": "476"}, 2]]], "expect": {"handed_to": [["arc", 1]]}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" (.rejected \"476\") 2]).handedTo == [(\"arc\", 1)]", "machine": "step", "start": "init"}, -{"name": "hints_on_handed.8", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", {"doubleSpend": ["X"]}, 2]]], "expect": {"word": "handed"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" (.doubleSpend [\"X\"]) 2]).word == .handed", "machine": "step", "start": "init"}, -{"name": "hints_on_handed.9", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", "orphanMempool", 2]]], "expect": {"word": "handed"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" .orphanMempool 2]).word == .handed", "machine": "step", "start": "init"}, -{"name": "hints_on_handed.10", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", "unknown", 2]]], "expect": {"word": "handed"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" .unknown 2]).word == .handed", "machine": "step", "start": "init"}, -{"name": "hints_on_handed.11", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", {"mined": 7}, 2]]], "expect": {"word": "handed"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" (.mined 7) 2]).word == .handed", "machine": "step", "start": "init"}, -{"name": "hints_on_handed.12", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", "staleBlock", 2]]], "expect": {"word": "handed"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" .staleBlock 2]).word == .handed", "machine": "step", "start": "init"}, -{"name": "discharge.1", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["discharge", "arc"]]], "expect": {"word": "built"}, "lean": "(runH [hand \"arc\" 1, .host (.discharge \"arc\")]).word == .built", "machine": "step", "start": "init"}, -{"name": "discharge.2", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["discharge", "arc"]]], "expect": {"handed_to": []}, "lean": "(runH [hand \"arc\" 1, .host (.discharge \"arc\")]).handedTo == []", "machine": "step", "start": "init"}, -{"name": "discharge.3", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hand", "taal", 2]], ["h0", ["discharge", "arc"]]], "expect": {"word": "handed"}, "lean": "(runH [hand \"arc\" 1, hand \"taal\" 2, .host (.discharge \"arc\")]).word == .handed", "machine": "step", "start": "init"}, -{"name": "discharge.4", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hand", "taal", 2]], ["h0", ["discharge", "arc"]]], "expect": {"handed_to": [["taal", 2]]}, "lean": "(runH [hand \"arc\" 1, hand \"taal\" 2, .host (.discharge \"arc\")]).handedTo == [(\"taal\", 2)]", "machine": "step", "start": "init"}, -{"name": "discharge.5", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["discharge", "nobody"]]], "expect": {"state_equals": [["h0", ["hand", "arc", 1]]]}, "lean": "(runH [hand \"arc\" 1, .host (.discharge \"nobody\")]) == (runH [hand \"arc\" 1])", "machine": "step", "start": "init"}, -{"name": "discharge.6", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", "accepted", 2]], ["h0", ["discharge", "arc"]]], "expect": {"word": "announced"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" .accepted 2, .host (.discharge \"arc\")]).word == .announced", "machine": "step", "start": "init"}, -{"name": "w4_abort_during_a_post.1", "trace": [["h0", ["build"]], ["h0", ["hand", "arc", 1]], ["h0", ["abandon"]]], "expect": {"word": "handed"}, "lean": "(runH [.host .build, hand \"arc\" 1, .host .abandon]).word == .handed", "machine": "step", "start": "init"}, -{"name": "w4_abort_during_a_post.2", "trace": [["h0", ["build"]], ["h0", ["hand", "arc", 1]], ["h0", ["abandon"]], ["h0", ["hint", "arc", "accepted", 3]]], "expect": {"word": "announced"}, "lean": "(runH [.host .build, hand \"arc\" 1, .host .abandon, hint \"arc\" .accepted 3]).word == .announced", "machine": "step", "start": "init"}, -{"name": "w4_abort_during_a_post.3", "trace": [["h0", ["build"]], ["h0", ["abandon"]], ["h0", ["hint", "arc", "accepted", 3]]], "expect": {"word": "abandoned"}, "lean": "(runH [.host .build, .host .abandon, hint \"arc\" .accepted 3]).word == .abandoned", "machine": "step", "start": "init"}, -{"name": "clock.1", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["tick", 10]]], "expect": {"reask": null}, "lean": "(runH [hand \"arc\" 1, .host (.tick 10)]).reask == none", "machine": "step", "start": "init"}, -{"name": "clock.2", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["tick", 11]]], "expect": {"reask": "reannounce"}, "lean": "(runH [hand \"arc\" 1, .host (.tick 11)]).reask == some .reannounce", "machine": "step", "start": "init"}, -{"name": "clock.3", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hand", "taal", 8]], ["h0", ["tick", 11]]], "expect": {"reask": "reannounce"}, "lean": "(runH [hand \"arc\" 1, hand \"taal\" 8, .host (.tick 11)]).reask == some .reannounce", "machine": "step", "start": "init"}, -{"name": "clock.4", "trace": [["h0", ["build"]], ["h0", ["tick", 1000]]], "expect": {"reask": null}, "lean": "(runH [.host .build, .host (.tick 1000)]).reask == none", "machine": "step", "start": "init"}, -{"name": "clock.5", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["tick", 11]], ["h0", ["hand", "arc", 11]]], "expect": {"reask": null}, "lean": "(runH [hand \"arc\" 1, .host (.tick 11), hand \"arc\" 11]).reask == none", "machine": "step", "start": "init"}, -{"name": "clock.6", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["tick", 11]], ["h0", ["hand", "arc", 11]], ["h0", ["tick", 20]]], "expect": {"reask": null}, "lean": "(runH [hand \"arc\" 1, .host (.tick 11), hand \"arc\" 11, .host (.tick 20)]).reask == none", "machine": "step", "start": "init"}, -{"name": "clock.7", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["tick", 11]], ["h0", ["hand", "arc", 11]], ["h0", ["tick", 21]]], "expect": {"reask": "reannounce"}, "lean": "(runH [hand \"arc\" 1, .host (.tick 11), hand \"arc\" 11, .host (.tick 21)]).reask == some .reannounce", "machine": "step", "start": "init"}, -{"name": "evidence_empties_the_list.1", "trace": [["h0", ["hand", "arc", 1]], ["hT", ["proof", 101, "root-T", "T"]]], "expect": {"handed_to": []}, "lean": "(run P (runH [hand \"arc\" 1]) [(hT, .evidence (.proof ⟨101, \"root-T\", \"T\"⟩))]).handedTo == []", "machine": "step", "start": "init"}, -{"name": "evidence_empties_the_list.2", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["verdict", {"rejected": "bad"}]]], "expect": {"handed_to": []}, "lean": "(runH [hand \"arc\" 1, .evidence (.verdict (.rejected \"bad\"))]).handedTo == []", "machine": "step", "start": "init"}, -{"name": "evidence_empties_the_list.3", "trace": [["h0", ["hand", "arc", 1]], ["hX", ["competitor", "X", 100, "root-X", "X"]]], "expect": {"handed_to": [["arc", 1]]}, "lean": "(run P (runH [hand \"arc\" 1]) [(hX, comp)]).handedTo == [(\"arc\", 1)]", "machine": "step", "start": "init"}, -{"name": "end_of_a_hold.1", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["endHold"]]], "expect": {"word": "abandoned"}, "lean": "(runH [hand \"arc\" 1, .host .endHold]).word == .abandoned", "machine": "step", "start": "init"}, -{"name": "end_of_a_hold.2", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["endHold"]]], "expect": {"handed_to": []}, "lean": "(runH [hand \"arc\" 1, .host .endHold]).handedTo == []", "machine": "step", "start": "init"}, -{"name": "end_of_a_hold.3", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", "accepted", 2]], ["h0", ["endHold"]]], "expect": {"word": "announced"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" .accepted 2, .host .endHold]).word == .announced", "machine": "step", "start": "init"}, -{"name": "handedConflicted", "trace": [["h0", ["hand", "arc", 1]], ["hX", ["competitor", "X", 100, "root-X", "X"]]], "expect": {"word": {"conflicted": ["X"]}}, "lean": "handedConflicted.word == .conflicted [\"X\"]", "machine": "step", "start": "init"}, -{"name": "dischargedAborted", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["discharge", "arc"]], ["h0", ["abandon"]]], "expect": {"word": "abandoned"}, "lean": "dischargedAborted.word == .abandoned", "machine": "step", "start": "init"}, -{"name": "spend_gate.1", "trace": [["h0", ["hand", "arc", 1]]], "expect": {"spendable": {"headers": "h0", "rule": null, "answer": false}}, "lean": "spendable P h0 none (runH [hand \"arc\" 1]) == false", "machine": "step", "start": "init"}, -{"name": "spend_gate.2", "trace": [["h0", ["hand", "arc", 1]]], "expect": {"spendable": {"headers": "h0", "rule": {"name": "names built", "allows": "built"}, "answer": false}}, "lean": "spendable P h0 (some ⟨\"names built\", fun w => w == .built⟩) (runH [hand \"arc\" 1]) == false", "machine": "step", "start": "init"}, -{"name": "spend_gate.3", "trace": [["h0", ["hand", "arc", 1]]], "expect": {"spendable": {"headers": "h0", "rule": {"name": "names handed", "allows": "handed"}, "answer": true}}, "lean": "spendable P h0 (some ⟨\"names handed\", fun w => w == .handed⟩) (runH [hand \"arc\" 1]) == true", "machine": "step", "start": "init"} +{"schema": "bsv-tracker-rows/1", "source": "bsv-stack-lean@a7ef91de104944e3b02c920a935e8549c19dcc89 lean/Tracker.lean (blob c2a6045a): namespace Tracker.HandedRows, all 93 #guard lines (the 46 of the word handed, from the heading \"The hand-over\" through \"The spend gate\", group handed; the 47 of the record and the door, from \"The competitor's proof goes on the record\" to the namespace's end, group recheck), and namespace Tracker.LeafRows, its 5 #guard lines (group leaf)", "rule": "one row, one #guard: each row of the groups handed, recheck and leaf is one #guard of the source, in its order, its text verbatim in lean (a #guard continued on a second line is joined by one space); nothing is invented and no row is a journal row. The group crate holds the crate's own rows, which no #guard states: its lean names the theorem the row instances", "naming": "a row is named by its heading in the source and its place under it (hand_over.4 is the fourth #guard under \"The hand-over\", on_the_record.2 the second under \"The competitor's proof goes on the record\", leaf.3 the third of Tracker.LeafRows); a heading named for a definition carries that definition's name (handedConflicted, seenReturns, sameViewOtherRecord.2, forkThenTip.4)", "machines": {"step": "the Lean's step, the machine without the recheck of conflicted: State::step under Params::new(10, 1), the source's P (ageThreshold 10, spendDepth 1)", "recheck": "the Lean's stepRecheck, the machine with the door: State::step under Params::new(10, 1).with_recheck_conflicted(true)"}, "start": {"init": "State.init \"T\": State::new of the tracked transaction's txid"}, "names": {"T": "the tracked transaction: hash(1), a txid nobody has bytes for; its own proof is stated at STATED_LEN (tests/common/mod.rs, proof)", "X": "a competitor: the bytes tx_bytes(2, 191); its id is the hash of those bytes, and its proof is built from them (tests/common/mod.rs, competitor)", "Z": "a competitor: the bytes tx_bytes(3, 191), as X", "V": "a competitor a node's verdict names: the id of the bytes tx_bytes(4, 191); no proof of it is offered", "C": "the name LeafRows offers X's proof for (leaf.4): the crate names a competitor by its proof's own txid, so it cannot be spelled"}, "headers": {"h0": {"tip": 99, "at": []}, "hX": {"tip": 100, "at": [[100, "B100", "root-X"]]}, "hY": {"tip": 101, "at": [[100, "B100b", "root-Y"]]}, "hT": {"tip": 102, "at": [[101, "B101b", "root-T"], [100, "B100b", "root-Y"]]}, "hXZ": {"tip": 100, "at": [[100, "B100", "root-X"], [99, "B99", "root-Z"]]}, "hYZ": {"tip": 101, "at": [[100, "B100b", "root-Y"], [99, "B99", "root-Z"]]}, "hA": {"tip": 98, "at": [[98, "B98", "root-A"]]}, "hA'": {"tip": 98, "at": [[98, "B98b", "root-A2"]]}, "hB": {"tip": 100, "at": [[100, "B100", "root-B"]]}}, "roots": {"root-T": "the root of T's proof at 101", "root-X": "the root of X's proof at 100", "root-Y": "a root no proof of the file reduces to", "root-Z": "the root of Z's proof at 99", "root-A": "the root of T's proof at 98", "root-A2": "a root no proof of the file reduces to", "root-B": "LeafRows' block at 100 holding T and X: each one's proof names the other as its sibling, T at offset 0 and X at 1, so the two proofs share the root"}, "inputs": {"build": "[\"build\"] is .host .build", "abandon": "[\"abandon\"] is .host .abandon", "hand": "[\"hand\", i, t] is hand i t: .host (.handOver i t), HostAction::HandOver { instance: i, at: t }", "discharge": "[\"discharge\", i] is .host (.discharge i)", "endHold": "[\"endHold\"] is .host .endHold", "tick": "[\"tick\", t] is .host (.tick t)", "hint": "[\"hint\", src, status, t] is hint src status t: Hint::new(src, status, t); mempoolPresent carries the hint's own source as the crate's MempoolPresent { source }; a name in doubleSpend is that name's id", "proof": "[\"proof\", height, root, leaf] is .evidence (.proof ⟨height, root, leaf⟩): the leaf's own proof (T's stated, a competitor's from its bytes) offered as the tracked transaction's", "competitor": "[\"competitor\", c, height, root, leaf] is .evidence (.competitor c ⟨height, root, leaf⟩)", "verdict": "[\"verdict\", v] is .evidence (.verdict v)", "reorg": "[\"reorg\", fh, d, [blocks], tip] is .evidence (.chain (.reorg fh d blocks tip)): ChainEvent::Reorg { fork_height: fh, depth: d, deactivated_headers: the named blocks, new_tip: the named block }", "tip": "[\"tip\", h, block] is .evidence (.chain (.tip h block)): ChainEvent::Tip at h with the named block's hash", "fork": "[\"fork\", h, [a, b], d] is .evidence (.chain (.fork h [a, b] d)): ChainEvent::Fork { height: h, competing_tips: the two named blocks, depth: d }", "invalidated": "[\"invalidated\", block] is .evidence (.chain (.invalidated block))", "recheck": "[\"recheck\"] is .evidence .recheck"}, "expect": {"word": "the word: a name, or {\"conflicted\": [names]}, {\"rejected\": reason}, {\"mined\": height}", "handed_to": "State::handed_to as [instance, at] pairs", "reask": "State::reask: null, a name, {\"hint\": [src, status, t]}, {\"competitorGone\": [names]}, {\"fork\": height} or {\"proofFailed\": height}", "state_equals": "the state equals the state of this other trace from the same start", "spendable": "doubts::spendable_eff under the named headers, Doubts::cold at their tip and the rule (null for none; else a rule that allows the one word it names)", "prior": "State::prior: null or a word", "suspect": "State::suspect", "rivals": "State::rivals, each [name, null or {height, root, leaf, block, header_root}, gone]: the txid, the checked proof and its header, the mark", "rivals_gone": "State::rivals' marks, in order", "evidence_equals": "State::evidence equals the evidence of the state of this other trace", "view_equals": "the Lean's view (word.chain(), evidence(), suspect()) equals the view of this other trace's state", "view_differs": "the view differs from the view of this other trace's state", "conflict_reads": "the Lean's conflictReads: the header reads of one Evidence::Recheck of the state under the door, counted", "state_with_reask": "the state equals the state of this other trace in every reader but the re-ask, which is the one named"}, "counts": {"handed": {"step": 46}, "recheck": {"recheck": 45, "step": 2}, "leaf": {"step": 5}, "crate": {"step": 1}}, "params": {"P": "the default: ageThreshold 10, spendDepth 1 (HandedRows.P)", "P0": "⟨0, 1⟩: ageThreshold 0, spendDepth 1, the parameters Tracker.LeafRows writes"}, "groups": {"handed": "the 46 rows of the word handed (HandedRows, \"The hand-over\" through \"The spend gate\")", "recheck": "the 47 rows of the record and the door (HandedRows, from \"The competitor's proof goes on the record\")", "leaf": "the 5 rows of Tracker.LeafRows", "crate": "the crate's own rows, no #guard of the source"}, "blocks": "a block's name is its hash's source: hash(n) where n is the name's bytes read big-endian; the chain events name blocks by the same names", "trace": "a trace is a list of [headers, input, machine]: each input under the named headers and through the named machine, as the source's run P (step) and runR (stepRecheck) build it; a row of the word's 46 names no machine per input and runs under its own","rows":[ +{"name": "hand_over.1", "trace": [["h0", ["build"]], ["h0", ["hand", "arc", 1]]], "expect": {"word": "handed"}, "lean": "(runH [.host .build, hand \"arc\" 1]).word == .handed", "machine": "step", "start": "init", "group": "handed"}, +{"name": "hand_over.2", "trace": [["h0", ["build"]], ["h0", ["hand", "arc", 1]]], "expect": {"handed_to": [["arc", 1]]}, "lean": "(runH [.host .build, hand \"arc\" 1]).handedTo == [(\"arc\", 1)]", "machine": "step", "start": "init", "group": "handed"}, +{"name": "hand_over.3", "trace": [["h0", ["hand", "arc", 1]]], "expect": {"word": "handed"}, "lean": "(runH [hand \"arc\" 1]).word == .handed", "machine": "step", "start": "init", "group": "handed"}, +{"name": "hand_over.4", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hand", "taal", 2]], ["h0", ["hand", "arc", 5]]], "expect": {"handed_to": [["arc", 5], ["taal", 2]]}, "lean": "(runH [hand \"arc\" 1, hand \"taal\" 2, hand \"arc\" 5]).handedTo == [(\"arc\", 5), (\"taal\", 2)]", "machine": "step", "start": "init", "group": "handed"}, +{"name": "hand_over.5", "trace": [["h0", ["build"]], ["h0", ["hint", "arc", "accepted", 1]], ["h0", ["hand", "arc", 9]]], "expect": {"word": "announced"}, "lean": "(runH [.host .build, hint \"arc\" .accepted 1, hand \"arc\" 9]).word == .announced", "machine": "step", "start": "init", "group": "handed"}, +{"name": "hand_over.6", "trace": [["h0", ["build"]], ["h0", ["hint", "arc", "accepted", 1]], ["h0", ["hand", "arc", 9]]], "expect": {"handed_to": []}, "lean": "(runH [.host .build, hint \"arc\" .accepted 1, hand \"arc\" 9]).handedTo == []", "machine": "step", "start": "init", "group": "handed"}, +{"name": "hand_over.7", "trace": [["h0", ["build"]], ["h0", ["abandon"]], ["h0", ["hand", "arc", 1]]], "expect": {"state_equals": [["h0", ["build"]], ["h0", ["abandon"]]]}, "lean": "(runH [.host .build, .host .abandon, hand \"arc\" 1]) == (runH [.host .build, .host .abandon])", "machine": "step", "start": "init", "group": "handed"}, +{"name": "hints_on_handed.1", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", "accepted", 2]]], "expect": {"word": "announced"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" .accepted 2]).word == .announced", "machine": "step", "start": "init", "group": "handed"}, +{"name": "hints_on_handed.2", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", "accepted", 2]]], "expect": {"handed_to": []}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" .accepted 2]).handedTo == []", "machine": "step", "start": "init", "group": "handed"}, +{"name": "hints_on_handed.3", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "peer", "mempoolPresent", 2]]], "expect": {"word": "announced"}, "lean": "(runH [hand \"arc\" 1, hint \"peer\" .mempoolPresent 2]).word == .announced", "machine": "step", "start": "init", "group": "handed"}, +{"name": "hints_on_handed.4", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", "seen", 2]]], "expect": {"word": "seen"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" .seen 2]).word == .seen", "machine": "step", "start": "init", "group": "handed"}, +{"name": "hints_on_handed.5", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", {"rejected": "476"}, 2]]], "expect": {"word": "handed"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" (.rejected \"476\") 2]).word == .handed", "machine": "step", "start": "init", "group": "handed"}, +{"name": "hints_on_handed.6", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", {"rejected": "476"}, 2]]], "expect": {"reask": {"hint": ["arc", {"rejected": "476"}, 2]}}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" (.rejected \"476\") 2]).reask == some (.hint ⟨\"arc\", .rejected \"476\", 2⟩)", "machine": "step", "start": "init", "group": "handed"}, +{"name": "hints_on_handed.7", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", {"rejected": "476"}, 2]]], "expect": {"handed_to": [["arc", 1]]}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" (.rejected \"476\") 2]).handedTo == [(\"arc\", 1)]", "machine": "step", "start": "init", "group": "handed"}, +{"name": "hints_on_handed.8", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", {"doubleSpend": ["X"]}, 2]]], "expect": {"word": "handed"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" (.doubleSpend [\"X\"]) 2]).word == .handed", "machine": "step", "start": "init", "group": "handed"}, +{"name": "hints_on_handed.9", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", "orphanMempool", 2]]], "expect": {"word": "handed"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" .orphanMempool 2]).word == .handed", "machine": "step", "start": "init", "group": "handed"}, +{"name": "hints_on_handed.10", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", "unknown", 2]]], "expect": {"word": "handed"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" .unknown 2]).word == .handed", "machine": "step", "start": "init", "group": "handed"}, +{"name": "hints_on_handed.11", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", {"mined": 7}, 2]]], "expect": {"word": "handed"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" (.mined 7) 2]).word == .handed", "machine": "step", "start": "init", "group": "handed"}, +{"name": "hints_on_handed.12", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", "staleBlock", 2]]], "expect": {"word": "handed"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" .staleBlock 2]).word == .handed", "machine": "step", "start": "init", "group": "handed"}, +{"name": "discharge.1", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["discharge", "arc"]]], "expect": {"word": "built"}, "lean": "(runH [hand \"arc\" 1, .host (.discharge \"arc\")]).word == .built", "machine": "step", "start": "init", "group": "handed"}, +{"name": "discharge.2", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["discharge", "arc"]]], "expect": {"handed_to": []}, "lean": "(runH [hand \"arc\" 1, .host (.discharge \"arc\")]).handedTo == []", "machine": "step", "start": "init", "group": "handed"}, +{"name": "discharge.3", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hand", "taal", 2]], ["h0", ["discharge", "arc"]]], "expect": {"word": "handed"}, "lean": "(runH [hand \"arc\" 1, hand \"taal\" 2, .host (.discharge \"arc\")]).word == .handed", "machine": "step", "start": "init", "group": "handed"}, +{"name": "discharge.4", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hand", "taal", 2]], ["h0", ["discharge", "arc"]]], "expect": {"handed_to": [["taal", 2]]}, "lean": "(runH [hand \"arc\" 1, hand \"taal\" 2, .host (.discharge \"arc\")]).handedTo == [(\"taal\", 2)]", "machine": "step", "start": "init", "group": "handed"}, +{"name": "discharge.5", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["discharge", "nobody"]]], "expect": {"state_equals": [["h0", ["hand", "arc", 1]]]}, "lean": "(runH [hand \"arc\" 1, .host (.discharge \"nobody\")]) == (runH [hand \"arc\" 1])", "machine": "step", "start": "init", "group": "handed"}, +{"name": "discharge.6", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", "accepted", 2]], ["h0", ["discharge", "arc"]]], "expect": {"word": "announced"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" .accepted 2, .host (.discharge \"arc\")]).word == .announced", "machine": "step", "start": "init", "group": "handed"}, +{"name": "w4_abort_during_a_post.1", "trace": [["h0", ["build"]], ["h0", ["hand", "arc", 1]], ["h0", ["abandon"]]], "expect": {"word": "handed"}, "lean": "(runH [.host .build, hand \"arc\" 1, .host .abandon]).word == .handed", "machine": "step", "start": "init", "group": "handed"}, +{"name": "w4_abort_during_a_post.2", "trace": [["h0", ["build"]], ["h0", ["hand", "arc", 1]], ["h0", ["abandon"]], ["h0", ["hint", "arc", "accepted", 3]]], "expect": {"word": "announced"}, "lean": "(runH [.host .build, hand \"arc\" 1, .host .abandon, hint \"arc\" .accepted 3]).word == .announced", "machine": "step", "start": "init", "group": "handed"}, +{"name": "w4_abort_during_a_post.3", "trace": [["h0", ["build"]], ["h0", ["abandon"]], ["h0", ["hint", "arc", "accepted", 3]]], "expect": {"word": "abandoned"}, "lean": "(runH [.host .build, .host .abandon, hint \"arc\" .accepted 3]).word == .abandoned", "machine": "step", "start": "init", "group": "handed"}, +{"name": "clock.1", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["tick", 10]]], "expect": {"reask": null}, "lean": "(runH [hand \"arc\" 1, .host (.tick 10)]).reask == none", "machine": "step", "start": "init", "group": "handed"}, +{"name": "clock.2", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["tick", 11]]], "expect": {"reask": "reannounce"}, "lean": "(runH [hand \"arc\" 1, .host (.tick 11)]).reask == some .reannounce", "machine": "step", "start": "init", "group": "handed"}, +{"name": "clock.3", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hand", "taal", 8]], ["h0", ["tick", 11]]], "expect": {"reask": "reannounce"}, "lean": "(runH [hand \"arc\" 1, hand \"taal\" 8, .host (.tick 11)]).reask == some .reannounce", "machine": "step", "start": "init", "group": "handed"}, +{"name": "clock.4", "trace": [["h0", ["build"]], ["h0", ["tick", 1000]]], "expect": {"reask": null}, "lean": "(runH [.host .build, .host (.tick 1000)]).reask == none", "machine": "step", "start": "init", "group": "handed"}, +{"name": "clock.5", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["tick", 11]], ["h0", ["hand", "arc", 11]]], "expect": {"reask": null}, "lean": "(runH [hand \"arc\" 1, .host (.tick 11), hand \"arc\" 11]).reask == none", "machine": "step", "start": "init", "group": "handed"}, +{"name": "clock.6", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["tick", 11]], ["h0", ["hand", "arc", 11]], ["h0", ["tick", 20]]], "expect": {"reask": null}, "lean": "(runH [hand \"arc\" 1, .host (.tick 11), hand \"arc\" 11, .host (.tick 20)]).reask == none", "machine": "step", "start": "init", "group": "handed"}, +{"name": "clock.7", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["tick", 11]], ["h0", ["hand", "arc", 11]], ["h0", ["tick", 21]]], "expect": {"reask": "reannounce"}, "lean": "(runH [hand \"arc\" 1, .host (.tick 11), hand \"arc\" 11, .host (.tick 21)]).reask == some .reannounce", "machine": "step", "start": "init", "group": "handed"}, +{"name": "evidence_empties_the_list.1", "trace": [["h0", ["hand", "arc", 1]], ["hT", ["proof", 101, "root-T", "T"]]], "expect": {"handed_to": []}, "lean": "(run P (runH [hand \"arc\" 1]) [(hT, .evidence (.proof ⟨101, \"root-T\", \"T\"⟩))]).handedTo == []", "machine": "step", "start": "init", "group": "handed"}, +{"name": "evidence_empties_the_list.2", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["verdict", {"rejected": "bad"}]]], "expect": {"handed_to": []}, "lean": "(runH [hand \"arc\" 1, .evidence (.verdict (.rejected \"bad\"))]).handedTo == []", "machine": "step", "start": "init", "group": "handed"}, +{"name": "evidence_empties_the_list.3", "trace": [["h0", ["hand", "arc", 1]], ["hX", ["competitor", "X", 100, "root-X", "X"]]], "expect": {"handed_to": [["arc", 1]]}, "lean": "(run P (runH [hand \"arc\" 1]) [(hX, comp)]).handedTo == [(\"arc\", 1)]", "machine": "step", "start": "init", "group": "handed"}, +{"name": "end_of_a_hold.1", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["endHold"]]], "expect": {"word": "abandoned"}, "lean": "(runH [hand \"arc\" 1, .host .endHold]).word == .abandoned", "machine": "step", "start": "init", "group": "handed"}, +{"name": "end_of_a_hold.2", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["endHold"]]], "expect": {"handed_to": []}, "lean": "(runH [hand \"arc\" 1, .host .endHold]).handedTo == []", "machine": "step", "start": "init", "group": "handed"}, +{"name": "end_of_a_hold.3", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["hint", "arc", "accepted", 2]], ["h0", ["endHold"]]], "expect": {"word": "announced"}, "lean": "(runH [hand \"arc\" 1, hint \"arc\" .accepted 2, .host .endHold]).word == .announced", "machine": "step", "start": "init", "group": "handed"}, +{"name": "handedConflicted", "trace": [["h0", ["hand", "arc", 1]], ["hX", ["competitor", "X", 100, "root-X", "X"]]], "expect": {"word": {"conflicted": ["X"]}}, "lean": "handedConflicted.word == .conflicted [\"X\"]", "machine": "step", "start": "init", "group": "handed"}, +{"name": "dischargedAborted", "trace": [["h0", ["hand", "arc", 1]], ["h0", ["discharge", "arc"]], ["h0", ["abandon"]]], "expect": {"word": "abandoned"}, "lean": "dischargedAborted.word == .abandoned", "machine": "step", "start": "init", "group": "handed"}, +{"name": "spend_gate.1", "trace": [["h0", ["hand", "arc", 1]]], "expect": {"spendable": {"headers": "h0", "rule": null, "answer": false}}, "lean": "spendable P h0 none (runH [hand \"arc\" 1]) == false", "machine": "step", "start": "init", "group": "handed"}, +{"name": "spend_gate.2", "trace": [["h0", ["hand", "arc", 1]]], "expect": {"spendable": {"headers": "h0", "rule": {"name": "names built", "allows": "built"}, "answer": false}}, "lean": "spendable P h0 (some ⟨\"names built\", fun w => w == .built⟩) (runH [hand \"arc\" 1]) == false", "machine": "step", "start": "init", "group": "handed"}, +{"name": "spend_gate.3", "trace": [["h0", ["hand", "arc", 1]]], "expect": {"spendable": {"headers": "h0", "rule": {"name": "names handed", "allows": "handed"}, "answer": true}}, "lean": "spendable P h0 (some ⟨\"names handed\", fun w => w == .handed⟩) (runH [hand \"arc\" 1]) == true", "machine": "step", "start": "init", "group": "handed"}, +{"name": "on_the_record.1", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"]], "expect": {"word": {"conflicted": ["X"]}}, "lean": "conflictedT.word == .conflicted [\"X\"]"}, +{"name": "on_the_record.2", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"]], "expect": {"prior": "announced"}, "lean": "conflictedT.prior == some .announced"}, +{"name": "on_the_record.3", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"]], "expect": {"rivals": [["X", {"height": 100, "root": "root-X", "leaf": "X", "block": "B100", "header_root": "root-X"}, false]]}, "lean": "conflictedT.rivals == [⟨\"X\", some ⟨⟨100, \"root-X\", \"X\"⟩, ⟨\"B100\", \"root-X\"⟩⟩, false⟩]"}, +{"name": "returned.1", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"word": "announced"}, "lean": "returned.word == .announced"}, +{"name": "returned.2", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"reask": {"competitorGone": ["X"]}}, "lean": "returned.reask == some (.competitorGone [\"X\"])"}, +{"name": "returned.3", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"suspect": false}, "lean": "returned.suspect == false"}, +{"name": "returned.4", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"rivals_gone": [true]}, "lean": "returned.rivals.map (·.gone) == [true]"}, +{"name": "returned.5", "group": "recheck", "machine": "step", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "step"]], "expect": {"state_equals": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"]]}, "lean": "run P conflictedT [(hY, reorgRow 100)] == conflictedT"}, +{"name": "bound.1", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 101, 1, ["B100"], "B101b"], "recheck"]], "expect": {"state_equals": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"]]}, "lean": "runR conflictedT [(hY, reorgRow 101)] == conflictedT"}, +{"name": "bound.2", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hX", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"word": {"conflicted": ["X"]}}, "lean": "(runR conflictedT [(hX, reorgRow 100)]).word == .conflicted [\"X\"]"}, +{"name": "bound.3", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hX", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"suspect": false}, "lean": "(runR conflictedT [(hX, reorgRow 100)]).suspect == false"}, +{"name": "bound.4", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hX", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"reask": null}, "lean": "(runR conflictedT [(hX, reorgRow 100)]).reask == none"}, +{"name": "fail_closed.1", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["h0", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"word": {"conflicted": ["X"]}}, "lean": "behind.word == .conflicted [\"X\"]"}, +{"name": "fail_closed.2", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["h0", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"suspect": true}, "lean": "behind.suspect == true"}, +{"name": "fail_closed.3", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["h0", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"reask": "recheck"}, "lean": "behind.reask == some .recheck"}, +{"name": "fail_closed.4", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["h0", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"], ["hY", ["tip", 101, "B101b"], "recheck"]], "expect": {"word": "announced"}, "lean": "(runR behind [(hY, tipRow)]).word == .announced"}, +{"name": "seenReturns", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "seen", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"word": "announced"}, "lean": "seenReturns.word == .announced"}, +{"name": "rejectedReturns.1", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["hand", "arc", 1], "step"], ["h0", ["verdict", {"rejected": "bad"}], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"]], "expect": {"word": {"conflicted": ["X"]}}, "lean": "(runR rejectedT [(hX, comp)]).word == .conflicted [\"X\"]"}, +{"name": "rejectedReturns.2", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["hand", "arc", 1], "step"], ["h0", ["verdict", {"rejected": "bad"}], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"word": {"rejected": "bad"}}, "lean": "rejectedReturns.word == .rejected \"bad\""}, +{"name": "returnHanded.1", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["hand", "arc", 1], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"word": "handed"}, "lean": "returnHanded.word == .handed"}, +{"name": "returnHanded.2", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["hand", "arc", 1], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"handed_to": [["arc", 1]]}, "lean": "returnHanded.handedTo == [(\"arc\", 1)]"}, +{"name": "other_words.1", "group": "recheck", "machine": "step", "start": "init", "trace": [["hA", ["proof", 98, "root-A", "T"], "step"], ["hA'", ["reorg", 98, 1, ["B98"], "B98b"], "step"]], "expect": {"word": "stale"}, "lean": "staleT.word == .stale"}, +{"name": "other_words.2", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["hA", ["proof", 98, "root-A", "T"], "step"], ["hA'", ["reorg", 98, 1, ["B98"], "B98b"], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"word": "stale"}, "lean": "(runR staleT [(hX, comp), (hY, reorgRow 100)]).word == .stale"}, +{"name": "other_words.3", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["hA", ["proof", 98, "root-A", "T"], "step"], ["hA'", ["reorg", 98, 1, ["B98"], "B98b"], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"evidence_equals": [["hA", ["proof", 98, "root-A", "T"], "step"], ["hA'", ["reorg", 98, 1, ["B98"], "B98b"], "step"]]}, "lean": "(runR staleT [(hX, comp), (hY, reorgRow 100)]).evidence == staleT.evidence"}, +{"name": "other_words.4", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["abandon"], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"word": "abandoned"}, "lean": "(runR (runH [.host .build, .host .abandon]) [(hX, comp), (hY, reorgRow 100)]).word == .abandoned"}, +{"name": "other_words.5", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"word": "built"}, "lean": "(runR (runH [.host .build]) [(hX, comp), (hY, reorgRow 100)]).word == .built"}, +{"name": "other_words.6", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"]], "expect": {"word": {"conflicted": ["X"]}}, "lean": "again.word == .conflicted [\"X\"]"}, +{"name": "other_words.7", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"]], "expect": {"prior": "announced"}, "lean": "again.prior == some .announced"}, +{"name": "other_words.8", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"]], "expect": {"rivals_gone": [false]}, "lean": "again.rivals.map (·.gone) == [false]"}, +{"name": "host_acts_under_conflicted.1", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["hand", "arc", 1], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "step"], ["hY", ["endHold"], "recheck"], ["hY", ["discharge", "arc"], "recheck"], ["hY", ["hand", "taal", 9], "recheck"]], "expect": {"word": {"conflicted": ["X"]}}, "lean": "(runR handedConflicted [(hY, .host .endHold), (hY, .host (.discharge \"arc\")), (hY, hand \"taal\" 9)]).word == .conflicted [\"X\"]"}, +{"name": "host_acts_under_conflicted.2", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["hand", "arc", 1], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "step"], ["hT", ["proof", 101, "root-T", "T"], "recheck"]], "expect": {"handed_to": []}, "lean": "(runR handedConflicted [(hT, .evidence (.proof ⟨101, \"root-T\", \"T\"⟩))]).handedTo == []"}, +{"name": "two_competitors.1", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hXZ", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hXZ", ["competitor", "Z", 99, "root-Z", "Z"], "recheck"]], "expect": {"word": {"conflicted": ["Z", "X"]}}, "lean": "two.word == .conflicted [\"Z\", \"X\"]"}, +{"name": "two_competitors.2", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hXZ", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hXZ", ["competitor", "Z", 99, "root-Z", "Z"], "recheck"]], "expect": {"conflict_reads": 2}, "lean": "conflictReads two == 2"}, +{"name": "two_competitors.3", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hXZ", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hXZ", ["competitor", "Z", 99, "root-Z", "Z"], "recheck"], ["hYZ", ["reorg", 99, 1, ["B100"], "B101b"], "recheck"]], "expect": {"word": {"conflicted": ["Z"]}}, "lean": "(runR two [(hYZ, reorgRow 99)]).word == .conflicted [\"Z\"]"}, +{"name": "two_competitors.4", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hXZ", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hXZ", ["competitor", "Z", 99, "root-Z", "Z"], "recheck"], ["hYZ", ["reorg", 99, 1, ["B100"], "B101b"], "recheck"]], "expect": {"rivals_gone": [false, true]}, "lean": "(runR two [(hYZ, reorgRow 99)]).rivals.map (·.gone) == [false, true]"}, +{"name": "sameViewOtherRecord.1", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"]], "expect": {"view_equals": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["verdict", {"conflicted": ["X"]}], "recheck"]]}, "lean": "view conflictedT == view namedX"}, +{"name": "sameViewOtherRecord.2", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]], "expect": {"view_differs": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["verdict", {"conflicted": ["X"]}], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"]]}, "lean": "sameViewOtherRecord.1 != sameViewOtherRecord.2"}, +{"name": "named_never_leaves.1", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["verdict", {"conflicted": ["V"]}], "recheck"]], "expect": {"word": {"conflicted": ["V"]}}, "lean": "named.word == .conflicted [\"V\"]"}, +{"name": "named_never_leaves.2", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["verdict", {"conflicted": ["V"]}], "recheck"], ["hY", ["reorg", 0, 1, ["B100"], "B101b"], "recheck"], ["hY", ["recheck"], "recheck"], ["hY", ["tip", 101, "B101b"], "recheck"]], "expect": {"word": {"conflicted": ["V"]}}, "lean": "(runR named [(hY, reorgRow 0), (hY, .evidence .recheck), (hY, tipRow)]).word == .conflicted [\"V\"]"}, +{"name": "no_word_on_a_broadcaster", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["hint", "arc", {"mined": 101}, 9], "recheck"], ["hY", ["hint", "arc", "accepted", 9], "recheck"], ["hY", ["hint", "arc", "seen", 9], "recheck"]], "expect": {"word": {"conflicted": ["X"]}}, "lean": "(runR conflictedT [(hY, hint \"arc\" (.mined 101) 9), (hY, hint \"arc\" .accepted 9), (hY, hint \"arc\" .seen 9)]).word == .conflicted [\"X\"]"}, +{"name": "forkThenTip.1", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hX", ["fork", 100, ["a", "b"], 1], "recheck"]], "expect": {"suspect": true}, "lean": "forked.suspect == true"}, +{"name": "forkThenTip.2", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hX", ["fork", 100, ["a", "b"], 1], "recheck"]], "expect": {"reask": {"fork": 100}}, "lean": "forked.reask == some (.fork 100)"}, +{"name": "forkThenTip.3", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hX", ["fork", 100, ["a", "b"], 1], "recheck"], ["hY", ["tip", 101, "B101b"], "recheck"]], "expect": {"word": "announced"}, "lean": "forkThenTip.word == .announced"}, +{"name": "forkThenTip.4", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["tip", 101, "B101b"], "recheck"]], "expect": {"state_equals": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"]]}, "lean": "runR conflictedT [(hY, tipRow)] == conflictedT"}, +{"name": "forkThenTip.5", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["invalidated", "B100"], "recheck"]], "expect": {"word": "announced"}, "lean": "(runR conflictedT [(hY, .evidence (.chain (.invalidated \"B100\")))]).word == .announced"}, +{"name": "returned_then_mined.1", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hY", ["reorg", 100, 1, ["B100"], "B101b"], "recheck"], ["hT", ["proof", 101, "root-T", "T"], "recheck"]], "expect": {"word": {"mined": 101}}, "lean": "(runR returned [(hT, .evidence (.proof ⟨101, \"root-T\", \"T\"⟩))]).word == .mined 101"}, +{"name": "returned_then_mined.2", "group": "recheck", "machine": "recheck", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hX", ["competitor", "X", 100, "root-X", "X"], "recheck"], ["hT", ["proof", 101, "root-T", "T"], "recheck"]], "expect": {"word": {"mined": 101}}, "lean": "(runR conflictedT [(hT, .evidence (.proof ⟨101, \"root-T\", \"T\"⟩))]).word == .mined 101"}, +{"name": "leaf.1", "group": "leaf", "machine": "step", "start": "init", "trace": [["hB", ["proof", 100, "root-B", "X"], "step"]], "expect": {"word": "unknown"}, "lean": "(step ⟨0, 1⟩ hB (State.init \"T\") (.evidence (.proof pX))).word == .unknown", "params": "P0"}, +{"name": "leaf.2", "group": "leaf", "machine": "step", "start": "init", "trace": [["hB", ["proof", 100, "root-B", "X"], "step"]], "expect": {"reask": {"proofFailed": 100}}, "lean": "(step ⟨0, 1⟩ hB (State.init \"T\") (.evidence (.proof pX))).reask == some (.proofFailed 100)", "params": "P0"}, +{"name": "leaf.3", "group": "leaf", "machine": "step", "start": "init", "trace": [["hB", ["proof", 100, "root-B", "T"], "step"]], "expect": {"word": {"mined": 100}}, "lean": "(step ⟨0, 1⟩ hB (State.init \"T\") (.evidence (.proof pT))).word == .mined 100", "params": "P0"}, +{"name": "leaf.4", "group": "leaf", "machine": "step", "start": "init", "trace": [["hB", ["competitor", "C", 100, "root-B", "X"], "step"]], "expect": {"word": "unknown"}, "lean": "(step ⟨0, 1⟩ hB (State.init \"T\") (.evidence (.competitor \"C\" pX))).word == .unknown", "params": "P0"}, +{"name": "leaf.5", "group": "leaf", "machine": "step", "start": "init", "trace": [["hB", ["competitor", "X", 100, "root-B", "X"], "step"]], "expect": {"word": {"conflicted": ["X"]}}, "lean": "(step ⟨0, 1⟩ hB (State.init \"T\") (.evidence (.competitor \"X\" pX))).word == .conflicted [\"X\"]", "params": "P0"}, +{"name": "self_competitor_refused", "group": "crate", "machine": "step", "start": "init", "trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"], ["hT", ["competitor", "T", 101, "root-T", "T"], "step"]], "expect": {"state_with_reask": {"trace": [["h0", ["build"], "step"], ["h0", ["hand", "arc", 1], "step"], ["h0", ["hint", "arc", "accepted", 2], "step"]], "reask": {"proofFailed": 101}}}, "lean": "competitor_is_another: step P hd s (.evidence (.competitor s.txid p)) = { s with reask := some (.proofFailed p.height) }, at s := taken"} ]} From ae6df0e263866d6e279470cddab4be3c4ad4c2b0 Mon Sep 17 00:00:00 2001 From: John Calhoun Date: Sun, 29 Nov 2026 00:02:48 -0500 Subject: [PATCH 02/12] tests: three of the four properties over both machines, competitors from their bytes (for #47) mined_implies_checked_proof, stale_iff_header_inactive and hint_changes_no_chain_word run each trace under the latch and under the door, with two competitors whose proofs are built from their bytes; a hint writes no record. same_evidence_same_word stays over the latch: theorem (iv) is a statement of step, and sameViewOtherRecord shows equal views part over the door. Co-Authored-By: Claude Opus 5.5 --- tests/properties.rs | 292 +++++++++++++++++++++++++------------------- 1 file changed, 166 insertions(+), 126 deletions(-) diff --git a/tests/properties.rs b/tests/properties.rs index 23ec317..015e3e2 100644 --- a/tests/properties.rs +++ b/tests/properties.rs @@ -10,6 +10,16 @@ //! three of the hand-over (for #56): a hand-over to one of three instances, //! a discharge, the end of a hold; the word `handed`'s own statements are //! `tests/handed_properties.rs`. +//! +//! Three of the four run each trace under both machines (for #47): the latch +//! (the Lean's `step`) and the machine with the door +//! (`Params::recheck_conflicted`, the Lean's `stepRecheck`), and a +//! competitor's proof is one of two competitors' (`tx_bytes(2, 191)` and +//! `tx_bytes(3, 191)`), built from its bytes. `same_evidence_same_word` runs +//! over the latch alone: theorem (iv) is a statement of `step`, and over the +//! door two hosts agree on the word only where they hold the same record of +//! the conflict (the Lean's `sameViewOtherRecord`); the recheck's own +//! statements are `tests/recheck_properties.rs`. // The lint bar binds the library; a test may unwrap, and its fixtures fail loudly // (bsv-stack-lean #134). #![allow( @@ -24,6 +34,19 @@ use common::*; use proptest::prelude::*; use proptest::test_runner::{Config, RngAlgorithm, TestRng, TestRunner}; +/// The two machines: the latch, then the machine with the door. +const MODES: [bool; 2] = [false, true]; + +/// The tests' parameters under the machine `door` names. +fn machine(door: bool) -> Params { + params().with_recheck_conflicted(door) +} + +/// A hint or a host act, which answers no error, under `p`. +fn play(s: &mut State, p: &Params, h: &TestHeaders, i: Input) { + s.step(p, h, i).unwrap(); +} + fn runner() -> TestRunner { TestRunner::new_with_rng( Config { @@ -87,12 +110,13 @@ fn host(code: u8, observed: u64) -> Input { /// of the state and no input (the plan's K12). fn act( s: &mut State, + p: &Params, subject: &Subject, h: &TestHeaders, a: Option, ) -> Result<(), CheckError> { match a { - Some(i) => s.step(¶ms(), h, i), + Some(i) => s.step(p, h, i), None => subject.measure(s), } } @@ -112,7 +136,7 @@ fn input( return None; } let own = subject.own(height, sibling, road); - let other = competitor(2, height, sibling); + let other = competitor(2 + sibling % 2, height, sibling); Some(Input::Evidence(match code { 0 => { h.insert(&own, u64::from(height)); @@ -176,26 +200,28 @@ fn mined_implies_checked_proof() { runner() .run(&trace(), |(kind, trace)| { let subject = Subject::of(kind); - let mut s = subject.state(); - let mut h = TestHeaders::default(); - for (code, height, sibling, noise, time) in trace { - let a = input(&mut h, &subject, code, height, sibling, noise); - let _ = act(&mut s, &subject, &h, a); - step(&mut s, &h, status(noise, height, u64::from(time))); - step(&mut s, &h, host(noise, u64::from(time))); - if let Word::Mined(mined) = s.word() { - let checked = s.evidence().unwrap(); - prop_assert_eq!(mined.height(), checked.proof().height()); - prop_assert_eq!(mined.checked(), checked); - prop_assert_eq!(checked.proof().txid(), s.txid()); - prop_assert_eq!( - checked.proof().path().compute_root(Some(s.txid())).unwrap(), - checked.header().merkle_root.clone() - ); - prop_assert!(checked.depth() >= 1); - prop_assert!(s.tx_len() != Some(AMBIGUOUS_TX_LEN)); - // A proof that writes `mined` leaves no instance named. - prop_assert!(s.handed_to().is_empty()); + for p in MODES.map(machine) { + let mut s = subject.state(); + let mut h = TestHeaders::default(); + for &(code, height, sibling, noise, time) in &trace { + let a = input(&mut h, &subject, code, height, sibling, noise); + let _ = act(&mut s, &p, &subject, &h, a); + play(&mut s, &p, &h, status(noise, height, u64::from(time))); + play(&mut s, &p, &h, host(noise, u64::from(time))); + if let Word::Mined(mined) = s.word() { + let checked = s.evidence().unwrap(); + prop_assert_eq!(mined.height(), checked.proof().height()); + prop_assert_eq!(mined.checked(), checked); + prop_assert_eq!(checked.proof().txid(), s.txid()); + prop_assert_eq!( + checked.proof().path().compute_root(Some(s.txid())).unwrap(), + checked.header().merkle_root.clone() + ); + prop_assert!(checked.depth() >= 1); + prop_assert!(s.tx_len() != Some(AMBIGUOUS_TX_LEN)); + // A proof that writes `mined` leaves no instance named. + prop_assert!(s.handed_to().is_empty()); + } } } Ok(()) @@ -217,93 +243,98 @@ fn stale_iff_header_inactive() { .run( &(states, 0u32..22, moved), |(states, fork_height, moved)| { - let mut tracker = Tracker::new(params()); - let mut h = TestHeaders::default(); - let mut before = vec![]; - for (n, (height, kind)) in states.into_iter().enumerate() { - // Kind 0 is mined on a stated length; kind 1 is tracked - // from its bytes and mined by a proof built from them; - // kind 4 is tracked from 64 bytes, which take no proof. - let n = n as u64 + 100; - let bytes = match kind { - 1 => Some(tx_bytes(n, 191)), - 4 => Some(tx_bytes(n, 64)), - _ => None, - }; - let txid = match &bytes { - Some(b) => tracker.track_bytes(b).unwrap().txid().to_owned(), - None => tracker.track(hash(n)).txid().to_owned(), - }; - match kind { - 0 | 1 => { - let p = match &bytes { - Some(b) => proof_of(b, height, 1_000), - None => proof(&txid, height, 1_000), - }; - h.insert(&p, u64::from(height)); - tracker - .apply(&txid, &h, Input::Evidence(Evidence::Proof(p))) - .unwrap(); - } - 2 => { - tracker - .apply(&txid, &h, Input::Host(HostAction::Build)) - .unwrap(); - } - 3 => { - tracker - .apply( + for p in MODES.map(machine) { + let mut tracker = Tracker::new(p); + let mut h = TestHeaders::default(); + let mut before = vec![]; + for (n, &(height, kind)) in states.iter().enumerate() { + // Kind 0 is mined on a stated length; kind 1 is tracked + // from its bytes and mined by a proof built from them; + // kind 4 is tracked from 64 bytes, which take no proof. + let n = n as u64 + 100; + let bytes = match kind { + 1 => Some(tx_bytes(n, 191)), + 4 => Some(tx_bytes(n, 64)), + _ => None, + }; + let txid = match &bytes { + Some(b) => tracker.track_bytes(b).unwrap().txid().to_owned(), + None => tracker.track(hash(n)).txid().to_owned(), + }; + match kind { + 0 | 1 => { + let p = match &bytes { + Some(b) => proof_of(b, height, 1_000), + None => proof(&txid, height, 1_000), + }; + h.insert(&p, u64::from(height)); + tracker + .apply(&txid, &h, Input::Evidence(Evidence::Proof(p))) + .unwrap(); + } + 2 => { + tracker + .apply(&txid, &h, Input::Host(HostAction::Build)) + .unwrap(); + } + 3 => { + tracker + .apply( + &txid, + &h, + Input::Evidence(Evidence::Verdict(NodeVerdict::Rejected { + reason: "node".into(), + })), + ) + .unwrap(); + } + _ => { + let p = Proof::with_stated_len( &txid, - &h, - Input::Evidence(Evidence::Verdict(NodeVerdict::Rejected { - reason: "node".into(), - })), + 63, + path_of(&txid, height, 1_000), ) .unwrap(); + h.insert(&p, u64::from(height)); + let refused = + tracker.apply(&txid, &h, Input::Evidence(Evidence::Proof(p))); + prop_assert_eq!(refused, Err(CheckError::AmbiguousLength)); + } } - _ => { - let p = - Proof::with_stated_len(&txid, 63, path_of(&txid, height, 1_000)) - .unwrap(); - h.insert(&p, u64::from(height)); - let refused = - tracker.apply(&txid, &h, Input::Evidence(Evidence::Proof(p))); - prop_assert_eq!(refused, Err(CheckError::AmbiguousLength)); - } + before.push(tracker.get(&txid).unwrap().clone()); } - before.push(tracker.get(&txid).unwrap().clone()); - } - // The new branch: some heights at or above the fork carry new roots. - for height in fork_height.max(1)..20 { - if moved[height as usize] { - h.move_root(height, u64::from(height) + 500); + // The new branch: some heights at or above the fork carry new roots. + for height in fork_height.max(1)..20 { + if moved[height as usize] { + h.move_root(height, u64::from(height) + 500); + } } - } - let affected = tracker.on_chain(&h, reorg(fork_height)); - let expected = before - .iter() - .filter(|s| s.word().height().is_some_and(|h| h >= fork_height)) - .count(); - prop_assert_eq!(affected.len(), expected); - prop_assert!(affected.len() <= before.len()); - for old in before { - let after = tracker.get(old.txid()).unwrap(); - let Some(height) = old.word().height().filter(|h| *h >= fork_height) else { - prop_assert_eq!(after, &old); - continue; - }; - prop_assert!(affected + let affected = tracker.on_chain(&h, reorg(fork_height)); + let expected = before .iter() - .any(|u| u.txid == old.txid() && u.result.is_ok())); - prop_assert_eq!(after.evidence(), old.evidence()); - prop_assert!(!after.suspect()); - let active = &h.headers[&height].merkle_root; - if active == old.evidence().unwrap().root() { - prop_assert_eq!(after, &old); - } else { - prop_assert_eq!(after.word(), &Word::Stale); - let reorg = Reask::Reorg { fork_height }; - prop_assert_eq!(after.reask(), Some(&reorg)); + .filter(|s| s.word().height().is_some_and(|h| h >= fork_height)) + .count(); + prop_assert_eq!(affected.len(), expected); + prop_assert!(affected.len() <= before.len()); + for old in before { + let after = tracker.get(old.txid()).unwrap(); + let Some(height) = old.word().height().filter(|h| *h >= fork_height) else { + prop_assert_eq!(after, &old); + continue; + }; + prop_assert!(affected + .iter() + .any(|u| u.txid == old.txid() && u.result.is_ok())); + prop_assert_eq!(after.evidence(), old.evidence()); + prop_assert!(!after.suspect()); + let active = &h.headers[&height].merkle_root; + if active == old.evidence().unwrap().root() { + prop_assert_eq!(after, &old); + } else { + prop_assert_eq!(after.word(), &Word::Stale); + let reorg = Reask::Reorg { fork_height }; + prop_assert_eq!(after.reask(), Some(&reorg)); + } } } Ok(()) @@ -317,28 +348,33 @@ fn hint_changes_no_chain_word() { runner() .run(&trace(), |(kind, trace)| { let subject = Subject::of(kind); - let mut s = subject.state(); - let mut h = TestHeaders::default(); - for (code, height, sibling, noise, time) in trace { - let a = input(&mut h, &subject, code, height, sibling, noise); - let _ = act(&mut s, &subject, &h, a); - step(&mut s, &h, host(noise, u64::from(time))); - let before = s.clone(); - step(&mut s, &h, status(noise, height, u64::from(time))); - prop_assert_eq!(s.word().chain(), before.word().chain()); - prop_assert_eq!(s.evidence(), before.evidence()); - prop_assert_eq!(s.suspect(), before.suspect()); - prop_assert_eq!(s.tx_len(), before.tx_len()); - if s.word() != before.word() { - prop_assert!(matches!( - (before.word(), s.word()), - (Word::Built | Word::Handed, Word::Announced | Word::Seen) - | (Word::Announced, Word::Seen) - )); - // A hint that moves the word empties the list. - prop_assert!(s.handed_to().is_empty()); - } else { - prop_assert_eq!(s.handed_to(), before.handed_to()); + for p in MODES.map(machine) { + let mut s = subject.state(); + let mut h = TestHeaders::default(); + for &(code, height, sibling, noise, time) in &trace { + let a = input(&mut h, &subject, code, height, sibling, noise); + let _ = act(&mut s, &p, &subject, &h, a); + play(&mut s, &p, &h, host(noise, u64::from(time))); + let before = s.clone(); + play(&mut s, &p, &h, status(noise, height, u64::from(time))); + prop_assert_eq!(s.word().chain(), before.word().chain()); + prop_assert_eq!(s.evidence(), before.evidence()); + prop_assert_eq!(s.suspect(), before.suspect()); + prop_assert_eq!(s.tx_len(), before.tx_len()); + if s.word() != before.word() { + prop_assert!(matches!( + (before.word(), s.word()), + (Word::Built | Word::Handed, Word::Announced | Word::Seen) + | (Word::Announced, Word::Seen) + )); + // A hint that moves the word empties the list. + prop_assert!(s.handed_to().is_empty()); + } else { + prop_assert_eq!(s.handed_to(), before.handed_to()); + } + // A hint writes no record of a conflict. + prop_assert_eq!(s.rivals(), before.rivals()); + prop_assert_eq!(s.prior(), before.prior()); } } Ok(()) @@ -346,6 +382,10 @@ fn hint_changes_no_chain_word() { .unwrap(); } +/// Theorem (iv), over the latch alone (`State::step` with +/// `Params::recheck_conflicted` off): the Lean states it of `step`, and over +/// the door equal views of two states that hold different records of a +/// conflict give different words (`sameViewOtherRecord`). #[test] fn same_evidence_same_word() { runner() @@ -361,8 +401,8 @@ fn same_evidence_same_word() { step(&mut b, &h, status(noise_b, height, u64::from(noise_b))); step(&mut a, &h, host(noise_a, u64::from(noise_a))); step(&mut b, &h, host(noise_b, u64::from(noise_b))); - let result_a = act(&mut a, &subject, &h, i.clone()); - let result_b = act(&mut b, &subject, &h, i); + let result_a = act(&mut a, ¶ms(), &subject, &h, i.clone()); + let result_b = act(&mut b, ¶ms(), &subject, &h, i); prop_assert_eq!(result_a, result_b); prop_assert_eq!(a.tx_len(), b.tx_len()); prop_assert_eq!(a.word().chain(), b.word().chain()); From 096ac3b6146be19cfeb19906c0ddd9fc14125170 Mon Sep 17 00:00:00 2001 From: John Calhoun Date: Sun, 29 Nov 2026 00:06:40 -0500 Subject: [PATCH 03/12] tests: the recheck of conflicted's theorems as properties, each named for its Lean theorem (for #47) 23 properties named for the theorems of the section "The recheck of conflicted" of lean/Tracker.lean at bsv-stack-lean a7ef91de, and 3 of the crate's own (a competitor's length is its own; no run lists an id whose only entry is gone; conflicted from handed keeps its list). 256 cases from the fixed ChaCha seed, no failure persistence; every trace runs under both machines, two competitors' proofs built from their bytes, and each premise is met in some case. Co-Authored-By: Claude Opus 5.5 --- tests/recheck_properties.rs | 1217 +++++++++++++++++++++++++++++++++++ 1 file changed, 1217 insertions(+) create mode 100644 tests/recheck_properties.rs diff --git a/tests/recheck_properties.rs b/tests/recheck_properties.rs new file mode 100644 index 0000000..4651dea --- /dev/null +++ b/tests/recheck_properties.rs @@ -0,0 +1,1217 @@ +//! The recheck of `conflicted`'s theorems as randomized statements, each test +//! named for the Lean theorem it mirrors: `lean/Tracker.lean` of +//! bsv-stack-lean at `a7ef91de`, the section "The recheck of `conflicted`" +//! and the statements it names, as they stand there (`docs/VERIFICATION.md`, +//! "The recheck of `conflicted`'s tests of record", is the table). 256 +//! reproducible cases per test, using an explicit ChaCha seed and no failure +//! persistence, network, clock or storage, as `tests/properties.rs`. No case +//! is a journal row. +//! +//! Every state is reached by a random trace from the tracked transaction's +//! birth (`Subject`: a txid alone, or bytes of 63, 64, 65 or 191, born +//! measured or from its txid), each trace run under both machines: the +//! latch (`Params::recheck_conflicted` off, the Lean's `step`) and the +//! machine with the door (on, `stepRecheck`). The draw: every host act and +//! the three of the hand-over, every hint status, the subject's own proof by +//! either constructor with and without its header, the proofs of two +//! competitors built from their bytes (`tx_bytes(2, 191)` and +//! `tx_bytes(3, 191)`) with and without their header, both node verdicts (a +//! `conflicted` one naming a competitor no proof is offered for, or one of +//! the two), the competitors' roots moved, dropped and put back in the +//! headers, reorgs, forks, tips, splits, resolved splits, invalidations, a +//! recheck under headers that answer, that have no header and that fault, +//! and the measure. A statement of one step is asked of every step; a +//! statement of one act on a state, of that act played on a copy of every +//! state; an invariant, of every state. Each statement's premise is met in +//! some case (checked). +//! +//! The Lean's `rootGone`, `unanswered`, `rivalAtOrAbove` and `leaveWord` are +//! not public items of the crate; each is mirrored here as a local function +//! under its name. +// The lint bar binds the library; a test may unwrap, and its fixtures fail loudly +// (bsv-stack-lean #134). A test carries its Lean theorem's name, case and all. +#![allow( + non_snake_case, + clippy::pedantic, + clippy::unwrap_used, + clippy::expect_used, + clippy::panic +)] +mod common; +use bsv_tracker::*; +use common::*; +use proptest::prelude::*; +use proptest::test_runner::{Config, RngAlgorithm, TestCaseError, TestRng, TestRunner}; +use std::cell::Cell; + +fn runner() -> TestRunner { + TestRunner::new_with_rng( + Config { + cases: 256, + failure_persistence: None, + ..Config::default() + }, + TestRng::deterministic_rng(RngAlgorithm::ChaCha), + ) +} + +/// The age threshold of the draw. +const AGE: u64 = 10; + +fn latch() -> Params { + Params::new(AGE, 1) +} + +fn door() -> Params { + latch().with_recheck_conflicted(true) +} + +/// The two competitors' numbers: their bytes are `tx_bytes(n, 191)`. +const COMPETITORS: [u64; 2] = [2, 3]; + +// --------------------------------------------------------------------------- +// The Lean's functions, mirrored +// --------------------------------------------------------------------------- + +/// `Tracker.rootGone`: a header at the competitor's height whose root is not +/// the competitor's stored root. No header, a headers fault and a competitor +/// with no proof are not gone. +fn rootGone(h: &TestHeaders, r: &Competitor) -> bool { + r.checked().is_some_and( + |c| matches!(h.header_at(c.height()), Ok(Some(header)) if header.merkle_root != c.root()), + ) +} + +/// `Tracker.unanswered`: a standing competitor with a proof whose height has +/// no header. The crate fails closed on a headers fault too. +fn unanswered(h: &TestHeaders, r: &Competitor) -> bool { + r.standing() + && r.checked() + .is_some_and(|c| !matches!(h.header_at(c.height()), Ok(Some(_)))) +} + +/// `Tracker.rivalAtOrAbove`. +fn rivalAtOrAbove(fh: u32, s: &State) -> bool { + s.rivals() + .iter() + .any(|r| r.standing() && r.checked().is_some_and(|c| fh <= c.height())) +} + +/// `Tracker.leaveWord`. +fn leaveWord(prior: Option<&Word>) -> Word { + match prior { + Some(Word::Seen) => Word::Announced, + Some(Word::Mined(_) | Word::Conflicted { .. }) | None => Word::Unknown, + Some(w) => w.clone(), + } +} + +/// Every record's competitor gone or its root gone: the condition of the +/// return (`recheckConflict_leaves_iff`'s right side, non-empty). +fn all_gone(h: &TestHeaders, s: &State) -> bool { + !s.rivals().is_empty() && s.rivals().iter().all(|r| r.gone() || rootGone(h, r)) +} + +fn conflicted(s: &State) -> Option<&Vec> { + match s.word() { + Word::Conflicted { competitors } => Some(competitors), + _ => None, + } +} + +/// An input the door takes from a `conflicted` word: a chain event or a +/// recheck. +fn door_takes(i: &Input) -> bool { + matches!(i, Input::Evidence(Evidence::Chain(_) | Evidence::Recheck)) +} + +/// Two states equal in every reader but the re-ask. +fn same_but_reask(a: &State, b: &State) -> bool { + a.txid() == b.txid() + && a.word() == b.word() + && a.evidence() == b.evidence() + && a.suspect() == b.suspect() + && a.hints() == b.hints() + && a.last_hint_at() == b.last_hint_at() + && a.handed_to() == b.handed_to() + && a.rivals() == b.rivals() + && a.prior() == b.prior() + && a.tx_len() == b.tx_len() +} + +// --------------------------------------------------------------------------- +// The draw +// --------------------------------------------------------------------------- + +/// A subject's kind, and per step: the act's code, two draws and the clock's +/// advance. +type Trace = (u8, Vec<(u8, u8, u8, u8)>); + +fn trace() -> impl Strategy { + ( + any::(), + prop::collection::vec((0u8..36, any::(), any::(), 0u8..4), 1..60), + ) +} + +/// Every hint status, by `code % 10`. +fn hint_of(code: u8, height: u32, observed: u64) -> Hint { + let source = INSTANCES[usize::from(code / 10) % 3]; + let status = match code % 10 { + 0 => HintStatus::Accepted, + 1 => HintStatus::Seen, + 2 => HintStatus::Mined { height }, + 3 => HintStatus::StaleBlock, + 4 => HintStatus::Rejected { + reason: "476".into(), + }, + 5 => HintStatus::DoubleSpend { + competitors: vec![competitor(2, height, 30).txid().to_owned()], + }, + 6 => HintStatus::OrphanMempool, + 7 => HintStatus::MempoolPresent { + source: source.to_owned(), + }, + 8 => HintStatus::Unknown, + _ => HintStatus::Seen, + }; + Hint::new(source, status, observed) +} + +/// The world of one trace: the subject, its state, the headers and the clock. +struct World { + subject: Subject, + s: State, + h: TestHeaders, + clock: u64, +} + +/// The block a competitor's header is written as at `height`. +fn block(height: u32) -> u64 { + u64::from(height) +} + +/// One act of the trace, or (`None`) the measure act. Competitors' proofs +/// and the moves of their roots are drawn often, so the trace reaches +/// `conflicted` with a record and leaves it every way. +fn input(w: &mut World, code: u8, a: u8, b: u8) -> Option { + w.h.fault = false; + let height = u32::from(b % 6) + 1; + let sibling = u64::from(a % 3) + 20; + let at = w.clock; + let own = w.subject.own(height, sibling, a); + let rival = competitor(COMPETITORS[usize::from(a) % 2], height, sibling); + Some(match code { + 0 => Input::Host(HostAction::Build), + 1 => Input::Host(HostAction::Abandon), + 2 => Input::Host(HostAction::SpendAttempt), + 3 => Input::Host(HostAction::Tick(at + AGE * u64::from(a % 2))), + 4..=6 => Input::Host(hand_act(a, at)), + 7..=9 => Input::Hint(hint_of(a, height, at)), + 10 | 11 => { + w.h.insert(&own, block(height)); + Input::Evidence(Evidence::Proof(own)) + } + 12 => Input::Evidence(Evidence::Proof(own)), + 13..=16 => { + w.h.insert(&rival, block(height)); + Input::Evidence(Evidence::Competitor(rival)) + } + 17 => Input::Evidence(Evidence::Competitor(rival)), + 18 => Input::Evidence(Evidence::Verdict(NodeVerdict::Rejected { + reason: format!("node-{a}"), + })), + 19 => Input::Evidence(Evidence::Verdict(NodeVerdict::Conflicted { + competitors: vec![match a % 3 { + 0 => hash(50), + _ => rival.txid().to_owned(), + }], + })), + 20 | 21 => { + w.h.move_root(height, block(height) + 500); + Input::Evidence(Evidence::Chain(reorg(height))) + } + 22 => Input::Evidence(Evidence::Chain(reorg(height))), + 23 => Input::Evidence(Evidence::Chain(fork(height))), + 24 => Input::Evidence(Evidence::Chain(tip(height + 6, 90))), + 25 => { + w.h.move_root(height, block(height) + 500); + Input::Evidence(Evidence::Chain(ChainEvent::Invalidated { + block_hash: hash(block(height)), + })) + } + 26 => { + w.h.move_root(height, block(height) + 500); + Input::Evidence(Evidence::Recheck) + } + 27 => Input::Evidence(Evidence::Recheck), + 28 => { + w.h.headers.remove(&height); + Input::Evidence(Evidence::Recheck) + } + 29 => { + w.h.fault = true; + Input::Evidence(Evidence::Recheck) + } + 30 => Input::Evidence(Evidence::Chain(split(height))), + 31 => Input::Evidence(Evidence::Chain(split_resolved(height))), + 32 => { + w.h.headers.remove(&height); + Input::Evidence(Evidence::Chain(reorg(height))) + } + // The competitor's root put back: its header at its height again. + 33 => { + w.h.insert(&rival, block(height)); + Input::Evidence(Evidence::Chain(tip(height + 6, 91))) + } + 34 => Input::Host(HostAction::HandOver { + instance: INSTANCES[usize::from(a) % 3].into(), + at, + }), + _ => return None, + }) +} + +/// One step of a trace: the state on both sides of it and what was played. +struct Step<'a> { + before: &'a State, + input: &'a Option, + result: &'a Result<(), CheckError>, + after: &'a State, + h: &'a TestHeaders, + p: &'a Params, + subject: &'a Subject, + a: u8, + b: u8, + opening: bool, +} + +/// Run 256 traces, each under both machines, and hand every step to `check`. +fn each_step(check: impl Fn(&Step<'_>) -> Result<(), TestCaseError>) { + runner() + .run(&trace(), |(kind, trace)| { + for p in [latch(), door()] { + let subject = Subject::of(kind); + let s = subject.state(); + let mut w = World { + subject, + s, + h: TestHeaders::default(), + clock: 0, + }; + for (n, &(code, a, b, dt)) in trace.iter().enumerate() { + w.clock += u64::from(dt); + let i = input(&mut w, code, a, b); + let before = w.s.clone(); + let result = match &i { + Some(i) => w.s.step(&p, &w.h, i.clone()), + None => w.subject.measure(&mut w.s), + }; + check(&Step { + before: &before, + input: &i, + result: &result, + after: &w.s, + h: &w.h, + p: &p, + subject: &w.subject, + a, + b, + opening: n == 0, + })?; + } + } + Ok(()) + }) + .unwrap(); +} + +/// Every state a trace reaches, the birth included. +fn each_state(check: impl Fn(&Step<'_>) -> Result<(), TestCaseError>) { + each_step(|e| { + if e.opening { + check(&Step { + after: e.before, + ..*e + })?; + } + check(e) + }); +} + +/// Every state the door reaches. +fn each_door_state(check: impl Fn(&Step<'_>) -> Result<(), TestCaseError>) { + each_state(|e| { + if e.p.recheck_conflicted { + check(e)?; + } + Ok(()) + }); +} + +/// `act` played on a copy of `s`. +fn play(s: &State, p: &Params, h: &impl Headers, act: Input) -> (State, Result<(), CheckError>) { + let mut t = s.clone(); + let r = t.step(p, h, act); + (t, r) +} + +/// The chain events a statement plays at `height`. +fn chain_rows(height: u32) -> Vec { + vec![ + reorg(height), + fork(height), + tip(height, 90), + split(height), + split_resolved(height), + ChainEvent::Invalidated { + block_hash: hash(block(height)), + }, + ] +} + +/// The headers a statement plays under: the trace's, those with every +/// competitor's root moved, and those that answer nothing. +fn headers_of(e: &Step<'_>) -> [TestHeaders; 3] { + let mut moved = e.h.clone(); + moved.fault = false; + for height in 1..=6 { + moved.move_root(height, block(height) + 700); + } + [e.h.clone(), moved, TestHeaders::default()] +} + +/// A statement's premise met at least once over the 256 traces. +fn reached(what: &str, n: &Cell) { + assert!(n.get() > 0, "{what}: the premise is never met"); +} + +fn hit(n: &Cell) { + n.set(n.get() + 1); +} + +// --------------------------------------------------------------------------- +// The two machines +// --------------------------------------------------------------------------- + +/// Over the latch, a `conflicted` word stays as it is under every chain event +/// and every recheck. +#[test] +fn step_conflicted_latched() { + let n = Cell::new(0); + each_state(|e| { + if e.p.recheck_conflicted || conflicted(e.after).is_none() { + return Ok(()); + } + hit(&n); + for h in headers_of(e) { + for ev in chain_rows(u32::from(e.b % 6) + 1) { + let (t, _) = play(e.after, e.p, &h, Input::Evidence(Evidence::Chain(ev))); + prop_assert_eq!(&t, e.after); + } + let (t, _) = play(e.after, e.p, &h, Input::Evidence(Evidence::Recheck)); + prop_assert_eq!(&t, e.after); + } + Ok(()) + }); + reached("a conflicted word under the latch", &n); +} + +/// The two machines agree on every input but a chain event or a recheck +/// that meets a `conflicted` word: the state and the answer. +#[test] +fn stepRecheck_eq_step() { + let (n, m) = (Cell::new(0), Cell::new(0)); + each_step(|e| { + let Some(i) = e.input else { return Ok(()) }; + if conflicted(e.before).is_some() && door_takes(i) { + return Ok(()); + } + if conflicted(e.before).is_some() { + hit(&m); + } + hit(&n); + let (a, ra) = play(e.before, &latch(), e.h, i.clone()); + let (b, rb) = play(e.before, &door(), e.h, i.clone()); + prop_assert_eq!(a, b); + prop_assert_eq!(ra, rb); + Ok(()) + }); + reached("a step the two machines agree on", &n); + reached("a conflicted word meeting another input", &m); +} + +/// Off `conflicted`, the door's recheck and chain rows are the latch's: the +/// crate's road to `recheckConflict_spares_others` (the recheck of the +/// conflict reads no other word). +#[test] +fn recheckConflict_spares_others() { + let n = Cell::new(0); + each_door_state(|e| { + if conflicted(e.after).is_some() { + return Ok(()); + } + hit(&n); + for h in headers_of(e) { + let mut rows: Vec = chain_rows(u32::from(e.b % 6) + 1) + .into_iter() + .map(|ev| Input::Evidence(Evidence::Chain(ev))) + .collect(); + rows.push(Input::Evidence(Evidence::Recheck)); + for i in rows { + prop_assert_eq!( + play(e.after, &door(), &h, i.clone()), + play(e.after, &latch(), &h, i) + ); + } + } + Ok(()) + }); + reached("a word that is not conflicted", &n); +} + +// --------------------------------------------------------------------------- +// The recheck of the conflict +// --------------------------------------------------------------------------- + +/// A recheck leaves `conflicted` exactly when the record is not empty and +/// every competitor on it is gone or has lost its root. +#[test] +fn recheckConflict_leaves_iff() { + let (left, stayed) = (Cell::new(0), Cell::new(0)); + each_door_state(|e| { + if conflicted(e.after).is_none() { + return Ok(()); + } + for h in headers_of(e) { + let (t, _) = play(e.after, e.p, &h, Input::Evidence(Evidence::Recheck)); + let leaves = conflicted(&t).is_none(); + hit(if leaves { &left } else { &stayed }); + prop_assert_eq!(leaves, all_gone(&h, e.after)); + } + Ok(()) + }); + reached("a recheck that returns", &left); + reached("a recheck that keeps conflicted", &stayed); +} + +/// A return writes the word held before (`leaveWord prior`), re-asks the +/// competitors of the word, clears the mark and keeps the evidence. +#[test] +fn conflict_leaves_to_prior() { + let n = Cell::new(0); + each_door_state(|e| { + let Some(cs) = conflicted(e.after) else { + return Ok(()); + }; + for h in headers_of(e) { + let (t, r) = play(e.after, e.p, &h, Input::Evidence(Evidence::Recheck)); + if conflicted(&t).is_some() { + continue; + } + hit(&n); + prop_assert_eq!(r, Ok(())); + prop_assert_eq!(t.word(), &leaveWord(e.after.prior())); + let gone = Reask::CompetitorGone { + competitors: cs.clone(), + }; + prop_assert_eq!(t.reask(), Some(&gone)); + prop_assert!(!t.suspect()); + prop_assert_eq!(t.evidence(), e.after.evidence()); + prop_assert_eq!(t.rivals().len(), e.after.rivals().len()); + } + Ok(()) + }); + reached("a return", &n); +} + +/// A standing competitor whose height has no header keeps the word +/// `conflicted`, schedules a re-read and leaves the mark as it was. +#[test] +fn conflict_no_header_fails_closed() { + let n = Cell::new(0); + each_door_state(|e| { + if conflicted(e.after).is_none() { + return Ok(()); + } + for h in headers_of(e) { + if !e.after.rivals().iter().any(|r| unanswered(&h, r)) { + continue; + } + hit(&n); + let (t, r) = play(e.after, e.p, &h, Input::Evidence(Evidence::Recheck)); + prop_assert!(conflicted(&t).is_some()); + prop_assert_eq!(t.reask(), Some(&Reask::Recheck)); + prop_assert_eq!(t.suspect(), e.after.suspect()); + prop_assert!(matches!( + r, + Err(CheckError::Unavailable(_) | CheckError::Headers(_)) + )); + } + Ok(()) + }); + reached("an unanswered competitor", &n); +} + +/// A competitor a node's verdict named, standing on the record, keeps the +/// word `conflicted` under every recheck. +#[test] +fn verdict_named_never_leaves() { + let n = Cell::new(0); + each_door_state(|e| { + if conflicted(e.after).is_none() + || !e + .after + .rivals() + .iter() + .any(|r| r.checked().is_none() && r.standing()) + { + return Ok(()); + } + hit(&n); + for h in headers_of(e) { + let (t, _) = play(e.after, e.p, &h, Input::Evidence(Evidence::Recheck)); + prop_assert!(conflicted(&t).is_some()); + for ev in chain_rows(u32::from(e.b % 6) + 1) { + let (t, _) = play(e.after, e.p, &h, Input::Evidence(Evidence::Chain(ev))); + prop_assert!(conflicted(&t).is_some()); + } + } + Ok(()) + }); + reached("a named competitor standing", &n); +} + +/// A recheck marks a competitor gone exactly when it was gone or a header is +/// at its height with another root than its proof's; the record keeps its +/// order and its length. +#[test] +fn rootGone_iff() { + let n = Cell::new(0); + each_door_state(|e| { + if conflicted(e.after).is_none() || e.after.rivals().is_empty() { + return Ok(()); + } + for h in headers_of(e) { + let (t, _) = play(e.after, e.p, &h, Input::Evidence(Evidence::Recheck)); + prop_assert_eq!(t.rivals().len(), e.after.rivals().len()); + for (was, now) in e.after.rivals().iter().zip(t.rivals()) { + prop_assert_eq!(was.txid(), now.txid()); + prop_assert_eq!(was.checked(), now.checked()); + prop_assert_eq!(now.gone(), was.gone() || rootGone(&h, was)); + if !was.gone() && now.gone() { + hit(&n); + } + } + } + Ok(()) + }); + reached("a competitor marked gone", &n); +} + +/// The competitor's own state, `mined` on the proof the record keeps, reads +/// `stale` at a recheck exactly when ours marks that competitor gone. +#[test] +fn rootGone_iff_competitor_stale() { + let (stale, standing) = (Cell::new(0), Cell::new(0)); + each_door_state(|e| { + if conflicted(e.after).is_none() { + return Ok(()); + } + for h in headers_of(e) { + let (t, _) = play(e.after, e.p, &h, Input::Evidence(Evidence::Recheck)); + for (k, r) in e.after.rivals().iter().enumerate() { + let Some(c) = r.checked().filter(|_| r.standing()) else { + continue; + }; + let n = COMPETITORS + .into_iter() + .find(|&n| txid_of(&tx_bytes(n, 191)) == r.txid()) + .unwrap(); + let mut sx = State::measured(&tx_bytes(n, 191)); + let mut then = TestHeaders::default(); + then.tip = c.height(); + then.headers.insert(c.height(), c.header().clone()); + sx.step( + &latch(), + &then, + Input::Evidence(Evidence::Proof(c.proof().clone())), + ) + .unwrap(); + prop_assert!(matches!(sx.word(), Word::Mined(_))); + let _ = sx.step(&latch(), &h, Input::Evidence(Evidence::Recheck)); + let is_stale = sx.word() == &Word::Stale; + hit(if is_stale { &stale } else { &standing }); + prop_assert_eq!(is_stale, rootGone(&h, r)); + prop_assert_eq!(is_stale, t.rivals()[k].gone()); + } + } + Ok(()) + }); + reached("a competitor's own word stale", &stale); + reached("a competitor's own word standing", &standing); +} + +// --------------------------------------------------------------------------- +// The feed on a conflicted word +// --------------------------------------------------------------------------- + +/// A reorg leaves `conflicted` exactly when a standing competitor with a +/// proof is at or above its fork height and every competitor is gone or has +/// lost its root. +#[test] +fn conflict_reorg_exact() { + let (left, stayed) = (Cell::new(0), Cell::new(0)); + each_door_state(|e| { + if conflicted(e.after).is_none() { + return Ok(()); + } + for h in headers_of(e) { + for fh in 0..=7 { + let (t, _) = play( + e.after, + e.p, + &h, + Input::Evidence(Evidence::Chain(reorg(fh))), + ); + let leaves = conflicted(&t).is_none(); + hit(if leaves { &left } else { &stayed }); + prop_assert_eq!(leaves, rivalAtOrAbove(fh, e.after) && all_gone(&h, e.after)); + } + } + Ok(()) + }); + reached("a reorg that returns", &left); + reached("a reorg that keeps conflicted", &stayed); +} + +/// A reorg above every standing competitor with a proof leaves the state as +/// it is. +#[test] +fn conflict_reorg_spares_below() { + let n = Cell::new(0); + each_door_state(|e| { + if conflicted(e.after).is_none() { + return Ok(()); + } + for h in headers_of(e) { + for fh in 0..=7 { + if rivalAtOrAbove(fh, e.after) { + continue; + } + hit(&n); + let (t, r) = play( + e.after, + e.p, + &h, + Input::Evidence(Evidence::Chain(reorg(fh))), + ); + prop_assert_eq!(&t, e.after); + prop_assert_eq!(r, Ok(())); + } + } + Ok(()) + }); + reached("a reorg above the record", &n); +} + +/// A tip on an unmarked `conflicted` word leaves the state as it is. +#[test] +fn conflict_tip_unmarked() { + let n = Cell::new(0); + each_door_state(|e| { + if conflicted(e.after).is_none() || e.after.suspect() { + return Ok(()); + } + hit(&n); + for h in headers_of(e) { + let (t, _) = play( + e.after, + e.p, + &h, + Input::Evidence(Evidence::Chain(tip(u32::from(e.b), 90))), + ); + prop_assert_eq!(&t, e.after); + } + Ok(()) + }); + reached("an unmarked conflicted word", &n); +} + +/// The feed on a `conflicted` word keeps the evidence and the txid (and the +/// tracked transaction's measure). +#[test] +fn onChainConflict_keeps() { + let n = Cell::new(0); + each_door_state(|e| { + if conflicted(e.after).is_none() { + return Ok(()); + } + hit(&n); + for h in headers_of(e) { + for ev in chain_rows(u32::from(e.b % 6) + 1) { + let (t, _) = play(e.after, e.p, &h, Input::Evidence(Evidence::Chain(ev))); + prop_assert_eq!(t.evidence(), e.after.evidence()); + prop_assert_eq!(t.txid(), e.after.txid()); + prop_assert_eq!(t.tx_len(), e.after.tx_len()); + } + } + Ok(()) + }); + reached("a conflicted word", &n); +} + +// --------------------------------------------------------------------------- +// The words a conflict leaves to, and the words it is written from +// --------------------------------------------------------------------------- + +/// A step of the door that leaves `conflicted` is the transaction's own +/// proof (to `mined` at its height), a node's `rejected` (to `rejected`), or +/// a chain event or a recheck that returns (to `leaveWord prior`, every +/// competitor gone or its root gone). +#[test] +fn conflicted_exits() { + let (proof, rejected, returned) = (Cell::new(0), Cell::new(0), Cell::new(0)); + each_step(|e| { + if !e.p.recheck_conflicted + || conflicted(e.before).is_none() + || conflicted(e.after).is_some() + { + return Ok(()); + } + match e.input { + Some(Input::Evidence(Evidence::Proof(p))) => { + hit(&proof); + prop_assert!(matches!(e.after.word(), Word::Mined(m) if m.height() == p.height())); + } + Some(Input::Evidence(Evidence::Verdict(NodeVerdict::Rejected { reason }))) => { + hit(&rejected); + let w = Word::Rejected { + reason: reason.clone(), + }; + prop_assert_eq!(e.after.word(), &w); + } + Some(i) if door_takes(i) => { + hit(&returned); + prop_assert_eq!(e.after.word(), &leaveWord(e.before.prior())); + prop_assert!(all_gone(e.h, e.before)); + } + other => prop_assert!(false, "{:?} left conflicted", other), + } + Ok(()) + }); + reached("an exit by proof", &proof); + reached("an exit by rejected", &rejected); + reached("an exit by the door", &returned); +} + +/// No hint moves a `conflicted` word. +#[test] +fn hint_never_moves_conflicted() { + let n = Cell::new(0); + each_door_state(|e| { + if conflicted(e.after).is_none() { + return Ok(()); + } + hit(&n); + for code in 0..10 { + let (t, _) = play( + e.after, + e.p, + e.h, + Input::Hint(hint_of(code, u32::from(e.b % 6) + 1, 99)), + ); + prop_assert_eq!(t.word(), e.after.word()); + } + Ok(()) + }); + reached("a conflicted word", &n); +} + +/// A step of the door writes a fresh `handed` only by a hand-over, or by a +/// return from a `conflicted` word whose prior word was `handed`. +#[test] +fn handed_written_cases() { + let (by_hand, by_return) = (Cell::new(0), Cell::new(0)); + each_step(|e| { + if !e.p.recheck_conflicted + || e.before.word() == &Word::Handed + || e.after.word() != &Word::Handed + { + return Ok(()); + } + if matches!(e.input, Some(Input::Host(HostAction::HandOver { .. }))) { + hit(&by_hand); + } else { + hit(&by_return); + prop_assert!(conflicted(e.before).is_some()); + prop_assert_eq!(e.before.prior(), Some(&Word::Handed)); + prop_assert!(!e.after.handed_to().is_empty()); + } + Ok(()) + }); + reached("handed by a hand-over", &by_hand); + reached("handed by a return", &by_return); +} + +// --------------------------------------------------------------------------- +// Evidence over the door +// --------------------------------------------------------------------------- + +/// Along every run of the door, a `mined` word holds a checked proof at its +/// height whose header carries its root (`Evidenced`). +#[test] +fn evidenced_runRecheck() { + let n = Cell::new(0); + each_door_state(|e| { + if let Word::Mined(m) = e.after.word() { + hit(&n); + let c = e.after.evidence().unwrap(); + prop_assert_eq!(c.height(), m.height()); + prop_assert_eq!(c.header().merkle_root.as_str(), c.root()); + } + Ok(()) + }); + reached("a mined word", &n); +} + +/// Along every run of the door from the birth, a `mined` word's evidence is +/// a proof of the tracked transaction's own txid. +#[test] +fn mined_rests_on_its_leaf() { + let n = Cell::new(0); + each_door_state(|e| { + if let Word::Mined(m) = e.after.word() { + hit(&n); + let c = e.after.evidence().unwrap(); + prop_assert_eq!(c.proof().txid(), e.after.txid()); + prop_assert_eq!(c.proof().height(), m.height()); + prop_assert_eq!( + c.proof().path().compute_root(Some(e.after.txid())).unwrap(), + c.header().merkle_root.clone() + ); + } + Ok(()) + }); + reached("a mined word", &n); +} + +/// A competitor's proof of the tracked txid itself is refused in either +/// machine: the state as it was, but the re-ask, which names the proof's +/// height. +#[test] +fn competitor_is_another() { + let n = Cell::new(0); + each_state(|e| { + hit(&n); + let height = u32::from(e.b % 6) + 1; + let own = e.subject.own(height, 40, e.a); + let mut h = e.h.clone(); + h.fault = false; + h.insert(&own, block(height)); + let (t, r) = play(e.after, e.p, &h, Input::Evidence(Evidence::Competitor(own))); + prop_assert_eq!(r, Err(CheckError::TxidMismatch)); + prop_assert!(same_but_reask(&t, e.after)); + prop_assert_eq!(t.reask(), Some(&Reask::ProofFailed { height })); + Ok(()) + }); + reached("a state", &n); +} + +/// From every state of the door, the transaction's own proof whose root our +/// header carries writes `mined` at its height. The crate's length rule +/// stands beside it: the subject is not of 64 bytes and the proof's length +/// agrees with it (the stated lie is left out). +#[test] +fn returned_then_mined() { + let (n, from_conflicted) = (Cell::new(0), Cell::new(0)); + each_door_state(|e| { + if e.subject.len() == AMBIGUOUS_TX_LEN || e.a % 3 == 2 { + return Ok(()); + } + hit(&n); + if conflicted(e.after).is_some() + || e.after + .reask() + .is_some_and(|r| matches!(r, Reask::CompetitorGone { .. })) + { + hit(&from_conflicted); + } + let height = u32::from(e.b % 6) + 1; + let own = e.subject.own(height, 41, e.a); + let mut h = e.h.clone(); + h.fault = false; + h.insert(&own, block(height)); + let (t, r) = play(e.after, e.p, &h, Input::Evidence(Evidence::Proof(own))); + prop_assert_eq!(r, Ok(())); + prop_assert!(matches!(t.word(), Word::Mined(m) if m.height() == height)); + Ok(()) + }); + reached("a state the proof may mine", &n); + reached("a conflicted or returned state", &from_conflicted); +} + +// --------------------------------------------------------------------------- +// The selection and the reads +// --------------------------------------------------------------------------- + +/// A recheck of a `conflicted` word reads one header a standing competitor +/// with a proof, no more than the record holds; a tip on an unmarked word +/// reads none. +#[test] +fn conflictReads_le() { + let n = Cell::new(0); + each_door_state(|e| { + if conflicted(e.after).is_none() { + return Ok(()); + } + hit(&n); + let expected = e + .after + .rivals() + .iter() + .filter(|r| r.standing() && r.checked().is_some()) + .count(); + let counting = Counting { + inner: e.h, + reads: Cell::new(0), + }; + let _ = play(e.after, e.p, &counting, Input::Evidence(Evidence::Recheck)); + prop_assert_eq!(counting.reads.get() as usize, expected); + prop_assert!(expected <= e.after.rivals().len()); + if !e.after.suspect() { + let counting = Counting { + inner: e.h, + reads: Cell::new(0), + }; + let _ = play( + e.after, + e.p, + &counting, + Input::Evidence(Evidence::Chain(tip(99, 90))), + ); + prop_assert_eq!(counting.reads.get(), 0); + } + Ok(()) + }); + reached("a conflicted word", &n); +} + +/// Headers that count the reads asked of them. +struct Counting<'a> { + inner: &'a TestHeaders, + reads: Cell, +} + +impl Headers for Counting<'_> { + fn header_at(&self, height: u32) -> Result, HeaderError> { + self.reads.set(self.reads.get() + 1); + self.inner.header_at(height) + } + fn tip_height(&self) -> Result { + self.inner.tip_height() + } +} + +/// Several tracked transactions, each driven by its own trace under the +/// door, and a reorg at `fh` over headers whose roots at or above it moved: +/// `(the states before, the tracker after, the updates)`. +type Reorged = (Vec, Tracker, Vec); + +fn reorged(traces: &[Trace], fh: u32, moved: &[bool]) -> Reorged { + let mut tracker = Tracker::new(door()); + let mut h = TestHeaders::default(); + let mut before = vec![]; + for (k, (kind, trace)) in traces.iter().enumerate() { + let subject = Subject { + txid: hash(200 + k as u64), + ..Subject::of(*kind) + }; + let subject = match subject.bytes { + Some(_) => { + let bytes = tx_bytes(200 + k as u64, 191); + Subject { + txid: txid_of(&bytes), + bytes: Some(bytes), + born_measured: subject.born_measured, + } + } + None => subject, + }; + tracker.track(&subject.txid); + let mut w = World { + s: subject.state(), + subject, + h: h.clone(), + clock: 0, + }; + for &(code, a, b, dt) in trace { + w.clock += u64::from(dt); + w.h = h.clone(); + // The world's headers move only by proofs here, so every word + // stands on one set of headers. + let i = input(&mut w, code, a, b); + if let Some(i) = i { + if !door_takes(&i) { + h = w.h.clone(); + let _ = tracker.apply(&w.subject.txid, &h, i); + } + } + } + before.push(tracker.get(&w.subject.txid).unwrap().clone()); + } + for height in fh.max(1)..=6 { + if moved[height as usize] { + h.move_root(height, block(height) + 900); + } + } + let updates = tracker.on_chain(&h, reorg(fh)); + (before, tracker, updates) +} + +fn tracker_draw() -> impl Strategy, u32, Vec)> { + ( + prop::collection::vec(trace(), 1..8), + 0u32..8, + prop::collection::vec(any::(), 8), + ) +} + +/// `minedAtOrAbove` and `conflictedAtOrAbove`, the two selections of a +/// reorg at `fh`. +fn selected(fh: u32, s: &State) -> bool { + s.word().height().is_some_and(|h| fh <= h) || (conflicted(s).is_some() && rivalAtOrAbove(fh, s)) +} + +/// Over `Tracker::on_chain` with the door: a reorg touches no state that +/// neither selection names. +#[test] +fn reorg_touches_only_the_recheck_sets() { + let (spared, touched) = (Cell::new(0), Cell::new(0)); + runner() + .run(&tracker_draw(), |(traces, fh, moved)| { + let (before, tracker, _) = reorged(&traces, fh, &moved); + for old in &before { + let after = tracker.get(old.txid()).unwrap(); + if selected(fh, old) { + hit(&touched); + } else { + hit(&spared); + prop_assert_eq!(after, old); + } + } + Ok(()) + }) + .unwrap(); + reached("a state the reorg spares", &spared); + reached("a state the reorg selects", &touched); +} + +/// The selection of a reorg is exactly the `mined` words at or above its +/// fork height and the `conflicted` words with a standing competitor at or +/// above it (`conflictReask_only`), each once and no more than the host +/// tracks (`conflictReask_bounded`). +#[test] +fn conflictReask_only() { + let n = Cell::new(0); + runner() + .run(&tracker_draw(), |(traces, fh, moved)| { + let (before, _, updates) = reorged(&traces, fh, &moved); + let want: std::collections::BTreeSet<&str> = before + .iter() + .filter(|s| selected(fh, s)) + .map(State::txid) + .collect(); + let got: Vec<&str> = updates.iter().map(|u| u.txid.as_str()).collect(); + let unique: std::collections::BTreeSet<&str> = got.iter().copied().collect(); + prop_assert_eq!(unique.len(), got.len()); + prop_assert_eq!(&unique, &want); + prop_assert!(got.len() <= before.len()); + if before + .iter() + .any(|s| conflicted(s).is_some() && rivalAtOrAbove(fh, s)) + { + hit(&n); + } + Ok(()) + }) + .unwrap(); + reached("a conflicted word the reorg selects", &n); +} + +// --------------------------------------------------------------------------- +// The crate's own +// --------------------------------------------------------------------------- + +/// The crate's own (the length rule's K4 scope; ahead of the Lean, whose +/// competitor has no length): a competitor's proof is judged by the +/// competitor's own length and never moves the tracked transaction's +/// measure, whatever that measure is, 64 included; a checked competitor +/// goes on the record with its length. +#[test] +fn a_competitors_length_is_its_own() { + let (n, at_64) = (Cell::new(0), Cell::new(0)); + each_step(|e| { + let Some(Input::Evidence(Evidence::Competitor(p))) = e.input else { + return Ok(()); + }; + prop_assert_eq!(e.after.tx_len(), e.before.tx_len()); + if e.result.is_ok() && !matches!(e.before.word(), Word::Mined(_)) { + hit(&n); + if e.before.tx_len() == Some(AMBIGUOUS_TX_LEN) { + hit(&at_64); + } + prop_assert!(conflicted(e.after).is_some()); + let entry = &e.after.rivals()[0]; + prop_assert_eq!(entry.txid(), p.txid()); + prop_assert_eq!(entry.tx_len(), Some(191)); + } + Ok(()) + }); + reached("a competitor on the record", &n); + reached( + "a competitor beside a tracked transaction measured at 64", + &at_64, + ); +} + +/// The crate's own (the decoder's third shape, which it leaves as it is): no +/// run from the birth lists an id on a `conflicted` word whose entries on the +/// record are all marked gone; every listed id stands on the record. +#[test] +fn no_run_lists_an_id_whose_only_entry_is_gone() { + let n = Cell::new(0); + each_state(|e| { + let Some(cs) = conflicted(e.after) else { + return Ok(()); + }; + hit(&n); + prop_assert!(!e.after.rivals().is_empty()); + for id in cs { + prop_assert!(e + .after + .rivals() + .iter() + .any(|r| r.txid() == id && r.standing())); + } + Ok(()) + }); + reached("a conflicted word", &n); +} + +/// The crate's own (the decoder's refusal of `conflicted` from `handed` with +/// no instance): along every run of either machine, a `conflicted` word whose +/// prior word is `handed` keeps a non-empty list, so its return gives +/// `handed` with an instance. +#[test] +fn conflicted_from_handed_keeps_its_list() { + let n = Cell::new(0); + each_state(|e| { + if conflicted(e.after).is_some() && e.after.prior() == Some(&Word::Handed) { + hit(&n); + prop_assert!(!e.after.handed_to().is_empty()); + } + Ok(()) + }); + reached("conflicted from handed", &n); +} From 99e4447ceb814ae6d6a33209051ea9927703b180 Mon Sep 17 00:00:00 2001 From: John Calhoun Date: Sun, 29 Nov 2026 00:09:45 -0500 Subject: [PATCH 04/12] compact: refuse conflicted whose prior word is handed with no instance (for #47) No run writes it (the property conflicted_from_handed_keeps_its_list): a conflict begun from handed keeps the list for its return, and a return from such bytes would give handed with no instance, which the decoder refuses on its own bytes. Issue 57's rows of pull request 72, item 2. Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index 704b68b..da68bb0 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -46,12 +46,14 @@ //! (`handed word with no instance`); an instance named twice //! (`instance named twice`); instances beside a word that holds none, any word //! but `handed` and `conflicted` whose prior word is `handed` -//! (`instances beside a word that holds none`); a prior word that is `mined` -//! or `conflicted`, which no run writes (`prior word`); a competitor's checked -//! proof with no length (`competitor's proof with no length`); a length beside -//! a competitor with no proof (`named competitor with a length`); and a -//! competitor with no proof marked gone, which has no root to lose -//! (`named competitor marked gone`). As [`CompactError::Evidence`]: a +//! (`instances beside a word that holds none`); `conflicted` whose prior +//! word is `handed` with no instance, whose return would be `handed` with +//! none (`conflicted from handed with no instance`); a prior word that is +//! `mined` or `conflicted`, which no run writes (`prior word`); a competitor's +//! checked proof with no length (`competitor's proof with no length`); a +//! length beside a competitor with no proof (`named competitor with a +//! length`); and a competitor with no proof marked gone, which has no root +//! to lose (`named competitor marked gone`). As [`CompactError::Evidence`]: a //! competitor that is the tracked transaction, or whose proof is another //! transaction's ([`CheckError::TxidMismatch`]); a competitor's length of 64 //! ([`CheckError::AmbiguousLength`]); and a competitor's record that does not @@ -229,11 +231,16 @@ pub(crate) fn decode(bytes: &[u8]) -> Result { return Err(CompactError::Evidence(CheckError::AmbiguousLength)); } // The instances stand beside `handed`, and beside `conflicted` whose - // conflict began from `handed` (kept for its return). + // conflict began from `handed` (kept for its return), which holds one. match (&word, handed_to.is_empty()) { (Some(Word::Handed), true) => { return Err(CompactError::Malformed("handed word with no instance")); } + (Some(Word::Conflicted { .. }), true) if prior == Some(Word::Handed) => { + return Err(CompactError::Malformed( + "conflicted from handed with no instance", + )); + } (Some(Word::Handed), _) | (_, true) => {} (Some(Word::Conflicted { .. }), _) if prior == Some(Word::Handed) => {} _ => { From d862a6d165eb124bde4ac4712f1d5615e45e10d0 Mon Sep 17 00:00:00 2001 From: John Calhoun Date: Sun, 29 Nov 2026 00:09:45 -0500 Subject: [PATCH 05/12] state, tracker: a set in the named join and in the door's selection, behaviour unchanged (for #47) name_the_unrecorded and Tracker::on_chain each scanned a list per item; the list and the record grow with every verdict a node repeats. Each now keeps the ids it has in a set; the order written and the ids selected are as before. Issue 57's rows of pull request 72, item 4. Co-Authored-By: Claude Opus 5.5 --- src/state.rs | 4 +++- src/tracker.rs | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/state.rs b/src/state.rs index ead8a71..9d35dc4 100644 --- a/src/state.rs +++ b/src/state.rs @@ -1490,8 +1490,10 @@ impl State { /// Ahead of the Lean: `Tracker.onCompetitor` and `Tracker.onVerdict` keep /// the record of such a state as it was. fn name_the_unrecorded(listed: &[TxId], rivals: &mut Vec) { + let mut recorded: std::collections::BTreeSet = + rivals.iter().map(|r| r.txid.clone()).collect(); for id in listed { - if !rivals.iter().any(|r| &r.txid == id) { + if recorded.insert(id.clone()) { rivals.push(Competitor::named(id.clone())); } } diff --git a/src/tracker.rs b/src/tracker.rs index 30c1a45..4c34a17 100644 --- a/src/tracker.rs +++ b/src/tracker.rs @@ -327,8 +327,9 @@ impl Tracker { .unwrap_or_default(), _ => BTreeSet::new(), }; + let mut selected: BTreeSet = targets.iter().cloned().collect(); for txid in conflicted { - if !targets.contains(&txid) { + if selected.insert(txid.clone()) { targets.push(txid); } } From 320c69548b0b48177284819a07886b6445295ebd Mon Sep 17 00:00:00 2001 From: John Calhoun Date: Sun, 29 Nov 2026 00:09:46 -0500 Subject: [PATCH 06/12] tests: four goldens with a record, #47's refusals as bytes, and the return check made live (for #47) The goldens carry each competitor's length beside the tracked transaction's own field (191 on the record, 65 or unmeasured in the last field), the named competitor with none, and the return with the record marked. The refusals are spelled from the same pieces; a record with no prior word is read, and a run writes one (a restored version 1 row joined). The generator of tests/compact.rs runs each step under either machine with two competitors; the property a_conflicted_word_and_its_record_name_the_same_competitors reads the row's conflict before the step, so a return by that step is checked. Co-Authored-By: Claude Opus 5.5 --- tests/compact.rs | 42 ++++-- tests/compact_golden.rs | 300 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 333 insertions(+), 9 deletions(-) diff --git a/tests/compact.rs b/tests/compact.rs index 1a10109..fa9a443 100644 --- a/tests/compact.rs +++ b/tests/compact.rs @@ -68,7 +68,7 @@ fn status(code: u8, height: u32, n: u64) -> Hint { fn input(h: &mut TestHeaders, subject: &Subject, code: u8, height: u32, n: u64) -> Input { h.fault = false; let own = subject.own(height, n, (n >> 3) as u8); - let other = competitor(2, height, n); + let other = competitor(2 + n % 2, height, n); match code % 17 { 0 | 1 => { h.insert(&own, u64::from(height)); @@ -105,7 +105,9 @@ fn input(h: &mut TestHeaders, subject: &Subject, code: u8, height: u32, n: u64) /// places (GHSA-jjhc-7hvh-c3hm, BRC-237); and, for #47, the door at random /// places: the block of the newest standing competitor replaced and the /// reorg at its height fed under `Params::recheck_conflicted`, so the record -/// holds marks and the word returns. +/// holds marks and the word returns; each step of the trace under the latch +/// or the door (a bit of the hint byte picks), and a competitor's proof one +/// of two competitors', built from its bytes. fn states() -> impl Strategy)> { ( any::(), @@ -122,7 +124,8 @@ fn build(kind: u8, trace: Vec<(u8, u32, u64, u8)>) -> State { let mut h = TestHeaders::default(); for (code, height, n, hint) in trace { let i = input(&mut h, &subject, code, height, n); - let _ = s.step(¶ms(), &h, i); + let machine = params().with_recheck_conflicted(hint & 0x40 != 0); + let _ = s.step(&machine, &h, i); if hint % 3 == 0 { let _ = s.step(¶ms(), &h, Input::Hint(status(hint, height, n))); } @@ -302,21 +305,30 @@ fn a_conflicted_word_and_its_record_name_the_same_competitors() { let machine = params().with_recheck_conflicted(hint & 0x80 != 0); let empty_before = s.rivals().is_empty() && untouched.is_some(); let i = input(&mut h, &subject, code, height, n); + // Read before the step, so that a return by this very step + // finds the row's conflict still open. + let was_left = left; + let was_conflicted = matches!(s.word(), Word::Conflicted { .. }); let _ = s.step(&machine, &h, i); if empty_before && !s.rivals().is_empty() { joined.set(joined.get() + 1); } + // The row's own competitors never leave: a return is of a + // later conflict, begun after the row's ended by another door. + if from_row + && was_conflicted + && !matches!(s.word(), Word::Conflicted { .. }) + && matches!(s.reask(), Some(Reask::CompetitorGone { .. })) + { + prop_assert!(was_left); + returned_from_a_row.set(returned_from_a_row.get() + 1); + } if !matches!(s.word(), Word::Conflicted { .. }) { left = true; } if !s.rivals().is_empty() || !matches!(s.word(), Word::Conflicted { .. }) { untouched = None; } - // The row's own competitors never leave: a return is of a - // later conflict, begun after the row's ended by another door. - if from_row && matches!(s.reask(), Some(Reask::CompetitorGone { .. })) { - prop_assert!(left); - } word_and_record_agree(&s, untouched.as_ref())?; if hint % 11 == 4 { let newest = s @@ -328,12 +340,20 @@ fn a_conflicted_word_and_its_record_name_the_same_competitors() { if let Some(at) = newest { h.move_root(at, n); let door = params().with_recheck_conflicted(true); + let was_conflicted = matches!(s.word(), Word::Conflicted { .. }); let _ = s.step(&door, &h, Input::Evidence(Evidence::Chain(reorg(at)))); - if from_row && matches!(s.reask(), Some(Reask::CompetitorGone { .. })) { + if from_row + && was_conflicted + && !matches!(s.word(), Word::Conflicted { .. }) + { // The row's own competitors never leave. prop_assert!(left); returned_from_a_row.set(returned_from_a_row.get() + 1); } + if !matches!(s.word(), Word::Conflicted { .. }) { + left = true; + untouched = None; + } word_and_record_agree(&s, untouched.as_ref())?; } } @@ -349,6 +369,10 @@ fn a_conflicted_word_and_its_record_name_the_same_competitors() { ); assert!(restored_rows.get() > 0, "restored rows: none"); assert!(joined.get() > 0, "joins on a restored row: none"); + assert!( + returned_from_a_row.get() > 0, + "returns of a later conflict on a restored row: none" + ); } #[test] diff --git a/tests/compact_golden.rs b/tests/compact_golden.rs index 2ac039c..9445291 100644 --- a/tests/compact_golden.rs +++ b/tests/compact_golden.rs @@ -1019,3 +1019,303 @@ fn a_version_1_conflicted_row_nothing_joins_never_leaves_and_writes_back_whole() fn chain_reorg(height: u32) -> Input { Input::Evidence(Evidence::Chain(reorg(height))) } + +// --------------------------------------------------------------------------- +// The record of a conflict and the door (for #47) +// --------------------------------------------------------------------------- + +/// The competitor of the record goldens: `tx_bytes(2, 191)`, its proof at +/// height 10 built from those bytes (sibling `hash(3)`), its header block +/// `hash(10)`. +fn competitor_x() -> (Proof, TestHeaders) { + let p = competitor(2, 10, 3); + let mut h = TestHeaders::default(); + h.insert(&p, 10); + (p, h) +} + +fn conflicted_with_a_checked_competitor_state() -> State { + let (p, h) = competitor_x(); + let mut s = State::new(hash(1)); + step(&mut s, &h, Input::Host(HostAction::Build)); + step( + &mut s, + &h, + Input::Hint(Hint::new("arc", HintStatus::Accepted, 2)), + ); + step(&mut s, &h, Input::Evidence(Evidence::Competitor(p))); + assert_eq!(s.prior(), Some(&Word::Announced)); + assert_eq!(s.rivals()[0].tx_len(), Some(191)); + s +} + +fn conflicted_from_handed_state() -> State { + let (p, h) = competitor_x(); + // The tracked transaction measured at 65 bytes: the state's field is its + // own, and the competitor's length beside it is the competitor's. + let mut s = State::measured(&tx_bytes(1, 65)); + step(&mut s, &h, hand_over("arc", 5)); + step(&mut s, &h, Input::Evidence(Evidence::Competitor(p))); + assert_eq!(s.prior(), Some(&Word::Handed)); + assert_eq!(s.handed_to(), &[HandedTo::new("arc", 5)]); + assert_eq!((s.tx_len(), s.rivals()[0].tx_len()), (Some(65), Some(191))); + s +} + +fn conflicted_named_by_a_node_state() -> State { + let (p, h) = competitor_x(); + let mut s = State::new(hash(1)); + step(&mut s, &h, Input::Host(HostAction::Build)); + step( + &mut s, + &h, + Input::Evidence(Evidence::Verdict(NodeVerdict::Conflicted { + competitors: vec![p.txid().to_owned()], + })), + ); + assert_eq!(s.rivals()[0].checked(), None); + assert_eq!(s.rivals()[0].tx_len(), None); + s +} + +fn returned_with_the_record_marked_state() -> State { + let mut s = conflicted_with_a_checked_competitor_state(); + let (_, mut h) = competitor_x(); + h.move_root(10, 510); + let door = params().with_recheck_conflicted(true); + s.step(&door, &h, Input::Evidence(Evidence::Chain(reorg(10)))) + .unwrap(); + assert_eq!(s.word(), &Word::Announced); + assert!(s.rivals()[0].gone()); + assert!(matches!(s.reask(), Some(Reask::CompetitorGone { .. }))); + s +} + +/// The id of the competitor `tx_bytes(2, 191)` (`00` and its txid). +const X: &str = "0026799f2d2e3c4eff3897459139bc0a02649d75829e7d06be2498fa921604ff09"; +/// The id of the root of its proof at 10, the same in its header. +const ROOT: &str = "00f0a67227cc922b25030f8d686492b9eadb5417a867a8c503d1754f1f33d057c7"; + +/// The competitor's checked proof as the record writes it: its txid; its +/// path (height `0a`, one level of two leaves: offset `00` flags `06` and +/// its txid, offset `01` flags `04` and `hash(3)`); its header's hash +/// (`hash(10)`) and root; its root; its depth `01`. +fn x_checked() -> String { + [ + X, + "0a0102", + "0006", + X, + "0104", + &format!("00{}", hash(3)), + &format!("00{}", hash(10)), + ROOT, + ROOT, + "01", + ] + .concat() +} + +/// One competitor on the record: its id, its length (`len`: `00` none, or +/// `01` and a varint), its checked proof (`00` none, or `01` and the proof) +/// and its mark. +fn entry(id: &str, len: &str, checked: Option<&str>, gone: &str) -> String { + let checked = checked.map_or("00".to_owned(), |c| format!("01{c}")); + [id, len, &checked, gone].concat() +} + +/// The hint "arc" accepted at 2 (`03 617263`, tag `00`, at `02`, no +/// verdict), alone on the list, and its time as the last hint's (`01 02`). +const ARC_ACCEPTED_AT_2: &str = "01036172630002000102"; + +fn conflicted_with_a_checked_competitor_bytes(len: &str, prior: &str) -> String { + [ + &opening(), + &format!("0701{X}"), + "0000", + ARC_ACCEPTED_AT_2, + "00", + "00", + "01", + &entry(X, len, Some(&x_checked()), "00"), + prior, + "00", + ] + .concat() +} + +/// A competitor's proof from its bytes on an `announced` word: word tag `07` +/// with the competitor's id; no evidence, not suspect; the hint and its time; +/// no re-ask, no instance; a record of one (`01`): the competitor's id, its +/// own length 191 (`01 bf01`), its checked proof, standing (`00`); the prior +/// word `announced` (`01 02`); and the tracked transaction's own length +/// field, unmeasured (`00`). +#[test] +fn conflicted_with_a_checked_competitor() { + golden( + "conflicted with a checked competitor", + &conflicted_with_a_checked_competitor_state(), + &conflicted_with_a_checked_competitor_bytes("01bf01", "0102"), + ); +} + +fn conflicted_from_handed_bytes(instances: &str) -> String { + [ + "0200a52356b689764778ad032561f508391e10c09db85ba9a9c382073c69f9638cb5", + &format!("0701{X}"), + "0000", + "0000", + "00", + instances, + "01", + &entry(X, "01bf01", Some(&x_checked()), "00"), + "0109", + "0141", + ] + .concat() +} + +/// A `handed` word joined by a competitor: the instance "arc" at `05` kept +/// for the return; the prior word `handed` (`01 09`); and two lengths that +/// are not one: the competitor's 191 on the record (`01 bf01`) and the +/// tracked transaction's own 65 in the last field (`01 41`). +#[test] +fn conflicted_from_handed() { + golden( + "conflicted from handed", + &conflicted_from_handed_state(), + &conflicted_from_handed_bytes("010361726305"), + ); +} + +fn conflicted_named_by_a_node_bytes(record: &str) -> String { + [ + &opening(), + &format!("0701{X}"), + "0000000000", + "00", + "01", + record, + "0101", + "00", + ] + .concat() +} + +/// A node's verdict names the competitor: on the record with no length +/// (`00`), no proof (`00`), standing (`00`); the prior word `built` +/// (`01 01`). +#[test] +fn conflicted_named_by_a_node() { + golden( + "conflicted named by a node", + &conflicted_named_by_a_node_state(), + &conflicted_named_by_a_node_bytes(&entry(X, "00", None, "00")), + ); +} + +/// The return through the door: word `announced` (`02`); the hint kept; the +/// re-ask `competitor gone` (`01 08`) naming the word's one competitor; the +/// record kept with its competitor marked gone (`01`), its length and its +/// proof as they were; the prior word kept (`01 02`). +#[test] +fn returned_with_the_record_marked() { + golden( + "returned with the record marked", + &returned_with_the_record_marked_state(), + &[ + &opening(), + "02", + "0000", + ARC_ACCEPTED_AT_2, + &format!("010801{X}"), + "00", + "01", + &entry(X, "01bf01", Some(&x_checked()), "01"), + "0102", + "00", + ] + .concat(), + ); +} + +/// #47's refusals, each spelled as bytes beside the golden it departs from. +#[test] +fn record_refusals() { + let malformed = CompactError::Malformed; + let z = format!("00{}", txid_of(&tx_bytes(3, 191))); + let tracked = format!("00{}", hash(1)); + for (name, bytes, why) in [ + ( + "a checked proof with no length", + conflicted_with_a_checked_competitor_bytes("00", "0102"), + malformed("competitor's proof with no length"), + ), + ( + "a competitor's length of 64", + conflicted_with_a_checked_competitor_bytes("0140", "0102"), + CompactError::Evidence(CheckError::AmbiguousLength), + ), + ( + "a prior word mined", + conflicted_with_a_checked_competitor_bytes("01bf01", "0104"), + malformed("prior word"), + ), + ( + "a prior word conflicted", + conflicted_with_a_checked_competitor_bytes("01bf01", "010700"), + malformed("prior word"), + ), + ( + "a length beside no proof", + conflicted_named_by_a_node_bytes(&entry(X, "01bf01", None, "00")), + malformed("named competitor with a length"), + ), + ( + "a named competitor marked gone", + conflicted_named_by_a_node_bytes(&entry(X, "00", None, "01")), + malformed("named competitor marked gone"), + ), + ( + "a competitor that is the tracked transaction", + conflicted_named_by_a_node_bytes(&entry(&tracked, "00", None, "00")), + CompactError::Evidence(CheckError::TxidMismatch), + ), + ( + "a competitor whose proof is another's", + conflicted_named_by_a_node_bytes(&entry(&z, "01bf01", Some(&x_checked()), "00")), + CompactError::Evidence(CheckError::TxidMismatch), + ), + ( + "conflicted from handed with no instance", + conflicted_from_handed_bytes("00"), + malformed("conflicted from handed with no instance"), + ), + ] { + refused(name, &bytes, why); + } + // The record with no prior word is read: a restored version 1 row that a + // competitor joined is such a state (`a_record_with_no_prior_word_...`). + let no_prior = conflicted_with_a_checked_competitor_bytes("01bf01", "00"); + let s = State::from_compact(&unhex(&no_prior)).unwrap(); + assert_eq!(s.prior(), None); + assert_eq!(hex(&s.to_compact()), no_prior); +} + +/// A record with no prior word, written by a run: the published version 1 +/// `conflicted` row restored, a competitor's proof joined to it (the row's +/// own competitors named on the record), and its bytes read back whole. +#[test] +fn a_record_with_no_prior_word_is_written_by_a_run_and_restores() { + let (mut s, _) = version_1_conflicted(); + assert_eq!(s.prior(), None); + let (p, h) = competitor_x(); + s.step(¶ms(), &h, Input::Evidence(Evidence::Competitor(p))) + .unwrap(); + assert!(!s.rivals().is_empty()); + assert_eq!(s.prior(), None); + let bytes = s.to_compact(); + let restored = State::from_compact(&bytes).unwrap(); + assert_eq!(restored, s); + assert_eq!(restored.to_compact(), bytes); +} From e32b64dc4c54383d895976a175811912784a886f Mon Sep 17 00:00:00 2001 From: John Calhoun Date: Sun, 29 Nov 2026 00:10:43 -0500 Subject: [PATCH 07/12] tests: the three scenarios of record under both machines, the same states step by step (for #47) The latch, the production proofs and the reorg nobody hears meet no conflicted word, so stepRecheck_eq_step says the door changes none of their states: each runs under both machines and the trails are compared. Co-Authored-By: Claude Opus 5.5 --- tests/scenarios.rs | 145 ++++++++++++++++++++++++++++++++++++--------- 1 file changed, 117 insertions(+), 28 deletions(-) diff --git a/tests/scenarios.rs b/tests/scenarios.rs index 74a2b94..6367178 100644 --- a/tests/scenarios.rs +++ b/tests/scenarios.rs @@ -1,5 +1,8 @@ //! Local tracker projections of the seven corpus witnesses at stack pin f95520f. //! Actual wallet calls, caches and feed delivery are integration lane work. +//! The three scenarios of `lean/Tracker/Scenarios.lean` (the latch, the +//! production proofs, the reorg nobody hears) run under both machines (for +//! #47) and give the same states. // The lint bar binds the library; a test may unwrap, and its fixtures fail loudly // (bsv-stack-lean #134). #![allow( @@ -12,18 +15,51 @@ mod common; use bsv_tracker::*; use common::*; -#[test] -fn mined_orphaned_remined_broadcaster_latch() { +/// A step of a scenario under the machine `p`, its state kept in the trail. +fn go(p: &Params, trail: &mut Vec, s: &mut State, h: &TestHeaders, i: Input) { + s.step(p, h, i).unwrap(); + trail.push(s.clone()); +} + +/// The scenario under the latch and under the machine with the door +/// (`Params::recheck_conflicted`, for #47): no step of it meets a +/// `conflicted` word, so the Lean's `stepRecheck_eq_step` says the two give +/// the same states, step by step. +fn both_machines(scenario: fn(&Params, &mut Vec)) { + let (mut latch, mut door) = (vec![], vec![]); + scenario(¶ms(), &mut latch); + scenario(¶ms().with_recheck_conflicted(true), &mut door); + assert!(!latch.is_empty()); + assert!(latch + .iter() + .all(|s| !matches!(s.word(), Word::Conflicted { .. }))); + assert_eq!(latch, door); +} + +fn mined_orphaned_remined_broadcaster_latch_under(p: &Params, trail: &mut Vec) { let txid = hash(1); let mut s = State::new(&txid); let mut h = TestHeaders::default(); announce(&mut s, &h); + trail.push(s.clone()); let old = proof(&txid, 100, 2); h.insert(&old, 100); - step(&mut s, &h, hint(HintStatus::Mined { height: 100 }, 2)); + go( + p, + trail, + &mut s, + &h, + hint(HintStatus::Mined { height: 100 }, 2), + ); assert_eq!(s.word(), &Word::Seen); assert!(matches!(s.reask(), Some(Reask::Hint(_)))); - step(&mut s, &h, Input::Evidence(Evidence::Proof(old.clone()))); + go( + p, + trail, + &mut s, + &h, + Input::Evidence(Evidence::Proof(old.clone())), + ); mined(&s, 100); assert_eq!(s.reask(), None); step( @@ -39,52 +75,72 @@ fn mined_orphaned_remined_broadcaster_latch() { assert!(s.suspect()); assert_eq!(s.reask(), Some(&Reask::Fork { height: 100 })); h.insert(&proof(&hash(3), 100, 4), 101); - step(&mut s, &h, Input::Evidence(Evidence::Chain(reorg(100)))); + go( + p, + trail, + &mut s, + &h, + Input::Evidence(Evidence::Chain(reorg(100))), + ); assert_eq!(s.word(), &Word::Stale); assert!(!s.suspect()); assert_eq!(s.reask(), Some(&Reask::Reorg { fork_height: 100 })); let retained = s.evidence().cloned(); - step(&mut s, &h, hint(HintStatus::StaleBlock, 3)); + go(p, trail, &mut s, &h, hint(HintStatus::StaleBlock, 3)); assert_eq!(s.word(), &Word::Stale); assert_eq!(s.evidence(), retained.as_ref()); - step(&mut s, &h, hint(HintStatus::Mined { height: 100 }, 4)); + go( + p, + trail, + &mut s, + &h, + hint(HintStatus::Mined { height: 100 }, 4), + ); assert_eq!(s.word(), &Word::Stale); assert!(matches!( - s.step(¶ms(), &h, Input::Evidence(Evidence::Proof(old))), + s.step(p, &h, Input::Evidence(Evidence::Proof(old))), Err(CheckError::RootMismatch(100)) )); assert_eq!(s.word(), &Word::Stale); assert_eq!(s.reask(), Some(&Reask::ProofFailed { height: 100 })); - step(&mut s, &h, hint(HintStatus::Seen, 5)); + go(p, trail, &mut s, &h, hint(HintStatus::Seen, 5)); assert_eq!(s.word(), &Word::Stale); - step(&mut s, &h, Input::Host(HostAction::Tick(1_000))); + go(p, trail, &mut s, &h, Input::Host(HostAction::Tick(1_000))); assert_eq!(s.word(), &Word::Stale); assert!(matches!(s.reask(), Some(Reask::Hint(_)))); let new = proof(&txid, 102, 5); h.insert(&new, 102); - step(&mut s, &h, Input::Evidence(Evidence::Proof(new))); + go(p, trail, &mut s, &h, Input::Evidence(Evidence::Proof(new))); mined(&s, 102); assert_eq!(s.reask(), None); - step(&mut s, &h, hint(HintStatus::StaleBlock, 1_001)); + go(p, trail, &mut s, &h, hint(HintStatus::StaleBlock, 1_001)); mined(&s, 102); - step(&mut s, &h, Input::Host(HostAction::SpendAttempt)); + go(p, trail, &mut s, &h, Input::Host(HostAction::SpendAttempt)); mined(&s, 102); assert_eq!(s.reask(), Some(&Reask::Spend)); - step(&mut s, &h, Input::Evidence(Evidence::Recheck)); + go(p, trail, &mut s, &h, Input::Evidence(Evidence::Recheck)); mined(&s, 102); // The landed Tracker.recheck clears the completed trigger (Lean line 340). assert_eq!(s.reask(), None); } #[test] -fn reorg_announced_nobody_hears_go_server_ts_client_shape() { +fn mined_orphaned_remined_broadcaster_latch() { + both_machines(mined_orphaned_remined_broadcaster_latch_under); +} + +fn reorg_announced_nobody_hears_go_server_ts_client_shape_under( + p: &Params, + trail: &mut Vec, +) { let txid = hash(1); let mut s = State::new(&txid); let mut h = TestHeaders::default(); announce(&mut s, &h); + trail.push(s.clone()); let old = proof(&txid, 100, 2); h.insert(&old, 100); - step(&mut s, &h, Input::Evidence(Evidence::Proof(old))); + go(p, trail, &mut s, &h, Input::Evidence(Evidence::Proof(old))); mined(&s, 100); h.insert(&proof(&hash(3), 100, 4), 101); mined(&s, 100); @@ -100,44 +156,72 @@ fn reorg_announced_nobody_hears_go_server_ts_client_shape() { mined(&s, 100); let wire = serde_json::to_vec(&ChainEnvelope::new(reorg(100))).unwrap(); let event = decode_envelope(&wire).unwrap(); - step(&mut s, &h, Input::Evidence(Evidence::Chain(event))); + go( + p, + trail, + &mut s, + &h, + Input::Evidence(Evidence::Chain(event)), + ); assert_eq!(s.word(), &Word::Stale); - step(&mut no_feed, &h, Input::Evidence(Evidence::Recheck)); + go( + p, + trail, + &mut no_feed, + &h, + Input::Evidence(Evidence::Recheck), + ); assert_eq!(no_feed.word(), &Word::Stale); - step(&mut s, &h, Input::Host(HostAction::Tick(1_000))); + go(p, trail, &mut s, &h, Input::Host(HostAction::Tick(1_000))); assert_eq!(s.word(), &Word::Stale); - step(&mut s, &h, hint(HintStatus::Seen, 1_001)); + go(p, trail, &mut s, &h, hint(HintStatus::Seen, 1_001)); assert_eq!(s.word(), &Word::Stale); - step(&mut s, &h, Input::Host(HostAction::SpendAttempt)); + go(p, trail, &mut s, &h, Input::Host(HostAction::SpendAttempt)); assert_eq!(s.word(), &Word::Stale); assert_eq!(s.reask(), Some(&Reask::Spend)); - step(&mut s, &h, Input::Evidence(Evidence::Recheck)); + go(p, trail, &mut s, &h, Input::Evidence(Evidence::Recheck)); assert_eq!(s.word(), &Word::Stale); assert_eq!(s.reask(), Some(&Reask::Spend)); } #[test] -fn production_proofs_orphaned_healed_without_a_hand() { +fn reorg_announced_nobody_hears_go_server_ts_client_shape() { + both_machines(reorg_announced_nobody_hears_go_server_ts_client_shape_under); +} + +fn production_proofs_orphaned_healed_without_a_hand_under(p: &Params, trail: &mut Vec) { let mut h = TestHeaders::default(); for n in [1, 2] { let txid = hash(n); let mut s = State::new(&txid); let old = proof(&txid, 100, n + 10); h.insert(&old, 100); - step(&mut s, &h, Input::Evidence(Evidence::Proof(old.clone()))); + go( + p, + trail, + &mut s, + &h, + Input::Evidence(Evidence::Proof(old.clone())), + ); mined(&s, 100); h.insert(&proof(&hash(3), 100, 20), 101); - step(&mut s, &h, Input::Evidence(Evidence::Chain(reorg(100)))); + go( + p, + trail, + &mut s, + &h, + Input::Evidence(Evidence::Chain(reorg(100))), + ); assert_eq!(s.word(), &Word::Stale); assert!(s - .step(¶ms(), &h, Input::Evidence(Evidence::Proof(old))) + .step(p, &h, Input::Evidence(Evidence::Proof(old))) .is_err()); assert_eq!(s.word(), &Word::Stale); let new = proof(&txid, 102, n + 30); h.insert(&new, 102); - step(&mut s, &h, Input::Evidence(Evidence::Proof(new))); + go(p, trail, &mut s, &h, Input::Evidence(Evidence::Proof(new))); mined(&s, 102); - step(&mut s, &h, Input::Evidence(Evidence::Recheck)); + go(p, trail, &mut s, &h, Input::Evidence(Evidence::Recheck)); mined(&s, 102); assert_eq!( s.evidence().unwrap().header().merkle_root, @@ -146,6 +230,11 @@ fn production_proofs_orphaned_healed_without_a_hand() { } } +#[test] +fn production_proofs_orphaned_healed_without_a_hand() { + both_machines(production_proofs_orphaned_healed_without_a_hand_under); +} + #[test] fn contract_1_versioned_envelope_fails_loud() { let txid = hash(1); From d2f93ed5d85b80c631457b74331a063bac3c1d5f Mon Sep 17 00:00:00 2001 From: John Calhoun Date: Sun, 29 Nov 2026 00:18:38 -0500 Subject: [PATCH 08/12] ci: the vectors job runs the rows of the record and the door by name (for #47) The tracker's rows step runs rows_of_record_recheck beside rows_of_record_handed and greps its two count lines: 14 named passes. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3d3de1e..9fdd443 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -159,13 +159,19 @@ jobs: grep -q '^test result: ok. 1 passed; 0 failed; 0 ignored' proof_length.out # tests/vectors/tracker/rows_of_record.json: the Lean's rows of the word - # handed, under the machine without the recheck + # handed, under the machine without the recheck; the rows of the record + # and the door, of LeafRows and the crate's own, each under its own + # machine; and the latch's rows again through the door where + # stepRecheck_eq_step covers them - name: The tracker's rows of record run: | cargo test --locked --test tracker_rows -- --exact --nocapture \ - rows_of_record_handed | tee tracker_rows.out + rows_of_record_handed \ + rows_of_record_recheck | tee tracker_rows.out grep -q '^rows_of_record_handed: 46 rows under step, 0 divergences, 0 not spelled$' tracker_rows.out - grep -q '^test result: ok. 1 passed; 0 failed; 0 ignored' tracker_rows.out + grep -q '^rows_of_record_recheck: 53 rows, 45 under recheck and 8 under step, 0 divergences, 1 not spelled, 0 ahead of the Lean$' tracker_rows.out + grep -q '^rows_of_record_latch_through_the_door: 52 of 54 rows of the latch covered by stepRecheck_eq_step and replayed under recheck, 1 not covered, 0 divergences, 1 not spelled$' tracker_rows.out + grep -q '^test result: ok. 2 passed; 0 failed; 0 ignored' tracker_rows.out # The wallet, the overlay engine and the app layer host this crate in wasm. wasm32: From c3e088f69ab6c56b9c6a3c49e0d1d62d32301ac5 Mon Sep 17 00:00:00 2001 From: John Calhoun Date: Sun, 29 Nov 2026 00:18:38 -0500 Subject: [PATCH 09/12] CHANGELOG, docs: the recheck of conflicted's tests of record (for #47) The rows of both machines and their replay, the properties beside their theorems, the goldens and refusals, issue 57's rows of the earlier change, and the eight planted faults with the tests that caught each. VERIFICATION says that two hosts agree on the word under the door only where they hold the same record. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 +++++ docs/VERIFICATION.md | 101 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 83af393..675a973 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,17 @@ Mirrored from bsv-stack-lean's `lean/Tracker.lean` at `a7ef91de` (section "The r - `tests/compact_golden.rs`: every golden string is byte-identical but `conflicted_by_ids_and_text`'s tail, where the node's verdict now writes its two competitors on the record and the prior word `unknown`; its old ending is quoted in its doc. `version_1_bytes_still_restore` and `version_2_is_version_1_with_four_empty_fields` read that one state's record apart; `handed_refusals` and `tests/compact.rs`'s `version_2_refusals` lose the refusals of a record "held empty in this release"; `an_instance_beside_each_word_of_record` reads the list kept beside `conflicted` only when its prior word is `handed`. - Tests: `tests/transitions.rs` (the latch over a `conflicted` word under every chain event and a recheck; a competitor's proof for the tracked txid, refused in both modes, the latch's old answer quoted; the record and the prior word; a competitor's length and the tracked transaction's measure kept apart, the K4 scope of the crate's issue 57; the door's rows over one state), `tests/reorg_by_root.rs` (the latch's outputs over a registry with `conflicted` words, unchanged with the flag named off; the selection under the door; one header read per standing competitor with a proof), `tests/compact.rs` (a state with a record round-trips; the record's refusals; the round trip's generator feeds the door), `tests/labels.rs` (`competitor_gone`), a unit test of `leave_word`. `tests/handed_properties.rs`'s `handed_to_only_beside_handed` is tightened to `conflicted` whose prior word is `handed`, both ways. +### Tests: the recheck of `conflicted`'s tests of record (for #47) + +Mirrored from bsv-stack-lean's `lean/Tracker.lean` at `a7ef91de` (blob `c2a6045a`): the rows of the namespace `Tracker.HandedRows` from "The competitor's proof goes on the record" to its end and the namespace `Tracker.LeafRows`, and the theorems of the section "The recheck of `conflicted`". The crate is one machine with a mode; its tests run the Lean's rows of both machines, each under its own. + +- `tests/vectors/tracker/rows_of_record.json` (sha256 `0e8f13056b9fd5dfd0785f870c0347f1565a918176216f87313c6ec9fec2d3e1`) gains the 47 rows of the record and the door and the 5 of `LeafRows`, one row one `#guard`, its text verbatim, and one row of the crate's own (`self_competitor_refused`, `Tracker.competitor_is_another` at a taken payment); every row names its group and its machine, and each input of a trace the machine the source passes it through (`run P` or `runR`). 99 rows: the 46 of the word under `step`; of the 53, 45 under the door and 8 under the latch. `LeafRows`' competitor named "C" offered X's proof is listed by name as not spelled: the crate names a competitor by its proof's own txid. +- `tests/tracker_rows.rs`, `rows_of_record_recheck` (new): every row of the 53 under its own machine, `0 divergences, 1 not spelled, 0 ahead of the Lean` (no row starts from a state stored before the record existed, so none meets the crate's named join); then the 54 rows of the latch a second time through the door wherever `stepRecheck_eq_step`'s premise holds at every step of the row's traces: 52 replayed, 1 not covered (`returned.5`, the latch's own reorg on `conflictedT`), 0 divergences. The `vectors` job runs it by name beside `rows_of_record_handed` and greps its three lines: 14 named passes. +- `tests/recheck_properties.rs` (new): 23 properties, each named for its Lean theorem (`step_conflicted_latched` to `conflictReask_only` and `conflictReads_le`), and 3 of the crate's own (`a_competitors_length_is_its_own`, the length rule's scope: a competitor's length never moves the tracked transaction's measure, 64 included; `no_run_lists_an_id_whose_only_entry_is_gone`; `conflicted_from_handed_keeps_its_list`). 256 cases each from the fixed ChaCha seed, no failure persistence; every trace runs under both machines, with two competitors whose proofs are built from their bytes, and each premise is met in some case. +- `tests/properties.rs`: `mined_implies_checked_proof`, `stale_iff_header_inactive` and `hint_changes_no_chain_word` run each trace under both machines with two competitors; `same_evidence_same_word` stays over the latch: two hosts agree on the word under the door only where they hold the same record. `tests/compact.rs`: the generator runs each step under either machine with two competitors; `a_conflicted_word_and_its_record_name_the_same_competitors` reads the row's conflict before the step, so a return by that very step is checked (it was not), and fails when the named join is removed. `tests/scenarios.rs`: the three scenarios of record run under both machines and give the same states step by step. +- `tests/compact_golden.rs`: four goldens with a record, each spelled field by field, each competitor's length beside the tracked transaction's own field: `conflicted_with_a_checked_competitor` (prior `announced`), `conflicted_from_handed` (the instance kept, the competitor's 191 beside the tracked transaction's 65), `conflicted_named_by_a_node` (no length, no proof), `returned_with_the_record_marked` (`announced`, `competitor_gone`, the mark); `record_refusals`, #47's refusals as bytes beside them; and `a_record_with_no_prior_word_is_written_by_a_run_and_restores` (a restored version 1 row that a competitor joined: read, not refused). +- Refused, in the compact form: `conflicted` whose prior word is `handed` with no instance (`Malformed("conflicted from handed with no instance")`), whose return would be `handed` with none; no run writes it. The named join and the door's selection keep the ids they hold in a set; behaviour unchanged. + ### Hosts: what a host of 0.9.0-beta.11 changes to take the tenth word (for #56) **A host of 0.9.0-beta.11 changes each exhaustive match on `Word`, and may start feeding three acts.** (1) `Word` has a tenth word, `Word::Handed`, and is still not `#[non_exhaustive]`, on purpose: every exhaustive match on `Word` outside the crate stops compiling (E0004) until it names the word, because each place that names words must decide what `handed` means for it. (2) A host that feeds no `HostAction::HandOver` never sees `Word::Handed`, and every word it sees is the word it saw at 0.9.0-beta.11: no other act, hint or evidence writes it (the Lean's `handedNamed_run` and the arms of `step` in `lean/Tracker.lean` at bsv-stack-lean `08ce467d`). Once a host feeds the act, a rule that reads a word by its text or through a wildcard arm reads `handed` as whatever that arm says, in silence; name each before feeding the act. (3) A re-ask of the new kind `Reask::Reannounce` asks the host to post the bytes again to each instance of `State::handed_to()`; it is never a proof request, so a host that fetches a proof for every due re-ask whatever its kind fetches the wrong thing for it. `Reask::LABELS` gains `"reannounce"` at its end. (4) `State::to_compact` writes version 2 of the compact form. Version 1 bytes a host stored still restore, as the same state with no instance; an older crate refuses version 2 bytes with `CompactError::UnknownVersion(2)` and restores nothing. diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index 2283cf7..e59d9b8 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -1707,3 +1707,104 @@ Not mirrored here, each a host's: the wallet's statements over the word (`lean/W | `a_version_1_conflicted_row_is_latched_with_the_door_off` | the same row and join with the door off: the reorg leaves the state whole | green | green | | `a_version_1_conflicted_row_nothing_joins_never_leaves_and_writes_back_whole` | the row restored and never joined, the door on, two reorgs, a recheck and a tip: the state as restored, its record empty, and its bytes the version 1 row with the opening byte `02` and four empty fields, spelled as a literal | green | green | | `a_conflicted_word_and_its_record_name_the_same_competitors` (`tests/compact.rs`) `[AHEAD OF THE LEAN]` | over the round trip's generator (256 cases), every other case born a restored version 1 row on `hash(9)`, each step under the door or the latch: after every step a `conflicted` word's ids and its record's standing ids are one set unless the record is empty, an empty record stands beside the row's own word alone, and a restored row returns only from a later conflict begun after the subject's own proof ended the row's | red | green: 129 restored rows, 46 joins on a restored row, 1 return of a later conflict | + +## The recheck of `conflicted`'s tests of record (for #47, 2026-11-29) + +The record of a conflict, the prior word and the door behind `Params::recheck_conflicted` landed in an earlier change; this section is their tests of record: the Lean's executable rows of both machines in the rows file with their replay, and the theorems of the section "The recheck of `conflicted`" as properties. The crate is one machine with a mode (the keeper's ruling, on the condition that its tests run the Lean's rows of both machines): the replay runs each row under the machine its source runs it in. + +[SRC] The stack: bsv-stack-lean at `a7ef91de` (`a7ef91de104944e3b02c920a935e8549c19dcc89`), `lean/Tracker.lean` (blob `c2a6045a`), the namespaces `Tracker.HandedRows` and `Tracker.LeafRows` and the section "The recheck of `conflicted`". Its `main` on this host's clone is the same commit, read without a fetch: `onCompetitor` and `onVerdict` still keep the record of a restored version 1 row as it was, so the crate's named join stays `[AHEAD OF THE LEAN]`. + +[X] The rows, counted at that commit with `grep -c '^#guard'`: 110 in the file; `HandedRows` 93, of which the 47 from "The competitor's proof goes on the record" to the namespace's end are the record's and the door's (the plan's 47); `LeafRows` 5. 52 rows of the Lean, against the plan's 52 (which counted 47, 4 of `LeafRows` and 1 of the crate's own): all 52 are transcribed, one of them is not spelled, and the crate's own row comes beside them, 53 in all. + +**The rows file**, `tests/vectors/tracker/rows_of_record.json` (sha256 `0e8f13056b9fd5dfd0785f870c0347f1565a918176216f87313c6ec9fec2d3e1`). Each row names its group (`handed`, `recheck`, `leaf`, `crate`) and the machine it runs under (`step`, the latch, `State::step` under `Params::new(10, 1)`; `recheck`, the door, the same with `with_recheck_conflicted(true)`), and each input of a new row's trace the machine the source passes it through: the source's `runH` and `run P` are `step`, its `runR` is `recheck`. The `LeafRows` rows run under `⟨0, 1⟩` (`params: P0`). The headers are the source's (`h0`, `hX`, `hY`, `hT`, `hXZ`, `hYZ`, `hA`, `hA'`, `hB`), a block's hash is its name's bytes read as a number, and `root-B`, `LeafRows`' block holding T and X, is the root of two proofs that name each other as their sibling. The competitors are bytes (`X`, `Z`; `V` is named by a verdict alone) and their proofs are built from them. The new asserts read the prior word, the mark, the record (each competitor's txid, its checked proof's height, root, leaf and header), the marks in order, the evidence of another trace's state, the Lean's `view` (`word.chain()`, `evidence()`, `suspect()`) against another's, and `conflictReads` as the header reads of one recheck under the door, counted. The Lean's machine answers no error; the crate's error beside a state is printed and the row judges the state (a row of the word's 46 names none, and an error there is a divergence). + +| group | rows | under `recheck` | under `step` | +|---|---|---|---| +| `handed` | 46 | | 46 | +| `recheck` | 47 | 45 | 2 (`returned.5`, the latch's reorg on `conflictedT`; `other_words.1`, `staleT` built by `run P`) | +| `leaf` | 5 | | 5 (`leaf.4` not spelled) | +| `crate` | 1 | | 1 (`self_competitor_refused`) | + +Not spelled, by name: `leaf.4`, a competitor named "C" offered X's proof. `Evidence::Competitor(Proof)` names the competitor by its proof's own txid, so a proof of another leaf cannot be offered for C. + +**The replay**, `tests/tracker_rows.rs`. `rows_of_record_handed` is as before. `rows_of_record_recheck` runs the 53 rows each under its own machine, then every row of the latch in the file (54: the word's 46, the two of the door's group, the leaf rows and the crate's) a second time with the flag on wherever the Lean's `stepRecheck_eq_step` states the two machines agree: its premise, that a step meets a word that is not `conflicted` or an input that is neither a chain event nor a recheck, is read at every step of the row's trace and of a trace it compares with; a row where it fails is printed as not covered and not judged, since no theorem states the machines agree there. No row starts from a state stored before the record existed (every row starts at `State.init "T"`), so no row is one the crate answers ahead of the Lean by its named join: the count is 0. + +```text +$ cargo test --locked --test tracker_rows -- --exact --nocapture rows_of_record_handed rows_of_record_recheck +rows_of_record_handed: 46 rows under step, 0 divergences, 0 not spelled +not spelled: leaf.4: a competitor named C offered X's proof: the crate names a competitor by its proof's own txid (Evidence::Competitor(Proof)), so a proof of another leaf cannot be offered for C +the crate's error beside the state: fail_closed.1: the step ["reorg",100,1,["B100"],"B101b"] answered Unavailable(100) +the crate's error beside the state: leaf.1: the step ["proof",100,"root-B","X"] answered TxidMismatch +the crate's error beside the state: self_competitor_refused: the step ["competitor","T",101,"root-T","T"] answered TxidMismatch +rows_of_record_recheck: 53 rows, 45 under recheck and 8 under step, 0 divergences, 1 not spelled, 0 ahead of the Lean +not covered by stepRecheck_eq_step: returned.5: a conflicted word meets ["reorg",100,1,["B100"],"B101b"] +rows_of_record_latch_through_the_door: 52 of 54 rows of the latch covered by stepRecheck_eq_step and replayed under recheck, 1 not covered, 0 divergences, 1 not spelled +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +``` + +(Lines of the same kind for `fail_closed.2` to `.4` and `leaf.2` are left out above.) The `vectors` job runs both by name and greps the three count lines: its named passes go from 13 to 14. + +**The properties**, `tests/recheck_properties.rs`: 26 tests, 23 named for the Lean theorems they mirror and 3 of the crate's own, 256 cases each from the explicit ChaCha seed with no failure persistence. Every trace of up to 59 acts runs from the subject's birth under both machines: every host act and the three of the hand-over, every hint status, the subject's own proof by either constructor with and without its header, the proofs of two competitors (`tx_bytes(2, 191)`, `tx_bytes(3, 191)`) built from their bytes with and without their header, both verdicts (a `conflicted` one naming one of the two or a competitor no proof is offered for), the competitors' roots moved, dropped and put back, reorgs, forks, tips, splits, resolved splits, invalidations, rechecks under headers that answer, have no header and fault, and the measure. An act's statement is asked of it played on a copy of every state under the trace's headers, the same with every root moved, and headers that answer nothing. Each premise is met in some case (checked). The Lean's `rootGone`, `unanswered`, `rivalAtOrAbove` and `leaveWord` are mirrored in the test under their names. + +| test | the Lean's theorem | what is checked | +|---|---|---| +| `step_conflicted_latched` | `step_conflicted_latched` | over the latch, every chain event and recheck leaves a `conflicted` state as it is | +| `stepRecheck_eq_step` | `stepRecheck_eq_step` | on every step its premise covers, the two machines give the same state and answer (a `conflicted` word meeting another input occurs) | +| `recheckConflict_spares_others` | `recheckConflict_spares_others`, by the crate's road (`stepRecheck_of_not_conflicted`) | off `conflicted`, the door's chain rows and recheck are the latch's | +| `recheckConflict_leaves_iff` | `recheckConflict_leaves_iff` | a recheck returns exactly when the record is not empty and each competitor is gone or its root is gone (both sides occur) | +| `conflict_leaves_to_prior` | `conflict_leaves_to_prior` | a return writes `leaveWord prior`, `CompetitorGone` of the word's competitors, the mark cleared, the evidence and the record's length kept | +| `conflict_no_header_fails_closed` | `conflict_no_header_fails_closed` | an unanswered competitor keeps `conflicted`, `Reask::Recheck`, the mark as it was, and a fault | +| `verdict_named_never_leaves` | `verdict_named_never_leaves` | a standing named competitor keeps `conflicted` under every recheck and chain row | +| `rootGone_iff` | `rootGone_iff`, `markGone_gone` | a recheck marks a competitor gone exactly when it was or a header at its height has another root; order, txids and proofs kept | +| `rootGone_iff_competitor_stale` | `rootGone_iff_competitor_stale` | the competitor's own state, `mined` on the record's proof, reads `stale` at a recheck exactly when ours marks it gone (both occur) | +| `conflict_reorg_exact` | `conflict_reorg_exact` | a reorg at each fork height 0 to 7 returns exactly when a standing competitor with a proof is at or above it and all are gone | +| `conflict_reorg_spares_below` | `conflict_reorg_spares_below` | a reorg above every standing competitor leaves the state as it is | +| `conflict_tip_unmarked` | `conflict_tip_unmarked` | a tip on an unmarked `conflicted` word leaves it as it is | +| `onChainConflict_keeps` | `onChainConflict_keeps` | the feed on `conflicted` keeps the evidence, the txid and the measure | +| `conflicted_exits` | `conflicted_exits` | a door step leaving `conflicted` is the own proof (to `mined` at its height), `rejected`, or a return to `leaveWord prior` with all gone (each occurs) | +| `hint_never_moves_conflicted` | `hint_never_moves_conflicted` | no hint status moves a `conflicted` word | +| `handed_written_cases` | `handed_written_cases` | a door step writes a fresh `handed` by a hand-over or by a return from `conflicted` with prior `handed`, with its list (both occur) | +| `evidenced_runRecheck` | `evidenced_runRecheck` | along the door, a `mined` word holds a checked proof at its height whose header carries its root | +| `mined_rests_on_its_leaf` | `mined_rests_on_its_leaf` | along the door from the birth, a `mined` word's proof is of the tracked txid | +| `competitor_is_another` | `competitor_is_another` | in either machine, a competitor's proof of the tracked txid is `TxidMismatch`, the state as it was but `ProofFailed` at its height | +| `returned_then_mined` | `returned_then_mined` | from every state of the door, the own proof under a header carrying it writes `mined` at its height; the crate's length rule beside it (no subject of 64 bytes, no stated lie) | +| `conflictReads_le` | `conflictReads_le` | a recheck of `conflicted` reads one header a standing competitor with a proof, no more than the record holds; a tip on an unmarked word reads none | +| `reorg_touches_only_the_recheck_sets` | `reorg_touches_only_the_recheck_sets` | over `Tracker::on_chain` with the door and up to seven tracked states, a reorg leaves untouched every state neither selection names | +| `conflictReask_only` | `conflictReask_only`, `conflictReask_bounded` | the reorg's updates are exactly the `mined` at or above and the `conflicted` with a standing competitor at or above, each once, no more than tracked | +| `a_competitors_length_is_its_own` | none: the crate's own (the length rule's K4 scope, ahead of the Lean) | a competitor's step never moves the tracked measure, 64 included; a checked competitor enters the record at its own 191 | +| `no_run_lists_an_id_whose_only_entry_is_gone` | none: the crate's own (the decoder's third shape, left as it is) | along every run from the birth, every id of a `conflicted` list stands on a non-empty record | +| `conflicted_from_handed_keeps_its_list` | none: the crate's own (the ground of the decoder's refusal below) | along every run of either machine, `conflicted` with prior `handed` holds a non-empty list | + +The plan named 22 properties, counting `conflictReask_only` with `conflictReask_bounded` and leaving `conflictReads_le` beside them; here they are 23 and the bounded statement rides `conflictReask_only`. + +**Over the latch alone**: `same_evidence_same_word` (`tests/properties.rs`) runs over the latch alone, since theorem (iv) is a statement of `step` and the Lean's `sameViewOtherRecord` shows equal views part over the door: two hosts agree on the word under the door only where they hold the same record of the conflict. Its three companions run each trace under both machines, with the two competitors; `tests/compact.rs`'s generator runs each step under either machine; `tests/scenarios.rs` runs the three scenarios of record under both and compares the states step by step. + +**The goldens and the refusals**, `tests/compact_golden.rs`, on the layout the record rides at version 2 (no prerelease reads version 2 yet, so no version 3), each spelled from field pieces: + +| golden | the state | the record and the fields beside it | +|---|---|---| +| `conflicted_with_a_checked_competitor` | built, an acceptance from "arc", X's proof at 10 | `01`, X's id, its length `01 bf01`, its checked proof, `00`; prior `01 02`; the tracked transaction's field `00` | +| `conflicted_from_handed` | measured at 65 bytes, handed to "arc" at 5, X's proof | the instance `01 03617263 05` kept; X at `01 bf01`; prior `01 09`; the tracked field `01 41` | +| `conflicted_named_by_a_node` | built, a verdict naming X | X's id, `00 00 00` (no length, no proof, standing); prior `01 01` | +| `returned_with_the_record_marked` | the first, X's root moved, the reorg at 10 under the door | word `02`; re-ask `01 08 01` and X's id; X at `01 bf01` marked `01`; prior `01 02` | + +`record_refusals`: a checked proof with no length, a competitor's length of 64, a prior word `mined` and one `conflicted`, a length beside no proof, a named competitor marked gone, a competitor that is the tracked transaction, one whose proof is another's, and `conflicted` from `handed` with no instance; and the record with no prior word read back whole. `a_record_with_no_prior_word_is_written_by_a_run_and_restores`: the published version 1 `conflicted` row, a competitor joined, its bytes restored equal. + +**Issue 57's rows of the earlier change.** The decoder now refuses `conflicted` whose prior word is `handed` with no instance (`Malformed("conflicted from handed with no instance")`), whose return would give `handed` with none; `conflicted_from_handed_keeps_its_list` says no run writes it. A record with no prior word is read, pinned by the run above. A list naming an id whose only entry is gone is left to the decoder as it is, and `no_run_lists_an_id_whose_only_entry_is_gone` says no run writes it. The property `a_conflicted_word_and_its_record_name_the_same_competitors` read its flag from the same step it checked; it now reads the row's conflict before the step, asserts a return of a later conflict occurs, and fails when the named join is removed (below). The named join and the door's selection keep their ids in a set; behaviour unchanged. + +[X] Eight faults planted in the arms the door added, one at a time and reverted after (`git diff origin/beta -- src` at the end holds the two source changes above alone), the full suite run each time; each fails some of this change's tests: + +| the fault | this change's tests that failed | others | +|---|---|---| +| the return when one competitor still stands (`standing.len() <= 1`) | `conflict_no_header_fails_closed`, `conflict_reorg_exact`, `conflicted_exits`, `recheckConflict_leaves_iff`, `verdict_named_never_leaves`, `rows_of_record_recheck`, `a_conflicted_word_and_its_record_name_the_same_competitors` | five of the earlier change | +| the prior word read without the cap of `seen` | `conflict_leaves_to_prior`, `rows_of_record_recheck` | two | +| the self refusal removed | `competitor_is_another` | one | +| a verdict-named competitor marked gone at a recheck | `conflict_reorg_exact`, `conflicted_exits`, `recheckConflict_leaves_iff`, `rootGone_iff`, `verdict_named_never_leaves`, `rows_of_record_recheck`, `a_conflicted_word_and_its_record_name_the_same_competitors`, `compact_round_trip_over_256_random_states`, `every_proper_prefix_is_truncated_and_a_suffix_is_trailing` | four | +| the record dropped on a hint | `hint_changes_no_chain_word`, `no_run_lists_an_id_whose_only_entry_is_gone`, `a_conflicted_word_and_its_record_name_the_same_competitors` | none | +| the named join removed | `a_conflicted_word_and_its_record_name_the_same_competitors` | one | +| the decoder's new refusal removed | `record_refusals` | none | +| a competitor's length read as the tracked transaction's measure | `a_competitors_length_is_its_own`, `conflicted_from_handed`, `compact_round_trip_over_256_random_states`, `every_proper_prefix_is_truncated_and_a_suffix_is_trailing` | eleven of the length rule's | + +The self refusal removed is caught by a property and not by the row `self_competitor_refused`: the tracked transaction of the file has no bytes, so its proof offered as a competitor's is refused by the length rule as well (`Unmeasured`, with the same re-ask), and the row, which judges the state, cannot tell the two refusals apart. + +Not mirrored here, each a host's: the wallet over the door (`settleR`, `relock`, `ReturnSettles`, `returnBreaksFree`), the current depth of a kept competitor's proof against the tip (for the keeper to rule), and theorem (iv) over the door, which the Lean does not state. From cff1599158dbdd772004f401eba0ea71176c86e2 Mon Sep 17 00:00:00 2001 From: John Calhoun Date: Sun, 29 Nov 2026 00:19:51 -0500 Subject: [PATCH 10/12] tests: the lint bar's two findings in the new tests (for #47) clippy -D warnings: a struct literal for the competitor's headers, and the replay's large state variant boxed. Co-Authored-By: Claude Opus 5.5 --- tests/recheck_properties.rs | 6 ++++-- tests/tracker_rows.rs | 6 +++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/tests/recheck_properties.rs b/tests/recheck_properties.rs index 4651dea..f790bb9 100644 --- a/tests/recheck_properties.rs +++ b/tests/recheck_properties.rs @@ -629,8 +629,10 @@ fn rootGone_iff_competitor_stale() { .find(|&n| txid_of(&tx_bytes(n, 191)) == r.txid()) .unwrap(); let mut sx = State::measured(&tx_bytes(n, 191)); - let mut then = TestHeaders::default(); - then.tip = c.height(); + let mut then = TestHeaders { + tip: c.height(), + ..TestHeaders::default() + }; then.headers.insert(c.height(), c.header().clone()); sx.step( &latch(), diff --git a/tests/tracker_rows.rs b/tests/tracker_rows.rs index 332f0f3..3c56ee5 100644 --- a/tests/tracker_rows.rs +++ b/tests/tracker_rows.rs @@ -495,7 +495,7 @@ enum Mode { /// What the replay of one trace gives. enum Ran { /// The state, and the crate's errors along the trace. - State(State, Vec), + State(Box, Vec), /// Under `Mode::Door`, a step outside `stepRecheck_eq_step`'s premise: /// a `conflicted` word met a chain event or a recheck. Uncovered(String), @@ -538,7 +538,7 @@ impl Ctx<'_> { errors.push(format!("the step {} answered {e:?}", step[1])); } } - Ok(Ran::State(s, errors)) + Ok(Ran::State(Box::new(s), errors)) } /// What a row expects, against the state after its trace: `Ok(false)` @@ -550,7 +550,7 @@ impl Ctx<'_> { let (what, want) = expect.iter().next().unwrap(); let other = |trace: &Value| -> Result, String> { match self.run(trace)? { - Ran::State(t, _) => Ok(Some(t)), + Ran::State(t, _) => Ok(Some(*t)), Ran::Uncovered(_) => Ok(None), } }; From 5de9f7dd553f9e77b73f4e1ef59e36351380ea5a Mon Sep 17 00:00:00 2001 From: John Calhoun Date: Sun, 29 Nov 2026 00:21:15 -0500 Subject: [PATCH 11/12] tests: a re-ask held in a binding, so the declared rust-version builds (for #47) cargo +1.88 refuses the temporary borrowed in competitor_is_another's assert (E0716). Co-Authored-By: Claude Opus 5.5 --- tests/recheck_properties.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/recheck_properties.rs b/tests/recheck_properties.rs index f790bb9..ce29e53 100644 --- a/tests/recheck_properties.rs +++ b/tests/recheck_properties.rs @@ -914,7 +914,8 @@ fn competitor_is_another() { let (t, r) = play(e.after, e.p, &h, Input::Evidence(Evidence::Competitor(own))); prop_assert_eq!(r, Err(CheckError::TxidMismatch)); prop_assert!(same_but_reask(&t, e.after)); - prop_assert_eq!(t.reask(), Some(&Reask::ProofFailed { height })); + let failed = Reask::ProofFailed { height }; + prop_assert_eq!(t.reask(), Some(&failed)); Ok(()) }); reached("a state", &n); From c993922b626201f6e12e8c2d5c8752923a51b6ab Mon Sep 17 00:00:00 2001 From: John Calhoun Date: Sun, 29 Nov 2026 00:22:17 -0500 Subject: [PATCH 12/12] docs: a golden's row names the state it starts from (rule 6) (for #47) Co-Authored-By: Claude Opus 5.5 --- docs/VERIFICATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index e59d9b8..b6ab7a7 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -1786,7 +1786,7 @@ The plan named 22 properties, counting `conflictReask_only` with `conflictReask_ | `conflicted_with_a_checked_competitor` | built, an acceptance from "arc", X's proof at 10 | `01`, X's id, its length `01 bf01`, its checked proof, `00`; prior `01 02`; the tracked transaction's field `00` | | `conflicted_from_handed` | measured at 65 bytes, handed to "arc" at 5, X's proof | the instance `01 03617263 05` kept; X at `01 bf01`; prior `01 09`; the tracked field `01 41` | | `conflicted_named_by_a_node` | built, a verdict naming X | X's id, `00 00 00` (no length, no proof, standing); prior `01 01` | -| `returned_with_the_record_marked` | the first, X's root moved, the reorg at 10 under the door | word `02`; re-ask `01 08 01` and X's id; X at `01 bf01` marked `01`; prior `01 02` | +| `returned_with_the_record_marked` | `conflicted_with_a_checked_competitor`'s state, X's root moved, the reorg at 10 under the door | word `02`; re-ask `01 08 01` and X's id; X at `01 bf01` marked `01`; prior `01 02` | `record_refusals`: a checked proof with no length, a competitor's length of 64, a prior word `mined` and one `conflicted`, a length beside no proof, a named competitor marked gone, a competitor that is the tracked transaction, one whose proof is another's, and `conflicted` from `handed` with no instance; and the record with no prior word read back whole. `a_record_with_no_prior_word_is_written_by_a_run_and_restores`: the published version 1 `conflicted` row, a competitor joined, its bytes restored equal.