-- 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 #-}
{-# OPTIONS_HADDOCK hide #-}

-- | Select the language views for the outer body's actual script purposes.
-- Mirrors the pinned native get_needed_scripts/get_plutus_languages_used domain
-- traversal, but fails explicitly when a required script or cost model is absent.
-- Script hashing remains in IO; all supplied values and encodings stay unchanged.
module Cometa.Internal.BalancingScripts (usedCostModels) where

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

import qualified Codec.CBOR.Decoding as D
import qualified Cometa.Address as Address
import qualified Cometa.Address.Reward as Reward
import qualified Cometa.Address.Shelley as Shelley
import qualified Cometa.Certificate as Certificate
import qualified Cometa.Certificate.Collection as Certificates
import qualified Cometa.Credential as Credential
import Cometa.Error (Error (InvalidBuildingRequest))
import qualified Cometa.Governance.Action as Action
import qualified Cometa.Governance.Proposal as Proposal
import qualified Cometa.Governance.Voting as Voting
import qualified Cometa.Internal.TransactionCbor as Cbor
import qualified Cometa.Protocol.CostModels as Models
import Cometa.Protocol.Parameters (Parameters)
import qualified Cometa.Protocol.Parameters as Parameters
import qualified Cometa.Script as Script
import qualified Cometa.Script.Plutus as Plutus
import qualified Cometa.SubTransaction as Sub
import qualified Cometa.SubTransaction.Body as SubBody
import Cometa.Transaction (Transaction)
import qualified Cometa.Transaction as Tx
import qualified Cometa.Transaction.Body as Body
import qualified Cometa.Transaction.Fields as Fields
import qualified Cometa.Transaction.Input as Input
import qualified Cometa.Transaction.Output as Output
import Cometa.Transaction.Utxo (Utxo)
import qualified Cometa.Transaction.Utxo as Utxo
import qualified Cometa.Transaction.Witnesses as Witnesses
import Control.Monad (unless)
import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT)
import Data.ByteString (ByteString)
import qualified Data.List as List
import qualified Data.Map.Strict as Map
import Data.Maybe (catMaybes, fromMaybe, mapMaybe)
import qualified Data.Set as Set
import Data.Word (Word8)

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

-- | Select only languages used by required outer scripts. Nested scripts may
-- provide a needed outer script, but nested purposes do not add outer language
-- views. Relevant reference scripts come only from spending/reference inputs of
-- the outer body and nested bodies, never arbitrary wallet/collateral snapshots.
-- Missing/conflicting resolutions, scripts and cost models fail explicitly.
usedCostModels :: Parameters -> [Utxo] -> Transaction -> IO (Either Error Models.CostModels)
usedCostModels :: Parameters -> [Utxo] -> Transaction -> IO (Either Error CostModels)
usedCostModels Parameters
parameters [Utxo]
resolved Transaction
transaction = ExceptT Error IO CostModels -> IO (Either Error CostModels)
forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT (ExceptT Error IO CostModels -> IO (Either Error CostModels))
-> ExceptT Error IO CostModels -> IO (Either Error CostModels)
forall a b. (a -> b) -> a -> b
$ do
  Map Input Utxo
table <- Either Error (Map Input Utxo) -> ExceptT Error IO (Map Input Utxo)
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except ([Utxo] -> Either Error (Map Input Utxo)
snapshotTable [Utxo]
resolved)
  let body :: Body
body = EncodedBody -> Body
Body.toBody (Transaction -> EncodedBody
Tx.body Transaction
transaction)
      fields :: Fields
fields = Body -> Fields
Body.bodyFields Body
body
      nested :: [SubTransaction]
nested = [SubTransaction] -> Maybe [SubTransaction] -> [SubTransaction]
forall a. a -> Maybe a -> a
fromMaybe [] (Body -> Maybe [SubTransaction]
Body.bodySubTransactions Body
body)
      allFields :: [Fields]
