ppad-bolt8-0.1.1: Encrypted and authenticated transport per BOLT #8
Copyright(c) 2025 Jared Tobin
LicenseMIT
MaintainerJared Tobin <jared@ppad.tech>
Safe HaskellNone
LanguageHaskell2010

Lightning.Protocol.BOLT8

Description

Encrypted and authenticated transport for the Lightning Network, per BOLT #8: the Noise_XK_secp256k1_ChaChaPoly_SHA256 handshake, followed by length-prefixed, authenticated encryption of messages.

The library is pure; reading from and writing to the network is up to the caller.

Handshake

The initiator knows the responder's static public key in advance. It sends act one (act1), receives act two, and replies with act three (act3). The responder receives act one, replies with act two (act2), and receives act three (finalize), which authenticates the initiator's static key. Both sides end up with a Handshake.

>>> :set -XOverloadedStrings
>>> import qualified Data.ByteString as BS
>>> let Just i = keypair (BS.replicate 32 0x11)
>>> let Just r = keypair (BS.replicate 32 0x21)
>>> -- initiator, knowing r's public key; entropy must be random!
>>> let Right (msg1, i_hs) = act1 i (keypair_pub r) (BS.replicate 32 0x12)
>>> -- responder
>>> let Right (msg2, r_hs) = act2 r (BS.replicate 32 0x22) msg1
>>> -- initiator
>>> let Right (msg3, i_res) = act3 i_hs msg2
>>> -- responder
>>> let Right r_res = finalize r_hs msg3
>>> handshake_remote_static r_res == keypair_pub i
True

Transport

A Handshake carries a Sender for outgoing messages and a Receiver for incoming ones. They are independent, so a writer thread can own the Sender and a reader thread the Receiver.

>>> let Right (ct, i_snd) = encrypt (handshake_sender i_res) "hello"
>>> fmap fst (decrypt (handshake_receiver r_res) ct)
Right "hello"

On a byte stream, read exactly 18 bytes and pass them to decrypt_header, which returns the number of bytes to read next; then read exactly that many bytes and pass them to decrypt_body. decrypt does both for a buffer holding exactly one frame.

Keys rotate every 1000 nonces, i.e. every 500 messages in each direction; this is handled internally. Messages are at most 65535 bytes.

Security

  • Use each state exactly once. Every function that takes an Initiator, Responder, Sender, Receiver or Pending returns the next state, and the caller must continue with that. States are ordinary immutable values, so nothing stops an old one from being used again, and doing so is catastrophic: encrypting twice with the same Sender reuses a nonce, which reveals the XOR of the two plaintexts and allows forgeries, and decrypting with an old Receiver accepts replayed frames.
  • Ephemeral entropy must be fresh. The 32 bytes passed to act1 and act2 are used directly as the ephemeral secret key. They must come from a cryptographically secure random source, be uniformly random, and never be reused.
  • Any error is fatal. BOLT #8 requires terminating the connection on any handshake or transport failure. Don't retry with the previous state. The one exception is encrypt rejecting an oversized message, which advances nothing.
Synopsis

Keys

data Keypair Source #

A secp256k1 keypair: a secret key and its public key.

Has no Show or Eq instance, as it contains secret material.

Instances

Instances details
NFData Keypair Source # 
Instance details

Defined in Lightning.Protocol.BOLT8

Methods

rnf :: Keypair -> () #

keypair :: ByteString -> Maybe Keypair Source #

Construct a keypair from a 32-byte secret key.

The bytes are used directly as the secret key, so they must be uniformly random and kept secret. Returns Nothing if the input is not 32 bytes, or is not a valid secp256k1 secret key (zero, or not less than the curve order).

>>> import Data.Maybe (isJust)
>>> isJust (keypair (BS.replicate 32 0x11))
True
>>> isJust (keypair (BS.replicate 32 0x00))
False

keypair_pub :: Keypair -> Pub Source #

The public key of a keypair.

