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

-- | Versioned compiled Plutus scripts with exact byte identity. Compiled bytes
-- usually contain one CBOR bytestring around Flat code; script CBOR adds another
-- bytestring layer. Import never guesses or removes a layer. Raw-byte import
-- checks nonemptiness; CBOR import also checks outer framing. Neither checks
-- whether code is executable for its version.
--
-- @
-- import qualified Cometa.Script.Plutus as Plutus
-- import qualified Data.ByteString as ByteString
--
-- script = Plutus.fromBytes Plutus.V3 (ByteString.pack [0x45, 1, 0, 0, 0x24, 0x99])
-- @
module Cometa.Script.Plutus
  ( -- * Compiled scripts
    Version (..),
    PlutusScript,
    fromBytes,
    toBytes,
    version,

    -- * Script CBOR
    encodeCbor,
    decodeCbor,

    -- * Hashing and parameter application
    hash,
    applyParams,
  )
where

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

import qualified Codec.CBOR.Decoding as Decode
import qualified Codec.CBOR.Encoding as Encode
import qualified Codec.CBOR.Read as Read
import qualified Codec.CBOR.Write as Write
import Cometa.Credential (ScriptHash)
import qualified Cometa.Credential as Credential
import qualified Cometa.Crypto.Blake2b as Blake2b
import Cometa.Error (Error (..))
import Cometa.Internal.Error (fromNativeFailure)
import qualified Cometa.Internal.FFI.Cbor as Buffer
import qualified Cometa.Internal.FFI.Script as Native
import Cometa.Internal.Failure (NativeFailure (..))
import Cometa.Internal.Ownership (copyStaticText, withOwnedOutput)
import Cometa.PlutusData (PlutusData)
import qualified Cometa.PlutusData as PlutusData
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Lazy as Lazy
import qualified Data.Text as Text
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Ptr (castPtr, nullPtr)
import Foreign.Storable (poke)

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

-- | Ledger language version; ordering follows version number. Availability
-- depends on the ledger era; this type does not assert deployment support.
data Version = V1 | V2 | V3 | V4
  deriving (Version -> Version -> Bool
(Version -> Version -> Bool)
-> (Version -> Version -> Bool) -> Eq Version
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Version -> Version -> Bool
== :: Version -> Version -> Bool
$c/= :: Version -> Version -> Bool
/= :: Version -> Version -> Bool
Eq, Eq Version
Eq Version =>
(Version -> Version -> Ordering)
-> (Version -> Version -> Bool)
-> (Version -> Version -> Bool)
-> (Version -> Version -> Bool)
-> (Version -> Version -> Bool)
-> (Version -> Version -> Version)
-> (Version -> Version -> Version)
-> Ord Version
Version -> Version -> Bool
Version -> Version -> Ordering
Version -> Version -> Version
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: Version -> Version -> Ordering
compare :: Version -> Version -> Ordering
$c< :: Version -> Version -> Bool
< :: Version -> Version -> Bool
$c<= :: Version -> Version -> Bool
<= :: Version -> Version -> Bool
$c> :: Version -> Version -> Bool
> :: Version -> Version -> Bool
$c>= :: Version -> Version -> Bool
>= :: Version -> Version -> Bool
$cmax :: Version -> Version -> Version
max :: Version -> Version -> Version
$cmin :: Version -> Version -> Version
min :: Version -> Version -> Version
Ord, Int -> Version -> ShowS
[Version] -> ShowS
Version -> String
(Int -> Version -> ShowS)
-> (Version -> String) -> ([Version] -> ShowS) -> Show Version
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Version -> ShowS
showsPrec :: Int -> Version -> ShowS
$cshow :: Version -> String
show :: Version -> String
$cshowList :: [Version] -> ShowS
showList :: [Version] -> ShowS
Show, Int -> Version
Version -> Int
Version -> [Version]
Version -> Version
Version -> Version -> [Version]
Version -> Version -> Version -> [Version]
(Version -> Version)
-> (Version -> Version)
-> (Int -> Version)
-> (Version -> Int)
-> (Version -> [Version])
-> (Version -> Version -> [Version])
-> (Version -> Version -> [Version])
-> (Version -> Version -> Version -> [Version])
-> Enum Version
forall a.
(a -> a)
-> (a -> a)
-> (Int -> a)
-> (a -> Int)
-> (a -> [a])
-> (a -> a -> [a])
-> (a -> a -> [a])
-> (a -> a -> a -> [a])
-> Enum a
$csucc :: Version -> Version
succ :: Version -> Version
$cpred :: Version -> Version
pred :: Version -> Version
$ctoEnum :: Int -> Version
toEnum :: Int -> Version
$cfromEnum :: Version -> Int
fromEnum :: Version -> Int
$cenumFrom :: Version -> [Version]
enumFrom :: Version -> [Version]
$cenumFromThen :: Version -> Version -> [Version]
enumFromThen :: Version -> Version -> [Version]
$cenumFromTo :: Version -> Version -> [Version]
enumFromTo :: Version -> Version -> [Version]
$cenumFromThenTo :: Version -> Version -> Version -> [Version]
enumFromThenTo :: Version -> Version -> Version -> [Version]
Enum, Version
Version -> Version -> Bounded Version
forall a. a -> a -> Bounded a
$cminBound :: Version
minBound :: Version
$cmaxBound :: Version
maxBound :: Version
Bounded)

