-- 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 OverloadedStrings #-}

-- | BLAKE2b digests as immutable byte sequences. This general digest type does
-- not distinguish payment, stake, or script hashes.
--
-- @
-- import qualified Cometa.Crypto.Blake2b as Blake2b
-- import qualified Data.ByteString.Char8 as ByteString
--
-- main :: IO ()
-- main = do
--   result <- Blake2b.compute 32 (ByteString.pack "abc")
--   print (Blake2b.toHex <$> result)
-- @
module Cometa.Crypto.Blake2b
  ( Blake2bHash,

    -- * Hashing
    compute,

    -- * Importing digests
    fromBytes,
    fromHex,

    -- * Inspection
    toBytes,
    toHex,

    -- * CBOR
    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 Cometa.Error (Error (..))
import Cometa.Internal.Error (fromNativeFailure)
import qualified Cometa.Internal.FFI.Native as Native
import Cometa.Internal.Ownership (copyHashResult)
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Lazy as Lazy
import Data.Char (isDigit)
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Word (Word8)
import Foreign.Ptr (castPtr)

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

-- | A nonempty digest byte sequence. Equality compares bytes; ordering is
-- lexicographic byte ordering.
-- 'Show' is diagnostic; use 'toHex' for a stable textual encoding.
newtype Blake2bHash = Blake2bHash ByteString
  deriving (Blake2bHash -> Blake2bHash -> Bool
(Blake2bHash -> Blake2bHash -> Bool)
-> (Blake2bHash -> Blake2bHash -> Bool) -> Eq Blake2bHash
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Blake2bHash -> Blake2bHash -> Bool
== :: Blake2bHash -> Blake2bHash -> Bool
$c/= :: Blake2bHash -> Blake2bHash -> Bool
/= :: Blake2bHash -> Blake2bHash -> Bool
Eq, Eq Blake2bHash
Eq Blake2bHash =>
(Blake2bHash -> Blake2bHash -> Ordering)
-> (Blake2bHash -> Blake2bHash -> Bool)
-> (Blake2bHash -> Blake2bHash -> Bool)
-> (Blake2bHash -> Blake2bHash -> Bool)
-> (Blake2bHash -> Blake2bHash -> Bool)
-> (Blake2bHash -> Blake2bHash -> Blake2bHash)
-> (Blake2bHash -> Blake2bHash -> Blake2bHash)
-> Ord Blake2bHash
Blake2bHash -> Blake2bHash -> Bool
Blake2bHash -> Blake2bHash -> Ordering
Blake2bHash -> Blake2bHash -> Blake2bHash
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 :: Blake2bHash -> Blake2bHash -> Ordering
compare :: Blake2bHash -> Blake2bHash -> Ordering
$c< :: Blake2bHash -> Blake2bHash -> Bool
< :: Blake2bHash -> Blake2bHash -> Bool
$c<= :: Blake2bHash -> Blake2bHash -> Bool
<= :: Blake2bHash -> Blake2bHash -> Bool
$c> :: Blake2bHash -> Blake2bHash -> Bool
> :: Blake2bHash -> Blake2bHash -> Bool
$c>= :: Blake2bHash -> Blake2bHash -> Bool
>= :: Blake2bHash -> Blake2bHash -> Bool
$cmax :: Blake2bHash -> Blake2bHash -> Blake2bHash
max :: Blake2bHash -> Blake2bHash -> Blake2bHash
$cmin :: Blake2bHash -> Blake2bHash -> Blake2bHash
min :: Blake2bHash -> Blake2bHash -> Blake2bHash
Ord, Int -> Blake2bHash -> ShowS
[Blake2bHash] -> ShowS
Blake2bHash -> String
(Int -> Blake2bHash -> ShowS)
-> (Blake2bHash -> String)
-> ([Blake2bHash] -> ShowS)
-> Show Blake2bHash
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Blake2bHash -> ShowS
showsPrec :: Int -> Blake2bHash -> ShowS
$cshow :: Blake2bHash -> String
show :: Blake2bHash -> String
$cshowList :: [Blake2bHash] -> ShowS
showList :: [Blake2bHash] -> ShowS
Show)

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

-- | Compute an unkeyed digest with an output length of 16 through 64 bytes.
-- Invalid output lengths return 'InvalidHashLength'. Empty messages are currently
-- unsupported and return 'NativeError' with code @OutOfBoundsMemoryRead@.
-- Other cardano-c failures also return 'NativeError'.
compute ::
  -- | Digest length in bytes, from 16 through 64 inclusive.
  Int ->
  -- | Nonempty message to hash.
  ByteString ->
  -- | Digest with the requested length, or a validation or operation failure.
  IO (Either Error Blake2bHash)
compute :: Int -> ByteString -> IO (Either Error Blake2bHash)
compute Int
hashLength ByteString
bytes
  | Int
hashLength Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
16 Bool -> Bool -> Bool
|| Int
hashLength Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
64 = Either Error Blake2bHash -> IO (Either Error Blake2bHash)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error Blake2bHash
forall a b. a -> Either a b
Left (Int -> Error
InvalidHashLength Int
hashLength))
  | Bool
