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

-- | Transactions retain exact body, witnesses and outer framing. Decoding does
-- not verify signatures, script execution, auxiliary-data hashes or ledger rules.
-- Witness updates preserve the bytes used for the transaction ID. A changed body
-- removes outer verification-key and bootstrap signatures; embedded transaction
-- witnesses remain part of their own unchanged bodies.
--
-- @
-- import qualified Cometa.Transaction as Tx
--
-- reload bytes = Tx.encodeCbor <$> Tx.decodeCbor bytes
-- @
module Cometa.Transaction
  ( Transaction,
    Frame (..),
    fromBody,
    assemble,
    decodeCbor,
    encodeCbor,
    body,
    witnesses,
    frame,
    scriptValidity,
    auxiliaryData,
    hasScriptData,
    transactionId,
    setBody,
    setBodySetEncoding,
    setFee,
    setScriptValidity,
    setAuxiliaryData,
    setWitnesses,
    addWitnesses,
  )
where

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

import qualified Codec.CBOR.Decoding as D
import qualified Codec.CBOR.Read as R
import qualified Codec.CBOR.Term as T
import Cometa.Encoding.Set (SetEncoding)
import Cometa.Error (Error (..))
import qualified Cometa.Transaction.AuxiliaryData as Auxiliary
import qualified Cometa.Transaction.Body as Body
import qualified Cometa.Transaction.Witnesses as Witnesses
import Cometa.TransactionId (TransactionId)
import Control.Monad (replicateM, unless)
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Lazy as Lazy
import qualified Data.Text as Text
import Data.Word (Word64)

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

-- | Outer transaction field order. These layouts describe representation, not
-- validity in a particular ledger era.
data Frame
  = -- | @[body,witnesses,auxiliary-data-or-null]@; script validity is true.
    Historical
  | -- | @[body,witnesses,script-validity,auxiliary-data-or-null]@.
    Mempool
  | -- | @[body,witnesses,auxiliary-data-or-null,script-validity]@.
    Block
  deriving (Frame -> Frame -> Bool
(Frame -> Frame -> Bool) -> (Frame -> Frame -> Bool) -> Eq Frame
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Frame -> Frame -> Bool
== :: Frame -> Frame -> Bool
$c/= :: Frame -> Frame -> Bool
/= :: Frame -> Frame -> Bool
Eq, Eq Frame
Eq Frame =>
(Frame -> Frame -> Ordering)
-> (Frame -> Frame -> Bool)
-> (Frame -> Frame -> Bool)
-> (Frame -> Frame -> Bool)
-> (Frame -> Frame -> Bool)
-> (Frame -> Frame -> Frame)
-> (Frame -> Frame -> Frame)
-> Ord Frame
Frame -> Frame -> Bool
Frame -> Frame -> Ordering
Frame -> Frame -> Frame
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 :: Frame -> Frame -> Ordering
compare :: Frame -> Frame -> Ordering
$c< :: Frame -> Frame -> Bool
< :: Frame -> Frame -> Bool
$c<= :: Frame -> Frame -> Bool
<= :: Frame -> Frame -> Bool
$c> :: Frame -> Frame -> Bool
> :: Frame -> Frame -> Bool
$c>= :: Frame -> Frame -> Bool
>= :: Frame -> Frame -> Bool
$cmax :: Frame -> Frame -> Frame
max :: Frame -> Frame -> Frame
$cmin :: Frame -> Frame -> Frame
min :: Frame -> Frame -> Frame
Ord, Int -> Frame -> ShowS
[Frame] -> ShowS
Frame -> String
(Int -> Frame -> ShowS)
-> (Frame -> String) -> ([Frame] -> ShowS) -> Show Frame
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Frame -> ShowS
showsPrec :: Int -> Frame -> ShowS
$cshow :: Frame -> String
show :: Frame -> String
$cshowList :: [Frame] -> ShowS
showList :: [Frame] -> ShowS
Show)