allFields = Fields
fields Fields -> [Fields] -> [Fields]
forall a. a -> [a] -> [a]
: (SubTransaction -> Fields) -> [SubTransaction] -> [Fields]
forall a b. (a -> b) -> [a] -> [b]
map (Body -> Fields
SubBody.fields (Body -> Fields)
-> (SubTransaction -> Body) -> SubTransaction -> Fields
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EncodedBody -> Body
SubBody.toBody (EncodedBody -> Body)
-> (SubTransaction -> EncodedBody) -> SubTransaction -> Body
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SubTransaction -> EncodedBody
Sub.body) [SubTransaction]
nested
      relevant :: [Input]
relevant = Set Input -> [Input]
forall a. Set a -> [a]
Set.toList ([Input] -> Set Input
forall a. Ord a => [a] -> Set a
Set.fromList ((Fields -> [Input]) -> [Fields] -> [Input]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Fields -> [Input]
references [Fields]
allFields))
      witnessScripts :: [Script]
witnessScripts =
        Witnesses -> [Script]
Witnesses.scripts (EncodedWitnesses -> Witnesses
Witnesses.toWitnesses (Transaction -> EncodedWitnesses
Tx.witnesses Transaction
transaction))
          [Script] -> [Script] -> [Script]
forall a. Semigroup a => a -> a -> a
<> (SubTransaction -> [Script]) -> [SubTransaction] -> [Script]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Witnesses -> [Script]
Witnesses.scripts (Witnesses -> [Script])
-> (SubTransaction -> Witnesses) -> SubTransaction -> [Script]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EncodedWitnesses -> Witnesses
Witnesses.toWitnesses (EncodedWitnesses -> Witnesses)
-> (SubTransaction -> EncodedWitnesses)
-> SubTransaction
-> Witnesses
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SubTransaction -> EncodedWitnesses
Sub.witnesses) [SubTransaction]
nested
  [Utxo]
sources <- Either Error [Utxo] -> ExceptT Error IO [Utxo]
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except ((Input -> Either Error Utxo) -> [Input] -> Either Error [Utxo]
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) -> [a] -> f [b]
traverse (Map Input Utxo -> Input -> Either Error Utxo
resolve Map Input Utxo
table) [Input]
relevant)
  [Utxo]
spending <- Either Error [Utxo] -> ExceptT Error IO [Utxo]
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except ((Input -> Either Error Utxo) -> [Input] -> Either Error [Utxo]
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) -> [a] -> f [b]
traverse (Map Input Utxo -> Input -> Either Error Utxo
resolve Map Input Utxo
table) (Fields -> [Input]
Fields.fieldInputs Fields
fields))
  [ScriptHash]
policies <- Either Error [ScriptHash] -> ExceptT Error IO [ScriptHash]
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except (ByteString -> Either Error [ScriptHash]
mintPolicies (EncodedBody -> ByteString
Body.toCbor (Transaction -> EncodedBody
Tx.body Transaction
transaction)))
  let needed :: Set ScriptHash
needed = [ScriptHash] -> Set ScriptHash
forall a. Ord a => [a] -> Set a
Set.fromList ((Utxo -> Maybe ScriptHash) -> [Utxo] -> [ScriptHash]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (Output -> Maybe ScriptHash
paymentScript (Output -> Maybe ScriptHash)
-> (Utxo -> Output) -> Utxo -> Maybe ScriptHash
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Utxo -> Output
Utxo.output) [Utxo]
spending [ScriptHash] -> [ScriptHash] -> [ScriptHash]
forall a. Semigroup a => a -> a -> a
<> [ScriptHash]
policies [ScriptHash] -> [ScriptHash] -> [ScriptHash]
forall a. Semigroup a => a -> a -> a
<> Fields -> [ScriptHash]
fieldScripts Fields
fields)
      provided :: [Script]
