-- 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 #-}
{-# OPTIONS_HADDOCK hide #-}

-- | Private native evaluator injection. Public direct Haskell evaluation avoids
-- a C roundtrip. Runtime scopes root registrations through final callback unwind;
-- no native context handle appears in the public evaluator record.
module Cometa.Internal.EvaluationNative
  ( NativeEvaluator,
    withEvaluator,
    withProviderEvaluator,
    withDispatch,
    withRetained,
    close,
    evaluate,
    evaluateRepeated,
    dispatch,
    runUnchecked,
  )
where

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

import qualified Codec.CBOR.Encoding as E
import Cometa.Error (Error (..))
import qualified Cometa.Internal.Evaluation as Evaluation
import qualified Cometa.Internal.FFI.Evaluation as FFI
import qualified Cometa.Internal.Runtime as Runtime
import qualified Cometa.Internal.TransactionCbor as Cbor
import qualified Cometa.Transaction as Tx
import qualified Cometa.Transaction.Redeemer as Redeemer
import qualified Cometa.Transaction.Utxo as Utxo
import Data.ByteString (ByteString)
import Data.Word (Word32)

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

data NativeEvaluator = NativeEvaluator !Runtime.Runtime !Evaluation.Target !Bool

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

withEvaluator :: Evaluation.Evaluator -> Evaluation.Target -> (NativeEvaluator -> IO (Either Error a)) -> IO (Either Error a)
withEvaluator :: forall a.
Evaluator
-> Target
-> (NativeEvaluator -> IO (Either Error a))
-> IO (Either Error a)
withEvaluator Evaluator
evaluator Target
target = Target
-> Dispatch
-> (NativeEvaluator -> IO (Either Error a))
-> IO (Either Error a)
forall a.
Target
-> Dispatch
-> (NativeEvaluator -> IO (Either Error a))
-> IO (Either Error a)
withDispatch Target
target (Evaluator -> Target -> Dispatch
dispatch Evaluator
evaluator Target
target)

-- | Real provider-backed native factory, bound to the provider's top-level ABI.
withProviderEvaluator :: Evaluation.Evaluator -> (NativeEvaluator -> IO (Either Error a)) -> IO (Either Error a)
withProviderEvaluator :: forall a.
Evaluator
-> (NativeEvaluator -> IO (Either Error a)) -> IO (Either Error a)
withProviderEvaluator Evaluator
evaluator NativeEvaluator -> IO (Either Error a)
action = Dispatch -> (Runtime -> IO (Either Error a)) -> IO (Either Error a)
forall a.
Dispatch -> (Runtime -> IO (Either Error a)) -> IO (Either Error a)
Runtime.withRuntime Dispatch
route ((Runtime -> IO (Either Error a)) -> IO (Either Error a))
-> (Runtime -> IO (Either Error a)) -> IO (Either Error a)
forall a b. (a -> b) -> a -> b
$ \Runtime
runtime -> NativeEvaluator -> IO (Either Error a)
action (Runtime -> Target -> Bool -> NativeEvaluator
NativeEvaluator Runtime
runtime Target
Evaluation.TopLevel Bool
True)
  where
    route :: Dispatch
route Word32
operation = Evaluator -> Target -> Dispatch
dispatch Evaluator
evaluator Target
Evaluation.TopLevel (if Word32
operation Word32 -> Word32 -> Bool
forall a. Eq a => a -> a -> Bool
== Word32
9 then Word32
100 else Word32
operation)

-- | Private malformed-transport injection for ownership tests.
withDispatch :: Evaluation.Target -> Runtime.Dispatch -> (NativeEvaluator -> IO (Either Error a)) -> IO (Either Error a)
withDispatch :: forall a.
Target
-> Dispatch
-> (NativeEvaluator -> IO (Either Error a))
-> IO (Either Error a)
withDispatch Target
target Dispatch
handler NativeEvaluator -> IO (Either Error a)
action = Dispatch -> (Runtime -> IO (Either Error a)) -> IO (Either Error a)
forall a.
Dispatch -> (Runtime -> IO (Either Error a)) -> IO (Either Error a)
Runtime.withRuntime Dispatch
handler ((Runtime -> IO (Either Error a)) -> IO (Either Error a))
-> (Runtime -> IO (Either Error a)) -> IO (Either Error a)
forall a b. (a -> b) -> a -> b
$ \Runtime
runtime -> NativeEvaluator -> IO (Either Error a)
action (Runtime -> Target -> Bool -> NativeEvaluator
NativeEvaluator Runtime
runtime Target
target Bool
False)

withRetained :: NativeEvaluator -> (NativeEvaluator -> IO (Either Error a)) -> IO (Either Error a)
withRetained :: forall a.
NativeEvaluator
-> (NativeEvaluator -> IO (Either Error a)) -> IO (Either Error a)
withRetained (NativeEvaluator Runtime
runtime Target
target Bool
provider) NativeEvaluator -> IO (Either Error a)
action = Runtime -> (Runtime -> IO (Either Error a)) -> IO (Either Error a)
forall a.
Runtime -> (Runtime -> IO (Either Error a)) -> IO (Either Error a)
Runtime.withRetained Runtime
runtime ((Runtime -> IO (Either Error a)) -> IO (Either Error a))
-> (Runtime -> IO (Either Error a)) -> IO (Either Error a)
forall a b. (a -> b) -> a -> b
$ \Runtime
alias -> NativeEvaluator -> IO (Either Error a)
action (Runtime -> Target -> Bool -> NativeEvaluator
NativeEvaluator Runtime
alias Target
target Bool
provider)

close :: NativeEvaluator -> IO (Either Error ())
close :: NativeEvaluator -> IO (Either Error ())
close (NativeEvaluator Runtime
runtime Target
_ Bool
_) = Runtime -> IO (Either Error ())
Runtime.close Runtime
runtime

evaluate :: NativeEvaluator -> Tx.Transaction -> [Utxo.Utxo] -> IO (Either Error Evaluation.Budgets)
evaluate :: NativeEvaluator
-> Transaction -> [Utxo] -> IO (Either Error Budgets)
evaluate = Word32
-> NativeEvaluator
-> Transaction
-> [Utxo]
-> IO (Either Error Budgets)
evaluateRepeated Word32
1

evaluateRepeated :: Word32 -> NativeEvaluator -> Tx.Transaction -> [Utxo.Utxo] -> IO (Either Error Evaluation.Budgets)
evaluateRepeated :: Word32
-> NativeEvaluator
-> Transaction
-> [Utxo]
-> IO (Either Error Budgets)
evaluateRepeated Word32
count handle :: NativeEvaluator
handle@(NativeEvaluator Runtime
_ Target
target Bool
_) Transaction
transaction [Utxo]
resolved = case Target -> Transaction -> [Utxo] -> Either Error ()
Evaluation.validateRequest Target
target Transaction
transaction [Utxo]
resolved of
  Left Error
failure -> Either Error Budgets -> IO (Either Error Budgets)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error Budgets
forall a b. a -> Either a b
Left Error
failure)
  Right () -> do
    Either Error ByteString