-- | An immutable transaction. Equality compares exact encoded representation,
-- including nonminimal encodings and definite versus indefinite framing.
-- 'Show' is diagnostic; use 'encodeCbor' for storage.
data Transaction = Transaction
  { Transaction -> EncodedBody
transactionBody :: !Body.EncodedBody,
    Transaction -> EncodedWitnesses
transactionWitnesses :: !Witnesses.EncodedWitnesses,
    Transaction -> Frame
transactionFrame :: !Frame,
    Transaction -> Bool
transactionValidity :: !Bool,
    Transaction -> Maybe EncodedAuxiliaryData
transactionAuxiliary :: !(Maybe Auxiliary.EncodedAuxiliaryData),
    Transaction -> ByteString
transactionPrefix :: !ByteString,
    Transaction -> ByteString
transactionSuffix :: !ByteString
  }
  deriving (Int -> Transaction -> ShowS
[Transaction] -> ShowS
Transaction -> String
(Int -> Transaction -> ShowS)
-> (Transaction -> String)
-> ([Transaction] -> ShowS)
-> Show Transaction
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Transaction -> ShowS
showsPrec :: Int -> Transaction -> ShowS
$cshow :: Transaction -> String
show :: Transaction -> String
$cshowList :: [Transaction] -> ShowS
showList :: [Transaction] -> ShowS
Show)

instance Eq Transaction where
  Transaction
left == :: Transaction -> Transaction -> Bool
== Transaction
right = Transaction -> ByteString
encodeCbor Transaction
left ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== Transaction -> ByteString
encodeCbor Transaction
right

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

-- | Assemble an unsigned transaction with a definite four-field mempool frame,
-- true script validity, empty witnesses and absent auxiliary data. This does not
-- balance the body or assert ledger validity.
fromBody :: Body.EncodedBody -> Transaction
fromBody :: EncodedBody -> Transaction
fromBody EncodedBody
encodedBody = EncodedBody
-> EncodedWitnesses -> Maybe EncodedAuxiliaryData -> Transaction
assemble EncodedBody
encodedBody (Witnesses -> EncodedWitnesses
Witnesses.fromWitnesses Witnesses
Witnesses.empty) Maybe EncodedAuxiliaryData
forall a. Maybe a
Nothing

-- | Assemble a fresh definite mempool frame with true script validity. The body,
-- witness set and optional auxiliary data retain their supplied exact bytes.
-- This does not check signatures or the body's auxiliary-data commitment.
assemble :: Body.EncodedBody -> Witnesses.EncodedWitnesses -> Maybe Auxiliary.EncodedAuxiliaryData -> Transaction
assemble :: EncodedBody
-> EncodedWitnesses -> Maybe EncodedAuxiliaryData -> Transaction
assemble EncodedBody
encodedBody EncodedWitnesses
encodedWitnesses Maybe EncodedAuxiliaryData
auxiliary =
  EncodedBody
-> EncodedWitnesses
-> Frame
-> Bool
-> Maybe EncodedAuxiliaryData
-> ByteString
-> ByteString
-> Transaction
Transaction
    EncodedBody
encodedBody
    EncodedWitnesses
encodedWitnesses
    Frame
Mempool
    Bool
True
    Maybe EncodedAuxiliaryData
auxiliary
    (Word8 -> ByteString
ByteString.singleton Word8
0x84)
    (Word8 -> ByteString
ByteString.singleton Word8
0xf5 ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
-> (EncodedAuxiliaryData -> ByteString)
-> Maybe EncodedAuxiliaryData
-> ByteString
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Word8 -> ByteString
ByteString.singleton Word8
0xf6) EncodedAuxiliaryData -> ByteString
Auxiliary.toCbor Maybe EncodedAuxiliaryData
auxiliary)

-- | Decode exactly one historical, mempool or block frame, accepting definite
-- and indefinite arrays. Preserve every byte. Malformed, trailing, unsupported
-- or duplicate-field encodings return a structured error. No native resources
-- or secret keys are acquired.
decodeCbor :: ByteString -> Either Error Transaction
decodeCbor :: ByteString -> Either Error Transaction
decodeCbor ByteString
bytes = case (forall s. Decoder s (Either Error Transaction))
-> ByteString
-> Either DeserialiseFailure (ByteString, Either Error Transaction)
forall a.
(forall s. Decoder s a)
-> ByteString -> Either DeserialiseFailure (ByteString, a)
R.deserialiseFromBytes (ByteString -> Decoder s (Either Error Transaction)
forall s. ByteString -> Decoder s (Either Error Transaction)
decodeFrame ByteString
bytes) (ByteString -> ByteString
Lazy.fromStrict ByteString
bytes) of
  Left DeserialiseFailure
