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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
56 changes: 1 addition & 55 deletions WISHLIST.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>` 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<Either<Distance, Duration>> = 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<Distance, Duration>) => 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<Either<Distance, Duration>> = 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<Distance, Duration>) => 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 <https://docs.simplicity-lang.org/documentation/timelock>
* ~~Relative timelocks (replacements for deprecated jets)~~ (done; see `simf/lib/timelocks.simf`). See also <https://docs.simplicity-lang.org/documentation/timelocks>
* Fee management?
* More convenient SHA256?
14 changes: 14 additions & 0 deletions docs/stdlib.json
Original file line number Diff line number Diff line change
Expand Up @@ -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`."
}
]
20 changes: 20 additions & 0 deletions simf/lib/timelocks.simf
Original file line number Diff line number Diff line change
@@ -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<Distance, Duration> {
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::<Duration>(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::<Distance>(current_relative_lock());
assert!(jet::le_16(min_duration, actual_duration));
}
24 changes: 24 additions & 0 deletions simf/tests/timelocks.simf
Original file line number Diff line number Diff line change
@@ -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 => (),
};
}
106 changes: 99 additions & 7 deletions tests/stdlib/common/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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")
Expand Down Expand Up @@ -332,15 +336,24 @@ pub fn assert_error_msg(
result: Result<String, anyhow::Error>,
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}");
}
};

Expand Down Expand Up @@ -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<W>(
context: &simplex::TestContext,
program: &impl AsRef<Program>,
witness: W,
sequence: Sequence,
) -> anyhow::Result<FinalTransaction>
where
W: Into<WitnessValues> + '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<W>(
context: &simplex::TestContext,
program: &impl AsRef<Program>,
witness: W,
sequence: Sequence,
) -> anyhow::Result<String>
where
W: Into<WitnessValues> + '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<W>(
context: &simplex::TestContext,
program: impl AsRef<Program>,
witness: W,
sequence: Sequence,
blocks_to_mine: u64,
expect: Expect,
) -> anyhow::Result<()>
where
W: Into<WitnessValues> + '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)
}
1 change: 1 addition & 0 deletions tests/stdlib/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ mod common;
mod asserts;
mod binary;
mod secp256k1;
mod timelocks;
mod u1;
mod u128;
mod u16;
Expand Down
Loading
Loading