Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 57 additions & 4 deletions packages/rs-core-proof/src/bootstrap.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! The bootstrap envelope: a proof chain plus Merkle openings of records under
//! the target's roots, as `getquorumproofchain` returns in `bootstrap_hex`.
use crate::chain::{QuorumProofChain, MAX_PROOF_BYTES};
use crate::chain::{Progress, QuorumProofChain, MAX_PROOF_BYTES};
use crate::merkle::MerklePath;
use crate::state::State;
use crate::wire::{sha256d, Reader, Result};
Expand Down Expand Up @@ -60,16 +60,69 @@ pub fn verify<'a>(
trusted: &State,
minimum_height: u32,
) -> Result<VerifiedBootstrap<'a>> {
start(bytes, trusted, minimum_height)?.finish()
}

/// Begin verifying an envelope as [`verify`] does, so the caller can verify
/// its chain's links one at a time with [`Verification::verify_link`] and do
/// other work between them. Each link costs a BLS verification and the X11
/// hashes of its ancestor headers.
///
/// Decodes the envelope and makes every check that comes before the first
/// link; [`Verification::finish`] makes the rest. Verifying links one at a
/// time accepts and rejects exactly what [`verify`] does.
pub fn start<'a>(
bytes: &'a [u8],
trusted: &State,
minimum_height: u32,
) -> Result<Verification<'a>> {
if bytes.len() > MAX_PROOF_BYTES {
return Err(Error("bootstrap size limit"));
}
let mut r = Reader::new(bytes);
let chain = QuorumProofChain::decode(r.blob(MAX_PROOF_BYTES)?)?;
let mut records = Reader::new(bytes);
let chain = QuorumProofChain::decode(records.blob(MAX_PROOF_BYTES)?)?;
// Decided before any signature work: the height alone makes it useless.
if chain.target.height < minimum_height {
return Err(Error::STALE_TARGET);
}
let state = chain.verify(trusted)?;
let progress = chain.start(trusted)?;
Ok(Verification {
chain,
progress,
records,
})
}

/// An envelope part-way through verification. Only [`start`] constructs it.
pub struct Verification<'a> {
chain: QuorumProofChain,
progress: Progress,
/// The envelope after the chain: its records.
records: Reader<'a>,
}

impl<'a> Verification<'a> {
/// How many of the chain's links are still to verify.
pub fn links_left(&self) -> usize {
self.progress.links_left(&self.chain)
}

/// Verify the next link of the chain. An error means the envelope is
/// invalid, except when no link is left, which is an error too.
pub fn verify_link(&mut self) -> Result<()> {
self.chain.verify_link(&mut self.progress)
}

/// Verify any links left, then the target and the records, and return
/// the verified envelope.
pub fn finish(self) -> Result<VerifiedBootstrap<'a>> {
let state = self.chain.finish(self.progress)?;
open_records(self.records, state)
}
}

