diff --git a/CHANGELOG.md b/CHANGELOG.md index 62ed360..83af393 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,45 @@ ## [Unreleased] +### Hosts: what a host changes to take the record of a conflict and the recheck of `conflicted` (for #47) + +**A host changes nothing to keep today's machine, and one answer moves for every host.** (1) The latch is the default: `Params::new` sets `Params::recheck_conflicted` to `false`, and with it off a `conflicted` word stays `conflicted` under every chain event and recheck, as before; it leaves only by its own checked proof or a node's `rejected`. (2) For every host, in either mode: a proof offered as a competitor's whose txid is the tracked transaction's is refused, `Err(CheckError::TxidMismatch)` with `Reask::ProofFailed` and nothing else moved, where the latch wrote `conflicted` on the tracked transaction from its own proof. A competitor is another transaction; such bytes go to `Evidence::Proof`. (3) What a host must have checked before it feeds `Evidence::Competitor`: the hash of the competitor's bytes is the crate's check (the proof is built with `Proof::new` from those bytes); that those bytes spend an input of the tracked transaction stays the host's, which the crate cannot see. A competitor known only by someone's word is a hint or a node's verdict. (4) A host that turns the door on, `Params::new(..).with_recheck_conflicted(true)`, feeds its header feed's rows as it does today (`Tracker::on_chain`, or `Evidence::Chain` and `Evidence::Recheck` on one state); after a restore it feeds `Evidence::Recheck` to a `conflicted` word it wants read against today's headers (a restored record is not marked suspect); and on `Reask::CompetitorGone` it fetches the tracked transaction's proof and the named competitors' again. It turns the door on only when its own rules for a returned word are ready: a coin it released when the payment read `conflicted` is still released after the return unless the host locks it back. (5) `State`'s equality compares the record and the prior word; a match on `Reask` outside the crate already carries a wildcard arm (`#[non_exhaustive]`), and `Reask::LABELS` appends `competitor_gone`. + +```rust +// The latch, today's machine: nothing to change. +let params = Params::new(3600, 1); +// The door, when the host's own rules lock back a returned payment's inputs. +let params = Params::new(3600, 1).with_recheck_conflicted(true); + +// Before: a competitor's proof for the tracked txid wrote conflicted [txid]. +// This line, for every host: refused; the proof door takes such a proof. +assert_eq!( + state.step(¶ms, &headers, Input::Evidence(Evidence::Competitor(own_proof))), + Err(CheckError::TxidMismatch) +); +``` + +### Added: the record of a conflict, the word it began from, and the door (for #47) + +Mirrored from bsv-stack-lean's `lean/Tracker.lean` at `a7ef91de` (section "The recheck of `conflicted`"; `onCompetitor`, `onVerdict`, `keptRivals`, `keptPrior`, `verdictRivals`, `verdictPrior`, `leaveWord`, `recheckConflict`, `onChainConflict`, `rivalAtOrAbove`, `rivalCheckedAgainst`, `stepRecheck`, `conflictReask`). + +- `Competitor`, re-exported at the crate root (`Tracker.Competitor`): a competitor on the record, with private fields and the readers `txid()`, `tx_len()`, `checked()`, `gone()` and `standing()`. `tx_len()` is the competitor's own measured length, `Some` for a competitor entered by a proof (never 64) and `None` for one a node's verdict named; it is never the tracked transaction's measure (ahead of the Lean, whose `Competitor` has no length yet). No public constructor and no serde form: a checked proof has neither. +- `State::rivals() -> &[Competitor]` (`State.rivals`), the newest at the front, and `State::prior() -> Option<&Word>` (`State.prior`), the word held when the conflict began. A checked competitor's proof puts the competitor on the record with its proof and length; a node's `conflicted` verdict puts its competitors on it with neither, so no root rechecks them; a conflict that begins starts its own record and keeps the word of its moment as the prior word; a later competitor joins it. A `rejected` verdict and a `mined` word's re-ask leave both. The record is kept, with its marks, after the word leaves `conflicted`. +- `Params::recheck_conflicted: bool`, `false` in `Params::new`, and `Params::with_recheck_conflicted` (`Params` is `#[non_exhaustive]`: no host breaks). `State::step` reads it: off, the latch (`Tracker.step`); on, the machine with the door (`Tracker.stepRecheck`), where a `conflicted` word meeting a chain event or an executed recheck goes through the recheck of the conflict and every other input is the latch's step. +- The recheck reads the host's header at each standing competitor's height that carries a proof, one read each. A header with another root marks the competitor gone; no header, or a headers fault, is not gone. Every competitor gone: the word returns to `leave_word(prior)` (`seen` returns as `announced`; `mined`, `conflicted` or none would read `unknown`; every other word as it was, `handed` with its instances), with `Reask::CompetitorGone { competitors }` naming the word's competitors, the record kept and marked, the suspect mark cleared. A standing competitor unanswered: `conflicted` on the standing competitors, `Reask::Recheck`, the mark as it was, and `Err(CheckError::Unavailable(h))` or `Err(CheckError::Headers(e))` for the unanswered competitor nearest the front. Else `conflicted` on the standing ones, the marks cleared. An empty record and a competitor a node named never leave this way. A restored version 1 `conflicted` row's competitors stand on the record as named ones once a competitor or a verdict joins the word (each id of the word's list with no entry on the record goes on it as named, ahead of `onCompetitor` and `onVerdict` in bsv-stack-lean's `lean/Tracker.lean` at `9a727a64`), so under the door such a row never leaves by a chain event or a recheck. +- The feed under the door, as for `mined`: a reorg at or below a standing competitor's height marks the word and rechecks; an invalidation of a standing competitor's checked header marks and rechecks; a fork at or below one marks it with `Reask::Fork`; a tip rechecks a marked word and reads nothing for an unmarked one. The crate's split meets a `conflicted` word as a fork, and its resolved split as the tip of a marked word at or below a standing competitor, as both meet a `mined` word (the stack's `ChainEvent` has no split). +- `Tracker` keeps two indexes for `conflicted` words: the heights of their standing checked competitors and the headers those were checked against. Under the flag alone, `Tracker::on_chain` adds the words they select to a reorg's, a fork's, a split's and an invalidation's targets, after the `mined` words and with no txid twice. With the flag off the selection and every output are the latch's. +- `Reask::CompetitorGone { competitors: Vec }`, label `competitor_gone`, compact re-ask tag `8`. +- `Evidence::Competitor`'s doc says what the host must have shown: the hash of the competitor's bytes is the crate's check, and the spend of our input stays the host's. + +### Changed: a competitor's proof for the tracked txid is refused, and the compact form carries the record (for #47) + +- `State::step` on `Evidence::Competitor`, in order: a proof whose txid is the tracked one is refused (`CheckError::TxidMismatch`, `Reask::ProofFailed`, the word and the record untouched; `Tracker.competitor_is_another`); then the competitor's own length (a proof not built from its bytes is `CheckError::Unmeasured`); then the header check. +- The compact form fills the two fields version 2 already carries, with no new version: no published release reads version 2. The record: a varint count, then each competitor's txid (an id), its length (`0`, or `1` and a varint), its checked proof (`0`, or `1` and the record as the evidence field writes it, read back as a record and never checked against headers) and its mark. The prior word: `0`, or `1` and a word as the word field writes it. Re-ask tag `8`, competitor gone, and its ids. A record restores exactly, its competitors not marked suspect; a version 1 row restores with an empty record and no prior word. +- Refused, through the variants `CompactError` has: re-ask tag `8` under version 1 (`Malformed("re-ask tag")`); a prior word `mined` or `conflicted` (`Malformed("prior word")`); a competitor's checked proof with no length (`Malformed("competitor's proof with no length")`); a length beside a competitor with no proof (`Malformed("named competitor with a length")`); a competitor with no proof marked gone (`Malformed("named competitor marked gone")`); a competitor that is the tracked transaction, or whose proof is another transaction's (`Evidence(CheckError::TxidMismatch)`); a competitor's length of 64 (`Evidence(CheckError::AmbiguousLength)`); a competitor's record that does not hold together (`Evidence(_)`). Instances now stand only beside `handed` and beside `conflicted` whose prior word is `handed` (`Malformed("instances beside a word that holds none")`). +- `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. + ### 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/README.md b/README.md index 5ddda22..3cc30e5 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,10 @@ so the host tells it the length, and these are the host's duties: unmeasured, and a host that holds its bytes hands them to `State::measure` before it serves the inclusion. - Build a competitor's proof from the competitor's own bytes; any other is - refused (`CheckError::Unmeasured`). + refused (`CheckError::Unmeasured`). The hash of those bytes is the crate's + check; that they spend an input of the tracked transaction stays the + host's to have shown. A proof for the tracked transaction itself is no + competitor's and is refused (`CheckError::TxidMismatch`). - Read every `Result` of a measure or a restore. `State::measure`, `Tracker::track_bytes` and `Tracker::restore` answer `CheckError::AmbiguousLength` when a measure of 64 bytes meets a proof the @@ -101,8 +104,9 @@ An unavailable header or failed check keeps the word and schedules a re-ask. Broadcaster rejection and mempool conflict do not by themselves write `Rejected` or `Conflicted`. `NodeVerdict` is a separate host-supplied authority boundary; a host must not -relabel a broadcaster's refusal as a local node verdict. The host also supplies -the fact that a proved competitor spends one of the tracked inputs. +relabel a broadcaster's refusal as a local node verdict. The crate checks that +a competitor's proof was built from bytes that hash to its txid; the host +supplies the fact that those bytes spend one of the tracked inputs. The host supplies `Headers`, `ProofFetcher`, `HintSource` and `Clock`, executes scheduled re-asks and reports decoding and check errors. After a chain event a diff --git a/docs/SPEC.md b/docs/SPEC.md index 6596751..6e7a83a 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -90,7 +90,7 @@ A transaction of exactly 64 bytes is never taken as proven by a merkle path (BRC No proof built from 64 bytes or on a stated 64 reaches the door: neither constructor yields one. A proof the door takes is kept in the record with no length: the state's measure, beside it, is the length. A row "built from bytes at another length" is reachable only by two byte strings of one hash; the unit test in `src/state.rs` reaches it. -The competitor door takes a proof built from the competitor's own bytes and refuses any other, `Err(Unmeasured)` with the word kept and `Reask::ProofFailed`. The competitor is judged by its own length, never by the tracked transaction's measure: a state measured at 64 still takes a competitor's proof. That the competitor spends an input of the tracked transaction stays the host's to have shown. +The competitor door takes a proof built from the competitor's own bytes and refuses any other, `Err(Unmeasured)` with the word kept and `Reask::ProofFailed`. The competitor is judged by its own length, never by the tracked transaction's measure: a state measured at 64 still takes a competitor's proof. The hash of the competitor's bytes is the crate's check; that the competitor spends an input of the tracked transaction stays the host's to have shown. A proof offered as a competitor's for the tracked txid itself is refused, `Err(TxidMismatch)` with the word and the record kept and `Reask::ProofFailed` (for #47): the proof door is the one that takes it. A competitor's length is kept on the record of the conflict beside its proof (`Competitor::tx_len`) and never unsays the tracked transaction's word. ### The fault roads diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index ad15c58..2283cf7 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -1694,3 +1694,16 @@ The four properties of `tests/properties.rs` keep their names and statements ove At the opening run the seventh fault was caught by the earlier change's example alone: the trace reached a pending `reannounce` beside another word than `handed` in no case. The draw now ticks at the due time five codes in thirty, and `handOver_clears_reannounce` checks that premise is met; it fails on that fault. Not mirrored here, each a host's: the wallet's statements over the word (`lean/Wallet/Handed.lean`, `TakenOnlyHanded`), the merge rank of `handed`, the held answer `heldAnswer .handed`, the refusal of the end of a hold for an action of the host's own (the crate cannot see an origin), and the gate vectors' rows that name `handed`. The rows and the statements of the recheck of `conflicted` (`stepRecheck`, `handed_written_cases`, `returnHanded`) are not in this section. + +## A restored version 1 `conflicted` row under the door (for #47, 2026-11-28) + +[SRC] bsv-stack-lean `lean/Tracker.lean` at `9a727a64` (`9a727a64653b602377b6c3acad543e6997544bfb`): a `State` stored before the record existed reads with `rivals := []` and `prior := none`, and `recheckConflict` leaves a `conflicted` word with no record as it is. `onCompetitor` and `onVerdict` join such a word with `keptRivals`, which keeps the record as it was: the word then lists the stored competitors and the record holds the joined one alone, so the stored ones do not stand once the joined one's root is gone. The crate names them instead, and builds ahead of the Lean there. + +[X] `cargo test --locked`, each answer at the pull request's base before the cure and after it: + +| test | what is checked | before | after | +|---|---|---|---| +| `a_version_1_conflicted_row_keeps_its_competitors_under_the_door` `[AHEAD OF THE LEAN]` | the published `conflicted` row of record (`tests/compact_golden.rs`'s `VERSION_1`), the door on, a checked competitor Z joins, a reorg removes Z's root: the word stays `conflicted` on the row's two competitors, Z marked gone on the record, no `Reask::CompetitorGone`; a later reorg, a recheck and a tip leave it | red: the word read `unknown` with `CompetitorGone` | green | +| `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 | diff --git a/src/compact.rs b/src/compact.rs index d082276..704b68b 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -11,14 +11,14 @@ //! | suspect | `0` or `1` | //! | hints | a varint count, then each hint, the newest at the front | //! | last hint time | `0`, or `1` and a varint | -//! | re-ask | `0`, or `1` and a tag byte (`0` reorg, `1` fork, `2` hint, `3` proof failed, `4` recheck, `5` age, `6` spend, `7` reannounce) and its payload | +//! | re-ask | `0`, or `1` and a tag byte (`0` reorg, `1` fork, `2` hint, `3` proof failed, `4` recheck, `5` age, `6` spend, `7` reannounce, `8` competitor gone and its ids) and its payload | //! | instances | a varint count, then each instance (a string) and the time of its hand-over (a varint), in [`State::handed_to`]'s order | -//! | competitors | a varint count, `0`: the record of a conflict, which this release holds empty | -//! | prior word | `0`: the word held when a conflict began, which this release holds empty | +//! | competitors | a varint count, then each competitor of [`State::rivals`], the newest at the front: its txid (an id), its length (`0`, or `1` and a varint), its checked proof (`0`, or `1` and the record as the evidence field writes it) and its mark (`0` standing, `1` gone) | +//! | prior word | `0`, or `1` and the word held when the conflict began ([`State::prior`]), as the word field writes it | //! | tx length | `0`: the host never handed the transaction's bytes. Or `1` and a varint: the transaction's measured length in bytes ([`State::tx_len`]) | //! //! Version 1 is version 2 without its last four fields, with no word tag `9` -//! and no re-ask tag `7`. The reader reads both: a version 1 row restores as +//! and no re-ask tags `7` and `8`. The reader reads both: a version 1 row restores as //! the state it restored to before, with no instance, no competitor, no //! prior word and no measured length. //! @@ -41,20 +41,33 @@ //! The decoder accepts only the bytes the encoder writes: a non-canonical //! varint, an id written as text that has the raw form, a flag outside its set //! or trailing bytes are each refused. So are, as [`CompactError::Malformed`]: -//! word tag `9` or re-ask tag `7` under version 1 (`word tag`, `re-ask tag`); -//! a `handed` word with no instance (`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` -//! (`instances beside a word that holds none`); a count of competitors that is -//! not `0` (`competitors`); and a prior word that is not `0` (`prior word`). +//! word tag `9` or re-ask tag `7` or `8` under version 1 (`word tag`, +//! `re-ask tag`); a `handed` word with no instance +//! (`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 +//! 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 +//! hold together. The record restores exactly, its competitors not marked +//! suspect; its stored proofs are read back as records, never checked against +//! headers. //! //! [`State::to_compact`]: crate::State::to_compact +//! [`State::rivals`]: crate::State::rivals +//! [`State::prior`]: crate::State::prior //! [`State::handed_to`]: crate::State::handed_to //! [`State::tx_len`]: crate::State::tx_len use crate::{ - CheckError, CheckedProof, HandedTo, Header, Height, Hint, HintStatus, Proof, Reask, Timestamp, - TxId, Verdict, Word, AMBIGUOUS_TX_LEN, + CheckError, CheckedProof, Competitor, HandedTo, Header, Height, Hint, HintStatus, Proof, Reask, + Timestamp, TxId, Verdict, Word, AMBIGUOUS_TX_LEN, }; use bsv_rs::transaction::{MerklePath, MerklePathLeaf}; use std::fmt; @@ -100,6 +113,8 @@ pub(crate) struct Parts { pub last_hint_at: Option, pub reask: Option, pub handed_to: Vec, + pub rivals: Vec, + pub prior: Option, /// None for a version 1 row and for a state the host never measured. pub tx_len: Option, } @@ -113,6 +128,8 @@ pub(crate) struct Fields<'a> { pub last_hint_at: Option, pub reask: Option<&'a Reask>, pub handed_to: &'a [HandedTo], + pub rivals: &'a [Competitor], + pub prior: Option<&'a Word>, pub tx_len: Option, } @@ -120,18 +137,7 @@ pub(crate) fn encode(fields: &Fields<'_>) -> Vec { let mut w = Writer(vec![COMPACT_VERSION]); w.id(fields.txid); w.word(fields.word); - match fields.evidence { - None => w.byte(0), - Some(checked) => { - w.byte(1); - w.id(checked.proof().txid()); - w.path(checked.proof().path()); - w.id(&checked.header().hash); - w.id(&checked.header().merkle_root); - w.id(checked.root()); - w.varint(checked.depth()); - } - } + w.option(fields.evidence, Writer::checked); w.flag(fields.suspect); w.len(fields.hints.len()); for hint in fields.hints { @@ -150,9 +156,15 @@ pub(crate) fn encode(fields: &Fields<'_>) -> Vec { w.string(&held.instance); w.varint(held.at); } - // The record of competitors and the prior word: empty in this release. - w.len(0); - w.byte(0); + // The record of the conflict, the newest at the front, and the prior word. + w.len(fields.rivals.len()); + for rival in fields.rivals { + w.id(rival.txid()); + w.option(rival.tx_len(), Writer::varint); + w.option(rival.checked(), Writer::checked); + w.flag(rival.gone()); + } + w.option(fields.prior, Writer::word); // The measured length, the last field. w.option(fields.tx_len, Writer::varint); w.0 @@ -170,23 +182,7 @@ pub(crate) fn decode(bytes: &[u8]) -> Result { return Err(CompactError::Malformed("txid not lowercase")); } let word = r.word()?; - let evidence = if r.flag()? { - let proof_txid = r.id()?; - let path = r.path()?; - let header = Header { - hash: r.id()?, - merkle_root: r.id()?, - }; - let root = r.id()?; - let depth = r.varint()?; - let proof = Proof::record(&proof_txid, path).map_err(CompactError::Evidence)?; - if proof.txid() != txid { - return Err(CompactError::Evidence(CheckError::TxidMismatch)); - } - Some(CheckedProof::restored(proof, header, root, depth).map_err(CompactError::Evidence)?) - } else { - None - }; + let evidence = r.option(|r| r.checked(&txid))?; let suspect = r.flag()?; let count = r.count()?; let mut hints = Vec::with_capacity(count); @@ -196,6 +192,8 @@ pub(crate) fn decode(bytes: &[u8]) -> Result { let last_hint_at = r.option(Reader::varint)?; let reask = r.option(Reader::reask)?; let mut handed_to: Vec = vec![]; + let mut rivals = vec![]; + let mut prior = None; let mut tx_len = None; if version >= 2 { let count = r.count()?; @@ -207,12 +205,19 @@ pub(crate) fn decode(bytes: &[u8]) -> Result { } handed_to.push(HandedTo::new(instance, at)); } - if r.varint()? != 0 { - return Err(CompactError::Malformed("competitors")); - } - if r.byte()? != 0 { - return Err(CompactError::Malformed("prior word")); + let count = r.count()?; + for _ in 0..count { + rivals.push(r.competitor(&txid)?); } + prior = match r.option(Reader::word)? { + None => None, + // No run writes `mined` or `conflicted` as the word a conflict + // began from. + Some(None | Some(Word::Conflicted { .. })) => { + return Err(CompactError::Malformed("prior word")); + } + Some(Some(word)) => Some(word), + }; tx_len = r.option(Reader::varint)?; } if !r.bytes.is_empty() { @@ -223,11 +228,14 @@ pub(crate) fn decode(bytes: &[u8]) -> Result { if tx_len == Some(AMBIGUOUS_TX_LEN) && evidence.is_some() { return Err(CompactError::Evidence(CheckError::AmbiguousLength)); } + // The instances stand beside `handed`, and beside `conflicted` whose + // conflict began from `handed` (kept for its return). match (&word, handed_to.is_empty()) { (Some(Word::Handed), true) => { return Err(CompactError::Malformed("handed word with no instance")); } - (Some(Word::Handed | Word::Conflicted { .. }), _) | (_, true) => {} + (Some(Word::Handed), _) | (_, true) => {} + (Some(Word::Conflicted { .. }), _) if prior == Some(Word::Handed) => {} _ => { return Err(CompactError::Malformed( "instances beside a word that holds none", @@ -243,6 +251,8 @@ pub(crate) fn decode(bytes: &[u8]) -> Result { last_hint_at, reask, handed_to, + rivals, + prior, tx_len, }) } @@ -323,6 +333,15 @@ impl Writer { Word::Abandoned => self.byte(8), } } + /// A checked proof: its txid, path, header hash and root, root and depth. + fn checked(&mut self, checked: &CheckedProof) { + self.id(checked.proof().txid()); + self.path(checked.proof().path()); + self.id(&checked.header().hash); + self.id(&checked.header().merkle_root); + self.id(checked.root()); + self.varint(checked.depth()); + } fn path(&mut self, path: &MerklePath) { self.height(path.block_height); self.len(path.path.len()); @@ -398,6 +417,10 @@ impl Writer { Reask::Age => self.byte(5), Reask::Spend => self.byte(6), Reask::Reannounce => self.byte(7), + Reask::CompetitorGone { competitors } => { + self.byte(8); + self.ids(competitors); + } } } } @@ -518,6 +541,50 @@ impl Reader<'_> { _ => return Err(CompactError::Malformed("word tag")), })) } + /// A checked proof of `txid`, read back with [`Proof::record`] and held + /// together by `CheckedProof::restored`, never checked against headers. + fn checked(&mut self, txid: &str) -> Result { + let proof_txid = self.id()?; + let path = self.path()?; + let header = Header { + hash: self.id()?, + merkle_root: self.id()?, + }; + let root = self.id()?; + let depth = self.varint()?; + let proof = Proof::record(&proof_txid, path).map_err(CompactError::Evidence)?; + if proof.txid() != txid { + return Err(CompactError::Evidence(CheckError::TxidMismatch)); + } + CheckedProof::restored(proof, header, root, depth).map_err(CompactError::Evidence) + } + /// One competitor of the record of a conflict on the state of `tracked`: + /// its txid, its length, its checked proof and its mark. + fn competitor(&mut self, tracked: &str) -> Result { + let txid = self.id()?; + if txid == tracked { + return Err(CompactError::Evidence(CheckError::TxidMismatch)); + } + let tx_len = self.option(Self::varint)?; + let checked = self.option(|r| r.checked(&txid))?; + let gone = self.flag()?; + match (&checked, tx_len) { + (Some(_), None) => { + return Err(CompactError::Malformed("competitor's proof with no length")); + } + (None, Some(_)) => { + return Err(CompactError::Malformed("named competitor with a length")); + } + (Some(_), Some(AMBIGUOUS_TX_LEN)) => { + return Err(CompactError::Evidence(CheckError::AmbiguousLength)); + } + (None, None) if gone => { + return Err(CompactError::Malformed("named competitor marked gone")); + } + _ => {} + } + Ok(Competitor::restored(txid, tx_len, checked, gone)) + } fn path(&mut self) -> Result { let block_height = self.height()?; let levels = self.count()?; @@ -604,6 +671,9 @@ impl Reader<'_> { 5 => Reask::Age, 6 => Reask::Spend, 7 if self.version >= 2 => Reask::Reannounce, + 8 if self.version >= 2 => Reask::CompetitorGone { + competitors: self.ids()?, + }, _ => return Err(CompactError::Malformed("re-ask tag")), }) } @@ -681,6 +751,9 @@ mod tests { Reask::Age, Reask::Spend, Reask::Reannounce, + Reask::CompetitorGone { + competitors: vec![], + }, ]; assert_eq!(every.len(), Reask::LABELS.len()); let mut tags: Vec = every.iter().map(reask_tag).collect(); diff --git a/src/lib.rs b/src/lib.rs index c6143c7..d9150f3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,7 +19,8 @@ pub use evidence::{ pub use hints::{Hint, HintStatus, Verdict, VerdictError}; pub use host::{Clock, HintSource, ProofFetcher, SpendCheck}; pub use state::{ - Evidence, HandedTo, HostAction, Input, Mined, NodeVerdict, Params, Reask, State, Word, + Competitor, Evidence, HandedTo, HostAction, Input, Mined, NodeVerdict, Params, Reask, State, + Word, }; pub use tracker::{ChainUpdate, Tracker}; diff --git a/src/state.rs b/src/state.rs index 448eb00..ead8a71 100644 --- a/src/state.rs +++ b/src/state.rs @@ -143,15 +143,26 @@ pub enum Evidence { /// proof taken out of a record, which carries no length /// ([`CheckError::Unmeasured`]). Proof(Proof), - /// A proof of a competing transaction's inclusion. What the host must - /// have shown: that the competitor spends an input of the tracked - /// transaction, which the crate cannot see. The proof is built from the - /// competitor's own bytes ([`Proof::new`]), so its txid is their hash - /// and its length is theirs; any other proof is refused - /// ([`CheckError::Unmeasured`]). The competitor is judged by its own - /// length, never by the tracked transaction's measure. A competitor - /// known only by someone's word is a hint or a node's verdict, never - /// this. + /// A proof of a competing transaction's inclusion. + /// + /// The hash of the competitor's bytes is the crate's check: the proof is + /// built from the competitor's own bytes ([`Proof::new`]), so its txid + /// is their hash and its length is theirs, and any other proof is + /// refused ([`CheckError::Unmeasured`]). The spend of our input stays the + /// host's: the host offers a proof here only when those bytes spend an + /// input of the tracked transaction, which the crate cannot see. A + /// competitor is another transaction: a proof whose txid is the tracked + /// one is refused ([`CheckError::TxidMismatch`]), for every host and in + /// either mode, and goes to [`Evidence::Proof`] instead. The competitor + /// is judged by its own length, never by the tracked transaction's + /// measure. A competitor known only by someone's word is a hint or a + /// node's verdict, never this. + /// + /// A checked competitor goes on the record of the conflict + /// ([`State::rivals`]) with its proof and its length, and the word held + /// when the conflict began is kept ([`State::prior`]): the recheck of + /// `conflicted` ([`Params::recheck_conflicted`]) reads both. + /// `Tracker.onCompetitor`. Competitor(Proof), /// A chain event from the host's header feed. Chain(ChainEvent), @@ -186,6 +197,82 @@ impl HandedTo { } } } +/// A competitor on the record of a conflict (`Tracker.Competitor`): its txid, +/// its measured length, the proof the host's headers confirmed when the word +/// was written with the header it was checked against (or none for a +/// competitor a node's verdict named, which no root rechecks), and whether a +/// recheck found its root gone. +/// +/// The fields are private: a competitor is written by the crate's doors +/// alone ([`Evidence::Competitor`], [`NodeVerdict::Conflicted`]) and read by +/// [`State::rivals`]. It has no serde form, since a checked proof has none +/// (bytes are not a check); a host stores the inputs that built it, or the +/// whole state by [`State::to_compact`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Competitor { + txid: TxId, + tx_len: Option, + checked: Option>, + gone: bool, +} +impl Competitor { + /// A competitor a node's verdict named: no proof, no length. + fn named(txid: TxId) -> Self { + Self { + txid, + tx_len: None, + checked: None, + gone: false, + } + } + /// A competitor on the record, as the compact form restores it. + pub(crate) fn restored( + txid: TxId, + tx_len: Option, + checked: Option, + gone: bool, + ) -> Self { + Self { + txid, + tx_len, + checked: checked.map(Arc::new), + gone, + } + } + /// The competing transaction. + #[must_use] + pub fn txid(&self) -> &str { + &self.txid + } + /// The competitor's own length in bytes, measured from the bytes its + /// proof was built from: `Some` for a competitor entered by a proof + /// (never [`AMBIGUOUS_TX_LEN`]), `None` for one a node's verdict named. + /// It is the competitor's alone and never the tracked transaction's + /// measure ([`State::tx_len`]). Ahead of the Lean: the field's name there + /// will be `Competitor.txLen`. + #[must_use] + pub fn tx_len(&self) -> Option { + self.tx_len + } + /// The competitor's checked proof and the header it was checked against, + /// or `None` for a competitor a node's verdict named. + #[must_use] + pub fn checked(&self) -> Option<&CheckedProof> { + self.checked.as_deref() + } + /// Whether a recheck found the competitor's root gone from the host's + /// headers at its height. Once marked, it stays marked. + #[must_use] + pub fn gone(&self) -> bool { + self.gone + } + /// Whether no recheck has found the competitor's root gone + /// (`Tracker.Competitor.standing`). + #[must_use] + pub fn standing(&self) -> bool { + !self.gone + } +} /// Acts supplied by the host, including its clock and spend guard. /// /// `#[non_exhaustive]` (bsv-stack-lean `docs/DECISIONS-2026-10-19.md` @@ -313,6 +400,15 @@ pub enum Reask { /// request, and never [`Reask::Age`]; the next /// [`HostAction::HandOver`] clears it. `Tracker.Reask.reannounce`. Reannounce, + /// Every competitor's root is gone from the host's headers: the + /// `conflicted` word has returned to the word held before the conflict + /// ([`State::prior`]). Fetch the tracked transaction's proof and the + /// named competitors' proofs again. Written only under + /// [`Params::recheck_conflicted`]. `Tracker.Reask.competitorGone`. + CompetitorGone { + /// The competitors the `conflicted` word named before it returned. + competitors: Vec, + }, } impl Reask { /// Every kind's word, in declaration order, which is the order of the @@ -327,6 +423,7 @@ impl Reask { "age", "spend", "reannounce", + "competitor_gone", ]; /// The kind's stable word, the payload not in it: `reorg` for /// `Reorg { fork_height: 10 }`, `hint` for any `Hint(_)`. @@ -341,6 +438,7 @@ impl Reask { Self::Age => "age", Self::Spend => "spend", Self::Reannounce => "reannounce", + Self::CompetitorGone { .. } => "competitor_gone", } } } @@ -404,6 +502,24 @@ pub struct Params { /// [`doubts::accepts`]: crate::doubts::accepts /// [`decode_envelope`]: crate::decode_envelope pub versions: Vec, + /// Which of the two machines the host runs. `false`, the default, is + /// the latch (`Tracker.step`): a `conflicted` word stays `conflicted` + /// under every chain event and recheck, and leaves only by its own + /// checked proof or a node's `rejected`. `true` is the machine with the + /// door (`Tracker.stepRecheck`): a chain event that names a standing + /// competitor on a `conflicted` word's record ([`State::rivals`]), and an + /// executed [`Evidence::Recheck`] on that word, read the host's header at + /// each standing competitor's height. When every competitor's root is + /// gone, the word returns to the word held before the conflict + /// ([`State::prior`]), a `seen` as `announced`, with + /// [`Reask::CompetitorGone`]; a competitor a node's verdict named never + /// leaves this way. Every other input runs the latch's step in either + /// mode. + /// + /// A host turns it on only when its own rules for a returned word are + /// ready: a coin it released when the payment read `conflicted` is still + /// released after the return, unless the host locks it back. + pub recheck_conflicted: bool, } impl Params { /// The row versions [`decode_envelope`](crate::decode_envelope) reads: 1, @@ -412,7 +528,8 @@ impl Params { /// The parameters a host must say: the age threshold, in the clock's /// seconds, and the spend depth. The feed's named number is absent (no - /// check, today's host) and the row versions are [`Params::VERSIONS`]. + /// check, today's host), the row versions are [`Params::VERSIONS`] and + /// the machine is the latch ([`Params::recheck_conflicted`] is `false`). #[must_use] pub fn new(age_threshold: Timestamp, spend_depth: u64) -> Self { Self { @@ -420,6 +537,7 @@ impl Params { bound: None, spend_depth, versions: Self::VERSIONS.to_vec(), + recheck_conflicted: false, } } @@ -443,6 +561,14 @@ impl Params { self.versions = versions; self } + + /// The same parameters with the machine `recheck_conflicted` names: + /// `true` for the machine with the door, `false` for the latch. + #[must_use] + pub fn with_recheck_conflicted(mut self, recheck_conflicted: bool) -> Self { + self.recheck_conflicted = recheck_conflicted; + self + } } /// The complete private state of one transaction. /// @@ -459,6 +585,8 @@ pub struct State { last_hint_at: Option, reask: Option, handed_to: Vec, + rivals: Vec, + prior: Option, tx_len: Option, } impl State { @@ -505,6 +633,8 @@ impl State { last_hint_at: None, reask: None, handed_to: vec![], + rivals: vec![], + prior: None, tx_len, } } @@ -554,6 +684,25 @@ impl State { pub fn handed_to(&self) -> &[HandedTo] { &self.handed_to } + /// The record of the conflict (`Tracker.State.rivals`), the newest at the + /// front: each competitor a checked competitor's proof or a node's + /// `conflicted` verdict put on it, beside and never in + /// [`State::evidence`]. A conflict that begins starts its own record; a + /// later competitor joins it while the word is `conflicted`. Kept, with + /// its marks, after the word leaves `conflicted`. + #[must_use] + pub fn rivals(&self) -> &[Competitor] { + &self.rivals + } + /// The word held when the conflict began (`Tracker.State.prior`), or + /// `None` before any conflict. Never `Mined` and never `Conflicted`. The + /// latch reads it nowhere; under [`Params::recheck_conflicted`] a + /// conflict whose every competitor's root is gone returns to it, a + /// `Seen` as `Announced`. + #[must_use] + pub fn prior(&self) -> Option<&Word> { + self.prior.as_ref() + } /// The transaction's measured length in bytes, or `None` where the host /// never handed the bytes. It is written only from bytes the crate hashed /// to this state's txid ([`State::measured`], [`State::measure`], @@ -660,9 +809,9 @@ impl State { } /// The compact byte form (bsv-stack-lean #92), version 2: a version byte, /// the txid, the word, the evidence, the suspect mark, the hints, the last - /// hint time, the re-ask, the instances of [`State::handed_to`], two - /// fields this release holds empty (the record of a conflict's - /// competitors and the word held when it began), and the measured length + /// hint time, the re-ask, the instances of [`State::handed_to`], the + /// record of a conflict ([`State::rivals`]), the word held when it began + /// ([`State::prior`]), and the measured length /// ([`State::tx_len`]). The layout is in the source of `src/compact.rs`; the /// version byte changes when the layout does, so a later release tells an /// earlier layout from its own rather than misreading it. @@ -677,6 +826,8 @@ impl State { last_hint_at: self.last_hint_at, reask: self.reask.as_ref(), handed_to: &self.handed_to, + rivals: &self.rivals, + prior: self.prior.as_ref(), tx_len: self.tx_len, }) } @@ -694,6 +845,16 @@ impl State { /// as it does any suspect word; a host holding the state alone feeds /// [`Evidence::Recheck`] before it serves the inclusion. /// + /// The record of a conflict and the prior word return exactly: a + /// competitor's checked proof comes back as its record, held together + /// but not checked against any headers, and its competitor is not marked + /// suspect. A host under [`Params::recheck_conflicted`] that wants the + /// record read against today's headers feeds [`Evidence::Recheck`]. A + /// version 1 row restores with an empty record and no prior word, which + /// never leaves `conflicted` by a recheck; a competitor or a verdict that + /// joins it puts the row's own competitors on the record as named, so + /// they never leave either. + /// /// The measured length returns as it was written: a version 2 row /// restores [`State::tx_len`], and a version 1 row restores unmeasured. /// A `mined` row of version 1 was written before the crate measured a @@ -714,7 +875,10 @@ impl State { /// `mined` word with no stored proof among them), and /// [`CompactError::Evidence`] for a stored proof that does not hold /// together, or that stands beside a measured length of 64 bytes - /// ([`CheckError::AmbiguousLength`]). + /// ([`CheckError::AmbiguousLength`]); and for a competitor on the record + /// that is the tracked transaction or whose proof is another's + /// ([`CheckError::TxidMismatch`]), that holds a length of 64, or whose + /// stored proof does not hold together. pub fn from_compact(bytes: &[u8]) -> Result { let parts = crate::compact::decode(bytes)?; let evidence = parts.evidence.map(Arc::new); @@ -738,6 +902,8 @@ impl State { last_hint_at: parts.last_hint_at, reask: parts.reask, handed_to: parts.handed_to, + rivals: parts.rivals, + prior: parts.prior, tx_len: parts.tx_len, }; if mined { @@ -770,12 +936,52 @@ impl State { /// state's measure, and [`CheckError::Unmeasured`] for a proof with no /// length an unmeasured state can read or a competitor's proof not built /// from its bytes: the word and the record kept, the re-ask recorded. + /// + /// # The two machines + /// + /// [`Params::recheck_conflicted`] names the machine. Off, the default, it + /// is the latch (`Tracker.step`): a `Conflicted` word stays as it is under + /// every chain event and recheck. On, it is the machine with the door + /// (`Tracker.stepRecheck`): a `Conflicted` word meeting an + /// [`Evidence::Chain`] or an [`Evidence::Recheck`] goes through the + /// recheck of the conflict, and every other input is the latch's step. + /// The recheck reads the host's header at the height of each standing + /// competitor that carries a proof, one read each, and nothing more: a + /// header there with another root than the competitor's marks it gone, + /// and no header (or a headers fault) is not gone (fail closed). Every + /// competitor gone: the word returns to the word held before the + /// conflict ([`State::prior`]), a `Seen` as `Announced`, with + /// [`Reask::CompetitorGone`] naming the word's competitors, the record + /// kept with its marks, the suspect mark cleared, and the instances kept + /// only when the word returned to is `Handed`. A standing competitor + /// unanswered: `Conflicted` on the standing ones with [`Reask::Recheck`], + /// the suspect mark as it was, and the fault of the unanswered competitor + /// nearest the front ([`CheckError::Unavailable`] or + /// [`CheckError::Headers`]). Else `Conflicted` on the standing ones, the + /// marks cleared. An empty record (a `Conflicted` row restored from + /// version 1 bytes) is never read and never leaves this way, nor does a + /// competitor a node's verdict named, which has no root to lose. + /// + /// What starts the recheck is a row of the feed, never a timer: a reorg + /// at or below a standing competitor's height, an invalidation of the + /// header a competitor was checked against, and a tip on a word a fork + /// (or a split) at or below one marked suspect; a resolved split at or + /// below one rechecks a marked word, as it does a `Mined` one. pub fn step( &mut self, params: &Params, headers: &H, input: Input, ) -> Result<(), CheckError> { + if params.recheck_conflicted && matches!(self.word, Word::Conflicted { .. }) { + match &input { + Input::Evidence(Evidence::Chain(event)) => { + return self.on_chain_conflict(headers, event); + } + Input::Evidence(Evidence::Recheck) => return self.recheck_conflict(headers), + _ => {} + } + } match input { Input::Hint(hint) => self.on_hint(hint), Input::Host(action) => self.on_host(params, &action), @@ -947,6 +1153,14 @@ impl State { } } + /// `Tracker.onCompetitor`, in order: the tracked txid itself is refused + /// (a competitor is another transaction); then the competitor's own + /// length, read from its bytes and never the tracked transaction's + /// measure; then the header check. A checked competitor writes + /// `Conflicted` with itself at the front and goes on the record with its + /// proof and length, the word of this moment kept as the prior word when + /// the conflict begins, unless the word is `Mined`, whose proof is + /// re-asked instead. The list of instances is untouched. fn on_competitor( &mut self, headers: &H, @@ -954,22 +1168,39 @@ impl State { ) -> Result<(), CheckError> { let height = proof.height(); let competitor = proof.txid().to_owned(); - // The competitor's own length, read from its bytes; never the tracked - // transaction's measure. - if !matches!(proof.length(), Some(Len::Measured(_))) { + if competitor == self.txid { self.reask = Some(Reask::ProofFailed { height }); - return Err(CheckError::Unmeasured); + return Err(CheckError::TxidMismatch); } + let Some(Len::Measured(tx_len)) = proof.length() else { + self.reask = Some(Reask::ProofFailed { height }); + return Err(CheckError::Unmeasured); + }; match crate::evidence::check_snapshot(headers, proof) { - Ok(_) => { - match &mut self.word { - Word::Mined(_) => self.reask = Some(Reask::Recheck), - Word::Conflicted { competitors } => competitors.insert(0, competitor), - _ => { - self.word = Word::Conflicted { + Ok(checked) => { + if matches!(self.word, Word::Mined(_)) { + self.reask = Some(Reask::Recheck); + return Ok(()); + } + let entry = Competitor { + txid: competitor.clone(), + tx_len: Some(tx_len), + checked: Some(Arc::new(checked)), + gone: false, + }; + if let Word::Conflicted { competitors } = &mut self.word { + name_the_unrecorded(competitors, &mut self.rivals); + competitors.insert(0, competitor); + self.rivals.insert(0, entry); + } else { + let before = std::mem::replace( + &mut self.word, + Word::Conflicted { competitors: vec![competitor], - } - } + }, + ); + self.rivals = vec![entry]; + self.prior = Some(before); } Ok(()) } @@ -1075,32 +1306,206 @@ impl State { Ok(()) } + /// A chain event, through the machine `params` names: the door for a + /// `Conflicted` word under [`Params::recheck_conflicted`], else the + /// latch's [`State::on_chain`]. What [`Tracker::on_chain`](crate::Tracker::on_chain) + /// runs on each word it selects. + pub(crate) fn chain_step( + &mut self, + params: &Params, + headers: &H, + event: &ChainEvent, + ) -> Result<(), CheckError> { + if params.recheck_conflicted && matches!(self.word, Word::Conflicted { .. }) { + self.on_chain_conflict(headers, event) + } else { + self.on_chain(headers, event) + } + } + + /// `Tracker.onChainConflict`: the feed on a `Conflicted` word, as it is + /// on a `Mined` one. A reorg at or below a standing competitor's height + /// marks the word and rechecks it; an invalidation of a standing + /// competitor's checked header marks and rechecks; a fork at or below + /// one marks it with [`Reask::Fork`] and waits; a tip rechecks a marked + /// word and reads nothing for an unmarked one. The crate's split is a + /// fork, and its resolved split a tip of a marked word at or below a + /// standing competitor, as for `Mined` (the stack's `ChainEvent` has no + /// split). + fn on_chain_conflict( + &mut self, + headers: &H, + event: &ChainEvent, + ) -> Result<(), CheckError> { + match event { + ChainEvent::Tip { .. } if self.suspect => self.recheck_conflict(headers), + ChainEvent::Fork { height, .. } + | ChainEvent::Split { + fork_height: height, + .. + } if self.rival_at_or_above(*height) => { + self.suspect = true; + self.reask = Some(Reask::Fork { height: *height }); + Ok(()) + } + ChainEvent::Reorg { fork_height, .. } if self.rival_at_or_above(*fork_height) => { + self.suspect = true; + self.recheck_conflict(headers) + } + ChainEvent::SplitResolved { fork_height, .. } + if self.suspect && self.rival_at_or_above(*fork_height) => + { + self.recheck_conflict(headers) + } + ChainEvent::Invalidated { block_hash } if self.rival_checked_against(block_hash) => { + self.suspect = true; + self.recheck_conflict(headers) + } + _ => Ok(()), + } + } + + /// `Tracker.recheckConflict`: see [`State::step`], "The two machines". + /// `Tracker.rootGone` is the header read here: a header at the + /// competitor's height whose root is not the competitor's stored root. + fn recheck_conflict(&mut self, headers: &H) -> Result<(), CheckError> { + let Word::Conflicted { competitors } = &self.word else { + return Ok(()); + }; + if self.rivals.is_empty() { + return Ok(()); + } + let competitors = competitors.clone(); + let mut fault = None; + for rival in self.rivals.iter_mut().filter(|r| r.standing()) { + let Some(checked) = &rival.checked else { + continue; + }; + let height = checked.height(); + match headers.header_at(height) { + Ok(Some(header)) => { + if header.merkle_root != checked.root() { + rival.gone = true; + } + } + Ok(None) => { + fault.get_or_insert(CheckError::Unavailable(height)); + } + Err(error) => { + fault.get_or_insert(CheckError::Headers(error)); + } + } + } + let standing: Vec = self + .rivals + .iter() + .filter(|r| r.standing()) + .map(|r| r.txid.clone()) + .collect(); + if standing.is_empty() { + self.word = leave_word(self.prior.as_ref()); + if self.word != Word::Handed { + self.handed_to.clear(); + } + self.reask = Some(Reask::CompetitorGone { competitors }); + self.suspect = false; + return Ok(()); + } + self.word = Word::Conflicted { + competitors: standing, + }; + if let Some(fault) = fault { + self.reask = Some(Reask::Recheck); + return Err(fault); + } + self.suspect = false; + self.reask = None; + Ok(()) + } + + /// `Tracker.rivalAtOrAbove`: a standing competitor with a proof at or + /// above `height`. + fn rival_at_or_above(&self, height: Height) -> bool { + self.rivals + .iter() + .any(|r| r.standing() && r.checked().is_some_and(|c| height <= c.height())) + } + + /// `Tracker.rivalCheckedAgainst`: a standing competitor whose proof was + /// checked against the header `block_hash`. + fn rival_checked_against(&self, block_hash: &str) -> bool { + self.rivals + .iter() + .any(|r| r.standing() && r.checked().is_some_and(|c| c.header().hash == block_hash)) + } + fn checked_against(&self, block_hash: &str) -> bool { matches!(&self.word, Word::Mined(m) if m.checked().header().hash == block_hash) } + /// `Tracker.onVerdict`: a `Mined` word re-asks its proof. Else + /// `Rejected` writes its word, empties the list of instances and leaves + /// the record and the prior word; `Conflicted` writes its competitors at + /// the front, puts them on the record with no proof (no root rechecks + /// them) and keeps the prior word as a competitor's proof does. fn on_verdict(&mut self, verdict: NodeVerdict) { if matches!(self.word, Word::Mined(_)) { self.reask = Some(Reask::Recheck); return; } - self.word = match verdict { + match verdict { // `Tracker.verdictHanded`: `rejected` empties the list, // `conflicted` keeps it. NodeVerdict::Rejected { reason } => { self.handed_to.clear(); - Word::Rejected { reason } + self.word = Word::Rejected { reason }; } - NodeVerdict::Conflicted { mut competitors } => { + NodeVerdict::Conflicted { competitors } => { + let named: Vec = + competitors.iter().cloned().map(Competitor::named).collect(); if let Word::Conflicted { competitors: previous, - } = &self.word + } = &mut self.word { - competitors.extend(previous.iter().cloned()); + name_the_unrecorded(previous, &mut self.rivals); + previous.splice(0..0, competitors); + self.rivals.splice(0..0, named); + } else { + let before = + std::mem::replace(&mut self.word, Word::Conflicted { competitors }); + self.rivals = named; + self.prior = Some(before); } - Word::Conflicted { competitors } } - }; + } + } +} + +/// Before a competitor joins a `Conflicted` word: each id of the word's list +/// with no entry on the record goes on it as named, after the entries it +/// holds, so the word's list and the record's standing ids are one set +/// after the join. Only a restored version 1 row, whose record is empty, +/// lists such an id: its competitors then stand as named ones and never +/// leave by a chain event or a recheck. A row nothing joins is not touched. +/// 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) { + for id in listed { + if !rivals.iter().any(|r| &r.txid == id) { + rivals.push(Competitor::named(id.clone())); + } + } +} + +/// `Tracker.leaveWord`: the word a conflict leaves to, the word held before +/// it with the hint tier no higher than `Announced` (a `Seen` held before +/// returns as `Announced`). Never `Mined` and never `Conflicted`: a prior +/// word that names one, or none, reads `Unknown`. +pub(crate) fn leave_word(prior: Option<&Word>) -> Word { + match prior { + Some(Word::Seen) => Word::Announced, + Some(Word::Mined(_) | Word::Conflicted { .. }) | None => Word::Unknown, + Some(word) => word.clone(), } } @@ -1211,4 +1616,31 @@ mod tests { ); assert_eq!(state, before); } + + /// `Tracker.leaveWord`, every arm: `seen` returns as `announced`; a + /// prior word that is `mined`, `conflicted` or none reads `unknown`; + /// every other word returns as it was. + #[test] + fn leave_word_caps_seen_and_never_returns_a_chain_claim_it_cannot_hold() { + use super::leave_word; + assert_eq!(leave_word(Some(&Word::Seen)), Word::Announced); + assert_eq!(leave_word(None), Word::Unknown); + assert_eq!( + leave_word(Some(&Word::Conflicted { + competitors: vec!["x".into()] + })), + Word::Unknown + ); + for word in [ + Word::Unknown, + Word::Built, + Word::Handed, + Word::Announced, + Word::Stale, + Word::Rejected { reason: "r".into() }, + Word::Abandoned, + ] { + assert_eq!(leave_word(Some(&word)), word); + } + } } diff --git a/src/tracker.rs b/src/tracker.rs index 182ed08..30c1a45 100644 --- a/src/tracker.rs +++ b/src/tracker.rs @@ -1,5 +1,6 @@ use crate::{ - ChainEvent, CheckError, Hash, Headers, Height, Input, Params, Reask, State, TxId, Word, + ChainEvent, CheckError, CheckedProof, Hash, Headers, Height, Input, Params, Reask, State, TxId, + Word, }; use std::collections::{BTreeMap, BTreeSet}; @@ -17,7 +18,8 @@ pub struct ChainUpdate { /// A host's tracked transactions, with indexes for targeted chain events. /// Hints, ages and spend attempts name one transaction. A tip uses only the /// suspect set; reorgs, forks and splits use only the relevant mined height -/// range. +/// range, and under [`Params::recheck_conflicted`] the range of the +/// `conflicted` words' standing competitors too. #[derive(Clone, Debug)] pub struct Tracker { params: Params, @@ -25,6 +27,12 @@ pub struct Tracker { mined: BTreeMap>, headers: BTreeMap>, suspect: BTreeSet, + /// The `conflicted` words by the heights of their standing competitors + /// that carry a proof. + rival_heights: BTreeMap>, + /// The `conflicted` words by the headers their standing competitors' + /// proofs were checked against. + rival_headers: BTreeMap>, } #[derive(Debug, PartialEq, Eq)] @@ -32,9 +40,18 @@ struct Index { height: Option, header: Option, suspect: bool, + rival_heights: BTreeSet, + rival_headers: BTreeSet, } impl Index { fn of(state: &State) -> Self { + let standing = || { + state + .rivals() + .iter() + .filter(|r| matches!(state.word(), Word::Conflicted { .. }) && r.standing()) + .filter_map(|r| r.checked()) + }; Self { height: state.word().height(), header: match state.word() { @@ -42,6 +59,8 @@ impl Index { _ => None, }, suspect: state.suspect(), + rival_heights: standing().map(CheckedProof::height).collect(), + rival_headers: standing().map(|c| c.header().hash.clone()).collect(), } } } @@ -56,6 +75,8 @@ impl Tracker { mined: BTreeMap::new(), headers: BTreeMap::new(), suspect: BTreeSet::new(), + rival_heights: BTreeMap::new(), + rival_headers: BTreeMap::new(), } } /// Begin tracking one transaction; repeating this does not erase its state. @@ -212,6 +233,24 @@ impl Tracker { remove_index(&mut self.headers, &hash, &txid); } self.suspect.remove(&txid); + for h in &old.rival_heights { + remove_index(&mut self.rival_heights, h, &txid); + } + for hash in &old.rival_headers { + remove_index(&mut self.rival_headers, hash, &txid); + } + for &h in &new.rival_heights { + self.rival_heights + .entry(h) + .or_default() + .insert(txid.clone()); + } + for hash in new.rival_headers { + self.rival_headers + .entry(hash) + .or_default() + .insert(txid.clone()); + } if let Some(h) = new.height { self.mined.entry(h).or_default().insert(txid.clone()); } @@ -233,6 +272,15 @@ impl Tracker { /// against `headers` by its stored root. Only a word whose root moved /// comes back with [`Reask::Reorg`]; a host fetches proofs for those /// alone, a few a pass, the pacing being the host's. + /// + /// Under [`Params::recheck_conflicted`] the selection also names, after + /// the `mined` words and with no txid twice, the `conflicted` words with + /// a standing competitor at or above a reorg's, a fork's or a split's + /// height, and those whose standing competitor was checked against an + /// invalidated block (`Tracker.conflictReask`): the recheck is bounded by + /// those words, never by the chain. Each runs the door + /// ([`State::step`], "The two machines"). With the mode off the selection + /// and every output are the latch's. // By reference would break the public API; a later minor (bsv-stack-lean #134). #[allow(clippy::needless_pass_by_value)] pub fn on_chain( @@ -240,7 +288,7 @@ impl Tracker { headers: &H, event: ChainEvent, ) -> Vec { - let targets: Vec = match &event { + let mut targets: Vec = match &event { ChainEvent::Fork { height, .. } => self.at_or_above(*height), ChainEvent::Reorg { fork_height, .. } | ChainEvent::Split { fork_height, .. } @@ -253,11 +301,44 @@ impl Tracker { ChainEvent::Tip { .. } => self.suspect.iter().cloned().collect(), ChainEvent::Frozen { .. } | ChainEvent::TipAge { .. } => vec![], }; + if self.params.recheck_conflicted { + let conflicted: BTreeSet = match &event { + ChainEvent::Fork { height, .. } + | ChainEvent::Reorg { + fork_height: height, + .. + } + | ChainEvent::Split { + fork_height: height, + .. + } + | ChainEvent::SplitResolved { + fork_height: height, + .. + } => self + .rival_heights + .range(*height..) + .flat_map(|(_, ids)| ids.iter().cloned()) + .collect(), + ChainEvent::Invalidated { block_hash } => self + .rival_headers + .get(block_hash) + .cloned() + .unwrap_or_default(), + _ => BTreeSet::new(), + }; + for txid in conflicted { + if !targets.contains(&txid) { + targets.push(txid); + } + } + } targets .into_iter() .map(|txid| { - let result = - self.apply_transition(&txid, |_, state| state.on_chain(headers, &event)); + let result = self.apply_transition(&txid, |params, state| { + state.chain_step(params, headers, &event) + }); let reask = self.states[&txid].reask().cloned(); ChainUpdate { txid, diff --git a/tests/compact.rs b/tests/compact.rs index 5088db4..1a10109 100644 --- a/tests/compact.rs +++ b/tests/compact.rs @@ -102,7 +102,10 @@ fn input(h: &mut TestHeaders, subject: &Subject, code: u8, height: u32, n: u64) /// writes: the birth (`Subject`: a txid alone, or bytes of 63, 64, 65 or 191, /// born measured or from the txid), the subject's own proofs by either /// constructor at a length that agrees or not, and the measure act at random -/// places (GHSA-jjhc-7hvh-c3hm, BRC-237). +/// 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. fn states() -> impl Strategy)> { ( any::(), @@ -126,6 +129,19 @@ fn build(kind: u8, trace: Vec<(u8, u32, u64, u8)>) -> State { if hint % 7 == 1 { let _ = subject.measure(&mut s); } + if hint % 11 == 4 { + let newest = s + .rivals() + .iter() + .find(|r| r.standing()) + .and_then(Competitor::checked) + .map(CheckedProof::height); + if let Some(at) = newest { + h.move_root(at, n); + let door = params().with_recheck_conflicted(true); + let _ = s.step(&door, &h, Input::Evidence(Evidence::Chain(reorg(at)))); + } + } } s } @@ -135,6 +151,7 @@ fn compact_round_trip_over_256_random_states() { let mined = Cell::new(0); let (measured_mined, at_64, unmeasured) = (Cell::new(0), Cell::new(0), Cell::new(0)); let (handed, conflicted_held) = (Cell::new(0), Cell::new(0)); + let (recorded, marked, returned) = (Cell::new(0), Cell::new(0), Cell::new(0)); runner() .run(&states(), |(kind, trace)| { let s = build(kind, trace); @@ -162,6 +179,18 @@ fn compact_round_trip_over_256_random_states() { _ => {} } prop_assert_eq!(restored.handed_to(), s.handed_to()); + // The record of a conflict and the prior word (for #47). + if s.rivals().iter().any(|r| r.checked().is_some()) { + recorded.set(recorded.get() + 1); + } + if s.rivals().iter().any(Competitor::gone) { + marked.set(marked.get() + 1); + } + if matches!(s.reask(), Some(Reask::CompetitorGone { .. })) { + returned.set(returned.get() + 1); + } + prop_assert_eq!(restored.rivals(), s.rivals()); + prop_assert_eq!(restored.prior(), s.prior()); if let Word::Mined(m) = s.word() { mined.set(mined.get() + 1); // The word and its record come back; the recheck falls due. @@ -194,11 +223,134 @@ fn compact_round_trip_over_256_random_states() { ("unmeasured", unmeasured.get()), ("handed", handed.get()), ("conflicted keeping its instances", conflicted_held.get()), + ("a record with a checked competitor", recorded.get()), + ("a competitor marked gone", marked.get()), + ("a returned word", returned.get()), ] { assert!(n > 0, "{what}: none"); } } +/// A version 1 `conflicted` row on `hash(9)` for the subject's txid, as a +/// published release wrote it: the version, the txid (34 bytes, from the +/// subject's own bytes), word tag 7 with its one id, then version 1's five +/// empty fields. It restores with an empty record and no prior word. +fn version_1_conflicted_of(subject: &Subject) -> State { + let born = subject.state().to_compact(); + let mut v1 = vec![1]; + v1.extend_from_slice(&born[1..34]); + v1.extend_from_slice(&[7, 1, 0]); + v1.extend((0..32).map(|i| u8::from_str_radix(&hash(9)[2 * i..2 * i + 2], 16).unwrap())); + v1.extend_from_slice(&[0; 5]); + let s = State::from_compact(&v1).unwrap(); + assert_eq!(s.txid(), subject.txid); + assert!(s.rivals().is_empty()); + s +} + +/// The ids of a `conflicted` word's list and the ids standing on its record +/// are one set, unless the record is empty (a restored version 1 row that +/// nothing has joined, whose word is still the row's own). +fn word_and_record_agree( + s: &State, + restored_untouched: Option<&Word>, +) -> Result<(), TestCaseError> { + if let Word::Conflicted { competitors } = s.word() { + if s.rivals().is_empty() { + prop_assert_eq!(Some(s.word()), restored_untouched); + } else { + let listed: std::collections::BTreeSet<&str> = + competitors.iter().map(String::as_str).collect(); + let standing: std::collections::BTreeSet<&str> = s + .rivals() + .iter() + .filter(|r| r.standing()) + .map(Competitor::txid) + .collect(); + prop_assert_eq!(listed, standing); + } + } + Ok(()) +} + +/// For #47: over the round trip's generator, every other case born as a +/// restored version 1 `conflicted` row, each step under the door or the latch +/// (the hint byte picks), and the door's reorg at random places as `build` +/// feeds it: after every step the word and the record name the same +/// competitors, unless the record is empty. A restored row that a competitor +/// or a verdict joins puts the row's own competitors on the record as named. +#[test] +fn a_conflicted_word_and_its_record_name_the_same_competitors() { + let (restored_rows, joined, returned_from_a_row) = (Cell::new(0), Cell::new(0), Cell::new(0)); + runner() + .run(&states(), |(kind, trace)| { + let subject = Subject::of(kind); + let from_row = kind % 2 == 1; + let mut s = if from_row { + restored_rows.set(restored_rows.get() + 1); + version_1_conflicted_of(&subject) + } else { + subject.state() + }; + let mut untouched = from_row.then(|| s.word().clone()); + // Whether the row's own conflict has ended by another door (the + // subject's proof): a later conflict has its own record and may return. + let mut left = false; + let mut h = TestHeaders::default(); + word_and_record_agree(&s, untouched.as_ref())?; + for (code, height, n, hint) in trace { + 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); + let _ = s.step(&machine, &h, i); + if empty_before && !s.rivals().is_empty() { + joined.set(joined.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 + .rivals() + .iter() + .find(|r| r.standing()) + .and_then(Competitor::checked) + .map(CheckedProof::height); + if let Some(at) = newest { + h.move_root(at, n); + let door = params().with_recheck_conflicted(true); + let _ = s.step(&door, &h, Input::Evidence(Evidence::Chain(reorg(at)))); + if from_row && matches!(s.reask(), Some(Reask::CompetitorGone { .. })) { + // The row's own competitors never leave. + prop_assert!(left); + returned_from_a_row.set(returned_from_a_row.get() + 1); + } + word_and_record_agree(&s, untouched.as_ref())?; + } + } + } + Ok(()) + }) + .unwrap(); + println!( + "restored rows {}, joins on a restored row {}, returns from a restored row {}", + restored_rows.get(), + joined.get(), + returned_from_a_row.get() + ); + assert!(restored_rows.get() > 0, "restored rows: none"); + assert!(joined.get() > 0, "joins on a restored row: none"); +} + #[test] fn every_proper_prefix_is_truncated_and_a_suffix_is_trailing() { // Over the generator: every birth, measured or not, and every length @@ -392,10 +544,12 @@ fn version_2_refusals() { v1[0] = 1; v1.extend_from_slice(&[1, 7]); malformed(&v1, "re-ask tag"); - // Re-ask tag 8 is not read by this release. - let mut eight = bytes.clone(); - eight[40] = 8; - malformed(&eight, "re-ask tag"); + // Nor re-ask tag 8, which version 2 reads (for #47). + let mut v1 = State::new(&txid).to_compact(); + v1.truncate(v1.len() - 5); + v1[0] = 1; + v1.extend_from_slice(&[1, 8, 0]); + malformed(&v1, "re-ask tag"); // A handed word with no instance. let mut none = bytes[..41].to_vec(); @@ -411,13 +565,8 @@ fn version_2_refusals() { beside[34] = tag; malformed(&beside, "instances beside a word that holds none"); } - // The record of competitors and the prior word are empty in this release. - let mut rivals = bytes.clone(); - rivals[48] = 1; - malformed(&rivals, "competitors"); - let mut prior = bytes.clone(); - prior[49] = 1; - malformed(&prior, "prior word"); + // The record of competitors and the prior word hold values since #47: + // their refusals are `the_record_and_the_prior_word_refusals`. // A version 1 row with the three fields is trailing. let mut long = State::new(&txid).to_compact(); long[0] = 1; @@ -542,3 +691,191 @@ fn find(haystack: &[u8], needle: &[u8], from: usize) -> usize { .position(|w| w == needle) .unwrap() } + +/// A conflicted state on X's checked proof (`tx_bytes(2, 191)` at 10), and the +/// offset of X's entry on the record: its id is the second `00` and X's raw +/// bytes (the word's list holds one before it, its proof and path two after). +fn with_a_checked_competitor() -> (State, Vec, usize) { + let x = competitor(2, 10, 3); + let mut h = TestHeaders::default(); + h.insert(&x, 10); + let mut s = State::new(hash(1)); + step(&mut s, &h, Input::Evidence(Evidence::Competitor(x.clone()))); + let bytes = s.to_compact(); + let mut id = vec![0u8]; + id.extend((0..32).map(|i| u8::from_str_radix(&x.txid()[2 * i..2 * i + 2], 16).unwrap())); + let at: Vec = (0..bytes.len() - 33) + .filter(|&i| bytes[i..i + 33] == id[..]) + .collect(); + // The word's list, the record's entry, the record's proof and its + // path's leaf. + assert_eq!(at.len(), 4); + (s, bytes, at[1]) +} + +/// A state with a record round-trips: a checked competitor with its length +/// and its proof, a named one, the marks after a return and the prior word. +/// A restored record is not marked suspect: it comes back exactly. +#[test] +fn a_state_with_a_record_round_trips() { + let (s, bytes, at) = with_a_checked_competitor(); + // The length of 191 (`01 bf 01`), then the checked proof. + assert_eq!(&bytes[at + 33..at + 37], &[1, 0xbf, 1, 1]); + // The mark, the prior word `unknown` and no measured length. + assert_eq!(&bytes[bytes.len() - 4..], &[0, 1, 0, 0]); + let restored = State::from_compact(&bytes).unwrap(); + assert_eq!(restored, s); + assert!(!restored.suspect()); + assert_eq!(restored.rivals()[0].tx_len(), Some(191)); + assert!(restored.rivals()[0].checked().is_some()); + + // After a return: the mark, the re-ask, a named competitor beside. + let x = competitor(2, 10, 3); + let mut h = TestHeaders::default(); + h.insert(&x, 10); + let door = params().with_recheck_conflicted(true); + let mut r = State::new(hash(1)); + step(&mut r, &h, Input::Host(HostAction::Build)); + r.step( + &door, + &h, + Input::Evidence(Evidence::Verdict(NodeVerdict::Conflicted { + competitors: vec![hash(5)], + })), + ) + .unwrap(); + r.step(&door, &h, Input::Evidence(Evidence::Competitor(x))) + .unwrap(); + assert_eq!(r.prior(), Some(&Word::Built)); + let named = State::from_compact(&r.to_compact()).unwrap(); + assert_eq!(named, r); + // Only the named competitor stands, so the word never returns; a + // version 2 row keeps that across the bytes. + h.move_root(10, 300); + r.step(&door, &h, Input::Evidence(Evidence::Chain(reorg(10)))) + .unwrap(); + assert_eq!( + r.word(), + &Word::Conflicted { + competitors: vec![hash(5)] + } + ); + let marks: Vec = r.rivals().iter().map(Competitor::gone).collect(); + assert_eq!(marks, [true, false]); + assert_eq!(State::from_compact(&r.to_compact()).unwrap(), r); + + let mut gone = State::new(hash(1)); + let x = competitor(2, 10, 3); + let mut hx = TestHeaders::default(); + hx.insert(&x, 10); + gone.step(&door, &hx, Input::Evidence(Evidence::Competitor(x))) + .unwrap(); + hx.move_root(10, 300); + gone.step(&door, &hx, Input::Evidence(Evidence::Chain(reorg(10)))) + .unwrap(); + assert!(matches!(gone.reask(), Some(Reask::CompetitorGone { .. }))); + let bytes = gone.to_compact(); + assert_eq!(State::from_compact(&bytes).unwrap(), gone); + assert_eq!(State::from_compact(&bytes).unwrap().to_compact(), bytes); +} + +/// The record's and the prior word's refusals (for #47): each byte string +/// the encoder never writes. +#[test] +fn the_record_and_the_prior_word_refusals() { + let refused = |b: &[u8], why: CompactError, what: &str| { + assert_eq!(State::from_compact(b), Err(why), "{what}"); + }; + let malformed = CompactError::Malformed; + let (s, bytes, at) = with_a_checked_competitor(); + + // A competitor that is the tracked transaction. + let mut own = bytes.clone(); + own[at + 1..at + 33].copy_from_slice(&bytes[2..34]); + refused( + &own, + CompactError::Evidence(CheckError::TxidMismatch), + "the tracked txid as a competitor", + ); + // A competitor's proof that is another transaction's. + let mut other = bytes.clone(); + other[at + 32] ^= 1; + refused( + &other, + CompactError::Evidence(CheckError::TxidMismatch), + "a proof of another txid", + ); + // A checked proof with no length. + let mut no_len = bytes.clone(); + no_len.splice(at + 33..at + 36, [0]); + refused( + &no_len, + malformed("competitor's proof with no length"), + "no length", + ); + // A length of 64. + let mut at_64 = bytes.clone(); + at_64.splice(at + 33..at + 36, [1, 64]); + refused( + &at_64, + CompactError::Evidence(CheckError::AmbiguousLength), + "a length of 64", + ); + // A record that does not hold together: its root changed. + let gone_at = bytes.len() - 4; + let mut root = bytes.clone(); + root[gone_at - 2] ^= 1; + assert!( + matches!(State::from_compact(&root), Err(CompactError::Evidence(_))), + "a root that does not hold" + ); + // A competitor marked gone keeps its mark: a checked one restores. + let mut marked = bytes.clone(); + marked[gone_at] = 1; + let restored = State::from_compact(&marked).unwrap(); + assert!(restored.rivals()[0].gone()); + assert_eq!(restored.word(), s.word()); + + // A named competitor (a node's verdict): `id 00 00 00`. + let mut v = State::new(hash(1)); + step( + &mut v, + &TestHeaders::default(), + Input::Evidence(Evidence::Verdict(NodeVerdict::Conflicted { + competitors: vec![hash(9)], + })), + ); + let named = v.to_compact(); + let tail = named.len() - 6; + assert_eq!(&named[tail..], &[0, 0, 0, 1, 0, 0]); + let mut with_len = named.clone(); + with_len.splice(tail..tail + 1, [1, 5]); + refused( + &with_len, + malformed("named competitor with a length"), + "a named competitor with a length", + ); + let mut gone = named.clone(); + gone[tail + 2] = 1; + refused( + &gone, + malformed("named competitor marked gone"), + "a named competitor marked gone", + ); + + // The prior word: never `mined` (tag 4) and never `conflicted` (tag 7). + let prior = named.len() - 3; + for word in [vec![4u8], vec![7, 0]] { + let mut b = named.clone(); + b.splice(prior..prior + 2, [1].into_iter().chain(word)); + refused(&b, malformed("prior word"), "a prior word"); + } + let mut flag = named.clone(); + flag[prior] = 2; + refused(&flag, malformed("flag"), "a prior word's flag"); + + // A count of competitors past the bytes left. + let mut count = named.clone(); + count[tail - 34] = 9; + refused(&count, CompactError::Truncated, "a count past the bytes"); +} diff --git a/tests/compact_golden.rs b/tests/compact_golden.rs index 3c76499..2ac039c 100644 --- a/tests/compact_golden.rs +++ b/tests/compact_golden.rs @@ -355,6 +355,13 @@ fn conflicted_by_ids_and_text_state() -> State { s } +/// A node's `conflicted` verdict puts its competitors on the record with no +/// proof and keeps the word the conflict began from (`Tracker.onVerdict`, +/// for #47): after the re-ask, no instance (`00`), a record of two (`02`: +/// the id of `hash(8)`, then "Not-An-Id" as text, each with no length, no +/// proof and no mark, `000000`), the prior word `unknown` (`0100`) and no +/// measured length (`00`). Before #47 the record and the prior word were +/// held empty, and the bytes ended `000000000000000000`. #[test] fn conflicted_by_ids_and_text() { golden( @@ -363,7 +370,8 @@ fn conflicted_by_ids_and_text() { concat!( "02000000000000000000000000000000000000000000000000000000000000000001070200000000", "000000000000000000000000000000000000000000000000000000000801094e6f742d416e2d4964", - "000000000000000000", + "0000000000000200000000000000000000000000000000000000000000000000000000000000000800", + "000001094e6f742d416e2d4964000000010000", ), ); } @@ -632,10 +640,23 @@ fn version_1_bytes_still_restore() { assert_eq!(restored.hints(), built.hints(), "{name}"); assert_eq!(restored.last_hint_at(), built.last_hint_at(), "{name}"); assert_eq!(restored.txid(), built.txid(), "{name}"); + } else if matches!(built.word(), Word::Conflicted { .. }) { + // A version 1 row restores with an empty record and no prior + // word; the state a verdict builds since #47 holds both. + assert_eq!(restored.word(), built.word(), "{name}"); + assert_eq!(restored.evidence(), built.evidence(), "{name}"); + assert_eq!(restored.hints(), built.hints(), "{name}"); + assert_eq!(restored.reask(), built.reask(), "{name}"); + assert_eq!(restored.suspect(), built.suspect(), "{name}"); + assert_eq!(restored.txid(), built.txid(), "{name}"); + assert_eq!(built.rivals().len(), 2, "{name}"); + assert_eq!(built.prior(), Some(&Word::Unknown), "{name}"); } else { assert_eq!(restored, built, "{name}"); } assert!(restored.handed_to().is_empty(), "{name}"); + assert!(restored.rivals().is_empty(), "{name}"); + assert_eq!(restored.prior(), None, "{name}"); } } @@ -643,7 +664,11 @@ fn version_1_bytes_still_restore() { fn version_2_is_version_1_with_four_empty_fields() { for (name, build, v1) in VERSION_1 { let built = build(); - assert_eq!(hex(&built.to_compact()), version_2_of(v1), "{name}"); + // The conflicted state of record holds a record since #47 + // (`conflicted_by_ids_and_text`); its version 1 row holds none. + if !matches!(built.word(), Word::Conflicted { .. }) { + assert_eq!(hex(&built.to_compact()), version_2_of(v1), "{name}"); + } let from_1 = State::from_compact(&unhex(v1)).unwrap(); let from_2 = State::from_compact(&unhex(&version_2_of(v1))).unwrap(); assert_eq!(from_2, from_1, "{name}"); @@ -779,10 +804,10 @@ fn handed_refusals() { &format!("{v1}00000000000107"), malformed("re-ask tag"), ); - // Re-ask tag 8 is not read by this release. + // Nor re-ask tag 8, which version 2 reads since #47. refused( - "re-ask tag 8", - &format!("{o}09000000000108010361726305000000"), + "version 1, re-ask tag 8", + &format!("{v1}0000000000010800"), malformed("re-ask tag"), ); // A handed word with no instance. @@ -808,17 +833,9 @@ fn handed_refusals() { malformed("instances beside a word that holds none"), ); } - // The record of competitors and the prior word are empty in this release. - refused( - "a competitor", - &format!("{o}09000000000107010361726305010000"), - malformed("competitors"), - ); - refused( - "a prior word", - &format!("{o}09000000000107010361726305000100"), - malformed("prior word"), - ); + // The record of competitors and the prior word hold values since #47: + // their refusals are `tests/compact.rs`'s + // `the_record_and_the_prior_word_refusals`. // The length's byte is the last: without it the bytes end inside a field. refused( "no length field", @@ -828,27 +845,177 @@ fn handed_refusals() { } /// One instance written into each of the ten states of record (each of them -/// holds none) is refused beside every word but `conflicted`, which keeps -/// a list for its return, and there it restores. +/// holds none) is refused beside every word, `conflicted` among them, whose +/// version 1 row holds no prior word. Beside `conflicted` whose prior word +/// is `handed` (`0109`) the instance is the list kept for its return, and +/// there it restores (for #47). #[test] fn an_instance_beside_each_word_of_record() { - for (name, build, _) in VERSION_1 { - let s = build(); - let bytes = hex(&s.to_compact()); - // The instances, the competitors, the prior word and the length. - assert!(bytes.ends_with("00000000"), "{name}"); - let (head, tail) = bytes.split_at(bytes.len() - 8); - let with = format!("{head}010361726305{}", &tail[2..]); - if matches!(s.word(), Word::Conflicted { .. }) { - let restored = State::from_compact(&unhex(&with)).unwrap(); + for (name, _, v1) in VERSION_1 { + // The instance after the re-ask, then no competitor, no prior word + // and no length. + let with = format!("02{}010361726305000000", &v1[2..]); + refused( + name, + &with, + CompactError::Malformed("instances beside a word that holds none"), + ); + if v1[66..].starts_with("07") { + let handed = format!("02{}01036172630500010900", &v1[2..]); + let restored = State::from_compact(&unhex(&handed)).unwrap(); assert_eq!(restored.handed_to(), &[HandedTo::new("arc", 5)], "{name}"); - assert_eq!(hex(&restored.to_compact()), with, "{name}"); - } else { - refused( - name, - &with, - CompactError::Malformed("instances beside a word that holds none"), - ); + assert_eq!(restored.prior(), Some(&Word::Handed), "{name}"); + assert_eq!(hex(&restored.to_compact()), handed, "{name}"); + } + } +} + +// --------------------------------------------------------------------------- +// A version 1 `conflicted` row under the door (for #47): the row the +// published 0.9.0-beta.10 writes holds the word's list and no record. +// --------------------------------------------------------------------------- + +/// The version 1 row of `conflicted` of record, as a published release wrote +/// it: the word on `hash(8)` and "Not-An-Id", no record, no prior word. +fn version_1_conflicted() -> (State, Vec) { + let (_, _, v1) = VERSION_1 + .iter() + .find(|(name, _, _)| *name == "conflicted") + .unwrap(); + let restored = State::from_compact(&unhex(v1)).unwrap(); + assert!(restored.rivals().is_empty()); + assert_eq!(restored.prior(), None); + let listed = vec![hash(8), "Not-An-Id".to_owned()]; + assert_eq!( + restored.word(), + &Word::Conflicted { + competitors: listed.clone() + } + ); + (restored, listed) +} + +/// Z, a checked competitor at 9; headers that carry its root (`hz`) and the +/// same height with its root moved (`gone`). +fn z_and_its_headers() -> (Proof, TestHeaders, TestHeaders) { + let z = competitor(3, 9, 3); + let mut hz = TestHeaders::default(); + hz.insert(&z, 9); + let mut gone = hz.clone(); + gone.move_root(9, 300); + gone.tip = 10; + (z, hz, gone) +} + +/// The reader's row. A restored version 1 `conflicted` row, the door on, a +/// checked competitor Z joins and a reorg then removes Z's root. The word's +/// competitors from the published row are put on the record as named when Z +/// joins, so they stand: the word stays `conflicted` on them (Z, gone, leaves +/// the word's list and stays on the record marked), and no +/// `Reask::CompetitorGone` is scheduled. Before the cure the record held Z +/// alone and the word returned to `unknown` with `CompetitorGone`. +#[test] +fn a_version_1_conflicted_row_keeps_its_competitors_under_the_door() { + let (mut s, listed) = version_1_conflicted(); + let (z, hz, gone) = z_and_its_headers(); + let door = params().with_recheck_conflicted(true); + s.step(&door, &hz, Input::Evidence(Evidence::Competitor(z.clone()))) + .unwrap(); + let mut joined = vec![z.txid().to_owned()]; + joined.extend(listed.iter().cloned()); + assert_eq!( + s.word(), + &Word::Conflicted { + competitors: joined.clone() + } + ); + let ids: Vec<&str> = s.rivals().iter().map(Competitor::txid).collect(); + assert_eq!(ids, joined); + let proofs: Vec = s.rivals().iter().map(|r| r.checked().is_some()).collect(); + assert_eq!(proofs, [true, false, false]); + assert_eq!(s.prior(), None); + assert_eq!(s.step(&door, &gone, chain_reorg(9)), Ok(())); + assert_eq!( + s.word(), + &Word::Conflicted { + competitors: listed.clone() + } + ); + let marks: Vec = s.rivals().iter().map(Competitor::gone).collect(); + assert_eq!(marks, [true, false, false]); + assert_eq!(s.reask(), None); + assert!(!s.suspect()); + // Nothing the door reads moves it again: the published row's + // competitors are named, and a named competitor has no root to lose. + let held = s.clone(); + for input in [ + chain_reorg(0), + Input::Evidence(Evidence::Recheck), + Input::Evidence(Evidence::Chain(tip(11, 11))), + ] { + s.step(&door, &gone, input).unwrap(); + } + assert_eq!(s.word(), held.word()); + assert!(!matches!(s.reask(), Some(Reask::CompetitorGone { .. }))); + // The record restores whole from the bytes it writes. + assert_eq!(State::from_compact(&s.to_compact()).unwrap(), s); +} + +/// The same row with the door off: the latch leaves the joined word whole +/// under the reorg, as before the cure. +#[test] +fn a_version_1_conflicted_row_is_latched_with_the_door_off() { + let (mut s, listed) = version_1_conflicted(); + let (z, hz, gone) = z_and_its_headers(); + s.step( + ¶ms(), + &hz, + Input::Evidence(Evidence::Competitor(z.clone())), + ) + .unwrap(); + let mut joined = vec![z.txid().to_owned()]; + joined.extend(listed); + assert_eq!( + s.word(), + &Word::Conflicted { + competitors: joined } + ); + let before = s.clone(); + assert_eq!(s.step(¶ms(), &gone, chain_reorg(9)), Ok(())); + assert_eq!(s, before); +} + +/// A version 1 `conflicted` row that no competitor joins is never touched: +/// the door on, a reorg, a recheck and a tip leave it as it was restored, its +/// record empty, and it writes back the bytes the base wrote for it (the +/// version 1 row with the opening byte `02` and four empty fields after the +/// re-ask). +#[test] +fn a_version_1_conflicted_row_nothing_joins_never_leaves_and_writes_back_whole() { + let (restored, _) = version_1_conflicted(); + let written = concat!( + "02000000000000000000000000000000000000000000000000000000000000000001070200000000", + "000000000000000000000000000000000000000000000000000000000801094e6f742d416e2d4964", + "000000000000000000", + ); + assert_eq!(hex(&restored.to_compact()), written); + let (_, _, gone) = z_and_its_headers(); + let door = params().with_recheck_conflicted(true); + let mut s = restored.clone(); + for input in [ + chain_reorg(0), + chain_reorg(9), + Input::Evidence(Evidence::Recheck), + Input::Evidence(Evidence::Chain(tip(11, 11))), + ] { + assert_eq!(s.step(&door, &gone, input), Ok(())); } + assert_eq!(s, restored); + assert!(s.rivals().is_empty()); + assert_eq!(hex(&s.to_compact()), written); +} + +fn chain_reorg(height: u32) -> Input { + Input::Evidence(Evidence::Chain(reorg(height))) } diff --git a/tests/handed_properties.rs b/tests/handed_properties.rs index 9491b54..a495cdb 100644 --- a/tests/handed_properties.rs +++ b/tests/handed_properties.rs @@ -736,23 +736,30 @@ fn onEvidence_word() { /// The crate's own statement, not a theorem of the Lean (the converse of /// `HandedNamed` the decoder refuses, the plan's K3): along every run, a /// state holds a list of instances only beside `handed`, or beside -/// `conflicted`, which keeps the list for its return. Over the machine -/// without the recheck. +/// `conflicted` whose conflict began from `handed` (its prior word, for +/// #47), which keeps the list for its return; and such a `conflicted` word +/// holds one. Over the machine without the recheck. #[test] fn handed_to_only_beside_handed() { let kept = Cell::new(0); each_state(|e| { + let from_handed = matches!(e.after.word(), Word::Conflicted { .. }) + && e.after.prior() == Some(&Word::Handed); if !e.after.handed_to().is_empty() { prop_assert!( - matches!(e.after.word(), Word::Handed | Word::Conflicted { .. }), - "{:?} holds {:?}", + matches!(e.after.word(), Word::Handed) || from_handed, + "{:?} (prior {:?}) holds {:?}", e.after.word(), + e.after.prior(), e.after.handed_to() ); - if matches!(e.after.word(), Word::Conflicted { .. }) { + if from_handed { kept.set(kept.get() + 1); } } + if from_handed { + prop_assert!(!e.after.handed_to().is_empty()); + } Ok(()) }); reached("conflicted keeping a list", &kept); diff --git a/tests/labels.rs b/tests/labels.rs index f7381f7..e89bcb7 100644 --- a/tests/labels.rs +++ b/tests/labels.rs @@ -85,6 +85,12 @@ fn reasks() -> Vec<(Reask, &'static str)> { (Reask::Age, "age"), (Reask::Spend, "spend"), (Reask::Reannounce, "reannounce"), + ( + Reask::CompetitorGone { + competitors: vec!["bb".repeat(32)], + }, + "competitor_gone", + ), ] } @@ -124,7 +130,8 @@ fn the_lists_are_the_words_in_declaration_order() { "recheck", "age", "spend", - "reannounce" + "reannounce", + "competitor_gone" ] ); let mut words: Vec<&str> = statuses().iter().map(|(_, w, _)| *w).collect(); diff --git a/tests/length_properties.rs b/tests/length_properties.rs index 136064d..282d1a2 100644 --- a/tests/length_properties.rs +++ b/tests/length_properties.rs @@ -90,10 +90,14 @@ fn record(txid: &str, len: u64, height: u32, sibling: u64) -> Proof { } /// The version 1 bytes of a state version 1 can hold (no instance, no -/// measure): version 2's with the opening byte `01` and its last four -/// fields, each empty, cut. +/// record of a conflict, no prior word, no measure): version 2's with the +/// opening byte `01` and its last four fields, each empty, cut. fn version_1(s: &State) -> Option> { - if !s.handed_to().is_empty() || s.tx_len().is_some() { + if !s.handed_to().is_empty() + || !s.rivals().is_empty() + || s.prior().is_some() + || s.tx_len().is_some() + { return None; } let mut b = s.to_compact(); diff --git a/tests/reorg_by_root.rs b/tests/reorg_by_root.rs index d20dc1b..634e5bc 100644 --- a/tests/reorg_by_root.rs +++ b/tests/reorg_by_root.rs @@ -195,3 +195,213 @@ fn a_mempool_presence_over_built_and_over_announced_reads_announced() { // The same word either way. assert_eq!(built.word(), announced.word()); } + +/// The latch's outputs over a registry that holds a `mined` word at 100, a +/// `conflicted` word whose competitor's proof is at 104, and a `conflicted` +/// word a node named: every chain event the feed carries, with the blocks at +/// 100 and 104 replaced before the reorg. The updates of each event and the states +/// after the last. +fn latch_outputs(params: Params) -> (Vec>, Vec) { + let mut h = TestHeaders::default(); + let mut tracker = Tracker::new(params); + let own = proof(&hash(100), 100, 7); + h.insert(&own, 100); + tracker + .apply(&hash(100), &h, Input::Evidence(Evidence::Proof(own))) + .unwrap(); + let rival = competitor(2, 104, 7); + h.insert(&rival, 104); + tracker + .apply(&hash(1), &h, Input::Host(HostAction::Build)) + .unwrap(); + tracker + .apply(&hash(1), &h, hint(HintStatus::Accepted, 1)) + .unwrap(); + tracker + .apply(&hash(1), &h, Input::Evidence(Evidence::Competitor(rival))) + .unwrap(); + tracker + .apply( + &hash(3), + &h, + Input::Evidence(Evidence::Verdict(NodeVerdict::Conflicted { + competitors: vec![hash(4)], + })), + ) + .unwrap(); + let block = h.headers[&104].hash.clone(); + let mut updates = vec![ + tracker.on_chain(&h, fork(100)), + tracker.on_chain(&h, split(100)), + tracker.on_chain(&h, split_resolved(100)), + tracker.on_chain(&h, tip(104, 104)), + tracker.on_chain(&h, ChainEvent::Invalidated { block_hash: block }), + ]; + h.move_root(100, 300); + h.move_root(104, 304); + updates.push(tracker.on_chain(&h, reorg(99))); + updates.push(tracker.on_chain(&h, tip(105, 105))); + let states = [hash(100), hash(1), hash(3)] + .iter() + .map(|t| tracker.get(t).unwrap().clone()) + .collect(); + (updates, states) +} + +#[test] +fn the_latch_selects_no_conflicted_word_and_moves_none() { + let (updates, states) = latch_outputs(params()); + // An event names the mined word alone, never a conflicted one: the + // resolved split clears the fork's mark, so the tip names nothing, and + // the invalidated block is the competitor's. + let named: Vec> = updates + .iter() + .map(|u| u.iter().map(|c| c.txid.as_str()).collect()) + .collect(); + let mined_word = hash(100); + let m = mined_word.as_str(); + assert_eq!( + named, + [vec![m], vec![m], vec![m], vec![], vec![], vec![m], vec![]] + ); + assert_eq!(states[0].word(), &Word::Stale); + assert_eq!(states[0].reask(), Some(&Reask::Reorg { fork_height: 99 })); + assert_eq!( + states[1].word(), + &Word::Conflicted { + competitors: vec![competitor(2, 104, 7).txid().to_owned()] + } + ); + assert!(!states[1].suspect()); + assert_eq!(states[1].reask(), None); + assert_eq!( + states[2].word(), + &Word::Conflicted { + competitors: vec![hash(4)] + } + ); +} + +#[test] +fn the_latch_outputs_are_the_same_with_the_mode_named_off() { + assert_eq!( + latch_outputs(params().with_recheck_conflicted(false)), + latch_outputs(params()) + ); +} + +/// The same registry under the door (`Tracker.conflictReask`): an event names +/// the conflicted word whose standing competitor's proof is at or above its +/// height, or was checked against its block, after the mined word; a +/// conflicted word a node named is never selected; the reorg that removes the +/// competitor's block returns the word. +#[test] +fn the_door_selects_the_conflicted_words_its_competitors_name() { + let (updates, states) = latch_outputs(params().with_recheck_conflicted(true)); + let named: Vec> = updates + .iter() + .map(|u| u.iter().map(|c| c.txid.as_str()).collect()) + .collect(); + let (mined_word, rival_word) = (hash(100), hash(1)); + let (m, r) = (mined_word.as_str(), rival_word.as_str()); + assert_eq!( + named, + [ + vec![m, r], + vec![m, r], + vec![m, r], + vec![], + vec![r], + vec![m, r], + vec![] + ] + ); + assert!(updates.iter().flatten().all(|u| u.result.is_ok())); + assert_eq!(states[0].word(), &Word::Stale); + assert_eq!(states[1].word(), &Word::Announced); + assert_eq!( + states[1].reask(), + Some(&Reask::CompetitorGone { + competitors: vec![competitor(2, 104, 7).txid().to_owned()] + }) + ); + assert_eq!( + updates[5][1].reask, + states[1].reask().cloned(), + "the update carries the re-ask" + ); + assert_eq!( + states[2].word(), + &Word::Conflicted { + competitors: vec![hash(4)] + } + ); +} + +/// Headers that count their reads. +struct Counted<'a> { + inner: &'a TestHeaders, + reads: std::cell::Cell, +} +impl Headers for Counted<'_> { + 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() + } +} + +/// `Tracker.conflictReads`: a reorg reads one header per standing competitor +/// that carries a proof on each selected word, none for a word the selection +/// does not name, and none for a competitor a node named. +#[test] +fn the_door_reads_one_header_per_standing_competitor_with_a_proof() { + let mut h = TestHeaders::default(); + let (x, z, low) = ( + competitor(2, 104, 7), + competitor(3, 105, 7), + competitor(5, 90, 7), + ); + for p in [&x, &z, &low] { + h.insert(p, u64::from(p.height())); + } + let mut tracker = Tracker::new(params().with_recheck_conflicted(true)); + for p in [&x, &z] { + tracker + .apply( + &hash(1), + &h, + Input::Evidence(Evidence::Competitor(p.clone())), + ) + .unwrap(); + } + tracker + .apply( + &hash(1), + &h, + Input::Evidence(Evidence::Verdict(NodeVerdict::Conflicted { + competitors: vec![hash(4)], + })), + ) + .unwrap(); + // A conflicted word whose one competitor is below the fork height. + tracker + .apply(&hash(6), &h, Input::Evidence(Evidence::Competitor(low))) + .unwrap(); + let counted = Counted { + inner: &h, + reads: std::cell::Cell::new(0), + }; + let updates = tracker.on_chain(&counted, reorg(100)); + assert_eq!(updates.len(), 1); + assert_eq!(updates[0].txid, hash(1)); + assert_eq!(counted.reads.get(), 2); + assert_eq!( + tracker.get(&hash(1)).unwrap().word(), + &Word::Conflicted { + competitors: vec![hash(4), z.txid().to_owned(), x.txid().to_owned()] + } + ); +} diff --git a/tests/transitions.rs b/tests/transitions.rs index 10924eb..6d0aaa4 100644 --- a/tests/transitions.rs +++ b/tests/transitions.rs @@ -775,3 +775,551 @@ fn handed_to_is_stored_by_its_serde_form() { assert_eq!(text, r#"{"instance":"arcade","at":1700000000}"#); assert_eq!(serde_json::from_str::(&text).unwrap(), held); } + +/// A `conflicted` word under the latch: every chain event and an executed +/// recheck leave the state whole, even when the competitor's block has been +/// replaced (`Tracker.step_conflicted_latched`). +#[test] +fn a_conflicted_word_is_latched_under_every_chain_event_and_a_recheck() { + let mut h = TestHeaders::default(); + let rival = competitor(2, 10, 3); + h.insert(&rival, 10); + let mut s = State::new(hash(1)); + step(&mut s, &h, Input::Host(HostAction::Build)); + step(&mut s, &h, hint(HintStatus::Accepted, 1)); + step( + &mut s, + &h, + Input::Evidence(Evidence::Competitor(rival.clone())), + ); + let before = s.clone(); + let block = h.headers[&10].hash.clone(); + let mut moved = h.clone(); + moved.move_root(10, 300); + for headers in [&h, &moved] { + for input in [ + Input::Evidence(Evidence::Chain(tip(11, 11))), + Input::Evidence(Evidence::Chain(fork(10))), + Input::Evidence(Evidence::Chain(reorg(9))), + Input::Evidence(Evidence::Chain(split(10))), + Input::Evidence(Evidence::Chain(split_resolved(10))), + Input::Evidence(Evidence::Chain(ChainEvent::Invalidated { + block_hash: block.clone(), + })), + Input::Evidence(Evidence::Recheck), + ] { + assert_eq!(s.step(¶ms(), headers, input), Ok(())); + assert_eq!(s, before); + } + } +} + +/// A proof offered as a competitor's whose txid is the tracked one: a +/// competitor is another transaction (`Tracker.competitor_is_another`), so +/// the door refuses it with `TxidMismatch` and `ProofFailed`, the word and +/// the record untouched, for every host and in either mode. +/// +/// It replaces the latch's old answer, which wrote `conflicted` on the +/// tracked transaction from its own proof: +/// +/// ```text +/// step(&mut s, &h, Input::Evidence(Evidence::Competitor(own))); +/// assert_eq!(s.word(), &Word::Conflicted { competitors: vec![s.txid().to_owned()] }); +/// ``` +#[test] +fn a_competitor_proof_for_the_tracked_txid() { + let bytes = tx_bytes(1, 191); + let own = proof_of(&bytes, 10, 3); + let mut h = TestHeaders::default(); + h.insert(&own, 10); + for recheck in [false, true] { + let params = params().with_recheck_conflicted(recheck); + let mut s = State::measured(&bytes); + step(&mut s, &h, Input::Host(HostAction::Build)); + let before = s.clone(); + assert_eq!( + s.step( + ¶ms, + &h, + Input::Evidence(Evidence::Competitor(own.clone())) + ), + Err(CheckError::TxidMismatch) + ); + assert_eq!(s.word(), &Word::Built); + assert!(s.rivals().is_empty()); + assert_eq!(s.prior(), None); + assert_eq!(s.reask(), Some(&Reask::ProofFailed { height: 10 })); + assert_eq!(s.evidence(), before.evidence()); + // The proof door is the one that takes it. + assert_eq!( + s.step(¶ms, &h, Input::Evidence(Evidence::Proof(own.clone()))), + Ok(()) + ); + mined(&s, 10); + } +} + +/// The record of a conflict (`Tracker.onCompetitor`, `Tracker.onVerdict`): +/// a checked competitor goes on it at the front with its proof and its own +/// length, a node's named competitor with neither; the prior word is the +/// word of the moment the conflict began and is kept while it lasts; a +/// `mined` word only re-asks; a `rejected` verdict leaves record and prior. +#[test] +fn the_record_and_the_prior_word() { + let mut h = TestHeaders::default(); + let x = competitor(2, 10, 3); + let z = competitor(3, 11, 3); + h.insert(&x, 10); + h.insert(&z, 11); + let mut s = State::new(hash(1)); + step(&mut s, &h, Input::Host(HostAction::Build)); + step(&mut s, &h, hint(HintStatus::Seen, 1)); + step(&mut s, &h, Input::Evidence(Evidence::Competitor(x.clone()))); + assert_eq!(s.prior(), Some(&Word::Seen)); + assert_eq!(s.rivals().len(), 1); + assert_eq!(s.rivals()[0].txid(), x.txid()); + assert_eq!(s.rivals()[0].tx_len(), Some(191)); + assert_eq!(s.rivals()[0].checked().unwrap().height(), 10); + assert!(s.rivals()[0].standing() && !s.rivals()[0].gone()); + step( + &mut s, + &h, + Input::Evidence(Evidence::Verdict(NodeVerdict::Conflicted { + competitors: vec![hash(4)], + })), + ); + step(&mut s, &h, Input::Evidence(Evidence::Competitor(z.clone()))); + assert_eq!( + s.word(), + &Word::Conflicted { + competitors: vec![z.txid().into(), hash(4), x.txid().into()] + } + ); + let named: Vec<(&str, Option, bool)> = s + .rivals() + .iter() + .map(|r| (r.txid(), r.tx_len(), r.checked().is_some())) + .collect(); + assert_eq!( + named, + [ + (z.txid(), Some(191), true), + (hash(4).as_str(), None, false), + (x.txid(), Some(191), true), + ] + ); + // The prior word is the one the conflict began from. + assert_eq!(s.prior(), Some(&Word::Seen)); + let record = s.rivals().to_vec(); + step( + &mut s, + &h, + Input::Evidence(Evidence::Verdict(NodeVerdict::Rejected { + reason: "no".into(), + })), + ); + assert_eq!(s.rivals(), record.as_slice()); + assert_eq!(s.prior(), Some(&Word::Seen)); + // A conflict that begins again starts its own record from the word of + // its moment. + step(&mut s, &h, Input::Evidence(Evidence::Competitor(x.clone()))); + assert_eq!( + s.prior(), + Some(&Word::Rejected { + reason: "no".into() + }) + ); + assert_eq!(s.rivals().len(), 1); + // A mined word re-asks and keeps its record as it was. + let own = proof(&hash(1), 12, 3); + h.insert(&own, 12); + step(&mut s, &h, Input::Evidence(Evidence::Proof(own))); + let kept = s.rivals().to_vec(); + step(&mut s, &h, Input::Evidence(Evidence::Competitor(z))); + mined(&s, 12); + assert_eq!(s.reask(), Some(&Reask::Recheck)); + assert_eq!(s.rivals(), kept.as_slice()); +} + +/// K4's scope (the crate's issue 57): a measure of 64 bytes is a fault road +/// for the tracked transaction's own proof alone. A competitor's proof on +/// the record is the competitor's and is judged by its own length: the +/// tracked transaction's measure never unsays it, and the competitor's door +/// never reads that measure. +#[test] +fn a_competitors_length_and_the_tracked_measure_are_kept_apart() { + let ours = tx_bytes(1, 64); + let x = competitor(2, 10, 3); + let mut h = TestHeaders::default(); + h.insert(&x, 10); + // Unmeasured, conflicted on X's proof, then measured at 64: no fault, + // the word and the record kept. + let mut s = State::new(txid_of(&ours)); + step(&mut s, &h, Input::Evidence(Evidence::Competitor(x.clone()))); + let before = s.clone(); + assert_eq!(s.measure(&ours), Ok(())); + assert_eq!(s.tx_len(), Some(64)); + assert_eq!(s.word(), before.word()); + assert_eq!(s.rivals(), before.rivals()); + assert_eq!(s.rivals()[0].tx_len(), Some(191)); + // Measured at 64 from birth: the competitor's door takes X's proof. + let mut m = State::measured(&ours); + step(&mut m, &h, Input::Evidence(Evidence::Competitor(x.clone()))); + assert_eq!( + m.word(), + &Word::Conflicted { + competitors: vec![x.txid().to_owned()] + } + ); + assert_eq!(m.rivals()[0].tx_len(), Some(191)); + assert_eq!(m.tx_len(), Some(64)); +} + +// --------------------------------------------------------------------------- +// The door: the recheck of `conflicted` (for #47), the Lean's `stepRecheck` +// --------------------------------------------------------------------------- + +/// The machine with the door. +fn door() -> Params { + params().with_recheck_conflicted(true) +} + +/// Headers that carry X's root at 10 (`hX`), the same height with another +/// root (`hY`), and none at all (`h0`); X's proof. +fn door_headers() -> (TestHeaders, TestHeaders, TestHeaders, Proof) { + let x = competitor(2, 10, 3); + let mut hx = TestHeaders::default(); + hx.insert(&x, 10); + let mut hy = hx.clone(); + hy.move_root(10, 300); + hy.tip = 11; + (hx, hy, TestHeaders::default(), x) +} + +/// `taken`, then X's checked proof: `conflictedT`. +fn conflicted_t(hx: &TestHeaders, x: &Proof) -> State { + let mut s = State::new(hash(1)); + step(&mut s, hx, Input::Host(HostAction::Build)); + step(&mut s, hx, hint(HintStatus::Accepted, 2)); + s.step( + &door(), + hx, + Input::Evidence(Evidence::Competitor(x.clone())), + ) + .unwrap(); + s +} + +fn chain(e: ChainEvent) -> Input { + Input::Evidence(Evidence::Chain(e)) +} + +#[test] +fn the_door_returns_a_conflict_whose_competitor_lost_its_root() { + let (hx, hy, _, x) = door_headers(); + let t = conflicted_t(&hx, &x); + assert_eq!(t.prior(), Some(&Word::Announced)); + // `returned`: the reorg at the competitor's height, the root gone. + let mut returned = t.clone(); + assert_eq!(returned.step(&door(), &hy, chain(reorg(10))), Ok(())); + assert_eq!(returned.word(), &Word::Announced); + assert_eq!( + returned.reask(), + Some(&Reask::CompetitorGone { + competitors: vec![x.txid().to_owned()] + }) + ); + assert!(!returned.suspect()); + let marks: Vec = returned.rivals().iter().map(Competitor::gone).collect(); + assert_eq!(marks, [true]); + assert_eq!(returned.prior(), Some(&Word::Announced)); + // The latch leaves the same state as it was on the same row. + let mut latched = t.clone(); + assert_eq!(latched.step(¶ms(), &hy, chain(reorg(10))), Ok(())); + assert_eq!(latched, t); + // After the return the transaction's own proof writes `mined`. + let own = proof(&hash(1), 11, 3); + let mut ht = hy.clone(); + ht.insert(&own, 11); + let mut mined_after = returned.clone(); + mined_after + .step(&door(), &ht, Input::Evidence(Evidence::Proof(own.clone()))) + .unwrap(); + mined(&mined_after, 11); + // So it does from `conflicted`, with no recheck at all. + let mut direct = t.clone(); + direct + .step(&door(), &ht, Input::Evidence(Evidence::Proof(own))) + .unwrap(); + mined(&direct, 11); + // A competitor proven again after the return starts a fresh record. + let mut again = returned.clone(); + again + .step( + &door(), + &hx, + Input::Evidence(Evidence::Competitor(x.clone())), + ) + .unwrap(); + assert_eq!( + again.word(), + &Word::Conflicted { + competitors: vec![x.txid().to_owned()] + } + ); + assert_eq!(again.prior(), Some(&Word::Announced)); + let marks: Vec = again.rivals().iter().map(Competitor::gone).collect(); + assert_eq!(marks, [false]); +} + +#[test] +fn the_door_is_bounded_and_keeps_a_root_that_stands() { + let (hx, hy, _, x) = door_headers(); + let t = conflicted_t(&hx, &x); + // A reorg above the competitor's height reads nothing. + let mut above = t.clone(); + assert_eq!(above.step(&door(), &hy, chain(reorg(11))), Ok(())); + assert_eq!(above, t); + // A reorg whose new branch still carries the root: the word stands and + // the marks clear. + let mut stands = t.clone(); + assert_eq!(stands.step(&door(), &hx, chain(reorg(10))), Ok(())); + assert_eq!(stands.word(), t.word()); + assert!(!stands.suspect()); + assert_eq!(stands.reask(), None); + // A tip on an unmarked word reads nothing. + let mut tipped = t.clone(); + assert_eq!(tipped.step(&door(), &hy, chain(tip(11, 11))), Ok(())); + assert_eq!(tipped, t); +} + +#[test] +fn the_door_fails_closed_without_a_header() { + let (hx, hy, h0, x) = door_headers(); + let t = conflicted_t(&hx, &x); + // `behind`: no header at the competitor's height. + let mut behind = t.clone(); + assert_eq!( + behind.step(&door(), &h0, chain(reorg(10))), + Err(CheckError::Unavailable(10)) + ); + assert_eq!(behind.word(), t.word()); + assert!(behind.suspect()); + assert_eq!(behind.reask(), Some(&Reask::Recheck)); + // The next tip with the header back reads it, and the word leaves. + assert_eq!(behind.step(&door(), &hy, chain(tip(11, 11))), Ok(())); + assert_eq!(behind.word(), &Word::Announced); + // A headers fault is not gone either. + let mut fault = hy.clone(); + fault.fault = true; + let mut faulted = t.clone(); + assert!(matches!( + faulted.step(&door(), &fault, Input::Evidence(Evidence::Recheck)), + Err(CheckError::Headers(_)) + )); + assert_eq!(faulted.word(), t.word()); + assert_eq!(faulted.reask(), Some(&Reask::Recheck)); + // An executed recheck with the root gone returns the word. + let mut rechecked = t.clone(); + assert_eq!( + rechecked.step(&door(), &hy, Input::Evidence(Evidence::Recheck)), + Ok(()) + ); + assert_eq!(rechecked.word(), &Word::Announced); +} + +/// `leaveWord` over the words a conflict began from (ruling 28.8.3 (1b)): +/// `seen` returns as `announced`; `rejected`, `stale` with its own proof +/// kept, `abandoned`, `built`, and `handed` with its instances, as they were. +#[test] +fn the_door_returns_to_the_word_held_before() { + let (hx, hy, _, x) = door_headers(); + let through = |mut s: State| { + s.step( + &door(), + &hx, + Input::Evidence(Evidence::Competitor(x.clone())), + ) + .unwrap(); + s.step(&door(), &hy, chain(reorg(10))).unwrap(); + s + }; + let mut seen = State::new(hash(1)); + step(&mut seen, &hx, Input::Host(HostAction::Build)); + step(&mut seen, &hx, hint(HintStatus::Seen, 2)); + assert_eq!(through(seen).word(), &Word::Announced); + + let mut rejected = State::new(hash(1)); + step( + &mut rejected, + &hx, + Input::Evidence(Evidence::Verdict(NodeVerdict::Rejected { + reason: "bad".into(), + })), + ); + assert_eq!( + through(rejected).word(), + &Word::Rejected { + reason: "bad".into() + } + ); + + let mut handed = State::new(hash(1)); + step( + &mut handed, + &hx, + Input::Host(HostAction::HandOver { + instance: "arc".into(), + at: 1, + }), + ); + let back = through(handed); + assert_eq!(back.word(), &Word::Handed); + assert_eq!(back.handed_to(), &[HandedTo::new("arc", 1)]); + + let mut built = State::new(hash(1)); + step(&mut built, &hx, Input::Host(HostAction::Build)); + assert_eq!(through(built.clone()).word(), &Word::Built); + step(&mut built, &hx, Input::Host(HostAction::Abandon)); + assert_eq!(through(built).word(), &Word::Abandoned); + + // `stale`: our own old proof at 8, its root moved; the record kept. + let own = proof(&hash(1), 8, 3); + let mut ha = TestHeaders::default(); + ha.insert(&own, 8); + let mut stale = State::new(hash(1)); + step(&mut stale, &ha, Input::Evidence(Evidence::Proof(own))); + ha.move_root(8, 400); + step(&mut stale, &ha, chain(reorg(8))); + assert_eq!(stale.word(), &Word::Stale); + let evidence = stale.evidence().cloned(); + let back = through(stale); + assert_eq!(back.word(), &Word::Stale); + assert_eq!(back.evidence(), evidence.as_ref()); +} + +#[test] +fn the_door_keeps_a_standing_competitor_and_never_returns_a_named_one() { + let (hx, _, _, x) = door_headers(); + // Two competitors, X at 10 and Z at 9; the block at 10 alone removed. + let z = competitor(3, 9, 3); + let mut hxz = hx.clone(); + hxz.insert(&z, 9); + let mut hyz = hxz.clone(); + hyz.move_root(10, 300); + let mut s = conflicted_t(&hxz, &x); + s.step( + &door(), + &hxz, + Input::Evidence(Evidence::Competitor(z.clone())), + ) + .unwrap(); + assert_eq!(s.step(&door(), &hyz, chain(reorg(9))), Ok(())); + assert_eq!( + s.word(), + &Word::Conflicted { + competitors: vec![z.txid().to_owned()] + } + ); + let marks: Vec = s.rivals().iter().map(Competitor::gone).collect(); + assert_eq!(marks, [false, true]); + + // A competitor a node named never leaves by the recheck. + let mut named = State::new(hash(1)); + step(&mut named, &hx, Input::Host(HostAction::Build)); + step( + &mut named, + &hx, + Input::Evidence(Evidence::Verdict(NodeVerdict::Conflicted { + competitors: vec![hash(5)], + })), + ); + let mut hy = hx.clone(); + hy.move_root(10, 300); + for input in [ + chain(reorg(0)), + Input::Evidence(Evidence::Recheck), + chain(tip(11, 11)), + ] { + named.step(&door(), &hy, input).unwrap(); + } + assert_eq!( + named.word(), + &Word::Conflicted { + competitors: vec![hash(5)] + } + ); + // An empty record (a version 1 row) never leaves either. + let v1 = { + // The conflicted word of X with no record: the version, the txid + // (34 bytes), word tag 7 and its one id (34 bytes), then version 1's + // five empty fields. + let mut c = State::new(hash(1)); + c.step( + &door(), + &hx, + Input::Evidence(Evidence::Competitor(x.clone())), + ) + .unwrap(); + let mut b = c.to_compact(); + assert_eq!((b[34], b[35]), (7, 1)); + b.truncate(34 + 2 + 33 + 5); + b[0] = 1; + State::from_compact(&b).unwrap() + }; + assert!(v1.rivals().is_empty()); + let mut empty = v1.clone(); + empty + .step(&door(), &hy, Input::Evidence(Evidence::Recheck)) + .unwrap(); + assert_eq!(empty, v1); +} + +#[test] +fn the_door_reads_a_fork_then_a_tip_an_invalidation_and_splits() { + let (hx, hy, _, x) = door_headers(); + let t = conflicted_t(&hx, &x); + // `forkThenTip`: a fork at or below the competitor marks; the next tip + // reads the header, and here the word leaves. + let mut forked = t.clone(); + forked.step(&door(), &hx, chain(fork(10))).unwrap(); + assert!(forked.suspect()); + assert_eq!(forked.reask(), Some(&Reask::Fork { height: 10 })); + forked.step(&door(), &hy, chain(tip(11, 11))).unwrap(); + assert_eq!(forked.word(), &Word::Announced); + // An invalidation of the competitor's header reads too. + let block = hx.headers[&10].hash.clone(); + let mut invalidated = t.clone(); + invalidated + .step( + &door(), + &hy, + chain(ChainEvent::Invalidated { block_hash: block }), + ) + .unwrap(); + assert_eq!(invalidated.word(), &Word::Announced); + // The crate's split is a fork, its resolution a tip of a marked word. + let mut split_word = t.clone(); + split_word.step(&door(), &hx, chain(split(10))).unwrap(); + assert!(split_word.suspect()); + assert_eq!(split_word.reask(), Some(&Reask::Fork { height: 10 })); + split_word + .step(&door(), &hy, chain(split_resolved(10))) + .unwrap(); + assert_eq!(split_word.word(), &Word::Announced); + // No word on a broadcaster's word, and the host acts of `handed` move + // no conflicted word. + let mut hinted = t.clone(); + for input in [ + hint(HintStatus::Mined { height: 11 }, 9), + hint(HintStatus::Accepted, 9), + hint(HintStatus::Seen, 9), + Input::Host(HostAction::EndHold), + Input::Host(HostAction::Discharge { + instance: "arc".into(), + }), + ] { + hinted.step(&door(), &hy, input).unwrap(); + assert_eq!(hinted.word(), t.word()); + } +}