-- 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.

-- | Scoped Ed25519 signing keys. Normal keys contain a 32-byte seed; extended
-- keys contain a 64-byte expanded scalar and nonce prefix, rather than a seed/public-key
-- pair. Keys have no printable or equality representation.
--
-- The continuation receives a key valid until its scope exits. Keeping the
-- handle afterward is possible, but all subsequent operations return
-- 'SigningKeyClosed'. Scope exit and 'close' wait for ongoing operations.
-- Callback exceptions, including cancellation, propagate after cleanup.
--
-- Closing a key ends access through its handle. It does not erase the input
-- bytes or text supplied by the application, or any explicitly exported copies.
--
-- @
-- import qualified Cometa.Crypto.Ed25519.SigningKey as SigningKey
--
-- -- seed must contain exactly 32 bytes obtained from the application.
-- signMessage seed message =
--   SigningKey.withNormalKey seed $ \key -> SigningKey.sign key message
-- @
module Cometa.Crypto.Ed25519.SigningKey
  ( SigningKey,

    -- * Scoped import and copying
    withNormalKey,
    withExtendedKey,
    withNormalKeyHex,
    withExtendedKeyHex,
    withClone,
    close,

    -- * Inspection and signing
    byteLength,
    hexLength,
    publicKey,
    sign,

    -- * Explicit secret export
    exportBytes,
    exportHex,
  )
where

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

import Cometa.Crypto.Ed25519.PublicKey (PublicKey)
import qualified Cometa.Crypto.Ed25519.PublicKey as PublicKey
import Cometa.Crypto.Ed25519.Signature (Signature)
import qualified Cometa.Crypto.Ed25519.Signature as Signature
import Cometa.Error (Error (..))
import Cometa.Internal.Ed25519SigningKey (SigningKey (..))
import Cometa.Internal.Error (fromNativeFailure)
import qualified Cometa.Internal.Hex as Hex
import qualified Cometa.Internal.SigningKey as Internal
import Control.Monad (join)
import Data.ByteString (ByteString)
import Data.Text (Text)

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

-- | Import exactly 32 seed bytes and run the continuation. Invalid length returns
-- 'InvalidEd25519SigningKeyLength' with expected then actual byte counts, without
-- invoking the continuation. Its expected failures are returned directly.
-- Imported bytes remain in application memory after the scoped key closes.
withNormalKey :: ByteString -> (SigningKey -> IO (Either Error value)) -> IO (Either Error value)
withNormalKey :: forall value.
ByteString
-> (SigningKey -> IO (Either Error value))
-> IO (Either Error value)
withNormalKey ByteString
bytes SigningKey -> IO (Either Error value)
action = Either Failure (Either Error value) -> Either Error value
forall value.
Either Failure (Either Error value) -> Either Error value
flatten (Either Failure (Either Error value) -> Either Error value)
-> IO (Either Failure (Either Error value))
-> IO (Either Error value)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString
-> (Key -> IO (Either Error value))
-> IO (Either Failure (Either Error value))
forall value.
ByteString -> (Key -> IO value) -> IO (Either Failure value)
Internal.withNormalKey ByteString
bytes (SigningKey -> IO (Either Error value)
action (SigningKey -> IO (Either Error value))
-> (Key -> SigningKey) -> Key -> IO (Either Error value)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Key -> SigningKey
SigningKey)

-- | Import exactly 64 expanded scalar and nonce-prefix bytes and run the continuation. This is
-- the Cardano extended format, not a normal seed followed by a public key.
-- Length is validated; an unusable scalar can fail later derivation or signing.
-- Failure and cleanup behavior matches 'withNormalKey'.
withExtendedKey :: ByteString -> (SigningKey -> IO (Either Error value)) -> IO (Either Error value)
withExtendedKey :: forall value.
ByteString
-> (SigningKey -> IO (Either Error value))
-> IO (Either Error value)
withExtendedKey ByteString
bytes SigningKey -> IO (Either Error value)
action = Either Failure (Either Error value) -> Either Error value
forall value.
Either Failure (Either Error value) -> Either Error value
flatten (Either Failure (Either Error value) -> Either Error value)
-> IO (Either Failure (Either Error value))
-> IO (Either Error value)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString
-> (Key -> IO (Either Error value))
-> IO (Either Failure (Either Error value))
forall value.
ByteString -> (Key -> IO value) -> IO (Either Failure value)
Internal.withExtendedKey ByteString
bytes (SigningKey -> IO (Either Error value)
action (SigningKey -> IO (Either Error value))
-> (Key -> SigningKey) -> Key -> IO (Either Error value)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Key -> SigningKey
SigningKey)

