{-# LANGUAGE OverloadedStrings #-}
-- Copyright 2026 Biglup Labs
-- SPDX-License-Identifier: Apache-2.0
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--     https://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE RoleAnnotations #-}

-- | Role-specific credentials for payments, staking, governance and guards.
-- Hashes contain exactly 28 bytes. Equality and ordering compare kind and bytes;
-- diagnostic 'Show' output is not an interchange encoding.
--
-- @
-- import qualified Cometa.Credential as Credential
-- import qualified Cometa.Error
-- import qualified Data.ByteString as ByteString
--
-- payment :: Either Cometa.Error.Error (Credential.Credential Credential.Payment)
-- payment = Credential.KeyCredential <$> Credential.keyHashFromBytes (ByteString.replicate 28 0)
-- @
module Cometa.Credential
  ( Payment,
    Stake,
    Guard,
    DRep,
    CommitteeHot,
    CommitteeCold,
    Genesis,
    GenesisDelegate,
    StakePool,
    KeyHash,
    keyHashFromBytes,
    keyHashBytes,
    ScriptHash,
    scriptHashFromBytes,
    scriptHashBytes,
    Credential (..),
    fromPublicKey,
    encodeCbor,
    decodeCbor,
  )
where

-- IMPORTS --------------------------------------------------------------------

import qualified Codec.CBOR.Encoding as E
import qualified Codec.CBOR.Read as R
import qualified Codec.CBOR.Term as T
import qualified Codec.CBOR.Write as W
import qualified Cometa.Crypto.Blake2b as Blake2b
import qualified Cometa.Crypto.Ed25519.PublicKey as PublicKey
import Cometa.Error (Error (InvalidCredentialCbor, InvalidCredentialHashLength))
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Lazy as Lazy
import qualified Data.Text as Text

-- TYPES ----------------------------------------------------------------------

-- | Role of a payment key or credential.
data Payment

-- | Role of a staking key or credential.
data Stake

-- | Role of a Dijkstra transaction guard credential.
data Guard

-- | Role of a delegated representative's voting credential.
data DRep

-- | Role of a constitutional committee member's voting credential.
data CommitteeHot

-- | Role of a constitutional committee member's authorization credential.
data CommitteeCold

-- | Role of a genesis key authorizing delegation or a legacy protocol update.
data Genesis

-- | Role of a delegate authorized by a genesis key.
data GenesisDelegate

-- | Role of a stake pool operator's key hash.
data StakePool

-- | A 28-byte key hash. Hashes in different roles are distinct types;
-- importing bytes assigns their role.
type role KeyHash nominal

newtype KeyHash purpose = KeyHash ByteString deriving (KeyHash purpose -> KeyHash purpose -> Bool
(KeyHash purpose -> KeyHash purpose -> Bool)
-> (KeyHash purpose -> KeyHash purpose -> Bool)
-> Eq (KeyHash purpose)
forall purpose. KeyHash purpose -> KeyHash purpose -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: forall purpose. KeyHash purpose -> KeyHash purpose -> Bool
== :: KeyHash purpose -> KeyHash purpose -> Bool
$c/= :: forall purpose. KeyHash purpose -> KeyHash purpose -> Bool
/= :: KeyHash purpose -> KeyHash purpose -> Bool
Eq, Eq (KeyHash purpose)
Eq (KeyHash purpose) =>
(KeyHash purpose -> KeyHash purpose -> Ordering)
-> (KeyHash purpose -> KeyHash purpose -> Bool)
-> (KeyHash purpose -> KeyHash purpose -> Bool)
-> (KeyHash purpose -> KeyHash purpose -> Bool)
-> (KeyHash purpose -> KeyHash purpose -> Bool)
-> (KeyHash purpose -> KeyHash purpose -> KeyHash purpose)
-> (KeyHash purpose -> KeyHash purpose -> KeyHash purpose)
-> Ord (KeyHash purpose)
KeyHash purpose -> KeyHash purpose -> Bool
KeyHash purpose -> KeyHash purpose -> Ordering
KeyHash purpose -> KeyHash purpose -> KeyHash purpose
forall purpose. Eq (KeyHash purpose)
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
forall purpose. KeyHash purpose -> KeyHash purpose -> Bool
forall purpose. KeyHash purpose -> KeyHash purpose -> Ordering
forall purpose.
KeyHash purpose -> KeyHash purpose -> KeyHash purpose
$ccompare :: forall purpose. KeyHash purpose -> KeyHash purpose -> Ordering
compare :: KeyHash purpose -> KeyHash purpose -> Ordering
$c< :: forall purpose. KeyHash purpose -> KeyHash purpose -> Bool
< :: KeyHash purpose -> KeyHash purpose -> Bool
$c<= :: forall purpose. KeyHash purpose -> KeyHash purpose -> Bool
<= :: KeyHash purpose -> KeyHash purpose -> Bool
$c> :: forall purpose. KeyHash purpose -> KeyHash purpose -> Bool
> :: KeyHash purpose -> KeyHash purpose -> Bool
$c>= :: forall purpose. KeyHash purpose -> KeyHash purpose -> Bool
>= :: KeyHash purpose -> KeyHash purpose -> Bool
$cmax :: forall purpose.
KeyHash purpose -> KeyHash purpose -> KeyHash purpose
max :: KeyHash purpose -> KeyHash purpose -> KeyHash purpose
$cmin :: forall purpose.
KeyHash purpose -> KeyHash purpose -> KeyHash purpose
min :: KeyHash purpose -> KeyHash purpose -> KeyHash purpose
Ord, Int -> KeyHash purpose -> ShowS
[KeyHash purpose] -> ShowS
KeyHash purpose -> String
(Int -> KeyHash purpose -> ShowS)
-> (KeyHash purpose -> String)
-> ([KeyHash purpose] -> ShowS)
-> Show (KeyHash purpose)
forall purpose. Int -> KeyHash purpose -> ShowS
forall purpose. [KeyHash purpose] -> ShowS
forall purpose. KeyHash purpose -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: forall purpose. Int -> KeyHash purpose -> ShowS
showsPrec :: Int -> KeyHash purpose -> ShowS
$cshow :: forall purpose. KeyHash purpose -> String
show :: KeyHash purpose -> String
$cshowList :: forall purpose. [KeyHash purpose] -> ShowS
showList :: [KeyHash purpose] -> ShowS
Show)

-- | A 28-byte script hash, usable in any credential role.
newtype ScriptHash = ScriptHash ByteString deriving (ScriptHash -> ScriptHash -> Bool
(ScriptHash -> ScriptHash -> Bool)
-> (ScriptHash -> ScriptHash -> Bool) -> Eq ScriptHash
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ScriptHash -> ScriptHash -> Bool
== :: ScriptHash -> ScriptHash -> Bool
$c/= :: ScriptHash -> ScriptHash -> Bool
/= :: ScriptHash -> ScriptHash -> Bool
Eq, Eq ScriptHash
Eq ScriptHash =>
(ScriptHash -> ScriptHash -> Ordering)
-> (ScriptHash -> ScriptHash -> Bool)
-> (ScriptHash -> ScriptHash -> Bool)
-> (ScriptHash -> ScriptHash -> Bool)
-> (ScriptHash -> ScriptHash -> Bool)
-> (ScriptHash -> ScriptHash -> ScriptHash)
-> (ScriptHash -> ScriptHash -> ScriptHash)
-> Ord ScriptHash
ScriptHash -> ScriptHash -> Bool
ScriptHash -> ScriptHash -> Ordering
ScriptHash -> ScriptHash -> ScriptHash
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 :: ScriptHash -> ScriptHash -> Ordering
compare :: ScriptHash -> ScriptHash -> Ordering
$c< :: ScriptHash -> ScriptHash -> Bool
< :: ScriptHash -> ScriptHash -> Bool
$c<= :: ScriptHash -> ScriptHash -> Bool
<= :: ScriptHash -> ScriptHash -> Bool
$c> :: ScriptHash -> ScriptHash -> Bool
> :: ScriptHash -> ScriptHash -> Bool
$c>= :: ScriptHash -> ScriptHash -> Bool
>= :: ScriptHash -> ScriptHash -> Bool
$cmax :: ScriptHash -> ScriptHash -> ScriptHash
max :: ScriptHash -> ScriptHash -> ScriptHash
$cmin :: ScriptHash -> ScriptHash -> ScriptHash
min :: ScriptHash -> ScriptHash -> ScriptHash
Ord, Int -> ScriptHash -> ShowS
[ScriptHash] -> ShowS
ScriptHash -> String
(Int -> ScriptHash -> ShowS)
-> (ScriptHash -> String)
-> ([ScriptHash] -> ShowS)
-> Show ScriptHash
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ScriptHash -> ShowS
showsPrec :: Int -> ScriptHash -> ShowS
$cshow :: ScriptHash -> String
show :: ScriptHash -> String
$cshowList :: [ScriptHash] -> ShowS
showList :: [ScriptHash] -> ShowS
Show)

-- | A key or script controlling the role selected by the type parameter.
-- Ordering places key credentials before script credentials, then compares bytes.
type role Credential nominal

data Credential purpose
  = -- | Authority identified by a key hash in this role.
    KeyCredential !(KeyHash purpose)
  | -- | Authority identified by a script hash.
    ScriptCredential !ScriptHash
  deriving (Credential purpose -> Credential purpose -> Bool
(Credential purpose -> Credential purpose -> Bool)
-> (Credential purpose -> Credential purpose -> Bool)
-> Eq (Credential purpose)
forall purpose. Credential purpose -> Credential purpose -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: forall purpose. Credential purpose -> Credential purpose -> Bool
== :: Credential purpose -> Credential purpose -> Bool
$c/= :: forall purpose. Credential purpose -> Credential purpose -> Bool
/= :: Credential purpose -> Credential purpose -> Bool
Eq, Eq (Credential purpose)
Eq (Credential purpose) =>
(Credential purpose -> Credential purpose -> Ordering)
-> (Credential purpose -> Credential purpose -> Bool)
-> (Credential purpose -> Credential purpose -> Bool)
-> (Credential purpose -> Credential purpose -> Bool)
-> (Credential purpose -> Credential purpose -> Bool)
-> (Credential purpose -> Credential purpose -> Credential purpose)
-> (Credential purpose -> Credential purpose -> Credential purpose)
-> Ord (Credential purpose)
Credential purpose -> Credential purpose -> Bool
Credential purpose -> Credential purpose -> Ordering
Credential purpose -> Credential purpose -> Credential purpose
forall purpose. Eq (Credential purpose)
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
forall purpose. Credential purpose -> Credential purpose -> Bool
forall purpose.
Credential purpose -> Credential purpose -> Ordering
forall purpose.
Credential purpose -> Credential purpose -> Credential purpose
$ccompare :: forall purpose.
Credential purpose -> Credential purpose -> Ordering
compare :: Credential purpose -> Credential purpose -> Ordering
$c< :: forall purpose. Credential purpose -> Credential purpose -> Bool
< :: Credential purpose -> Credential purpose -> Bool
$c<= :: forall purpose. Credential purpose -> Credential purpose -> Bool
<= :: Credential purpose -> Credential purpose -> Bool
$c> :: forall purpose. Credential purpose -> Credential purpose -> Bool
> :: Credential purpose -> Credential purpose -> Bool
$c>= :: forall purpose. Credential purpose -> Credential purpose -> Bool
>= :: Credential purpose -> Credential purpose -> Bool
$cmax :: forall purpose.
Credential purpose -> Credential purpose -> Credential purpose
max :: Credential purpose -> Credential purpose -> Credential purpose
$cmin :: forall purpose.
Credential purpose -> Credential purpose -> Credential purpose
min :: Credential purpose -> Credential purpose -> Credential purpose
Ord, Int -> Credential purpose -> ShowS
[Credential purpose] -> ShowS
Credential purpose -> String
(Int -> Credential purpose -> ShowS)
-> (Credential purpose -> String)
-> ([Credential purpose] -> ShowS)
-> Show (Credential purpose)
forall purpose. Int -> Credential purpose -> ShowS
forall purpose. [Credential purpose] -> ShowS
forall purpose. Credential purpose -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: forall purpose. Int -> Credential purpose -> ShowS
showsPrec :: Int -> Credential purpose -> ShowS
$cshow :: forall purpose. Credential purpose -> String
show :: Credential purpose -> String
$cshowList :: forall purpose. [Credential purpose] -> ShowS
showList :: [Credential purpose] -> ShowS
Show)

-- DEFINITIONS ----------------------------------------------------------------

-- | Import a key hash without hashing. Any length except 28 returns
-- 'InvalidCredentialHashLength' with the actual byte count.
keyHashFromBytes :: ByteString -> Either Error (KeyHash purpose)
keyHashFromBytes :: forall purpose. ByteString -> Either Error (KeyHash purpose)
keyHashFromBytes ByteString
bytes = ByteString -> KeyHash purpose
forall purpose. ByteString -> KeyHash purpose
KeyHash (ByteString -> KeyHash purpose)
-> Either Error ByteString -> Either Error (KeyHash purpose)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either Error ByteString
validateHash ByteString
bytes

-- | Exact key-hash bytes.
keyHashBytes :: KeyHash purpose -> ByteString
keyHashBytes :: forall purpose. KeyHash purpose -> ByteString
keyHashBytes (KeyHash ByteString
bytes) = ByteString
bytes

-- | Import a script hash without hashing. Any length except 28 returns
-- 'InvalidCredentialHashLength' with the actual byte count.
scriptHashFromBytes :: ByteString -> Either Error ScriptHash
scriptHashFromBytes :: ByteString -> Either Error ScriptHash
scriptHashFromBytes ByteString
bytes = ByteString -> ScriptHash
ScriptHash (ByteString -> ScriptHash)
-> Either Error ByteString -> Either Error ScriptHash
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either Error ByteString
validateHash ByteString
bytes

-- | Exact script-hash bytes.
scriptHashBytes :: ScriptHash -> ByteString
scriptHashBytes :: ScriptHash -> ByteString
scriptHashBytes (ScriptHash ByteString
bytes) = ByteString
bytes

validateHash :: ByteString -> Either Error ByteString
validateHash :: ByteString -> Either Error ByteString
validateHash ByteString
bytes
  | ByteString -> Int
ByteString.length ByteString
bytes Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
28 = ByteString -> Either Error ByteString
forall a b. b -> Either a b
Right ByteString
bytes
  | Bool
otherwise = Error -> Either Error ByteString
forall a b. a -> Either a b
Left (Int -> Error
InvalidCredentialHashLength (ByteString -> Int
ByteString.length ByteString
bytes))

-- | Hash a verification key using BLAKE2b-224 and assign the requested role.
-- The caller selects the credential role through the result type. Native failures
-- return 'Cometa.Error.NativeError'; unexpected digest lengths return
-- 'Cometa.Error.NativeContractViolation'.
fromPublicKey :: PublicKey.PublicKey -> IO (Either Error (Credential purpose))
fromPublicKey :: forall purpose. PublicKey -> IO (Either Error (Credential purpose))
fromPublicKey PublicKey
publicKey = (Either Error Blake2bHash -> Either Error (Credential purpose))
-> IO (Either Error Blake2bHash)
-> IO (Either Error (Credential purpose))
forall a b. (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((Blake2bHash -> Credential purpose)
-> Either Error Blake2bHash -> Either Error (Credential purpose)
forall a b. (a -> b) -> Either Error a -> Either Error b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (KeyHash purpose -> Credential purpose
forall purpose. KeyHash purpose -> Credential purpose
KeyCredential (KeyHash purpose -> Credential purpose)
-> (Blake2bHash -> KeyHash purpose)
-> Blake2bHash
-> Credential purpose
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> KeyHash purpose
forall purpose. ByteString -> KeyHash purpose
KeyHash (ByteString -> KeyHash purpose)
-> (Blake2bHash -> ByteString) -> Blake2bHash -> KeyHash purpose
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Blake2bHash -> ByteString
Blake2b.toBytes)) (PublicKey -> IO (Either Error Blake2bHash)
PublicKey.hash PublicKey
publicKey)

-- | Encode the credential kind and 28-byte hash as a two-element CBOR array.
-- This produces a fresh definite-length encoding; it does not hash the value.
encodeCbor :: Credential purpose -> ByteString
encodeCbor :: forall purpose. Credential purpose -> ByteString
encodeCbor Credential purpose
credential =
  Encoding -> ByteString
W.toStrictByteString (Encoding -> ByteString) -> Encoding -> ByteString
forall a b. (a -> b) -> a -> b
$
    Word -> Encoding
E.encodeListLen Word
2 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> case Credential purpose
credential of
      KeyCredential KeyHash purpose
hash -> Word -> Encoding
E.encodeWord Word
0 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ByteString -> Encoding
E.encodeBytes (KeyHash purpose -> ByteString
forall purpose. KeyHash purpose -> ByteString
keyHashBytes KeyHash purpose
hash)
      ScriptCredential ScriptHash
hash -> Word -> Encoding
E.encodeWord Word
1 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ByteString -> Encoding
E.encodeBytes (ScriptHash -> ByteString
scriptHashBytes ScriptHash
hash)

-- | Decode exactly one credential array, checking its kind and hash length.
-- Definite and indefinite arrays and byte strings are accepted. Trailing data
-- and other shapes return 'InvalidCredentialCbor'; invalid hash lengths return
-- 'InvalidCredentialHashLength'. The result type selects the credential role.
decodeCbor :: ByteString -> Either Error (Credential purpose)
decodeCbor :: forall purpose. ByteString -> Either Error (Credential purpose)
decodeCbor ByteString
bytes = case (forall s. Decoder s Term)
-> ByteString -> Either DeserialiseFailure (ByteString, Term)
forall a.
(forall s. Decoder s a)
-> ByteString -> Either DeserialiseFailure (ByteString, a)
R.deserialiseFromBytes Decoder s Term
forall s. Decoder s Term
T.decodeTerm (ByteString -> ByteString
Lazy.fromStrict ByteString
bytes) of
  Left DeserialiseFailure
failure -> Error -> Either Error (Credential purpose)
forall a b. a -> Either a b
Left (Text -> Error
InvalidCredentialCbor (String -> Text
Text.pack (DeserialiseFailure -> String
forall a. Show a => a -> String
show DeserialiseFailure
failure)))
  Right (ByteString
rest, Term
term)
    | Bool -> Bool
not (ByteString -> Bool
Lazy.null ByteString
rest) -> Error -> Either Error (Credential purpose)
forall a b. a -> Either a b
Left (Text -> Error
InvalidCredentialCbor Text
"Trailing credential CBOR")
    | Bool
otherwise -> case Term
term of
        T.TList [Term]
values -> [Term] -> Either Error (Credential purpose)
forall {purpose}. [Term] -> Either Error (Credential purpose)
decodeFields [Term]
values
        T.TListI [Term]
values -> [Term] -> Either Error (Credential purpose)
forall {purpose}. [Term] -> Either Error (Credential purpose)
decodeFields [Term]
values
        Term
_ -> Error -> Either Error (Credential purpose)
forall a b. a -> Either a b
Left (Text -> Error
InvalidCredentialCbor Text
"Expected credential array")
  where
    decodeFields :: [Term] -> Either Error (Credential purpose)
decodeFields [T.TInt Int
kind, Term
hash] = case Term
hash of
      T.TBytes ByteString
value -> Int -> ByteString -> Either Error (Credential purpose)
forall {a} {purpose}.
(Eq a, Num a) =>
a -> ByteString -> Either Error (Credential purpose)
construct Int
kind ByteString
value
      T.TBytesI ByteString
value -> Int -> ByteString -> Either Error (Credential purpose)
forall {a} {purpose}.
(Eq a, Num a) =>
a -> ByteString -> Either Error (Credential purpose)
construct Int
kind (ByteString -> ByteString
Lazy.toStrict ByteString
value)
      Term
_ -> Error -> Either Error (Credential purpose)
forall a b. a -> Either a b
Left (Text -> Error
InvalidCredentialCbor Text
"Expected credential hash bytes")
    decodeFields [Term]
_ = Error -> Either Error (Credential purpose)
forall a b. a -> Either a b
Left (Text -> Error
InvalidCredentialCbor Text
"Expected credential kind and hash")
    construct :: a -> ByteString -> Either Error (Credential purpose)
construct a
0 ByteString
value = KeyHash purpose -> Credential purpose
forall purpose. KeyHash purpose -> Credential purpose
KeyCredential (KeyHash purpose -> Credential purpose)
-> Either Error (KeyHash purpose)
-> Either Error (Credential purpose)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either Error (KeyHash purpose)
forall purpose. ByteString -> Either Error (KeyHash purpose)
keyHashFromBytes ByteString
value
    construct a
1 ByteString
value = ScriptHash -> Credential purpose
forall purpose. ScriptHash -> Credential purpose
ScriptCredential (ScriptHash -> Credential purpose)
-> Either Error ScriptHash -> Either Error (Credential purpose)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either Error ScriptHash
scriptHashFromBytes ByteString
value
    construct a
_ ByteString
_ = Error -> Either Error (Credential purpose)
forall a b. a -> Either a b
Left (Text -> Error
InvalidCredentialCbor Text
"Unknown credential kind")