| Copyright | (c) 2025 Jared Tobin |
|---|---|
| License | MIT |
| Maintainer | Jared Tobin <jared@ppad.tech> |
| Safe Haskell | None |
| Language | Haskell2010 |
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 iTrue
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,ReceiverorPendingreturns 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 sameSenderreuses a nonce, which reveals the XOR of the two plaintexts and allows forgeries, and decrypting with an oldReceiveraccepts replayed frames.
- Ephemeral entropy must be fresh. The 32 bytes passed to
act1andact2are 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
encryptrejecting an oversized message, which advances nothing.
Synopsis
- data Keypair
- keypair :: ByteString -> Maybe Keypair
- keypair_pub :: Keypair -> Pub
- data Pub
- parse_pub :: ByteString -> Maybe Pub
- serialize_pub :: Pub -> ByteString
- data Handshake
- handshake_sender :: Handshake -> Sender
- handshake_receiver :: Handshake -> Receiver
- handshake_remote_static :: Handshake -> Pub
- data Initiator
- act1 :: Keypair -> Pub -> ByteString -> Either Error (ByteString, Initiator)
- act3 :: Initiator -> ByteString -> Either Error (ByteString, Handshake)
- data Responder
- act2 :: Keypair -> ByteString -> ByteString -> Either Error (ByteString, Responder)
- finalize :: Responder -> ByteString -> Either Error Handshake
- data Sender
- encrypt :: Sender -> ByteString -> Either Error (ByteString, Sender)
- data Receiver
- decrypt :: Receiver -> ByteString -> Either Error (ByteString, Receiver)
- data Pending
- decrypt_header :: Receiver -> ByteString -> Either Error (Int, Pending)
- decrypt_body :: Pending -> ByteString -> Either Error (ByteString, Receiver)
- data Error
Keys
A secp256k1 keypair: a secret key and its public key.
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 rPub "028d7500dd4c12685d1f568b4c2b5048e8534b873319f3a8daa612b469132ec7f7"
A secp256k1 public key.
Show renders the 33-byte compressed encoding in hex.
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
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.
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
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
Arguments
| :: Initiator | state from |
| -> 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
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
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 iTrue
Transport
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
State for decrypting incoming messages.
Each decrypt or decrypt_header consumes the Receiver.
Never use a Receiver twice: doing so accepts replayed frames.
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
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.
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
Arguments
| :: Pending | state from |
| -> 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
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
| NFData Error Source # | |||||
Defined in Lightning.Protocol.BOLT8 | |||||
| Generic Error Source # | |||||
Defined in Lightning.Protocol.BOLT8 Associated Types
| |||||
| Show Error Source # | |||||
| Eq Error Source # | |||||
| type Rep Error Source # | |||||
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)))) | |||||