provided = [Script]
witnessScripts [Script] -> [Script] -> [Script]
forall a. Semigroup a => a -> a -> a
<> (Utxo -> Maybe Script) -> [Utxo] -> [Script]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (Output -> Maybe Script
Output.referenceScript (Output -> Maybe Script)
-> (Utxo -> Output) -> Utxo -> Maybe Script
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Utxo -> Output
Utxo.output) [Utxo]
sources
  [(ScriptHash, Script)]
hashed <- (Script -> ExceptT Error IO (ScriptHash, Script))
-> [Script] -> ExceptT Error IO [(ScriptHash, Script)]
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) -> [a] -> f [b]
traverse Script -> ExceptT Error IO (ScriptHash, Script)
hashScript [Script]
provided
  [Maybe Word8]
languages <- Either Error [Maybe Word8] -> ExceptT Error IO [Maybe Word8]
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except ((ScriptHash -> Either Error (Maybe Word8))
-> [ScriptHash] -> Either Error [Maybe Word8]
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) -> [a] -> f [b]
traverse (Map ScriptHash Script -> ScriptHash -> Either Error (Maybe Word8)
languageFor ([(ScriptHash, Script)] -> Map ScriptHash Script
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList [(ScriptHash, Script)]
hashed)) (Set ScriptHash -> [ScriptHash]
forall a. Set a -> [a]
Set.toList Set ScriptHash
needed))
  [CostModel]
models <- Either Error [CostModel] -> ExceptT Error IO [CostModel]
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except ((Word8 -> Either Error CostModel)
-> [Word8] -> Either Error [CostModel]
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) -> [a] -> f [b]
traverse Word8 -> Either Error CostModel
lookupModel (Set Word8 -> [Word8]
forall a. Set a -> [a]
Set.toList ([Word8] -> Set Word8
forall a. Ord a => [a] -> Set a
Set.fromList ([Maybe Word8] -> [Word8]
forall a. [Maybe a] -> [a]
catMaybes [Maybe Word8]
languages))))
  CostModels -> ExceptT Error IO CostModels
forall a. a -> ExceptT Error IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([CostModel] -> CostModels
Models.fromList [CostModel]
models)
  where
    hashScript :: Script -> ExceptT Error IO (ScriptHash, Script)
hashScript Script
script = do
      ScriptHash
digest <- IO (Either Error ScriptHash) -> ExceptT Error IO ScriptHash
forall e (m :: * -> *) a. m (Either e a) -> ExceptT e m a
ExceptT (Script -> IO (Either Error ScriptHash)
Script.hash Script
script)
      (ScriptHash, Script) -> ExceptT Error IO (ScriptHash, Script)
forall a. a -> ExceptT Error IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ScriptHash
digest, Script
script)
    lookupModel :: Word8 -> Either Error CostModel
lookupModel Word8
language =
      Either Error CostModel
-> (CostModel -> Either Error CostModel)
-> Maybe CostModel
-> Either Error CostModel
forall b a. b -> (a -> b) -> Maybe a -> b
maybe
        (Error -> Either Error CostModel
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"A required script language has no cost model"))
        CostModel -> Either Error CostModel
forall a b. b -> Either a b
Right
        (Parameters -> Maybe CostModels
Parameters.parameterCostModels Parameters
parameters Maybe CostModels
-> (CostModels -> Maybe CostModel) -> Maybe CostModel
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Word8 -> CostModels -> Maybe CostModel
Models.lookup Word8
language)

snapshotTable :: [Utxo] -> Either Error (Map.Map Input.Input Utxo)
snapshotTable :: [Utxo] -> Either Error (Map Input Utxo)
snapshotTable = (Either Error (Map Input Utxo)
 -> Utxo -> Either Error (Map Input Utxo))