failure -> Error -> Either Error Transaction
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionCbor (String -> Text
Text.pack (DeserialiseFailure -> String
forall a. Show a => a -> String
show DeserialiseFailure
failure)))
  Right (ByteString
rest, Either Error Transaction
result)
    | ByteString -> Bool
Lazy.null ByteString
rest -> Either Error Transaction
result
    | Bool
otherwise -> Error -> Either Error Transaction
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionCbor Text
"Trailing transaction CBOR")

-- | Exact transaction encoding. Updates retain unchanged component bytes and
-- the original outer array header and ending, including indefinite framing.
encodeCbor :: Transaction -> ByteString
encodeCbor :: Transaction -> ByteString
encodeCbor Transaction
transaction =
  Transaction -> ByteString
transactionPrefix Transaction
transaction
    ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> EncodedBody -> ByteString
Body.toCbor (Transaction -> EncodedBody
body Transaction
transaction)
    ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> EncodedWitnesses -> ByteString
Witnesses.toCbor (Transaction -> EncodedWitnesses
witnesses Transaction
transaction)
    ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Transaction -> ByteString
transactionSuffix Transaction
transaction

-- | Body with its exact identity-bearing encoding.
body :: Transaction -> Body.EncodedBody
body :: Transaction -> EncodedBody
body = Transaction -> EncodedBody
transactionBody

-- | Outer witness set with its exact encoding.
witnesses :: Transaction -> Witnesses.EncodedWitnesses
witnesses :: Transaction -> EncodedWitnesses
witnesses = Transaction -> EncodedWitnesses
transactionWitnesses

-- | Original outer field order.
frame :: Transaction -> Frame
frame :: Transaction -> Frame
frame = Transaction -> Frame
transactionFrame

-- | Claimed script validity. Historical frames implicitly claim true.
scriptValidity :: Transaction -> Bool
scriptValidity :: Transaction -> Bool
scriptValidity = Transaction -> Bool
transactionValidity

-- | Optional auxiliary data, preserving its original encoding.
auxiliaryData :: Transaction -> Maybe Auxiliary.EncodedAuxiliaryData
auxiliaryData :: Transaction -> Maybe EncodedAuxiliaryData
auxiliaryData = Transaction -> Maybe EncodedAuxiliaryData
transactionAuxiliary

-- | Whether the outer witness set contains at least one datum or redeemer.
-- Script bytes alone do not count, and nested transactions are inspected
-- independently. This does not run or validate a script.
hasScriptData :: Transaction -> Bool
hasScriptData :: Transaction -> Bool
hasScriptData Transaction
transaction =
  let values :: Witnesses
values = EncodedWitnesses -> Witnesses
Witnesses.toWitnesses (Transaction -> EncodedWitnesses
witnesses Transaction
transaction)
   in Bool -> Bool
not ([EncodedPlutusData] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (Witnesses -> [EncodedPlutusData]
Witnesses.datums Witnesses
values) Bool -> Bool -> Bool
&& [Redeemer] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (Witnesses -> [Redeemer]
Witnesses.redeemers Witnesses
values))

-- | BLAKE2b-256 of the exact body bytes, independent of witnesses and framing.
-- Native hashing failures return 'NativeError'.
transactionId :: Transaction -> IO (Either Error TransactionId)
transactionId :: Transaction -> IO (Either Error TransactionId)
transactionId = EncodedBody -> IO (Either Error TransactionId)
Body.hash (EncodedBody -> IO (Either Error TransactionId))
-> (Transaction -> EncodedBody)
-> Transaction
-> IO (Either Error TransactionId)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> EncodedBody
body

