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

-- | Cardano Ed25519-BIP32 public keys: a 32-byte verification key followed by a
-- 32-byte chain code. These are not secp256k1 Bitcoin BIP32 keys. Import validates
-- length only; an invalid curve point can fail later derivation.
--
-- @
-- import qualified Cometa.Crypto.Bip32.PublicKey as PublicKey
--
-- roundTrip key = PublicKey.fromBytes (PublicKey.toBytes key) == Right key
-- @
module Cometa.Crypto.Bip32.PublicKey
  ( PublicKey,

    -- * Import and serialization
    fromBytes,
    fromHex,
    toBytes,
    toHex,
    byteLength,
    hexLength,

    -- * Derivation and conversion
    derive,
    toEd25519,
    hash,
  )
where

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

import qualified Cometa.Crypto.Blake2b as Blake2b
import qualified Cometa.Crypto.Ed25519.PublicKey as Ed25519
import Cometa.Error (Error (..))
import Cometa.Internal.Error (fromNativeFailure)
import qualified Cometa.Internal.FFI.Bip32 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 (copyStaticText)
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import Data.Text (Text)
import Data.Word (Word32)
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Marshal.Array (withArrayLen)
import Foreign.Ptr (castPtr)

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

-- | Immutable 64-byte public key and chain code. Equality compares exact bytes;
-- ordering is lexicographic. 'Show' is diagnostic; 'toHex' is stable serialization.
data PublicKey = PublicKey !Ed25519.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 64 bytes; other lengths return 'InvalidBip32PublicKeyLength'.
-- Curve-point validity is not checked.
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
64 = Error -> Either Error PublicKey
forall a b. a -> Either a b
Left (Int -> Error
InvalidBip32PublicKeyLength (ByteString -> Int
ByteString.length ByteString
bytes))
  | Bool
otherwise = do
      PublicKey
key <- ByteString -> Either Error PublicKey
Ed25519.fromBytes (Int -> ByteString -> ByteString
ByteString.take Int
32 ByteString
bytes)
      PublicKey -> Either Error PublicKey
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (PublicKey -> ByteString -> PublicKey
PublicKey PublicKey
key (Int -> ByteString -> ByteString
ByteString.drop Int
32 ByteString
bytes))

-- | Import 128 ASCII hex digits in either case, without prefix or whitespace.
-- Empty or malformed text returns 'InvalidHex'; a well-formed wrong length returns
-- 'InvalidBip32PublicKeyLength'.
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 all 64 bytes, including the chain code.
toBytes :: PublicKey -> ByteString
toBytes :: PublicKey -> ByteString
toBytes (PublicKey PublicKey
key ByteString
chainCode) = PublicKey -> ByteString
Ed25519.toBytes PublicKey
key ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
chainCode

-- | Render 128 lowercase ASCII hexadecimal digits without 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 length, always 64 bytes.
byteLength :: PublicKey -> Int
byteLength :: PublicKey -> Int
byteLength PublicKey
_ = Int
64

-- | Hexadecimal digit count, always 128, excluding a terminator.
hexLength :: PublicKey -> Int
hexLength :: PublicKey -> Int
hexLength PublicKey
key = Int
2 Int -> Int -> Int
forall a. Num a => a -> a -> a
* PublicKey -> Int
byteLength PublicKey
key

-- | Derive a path in order. Each encoded index must be in @0..2^31-1@;
-- any high-bit (hardened) index returns 'HardenedPublicDerivation' before native
-- work. An empty path returns the original value. Native derivation failures
-- return 'NativeError'. The source is unchanged.
derive :: PublicKey -> [Word32] -> IO (Either Error PublicKey)
derive :: PublicKey -> [Word32] -> IO (Either Error PublicKey)
derive PublicKey
key [Word32]
path
  | Just Word32
index <- [Word32] -> Maybe Word32
forall {a}. (Ord a, Num a) => [a] -> Maybe a
firstHardened [Word32]
path = Either Error PublicKey -> IO (Either Error PublicKey)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error PublicKey
forall a b. a -> Either a b
Left (Word32 -> Error
HardenedPublicDerivation Word32
index))
  | [Word32] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Word32]
path = Either Error PublicKey -> IO (Either Error PublicKey)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (PublicKey -> Either Error PublicKey
forall a b. b -> Either a b
Right PublicKey
key)
  | Bool
