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

-- | Dijkstra subtransaction bodies. Their schema contains shared transaction
-- fields but excludes fees, legacy updates, collateral, nested subtransactions
-- and starting-account-balance requirements.
--
-- @
-- minimal = body [] []
-- @
module Cometa.SubTransaction.Body
  ( Body,
    body,
    fromFields,
    fields,
    encodeCbor,
    encodeCborWith,
    SetField (..),
    setEncoding,
    withSetEncoding,
    EncodedBody,
    decodeCbor,
    fromBody,
    toBody,
    toCbor,
    hash,
  )
where

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

import qualified Codec.CBOR.Encoding as E
import qualified Cometa.Crypto.Blake2b as Blake2b
import Cometa.Encoding.Set (SetEncoding)
import Cometa.Error (Error (..))
import qualified Cometa.Internal.SetEncoding as SetEncoding
import qualified Cometa.Internal.TransactionCbor as Cbor
import Cometa.Internal.TransactionFields (Fields)
import qualified Cometa.Internal.TransactionFields as Fields
import Cometa.Transaction.Input (Input)
import Cometa.Transaction.Output (Output)
import Cometa.TransactionId (TransactionId)
import qualified Cometa.TransactionId as Id
import Control.Monad (unless)
import Data.ByteString (ByteString)
import Data.List (sortOn)
import qualified Data.Map.Strict as Map
import Data.Word (Word64)

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

-- | Shared semantic fields with the subtransaction schema. Equality compares
-- fields, distinguishing absence, empty collections and embedded datum bytes.
newtype Body = Body Fields deriving (Body -> Body -> Bool
(Body -> Body -> Bool) -> (Body -> Body -> Bool) -> Eq Body
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Body -> Body -> Bool
== :: Body -> Body -> Bool
$c/= :: Body -> Body -> Bool
/= :: Body -> Body -> Bool
Eq, Int -> Body -> ShowS
[Body] -> ShowS
Body -> String
(Int -> Body -> ShowS)
-> (Body -> String) -> ([Body] -> ShowS) -> Show Body
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Body -> ShowS
showsPrec :: Int -> Body -> ShowS
$cshow :: Body -> String
show :: Body -> String
$cshowList :: [Body] -> ShowS
showList :: [Body] -> ShowS
Show)

-- | Exact imported subtransaction-body encoding. Equality compares exact bytes.
data EncodedBody = EncodedBody !ByteString !Body !(Map.Map Word64 ByteString) deriving (Int -> EncodedBody -> ShowS
[EncodedBody] -> ShowS
EncodedBody -> String
(Int -> EncodedBody -> ShowS)
-> (EncodedBody -> String)
-> ([EncodedBody] -> ShowS)
-> Show EncodedBody
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> EncodedBody -> ShowS
showsPrec :: Int -> EncodedBody -> ShowS
$cshow :: EncodedBody -> String
show :: EncodedBody -> String
$cshowList :: [EncodedBody] -> ShowS
showList :: [EncodedBody] -> ShowS
Show)

instance Eq EncodedBody where
  EncodedBody
left == :: EncodedBody -> EncodedBody -> Bool
== EncodedBody
right = EncodedBody -> ByteString
toCbor EncodedBody
left ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== EncodedBody -> ByteString
toCbor EncodedBody
right