-- | Replace the body. A semantically equal body is an exact no-op, retaining
-- existing signatures and encodings. A changed body uses the supplied encoding
-- and removes only the outer verification-key and bootstrap witnesses. Scripts,
-- datums, redeemers, auxiliary data and nested transaction witnesses are retained.
-- The caller must recheck fees, auxiliary-data commitments and ledger validity.
setBody :: Body.EncodedBody -> Transaction -> Transaction
setBody :: EncodedBody -> Transaction -> Transaction
setBody EncodedBody
replacement Transaction
transaction
  | EncodedBody -> Body
Body.toBody EncodedBody
replacement Body -> Body -> Bool
forall a. Eq a => a -> a -> Bool
== EncodedBody -> Body
Body.toBody (Transaction -> EncodedBody
body Transaction
transaction) = Transaction
transaction
  | Bool
otherwise =
      Transaction
transaction
        { transactionBody = replacement,
          transactionWitnesses = Witnesses.removeKeyWitnesses (witnesses transaction)
        }

-- | Change the fee in lovelace, removing outer key signatures when it changes.
-- An unchanged fee preserves the complete original transaction.
setFee :: Word64 -> Transaction -> Transaction
setFee :: Word64 -> Transaction -> Transaction
setFee Word64
lovelace Transaction
transaction =
  EncodedBody -> Transaction -> Transaction
setBody (Word64 -> EncodedBody -> EncodedBody
Body.setFeeEncoded Word64
lovelace (Transaction -> EncodedBody
body Transaction
transaction)) Transaction
transaction

-- | Change claimed script validity without changing the body hash or witnesses.
-- A same-value update is an exact no-op. Historical frames cannot encode false:
-- setting false promotes them to mempool order, retaining definite/indefinite
-- framing and every component byte. Other frames retain their original order.
setScriptValidity :: Bool -> Transaction -> Transaction
setScriptValidity :: Bool -> Transaction -> Transaction
setScriptValidity Bool
valid Transaction
transaction
  | Bool
valid Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
== Transaction -> Bool
scriptValidity Transaction
transaction = Transaction
transaction
  | Bool
otherwise =
      Transaction
transaction
        { transactionValidity = valid,
          transactionFrame = if frame transaction == Historical then Mempool else frame transaction,
          transactionPrefix = if frame transaction == Historical then promotePrefix prefix else prefix,
          transactionSuffix = case frame transaction of
            Frame
Historical -> ByteString
boolean ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
suffix
            Frame
Mempool -> ByteString
boolean ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Int -> ByteString -> ByteString
ByteString.drop Int
1 ByteString
suffix
            Frame
Block -> ByteString
-> (EncodedAuxiliaryData -> ByteString)
-> Maybe EncodedAuxiliaryData
-> ByteString
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Word8 -> ByteString
ByteString.singleton Word8
0xf6) EncodedAuxiliaryData -> ByteString
Auxiliary.toCbor (Transaction -> Maybe EncodedAuxiliaryData
auxiliaryData Transaction
transaction) ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
boolean ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
ending
        }
  where
    prefix :: ByteString
prefix = Transaction -> ByteString
transactionPrefix Transaction
transaction
    suffix :: ByteString
suffix = Transaction -> ByteString
transactionSuffix Transaction
transaction
    boolean :: ByteString
boolean = Word8 -> ByteString
ByteString.singleton (if Bool
valid then Word8
0xf5 else Word8
0xf4)
    ending :: ByteString
ending = if ByteString
prefix ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== Word8 -> ByteString
ByteString.singleton Word8
0x9f then Word8 -> ByteString
ByteString.singleton Word8
0xff else ByteString
ByteString.empty
    promotePrefix :: ByteString -> ByteString
promotePrefix ByteString
original
      | ByteString
original ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== Word8 -> ByteString
ByteString.singleton Word8
0x9f = ByteString
original
      | ByteString -> Int
ByteString.length ByteString
original Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1 = Word8 -> ByteString
ByteString.singleton Word8
0x84
      | Bool
otherwise = case ByteString -> Maybe (ByteString, Word8)
ByteString.unsnoc ByteString
original of
          Maybe (ByteString, Word8)
Nothing -> Word8 -> ByteString
ByteString.singleton Word8
0x84
          Just (ByteString
initial, Word8
_) -> ByteString
initial ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Word8 -> ByteString
ByteString.singleton Word8
4

