Skip to main content

torvyon_core/
atomic_swap.rs

1//! Atomic swaps built from two HTLCs that share one secret hash.
2//!
3//! Same chain (both locks on Torvyon): [`AtomicSwap::locks`].
4//!
5//! Across chains (one lock on Torvyon, the other on a different chain whose
6//! HTLC is built with that chain's own tools): express each deadline as a
7//! height on its own chain with [`ChainClock::height_after`], check the order
8//! with [`AtomicSwap::check_cross_chain`], and build the Torvyon side with
9//! [`AtomicSwap::funding_lock`].
10//!
11//! The rule in both cases: the **initiator** (who created the secret) must be
12//! able to refund only well **after** the participant's refund opens, so the
13//! participant always has time to claim once the secret is revealed.
14
15use zeroize::Zeroize;
16
17use crate::{
18    conditions::{Condition, ConditionTemplates, HtlcTemplate},
19    hash::sha256,
20    Error, PublicKey, Result,
21};
22
23/// A fresh swap secret. The secret is wiped from memory on drop.
24pub struct SwapSecret {
25    /// 32 random bytes. Keep private until claiming.
26    pub secret: [u8; 32],
27    /// SHA-256 of the secret — safe to share.
28    pub hash: [u8; 32],
29}
30
31impl Drop for SwapSecret {
32    fn drop(&mut self) {
33        self.secret.zeroize();
34    }
35}
36
37/// Parameters for a swap where both locks are on the same chain.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct AtomicSwapParams {
40    /// SHA-256 of the initiator's secret.
41    pub secret_hash: [u8; 32],
42    /// Initiator: knows the secret and claims the participant's lock first.
43    pub initiator_key: PublicKey,
44    /// Participant: learns the secret from the initiator's claim.
45    pub participant_key: PublicKey,
46    /// Height after which the initiator can refund its own lock.
47    pub initiator_refund_height: u64,
48    /// Height after which the participant can refund. Must be earlier.
49    pub participant_refund_height: u64,
50    /// Blocks the participant needs to claim after the secret is revealed.
51    pub safety_margin_blocks: u64,
52}
53
54/// The two locks of a same-chain swap.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct SwapLocks {
57    /// Funded by the initiator; the participant claims it with the secret.
58    pub initiator_lock: Condition,
59    /// Funded by the participant; the initiator claims it with the secret.
60    pub participant_lock: Condition,
61}
62
63/// Block timing of one chain, for converting durations into heights.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub struct ChainClock {
66    /// Current tip height.
67    pub tip: u64,
68    /// Average seconds per block (Torvyon mainnet 20, testnet 60).
69    pub block_seconds: u64,
70}
71
72impl ChainClock {
73    /// Height reached about `seconds` from now (rounded up).
74    pub fn height_after(&self, seconds: u64) -> u64 {
75        let blocks = seconds.div_ceil(self.block_seconds.max(1));
76        self.tip.saturating_add(blocks)
77    }
78
79    /// Estimated seconds until `height` (0 if already reached).
80    pub fn seconds_until(&self, height: u64) -> u64 {
81        height.saturating_sub(self.tip).saturating_mul(self.block_seconds)
82    }
83}
84
85/// One side of a cross-chain swap: that chain's clock and the refund height
86/// of the lock on it.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub struct SwapLeg {
89    /// Timing of the chain this lock is on.
90    pub clock: ChainClock,
91    /// Refund height of the lock, on that chain.
92    pub refund_height: u64,
93}
94
95/// Estimated time until each refund opens, from [`AtomicSwap::check_cross_chain`].
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub struct SwapTimeouts {
98    /// Seconds until the initiator's refund opens.
99    pub initiator_refund_seconds: u64,
100    /// Seconds until the participant's refund opens.
101    pub participant_refund_seconds: u64,
102}
103
104/// Atomic swap helpers. Convenience only — nothing here is a consensus rule.
105#[derive(Debug, Clone, Copy)]
106pub struct AtomicSwap;
107
108impl AtomicSwap {
109    /// New random secret and its hash.
110    pub fn new_secret() -> Result<SwapSecret> {
111        let mut secret = [0u8; 32];
112        getrandom::getrandom(&mut secret).map_err(|_| Error::InvalidSwap("no randomness".into()))?;
113        let hash = sha256(&secret);
114        Ok(SwapSecret { secret, hash })
115    }
116
117    /// Both locks of a same-chain swap. Rejects timeouts where the
118    /// participant would not have `safety_margin_blocks` to claim.
119    pub fn locks(p: AtomicSwapParams) -> Result<SwapLocks> {
120        if p.initiator_refund_height < p.participant_refund_height.saturating_add(p.safety_margin_blocks) {
121            return Err(Error::InvalidSwap(
122                "initiator refund height must be at least safety_margin_blocks after the participant refund height".into(),
123            ));
124        }
125        Ok(SwapLocks {
126            initiator_lock: Self::funding_lock(
127                p.initiator_key,
128                p.participant_key,
129                p.secret_hash,
130                p.initiator_refund_height,
131            ),
132            participant_lock: Self::funding_lock(
133                p.participant_key,
134                p.initiator_key,
135                p.secret_hash,
136                p.participant_refund_height,
137            ),
138        })
139    }
140
141    /// The HTLC one party funds: `counterparty` claims with the secret,
142    /// `funder` refunds after `refund_height`. For a cross-chain swap this is
143    /// the Torvyon side; the other chain gets the mirror-image HTLC.
144    pub fn funding_lock(
145        funder: PublicKey,
146        counterparty: PublicKey,
147        secret_hash: [u8; 32],
148        refund_height: u64,
149    ) -> Condition {
150        ConditionTemplates::htlc(HtlcTemplate {
151            recipient_key: counterparty,
152            refund_key: funder,
153            secret_hash,
154            refund_height,
155        })
156    }
157
158    /// Checks a cross-chain swap's deadlines in time rather than blocks:
159    /// the initiator's refund must open at least `safety_margin_seconds`
160    /// after the participant's, and the participant's must be in the future.
161    pub fn check_cross_chain(
162        initiator: SwapLeg,
163        participant: SwapLeg,
164        safety_margin_seconds: u64,
165    ) -> Result<SwapTimeouts> {
166        let t = SwapTimeouts {
167            initiator_refund_seconds: initiator.clock.seconds_until(initiator.refund_height),
168            participant_refund_seconds: participant.clock.seconds_until(participant.refund_height),
169        };
170        if t.participant_refund_seconds == 0 {
171            return Err(Error::InvalidSwap(
172                "participant refund height is not in the future".into(),
173            ));
174        }
175        if t.initiator_refund_seconds < t.participant_refund_seconds.saturating_add(safety_margin_seconds) {
176            return Err(Error::InvalidSwap(format!(
177                "initiator refund opens in ~{}s, must be at least {}s after the participant refund (~{}s)",
178                t.initiator_refund_seconds, safety_margin_seconds, t.participant_refund_seconds
179            )));
180        }
181        Ok(t)
182    }
183
184    /// The secret among revealed preimages (e.g. the witness of a claim), if any.
185    pub fn revealed_secret<'a>(
186        preimages: impl IntoIterator<Item = &'a [u8]>,
187        secret_hash: &[u8; 32],
188    ) -> Option<Vec<u8>> {
189        preimages
190            .into_iter()
191            .find(|p| &sha256(p) == secret_hash)
192            .map(<[u8]>::to_vec)
193    }
194}