-> Either Error (Map Input Utxo)
-> [Utxo]
-> Either Error (Map Input Utxo)
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
List.foldl' Either Error (Map Input Utxo)
-> Utxo -> Either Error (Map Input Utxo)
add (Map Input Utxo -> Either Error (Map Input Utxo)
forall a b. b -> Either a b
Right Map Input Utxo
forall k a. Map k a
Map.empty)
  where
    add :: Either Error (Map Input Utxo)
-> Utxo -> Either Error (Map Input Utxo)
add Either Error (Map Input Utxo)
result Utxo
utxo = do
      Map Input Utxo
table <- Either Error (Map Input Utxo)
result
      case Input -> Map Input Utxo -> Maybe Utxo
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup (Utxo -> Input
Utxo.input Utxo
utxo) Map Input Utxo
table of
        Just Utxo
previous -> do
          Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Utxo
previous Utxo -> Utxo -> Bool
forall a. Eq a => a -> a -> Bool
== Utxo
utxo) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"Conflicting script-resolution snapshots"))
          Map Input Utxo -> Either Error (Map Input Utxo)
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Map Input Utxo
table
        Maybe Utxo
Nothing -> Map Input Utxo -> Either Error (Map Input Utxo)
forall a b. b -> Either a b
Right (Input -> Utxo -> Map Input Utxo -> Map Input Utxo
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert (Utxo -> Input
Utxo.input Utxo
utxo) Utxo
utxo Map Input Utxo
table)

resolve :: Map.Map Input.Input Utxo -> Input.Input -> Either Error Utxo
resolve :: Map Input Utxo -> Input -> Either Error Utxo
resolve Map Input Utxo
table Input
reference = Either Error Utxo
-> (Utxo -> Either Error Utxo) -> Maybe Utxo -> Either Error Utxo
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Error -> Either Error Utxo
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"A script-resolution input is missing")) Utxo -> Either Error Utxo
forall a b. b -> Either a b
Right (Input -> Map Input Utxo -> Maybe Utxo
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Input
reference Map Input Utxo
table)

references :: Fields.Fields -> [Input.Input]
references :: Fields -> [Input]
references Fields
fields = Fields -> [Input]
Fields.fieldInputs Fields
fields [Input] -> [Input] -> [Input]
forall a. Semigroup a => a -> a -> a
<> [Input] -> Maybe [Input] -> [Input]
forall a. a -> Maybe a -> a
fromMaybe [] (Fields -> Maybe [Input]
Fields.fieldReferenceInputs Fields
fields)

paymentScript :: Output.Output -> Maybe Credential.ScriptHash
paymentScript :: Output -> Maybe ScriptHash
paymentScript Output
output = case Output -> Address
Output.address Output
output of
  Address.ShelleyAddress Address
address -> Credential Payment -> Maybe ScriptHash
forall purpose. Credential purpose -> Maybe ScriptHash
credentialScript (Address -> Credential Payment
Shelley.paymentCredential Address
address)
  Address.ByronAddress Address
_ -> Maybe ScriptHash
forall a. Maybe a
Nothing
  Address.RewardAddress RewardAddress
_ -> Maybe ScriptHash
forall a. Maybe a
Nothing

credentialScript :: Credential.Credential purpose -> Maybe Credential.ScriptHash
credentialScript :: forall purpose. Credential purpose -> Maybe ScriptHash
credentialScript Credential purpose
credential = case Credential purpose
credential of
  Credential.KeyCredential KeyHash purpose
_ -> Maybe ScriptHash
forall a. Maybe a
Nothing
  Credential.ScriptCredential ScriptHash
hash -> ScriptHash -> Maybe ScriptHash
forall a. a -> Maybe a
Just ScriptHash
hash

-- Native walker visits only field14 guards, not the field24 account guard map.
fieldScripts :: Fields.Fields -> [Credential.ScriptHash]
fieldScripts :: Fields -> [ScriptHash]
fieldScripts Fields
fields =
  ((RewardAddress, Word64) -> Maybe ScriptHash)
