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. 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/WISHLIST.md b/WISHLIST.md index 62ed2ad..524b056 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)~~ (done; see `simf/lib/timelocks.simf`). See also * Fee management? * More convenient SHA256? diff --git a/docs/stdlib.json b/docs/stdlib.json index 2ec57e2..4d40070 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. 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. 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 new file mode 100644 index 0000000..c4cc0f3 --- /dev/null +++ b/simf/lib/timelocks.simf @@ -0,0 +1,20 @@ +/// 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())) +} + +/// 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) { + let actual_duration: Duration = unwrap_right::(current_relative_lock()); + assert!(jet::le_16(min_duration, actual_duration)); +} 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..317d743 --- /dev/null +++ b/tests/stdlib/timelocks.rs @@ -0,0 +1,213 @@ +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, +} + +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, + } +} + +fn seq_disabled() -> Sequence { + Sequence::MAX +} + +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)) +} + +#[simplex::test] +fn tx_version_below_2_fails(context: simplex::TestContext) -> anyhow::Result<()> { + // 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(); + + let script = fund(&context, &program, DEFAULT_SEND_AMOUNT)?; + let utxos = context + .get_default_provider() + .fetch_scripthash_utxos(&script)?; + + let mut ft = FinalTransaction::new(); + 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; + + 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(()) +} + +#[simplex::test] +fn distance_disabled_sequence_is_pruned(context: simplex::TestContext) -> anyhow::Result<()> { + 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<()> { + 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<()> { + // Blocks are mined so that the real distance suffices: only the declared value counts. + run_with_sequence( + &context, + program(), + witness(EnforceRelativeDistance), + seq_distance(MIN_DISTANCE - 1), + u64::from(MIN_DISTANCE), + Expect::AssertFailed, + ) +} + +#[simplex::test] +fn distance_equal_minimum_succeeds(context: simplex::TestContext) -> anyhow::Result<()> { + 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<()> { + // Local execution succeeds; the node's BIP68 check rejects the broadcast. + run_with_sequence( + &context, + program(), + witness(EnforceRelativeDistance), + seq_distance(MIN_DISTANCE), + 0, + Expect::BroadcastRejected, + ) +} + +#[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<()> { + 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<()> { + 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<()> { + run_with_sequence( + &context, + program(), + witness(EnforceRelativeDuration), + seq_duration(MIN_DURATION), + 0, + Expect::BroadcastRejected, + ) +} + +// 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.