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

-- | Scoped encrypted software key storage. Each public-key operation requests a password
-- from the supplied action. Passwords are raw bytes (including NUL), 1 through
-- 128 bytes; no text normalization is performed. Keep application-owned inputs
-- and callback results only as long as your application requires: closing cannot
-- erase those Haskell values or copies made by the application.
--
-- A handler closes on every continuation exit, including exceptions. Escaped
-- handles reject further operations. Operations on independent handlers may run
-- concurrently; overlap and callback reentry on the same handler return
-- 'KeyHandlerBusy'. A password action must not wait for another operation on
-- its own handler. Cancellation waits for the password action and native work
-- to unwind; an action that masks cancellation can delay cleanup.
--
-- @
-- import qualified Cometa.KeyHandler.Software as Software
--
-- storeEntropy entropy encryptionPassword requestPassword =
--   Software.withEntropy entropy encryptionPassword requestPassword Software.serialize
-- @
module Cometa.KeyHandler.Software
  ( -- * Capabilities
    Handler,
    Bip32,
    Ed25519,
    LoadedHandler (..),

    -- * Scoped construction
    withEntropy,
    withSigningKey,
    withSerialized,

    -- * Operations
    close,
    accountPublicKey,
    publicKey,
    name,
    serialize,
    signTransaction,
    signTransactionAt,
    signSubTransaction,
    signSubTransactionAt,
  )
where

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

import qualified Cometa.Crypto.Bip32.PublicKey as Bip32Public
import Cometa.Crypto.DerivationPath (AccountPath)
import qualified Cometa.Crypto.DerivationPath as Path
import qualified Cometa.Crypto.Ed25519.PublicKey as EdPublic
import Cometa.Crypto.Ed25519.SigningKey (SigningKey)
import Cometa.Error (Error (..))
import Cometa.Internal.Ed25519SigningKey (SigningKey (..))
import Cometa.Internal.Error (fromNativeFailure)
import qualified Cometa.Internal.KeyHandler as Internal
import qualified Cometa.SubTransaction as SubTransaction
import qualified Cometa.Transaction as Transaction
import qualified Cometa.Transaction.Witnesses as Witnesses
import Control.Monad (join)
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import Data.List.NonEmpty (NonEmpty)
import qualified Data.List.NonEmpty as NonEmpty
import Data.Text (Text)
import Data.Word (Word32)
import Foreign.C.Types (CUInt)

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

-- | BIP32 capability: derive an account public key from encrypted entropy.
data Bip32

-- | Ed25519 capability: recover the public key associated with encrypted key bytes.
data Ed25519

-- | A scoped handler whose capability determines the available operations.
-- No equality or printable representation exposes secret storage.
type role Handler nominal

newtype Handler mode = Handler Internal.Handler

-- | The serialized format determines the handler capability. Metadata is CRC
-- protected, not authenticated; accept storage only from a trusted source.
data LoadedHandler
  = -- | A handler storing BIP39 entropy for hierarchical account derivation.
    Bip32Handler (Handler Bip32)
  | -- | A handler storing a normal or extended Ed25519 signing key.
    Ed25519Handler (Handler Ed25519)

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

-- | Encrypt BIP39 entropy (16, 20, 24, 28 or 32 bytes) immediately with the
-- supplied encryption password, then run the continuation. The request action
-- supplies a fresh password for each derivation. Root derivation uses the empty
-- BIP39 password; the encryption password only protects storage.
withEntropy :: ByteString -> ByteString -> IO ByteString -> (Handler Bip32 -> IO (Either Error value)) -> IO (Either Error value)
withEntropy :: forall value.
ByteString
-> ByteString
-> IO ByteString
-> (Handler Bip32 -> IO (Either Error value))
-> IO (Either Error value)
withEntropy ByteString
entropy ByteString
password IO ByteString
request Handler Bip32 -> IO (Either Error value)
action
  | Int
size 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 Int
size))
  | 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
-> IO ByteString
-> (Handler -> IO (Either Error value))
-> IO (Either Failure (Either Error value))
forall value.
ByteString
-> ByteString
-> IO ByteString
-> (Handler -> IO value)
-> IO (Either Failure value)
Internal.withEntropy ByteString
entropy ByteString
password IO ByteString
request (Handler Bip32 -> IO (Either Error value)
action (Handler Bip32 -> IO (Either Error value))
-> (Handler -> Handler Bip32) -> Handler -> IO (Either Error value)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Handler -> Handler Bip32
forall mode. Handler -> Handler mode
Handler)
  where
    size :: Int
