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
21 changes: 21 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,27 @@ jobs:
run: |
cargo build --workspace --all-features --verbose

- name: Unit
env:
SIMPLEX_TEST_VERBOSE: ${{ runner.debug == '1' && '-v' || '' }}
run: |
simplex test --no-simplex --test-threads 4 "${SIMPLEX_TEST_VERBOSE}" -- --release

- name: Fuzz
env:
SIMPLEX_TEST_VERBOSE: ${{ runner.debug == '1' && '-v' || '' }}
run: |
simplex test --fuzz --test-threads 4 "${SIMPLEX_TEST_VERBOSE}" -- --release

# Each run draws a new seed: keep the persisted failing cases to reproduce them locally.
- name: Upload fuzz failures
if: ${{ failure() }}
uses: actions/upload-artifact@v4
with:
name: fuzz-failures-${{ matrix.os }}
path: fuzz-failures/
if-no-files-found: ignore

- name: Test
env:
SIMPLEX_TEST_VERBOSE: ${{ runner.debug == '1' && '-v' || '' }}
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ target/

# Simplex output
src/artifacts
/fuzz-failures

# IDE/editors (optional but common minimal)
**/.DS_Store
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
- Extended functions for retrieving information from `OP_RETURN`.
- Conversion and bit functions for `u2` and `u4`.
- Functions for asserting script hashes.
- Fuzz tests for `secp256k1` operations.

### Changed
- Bumped Simplex to 0.2.0.
- Aligned existing testing API with changes in Simplex.
- `secp256k1` unit tests run without a node, on fixed values.

## [0.2.0]

Expand Down
21 changes: 0 additions & 21 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ smplx-std = { git = "https://github.com/BlockstreamResearch/smplx", branch = "fi
anyhow = { version = "1.0.101" }
rand = { version = "0.8.6" }
primitive-types = { version = "0.14" }
num-bigint = { version = "0.5.1" }
num-traits = { version = "0.2.19" }
secp256k1-zkp = { version = "0.11.0", features = ["rand"] }

# TODO: Remove this patch only when SimplicityHL uses a simplicity-lang release with the pruning fix.
Expand Down
4 changes: 2 additions & 2 deletions Simplex.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
# url = "<esplora url>"
# network = "<Liquid, LiquidTestnet, ElementsRegtest>"

# [test.fuzz]
# cases = 10
[test.fuzz]
cases = 100
# seed = 12345
# network = "<Liquid, LiquidTestnet, ElementsRegtest>"

Expand Down
40 changes: 40 additions & 0 deletions tests/stdlib/common/case.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use simplex::program::{Program, ProgramSchema};
use simplex::simplicityhl::Arguments;

use simplex::fuzz::FuzzProgramTrait;

use crate::common::core::Expect;
use crate::common::unit;

pub trait DispatchCase: Sized + 'static {
type Program: FuzzProgramTrait;

const PROGRAM_NAME: &'static str = "program";

fn arguments() -> <Self::Program as ProgramSchema>::Arguments;

fn into_witness(self) -> <Self::Program as ProgramSchema>::Witness;

fn program() -> Program {
let arguments: Arguments = Self::arguments().into();

Self::Program::build_program(&arguments)
.unwrap_or_else(|error| panic!("{} does not compile: {error}", Self::PROGRAM_NAME))
}

#[track_caller]
fn accepts(self) {
unit::check(&Self::program(), self.into_witness(), Expect::Ok);
}

#[track_caller]
fn rejects(self, reason: Expect) {
assert_ne!(
reason,
Expect::Ok,
"use `accepts` for cases that must succeed"
);

unit::check(&Self::program(), self.into_witness(), reason);
}
}
2 changes: 1 addition & 1 deletion tests/stdlib/common/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use simplicityhl_std::artifacts::tests::mock::derived_mock::MockWitness;

use crate::common::utxo_helper::{DEFAULT_SEND_AMOUNT, search_utxo_by_txid};

#[derive(Clone, Copy)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Expect {
/// The spend succeeds.
Ok,
Expand Down
71 changes: 71 additions & 0 deletions tests/stdlib/common/fuzz.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
use std::fmt::Debug;

use simplex::simplicityhl::Arguments;

use simplex::fuzz::proptest::strategy::Strategy;
use simplex::fuzz::{FuzzProgramValues, Scenario};
use simplex::{FuzzMode, TestContext};

use simplex::fuzz::Expect;

use crate::common::case::DispatchCase;

const DEFAULT_SPENT_INPUT: usize = 0;

