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

-- | Ed25519 public keys as immutable 32-byte values. Import checks encoded
-- length; it does not establish that a key belongs to a particular person or
-- that a signature verifies. Use 'verify' to check a message and signature.
--
-- @
-- import qualified Cometa.Crypto.Ed25519.PublicKey as PublicKey
--
-- roundTrip :: PublicKey.PublicKey -> Bool
-- roundTrip value = PublicKey.fromBytes (PublicKey.toBytes value) == Right value
-- @
module Cometa.Crypto.Ed25519.PublicKey
  ( PublicKey,

    -- * Import
    fromBytes,
    fromHex,

    -- * Inspection
    toBytes,
    toHex,
    byteLength,
    hexLength,

    -- * Verification and hashing
    verify,
    hash,
  )
where

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

import qualified Cometa.Crypto.Blake2b as Blake2b
import Cometa.Crypto.Ed25519.Signature (Signature)
import qualified Cometa.Crypto.Ed25519.Signature as Signature
import Cometa.Error (Error (..))
import Cometa.Internal.Error (fromNativeFailure)
import qualified Cometa.Internal.FFI.Ed25519Values as Native
import qualified Cometa.Internal.FFI.Native as Status
import Cometa.Internal.Failure (NativeFailure (..))
import qualified Cometa.Internal.Hex as Hex
import Cometa.Internal.Ownership (copyHashResult, copyStaticText)
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import Data.Text (Text)
import Foreign.Marshal.Alloc (alloca)
import Foreign.Ptr (castPtr)
import Foreign.Storable (peek)

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

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

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

-- | Import exactly 32 bytes. Other lengths return 'InvalidEd25519PublicKeyLength'.
-- Only length is validated; this constructor does not check curve-point validity.
fromBytes :: ByteString -> Either Error PublicKey
fromBytes :: ByteString -> Either Error PublicKey
fromBytes ByteString
bytes
  | ByteString -> Int
ByteString.length ByteString
bytes Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
32 = Error -> Either Error PublicKey
forall a b. a -> Either a b
Left (Int -> Error
InvalidEd25519PublicKeyLength (ByteString -> Int
ByteString.length ByteString
bytes))
  | Bool
otherwise = PublicKey -> Either Error PublicKey
forall a b. b -> Either a b
Right (ByteString -> PublicKey
PublicKey ByteString
bytes)

-- | Import 64 ASCII hexadecimal digits, accepting either case. No whitespace
-- or prefix is accepted. Empty, odd-length or nonhexadecimal text returns
-- 'InvalidHex'; valid hex of another byte length returns 'InvalidEd25519PublicKeyLength'.
fromHex :: Text -> Either Error PublicKey
fromHex :: Text -> Either Error PublicKey
fromHex Text
text = do
  ByteString
bytes <- Either Error ByteString
-> (ByteString -> Either Error ByteString)
-> Maybe ByteString
-> Either Error ByteString
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Error -> Either Error ByteString
forall a b. a -> Either a b
Left Error
InvalidHex) ByteString -> Either Error ByteString
forall a b. b -> Either a b
Right (Text -> Maybe ByteString
Hex.decodeHex Text
text)
  if ByteString -> Bool
ByteString.null ByteString
bytes then Error -> Either Error PublicKey
forall a b. a -> Either a b
Left Error
InvalidHex else ByteString -> Either Error PublicKey
fromBytes ByteString
bytes

-- | Retrieve the exact encoded bytes.
toBytes :: PublicKey -> ByteString
toBytes :: PublicKey -> ByteString
toBytes (PublicKey ByteString
bytes) = ByteString
bytes

-- | Render lowercase ASCII hexadecimal digits without a prefix or whitespace.
toHex :: PublicKey -> Text
toHex :: PublicKey -> Text
toHex = ByteString -> Text
Hex.encodeHex (ByteString -> Text)
-> (PublicKey -> ByteString) -> PublicKey -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PublicKey -> ByteString
toBytes

-- | Encoded byte length, always 32.
byteLength :: PublicKey -> Int
byteLength :: PublicKey -> Int
byteLength = ByteString -> Int
ByteString.length (ByteString -> Int)
-> (PublicKey -> ByteString) -> PublicKey -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PublicKey -> ByteString
toBytes

-- | Hexadecimal digit count, always 64. No terminator is included.
hexLength :: PublicKey -> Int
hexLength :: PublicKey -> Int
hexLength PublicKey
value = Int
2 Int -> Int -> Int
forall a. Num a => a -> a -> a
* PublicKey -> Int
byteLength PublicKey
value

-- | Check an Ed25519 signature for the exact message bytes. Empty messages and
-- embedded NUL bytes are supported. 'Right' 'True' means verification succeeded;
-- 'Right' 'False' means it did not. Allocation or other operation failures return
-- 'NativeError'. This operation uses ordinary Ed25519 on the supplied message.
verify :: PublicKey -> ByteString -> Signature -> IO (Either Error Bool)
verify :: PublicKey -> ByteString -> Signature -> IO (Either Error Bool)
verify PublicKey
publicKey ByteString
message Signature
signature =
  ByteString
-> (CStringLen -> IO (Either Error Bool)) -> IO (Either Error Bool)
forall a. ByteString -> (CStringLen -> IO a) -> IO a
ByteString.useAsCStringLen (PublicKey -> ByteString
toBytes PublicKey
publicKey) ((CStringLen -> IO (Either Error Bool)) -> IO (Either Error Bool))
-> (CStringLen -> IO (Either Error Bool)) -> IO (Either Error Bool)
forall a b. (a -> b) -> a -> b
$ \(Ptr CChar
keyBytes, Int
keySize) ->
    ByteString