/// Open the records after the chain under the verified target `state`.
fn open_records(mut r: Reader<'_>, state: State) -> Result<VerifiedBootstrap<'_>> {
let count = r.u8()?;
if !(1..=MAX_RECORDS).contains(&count) {
return Err(Error("projection count"));
Expand Down
93 changes: 72 additions & 21 deletions packages/rs-core-proof/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
//! coinbase commits to new masternode and quorum roots.
use crate::bls;
use crate::merkle::MerklePath;
use crate::state::State;
use crate::state::{ProofNetwork, State};
use crate::transaction::{
coinbase_roots, mined_commitment, parse_commitment, Commitment, MAX_COMMITMENT_BYTES,
MAX_TRANSACTION_BYTES,
Expand Down Expand Up @@ -156,6 +156,32 @@ impl Link {
}
}

/// How far [`QuorumProofChain::verify`] has got: the links verified so far
/// and the ChainLock quorum the last of them mined.
#[derive(Debug)]
pub(crate) struct Progress {
network: ProofNetwork,
signer: Commitment,
height: u32,
next_link: usize,
}

impl Progress {
/// How many links are still to verify.
pub(crate) fn links_left(&self, chain: &QuorumProofChain) -> usize {
chain.links.len().saturating_sub(self.next_link)
}
}

/// `commitment`, if it is of the network's ChainLock quorum type.
fn ensure_chainlock(commitment: Commitment, network: ProofNetwork) -> Result<Commitment> {
if commitment.quorum_type == network.chainlock_quorum_type() {
Ok(commitment)
} else {
Err(Error("unexpected quorum type"))
}
}

/// A `DASHNC02` proof chain, as `getquorumproofchain` returns in `proof_hex`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QuorumProofChain {
Expand All @@ -179,6 +205,12 @@ impl QuorumProofChain {
/// The chain must start from exactly `trusted`; a relay cannot choose the
/// checkpoint.
pub fn verify(&self, trusted: &State) -> Result<State> {
self.finish(self.start(trusted)?)
}

/// The checks before any link: the anchor, the chain's size limits and
/// the seed's opening under the checkpoint's quorum root.
pub(crate) fn start(&self, trusted: &State) -> Result<Progress> {
if &self.anchor != trusted {
return Err(Error::UNTRUSTED_CHECKPOINT);
}
Expand All @@ -190,28 +222,47 @@ impl QuorumProofChain {
if headers > MAX_PROOF_HEADERS {
return Err(Error("ancestor budget/height"));
}
let chainlock_type = trusted.network.chainlock_quorum_type();
let ensure_chainlock = |commitment: Commitment| {
if commitment.quorum_type == chainlock_type {
Ok(commitment)
} else {
Err(Error("unexpected quorum type"))
}
};

let mut signer = ensure_chainlock(parse_commitment(&self.seed)?)?;
let signer = ensure_chainlock(parse_commitment(&self.seed)?, trusted.network)?;
self.seed_path
.verify(sha256d(&self.seed), &trusted.quorum_root)?;
let mut height = trusted.height;
for link in &self.links {
link.certificate.verify(&signer, height)?;
let next = ensure_chainlock(link.mined_commitment()?)?;
if next.quorum_hash == signer.quorum_hash {
return Err(Error("redundant signer"));
}
signer = next;
height = link.certificate.height;
Ok(Progress {
network: trusted.network,
signer,
height: trusted.height,
next_link: 0,
})
}

/// Verify the next link: its certificate by the current signer, and the
/// ChainLock quorum it mines, which signs from then on.
pub(crate) fn verify_link(&self, progress: &mut Progress) -> Result<()> {
let link = self
.links
.get(progress.next_link)
.ok_or(Error("no link left"))?;
link.certificate.verify(&progress.signer, progress.height)?;
let next = ensure_chainlock(link.mined_commitment()?, progress.network)?;
if next.quorum_hash == progress.signer.quorum_hash {
return Err(Error("redundant signer"));
}
progress.signer = next;
progress.height = link.certificate.height;
progress.next_link += 1;
Ok(())
}

/// Verify the links left, then the target and its coinbase, and return
/// the target block's state.
pub(crate) fn finish(&self, mut progress: Progress) -> Result<State> {
while progress.links_left(self) > 0 {
self.verify_link(&mut progress)?;
}
let Progress {
network,
signer,
height,
..
} = progress;
let block_hash = self.target.verify(&signer, height)?;
if self.coinbase.path.index != 0 {
return Err(Error("coinbase inclusion"));
Expand All @@ -220,7 +271,7 @@ impl QuorumProofChain {
let (masternode_root, quorum_root) =
coinbase_roots(&self.coinbase.transaction, self.target.height)?;
Ok(State {
network: trusted.network,
network,
height: self.target.height,
block_hash,
masternode_root,
Expand Down
36 changes: 36 additions & 0 deletions packages/rs-core-proof/tests/synthetic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -554,3 +554,39 @@ fn should_reject_commitments_core_rejects() {
);
}
}

/// A relay may send a valid chain through every ChainLock quorum since the
/// checkpoint. A caller verifying it link by link sees each link verify in
/// turn, and a bad link fails exactly when its turn comes.
#[test]
fn should_verify_a_long_chain_one_link_at_a_time() {
let quorums: Vec<Quorum> = (2..42).map(|seed| Quorum::new(seed, CHAINLOCK)).collect();
let next: Vec<&Quorum> = quorums.iter().collect();
let seed = Quorum::new(1, CHAINLOCK);
let built = build(&seed, &next, 4);
let bytes = envelope(&built.chain, 1, &[(0, &built.record)]);

let mut verification = bootstrap::start(&bytes, &built.checkpoint, 0).unwrap();
assert_eq!(verification.links_left(), 40);
for left in (0..40).rev() {
verification.verify_link().unwrap();
assert_eq!(verification.links_left(), left);
}
let verified = verification.finish().unwrap();
assert_eq!(verified.state().height, built.chain.target.height);

// Link 20 is signed by the wrong quorum.
let mut tampered = built.chain.clone();
tampered.links[20] = link(
&seed,
&quorums[20].commitment(),
tampered.links[20].certificate.height,
);
let bytes = envelope(&tampered, 1, &[(0, &built.record)]);
let mut verification = bootstrap::start(&bytes, &built.checkpoint, 0).unwrap();
for _ in 0..20 {
verification.verify_link().unwrap();
}
assert!(verification.verify_link().is_err());
assert!(bootstrap::verify(&bytes, &built.checkpoint, 0).is_err());
}
66 changes: 66 additions & 0 deletions packages/rs-core-proof/tests/verification.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,3 +214,69 @@ fn should_verify_a_proof_signed_by_the_checkpoint_quorum_itself() {
let verified = bootstrap::verify(&f.bootstrap, &f.checkpoint, f.target.height).unwrap();
assert_eq!(verified.state(), &f.target);
}

/// Verify one link at a time, as an async caller does between yields.
fn verify_stepwise<'a>(
bytes: &'a [u8],
trusted: &State,
minimum_height: u32,
) -> dash_core_proof::Result<bootstrap::VerifiedBootstrap<'a>> {
let mut verification = bootstrap::start(bytes, trusted, minimum_height)?;
while verification.links_left() > 0 {
let left = verification.links_left();
verification.verify_link()?;
assert_eq!(verification.links_left(), left - 1);
}
verification.finish()
}

#[test]
fn should_verify_link_by_link_exactly_as_in_one_call() {
for (f, links) in [(mainnet(), 2), (testnet(), 4)] {
let started = bootstrap::start(&f.bootstrap, &f.checkpoint, 0).unwrap();
assert_eq!(started.links_left(), links);
let whole = bootstrap::verify(&f.bootstrap, &f.checkpoint, 0).unwrap();
let stepwise = verify_stepwise(&f.bootstrap, &f.checkpoint, 0).unwrap();
assert_eq!(stepwise.state(), whole.state());
assert_eq!(stepwise.records(), whole.records());
// `finish` verifies whatever links are left.
let finished = bootstrap::start(&f.bootstrap, &f.checkpoint, 0)
.unwrap()
.finish()
.unwrap();
assert_eq!(finished.state(), whole.state());
}
}

#[test]
fn should_reject_link_by_link_whatever_one_call_rejects() {
let f = testnet();
let stale = verify_stepwise(&f.bootstrap, &f.checkpoint, f.target.height + 1).unwrap_err();
assert_eq!(
stale.kind(),
bootstrap::verify(&f.bootstrap, &f.checkpoint, f.target.height + 1)
.unwrap_err()
.kind()
);
for i in (0..f.bootstrap.len()).step_by(61) {
let mut corrupt = f.bootstrap.clone();
corrupt[i] ^= 0x01;
assert_eq!(
format!(
"{:?}",
verify_stepwise(&corrupt, &f.checkpoint, 0).map(|v| v.state().clone())
),
format!(
"{:?}",
bootstrap::verify(&corrupt, &f.checkpoint, 0).map(|v| v.state().clone())
),
"flip at {i}"
);
}
for n in (0..f.bootstrap.len()).step_by(97) {
assert!(
verify_stepwise(&f.bootstrap[..n], &f.checkpoint, 0).is_err(),
"cut at {n}"
);
}
}
5 changes: 4 additions & 1 deletion packages/rs-sdk-trusted-context-provider/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ web-sys = { version = "0.3.85", features = [
"AbortController",
"AbortSignal",
"Headers",
"MessageChannel",
"MessagePort",
"ReadableStream",
"Request",
"RequestCache",
Expand All @@ -86,7 +88,8 @@ web-sys = { version = "0.3.85", features = [
] }

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# Waits out the gap between two refreshes of the quorum lists.
# Waits out the gap between two refreshes of the quorum lists, and pauses
# between slices of a long proof's verification.
tokio = { version = "1.40", features = ["time"] }

[target.'cfg(not(target_os = "android"))'.dependencies]
Expand Down
Loading
Loading