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

-- | Each invocation owns a distinct evaluator and parsed transaction snapshot.
-- Safe synchronous C return encloses every native owner, including cancellation.
module Cometa.Internal.Evaluation.Native (Config (..), evaluator, runUnchecked) where

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

import qualified Codec.CBOR.Encoding as E
import Cometa.Error (Error (..))
import qualified Cometa.Error.Code as Code
import qualified Cometa.Internal.Evaluation as Evaluation
import qualified Cometa.Internal.FFI.Native as Status
import qualified Cometa.Internal.FFI.NativeEvaluation as FFI
import qualified Cometa.Internal.FFI.Runtime as Raw
import qualified Cometa.Internal.Runtime as Runtime
import qualified Cometa.Internal.TransactionCbor as Cbor
import qualified Cometa.Protocol.CostModels as Models
import qualified Cometa.SlotConfig as Slots
import qualified Cometa.SubTransaction as Sub
import qualified Cometa.SubTransaction.Body as SubBody
import qualified Cometa.Transaction as Tx
import qualified Cometa.Transaction.Body as Body
import qualified Cometa.Transaction.Fields as Fields
import qualified Cometa.Transaction.Redeemer as Redeemer
import qualified Cometa.Transaction.Utxo as Utxo
import Control.Exception (bracket)
import Control.Monad (unless)
import Data.ByteString (ByteString)
import Data.Foldable (traverse_)
import Data.Maybe (fromMaybe)
import qualified Data.Set as Set
import qualified Data.Text.Encoding as Text
import Data.Word (Word64)
import Foreign.Marshal.Alloc (alloca)
import Foreign.Ptr (Ptr, nullPtr)
import Foreign.Storable (peek, poke)

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

-- | Native evaluator context. The schedule applies to every validity interval;
-- the protocol major selects language and builtin availability. Missing cost
-- models use the built-in per-version defaults. This is phase-2 execution,
-- not a check that the complete transaction is admissible on chain.
data Config = Config
  { -- | Constant-duration schedule, in Unix milliseconds.
    Config -> SlotConfig
slotConfig :: !Slots.SlotConfig,
    -- | Ledger protocol major version (minor versions do not affect this VM).
    Config -> Word64
protocolMajor :: !Word64,
    -- | Ledger coefficients keyed by language id; empty selects VM defaults.
    Config -> CostModels
costModels :: !Models.CostModels
  }
  deriving (Config -> Config -> Bool
(Config -> Config -> Bool)
-> (Config -> Config -> Bool) -> Eq Config
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Config -> Config -> Bool
== :: Config -> Config -> Bool
$c/= :: Config -> Config -> Bool
/= :: Config -> Config -> Bool
Eq, Int -> Config -> ShowS
[Config] -> ShowS
Config -> String
(Int -> Config -> ShowS)
-> (Config -> String) -> ([Config] -> ShowS) -> Show Config
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Config -> ShowS
showsPrec :: Int -> Config -> ShowS
$cshow :: Config -> String
show :: Config -> String
$cshowList :: [Config] -> ShowS
showList :: [Config] -> ShowS
Show)

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

-- | Construct an injectable evaluator. Every target evaluates all levels: a
-- failure in any level fails the request, and execution consumes a shared limit
-- of 100,000,000 memory units and 100,000,000,000 CPU steps. The target selects
-- only which level's budgets are returned. No transaction bytes are changed.
--
-- All spending and reference inputs at every level must resolve exactly once;
-- extra resolved UTxOs are allowed. Validity bounds must fit the supplied slot
-- schedule. No scripts returns empty budgets after these checks.
evaluator :: Config -> Evaluation.Evaluator
evaluator :: Config -> Evaluator
evaluator Config
config = (Target -> Transaction -> [Utxo] -> IO (Either Error Budgets))
-> Evaluator
Evaluation.Evaluator ((Target -> Transaction -> [Utxo] -> IO (Either Error Budgets))
 -> Evaluator)
-> (Target -> Transaction -> [Utxo] -> IO (Either Error Budgets))
-> Evaluator
forall a b. (a -> b) -> a -> b
$ \Target
target Transaction
transaction [Utxo]
resolved -> case Config -> Target -> Transaction -> [Utxo] -> Either Error ()
validate Config
config 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 <- Config
-> Target
-> ByteString
-> ByteString
-> IO (Either Error ByteString)
runUnchecked Config
config Target
target (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]
returned <- ByteString -> Either Error [Redeemer]
Redeemer.decodeCollectionCbor ByteString
bytes
      Target -> Transaction -> [Redeemer] -> Either Error Budgets
Evaluation.budgetsFromRedeemers Target
target Transaction
transaction [Redeemer]
returned

validate :: Config -> Evaluation.Target -> Tx.Transaction -> [Utxo.Utxo] -> Either Error ()
validate :: Config -> Target -> Transaction -> [Utxo] -> Either Error ()
validate Config
config Target
target Transaction
transaction [Utxo]
resolved = do
  Target -> Transaction -> [Utxo] -> Either Error ()