-> (CStringLen -> IO (Either Error Bool)) -> IO (Either Error Bool)
forall a. ByteString -> (CStringLen -> IO a) -> IO a
ByteString.useAsCStringLen (Signature -> ByteString
Signature.toBytes Signature
signature) ((CStringLen -> IO (Either Error Bool)) -> IO (Either Error Bool))
-> (CStringLen -> IO (Either Error Bool)) -> IO (Either Error Bool)
forall a b. (a -> b) -> a -> b
$ \(Ptr CChar
signatureBytes, Int
signatureSize) ->
      ByteString
-> (CStringLen -> IO (Either Error Bool)) -> IO (Either Error Bool)
forall a. ByteString -> (CStringLen -> IO a) -> IO a
ByteString.useAsCStringLen ByteString
message ((CStringLen -> IO (Either Error Bool)) -> IO (Either Error Bool))
-> (CStringLen -> IO (Either Error Bool)) -> IO (Either Error Bool)
forall a b. (a -> b) -> a -> b
$ \(Ptr CChar
messageBytes, Int
messageSize) ->
        (Ptr CInt -> IO (Either Error Bool)) -> IO (Either Error Bool)
forall a b. Storable a => (Ptr a -> IO b) -> IO b
alloca ((Ptr CInt -> IO (Either Error Bool)) -> IO (Either Error Bool))
-> (Ptr CInt -> IO (Either Error Bool)) -> IO (Either Error Bool)
forall a b. (a -> b) -> a -> b
$ \Ptr CInt
verified -> do
          NativeCode
code <- Ptr Word8
-> CSize
-> Ptr Word8
-> CSize
-> Ptr Word8
-> CSize
-> Ptr CInt
-> IO NativeCode
Native.cVerify (Ptr CChar -> Ptr Word8
forall a b. Ptr a -> Ptr b
castPtr Ptr CChar
keyBytes) (Int -> CSize
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
keySize) (Ptr CChar -> Ptr Word8
forall a b. Ptr a -> Ptr b
castPtr Ptr CChar
signatureBytes) (Int -> CSize
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
signatureSize) (Ptr CChar -> Ptr Word8
forall a b. Ptr a -> Ptr b
castPtr Ptr CChar
messageBytes) (Int -> CSize
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
messageSize) Ptr CInt
verified
          if NativeCode
code NativeCode -> NativeCode -> Bool
forall a. Eq a => a -> a -> Bool
== NativeCode
Status.success
            then Bool -> Either Error Bool
forall a b. b -> Either a b
Right (Bool -> Either Error Bool)
-> (CInt -> Bool) -> CInt -> Either Error Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (CInt -> CInt -> Bool
forall a. Eq a => a -> a -> Bool
/= CInt
0) (CInt -> Either Error Bool) -> IO CInt -> IO (Either Error Bool)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Ptr CInt -> IO CInt
forall a. Storable a => Ptr a -> IO a
peek Ptr CInt
verified
            else do
              Text
diagnostic <- NativeCode -> IO (Ptr CChar)
Status.cErrorMessage NativeCode
code IO (Ptr CChar) -> (Ptr CChar -> IO Text) -> IO Text
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Ptr CChar -> IO Text
copyStaticText
              Either Error Bool -> IO (Either Error Bool)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error Bool
forall a b. a -> Either a b
Left (NativeFailure -> Error
fromNativeFailure (Text -> Integer -> Text -> NativeFailure
NativeFailure Text
"ed25519.publicKey.verify" (NativeCode -> Integer
forall a. Integral a => a -> Integer
toInteger NativeCode
code) Text
diagnostic)))

-- | Compute the 28-byte BLAKE2b-224 digest of the encoded public key. The result
-- is a general digest, without a payment/stake role distinction. Operation
-- failures return 'NativeError'.
hash :: PublicKey -> IO (Either Error Blake2b.Blake2bHash)
hash :: PublicKey -> IO (Either Error Blake2bHash)
hash PublicKey
publicKey =
  ByteString
-> (CStringLen -> IO (Either Error Blake2bHash))
-> IO (Either Error Blake2bHash)
forall a. ByteString -> (CStringLen -> IO a) -> IO a
ByteString.useAsCStringLen (PublicKey -> ByteString
toBytes PublicKey
publicKey) ((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) -> do
    Either NativeFailure ByteString
result <- Text
-> (Ptr (Ptr NativeHash) -> IO NativeCode)
-> IO (Either NativeFailure ByteString)
copyHashResult Text
"ed25519.publicKey.hash" (Ptr Word8 -> CSize -> Ptr (Ptr NativeHash) -> IO NativeCode
Native.cPublicKeyHash (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))
    Either Error Blake2bHash -> IO (Either Error Blake2bHash)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error Blake2bHash -> IO (Either Error Blake2bHash))
-> Either Error Blake2bHash -> IO (Either Error Blake2bHash)
forall a b. (a -> b) -> a -> b
$ case Either NativeFailure ByteString
result of
      Left NativeFailure
failure -> Error -> Either Error Blake2bHash
forall a b. a -> Either a b
Left (NativeFailure -> Error
fromNativeFailure NativeFailure
failure)
      Right ByteString
bytes
        | ByteString -> Int
ByteString.length ByteString
bytes Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
28 -> Error -> Either Error Blake2bHash
forall a b. a -> Either a b
Left (Text -> Error
NativeContractViolation Text
"ed25519.publicKey.hash")
        | Bool
otherwise -> ByteString -> Either Error Blake2bHash
Blake2b.fromBytes ByteString
bytes