-- | Set-valued fields in this body schema. Outputs and maps are not sets.
data SetField
  = -- | Spending inputs.
    Inputs
  | -- | Stake and governance certificates.
    Certificates
  | -- | Required signer or guard credentials.
    Guards
  | -- | Reference inputs.
    ReferenceInputs
  | -- | Governance proposals.
    Proposals
  deriving (SetField -> SetField -> Bool
(SetField -> SetField -> Bool)
-> (SetField -> SetField -> Bool) -> Eq SetField
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: SetField -> SetField -> Bool
== :: SetField -> SetField -> Bool
$c/= :: SetField -> SetField -> Bool
/= :: SetField -> SetField -> Bool
Eq, Eq SetField
Eq SetField =>
(SetField -> SetField -> Ordering)
-> (SetField -> SetField -> Bool)
-> (SetField -> SetField -> Bool)
-> (SetField -> SetField -> Bool)
-> (SetField -> SetField -> Bool)
-> (SetField -> SetField -> SetField)
-> (SetField -> SetField -> SetField)
-> Ord SetField
SetField -> SetField -> Bool
SetField -> SetField -> Ordering
SetField -> SetField -> SetField
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 :: SetField -> SetField -> Ordering
compare :: SetField -> SetField -> Ordering
$c< :: SetField -> SetField -> Bool
< :: SetField -> SetField -> Bool
$c<= :: SetField -> SetField -> Bool
<= :: SetField -> SetField -> Bool
$c> :: SetField -> SetField -> Bool
> :: SetField -> SetField -> Bool
$c>= :: SetField -> SetField -> Bool
>= :: SetField -> SetField -> Bool
$cmax :: SetField -> SetField -> SetField
max :: SetField -> SetField -> SetField
$cmin :: SetField -> SetField -> SetField
min :: SetField -> SetField -> SetField
Ord, Int -> SetField -> ShowS
[SetField] -> ShowS
SetField -> String
(Int -> SetField -> ShowS)
-> (SetField -> String) -> ([SetField] -> ShowS) -> Show SetField
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> SetField -> ShowS
showsPrec :: Int -> SetField -> ShowS
$cshow :: SetField -> String
show :: SetField -> String
$cshowList :: [SetField] -> ShowS
showList :: [SetField] -> ShowS
Show, Int -> SetField
SetField -> Int
SetField -> [SetField]
SetField -> SetField
SetField -> SetField -> [SetField]
SetField -> SetField -> SetField -> [SetField]
(SetField -> SetField)
-> (SetField -> SetField)
-> (Int -> SetField)
-> (SetField -> Int)
-> (SetField -> [SetField])
-> (SetField -> SetField -> [SetField])
-> (SetField -> SetField -> [SetField])
-> (SetField -> SetField -> SetField -> [SetField])
-> Enum SetField
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 :: SetField -> SetField
succ :: SetField -> SetField
$cpred :: SetField -> SetField
pred :: SetField -> SetField
$ctoEnum :: Int -> SetField
toEnum :: Int -> SetField
$cfromEnum :: SetField -> Int
fromEnum :: SetField -> Int
$cenumFrom :: SetField -> [SetField]
enumFrom :: SetField -> [SetField]
$cenumFromThen :: SetField -> SetField -> [SetField]
enumFromThen :: SetField -> SetField -> [SetField]
$cenumFromTo :: SetField -> SetField -> [SetField]
enumFromTo :: SetField -> SetField -> [SetField]
$cenumFromThenTo :: SetField -> SetField -> SetField -> [SetField]
enumFromThenTo :: SetField -> SetField -> SetField -> [SetField]
Enum, SetField
SetField -> SetField -> Bounded SetField
forall a. a -> a -> Bounded a
$cminBound :: SetField
minBound :: SetField
$cmaxBound :: SetField
maxBound :: SetField
Bounded)

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

-- | Assemble required references and ordered outputs; all optional fields absent.
body :: [Input] -> [Output] -> Body
body :: [Input] -> [Output] -> Body
body [Input]
inputs [Output]
outputs = Fields -> Body
Body ([Input] -> [Output] -> Fields
Fields.fields [Input]
inputs [Output]
outputs)

-- | Assemble shared fields without introducing unsupported top-level fields.
fromFields :: Fields -> Body
fromFields :: Fields -> Body
fromFields = Fields -> Body
Body

-- | Inspect all shared semantic fields.
fields :: Body -> Fields
fields :: Body -> Fields
fields (Body Fields
value) = Fields
value

-- | Fresh definite body map in ascending numeric field order. Embedded datums
-- retain exact encoding; imported body identity is obtained through 'toCbor'.
encodeCbor :: Body -> Either Error ByteString
encodeCbor :: Body -> Either Error ByteString
encodeCbor (Body Fields
value) = Bool -> Fields -> Either Error ()
Fields.validateFields Bool
True Fields
value 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
>> ByteString -> Either Error ByteString
forall a b. b -> Either a b
Right (Encoding -> ByteString
Cbor.encode (Word -> Encoding
E.encodeMapLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([(Word64, Encoding)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(Word64, Encoding)]
pairs)) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ((Word64, Encoding) -> Encoding)
-> [(Word64, Encoding)] -> Encoding
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (\(Word64
key, Encoding
payload) -> Word64 -> Encoding
E.encodeWord64 Word64
key Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Encoding
payload) (((Word64, Encoding) -> Word64)
-> [(Word64, Encoding)] -> [(Word64, Encoding)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (Word64, Encoding) -> Word64
forall a b. (a, b) -> a
fst [(Word64, Encoding)]
pairs)))
  where
    pairs :: [(Word64, Encoding)]