Evaluation.validateRequest Target
target Transaction
transaction [Utxo]
resolved
  (Fields -> Either Error ()) -> [Fields] -> Either Error ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ Fields -> Either Error ()
checkLevel [Fields]
levels
  where
    body :: Body
body = EncodedBody -> Body
Body.toBody (Transaction -> EncodedBody
Tx.body Transaction
transaction)
    levels :: [Fields]
levels = Body -> Fields
Body.bodyFields Body
body Fields -> [Fields] -> [Fields]
forall a. a -> [a] -> [a]
: [Fields]
-> ([SubTransaction] -> [Fields])
-> Maybe [SubTransaction]
-> [Fields]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] ((SubTransaction -> Fields) -> [SubTransaction] -> [Fields]
forall a b. (a -> b) -> [a] -> [b]
map (Body -> Fields
SubBody.fields (Body -> Fields)
-> (SubTransaction -> Body) -> SubTransaction -> Fields
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EncodedBody -> Body
SubBody.toBody (EncodedBody -> Body)
-> (SubTransaction -> EncodedBody) -> SubTransaction -> Body
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SubTransaction -> EncodedBody
Sub.body)) (Body -> Maybe [SubTransaction]
Body.bodySubTransactions Body
body)
    available :: Set Input
available = [Input] -> Set Input
forall a. Ord a => [a] -> Set a
Set.fromList ((Utxo -> Input) -> [Utxo] -> [Input]
forall a b. (a -> b) -> [a] -> [b]
map Utxo -> Input
Utxo.input [Utxo]
resolved)
    checkLevel :: Fields -> Either Error ()
checkLevel Fields
fields = do
      let required :: [Input]
required = Fields -> [Input]
Fields.fieldInputs Fields
fields [Input] -> [Input] -> [Input]
forall a. [a] -> [a] -> [a]
++ [Input] -> Maybe [Input] -> [Input]
forall a. a -> Maybe a -> a
fromMaybe [] (Fields -> Maybe [Input]
Fields.fieldReferenceInputs Fields
fields)
      Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ((Input -> Bool) -> [Input] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (Input -> Set Input -> Bool
forall a. Ord a => a -> Set a -> Bool
`Set.member` Set Input
available) [Input]
required) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidEvaluationRequest Text
"All spending and reference inputs must resolve"))
      (Word64 -> Either Error Word64) -> Maybe Word64 -> Either Error ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ (SlotConfig -> Word64 -> Either Error Word64
Slots.slotToTime (Config -> SlotConfig
slotConfig Config
config)) (Fields -> Maybe Word64
Fields.fieldInvalidBefore Fields
fields)
      (Word64 -> Either Error Word64) -> Maybe Word64 -> Either Error ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ (SlotConfig -> Word64 -> Either Error Word64
Slots.slotToTime (Config -> SlotConfig
slotConfig Config
config)) (Fields -> Maybe Word64
Fields.fieldInvalidAfter Fields
fields)

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)

-- | Internal malformed transport boundary for partial-cleanup tests.
runUnchecked :: Config -> Evaluation.Target -> ByteString -> ByteString -> IO (Either Error ByteString)
runUnchecked :: Config
-> Target
-> ByteString
-> ByteString
-> IO (Either Error ByteString)
runUnchecked Config
config Target
target ByteString
transaction ByteString
resolved =
  ByteString
