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

-- | Transaction bodies with typed semantic fields and exact imported identity.
-- Construct a minimal body, update its typed fields, then retain 'EncodedBody'
-- for hashing or signing. Reassembling semantic fields deliberately produces a
-- fresh encoding and can change a transaction identifier.
--
-- @
-- minimal = body [] [] 0
-- @
module Cometa.Transaction.Body
  ( Body (..),
    body,
    fee,
    setFee,
    setFeeEncoded,
    encodeCbor,
    encodeCborWith,
    SetField (..),
    setEncoding,
    inputsAreTagged,
    withSetEncoding,
    EncodedBody,
    decodeCbor,
    fromBody,
    toBody,
    toCbor,
    hash,
  )
where

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

import qualified Codec.CBOR.Decoding as D
import qualified Codec.CBOR.Encoding as E
import Cometa.Address.Reward (RewardAddress)
import qualified Cometa.Crypto.Blake2b as Blake2b
import Cometa.Encoding.Set (SetEncoding (TaggedSet))
import Cometa.Error (Error (..))
import qualified Cometa.Internal.SetEncoding as SetEncoding
import qualified Cometa.Internal.TransactionCbor as Cbor
import Cometa.Internal.TransactionFields (BalanceInterval, Entries, Fields)
import qualified Cometa.Internal.TransactionFields as Fields
import Cometa.Protocol.ProposedUpdates (UpdateProposal)
import qualified Cometa.Protocol.ProposedUpdates as Updates
import Cometa.SubTransaction (SubTransaction)
import qualified Cometa.SubTransaction as Sub
import Cometa.Transaction.Input (Input)
import qualified Cometa.Transaction.Input as Input
import Cometa.Transaction.Output (Output)
import qualified Cometa.Transaction.Output as Output
import Cometa.TransactionId (TransactionId)
import qualified Cometa.TransactionId as Id
import Control.Monad (unless, when)
import Data.ByteString (ByteString)
import Data.List (sort, sortOn)
import qualified Data.Map.Strict as Map
import Data.Word (Word64)

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

-- | Semantic transaction-body data. Equality includes field presence, list order,
-- and exact encodings of embedded hash-bearing data. It does not compare the
-- imported containing-body encoding. No ledger-state validation is implied.
data Body = Body
  { -- | Shared spending, output, validity, certificate, asset and governance fields.
    Body -> Fields
bodyFields :: !Fields,
    -- | Transaction fee in lovelace, from zero through 2^64 - 1.
    Body -> Word64
bodyFee :: !Word64,
    -- | Legacy genesis-authorized protocol parameter update proposal.
    Body -> Maybe UpdateProposal
bodyUpdate :: !(Maybe UpdateProposal),
    -- | Inputs reserved as script-failure collateral; absence differs from empty.
    Body -> Maybe [Input]
bodyCollateral :: !(Maybe [Input]),
    -- | Optional output returning excess collateral on script failure.
    Body -> Maybe Output
bodyCollateralReturn :: !(Maybe Output),
    -- | Total collateral claimed, in lovelace; absence differs from zero.
    Body -> Maybe Word64
bodyTotalCollateral :: !(Maybe Word64),
    -- | Dijkstra subtransactions in serialized order, each retaining its exact
    -- body, witnesses and auxiliary-data representation.
    Body -> Maybe [SubTransaction]
bodySubTransactions :: !(Maybe [SubTransaction]),
    -- | Dijkstra requirements on initial account balances before this transaction.
    Body -> Maybe (Entries RewardAddress BalanceInterval)
bodyStartingAccountBalanceIntervals :: !(Maybe (Entries RewardAddress BalanceInterval))
  }
  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 transaction-body bytes paired with semantic data. Equality compares
-- bytes, so alternative integer widths, tags and map order remain distinguishable.
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
  | -- | Collateral inputs.
    CollateralInputs
  | -- | Included subtransactions; their internal encodings are unchanged.
    SubTransactions
  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, ordered outputs and fee with optional fields