-- | Nonempty immutable compiled bytes and their version, with the exact outer
-- script CBOR preserved on import. Equality compares version and outer encoding;
-- ordering is version first, then lexicographic encoding. 'Show' is diagnostic.
data PlutusScript = PlutusScript !Version !ByteString !ByteString
  deriving (Int -> PlutusScript -> ShowS
[PlutusScript] -> ShowS
PlutusScript -> String
(Int -> PlutusScript -> ShowS)
-> (PlutusScript -> String)
-> ([PlutusScript] -> ShowS)
-> Show PlutusScript
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PlutusScript -> ShowS
showsPrec :: Int -> PlutusScript -> ShowS
$cshow :: PlutusScript -> String
show :: PlutusScript -> String
$cshowList :: [PlutusScript] -> ShowS
showList :: [PlutusScript] -> ShowS
Show)

instance Eq PlutusScript where
  PlutusScript
left == :: PlutusScript -> PlutusScript -> Bool
== PlutusScript
right = PlutusScript -> Version
version PlutusScript
left Version -> Version -> Bool
forall a. Eq a => a -> a -> Bool
== PlutusScript -> Version
version PlutusScript
right Bool -> Bool -> Bool
&& PlutusScript -> ByteString
encodeCbor PlutusScript
left ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== PlutusScript -> ByteString
encodeCbor PlutusScript
right

instance Ord PlutusScript where
  compare :: PlutusScript -> PlutusScript -> Ordering
compare PlutusScript
left PlutusScript
right = (Version, ByteString) -> (Version, ByteString) -> Ordering
forall a. Ord a => a -> a -> Ordering
compare (PlutusScript -> Version
version PlutusScript
left, PlutusScript -> ByteString
encodeCbor PlutusScript
left) (PlutusScript -> Version
version PlutusScript
right, PlutusScript -> ByteString
encodeCbor PlutusScript
right)

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

-- | Import opaque compiled bytes without decoding or normalizing their contents.
-- Empty input returns 'EmptyPlutusScript'. Executability is checked only when a
-- VM operation such as 'applyParams' decodes the program.
fromBytes :: Version -> ByteString -> Either Error PlutusScript
fromBytes :: Version -> ByteString -> Either Error PlutusScript
fromBytes Version
language ByteString
bytes
  | ByteString -> Bool
ByteString.null ByteString
bytes = Error -> Either Error PlutusScript
forall a b. a -> Either a b
Left Error
EmptyPlutusScript
  | Bool
otherwise = PlutusScript -> Either Error PlutusScript
forall a b. b -> Either a b
Right (Version -> ByteString -> ByteString -> PlutusScript
PlutusScript Version
language ByteString
bytes (Encoding -> ByteString
Write.toStrictByteString (ByteString -> Encoding
Encode.encodeBytes ByteString
bytes)))

-- | Exact compiled bytes, excluding the outer script CBOR bytestring layer.
toBytes :: PlutusScript -> ByteString
toBytes :: PlutusScript -> ByteString
toBytes (PlutusScript Version
_ ByteString
bytes ByteString
_) = ByteString
bytes