-- | Replace auxiliary data without changing the body or its key signatures.
-- This does not update the body's auxiliary-data commitment: supply a matching
-- body separately using 'setBody'. Equal auxiliary bytes are an exact no-op.
setAuxiliaryData :: Maybe Auxiliary.EncodedAuxiliaryData -> Transaction -> Transaction
setAuxiliaryData :: Maybe EncodedAuxiliaryData -> Transaction -> Transaction
setAuxiliaryData Maybe EncodedAuxiliaryData
replacement Transaction
transaction
  | Maybe EncodedAuxiliaryData
replacement Maybe EncodedAuxiliaryData -> Maybe EncodedAuxiliaryData -> Bool
forall a. Eq a => a -> a -> Bool
== Transaction -> Maybe EncodedAuxiliaryData
auxiliaryData Transaction
transaction = Transaction
transaction
  | Bool
otherwise =
      Transaction
transaction
        { transactionAuxiliary = replacement,
          transactionSuffix = case frame transaction of
            Frame
Historical -> ByteString
auxiliary ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
ending
            Frame
Mempool -> ByteString
boolean ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
auxiliary ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
ending
            Frame
Block -> ByteString
auxiliary ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
boolean ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
ending
        }
  where
    auxiliary :: ByteString
auxiliary = ByteString
-> (EncodedAuxiliaryData -> ByteString)
-> Maybe EncodedAuxiliaryData
-> ByteString
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Word8 -> ByteString
ByteString.singleton Word8
0xf6) EncodedAuxiliaryData -> ByteString
Auxiliary.toCbor Maybe EncodedAuxiliaryData
replacement
    boolean :: ByteString
boolean = Word8 -> ByteString
ByteString.singleton (if Transaction -> Bool
scriptValidity Transaction
transaction then Word8
0xf5 else Word8
0xf4)
    ending :: ByteString
ending = if Transaction -> ByteString
transactionPrefix Transaction
transaction ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== Word8 -> ByteString
ByteString.singleton Word8
0x9f then Word8 -> ByteString
ByteString.singleton Word8
0xff else ByteString
ByteString.empty

-- | Replace the outer witness set without changing the body, its hash or any
-- framing bytes. An equal witness value preserves the original encoding.
setWitnesses :: Witnesses.EncodedWitnesses -> Transaction -> Transaction
setWitnesses :: EncodedWitnesses -> Transaction -> Transaction
setWitnesses EncodedWitnesses
replacement Transaction
transaction
  | EncodedWitnesses -> Witnesses
Witnesses.toWitnesses EncodedWitnesses
replacement Witnesses -> Witnesses -> Bool
forall a. Eq a => a -> a -> Bool
== EncodedWitnesses -> Witnesses
Witnesses.toWitnesses (Transaction -> EncodedWitnesses
witnesses Transaction
transaction) = Transaction
transaction
  | Bool
otherwise = Transaction
transaction {transactionWitnesses = replacement}

-- | Merge partial witnesses into the outer set. Conflicting signatures for the
-- same verification key fail. Unchanged body and nested witness bytes remain
-- exact; no signature verification or script evaluation occurs.
addWitnesses :: Witnesses.EncodedWitnesses -> Transaction -> Either Error Transaction
addWitnesses :: EncodedWitnesses -> Transaction -> Either Error Transaction
addWitnesses EncodedWitnesses
additions Transaction
transaction = do
  EncodedWitnesses
combined <- EncodedWitnesses
-> EncodedWitnesses -> Either Error EncodedWitnesses
Witnesses.mergeEncoded (Transaction -> EncodedWitnesses
witnesses Transaction
transaction) EncodedWitnesses
additions
  Transaction -> Either Error Transaction
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (EncodedWitnesses -> Transaction -> Transaction
setWitnesses EncodedWitnesses
combined Transaction
transaction)

-- The spans come from the original immutable input. Parsing a term only locates
-- its end; component decoders validate their schema against the exact slice.
decodeFrame :: ByteString -> D.Decoder s (Either Error Transaction)
decodeFrame :: forall s. ByteString -> Decoder s (Either Error Transaction)
decodeFrame ByteString
bytes = do
  Maybe Int
