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

-- |
-- Module: Lightning.Protocol.BOLT9
-- Copyright: (c) 2025 Jared Tobin
-- License: MIT
-- Maintainer: Jared Tobin <jared@ppad.tech>
--
-- Feature flags for the Lightning Network, per
-- [BOLT #9](https://github.com/lightning/bolts/blob/master/09-features.md).
--
-- A feature vector is a big-endian bit field. Features are assigned
-- pairs of bits: setting the even bit means the feature is required,
-- setting the odd bit means it is optional (/it's ok to be odd/).
--
-- The examples below assume:
--
-- >>> :set -XOverloadedStrings
-- >>> import Lightning.Protocol.BOLT9
--
-- Build a vector, check it before sending it, and render it:
--
-- >>> let fv = set_feature_with_deps OptionZeroconf Optional empty
-- >>> list_features fv
-- [(OptionScidAlias,Optional),(OptionZeroconf,Optional)]
-- >>> validate_local InitContext fv
-- Right ()
-- >>> render fv
-- "\b\128\NUL\NUL\NUL\NUL\NUL"
--
-- Check a vector received from a peer:
--
-- >>> validate_remote InitContext (parse "\DLE\NUL\NUL")
-- Left (UnknownBit 20 :| [])
-- >>> validate_remote InitContext (parse "\STX\NUL\NUL")
-- Right ()

module Lightning.Protocol.BOLT9 (
  -- * Feature vectors
    FeatureVector
  , parse
  , render
  , empty
  , union

  -- * Bits
  , set_bit
  , clear_bit
  , test_bit
  , set_bits

  -- * Known features
  , Feature(..)
  , known_features
  , feature_by_bit
  , feature_bit
  , feature_name
  , feature_contexts
  , feature_dependencies
  , feature_assumed

  -- * Feature operations
  , FeatureLevel(..)
  , set_feature
  , set_feature_with_deps
  , clear_feature
  , test_feature
  , list_features

  -- * Validation
  , Context(..)
  , ValidationError(..)
  , validate_local
  , validate_remote

  -- * Channel types
  , ChannelType(..)
  , BasicChannelType(..)
  , channel_type
  , channel_type_features
  ) where

import Control.DeepSeq (NFData(..))
import qualified Data.Bits as B
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.List (find)
import Data.List.NonEmpty (NonEmpty(..))
import Data.Maybe (isNothing)
import Data.Word (Word8)
import GHC.Generics (Generic)

-- feature vectors -----------------------------------------------------------

-- | A feature vector.
--
--   Bit 0 is the least significant bit of the last byte. A vector
--   produced by 'parse' keeps its bytes exactly, so 'render' gives
--   them back unchanged (signatures over gossip messages cover them).
--   Every other operation produces a minimally-encoded vector, i.e.
--   one without leading zero bytes.
--
--   Equality ignores leading zero bytes.
--
--   >>> parse "\NUL\STX" == parse "\STX"
--   True
--   >>> set_bit 1 empty
--   parse "\STX"
newtype FeatureVector = FeatureVector ByteString

instance Eq FeatureVector where
  FeatureVector ByteString
a == :: FeatureVector -> FeatureVector -> Bool
== FeatureVector ByteString
b = ByteString -> ByteString
strip ByteString
a ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString -> ByteString
strip ByteString
b

instance Show FeatureVector where
  showsPrec :: Int -> FeatureVector -> ShowS
showsPrec Int
d (FeatureVector ByteString
bs) = 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
"parse " ShowS -> ShowS -> ShowS
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> ByteString -> ShowS
forall a. Show a => Int -> a -> ShowS
showsPrec Int
11 ByteString
bs

instance NFData FeatureVector where
  rnf :: FeatureVector -> ()
rnf (FeatureVector ByteString
bs) = ByteString -> ()
forall a. NFData a => a -> ()
rnf ByteString
bs

-- | Parse a feature vector from its wire bytes. Every byte string is a
--   valid feature vector.
--
--   >>> test_bit 9 (parse "\STX\NUL")
--   True
parse :: ByteString -> FeatureVector
parse :: ByteString -> FeatureVector
parse = ByteString -> FeatureVector
FeatureVector
{-# INLINE parse #-}

-- | The wire bytes of a feature vector: the original bytes of a vector
--   produced by 'parse', and the minimal encoding of any other.
--
--   >>> render (parse "\NUL\STX")
--   "\NUL\STX"
--   >>> render (union (parse "\NUL\STX") empty)
--   "\STX"
render :: FeatureVector -> ByteString
render :: FeatureVector -> ByteString
render (FeatureVector ByteString
bs) = ByteString
bs
{-# INLINE render #-}

-- | The empty feature vector.
--
--   >>> render empty
--   ""
empty :: FeatureVector
empty :: FeatureVector
empty = ByteString -> FeatureVector
FeatureVector ByteString
BS.empty

-- | The bitwise OR of two feature vectors.
--
--   BOLT #1 requires the receiver of an @init@ message to combine its
--   @globalfeatures@ and @features@ fields this way.
--
--   >>> set_bits (union (parse "\STX") (parse "\SOH\NUL"))
--   [1,8]
union :: FeatureVector -> FeatureVector -> FeatureVector
union :: FeatureVector -> FeatureVector -> FeatureVector
union (FeatureVector ByteString
a) (FeatureVector ByteString
b) =
  ByteString -> FeatureVector
FeatureVector ((Word8 -> Word8 -> Word8) -> ByteString -> ByteString -> ByteString
combine Word8 -> Word8 -> Word8
forall a. Bits a => a -> a -> a
(B..|.) ByteString
a ByteString
b)

-- bits ----------------------------------------------------------------------

-- | Set the bit at the given index. Negative indices are ignored.
--
--   >>> render (set_bit 9 empty)
--   "\STX\NUL"
set_bit :: Int -> FeatureVector -> FeatureVector
set_bit :: Int -> FeatureVector -> FeatureVector
set_bit !Int
i (FeatureVector ByteString
bs)
  | Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0     = ByteString -> FeatureVector
FeatureVector (ByteString -> ByteString
strip ByteString
bs)
  | Bool
otherwise = ByteString -> FeatureVector
FeatureVector ((Word8 -> Word8 -> Word8) -> ByteString -> ByteString -> ByteString
combine Word8 -> Word8 -> Word8
forall a. Bits a => a -> a -> a
(B..|.) ByteString
bs (Int -> ByteString
single Int
i))

-- | Clear the bit at the given index. Negative indices are ignored.
--
--   >>> render (clear_bit 9 (parse "\STX\SOH"))
--   "\SOH"
clear_bit :: Int -> FeatureVector -> FeatureVector
clear_bit :: Int -> FeatureVector -> FeatureVector
clear_bit !Int
i (FeatureVector ByteString
bs)
  | Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0 Bool -> Bool -> Bool
|| Int
i Int -> Int -> Int
forall a. Integral a => a -> a -> a
`quot` Int
8 Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= ByteString -> Int
BS.length ByteString
s = ByteString -> FeatureVector
FeatureVector ByteString
s
  | Bool
otherwise = ByteString -> FeatureVector
FeatureVector ((Word8 -> Word8 -> Word8) -> ByteString -> ByteString -> ByteString
combine Word8 -> Word8 -> Word8
forall a. Bits a => a -> a -> a
clr ByteString
s (Int -> ByteString
single Int
i))
  where
    s :: ByteString
s = ByteString -> ByteString
strip ByteString
bs
    clr :: a -> a -> a
clr a
x a
y = a
x a -> a -> a
forall a. Bits a => a -> a -> a
B..&. a -> a
forall a. Bits a => a -> a
B.complement a
y

-- | Test the bit at the given index. Negative indices are never set.
--
--   >>> test_bit 9 (parse "\STX\NUL")
--   True
--   >>> test_bit 8 (parse "\STX\NUL")
--   False
test_bit :: Int -> FeatureVector -> Bool
test_bit :: Int -> FeatureVector -> Bool
test_bit !Int
i (FeatureVector ByteString
bs)
  | Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0 Bool -> Bool -> Bool
|| Int
q Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
len = Bool
False
  | Bool
otherwise         = Word8 -> Int -> Bool
forall a. Bits a => a -> Int -> Bool
B.testBit (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs (Int
len Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
q)) Int
r
  where
    len :: Int
len    = ByteString -> Int
BS.length ByteString
bs
    (Int
q, Int
r) = Int
i Int -> Int -> (Int, Int)
forall a. Integral a => a -> a -> (a, a)
`quotRem` Int
8

-- | The indices of all set bits, in ascending order.
--
--   >>> set_bits (parse "\STX\NUL\SOH")
--   [0,17]
set_bits :: FeatureVector -> [Int]
set_bits :: FeatureVector -> [Int]
set_bits (FeatureVector ByteString
bs) = Int -> [Int]
go Int
0
  where
    !len :: Int
len = ByteString -> Int
BS.length ByteString
bs
    go :: Int -> [Int]
go !Int
q
      | Int
q Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
len  = []
      | Bool
otherwise =
          let !w :: Word8
w = HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs (Int
len Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
q)
          in  [Int
q Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
8 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
r | Int
r <- [Int
0 .. Int
7], Word8 -> Int -> Bool
forall a. Bits a => a -> Int -> Bool
B.testBit Word8
w Int
r] [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ Int -> [Int]
go (Int
q Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)

-- Drop leading zero bytes.
strip :: ByteString -> ByteString
strip :: ByteString -> ByteString
strip = (Word8 -> Bool) -> ByteString -> ByteString
BS.dropWhile (Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
== Word8
0)
{-# INLINE strip #-}

-- The minimal encoding of a vector with only bit i set (i >= 0).
single :: Int -> ByteString
single :: Int -> ByteString
single Int
i = Word8 -> ByteString -> ByteString
BS.cons (Int -> Word8
forall a. Bits a => Int -> a
B.bit Int
r) (Int -> Word8 -> ByteString
BS.replicate Int
q Word8
0)
  where
    (Int
q, Int
r) = Int
i Int -> Int -> (Int, Int)
forall a. Integral a => a -> a -> (a, a)
`quotRem` Int
8

-- Combine two encodings bytewise, aligned at their last bytes (the
-- shorter one padded with leading zeros), and strip the result.
combine
  :: (Word8 -> Word8 -> Word8) -> ByteString -> ByteString -> ByteString
combine :: (Word8 -> Word8 -> Word8) -> ByteString -> ByteString -> ByteString
combine Word8 -> Word8 -> Word8
f ByteString
a ByteString
b = ByteString -> ByteString
strip ((ByteString, Maybe Int) -> ByteString
forall a b. (a, b) -> a
fst (Int
-> (Int -> Maybe (Word8, Int)) -> Int -> (ByteString, Maybe Int)
forall a.
Int -> (a -> Maybe (Word8, a)) -> a -> (ByteString, Maybe a)
BS.unfoldrN Int
n Int -> Maybe (Word8, Int)
step Int
0))
  where
    !la :: Int
la = ByteString -> Int
BS.length ByteString
a
    !lb :: Int
lb = ByteString -> Int
BS.length ByteString
b
    !n :: Int
n  = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
la Int
lb
    byte :: ByteString -> Int -> Int -> Word8
byte ByteString
s Int
ls Int
k
      | Int
k Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
ls = Word8
0
      | Bool
otherwise  = HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
s (Int
k Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
ls)
    step :: Int -> Maybe (Word8, Int)
step !Int
k = (Word8, Int) -> Maybe (Word8, Int)
forall a. a -> Maybe a
Just (Word8 -> Word8 -> Word8
f (ByteString -> Int -> Int -> Word8
byte ByteString
a Int
la Int
k) (ByteString -> Int -> Int -> Word8
byte ByteString
b Int
lb Int
k), Int
k Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)

-- known features ------------------------------------------------------------

-- | The features assigned in the BOLT #9 table.
data Feature
  = OptionDataLossProtect           -- ^ 0/1 @option_data_loss_protect@
  | OptionUpfrontShutdownScript     -- ^ 4/5 @option_upfront_shutdown_script@
  | GossipQueries                   -- ^ 6/7 @gossip_queries@
  | VarOnionOptin                   -- ^ 8/9 @var_onion_optin@
  | GossipQueriesEx                 -- ^ 10/11 @gossip_queries_ex@
  | OptionStaticRemotekey           -- ^ 12/13 @option_static_remotekey@
  | PaymentSecret                   -- ^ 14/15 @payment_secret@
  | BasicMpp                        -- ^ 16/17 @basic_mpp@
  | OptionSupportLargeChannel       -- ^ 18/19 @option_support_large_channel@
  | OptionAnchors                   -- ^ 22/23 @option_anchors@
  | OptionRouteBlinding             -- ^ 24/25 @option_route_blinding@
  | OptionShutdownAnysegwit         -- ^ 26/27 @option_shutdown_anysegwit@
  | OptionDualFund                  -- ^ 28/29 @option_dual_fund@
  | OptionQuiesce                   -- ^ 34/35 @option_quiesce@
  | OptionAttributionData           -- ^ 36/37 @option_attribution_data@
  | OptionOnionMessages             -- ^ 38/39 @option_onion_messages@
  | ZeroFeeCommitments              -- ^ 40/41 @zero_fee_commitments@
  | OptionProvideStorage            -- ^ 42/43 @option_provide_storage@
  | OptionChannelType               -- ^ 44/45 @option_channel_type@
  | OptionScidAlias                 -- ^ 46/47 @option_scid_alias@
  | OptionPaymentMetadata           -- ^ 48/49 @option_payment_metadata@
  | OptionZeroconf                  -- ^ 50/51 @option_zeroconf@
  | OptionSimpleClose               -- ^ 60/61 @option_simple_close@
  | OptionSplice                    -- ^ 62/63 @option_splice@
  | OptionOnionMessagesOnlyChannels
    -- ^ 66/67 @option_onion_messages_only_channels@
  deriving (Feature -> Feature -> Bool
(Feature -> Feature -> Bool)
-> (Feature -> Feature -> Bool) -> Eq Feature
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Feature -> Feature -> Bool
== :: Feature -> Feature -> Bool
$c/= :: Feature -> Feature -> Bool
/= :: Feature -> Feature -> Bool
Eq, Eq Feature
Eq Feature =>
(Feature -> Feature -> Ordering)
-> (Feature -> Feature -> Bool)
-> (Feature -> Feature -> Bool)
-> (Feature -> Feature -> Bool)
-> (Feature -> Feature -> Bool)
-> (Feature -> Feature -> Feature)
-> (Feature -> Feature -> Feature)
-> Ord Feature
Feature -> Feature -> Bool
Feature -> Feature -> Ordering
Feature -> Feature -> Feature
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: Feature -> Feature -> Ordering
compare :: Feature -> Feature -> Ordering
$c< :: Feature -> Feature -> Bool
< :: Feature -> Feature -> Bool
$c<= :: Feature -> Feature -> Bool
<= :: Feature -> Feature -> Bool
$c> :: Feature -> Feature -> Bool
> :: Feature -> Feature -> Bool
$c>= :: Feature -> Feature -> Bool
>= :: Feature -> Feature -> Bool
$cmax :: Feature -> Feature -> Feature
max :: Feature -> Feature -> Feature
$cmin :: Feature -> Feature -> Feature
min :: Feature -> Feature -> Feature
Ord, Int -> Feature -> ShowS
[Feature] -> ShowS
Feature -> String
(Int -> Feature -> ShowS)
-> (Feature -> String) -> ([Feature] -> ShowS) -> Show Feature
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Feature -> ShowS
showsPrec :: Int -> Feature -> ShowS
$cshow :: Feature -> String
show :: Feature -> String
$cshowList :: [Feature] -> ShowS
showList :: [Feature] -> ShowS
Show, (forall x. Feature -> Rep Feature x)
-> (forall x. Rep Feature x -> Feature) -> Generic Feature
forall x. Rep Feature x -> Feature
forall x. Feature -> Rep Feature x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Feature -> Rep Feature x
from :: forall x. Feature -> Rep Feature x
$cto :: forall x. Rep Feature x -> Feature
to :: forall x. Rep Feature x -> Feature
Generic)

instance NFData Feature

-- | All known features, in bit order.
--
--   >>> length known_features
--   25
known_features :: [Feature]
known_features :: [Feature]
known_features = [
    Feature
OptionDataLossProtect
  , Feature
OptionUpfrontShutdownScript
  , Feature
GossipQueries
  , Feature
VarOnionOptin
  , Feature
GossipQueriesEx
  , Feature
OptionStaticRemotekey
  , Feature
PaymentSecret
  , Feature
BasicMpp
  , Feature
OptionSupportLargeChannel
  , Feature
OptionAnchors
  , Feature
OptionRouteBlinding
  , Feature
OptionShutdownAnysegwit
  , Feature
OptionDualFund
  , Feature
OptionQuiesce
  , Feature
OptionAttributionData
  , Feature
OptionOnionMessages
  , Feature
ZeroFeeCommitments
  , Feature
OptionProvideStorage
  , Feature
OptionChannelType
  , Feature
OptionScidAlias
  , Feature
OptionPaymentMetadata
  , Feature
OptionZeroconf
  , Feature
OptionSimpleClose
  , Feature
OptionSplice
  , Feature
OptionOnionMessagesOnlyChannels
  ]

-- A row of the BOLT #9 table.
data Entry = Entry {
    Entry -> Int
e_bit      :: !Int
  , Entry -> String
e_name     :: !String
  , Entry -> [Context]
e_contexts :: ![Context]
  , Entry -> [Feature]
e_deps     :: ![Feature]
  , Entry -> Bool
e_assumed  :: !Bool
  }

entry :: Feature -> Entry
entry :: Feature -> Entry
entry Feature
f = case Feature
f of
  Feature
OptionDataLossProtect ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
0 String
"option_data_loss_protect" [] [] Bool
True
  Feature
OptionUpfrontShutdownScript ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
4 String
"option_upfront_shutdown_script" [Context]
_IN [] Bool
False
  Feature
GossipQueries ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
6 String
"gossip_queries" [] [] Bool
False
  Feature
VarOnionOptin ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
8 String
"var_onion_optin" [] [] Bool
True
  Feature
GossipQueriesEx ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
10 String
"gossip_queries_ex" [Context]
_IN [] Bool
False
  Feature
OptionStaticRemotekey ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
12 String
"option_static_remotekey" [] [] Bool
True
  Feature
PaymentSecret ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
14 String
"payment_secret" [] [] Bool
True
  Feature
BasicMpp ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
16 String
"basic_mpp" [Context]
_IN9 [Feature
PaymentSecret] Bool
False
  Feature
OptionSupportLargeChannel ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
18 String
"option_support_large_channel" [Context]
_IN [] Bool
False
  Feature
OptionAnchors ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
22 String
"option_anchors" [Context]
_INT [] Bool
False
  Feature
OptionRouteBlinding ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
24 String
"option_route_blinding" [Context]
_IN9 [] Bool
False
  Feature
OptionShutdownAnysegwit ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
26 String
"option_shutdown_anysegwit" [Context]
_IN [] Bool
False
  Feature
OptionDualFund ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
28 String
"option_dual_fund" [Context]
_IN [] Bool
False
  Feature
OptionQuiesce ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
34 String
"option_quiesce" [Context]
_IN [] Bool
False
  Feature
OptionAttributionData ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
36 String
"option_attribution_data" [Context]
_IN9 [] Bool
False
  Feature
OptionOnionMessages ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
38 String
"option_onion_messages" [Context]
_IN [] Bool
False
  Feature
ZeroFeeCommitments ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
40 String
"zero_fee_commitments" [Context]
_IN [Feature
OptionChannelType] Bool
False
  Feature
OptionProvideStorage ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
42 String
"option_provide_storage" [Context]
_IN [] Bool
False
  Feature
OptionChannelType ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
44 String
"option_channel_type" [] [] Bool
True
  Feature
OptionScidAlias ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
46 String
"option_scid_alias" [Context]
_INT [] Bool
False
  Feature
OptionPaymentMetadata ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
48 String
"option_payment_metadata" [Context
InvoiceContext] [] Bool
False
  Feature
OptionZeroconf ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
50 String
"option_zeroconf" [Context]
_INT [Feature
OptionScidAlias] Bool
False
  Feature
OptionSimpleClose ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
60 String
"option_simple_close" [Context]
_IN [Feature
OptionShutdownAnysegwit] Bool
False
  Feature
OptionSplice ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
62 String
"option_splice" [Context]
_IN [] Bool
False
  Feature
OptionOnionMessagesOnlyChannels ->
    Int -> String -> [Context] -> [Feature] -> Bool -> Entry
Entry Int
66 String
"option_onion_messages_only_channels" [Context]
_IN
      [Feature
OptionOnionMessages] Bool
False
  where
    _IN :: [Context]
_IN  = [Context
InitContext, Context
NodeContext]
    _IN9 :: [Context]
_IN9 = [Context
InitContext, Context
NodeContext, Context
InvoiceContext]
    _INT :: [Context]
_INT = [Context
InitContext, Context
NodeContext, Context
ChannelTypeContext]

-- | The feature that a bit (even or odd) belongs to, if any.
--
--   >>> feature_by_bit 16
--   Just BasicMpp
--   >>> feature_by_bit 17
--   Just BasicMpp
--   >>> feature_by_bit 20
--   Nothing
feature_by_bit :: Int -> Maybe Feature
feature_by_bit :: Int -> Maybe Feature
feature_by_bit !Int
i
  | Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0 Bool -> Bool -> Bool
|| Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
max_known_bit = Maybe Feature
forall a. Maybe a
Nothing
  | Bool
otherwise = (Feature -> Bool) -> [Feature] -> Maybe Feature
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
base) (Int -> Bool) -> (Feature -> Int) -> Feature -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Feature -> Int
feature_bit) [Feature]
known_features
  where
    base :: Int
base = Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
i Int -> Int -> Int
forall a. Integral a => a -> a -> a
`rem` Int
2

-- The highest bit assigned to any known feature.
max_known_bit :: Int
max_known_bit :: Int
max_known_bit = (Feature -> Int -> Int) -> Int -> [Feature] -> Int
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (Int -> Int -> Int
forall a. Ord a => a -> a -> a
max (Int -> Int -> Int) -> (Feature -> Int) -> Feature -> Int -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) (Int -> Int) -> (Feature -> Int) -> Feature -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Feature -> Int
feature_bit) Int
0 [Feature]
known_features

-- | A feature's even (required) bit. Its odd (optional) bit is the
--   next one up.
--
--   >>> feature_bit BasicMpp
--   16
feature_bit :: Feature -> Int
feature_bit :: Feature -> Int
feature_bit = Entry -> Int
e_bit (Entry -> Int) -> (Feature -> Entry) -> Feature -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Feature -> Entry
entry

-- | A feature's name in the BOLT #9 table.
--
--   >>> feature_name BasicMpp
--   "basic_mpp"
feature_name :: Feature -> String
feature_name :: Feature -> String
feature_name = Entry -> String
e_name (Entry -> String) -> (Feature -> Entry) -> Feature -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Feature -> Entry
entry

-- | The contexts the BOLT #9 table lists for a feature, in table order.
--   The list is empty for ASSUMED features and for 'GossipQueries'.
--
--   >>> feature_contexts BasicMpp
--   [InitContext,NodeContext,InvoiceContext]
--   >>> feature_contexts PaymentSecret
--   []
feature_contexts :: Feature -> [Context]
feature_contexts :: Feature -> [Context]
feature_contexts = Entry -> [Context]
e_contexts (Entry -> [Context]) -> (Feature -> Entry) -> Feature -> [Context]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Feature -> Entry
entry

-- | A feature's direct dependencies.
--
--   >>> feature_dependencies OptionZeroconf
--   [OptionScidAlias]
feature_dependencies :: Feature -> [Feature]
feature_dependencies :: Feature -> [Feature]
feature_dependencies = Entry -> [Feature]
e_deps (Entry -> [Feature]) -> (Feature -> Entry) -> Feature -> [Feature]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Feature -> Entry
entry

-- | Whether BOLT #9 marks a feature ASSUMED, i.e. supported by all
--   nodes.
--
--   >>> feature_assumed PaymentSecret
--   True
feature_assumed :: Feature -> Bool
feature_assumed :: Feature -> Bool
feature_assumed = Entry -> Bool
e_assumed (Entry -> Bool) -> (Feature -> Entry) -> Feature -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Feature -> Entry
entry

-- feature operations --------------------------------------------------------

-- | The level at which a feature is set.
data FeatureLevel
  = Required  -- ^ the even bit is set
  | Optional  -- ^ the odd bit is set
  deriving (FeatureLevel -> FeatureLevel -> Bool
(FeatureLevel -> FeatureLevel -> Bool)
-> (FeatureLevel -> FeatureLevel -> Bool) -> Eq FeatureLevel
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: FeatureLevel -> FeatureLevel -> Bool
== :: FeatureLevel -> FeatureLevel -> Bool
$c/= :: FeatureLevel -> FeatureLevel -> Bool
/= :: FeatureLevel -> FeatureLevel -> Bool
Eq, Eq FeatureLevel
Eq FeatureLevel =>
(FeatureLevel -> FeatureLevel -> Ordering)
-> (FeatureLevel -> FeatureLevel -> Bool)
-> (FeatureLevel -> FeatureLevel -> Bool)
-> (FeatureLevel -> FeatureLevel -> Bool)
-> (FeatureLevel -> FeatureLevel -> Bool)
-> (FeatureLevel -> FeatureLevel -> FeatureLevel)
-> (FeatureLevel -> FeatureLevel -> FeatureLevel)
-> Ord FeatureLevel
FeatureLevel -> FeatureLevel -> Bool
FeatureLevel -> FeatureLevel -> Ordering
FeatureLevel -> FeatureLevel -> FeatureLevel
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: FeatureLevel -> FeatureLevel -> Ordering
compare :: FeatureLevel -> FeatureLevel -> Ordering
$c< :: FeatureLevel -> FeatureLevel -> Bool
< :: FeatureLevel -> FeatureLevel -> Bool
$c<= :: FeatureLevel -> FeatureLevel -> Bool
<= :: FeatureLevel -> FeatureLevel -> Bool
$c> :: FeatureLevel -> FeatureLevel -> Bool
> :: FeatureLevel -> FeatureLevel -> Bool
$c>= :: FeatureLevel -> FeatureLevel -> Bool
>= :: FeatureLevel -> FeatureLevel -> Bool
$cmax :: FeatureLevel -> FeatureLevel -> FeatureLevel
max :: FeatureLevel -> FeatureLevel -> FeatureLevel
$cmin :: FeatureLevel -> FeatureLevel -> FeatureLevel
min :: FeatureLevel -> FeatureLevel -> FeatureLevel
Ord, Int -> FeatureLevel -> ShowS
[FeatureLevel] -> ShowS
FeatureLevel -> String
(Int -> FeatureLevel -> ShowS)
-> (FeatureLevel -> String)
-> ([FeatureLevel] -> ShowS)
-> Show FeatureLevel
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> FeatureLevel -> ShowS
showsPrec :: Int -> FeatureLevel -> ShowS
$cshow :: FeatureLevel -> String
show :: FeatureLevel -> String
$cshowList :: [FeatureLevel] -> ShowS
showList :: [FeatureLevel] -> ShowS
Show, (forall x. FeatureLevel -> Rep FeatureLevel x)
-> (forall x. Rep FeatureLevel x -> FeatureLevel)
-> Generic FeatureLevel
forall x. Rep FeatureLevel x -> FeatureLevel
forall x. FeatureLevel -> Rep FeatureLevel x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. FeatureLevel -> Rep FeatureLevel x
from :: forall x. FeatureLevel -> Rep FeatureLevel x
$cto :: forall x. Rep FeatureLevel x -> FeatureLevel
to :: forall x. Rep FeatureLevel x -> FeatureLevel
Generic)

instance NFData FeatureLevel

level_bit :: Feature -> FeatureLevel -> Int
level_bit :: Feature -> FeatureLevel -> Int
level_bit Feature
f FeatureLevel
Required = Feature -> Int
feature_bit Feature
f
level_bit Feature
f FeatureLevel
Optional = Feature -> Int
feature_bit Feature
f Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1
{-# INLINE level_bit #-}

-- | Set a feature at the given level, clearing the other bit of its
--   pair.
--
--   >>> set_bits (set_feature BasicMpp Optional empty)
--   [17]
--   >>> set_bits (set_feature BasicMpp Required (set_bit 17 empty))
--   [16]
set_feature :: Feature -> FeatureLevel -> FeatureVector -> FeatureVector
set_feature :: Feature -> FeatureLevel -> FeatureVector -> FeatureVector
set_feature Feature
f FeatureLevel
l = Int -> FeatureVector -> FeatureVector
set_bit (Feature -> FeatureLevel -> Int
level_bit Feature
f FeatureLevel
l) (FeatureVector -> FeatureVector)
-> (FeatureVector -> FeatureVector)
-> FeatureVector
-> FeatureVector
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> FeatureVector -> FeatureVector
clear_bit (Feature -> FeatureLevel -> Int
level_bit Feature
f FeatureLevel
other)
  where
    other :: FeatureLevel
other = case FeatureLevel
l of
      FeatureLevel
Required -> FeatureLevel
Optional
      FeatureLevel
Optional -> FeatureLevel
Required

-- | Set a feature at the given level, together with its transitive
--   dependencies (ASSUMED ones included). Dependencies that are not
--   yet set are set at the same level; those already set keep theirs.
--
--   >>> list_features (set_feature_with_deps BasicMpp Optional empty)
--   [(PaymentSecret,Optional),(BasicMpp,Optional)]
set_feature_with_deps
  :: Feature -> FeatureLevel -> FeatureVector -> FeatureVector
set_feature_with_deps :: Feature -> FeatureLevel -> FeatureVector -> FeatureVector
set_feature_with_deps Feature
f FeatureLevel
l FeatureVector
fv =
    (Feature -> FeatureVector -> FeatureVector)
-> FeatureVector -> [Feature] -> FeatureVector
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr Feature -> FeatureVector -> FeatureVector
ensure (Feature -> FeatureLevel -> FeatureVector -> FeatureVector
set_feature Feature
f FeatureLevel
l FeatureVector
fv) (Feature -> [Feature]
feature_dependencies Feature
f)
  where
    ensure :: Feature -> FeatureVector -> FeatureVector
ensure Feature
d FeatureVector
acc =
      let acc' :: FeatureVector
acc' = case Feature -> FeatureVector -> Maybe FeatureLevel
test_feature Feature
d FeatureVector
acc of
            Just FeatureLevel
_  -> FeatureVector
acc
            Maybe FeatureLevel
Nothing -> Feature -> FeatureLevel -> FeatureVector -> FeatureVector
set_feature Feature
d FeatureLevel
l FeatureVector
acc
      in  (Feature -> FeatureVector -> FeatureVector)
-> FeatureVector -> [Feature] -> FeatureVector
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr Feature -> FeatureVector -> FeatureVector
ensure FeatureVector
acc' (Feature -> [Feature]
feature_dependencies Feature
d)

-- | Clear both bits of a feature.
--
--   >>> clear_feature BasicMpp (set_feature BasicMpp Optional empty)
--   parse ""
clear_feature :: Feature -> FeatureVector -> FeatureVector
clear_feature :: Feature -> FeatureVector -> FeatureVector
clear_feature Feature
f =
  Int -> FeatureVector -> FeatureVector
clear_bit (Feature -> FeatureLevel -> Int
level_bit Feature
f FeatureLevel
Required) (FeatureVector -> FeatureVector)
-> (FeatureVector -> FeatureVector)
-> FeatureVector
-> FeatureVector
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> FeatureVector -> FeatureVector
clear_bit (Feature -> FeatureLevel -> Int
level_bit Feature
f FeatureLevel
Optional)

-- | The level at which a feature is set, if it is.
--
--   A feature with both bits set is 'Required', as BOLT #9 directs the
--   receiver to treat it.
--
--   >>> test_feature BasicMpp (set_bit 17 empty)
--   Just Optional
--   >>> test_feature BasicMpp (set_bit 16 (set_bit 17 empty))
--   Just Required
--   >>> test_feature BasicMpp empty
--   Nothing
test_feature :: Feature -> FeatureVector -> Maybe FeatureLevel
test_feature :: Feature -> FeatureVector -> Maybe FeatureLevel
test_feature Feature
f FeatureVector
fv
  | Int -> FeatureVector -> Bool
test_bit (Feature -> FeatureLevel -> Int
level_bit Feature
f FeatureLevel
Required) FeatureVector
fv = FeatureLevel -> Maybe FeatureLevel
forall a. a -> Maybe a
Just FeatureLevel
Required
  | Int -> FeatureVector -> Bool
test_bit (Feature -> FeatureLevel -> Int
level_bit Feature
f FeatureLevel
Optional) FeatureVector
fv = FeatureLevel -> Maybe FeatureLevel
forall a. a -> Maybe a
Just FeatureLevel
Optional
  | Bool
otherwise                          = Maybe FeatureLevel
forall a. Maybe a
Nothing

-- | The known features set in a vector, in bit order.
--
--   >>> list_features (parse "\SOH\128\NUL")
--   [(PaymentSecret,Optional),(BasicMpp,Required)]
list_features :: FeatureVector -> [(Feature, FeatureLevel)]
list_features :: FeatureVector -> [(Feature, FeatureLevel)]
list_features FeatureVector
fv =
  [(Feature
f, FeatureLevel
l) | Feature
f <- [Feature]
known_features, Just FeatureLevel
l <- [Feature -> FeatureVector -> Maybe FeatureLevel
test_feature Feature
f FeatureVector
fv]]

-- validation ----------------------------------------------------------------

-- | A field in which feature bits are presented: the values of the
--   Context column of the BOLT #9 table.
--
--   The table's @C-@ and @C+@ are not further contexts. They mark a
--   feature presented in @channel_announcement@ as always optional or
--   always required. No feature at the implemented spec revision is
--   presented in @channel_announcement@ in any form.
data Context
  = InitContext         -- ^ @I@: the @init@ message
  | NodeContext         -- ^ @N@: @node_announcement@
  | ChannelContext      -- ^ @C@: @channel_announcement@
  | InvoiceContext      -- ^ @9@: BOLT #11 invoices
  | BlindedContext      -- ^ @B@: @allowed_features@ of a blinded path
  | ChannelTypeContext  -- ^ @T@: the @channel_type@ field
  deriving (Context -> Context -> Bool
(Context -> Context -> Bool)
-> (Context -> Context -> Bool) -> Eq Context
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Context -> Context -> Bool
== :: Context -> Context -> Bool
$c/= :: Context -> Context -> Bool
/= :: Context -> Context -> Bool
Eq, Eq Context
Eq Context =>
(Context -> Context -> Ordering)
-> (Context -> Context -> Bool)
-> (Context -> Context -> Bool)
-> (Context -> Context -> Bool)
-> (Context -> Context -> Bool)
-> (Context -> Context -> Context)
-> (Context -> Context -> Context)
-> Ord Context
Context -> Context -> Bool
Context -> Context -> Ordering
Context -> Context -> Context
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: Context -> Context -> Ordering
compare :: Context -> Context -> Ordering
$c< :: Context -> Context -> Bool
< :: Context -> Context -> Bool
$c<= :: Context -> Context -> Bool
<= :: Context -> Context -> Bool
$c> :: Context -> Context -> Bool
> :: Context -> Context -> Bool
$c>= :: Context -> Context -> Bool
>= :: Context -> Context -> Bool
$cmax :: Context -> Context -> Context
max :: Context -> Context -> Context
$cmin :: Context -> Context -> Context
min :: Context -> Context -> Context
Ord, Int -> Context -> ShowS
[Context] -> ShowS
Context -> String
(Int -> Context -> ShowS)
-> (Context -> String) -> ([Context] -> ShowS) -> Show Context
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Context -> ShowS
showsPrec :: Int -> Context -> ShowS
$cshow :: Context -> String
show :: Context -> String
$cshowList :: [Context] -> ShowS
showList :: [Context] -> ShowS
Show, (forall x. Context -> Rep Context x)
-> (forall x. Rep Context x -> Context) -> Generic Context
forall x. Rep Context x -> Context
forall x. Context -> Rep Context x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Context -> Rep Context x
from :: forall x. Context -> Rep Context x
$cto :: forall x. Rep Context x -> Context
to :: forall x. Rep Context x -> Context
Generic)

instance NFData Context

-- | A rule a feature vector breaks.
data ValidationError
  = UnknownBit {-# UNPACK #-} !Int
    -- ^ a bit belonging to no known feature is set
  | BothBitsSet !Feature
    -- ^ both bits of a feature are set
  | ContextNotAllowed !Feature !Context
    -- ^ a feature is set in a context that doesn't present it
  | MissingDependency !Feature !Feature
    -- ^ a set feature (first) lacks a dependency (second)
  | InvalidChannelType
    -- ^ a @channel_type@ is not a type that BOLT #2 defines
  deriving (ValidationError -> ValidationError -> Bool
(ValidationError -> ValidationError -> Bool)
-> (ValidationError -> ValidationError -> Bool)
-> Eq ValidationError
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ValidationError -> ValidationError -> Bool
== :: ValidationError -> ValidationError -> Bool
$c/= :: ValidationError -> ValidationError -> Bool
/= :: ValidationError -> ValidationError -> Bool
Eq, Int -> ValidationError -> ShowS
[ValidationError] -> ShowS
ValidationError -> String
(Int -> ValidationError -> ShowS)
-> (ValidationError -> String)
-> ([ValidationError] -> ShowS)
-> Show ValidationError
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ValidationError -> ShowS
showsPrec :: Int -> ValidationError -> ShowS
$cshow :: ValidationError -> String
show :: ValidationError -> String
$cshowList :: [ValidationError] -> ShowS
showList :: [ValidationError] -> ShowS
Show, (forall x. ValidationError -> Rep ValidationError x)
-> (forall x. Rep ValidationError x -> ValidationError)
-> Generic ValidationError
forall x. Rep ValidationError x -> ValidationError
forall x. ValidationError -> Rep ValidationError x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ValidationError -> Rep ValidationError x
from :: forall x. ValidationError -> Rep ValidationError x
$cto :: forall x. Rep ValidationError x -> ValidationError
to :: forall x. Rep ValidationError x -> ValidationError
Generic)

instance NFData ValidationError

-- | Validate a feature vector that we're about to send in the given
--   context, per the origin requirements of BOLT #9 and BOLT #1.
--
--   For 'ChannelTypeContext', the vector must be a channel type that
--   BOLT #2 defines (see 'channel_type'). For every other context,
--   checks that:
--
--   * no bit outside the known features is set;
--   * no feature has both bits set;
--   * each set feature is presented in the context. A feature with an
--     empty Context column (the ASSUMED features and 'GossipQueries')
--     is accepted in 'InitContext', 'NodeContext' and
--     'InvoiceContext', where deployed nodes still present it;
--   * each set feature's dependencies are set. A dependency on an
--     ASSUMED feature counts as met even when its bits are clear.
--
--   Errors are reported in that order. No known feature is presented
--   in 'ChannelContext' or 'BlindedContext', so only the empty vector
--   passes there (as BOLT #4 requires of @allowed_features@).
--
--   >>> validate_local InitContext (set_feature OptionZeroconf Optional empty)
--   Left (MissingDependency OptionZeroconf OptionScidAlias :| [])
--   >>> validate_local InitContext (set_feature BasicMpp Optional empty)
--   Right ()
--   >>> validate_local InitContext (set_bit 101 empty)
--   Left (UnknownBit 101 :| [])
validate_local
  :: Context -> FeatureVector -> Either (NonEmpty ValidationError) ()
validate_local :: Context -> FeatureVector -> Either (NonEmpty ValidationError) ()
validate_local Context
ctx FeatureVector
fv = [ValidationError] -> Either (NonEmpty ValidationError) ()
forall e. [e] -> Either (NonEmpty e) ()
to_either ([ValidationError] -> Either (NonEmpty ValidationError) ())
-> [ValidationError] -> Either (NonEmpty ValidationError) ()
forall a b. (a -> b) -> a -> b
$ case Context
ctx of
  Context
ChannelTypeContext -> FeatureVector -> [ValidationError]
channel_type_errors FeatureVector
fv
  Context
_ ->  (Int -> Bool) -> FeatureVector -> [ValidationError]
unknown_bits (Bool -> Int -> Bool
forall a b. a -> b -> a
const Bool
True) FeatureVector
fv
     [ValidationError] -> [ValidationError] -> [ValidationError]
forall a. [a] -> [a] -> [a]
++ FeatureVector -> [ValidationError]
both_bits_errors FeatureVector
fv
     [ValidationError] -> [ValidationError] -> [ValidationError]
forall a. [a] -> [a] -> [a]
++ Context -> FeatureVector -> [ValidationError]
context_errors Context
ctx FeatureVector
fv
     [ValidationError] -> [ValidationError] -> [ValidationError]
forall a. [a] -> [a] -> [a]
++ FeatureVector -> [ValidationError]
dependency_errors FeatureVector
fv

-- | Validate a feature vector received in the given context, per the
--   receiver requirements for that context:
--
--   * 'InitContext' (BOLT #1) and 'InvoiceContext' (BOLT #11): no
--     unknown even bit is set, and each set feature's dependencies are
--     set (ASSUMED dependencies count as met).
--   * 'NodeContext' and 'ChannelContext' (BOLT #7): no unknown even
--     bit is set. A failure here means the node or channel must not be
--     routed through; the announcement itself is still valid.
--   * 'BlindedContext' (BOLT #4): no unknown bit is set, odd or even.
--   * 'ChannelTypeContext' (BOLT #2): the vector is a defined channel
--     type (see 'channel_type').
--
--   Unknown odd bits are otherwise ignored. A feature with both bits
--   set is not an error; it counts as 'Required' (see 'test_feature').
--   Nor is a known feature outside its listed contexts, since that
--   rule binds only the sender.
--
--   >>> validate_remote InitContext (set_bit 101 empty)
--   Right ()
--   >>> validate_remote InitContext (set_bit 100 empty)
--   Left (UnknownBit 100 :| [])
--   >>> validate_remote BlindedContext (set_bit 101 empty)
--   Left (UnknownBit 101 :| [])
validate_remote
  :: Context -> FeatureVector -> Either (NonEmpty ValidationError) ()
validate_remote :: Context -> FeatureVector -> Either (NonEmpty ValidationError) ()
validate_remote Context
ctx FeatureVector
fv = [ValidationError] -> Either (NonEmpty ValidationError) ()
forall e. [e] -> Either (NonEmpty e) ()
to_either ([ValidationError] -> Either (NonEmpty ValidationError) ())
-> [ValidationError] -> Either (NonEmpty ValidationError) ()
forall a b. (a -> b) -> a -> b
$ case Context
ctx of
  Context
InitContext        -> [ValidationError]
unknown_even [ValidationError] -> [ValidationError] -> [ValidationError]
forall a. [a] -> [a] -> [a]
++ FeatureVector -> [ValidationError]
dependency_errors FeatureVector
fv
  Context
NodeContext        -> [ValidationError]
unknown_even
  Context
ChannelContext     -> [ValidationError]
unknown_even
  Context
InvoiceContext     -> [ValidationError]
unknown_even [ValidationError] -> [ValidationError] -> [ValidationError]
forall a. [a] -> [a] -> [a]
++ FeatureVector -> [ValidationError]
dependency_errors FeatureVector
fv
  Context
BlindedContext     -> (Int -> Bool) -> FeatureVector -> [ValidationError]
unknown_bits (Bool -> Int -> Bool
forall a b. a -> b -> a
const Bool
True) FeatureVector
fv
  Context
ChannelTypeContext -> FeatureVector -> [ValidationError]
channel_type_errors FeatureVector
fv
  where
    unknown_even :: [ValidationError]
unknown_even = (Int -> Bool) -> FeatureVector -> [ValidationError]
unknown_bits Int -> Bool
forall a. Integral a => a -> Bool
even FeatureVector
fv

to_either :: [e] -> Either (NonEmpty e) ()
to_either :: forall e. [e] -> Either (NonEmpty e) ()
to_either []       = () -> Either (NonEmpty e) ()
forall a b. b -> Either a b
Right ()
to_either (e
e : [e]
es) = NonEmpty e -> Either (NonEmpty e) ()
forall a b. a -> Either a b
Left (e
e e -> [e] -> NonEmpty e
forall a. a -> [a] -> NonEmpty a
:| [e]
es)

-- Unknown set bits satisfying the predicate.
unknown_bits :: (Int -> Bool) -> FeatureVector -> [ValidationError]
unknown_bits :: (Int -> Bool) -> FeatureVector -> [ValidationError]
unknown_bits Int -> Bool
p FeatureVector
fv =
  [ Int -> ValidationError
UnknownBit Int
i
  | Int
i <- FeatureVector -> [Int]
set_bits FeatureVector
fv, Int -> Bool
p Int
i, Maybe Feature -> Bool
forall a. Maybe a -> Bool
isNothing (Int -> Maybe Feature
feature_by_bit Int
i) ]

both_bits_errors :: FeatureVector -> [ValidationError]
both_bits_errors :: FeatureVector -> [ValidationError]
both_bits_errors FeatureVector
fv =
  [ Feature -> ValidationError
BothBitsSet Feature
f
  | Feature
f <- [Feature]
known_features
  , Int -> FeatureVector -> Bool
test_bit (Feature -> FeatureLevel -> Int
level_bit Feature
f FeatureLevel
Required) FeatureVector
fv
  , Int -> FeatureVector -> Bool
test_bit (Feature -> FeatureLevel -> Int
level_bit Feature
f FeatureLevel
Optional) FeatureVector
fv ]

context_errors :: Context -> FeatureVector -> [ValidationError]
context_errors :: Context -> FeatureVector -> [ValidationError]
context_errors Context
ctx FeatureVector
fv =
  [ Feature -> Context -> ValidationError
ContextNotAllowed Feature
f Context
ctx
  | (Feature
f, FeatureLevel
_) <- FeatureVector -> [(Feature, FeatureLevel)]
list_features FeatureVector
fv, Bool -> Bool
not (Feature -> Bool
presented Feature
f) ]
  where
    presented :: Feature -> Bool
presented Feature
f = case Feature -> [Context]
feature_contexts Feature
f of
      [] -> Context
ctx Context -> [Context] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Context
InitContext, Context
NodeContext, Context
InvoiceContext]
      [Context]
cs -> Context
ctx Context -> [Context] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Context]
cs

dependency_errors :: FeatureVector -> [ValidationError]
dependency_errors :: FeatureVector -> [ValidationError]
dependency_errors FeatureVector
fv =
  [ Feature -> Feature -> ValidationError
MissingDependency Feature
f Feature
d
  | (Feature
f, FeatureLevel
_) <- FeatureVector -> [(Feature, FeatureLevel)]
list_features FeatureVector
fv
  , Feature
d <- Feature -> [Feature]
feature_dependencies Feature
f
  , Bool -> Bool
not (Feature -> Bool
feature_assumed Feature
d)
  , Maybe FeatureLevel -> Bool
forall a. Maybe a -> Bool
isNothing (Feature -> FeatureVector -> Maybe FeatureLevel
test_feature Feature
d FeatureVector
fv) ]

channel_type_errors :: FeatureVector -> [ValidationError]
channel_type_errors :: FeatureVector -> [ValidationError]
channel_type_errors FeatureVector
fv = case FeatureVector -> Maybe ChannelType
channel_type FeatureVector
fv of
  Maybe ChannelType
Nothing -> [ValidationError
InvalidChannelType]
  Just ChannelType
_  -> []

-- channel types -------------------------------------------------------------

-- | The basic channel types of BOLT #2.
data BasicChannelType
  = BasicStaticRemotekey
    -- ^ 'OptionStaticRemotekey' (bit 12)
  | BasicAnchors
    -- ^ 'OptionAnchors' and 'OptionStaticRemotekey' (bits 22 and 12)
  | BasicZeroFeeCommitments
    -- ^ 'ZeroFeeCommitments' (bit 40)
  deriving (BasicChannelType -> BasicChannelType -> Bool
(BasicChannelType -> BasicChannelType -> Bool)
-> (BasicChannelType -> BasicChannelType -> Bool)
-> Eq BasicChannelType
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: BasicChannelType -> BasicChannelType -> Bool
== :: BasicChannelType -> BasicChannelType -> Bool
$c/= :: BasicChannelType -> BasicChannelType -> Bool
/= :: BasicChannelType -> BasicChannelType -> Bool
Eq, Eq BasicChannelType
Eq BasicChannelType =>
(BasicChannelType -> BasicChannelType -> Ordering)
-> (BasicChannelType -> BasicChannelType -> Bool)
-> (BasicChannelType -> BasicChannelType -> Bool)
-> (BasicChannelType -> BasicChannelType -> Bool)
-> (BasicChannelType -> BasicChannelType -> Bool)
-> (BasicChannelType -> BasicChannelType -> BasicChannelType)
-> (BasicChannelType -> BasicChannelType -> BasicChannelType)
-> Ord BasicChannelType
BasicChannelType -> BasicChannelType -> Bool
BasicChannelType -> BasicChannelType -> Ordering
BasicChannelType -> BasicChannelType -> BasicChannelType
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: BasicChannelType -> BasicChannelType -> Ordering
compare :: BasicChannelType -> BasicChannelType -> Ordering
$c< :: BasicChannelType -> BasicChannelType -> Bool
< :: BasicChannelType -> BasicChannelType -> Bool
$c<= :: BasicChannelType -> BasicChannelType -> Bool
<= :: BasicChannelType -> BasicChannelType -> Bool
$c> :: BasicChannelType -> BasicChannelType -> Bool
> :: BasicChannelType -> BasicChannelType -> Bool
$c>= :: BasicChannelType -> BasicChannelType -> Bool
>= :: BasicChannelType -> BasicChannelType -> Bool
$cmax :: BasicChannelType -> BasicChannelType -> BasicChannelType
max :: BasicChannelType -> BasicChannelType -> BasicChannelType
$cmin :: BasicChannelType -> BasicChannelType -> BasicChannelType
min :: BasicChannelType -> BasicChannelType -> BasicChannelType
Ord, Int -> BasicChannelType -> ShowS
[BasicChannelType] -> ShowS
BasicChannelType -> String
(Int -> BasicChannelType -> ShowS)
-> (BasicChannelType -> String)
-> ([BasicChannelType] -> ShowS)
-> Show BasicChannelType
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> BasicChannelType -> ShowS
showsPrec :: Int -> BasicChannelType -> ShowS
$cshow :: BasicChannelType -> String
show :: BasicChannelType -> String
$cshowList :: [BasicChannelType] -> ShowS
showList :: [BasicChannelType] -> ShowS
Show, (forall x. BasicChannelType -> Rep BasicChannelType x)
-> (forall x. Rep BasicChannelType x -> BasicChannelType)
-> Generic BasicChannelType
forall x. Rep BasicChannelType x -> BasicChannelType
forall x. BasicChannelType -> Rep BasicChannelType x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. BasicChannelType -> Rep BasicChannelType x
from :: forall x. BasicChannelType -> Rep BasicChannelType x
$cto :: forall x. Rep BasicChannelType x -> BasicChannelType
to :: forall x. Rep BasicChannelType x -> BasicChannelType
Generic)

instance NFData BasicChannelType

-- | A channel type, per BOLT #2: a basic type plus any of the
--   'OptionScidAlias' and 'OptionZeroconf' variations.
--
--   Channel types are an enumeration that reuses even feature bits;
--   they aren't subject to the dependency or context rules for
--   feature vectors. BOLT #2 also forbids 'OptionScidAlias' in the
--   channel type of a channel to be announced, which needs the
--   @announce_channel@ flag to check.
data ChannelType = ChannelType {
    ChannelType -> BasicChannelType
ct_basic      :: !BasicChannelType
  , ChannelType -> Bool
ct_scid_alias :: !Bool
  , ChannelType -> Bool
ct_zeroconf   :: !Bool
  }
  deriving (ChannelType -> ChannelType -> Bool
(ChannelType -> ChannelType -> Bool)
-> (ChannelType -> ChannelType -> Bool) -> Eq ChannelType
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ChannelType -> ChannelType -> Bool
== :: ChannelType -> ChannelType -> Bool
$c/= :: ChannelType -> ChannelType -> Bool
/= :: ChannelType -> ChannelType -> Bool
Eq, Int -> ChannelType -> ShowS
[ChannelType] -> ShowS
ChannelType -> String
(Int -> ChannelType -> ShowS)
-> (ChannelType -> String)
-> ([ChannelType] -> ShowS)
-> Show ChannelType
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ChannelType -> ShowS
showsPrec :: Int -> ChannelType -> ShowS
$cshow :: ChannelType -> String
show :: ChannelType -> String
$cshowList :: [ChannelType] -> ShowS
showList :: [ChannelType] -> ShowS
Show, (forall x. ChannelType -> Rep ChannelType x)
-> (forall x. Rep ChannelType x -> ChannelType)
-> Generic ChannelType
forall x. Rep ChannelType x -> ChannelType
forall x. ChannelType -> Rep ChannelType x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ChannelType -> Rep ChannelType x
from :: forall x. ChannelType -> Rep ChannelType x
$cto :: forall x. Rep ChannelType x -> ChannelType
to :: forall x. Rep ChannelType x -> ChannelType
Generic)

instance NFData ChannelType

-- | The channel type that a @channel_type@ vector encodes, if it is a
--   defined one. Leading zero bytes are ignored.
--
--   >>> let zeroconf = ChannelType BasicStaticRemotekey False True
--   >>> channel_type (parse "\EOT\NUL\NUL\NUL\NUL\DLE\NUL") == Just zeroconf
--   True
--   >>> channel_type (set_bit 13 empty)
--   Nothing
channel_type :: FeatureVector -> Maybe ChannelType
channel_type :: FeatureVector -> Maybe ChannelType
channel_type FeatureVector
fv = (ChannelType -> Bool) -> [ChannelType] -> Maybe ChannelType
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((FeatureVector -> FeatureVector -> Bool
forall a. Eq a => a -> a -> Bool
== FeatureVector
fv) (FeatureVector -> Bool)
-> (ChannelType -> FeatureVector) -> ChannelType -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ChannelType -> FeatureVector
channel_type_features) [ChannelType]
channel_types

-- All defined channel types.
channel_types :: [ChannelType]
channel_types :: [ChannelType]
channel_types =
  [ BasicChannelType -> Bool -> Bool -> ChannelType
ChannelType BasicChannelType
b Bool
s Bool
z
  | BasicChannelType
b <- [BasicChannelType
BasicStaticRemotekey, BasicChannelType
BasicAnchors, BasicChannelType
BasicZeroFeeCommitments]
  , Bool
s <- [Bool
False, Bool
True]
  , Bool
z <- [Bool
False, Bool
True] ]

-- | The @channel_type@ vector for a channel type.
--
--   >>> let anchors = ChannelType BasicAnchors False False
--   >>> render (channel_type_features anchors)
--   "@\DLE\NUL"
channel_type_features :: ChannelType -> FeatureVector
channel_type_features :: ChannelType -> FeatureVector
channel_type_features (ChannelType BasicChannelType
b Bool
s Bool
z) =
    (Feature -> FeatureVector -> FeatureVector)
-> FeatureVector -> [Feature] -> FeatureVector
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (\Feature
f -> Feature -> FeatureLevel -> FeatureVector -> FeatureVector
set_feature Feature
f FeatureLevel
Required) FeatureVector
empty
      (BasicChannelType -> [Feature]
basic BasicChannelType
b [Feature] -> [Feature] -> [Feature]
forall a. [a] -> [a] -> [a]
++ [Feature
OptionScidAlias | Bool
s] [Feature] -> [Feature] -> [Feature]
forall a. [a] -> [a] -> [a]
++ [Feature
OptionZeroconf | Bool
z])
  where
    basic :: BasicChannelType -> [Feature]
basic BasicChannelType
BasicStaticRemotekey    = [Feature
OptionStaticRemotekey]
    basic BasicChannelType
BasicAnchors            = [Feature
OptionAnchors, Feature
OptionStaticRemotekey]
    basic BasicChannelType
BasicZeroFeeCommitments = [Feature
ZeroFeeCommitments]