result <- Word32
-> NativeEvaluator
-> ByteString
-> ByteString
-> IO (Either Error ByteString)
runUnchecked Word32
count NativeEvaluator
handle (Transaction -> ByteString
Tx.encodeCbor Transaction
transaction) ([Utxo] -> ByteString
encodeUtxos [Utxo]
resolved)
    Either Error Budgets -> IO (Either Error Budgets)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error Budgets -> IO (Either Error Budgets))
-> Either Error Budgets -> IO (Either Error Budgets)
forall a b. (a -> b) -> a -> b
$ do
      ByteString
bytes <- Either Error ByteString
result
      [Redeemer]
redeemers <- ByteString -> Either Error [Redeemer]
Redeemer.decodeCollectionCbor ByteString
bytes
      Target -> Transaction -> [Redeemer] -> Either Error Budgets
Evaluation.budgetsFromRedeemers Target
target Transaction
transaction [Redeemer]
redeemers

-- | Test-only malformed/reply and partial-cleanup injection boundary. Runtime
-- activation still encloses all native work and callbacks.
runUnchecked :: Word32 -> NativeEvaluator -> ByteString -> ByteString -> IO (Either Error ByteString)
runUnchecked :: Word32
-> NativeEvaluator
-> ByteString
-> ByteString
-> IO (Either Error ByteString)
runUnchecked Word32
count (NativeEvaluator Runtime
runtime Target
_ Bool
provider) ByteString
transaction ByteString
resolved = Runtime
-> (Ptr Context -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a.
Runtime
-> (Ptr Context -> IO (Either Error a)) -> IO (Either Error a)
Runtime.withOperation Runtime
runtime ((Ptr Context -> IO (Either Error ByteString))
 -> IO (Either Error ByteString))
-> (Ptr Context -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ \Ptr Context
context ->
  ByteString
-> (Ptr Word8 -> CSize -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a. ByteString -> (Ptr Word8 -> CSize -> IO a) -> IO a
Runtime.withBytes ByteString
transaction ((Ptr Word8 -> CSize -> IO (Either Error ByteString))
 -> IO (Either Error ByteString))
-> (Ptr Word8 -> CSize -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
txBytes CSize
txSize ->
    ByteString
-> (Ptr Word8 -> CSize -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a. ByteString -> (Ptr Word8 -> CSize -> IO a) -> IO a
Runtime.withBytes ByteString
resolved ((Ptr Word8 -> CSize -> IO (Either Error ByteString))
 -> IO (Either Error ByteString))
-> (Ptr Word8 -> CSize -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
utxoBytes CSize
utxoSize ->
      Text
-> (Ptr (Ptr Buffer) -> IO NativeCode)
-> IO (Either Error ByteString)
Runtime.withOwnedBuffer Text
"evaluation.evaluate" ((if Bool
provider then Ptr Context
-> Ptr Word8
-> CSize
-> Ptr Word8
-> CSize
-> Word32
-> Ptr (Ptr Buffer)
-> IO NativeCode
FFI.cRunProvider else Ptr Context
-> Ptr Word8
-> CSize
-> Ptr Word8
-> CSize
-> Word32
-> Ptr (Ptr Buffer)
-> IO NativeCode
FFI.cRun) Ptr Context
context Ptr Word8
txBytes CSize
txSize Ptr Word8
utxoBytes CSize
utxoSize Word32
count)

-- | Native serialization snapshots the complete native transaction. Its outer
-- frame may be definite even when the original input used an indefinite array;
-- existing exact body, script, argument and witness child encodings are retained.
dispatch :: Evaluation.Evaluator -> Evaluation.Target -> Runtime.Dispatch
dispatch :: Evaluator -> Target -> Dispatch
dispatch Evaluator
evaluator Target
target Word32
operation ByteString
input
  | Word32
operation Word32 -> Word32 -> Bool
forall a. Eq a => a -> a -> Bool
/= Word32
100 = Either Error ByteString -> IO (Either Error ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error ByteString
forall a b. a -> Either a b
Left (Text -> Error
UnsupportedOperation Text
"Unknown evaluator callback operation"))
  | Bool
otherwise = case ByteString -> Either Error (Transaction, [Utxo])
decodeRequest ByteString
input of
      Left Error
failure -> Either Error ByteString -> IO (Either Error ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error ByteString
forall a b. a -> Either a b
Left Error
failure)
      Right (Transaction
transaction, [Utxo]
resolved) -> do
        Either Error Budgets
result <- Evaluator
-> Target -> Transaction -> [Utxo] -> IO (Either Error Budgets)
Evaluation.evaluate Evaluator
evaluator Target
target Transaction
transaction [Utxo]
resolved
        Either Error ByteString -> IO (Either Error ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error ByteString -> IO (Either Error ByteString))
-> Either Error ByteString -> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ do
          Budgets
computed <- Either Error Budgets
result
          [Redeemer]
values <- Target -> Transaction -> Budgets -> Either Error [Redeemer]
Evaluation.checkedRedeemers Target
target Transaction
transaction Budgets
computed
          [Redeemer] -> Either Error ByteString
Redeemer.encodeCollectionCbor [Redeemer]
values

encodeUtxos :: [Utxo.Utxo] -> ByteString
encodeUtxos :: [Utxo] -> ByteString
encodeUtxos [Utxo]
values = Encoding -> ByteString
Cbor.encode (Word -> Encoding
E.encodeListLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([Utxo] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Utxo]
values)) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> (Utxo -> Encoding) -> [Utxo] -> Encoding
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (ByteString -> Encoding
Cbor.raw (ByteString -> Encoding)
-> (Utxo -> ByteString) -> Utxo -> Encoding
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Utxo -> ByteString
Utxo.encodeCbor) [Utxo]
values)

decodeRequest :: ByteString -> Either Error (Tx.Transaction, [Utxo.Utxo])
decodeRequest :: ByteString -> Either Error (Transaction, [Utxo])
decodeRequest ByteString
bytes = (Text -> Error)
-> (forall s. Decoder s (Transaction, [Utxo]))
-> ByteString
-> Either Error (Transaction, [Utxo])
forall a.
(Text -> Error)
-> (forall s. Decoder s a) -> ByteString -> Either Error a
Cbor.decodeAs Text -> Error
InvalidEvaluationRequest Decoder s (Transaction, [Utxo])
forall s. Decoder s (Transaction, [Utxo])
parser ByteString
bytes
  where
    parser :: Decoder s (Transaction, [Utxo])
parser = Int
-> Decoder s (Transaction, [Utxo])
-> Decoder s (Transaction, [Utxo])
forall s a. Int -> Decoder s a -> Decoder s a
Cbor.array Int
2 ((,) (Transaction -> [Utxo] -> (Transaction, [Utxo]))
-> Decoder s Transaction
-> Decoder s ([Utxo] -> (Transaction, [Utxo]))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString
-> (ByteString -> Either Error Transaction)
-> Decoder s Transaction
forall a s.
ByteString -> (ByteString -> Either Error a) -> Decoder s a
Cbor.nested ByteString
bytes ByteString -> Either Error Transaction
Tx.decodeCbor Decoder s ([Utxo] -> (Transaction, [Utxo]))
-> Decoder s [Utxo] -> Decoder s (Transaction, [Utxo])
forall a b. Decoder s (a -> b) -> Decoder s a -> Decoder s b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Decoder s Utxo -> Decoder s [Utxo]
forall s a. Decoder s a -> Decoder s [a]
Cbor.list (ByteString -> (ByteString -> Either Error Utxo) -> Decoder s Utxo
forall a s.
ByteString -> (ByteString -> Either Error a) -> Decoder s a
Cbor.nested ByteString
bytes ByteString -> Either Error Utxo
Utxo.decodeCbor))