-- | Import 64 ASCII hex digits representing a normal 32-byte seed. Both letter
-- cases are accepted; no prefix or whitespace is allowed. Malformed or empty
-- text returns 'InvalidHex'; well-formed wrong length returns
-- 'InvalidEd25519SigningKeyLength'. Closing the key does not erase the supplied text.
withNormalKeyHex :: Text -> (SigningKey -> IO (Either Error value)) -> IO (Either Error value)
withNormalKeyHex :: forall value.
Text
-> (SigningKey -> IO (Either Error value))
-> IO (Either Error value)
withNormalKeyHex Text
text SigningKey -> IO (Either Error value)
action = Either Failure (Either Error value) -> Either Error value
forall value.
Either Failure (Either Error value) -> Either Error value
flatten (Either Failure (Either Error value) -> Either Error value)
-> IO (Either Failure (Either Error value))
-> IO (Either Error value)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Text
-> (Key -> IO (Either Error value))
-> IO (Either Failure (Either Error value))
forall value.
Text -> (Key -> IO value) -> IO (Either Failure value)
Internal.withNormalKeyHex Text
text (SigningKey -> IO (Either Error value)
action (SigningKey -> IO (Either Error value))
-> (Key -> SigningKey) -> Key -> IO (Either Error value)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Key -> SigningKey
SigningKey)

-- | Import 128 ASCII hex digits representing an expanded 64-byte scalar and nonce-prefix key.
-- Validation and lifetime limitations match 'withNormalKeyHex'.
withExtendedKeyHex :: Text -> (SigningKey -> IO (Either Error value)) -> IO (Either Error value)
withExtendedKeyHex :: forall value.
Text
-> (SigningKey -> IO (Either Error value))
-> IO (Either Error value)
withExtendedKeyHex Text
text SigningKey -> IO (Either Error value)
action = Either Failure (Either Error value) -> Either Error value
forall value.
Either Failure (Either Error value) -> Either Error value
flatten (Either Failure (Either Error value) -> Either Error value)
-> IO (Either Failure (Either Error value))
-> IO (Either Error value)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Text
-> (Key -> IO (Either Error value))
-> IO (Either Failure (Either Error value))
forall value.
Text -> (Key -> IO value) -> IO (Either Failure value)
Internal.withExtendedKeyHex Text
text (SigningKey -> IO (Either Error value)
action (SigningKey -> IO (Either Error value))
-> (Key -> SigningKey) -> Key -> IO (Either Error value)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Key -> SigningKey
SigningKey)

-- | Run a continuation with an independent secret copy. Closing the source does
-- not close the copy, and closing the copy does not close its source. The copy
-- closes on every exit. A closed source returns 'SigningKeyClosed'.
withClone :: SigningKey -> (SigningKey -> IO (Either Error value)) -> IO (Either Error value)
withClone :: forall value.
SigningKey
-> (SigningKey -> IO (Either Error value))
-> IO (Either Error value)
withClone (SigningKey Key
key) SigningKey -> IO (Either Error value)
action = Either Failure (Either Error value) -> Either Error value
forall value.
Either Failure (Either Error value) -> Either Error value
flatten (Either Failure (Either Error value) -> Either Error value)
-> IO (Either Failure (Either Error value))
-> IO (Either Error value)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Key
-> (Key -> IO (Either Error value))
-> IO (Either Failure (Either Error value))
forall value. Key -> (Key -> IO value) -> IO (Either Failure value)
Internal.withClone Key
key (SigningKey -> IO (Either Error value)
action (SigningKey -> IO (Either Error value))
-> (Key -> SigningKey) -> Key -> IO (Either Error value)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Key -> SigningKey
SigningKey)

-- | Close the key; repeated calls have no effect. Wait for ongoing operations before returning;
-- no new operation can use the closed handle. Scope exit also closes it.
close :: SigningKey -> IO ()
close :: SigningKey -> IO ()
close (SigningKey Key
key) = Key -> IO ()
Internal.close Key
key

-- | Number of secret bytes: 32 for a normal seed, 64 for an extended key.
-- This reveals no secret contents. A closed handle returns 'SigningKeyClosed'.
byteLength :: SigningKey -> IO (Either Error Int)
byteLength :: SigningKey -> IO (Either Error Int)
byteLength (SigningKey Key
key) = Either Failure Int -> Either Error Int
forall value. Either Failure value -> Either Error value
mapFailure (Either Failure Int -> Either Error Int)
-> IO (Either Failure Int) -> IO (Either Error Int)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Key -> IO (Either Failure Int)
Internal.byteLength Key
key

-- | Number of hexadecimal digits, excluding any terminator: 64 or 128. No secret
-- copy is created. A closed handle returns 'SigningKeyClosed'.
hexLength :: SigningKey -> IO (Either Error Int)
hexLength :: SigningKey -> IO (Either Error Int)
hexLength SigningKey
key = (Int -> Int) -> Either Error Int -> Either Error Int
forall a b. (a -> b) -> Either Error a -> Either Error b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
2) (Either Error Int -> Either Error Int)
-> IO (Either Error Int) -> IO (Either Error Int)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> SigningKey -> IO (Either Error Int)
byteLength SigningKey
key

