From e4e8298fcde7e87798f250c32514386e7b563fba Mon Sep 17 00:00:00 2001 From: Dave Hrycyszyn Date: Thu, 25 Jul 2024 19:12:39 +0100 Subject: [PATCH] Adding an htlc model file --- side-node/src/bitcoin/htlc.rs | 80 +++++++++++++++++++++++++++++++++++ side-node/src/bitcoin/mod.rs | 1 + 2 files changed, 81 insertions(+) create mode 100644 side-node/src/bitcoin/htlc.rs diff --git a/side-node/src/bitcoin/htlc.rs b/side-node/src/bitcoin/htlc.rs new file mode 100644 index 0000000..8feece7 --- /dev/null +++ b/side-node/src/bitcoin/htlc.rs @@ -0,0 +1,80 @@ +use std::str::FromStr; + +use bdk_wallet::miniscript::descriptor::Wsh; +use bdk_wallet::miniscript::policy::{self, Concrete, Liftable}; +use bitcoin::Address; + +/// A hash time locked contract between two parties. +/// +/// If the hash preimage of the hashlock is revealed, the value is sent to the redeem_identity. +/// +/// Alternately, if the refund timelock expires, the value can be refunded to the refund_identity. +pub(crate) struct Htlc { + value: u64, + redeem_identity: Address, + hashlock: String, + refund_timelock: u64, + refund_indentiy: Address, +} + +impl Htlc { + /// Create a new HTLC. + pub(crate) fn new( + value: u64, + redeem_identity: Address, + hashlock: String, + refund_timelock: u64, + refund_indentiy: Address, + ) -> Self { + Self { + value, + redeem_identity, + hashlock, + refund_timelock, + refund_indentiy, + } + } + + pub(crate) fn to_miniscript_policy(&self) -> policy::Concrete { + Concrete::::from_str(&format!( + "or(10@and(sha256({secret_hash}),pk({redeem_identity})),1@and(older({expiry}),pk({refund_identity})))", + secret_hash = self.hashlock, + redeem_identity = self.redeem_identity, + refund_identity = self.refund_indentiy, + expiry = self.refund_timelock + )).expect("Policy compilation only fails on resource limits or mixed timelocks") + } + + pub(crate) fn to_miniscript_descriptor(&self) -> Wsh { + Wsh::new( + self.to_miniscript_policy() + .compile() + .expect("Policy compilation only fails on resource limits or mixed timelocks"), + ) + .expect("Resource limits") + } + + /// Translate the HTLC to Bitcoin op_codes. + pub(crate) fn to_script(&self) -> String { + format!( + "OP_IF + OP_SHA256 + {} + OP_EQUALVERIFY + OP_DUP + OP_HASH160 + {} + OP_ELSE + {} + OP_CHECKLOCKTIMEVERIFY + OP_DROP + OP_DUP + OP_HASH160 + {} + OP_ENDIF + OP_EQUALVERIFY + OP_CHECKSIG", + self.hashlock, self.redeem_identity, self.refund_timelock, self.refund_indentiy + ) + } +} diff --git a/side-node/src/bitcoin/mod.rs b/side-node/src/bitcoin/mod.rs index 784440b..50092fa 100644 --- a/side-node/src/bitcoin/mod.rs +++ b/side-node/src/bitcoin/mod.rs @@ -1,3 +1,4 @@ pub mod clients; pub mod driver; +pub mod htlc; pub mod keys;