size = ByteString -> Int
ByteString.length ByteString
entropy

-- | Encrypt a copy of a scoped normal or extended signing key. The source stays
-- usable independently. A closed source returns 'SigningKeyClosed'.
withSigningKey :: SigningKey -> ByteString -> IO ByteString -> (Handler Ed25519 -> IO (Either Error value)) -> IO (Either Error value)
withSigningKey :: forall value.
SigningKey
-> ByteString
-> IO ByteString
-> (Handler Ed25519 -> IO (Either Error value))
-> IO (Either Error value)
withSigningKey (SigningKey Key
source) ByteString
password IO ByteString
request Handler Ed25519 -> 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
-> ByteString
-> IO ByteString
-> (Handler -> IO (Either Error value))
-> IO (Either Failure (Either Error value))
forall value.
Key
-> ByteString
-> IO ByteString
-> (Handler -> IO value)
-> IO (Either Failure value)
Internal.withSigningKey Key
source ByteString
password IO ByteString
request (Handler Ed25519 -> IO (Either Error value)
action (Handler Ed25519 -> IO (Either Error value))
-> (Handler -> Handler Ed25519)
-> Handler
-> IO (Either Error value)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Handler -> Handler Ed25519
forall mode. Handler -> Handler mode
Handler)

-- | Open the native binary storage format. Validates framing, type, canonical
-- encrypted payload sizes and checksum before invoking the continuation. It does not
-- request a password or authenticate the encrypted payload until a public-key
-- operation is requested. Wrong passwords fail that later operation.
withSerialized :: ByteString -> IO ByteString -> (LoadedHandler -> IO (Either Error value)) -> IO (Either Error value)
withSerialized :: forall value.
ByteString
-> IO ByteString
-> (LoadedHandler -> IO (Either Error value))
-> IO (Either Error value)
withSerialized ByteString
bytes IO ByteString
request LoadedHandler -> 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
-> IO ByteString
-> (Bool -> Handler -> IO (Either Error value))
-> IO (Either Failure (Either Error value))
forall value.
ByteString
-> IO ByteString
-> (Bool -> Handler -> IO value)
-> IO (Either Failure value)
Internal.withSerialized
      ByteString
bytes
      IO ByteString
request
      ( \Bool
bip32 Handler
handler ->
          LoadedHandler -> IO (Either Error value)
action (if Bool
bip32 then Handler Bip32 -> LoadedHandler
Bip32Handler (Handler -> Handler Bip32
forall mode. Handler -> Handler mode
Handler Handler
handler) else Handler Ed25519 -> LoadedHandler
Ed25519Handler (Handler -> Handler Ed25519
forall mode. Handler -> Handler mode
Handler Handler
handler))
      )

-- | Close immediately, or return 'KeyHandlerBusy' if an operation is active.
-- Repeated close succeeds. Scope exit waits for ongoing work and closes even
-- when a prior explicit close returned busy.
close :: Handler mode -> IO (Either Error ())
close :: forall mode. Handler mode -> IO (Either Error ())
close (Handler Handler
handler) = Either Failure () -> Either Error ()
forall value. Either Failure value -> Either Error value
mapFailure (Either Failure () -> Either Error ())
-> IO (Either Failure ()) -> IO (Either Error ())
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Handler -> IO (Either Failure ())
Internal.close Handler
handler

-- | Derive the account extended public key at three hardened path components.
-- The public result remains usable after this handler closes.
accountPublicKey :: Handler Bip32 -> AccountPath -> IO (Either Error Bip32Public.PublicKey)
accountPublicKey :: Handler Bip32 -> AccountPath -> IO (Either Error PublicKey)
accountPublicKey (Handler Handler
handler) AccountPath
path = do
  Either Failure ByteString
result <- Handler
-> Word32 -> Word32 -> Word32 -> IO (Either Failure ByteString)
Internal.accountPublicKey Handler
handler ((AccountPath -> Index) -> Word32
component AccountPath -> Index
Path.purpose) ((AccountPath -> Index) -> Word32
component AccountPath -> Index
Path.coinType) ((AccountPath -> Index) -> Word32
component AccountPath -> Index
Path.account)
  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
