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

-- |
-- Module: Lightning.Protocol.BOLT3.Keys
-- Copyright: (c) 2025 Jared Tobin
-- License: MIT
-- Maintainer: Jared Tobin <jared@ppad.tech>
--
-- Key derivation, per-commitment secrets and commitment number
-- obscuring, per BOLT #3.

module Lightning.Protocol.BOLT3.Keys (
    -- * Per-commitment points
    derive_per_commitment_point
  , derive_per_commitment_point'

    -- * Public keys
  , derive_pubkey
  , derive_revocationpubkey
  , CommitmentKeys(..)
  , derive_commitment_keys
  , derive_commitment_keys'

    -- * Private keys
  , derive_privkey
  , derive_revocationprivkey

    -- * Per-commitment secrets
  , generate_from_seed
  , SecretStore
  , empty_secret_store
  , insert_secret
  , derive_old_secret
  , secret_store
  , un_secret_store

    -- * Commitment number obscuring
  , obscured_commitment_number
  ) where

import Control.DeepSeq (NFData(..))
import qualified Crypto.Curve.Secp256k1 as S
import qualified Crypto.Hash.SHA256 as SHA256
import qualified Data.Choice as C
import Data.Bits ((.&.), (.|.), complement, complementBit, shiftL, shiftR,
                  testBit, xor)
import qualified Data.ByteString as BS
import Data.Word (Word64)
import GHC.Generics (Generic)
import Lightning.Protocol.BOLT1 (Point, PerCommitmentSecret)
import qualified Lightning.Protocol.BOLT1 as BOLT1
import Lightning.Protocol.BOLT3.Types
import qualified Numeric.Montgomery.Secp256k1.Scalar as SC

-- points ---------------------------------------------------------------------

-- Serialize a secp256k1 point, failing on the point at infinity.
to_point :: S.Projective -> Maybe Point
to_point :: Projective -> Maybe Point
to_point Projective
p
  | Projective
p Projective -> Projective -> Bool
forall a. Eq a => a -> a -> Bool
== Projective
S._CURVE_ZERO = Maybe Point
forall a. Maybe a
Nothing
  | Bool
otherwise          = case ByteString -> Maybe Point
BOLT1.point (Projective -> ByteString
S.serialize_point Projective
p) of
      Just Point
pt -> Point -> Maybe Point
forall a. a -> Maybe a
Just Point
pt
      Maybe Point
