{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}

module Cardano.Chain.Common.AddrAttributes (
  AddrAttributes (..),
  HDAddressPayload (..),
)
where

import Cardano.Chain.Common.Attributes (
  Attributes (..),
  decCBORAttributes,
  encCBORAttributes,
 )
import Cardano.Chain.Common.NetworkMagic (NetworkMagic (..))
import Cardano.HeapWords (HeapWords (..))
import Cardano.Ledger.Binary (
  DecCBOR (..),
  Decoder,
  EncCBOR (..),
  FromCBOR (..),
  ToCBOR (..),
  byronProtVer,
  decodeBytesCanonical,
  decodeFull,
  decodeFullDecoder,
  decodeWord32Canonical,
  fromByronCBOR,
  serialize,
  toByronCBOR,
  toCborError,
 )
import Cardano.Prelude hiding (toCborError)
import Data.Aeson (ToJSON (..), object, (.=))
import qualified Data.ByteString.Char8 as Char8
import Data.Text.Lazy.Builder (Builder)
import Formatting (bprint, builder)
import qualified Formatting.Buildable as B
import NoThunks.Class (NoThunks (..))

-- | Additional information stored along with address. It's intended
-- to be put into 'Attributes' data type to make it extensible with
-- softfork.
data AddrAttributes = AddrAttributes
  { AddrAttributes -> Maybe HDAddressPayload
aaVKDerivationPath :: !(Maybe HDAddressPayload)
  , AddrAttributes -> NetworkMagic
aaNetworkMagic :: !NetworkMagic
  }
  deriving (AddrAttributes -> AddrAttributes -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: AddrAttributes -> AddrAttributes -> Bool
$c/= :: AddrAttributes -> AddrAttributes -> Bool
== :: AddrAttributes -> AddrAttributes -> Bool
$c== :: AddrAttributes -> AddrAttributes -> Bool
Eq, Eq AddrAttributes
AddrAttributes -> AddrAttributes -> Bool
AddrAttributes -> AddrAttributes -> Ordering
AddrAttributes -> AddrAttributes -> AddrAttributes
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
min :: AddrAttributes -> AddrAttributes -> AddrAttributes
$cmin :: AddrAttributes -> AddrAttributes -> AddrAttributes
max :: AddrAttributes -> AddrAttributes -> AddrAttributes
$cmax :: AddrAttributes -> AddrAttributes -> AddrAttributes
>= :: AddrAttributes -> AddrAttributes -> Bool
$c>= :: AddrAttributes -> AddrAttributes -> Bool
> :: AddrAttributes -> AddrAttributes -> Bool
$c> :: AddrAttributes -> AddrAttributes -> Bool
<= :: AddrAttributes -> AddrAttributes -> Bool
$c<= :: AddrAttributes -> AddrAttributes -> Bool
< :: AddrAttributes -> AddrAttributes -> Bool
$c< :: AddrAttributes -> AddrAttributes -> Bool
compare :: AddrAttributes -> AddrAttributes -> Ordering
$ccompare :: AddrAttributes -> AddrAttributes -> Ordering
Ord, Int -> AddrAttributes -> ShowS
[AddrAttributes] -> ShowS
AddrAttributes -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [AddrAttributes] -> ShowS
$cshowList :: [AddrAttributes] -> ShowS
show :: AddrAttributes -> String
$cshow :: AddrAttributes -> String
showsPrec :: Int -> AddrAttributes -> ShowS
$cshowsPrec :: Int -> AddrAttributes -> ShowS
Show, forall x. Rep AddrAttributes x -> AddrAttributes
forall x. AddrAttributes -> Rep AddrAttributes x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cto :: forall x. Rep AddrAttributes x -> AddrAttributes
$cfrom :: forall x. AddrAttributes -> Rep AddrAttributes x
Generic, AddrAttributes -> ()
forall a. (a -> ()) -> NFData a
rnf :: AddrAttributes -> ()
$crnf :: AddrAttributes -> ()
NFData, Context -> AddrAttributes -> IO (Maybe ThunkInfo)
Proxy AddrAttributes -> String
forall a.
(Context -> a -> IO (Maybe ThunkInfo))
-> (Context -> a -> IO (Maybe ThunkInfo))
-> (Proxy a -> String)
-> NoThunks a
showTypeOf :: Proxy AddrAttributes -> String
$cshowTypeOf :: Proxy AddrAttributes -> String
wNoThunks :: Context -> AddrAttributes -> IO (Maybe ThunkInfo)
$cwNoThunks :: Context -> AddrAttributes -> IO (Maybe ThunkInfo)
noThunks :: Context -> AddrAttributes -> IO (Maybe ThunkInfo)
$cnoThunks :: Context -> AddrAttributes -> IO (Maybe ThunkInfo)
NoThunks)