-- absent. Empty input/output lists are representable but may fail ledger rules.
body :: [Input] -> [Output] -> Word64 -> Body
body :: [Input] -> [Output] -> Word64 -> Body
body [Input]
inputs [Output]
outputs Word64
amount = Fields
-> Word64
-> Maybe UpdateProposal
-> Maybe [Input]
-> Maybe Output
-> Maybe Word64
-> Maybe [SubTransaction]
-> Maybe (Entries RewardAddress BalanceInterval)
-> Body
Body ([Input] -> [Output] -> Fields
Fields.fields [Input]
inputs [Output]
outputs) Word64
amount Maybe UpdateProposal
forall a. Maybe a
Nothing Maybe [Input]
forall a. Maybe a
Nothing Maybe Output
forall a. Maybe a
Nothing Maybe Word64
forall a. Maybe a
Nothing Maybe [SubTransaction]
forall a. Maybe a
Nothing Maybe (Entries RewardAddress BalanceInterval)
forall a. Maybe a
Nothing

-- | Fee measured in lovelace.
fee :: Body -> Word64
fee :: Body -> Word64
fee = Body -> Word64
bodyFee

-- | Set a fee in lovelace. Other semantic fields remain independent. Construct
-- a fresh 'EncodedBody' before signing this edited body.
setFee :: Word64 -> Body -> Body
setFee :: Word64 -> Body -> Body
setFee Word64
amount Body
value = Body
value {bodyFee = amount}

-- | Edit only a validated body's fee, retaining exact nested field bytes.
-- An unchanged fee returns the exact original body. A changed fee uses a fresh
-- definite outer map in numeric key order; other fields keep their original
-- encodings, including imported historical empty collections. The input snapshot
-- remains independent. Any signatures over the previous identifier need renewal.
setFeeEncoded :: Word64 -> EncodedBody -> EncodedBody
setFeeEncoded :: Word64 -> EncodedBody -> EncodedBody
setFeeEncoded Word64
amount original :: EncodedBody
original@(EncodedBody ByteString
_ Body
semantic Map Word64 ByteString
fields)
  | Word64
amount Word64 -> Word64 -> Bool
forall a. Eq a => a -> a -> Bool
== Body -> Word64
fee Body
semantic = EncodedBody
original
  | Bool
otherwise = ByteString -> Body -> Map Word64 ByteString -> EncodedBody
EncodedBody ByteString
bytes (Word64 -> Body -> Body
setFee Word64
amount Body
semantic) Map Word64 ByteString
updated
  where
    updated :: Map Word64 ByteString
updated = Word64
-> ByteString -> Map Word64 ByteString -> Map Word64 ByteString
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert Word64
2 (Encoding -> ByteString
Cbor.encode (Word64 -> Encoding
E.encodeWord64 Word64
amount)) Map Word64 ByteString
fields
    bytes :: ByteString
bytes = 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))

-- | Encode a fresh definite map in numeric field order, using shortest numbers
-- and tag 258 on sets. Present empty or duplicate guards return
-- 'InvalidTransactionField'. Embedded inline data and subtransactions retain exact
-- identity. Importing an existing signed body should use 'toCbor' instead.
encodeCbor :: Body -> Either Error ByteString
encodeCbor :: Body -> Either Error ByteString
encodeCbor Body
value = do
  Bool -> Fields -> Either Error ()
Fields.validateFields Bool
False (Body -> Fields
bodyFields Body
value)
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool
-> ([SubTransaction] -> Bool) -> Maybe [SubTransaction] -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False [SubTransaction] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (Body -> Maybe [SubTransaction]
bodySubTransactions Body
value)) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionField Text
"Present subtransaction set must be nonempty"))
  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 (Body -> Fields
bodyFields Body
value)
        [(Word64, Encoding)]