size <- Decoder s (Maybe Int)
forall s. Decoder s (Maybe Int)
D.decodeListLenOrIndef
  [(ByteString, Int, Int)]
fields <- case Maybe Int
size of
    Just Int
count -> do
      Bool -> Decoder s () -> Decoder s ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Int
count Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
3 Bool -> Bool -> Bool
|| Int
count Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
4) (String -> Decoder s ()
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"Incorrect transaction frame arity")
      Int
-> Decoder s (ByteString, Int, Int)
-> Decoder s [(ByteString, Int, Int)]
forall (m :: * -> *) a. Applicative m => Int -> m a -> m [a]
replicateM Int
count Decoder s (ByteString, Int, Int)
forall {s}. Decoder s (ByteString, Int, Int)
item
    Maybe Int
Nothing -> Decoder s [(ByteString, Int, Int)]
forall {s}. Decoder s [(ByteString, Int, Int)]
indefinite
  Either Error Transaction -> Decoder s (Either Error Transaction)
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error Transaction -> Decoder s (Either Error Transaction))
-> Either Error Transaction -> Decoder s (Either Error Transaction)
forall a b. (a -> b) -> a -> b
$ case [(ByteString, Int, Int)]
fields of
    [(ByteString
bodyBytes, Int
start, Int
_), (ByteString
witnessBytes, Int
_, Int
witnessEnd), (ByteString
third, Int
_, Int
_)] ->
      Frame
-> Bool
-> ByteString
-> ByteString
-> ByteString
-> Int
-> Int
-> Either Error Transaction
assembleDecoded Frame
Historical Bool
True ByteString
bodyBytes ByteString
witnessBytes ByteString
third Int
start Int
witnessEnd
    [(ByteString
bodyBytes, Int
start, Int
_), (ByteString
witnessBytes, Int
_, Int
witnessEnd), (ByteString
third, Int
_, Int
_), (ByteString
fourth, Int
_, Int
_)]
      | ByteString
third ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== Bool -> ByteString
boolBytes Bool
True Bool -> Bool -> Bool
|| ByteString
third ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== Bool -> ByteString
boolBytes Bool
False ->
          Frame
-> Bool
-> ByteString
-> ByteString
-> ByteString
-> Int
-> Int
-> Either Error Transaction
assembleDecoded Frame
Mempool (ByteString
third ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== Bool -> ByteString
boolBytes Bool
True) ByteString
bodyBytes ByteString
witnessBytes ByteString
fourth Int
start Int
witnessEnd
      | ByteString
fourth ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== Bool -> ByteString
boolBytes Bool
True Bool -> Bool -> Bool
|| ByteString
fourth ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== Bool -> ByteString
boolBytes Bool
False ->
          Frame
-> Bool
-> ByteString
-> ByteString
-> ByteString
-> Int
-> Int
-> Either Error Transaction
assembleDecoded Frame
Block (ByteString
fourth ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== Bool -> ByteString
boolBytes Bool
True) ByteString
bodyBytes ByteString
witnessBytes ByteString
third Int
start Int
witnessEnd
    [(ByteString, Int, Int)]
_ -> Error -> Either Error Transaction
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionCbor Text
"Invalid transaction frame")
  where
    item :: Decoder s (ByteString, Int, Int)
item = do
      (Term
_, ByteOffset
start, ByteOffset
end) <- Decoder s Term -> Decoder s (Term, ByteOffset, ByteOffset)
forall s a. Decoder s a -> Decoder s (a, ByteOffset, ByteOffset)
D.decodeWithByteSpan Decoder s Term
forall s. Decoder s Term
T.decodeTerm
      let value :: ByteString
value = 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)
      (ByteString, Int, Int) -> Decoder s (ByteString, Int, Int)
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ByteString
value, ByteOffset -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral ByteOffset
start, ByteOffset -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral ByteOffset
end)
    indefinite :: Decoder s [(ByteString, Int, Int)]
indefinite = do
      Bool
ended <- Decoder s Bool
forall s. Decoder s Bool
D.decodeBreakOr
      if Bool