otherwise =
      ByteString
-> (CStringLen -> IO (Either Error Blake2bHash))
-> IO (Either Error Blake2bHash)
forall a. ByteString -> (CStringLen -> IO a) -> IO a
ByteString.useAsCStringLen ByteString
bytes ((CStringLen -> IO (Either Error Blake2bHash))
 -> IO (Either Error Blake2bHash))
-> (CStringLen -> IO (Either Error Blake2bHash))
-> IO (Either Error Blake2bHash)
forall a b. (a -> b) -> a -> b
$ \(Ptr CChar
input, Int
size) ->
        (NativeFailure -> Either Error Blake2bHash)
-> (ByteString -> Either Error Blake2bHash)
-> Either NativeFailure ByteString
-> Either Error Blake2bHash
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Error -> Either Error Blake2bHash
forall a b. a -> Either a b
Left (Error -> Either Error Blake2bHash)
-> (NativeFailure -> Error)
-> NativeFailure
-> Either Error Blake2bHash
forall b c a. (b -> c) -> (a -> b) -> a -> c
. NativeFailure -> Error
fromNativeFailure) (Blake2bHash -> Either Error Blake2bHash
forall a b. b -> Either a b
Right (Blake2bHash -> Either Error Blake2bHash)
-> (ByteString -> Blake2bHash)
-> ByteString
-> Either Error Blake2bHash
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Blake2bHash
Blake2bHash)
          (Either NativeFailure ByteString -> Either Error Blake2bHash)
-> IO (Either NativeFailure ByteString)
-> IO (Either Error Blake2bHash)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Text
-> (Ptr (Ptr NativeHash) -> IO NativeCode)
-> IO (Either NativeFailure ByteString)
copyHashResult Text
"blake2b.compute" (Ptr Word8
-> CSize -> CSize -> Ptr (Ptr NativeHash) -> IO NativeCode
Native.cCompute (Ptr CChar -> Ptr Word8
forall a b. Ptr a -> Ptr b
castPtr Ptr CChar
input) (Int -> CSize
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
size) (Int -> CSize
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
hashLength))

-- | Import digest bytes without hashing them. Any nonempty length is accepted;
-- this operation does not assert a particular digest role or algorithm variant.
-- Empty input returns 'EmptyHash'.
fromBytes :: ByteString -> Either Error Blake2bHash
fromBytes :: ByteString -> Either Error Blake2bHash
fromBytes ByteString
bytes
  | ByteString -> Bool
ByteString.null ByteString
bytes = Error -> Either Error Blake2bHash
forall a b. a -> Either a b
Left Error
EmptyHash
  | Bool
otherwise = Blake2bHash -> Either Error Blake2bHash
forall a b. b -> Either a b
Right (ByteString -> Blake2bHash
Blake2bHash ByteString
bytes)

-- | Import nonempty, even-length ASCII hexadecimal text, accepting both cases.
-- Malformed text returns 'InvalidHex'. No whitespace or prefix is accepted.
fromHex :: Text -> Either Error Blake2bHash
fromHex :: Text -> Either Error Blake2bHash
fromHex Text
text =
  case String -> Maybe [Word8]
decodeHex (Text -> String
Text.unpack Text
text) of
    Maybe [Word8]
Nothing -> Error -> Either Error Blake2bHash
forall a b. a -> Either a b
Left Error
InvalidHex
    Just [] -> Error -> Either Error Blake2bHash
forall a b. a -> Either a b
Left Error
InvalidHex
    Just [Word8]
bytes -> ByteString -> Either Error Blake2bHash
fromBytes ([Word8] -> ByteString
ByteString.pack [Word8]
bytes)

-- | Observe the immutable digest bytes.
toBytes :: Blake2bHash -> ByteString
toBytes :: Blake2bHash -> ByteString
toBytes (Blake2bHash ByteString
bytes) = ByteString
bytes

-- | Encode the digest as lowercase ASCII hex, without a prefix or whitespace.
toHex :: Blake2bHash -> Text
toHex :: Blake2bHash -> Text
toHex = String -> Text
Text.pack (String -> Text) -> (Blake2bHash -> String) -> Blake2bHash -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Word8 -> String) -> [Word8] -> String
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Word8 -> String
forall {a} {a}. (Integral a, Enum a) => a -> [a]
encodeByte ([Word8] -> String)
-> (Blake2bHash -> [Word8]) -> Blake2bHash -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> [Word8]
ByteString.unpack (ByteString -> [Word8])
-> (Blake2bHash -> ByteString) -> Blake2bHash -> [Word8]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Blake2bHash -> ByteString
toBytes
  where
    encodeByte :: a -> [a]
encodeByte a
byte = [a -> a
forall {a} {a}. (Integral a, Enum a) => a -> a
digit (a
byte a -> a -> a
forall a. Integral a => a -> a -> a
`div` a
16), a -> a
forall {a} {a}. (Integral a, Enum a) => a -> a
digit (a
byte a -> a -> a
forall a. Integral a => a -> a -> a
`mod` a
16)]
    digit :: a -> a