>>> let Just r = keypair (BS.replicate 32 0x21)
>>> keypair_pub r
Pub "028d7500dd4c12685d1f568b4c2b5048e8534b873319f3a8daa612b469132ec7f7"

data Pub Source #

A secp256k1 public key.

Show renders the 33-byte compressed encoding in hex.

Instances

Instances details
NFData Pub Source # 
Instance details

Defined in Lightning.Protocol.BOLT8

Methods

rnf :: Pub -> () #

Show Pub Source # 
Instance details

Defined in Lightning.Protocol.BOLT8

Methods

showsPrec :: Int -> Pub -> ShowS #

show :: Pub -> String #

showList :: [Pub] -> ShowS #

Eq Pub Source # 
Instance details

Defined in Lightning.Protocol.BOLT8

Methods

(==) :: Pub -> Pub -> Bool #

(/=) :: Pub -> Pub -> Bool #

parse_pub :: ByteString -> Maybe Pub Source #

Parse a 33-byte compressed public key.

>>> let Just r = keypair (BS.replicate 32 0x21)
>>> parse_pub (serialize_pub (keypair_pub r)) == Just (keypair_pub r)
True
>>> parse_pub (BS.replicate 33 0x04)
Nothing

serialize_pub :: Pub -> ByteString Source #

Serialize a public key in 33-byte compressed form.

>>> let Just r = keypair (BS.replicate 32 0x21)
>>> BS.length (serialize_pub (keypair_pub r))
33

Handshake

data Handshake Source #

The result of a successful handshake: the initial transport states and the remote party's authenticated static public key.

Take the Sender and Receiver out once, right after the handshake, and don't keep the Handshake around: it always yields the initial states, and encrypting with the initial Sender a second time reuses a nonce.

Instances

Instances details
NFData Handshake Source # 
Instance details

Defined in Lightning.Protocol.BOLT8

Methods

rnf :: Handshake -> () #

handshake_sender :: Handshake -> Sender Source #

The initial Sender, for encrypting outgoing messages.

Call this once per handshake. Every call returns the same initial state, so encrypting with the result of a second call reuses a nonce.

handshake_receiver :: Handshake -> Receiver Source #

The initial Receiver, for decrypting incoming messages.

Call this once per handshake. Every call returns the same initial state, so decrypting with the result of a second call accepts replayed frames.

handshake_remote_static :: Handshake -> Pub Source #

The remote party's static public key, authenticated by the handshake. For the initiator, this is the key passed to act1.

Initiator

data Initiator Source #

The initiator's handshake state between acts one and three.

Produced by act1 and consumed by act3. Contains secret material; use it once.

Instances

Instances details
NFData Initiator Source # 
Instance details

Defined in Lightning.Protocol.BOLT8

Methods

rnf :: Initiator -> () #

act1 Source #

Arguments

:: Keypair

local static keypair

-> Pub

responder's static public key

-> ByteString

32 bytes of fresh entropy

-> Either Error (ByteString, Initiator) 

Initiator: produce act one (50 bytes).

Takes the local static keypair, the responder's static public key, and 32 bytes of entropy for the ephemeral key. Returns act one and the state for act3.

The entropy is used directly as the ephemeral secret key. It must be fresh, uniformly random output of a cryptographically secure random source, and must never be reused. Fails with InvalidEntropy if it is not a valid secret key.

>>> let Just i = keypair (BS.replicate 32 0x11)
>>> let Just r = keypair (BS.replicate 32 0x21)
>>> let ent = BS.replicate 32 0x12 -- use random bytes in practice
>>> fmap (BS.length . fst) (act1 i (keypair_pub r) ent)
Right 50

act3 Source #

Arguments

:: Initiator

state from act1

-> ByteString

act two

-> Either Error (ByteString, Handshake) 

Initiator: process act two and produce act three (66 bytes), completing the handshake.

Any error means the connection must be terminated.

Continuing the module-level example:

>>> fmap (BS.length . fst) (act3 i_hs msg2)
Right 66

Responder

data Responder Source #

The responder's handshake state between acts two and three.