-> [(RewardAddress, Word64)] -> [ScriptHash]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (Credential Stake -> Maybe ScriptHash
forall purpose. Credential purpose -> Maybe ScriptHash
credentialScript (Credential Stake -> Maybe ScriptHash)
-> ((RewardAddress, Word64) -> Credential Stake)
-> (RewardAddress, Word64)
-> Maybe ScriptHash
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RewardAddress -> Credential Stake
Reward.credential (RewardAddress -> Credential Stake)
-> ((RewardAddress, Word64) -> RewardAddress)
-> (RewardAddress, Word64)
-> Credential Stake
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (RewardAddress, Word64) -> RewardAddress
forall a b. (a, b) -> a
fst) ([(RewardAddress, Word64)]
-> (Entries RewardAddress Word64 -> [(RewardAddress, Word64)])
-> Maybe (Entries RewardAddress Word64)
-> [(RewardAddress, Word64)]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] Entries RewardAddress Word64 -> [(RewardAddress, Word64)]
forall key value. Entries key value -> [(key, value)]
Fields.entries (Fields -> Maybe (Entries RewardAddress Word64)
Fields.fieldWithdrawals Fields
fields))
    [ScriptHash] -> [ScriptHash] -> [ScriptHash]
forall a. Semigroup a => a -> a -> a
<> (Certificate -> [ScriptHash]) -> [Certificate] -> [ScriptHash]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Certificate -> [ScriptHash]
certificateScripts ([Certificate]
-> (Certificates -> [Certificate])
-> Maybe Certificates
-> [Certificate]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] Certificates -> [Certificate]
Certificates.toList (Fields -> Maybe Certificates
Fields.fieldCertificates Fields
fields))
    [ScriptHash] -> [ScriptHash] -> [ScriptHash]
forall a. Semigroup a => a -> a -> a
<> ((Voter, ActionId, VotingProcedure) -> [ScriptHash])
-> [(Voter, ActionId, VotingProcedure)] -> [ScriptHash]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (\(Voter
voter, ActionId
_, VotingProcedure
_) -> Voter -> [ScriptHash]
voterScripts Voter
voter) ([(Voter, ActionId, VotingProcedure)]
-> (VotingProcedures -> [(Voter, ActionId, VotingProcedure)])
-> Maybe VotingProcedures
-> [(Voter, ActionId, VotingProcedure)]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] VotingProcedures -> [(Voter, ActionId, VotingProcedure)]
Voting.toList (Fields -> Maybe VotingProcedures
Fields.fieldVotingProcedures Fields
fields))
    [ScriptHash] -> [ScriptHash] -> [ScriptHash]
forall a. Semigroup a => a -> a -> a
<> (Proposal -> Maybe ScriptHash) -> [Proposal] -> [ScriptHash]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (Action -> Maybe ScriptHash
proposalPolicy (Action -> Maybe ScriptHash)
-> (Proposal -> Action) -> Proposal -> Maybe ScriptHash
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Proposal -> Action
Proposal.proposalAction) ([Proposal]
-> (Proposals -> [Proposal]) -> Maybe Proposals -> [Proposal]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] Proposals -> [Proposal]
Proposal.toList (Fields -> Maybe Proposals
Fields.fieldProposalProcedures Fields
fields))
    [ScriptHash] -> [ScriptHash] -> [ScriptHash]
forall a. Semigroup a => a -> a -> a
<> (Credential Guard -> Maybe ScriptHash)
-> [Credential Guard] -> [ScriptHash]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe Credential Guard -> Maybe ScriptHash
forall purpose. Credential purpose -> Maybe ScriptHash
credentialScript ([Credential Guard]
-> Maybe [Credential Guard] -> [Credential Guard]
forall a. a -> Maybe a -> a
fromMaybe [] (Fields -> Maybe [Credential Guard]
Fields.fieldGuards Fields
fields))