Nothing -> Maybe Point
forall a. a
internal_error
{-# INLINE to_point #-}

-- per-commitment points ------------------------------------------------------

-- | Derive the per-commitment point from a per-commitment secret:
--
--   @per_commitment_point = per_commitment_secret * G@
--
--   Fails if the secret is not a valid secp256k1 secret key.
--
--   >>> let Just s = BOLT1.per_commitment_secret (BS.pack [31, 30 .. 0])
--   >>> let Just (PerCommitmentPoint p) = derive_per_commitment_point s
--   >>> B16.encode (BOLT1.un_point p)
--   "025f7117a78150fe2ef97db7cfc83bd57b2e2c0d0dd25eaf467a4a1c2a45ce1486"
derive_per_commitment_point
  :: PerCommitmentSecret
  -> Maybe PerCommitmentPoint
derive_per_commitment_point :: PerCommitmentSecret -> Maybe PerCommitmentPoint
derive_per_commitment_point PerCommitmentSecret
s = do
  sk <- ByteString -> Maybe Wider
S.parse_int256 (PerCommitmentSecret -> ByteString
BOLT1.un_per_commitment_secret PerCommitmentSecret
s)
  pk <- S.derive_pub sk
  PerCommitmentPoint <$> to_point pk

-- | As 'derive_per_commitment_point', but uses a precomputed
--   'S.Context' to speed up the scalar multiplication.
derive_per_commitment_point'
  :: S.Context
  -> PerCommitmentSecret
  -> Maybe PerCommitmentPoint
derive_per_commitment_point' :: Context -> PerCommitmentSecret -> Maybe PerCommitmentPoint
derive_per_commitment_point' Context
tex PerCommitmentSecret
s = do
  sk <- ByteString -> Maybe Wider
S.parse_int256 (PerCommitmentSecret -> ByteString
BOLT1.un_per_commitment_secret PerCommitmentSecret
s)
  pk <- S.derive_pub' tex sk
  PerCommitmentPoint <$> to_point pk

-- public keys ----------------------------------------------------------------

-- | Derive a per-commitment public key from a basepoint:
--
--   @pubkey = basepoint + SHA256(per_commitment_point || basepoint) * G@
--
--   This gives @local_htlcpubkey@, @remote_htlcpubkey@,
--   @local_delayedpubkey@ and the like, depending on the basepoint;
--   'derive_commitment_keys' derives all of a commitment's keys at
--   once.
--
--   Fails if the basepoint is not on the curve.
--
--   >>> let Just s = BOLT1.per_commitment_secret (BS.pack [31, 30 .. 0])
--   >>> let Just pcp = derive_per_commitment_point s
--   >>> let Just b = BOLT1.per_commitment_secret (BS.pack [0 .. 31])
--   >>> let Just (PerCommitmentPoint bp) = derive_per_commitment_point b
--   >>> fmap (B16.encode . BOLT1.un_point) (derive_pubkey bp pcp)
--   Just "0235f2dbfaa89b57ec7b055afe29849ef7ddfeb1cefdb9ebdc43f5494984db29e5"
derive_pubkey :: Point -> PerCommitmentPoint -> Maybe Point
derive_pubkey :: Point -> PerCommitmentPoint -> Maybe Point
derive_pubkey = (ByteString -> Maybe Projective)
-> Point -> PerCommitmentPoint -> Maybe Point
derive_pubkey_with ByteString -> Maybe Projective
mul_g
{-# INLINE derive_pubkey #-}

-- Multiply the generator by a 32-byte scalar.
mul_g :: BS.ByteString -> Maybe S.Projective
mul_g :: ByteString -> Maybe Projective
mul_g ByteString
bs = Wider -> Maybe Projective
S.derive_pub (Wider -> Maybe Projective) -> Maybe Wider -> Maybe Projective
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< ByteString -> Maybe Wider
S.parse_int256 ByteString
bs
{-# INLINE mul_g #-}

-- As 'mul_g', using a precomputed context.
mul_g' :: S.Context -> BS.ByteString -> Maybe S.Projective
mul_g' :: Context -> ByteString -> Maybe Projective
mul_g' Context
tex ByteString
bs = Context -> Wider -> Maybe Projective
S.derive_pub' Context
tex (Wider -> Maybe Projective) -> Maybe Wider -> Maybe Projective
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< ByteString -> Maybe Wider
S.parse_int256 ByteString
bs
{-# INLINE mul_g' #-}

derive_pubkey_with
  :: (BS.ByteString -> Maybe S.Projective)
  -> Point
  -> PerCommitmentPoint
  -> Maybe Point
derive_pubkey_with :: (ByteString -> Maybe Projective)
-> Point -> PerCommitmentPoint -> Maybe Point
derive_pubkey_with ByteString -> Maybe Projective
mul Point
bp (PerCommitmentPoint Point
pcp) = do
  let !bp_bs :: ByteString
bp_bs = Point -> ByteString
BOLT1.un_point Point
bp
  base <- ByteString -> Maybe Projective
S.parse_point ByteString
bp_bs
  t    <- mul (SHA256.hash (BOLT1.un_point pcp <> bp_bs))
  to_point (S.add base t)
{-# INLINE derive_pubkey_with #-}

-- | Derive a commitment's @revocationpubkey@ from the revocation
--   basepoint of the party that will hold the revocation key, and the
--   commitment owner's per-commitment point:
--
--   @
--   revocationpubkey =
--       revocation_basepoint
--         * SHA256(revocation_basepoint || per_commitment_point)
--     + per_commitment_point
--         * SHA256(per_commitment_point || revocation_basepoint)
--   @
--
--   Fails if either point is not on the curve.
--
--   >>> let Just s = BOLT1.per_commitment_secret (BS.pack [31, 30 .. 0])
--   >>> let Just pcp = derive_per_commitment_point s
--   >>> let Just b = BOLT1.per_commitment_secret (BS.pack [0 .. 31])
--   >>> let Just (PerCommitmentPoint p) = derive_per_commitment_point b
--   >>> let Just r = derive_revocationpubkey (RevocationBasepoint p) pcp
--   >>> (\(RevocationPubkey k) -> B16.encode (BOLT1.un_point k)) r
--   "02916e326636d19c33f13e8c0c3a03dd157f332f3e99c317c141dd865eb01f8ff0"
derive_revocationpubkey
  :: RevocationBasepoint
  -> PerCommitmentPoint
  -> Maybe RevocationPubkey
derive_revocationpubkey :: RevocationBasepoint -> PerCommitmentPoint -> Maybe RevocationPubkey
derive_revocationpubkey
  (RevocationBasepoint Point
rbp)
  (PerCommitmentPoint Point
pcp) = do
    let !rbp_bs :: ByteString
rbp_bs = Point -> ByteString
BOLT1.un_point Point
rbp
        !pcp_bs :: ByteString
pcp_bs = Point -> ByteString
BOLT1.un_point Point
pcp
    r  <- ByteString -> Maybe Projective
S.parse_point ByteString
rbp_bs
    p  <- S.parse_point pcp_bs
    s1 <- S.parse_int256 (SHA256.hash (rbp_bs <> pcp_bs))
    s2 <- S.parse_int256 (SHA256.hash (pcp_bs <> rbp_bs))
    p1 <- S.mul r s1
    p2 <- S.mul p s2
    RevocationPubkey <$> to_point (S.add p1 p2)

-- | The keys a commitment transaction's scripts use.
data CommitmentKeys = CommitmentKeys
  { CommitmentKeys -> RevocationPubkey
ck_revocation_pubkey :: !RevocationPubkey
  , CommitmentKeys -> LocalDelayedPubkey
ck_local_delayed     :: !LocalDelayedPubkey
  , CommitmentKeys -> LocalHtlcPubkey
ck_local_htlc        :: !LocalHtlcPubkey
  , CommitmentKeys -> RemoteHtlcPubkey
ck_remote_htlc       :: !RemoteHtlcPubkey
  , CommitmentKeys -> RemotePubkey
ck_remote_payment    :: !RemotePubkey
  , CommitmentKeys -> FundingPubkey
ck_local_funding     :: !FundingPubkey
  , CommitmentKeys -> FundingPubkey
ck_remote_funding    :: !FundingPubkey
  } deriving (CommitmentKeys -> CommitmentKeys -> Bool
(CommitmentKeys -> CommitmentKeys -> Bool)
-> (CommitmentKeys -> CommitmentKeys -> Bool) -> Eq CommitmentKeys
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: CommitmentKeys -> CommitmentKeys -> Bool
== :: CommitmentKeys -> CommitmentKeys -> Bool
$c/= :: CommitmentKeys -> CommitmentKeys -> Bool
/= :: CommitmentKeys -> CommitmentKeys -> Bool
Eq, Int -> CommitmentKeys -> ShowS
[CommitmentKeys] -> ShowS
CommitmentKeys -> String
(Int -> CommitmentKeys -> ShowS)
-> (CommitmentKeys -> String)
-> ([CommitmentKeys] -> ShowS)
-> Show CommitmentKeys
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CommitmentKeys -> ShowS
showsPrec :: Int -> CommitmentKeys -> ShowS
$cshow :: CommitmentKeys -> String
show :: CommitmentKeys -> String
$cshowList :: [CommitmentKeys] -> ShowS
showList :: [CommitmentKeys] -> ShowS
Show, (forall x. CommitmentKeys -> Rep CommitmentKeys x)
-> (forall x. Rep CommitmentKeys x -> CommitmentKeys)
-> Generic CommitmentKeys
forall x. Rep CommitmentKeys x -> CommitmentKeys
forall x. CommitmentKeys -> Rep CommitmentKeys x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. CommitmentKeys -> Rep CommitmentKeys x
from :: forall x. CommitmentKeys -> Rep CommitmentKeys x
$cto :: forall x. Rep CommitmentKeys x -> CommitmentKeys
to :: forall x. Rep CommitmentKeys x -> CommitmentKeys
Generic)

instance NFData CommitmentKeys

-- | Derive the keys for a commitment transaction from both parties'
--   basepoints and funding pubkeys, and the commitment owner's
--   per-commitment point.
--
--   The owner is the "local" party: its delayed and HTLC basepoints
--   give @local_delayedpubkey@ and @local_htlcpubkey@, while the other
--   party's revocation and HTLC basepoints give @revocationpubkey@ and
--   @remote_htlcpubkey@. As every supported 'CommitmentFormat' uses
--   @option_static_remotekey@, @remotepubkey@ is the other party's
--   @payment_basepoint@.
--
--   Fails if a basepoint it derives a key from, or the per-commitment
--   point, is not on the curve.
derive_commitment_keys
  :: Basepoints          -- ^ the owner's basepoints
  -> FundingPubkey       -- ^ the owner's funding pubkey
  -> Basepoints          -- ^ the other party's basepoints
  -> FundingPubkey       -- ^ the other party's funding pubkey
  -> PerCommitmentPoint  -- ^ the owner's per-commitment point
  -> Maybe CommitmentKeys
derive_commitment_keys :: Basepoints
-> FundingPubkey
-> Basepoints
-> FundingPubkey
-> PerCommitmentPoint
-> Maybe CommitmentKeys
derive_commitment_keys = (ByteString -> Maybe Projective)
-> Basepoints
-> FundingPubkey
-> Basepoints
-> FundingPubkey
-> PerCommitmentPoint
-> Maybe CommitmentKeys
derive_commitment_keys_with ByteString -> Maybe Projective
mul_g

-- | As 'derive_commitment_keys', but uses a precomputed 'S.Context'
--   to speed up the scalar multiplications.
derive_commitment_keys'
  :: S.Context
  -> Basepoints
  -> FundingPubkey
  -> Basepoints
  -> FundingPubkey
  -> PerCommitmentPoint
  -> Maybe CommitmentKeys
derive_commitment_keys' :: Context
-> Basepoints
-> FundingPubkey
-> Basepoints
-> FundingPubkey
-> PerCommitmentPoint
-> Maybe CommitmentKeys
derive_commitment_keys' Context
tex = (ByteString -> Maybe Projective)
-> Basepoints
-> FundingPubkey
-> Basepoints
-> FundingPubkey
-> PerCommitmentPoint
-> Maybe CommitmentKeys
derive_commitment_keys_with (Context -> ByteString -> Maybe Projective
mul_g' Context
tex)

derive_commitment_keys_with
  :: (BS.ByteString -> Maybe S.Projective)
  -> Basepoints
  -> FundingPubkey
  -> Basepoints
  -> FundingPubkey
  -> PerCommitmentPoint
  -> Maybe CommitmentKeys
derive_commitment_keys_with :: (ByteString -> Maybe Projective)
-> Basepoints
-> FundingPubkey
-> Basepoints
-> FundingPubkey
-> PerCommitmentPoint
-> Maybe CommitmentKeys
derive_commitment_keys_with ByteString -> Maybe Projective
mul Basepoints
local FundingPubkey
local_fund Basepoints
remote FundingPubkey
remote_fund PerCommitmentPoint
pcp = do
  let DelayedPaymentBasepoint Point
local_delayed_bp = Basepoints -> DelayedPaymentBasepoint
bp_delayed_payment Basepoints
local
      HtlcBasepoint Point
local_htlc_bp = Basepoints -> HtlcBasepoint
bp_htlc Basepoints
local
      HtlcBasepoint Point
remote_htlc_bp = Basepoints -> HtlcBasepoint
bp_htlc Basepoints
remote
      PaymentBasepoint Point
remote_payment_bp = Basepoints -> PaymentBasepoint
bp_payment Basepoints
remote
  revocation   <- RevocationBasepoint -> PerCommitmentPoint -> Maybe RevocationPubkey
derive_revocationpubkey (Basepoints -> RevocationBasepoint
bp_revocation Basepoints
remote) PerCommitmentPoint
pcp
  delayed      <- derive_pubkey_with mul local_delayed_bp pcp
  local_htlc   <- derive_pubkey_with mul local_htlc_bp pcp
  remote_htlc  <- derive_pubkey_with mul remote_htlc_bp pcp
  pure CommitmentKeys
    { ck_revocation_pubkey = revocation
    , ck_local_delayed     = LocalDelayedPubkey delayed
    , ck_local_htlc        = LocalHtlcPubkey local_htlc
    , ck_remote_htlc       = RemoteHtlcPubkey remote_htlc
    , ck_remote_payment    = RemotePubkey remote_payment_bp
    , ck_local_funding     = local_fund
    , ck_remote_funding    = remote_fund
    }

-- private keys ---------------------------------------------------------------

-- | Derive the private key for a per-commitment public key from its
--   basepoint secret:
--
--   @privkey = basepoint_secret + SHA256(per_commitment_point || basepoint)@
--
--   where @basepoint = basepoint_secret * G@. The result is the secret
--   key for @'derive_pubkey' basepoint per_commitment_point@.
--
--   The arithmetic on the secret is constant-time. Fails (with
--   negligible probability) if the result is zero.
--
--   >>> let Just s = BOLT1.per_commitment_secret (BS.pack [31, 30 .. 0])
--   >>> let Just pcp = derive_per_commitment_point s
--   >>> let Just k = seckey (BS.pack [0 .. 31])
--   >>> fmap (B16.encode . un_seckey) (derive_privkey k pcp)
--   Just "cbced912d3b21bf196a766651e436aff192362621ce317704ea2f75d87e7be0f"
derive_privkey :: Seckey -> PerCommitmentPoint -> Maybe Seckey
derive_privkey :: Seckey -> PerCommitmentPoint -> Maybe Seckey
derive_privkey (Seckey ByteString
sk_bs) (PerCommitmentPoint Point
pcp) = do
  sk <- ByteString -> Maybe Wider
S.parse_int256 ByteString
sk_bs
  bp <- to_point =<< S.derive_pub sk
  let !h = ByteString -> ByteString
SHA256.hash (Point -> ByteString
BOLT1.un_point Point
pcp ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Point -> ByteString
BOLT1.un_point Point
bp)
  to_seckey (SC.to sk + SC.to (S.unsafe_roll32 h))

-- | Derive a commitment's @revocationprivkey@ from the revocation
--   basepoint secret and the commitment's (revealed) per-commitment
--   secret:
--
--   @
--   revocationprivkey =
--       revocation_basepoint_secret
--         * SHA256(revocation_basepoint || per_commitment_point)
--     + per_commitment_secret
--         * SHA256(per_commitment_point || revocation_basepoint)
--   @
--
--   The result is the secret key for the 'derive_revocationpubkey'
--   of the corresponding points.
--
--   The arithmetic on the secrets is constant-time. Fails if the
--   per-commitment secret is not a valid secret key, or (with
--   negligible probability) if the result is zero.
--
--   >>> let Just s = BOLT1.per_commitment_secret (BS.pack [31, 30 .. 0])
--   >>> let Just k = seckey (BS.pack [0 .. 31])
--   >>> fmap (B16.encode . un_seckey) (derive_revocationprivkey k s)
--   Just "d09ffff62ddb2297ab000cc85bcb4283fdeb6aa052affbc9dddcf33b61078110"
derive_revocationprivkey
  :: Seckey               -- ^ revocation basepoint secret
  -> PerCommitmentSecret  -- ^ per-commitment secret
  -> Maybe Seckey
derive_revocationprivkey :: Seckey -> PerCommitmentSecret -> Maybe Seckey
derive_revocationprivkey (Seckey ByteString
rbs_bs) PerCommitmentSecret
pcs = do
  let !pcs_bs :: ByteString
pcs_bs = PerCommitmentSecret -> ByteString
BOLT1.un_per_commitment_secret PerCommitmentSecret
pcs
  rbs <- ByteString -> Maybe Wider
S.parse_int256 ByteString
rbs_bs
  ps  <- S.parse_int256 pcs_bs
  rbp <- to_point =<< S.derive_pub rbs
  pcp <- to_point =<< S.derive_pub ps
  let !rbp_bs = Point -> ByteString
BOLT1.un_point Point
rbp
      !pcp_bs = Point -> ByteString
BOLT1.un_point Point
pcp
      !h1 = Wider -> Montgomery
SC.to (ByteString -> Wider
S.unsafe_roll32 (ByteString -> ByteString
SHA256.hash (ByteString
rbp_bs ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
pcp_bs)))
      !h2 = Wider -> Montgomery
SC.to (ByteString -> Wider
S.unsafe_roll32 (ByteString -> ByteString
SHA256.hash (ByteString
pcp_bs ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
rbp_bs)))
  to_seckey (SC.to rbs * h1 + SC.to ps * h2)

-- The secret key for a nonzero scalar. Reduction, arithmetic and the
-- zero check are constant-time (ppad-fixed).
to_seckey :: SC.Montgomery -> Maybe Seckey
to_seckey :: Montgomery -> Maybe Seckey
to_seckey Montgomery
r
  | Choice -> Bool
C.decide (Montgomery -> Montgomery -> Choice
SC.eq Montgomery
r Montgomery
0) = Maybe Seckey
forall a. Maybe a
Nothing
  | Bool
otherwise            = Seckey -> Maybe Seckey
forall a. a -> Maybe a
Just (ByteString -> Seckey
Seckey (Wider -> ByteString
S.unroll32 (Montgomery -> Wider
SC.retr Montgomery
r)))

-- per-commitment secrets -----------------------------------------------------

-- Wrap a 32-byte value as a per-commitment secret.
to_secret :: BS.ByteString -> PerCommitmentSecret
to_secret :: ByteString -> PerCommitmentSecret
to_secret ByteString
bs = case ByteString -> Maybe PerCommitmentSecret
BOLT1.per_commitment_secret ByteString
bs of
  Just PerCommitmentSecret
s  -> PerCommitmentSecret
s
  Maybe PerCommitmentSecret
Nothing -> PerCommitmentSecret
forall a. a
internal_error
{-# INLINE to_secret #-}

-- Flip bit b (< 256) of a 32-byte value: the (b mod 8) bit of the
-- (b div 8) byte.
flip_bit :: Int -> BS.ByteString -> BS.ByteString
flip_bit :: Int -> ByteString -> ByteString
flip_bit Int
b ByteString
bs =
  let !(ByteString
pre, ByteString
post) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt (Int
b Int -> Int -> Int
forall a. Bits a => a -> Int -> a
`shiftR` Int
3) ByteString
bs
  in  case ByteString -> Maybe (Word8, ByteString)
BS.uncons ByteString
post of
        Just (Word8
h, ByteString
t) -> ByteString
pre ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Word8 -> ByteString -> ByteString
BS.cons (Word8 -> Int -> Word8
forall a. Bits a => a -> Int -> a
complementBit Word8
h (Int
b Int -> Int -> Int
forall a. Bits a => a -> a -> a
.&. Int
7)) ByteString
t
        Maybe (Word8, ByteString)
Nothing     -> ByteString
bs
{-# INLINE flip_bit #-}

-- The spec's derive_secret: the secret for index i, from a base
-- secret whose index agrees with i in bits 47 down to 'bits'.
derive_secret :: BS.ByteString -> Int -> Word64 -> BS.ByteString
derive_secret :: ByteString -> Int -> Word64 -> ByteString
derive_secret ByteString
base Int
bits Word64
i = Int -> ByteString -> ByteString
go (Int
bits Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1) ByteString
base where
  go :: Int -> ByteString -> ByteString
go !Int
b !ByteString
p
    | Int
b Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0       = ByteString
p
    | Word64 -> Int -> Bool
forall a. Bits a => a -> Int -> Bool
testBit Word64
i Int
b = Int -> ByteString -> ByteString
go (Int
b Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1) (ByteString -> ByteString
SHA256.hash (Int -> ByteString -> ByteString
flip_bit Int
b ByteString
p))
    | Bool
otherwise   = Int -> ByteString -> ByteString
go (Int
b Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1) ByteString
p

-- | Generate the per-commitment secret with a given index from a seed,
--   per BOLT #3's @generate_from_seed@.
--
--   >>> let Just s = seed (BS.replicate 32 0xff)
--   >>> let Just i = secret_index 281474976710655
--   >>> B16.encode (BOLT1.un_per_commitment_secret (generate_from_seed s i))
--   "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc"
generate_from_seed :: Seed -> SecretIndex -> PerCommitmentSecret
generate_from_seed :: Seed -> SecretIndex -> PerCommitmentSecret
generate_from_seed (Seed ByteString
s) (SecretIndex Word64
i) = ByteString -> PerCommitmentSecret
to_secret (ByteString -> Int -> Word64 -> ByteString
derive_secret ByteString
s Int
48 Word64
i)

-- | Compact storage for the per-commitment secrets received from a
--   peer, per BOLT #3's "Efficient Per-commitment Secret Storage".
--
--   Holds at most 49 secrets, from which every secret received so far
--   can be derived. This is secret material: its 'Show' instance is
--   redacted, and it has no 'Eq' instance.
newtype SecretStore = SecretStore [Entry]

-- A stored secret: its bucket (the number of trailing zeros of its
-- index), index, and value. Kept in ascending bucket order.
data Entry = Entry
  {-# UNPACK #-} !Int
  {-# UNPACK #-} !Word64
  !BS.ByteString

instance Show SecretStore where
  showsPrec :: Int -> SecretStore -> ShowS
showsPrec Int
d SecretStore
_ = Bool -> ShowS -> ShowS
showParen (Int
d Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
10) (ShowS -> ShowS) -> ShowS -> ShowS
forall a b. (a -> b) -> a -> b
$
    String -> ShowS
showString String
"SecretStore <redacted>"

instance NFData SecretStore where
  rnf :: SecretStore -> ()
rnf (SecretStore [Entry]
es) = [Entry] -> ()
rnf_entries [Entry]
es where
    rnf_entries :: [Entry] -> ()
rnf_entries [] = ()
    rnf_entries (Entry Int
_ Word64
_ ByteString
s : [Entry]
rest) = ByteString -> ()
forall a. NFData a => a -> ()
rnf ByteString
s () -> () -> ()
forall a b. a -> b -> b
`seq` [Entry] -> ()
rnf_entries [Entry]
rest

-- | The empty 'SecretStore'.
empty_secret_store :: SecretStore
empty_secret_store :: SecretStore
empty_secret_store = [Entry] -> SecretStore
SecretStore []

-- The bucket for an index: its number of trailing zeros (48 for 0).
bucket_of :: Word64 -> Int
bucket_of :: Word64 -> Int
bucket_of Word64
i = Int -> Int
go Int
0 where
  go :: Int -> Int
go !Int
b
    | Int
b Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
47      = Int
48
    | Word64 -> Int -> Bool
forall a. Bits a => a -> Int -> Bool
testBit Word64
i Int
b = Int
b
    | Bool
otherwise   = Int -> Int
go (Int
b Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)

-- Whether a secret at index j in bucket b can derive index i.
can_derive :: Int -> Word64 -> Word64 -> Bool
can_derive :: Int -> Word64 -> Word64 -> Bool
can_derive Int
b Word64
j Word64
i = Word64
i Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.&. Word64 -> Word64
forall a. Bits a => a -> a
complement ((Word64
1 Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
`shiftL` Int
b) Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Word64
1) Word64 -> Word64 -> Bool
forall a. Eq a => a -> a -> Bool
== Word64
j
{-# INLINE can_derive #-}

-- | Add a newly received per-commitment secret to the store, per
--   BOLT #3's @insert_secret@.
--
--   Fails if a stored secret cannot be derived from the new one, i.e.
--   if the secrets were not generated from the same seed (or were not
--   received in order).
--
--   >>> let Just s = seed (BS.replicate 32 0xff)
--   >>> let Just i = secret_index 281474976710655
--   >>> let secret = generate_from_seed s i
--   >>> let Just st = insert_secret secret i empty_secret_store
--   >>> fmap (== secret) (derive_old_secret i st)
--   Just True
insert_secret
  :: PerCommitmentSecret
  -> SecretIndex
  -> SecretStore
  -> Maybe SecretStore
insert_secret :: PerCommitmentSecret
-> SecretIndex -> SecretStore -> Maybe SecretStore
insert_secret PerCommitmentSecret
pcs (SecretIndex Word64
i) (SecretStore [Entry]
known)
  | (Entry -> Bool) -> [Entry] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Entry -> Bool
derives [Entry]
known = SecretStore -> Maybe SecretStore
forall a. a -> Maybe a
Just (SecretStore -> Maybe SecretStore)
-> SecretStore -> Maybe SecretStore
forall a b. (a -> b) -> a -> b
$! [Entry] -> SecretStore
SecretStore ([Entry] -> [Entry]
put [Entry]
known)
  | Bool
otherwise         = Maybe SecretStore
forall a. Maybe a
Nothing
  where
    !s :: ByteString
s = PerCommitmentSecret -> ByteString
BOLT1.un_per_commitment_secret PerCommitmentSecret
pcs
    !b :: Int
b = Word64 -> Int
bucket_of Word64
i
    !e :: Entry
e = Int -> Word64 -> ByteString -> Entry
Entry Int
b Word64
i ByteString
s

    -- every secret in a lower bucket must derive from the new one
    derives :: Entry -> Bool
derives (Entry Int
kb Word64
ki ByteString
ks)
      | Int
kb Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
b    = ByteString -> PerCommitmentSecret
to_secret (ByteString -> Int -> Word64 -> ByteString
derive_secret ByteString
s Int
b Word64
ki) PerCommitmentSecret -> PerCommitmentSecret -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString -> PerCommitmentSecret
to_secret ByteString
ks
      | Bool
otherwise = Bool
True

    -- replace this bucket's entry, keeping ascending bucket order
    put :: [Entry] -> [Entry]
put [] = [Entry
e]
    put (k :: Entry
k@(Entry Int
kb Word64
_ ByteString
_) : [Entry]
ks) = case Int -> Int -> Ordering
forall a. Ord a => a -> a -> Ordering
compare Int
kb Int
b of
      Ordering
LT -> Entry
k Entry -> [Entry] -> [Entry]
forall a. a -> [a] -> [a]
: [Entry] -> [Entry]
put [Entry]
ks
      Ordering
EQ -> Entry
e Entry -> [Entry] -> [Entry]
forall a. a -> [a] -> [a]
: [Entry]
ks
      Ordering
GT -> Entry
e Entry -> [Entry] -> [Entry]
forall a. a -> [a] -> [a]
: Entry
k Entry -> [Entry] -> [Entry]
forall a. a -> [a] -> [a]
: [Entry]
ks

-- | Derive a previously received per-commitment secret from the
--   store. Fails if the index has not been received.
derive_old_secret
  :: SecretIndex
  -> SecretStore
  -> Maybe PerCommitmentSecret
derive_old_secret :: SecretIndex -> SecretStore -> Maybe PerCommitmentSecret
derive_old_secret (SecretIndex Word64
i) (SecretStore [Entry]
known) = [Entry] -> Maybe PerCommitmentSecret
go [Entry]
known where
  go :: [Entry] -> Maybe PerCommitmentSecret
go [] = Maybe PerCommitmentSecret
forall a. Maybe a
Nothing
  go (Entry Int
b Word64
j ByteString
s : [Entry]
rest)
    | Int -> Word64 -> Word64 -> Bool
can_derive Int
b Word64
j Word64
i = PerCommitmentSecret -> Maybe PerCommitmentSecret
forall a. a -> Maybe a
Just (PerCommitmentSecret -> Maybe PerCommitmentSecret)
-> PerCommitmentSecret -> Maybe PerCommitmentSecret
forall a b. (a -> b) -> a -> b
$! ByteString -> PerCommitmentSecret
to_secret (ByteString -> Int -> Word64 -> ByteString
derive_secret ByteString
s Int
b Word64
i)
    | Bool
otherwise        = [Entry] -> Maybe PerCommitmentSecret
go [Entry]
rest

-- | Rebuild a 'SecretStore' from its entries, e.g. as produced by
--   'un_secret_store'.
--
--   Fails if two entries share a bucket (i.e. their indices have the
--   same number of trailing zeros), or if an entry contradicts another
--   from which it can be derived.
secret_store
  :: [(SecretIndex, PerCommitmentSecret)]
  -> Maybe SecretStore
secret_store :: [(SecretIndex, PerCommitmentSecret)] -> Maybe SecretStore
secret_store = [Entry]
-> [(SecretIndex, PerCommitmentSecret)] -> Maybe SecretStore
go [] where
  go :: [Entry]
-> [(SecretIndex, PerCommitmentSecret)] -> Maybe SecretStore
go [Entry]
acc [] = SecretStore -> Maybe SecretStore
forall a. a -> Maybe a
Just ([Entry] -> SecretStore
SecretStore [Entry]
acc)
  go [Entry]
acc ((SecretIndex Word64
i, PerCommitmentSecret
pcs) : [(SecretIndex, PerCommitmentSecret)]
rest) = do
    let !e :: Entry
e = Int -> Word64 -> ByteString -> Entry
Entry (Word64 -> Int
bucket_of Word64
i) Word64
i (PerCommitmentSecret -> ByteString
BOLT1.un_per_commitment_secret PerCommitmentSecret
pcs)
    acc' <- Entry -> [Entry] -> Maybe [Entry]
place Entry
e [Entry]
acc
    go acc' rest

  -- insert in ascending bucket order, checking consistency with the
  -- entries already placed
  place :: Entry -> [Entry] -> Maybe [Entry]
place e :: Entry
e@(Entry Int
b Word64
i ByteString
s) [Entry]
es
    | (Entry -> Bool) -> [Entry] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (Entry -> Entry -> Bool
forall {p}. p -> Entry -> Bool
consistent Entry
e) [Entry]
es = [Entry] -> Maybe [Entry]
put [Entry]
es
    | Bool
otherwise             = Maybe [Entry]
forall a. Maybe a
Nothing
    where
      put :: [Entry] -> Maybe [Entry]
put [] = [Entry] -> Maybe [Entry]
forall a. a -> Maybe a
Just [Entry
e]
      put (k :: Entry
k@(Entry Int
kb Word64
_ ByteString
_) : [Entry]
ks) = case Int -> Int -> Ordering
forall a. Ord a => a -> a -> Ordering
compare Int
kb Int
b of
        Ordering
LT -> (Entry
k Entry -> [Entry] -> [Entry]
forall a. a -> [a] -> [a]
:) ([Entry] -> [Entry]) -> Maybe [Entry] -> Maybe [Entry]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [Entry] -> Maybe [Entry]
put [Entry]
ks
        Ordering
EQ -> Maybe [Entry]
forall a. Maybe a
Nothing
        Ordering
GT -> [Entry] -> Maybe [Entry]
forall a. a -> Maybe a
Just (Entry
e Entry -> [Entry] -> [Entry]
forall a. a -> [a] -> [a]
: Entry
k Entry -> [Entry] -> [Entry]
forall a. a -> [a] -> [a]
: [Entry]
ks)
      consistent :: p -> Entry -> Bool
consistent p
_ (Entry Int
kb Word64
ki ByteString
ks)
        | Int
kb Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
b Bool -> Bool -> Bool
&& Int -> Word64 -> Word64 -> Bool
can_derive Int
kb Word64
ki Word64
i =
            ByteString -> PerCommitmentSecret
to_secret (ByteString -> Int -> Word64 -> ByteString
derive_secret ByteString
ks Int
kb Word64
i) PerCommitmentSecret -> PerCommitmentSecret -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString -> PerCommitmentSecret
to_secret ByteString
s
        | Int
kb Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
b Bool -> Bool -> Bool
&& Int -> Word64 -> Word64 -> Bool
can_derive Int
b Word64
i Word64
ki =
            ByteString -> PerCommitmentSecret
to_secret (ByteString -> Int -> Word64 -> ByteString
derive_secret ByteString
s Int
b Word64
ki) PerCommitmentSecret -> PerCommitmentSecret -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString -> PerCommitmentSecret
to_secret ByteString
ks
        | Bool
otherwise = Bool
True

-- | The entries of a 'SecretStore', for persistence; see
--   'secret_store'.
un_secret_store :: SecretStore -> [(SecretIndex, PerCommitmentSecret)]
un_secret_store :: SecretStore -> [(SecretIndex, PerCommitmentSecret)]
un_secret_store (SecretStore [Entry]
es) =
  [ (Word64 -> SecretIndex
SecretIndex Word64
i, ByteString -> PerCommitmentSecret
to_secret ByteString
s) | Entry Int
_ Word64
i ByteString
s <- [Entry]
es ]

-- commitment number obscuring ------------------------------------------------

-- | Obscure a commitment number, by XOR with the lower 48 bits of
--
--   @SHA256(payment_basepoint from open_channel
--           || payment_basepoint from accept_channel)@
--
--   As XOR is an involution, applying this to an obscured number
--   recovers the commitment number. ('build_commitment_tx' obscures
--   the commitment number itself.)
--
--   >>> let pay h = fmap PaymentBasepoint (BOLT1.point =<< B16.decode h)
--   >>> let o1 = "034f355bdcb7cc0af728ef3cceb9615d9068"
--   >>> let Just o = pay (o1 <> "4bb5b2ca5f859ab0f0b704075871aa")
--   >>> let a1 = "032c0b7cf95324a07d05398b240174dc0c2b"
--   >>> let Just a = pay (a1 <> "e444d96b159aa6c7f7b1e668680991")
--   >>> fmap (obscured_commitment_number o a) (commitment_number 42)
--   Just 48035859142974
obscured_commitment_number
  :: PaymentBasepoint   -- ^ opener's payment_basepoint
  -> PaymentBasepoint   -- ^ accepter's payment_basepoint
  -> CommitmentNumber
  -> Word64
obscured_commitment_number :: PaymentBasepoint -> PaymentBasepoint -> CommitmentNumber -> Word64
obscured_commitment_number
  (PaymentBasepoint Point
opener)
  (PaymentBasepoint Point
accepter)
  CommitmentNumber
cn =
    let !h :: ByteString
h = ByteString -> ByteString
SHA256.hash (Point -> ByteString
BOLT1.un_point Point
opener ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Point -> ByteString
BOLT1.un_point Point
accepter)
        !mask :: Word64
mask = (Word64 -> Word8 -> Word64) -> Word64 -> ByteString -> Word64
forall a. (a -> Word8 -> a) -> a -> ByteString -> a
BS.foldl' (\Word64
acc Word8
x -> (Word64
acc Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
`shiftL` Int
8) Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.|. Word8 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
x) Word64
0
                  (Int -> ByteString -> ByteString
BS.drop Int
26 ByteString
h)
    in  CommitmentNumber -> Word64
un_commitment_number CommitmentNumber
cn Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
`xor` Word64
mask