Produced by act2 and consumed by finalize. Contains secret material; use it once.

Instances

Instances details
NFData Responder Source # 
Instance details

Defined in Lightning.Protocol.BOLT8

Methods

rnf :: Responder -> () #

act2 Source #

Arguments

:: Keypair

local static keypair

-> ByteString

32 bytes of fresh entropy

-> ByteString

act one

-> Either Error (ByteString, Responder) 

Responder: process act one and produce act two (50 bytes).

Takes the local static keypair, 32 bytes of entropy for the ephemeral key, and act one. Returns act two and the state for finalize.

The entropy is used directly as the ephemeral secret key. It must be fresh, uniformly random output of a cryptographically secure random source, and must never be reused. Fails with InvalidEntropy if it is not a valid secret key.

Any error means the connection must be terminated.

>>> let Just i = keypair (BS.replicate 32 0x11)
>>> let Just r = keypair (BS.replicate 32 0x21)
>>> let Right (msg1, _) = act1 i (keypair_pub r) (BS.replicate 32 0x12)
>>> fmap (BS.length . fst) (act2 r (BS.replicate 32 0x22) msg1)
Right 50
>>> fmap fst (act2 r (BS.replicate 32 0x22) (BS.take 49 msg1))
Left InvalidLength

finalize Source #

Arguments

:: Responder

state from act2

-> ByteString

act three

-> Either Error Handshake 

Responder: process act three, completing the handshake and authenticating the initiator's static public key.

Any error means the connection must be terminated.

Continuing the module-level example:

>>> let Right r_res' = finalize r_hs msg3
>>> handshake_remote_static r_res' == keypair_pub i
True

Transport

data Sender Source #

State for encrypting outgoing messages.

Each encrypt returns the next Sender. Never use a Sender twice: doing so reuses a nonce.

Instances

Instances details
NFData Sender Source # 
Instance details

Defined in Lightning.Protocol.BOLT8

Methods

rnf :: Sender -> () #

encrypt Source #

Arguments

:: Sender

current state

-> ByteString

message

-> Either Error (ByteString, Sender) 

Encrypt a message of at most 65535 bytes.

Returns the frame to send (the message length plus 34 bytes) and the next Sender, which must be used for the following message. Encrypting with the same Sender twice reuses a nonce and breaks confidentiality and authenticity.

Fails only with InvalidLength, for an oversized message. Nothing is encrypted in that case, so the given Sender remains the current one and the connection can continue.

Continuing the module-level example:

>>> fmap (BS.length . fst) (encrypt i_snd "hello")
Right 39
>>> fmap fst (encrypt i_snd (BS.replicate 65536 0x00))
Left InvalidLength

data Receiver Source #

State for decrypting incoming messages.

Each decrypt or decrypt_header consumes the Receiver. Never use a Receiver twice: doing so accepts replayed frames.

Instances

Instances details
NFData Receiver Source # 
Instance details

Defined in Lightning.Protocol.BOLT8

Methods

rnf :: Receiver -> () #

decrypt Source #

Arguments

:: Receiver

current state

-> ByteString

one frame

-> Either Error (ByteString, Receiver) 

Decrypt a buffer holding exactly one frame.

Returns the message and the next Receiver. Fails with InvalidLength if the buffer is not exactly one frame, and with InvalidMAC if authentication fails. Any error means the connection must be terminated.

Continuing the module-level example:

>>> fmap fst (decrypt (handshake_receiver r_res) ct)
Right "hello"
>>> fmap fst (decrypt (handshake_receiver r_res) (BS.take 38 ct))
Left InvalidLength

data Pending Source #

A Receiver that has decrypted a frame header and awaits the frame body.

Produced by decrypt_header and consumed by decrypt_body. Use it once.

Instances

Instances details
NFData Pending Source # 
Instance details

Defined in Lightning.Protocol.BOLT8

Methods

rnf :: Pending -> () #

decrypt_header Source #

Arguments

:: Receiver

current state

-> ByteString

18-byte header

-> Either Error (Int, Pending) 