instance HeapWords AddrAttributes where
  heapWords :: AddrAttributes -> Int
heapWords AddrAttributes
aa =
    Int
3
      forall a. Num a => a -> a -> a
+ forall a. HeapWords a => a -> Int
heapWords (AddrAttributes -> Maybe HDAddressPayload
aaVKDerivationPath AddrAttributes
aa)
      forall a. Num a => a -> a -> a
+ forall a. HeapWords a => a -> Int
heapWords (AddrAttributes -> NetworkMagic
aaNetworkMagic AddrAttributes
aa)

instance B.Buildable AddrAttributes where
  build :: AddrAttributes -> Builder
build AddrAttributes
aa =
    forall a. Format Builder a -> a
bprint
      (Format (Builder -> Builder) (Builder -> Builder)
"AddrAttributes { derivation path: " forall {k} (cat :: k -> k -> *) (b :: k) (c :: k) (a :: k).
Category cat =>
cat b c -> cat a b -> cat a c
. forall r. Format r (Builder -> r)
builder forall {k} (cat :: k -> k -> *) (b :: k) (c :: k) (a :: k).
Category cat =>
cat b c -> cat a b -> cat a c
. Format Builder Builder
" }")
      Builder
derivationPathBuilder
    where
      derivationPathBuilder :: Builder
      derivationPathBuilder :: Builder
derivationPathBuilder = case AddrAttributes -> Maybe HDAddressPayload
aaVKDerivationPath AddrAttributes
aa of
        Maybe HDAddressPayload
Nothing -> Builder
"{}"
        Just HDAddressPayload
_ -> Builder
"{path is encrypted}"

-- Used for debugging purposes only
instance ToJSON AddrAttributes

{- NOTE: Address attributes serialization
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

'Attributes' are conceptually a map, where keys are numbers ('Word8').

For address there are two attributes:
  - 1 - derivation path, defaults to 'Nothing'.

-}

instance ToCBOR (Attributes AddrAttributes) where
  toCBOR :: Attributes AddrAttributes -> Encoding
toCBOR = forall a. EncCBOR a => a -> Encoding
toByronCBOR

instance FromCBOR (Attributes AddrAttributes) where
  fromCBOR :: forall s. Decoder s (Attributes AddrAttributes)
fromCBOR = forall a s. DecCBOR a => Decoder s a
fromByronCBOR

instance EncCBOR (Attributes AddrAttributes) where
  -- FIXME @avieth it was observed that for a 150kb block, this call to
  -- encCBORAttributes allocated 3.685mb
  -- Try using serialize rather than serialize', to avoid the
  -- toStrict call.
  -- Also consider using a custom builder strategy; serialized attributes are
  -- probably small, right?
  encCBOR :: Attributes AddrAttributes -> Encoding
encCBOR attrs :: Attributes AddrAttributes
attrs@Attributes {attrData :: forall h. Attributes h -> h
attrData = AddrAttributes Maybe HDAddressPayload
derivationPath NetworkMagic
networkMagic} =
    forall t. [(Word8, t -> LByteString)] -> Attributes t -> Encoding
encCBORAttributes [(Word8, AddrAttributes -> LByteString)]
listWithIndices Attributes AddrAttributes
attrs
    where
      listWithIndices :: [(Word8, AddrAttributes -> LByteString)]
      listWithIndices :: [(Word8, AddrAttributes -> LByteString)]
