-- 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 Cardano Ed25519-BIP32 private keys. A key contains a 64-byte expanded
-- Ed25519 secret and a 32-byte chain code. It has no 'Show' or equality instance.
-- Handles reject operations after scope exit or explicit 'close'; escaped handles
-- do not extend usable lifetime. Exceptions and cancellation propagate after cleanup.
-- Closing cannot erase application inputs or explicitly exported copies.
--
-- @
-- import qualified Cometa.Crypto.Bip32.PrivateKey as PrivateKey
--
-- -- bytes must contain a 96-byte application key.
-- derivePublic bytes = PrivateKey.withKey bytes $ \root ->
--   PrivateKey.withDerived root [PrivateKey.harden 1852, PrivateKey.harden 1815,
--     PrivateKey.harden 0, 0, 0] PrivateKey.publicKey
-- @
module Cometa.Crypto.Bip32.PrivateKey
  ( PrivateKey,

    -- * Scoped acquisition
    withKey,
    withKeyHex,
    withEntropy,
    withClone,
    withDerived,
    withSigningKey,
    close,

    -- * Derivation indices
    harden,

    -- * Inspection
    byteLength,
    hexLength,
    publicKey,

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

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

import qualified Cometa.Crypto.Bip32.PublicKey as PublicKey
import Cometa.Crypto.Ed25519.SigningKey (SigningKey)
import Cometa.Error (Error (..))
import qualified Cometa.Internal.Bip32PrivateKey as Internal
import qualified Cometa.Internal.Ed25519SigningKey as Signing
import Cometa.Internal.Error (fromNativeFailure)
import qualified Cometa.Internal.Hex as Hex
import Control.Monad (join)
import Data.Bits ((.|.))
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import Data.Text (Text)
import Data.Word (Word32)

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

-- | Opaque scoped 96-byte secret. Independent derived keys and clones may outlive
-- the source's usable lifetime only within their own active scopes.
newtype PrivateKey = PrivateKey Internal.Key

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

-- | Import exactly 96 bytes and run the continuation. Only encoded length is
-- checked; invalid scalars may fail later operations. Wrong lengths return
-- 'InvalidBip32PrivateKeyLength' without invoking the continuation. Acquisition
-- and callback failures share one 'Either'; callback exceptions propagate.
withKey :: ByteString -> (PrivateKey -> IO (Either Error value)) -> IO (Either Error value)
withKey :: forall value.
ByteString
-> (PrivateKey -> IO (Either Error value))
-> IO (Either Error value)
withKey ByteString
bytes PrivateKey -> 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.withBytesKey ByteString
bytes (PrivateKey -> IO (Either Error value)
action (PrivateKey -> IO (Either Error value))
-> (Key -> PrivateKey) -> Key -> IO (Either Error value)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Key -> PrivateKey
PrivateKey)

-- | Import exactly 192 ASCII hexadecimal digits, accepting either case without
-- whitespace or prefix. Empty/malformed text returns 'InvalidHex'; valid hex of
-- another length returns 'InvalidBip32PrivateKeyLength'. Input text remains in
-- application memory after closure. Cleanup matches 'withKey'.
withKeyHex :: Text -> (PrivateKey -> IO (Either Error value)) -> IO (Either Error value)
withKeyHex :: forall value.
Text
-> (PrivateKey -> IO (Either Error value))
-> IO (Either Error value)
withKeyHex Text
text PrivateKey -> 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.withHexKey Text
text (PrivateKey -> IO (Either Error value)
action (PrivateKey -> IO (Either Error value))
-> (Key -> PrivateKey) -> Key -> IO (Either Error value)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Key -> PrivateKey
PrivateKey)

-- | Derive a root from raw password bytes and BIP39 entropy bytes, respectively.
-- Entropy must contain 16, 20, 24, 28 or 32 bytes; other lengths return
-- 'InvalidBip39EntropyLength'. Password may be empty and may contain NUL bytes.
-- This uses Cardano's PBKDF2-HMAC-SHA512 with 4096 iterations and 96 output bytes,
-- followed by scalar clamping. No text normalization is performed. This accepts
-- entropy, not a mnemonic sentence or a 64-byte BIP39 seed. Inputs remain in
-- application memory; failures and cleanup match 'withKey'.
withEntropy :: ByteString -> ByteString -> (PrivateKey -> IO (Either Error value)) -> IO (Either Error value)
withEntropy :: forall value.
ByteString
-> ByteString
-> (PrivateKey -> IO (Either Error value))
-> IO (Either Error value)
withEntropy ByteString
password ByteString
entropy PrivateKey -> IO (Either Error value)
action
  | ByteString -> Int
ByteString.length ByteString
entropy Int -> [Int] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [Int
16, Int
20, Int
24, Int
28, Int
32] = Either Error value -> IO (Either Error value)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error value
forall a b. a -> Either a b
Left (Int -> Error
InvalidBip39EntropyLength (ByteString -> Int
ByteString.length ByteString
entropy)))
  | Bool
