Skip to content
Open
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
# Unreleased

* Fix `RedeemNode::prune` producing programs that consensus rejects, and add `ExecutionError::PruningFailed` [#391](https://github.com/BlockstreamResearch/rust-simplicity/issues/391).
* Implement the Bitcoin jet cost and CMR tables: `Bitcoin::cost()` and `Bitcoin::cmr()`
no longer panic and now return the values from libsimplicity's canonical
`primitiveJetNode.inc`, for all 428 jets in the Bitcoin jet set. Re-vendors
libsimplicity to `4e0beb5`.
* Add `Cost::get_padding_size`, returning the chain-agnostic length of the padding witness
stack item needed to bring a cost within the witness budget, and `Cost::get_padding_bytes`,
returning the chain-specific bytes that fill it (an all-zero item on Bitcoin, an annex on
Elements). Deprecate `Cost::get_padding` in favour of these. The padding length is now the
smallest that covers the deficit: it accounts for the CompactSize length prefix of the
padding item and for any growth of the item-count prefix.
* `Cost::is_budget_valid` now takes `&[Vec<u8>]` instead of `&Vec<Vec<u8>>` and computes the
serialized witness length directly rather than via the Elements consensus encoder, making it
available under the `bitcoin` feature (which `elements` implies) as well as `elements`.
* Declare the FFI bindings for the Bitcoin tx-context jets and drop the `Arc`s from the
Bitcoin and Elements environments.

# 0.9.0 - 2026-09-16

Expand Down
2 changes: 1 addition & 1 deletion simplicity-sys/depend/simplicity-HEAD-revision.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
# This file has been automatically generated.
3f0bb69c4547bcf3483ca5ccbd06699464166650
4e0beb5947b7e75ee7974d82a1447e89a0b4b5d6
3 changes: 0 additions & 3 deletions simplicity-sys/src/c_jets/c_env/bitcoin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,6 @@ pub struct CTapEnv {
_data: (),
}

// Will uncomment in a later commit; need to update libsimplicity first so these
// symbols have something to link against.
extern "C" {
#[link_name = "rustsimplicity_0_8_c_sizeof_rawBitcoinBuffer"]
pub static c_sizeof_rawBuffer: c_size_t;
Expand Down Expand Up @@ -136,7 +134,6 @@ impl CRawBuffer {
}
}

// Will uncomment in a later commit; need to update libsimplicity first.
#[cfg(test)]
mod tests {
use core::mem::{align_of, size_of};
Expand Down
301 changes: 260 additions & 41 deletions src/analysis.rs

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions src/jet/bitcoin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

mod c_env;
mod environment;
#[cfg(test)]
mod spec_tests;
#[cfg(test)]
mod tests;

pub use environment::BitcoinEnv;

Expand Down
169 changes: 169 additions & 0 deletions src/jet/bitcoin/spec_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
// SPDX-License-Identifier: CC0-1.0

//! Checks that every Bitcoin jet's Rust `cmr()` and `cost()` agree with the
//! values in libsimplicity's vendored `primitiveJetNode.inc`.
//!
//! Unlike a frozen copy of the generated table, this re-reads the C data the
//! generator is itself derived from, so it catches drift between the generated
//! Rust and the C: if a cost or CMR changes in the `.inc` without a matching
//! regeneration, this test fails. `update_jets.sh --check` only verifies that
//! the generator output is unchanged; it cannot see the `.inc` moving
//! underneath it.

use std::collections::HashMap;

use super::Bitcoin;
use crate::jet::Jet;
use crate::merkle::cmr::Cmr;

/// The vendored C data, included at compile time.
const PRIMITIVE_JET_NODE_INC: &str =
include_str!("../../../simplicity-sys/depend/simplicity/bitcoin/primitiveJetNode.inc");

/// The generated `c_jet_ptr` mapping from `Bitcoin` variant to C symbol, used
/// to pair each Rust jet with its `.inc` entry.
const GENERATED_INIT: &str = include_str!("../init/bitcoin.rs");

/// A single `.inc` entry.
struct JetSpec {
cmr: Cmr,
cost_milliweight: u32,
}

/// Parse the subset of `primitiveJetNode.inc` we care about: for each
/// `[NAME] = { ... }` block, the `.jet` symbol and the `.cmr`/`.cost` fields.
///
/// The generator emits this file as a plain C array initialiser with one field
/// per line, so a line-oriented parse is sufficient.
fn parse_inc(inc: &str) -> HashMap<String, JetSpec> {
let mut out = HashMap::new();
let mut symbol: Option<String> = None;
let mut cmr_bytes: Option<[u8; 32]> = None;
let mut cost: Option<u32> = None;

for line in inc.lines() {
let line = line.trim();
if let Some(rest) = line.strip_prefix(", .jet = ") {
symbol = Some(rest.trim().to_owned());
} else if let Some(rest) = line.strip_prefix(", .cmr = {{") {
cmr_bytes = Some(parse_cmr(rest));
} else if let Some(rest) = line.strip_prefix(", .cost = ") {
let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
cost = Some(digits.parse().expect("cost digits"));
} else if line == "}" {
if let (Some(sym), Some(cmr), Some(c)) = (symbol.take(), cmr_bytes.take(), cost.take())
{
out.insert(
sym,
JetSpec {
cmr: Cmr::from_byte_array(cmr),
cost_milliweight: c,
},
);
}
}
}
out
}

/// Parse a `.cmr = {{0x49425a86u, 0xe20a676du, ...}}` line into 32 bytes.
/// Each word is big-endian; the words appear in order.
fn parse_cmr(rest: &str) -> [u8; 32] {
let mut bytes = [0u8; 32];
let mut n = 0usize;
for word in rest.split(',') {
let word = word.trim().trim_end_matches('}').trim();
let hex = word
.strip_prefix("0x")
.and_then(|w| w.strip_suffix('u'))
.expect("cmr word is 0x...u");
let value = u32::from_str_radix(hex, 16).expect("cmr word hex");
bytes[n * 4..n * 4 + 4].copy_from_slice(&value.to_be_bytes());
n += 1;
}
assert_eq!(n, 8, "cmr must have 8 u32 words, got {n}");
bytes
}

/// Parse the generated `c_jet_ptr` function to map every `Bitcoin::Variant` to
/// the `jets_wrapper` symbol it dispatches to (e.g. `Bitcoin::Add16` ->
/// `add_16`, `Bitcoin::TxHash` -> `bitcoin_tx_hash`).
fn parse_symbol_map(init: &str) -> HashMap<String, String> {
let mut map = HashMap::new();
for line in init.lines() {
let line = line.trim();
let Some((lhs, rhs)) = line.split_once("=>") else {
continue;
};
let Some(variant) = lhs.trim().strip_prefix("Bitcoin::") else {
continue;
};
let variant = variant.trim().trim_end_matches(',').trim();
let rhs = rhs.trim().trim_end_matches(',');
if let Some(symbol) = rhs.rsplit("::").next() {
map.insert(variant.to_owned(), symbol.to_owned());
}
}
map
}

/// The wrapper symbol is the `.jet` symbol in the `.inc` with its
/// `rustsimplicity_<major>_<minor>_` prefix removed.
fn lookup<'a>(specs: &'a HashMap<String, JetSpec>, symbol: &str) -> Option<&'a JetSpec> {
specs.iter().find_map(|(sym, spec)| {
let rest = sym.strip_prefix("rustsimplicity_")?;
// Skip the two version components (all digits, underscore-separated).
let mut parts = rest.splitn(3, '_');
let major = parts.next()?;
let minor = parts.next()?;
let name = parts.next()?;
let is_version = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
(is_version(major) && is_version(minor) && name == symbol).then_some(spec)
})
}

#[test]
fn generated_tables_match_primitive_jet_node_inc() {
let specs = parse_inc(PRIMITIVE_JET_NODE_INC);
let symbols = parse_symbol_map(GENERATED_INIT);

assert!(
!specs.is_empty() && !symbols.is_empty(),
"failed to parse the vendored .inc or the generated c_jet_ptr table"
);

let mut checked = 0usize;
let mut missing = Vec::new();
for jet in Bitcoin::ALL {
let name = format!("{jet:?}");
let Some(symbol) = symbols.get(&name) else {
missing.push(name);
continue;
};
let Some(spec) = lookup(&specs, symbol) else {
missing.push(name);
continue;
};
assert_eq!(
jet.cmr(),
spec.cmr,
"{name}: CMR differs from primitiveJetNode.inc ({symbol})"
);
assert_eq!(
jet.cost().to_string(),
spec.cost_milliweight.to_string(),
"{name}: cost differs from primitiveJetNode.inc ({symbol})"
);
checked += 1;
}

assert!(
missing.is_empty(),
"jets not found in the .inc: {missing:?}"
);
assert_eq!(
checked,
Bitcoin::ALL.len(),
"not every jet in Bitcoin::ALL was checked"
);
}
Loading
Loading