{-# LANGUAGE LambdaCase #-}

{- |
Module      : Singular.State.Preimage
Description : The hashed-name preimages of the Singular state, as bytes
License     : Apache-2.0

Every hashed name of the Singular state is the blake2b-256 hash of a preimage,
and the preimage is the Plutus Data serialisation of a structured value with
one constructor per role. The constructors are numbered as the model's
@Preimage@, so two roles never share a preimage even when they carry the same
fields.

The bytes are pinned by the vectors in
@test\/fixtures\/preimage-vectors.json@, which the on-chain functions of
@singular_state\/preimage.ak@ reproduce as well. Nothing here builds a
transaction.
-}
module Singular.State.Preimage
    ( -- * The roles
      Preimage (..)
    , encodePreimage
    , roleName

      -- * The names the line builds
    , stateTokenName
    , activeTokenName
    , configurationTokenName
    , registrationPreimage
    , terminationPreimage
    , approvalName
    , initialDatumHash
    , seedData
    ) where

import Codec.Serialise (serialise)
import Crypto.Hash (Blake2b_256 (..), hashWith)
import Data.ByteArray qualified as BA
import Data.ByteString (ByteString)
import Data.ByteString.Lazy qualified as BL
import Data.ByteString.Short qualified as SBS
import PlutusCore.Data (Data (..))
import PlutusLedgerApi.V3
    ( Address
    , DatumHash (..)
    , Lovelace
    , getLovelace
    )
import PlutusTx.Builtins.Internal
    ( BuiltinByteString (..)
    , BuiltinData (..)
    )
import PlutusTx.IsData.Class (toBuiltinData)

import Cardano.Crypto.Hash.Class (hashToBytes)
import Cardano.Ledger.BaseTypes (TxIx (..))
import Cardano.Ledger.Hashes (extractHash)
import Cardano.Ledger.Mary.Value (AssetName (..))
import Cardano.Ledger.TxIn (TxId (..), TxIn (..))

import Singular.Registry.TrieState
    ( RegistryIdentity (..)
    , StatePolicyId (..)
    )

{- | The structured value hashed into a name, one constructor per role,
numbered as the model's @Preimage@.
-}
data Preimage
    = -- | The registry created by spending the seed.
      State TxIn
    | -- | The token that stands for a key in a registry.
      Active RegistryIdentity ByteString
    | -- | The registry's application configuration.
      ApplicationConfiguration RegistryIdentity
    | {- | The approval of one registration: registry, key, the address the
      holding sits at, the hash of the holding's initial datum and the deposit
      it holds.
      -}
      RegistrationApproval
        RegistryIdentity
        ByteString
        Address
        DatumHash
        Lovelace
    | -- | The approval of the termination of a key.
      TerminationApproval RegistryIdentity ByteString
    deriving stock (Preimage -> Preimage -> Bool
(Preimage -> Preimage -> Bool)
-> (Preimage -> Preimage -> Bool) -> Eq Preimage
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Preimage -> Preimage -> Bool
== :: Preimage -> Preimage -> Bool
$c/= :: Preimage -> Preimage -> Bool
/= :: Preimage -> Preimage -> Bool
Eq, Int -> Preimage -> ShowS
[Preimage] -> ShowS
Preimage -> String
(Int -> Preimage -> ShowS)
-> (Preimage -> String) -> ([Preimage] -> ShowS) -> Show Preimage
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Preimage -> ShowS
showsPrec :: Int -> Preimage -> ShowS
$cshow :: Preimage -> String
show :: Preimage -> String
$cshowList :: [Preimage] -> ShowS
showList :: [Preimage] -> ShowS
Show)

-- | The Plutus Data serialisation of a preimage.
encodePreimage :: Preimage -> ByteString
encodePreimage :: Preimage -> ByteString
encodePreimage = LazyByteString -> ByteString
BL.toStrict (LazyByteString -> ByteString)
-> (Preimage -> LazyByteString) -> Preimage -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Data -> LazyByteString
forall a. Serialise a => a -> LazyByteString
serialise (Data -> LazyByteString)
-> (Preimage -> Data) -> Preimage -> LazyByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Preimage -> Data
preimageData

-- | A preimage as the value that is serialised: one constructor per role.
preimageData :: Preimage -> Data
preimageData :: Preimage -> Data
preimageData = \case
    State TxIn
seed -> Integer -> [Data] -> Data
Constr Integer
0 [TxIn -> Data
seedData TxIn
seed]
    Active RegistryIdentity
registry ByteString
key -> Integer -> [Data] -> Data
Constr Integer
1 [RegistryIdentity -> Data
registryData RegistryIdentity
registry, ByteString -> Data
B ByteString
key]
    ApplicationConfiguration RegistryIdentity
registry -> Integer -> [Data] -> Data
Constr Integer
2 [RegistryIdentity -> Data
registryData RegistryIdentity
registry]
    RegistrationApproval RegistryIdentity
registry ByteString
key Address
holding DatumHash
hash Lovelace
deposit ->
        Integer -> [Data] -> Data
Constr
            Integer
3
            [ RegistryIdentity -> Data
registryData RegistryIdentity
registry
            , ByteString -> Data
B ByteString
key
            , Address -> Data
addressData Address
holding
            , DatumHash -> Data
datumHashData DatumHash
hash
            , Integer -> Data
I (Lovelace -> Integer
getLovelace Lovelace
deposit)
            ]
    TerminationApproval RegistryIdentity
registry ByteString
key ->
        Integer -> [Data] -> Data
Constr Integer
4 [RegistryIdentity -> Data
registryData RegistryIdentity
registry, ByteString -> Data
B ByteString
key]

-- | An output reference: the transaction id and the output index, as a script reads it.
seedData :: TxIn -> Data
seedData :: TxIn -> Data
seedData (TxIn (TxId SafeHash EraIndependentTxBody
hash) (TxIx Word16
index)) =
    Integer -> [Data] -> Data
Constr Integer
0 [ByteString -> Data
B (Hash HASH EraIndependentTxBody -> ByteString
forall h a. Hash h a -> ByteString
hashToBytes (SafeHash EraIndependentTxBody -> Hash HASH EraIndependentTxBody
forall i. SafeHash i -> Hash HASH i
extractHash SafeHash EraIndependentTxBody
hash)), Integer -> Data
I (Word16 -> Integer
forall a. Integral a => a -> Integer
toInteger Word16
index)]

-- | A registry identity: the state policy and the state token name.
registryData :: RegistryIdentity -> Data
registryData :: RegistryIdentity -> Data
registryData (RegistryIdentity (StatePolicyId ByteString
policy) (AssetName ShortByteString
name)) =
    Integer -> [Data] -> Data
Constr Integer
0 [ByteString -> Data
B ByteString
policy, ByteString -> Data
B (ShortByteString -> ByteString
SBS.fromShort ShortByteString
name)]

-- | An address, as the ledger hands it to a script.
addressData :: Address -> Data
addressData :: Address -> Data
addressData Address
address = case Address -> BuiltinData
forall a. ToData a => a -> BuiltinData
toBuiltinData Address
address of
    BuiltinData Data
data' -> Data
data'

-- | The hash of a datum: its 32 bytes.
datumHashData :: DatumHash -> Data
datumHashData :: DatumHash -> Data
datumHashData (DatumHash (BuiltinByteString ByteString
bytes)) = ByteString -> Data
B ByteString
bytes

-- | The name of a role: the blake2b-256 hash of its preimage.
roleName :: Preimage -> AssetName
roleName :: Preimage -> AssetName
roleName = ByteString -> AssetName
approvalName (ByteString -> AssetName)
-> (Preimage -> ByteString) -> Preimage -> AssetName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Preimage -> ByteString
encodePreimage

-- | The name of the state token of the registry created by spending the seed.
stateTokenName :: TxIn -> AssetName
stateTokenName :: TxIn -> AssetName
stateTokenName = Preimage -> AssetName
roleName (Preimage -> AssetName) -> (TxIn -> Preimage) -> TxIn -> AssetName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TxIn -> Preimage
State

-- | The name of the token that stands for a key in a registry.
activeTokenName :: RegistryIdentity -> ByteString -> AssetName
activeTokenName :: RegistryIdentity -> ByteString -> AssetName
activeTokenName RegistryIdentity
registry = Preimage -> AssetName
roleName (Preimage -> AssetName)
-> (ByteString -> Preimage) -> ByteString -> AssetName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RegistryIdentity -> ByteString -> Preimage
Active RegistryIdentity
registry

-- | The name of the token of the configuration record of a registry.
configurationTokenName :: RegistryIdentity -> AssetName
configurationTokenName :: RegistryIdentity -> AssetName
configurationTokenName = Preimage -> AssetName
roleName (Preimage -> AssetName)
-> (RegistryIdentity -> Preimage) -> RegistryIdentity -> AssetName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RegistryIdentity -> Preimage
ApplicationConfiguration

{- | The Plutus Data serialisation of the registration approval preimage: the
key, the registry, the address the holding sits at, the hash of the holding's
initial datum and the deposit.
-}
registrationPreimage
    :: ByteString
    -> RegistryIdentity
    -> Address
    -> DatumHash
    -> Lovelace
    -> ByteString
registrationPreimage :: ByteString
-> RegistryIdentity
-> Address
-> DatumHash
-> Lovelace
-> ByteString
registrationPreimage ByteString
key RegistryIdentity
registry Address
holding DatumHash
datumHash Lovelace
deposit =
    Preimage -> ByteString
encodePreimage
        (RegistryIdentity
-> ByteString -> Address -> DatumHash -> Lovelace -> Preimage
RegistrationApproval RegistryIdentity
registry ByteString
key Address
holding DatumHash
datumHash Lovelace
deposit)

{- | The Plutus Data serialisation of the termination approval preimage: the
registry and the key.
-}
terminationPreimage :: ByteString -> RegistryIdentity -> ByteString
terminationPreimage :: ByteString -> RegistryIdentity -> ByteString
terminationPreimage ByteString
key RegistryIdentity
registry =
    Preimage -> ByteString
encodePreimage (RegistryIdentity -> ByteString -> Preimage
TerminationApproval RegistryIdentity
registry ByteString
key)

-- | The name of the approval token whose preimage is the given bytes.
approvalName :: ByteString -> AssetName
approvalName :: ByteString -> AssetName
approvalName = ShortByteString -> AssetName
AssetName (ShortByteString -> AssetName)
-> (ByteString -> ShortByteString) -> ByteString -> AssetName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> ShortByteString
SBS.toShort (ByteString -> ShortByteString)
-> (ByteString -> ByteString) -> ByteString -> ShortByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Digest Blake2b_256 -> ByteString
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
bin -> bout
BA.convert (Digest Blake2b_256 -> ByteString)
-> (ByteString -> Digest Blake2b_256) -> ByteString -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Blake2b_256 -> ByteString -> Digest Blake2b_256
forall ba alg.
(ByteArrayAccess ba, HashAlgorithm alg) =>
alg -> ba -> Digest alg
hashWith Blake2b_256
Blake2b_256

{- | The hash a registration approval commits for the datum a holding starts
with: the blake2b-256 hash of its Plutus Data serialisation.
-}
initialDatumHash :: Data -> DatumHash
initialDatumHash :: Data -> DatumHash
initialDatumHash =
    BuiltinByteString -> DatumHash
DatumHash
        (BuiltinByteString -> DatumHash)
-> (Data -> BuiltinByteString) -> Data -> DatumHash
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> BuiltinByteString
BuiltinByteString
        (ByteString -> BuiltinByteString)
-> (Data -> ByteString) -> Data -> BuiltinByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Digest Blake2b_256 -> ByteString
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
bin -> bout
BA.convert
        (Digest Blake2b_256 -> ByteString)
-> (Data -> Digest Blake2b_256) -> Data -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Blake2b_256 -> ByteString -> Digest Blake2b_256
forall ba alg.
(ByteArrayAccess ba, HashAlgorithm alg) =>
alg -> ba -> Digest alg
hashWith Blake2b_256
Blake2b_256
        (ByteString -> Digest Blake2b_256)
-> (Data -> ByteString) -> Data -> Digest Blake2b_256
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LazyByteString -> ByteString
BL.toStrict
        (LazyByteString -> ByteString)
-> (Data -> LazyByteString) -> Data -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Data -> LazyByteString
forall a. Serialise a => a -> LazyByteString
serialise