ended
        then [(ByteString, Int, Int)] -> Decoder s [(ByteString, Int, Int)]
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure []
        else do
          (ByteString, Int, Int)
first <- Decoder s (ByteString, Int, Int)
forall {s}. Decoder s (ByteString, Int, Int)
item
          [(ByteString, Int, Int)]
remaining <- Decoder s [(ByteString, Int, Int)]
indefinite
          [(ByteString, Int, Int)] -> Decoder s [(ByteString, Int, Int)]
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((ByteString, Int, Int)
first (ByteString, Int, Int)
-> [(ByteString, Int, Int)] -> [(ByteString, Int, Int)]
forall a. a -> [a] -> [a]
: [(ByteString, Int, Int)]
remaining)
    assembleDecoded :: Frame
-> Bool
-> ByteString
-> ByteString
-> ByteString
-> Int
-> Int
-> Either Error Transaction
assembleDecoded Frame
layout Bool
valid ByteString
bodyBytes ByteString
witnessBytes ByteString
auxiliaryBytes Int
start Int
witnessEnd = do
      EncodedBody
encodedBody <- ByteString -> Either Error EncodedBody
Body.decodeCbor ByteString
bodyBytes
      EncodedWitnesses
encodedWitnesses <- ByteString -> Either Error EncodedWitnesses
Witnesses.decodeCbor ByteString
witnessBytes
      Maybe EncodedAuxiliaryData
auxiliary <-
        if ByteString
auxiliaryBytes ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== Word8 -> ByteString
ByteString.singleton Word8
0xf6
          then Maybe EncodedAuxiliaryData
-> Either Error (Maybe EncodedAuxiliaryData)
forall a b. b -> Either a b
Right Maybe EncodedAuxiliaryData
forall a. Maybe a
Nothing
          else EncodedAuxiliaryData -> Maybe EncodedAuxiliaryData
forall a. a -> Maybe a
Just (EncodedAuxiliaryData -> Maybe EncodedAuxiliaryData)
-> Either Error EncodedAuxiliaryData
-> Either Error (Maybe EncodedAuxiliaryData)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either Error EncodedAuxiliaryData
Auxiliary.decodeCbor ByteString
auxiliaryBytes
      Transaction -> Either Error Transaction
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
        ( EncodedBody
-> EncodedWitnesses
-> Frame
-> Bool
-> Maybe EncodedAuxiliaryData
-> ByteString
-> ByteString
-> Transaction
Transaction
            EncodedBody
encodedBody
            EncodedWitnesses
encodedWitnesses
            Frame
layout
            Bool
valid
            Maybe EncodedAuxiliaryData
auxiliary
            (Int -> ByteString -> ByteString
ByteString.take Int
start ByteString
bytes)
            (Int -> ByteString -> ByteString
ByteString.drop Int
witnessEnd ByteString
bytes)
        )
    boolBytes :: Bool -> ByteString
boolBytes Bool
valid = Word8 -> ByteString
ByteString.singleton (if Bool
valid then Word8
0xf5 else Word8
0xf4)

-- | Change a present body's collection tag, retaining unrelated field bytes.
-- An encoding change removes outer key/bootstrap signatures even when the body
-- has the same semantic values. Absent fields and unchanged tags are exact no-ops.
-- Recheck fees and protocol encoding requirements before signing again.
setBodySetEncoding :: Body.SetField -> SetEncoding -> Transaction -> Transaction
setBodySetEncoding :: SetField -> SetEncoding -> Transaction -> Transaction
setBodySetEncoding SetField
field SetEncoding
requested Transaction
transaction
  | EncodedBody
replacement EncodedBody -> EncodedBody -> Bool
forall a. Eq a => a -> a -> Bool
== Transaction -> EncodedBody
body Transaction
transaction = Transaction
transaction
  | Bool
otherwise = Transaction
transaction {transactionBody = replacement, transactionWitnesses = Witnesses.removeKeyWitnesses (witnesses transaction)}
  where
    replacement :: EncodedBody
replacement = SetField -> SetEncoding -> EncodedBody -> EncodedBody
Body.withSetEncoding SetField
field SetEncoding
requested (Transaction -> EncodedBody
body Transaction
transaction)