From b83a8e3830a4dfe3f98c0d2277bc9045258610c1 Mon Sep 17 00:00:00 2001 From: Seth Schoen Date: Wed, 12 Aug 2026 15:24:16 -0700 Subject: [PATCH 1/9] Add relative timelock enforcement functions --- README.md | 6 ++++-- simf/lib/timelocks.simf | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 simf/lib/timelocks.simf diff --git a/README.md b/README.md index 79db4f9..d01cb47 100644 --- a/README.md +++ b/README.md @@ -69,8 +69,10 @@ simf/lib │ └── Utilities for detecting and enforcing `OP_RETURN` (null data) outputs. ├── asserts.simf │ └── Assertion helpers: `assert_eq_*` for uints and `bool`, plus `assert_none_*` for `Option`. -└── binary.simf - └── Basic binary logic operations: `and`, `or`, `not`, `xor`. +├── binary.simf +│ └── Basic binary logic operations: `and`, `or`, `not`, `xor`. +└── timelocks.simf + └── Enforcement of relative timelocks (`Distance` and `Duration`). ``` ## Installation diff --git a/simf/lib/timelocks.simf b/simf/lib/timelocks.simf new file mode 100644 index 0000000..c625ce2 --- /dev/null +++ b/simf/lib/timelocks.simf @@ -0,0 +1,35 @@ +pub fn enforce_relative_distance(min_distance: Distance) { + // Assert that the current input is spent in a transaction that can + // only appear a distance of at least min_distance blocks after the + // block containing the input UTXO. + // Panic otherwise. + + // This is a replacement for the deprecated jet::check_lock_distance. + + // Transaction version must be at least 2. + assert!(jet::le_32(2, jet::version())); + + // Fetch and parse sequence + let actual_data: Either = unwrap(jet::parse_sequence(jet::current_sequence())); + let actual_distance: Distance = unwrap_left::(actual_data); + + assert!(jet::le_16(min_distance, actual_distance)); +} + +pub fn enforce_relative_duration(min_duration: Duration) { + // Assert that the current input is spent in a transaction that can + // only appear a duration of at least min_duration units of 512 + // seconds after the creation of the block containing the input UTXO. + // Panic otherwise. + + // This is a replacement for the deprecated jet::check_lock_duration. + + // Transaction version must be at least 2. + assert!(jet::le_32(2, jet::version())); + + // Fetch and parse sequence + let actual_data: Either = unwrap(jet::parse_sequence(jet::current_sequence())); + let actual_duration: Duration = unwrap_right::(actual_data); + + assert!(jet::le_16(min_duration, actual_duration)); +} From ba80ea61eac560a283c06ae97332fd55af20e260 Mon Sep 17 00:00:00 2001 From: Seth Schoen Date: Wed, 18 Nov 2026 15:42:28 -0800 Subject: [PATCH 2/9] Add Simplex tests for timelock functions Co-Authored-By: Claude Opus 5.5 --- simf/tests/timelocks.simf | 24 ++++ tests/stdlib/common/core.rs | 106 ++++++++++++++-- tests/stdlib/main.rs | 1 + tests/stdlib/timelocks.rs | 244 ++++++++++++++++++++++++++++++++++++ 4 files changed, 368 insertions(+), 7 deletions(-) create mode 100644 simf/tests/timelocks.simf create mode 100644 tests/stdlib/timelocks.rs diff --git a/simf/tests/timelocks.simf b/simf/tests/timelocks.simf new file mode 100644 index 0000000..00a9ffd --- /dev/null +++ b/simf/tests/timelocks.simf @@ -0,0 +1,24 @@ +use crate::lib::timelocks::{enforce_relative_distance, enforce_relative_duration}; + +use crate::tests::support::dispatch::is_selected; + +fn main() { + let fn_idx: u8 = witness::FUNCTION_INDEX; + + let min_distance: Distance = witness::MIN_DISTANCE; + let min_duration: Duration = witness::MIN_DURATION; + + match is_selected(0, fn_idx) { + true => { + enforce_relative_distance(min_distance); + }, + false => (), + }; + + match is_selected(1, fn_idx) { + true => { + enforce_relative_duration(min_duration); + }, + false => (), + }; +} diff --git a/tests/stdlib/common/core.rs b/tests/stdlib/common/core.rs index fed6f99..f9c9e82 100644 --- a/tests/stdlib/common/core.rs +++ b/tests/stdlib/common/core.rs @@ -10,7 +10,7 @@ use simplex::simplicityhl::WitnessValues; use simplex::simplicityhl::elements::bitcoin::PublicKey; use simplex::simplicityhl::elements::opcodes::{self, All}; use simplex::simplicityhl::elements::script::Builder; -use simplex::simplicityhl::elements::{AssetId, Script, Txid}; +use simplex::simplicityhl::elements::{AssetId, Script, Sequence, Txid}; use simplex::transaction::partial_input::IssuanceInput; use simplex::transaction::{ FinalTransaction, NativeSignature, PartialInput, PartialOutput, ProgramInput, UTXO, @@ -28,13 +28,17 @@ pub enum Expect { AssertFailed, /// Execution reached a pruned branch (e.g. `unwrap(None)`). PrunedBranch, + /// Local execution succeeds, but the node rejects the transaction because a BIP68 + /// relative timelock declared in nSequence isn't yet satisfied on-chain. + BroadcastRejected, } impl Expect { - /// The exact broadcast error message for a failing expectation (`None` for `Ok`). + /// The exact broadcast error message for a local-execution failure + /// (`None` for `Ok` and `BroadcastRejected`). fn error_message(self) -> Option<&'static str> { match self { - Expect::Ok => None, + Expect::Ok | Expect::BroadcastRejected => None, Expect::AssertFailed => Some("Failed to prune program: Jet failed during execution"), Expect::PrunedBranch => { Some("Failed to prune program: Execution reached a pruned branch") @@ -332,15 +336,24 @@ pub fn assert_error_msg( result: Result, expect: Expect, ) -> anyhow::Result<()> { - match expect.error_message() { - None => { + match (expect, expect.error_message()) { + (Expect::BroadcastRejected, _) => { + let err = result + .expect_err("expected the node to reject the broadcast, but it succeeded") + .to_string(); + assert!( + err.contains("non-BIP68-final"), + "expected a `non-BIP68-final` rejection, got: {err}" + ); + } + (_, None) => { result?; } - Some(expected) => { + (_, Some(expected)) => { let err = result .expect_err("expected the spend to fail, but it succeeded") .to_string(); - assert!(err.contains(expected)); + assert!(err.contains(expected), "expected `{expected}`, got: {err}"); } }; @@ -397,3 +410,82 @@ where assert_error_msg(result, expect) } + +/// Construct a spend of the funded program UTXO whose input carries `sequence`. +/// +/// The sequence is set on the program input only. `FinalTransaction::set_sequence` would +/// also apply it to the fee inputs the signer adds, which would then be timelocked too. +pub fn construct_final_tx_with_sequence( + context: &simplex::TestContext, + program: &impl AsRef, + witness: W, + sequence: Sequence, +) -> anyhow::Result +where + W: Into + 'static, +{ + let signer = context.get_default_signer(); + let network = context.get_network(); + let program_script = &program.as_ref().get_script_pubkey(network); + let program_utxo = prepare_utxo(context, program_script, None)?; + + let mut ft = FinalTransaction::new(); + ft.add_program_input( + PartialInput::new(program_utxo.clone()).with_sequence(sequence), + ProgramInput::new(Box::new(program.as_ref().clone()), witness.into()), + None, + ); + + (ft, _) = add_mirror_output( + ft, + &program_utxo, + signer.get_blinding_public_key(), + network.policy_asset(), + )?; + + Ok(ft) +} + +/// Spend the funded program UTXO with `witness` and `sequence`. Return the broadcast result. +pub fn spend_with_sequence( + context: &simplex::TestContext, + program: &impl AsRef, + witness: W, + sequence: Sequence, +) -> anyhow::Result +where + W: Into + 'static, +{ + let ft = construct_final_tx_with_sequence(context, program, witness, sequence)?; + + Ok(context.get_default_signer().broadcast(&ft)?.to_string()) +} + +/// Fund + spend with the program input's nSequence set to `sequence` + assert the outcome. +/// +/// `blocks_to_mine` blocks are mined after the funding transaction confirms and before +/// the spend, so that a relative timelock in `sequence` can be satisfied on-chain. +pub fn run_with_sequence( + context: &simplex::TestContext, + program: impl AsRef, + witness: W, + sequence: Sequence, + blocks_to_mine: u64, + expect: Expect, +) -> anyhow::Result<()> +where + W: Into + 'static, +{ + fund(context, &program, DEFAULT_SEND_AMOUNT)?; + + if blocks_to_mine > 0 { + let tip = u64::from(context.get_default_provider().fetch_tip_height()?); + context + .get_network_utils() + .mine_until_height(tip + blocks_to_mine)?; + } + + let result = spend_with_sequence(context, &program, witness, sequence); + + assert_error_msg(result, expect) +} diff --git a/tests/stdlib/main.rs b/tests/stdlib/main.rs index a5c2be3..38f7713 100644 --- a/tests/stdlib/main.rs +++ b/tests/stdlib/main.rs @@ -3,6 +3,7 @@ mod common; mod asserts; mod binary; mod secp256k1; +mod timelocks; mod u1; mod u128; mod u16; diff --git a/tests/stdlib/timelocks.rs b/tests/stdlib/timelocks.rs new file mode 100644 index 0000000..f964e90 --- /dev/null +++ b/tests/stdlib/timelocks.rs @@ -0,0 +1,244 @@ +use simplex::program::ProgramTrait; +use simplex::simplicityhl::WitnessValues; +use simplex::simplicityhl::elements::Sequence; +use simplex::transaction::{FinalTransaction, PartialInput}; + +use crate::common::core::{Expect, fund, run_with_sequence}; +use crate::common::utxo_helper::DEFAULT_SEND_AMOUNT; + +use simplicityhl_std::artifacts::tests::timelocks::TimelocksProgram as TestTimelocksProgram; +use simplicityhl_std::artifacts::tests::timelocks::derived_timelocks::{ + TimelocksArguments as TestTimelocksArguments, TimelocksWitness as TestTimelocksWitness, +}; + +use FunctionToTest::*; + +/// Dispatch indices; these must match the `is_selected(N, ..)` arms in +/// `simf/tests/timelocks.simf`. +enum FunctionToTest { + EnforceRelativeDistance, + EnforceRelativeDuration, +} + +/// The minimum passed to the function under test in every case; only the sequence +/// value declared in the transaction varies between test cases. +const MIN_DISTANCE: u16 = 5; +const MIN_DURATION: u16 = 5; + +fn program() -> TestTimelocksProgram { + TestTimelocksProgram::new(&TestTimelocksArguments {}) +} + +fn witness(function: FunctionToTest) -> TestTimelocksWitness { + TestTimelocksWitness { + function_index: function as u8, + min_distance: MIN_DISTANCE, + min_duration: MIN_DURATION, + } +} + +// Raw BIP68 nSequence encodings. See rust-simplicity's `jets.c` (`parse_sequence`): +// bit 31 = disable flag (set => `None`), bit 22 = type flag (0 = blocks/Distance/Left, +// 1 = 512-second units/Duration/Right), low 16 bits = the declared value. +fn seq_disabled() -> Sequence { + Sequence::MAX +} + +fn seq_distance(blocks: u16) -> Sequence { + Sequence::from_consensus(u32::from(blocks)) +} + +fn seq_duration(units: u16) -> Sequence { + Sequence::from_consensus((1u32 << 22) | u32::from(units)) +} + +// ---------- shared: transaction version precondition ---------- + +#[simplex::test] +fn tx_version_below_2_fails(context: simplex::TestContext) -> anyhow::Result<()> { + // `FinalTransaction` always builds a version 2 transaction and doesn't expose a + // version setter, so the signer can't produce a version 1 transaction. Instead, + // extract the PSET, override its version, and call `ProgramTrait::finalize` + // directly: the same local Simplicity execution that `Signer::broadcast` runs + // before touching the network. + let program = program(); + let witness_values: WitnessValues = witness(EnforceRelativeDistance).into(); + + let script = fund(&context, &program, DEFAULT_SEND_AMOUNT)?; + let utxos = context + .get_default_provider() + .fetch_scripthash_utxos(&script)?; + + // `extract_pst` only reads the inputs and outputs, so the program and witness + // don't need to be attached here; they're passed to `finalize` below. + let mut ft = FinalTransaction::new(); + ft.add_input(PartialInput::new(utxos[0].clone()), None); + + let (mut pst, _secrets) = ft.extract_pst()?; + pst.global.tx_data.version = 1; + + let result = program + .as_ref() + .finalize(&pst, &witness_values, 0, context.get_network()); + + let err = result.expect_err("expected tx version < 2 to fail Simplicity execution"); + assert!( + err.to_string().contains("Jet failed during execution"), + "unexpected error: {err}" + ); + + Ok(()) +} + +// ---------- enforce_relative_distance ---------- + +#[simplex::test] +fn distance_disabled_sequence_is_pruned(context: simplex::TestContext) -> anyhow::Result<()> { + // Disable flag set -> jet::parse_sequence returns None -> unwrap(None) hits the + // pruned branch. Never reaches broadcast, so no mining needed. + run_with_sequence( + &context, + program(), + witness(EnforceRelativeDistance), + seq_disabled(), + 0, + Expect::PrunedBranch, + ) +} + +#[simplex::test] +fn distance_wrong_variant_is_pruned(context: simplex::TestContext) -> anyhow::Result<()> { + // Sequence declares a Duration (type flag set), but the function requires a + // Distance -> unwrap_left panics on Right(_). + run_with_sequence( + &context, + program(), + witness(EnforceRelativeDistance), + seq_duration(0), + 0, + Expect::PrunedBranch, + ) +} + +#[simplex::test] +fn distance_below_minimum_fails(context: simplex::TestContext) -> anyhow::Result<()> { + // Declared distance is below MIN_DISTANCE -> le_16 assert fails. + run_with_sequence( + &context, + program(), + witness(EnforceRelativeDistance), + seq_distance(MIN_DISTANCE - 1), + 0, + Expect::AssertFailed, + ) +} + +#[simplex::test] +fn distance_equal_minimum_succeeds(context: simplex::TestContext) -> anyhow::Result<()> { + // Mine enough blocks that the declared distance is satisfied on-chain, so the + // node's own BIP68 check at broadcast also passes. + run_with_sequence( + &context, + program(), + witness(EnforceRelativeDistance), + seq_distance(MIN_DISTANCE), + u64::from(MIN_DISTANCE), + Expect::Ok, + ) +} + +#[simplex::test] +fn distance_above_minimum_succeeds(context: simplex::TestContext) -> anyhow::Result<()> { + run_with_sequence( + &context, + program(), + witness(EnforceRelativeDistance), + seq_distance(MIN_DISTANCE + 1), + u64::from(MIN_DISTANCE + 1), + Expect::Ok, + ) +} + +#[simplex::test] +fn distance_sufficient_declared_insufficient_real_is_rejected( + context: simplex::TestContext, +) -> anyhow::Result<()> { + // The declared distance satisfies MIN_DISTANCE, so local execution succeeds, but no + // blocks are mined, so the real distance is short of the declared one and the node's + // BIP68 check rejects the broadcast. This shows the guarantee is enforced by + // consensus, not just by a value the spender writes into the transaction. + run_with_sequence( + &context, + program(), + witness(EnforceRelativeDistance), + seq_distance(MIN_DISTANCE), + 0, + Expect::BroadcastRejected, + ) +} + +// ---------- enforce_relative_duration ---------- + +#[simplex::test] +fn duration_disabled_sequence_is_pruned(context: simplex::TestContext) -> anyhow::Result<()> { + run_with_sequence( + &context, + program(), + witness(EnforceRelativeDuration), + seq_disabled(), + 0, + Expect::PrunedBranch, + ) +} + +#[simplex::test] +fn duration_wrong_variant_is_pruned(context: simplex::TestContext) -> anyhow::Result<()> { + // Sequence declares a Distance, but the function requires a Duration -> + // unwrap_right panics on Left(_). + run_with_sequence( + &context, + program(), + witness(EnforceRelativeDuration), + seq_distance(0), + 0, + Expect::PrunedBranch, + ) +} + +#[simplex::test] +fn duration_below_minimum_fails(context: simplex::TestContext) -> anyhow::Result<()> { + // This fails during local Simplicity execution, before the transaction reaches the + // node, so real chain state can't affect the outcome. Unlike the distance version, + // it can't also show that the spend fails when the real elapsed time does satisfy + // the declared duration: that needs median-time-past to advance, which requires a + // `setmocktime` helper that Simplex doesn't expose. + run_with_sequence( + &context, + program(), + witness(EnforceRelativeDuration), + seq_duration(MIN_DURATION - 1), + 0, + Expect::AssertFailed, + ) +} + +#[simplex::test] +fn duration_sufficient_declared_insufficient_real_is_rejected( + context: simplex::TestContext, +) -> anyhow::Result<()> { + // Duration counterpart of `distance_sufficient_declared_insufficient_real_is_rejected`. + // Median-time-past not having advanced far enough is the default state right after + // funding, so no mocktime is needed. + run_with_sequence( + &context, + program(), + witness(EnforceRelativeDuration), + seq_duration(MIN_DURATION), + 0, + Expect::BroadcastRejected, + ) +} + +// There are no `duration_*_minimum_succeeds` tests: they need median-time-past to +// advance by MIN_DURATION * 512 seconds, which regtest can't do without a +// `setmocktime` helper that Simplex doesn't expose. From 685f7fae74a1db99ad64d86b09ba2e8f6a3a45ea Mon Sep 17 00:00:00 2001 From: Seth Schoen Date: Wed, 12 Aug 2026 17:06:49 -0700 Subject: [PATCH 3/9] Update WISHLIST.md to note addition of timelock functions --- WISHLIST.md | 56 +---------------------------------------------------- 1 file changed, 1 insertion(+), 55 deletions(-) diff --git a/WISHLIST.md b/WISHLIST.md index 62ed2ad..5658344 100644 --- a/WISHLIST.md +++ b/WISHLIST.md @@ -103,60 +103,6 @@ Q. Are there (or could there be) standard protocols or conventions for (1) coven * `is_none`, `is_some` (as generic macros) * We currently have `is_none` where the type must be specified explicitly, but the compiler could figure out what it is and not require specifying it. * Oracle interpretation, once some oracle formats are standardized -* Relative timelocks (replacements for deprecated jets). - * Implementations: - * ```javascript - fn enforce_relative_distance(min_distance: Distance) { - // Assert that the current input is spent in a transaction that can - // only appear a distance of at least min_distance blocks after the input's - // UTXO. Panic otherwise. - - // Transaction version must be at least 2. - assert!(jet::le_32(2, jet::version())); - - // Fetch and parse sequence for current transaction - let parsed_seq: Option> = jet::parse_sequence(jet::current_sequence()); - - match parsed_seq { - // Failure condition - None => assert!(false), - // This is either a distance or a duration, but only a distance is - // acceptable here. - Some(actual_data: Either) => match actual_data { - // Is the actual distance greater than or equal to the specified min_distance? - Left(actual_distance: Distance) => assert!(jet::le_16(min_distance, actual_distance)), - // A duration is not acceptable in this context. - Right(actual_duration: Duration) => assert!(false), - }, - } - } - - fn enforce_relative_duration(min_duration: Duration) { - // Assert that the current input is spent in a transaction that can only - // appear a duration of at least min_duration units of 512 seconds after - // the input's UTXO. Panic otherwise. - - // Transaction version must be at least 2. - assert!(jet::le_32(2, jet::version())); - - // Fetch and parse sequence for current transaction - let parsed_seq: Option> = jet::parse_sequence(jet::current_sequence()); - - match parsed_seq { - // Failure condition - None => assert!(false), - // This is either a distance or a duration, but only a duration is - // acceptable here. - Some(actual_data: Either) => match actual_data { - // A distance is not acceptable in this context. - Left(actual_distance: Distance) => assert!(false), - // Is the actual duration greater than or equal to the specified min_duration? - Right(actual_duration: Duration) => assert!(jet::le_16(min_duration, actual_duration)), - }, - } - } - - ``` - * See also +√ Relative timelocks (replacements for deprecated jets). See also * Fee management? * More convenient SHA256? From bc76cda883cb1036fa75aa3d59860efe9a98cfcb Mon Sep 17 00:00:00 2001 From: Seth Schoen Date: Fri, 20 Nov 2026 14:30:57 -0800 Subject: [PATCH 4/9] Note timelock functions in CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ca0e3c7..6f31db0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ - Conversion and bit functions for `u2` and `u4`. - Functions for asserting script hashes. - Fuzz tests for `secp256k1` operations. +- `enforce_relative_distance` and `enforce_relative_duration`, replacements for the deprecated `jet::check_lock_distance` and `jet::check_lock_duration`. ### Changed - Bumped Simplex to 0.2.0. From c8163415254700c475065e9d923031e145af97fa Mon Sep 17 00:00:00 2001 From: Seth Schoen Date: Wed, 18 Nov 2026 15:43:03 -0800 Subject: [PATCH 5/9] Document timelock functions in stdlib.json Co-Authored-By: Claude Opus 5.5 --- docs/stdlib.json | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/stdlib.json b/docs/stdlib.json index 2ec57e2..ff405b6 100644 --- a/docs/stdlib.json +++ b/docs/stdlib.json @@ -2035,5 +2035,19 @@ "input_type": "u256", "output_type": "u128", "description": "Narrow a `u256` value to `u128`.\n\n## Panics\nPanics if the value does not fit in `u128`." + }, + { + "simplicityhl_name": "enforce_relative_distance", + "section": "Timelocks", + "input_type": "Distance", + "output_type": "()", + "description": "Asserts that the current input has a relative timelock of at least `min_distance` blocks, so the transaction can't be included in a block until at least that many blocks after the block that contains the UTXO being spent. Replaces the deprecated `jet::check_lock_distance`.\n\n## Panics\nPanics if the transaction version is less than 2, if the input's sequence number doesn't declare a relative timelock in blocks, or if the declared distance is less than `min_distance`." + }, + { + "simplicityhl_name": "enforce_relative_duration", + "section": "Timelocks", + "input_type": "Duration", + "output_type": "()", + "description": "Asserts that the current input has a relative timelock of at least `min_duration` units of 512 seconds, so the transaction can't be included in a block until at least that much time after the block that contains the UTXO being spent. Replaces the deprecated `jet::check_lock_duration`.\n\n## Panics\nPanics if the transaction version is less than 2, if the input's sequence number doesn't declare a relative timelock in units of 512 seconds, or if the declared duration is less than `min_duration`." } ] \ No newline at end of file From 56d03877bc1f450062404e7a74f5c85a1293926d Mon Sep 17 00:00:00 2001 From: Seth Schoen Date: Wed, 18 Nov 2026 22:17:25 -0800 Subject: [PATCH 6/9] Correct type annotation in timelocks.simf --- simf/lib/timelocks.simf | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/simf/lib/timelocks.simf b/simf/lib/timelocks.simf index c625ce2..39df82b 100644 --- a/simf/lib/timelocks.simf +++ b/simf/lib/timelocks.simf @@ -19,7 +19,8 @@ pub fn enforce_relative_distance(min_distance: Distance) { pub fn enforce_relative_duration(min_duration: Duration) { // Assert that the current input is spent in a transaction that can // only appear a duration of at least min_duration units of 512 - // seconds after the creation of the block containing the input UTXO. + // seconds, measured by median time past, after the block containing + // the input UTXO. // Panic otherwise. // This is a replacement for the deprecated jet::check_lock_duration. @@ -29,7 +30,7 @@ pub fn enforce_relative_duration(min_duration: Duration) { // Fetch and parse sequence let actual_data: Either = unwrap(jet::parse_sequence(jet::current_sequence())); - let actual_duration: Duration = unwrap_right::(actual_data); + let actual_duration: Duration = unwrap_right::(actual_data); assert!(jet::le_16(min_duration, actual_duration)); } From c09a095ea5671cd86a3ba6e3ad8440a1aefd364c Mon Sep 17 00:00:00 2001 From: Seth Schoen Date: Wed, 18 Nov 2026 22:17:49 -0800 Subject: [PATCH 7/9] Documentation/comment fixes for timelocks patch --- WISHLIST.md | 2 +- docs/stdlib.json | 2 +- tests/stdlib/timelocks.rs | 20 +++++++++++--------- 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/WISHLIST.md b/WISHLIST.md index 5658344..f4a668e 100644 --- a/WISHLIST.md +++ b/WISHLIST.md @@ -103,6 +103,6 @@ Q. Are there (or could there be) standard protocols or conventions for (1) coven * `is_none`, `is_some` (as generic macros) * We currently have `is_none` where the type must be specified explicitly, but the compiler could figure out what it is and not require specifying it. * Oracle interpretation, once some oracle formats are standardized -√ Relative timelocks (replacements for deprecated jets). See also +* ~~Relative timelocks (replacements for deprecated jets)~~ (done; see `simf/lib/timelocks.simf`). See also * Fee management? * More convenient SHA256? diff --git a/docs/stdlib.json b/docs/stdlib.json index ff405b6..596c63d 100644 --- a/docs/stdlib.json +++ b/docs/stdlib.json @@ -2048,6 +2048,6 @@ "section": "Timelocks", "input_type": "Duration", "output_type": "()", - "description": "Asserts that the current input has a relative timelock of at least `min_duration` units of 512 seconds, so the transaction can't be included in a block until at least that much time after the block that contains the UTXO being spent. Replaces the deprecated `jet::check_lock_duration`.\n\n## Panics\nPanics if the transaction version is less than 2, if the input's sequence number doesn't declare a relative timelock in units of 512 seconds, or if the declared duration is less than `min_duration`." + "description": "Asserts that the current input has a relative timelock of at least `min_duration` units of 512 seconds, so the transaction can't be included in a block until at least that much time, measured by median time past, after the block that contains the UTXO being spent. Replaces the deprecated `jet::check_lock_duration`.\n\n## Panics\nPanics if the transaction version is less than 2, if the input's sequence number doesn't declare a relative timelock in units of 512 seconds, or if the declared duration is less than `min_duration`." } ] \ No newline at end of file diff --git a/tests/stdlib/timelocks.rs b/tests/stdlib/timelocks.rs index f964e90..65fb7e3 100644 --- a/tests/stdlib/timelocks.rs +++ b/tests/stdlib/timelocks.rs @@ -109,7 +109,7 @@ fn distance_disabled_sequence_is_pruned(context: simplex::TestContext) -> anyhow #[simplex::test] fn distance_wrong_variant_is_pruned(context: simplex::TestContext) -> anyhow::Result<()> { // Sequence declares a Duration (type flag set), but the function requires a - // Distance -> unwrap_left panics on Right(_). + // Distance -> unwrap_left on Right(_) hits the pruned branch. run_with_sequence( &context, program(), @@ -122,13 +122,15 @@ fn distance_wrong_variant_is_pruned(context: simplex::TestContext) -> anyhow::Re #[simplex::test] fn distance_below_minimum_fails(context: simplex::TestContext) -> anyhow::Result<()> { - // Declared distance is below MIN_DISTANCE -> le_16 assert fails. + // Declared distance is below MIN_DISTANCE -> le_16 assert fails. MIN_DISTANCE blocks + // are mined first, so the spend fails even though the real distance would satisfy + // the minimum: only the declared value counts. run_with_sequence( &context, program(), witness(EnforceRelativeDistance), seq_distance(MIN_DISTANCE - 1), - 0, + u64::from(MIN_DISTANCE), Expect::AssertFailed, ) } @@ -194,7 +196,7 @@ fn duration_disabled_sequence_is_pruned(context: simplex::TestContext) -> anyhow #[simplex::test] fn duration_wrong_variant_is_pruned(context: simplex::TestContext) -> anyhow::Result<()> { // Sequence declares a Distance, but the function requires a Duration -> - // unwrap_right panics on Left(_). + // unwrap_right on Left(_) hits the pruned branch. run_with_sequence( &context, program(), @@ -210,8 +212,8 @@ fn duration_below_minimum_fails(context: simplex::TestContext) -> anyhow::Result // This fails during local Simplicity execution, before the transaction reaches the // node, so real chain state can't affect the outcome. Unlike the distance version, // it can't also show that the spend fails when the real elapsed time does satisfy - // the declared duration: that needs median-time-past to advance, which requires a - // `setmocktime` helper that Simplex doesn't expose. + // the declared duration: that needs median-time-past to advance, which requires + // mining blocks with later timestamps, and Simplex doesn't expose a way to do that. run_with_sequence( &context, program(), @@ -228,7 +230,7 @@ fn duration_sufficient_declared_insufficient_real_is_rejected( ) -> anyhow::Result<()> { // Duration counterpart of `distance_sufficient_declared_insufficient_real_is_rejected`. // Median-time-past not having advanced far enough is the default state right after - // funding, so no mocktime is needed. + // funding, so nothing needs to be done to the chain's timestamps. run_with_sequence( &context, program(), @@ -240,5 +242,5 @@ fn duration_sufficient_declared_insufficient_real_is_rejected( } // There are no `duration_*_minimum_succeeds` tests: they need median-time-past to -// advance by MIN_DURATION * 512 seconds, which regtest can't do without a -// `setmocktime` helper that Simplex doesn't expose. +// advance by MIN_DURATION * 512 seconds, which requires mining blocks with later +// timestamps, and Simplex doesn't expose a way to do that. From d84e48072e6900f74a7fefc0253e0b6ab8a372df Mon Sep 17 00:00:00 2001 From: Seth Schoen Date: Wed, 18 Nov 2026 22:26:50 -0800 Subject: [PATCH 8/9] Fix formatting per `simplex fmt` --- simf/lib/timelocks.simf | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/simf/lib/timelocks.simf b/simf/lib/timelocks.simf index 39df82b..c0d137a 100644 --- a/simf/lib/timelocks.simf +++ b/simf/lib/timelocks.simf @@ -10,7 +10,9 @@ pub fn enforce_relative_distance(min_distance: Distance) { assert!(jet::le_32(2, jet::version())); // Fetch and parse sequence - let actual_data: Either = unwrap(jet::parse_sequence(jet::current_sequence())); + let actual_data: Either = unwrap( + jet::parse_sequence(jet::current_sequence()) + ); let actual_distance: Distance = unwrap_left::(actual_data); assert!(jet::le_16(min_distance, actual_distance)); @@ -29,7 +31,10 @@ pub fn enforce_relative_duration(min_duration: Duration) { assert!(jet::le_32(2, jet::version())); // Fetch and parse sequence - let actual_data: Either = unwrap(jet::parse_sequence(jet::current_sequence())); + let actual_data: Either = unwrap( + jet::parse_sequence(jet::current_sequence()) + ); + let actual_duration: Duration = unwrap_right::(actual_data); assert!(jet::le_16(min_duration, actual_duration)); From 3a1932d132ccdb4ecd807cf40fe3b4ac8ee8cc49 Mon Sep 17 00:00:00 2001 From: Seth Schoen Date: Fri, 20 Nov 2026 14:29:11 -0800 Subject: [PATCH 9/9] Address review feedback on timelocks - Move function comments into `///` doc comments matching the library style. - Factor the shared version check and sequence parsing into a private helper. - Trim test comments that restated the code. - Make tx_version_below_2_fails declare a sufficient timelock, so the version check is the only thing that can reject it. - Explain what's wrong with the deprecated jets in stdlib.json. - Fix the timelocks.md link in WISHLIST.md. Co-Authored-By: Claude Opus 5.5 --- WISHLIST.md | 2 +- docs/stdlib.json | 4 +-- simf/lib/timelocks.simf | 45 +++++++++---------------------- tests/stdlib/timelocks.rs | 57 +++++++++------------------------------ 4 files changed, 27 insertions(+), 81 deletions(-) diff --git a/WISHLIST.md b/WISHLIST.md index f4a668e..524b056 100644 --- a/WISHLIST.md +++ b/WISHLIST.md @@ -103,6 +103,6 @@ Q. Are there (or could there be) standard protocols or conventions for (1) coven * `is_none`, `is_some` (as generic macros) * We currently have `is_none` where the type must be specified explicitly, but the compiler could figure out what it is and not require specifying it. * Oracle interpretation, once some oracle formats are standardized -* ~~Relative timelocks (replacements for deprecated jets)~~ (done; see `simf/lib/timelocks.simf`). See also +* ~~Relative timelocks (replacements for deprecated jets)~~ (done; see `simf/lib/timelocks.simf`). See also * Fee management? * More convenient SHA256? diff --git a/docs/stdlib.json b/docs/stdlib.json index 596c63d..4d40070 100644 --- a/docs/stdlib.json +++ b/docs/stdlib.json @@ -2041,13 +2041,13 @@ "section": "Timelocks", "input_type": "Distance", "output_type": "()", - "description": "Asserts that the current input has a relative timelock of at least `min_distance` blocks, so the transaction can't be included in a block until at least that many blocks after the block that contains the UTXO being spent. Replaces the deprecated `jet::check_lock_distance`.\n\n## Panics\nPanics if the transaction version is less than 2, if the input's sequence number doesn't declare a relative timelock in blocks, or if the declared distance is less than `min_distance`." + "description": "Asserts that the current input has a relative timelock of at least `min_distance` blocks, so the transaction can't be included in a block until at least that many blocks after the block that contains the UTXO being spent. Use this instead of the deprecated `jet::check_lock_distance`, which doesn't enforce a timelock on the input being spent: it passes if any input in the transaction declares a long enough relative timelock.\n\n## Panics\nPanics if the transaction version is less than 2, if the input's sequence number doesn't declare a relative timelock in blocks, or if the declared distance is less than `min_distance`." }, { "simplicityhl_name": "enforce_relative_duration", "section": "Timelocks", "input_type": "Duration", "output_type": "()", - "description": "Asserts that the current input has a relative timelock of at least `min_duration` units of 512 seconds, so the transaction can't be included in a block until at least that much time, measured by median time past, after the block that contains the UTXO being spent. Replaces the deprecated `jet::check_lock_duration`.\n\n## Panics\nPanics if the transaction version is less than 2, if the input's sequence number doesn't declare a relative timelock in units of 512 seconds, or if the declared duration is less than `min_duration`." + "description": "Asserts that the current input has a relative timelock of at least `min_duration` units of 512 seconds, so the transaction can't be included in a block until at least that much time, measured by median time past, after the block that contains the UTXO being spent. Use this instead of the deprecated `jet::check_lock_duration`, which doesn't enforce a timelock on the input being spent: it passes if any input in the transaction declares a long enough relative timelock.\n\n## Panics\nPanics if the transaction version is less than 2, if the input's sequence number doesn't declare a relative timelock in units of 512 seconds, or if the declared duration is less than `min_duration`." } ] \ No newline at end of file diff --git a/simf/lib/timelocks.simf b/simf/lib/timelocks.simf index c0d137a..c4cc0f3 100644 --- a/simf/lib/timelocks.simf +++ b/simf/lib/timelocks.simf @@ -1,41 +1,20 @@ -pub fn enforce_relative_distance(min_distance: Distance) { - // Assert that the current input is spent in a transaction that can - // only appear a distance of at least min_distance blocks after the - // block containing the input UTXO. - // Panic otherwise. - - // This is a replacement for the deprecated jet::check_lock_distance. - - // Transaction version must be at least 2. +/// Returns the relative timelock declared by the current input's sequence number. +/// Panics if the transaction version is less than 2 or if the sequence number doesn't declare a relative timelock. +fn current_relative_lock() -> Either { assert!(jet::le_32(2, jet::version())); + unwrap(jet::parse_sequence(jet::current_sequence())) +} - // Fetch and parse sequence - let actual_data: Either = unwrap( - jet::parse_sequence(jet::current_sequence()) - ); - let actual_distance: Distance = unwrap_left::(actual_data); - +/// Asserts that the current input has a relative timelock of at least `min_distance` blocks. +/// Panics if the transaction version is less than 2, if the input's sequence number doesn't declare a relative timelock in blocks, or if that timelock is less than `min_distance`. +pub fn enforce_relative_distance(min_distance: Distance) { + let actual_distance: Distance = unwrap_left::(current_relative_lock()); assert!(jet::le_16(min_distance, actual_distance)); } +/// Asserts that the current input has a relative timelock of at least `min_duration` units of 512 seconds. +/// Panics if the transaction version is less than 2, if the input's sequence number doesn't declare a relative timelock in 512-second units, or if that timelock is less than `min_duration`. pub fn enforce_relative_duration(min_duration: Duration) { - // Assert that the current input is spent in a transaction that can - // only appear a duration of at least min_duration units of 512 - // seconds, measured by median time past, after the block containing - // the input UTXO. - // Panic otherwise. - - // This is a replacement for the deprecated jet::check_lock_duration. - - // Transaction version must be at least 2. - assert!(jet::le_32(2, jet::version())); - - // Fetch and parse sequence - let actual_data: Either = unwrap( - jet::parse_sequence(jet::current_sequence()) - ); - - let actual_duration: Duration = unwrap_right::(actual_data); - + let actual_duration: Duration = unwrap_right::(current_relative_lock()); assert!(jet::le_16(min_duration, actual_duration)); } diff --git a/tests/stdlib/timelocks.rs b/tests/stdlib/timelocks.rs index 65fb7e3..317d743 100644 --- a/tests/stdlib/timelocks.rs +++ b/tests/stdlib/timelocks.rs @@ -20,8 +20,6 @@ enum FunctionToTest { EnforceRelativeDuration, } -/// The minimum passed to the function under test in every case; only the sequence -/// value declared in the transaction varies between test cases. const MIN_DISTANCE: u16 = 5; const MIN_DURATION: u16 = 5; @@ -37,9 +35,6 @@ fn witness(function: FunctionToTest) -> TestTimelocksWitness { } } -// Raw BIP68 nSequence encodings. See rust-simplicity's `jets.c` (`parse_sequence`): -// bit 31 = disable flag (set => `None`), bit 22 = type flag (0 = blocks/Distance/Left, -// 1 = 512-second units/Duration/Right), low 16 bits = the declared value. fn seq_disabled() -> Sequence { Sequence::MAX } @@ -48,19 +43,16 @@ fn seq_distance(blocks: u16) -> Sequence { Sequence::from_consensus(u32::from(blocks)) } +/// Sets the BIP68 type flag (bit 22), so `units` counts 512-second intervals. fn seq_duration(units: u16) -> Sequence { Sequence::from_consensus((1u32 << 22) | u32::from(units)) } -// ---------- shared: transaction version precondition ---------- - #[simplex::test] fn tx_version_below_2_fails(context: simplex::TestContext) -> anyhow::Result<()> { - // `FinalTransaction` always builds a version 2 transaction and doesn't expose a - // version setter, so the signer can't produce a version 1 transaction. Instead, - // extract the PSET, override its version, and call `ProgramTrait::finalize` - // directly: the same local Simplicity execution that `Signer::broadcast` runs - // before touching the network. + // A version 1 transaction can declare a timelock that consensus won't enforce. + // FinalTransaction always builds version 2, so set the version on the PSET + // and finalize directly. let program = program(); let witness_values: WitnessValues = witness(EnforceRelativeDistance).into(); @@ -69,10 +61,11 @@ fn tx_version_below_2_fails(context: simplex::TestContext) -> anyhow::Result<()> .get_default_provider() .fetch_scripthash_utxos(&script)?; - // `extract_pst` only reads the inputs and outputs, so the program and witness - // don't need to be attached here; they're passed to `finalize` below. let mut ft = FinalTransaction::new(); - ft.add_input(PartialInput::new(utxos[0].clone()), None); + ft.add_input( + PartialInput::new(utxos[0].clone()).with_sequence(seq_distance(MIN_DISTANCE)), + None, + ); let (mut pst, _secrets) = ft.extract_pst()?; pst.global.tx_data.version = 1; @@ -90,12 +83,8 @@ fn tx_version_below_2_fails(context: simplex::TestContext) -> anyhow::Result<()> Ok(()) } -// ---------- enforce_relative_distance ---------- - #[simplex::test] fn distance_disabled_sequence_is_pruned(context: simplex::TestContext) -> anyhow::Result<()> { - // Disable flag set -> jet::parse_sequence returns None -> unwrap(None) hits the - // pruned branch. Never reaches broadcast, so no mining needed. run_with_sequence( &context, program(), @@ -108,8 +97,6 @@ fn distance_disabled_sequence_is_pruned(context: simplex::TestContext) -> anyhow #[simplex::test] fn distance_wrong_variant_is_pruned(context: simplex::TestContext) -> anyhow::Result<()> { - // Sequence declares a Duration (type flag set), but the function requires a - // Distance -> unwrap_left on Right(_) hits the pruned branch. run_with_sequence( &context, program(), @@ -122,9 +109,7 @@ fn distance_wrong_variant_is_pruned(context: simplex::TestContext) -> anyhow::Re #[simplex::test] fn distance_below_minimum_fails(context: simplex::TestContext) -> anyhow::Result<()> { - // Declared distance is below MIN_DISTANCE -> le_16 assert fails. MIN_DISTANCE blocks - // are mined first, so the spend fails even though the real distance would satisfy - // the minimum: only the declared value counts. + // Blocks are mined so that the real distance suffices: only the declared value counts. run_with_sequence( &context, program(), @@ -137,8 +122,6 @@ fn distance_below_minimum_fails(context: simplex::TestContext) -> anyhow::Result #[simplex::test] fn distance_equal_minimum_succeeds(context: simplex::TestContext) -> anyhow::Result<()> { - // Mine enough blocks that the declared distance is satisfied on-chain, so the - // node's own BIP68 check at broadcast also passes. run_with_sequence( &context, program(), @@ -165,10 +148,7 @@ fn distance_above_minimum_succeeds(context: simplex::TestContext) -> anyhow::Res fn distance_sufficient_declared_insufficient_real_is_rejected( context: simplex::TestContext, ) -> anyhow::Result<()> { - // The declared distance satisfies MIN_DISTANCE, so local execution succeeds, but no - // blocks are mined, so the real distance is short of the declared one and the node's - // BIP68 check rejects the broadcast. This shows the guarantee is enforced by - // consensus, not just by a value the spender writes into the transaction. + // Local execution succeeds; the node's BIP68 check rejects the broadcast. run_with_sequence( &context, program(), @@ -179,8 +159,6 @@ fn distance_sufficient_declared_insufficient_real_is_rejected( ) } -// ---------- enforce_relative_duration ---------- - #[simplex::test] fn duration_disabled_sequence_is_pruned(context: simplex::TestContext) -> anyhow::Result<()> { run_with_sequence( @@ -195,8 +173,6 @@ fn duration_disabled_sequence_is_pruned(context: simplex::TestContext) -> anyhow #[simplex::test] fn duration_wrong_variant_is_pruned(context: simplex::TestContext) -> anyhow::Result<()> { - // Sequence declares a Distance, but the function requires a Duration -> - // unwrap_right on Left(_) hits the pruned branch. run_with_sequence( &context, program(), @@ -209,11 +185,6 @@ fn duration_wrong_variant_is_pruned(context: simplex::TestContext) -> anyhow::Re #[simplex::test] fn duration_below_minimum_fails(context: simplex::TestContext) -> anyhow::Result<()> { - // This fails during local Simplicity execution, before the transaction reaches the - // node, so real chain state can't affect the outcome. Unlike the distance version, - // it can't also show that the spend fails when the real elapsed time does satisfy - // the declared duration: that needs median-time-past to advance, which requires - // mining blocks with later timestamps, and Simplex doesn't expose a way to do that. run_with_sequence( &context, program(), @@ -228,9 +199,6 @@ fn duration_below_minimum_fails(context: simplex::TestContext) -> anyhow::Result fn duration_sufficient_declared_insufficient_real_is_rejected( context: simplex::TestContext, ) -> anyhow::Result<()> { - // Duration counterpart of `distance_sufficient_declared_insufficient_real_is_rejected`. - // Median-time-past not having advanced far enough is the default state right after - // funding, so nothing needs to be done to the chain's timestamps. run_with_sequence( &context, program(), @@ -241,6 +209,5 @@ fn duration_sufficient_declared_insufficient_real_is_rejected( ) } -// There are no `duration_*_minimum_succeeds` tests: they need median-time-past to -// advance by MIN_DURATION * 512 seconds, which requires mining blocks with later -// timestamps, and Simplex doesn't expose a way to do that. +// Currently, the duration happy path can't be tested: it needs median-time-past to +// advance, and Simplex can't mine blocks with later timestamps.