listWithIndices =
        [(Word8, AddrAttributes -> LByteString)]
derivationPathListWithIndices
          forall a. Semigroup a => a -> a -> a
<> [(Word8, AddrAttributes -> LByteString)]
networkMagicListWithIndices

      derivationPathListWithIndices :: [(Word8, AddrAttributes -> LByteString)]
      derivationPathListWithIndices :: [(Word8, AddrAttributes -> LByteString)]
derivationPathListWithIndices = case Maybe HDAddressPayload
derivationPath of
        Maybe HDAddressPayload
Nothing -> []
        -- 'unsafeFromJust' is safe, because 'case' ensures
        -- that derivation path is 'Just'.
        Just HDAddressPayload
_ -> [(Word8
1, forall a. EncCBOR a => Version -> a -> LByteString
serialize Version
byronProtVer forall {k} (cat :: k -> k -> *) (b :: k) (c :: k) (a :: k).
Category cat =>
cat b c -> cat a b -> cat a c
. forall a. Maybe a -> a
unsafeFromJust forall {k} (cat :: k -> k -> *) (b :: k) (c :: k) (a :: k).
Category cat =>
cat b c -> cat a b -> cat a c
. AddrAttributes -> Maybe HDAddressPayload
aaVKDerivationPath)]
      unsafeFromJust :: Maybe a -> a
      unsafeFromJust :: forall a. Maybe a -> a
unsafeFromJust =
        forall a. a -> Maybe a -> a
fromMaybe (forall a. HasCallStack => Text -> a
panic Text
"Maybe was Nothing in EncCBOR (Attributes AddrAttributes)")

      networkMagicListWithIndices :: [(Word8, AddrAttributes -> LByteString)]
      networkMagicListWithIndices :: [(Word8, AddrAttributes -> LByteString)]
networkMagicListWithIndices =
        case NetworkMagic
networkMagic of
          NetworkMagic
NetworkMainOrStage -> []
          NetworkTestnet Word32
x ->
            [(Word8
2, \AddrAttributes
_ -> forall a. EncCBOR a => Version -> a -> LByteString
serialize Version
byronProtVer Word32
x)]

instance DecCBOR (Attributes AddrAttributes) where
  decCBOR :: forall s. Decoder s (Attributes AddrAttributes)
decCBOR = forall t s.
t
-> (Word8 -> LByteString -> t -> Decoder s (Maybe t))
-> Decoder s (Attributes t)
decCBORAttributes AddrAttributes
initValue forall s.
Word8
-> LByteString
-> AddrAttributes
-> Decoder s (Maybe AddrAttributes)
go
    where
      initValue :: AddrAttributes
initValue =
        AddrAttributes
          { aaVKDerivationPath :: Maybe HDAddressPayload
aaVKDerivationPath = forall a. Maybe a
Nothing
          , aaNetworkMagic :: NetworkMagic
aaNetworkMagic = NetworkMagic
NetworkMainOrStage
          }

      go ::
        Word8 ->
        LByteString ->
        AddrAttributes ->
        Decoder s (Maybe AddrAttributes)
      go :: forall s.
Word8
-> LByteString
-> AddrAttributes
-> Decoder s (Maybe AddrAttributes)
go Word8
n LByteString
v AddrAttributes
acc = case Word8
n of
        Word8
1 ->
          (\HDAddressPayload
deriv -> forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$ AddrAttributes
acc {aaVKDerivationPath :: Maybe HDAddressPayload
aaVKDerivationPath = forall a. a -> Maybe a
Just HDAddressPayload
deriv})
            forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall (m :: * -> *) e a.
(MonadFail m, Buildable e) =>
Either e a -> m a
toCborError (forall a.
DecCBOR a =>
Version -> LByteString -> Either DecoderError a
decodeFull Version
byronProtVer LByteString
v)
        Word8