-> [(Word64, Encoding)] -> [(Word64, Encoding)]
forall a. [a] -> [a] -> [a]
++ [(Word64
2, Word64 -> Encoding
E.encodeWord64 (Body -> Word64
bodyFee Body
value))]
        [(Word64, Encoding)]
-> [(Word64, Encoding)] -> [(Word64, Encoding)]
forall a. [a] -> [a] -> [a]
++ Word64
-> (UpdateProposal -> Encoding)
-> Maybe UpdateProposal
-> [(Word64, Encoding)]
forall {a} {t} {b}. a -> (t -> b) -> Maybe t -> [(a, b)]
optional Word64
6 (ByteString -> Encoding
Cbor.raw (ByteString -> Encoding)
-> (UpdateProposal -> ByteString) -> UpdateProposal -> Encoding
forall b c a. (b -> c) -> (a -> b) -> a -> c
. UpdateProposal -> ByteString
Updates.encodeProposal) (Body -> Maybe UpdateProposal
bodyUpdate Body
value)
        [(Word64, Encoding)]
-> [(Word64, Encoding)] -> [(Word64, Encoding)]
forall a. [a] -> [a] -> [a]
++ Word64
-> ([Input] -> Encoding) -> Maybe [Input] -> [(Word64, Encoding)]
forall {a} {t} {b}. a -> (t -> b) -> Maybe t -> [(a, b)]
optional Word64
13 [Input] -> Encoding
inputSet (Body -> Maybe [Input]
bodyCollateral Body
value)
        [(Word64, Encoding)]
-> [(Word64, Encoding)] -> [(Word64, Encoding)]
forall a. [a] -> [a] -> [a]
++ Word64
-> (Output -> Encoding) -> Maybe Output -> [(Word64, Encoding)]
forall {a} {t} {b}. a -> (t -> b) -> Maybe t -> [(a, b)]
optional Word64
16 (ByteString -> Encoding
Cbor.raw (ByteString -> Encoding)
-> (Output -> ByteString) -> Output -> Encoding
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Output -> ByteString
Output.encodeCbor) (Body -> Maybe Output
bodyCollateralReturn Body
value)
        [(Word64, Encoding)]
-> [(Word64, Encoding)] -> [(Word64, Encoding)]
forall a. [a] -> [a] -> [a]
++ Word64
-> (Word64 -> Encoding) -> Maybe Word64 -> [(Word64, Encoding)]
forall {a} {t} {b}. a -> (t -> b) -> Maybe t -> [(a, b)]
optional Word64
17 Word64 -> Encoding
E.encodeWord64 (Body -> Maybe Word64
bodyTotalCollateral Body
value)
        [(Word64, Encoding)]
-> [(Word64, Encoding)] -> [(Word64, Encoding)]
forall a. [a] -> [a] -> [a]
++ Word64
-> ([SubTransaction] -> Encoding)
-> Maybe [SubTransaction]
-> [(Word64, Encoding)]
forall {a} {t} {b}. a -> (t -> b) -> Maybe t -> [(a, b)]
optional Word64
23 [SubTransaction] -> Encoding
forall {t :: * -> *}. Foldable t => t SubTransaction -> Encoding
subSet (Body -> Maybe [SubTransaction]
bodySubTransactions Body
value)
        [(Word64, Encoding)]
-> [(Word64, Encoding)] -> [(Word64, Encoding)]
forall a. [a] -> [a] -> [a]
++ Word64
-> (Entries RewardAddress BalanceInterval -> Encoding)
-> Maybe (Entries RewardAddress BalanceInterval)
-> [(Word64, Encoding)]
forall {a} {t} {b}. a -> (t -> b) -> Maybe t -> [(a, b)]
optional Word64
27 Entries RewardAddress BalanceInterval -> Encoding
Fields.encodeIntervals (Body -> Maybe (Entries RewardAddress BalanceInterval)
bodyStartingAccountBalanceIntervals Body
value)
    optional :: a -> (t -> b) -> Maybe t -> [(a, b)]