-- Registration0 carries no authorizing credential; registration7 does. Combined
-- certificates authorize the stake credential, not the delegated pool or DRep.
-- Committee hot authorization requires the cold credential. Do not use the hot
-- credential or constitution metadata/guardrails as additional cert purposes.
certificateScripts :: Certificate.Certificate -> [Credential.ScriptHash]
certificateScripts :: Certificate -> [ScriptHash]
certificateScripts Certificate
certificate = case Certificate
certificate of
  Certificate.StakeRegistration Credential Stake
_ -> []
  Certificate.StakeDeregistration Credential Stake
stake -> Credential Stake -> [ScriptHash]
forall {purpose}. Credential purpose -> [ScriptHash]
script Credential Stake
stake
  Certificate.StakeDelegation Credential Stake
stake KeyHash StakePool
_ -> Credential Stake -> [ScriptHash]
forall {purpose}. Credential purpose -> [ScriptHash]
script Credential Stake
stake
  Certificate.PoolRegistration PoolParameters
_ -> []
  Certificate.PoolRetirement KeyHash StakePool
_ Word64
_ -> []
  Certificate.GenesisKeyDelegation {} -> []
  Certificate.MoveInstantaneousRewards Mir
_ -> []
  Certificate.Registration Credential Stake
stake Word64
_ -> Credential Stake -> [ScriptHash]
forall {purpose}. Credential purpose -> [ScriptHash]
script Credential Stake
stake
  Certificate.Unregistration Credential Stake
stake Word64
_ -> Credential Stake -> [ScriptHash]
forall {purpose}. Credential purpose -> [ScriptHash]
script Credential Stake
stake
  Certificate.VoteDelegation Credential Stake
stake DRep
_ -> Credential Stake -> [ScriptHash]
forall {purpose}. Credential purpose -> [ScriptHash]
script Credential Stake
stake
  Certificate.StakeVoteDelegation Credential Stake
stake KeyHash StakePool
_ DRep
_ -> Credential Stake -> [ScriptHash]
forall {purpose}. Credential purpose -> [ScriptHash]
script Credential Stake
stake
  Certificate.StakeRegistrationDelegation Credential Stake
stake KeyHash StakePool
_ Word64
_ -> Credential Stake -> [ScriptHash]
forall {purpose}. Credential purpose -> [ScriptHash]
script Credential Stake
stake
  Certificate.VoteRegistrationDelegation Credential Stake
stake DRep
_ Word64
_ -> Credential Stake -> [ScriptHash]
forall {purpose}. Credential purpose -> [ScriptHash]
script Credential Stake
stake
  Certificate.StakeVoteRegistrationDelegation Credential Stake
stake KeyHash StakePool
_ DRep
_ Word64
_ -> Credential Stake -> [ScriptHash]
forall {purpose}. Credential purpose -> [ScriptHash]
script Credential Stake
stake
  Certificate.AuthorizeCommitteeHot Credential CommitteeCold
cold Credential CommitteeHot
_ -> Credential CommitteeCold -> [ScriptHash]
forall {purpose}. Credential purpose -> [ScriptHash]
script Credential CommitteeCold
cold
  Certificate.ResignCommitteeCold Credential CommitteeCold
cold Maybe Anchor
_ -> Credential CommitteeCold -> [ScriptHash]
forall {purpose}. Credential purpose -> [ScriptHash]
script Credential CommitteeCold
cold
  Certificate.RegisterDRep Credential DRep
drep Word64
_ Maybe Anchor
_ -> Credential DRep -> [ScriptHash]
forall {purpose}. Credential purpose -> [ScriptHash]
script Credential DRep
drep
  Certificate.UnregisterDRep Credential DRep
drep Word64
_ -> Credential DRep -> [ScriptHash]
forall {purpose}. Credential purpose -> [ScriptHash]
script Credential DRep
drep
  Certificate.UpdateDRep Credential DRep