Decrypt the 18-byte header (encrypted length and its MAC) at the start of a frame.

Returns the number of bytes in the rest of the frame (the message length plus a 16-byte MAC), which the caller should read exactly, and the state for decrypt_body. Fails with InvalidLength if the input is not 18 bytes, and with InvalidMAC if authentication fails. Any error means the connection must be terminated.

Continuing the module-level example:

>>> fmap fst (decrypt_header (handshake_receiver r_res) (BS.take 18 ct))
Right 21

decrypt_body Source #

Arguments

:: Pending

state from decrypt_header

-> ByteString

the rest of the frame

-> Either Error (ByteString, Receiver) 

Decrypt the rest of a frame, following decrypt_header.

The input must be exactly as long as decrypt_header reported. Returns the message and the next Receiver. Fails with InvalidLength on a length mismatch, and with InvalidMAC if authentication fails. Any error means the connection must be terminated.

Continuing the module-level example:

>>> let (hdr, rest) = BS.splitAt 18 ct
>>> let Right (n, p) = decrypt_header (handshake_receiver r_res) hdr
>>> fmap fst (decrypt_body p (BS.take n rest))
Right "hello"

Errors

data Error Source #

Handshake and transport errors.

Any error is fatal for the connection.

Constructors

InvalidEntropy

ephemeral entropy is not a valid secret key

InvalidLength

input of the wrong length, or a payload over 65535 bytes

InvalidVersion

unknown handshake version

InvalidPub

invalid public key in a handshake message

InvalidMAC

authentication failed

Instances

Instances details
NFData Error Source # 
Instance details

Defined in Lightning.Protocol.BOLT8

Methods

rnf :: Error -> () #

Generic Error Source # 
Instance details

Defined in Lightning.Protocol.BOLT8

Associated Types

type Rep Error 
Instance details

Defined in Lightning.Protocol.BOLT8

type Rep Error = D1 ('MetaData "Error" "Lightning.Protocol.BOLT8" "ppad-bolt8-0.1.1-A95ZCGZdbOV7qKTGkOanF3" 'False) ((C1 ('MetaCons "InvalidEntropy" 'PrefixI 'False) (U1 :: Type -> Type) :+: C1 ('MetaCons "InvalidLength" 'PrefixI 'False) (U1 :: Type -> Type)) :+: (C1 ('MetaCons "InvalidVersion" 'PrefixI 'False) (U1 :: Type -> Type) :+: (C1 ('MetaCons "InvalidPub" 'PrefixI 'False) (U1 :: Type -> Type) :+: C1 ('MetaCons "InvalidMAC" 'PrefixI 'False) (U1 :: Type -> Type))))

Methods

from :: Error -> Rep Error x #

to :: Rep Error x -> Error #

Show Error Source # 
Instance details

Defined in Lightning.Protocol.BOLT8

Methods

showsPrec :: Int -> Error -> ShowS #

show :: Error -> String #

showList :: [Error] -> ShowS #

Eq Error Source # 
Instance details

Defined in Lightning.Protocol.BOLT8

Methods

(==) :: Error -> Error -> Bool #

(/=) :: Error -> Error -> Bool #

type Rep Error Source # 
Instance details

Defined in Lightning.Protocol.BOLT8

type Rep Error = D1 ('MetaData "Error" "Lightning.Protocol.BOLT8" "ppad-bolt8-0.1.1-A95ZCGZdbOV7qKTGkOanF3" 'False) ((C1 ('MetaCons "InvalidEntropy" 'PrefixI 'False) (U1 :: Type -> Type) :+: C1 ('MetaCons "InvalidLength" 'PrefixI 'False) (U1 :: Type -> Type)) :+: (C1 ('MetaCons "InvalidVersion" 'PrefixI 'False) (U1 :: Type -> Type) :+: (C1 ('MetaCons "InvalidPub" 'PrefixI 'False) (U1 :: Type -> Type) :+: C1 ('MetaCons "InvalidMAC" 'PrefixI 'False) (U1 :: Type -> Type))))