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

-- | Native and versioned Plutus script alternatives. The combined CBOR form is
-- @[language, payload]@, where native is zero and Plutus versions are 1 through 4.
-- The envelope is normalized on encoding; each payload retains its exact bytes,
-- which determine script identity and hashing.
--
-- @
-- import qualified Cometa.Script as Script
-- import qualified Cometa.Script.Native as Native
--
-- script :: Script.Script
-- script = Script.Native (Native.allOf [])
-- @
module Cometa.Script
  ( Script (..),
    encodeCbor,
    decodeCbor,
    hash,
  )
where

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

import qualified Codec.CBOR.Decoding as Decode
import qualified Codec.CBOR.Encoding as Encode
import qualified Codec.CBOR.Read as Read
import Codec.CBOR.Term (decodeTerm)
import qualified Codec.CBOR.Write as Write
import Cometa.Credential (ScriptHash)
import Cometa.Error (Error (..))
import qualified Cometa.Script.Native as Native
import qualified Cometa.Script.Plutus as Plutus
import Control.Monad (unless)
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Lazy as Lazy
import qualified Data.Text as Text

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

-- | Script alternatives with Haskell-owned payloads. Equality and ordering
-- compare the alternative then its payload representation; native comes first.
data Script
  = -- | A signature/time/guard native script.
    Native !Native.NativeScript
  | -- | A compiled Plutus script carrying its language version.
    Plutus !Plutus.PlutusScript
  deriving (Script -> Script -> Bool
(Script -> Script -> Bool)
-> (Script -> Script -> Bool) -> Eq Script
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Script -> Script -> Bool
== :: Script -> Script -> Bool
$c/= :: Script -> Script -> Bool
/= :: Script -> Script -> Bool
Eq, Eq Script
Eq Script =>
(Script -> Script -> Ordering)
-> (Script -> Script -> Bool)
-> (Script -> Script -> Bool)
-> (Script -> Script -> Bool)
-> (Script -> Script -> Bool)
-> (Script -> Script -> Script)
-> (Script -> Script -> Script)
-> Ord Script
Script -> Script -> Bool
Script -> Script -> Ordering
Script -> Script -> Script
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 :: Script -> Script -> Ordering
compare :: Script -> Script -> Ordering
$c< :: Script -> Script -> Bool
< :: Script -> Script -> Bool
$c<= :: Script -> Script -> Bool
<= :: Script -> Script -> Bool
$c> :: Script -> Script -> Bool
> :: Script -> Script -> Bool
$c>= :: Script -> Script -> Bool
>= :: Script -> Script -> Bool
$cmax :: Script -> Script -> Script
max :: Script -> Script -> Script
$cmin :: Script -> Script -> Script
min :: Script -> Script -> Script
Ord, Int -> Script -> ShowS
[Script] -> ShowS
Script -> String
(Int -> Script -> ShowS)
-> (Script -> String) -> ([Script] -> ShowS) -> Show Script
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Script -> ShowS
showsPrec :: Int -> Script -> ShowS
$cshow :: Script -> String
show :: Script -> String
$cshowList :: [Script] -> ShowS
showList :: [Script] -> ShowS
Show)

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

-- | Encode a definite two-element array and minimal language tag, preserving the
-- payload's exact encoding. Nonminimal imported envelopes normalize on encoding;
-- they do not contribute to the script hash.
encodeCbor :: Script -> ByteString
encodeCbor :: Script -> ByteString
encodeCbor Script
script = Encoding -> ByteString
Write.toStrictByteString (Word -> Encoding
Encode.encodeListLen Word
2 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Encoding
payload)
  where
    payload :: Encoding
payload = case Script
script of
      Native NativeScript
native -> Word -> Encoding
Encode.encodeWord Word
0 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ByteString -> Encoding
Encode.encodePreEncoded (NativeScript -> ByteString
Native.encodeCbor NativeScript
native)
      Plutus PlutusScript
plutus -> Word -> Encoding
Encode.encodeWord (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Version -> Int
forall a. Enum a => a -> Int
fromEnum (PlutusScript -> Version
Plutus.version PlutusScript
plutus) Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ByteString -> Encoding
Encode.encodePreEncoded (PlutusScript -> ByteString
Plutus.encodeCbor PlutusScript
plutus)

-- | Decode exactly one two-element native/Plutus envelope. Unknown language tags,
-- incorrect arity, malformed payloads and trailing bytes return
-- 'InvalidScriptCbor'. Payload validators also retain their documented errors.
-- The envelope's encoding is not retained; the payload's encoding is exact.
decodeCbor :: ByteString -> Either Error Script
decodeCbor :: ByteString -> Either Error Script
decodeCbor ByteString
bytes = case (forall s. Decoder s (Word, ByteString))
-> ByteString
-> Either DeserialiseFailure (ByteString, (Word, ByteString))
forall a.
(forall s. Decoder s a)
-> ByteString -> Either DeserialiseFailure (ByteString, a)
Read.deserialiseFromBytes Decoder s (Word, ByteString)
forall s. Decoder s (Word, ByteString)
decodeEnvelope (ByteString -> ByteString
Lazy.fromStrict ByteString
bytes) of
  Left DeserialiseFailure
failure -> Error -> Either Error Script
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, (Word
language, ByteString
payload))
    | Bool -> Bool