drep Maybe Anchor
_ -> Credential DRep -> [ScriptHash]
forall {purpose}. Credential purpose -> [ScriptHash]
script Credential DRep
drep
  where
    script :: Credential purpose -> [ScriptHash]
script Credential purpose
credential = [ScriptHash]
-> (ScriptHash -> [ScriptHash]) -> Maybe ScriptHash -> [ScriptHash]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] ScriptHash -> [ScriptHash]
forall a. a -> [a]
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Credential purpose -> Maybe ScriptHash
forall purpose. Credential purpose -> Maybe ScriptHash
credentialScript Credential purpose
credential)

voterScripts :: Voting.Voter -> [Credential.ScriptHash]
voterScripts :: Voter -> [ScriptHash]
voterScripts Voter
voter = case Voter
voter of
  Voting.CommitteeVoter Credential CommitteeHot
credential -> Credential CommitteeHot -> [ScriptHash]
forall {purpose}. Credential purpose -> [ScriptHash]
script Credential CommitteeHot
credential
  Voting.DRepVoter Credential DRep
credential -> Credential DRep -> [ScriptHash]
forall {purpose}. Credential purpose -> [ScriptHash]
script Credential DRep
credential
  Voting.StakePoolVoter KeyHash StakePool
_ -> []
  where
    script :: Credential purpose -> [ScriptHash]
script Credential purpose
credential = [ScriptHash]
-> (ScriptHash -> [ScriptHash]) -> Maybe ScriptHash -> [ScriptHash]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] ScriptHash -> [ScriptHash]
forall a. a -> [a]
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Credential purpose -> Maybe ScriptHash
forall purpose. Credential purpose -> Maybe ScriptHash
credentialScript Credential purpose
credential)

proposalPolicy :: Action.Action -> Maybe Credential.ScriptHash
proposalPolicy :: Action -> Maybe ScriptHash
proposalPolicy Action
action = case Action
action of
  Action.ParameterChange Maybe ActionId
_ Update
_ Maybe ScriptHash
policy -> Maybe ScriptHash
policy
  Action.TreasuryWithdrawals Withdrawals
_ Maybe ScriptHash
policy -> Maybe ScriptHash
policy
  Action.HardForkInitiation Maybe ActionId
_ ProtocolVersion
_ -> Maybe ScriptHash
forall a. Maybe a
Nothing
  Action.NoConfidence Maybe ActionId
_ -> Maybe ScriptHash
forall a. Maybe a
Nothing
  Action.UpdateCommittee {} -> Maybe ScriptHash
forall a. Maybe a
Nothing
  Action.NewConstitution Maybe ActionId
_ Constitution
_ -> Maybe ScriptHash
forall a. Maybe a
Nothing
  Action
Action.InfoAction -> Maybe ScriptHash
forall a. Maybe a
Nothing

languageFor :: Map.Map Credential.ScriptHash Script.Script -> Credential.ScriptHash -> Either Error (Maybe Word8)
languageFor :: Map ScriptHash Script -> ScriptHash -> Either Error (Maybe Word8)
languageFor Map ScriptHash Script
provided ScriptHash
hash = case ScriptHash -> Map ScriptHash Script -> Maybe Script
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup ScriptHash
hash Map ScriptHash Script
provided of
  Maybe Script
Nothing -> Error -> Either Error (Maybe Word8)
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"A required body script is missing")
  Just (Script.Native NativeScript
_) -> Maybe Word8 -> Either Error (Maybe Word8)
forall a b. b -> Either a b
Right Maybe Word8
forall a. Maybe a
Nothing
  Just (Script.Plutus PlutusScript
script) -> Maybe Word8 -> Either Error (Maybe Word8)
forall a b. b -> Either a b
Right (Word8 -> Maybe Word8
forall a. a -> Maybe a
Just (Version -> Word8
languageId (PlutusScript -> Version
Plutus.version PlutusScript
script)))