Bip32Public.fromBytes)
  where
    component :: (AccountPath -> Index) -> Word32
component AccountPath -> Index
field = Index -> Word32
Path.indexValue (AccountPath -> Index
field AccountPath
path)

-- | Recover the Ed25519 public key. Each call requests a password, and the
-- returned immutable key remains usable after this handler closes.
publicKey :: Handler Ed25519 -> IO (Either Error EdPublic.PublicKey)
publicKey :: Handler Ed25519 -> IO (Either Error PublicKey)
publicKey (Handler Handler
handler) = do
  Either Failure ByteString
result <- Handler -> IO (Either Failure ByteString)
Internal.publicKey Handler
handler
  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
EdPublic.fromBytes)

-- | Implementation name for diagnostics. Does not request a password.
name :: Handler mode -> IO (Either Error Text)
name :: forall mode. Handler mode -> IO (Either Error Text)
name (Handler Handler
handler) = Either Failure Text -> Either Error Text
forall value. Either Failure value -> Either Error value
mapFailure (Either Failure Text -> Either Error Text)
-> IO (Either Failure Text) -> IO (Either Error Text)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Handler -> IO (Either Failure Text)
Internal.name Handler
handler

-- | Copy encrypted storage bytes for persistence; does not request a password.
-- The binary format contains encrypted key material and CRC-protected metadata.
-- The metadata is not cryptographically authenticated. The result can outlive
-- the scope; protect it against unauthorized modification and password guessing.
serialize :: Handler mode -> IO (Either Error ByteString)
serialize :: forall mode. Handler mode -> IO (Either Error ByteString)
serialize (Handler Handler
handler) = 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
<$> Handler -> IO (Either Failure ByteString)
Internal.serialize Handler
handler

-- | Sign the exact transaction-body hash using the encrypted Ed25519 key.
-- Requests a password once and returns partial witnesses, without changing the
-- transaction. Merge with 'Transaction.addWitnesses' to retain existing signatures.
-- Closed, busy, password and native failures follow the ordinary handler contract.
signTransaction :: Handler Ed25519 -> Transaction.Transaction -> IO (Either Error Witnesses.EncodedWitnesses)
signTransaction :: Handler Ed25519
-> Transaction -> IO (Either Error EncodedWitnesses)
signTransaction (Handler Handler
handler) = Handler
-> CUInt
-> [[Word32]]
-> ByteString
-> IO (Either Error EncodedWitnesses)
signEncoded Handler
handler CUInt
0 [] (ByteString -> IO (Either Error EncodedWitnesses))
-> (Transaction -> ByteString)
-> Transaction
-> IO (Either Error EncodedWitnesses)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> ByteString
Transaction.encodeCbor

-- | Derive each nonempty five-level path and sign the exact body hash. Requests
-- a password once for the whole batch. Returns only the generated witnesses;
-- duplicate paths are idempotent. No transaction bytes are changed.
signTransactionAt :: Handler Bip32 -> NonEmpty Path.DerivationPath -> Transaction.Transaction -> IO (Either Error Witnesses.EncodedWitnesses)
signTransactionAt :: Handler Bip32
-> NonEmpty DerivationPath
-> Transaction
-> IO (Either Error EncodedWitnesses)
signTransactionAt (Handler Handler
handler) NonEmpty DerivationPath
paths = Handler
-> CUInt
-> [[Word32]]
-> ByteString
-> IO (Either Error EncodedWitnesses)
signEncoded Handler
handler CUInt
1 ((DerivationPath -> [Word32]) -> [DerivationPath] -> [[Word32]]
forall a b. (a -> b) -> [a] -> [b]
map DerivationPath -> [Word32]
pathComponents (NonEmpty DerivationPath -> [DerivationPath]
forall a. NonEmpty a -> [a]
NonEmpty.toList NonEmpty DerivationPath
paths)) (ByteString -> IO (Either Error EncodedWitnesses))
-> (Transaction -> ByteString)
-> Transaction
-> IO (Either Error EncodedWitnesses)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> ByteString
Transaction.encodeCbor