-- | The declared ledger language version.
version :: PlutusScript -> Version
version :: PlutusScript -> Version
version (PlutusScript Version
language ByteString
_ ByteString
_) = Version
language

-- | Encode the outer script bytestring. Imported encodings retain their exact
-- form, including nonminimal lengths and indefinite chunks. Compiled bytes are
-- never normalized by this operation.
encodeCbor :: PlutusScript -> ByteString
encodeCbor :: PlutusScript -> ByteString
encodeCbor (PlutusScript Version
_ ByteString
_ ByteString
encoded) = ByteString
encoded

-- | Decode exactly one nonempty outer bytestring for the supplied version.
-- Malformed, trailing or schema-invalid input returns 'InvalidScriptCbor'; an
-- empty payload returns 'EmptyPlutusScript'. Both outer and compiled bytes retain
-- their identity; this operation does not decode executable Flat code.
decodeCbor :: Version -> ByteString -> Either Error PlutusScript
decodeCbor :: Version -> ByteString -> Either Error PlutusScript
decodeCbor Version
language ByteString
encoded = case (forall s. Decoder s ByteString)
-> ByteString -> Either DeserialiseFailure (ByteString, ByteString)
forall a.
(forall s. Decoder s a)
-> ByteString -> Either DeserialiseFailure (ByteString, a)
Read.deserialiseFromBytes Decoder s ByteString
forall s. Decoder s ByteString
decodeBytes (ByteString -> ByteString
Lazy.fromStrict ByteString
encoded) of
  Left DeserialiseFailure
failure -> Error -> Either Error PlutusScript
forall a b. a -> Either a b
Left (Text -> Error
InvalidScriptCbor (String -> Text
Text.pack (DeserialiseFailure -> String
forall a. Show a => a -> String
show DeserialiseFailure
failure)))
  Right (ByteString
trailing, ByteString
bytes)
    | Bool -> Bool
not (ByteString -> Bool
Lazy.null ByteString
trailing) -> Error -> Either Error PlutusScript
forall a b. a -> Either a b
Left (Text -> Error
InvalidScriptCbor Text
"Trailing bytes after Plutus script")
    | ByteString -> Bool
ByteString.null ByteString
bytes -> Error -> Either Error PlutusScript
forall a b. a -> Either a b
Left Error
EmptyPlutusScript
    | Bool
otherwise -> PlutusScript -> Either Error PlutusScript
forall a b. b -> Either a b
Right (Version -> ByteString -> ByteString -> PlutusScript
PlutusScript Version
language ByteString
bytes ByteString
encoded)

-- | Compute BLAKE2b-224 over the version prefix (1 through 4) followed by exact
-- compiled bytes. The outer script encoding does not participate in the hash.
-- Native hashing failures return 'Cometa.Error.NativeError'.
hash :: PlutusScript -> IO (Either Error ScriptHash)
hash :: PlutusScript -> IO (Either Error ScriptHash)
hash PlutusScript
script = do
  Either Error Blake2bHash
result <- Int -> ByteString -> IO (Either Error Blake2bHash)
Blake2b.compute Int
28 (Word8 -> ByteString -> ByteString
ByteString.cons (Int -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Version -> Int
forall a. Enum a => a -> Int
fromEnum (PlutusScript -> Version
version PlutusScript
script) Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)) (PlutusScript -> ByteString
toBytes PlutusScript
script))
  Either Error ScriptHash -> IO (Either Error ScriptHash)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error Blake2bHash
result Either Error Blake2bHash
-> (Blake2bHash -> Either Error ScriptHash)
-> Either Error ScriptHash
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 ScriptHash
Credential.scriptHashFromBytes (ByteString -> Either Error ScriptHash)
-> (Blake2bHash -> ByteString)
-> Blake2bHash
-> Either Error ScriptHash
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Blake2bHash -> ByteString
Blake2b.toBytes)