otherwise = 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
-> ByteString
-> (Key -> IO (Either Error value))
-> IO (Either Failure (Either Error value))
forall value.
ByteString
-> ByteString -> (Key -> IO value) -> IO (Either Failure value)
Internal.withEntropy ByteString
password ByteString
entropy (PrivateKey -> IO (Either Error value)
action (PrivateKey -> IO (Either Error value))
-> (Key -> PrivateKey) -> Key -> IO (Either Error value)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Key -> PrivateKey
PrivateKey)

-- | Run the continuation with an independent copy. Closing either key does
-- not affect the other; the copy closes on every exit. Closed sources return
-- 'Bip32PrivateKeyClosed'.
withClone :: PrivateKey -> (PrivateKey -> IO (Either Error value)) -> IO (Either Error value)
withClone :: forall value.
PrivateKey
-> (PrivateKey -> IO (Either Error value))
-> IO (Either Error value)
withClone (PrivateKey Key
key) PrivateKey -> 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 (PrivateKey -> IO (Either Error value)
action (PrivateKey -> IO (Either Error value))
-> (Key -> PrivateKey) -> Key -> IO (Either Error value)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Key -> PrivateKey
PrivateKey)

-- | Derive indices in order into an independent scope. All 'Word32' values are
-- accepted: @0..2^31-1@ are soft and @2^31..2^32-1@ are hardened. Use 'harden' to
-- set the high bit. An empty path makes an independent clone. The source remains
-- unchanged. Closed sources return 'Bip32PrivateKeyClosed'; operation failures
-- return 'NativeError'. The derived key closes before callback exceptions propagate.
withDerived :: PrivateKey -> [Word32] -> (PrivateKey -> IO (Either Error value)) -> IO (Either Error value)
withDerived :: forall value.
PrivateKey
-> [Word32]
-> (PrivateKey -> IO (Either Error value))
-> IO (Either Error value)
withDerived (PrivateKey Key
key) [Word32]
path PrivateKey -> 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
-> [Word32]
-> (Key -> IO (Either Error value))
-> IO (Either Failure (Either Error value))
forall value.
Key -> [Word32] -> (Key -> IO value) -> IO (Either Failure value)
Internal.withDerived Key
key [Word32]
path (PrivateKey -> IO (Either Error value)
action (PrivateKey -> IO (Either Error value))
-> (Key -> PrivateKey) -> Key -> IO (Either Error value)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Key -> PrivateKey
PrivateKey)