otherwise = ByteString
-> (CString -> IO (Either Error PublicKey))
-> IO (Either Error PublicKey)
forall a. ByteString -> (CString -> IO a) -> IO a
ByteString.useAsCString (PublicKey -> ByteString
toBytes PublicKey
key) ((CString -> IO (Either Error PublicKey))
 -> IO (Either Error PublicKey))
-> (CString -> IO (Either Error PublicKey))
-> IO (Either Error PublicKey)
forall a b. (a -> b) -> a -> b
$ \CString
bytes ->
      [Word32]
-> (Int -> Ptr Word32 -> IO (Either Error PublicKey))
-> IO (Either Error PublicKey)
forall a b. Storable a => [a] -> (Int -> Ptr a -> IO b) -> IO b
withArrayLen [Word32]
path ((Int -> Ptr Word32 -> IO (Either Error PublicKey))
 -> IO (Either Error PublicKey))
-> (Int -> Ptr Word32 -> IO (Either Error PublicKey))
-> IO (Either Error PublicKey)
forall a b. (a -> b) -> a -> b
$ \Int
size Ptr Word32
indices -> Int
-> (Ptr Word8 -> IO (Either Error PublicKey))
-> IO (Either Error PublicKey)
forall a b. Int -> (Ptr a -> IO b) -> IO b
allocaBytes Int
64 ((Ptr Word8 -> IO (Either Error PublicKey))
 -> IO (Either Error PublicKey))
-> (Ptr Word8 -> IO (Either Error PublicKey))
-> IO (Either Error PublicKey)
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
output -> do
        NativeCode
code <- Ptr Word8 -> Ptr Word32 -> CSize -> Ptr Word8 -> IO NativeCode
Native.cDerivePublic (CString -> Ptr Word8
forall a b. Ptr a -> Ptr b
castPtr CString
bytes) Ptr Word32
indices (Int -> CSize
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
size) Ptr Word8
output
        if NativeCode
code NativeCode -> NativeCode -> Bool
forall a. Eq a => a -> a -> Bool
== NativeCode
Status.success
          then ByteString -> Either Error PublicKey
fromBytes (ByteString -> Either Error PublicKey)
-> IO ByteString -> IO (Either Error PublicKey)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> CStringLen -> IO ByteString
ByteString.packCStringLen (Ptr Word8 -> CString
forall a b. Ptr a -> Ptr b
castPtr Ptr Word8
output, Int
64)
          else do
            Text
message <- NativeCode -> IO CString
Status.cErrorMessage NativeCode
code IO CString -> (CString -> 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
>>= CString -> IO Text
copyStaticText
            Either Error PublicKey -> IO (Either Error PublicKey)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error PublicKey
forall a b. a -> Either a b
Left (NativeFailure -> Error
fromNativeFailure (Text -> Integer -> Text -> NativeFailure
NativeFailure Text
"bip32.publicKey.derive" (NativeCode -> Integer
forall a. Integral a => a -> Integer
toInteger NativeCode
code) Text
message)))
  where
    firstHardened :: [a] -> Maybe a
firstHardened [] = Maybe a
forall a. Maybe a
Nothing
    firstHardened (a
index : [a]
rest)
      | a
index a -> a -> Bool
forall a. Ord a => a -> a -> Bool
>= a
0x80000000 = a -> Maybe a
forall a. a -> Maybe a
Just a
index
      | Bool
otherwise = [a] -> Maybe a
firstHardened [a]
rest

-- | Discard the chain code and return the first 32 bytes as an Ed25519 public
-- key. This does not validate curve membership or identity.
toEd25519 :: PublicKey -> Ed25519.PublicKey
toEd25519 :: PublicKey -> PublicKey
toEd25519 (PublicKey PublicKey
key ByteString
_) = PublicKey
key

-- | Compute BLAKE2b-224 over all 64 bytes, including the chain code, matching
-- the BIP32 public-key hash operation. For a payment/stake verification-key digest,
-- convert with 'toEd25519' and use 'Ed25519.hash' instead. Failures return 'NativeError'.
hash :: PublicKey -> IO (Either Error Blake2b.Blake2bHash)
hash :: PublicKey -> IO (Either Error Blake2bHash)
hash = Int -> ByteString -> IO (Either Error Blake2bHash)
Blake2b.compute Int
28 (ByteString -> IO (Either Error Blake2bHash))
-> (PublicKey -> ByteString)
-> PublicKey
-> IO (Either Error Blake2bHash)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PublicKey -> ByteString
toBytes