digit a
value
      | a
value a -> a -> Bool
forall a. Ord a => a -> a -> Bool
< a
10 = Int -> a
forall a. Enum a => Int -> a
toEnum (a -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral a
value Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Char -> Int
forall a. Enum a => a -> Int
fromEnum Char
'0')
      | Bool
otherwise = Int -> a
forall a. Enum a => Int -> a
toEnum (a -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral a
value Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
10 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Char -> Int
forall a. Enum a => a -> Int
fromEnum Char
'a')

-- | Total hexadecimal decoder: no unchecked indexing or partial digit conversion.
decodeHex :: String -> Maybe [Word8]
decodeHex :: String -> Maybe [Word8]
decodeHex [] = [Word8] -> Maybe [Word8]
forall a. a -> Maybe a
Just []
decodeHex (Char
high : Char
low : String
rest) = do
  Word8
highValue <- Char -> Maybe Word8
hexDigit Char
high
  Word8
lowValue <- Char -> Maybe Word8
hexDigit Char
low
  [Word8]
remaining <- String -> Maybe [Word8]
decodeHex String
rest
  [Word8] -> Maybe [Word8]
forall a. a -> Maybe a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((Word8
highValue Word8 -> Word8 -> Word8
forall a. Num a => a -> a -> a
* Word8
16 Word8 -> Word8 -> Word8
forall a. Num a => a -> a -> a
+ Word8
lowValue) Word8 -> [Word8] -> [Word8]
forall a. a -> [a] -> [a]
: [Word8]
remaining)
decodeHex [Char
_] = Maybe [Word8]
forall a. Maybe a
Nothing

hexDigit :: Char -> Maybe Word8
hexDigit :: Char -> Maybe Word8
hexDigit Char
character
  | Char -> Bool
isDigit Char
character = Word8 -> Maybe Word8
forall a. a -> Maybe a
Just (Char -> Word8
forall {b} {a}. (Num b, Enum a) => a -> b
offset Char
'0')
  | Char
character Char -> Char -> Bool
forall a. Ord a => a -> a -> Bool
>= Char
'a' Bool -> Bool -> Bool
&& Char
character Char -> Char -> Bool
forall a. Ord a => a -> a -> Bool
<= Char
'f' = Word8 -> Maybe Word8
forall a. a -> Maybe a
Just (Word8
10 Word8 -> Word8 -> Word8
forall a. Num a => a -> a -> a
+ Char -> Word8
forall {b} {a}. (Num b, Enum a) => a -> b
offset Char
'a')
  | Char
character Char -> Char -> Bool
forall a. Ord a => a -> a -> Bool
>= Char
'A' Bool -> Bool -> Bool
&& Char
character Char -> Char -> Bool
forall a. Ord a => a -> a -> Bool
<= Char
'F' = Word8 -> Maybe Word8
forall a. a -> Maybe a
Just (Word8
10 Word8 -> Word8 -> Word8
forall a. Num a => a -> a -> a
+ Char -> Word8
forall {b} {a}. (Num b, Enum a) => a -> b
offset Char
'A')
  | Bool
otherwise = Maybe Word8
forall a. Maybe a
Nothing
  where
    offset :: a -> b
offset a
start = Int -> b
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Char -> Int
forall a. Enum a => a -> Int
fromEnum Char
character Int -> Int -> Int
forall a. Num a => a -> a -> a
- a -> Int
forall a. Enum a => a -> Int
fromEnum a
start)

-- | Encode the digest as one definite-length CBOR byte string.
encodeCbor :: Blake2bHash -> ByteString
encodeCbor :: Blake2bHash -> ByteString
encodeCbor = Encoding -> ByteString
W.toStrictByteString (Encoding -> ByteString)
-> (Blake2bHash -> Encoding) -> Blake2bHash -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Encoding
E.encodeBytes (ByteString -> Encoding)
-> (Blake2bHash -> ByteString) -> Blake2bHash -> Encoding
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Blake2bHash -> ByteString
toBytes

-- | Import exactly one nonempty CBOR byte string without hashing it. Definite
-- and indefinite byte strings are accepted; invalid CBOR, other types and
-- trailing data return 'InvalidHashCbor'. Empty bytes return 'EmptyHash'.
decodeCbor :: ByteString -> Either Error Blake2bHash
decodeCbor :: ByteString -> Either Error Blake2bHash
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 Blake2bHash
forall a b. a -> Either a b
Left (Text -> Error
InvalidHashCbor (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 Blake2bHash
forall a b. a -> Either a b
Left (Text -> Error
InvalidHashCbor Text
"Trailing digest CBOR")
    | Bool
otherwise -> case Term
term of
        T.TBytes ByteString
value -> ByteString -> Either Error Blake2bHash
fromBytes ByteString
value
        T.TBytesI ByteString
value -> ByteString -> Either Error Blake2bHash
fromBytes (ByteString -> ByteString
Lazy.toStrict ByteString
value)
        Term
_ -> Error -> Either Error Blake2bHash
forall a b. a -> Either a b
Left (Text -> Error
InvalidHashCbor Text
"Expected digest byte string")