Skip to content
Draft
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
6 changes: 3 additions & 3 deletions fuzz/fuzz_targets/c_rust_merkle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
fn do_test(data: &[u8]) {
use simplicity::ffi::tests::{ffi::SimplicityErr, run_program, TestUpTo};
use simplicity::hashes::sha256::Midstate;
use simplicity::jet::Elements;
use simplicity::jet::ElementsTxEnv;
use simplicity::types;
use simplicity::{BitIter, RedeemNode};

Expand All @@ -18,7 +18,7 @@ fn do_test(data: &[u8]) {
// If the program doesn't decode, just use the first byte as a "length".
let prog_len: Option<usize> = types::Context::with_context(|ctx| {
let mut iter = BitIter::from(data);
match simplicity::decode::decode_expression::<_, Elements>(&ctx, &mut iter) {
match simplicity::decode::decode_expression::<_, ElementsTxEnv>(&ctx, &mut iter) {
Ok(_) => Some((iter.n_total_read() + 7) / 8),
Err(_) => match data.first() {
Some(&n) => Some(core::cmp::min(data.len(), n.into())),
Expand All @@ -36,7 +36,7 @@ fn do_test(data: &[u8]) {

let prog_iter = BitIter::from(program);
let wit_iter = BitIter::from(witness);
let rust_result = RedeemNode::<Elements>::decode(prog_iter, wit_iter);
let rust_result = RedeemNode::decode::<_, _, ElementsTxEnv>(prog_iter, wit_iter);

match (c_result, rust_result) {
(Ok(_), Err(e)) => panic!("C accepted code that Rust rejected: {}", e),
Expand Down
12 changes: 7 additions & 5 deletions fuzz/fuzz_targets/decode_program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,19 @@

#[cfg(any(fuzzing, test))]
fn do_test(data: &[u8]) {
use simplicity::jet::Core;
use simplicity::jet::CoreEnv;
use simplicity::{BitIter, BitWriter, RedeemNode};

let prog_iter = BitIter::new(data.iter().cloned());
let wit_iter = BitIter::new(core::iter::repeat(0));
if let Ok(program) = RedeemNode::<Core>::decode(prog_iter, wit_iter) {
if let Ok(program) = RedeemNode::decode::<_, _, CoreEnv>(prog_iter, wit_iter) {
let mut prog_reser = Vec::<u8>::new();
let mut wit_reser = std::io::sink();
let mut wit_reser = Vec::<u8>::new();

let mut prog_w = BitWriter::from(&mut prog_reser);
let mut wit_w = BitWriter::from(&mut wit_reser);
let prog_sink: &mut dyn std::io::Write = &mut prog_reser;
let wit_sink: &mut dyn std::io::Write = &mut wit_reser;
let mut prog_w = BitWriter::from(prog_sink);
let mut wit_w = BitWriter::from(wit_sink);
program
.encode(&mut prog_w, &mut wit_w)
.expect("encoding to vector");
Expand Down
6 changes: 3 additions & 3 deletions fuzz/fuzz_targets/parse_human.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@
#[cfg(any(fuzzing, test))]
fn do_test(data: &[u8]) {
use simplicity::human_encoding::Forest;
use simplicity::jet::Elements;
use simplicity::jet::ElementsTxEnv;

let s = match std::str::from_utf8(data) {
Ok(s) => s,
Err(_) => return,
};

if let Ok(program) = Forest::<Elements>::parse(s) {
if let Ok(program) = Forest::parse::<ElementsTxEnv>(s) {
let reserialize = program.string_serialize();
let round_trip = Forest::<Elements>::parse(&reserialize).unwrap();
let round_trip = Forest::parse::<ElementsTxEnv>(&reserialize).unwrap();
assert_eq!(program, round_trip);
}
}
Expand Down
4 changes: 2 additions & 2 deletions fuzz/fuzz_targets/regression_286.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

#[cfg(any(fuzzing, test))]
fn do_test(data: &[u8]) {
use simplicity::{jet::Core, types, BitIter, CommitNode};
use simplicity::{jet::CoreEnv, types, BitIter, CommitNode};

types::Context::with_context(|ctx| {
let mut extractor = simplicity_fuzz::Extractor::new(data);
Expand Down Expand Up @@ -32,7 +32,7 @@ fn do_test(data: &[u8]) {
let prog = finalized.encode_to_vec();
//println!("{}", simplicity::bitcoin::hex::DisplayHex::as_hex(&prog));
let prog = BitIter::from(prog);
let decode = CommitNode::<Core>::decode(prog).unwrap();
let decode = CommitNode::decode::<_, CoreEnv>(prog).unwrap();
assert_eq!(
finalized, decode,
"Constructed committed LHS; encoded and decoded to get RHS",
Expand Down
7 changes: 4 additions & 3 deletions jets-bench/src/check_all_jets.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use std::collections::BTreeMap;
use std::sync::Mutex;

use simplicity::jet::Jet as _;
use simplicity::jet::JetEnvironment;
use simplicity::BitIter;

type Jet = simplicity::jet::Elements;
type JetEnv = simplicity::jet::ElementsTxEnv;
type Jet = <simplicity::jet::ElementsTxEnv as JetEnvironment>::Jet;

static CHECKED_JETS: Mutex<Option<BTreeMap<Jet, usize>>> = Mutex::new(None);
pub const N_TOTAL: usize = 469;
Expand All @@ -22,7 +23,7 @@ pub fn initialize() {
for u2 in 0..=255 {
let arr = [u0, u1, u2];
let mut iter = BitIter::new(arr.iter().copied());
if let Ok(jet) = Jet::decode(&mut iter) {
if let Ok(jet) = JetEnv::decode_jet(&mut iter) {
map.insert(jet, 0);
}
}
Expand Down
12 changes: 7 additions & 5 deletions simpcli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
//

use simplicity::human_encoding::Forest;
use simplicity::jet::JetEnvironment;
use simplicity::node::CommitNode;
use simplicity::{self, BitIter};

Expand All @@ -22,7 +23,8 @@ use std::{env, fs};

/// What set of jets to use in the program.
// FIXME this should probably be configurable.
type DefaultJet = simplicity::jet::Elements;
type DefaultJetEnv = simplicity::jet::ElementsTxEnv;
type DefaultJet = <DefaultJetEnv as JetEnvironment>::Jet;

fn usage(process_name: &str) {
eprintln!("Usage:");
Expand Down Expand Up @@ -77,7 +79,7 @@ impl Command {

fn parse_file(name: &str) -> Result<Forest<DefaultJet>, String> {
let s = fs::read_to_string(name).map_err(|e| format!("failed to read file {}: {}", name, e))?;
match Forest::parse(&s) {
match Forest::parse::<DefaultJetEnv>(&s) {
Ok(prog) => Ok(prog),
Err(mut errs) => {
errs.add_context(std::sync::Arc::from(s));
Expand Down Expand Up @@ -154,16 +156,16 @@ fn main() -> Result<(), String> {
let v = simplicity::base64::Engine::decode(&STANDARD, first_arg.as_bytes())
.map_err(|e| format!("failed to parse base64: {}", e))?;
let iter = BitIter::from(v.into_iter());
let commit =
CommitNode::decode(iter).map_err(|e| format!("failed to decode program: {}", e))?;
let commit = CommitNode::decode::<_, DefaultJetEnv>(iter)
.map_err(|e| format!("failed to decode program: {}", e))?;
let prog = Forest::<DefaultJet>::from_program(commit);
println!("{}", prog.string_serialize());
}
Command::Graph => {
let v = simplicity::base64::Engine::decode(&STANDARD, first_arg.as_bytes())
.map_err(|e| format!("failed to parse base64: {}", e))?;
let iter = BitIter::from(v.into_iter());
let commit = CommitNode::<DefaultJet>::decode(iter)
let commit = CommitNode::decode::<_, DefaultJetEnv>(iter)
.map_err(|e| format!("failed to decode program: {}", e))?;
println!("{}", commit.display_as_dot());
}
Expand Down
24 changes: 12 additions & 12 deletions src/bit_encoding/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
//! Refer to [`crate::encode`] for information on the encoding.

use crate::dag::{Dag, DagLike, InternalSharing};
use crate::jet::Jet;
use crate::jet::{Jet, JetEnvironment};
use crate::merkle::cmr::Cmr;
use crate::node::{
ConstructNode, CoreConstructible, DisconnectConstructible, JetConstructible,
Expand Down Expand Up @@ -153,10 +153,10 @@ impl<J: Jet> DagLike for (usize, &'_ [DecodeNode<J>]) {
}
}

pub fn decode_expression<'brand, I: Iterator<Item = u8>, J: Jet>(
pub fn decode_expression<'brand, I: Iterator<Item = u8>, JE: JetEnvironment>(
ctx: &types::Context<'brand>,
bits: &mut BitIter<I>,
) -> Result<ArcNode<'brand, J>, Error> {
) -> Result<ArcNode<'brand, JE::Jet>, Error> {
enum Converted<'brand, J: Jet> {
Node(ArcNode<'brand, J>),
Hidden(Cmr),
Expand All @@ -176,14 +176,14 @@ pub fn decode_expression<'brand, I: Iterator<Item = u8>, J: Jet>(

let mut nodes = Vec::with_capacity(cmp::min(len, 10_000));
for _ in 0..len {
let new_node = decode_node(bits, nodes.len())?;
let new_node = decode_node::<_, JE>(bits, nodes.len())?;
nodes.push(new_node);
}

// It is a sharing violation for any hidden node to be repeated. Track them in this set.
let mut hidden_set = HashSet::<Cmr>::new();
// Convert the DecodeNode structure into a CommitNode structure
let mut converted = Vec::<Converted<J>>::with_capacity(len);
let mut converted = Vec::<Converted<JE::Jet>>::with_capacity(len);
for data in (nodes.len() - 1, &nodes[..]).post_order_iter::<InternalSharing>() {
// Check canonical order as we go
if data.index != data.node.0 {
Expand Down Expand Up @@ -237,15 +237,15 @@ pub fn decode_expression<'brand, I: Iterator<Item = u8>, J: Jet>(

/// Decode a single Simplicity node from bits and
/// insert it into a hash map at its index for future reference by ancestor nodes.
fn decode_node<I: Iterator<Item = u8>, J: Jet>(
fn decode_node<I: Iterator<Item = u8>, JE: JetEnvironment>(
bits: &mut BitIter<I>,
index: usize,
) -> Result<DecodeNode<J>, Error> {
) -> Result<DecodeNode<JE::Jet>, Error> {
// First bit: 1 for jets/words, 0 for normal combinators
if bits.read_bit()? {
// Second bit: 1 for jets, 0 for words
if bits.read_bit()? {
J::decode(bits).map(|jet| DecodeNode::Jet(jet))
JE::decode_jet(bits).map(DecodeNode::Jet)
} else {
let n = bits.read_natural(Some(32))?;
let word = Word::from_bits(bits, n - 1)?;
Expand Down Expand Up @@ -306,7 +306,7 @@ fn decode_node<I: Iterator<Item = u8>, J: Jet>(
mod tests {
use super::*;
use crate::encode;
use crate::jet::Core;
use crate::jet::CoreEnv;
use crate::node::{CommitNode, RedeemNode};
use crate::BitWriter;

Expand All @@ -317,14 +317,14 @@ mod tests {
// Should be able to decode this as an expression...
let mut iter = BitIter::from(&justjet[..]);
types::Context::with_context(|ctx| {
decode_expression::<_, Core>(&ctx, &mut iter).unwrap();
decode_expression::<_, CoreEnv>(&ctx, &mut iter).unwrap();
});
// ...but NOT as a CommitNode
let iter = BitIter::from(&justjet[..]);
CommitNode::<Core>::decode(iter).unwrap_err();
CommitNode::decode::<_, CoreEnv>(iter).unwrap_err();
// ...or as a RedeemNode
let iter = BitIter::from(&justjet[..]);
RedeemNode::<Core>::decode(iter, BitIter::from(&[][..])).unwrap_err();
RedeemNode::decode::<_, _, CoreEnv>(iter, BitIter::from(&[][..])).unwrap_err();
}

#[test]
Expand Down
8 changes: 4 additions & 4 deletions src/bit_encoding/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,9 @@ impl<N: node::Marker> SharingTracker<EncodeNode<'_, N>> for EncodeSharing<N> {
/// Encode a Simplicity program to bits, without witness data.
///
/// Returns the number of written bits.
pub fn encode_program<W: io::Write, N: node::Marker>(
pub fn encode_program<N: node::Marker>(
program: &node::Node<N>,
w: &mut BitWriter<W>,
w: &mut BitWriter<&mut dyn io::Write>,
) -> io::Result<usize> {
let iter = EncodeNode::Node(program).post_order_iter::<EncodeSharing<N>>();

Expand All @@ -172,9 +172,9 @@ pub fn encode_program<W: io::Write, N: node::Marker>(
}

/// Encode a node to bits.
fn encode_node<W: io::Write, N: node::Marker>(
fn encode_node<N: node::Marker>(
data: PostOrderIterItem<EncodeNode<N>>,
w: &mut BitWriter<W>,
w: &mut BitWriter<&mut dyn io::Write>,
) -> io::Result<()> {
// Handle Hidden nodes specially
let node = match data.node {
Expand Down
6 changes: 4 additions & 2 deletions src/bit_machine/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -599,9 +599,11 @@ impl From<JetFailed> for ExecutionError {
mod tests {
use super::*;

#[cfg(feature = "elements")]
use crate::jet::elements::ElementsEnv;
use crate::jet::CoreEnv;
#[cfg(feature = "elements")]
use crate::jet::{elements::ElementsEnv, Elements};
use crate::jet::ElementsTxEnv;
#[cfg(feature = "elements")]
use crate::{node::RedeemNode, BitIter};
#[cfg(feature = "elements")]
Expand All @@ -619,7 +621,7 @@ mod tests {

let prog = BitIter::from(prog_bytes);
let witness = BitIter::from(witness_bytes);
let prog = match RedeemNode::<Elements>::decode(prog, witness) {
let prog = match RedeemNode::decode::<_, _, ElementsTxEnv>(prog, witness) {
Ok(prog) => prog,
Err(e) => panic!("program {} failed: {}", prog_hex, e),
};
Expand Down
10 changes: 5 additions & 5 deletions src/human_encoding/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ mod named_node;
mod parse;

use crate::dag::{DagLike, MaxSharing};
use crate::jet::Jet;
use crate::jet::{Jet, JetEnvironment};
use crate::node::{self, CommitNode, NoWitness};
use crate::types;
use crate::{Cmr, ConstructNode, Ihr, Value};
Expand Down Expand Up @@ -74,8 +74,8 @@ pub struct Forest<J: Jet> {

impl<J: Jet> Forest<J> {
/// Parses a forest from a string
pub fn parse(s: &str) -> Result<Self, ErrorSet> {
parse::parse(s).map(|roots| Forest { roots })
pub fn parse<JE: JetEnvironment<Jet = J>>(s: &str) -> Result<Self, ErrorSet> {
parse::parse::<JE>(s).map(|roots| Forest { roots })
}

/// Parses a program from a bytestring
Expand Down Expand Up @@ -221,7 +221,7 @@ mod tests {
env: &JE,
) {
types::Context::with_context(|ctx| {
let program = Forest::<JE::Jet>::parse(s)
let program = Forest::parse::<JE>(s)
.expect("Failed to parse human encoding")
.to_witness_node(&ctx, witness)
.expect("Forest is missing expected root")
Expand All @@ -239,7 +239,7 @@ mod tests {
err_msg: &'static str,
) {
types::Context::with_context(|ctx| {
let program = match Forest::<JE::Jet>::parse(s)
let program = match Forest::<JE::Jet>::parse::<JE>(s)
.expect("Failed to parse human encoding")
.to_witness_node(&ctx, witness)
.expect("Forest is missing expected root")
Expand Down
2 changes: 1 addition & 1 deletion src/human_encoding/named_node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ impl<J: Jet> NamedCommitNode<J> {

/// Encode a Simplicity expression to bits without any witness data
#[deprecated(since = "0.5.0", note = "use Self::encode_without_witness instead")]
pub fn encode<W: io::Write>(&self, w: &mut BitWriter<W>) -> io::Result<usize> {
pub fn encode(&self, w: &mut BitWriter<&mut dyn io::Write>) -> io::Result<usize> {
let program_bits = encode::encode_program(self, w)?;
w.flush_all()?;
Ok(program_bits)
Expand Down
Loading
Loading