2 ->
          (\Word32
deriv -> forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$ AddrAttributes
acc {aaNetworkMagic :: NetworkMagic
aaNetworkMagic = Word32 -> NetworkMagic
NetworkTestnet Word32
deriv})
            forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall (m :: * -> *) e a.
(MonadFail m, Buildable e) =>
Either e a -> m a
toCborError
              (forall a.
Version
-> Text
-> (forall s. Decoder s a)
-> LByteString
-> Either DecoderError a
decodeFullDecoder Version
byronProtVer Text
"NetworkMagic" forall s. Decoder s Word32
decodeWord32Canonical LByteString
v)
        Word8
_ -> forall (f :: * -> *) a. Applicative f => a -> f a
pure forall a. Maybe a
Nothing

-- | Passphrase is a hash of root verification key.
data HDPassphrase = HDPassphrase !ByteString
  deriving (HDPassphrase -> HDPassphrase -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: HDPassphrase -> HDPassphrase -> Bool
$c/= :: HDPassphrase -> HDPassphrase -> Bool
== :: HDPassphrase -> HDPassphrase -> Bool
$c== :: HDPassphrase -> HDPassphrase -> Bool
Eq, Int -> HDPassphrase -> ShowS
[HDPassphrase] -> ShowS
HDPassphrase -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [HDPassphrase] -> ShowS
$cshowList :: [HDPassphrase] -> ShowS
show :: HDPassphrase -> String
$cshow :: HDPassphrase -> String
showsPrec :: Int -> HDPassphrase -> ShowS
$cshowsPrec :: Int -> HDPassphrase -> ShowS
Show)