-- | Decode a single-CBOR-wrapped Flat program, apply data constants in list
-- order, and serialize a new program with the same declared language version.
-- The first parameter is the innermost application. Even an empty list invokes
-- the VM and can normalize a noncanonical program encoding. The original script
-- is unchanged. Malformed programs or native failures return 'NativeError'.
-- This operation checks program decoding, not ledger-era or language validity.
applyParams :: PlutusScript -> [PlutusData] -> IO (Either Error PlutusScript)
applyParams :: PlutusScript -> [PlutusData] -> IO (Either Error PlutusScript)
applyParams PlutusScript
script [PlutusData]
parameters =
  ByteString
-> (CStringLen -> IO (Either Error PlutusScript))
-> IO (Either Error PlutusScript)
forall a. ByteString -> (CStringLen -> IO a) -> IO a
ByteString.useAsCStringLen (PlutusScript -> ByteString
toBytes PlutusScript
script) ((CStringLen -> IO (Either Error PlutusScript))
 -> IO (Either Error PlutusScript))
-> (CStringLen -> IO (Either Error PlutusScript))
-> IO (Either Error PlutusScript)
forall a b. (a -> b) -> a -> b
$ \(Ptr CChar
code, Int
codeSize) ->
    ByteString
-> (CStringLen -> IO (Either Error PlutusScript))
-> IO (Either Error PlutusScript)
forall a. ByteString -> (CStringLen -> IO a) -> IO a
ByteString.useAsCStringLen (PlutusData -> ByteString
PlutusData.encodeCbor ([PlutusData] -> PlutusData
PlutusData.List [PlutusData]
parameters)) ((CStringLen -> IO (Either Error PlutusScript))
 -> IO (Either Error PlutusScript))
-> (CStringLen -> IO (Either Error PlutusScript))
-> IO (Either Error PlutusScript)
forall a b. (a -> b) -> a -> b
$ \(Ptr CChar
params, Int
paramsSize) ->
      Int
-> (Ptr CChar -> IO (Either Error PlutusScript))
-> IO (Either Error PlutusScript)
forall a b. Int -> (Ptr a -> IO b) -> IO b
allocaBytes Int
1024 ((Ptr CChar -> IO (Either Error PlutusScript))
 -> IO (Either Error PlutusScript))
-> (Ptr CChar -> IO (Either Error PlutusScript))
-> IO (Either Error PlutusScript)
forall a b. (a -> b) -> a -> b
$ \Ptr CChar
diagnostic -> do
        Ptr CChar -> CChar -> IO ()
forall a. Storable a => Ptr a -> a -> IO ()
poke Ptr CChar
diagnostic CChar
0
        Either NativeFailure ByteString
result <-
          Text
-> (Ptr (Ptr NativeBuffer) -> IO ())
-> (Ptr (Ptr NativeBuffer) -> IO NativeCode)
-> (Ptr NativeBuffer -> IO (Either NativeFailure ByteString))
-> IO (Either NativeFailure ByteString)
forall native value.
Text
-> (Ptr (Ptr native) -> IO ())
-> (Ptr (Ptr native) -> IO NativeCode)
-> (Ptr native -> IO (Either NativeFailure value))
-> IO (Either NativeFailure value)
withOwnedOutput
            Text
"script.applyParams"
            Ptr (Ptr NativeBuffer) -> IO ()
Buffer.cBufferUnref
            (\Ptr (Ptr NativeBuffer)
output -> Ptr Word8
-> CSize
-> Ptr Word8
-> CSize
-> Ptr (Ptr NativeBuffer)
-> Ptr CChar
-> CSize
-> IO NativeCode
Native.cApplyParams (Ptr CChar -> Ptr Word8
forall a b. Ptr a -> Ptr b
castPtr Ptr CChar
code) (Int -> CSize
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
codeSize) (Ptr CChar -> Ptr Word8
forall a b. Ptr a -> Ptr b
castPtr Ptr CChar
params) (Int -> CSize
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
paramsSize) Ptr (Ptr NativeBuffer)
output Ptr CChar
diagnostic CSize
1024)
            Ptr NativeBuffer -> IO (Either NativeFailure ByteString)
copyBuffer
        case Either NativeFailure ByteString
result of
          Right ByteString
bytes -> Either Error PlutusScript -> IO (Either Error PlutusScript)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Version -> ByteString -> Either Error PlutusScript
fromBytes (PlutusScript -> Version
version PlutusScript
script) ByteString
bytes)
          Left failure :: NativeFailure
