diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 7b0a8316..6d545a3d 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -23,6 +23,7 @@ c_rust_merkle, decode_natural, decode_program, parse_human, +prune_generated, regression_286, regression_value, ] diff --git a/CHANGELOG.md b/CHANGELOG.md index 197b6fb2..2504f809 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # Unreleased +* Fix pruning keeping witness bits that only a hidden branch reads, which made the pruned program fail to decode with trailing witness bytes. Pruning now types only the nodes reachable through executed branches. +* Fix pruning hiding different branches of case nodes which become the same node once pruned, which made the encoded program reach a pruned branch. + # 0.9.0 - 2026-09-16 * Update `elements` to `0.27.0`, `bitcoin_hashes` to `1.2.0`, and `hex-conservative` to `1.2.0` [#368](https://github.com/BlockstreamResearch/rust-simplicity/pull/368), [#373](https://github.com/BlockstreamResearch/rust-simplicity/pull/373), [#376](https://github.com/BlockstreamResearch/rust-simplicity/pull/376). diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 7adbe83f..90f62542 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -67,6 +67,13 @@ test = false doc = false bench = false +[[bin]] +name = "prune_generated" +path = "fuzz_targets/prune_generated.rs" +test = false +doc = false +bench = false + [[bin]] name = "regression_286" path = "fuzz_targets/regression_286.rs" diff --git a/fuzz/fuzz_lib/generator.rs b/fuzz/fuzz_lib/generator.rs new file mode 100644 index 00000000..49972591 --- /dev/null +++ b/fuzz/fuzz_lib/generator.rs @@ -0,0 +1,364 @@ +// SPDX-License-Identifier: CC0-1.0 + +//! Type-directed program generator +//! +//! [`generate_program`] chooses a type first and then only combinators which can +//! have that type, so every program it produces is well-typed. It never generates +//! `fail`, assertions, `disconnect` or jets which can fail, so every program also +//! runs to completion. Case nodes branch on witness data, constants and jet +//! outputs, and nodes are sometimes reused, so that pruning has branches to hide +//! and nodes shared between hidden and kept code. + +use std::sync::Arc; + +use libfuzzer_sys::arbitrary::{Result, Unstructured}; +use simplicity::dag::{DagLike as _, InternalSharing}; +use simplicity::jet::{Elements, Jet as _}; +use simplicity::node::{CoreConstructible as _, Inner, SimpleFinalizer, WitnessConstructible as _}; +use simplicity::types::{self, Final}; +use simplicity::{ConstructNode, RedeemNode, Value}; + +/// Maximum number of combinators that the generator chooses, which bounds the +/// size of the program to a small multiple of this. +const MAX_BUDGET: usize = 200; + +/// Maximum bit width of a type for which a constant is scribed into the program. +const MAX_SCRIBE_WIDTH: usize = 16; + +/// Jets which cannot fail and do not read the transaction environment. +/// +/// These are Elements jets, rather than Core jets, because libsimplicity decodes +/// programs with the Elements jet codes. +const JETS: &[Elements] = &[ + Elements::Add8, + Elements::Add16, + Elements::Add32, + Elements::All8, + Elements::And8, + Elements::Ch8, + Elements::Complement8, + Elements::Complement32, + Elements::Eq1, + Elements::Eq8, + Elements::Eq16, + Elements::Eq32, + Elements::FullAdd8, + Elements::High8, + Elements::Increment8, + Elements::IsOne8, + Elements::IsZero8, + Elements::Le8, + Elements::LeftShift8, + Elements::Low8, + Elements::Lt8, + Elements::Lt32, + Elements::Maj8, + Elements::Max8, + Elements::Min8, + Elements::Multiply8, + Elements::Negate8, + Elements::One8, + Elements::Or8, + Elements::RightShift8, + Elements::Some8, + Elements::Subtract8, + Elements::Subtract32, + Elements::Xor8, + Elements::Xor32, +]; + +type Node<'brand> = Arc>; + +/// Generates a program of type 1 → 1, together with its witness data. +/// +/// Once `u` runs out of data the generator only makes cheap choices, so this +/// returns a program for any input. +pub fn generate_program(u: &mut Unstructured) -> Result> { + types::Context::with_context(|ctx| { + let mut gen = Generator { + budget: u.int_in_range(1..=MAX_BUDGET)?, + u, + ctx: &ctx, + pool: vec![], + }; + let unit = Final::unit(); + let program = gen + .node(&unit, &unit)? + .finalize_types() + .expect("generated programs are well-typed"); + + // The witness types are only known once the types are finalized. The + // finalizer below visits witness nodes in the same order as this loop. + let mut witness_values = vec![]; + for data in program.as_ref().post_order_iter::() { + if let Inner::Witness(_) = data.node.inner() { + witness_values.push(value(gen.u, &data.node.arrow().target)?); + } + } + Ok(program + .convert::(&mut SimpleFinalizer::new(witness_values.into_iter())) + .expect("generated programs have no disconnect nodes")) + }) +} + +struct Generator<'a, 'u, 'brand> { + u: &'a mut Unstructured<'u>, + ctx: &'a types::Context<'brand>, + /// Number of combinators left to choose before only leaves are generated. + budget: usize, + /// Every node generated so far, with the type it was generated for. + pool: Vec<(Arc, Arc, Node<'brand>)>, +} + +impl<'brand> Generator<'_, '_, 'brand> { + /// Generates a node of type `a` → `b`. + /// + /// Type inference may finalize the node to a smaller type, where nothing in + /// the program constrains part of `a` or `b`. + fn node(&mut self, a: &Arc, b: &Arc) -> Result> { + if self.budget == 0 { + return self.leaf(a, b); + } + self.budget -= 1; + + // `choose_index` returns 0 once the data runs out, so 0 must terminate. + let node = match self.u.choose_index(6)? { + 0 => self.leaf(a, b)?, + 1 => self.reuse(a, b)?, + 2 => self.shape(a, b)?, + 3 => { + let mid = self.ty(2)?; + let left = self.node(a, &mid)?; + let right = self.node(&mid, b)?; + typed(Node::comp(&left, &right)) + } + 4 => self.branch(a, b)?, + _ => self.jet(a, b)?, + }; + self.pool + .push((Arc::clone(a), Arc::clone(b), Arc::clone(&node))); + Ok(node) + } + + /// Generates a node of type `a` → `b` which has no children to generate. + fn leaf(&mut self, a: &Arc, b: &Arc) -> Result> { + if b.is_unit() { + Ok(Node::unit(self.ctx)) + } else if a == b && self.u.arbitrary()? { + Ok(Node::iden(self.ctx)) + } else if b.bit_width() <= MAX_SCRIBE_WIDTH && self.u.arbitrary()? { + // Constant words have source type 1, so discard the input first. + let constant = Node::scribe(self.ctx, &value(self.u, b)?); + Ok(typed(Node::comp(&Node::unit(self.ctx), &constant))) + } else { + Ok(Node::witness(self.ctx, None)) + } + } + + /// Returns a node of type `a` → `b` which was generated before, so that it is + /// shared, or a leaf if there is none. + fn reuse(&mut self, a: &Arc, b: &Arc) -> Result> { + let matches: Vec<_> = self + .pool + .iter() + .filter(|(pa, pb, _)| pa == a && pb == b) + .map(|(_, _, node)| Arc::clone(node)) + .collect(); + if matches.is_empty() { + self.leaf(a, b) + } else { + Ok(Arc::clone(&matches[self.u.choose_index(matches.len())?])) + } + } + + /// Generates a node whose combinator follows the shape of `a` or `b`. + fn shape(&mut self, a: &Arc, b: &Arc) -> Result> { + enum Shape { + InjL, + InjR, + Pair, + Take, + Drop, + Case, + } + + let mut shapes = vec![]; + if b.as_sum().is_some() { + shapes.extend([Shape::InjL, Shape::InjR]); + } + if b.as_product().is_some() { + shapes.push(Shape::Pair); + } + if let Some((a0, _)) = a.as_product() { + shapes.extend([Shape::Take, Shape::Drop]); + if a0.as_sum().is_some() { + shapes.push(Shape::Case); + } + } + if shapes.is_empty() { + return self.leaf(a, b); + } + + let sum = |ty: &Arc| ty.as_sum().map(|(l, r)| (Arc::clone(l), Arc::clone(r))); + let product = + |ty: &Arc| ty.as_product().map(|(l, r)| (Arc::clone(l), Arc::clone(r))); + Ok(match shapes[self.u.choose_index(shapes.len())?] { + Shape::InjL => Node::injl(&self.node(a, &sum(b).unwrap().0)?), + Shape::InjR => Node::injr(&self.node(a, &sum(b).unwrap().1)?), + Shape::Pair => { + let (b0, b1) = product(b).unwrap(); + typed(Node::pair(&self.node(a, &b0)?, &self.node(a, &b1)?)) + } + Shape::Take => Node::take(&self.node(&product(a).unwrap().0, b)?), + Shape::Drop => Node::drop_(&self.node(&product(a).unwrap().1, b)?), + Shape::Case => { + let (a0, a1) = product(a).unwrap(); + let (l, r) = sum(&a0).unwrap(); + let left = self.node(&Final::product(l, Arc::clone(&a1)), b)?; + let right = self.node(&Final::product(r, a1), b)?; + typed(Node::case(&left, &right)) + } + }) + } + + /// Generates `comp (pair s iden) (case l r)` of type `a` → `b`: compute a sum + /// from the input, then branch on it with the input available to both branches. + fn branch(&mut self, a: &Arc, b: &Arc) -> Result> { + let (l, r) = (self.ty(1)?, self.ty(1)?); + let scrutinee = self.node(a, &Final::sum(Arc::clone(&l), Arc::clone(&r)))?; + let left = self.node(&Final::product(l, Arc::clone(a)), b)?; + let right = self.node(&Final::product(r, Arc::clone(a)), b)?; + let input = typed(Node::pair(&scrutinee, &Node::iden(self.ctx))); + Ok(typed(Node::comp(&input, &typed(Node::case(&left, &right))))) + } + + /// Generates `comp s (comp jet t)` of type `a` → `b`, where `s` produces the + /// input of the jet and `t` consumes its output. + fn jet(&mut self, a: &Arc, b: &Arc) -> Result> { + let jet = JETS[self.u.choose_index(JETS.len())?]; + let source = self.node(a, &jet.source_ty().to_final())?; + let target = self.node(&jet.target_ty().to_final(), b)?; + let jet = Node::jet(self.ctx, &jet); + Ok(typed(Node::comp( + &source, + &typed(Node::comp(&jet, &target)), + ))) + } + + /// Generates a type of at most the given depth. + fn ty(&mut self, depth: usize) -> Result> { + let n_choices = if depth == 0 { 4 } else { 6 }; + Ok(match self.u.choose_index(n_choices)? { + 0 => Final::unit(), + 1 => Final::two_two_n_fixed::<0>(), + 2 => Final::two_two_n_fixed::<3>(), + // A type that some jet consumes or produces. + 3 => { + let jet = JETS[self.u.choose_index(JETS.len())?]; + if self.u.arbitrary()? { + jet.source_ty().to_final() + } else { + jet.target_ty().to_final() + } + } + 4 => Final::sum(self.ty(depth - 1)?, self.ty(depth - 1)?), + _ => Final::product(self.ty(depth - 1)?, self.ty(depth - 1)?), + }) + } +} + +/// Returns `n` deterministic pseudorandom inputs, for unit tests which run a +/// fuzz target on many generated programs without an RNG dependency. +pub fn pseudorandom_inputs(n: usize) -> impl Iterator> { + let mut state = 0x2545_f491_4f6c_dd1d_u64; + let mut next = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + (0..n).map(move |_| { + let len = 16 + (next() % 4096) as usize; + (0..len).map(|_| next() as u8).collect() + }) +} + +/// Generates a value of the given type. +fn value(u: &mut Unstructured, ty: &Final) -> Result { + if let Some((l, r)) = ty.as_sum() { + if u.arbitrary()? { + Ok(Value::right(Arc::clone(l), value(u, r)?)) + } else { + Ok(Value::left(value(u, l)?, Arc::clone(r))) + } + } else if let Some((l, r)) = ty.as_product() { + Ok(Value::product(value(u, l)?, value(u, r)?)) + } else { + Ok(Value::unit()) + } +} + +/// Unwraps the result of constructing a node, which only fails on a type error. +fn typed(result: std::result::Result) -> T { + result.expect("the generator only combines nodes of matching types") +} + +#[cfg(test)] +mod tests { + use super::*; + use simplicity::jet::elements::ElementsEnv; + use simplicity::BitMachine; + + #[test] + fn generator_yield() { + const N: usize = 1000; + let env = ElementsEnv::dummy(); + let (mut ran, mut over_50, mut max_nodes) = (0, 0, 0); + let (mut has_case, mut has_jet, mut has_witness, mut has_hidden) = (0, 0, 0, 0); + for data in pseudorandom_inputs(N) { + let program = generate_program(&mut Unstructured::new(&data)) + .expect("the generator accepts any input"); + let n_nodes = program + .as_ref() + .post_order_iter::() + .count(); + max_nodes = max_nodes.max(n_nodes); + if n_nodes > 50 { + over_50 += 1; + } + let has = |program: &RedeemNode, f: fn(&Inner<_, _, _>) -> bool| { + program + .post_order_iter::() + .any(|data| f(data.node.inner())) + }; + has_case += usize::from(has(&program, |i| matches!(i, Inner::Case(..)))); + has_jet += usize::from(has(&program, |i| matches!(i, Inner::Jet(..)))); + has_witness += usize::from(has(&program, |i| matches!(i, Inner::Witness(..)))); + + let mut mac = match BitMachine::for_program(&program) { + Ok(mac) => mac, + Err(_) => continue, + }; + mac.exec(&program, &env) + .expect("generated programs contain nothing that fails"); + ran += 1; + let pruned = program + .prune(&env) + .expect("pruning succeeds when execution does"); + has_hidden += usize::from(has(&pruned, |i| { + matches!(i, Inner::AssertL(..) | Inner::AssertR(..)) + })); + } + let stats = format!( + "of {N}: ran {ran}, >50 nodes {over_50} (max {max_nodes}), case {has_case}, \ + jet {has_jet}, witness {has_witness}, pruning hid a branch {has_hidden}" + ); + // The inputs are fixed, so these only change when the generator does. + assert_eq!(ran, N, "{stats}"); + assert!(over_50 >= N / 4, "{stats}"); + assert!(has_case >= N / 3, "{stats}"); + assert!(has_jet >= N / 3, "{stats}"); + assert!(has_witness >= N / 3, "{stats}"); + assert!(has_hidden >= N / 3, "{stats}"); + } +} diff --git a/fuzz/fuzz_lib/lib.rs b/fuzz/fuzz_lib/lib.rs index d3772c85..a62f43fa 100644 --- a/fuzz/fuzz_lib/lib.rs +++ b/fuzz/fuzz_lib/lib.rs @@ -7,8 +7,10 @@ use simplicity::types::Final as FinalTy; use simplicity::{BitIter, Value}; use std::sync::Arc; +mod generator; mod program; +pub use generator::{generate_program, pseudorandom_inputs}; pub use program::ProgramControl; /// A wrapper around a buffer which has utilities for extracting various diff --git a/fuzz/fuzz_targets/prune_generated.rs b/fuzz/fuzz_targets/prune_generated.rs new file mode 100644 index 00000000..7380123b --- /dev/null +++ b/fuzz/fuzz_targets/prune_generated.rs @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: CC0-1.0 + +#![cfg_attr(fuzzing, no_main)] + +#[cfg(any(fuzzing, test))] +fn do_test(data: &[u8]) { + use libfuzzer_sys::arbitrary::Unstructured; + use simplicity::ffi::tests::{ffi::SimplicityErr, run_program, TestUpTo}; + use simplicity::hashes::sha256::Midstate; + use simplicity::jet::{elements::ElementsEnv, Elements}; + use simplicity::{BitIter, BitMachine, RedeemNode}; + + let program = match simplicity_fuzz::generate_program(&mut Unstructured::new(data)) { + Ok(program) => program, + Err(_) => return, + }; + let env = ElementsEnv::dummy(); + let mut mac = match BitMachine::for_program(&program) { + Ok(mac) => mac, + Err(_) => return, + }; + mac.exec(&program, &env) + .expect("generated programs contain nothing that fails"); + + let pruned = program + .prune(&env) + .expect("pruning succeeds when execution does"); + assert_eq!(pruned.cmr(), program.cmr(), "pruning should keep the CMR"); + BitMachine::for_program(&pruned) + .expect("the pruned program is no larger") + .exec(&pruned, &env) + .expect("the pruned program should run"); + + // A decoder infers the types of the pruned program from its encoding, so it + // must infer the types that pruning did to read the witness data back. + let (prog, wit) = pruned.to_vec_with_witness(); + let decoded = + RedeemNode::decode::<_, _, Elements>(BitIter::from(&prog[..]), BitIter::from(&wit[..])) + .expect("the pruned program should decode"); + assert_eq!( + decoded.ihr(), + pruned.ihr(), + "the decoder should infer the types that pruning did" + ); + assert_eq!(decoded.to_vec_with_witness(), (prog.clone(), wit.clone())); + + // libsimplicity, the consensus implementation, accepts the pruned program + // and computes the same roots. + let c_pruned = run_program(&prog, &wit, TestUpTo::Everything, None, None) + .expect("libsimplicity should decode the pruned program"); + assert_eq!( + c_pruned.eval_result, + SimplicityErr::NoError, + "libsimplicity should accept the pruned program" + ); + assert_eq!( + &Midstate::from(c_pruned.cmr).to_parts().0, + pruned.cmr().as_ref() + ); + assert_eq!( + &Midstate::from(c_pruned.amr).to_parts().0, + pruned.amr().as_ref() + ); + assert_eq!( + &Midstate::from(c_pruned.ihr).to_parts().0, + pruned.ihr().as_ref() + ); + + // libsimplicity rejects the unpruned program for its unexecuted branches + // exactly when pruning hid a branch, so both agree on what was executed. + let unpruned = program.to_vec_with_witness(); + let c_unpruned = run_program(&unpruned.0, &unpruned.1, TestUpTo::Everything, None, None) + .expect("libsimplicity should decode the unpruned program"); + let expected = if unpruned == (prog, wit) { + SimplicityErr::NoError + } else { + SimplicityErr::AntiDoS + }; + assert_eq!( + c_unpruned.eval_result, expected, + "libsimplicity should reject the unpruned program exactly when pruning changed it" + ); +} + +#[cfg(fuzzing)] +libfuzzer_sys::fuzz_target!(|data| do_test(data)); + +#[cfg(not(fuzzing))] +fn main() {} + +#[cfg(test)] +mod tests { + #[test] + fn pseudorandom_inputs() { + for data in simplicity_fuzz::pseudorandom_inputs(1000) { + super::do_test(&data); + } + } +} diff --git a/fuzz/generate-files.sh b/fuzz/generate-files.sh index a350dc6c..0c205e71 100755 --- a/fuzz/generate-files.sh +++ b/fuzz/generate-files.sh @@ -90,7 +90,7 @@ $(for name in $(listTargetNames); do echo "$name,"; done) - name: Install Toolchain uses: dtolnay/rust-toolchain@master with: - toolchain: nightly-2024-07-01 + toolchain: nightly-2026-02-24 components: "llvm-tools-preview" - name: Install Dependencies diff --git a/src/jet/elements/environment.rs b/src/jet/elements/environment.rs index e022753c..d03bd982 100644 --- a/src/jet/elements/environment.rs +++ b/src/jet/elements/environment.rs @@ -109,7 +109,7 @@ where } } -#[cfg(test)] +#[cfg(any(test, feature = "test-utils"))] impl ElementsEnv { /// Return a dummy Elements environment pub fn dummy() -> Self { diff --git a/src/node/redeem.rs b/src/node/redeem.rs index 89202b5d..c768d1f2 100644 --- a/src/node/redeem.rs +++ b/src/node/redeem.rs @@ -13,7 +13,8 @@ use super::{ Converter, Hide, Inner, Marker, NoDisconnect, NoWitness, Node, }; -use std::collections::HashSet; +use std::collections::hash_map::Entry; +use std::collections::{HashMap, HashSet}; use std::io; use std::marker::PhantomData; use std::sync::Arc; @@ -269,7 +270,10 @@ impl RedeemNode { /// Pruning works as follows: /// 1) Run the redeem program on the Bit Machine. /// 2) Mark all (un)used case branches using the IHR of the case node. - /// 3) Rebuild the program and omit unused branches. + /// 3) Rebuild the program from the nodes reachable through used branches, + /// and omit unused branches. + /// 4) If case nodes with different IHRs became one node in the pruned program, + /// let them share the branches that any of them used, and go back to step 3. /// /// The pruning result depends on the witness data (which is already part of the redeem program) /// and on the transaction environment. These two inputs determine which case branches are @@ -279,7 +283,7 @@ impl RedeemNode { /// /// Pruning fails if the original, unpruned program fails to run on the Bit Machine (step 1). /// In this case, the witness data needs to be revised. - /// The other pruning steps (2 & 3) never fail. + /// The other pruning steps (2 to 4) never fail. pub fn prune(&self, env: &JE) -> Result, ExecutionError> { self.prune_with_tracker(env, &mut SetTracker::default()) } @@ -294,86 +298,104 @@ impl RedeemNode { env: &JE, tracker: &mut T, ) -> Result, ExecutionError> { - struct Pruner<'brand, 't, T> { - inference_context: types::Context<'brand>, - tracker: &'t mut T, + /// Which branches of each case node were used. + /// + /// Case nodes with different IHRs can become one node in the pruned program: + /// pruning makes their types smaller, and the IHR of a case node does not show + /// which branch it hides, if that branch holds no witness. Such case nodes are + /// merged here, and share the branches that any of them used. + struct Usage<'t, T> { + tracker: &'t T, + /// Case nodes which were merged into another, by IHR. + merged_into: HashMap, + /// The used left and right branches of each group of merged case nodes. + branches: HashMap, } - impl<'brand, 't, T> Converter> for Pruner<'brand, 't, T> - where - T: PruneTracker, - { - type Error = std::convert::Infallible; + impl Usage<'_, T> { + fn root(&self, mut ihr: Ihr) -> Ihr { + while let Some(&next) = self.merged_into.get(&ihr) { + ihr = next; + } + ihr + } - fn convert_witness( - &mut self, - _: &PostOrderIterItem<&RedeemNode>, - witness: &Value, - ) -> Result, Self::Error> { - // The pruned type is not finalized at this point, - // so we cannot prune the witness value. - Ok(Some(witness.shallow_clone())) + fn used(&mut self, ihr: Ihr) -> (bool, bool) { + let root = self.root(ihr); + let tracker = self.tracker; + *self + .branches + .entry(root) + .or_insert_with(|| (tracker.contains_left(root), tracker.contains_right(root))) } - fn convert_disconnect( - &mut self, - _: &PostOrderIterItem<&RedeemNode>, - right: Option<&Arc>>, - _: &Arc, - ) -> Result>>, Self::Error> { - debug_assert!( - right.is_some(), - "disconnected branch should exist in unpruned redeem program" - ); - Ok(right.map(Arc::clone)) + fn hide(&mut self, ihr: Ihr) -> Hide { + match self.used(ihr) { + (true, true) => Hide::Neither, + (false, true) => Hide::Left, + (true, false) => Hide::Right, + // Not executed, which happens inside a branch that is kept for a + // merged case node. Keep both branches. + (false, false) => Hide::Neither, + } } - fn prune_case( - &mut self, - data: &PostOrderIterItem<&RedeemNode>, - _left: &Arc, - _right: &Arc, - ) -> Result { - // The IHR of the pruned program may change, - // but the Converter trait gives us access to the unpruned node (`data`). - // The Bit Machine tracked (un)used case branches based on the unpruned IHR. - match ( - self.tracker.contains_left(data.node.ihr()), - self.tracker.contains_right(data.node.ihr()), - ) { - (true, true) => Ok(Hide::Neither), - (false, true) => Ok(Hide::Left), - (true, false) => Ok(Hide::Right), - (false, false) => Ok(Hide::Neither), // case nodes that were never executed will be pruned out by their ancestors + /// Merges the groups of two case nodes, and returns whether this changed + /// the branches that either group uses. + fn merge(&mut self, a: Ihr, b: Ihr) -> bool { + let (used_a, used_b) = (self.used(a), self.used(b)); + let (root_a, root_b) = (self.root(a), self.root(b)); + if root_a == root_b { + return false; } + let used = (used_a.0 || used_b.0, used_a.1 || used_b.1); + self.merged_into.insert(root_a, root_b); + self.branches.insert(root_b, used); + used != used_a || used != used_b } + } - fn convert_data( - &mut self, - _: &PostOrderIterItem<&RedeemNode>, - inner: Inner< - &Arc>, - &Option>>, - &Option, - >, - ) -> Result, Self::Error> { - let converted_inner = inner - .map(|node| node.cached_data()) - .map_witness(Option::::clone); - let retyped = ConstructData::from_inner(&self.inference_context, converted_inner) - .expect("pruned types should check out if unpruned types check out"); - Ok(retyped) + /// Walks the program from the root, descending only into used branches, + /// and returns the IHRs of the nodes to keep together with which branches + /// to hide for each of them. + fn kept_nodes( + root: &RedeemNode, + usage: &mut Usage, + ) -> HashMap { + let mut kept = HashMap::new(); + let mut stack = vec![root]; + while let Some(node) = stack.pop() { + if kept.contains_key(&node.ihr()) { + continue; + } + let hide = match node.inner() { + Inner::Case(..) => usage.hide(node.ihr()), + _ => Hide::Neither, + }; + kept.insert(node.ihr(), hide); + match (node.inner(), hide) { + (Inner::Case(_, right), Hide::Left) => stack.push(right), + (Inner::Case(left, _), Hide::Right) => stack.push(left), + _ => { + stack.extend(node.left_child()); + stack.extend(node.right_child()); + } + } } + kept } - struct Finalizer; + /// Finalizes the types of the pruned program, and records the IHR of each node. + struct Finalizer<'brand> { + ihrs: HashMap<*const ConstructNode<'brand>, Ihr>, + } - impl<'brand> Converter, Redeem> for Finalizer { + impl<'brand> Converter, Redeem> for Finalizer<'brand> { type Error = std::convert::Infallible; fn convert_witness( &mut self, - data: &PostOrderIterItem<&ConstructNode>, + data: &PostOrderIterItem<&ConstructNode<'brand>>, witness: &Option, ) -> Result { let pruned_target_ty = data @@ -392,9 +414,9 @@ impl RedeemNode { fn convert_disconnect( &mut self, - _: &PostOrderIterItem<&ConstructNode>, + _: &PostOrderIterItem<&ConstructNode<'brand>>, right: Option<&Arc>, - _: &Option>, + _: &Option>>, ) -> Result, Self::Error> { Ok(right .map(Arc::clone) @@ -403,7 +425,7 @@ impl RedeemNode { fn convert_data( &mut self, - data: &PostOrderIterItem<&ConstructNode>, + data: &PostOrderIterItem<&ConstructNode<'brand>>, inner: Inner<&Arc, &Arc, &Value>, ) -> Result, Self::Error> { // Finalize target types of witness nodes in advance so we can prune their values. @@ -416,36 +438,134 @@ impl RedeemNode { .map(|node| node.cached_data()) .map_disconnect(|node| node.cached_data()) .map_witness(Value::shallow_clone); - Ok(Arc::new(RedeemData::new(final_arrow, converted_inner))) + let redeem_data = Arc::new(RedeemData::new(final_arrow, converted_inner)); + self.ihrs.insert(data.node, redeem_data.ihr); + Ok(redeem_data) } } + /// Rebuilds the program bottom-up from the kept nodes alone, and turns case + /// nodes with an unused branch into assertions. Returns the pruned program, + /// and the IHR in it of each kept case node, by its IHR in `program`. + fn rebuild( + program: &RedeemNode, + kept: &HashMap, + ) -> (Arc, Vec<(Ihr, Ihr)>) { + // Nodes in hidden branches are never built, so they cannot constrain the + // types of the pruned program. + // Because the types of the pruned program may change, + // we construct a temporary witness program with unfinalized types. + // Nodes are identified by IHR, like the tracker identifies them: building + // IHR-equal nodes separately makes each copy keep the branches that only its + // twins executed. + types::Context::with_context(|inference_context| { + let mut built: HashMap> = HashMap::new(); + let mut cases = vec![]; + for data in program.post_order_iter::>() { + let node = data.node; + let hide = match kept.get(&node.ihr()) { + Some(&hide) => hide, + // Inside a hidden branch. + None => continue, + }; + // Children are visited before their parents, so kept children are built. + let child = |child: &Arc| Arc::clone(&built[&child.ihr()]); + let inner = match (node.inner(), hide) { + (Inner::Case(left, right), Hide::Left) => { + Inner::AssertR(left.cmr(), child(right)) + } + (Inner::Case(left, right), Hide::Right) => { + Inner::AssertL(child(left), right.cmr()) + } + (inner, _) => inner + .as_ref() + .map(&child) + .map_disconnect(|right| Some(child(right))) + // The pruned type is not finalized at this point, + // so we cannot prune the witness value. + .map_witness(|witness| Some(witness.shallow_clone())), + }; + let data = ConstructData::from_inner( + &inference_context, + inner + .as_ref() + .map(|node| node.cached_data()) + .map_witness(Option::::clone), + ) + .expect("pruned types should check out if unpruned types check out"); + let built_node = Arc::new(Node::from_parts(inner, data)); + if let Inner::Case(..) = node.inner() { + cases.push((node.ihr(), Arc::clone(&built_node))); + } + built.insert(node.ihr(), built_node); + } + let pruned_witness_program = &built[&program.ihr()]; + // Like a decoder, fix the program type to 1 → 1. + pruned_witness_program + .set_arrow_to_program() + .expect("pruned program should have program type"); + + // Finalize the types of the witness program. + // We obtain the pruned redeem program. + // Once the pruned type is finalized, we can proceed to prune witness values. + let mut finalizer = Finalizer { + ihrs: HashMap::new(), + }; + let pruned = pruned_witness_program + .convert::(&mut finalizer) + .expect("finalization is infallible"); + let case_ihrs = cases + .iter() + .map(|(ihr, node)| (*ihr, finalizer.ihrs[&Arc::as_ptr(node)])) + .collect(); + (pruned, case_ihrs) + }) + } + // 1) Run the Bit Machine and mark (un)used branches. // This is the only fallible step in the pruning process. let mut mac = BitMachine::for_program(self)?; mac.exec_with_tracker(self, env, tracker)?; - // 2) Prune out unused case branches. - // Because the types of the pruned program may change, - // we construct a temporary witness program with unfinalized types. - // Convert with `MaxSharing`: the tracker keys branch usage by IHR, so - // converting IHR-equal nodes separately makes each copy keep the branches - // that only its twins executed. - types::Context::with_context(|inference_context| { - let pruned_witness_program = self - .convert::, _, _>(&mut Pruner { - inference_context, - tracker, - }) - .expect("pruning unused branches is infallible"); - - // 3) Finalize the types of the witness program. - // We obtain the pruned redeem program. - // Once the pruned type is finalized, we can proceed to prune witness values. - Ok(pruned_witness_program - .convert::(&mut Finalizer) - .expect("finalization is infallible")) - }) + let mut usage = Usage { + tracker: &*tracker, + merged_into: HashMap::new(), + branches: HashMap::new(), + }; + // Every round that does not return merges two groups of case nodes, so there + // are at most as many rounds as case nodes. + let n_cases = self + .post_order_iter::>() + .filter(|data| matches!(data.node.inner(), Inner::Case(..))) + .count(); + let mut round = 0; + loop { + round += 1; + + // 2) Find the nodes to keep: those reachable from the root through used branches. + let kept = kept_nodes(self, &mut usage); + + // 3) Rebuild the program from the kept nodes and prune out unused case branches. + let (pruned, case_ihrs) = rebuild(self, &kept); + + // 4) Case nodes which became one node in the pruned program must keep the + // branches that any of them used, or the node that an encoder keeps hides a + // branch which the others use. Merge them, and rebuild if this changed which + // branches they keep. + let mut by_pruned_ihr = HashMap::new(); + let mut changed = false; + for (ihr, pruned_ihr) in case_ihrs { + match by_pruned_ihr.entry(pruned_ihr) { + Entry::Vacant(entry) => { + entry.insert(ihr); + } + Entry::Occupied(entry) => changed |= usage.merge(*entry.get(), ihr), + } + } + if !changed || round > n_cases { + return Ok(pruned); + } + } } /// Decode a Simplicity program from bits, including the witness data. @@ -1047,6 +1167,147 @@ mod tests { ); } + #[test] + fn prune_keeps_branches_of_case_nodes_that_become_equal() { + // Two separate `case unit unit` nodes with different types, so the tracker + // tells them apart. One only takes its right branch and the other only its + // left. Pruning makes their types equal, and the IHR of a case node does not + // show which branch it hides, so an encoder gives both the same node, which + // must keep both branches. Human encoding cannot express this program, + // because it merges nodes with the same CMR. + use crate::ffi::tests::{ffi::SimplicityErr, run_program, TestUpTo}; + use crate::jet::CoreEnv; + use crate::node::CoreConstructible; + + type ArcNode<'brand> = Arc>; + + let unpruned = types::Context::with_context(|ctx| { + let unit = || ArcNode::unit(&ctx); + // `case unit unit : 2 * 1 -> 1`, fed a right-tagged input. + let takes_right = ArcNode::comp( + &ArcNode::pair(&ArcNode::injr(&unit()), &unit()).unwrap(), + &ArcNode::case(&unit(), &unit()).unwrap(), + ) + .unwrap(); + // A left-tagged value of type 1 + 2. Its right branch never runs, but makes + // the right side 2 rather than 1 until pruning hides it. + let tag = ArcNode::comp( + &ArcNode::pair(&ArcNode::injl(&unit()), &unit()).unwrap(), + &ArcNode::case( + &ArcNode::injl(&unit()), + &ArcNode::injr(&ArcNode::injl(&unit())), + ) + .unwrap(), + ) + .unwrap(); + // `case unit unit : (1 + 2) * 1 -> 1`, fed that left-tagged value. + let takes_left = ArcNode::comp( + &ArcNode::pair(&tag, &unit()).unwrap(), + &ArcNode::case(&unit(), &unit()).unwrap(), + ) + .unwrap(); + ArcNode::comp(&ArcNode::pair(&takes_right, &takes_left).unwrap(), &unit()) + .unwrap() + .finalize_unpruned() + .expect("program should finalize") + }); + + let env = CoreEnv::new(); + let pruned = unpruned.prune(&env).expect("pruning should succeed"); + let (prog_bytes, witness_bytes) = pruned.to_vec_with_witness(); + let decoded = RedeemNode::decode::<_, _, Core>( + BitIter::from(&prog_bytes[..]), + BitIter::from(&witness_bytes[..]), + ) + .expect("pruned program should decode"); + BitMachine::for_program(&decoded) + .expect("pruned program has reasonable bounds") + .exec(&decoded, &env) + .expect("decoded program should not reach a pruned branch"); + + let c_result = run_program( + &prog_bytes, + &witness_bytes, + TestUpTo::Everything, + None, + None, + ) + .expect("libsimplicity should decode the pruned program"); + assert_eq!(c_result.eval_result, SimplicityErr::NoError); + } + + #[test] + #[cfg(feature = "human_encoding")] + fn prune_drops_witness_read_only_by_hidden_branch() { + // Only the right branch of the case reads `wit2`. With `wit1` selecting the + // left branch, pruning hides the right branch, nothing else reads `wit2`, and + // a decoder expects no bits for it. Both branches contain `drop iden`, so the + // hidden branch must not constrain the types of the pruned program through it. + use crate::ffi::tests::{ffi::SimplicityErr, run_program, TestUpTo}; + use crate::human_encoding::Forest; + use crate::jet::CoreEnv; + use std::collections::HashMap; + + // `drop iden` is defined once, so both branches point at the same node. + let pointer_shared = r#"wit1 := witness : 1 -> 2 +wit2 := witness : 1 -> 2^8 +input := pair wit1 wit2 : 1 -> 2 * 2^8 +proj := drop iden +skip_wit2 := comp proj unit +read_wit2 := comp proj (comp (pair iden iden) (comp jet_eq_8 jet_verify)) +main := comp input (case skip_wit2 read_wit2) : 1 -> 1"#; + // `drop iden` is written out twice: two pointer-distinct nodes with one IHR. + let ihr_shared = r#"wit1 := witness : 1 -> 2 +wit2 := witness : 1 -> 2^8 +input := pair wit1 wit2 : 1 -> 2 * 2^8 +skip_wit2 := comp (drop iden) unit +read_wit2 := comp (drop iden) (comp (pair iden iden) (comp jet_eq_8 jet_verify)) +main := comp input (case skip_wit2 read_wit2) : 1 -> 1"#; + let wit = HashMap::from([ + (Arc::from("wit1"), Value::u1(0)), + (Arc::from("wit2"), Value::u8(7)), + ]); + + for s in [pointer_shared, ihr_shared] { + let unpruned = types::Context::with_context(|ctx| { + Forest::parse::(s) + .expect("program should parse") + .to_witness_node(&ctx, &wit) + .expect("program should have main") + .finalize_unpruned() + .expect("program should finalize") + }); + + let pruned = unpruned + .prune(&CoreEnv::new()) + .expect("pruning should succeed"); + let (prog_bytes, witness_bytes) = pruned.to_vec_with_witness(); + let decoded = RedeemNode::decode::<_, _, Core>( + BitIter::from(&prog_bytes[..]), + BitIter::from(&witness_bytes[..]), + ) + .expect("pruned program should decode, so its witness holds no unread bits"); + assert_eq!( + decoded.ihr(), + pruned.ihr(), + "a decoder should infer the same types as pruning did" + ); + + // libsimplicity is the consensus implementation; check that it accepts the + // pruned program. The jets are in the hidden branch, so it can decode the + // program although it expects Elements jet codes. + let c_result = run_program( + &prog_bytes, + &witness_bytes, + TestUpTo::Everything, + None, + None, + ) + .expect("libsimplicity should decode the pruned program"); + assert_eq!(c_result.eval_result, SimplicityErr::NoError); + } + } + #[test] #[cfg(all(feature = "elements", feature = "human_encoding"))] fn prune() {