{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE DeriveGeneric #-}

-- |
-- Module: Lightning.Protocol.BOLT4.Blinding
-- Copyright: (c) 2025 Jared Tobin
-- License: MIT
-- Maintainer: Jared Tobin <jared@ppad.tech>
--
-- Route blinding.

module Lightning.Protocol.BOLT4.Blinding (
    BlindingError(..)
  , create_blinded_path
  , decrypt_recipient_data
  , unblind
  ) where

import Control.DeepSeq (NFData)
import qualified Crypto.AEAD.ChaCha20Poly1305 as AEAD
import qualified Crypto.Curve.Secp256k1 as Secp256k1
import qualified Data.ByteString as BS
import GHC.Generics (Generic)
import qualified Lightning.Protocol.BOLT1 as BOLT1
import Lightning.Protocol.BOLT4.Codec
import Lightning.Protocol.BOLT4.Prim
import Lightning.Protocol.BOLT4.Types

-- | Why a blinded route could not be created.
data BlindingError
  = EmptyPath
    -- ^ the route has no hops
  | InvalidNodeId {-# UNPACK #-} !Int
    -- ^ the node id of the hop with this index is not a valid point
  | InvalidHopData {-# UNPACK #-} !Int !EncodeError
    -- ^ the data of the hop with this index can't be encoded
  deriving (BlindingError -> BlindingError -> Bool
(BlindingError -> BlindingError -> Bool)
-> (BlindingError -> BlindingError -> Bool) -> Eq BlindingError
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: BlindingError -> BlindingError -> Bool
== :: BlindingError -> BlindingError -> Bool
$c/= :: BlindingError -> BlindingError -> Bool
/= :: BlindingError -> BlindingError -> Bool
Eq, Int -> BlindingError -> ShowS
[BlindingError] -> ShowS
BlindingError -> String
(Int -> BlindingError -> ShowS)
-> (BlindingError -> String)
-> ([BlindingError] -> ShowS)
-> Show BlindingError
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> BlindingError -> ShowS
showsPrec :: Int -> BlindingError -> ShowS
$cshow :: BlindingError -> String
show :: BlindingError -> String
$cshowList :: [BlindingError] -> ShowS
showList :: [BlindingError] -> ShowS
Show, (forall x. BlindingError -> Rep BlindingError x)
-> (forall x. Rep BlindingError x -> BlindingError)
-> Generic BlindingError
forall x. Rep BlindingError x -> BlindingError
forall x. BlindingError -> Rep BlindingError x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. BlindingError -> Rep BlindingError x
from :: forall x. BlindingError -> Rep BlindingError x
$cto :: forall x. Rep BlindingError x -> BlindingError
to :: forall x. Rep BlindingError x -> BlindingError
Generic)

instance NFData BlindingError

-- | Create a blinded route to oneself, given a seed for the route's
--   ephemeral keys (which must be fresh and random for every route) and
--   each node's id and data, from the introduction node to oneself.
--
--   >>> let Just seed = secret_key (BS.replicate 32 0x01)
--   >>> let Just me = secret_key (BS.replicate 32 0x45)
--   >>> let dat = empty_blinded_hop_data { bhd_path_id = Just "deadbeef" }
--   >>> let Right path = create_blinded_path seed [(public_key me, dat)]
--   >>> bp_first_node_id path == public_key me
--   True
--   >>> length (bp_hops path)
--   1
create_blinded_path
  :: SecretKey
  -> [(BOLT1.Point, BlindedHopData)]
  -> Either BlindingError BlindedPath
create_blinded_path :: SecretKey
-> [(Point, BlindedHopData)] -> Either BlindingError BlindedPath
create_blinded_path SecretKey
seed [(Point, BlindedHopData)]
nodes = case [(Point, BlindedHopData)]
nodes of
  [] -> BlindingError -> Either BlindingError BlindedPath
forall a b. a -> Either a b
Left BlindingError
EmptyPath
  (Point
intro, BlindedHopData
_) : [(Point, BlindedHopData)]
_ -> do
    hops <- ByteString
-> Projective
-> [(Int, (Point, BlindedHopData))]
-> Either BlindingError [BlindedHop]
go (SecretKey -> ByteString
sk_bytes SecretKey
seed) (SecretKey -> Projective
sk_pub SecretKey
seed) ([Int]
-> [(Point, BlindedHopData)] -> [(Int, (Point, BlindedHopData))]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] [(Point, BlindedHopData)]
nodes)
    pure (BlindedPath intro (public_key seed) hops)
  where
    go :: ByteString
-> Projective
-> [(Int, (Point, BlindedHopData))]
-> Either BlindingError [BlindedHop]
go ByteString
_ Projective
_ [] = [BlindedHop] -> Either BlindingError [BlindedHop]
forall a b. b -> Either a b
Right []
    go ByteString
e Projective
epub ((Int
i, (Point
nid, BlindedHopData
dat)) : [(Int, (Point, BlindedHopData))]
rest) = do
      let note :: Maybe b -> Either BlindingError b
note = Either BlindingError b
-> (b -> Either BlindingError b)
-> Maybe b
-> Either BlindingError b
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (BlindingError -> Either BlindingError b
forall a b. a -> Either a b
Left (Int -> BlindingError
InvalidNodeId Int
i)) b -> Either BlindingError b
forall a b. b -> Either a b
Right
      node <- Maybe Projective -> Either BlindingError Projective
forall {b}. Maybe b -> Either BlindingError b
note (Point -> Maybe Projective
from_point Point
nid)
      ss <- note (ecdh e node)
      bid <- note (blind_pub node (blinded_node_tweak ss) >>= to_point)
      plain <- either (Left . InvalidHopData i) Right
                 (encode_blinded_hop_data dat)
      enc <- maybe (Left (InvalidHopData i FieldTooLong)) Right
               (encrypt (derive_rho ss) plain)
      let hop = Point -> ByteString -> BlindedHop
BlindedHop Point
bid ByteString
enc
      case rest of
        [] -> [BlindedHop] -> Either BlindingError [BlindedHop]
forall a b. b -> Either a b
Right [BlindedHop
hop]
        [(Int, (Point, BlindedHopData))]
_  -> do
          let bf :: ByteString
bf = Projective -> SharedSecret -> ByteString
blinding_factor Projective
epub SharedSecret
ss
          e' <- Maybe ByteString -> Either BlindingError ByteString
forall {b}. Maybe b -> Either BlindingError b
note (ByteString -> ByteString -> Maybe ByteString
blind_scalar ByteString
e ByteString
bf)
          epub' <- note (blind_pub epub bf)
          (hop :) <$> go e' epub' rest

-- | Decrypt the @encrypted_recipient_data@ received by a node in a
--   blinded route, given the node's private key and the path key it
--   received.
--
--   Returns the decrypted data and the path key for the next node (the
--   data's @next_path_key_override@, if present).
--   'Lightning.Protocol.BOLT4.process' does this for payment onions.
--
--   >>> let Just seed = secret_key (BS.replicate 32 0x01)
--   >>> let Just me = secret_key (BS.replicate 32 0x45)
--   >>> let dat = empty_blinded_hop_data { bhd_path_id = Just "deadbeef" }
--   >>> let Right path = create_blinded_path seed [(public_key me, dat)]
--   >>> let [hop] = bp_hops path
--   >>> let pk = bp_first_path_key path
--   >>> let Right info = decrypt_recipient_data me pk (bh_encrypted_data hop)
--   >>> bhd_path_id (bi_data info)
--   Just "deadbeef"
decrypt_recipient_data
  :: SecretKey
  -> BOLT1.Point
  -> BS.ByteString
  -> Either ProcessError BlindedInfo
decrypt_recipient_data :: SecretKey -> Point -> ByteString -> Either ProcessError BlindedInfo
decrypt_recipient_data SecretKey
sk Point
pk ByteString
enc = do
  e <- Either ProcessError Projective
-> (Projective -> Either ProcessError Projective)
-> Maybe Projective
-> Either ProcessError Projective
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (ProcessError -> Either ProcessError Projective
forall a b. a -> Either a b
Left ProcessError
InvalidPathKey) Projective -> Either ProcessError Projective
forall a b. b -> Either a b
Right (Point -> Maybe Projective
from_point Point
pk)
  ss <- maybe (Left InvalidPathKey) Right (ecdh (sk_bytes sk) e)
  unblind ss e enc

-- Decrypt encrypted_recipient_data, given the shared secret with the path
-- key, and the path key.
unblind
  :: SharedSecret
  -> Secp256k1.Projective
  -> BS.ByteString
  -> Either ProcessError BlindedInfo
unblind :: SharedSecret
-> Projective -> ByteString -> Either ProcessError BlindedInfo
unblind SharedSecret
ss Projective
e ByteString
enc = do
  plain <- Either ProcessError ByteString
-> (ByteString -> Either ProcessError ByteString)
-> Maybe ByteString
-> Either ProcessError ByteString
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (ProcessError -> Either ProcessError ByteString
forall a b. a -> Either a b
Left ProcessError
InvalidRecipientData) ByteString -> Either ProcessError ByteString
forall a b. b -> Either a b
Right
             (DerivedKey -> ByteString -> Maybe ByteString
decrypt (SharedSecret -> DerivedKey
derive_rho SharedSecret
ss) ByteString
enc)
  dat <- either (const (Left InvalidRecipientData)) Right
           (decode_blinded_hop_data plain)
  next <- case bhd_next_path_key_override dat of
    Just Point
o  -> Point -> Either ProcessError Point
forall a b. b -> Either a b
Right Point
o
    Maybe Point
Nothing -> Either ProcessError Point
-> (Point -> Either ProcessError Point)
-> Maybe Point
-> Either ProcessError Point
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (ProcessError -> Either ProcessError Point
forall a b. a -> Either a b
Left ProcessError
InvalidPathKey) Point -> Either ProcessError Point
forall a b. b -> Either a b
Right
                 (Projective -> ByteString -> Maybe Projective
blind_pub Projective
e (Projective -> SharedSecret -> ByteString
blinding_factor Projective
e SharedSecret
ss) Maybe Projective -> (Projective -> Maybe Point) -> Maybe Point
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Projective -> Maybe Point
to_point)
  pure (BlindedInfo dat next)

-- ChaCha20-Poly1305 with an all-zero nonce and no associated data; the
-- tag follows the ciphertext. Fails only on counter overflow.
encrypt :: DerivedKey -> BS.ByteString -> Maybe BS.ByteString
encrypt :: DerivedKey -> ByteString -> Maybe ByteString
encrypt DerivedKey
k ByteString
plain =
  case ByteString
-> ByteString
-> ByteString
-> ByteString
-> Either Error (ByteString, ByteString)
AEAD.encrypt ByteString
BS.empty (DerivedKey -> ByteString
un_derived_key DerivedKey
k) (Int -> Word8 -> ByteString
BS.replicate Int
12 Word8
0) ByteString
plain of
    Right (ByteString
c, ByteString
t) -> ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just (ByteString
c ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
t)
    Left Error
_       -> Maybe ByteString
forall a. Maybe a
Nothing

decrypt :: DerivedKey -> BS.ByteString -> Maybe BS.ByteString
decrypt :: DerivedKey -> ByteString -> Maybe ByteString
decrypt DerivedKey
k ByteString
enc
  | ByteString -> Int
BS.length ByteString
enc Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
16 = Maybe ByteString
forall a. Maybe a
Nothing
  | Bool
otherwise =
      let (ByteString
c, ByteString
t) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt (ByteString -> Int
BS.length ByteString
enc Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
16) ByteString
enc
      in  case ByteString
-> ByteString
-> ByteString
-> (ByteString, ByteString)
-> Either Error ByteString
AEAD.decrypt ByteString
BS.empty (DerivedKey -> ByteString
un_derived_key DerivedKey
k) (Int -> Word8 -> ByteString
BS.replicate Int
12 Word8
0)
                 (ByteString
c, ByteString
t) of
            Right ByteString
p -> ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just ByteString
p
            Left Error
_  -> Maybe ByteString
forall a. Maybe a
Nothing