-- 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.
{-# OPTIONS_GHC -fno-cse -fno-full-laziness #-}
{-# OPTIONS_HADDOCK hide #-}

-- | Narrow purity exception for the audited pinned BIP39 conversion path.
-- No owner, callback, logger, RNG, allocator configuration or mutable error
-- state is reached. See docs/development/BIP39_PURITY.md for the build audit
-- and re-audit requirements. These concrete monomorphic NOINLINE boundaries
-- follow base's unsafePerformIO optimizer safeguards; never generalize them to
-- an arbitrary IO runner. Re-evaluation or sharing is semantically harmless.
-- Safe foreign calls unwind before finally wipes scratch on cancellation.
-- Results (including errors) are forced before leaving the private IO action.
module Cometa.Internal.Bip39Pure (Mnemonic, fromEntropy, fromText, fromWords, wordCount, exportText, exportEntropy) where

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

import Cometa.Error (Error (..))
import qualified Cometa.Error.Code as Code
import qualified Cometa.Internal.Bip39 as Internal
import Cometa.Internal.Error (fromNativeFailure)
import Cometa.Internal.Failure (NativeFailure (..))
import Control.Exception (evaluate)
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import Data.Char (isAsciiLower)
import Data.Text (Text)
import qualified Data.Text as Text
import System.IO.Unsafe (unsafePerformIO)

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

-- | A checksum-validated sequence of 12, 15, 18, 21 or 24 lowercase English
-- BIP39 words. Constructors are hidden; secret export is explicit.
newtype Mnemonic = Mnemonic [Text]

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

-- | Validate the bound before entering the audited conversion; force owned words.
{-# NOINLINE fromEntropy #-}
fromEntropy :: ByteString -> Either Error Mnemonic
fromEntropy :: ByteString -> Either Error Mnemonic
fromEntropy ByteString
entropy
  | 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] = Error -> Either Error Mnemonic
forall a b. a -> Either a b
Left (Int -> Error
InvalidBip39EntropyLength Int
size)
  | Bool
otherwise = IO (Either Error Mnemonic) -> Either Error Mnemonic
forall a. IO a -> a
unsafePerformIO (IO (Either Error Mnemonic) -> Either Error Mnemonic)
-> IO (Either Error Mnemonic) -> Either Error Mnemonic
forall a b. (a -> b) -> a -> b
$ do
      Either Error Mnemonic
result <- (Either NativeFailure [Text] -> Either Error Mnemonic)
-> IO (Either NativeFailure [Text]) -> IO (Either Error Mnemonic)
forall a b. (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((NativeFailure -> Either Error Mnemonic)
-> ([Text] -> Either Error Mnemonic)
-> Either NativeFailure [Text]
-> Either Error Mnemonic
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Error -> Either Error Mnemonic
forall a b. a -> Either a b
Left (Error -> Either Error Mnemonic)
-> (NativeFailure -> Error)
-> NativeFailure
-> Either Error Mnemonic
forall b c a. (b -> c) -> (a -> b) -> a -> c
. NativeFailure -> Error
fromNativeFailure) (Mnemonic -> Either Error Mnemonic
forall a b. b -> Either a b
Right (Mnemonic -> Either Error Mnemonic)
-> ([Text] -> Mnemonic) -> [Text] -> Either Error Mnemonic
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Text] -> Mnemonic
Mnemonic)) (ByteString -> IO (Either NativeFailure [Text])
Internal.fromEntropy ByteString
entropy)
      () -> IO ()
forall a. a -> IO a
evaluate (Either Error Mnemonic -> ()
forceMnemonic Either Error Mnemonic
result)
      Either Error Mnemonic -> IO (Either Error Mnemonic)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Either Error Mnemonic
result
  where
    size :: Int
size = ByteString -> Int
ByteString.length ByteString
entropy

-- | Unicode splitting is pure and delegates to the concrete word boundary.
fromText :: Text -> Either Error Mnemonic
fromText :: Text -> Either Error Mnemonic
fromText = [Text] -> Either Error Mnemonic
fromWords ([Text] -> Either Error Mnemonic)
-> (Text -> [Text]) -> Text -> Either Error Mnemonic
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> [Text]
Text.words

-- | Preserve domain/native errors; force the retained input words before return.
{-# NOINLINE fromWords #-}
fromWords :: [Text] -> Either Error Mnemonic
fromWords :: [Text] -> Either Error Mnemonic
fromWords [Text]
words' = case [Text] -> Either Error ()
validateWords [Text]
words' of
  Left Error
err -> Error -> Either Error Mnemonic
forall a b. a -> Either a b
Left Error
err
  Right () -> IO (Either Error Mnemonic) -> Either Error Mnemonic
forall a. IO a -> a
unsafePerformIO (IO (Either Error Mnemonic) -> Either Error Mnemonic)
-> IO (Either Error Mnemonic) -> Either Error Mnemonic
forall a b. (a -> b) -> a -> b
$ do
    Either Error Mnemonic
result <- (Either NativeFailure () -> Either Error Mnemonic)
-> IO (Either NativeFailure ()) -> IO (Either Error Mnemonic)
forall a b. (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((NativeFailure -> Either Error Mnemonic)
-> (() -> Either Error Mnemonic)
-> Either NativeFailure ()
-> Either Error Mnemonic
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Error -> Either Error Mnemonic
forall a b. a -> Either a b
Left (Error -> Either Error Mnemonic)
-> (NativeFailure -> Error)
-> NativeFailure
-> Either Error Mnemonic
forall b c a. (b -> c) -> (a -> b) -> a -> c
. NativeFailure -> Error
mnemonicError) (Either Error Mnemonic -> () -> Either Error Mnemonic
forall a b. a -> b -> a
const (Mnemonic -> Either Error Mnemonic
forall a b. b -> Either a b
Right ([Text] -> Mnemonic
Mnemonic [Text]
words')))) ([Text] -> IO (Either NativeFailure ())
Internal.validate [Text]
words')
    () -> IO ()
forall a. a -> IO a
evaluate (Either Error Mnemonic -> ()
forceMnemonic Either Error Mnemonic
result)
    Either Error Mnemonic -> IO (Either Error Mnemonic)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Either Error Mnemonic
result

-- | Inspect the materialized list.
wordCount :: Mnemonic -> Int
wordCount :: Mnemonic -> Int
wordCount (Mnemonic [Text]
words') = [Text] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Text]
words'

-- | Explicitly materialize a caller-requested secret phrase.
exportText :: Mnemonic -> Text
exportText :: Mnemonic -> Text
exportText (Mnemonic [Text]
words') = [Text] -> Text
Text.unwords [Text]
words'

-- | Preserve all native/contract errors; force the owned copy before return.
{-# NOINLINE exportEntropy #-}
exportEntropy :: Mnemonic -> Either Error ByteString
exportEntropy :: Mnemonic -> Either Error ByteString
exportEntropy (Mnemonic [Text]
words') = IO (Either Error ByteString) -> Either Error ByteString
forall a. IO a -> a
unsafePerformIO (IO (Either Error ByteString) -> Either Error ByteString)
-> IO (Either Error ByteString) -> Either Error ByteString
forall a b. (a -> b) -> a -> b
$ do
  Either Error ByteString
result <- (Either NativeFailure ByteString -> Either Error ByteString)
-> IO (Either NativeFailure ByteString)
-> IO (Either Error ByteString)
forall a b. (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((NativeFailure -> Either Error ByteString)
-> (ByteString -> Either Error ByteString)
-> Either NativeFailure ByteString
-> Either Error ByteString
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Error -> Either Error ByteString
forall a b. a -> Either a b
Left (Error -> Either Error ByteString)
-> (NativeFailure -> Error)
-> NativeFailure
-> Either Error ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. NativeFailure -> Error
fromNativeFailure) ByteString -> Either Error ByteString
forall a b. b -> Either a b
Right) ([Text] -> IO (Either NativeFailure ByteString)
Internal.exportEntropy [Text]
words')
  () -> IO ()
forall a. a -> IO a
evaluate (case Either Error ByteString
result of Left Error
err -> Error -> ()
forceError Error
err; Right ByteString
bytes -> ByteString -> Int
ByteString.length ByteString
bytes Int -> () -> ()
forall a b. a -> b -> b
`seq` ())
  Either Error ByteString -> IO (Either Error ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Either Error ByteString
result

validateWords :: [Text] -> Either Error ()
validateWords :: [Text] -> Either Error ()
validateWords [Text]
words'
  | Int
count Int -> [Int] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [Int
12, Int
15, Int
18, Int
21, Int
24] = Error -> Either Error ()
forall a b. a -> Either a b
Left (Int -> Error
InvalidBip39WordCount Int
count)
  | Bool
otherwise = ((Int, Text) -> Either Error ())
-> [(Int, Text)] -> Either Error ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Int, Text) -> Either Error ()
validate ([Int] -> [Text] -> [(Int, Text)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
1 ..] [Text]
words')
  where
    count :: Int
count = [Text] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Text]
words'
    validate :: (Int, Text) -> Either Error ()
validate (Int
position, Text
word)
      | Text -> Bool
Text.null Text
word Bool -> Bool -> Bool
|| Bool -> Bool
not ((Char -> Bool) -> Text -> Bool
Text.all Char -> Bool
isAsciiLower Text
word) = Error -> Either Error ()
forall a b. a -> Either a b
Left (Int -> Error
InvalidBip39Word Int
position)
      | Bool
otherwise = () -> Either Error ()
forall a b. b -> Either a b
Right ()

mnemonicError :: NativeFailure -> Error
mnemonicError :: NativeFailure -> Error
mnemonicError NativeFailure
failure = case NativeFailure
failure of
  NativeFailure Text
_ Integer
status Text
_
    | Integer -> ErrorCode
Code.fromNumber Integer
status ErrorCode -> ErrorCode -> Bool
forall a. Eq a => a -> a -> Bool
== ErrorCode
Code.InvalidChecksum -> Error
InvalidBip39Checksum
    | Integer -> ErrorCode
Code.fromNumber Integer
status ErrorCode -> ErrorCode -> Bool
forall a. Eq a => a -> a -> Bool
== ErrorCode
Code.InvalidArgument -> Error
UnknownBip39Word
  NativeFailure
_ -> NativeFailure -> Error
fromNativeFailure NativeFailure
failure

-- Force the actual word list, without constructing another secret phrase.
-- Strict Text/ByteString values own their contents; forcing their lengths and
-- every list cell leaves no deferred decoding or borrowed foreign reads.
forceMnemonic :: Either Error Mnemonic -> ()
forceMnemonic :: Either Error Mnemonic -> ()
forceMnemonic (Left Error
err) = Error -> ()
forceError Error
err
forceMnemonic (Right (Mnemonic [Text]
words')) = [Text] -> ()
forceWords [Text]
words'
  where
    forceWords :: [Text] -> ()
forceWords [] = ()
    forceWords (Text
word : [Text]
rest) = Text -> Int
Text.length Text
word Int -> () -> ()
forall a b. a -> b -> b
`seq` [Text] -> ()
forceWords [Text]
rest

forceError :: Error -> ()
forceError :: Error -> ()
forceError (NativeError Text
operation ErrorCode
code Text
diagnostic) =
  Text -> Int
Text.length Text
operation Int -> () -> ()
forall a b. a -> b -> b
`seq` ErrorCode -> Integer
Code.toNumber ErrorCode
code Integer -> () -> ()
forall a b. a -> b -> b
`seq` Text -> Int
Text.length Text
diagnostic Int -> () -> ()
forall a b. a -> b -> b
`seq` ()
forceError (NativeContractViolation Text
operation) = Text -> Int
Text.length Text
operation Int -> () -> ()
forall a b. a -> b -> b
`seq` ()
-- Remaining constructors are nullary or contain strict scalar fields.
forceError Error
err = Error
err Error -> () -> ()
forall a b. a -> b -> b
`seq` ()