-> (Ptr Word8 -> CSize -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a. ByteString -> (Ptr Word8 -> CSize -> IO a) -> IO a
Runtime.withBytes (CostModels -> ByteString
Models.encodeCbor (Config -> CostModels
costModels Config
config)) ((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
models CSize
modelsSize ->
    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
tx 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
utxos CSize
utxosSize ->
        (Ptr (Ptr Buffer) -> Ptr (Ptr Buffer) -> IO NativeCode)
-> IO (Either Error ByteString)
withResult (Word64
-> Word64
-> Word64
-> Word64
-> NativeCode
-> Word64
-> Ptr Word8
-> CSize
-> Ptr Word8
-> CSize
-> Ptr Word8
-> CSize
-> Ptr (Ptr Buffer)
-> Ptr (Ptr Buffer)
-> IO NativeCode
FFI.cRun (SlotConfig -> Word64
Slots.zeroTime SlotConfig
slots) (SlotConfig -> Word64
Slots.zeroSlot SlotConfig
slots) (SlotConfig -> Word64
Slots.slotLength SlotConfig
slots) (Config -> Word64
protocolMajor Config
config) NativeCode
isSub Word64
index Ptr Word8
models CSize
modelsSize Ptr Word8
tx CSize
txSize Ptr Word8
utxos CSize
utxosSize)
  where
    slots :: SlotConfig
slots = Config -> SlotConfig
slotConfig Config
config
    (NativeCode
isSub, Word64
index) = case Target
target of
      Target
Evaluation.TopLevel -> (NativeCode
0, Word64
0)
      Evaluation.SubTransaction Word64
position -> (NativeCode
1, Word64
position)

-- Both slots initialize under mask and release after copying on every path.
withResult :: (Ptr (Ptr Raw.Buffer) -> Ptr (Ptr Raw.Buffer) -> IO Status.NativeCode) -> IO (Either Error ByteString)
withResult :: (Ptr (Ptr Buffer) -> Ptr (Ptr Buffer) -> IO NativeCode)
-> IO (Either Error ByteString)
withResult Ptr (Ptr Buffer) -> Ptr (Ptr Buffer) -> IO NativeCode
call = (Ptr (Ptr Buffer) -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. Storable a => (Ptr a -> IO b) -> IO b
alloca ((Ptr (Ptr Buffer) -> IO (Either Error ByteString))
 -> IO (Either Error ByteString))
-> (Ptr (Ptr Buffer) -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ \Ptr (Ptr Buffer)
output -> (Ptr (Ptr Buffer) -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. Storable a => (Ptr a -> IO b) -> IO b
alloca ((Ptr (Ptr Buffer) -> IO (Either Error ByteString))
 -> IO (Either Error ByteString))
-> (Ptr (Ptr Buffer) -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ \Ptr (Ptr Buffer)
diagnostic ->
  IO ()
-> (() -> IO ())
-> (() -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracket
    (Ptr (Ptr Buffer) -> Ptr Buffer -> IO ()
forall a. Storable a => Ptr a -> a -> IO ()
poke Ptr (Ptr Buffer)
output Ptr Buffer
forall a. Ptr a
nullPtr IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Ptr (Ptr Buffer) -> Ptr Buffer -> IO ()
forall a. Storable a => Ptr a -> a -> IO ()
poke Ptr (Ptr Buffer)
diagnostic Ptr Buffer
forall a. Ptr a
nullPtr)
    (\() -> Ptr (Ptr Buffer) -> IO ()
Raw.cBufferRelease Ptr (Ptr Buffer)
output IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Ptr (Ptr Buffer) -> IO ()
Raw.cBufferRelease Ptr (Ptr Buffer)
diagnostic)
    ((() -> IO (Either Error ByteString))
 -> IO (Either Error ByteString))
-> (() -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ \() -> do
      NativeCode
status <- Ptr (Ptr Buffer) -> Ptr (Ptr Buffer) -> IO NativeCode
call Ptr (Ptr Buffer)
output Ptr (Ptr Buffer)
diagnostic
      if NativeCode
status NativeCode -> NativeCode -> Bool
forall a. Eq a => a -> a -> Bool
== NativeCode
Status.success
        then Ptr (Ptr Buffer) -> IO (Ptr Buffer)
forall a. Storable a => Ptr a -> IO a
peek Ptr (Ptr Buffer)
output IO (Ptr Buffer)
-> (Ptr Buffer -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Text -> Ptr Buffer -> IO (Either Error ByteString)
Runtime.copyBuffer Text
"evaluation.native"
        else do
          Ptr Buffer
pointer <- Ptr (Ptr Buffer) -> IO (Ptr Buffer)
forall a. Storable a => Ptr a -> IO a
peek Ptr (Ptr Buffer)
diagnostic
          if Ptr Buffer
pointer Ptr Buffer -> Ptr Buffer -> Bool
forall a. Eq a => a -> a -> Bool
== Ptr Buffer
forall a. Ptr a
nullPtr
            then do
              Either Error ()
checked <- Text -> NativeCode -> IO (Either Error ())
Runtime.checkStatus Text
"evaluation.native" NativeCode
status
              Either Error ByteString -> IO (Either Error ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error ()
checked Either Error ()
-> Either Error ByteString -> Either Error ByteString
forall a b. Either Error a -> Either Error b -> Either Error b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Error -> Either Error ByteString
forall a b. a -> Either a b
Left (Text -> Error
NativeContractViolation Text
"evaluation.native.status"))
            else do
              Either Error ByteString
copied <- Text -> Ptr Buffer -> IO (Either Error ByteString)
Runtime.copyBuffer Text
"evaluation.native.diagnostic" Ptr Buffer
pointer
              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
$ case Either Error ByteString
copied of
                Left Error
failure -> Error -> Either Error ByteString
forall a b. a -> Either a b
Left Error
failure
                Right ByteString
bytes -> Error -> Either Error ByteString
forall a b. a -> Either a b
Left (Text -> ErrorCode -> Text -> Error
NativeError Text
"evaluation.native" (Integer -> ErrorCode
Code.fromNumber (NativeCode -> Integer
forall a. Integral a => a -> Integer
toInteger NativeCode
status)) (OnDecodeError -> ByteString -> Text
Text.decodeUtf8With (\String
_ Maybe Word8
_ -> Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'\xfffd') ByteString
bytes))