optional a
key t -> b
encoder = [(a, b)] -> (t -> [(a, b)]) -> Maybe t -> [(a, b)]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] (\t
payload -> [(a
key, t -> b
encoder t
payload)])
    inputSet :: [Input] -> Encoding
inputSet [Input]
values = Word -> Encoding
E.encodeTag Word
258 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Word -> Encoding
E.encodeListLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([Input] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Input]
values)) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> (Input -> Encoding) -> [Input] -> 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)
-> (Input -> ByteString) -> Input -> Encoding
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Input -> ByteString
Input.encodeCbor) ([Input] -> [Input]
forall a. Ord a => [a] -> [a]
sort [Input]
values)
    subSet :: t SubTransaction -> Encoding
subSet t SubTransaction
values = Word -> Encoding
E.encodeTag Word
258 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Word -> Encoding
E.encodeListLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral (t SubTransaction -> Int
forall a. t a -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length t SubTransaction
values)) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> (SubTransaction -> Encoding) -> t SubTransaction -> Encoding
forall m a. Monoid m => (a -> m) -> t a -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (ByteString -> Encoding
Cbor.raw (ByteString -> Encoding)
-> (SubTransaction -> ByteString) -> SubTransaction -> Encoding
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SubTransaction -> ByteString
Sub.encodeCbor) t SubTransaction
values

-- | Validate fresh assembly and pair semantic data with its encoding. Present
-- empty guards or repeated 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 changing the original body bytes.
toBody :: EncodedBody -> Body
toBody :: EncodedBody -> Body
toBody (EncodedBody ByteString
_ Body
value Map Word64 ByteString
_) = Body
value

-- | Exact imported or freshly encoded ledger transaction-body bytes.
toCbor :: EncodedBody -> ByteString
toCbor :: EncodedBody -> ByteString
toCbor (EncodedBody ByteString
bytes Body
_ Map Word64 ByteString
_) = ByteString
bytes

-- | Decode all pinned native body fields, including typed Dijkstra fields 23-27.
-- Unknown keys, repeated keys, missing inputs/outputs/fee, malformed nested data,
-- and trailing bytes return a structured error. Definite and indefinite maps,
-- nonminimal numbers and optional set tags retain their original byte identity.
decodeCbor :: ByteString -> Either Error EncodedBody
decodeCbor :: ByteString -> Either Error EncodedBody
decodeCbor ByteString
bytes = do
  Map Word64 ByteString
fields <- (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
2, Word64
3, Word64
4, Word64
5, Word64
6, Word64
7, Word64
8, Word64
9, Word64
11, Word64
13, Word64
14, Word64
15, Word64
16, Word64
17, Word64
18, Word64
19, Word64
20, Word64
21, Word64
22, Word64
23, Word64
24, Word64
25, Word64
26, Word64
27]) (Map Word64 ByteString -> [Word64]
forall k a. Map k a -> [k]
Map.keys Map Word64 ByteString
fields)) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionField Text
"Unknown transaction body key"))
  Fields
common <- Map Word64 ByteString -> Either Error Fields
Fields.decodeFields Map Word64 ByteString
fields
  Word64
amount <- Word64
-> (ByteString -> Either Error Word64)
-> Map Word64 ByteString
-> Either Error Word64
forall {k} {a} {b}.
Ord k =>
k -> (a -> Either Error b) -> Map k a -> Either Error b
required Word64
2 ((forall s. Decoder s Word64) -> ByteString -> Either Error Word64
forall a. (forall s. Decoder s a) -> ByteString -> Either Error a
Cbor.decode Decoder s Word64
forall s. Decoder s Word64
D.decodeWord64) Map Word64 ByteString
fields
  Maybe UpdateProposal