pairs = Fields -> [(Word64, Encoding)]
Fields.encodeFields Fields
value

-- | Validate context-specific fields and pair them with fresh bytes. Present
-- empty certificates, mint or guards and duplicate guard credentials return
-- 'InvalidTransactionField'.
fromBody :: Body -> Either Error EncodedBody
fromBody :: Body -> Either Error EncodedBody
fromBody Body
value = Body -> Either Error ByteString
encodeCbor Body
value Either Error ByteString
-> (ByteString -> Either Error EncodedBody)
-> Either Error EncodedBody
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 EncodedBody
decodeCbor

-- | Inspect semantic fields without normalizing the exact body.
toBody :: EncodedBody -> Body
toBody :: EncodedBody -> Body
toBody (EncodedBody ByteString
_ Body
value Map Word64 ByteString
_) = Body
value

-- | Exact ledger subtransaction-body bytes.
toCbor :: EncodedBody -> ByteString
toCbor :: EncodedBody -> ByteString
toCbor (EncodedBody ByteString
bytes Body
_ Map Word64 ByteString
_) = ByteString
bytes

-- | Decode the complete subtransaction schema. Top-level-only fields and unknown
-- keys are rejected rather than dropped. Original map, set and number encodings
-- are preserved. Missing required fields and malformed nested data return errors.
decodeCbor :: ByteString -> Either Error EncodedBody
decodeCbor :: ByteString -> Either Error EncodedBody
decodeCbor ByteString
bytes = do
  Map Word64 ByteString
pairs <- (forall s. Decoder s (Map Word64 ByteString))
-> ByteString -> Either Error (Map Word64 ByteString)
forall a. (forall s. Decoder s a) -> ByteString -> Either Error a
Cbor.decode (ByteString -> Decoder s (Map Word64 ByteString)
forall s. ByteString -> Decoder s (Map Word64 ByteString)
Cbor.mapFields ByteString
bytes) ByteString
bytes
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ((Word64 -> Bool) -> [Word64] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (Word64 -> [Word64] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Word64
0, Word64
1, Word64
3, Word64
4, Word64
5, Word64
7, Word64
8, Word64
9, Word64
11, Word64
14, Word64
15, Word64
18, Word64
19, Word64
20, Word64
21, Word64
22, Word64
24, Word64
25, Word64
26]) (Map Word64 ByteString -> [Word64]
forall k a. Map k a -> [k]
Map.keys Map Word64 ByteString
pairs)) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionField Text
"Unsupported subtransaction body key"))
  Fields
value <- Map Word64 ByteString -> Either Error Fields
Fields.decodeFields Map Word64 ByteString
pairs
  Bool -> Fields -> Either Error ()
Fields.validateFields Bool
True Fields
value
  EncodedBody -> Either Error EncodedBody
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ByteString -> Body -> Map Word64 ByteString -> EncodedBody
EncodedBody ByteString
bytes (Fields -> Body
Body Fields
value) Map Word64 ByteString
pairs)

-- | Native BLAKE2b-256 of exact body bytes, with native errors retained.
hash :: EncodedBody -> IO (Either Error TransactionId)
hash :: EncodedBody -> IO (Either Error TransactionId)
hash EncodedBody
value = do
  Either Error Blake2bHash
result <- Int -> ByteString -> IO (Either Error Blake2bHash)
Blake2b.compute Int
32 (EncodedBody -> ByteString
toCbor EncodedBody
value)
  Either Error TransactionId -> IO (Either Error TransactionId)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error Blake2bHash
result Either Error Blake2bHash
-> (Blake2bHash -> Either Error TransactionId)
-> Either Error TransactionId
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 TransactionId
Id.fromBytes (ByteString -> Either Error TransactionId)
-> (Blake2bHash -> ByteString)
-> Blake2bHash
-> Either Error TransactionId
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Blake2bHash -> ByteString
Blake2b.toBytes)