-- | Run the continuation with an independent extended Ed25519 signing key,
-- discarding the chain code. Closing the source does not close the signing key.
-- The signing key closes on every exit and rejects escaped uses. Closed sources
-- return 'Bip32PrivateKeyClosed'; failures return 'NativeError'.
withSigningKey :: PrivateKey -> (SigningKey -> IO (Either Error value)) -> IO (Either Error value)
withSigningKey :: forall value.
PrivateKey
-> (SigningKey -> IO (Either Error value))
-> IO (Either Error value)
withSigningKey (PrivateKey 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.withSigningKey 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
Signing.SigningKey)

-- | Set the high bit of an encoded index. This is idempotent: an already hardened
-- index is unchanged. For example, @harden 1852 == 2147485500@.
harden :: Word32 -> Word32
harden :: Word32 -> Word32
harden Word32
index = Word32
index Word32 -> Word32 -> Word32
forall a. Bits a => a -> a -> a
.|. Word32
0x80000000

-- | Close this handle, waiting for active operations. Repeated closure is harmless.
-- Scope exit also closes it; no later operation can use this handle.
close :: PrivateKey -> IO ()
close :: PrivateKey -> IO ()
close (PrivateKey Key
key) = Key -> IO ()
Internal.close Key
key

-- | Secret byte count, always 96. Closed handles return
-- 'Bip32PrivateKeyClosed'.
byteLength :: PrivateKey -> IO (Either Error Int)
byteLength :: PrivateKey -> IO (Either Error Int)
byteLength (PrivateKey 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

-- | Hexadecimal digit count, always 192, excluding a terminator. Closed handles
-- return 'Bip32PrivateKeyClosed'.
hexLength :: PrivateKey -> IO (Either Error Int)
hexLength :: PrivateKey -> IO (Either Error Int)
hexLength PrivateKey
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
<$> PrivateKey -> IO (Either Error Int)
byteLength PrivateKey
key

-- | Derive an immutable 64-byte public key and chain code, usable after this
-- secret closes. A closed handle returns 'Bip32PrivateKeyClosed'; unusable scalar
-- or other operation failures return 'NativeError' without secret diagnostics.
publicKey :: PrivateKey -> IO (Either Error PublicKey.PublicKey)
publicKey :: PrivateKey -> IO (Either Error PublicKey)
publicKey (PrivateKey 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)

-- | Explicitly copy all 96 secret bytes into a Haskell ByteString. The result can
-- outlive this scope; closing cannot erase it or control subsequent application
-- copies. A closed handle returns 'Bip32PrivateKeyClosed'.
exportBytes :: PrivateKey -> IO (Either Error ByteString)
exportBytes :: PrivateKey -> IO (Either Error ByteString)
exportBytes (PrivateKey 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 192 lowercase ASCII hex digits without prefix. The text
-- has application-managed lifetime and is not erased on closure. A closed handle
-- returns 'Bip32PrivateKeyClosed'.
exportHex :: PrivateKey -> IO (Either Error Text)
exportHex :: PrivateKey -> IO (Either Error Text)
exportHex PrivateKey
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
<$> PrivateKey -> IO (Either Error ByteString)
exportBytes PrivateKey
key

flatten :: Either Internal.Failure (Either Error value) -> Either Error value
flatten :: forall value.
Either Failure (Either Error value) -> Either Error value
flatten = Either Error (Either Error value) -> Either Error value
forall (m :: * -> *) a. Monad m => m (m a) -> m a
join (Either Error (Either Error value) -> Either Error value)
-> (Either Failure (Either Error value)
    -> Either Error (Either Error value))
-> Either Failure (Either Error value)
-> Either Error value
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Either Failure (Either Error value)
-> Either Error (Either Error value)
forall value. Either Failure value -> Either Error value
mapFailure

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
Bip32PrivateKeyClosed
  Internal.InvalidLength Int
_ Int
actual -> Int -> Error
InvalidBip32PrivateKeyLength Int
actual
  Failure
Internal.InvalidHex -> Error
InvalidHex
  Internal.NativeFailure NativeFailure
failureValue -> NativeFailure -> Error
fromNativeFailure NativeFailure
failureValue