{-# LANGUAGE KindSignatures    #-}
{-# LANGUAGE OverloadedStrings #-}

module PlutusCore.Crypto.Utils (failWithMessage, byteStringAsHex) where

import PlutusCore.Builtin.Result (BuiltinResult, emit)
import PlutusCore.Evaluation.Result (evaluationFailure)

import Data.ByteString (ByteString, foldr')
import Data.Kind (Type)
import Data.Text (Text)
import Text.Printf (printf)

failWithMessage :: forall (a :: Type). Text -> Text -> BuiltinResult a
failWithMessage :: forall a. Text -> Text -> BuiltinResult a
failWithMessage Text
location Text
reason = do
  Text -> BuiltinResult ()
emit (Text -> BuiltinResult ()) -> Text -> BuiltinResult ()
forall a b. (a -> b) -> a -> b
$ Text
location Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
reason
  BuiltinResult a
forall err. AsEvaluationFailure err => err
evaluationFailure

byteStringAsHex :: ByteString -> String
byteStringAsHex :: ByteString -> [Char]
byteStringAsHex ByteString
bs = [Char]
"0x" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ ([[Char]] -> [Char]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
Prelude.concat ([[Char]] -> [Char]) -> [[Char]] -> [Char]
forall a b. (a -> b) -> a -> b
$ (Word8 -> [[Char]] -> [[Char]])
-> [[Char]] -> ByteString -> [[Char]]
forall a. (Word8 -> a -> a) -> a -> ByteString -> a
foldr' (\Word8
w [[Char]]
s -> ([Char] -> Word8 -> [Char]
forall r. PrintfType r => [Char] -> r
printf [Char]
"%02x" Word8
w)[Char] -> [[Char]] -> [[Char]]
forall a. a -> [a] -> [a]
:[[Char]]
s) [] ByteString
bs)