{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE BangPatterns #-}

-- |
-- Module: Lightning.Protocol.BOLT5.Detect
-- Copyright: (c) 2025 Jared Tobin
-- License: MIT
-- Maintainer: Jared Tobin <jared@ppad.tech>
--
-- Close identification, output classification, and preimage
-- extraction for BOLT #5 on-chain transaction handling.

module Lightning.Protocol.BOLT5.Detect (
    -- * Close identification
    identify_close

    -- * Output classification
  , classify_local_commit_outputs
  , classify_remote_commit_outputs
  , classify_revoked_commit_outputs

    -- * Preimage extraction
  , extract_preimage_offered
  , extract_preimage_htlc_success

    -- * Timeout check
  , htlc_timed_out
  ) where

import Bitcoin.Prim.Tx (OutPoint(..), TxId, Witness(..))
import qualified Bitcoin.Prim.Tx as BT
import qualified Crypto.Hash.SHA256 as SHA256
import qualified Data.ByteString as BS
import qualified Data.List.NonEmpty as NE
import Data.Word (Word32)
import Lightning.Protocol.BOLT1 (PaymentHash, PaymentPreimage)
import qualified Lightning.Protocol.BOLT1 as BOLT1
import Lightning.Protocol.BOLT3
import Lightning.Protocol.BOLT5.Types

-- close identification -----------------------------------------------

-- | Identify the type of channel close from a transaction that
--   spends the funding output.
--
--   Parses the on-chain transaction and compares its txid with the
--   txids of the known local and remote commitment transactions.
--   Comparing txids rather than bytes means the signed (segwit)
--   serialization found on chain matches the unsigned commitment.
--
--   Returns 'Nothing' if the bytes don't parse as a transaction or
--   the transaction matches neither commitment. Mutual close and
--   revoked commitment detection are left to the caller (e.g.
--   comparing with the closing transaction, or checking a secret
--   store for older commitment numbers).
identify_close
  :: CommitmentTx
  -- ^ Our local commitment tx.
  -> CommitmentTx
  -- ^ The remote commitment tx (current).
  -> BS.ByteString
  -- ^ Raw serialized transaction found on chain.
  -> Maybe CloseType
identify_close :: CommitmentTx -> CommitmentTx -> ByteString -> Maybe CloseType
identify_close !CommitmentTx
local !CommitmentTx
remote !ByteString
bytes = do
  !tx <- ByteString -> Maybe Tx
BT.from_bytes ByteString
bytes
  let !txid = Tx -> TxId
BT.txid Tx
tx
  if   commitment_txid local == txid
  then Just LocalCommitClose
  else if commitment_txid remote == txid
  then Just RemoteCommitClose
  else Nothing

-- output classification ----------------------------------------------

-- | Classify the outputs of our local commitment transaction.
--
--   Per BOLT #5: when our local commitment is on chain, we must
--   resolve each output. to_local requires a CSV-delayed spend,
--   to_remote is resolved by the commitment itself, HTLC outputs
--   need second-stage transactions, and our anchor can be spent
--   immediately.
--
--   Each HTLC output's HTLC is read from its bolt3 'OutputHTLC', so
--   the commitment must be the one bolt3 built for this state.
classify_local_commit_outputs
  :: CommitmentTx
  -- ^ Our local commitment transaction.
  -> CommitmentKeys
  -- ^ Derived keys for this commitment.
  -> ToSelfDelay
  -- ^ Remote's to_self_delay (CSV delay for our outputs).
  -> CommitmentFormat
  -> [UnresolvedOutput]
classify_local_commit_outputs :: CommitmentTx
-> CommitmentKeys
-> ToSelfDelay
-> CommitmentFormat
-> [UnresolvedOutput]
classify_local_commit_outputs !CommitmentTx
tx !CommitmentKeys
keys !ToSelfDelay
delay !CommitmentFormat
fmt =
    (OutputType -> OutputResolution)
-> CommitmentTx -> [UnresolvedOutput]
classify_outputs OutputType -> OutputResolution
resolve CommitmentTx
tx
  where
    resolve :: OutputType -> OutputResolution
resolve OutputType
t = case OutputType
t of
      OutputType
OutputToLocal ->
        ToSelfDelay
-> RevocationPubkey -> LocalDelayedPubkey -> OutputResolution
SpendToLocal ToSelfDelay
delay (CommitmentKeys -> RevocationPubkey
ck_revocation_pubkey CommitmentKeys
keys)
          (CommitmentKeys -> LocalDelayedPubkey
ck_local_delayed CommitmentKeys
keys)
      OutputType
OutputToRemote -> OutputResolution
Resolved
      OutputType
OutputLocalAnchor -> FundingPubkey -> OutputResolution
AnchorSpend (CommitmentKeys -> FundingPubkey
ck_local_funding CommitmentKeys
keys)
      OutputType
OutputRemoteAnchor -> OutputResolution
Resolved
      OutputHTLC HTLC
h -> case HTLC -> HTLCDirection
htlc_direction HTLC
h of
        HTLCDirection
HTLCOffered  -> HTLC -> CommitmentKeys -> CommitmentFormat -> OutputResolution
SpendHTLCTimeout HTLC
h CommitmentKeys
keys CommitmentFormat
fmt
        HTLCDirection
HTLCReceived -> HTLC -> CommitmentKeys -> CommitmentFormat -> OutputResolution
SpendHTLCSuccess HTLC
h CommitmentKeys
keys CommitmentFormat
fmt

-- | Classify the outputs of the remote commitment transaction.
--
--   Per BOLT #5: when the remote commitment is on chain, there are
--   no CSV delays on our outputs. We can spend HTLCs we offered
--   directly after timeout, and HTLCs we received directly with the
--   preimage.
--
--   The commitment, its keys and its HTLCs are from the remote's
--   point of view (as bolt3 builds the remote's commitment): an
--   HTLC the remote offered is one we received.
classify_remote_commit_outputs
  :: CommitmentTx
  -- ^ The remote commitment transaction.
  -> CommitmentKeys
  -- ^ Derived keys for this commitment (from the remote's point
  --   of view, so local and remote are swapped).
  -> [UnresolvedOutput]
classify_remote_commit_outputs :: CommitmentTx -> CommitmentKeys -> [UnresolvedOutput]
classify_remote_commit_outputs !CommitmentTx
tx !CommitmentKeys
keys =
    (OutputType -> OutputResolution)
-> CommitmentTx -> [UnresolvedOutput]
classify_outputs OutputType -> OutputResolution
resolve CommitmentTx
tx
  where
    resolve :: OutputType -> OutputResolution
resolve OutputType
t = case OutputType
t of
      OutputType
OutputToLocal -> OutputResolution
Resolved       -- the remote's to_local
      OutputType
OutputToRemote -> OutputResolution
Resolved      -- ours; resolved by the commitment
      OutputType
OutputLocalAnchor -> OutputResolution
Resolved   -- the remote's anchor
      OutputType
OutputRemoteAnchor -> FundingPubkey -> OutputResolution
AnchorSpend (CommitmentKeys -> FundingPubkey
ck_remote_funding CommitmentKeys
keys)
      OutputHTLC HTLC
h -> case HTLC -> HTLCDirection
htlc_direction HTLC
h of
        HTLCDirection
HTLCOffered  -> HTLC -> OutputResolution
SpendHTLCPreimageDirect HTLC
h  -- we received it
        HTLCDirection
HTLCReceived -> HTLC -> OutputResolution
SpendHTLCTimeoutDirect HTLC
h   -- we offered it

-- | Classify the outputs of a revoked commitment transaction.
--
--   Per BOLT #5: when a revoked commitment is on chain, we can
--   claim to_local and every HTLC output with the revocation key.
--   to_remote (ours) and the anchors are marked 'Resolved'.
classify_revoked_commit_outputs
  :: CommitmentTx
  -- ^ The revoked commitment transaction.
  -> RevocationPubkey
  -- ^ Revocation pubkey (derived from the revealed secret).
  -> [UnresolvedOutput]
classify_revoked_commit_outputs :: CommitmentTx -> RevocationPubkey -> [UnresolvedOutput]
classify_revoked_commit_outputs !CommitmentTx
tx !RevocationPubkey
revpk =
    (OutputType -> OutputResolution)
-> CommitmentTx -> [UnresolvedOutput]
classify_outputs OutputType -> OutputResolution
resolve CommitmentTx
tx
  where
    resolve :: OutputType -> OutputResolution
resolve OutputType
t = case OutputType
t of
      OutputType
OutputToLocal -> RevocationPubkey -> OutputResolution
Revoke RevocationPubkey
revpk
      OutputType
OutputToRemote -> OutputResolution
Resolved
      OutputType
OutputLocalAnchor -> OutputResolution
Resolved
      OutputType
OutputRemoteAnchor -> OutputResolution
Resolved
      OutputHTLC HTLC
h -> RevocationPubkey -> HTLCOutputType -> OutputResolution
RevokeHTLC RevocationPubkey
revpk (HTLCOutputType -> OutputResolution)
-> HTLCOutputType -> OutputResolution
forall a b. (a -> b) -> a -> b
$ case HTLC -> HTLCDirection
htlc_direction HTLC
h of
        HTLCDirection
HTLCOffered  -> CltvExpiry -> HTLCOutputType
HTLCOfferedOutput (HTLC -> CltvExpiry
htlc_cltv_expiry HTLC
h)
        HTLCDirection
HTLCReceived -> CltvExpiry -> HTLCOutputType
HTLCReceivedOutput (HTLC -> CltvExpiry
htlc_cltv_expiry HTLC
h)

-- | Pair each commitment output with its outpoint, value and
--   resolution.
classify_outputs
  :: (OutputType -> OutputResolution)
  -> CommitmentTx
  -> [UnresolvedOutput]
classify_outputs :: (OutputType -> OutputResolution)
-> CommitmentTx -> [UnresolvedOutput]
classify_outputs OutputType -> OutputResolution
resolve CommitmentTx
tx =
    (Word32 -> CommitmentOutput -> UnresolvedOutput)
-> [Word32] -> [CommitmentOutput] -> [UnresolvedOutput]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Word32 -> CommitmentOutput -> UnresolvedOutput
classify [Word32
0..] (NonEmpty CommitmentOutput -> [CommitmentOutput]
forall a. NonEmpty a -> [a]
NE.toList (CommitmentTx -> NonEmpty CommitmentOutput
ctx_outputs CommitmentTx
tx))
  where
    !txid :: TxId
txid = CommitmentTx -> TxId
commitment_txid CommitmentTx
tx
    classify :: Word32 -> CommitmentOutput -> UnresolvedOutput
    classify :: Word32 -> CommitmentOutput -> UnresolvedOutput
classify !Word32
idx !CommitmentOutput
out = UnresolvedOutput
      { uo_outpoint :: OutPoint
uo_outpoint = TxId -> Word32 -> OutPoint
OutPoint TxId
txid Word32
idx
      , uo_value :: Satoshi
uo_value    = CommitmentOutput -> Satoshi
co_value CommitmentOutput
out
      , uo_type :: OutputResolution
uo_type     = OutputType -> OutputResolution
resolve (CommitmentOutput -> OutputType
co_type CommitmentOutput
out)
      }

-- preimage extraction ------------------------------------------------

-- | Extract a payment preimage from the witness of an input
--   spending an offered HTLC output.
--
--   When the remote party claims an offered HTLC on our local
--   commitment, the witness (see bolt3's
--   'offered_htlc_witness_preimage') is:
--
--   @\<remotehtlcsig\> \<payment_preimage\> \<witness_script\>@
--
--   Returns the preimage only if it hashes to the given payment
--   hash. Any other spend of the output, e.g. by revocation, yields
--   'Nothing'.
extract_preimage_offered
  :: PaymentHash
  -- ^ Payment hash of the HTLC.
  -> Witness
  -- ^ Witness of the input spending the HTLC output.
  -> Maybe PaymentPreimage
extract_preimage_offered :: PaymentHash -> Witness -> Maybe PaymentPreimage
extract_preimage_offered !PaymentHash
ph (Witness [ByteString]
items) = case [ByteString]
items of
  [ByteString
_sig, ByteString
preimage, ByteString
_script] -> PaymentHash -> ByteString -> Maybe PaymentPreimage
check_preimage PaymentHash
ph ByteString
preimage
  [ByteString]
_ -> Maybe PaymentPreimage
forall a. Maybe a
Nothing

-- | Extract a payment preimage from the witness of an HTLC-success
--   transaction's input.
--
--   When the remote party claims an HTLC it received on its
--   commitment with an HTLC-success transaction, the witness (see
--   bolt3's 'htlc_success_witness') is:
--
--   @0 \<remotehtlcsig\> \<localhtlcsig\> \<payment_preimage\>
--   \<witness_script\>@
--
--   Returns the preimage only if it hashes to the given payment
--   hash.
extract_preimage_htlc_success
  :: PaymentHash
  -- ^ Payment hash of the HTLC.
  -> Witness
  -- ^ Witness of the HTLC-success transaction input.
  -> Maybe PaymentPreimage
extract_preimage_htlc_success :: PaymentHash -> Witness -> Maybe PaymentPreimage
extract_preimage_htlc_success !PaymentHash
ph (Witness [ByteString]
items) = case [ByteString]
items of
  [ByteString
_zero, ByteString
_remote_sig, ByteString
_local_sig, ByteString
preimage, ByteString
_script] ->
    PaymentHash -> ByteString -> Maybe PaymentPreimage
check_preimage PaymentHash
ph ByteString
preimage
  [ByteString]
_ -> Maybe PaymentPreimage
forall a. Maybe a
Nothing

-- | Accept a candidate preimage only if it hashes to the payment
--   hash.
check_preimage :: PaymentHash -> BS.ByteString -> Maybe PaymentPreimage
check_preimage :: PaymentHash -> ByteString -> Maybe PaymentPreimage
check_preimage !PaymentHash
ph !ByteString
bs
  | ByteString -> ByteString
SHA256.hash ByteString
bs ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== PaymentHash -> ByteString
BOLT1.un_payment_hash PaymentHash
ph = ByteString -> Maybe PaymentPreimage
BOLT1.payment_preimage ByteString
bs
  | Bool
otherwise = Maybe PaymentPreimage
forall a. Maybe a
Nothing

-- timeout check ------------------------------------------------------

-- | Whether an HTLC has timed out at the given block height: whether
--   the height is at least the HTLC's CLTV expiry.
--
--   >>> let Just amt = BOLT1.milli_satoshi 1000000
--   >>> let Just ph = BOLT1.payment_hash (BS.replicate 32 0xaa)
--   >>> let htlc = HTLC HTLCOffered amt ph (CltvExpiry 800000)
--   >>> htlc_timed_out 799999 htlc
--   False
--   >>> htlc_timed_out 800000 htlc
--   True
htlc_timed_out :: Word32 -> HTLC -> Bool
htlc_timed_out :: Word32 -> HTLC -> Bool
htlc_timed_out !Word32
height !HTLC
htlc =
  let CltvExpiry Word32
expiry = HTLC -> CltvExpiry
htlc_cltv_expiry HTLC
htlc
  in  Word32
height Word32 -> Word32 -> Bool
forall a. Ord a => a -> a -> Bool
>= Word32
expiry
{-# INLINE htlc_timed_out #-}

-- internal helpers ---------------------------------------------------

-- | The txid of a commitment transaction.
commitment_txid :: CommitmentTx -> TxId
commitment_txid :: CommitmentTx -> TxId
commitment_txid = Tx -> TxId
BT.txid (Tx -> TxId) -> (CommitmentTx -> Tx) -> CommitmentTx -> TxId
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CommitmentTx -> Tx
commitment_to_tx
{-# INLINE commitment_txid #-}