-- | Sign a sub-transaction's own exact body hash using the encrypted Ed25519 key.
-- The enclosing body and its signatures are independent of this operation.
signSubTransaction :: Handler Ed25519 -> SubTransaction.SubTransaction -> IO (Either Error Witnesses.EncodedWitnesses)
signSubTransaction :: Handler Ed25519
-> SubTransaction -> IO (Either Error EncodedWitnesses)
signSubTransaction (Handler Handler
handler) = Handler
-> CUInt
-> [[Word32]]
-> ByteString
-> IO (Either Error EncodedWitnesses)
signEncoded Handler
handler CUInt
2 [] (ByteString -> IO (Either Error EncodedWitnesses))
-> (SubTransaction -> ByteString)
-> SubTransaction
-> IO (Either Error EncodedWitnesses)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SubTransaction -> ByteString
SubTransaction.encodeCbor

-- | Derive the supplied paths and sign this sub-transaction's own body hash.
-- Requests a password once and returns partial witnesses without changing input.
signSubTransactionAt :: Handler Bip32 -> NonEmpty Path.DerivationPath -> SubTransaction.SubTransaction -> IO (Either Error Witnesses.EncodedWitnesses)
signSubTransactionAt :: Handler Bip32
-> NonEmpty DerivationPath
-> SubTransaction
-> IO (Either Error EncodedWitnesses)
signSubTransactionAt (Handler Handler
handler) NonEmpty DerivationPath
paths = Handler
-> CUInt
-> [[Word32]]
-> ByteString
-> IO (Either Error EncodedWitnesses)
signEncoded Handler
handler CUInt
3 ((DerivationPath -> [Word32]) -> [DerivationPath] -> [[Word32]]
forall a b. (a -> b) -> [a] -> [b]
map DerivationPath -> [Word32]
pathComponents (NonEmpty DerivationPath -> [DerivationPath]
forall a. NonEmpty a -> [a]
NonEmpty.toList NonEmpty DerivationPath
paths)) (ByteString -> IO (Either Error EncodedWitnesses))
-> (SubTransaction -> ByteString)
-> SubTransaction
-> IO (Either Error EncodedWitnesses)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SubTransaction -> ByteString
SubTransaction.encodeCbor

signEncoded :: Internal.Handler -> CUInt -> [[Word32]] -> ByteString -> IO (Either Error Witnesses.EncodedWitnesses)
signEncoded :: Handler
-> CUInt
-> [[Word32]]
-> ByteString
-> IO (Either Error EncodedWitnesses)
signEncoded Handler
handler CUInt
kind [[Word32]]
paths ByteString
bytes = do
  Either Failure ByteString
result <- Handler
-> CUInt
-> [[Word32]]
-> ByteString
-> IO (Either Failure ByteString)
Internal.signTransaction Handler
handler CUInt
kind [[Word32]]
paths ByteString
bytes
  Either Error EncodedWitnesses -> IO (Either Error EncodedWitnesses)
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 EncodedWitnesses)
-> Either Error EncodedWitnesses
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 EncodedWitnesses
Witnesses.decodeCbor)

pathComponents :: Path.DerivationPath -> [Word32]
pathComponents :: DerivationPath -> [Word32]
pathComponents DerivationPath
path =
  let account :: AccountPath
account = DerivationPath -> AccountPath
Path.accountPrefix DerivationPath
path
   in (Index -> Word32) -> [Index] -> [Word32]
forall a b. (a -> b) -> [a] -> [b]
map Index -> Word32
Path.indexValue [AccountPath -> Index
Path.purpose AccountPath
account, AccountPath -> Index
Path.coinType AccountPath
account, AccountPath -> Index
Path.account AccountPath
account, DerivationPath -> Index
Path.role DerivationPath
path, DerivationPath -> Index
Path.index DerivationPath
path]

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
KeyHandlerClosed
  Failure
Internal.Busy -> Error
KeyHandlerBusy
  Internal.PasswordLength Int
size -> Int -> Error
InvalidKeyHandlerPasswordLength Int
size
  Failure
Internal.InvalidStorage -> Error
InvalidKeyHandlerStorage
  Failure
Internal.SourceClosed -> Error
SigningKeyClosed
  Internal.NativeFailure NativeFailure
native -> NativeFailure -> Error
fromNativeFailure NativeFailure
native