-- | HDAddressPayload is a specific address attribute that was used by the
-- Cardano wallet at mainnet launch, prior to moving to a BIP-44 style scheme.
--
-- It consisted of
--
--   * serialized and encrypted using HDPassphrase derivation path from the
--   root key to given descendant key (using ChaChaPoly1305 algorithm)
--
--   * cryptographic tag
--
-- It is still distinguished as an attribute, but not used by the ledger,
-- because the attributes size limits treat this attribute specially.
newtype HDAddressPayload = HDAddressPayload
  { HDAddressPayload -> ByteString
getHDAddressPayload :: ByteString
  }
  deriving (HDAddressPayload -> HDAddressPayload -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: HDAddressPayload -> HDAddressPayload -> Bool
$c/= :: HDAddressPayload -> HDAddressPayload -> Bool
== :: HDAddressPayload -> HDAddressPayload -> Bool
$c== :: HDAddressPayload -> HDAddressPayload -> Bool
Eq, Eq HDAddressPayload
HDAddressPayload -> HDAddressPayload -> Bool
HDAddressPayload -> HDAddressPayload -> Ordering
HDAddressPayload -> HDAddressPayload -> HDAddressPayload
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
min :: HDAddressPayload -> HDAddressPayload -> HDAddressPayload
$cmin :: HDAddressPayload -> HDAddressPayload -> HDAddressPayload
max :: HDAddressPayload -> HDAddressPayload -> HDAddressPayload
$cmax :: HDAddressPayload -> HDAddressPayload -> HDAddressPayload
>= :: HDAddressPayload -> HDAddressPayload -> Bool
$c>= :: HDAddressPayload -> HDAddressPayload -> Bool
> :: HDAddressPayload -> HDAddressPayload -> Bool
$c> :: HDAddressPayload -> HDAddressPayload -> Bool
<= :: HDAddressPayload -> HDAddressPayload -> Bool
$c<= :: HDAddressPayload -> HDAddressPayload -> Bool
< :: HDAddressPayload -> HDAddressPayload -> Bool
$c< :: HDAddressPayload -> HDAddressPayload -> Bool
compare :: HDAddressPayload -> HDAddressPayload -> Ordering
$ccompare :: HDAddressPayload -> HDAddressPayload -> Ordering
Ord, Int -> HDAddressPayload -> ShowS
[HDAddressPayload] -> ShowS
HDAddressPayload -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [HDAddressPayload] -> ShowS
$cshowList :: [HDAddressPayload] -> ShowS
show :: HDAddressPayload -> String
$cshow :: HDAddressPayload -> String
showsPrec :: Int -> HDAddressPayload -> ShowS
$cshowsPrec :: Int -> HDAddressPayload -> ShowS
Show, forall x. Rep HDAddressPayload x -> HDAddressPayload
forall x. HDAddressPayload -> Rep HDAddressPayload x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cto :: forall x. Rep HDAddressPayload x -> HDAddressPayload
$cfrom :: forall x. HDAddressPayload -> Rep HDAddressPayload x
Generic)
  deriving newtype (Typeable HDAddressPayload
HDAddressPayload -> Encoding
(forall t. EncCBOR t => Proxy t -> Size)
-> Proxy [HDAddressPayload] -> Size
(forall t. EncCBOR t => Proxy t -> Size)
-> Proxy HDAddressPayload -> Size
forall a.
Typeable a
-> (a -> Encoding)
-> ((forall t. EncCBOR t => Proxy t -> Size) -> Proxy a -> Size)
-> ((forall t. EncCBOR t => Proxy t -> Size) -> Proxy [a] -> Size)
-> EncCBOR a
encodedListSizeExpr :: (forall t. EncCBOR t => Proxy t -> Size)
-> Proxy [HDAddressPayload] -> Size
$cencodedListSizeExpr :: (forall t. EncCBOR t => Proxy t -> Size)
-> Proxy [HDAddressPayload] -> Size
encodedSizeExpr :: (forall t. EncCBOR t => Proxy t -> Size)
-> Proxy HDAddressPayload -> Size
$cencodedSizeExpr :: (forall t. EncCBOR t => Proxy t -> Size)
-> Proxy HDAddressPayload -> Size
encCBOR :: HDAddressPayload -> Encoding
$cencCBOR :: HDAddressPayload -> Encoding
EncCBOR, HDAddressPayload -> Int
forall a. (a -> Int) -> HeapWords a
heapWords :: HDAddressPayload -> Int
$cheapWords :: HDAddressPayload -> Int
HeapWords)
  deriving anyclass (HDAddressPayload -> ()
forall a. (a -> ()) -> NFData a
rnf :: HDAddressPayload -> ()
$crnf :: HDAddressPayload -> ()
NFData, Context -> HDAddressPayload -> IO (Maybe ThunkInfo)
Proxy HDAddressPayload -> String
forall a.
(Context -> a -> IO (Maybe ThunkInfo))
-> (Context -> a -> IO (Maybe ThunkInfo))
-> (Proxy a -> String)
-> NoThunks a
showTypeOf :: Proxy HDAddressPayload -> String
$cshowTypeOf :: Proxy HDAddressPayload -> String
wNoThunks :: Context -> HDAddressPayload -> IO (Maybe ThunkInfo)
$cwNoThunks :: Context -> HDAddressPayload -> IO (Maybe ThunkInfo)
noThunks :: Context -> HDAddressPayload -> IO (Maybe ThunkInfo)
$cnoThunks :: Context -> HDAddressPayload -> IO (Maybe ThunkInfo)
NoThunks)

instance ToCBOR HDAddressPayload where
  toCBOR :: HDAddressPayload -> Encoding
toCBOR = forall a. EncCBOR a => a -> Encoding
toByronCBOR

instance FromCBOR HDAddressPayload where
  fromCBOR :: forall s. Decoder s HDAddressPayload
fromCBOR = forall a s. DecCBOR a => Decoder s a
fromByronCBOR

-- Used for debugging purposes only
instance ToJSON HDAddressPayload where
  toJSON :: HDAddressPayload -> Value
toJSON (HDAddressPayload ByteString
bs) = [Pair] -> Value
object [Key
"HDAddressPayload" forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= ByteString -> String
Char8.unpack ByteString
bs]

instance DecCBOR HDAddressPayload where
  decCBOR :: forall s. Decoder s HDAddressPayload
decCBOR = ByteString -> HDAddressPayload
HDAddressPayload forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall s. Decoder s ByteString
decodeBytesCanonical