updates <- Word64
-> (ByteString -> Either Error UpdateProposal)
-> Map Word64 ByteString
-> Either Error (Maybe UpdateProposal)
forall {f :: * -> *} {k} {a} {b}.
(Applicative f, Ord k) =>
k -> (a -> f b) -> Map k a -> f (Maybe b)
optional Word64
6 ((EncodedProposal -> UpdateProposal)
-> Either Error EncodedProposal -> Either Error UpdateProposal
forall a b. (a -> b) -> Either Error a -> Either Error b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap EncodedProposal -> UpdateProposal
Updates.toProposal (Either Error EncodedProposal -> Either Error UpdateProposal)
-> (ByteString -> Either Error EncodedProposal)
-> ByteString
-> Either Error UpdateProposal
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either Error EncodedProposal
Updates.decodeProposal) Map Word64 ByteString
fields
  Maybe [Input]
collateral <- Word64
-> (ByteString -> Either Error [Input])
-> Map Word64 ByteString
-> Either Error (Maybe [Input])
forall {f :: * -> *} {k} {a} {b}.
(Applicative f, Ord k) =>
k -> (a -> f b) -> Map k a -> f (Maybe b)
optional Word64
13 ByteString -> Either Error [Input]
inputDecoder Map Word64 ByteString
fields
  Maybe Output
collateralReturn <- Word64
-> (ByteString -> Either Error Output)
-> Map Word64 ByteString
-> Either Error (Maybe Output)
forall {f :: * -> *} {k} {a} {b}.
(Applicative f, Ord k) =>
k -> (a -> f b) -> Map k a -> f (Maybe b)
optional Word64
16 ((EncodedOutput -> Output)
-> Either Error EncodedOutput -> Either Error Output
forall a b. (a -> b) -> Either Error a -> Either Error b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap EncodedOutput -> Output
Output.toOutput (Either Error EncodedOutput -> Either Error Output)
-> (ByteString -> Either Error EncodedOutput)
-> ByteString
-> Either Error Output
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either Error EncodedOutput
Output.decodeCbor) Map Word64 ByteString
fields
  Maybe Word64
totalCollateral <- Word64
-> (ByteString -> Either Error Word64)
-> Map Word64 ByteString
-> Either Error (Maybe Word64)
forall {f :: * -> *} {k} {a} {b}.
(Applicative f, Ord k) =>
k -> (a -> f b) -> Map k a -> f (Maybe b)
optional Word64
17 ((forall s. Decoder s Word64) -> ByteString -> Either Error Word64
forall a. (forall s. Decoder s a) -> ByteString -> Either Error a
Cbor.decode Decoder s Word64
forall s. Decoder s Word64
D.decodeWord64) Map Word64 ByteString
fields
  Maybe [SubTransaction]
subs <- Word64
-> (ByteString -> Either Error [SubTransaction])
-> Map Word64 ByteString
-> Either Error (Maybe [SubTransaction])
forall {f :: * -> *} {k} {a} {b}.
(Applicative f, Ord k) =>
k -> (a -> f b) -> Map k a -> f (Maybe b)
optional Word64
23 ByteString -> Either Error [SubTransaction]
subDecoder Map Word64 ByteString
fields
  Maybe (Entries RewardAddress BalanceInterval)
starting <- Word64
-> (ByteString
    -> Either Error (Entries RewardAddress BalanceInterval))
-> Map Word64 ByteString
-> Either Error (Maybe (Entries RewardAddress BalanceInterval))
forall {f :: * -> *} {k} {a} {b}.
(Applicative f, Ord k) =>
k -> (a -> f b) -> Map k a -> f (Maybe b)
optional Word64
27 ByteString -> Either Error (Entries RewardAddress BalanceInterval)
Fields.decodeIntervals Map Word64 ByteString
fields
  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