-- | Derive an immutable public key which remains usable after this key closes.
-- A closed handle returns 'SigningKeyClosed'; derivation failures retain their
-- structured native status without including any secret input.
publicKey :: SigningKey -> IO (Either Error PublicKey)
publicKey :: SigningKey -> IO (Either Error PublicKey)
publicKey (SigningKey Key
key) = do
  Either Failure ByteString
result <- Key -> IO (Either Failure ByteString)
Internal.publicKeyBytes Key
key
  Either Error PublicKey -> IO (Either Error PublicKey)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Failure ByteString -> Either Error ByteString
forall value. Either Failure value -> Either Error value
mapFailure Either Failure ByteString
result Either Error ByteString
-> (ByteString -> Either Error PublicKey) -> Either Error PublicKey
forall a b.
Either Error a -> (a -> Either Error b) -> Either Error b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ByteString -> Either Error PublicKey
PublicKey.fromBytes)

-- | Sign the exact message bytes. Empty messages are supported. The returned
-- signature remains usable after this key closes. This does not prehash or encode
-- a message on the caller's behalf: transaction signing requires the raw body
-- digest, rather than full transaction CBOR or its hexadecimal representation.
-- A closed handle returns 'SigningKeyClosed'; failures never include key bytes.
sign :: SigningKey -> ByteString -> IO (Either Error Signature)
sign :: SigningKey -> ByteString -> IO (Either Error Signature)
sign (SigningKey Key
key) ByteString
message = do
  Either Failure ByteString
result <- Key -> ByteString -> IO (Either Failure ByteString)
Internal.signBytes Key
key ByteString
message
  Either Error Signature -> IO (Either Error Signature)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Failure ByteString -> Either Error ByteString
forall value. Either Failure value -> Either Error value
mapFailure Either Failure ByteString
result Either Error ByteString
-> (ByteString -> Either Error Signature) -> Either Error Signature
forall a b.
Either Error a -> (a -> Either Error b) -> Either Error b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ByteString -> Either Error Signature
Signature.fromBytes)

-- | Explicitly copy the secret into a new Haskell ByteString. The result can
-- outlive this key and its scope. Closing cannot erase that copy or control
-- copies made by the application; use this only when secret export is intended.
-- A closed handle returns 'SigningKeyClosed'.
exportBytes :: SigningKey -> IO (Either Error ByteString)
exportBytes :: SigningKey -> IO (Either Error ByteString)
exportBytes (SigningKey Key
key) = Either Failure ByteString -> Either Error ByteString
forall value. Either Failure value -> Either Error value
mapFailure (Either Failure ByteString -> Either Error ByteString)
-> IO (Either Failure ByteString) -> IO (Either Error ByteString)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Key -> IO (Either Failure ByteString)
Internal.exportBytes Key
key

-- | Explicitly export lowercase ASCII hexadecimal secret text without a prefix.
-- The exported text remains available after this key closes; closure does not erase it.
-- A closed handle returns 'SigningKeyClosed'.
exportHex :: SigningKey -> IO (Either Error Text)
exportHex :: SigningKey -> IO (Either Error Text)
exportHex SigningKey
key = (ByteString -> Text)
-> Either Error ByteString -> Either Error Text
forall a b. (a -> b) -> Either Error a -> Either Error b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ByteString -> Text
Hex.encodeHex (Either Error ByteString -> Either Error Text)
-> IO (Either Error ByteString) -> IO (Either Error Text)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> SigningKey -> IO (Either Error ByteString)
exportBytes SigningKey
key

-- | Keep acquisition failures flat with the continuation's expected failures.
flatten :: Either Internal.Failure (Either Error value) -> Either Error value
flatten :: forall value.
Either Failure (Either Error value) -> Either Error value
flatten Either Failure (Either Error value)
result = Either Error (Either Error value) -> Either Error value
forall (m :: * -> *) a. Monad m => m (m a) -> m a
join (Either Failure (Either Error value)
-> Either Error (Either Error value)
forall value. Either Failure value -> Either Error value
mapFailure Either Failure (Either Error value)
result)

mapFailure :: Either Internal.Failure value -> Either Error value
mapFailure :: forall value. Either Failure value -> Either Error value
mapFailure = (Failure -> Either Error value)
-> (value -> Either Error value)
-> Either Failure value
-> Either Error value
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Error -> Either Error value
forall a b. a -> Either a b
Left (Error -> Either Error value)
-> (Failure -> Error) -> Failure -> Either Error value
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Failure -> Error
publicFailure) value -> Either Error value
forall a b. b -> Either a b
Right

publicFailure :: Internal.Failure -> Error
publicFailure :: Failure -> Error
publicFailure Failure
failure = case Failure
failure of
  Failure
Internal.Closed -> Error
SigningKeyClosed
  Internal.InvalidLength Int
expected Int
actual -> Int -> Int -> Error
InvalidEd25519SigningKeyLength Int
expected Int
actual
  Failure
Internal.InvalidHex -> Error
InvalidHex
  Internal.NativeFailure NativeFailure
failureValue -> NativeFailure -> Error
fromNativeFailure NativeFailure
failureValue