not (ByteString -> Bool
Lazy.null ByteString
trailing) -> Error -> Either Error Script
forall a b. a -> Either a b
Left (Text -> Error
InvalidScriptCbor Text
"Trailing bytes after script envelope")
    | Bool
otherwise -> case Word
language of
        Word
0 -> NativeScript -> Script
Native (NativeScript -> Script)
-> Either Error NativeScript -> Either Error Script
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either Error NativeScript
Native.decodeCbor ByteString
payload
        Word
1 -> PlutusScript -> Script
Plutus (PlutusScript -> Script)
-> Either Error PlutusScript -> Either Error Script
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Version -> ByteString -> Either Error PlutusScript
Plutus.decodeCbor Version
Plutus.V1 ByteString
payload
        Word
2 -> PlutusScript -> Script
Plutus (PlutusScript -> Script)
-> Either Error PlutusScript -> Either Error Script
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Version -> ByteString -> Either Error PlutusScript
Plutus.decodeCbor Version
Plutus.V2 ByteString
payload
        Word
3 -> PlutusScript -> Script
Plutus (PlutusScript -> Script)
-> Either Error PlutusScript -> Either Error Script
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Version -> ByteString -> Either Error PlutusScript
Plutus.decodeCbor Version
Plutus.V3 ByteString
payload
        Word
4 -> PlutusScript -> Script
Plutus (PlutusScript -> Script)
-> Either Error PlutusScript -> Either Error Script
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Version -> ByteString -> Either Error PlutusScript
Plutus.decodeCbor Version
Plutus.V4 ByteString
payload
        Word
_ -> Error -> Either Error Script
forall a b. a -> Either a b
Left (Text -> Error
InvalidScriptCbor Text
"Unknown script language")
  where
    decodeEnvelope :: Decoder s (Word, ByteString)
decodeEnvelope = do
      Maybe Int
size <- Decoder s (Maybe Int)
forall s. Decoder s (Maybe Int)
Decode.decodeListLenOrIndef
      Bool -> Decoder s () -> Decoder s ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Bool -> (Int -> Bool) -> Maybe Int -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
True (Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
2) Maybe Int
size) (String -> Decoder s ()
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"Invalid script envelope arity")
      Word
language <- Decoder s Word
forall s. Decoder s Word
Decode.decodeWord
      (Term
_, ByteOffset
start, ByteOffset
end) <- Decoder s Term -> Decoder s (Term, ByteOffset, ByteOffset)
forall s a. Decoder s a -> Decoder s (a, ByteOffset, ByteOffset)
Decode.decodeWithByteSpan Decoder s Term
forall s. Decoder s Term
decodeTerm
      case Maybe Int
size of
        Just Int
_ -> () -> Decoder s ()
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
        Maybe Int
Nothing -> do
          Bool
ended <- Decoder s Bool
forall s. Decoder s Bool
Decode.decodeBreakOr
          Bool -> Decoder s () -> Decoder s ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless Bool
ended (String -> Decoder s ()
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"Unexpected script envelope field")
      let payload :: ByteString
payload = Int -> ByteString -> ByteString
ByteString.take (ByteOffset -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteOffset
end ByteOffset -> ByteOffset -> ByteOffset
forall a. Num a => a -> a -> a
- ByteOffset
start)) (Int -> ByteString -> ByteString
ByteString.drop (ByteOffset -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral ByteOffset
start) ByteString
bytes)
      (Word, ByteString) -> Decoder s (Word, ByteString)
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Word
language, ByteString
payload)

-- | Hash using the native prefix zero or the declared Plutus version prefix.
-- The combined envelope is excluded. Native failures return 'Cometa.Error.NativeError'.
hash :: Script -> IO (Either Error ScriptHash)
hash :: Script -> IO (Either Error ScriptHash)
hash Script
script = case Script
script of
  Native NativeScript
native -> NativeScript -> IO (Either Error ScriptHash)
Native.hash NativeScript
native
  Plutus PlutusScript
plutus -> PlutusScript -> IO (Either Error ScriptHash)
Plutus.hash PlutusScript
plutus