-> Word64
-> Maybe UpdateProposal
-> Maybe [Input]
-> Maybe Output
-> Maybe Word64
-> Maybe [SubTransaction]
-> Maybe (Entries RewardAddress BalanceInterval)
-> Body
Body Fields
common Word64
amount Maybe UpdateProposal
updates Maybe [Input]
collateral Maybe Output
collateralReturn Maybe Word64
totalCollateral Maybe [SubTransaction]
subs Maybe (Entries RewardAddress BalanceInterval)
starting) Map Word64 ByteString
fields)
  where
    required :: k -> (a -> Either Error b) -> Map k a -> Either Error b
required k
key a -> Either Error b
parser Map k a
fields = Either Error b
-> (a -> Either Error b) -> Maybe a -> Either Error b
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Error -> Either Error b
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionField Text
"Missing fee")) a -> Either Error b
parser (k -> Map k a -> Maybe a
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup k
key Map k a
fields)
    optional :: k -> (a -> f b) -> Map k a -> f (Maybe b)
optional k
key a -> f b
parser Map k a
fields = (a -> f b) -> Maybe a -> f (Maybe b)
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> Maybe a -> f (Maybe b)
traverse a -> f b
parser (k -> Map k a -> Maybe a
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup k
key Map k a
fields)
    inputDecoder :: ByteString -> Either Error [Input]
inputDecoder ByteString
payload = [Input] -> [Input]
forall a. Ord a => [a] -> [a]
sort ([Input] -> [Input])
-> Either Error [Input] -> Either Error [Input]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (forall s. Decoder s [Input]) -> ByteString -> Either Error [Input]
forall a. (forall s. Decoder s a) -> ByteString -> Either Error a
Cbor.decode (Decoder s Input -> Decoder s [Input]
forall s a. Decoder s a -> Decoder s [a]
Cbor.setList (ByteString -> (ByteString -> Either Error Input) -> Decoder s Input
forall a s.
ByteString -> (ByteString -> Either Error a) -> Decoder s a
Cbor.nested ByteString
payload ByteString -> Either Error Input
Input.decodeCbor)) ByteString
payload
    subDecoder :: ByteString -> Either Error [SubTransaction]
subDecoder ByteString
payload = do
      [SubTransaction]
values <- (forall s. Decoder s [SubTransaction])
-> ByteString -> Either Error [SubTransaction]
forall a. (forall s. Decoder s a) -> ByteString -> Either Error a
Cbor.decode (Decoder s SubTransaction -> Decoder s [SubTransaction]
forall s a. Decoder s a -> Decoder s [a]
Cbor.setList (ByteString
-> (ByteString -> Either Error SubTransaction)
-> Decoder s SubTransaction
forall a s.
ByteString -> (ByteString -> Either Error a) -> Decoder s a
Cbor.nested ByteString
payload ByteString -> Either Error SubTransaction
Sub.decodeCbor)) ByteString
payload
      Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when ([SubTransaction] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [SubTransaction]
values) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionField Text
"Present subtransaction set must be nonempty"))
      [SubTransaction] -> Either Error [SubTransaction]
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure [SubTransaction]
values

-- | Hash the exact body bytes with native BLAKE2b-256. This operation does not
-- normalize or rebuild the body. Native failures remain 'NativeError'.
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

-- | Whether the encoded spending-input collection carries set tag 258.
-- Other tagged collections do not affect this result; an absent input field
-- returns 'False'. This observes the exact body snapshot without re-encoding.
inputsAreTagged :: EncodedBody -> Bool
inputsAreTagged :: EncodedBody -> Bool
inputsAreTagged EncodedBody
encoded = SetField -> EncodedBody -> Maybe SetEncoding
setEncoding SetField
Inputs EncodedBody
encoded Maybe SetEncoding -> Maybe SetEncoding -> Bool
forall a. Eq a => a -> a -> Bool
== SetEncoding -> Maybe SetEncoding
forall a. a -> Maybe a
Just SetEncoding
TaggedSet

-- | 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
  SetField
CollateralInputs -> Word64
13
  SetField
SubTransactions -> Word64
23