{-# LANGUAGE LambdaCase #-}

module PlutusLedgerApi.Common.Hash where

import PlutusCore.Crypto.Hash (blake2b_224)
import PlutusLedgerApi.Common.SerialisedScript
import PlutusLedgerApi.Common.Versions

import Data.ByteString qualified as B
import Data.ByteString.Base16 qualified as Base16
import Data.ByteString.Short qualified as Short
import Data.Word

hashScript :: PlutusLedgerLanguage -> SerialisedScript -> B.ByteString
hashScript :: PlutusLedgerLanguage -> SerialisedScript -> ByteString
hashScript PlutusLedgerLanguage
ll = PlutusLedgerLanguage -> ByteString -> ByteString
hashScriptB PlutusLedgerLanguage
ll (ByteString -> ByteString)
-> (SerialisedScript -> ByteString)
-> SerialisedScript
-> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SerialisedScript -> ByteString
Short.fromShort
{-# INLINEABLE hashScript #-}

hashScriptHex :: PlutusLedgerLanguage -> B.ByteString -> Either String B.ByteString
hashScriptHex :: PlutusLedgerLanguage -> ByteString -> Either String ByteString
hashScriptHex PlutusLedgerLanguage
ll ByteString
prg = PlutusLedgerLanguage -> ByteString -> ByteString
hashScriptB PlutusLedgerLanguage
ll (ByteString -> ByteString)
-> Either String ByteString -> Either String ByteString
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either String ByteString
Base16.decode ByteString
prg
{-# INLINEABLE hashScriptHex #-}

hashScriptB :: PlutusLedgerLanguage -> B.ByteString -> B.ByteString
hashScriptB :: PlutusLedgerLanguage -> ByteString -> ByteString
hashScriptB PlutusLedgerLanguage
ll ByteString
prg =
  ByteString -> ByteString
Base16.encode (ByteString -> ByteString) -> ByteString -> ByteString
forall a b. (a -> b) -> a -> b
$ ByteString -> ByteString
blake2b_224 (Word8 -> ByteString
B.singleton (PlutusLedgerLanguage -> Word8
plutusVersionTag PlutusLedgerLanguage
ll) ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
prg)
{-# INLINEABLE hashScriptB #-}

plutusVersionTag :: PlutusLedgerLanguage -> Word8
plutusVersionTag :: PlutusLedgerLanguage -> Word8
plutusVersionTag = \case
  PlutusLedgerLanguage
PlutusV1 -> Word8
0x1
  PlutusLedgerLanguage
PlutusV2 -> Word8
0x2
  PlutusLedgerLanguage
PlutusV3 -> Word8
0x3
{-# INLINEABLE plutusVersionTag #-}