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

-- |
-- Module: Lightning.Protocol.BOLT1.TLV
-- Copyright: (c) 2025 Jared Tobin
-- License: MIT
-- Maintainer: Jared Tobin <jared@ppad.tech>
--
-- The TLV (type-length-value) format of BOLT #1.

module Lightning.Protocol.BOLT1.TLV (
    TlvRecord(..)
  , TlvStream
  , tlv_stream
  , un_tlv_stream
  , empty_tlv_stream
  , lookup_tlv
  , filter_tlv_stream
  , TlvError(..)
  , encode_tlv_stream
  , decode_tlv_stream
  ) where

import Control.DeepSeq (NFData)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Unsafe as BU
import qualified Data.List as L
import Data.Word (Word64)
import GHC.Generics (Generic)
import Lightning.Protocol.BOLT1.Prim

-- | A single TLV record.
data TlvRecord = TlvRecord
  { TlvRecord -> Word64
tlv_type  :: {-# UNPACK #-} !Word64
  , TlvRecord -> ByteString
tlv_value :: !BS.ByteString
  } deriving (TlvRecord -> TlvRecord -> Bool
(TlvRecord -> TlvRecord -> Bool)
-> (TlvRecord -> TlvRecord -> Bool) -> Eq TlvRecord
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: TlvRecord -> TlvRecord -> Bool
== :: TlvRecord -> TlvRecord -> Bool
$c/= :: TlvRecord -> TlvRecord -> Bool
/= :: TlvRecord -> TlvRecord -> Bool
Eq, Int -> TlvRecord -> ShowS
[TlvRecord] -> ShowS
TlvRecord -> String
(Int -> TlvRecord -> ShowS)
-> (TlvRecord -> String)
-> ([TlvRecord] -> ShowS)
-> Show TlvRecord
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> TlvRecord -> ShowS
showsPrec :: Int -> TlvRecord -> ShowS
$cshow :: TlvRecord -> String
show :: TlvRecord -> String
$cshowList :: [TlvRecord] -> ShowS
showList :: [TlvRecord] -> ShowS
Show, (forall x. TlvRecord -> Rep TlvRecord x)
-> (forall x. Rep TlvRecord x -> TlvRecord) -> Generic TlvRecord
forall x. Rep TlvRecord x -> TlvRecord
forall x. TlvRecord -> Rep TlvRecord x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. TlvRecord -> Rep TlvRecord x
from :: forall x. TlvRecord -> Rep TlvRecord x
$cto :: forall x. Rep TlvRecord x -> TlvRecord
to :: forall x. Rep TlvRecord x -> TlvRecord
Generic)

instance NFData TlvRecord

-- | A TLV stream: records in strictly increasing type order.
newtype TlvStream = TlvStream [TlvRecord]
  deriving (TlvStream -> TlvStream -> Bool
(TlvStream -> TlvStream -> Bool)
-> (TlvStream -> TlvStream -> Bool) -> Eq TlvStream
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: TlvStream -> TlvStream -> Bool
== :: TlvStream -> TlvStream -> Bool
$c/= :: TlvStream -> TlvStream -> Bool
/= :: TlvStream -> TlvStream -> Bool
Eq, Int -> TlvStream -> ShowS
[TlvStream] -> ShowS
TlvStream -> String
(Int -> TlvStream -> ShowS)
-> (TlvStream -> String)
-> ([TlvStream] -> ShowS)
-> Show TlvStream
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> TlvStream -> ShowS
showsPrec :: Int -> TlvStream -> ShowS
$cshow :: TlvStream -> String
show :: TlvStream -> String
$cshowList :: [TlvStream] -> ShowS
showList :: [TlvStream] -> ShowS
Show, (forall x. TlvStream -> Rep TlvStream x)
-> (forall x. Rep TlvStream x -> TlvStream) -> Generic TlvStream
forall x. Rep TlvStream x -> TlvStream
forall x. TlvStream -> Rep TlvStream x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. TlvStream -> Rep TlvStream x
from :: forall x. TlvStream -> Rep TlvStream x
$cto :: forall x. Rep TlvStream x -> TlvStream
to :: forall x. Rep TlvStream x -> TlvStream
Generic)

instance NFData TlvStream

-- | Construct a 'TlvStream' from records in any order. Fails if two
--   records share a type.
--
--   >>> let Just s = tlv_stream [TlvRecord 3 "b", TlvRecord 1 "a"]
--   >>> map tlv_type (un_tlv_stream s)
--   [1,3]
--   >>> tlv_stream [TlvRecord 1 "a", TlvRecord 1 "b"]
--   Nothing
tlv_stream :: [TlvRecord] -> Maybe TlvStream
tlv_stream :: [TlvRecord] -> Maybe TlvStream
tlv_stream [TlvRecord]
rs
  | [TlvRecord] -> Bool
increasing [TlvRecord]
sorted = TlvStream -> Maybe TlvStream
forall a. a -> Maybe a
Just ([TlvRecord] -> TlvStream
TlvStream [TlvRecord]
sorted)
  | Bool
otherwise         = Maybe TlvStream
forall a. Maybe a
Nothing
  where
    sorted :: [TlvRecord]
sorted = (TlvRecord -> Word64) -> [TlvRecord] -> [TlvRecord]
forall b a. Ord b => (a -> b) -> [a] -> [a]
L.sortOn TlvRecord -> Word64
tlv_type [TlvRecord]
rs

increasing :: [TlvRecord] -> Bool
increasing :: [TlvRecord] -> Bool
increasing (TlvRecord
a:rest :: [TlvRecord]
rest@(TlvRecord
b:[TlvRecord]
_)) = TlvRecord -> Word64
tlv_type TlvRecord
a Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
< TlvRecord -> Word64
tlv_type TlvRecord
b Bool -> Bool -> Bool
&& [TlvRecord] -> Bool
increasing [TlvRecord]
rest
increasing [TlvRecord]
_ = Bool
True

-- | The records of a 'TlvStream', in increasing type order.
un_tlv_stream :: TlvStream -> [TlvRecord]
un_tlv_stream :: TlvStream -> [TlvRecord]
un_tlv_stream (TlvStream [TlvRecord]
rs) = [TlvRecord]
rs
{-# INLINE un_tlv_stream #-}

-- | The empty 'TlvStream'.
empty_tlv_stream :: TlvStream
empty_tlv_stream :: TlvStream
empty_tlv_stream = [TlvRecord] -> TlvStream
TlvStream []

-- | The value of the record with the given type, if present.
--
--   >>> lookup_tlv 3 =<< tlv_stream [TlvRecord 1 "a", TlvRecord 3 "b"]
--   Just "b"
lookup_tlv :: Word64 -> TlvStream -> Maybe BS.ByteString
lookup_tlv :: Word64 -> TlvStream -> Maybe ByteString
lookup_tlv Word64
t (TlvStream [TlvRecord]
rs) = [TlvRecord] -> Maybe ByteString
go [TlvRecord]
rs
  where
    go :: [TlvRecord] -> Maybe ByteString
go [] = Maybe ByteString
forall a. Maybe a
Nothing
    go (TlvRecord Word64
u ByteString
v : [TlvRecord]
more)
      | Word64
u Word64 -> Word64 -> Bool
forall a. Eq a => a -> a -> Bool
== Word64
t    = ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just ByteString
v
      | Word64
u Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
> Word64
t     = Maybe ByteString
forall a. Maybe a
Nothing
      | Bool
otherwise = [TlvRecord] -> Maybe ByteString
go [TlvRecord]
more

-- | Keep the records whose types satisfy the predicate.
--
--   >>> let Just s = tlv_stream [TlvRecord 1 "", TlvRecord 2 ""]
--   >>> map tlv_type (un_tlv_stream (filter_tlv_stream odd s))
--   [1]
filter_tlv_stream :: (Word64 -> Bool) -> TlvStream -> TlvStream
filter_tlv_stream :: (Word64 -> Bool) -> TlvStream -> TlvStream
filter_tlv_stream Word64 -> Bool
p (TlvStream [TlvRecord]
rs) = [TlvRecord] -> TlvStream
TlvStream ((TlvRecord -> Bool) -> [TlvRecord] -> [TlvRecord]
forall a. (a -> Bool) -> [a] -> [a]
filter (Word64 -> Bool
p (Word64 -> Bool) -> (TlvRecord -> Word64) -> TlvRecord -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TlvRecord -> Word64
tlv_type) [TlvRecord]
rs)

-- | Why a TLV stream failed to decode.
data TlvError
  = TlvTruncated               -- ^ a type, length or value was cut off
  | TlvNonMinimalBigSize       -- ^ a type or length wasn't minimal
  | TlvNotStrictlyIncreasing   -- ^ types out of order or repeated
  | TlvUnknownEvenType !Word64 -- ^ an even type the context doesn't know
  deriving (TlvError -> TlvError -> Bool
(TlvError -> TlvError -> Bool)
-> (TlvError -> TlvError -> Bool) -> Eq TlvError
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: TlvError -> TlvError -> Bool
== :: TlvError -> TlvError -> Bool
$c/= :: TlvError -> TlvError -> Bool
/= :: TlvError -> TlvError -> Bool
Eq, Int -> TlvError -> ShowS
[TlvError] -> ShowS
TlvError -> String
(Int -> TlvError -> ShowS)
-> (TlvError -> String) -> ([TlvError] -> ShowS) -> Show TlvError
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> TlvError -> ShowS
showsPrec :: Int -> TlvError -> ShowS
$cshow :: TlvError -> String
show :: TlvError -> String
$cshowList :: [TlvError] -> ShowS
showList :: [TlvError] -> ShowS
Show, (forall x. TlvError -> Rep TlvError x)
-> (forall x. Rep TlvError x -> TlvError) -> Generic TlvError
forall x. Rep TlvError x -> TlvError
forall x. TlvError -> Rep TlvError x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. TlvError -> Rep TlvError x
from :: forall x. TlvError -> Rep TlvError x
$cto :: forall x. Rep TlvError x -> TlvError
to :: forall x. Rep TlvError x -> TlvError
Generic)

instance NFData TlvError

-- | Encode a 'TlvStream'.
--
--   >>> fmap encode_tlv_stream (tlv_stream [TlvRecord 1 "a"])
--   Just "\SOH\SOHa"
encode_tlv_stream :: TlvStream -> BS.ByteString
encode_tlv_stream :: TlvStream -> ByteString
encode_tlv_stream (TlvStream [TlvRecord]
rs) = [ByteString] -> ByteString
forall a. Monoid a => [a] -> a
mconcat ((TlvRecord -> [ByteString]) -> [TlvRecord] -> [ByteString]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap TlvRecord -> [ByteString]
enc [TlvRecord]
rs)
  where
    enc :: TlvRecord -> [ByteString]
enc (TlvRecord Word64
t ByteString
v) =
      [Word64 -> ByteString
encode_bigsize Word64
t, Word64 -> ByteString
encode_bigsize (Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Int
BS.length ByteString
v)), ByteString
v]

-- | Decode a TLV stream occupying the whole input, given a predicate
--   identifying the types known in the stream's context.
--
--   Per BOLT #1, decoding fails on truncation, non-minimal BigSize
--   encodings, types that are not strictly increasing, and unknown
--   even types. Every record is kept, including unknown odd ones, so
--   re-encoding reproduces the input.
--
--   >>> let Right s = decode_tlv_stream (== 1) "\SOH\SOHa\ETX\NUL"
--   >>> map tlv_type (un_tlv_stream s)
--   [1,3]
--   >>> decode_tlv_stream (== 1) "\STX\NUL"
--   Left (TlvUnknownEvenType 2)
decode_tlv_stream
  :: (Word64 -> Bool)  -- ^ is this type known?
  -> BS.ByteString
  -> Either TlvError TlvStream
decode_tlv_stream :: (Word64 -> Bool) -> ByteString -> Either TlvError TlvStream
decode_tlv_stream Word64 -> Bool
known = Maybe Word64
-> [TlvRecord] -> ByteString -> Either TlvError TlvStream
go Maybe Word64
forall a. Maybe a
Nothing []
  where
    go :: Maybe Word64
-> [TlvRecord] -> ByteString -> Either TlvError TlvStream
go !Maybe Word64
_ ![TlvRecord]
acc !ByteString
bs | ByteString -> Bool
BS.null ByteString
bs = TlvStream -> Either TlvError TlvStream
forall a b. b -> Either a b
Right ([TlvRecord] -> TlvStream
TlvStream ([TlvRecord] -> [TlvRecord]
forall a. [a] -> [a]
reverse [TlvRecord]
acc))
    go !Maybe Word64
prev ![TlvRecord]
acc !ByteString
bs = do
      (t, r0) <- ByteString -> Either TlvError (Word64, ByteString)
bigsize ByteString
bs
      case prev of
        Just Word64
p | Word64
t Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
<= Word64
p -> TlvError -> Either TlvError ()
forall a b. a -> Either a b
Left TlvError
TlvNotStrictlyIncreasing
        Maybe Word64
_ -> () -> Either TlvError ()
forall a. a -> Either TlvError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
      (l, r1) <- bigsize r0
      if l > fromIntegral (BS.length r1)
        then Left TlvTruncated
        else do
          let !n = Word64 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word64
l
              !v = Int -> ByteString -> ByteString
BU.unsafeTake Int
n ByteString
r1
              !r2 = Int -> ByteString -> ByteString
BU.unsafeDrop Int
n ByteString
r1
          if not (known t) && even t
            then Left (TlvUnknownEvenType t)
            else go (Just t) (TlvRecord t v : acc) r2

    bigsize :: ByteString -> Either TlvError (Word64, ByteString)
bigsize ByteString
b = case ByteString -> Either BigSizeError (Word64, ByteString)
decode_bigsize_detailed ByteString
b of
      Right (Word64, ByteString)
r                -> (Word64, ByteString) -> Either TlvError (Word64, ByteString)
forall a b. b -> Either a b
Right (Word64, ByteString)
r
      Left BigSizeError
BigSizeTruncated  -> TlvError -> Either TlvError (Word64, ByteString)
forall a b. a -> Either a b
Left TlvError
TlvTruncated
      Left BigSizeError
BigSizeNonMinimal -> TlvError -> Either TlvError (Word64, ByteString)
forall a b. a -> Either a b
Left TlvError
TlvNonMinimalBigSize