pub fn accepts<C, T>(
context: &TestContext<FuzzMode>,
inputs: impl Strategy<Value = T> + 'static,
build: impl Fn(T) -> C + 'static,
) where
C: DispatchCase,
T: Debug + 'static,
{
check(context, inputs, build, Expect::Accept);
}

pub fn rejects<C, T>(
context: &TestContext<FuzzMode>,
inputs: impl Strategy<Value = T> + 'static,
build: impl Fn(T) -> C + 'static,
) where
C: DispatchCase,
T: Debug + 'static,
{
check(context, inputs, build, Expect::Reject);
}

pub fn check<C, T>(
context: &TestContext<FuzzMode>,
inputs: impl Strategy<Value = T> + 'static,
build: impl Fn(T) -> C + 'static,
expect: Expect,
) where
C: DispatchCase,
T: Debug + 'static,
{
let arguments: Arguments = C::arguments().into();
let values = inputs.prop_map(move |input| {
FuzzProgramValues::from((arguments.clone(), build(input).into_witness().into()))
});

let mut scenario = Scenario::default();
scenario
.add::<C::Program>(C::PROGRAM_NAME)
.spends(DEFAULT_SPENT_INPUT)
.custom_strategy(values);

run_scenario(context, scenario, expect);
}

pub fn run_scenario(context: &TestContext<FuzzMode>, scenario: Scenario, expect: Expect) {
let engine = context.engine(scenario).spec(move |_| expect);

// Negative scenarios deliberately generate no accepting witness.
let engine = if expect == Expect::Reject {
engine.allow_unspendable()
} else {
engine
};

engine.run();
}
3 changes: 3 additions & 0 deletions tests/stdlib/common/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
pub mod case;
pub mod core;
pub mod fuzz;
pub mod helper;
pub mod u256_wrapper;
pub mod uint;
pub mod unit;
pub mod utxo_helper;
69 changes: 69 additions & 0 deletions tests/stdlib/common/unit.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use simplex::program::{Program, ProgramError, ProgramTrait};
use simplex::provider::SimplicityNetwork;
use simplex::simplicityhl::WitnessValues;
use simplex::simplicityhl::elements::{OutPoint, Script, Txid};
use simplex::simplicityhl::simplicity::bit_machine::ExecutionError;
use simplex::transaction::{FinalTransaction, PartialInput, PartialOutput, ProgramInput, UTXO};

use crate::common::core::Expect;

const AMOUNT: u64 = 1_000;

pub fn run(program: &Program, witness: impl Into<WitnessValues>) -> Result<(), ProgramError> {
let network = SimplicityNetwork::default_regtest();
let witness = witness.into();

let (pst, _) = unit_transaction(program, witness.clone(), network)
.extract_pst()
.expect("the unit transaction is explicit");

program.execute(&pst, &witness, 0, &network).map(|_| ())
}

/// A case that fails before the program runs (e.g. a malformed witness) panics instead of
/// matching `expect`.
#[track_caller]
pub fn check(program: &Program, witness: impl Into<WitnessValues>, expect: Expect) {
match outcome(run(program, witness)) {
Ok(actual) => assert_eq!(actual, expect, "unexpected program outcome"),
Err(error) => panic!("the case failed before the program ran: {error}"),
}
}

fn outcome(result: Result<(), ProgramError>) -> Result<Expect, ProgramError> {
let execution = match result {
Ok(()) => return Ok(Expect::Ok),
Err(ProgramError::Pruning(execution) | ProgramError::Execution(execution)) => execution,
Err(other) => return Err(other),
};

match execution {
ExecutionError::JetFailed(_) => Ok(Expect::AssertFailed),
ExecutionError::ReachedPrunedBranch(_) => Ok(Expect::PrunedBranch),
other => Err(ProgramError::Execution(other)),
}
}

fn unit_transaction(
program: &Program,
witness: WitnessValues,
network: SimplicityNetwork,
) -> FinalTransaction {
let asset = network.policy_asset();
let utxo = UTXO::explicit(
OutPoint::new(Txid::from_byte_array([0xf0; 32]), 0),
program.get_script_pubkey(&network),
AMOUNT,
asset,
);

let mut ft = FinalTransaction::new();
ft.add_program_input(
PartialInput::new(utxo),
ProgramInput::new(Box::new(program.clone()), witness),
None,
);
ft.add_output(PartialOutput::new(Script::from(vec![0x51]), AMOUNT, asset));

ft
}
Loading
Loading