failure@(NativeContractFailure Text
_) -> Either Error PlutusScript -> IO (Either Error PlutusScript)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error PlutusScript
forall a b. a -> Either a b
Left (NativeFailure -> Error
fromNativeFailure NativeFailure
failure))
          Left (NativeFailure Text
operation Integer
status Text
fallback) -> do
            Text
message <- Ptr CChar -> IO Text
copyStaticText Ptr CChar
diagnostic
            Either Error PlutusScript -> IO (Either Error PlutusScript)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error PlutusScript
forall a b. a -> Either a b
Left (NativeFailure -> Error
fromNativeFailure (Text -> Integer -> Text -> NativeFailure
NativeFailure Text
operation Integer
status (if Text -> Bool
Text.null Text
message then Text
fallback else Text
message))))
  where
    -- Copy borrowed result storage before the scoped buffer is released; no
    -- native storage or arena-backed values survive this operation.
    copyBuffer :: Ptr NativeBuffer -> IO (Either NativeFailure ByteString)
copyBuffer Ptr NativeBuffer
buffer = do
      CSize
size <- Ptr NativeBuffer -> IO CSize
Buffer.cBufferSize Ptr NativeBuffer
buffer
      Ptr Word8
bytes <- Ptr NativeBuffer -> IO (Ptr Word8)
Buffer.cBufferData Ptr NativeBuffer
buffer
      if Ptr Word8
bytes Ptr Word8 -> Ptr Word8 -> Bool
forall a. Eq a => a -> a -> Bool
== Ptr Word8
forall a. Ptr a
nullPtr Bool -> Bool -> Bool
|| CSize
size CSize -> CSize -> Bool
forall a. Eq a => a -> a -> Bool
== CSize
0 Bool -> Bool -> Bool
|| CSize -> Integer
forall a. Integral a => a -> Integer
toInteger CSize
size Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Int
forall a. Bounded a => a
maxBound :: Int)
        then Either NativeFailure ByteString
-> IO (Either NativeFailure ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (NativeFailure -> Either NativeFailure ByteString
forall a b. a -> Either a b
Left (Text -> NativeFailure
NativeContractFailure Text
"script.applyParams"))
        else ByteString -> Either NativeFailure ByteString
forall a b. b -> Either a b
Right (ByteString -> Either NativeFailure ByteString)
-> IO ByteString -> IO (Either NativeFailure ByteString)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> CStringLen -> IO ByteString
ByteString.packCStringLen (Ptr Word8 -> Ptr CChar
forall a b. Ptr a -> Ptr b
castPtr Ptr Word8
bytes, CSize -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral CSize
size)

decodeBytes :: Decode.Decoder s ByteString
decodeBytes :: forall s. Decoder s ByteString
decodeBytes = do
  TokenType
token <- Decoder s TokenType
forall s. Decoder s TokenType
Decode.peekTokenType
  if TokenType
token TokenType -> TokenType -> Bool
forall a. Eq a => a -> a -> Bool
== TokenType
Decode.TypeBytesIndef
    then do
      Decoder s ()
forall s. Decoder s ()
Decode.decodeBytesIndef
      [ByteString] -> Decoder s ByteString
forall {s}. [ByteString] -> Decoder s ByteString
loop []
    else Decoder s ByteString
forall s. Decoder s ByteString
Decode.decodeBytes
  where
    loop :: [ByteString] -> Decoder s ByteString
loop [ByteString]
accumulated = do
      Bool
ended <- Decoder s Bool
forall s. Decoder s Bool
Decode.decodeBreakOr
      if Bool
ended
        then ByteString -> Decoder s ByteString
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([ByteString] -> ByteString
ByteString.concat ([ByteString] -> [ByteString]
forall a. [a] -> [a]
reverse [ByteString]
accumulated))
        else do
          ByteString
chunk <- Decoder s ByteString
forall s. Decoder s ByteString
Decode.decodeBytes
          [ByteString] -> Decoder s ByteString
loop (ByteString
chunk ByteString -> [ByteString] -> [ByteString]
forall a. a -> [a] -> [a]
: [ByteString]
accumulated)