torvyon-core 0.1.2

Keys, addresses, post-quantum signing and transaction building for the Torvyon blockchain
Documentation
//! Atomic swaps built from two HTLCs that share one secret hash.
//!
//! Same chain (both locks on Torvyon): [`AtomicSwap::locks`].
//!
//! Across chains (one lock on Torvyon, the other on a different chain whose
//! HTLC is built with that chain's own tools): express each deadline as a
//! height on its own chain with [`ChainClock::height_after`], check the order
//! with [`AtomicSwap::check_cross_chain`], and build the Torvyon side with
//! [`AtomicSwap::funding_lock`].
//!
//! The rule in both cases: the **initiator** (who created the secret) must be
//! able to refund only well **after** the participant's refund opens, so the
//! participant always has time to claim once the secret is revealed.

use zeroize::Zeroize;

use crate::{
    conditions::{Condition, ConditionTemplates, HtlcTemplate},
    hash::sha256,
    Error, PublicKey, Result,
};

/// A fresh swap secret. The secret is wiped from memory on drop.
pub struct SwapSecret {
    /// 32 random bytes. Keep private until claiming.
    pub secret: [u8; 32],
    /// SHA-256 of the secret — safe to share.
    pub hash: [u8; 32],
}

impl Drop for SwapSecret {
    fn drop(&mut self) {
        self.secret.zeroize();
    }
}

/// Parameters for a swap where both locks are on the same chain.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AtomicSwapParams {
    /// SHA-256 of the initiator's secret.
    pub secret_hash: [u8; 32],
    /// Initiator: knows the secret and claims the participant's lock first.
    pub initiator_key: PublicKey,
    /// Participant: learns the secret from the initiator's claim.
    pub participant_key: PublicKey,
    /// Height after which the initiator can refund its own lock.
    pub initiator_refund_height: u64,
    /// Height after which the participant can refund. Must be earlier.
    pub participant_refund_height: u64,
    /// Blocks the participant needs to claim after the secret is revealed.
    pub safety_margin_blocks: u64,
}

/// The two locks of a same-chain swap.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SwapLocks {
    /// Funded by the initiator; the participant claims it with the secret.
    pub initiator_lock: Condition,
    /// Funded by the participant; the initiator claims it with the secret.
    pub participant_lock: Condition,
}

/// Block timing of one chain, for converting durations into heights.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChainClock {
    /// Current tip height.
    pub tip: u64,
    /// Average seconds per block (Torvyon mainnet 20, testnet 60).
    pub block_seconds: u64,
}

impl ChainClock {
    /// Height reached about `seconds` from now (rounded up).
    pub fn height_after(&self, seconds: u64) -> u64 {
        let blocks = seconds.div_ceil(self.block_seconds.max(1));
        self.tip.saturating_add(blocks)
    }

    /// Estimated seconds until `height` (0 if already reached).
    pub fn seconds_until(&self, height: u64) -> u64 {
        height.saturating_sub(self.tip).saturating_mul(self.block_seconds)
    }
}

/// One side of a cross-chain swap: that chain's clock and the refund height
/// of the lock on it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SwapLeg {
    /// Timing of the chain this lock is on.
    pub clock: ChainClock,
    /// Refund height of the lock, on that chain.
    pub refund_height: u64,
}

/// Estimated time until each refund opens, from [`AtomicSwap::check_cross_chain`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SwapTimeouts {
    /// Seconds until the initiator's refund opens.
    pub initiator_refund_seconds: u64,
    /// Seconds until the participant's refund opens.
    pub participant_refund_seconds: u64,
}

/// Atomic swap helpers. Convenience only — nothing here is a consensus rule.
#[derive(Debug, Clone, Copy)]
pub struct AtomicSwap;

impl AtomicSwap {
    /// New random secret and its hash.
    pub fn new_secret() -> Result<SwapSecret> {
        let mut secret = [0u8; 32];
        getrandom::getrandom(&mut secret).map_err(|_| Error::InvalidSwap("no randomness".into()))?;
        let hash = sha256(&secret);
        Ok(SwapSecret { secret, hash })
    }

    /// Both locks of a same-chain swap. Rejects timeouts where the
    /// participant would not have `safety_margin_blocks` to claim.
    pub fn locks(p: AtomicSwapParams) -> Result<SwapLocks> {
        if p.initiator_refund_height < p.participant_refund_height.saturating_add(p.safety_margin_blocks) {
            return Err(Error::InvalidSwap(
                "initiator refund height must be at least safety_margin_blocks after the participant refund height".into(),
            ));
        }
        Ok(SwapLocks {
            initiator_lock: Self::funding_lock(
                p.initiator_key,
                p.participant_key,
                p.secret_hash,
                p.initiator_refund_height,
            ),
            participant_lock: Self::funding_lock(
                p.participant_key,
                p.initiator_key,
                p.secret_hash,
                p.participant_refund_height,
            ),
        })
    }

    /// The HTLC one party funds: `counterparty` claims with the secret,
    /// `funder` refunds after `refund_height`. For a cross-chain swap this is
    /// the Torvyon side; the other chain gets the mirror-image HTLC.
    pub fn funding_lock(
        funder: PublicKey,
        counterparty: PublicKey,
        secret_hash: [u8; 32],
        refund_height: u64,
    ) -> Condition {
        ConditionTemplates::htlc(HtlcTemplate {
            recipient_key: counterparty,
            refund_key: funder,
            secret_hash,
            refund_height,
        })
    }

    /// Checks a cross-chain swap's deadlines in time rather than blocks:
    /// the initiator's refund must open at least `safety_margin_seconds`
    /// after the participant's, and the participant's must be in the future.
    pub fn check_cross_chain(
        initiator: SwapLeg,
        participant: SwapLeg,
        safety_margin_seconds: u64,
    ) -> Result<SwapTimeouts> {
        let t = SwapTimeouts {
            initiator_refund_seconds: initiator.clock.seconds_until(initiator.refund_height),
            participant_refund_seconds: participant.clock.seconds_until(participant.refund_height),
        };
        if t.participant_refund_seconds == 0 {
            return Err(Error::InvalidSwap(
                "participant refund height is not in the future".into(),
            ));
        }
        if t.initiator_refund_seconds < t.participant_refund_seconds.saturating_add(safety_margin_seconds) {
            return Err(Error::InvalidSwap(format!(
                "initiator refund opens in ~{}s, must be at least {}s after the participant refund (~{}s)",
                t.initiator_refund_seconds, safety_margin_seconds, t.participant_refund_seconds
            )));
        }
        Ok(t)
    }

    /// The secret among revealed preimages (e.g. the witness of a claim), if any.
    pub fn revealed_secret<'a>(
        preimages: impl IntoIterator<Item = &'a [u8]>,
        secret_hash: &[u8; 32],
    ) -> Option<Vec<u8>> {
        preimages
            .into_iter()
            .find(|p| &sha256(p) == secret_hash)
            .map(<[u8]>::to_vec)
    }
}