-- | Encode fresh body fields with the requested set tags. Embedded values keep
-- their own encoding choices. Protocol validity is the caller's responsibility.
encodeCborWith :: SetEncoding -> Body -> Either Error ByteString
encodeCborWith :: SetEncoding -> Body -> Either Error ByteString
encodeCborWith SetEncoding
requested Body
value = do
  EncodedBody
original <- Body -> Either Error EncodedBody
fromBody Body
value
  ByteString -> Either Error ByteString
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (EncodedBody -> ByteString
toCbor ((SetField -> EncodedBody -> EncodedBody)
-> EncodedBody -> [SetField] -> EncodedBody
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (SetField -> SetEncoding -> EncodedBody -> EncodedBody
`withSetEncoding` SetEncoding
requested) EncodedBody
original [SetField
forall a. Bounded a => a
minBound .. SetField
forall a. Bounded a => a
maxBound]))

-- | Observe one field's set tag. An absent optional field returns 'Nothing'.
setEncoding :: SetField -> EncodedBody -> Maybe SetEncoding
setEncoding :: SetField -> EncodedBody -> Maybe SetEncoding
setEncoding SetField
field (EncodedBody ByteString
_ Body
_ Map Word64 ByteString
values) = ByteString -> SetEncoding
SetEncoding.encoding (ByteString -> SetEncoding)
-> Maybe ByteString -> Maybe SetEncoding
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Word64 -> Map Word64 ByteString -> Maybe ByteString
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup (SetField -> Word64
setFieldKey SetField
field) Map Word64 ByteString
values

-- | Change one present field's set tag. Absence and an unchanged tag preserve
-- the exact original body. A change rebuilds the outer map in numeric key order,
-- retaining all other field bytes and the selected array's contents. It can
-- change the body hash: signatures over the previous body must be renewed.
withSetEncoding :: SetField -> SetEncoding -> EncodedBody -> EncodedBody
withSetEncoding :: SetField -> SetEncoding -> EncodedBody -> EncodedBody
withSetEncoding SetField
field SetEncoding
requested original :: EncodedBody
original@(EncodedBody ByteString
_ Body
semantic Map Word64 ByteString
values)
  | Map Word64 ByteString
updated Map Word64 ByteString -> Map Word64 ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== Map Word64 ByteString
values = EncodedBody
original
  | Bool
otherwise = ByteString -> Body -> Map Word64 ByteString -> EncodedBody
EncodedBody ByteString
encoded Body
semantic Map Word64 ByteString
updated
  where
    updated :: Map Word64 ByteString
updated = (ByteString -> ByteString)
-> Word64 -> Map Word64 ByteString -> Map Word64 ByteString
forall k a. Ord k => (a -> a) -> k -> Map k a -> Map k a
Map.adjust (SetEncoding -> ByteString -> ByteString
SetEncoding.withEncoding SetEncoding
requested) (SetField -> Word64
setFieldKey SetField
field) Map Word64 ByteString
values
    encoded :: ByteString
encoded = Encoding -> ByteString
Cbor.encode (Word -> Encoding
E.encodeMapLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Map Word64 ByteString -> Int
forall k a. Map k a -> Int
Map.size Map Word64 ByteString
updated)) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ((Word64, ByteString) -> Encoding)
-> [(Word64, ByteString)] -> Encoding
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (\(Word64
key, ByteString
payload) -> Word64 -> Encoding
E.encodeWord64 Word64
key Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ByteString -> Encoding
Cbor.raw ByteString
payload) (Map Word64 ByteString -> [(Word64, ByteString)]
forall k a. Map k a -> [(k, a)]
Map.toAscList Map Word64 ByteString
updated))

-- | Ledger map key of a supported set-valued field.
setFieldKey :: SetField -> Word64
setFieldKey :: SetField -> Word64
setFieldKey SetField
field = case SetField
field of
  SetField
Inputs -> Word64
0
  SetField
Certificates -> Word64
4
  SetField
Guards -> Word64
14
  SetField
ReferenceInputs -> Word64
18
  SetField
Proposals -> Word64
20