languageId :: Plutus.Version -> Word8
languageId :: Version -> Word8
languageId Version
version = case Version
version of
  Version
Plutus.V1 -> Word8
0
  Version
Plutus.V2 -> Word8
1
  Version
Plutus.V3 -> Word8
2
  Version
Plutus.V4 -> Word8
3

-- The semantic Mint observer intentionally normalizes zero/empty policy maps.
-- Native needed-script traversal still counts their original keys, so read only
-- these keys from the exact body encoding while the validated asset maps are
-- skipped. No source bytes or ledger values are reconstructed or normalized.
mintPolicies :: ByteString -> Either Error [Credential.ScriptHash]
mintPolicies :: ByteString -> Either Error [ScriptHash]
mintPolicies ByteString
bodyBytes = do
  Map Word64 ByteString
fields <- (Text -> Error)
-> (forall s. Decoder s (Map Word64 ByteString))
-> ByteString
-> Either Error (Map Word64 ByteString)
forall a.
(Text -> Error)
-> (forall s. Decoder s a) -> ByteString -> Either Error a
Cbor.decodeAs Text -> Error
InvalidBuildingRequest (ByteString -> Decoder s (Map Word64 ByteString)
forall s. ByteString -> Decoder s (Map Word64 ByteString)
Cbor.mapFields ByteString
bodyBytes) ByteString
bodyBytes
  case Word64 -> Map Word64 ByteString -> Maybe ByteString
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Word64
9 Map Word64 ByteString
fields of
    Maybe ByteString
Nothing -> [ScriptHash] -> Either Error [ScriptHash]
forall a b. b -> Either a b
Right []
    Just ByteString
bytes -> (Text -> Error)
-> (forall s. Decoder s [ScriptHash])
-> ByteString
-> Either Error [ScriptHash]
forall a.
(Text -> Error)
-> (forall s. Decoder s a) -> ByteString -> Either Error a
Cbor.decodeAs Text -> Error
InvalidBuildingRequest (((ByteString, ByteString) -> Decoder s ScriptHash)
-> [(ByteString, ByteString)] -> Decoder s [ScriptHash]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (ByteString, ByteString) -> Decoder s ScriptHash
forall {m :: * -> *} {b}.
MonadFail m =>
(ByteString, b) -> m ScriptHash
decodePolicy ([(ByteString, ByteString)] -> Decoder s [ScriptHash])
-> Decoder s [(ByteString, ByteString)] -> Decoder s [ScriptHash]
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Decoder s (ByteString, ByteString)
-> Decoder s [(ByteString, ByteString)]
forall s a. Decoder s a -> Decoder s [a]
Cbor.entries ((,) (ByteString -> ByteString -> (ByteString, ByteString))
-> Decoder s ByteString
-> Decoder s (ByteString -> (ByteString, ByteString))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s ByteString
forall s. Decoder s ByteString
D.decodeBytes Decoder s (ByteString -> (ByteString, ByteString))
-> Decoder s ByteString -> Decoder s (ByteString, ByteString)
forall a b. Decoder s (a -> b) -> Decoder s a -> Decoder s b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> ByteString -> Decoder s ByteString
forall s. ByteString -> Decoder s ByteString
Cbor.slice ByteString
bytes)) ByteString
bytes
  where
    decodePolicy :: (ByteString, b) -> m ScriptHash
decodePolicy (ByteString
bytes, b
_) = (Error -> m ScriptHash)
-> (ScriptHash -> m ScriptHash)
-> Either Error ScriptHash
-> m ScriptHash
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> m ScriptHash
forall a. String -> m a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> m ScriptHash)
-> (Error -> String) -> Error -> m ScriptHash
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Error -> String
forall a. Show a => a -> String
show) ScriptHash -> m ScriptHash
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ByteString -> Either Error ScriptHash
Credential.scriptHashFromBytes ByteString
bytes)