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

-- | Level-local index inspection shared by top-level and nested transactions.
module Cometa.Internal.TransactionIndices
  ( findInput,
    findReferenceInput,
    findOutput,
    findMintPolicy,
    findWithdrawal,
    findVote,
    findProposal,
    findRedeemer,
    certificateBytes,
  )
where

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

import qualified Codec.CBOR.Decoding as D
import qualified Codec.CBOR.Term as T
import Cometa.Address (Address)
import qualified Cometa.Address as Address
import qualified Cometa.Address.Reward as Reward
import Cometa.AssetId (AssetId (Ada))
import qualified Cometa.Credential as Credential
import Cometa.Evaluation (RedeemerId (..))
import qualified Cometa.Governance.Proposal as Proposal
import qualified Cometa.Governance.Voting as Voting
import qualified Cometa.Internal.TransactionCbor as Cbor
import qualified Cometa.NetworkId as Network
import Cometa.PolicyId (PolicyId)
import qualified Cometa.PolicyId as Policy
import qualified Cometa.Transaction.Fields as Fields
import Cometa.Transaction.Input (Input)
import qualified Cometa.Transaction.Output as Output
import qualified Cometa.Transaction.Redeemer as Redeemer
import qualified Cometa.Value as Value
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.List (sort)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)
import qualified Data.Set as Set
import Data.Word (Word64)

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

findInput :: Input -> Fields.Fields -> Maybe Word64
findInput :: Input -> Fields -> Maybe Word64
findInput Input
reference = (Input -> Bool) -> [Input] -> Maybe Word64
forall a. (a -> Bool) -> [a] -> Maybe Word64
position (Input -> Input -> Bool
forall a. Eq a => a -> a -> Bool
== Input
reference) ([Input] -> Maybe Word64)
-> (Fields -> [Input]) -> Fields -> Maybe Word64
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Input] -> [Input]
forall a. Ord a => [a] -> [a]
sort ([Input] -> [Input]) -> (Fields -> [Input]) -> Fields -> [Input]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Fields -> [Input]
Fields.fieldInputs

findReferenceInput :: Input -> Fields.Fields -> Maybe Word64
findReferenceInput :: Input -> Fields -> Maybe Word64
findReferenceInput Input
reference = (Input -> Bool) -> [Input] -> Maybe Word64
forall a. (a -> Bool) -> [a] -> Maybe Word64
position (Input -> Input -> Bool
forall a. Eq a => a -> a -> Bool
== Input
reference) ([Input] -> Maybe Word64)
-> (Fields -> [Input]) -> Fields -> Maybe Word64
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Input] -> [Input]
forall a. Ord a => [a] -> [a]
sort ([Input] -> [Input]) -> (Fields -> [Input]) -> Fields -> [Input]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Input] -> Maybe [Input] -> [Input]
forall a. a -> Maybe a -> a
fromMaybe [] (Maybe [Input] -> [Input])
-> (Fields -> Maybe [Input]) -> Fields -> [Input]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Fields -> Maybe [Input]
Fields.fieldReferenceInputs

findOutput :: Address -> Word64 -> Fields.Fields -> Maybe Word64
findOutput :: Address -> Word64 -> Fields -> Maybe Word64
findOutput Address
destination Word64
minimumLovelace = (Output -> Bool) -> [Output] -> Maybe Word64
forall a. (a -> Bool) -> [a] -> Maybe Word64
position Output -> Bool
matches ([Output] -> Maybe Word64)
-> (Fields -> [Output]) -> Fields -> Maybe Word64
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Fields -> [Output]
Fields.fieldOutputs
  where
    matches :: Output -> Bool
matches Output
output =
      Address -> ByteString
Address.toBytes (Output -> Address
Output.address Output
output) ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== Address -> ByteString
Address.toBytes Address
destination
        Bool -> Bool -> Bool
&& AssetId -> Value -> Integer
Value.quantity AssetId
Ada (Output -> Value
Output.value Output
output) Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
>= Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
minimumLovelace

findMintPolicy :: PolicyId -> ByteString -> Maybe Word64
findMintPolicy :: PolicyId -> ByteString -> Maybe Word64
findMintPolicy PolicyId
policy ByteString
bytes = do
  ByteString
mint <- Word64 -> ByteString -> Maybe ByteString
fieldBytes Word64
9 ByteString
bytes
  [ByteString]
policies <- (Error -> Maybe [ByteString])
-> ([ByteString] -> Maybe [ByteString])
-> Either Error [ByteString]
-> Maybe [ByteString]
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Maybe [ByteString] -> Error -> Maybe [ByteString]
forall a b. a -> b -> a
const Maybe [ByteString]
forall a. Maybe a
Nothing) [ByteString] -> Maybe [ByteString]
forall a. a -> Maybe a
Just ((forall s. Decoder s [ByteString])
-> ByteString -> Either Error [ByteString]
forall a. (forall s. Decoder s a) -> ByteString -> Either Error a
Cbor.decode (Decoder s ByteString -> Decoder s [ByteString]
forall s a. Decoder s a -> Decoder s [a]
Cbor.entries (Decoder s ByteString
forall s. Decoder s ByteString
D.decodeBytes Decoder s ByteString -> Decoder s Term -> Decoder s ByteString
forall a b. Decoder s a -> Decoder s b -> Decoder s a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* Decoder s Term
forall s. Decoder s Term
T.decodeTerm)) ByteString
mint)
  (ByteString -> Bool) -> [ByteString] -> Maybe Word64
forall a. (a -> Bool) -> [a] -> Maybe Word64
position (ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== PolicyId -> ByteString
Policy.toBytes PolicyId
policy) ([ByteString] -> [ByteString]
forall a. Ord a => [a] -> [a]
sort [ByteString]
policies)

-- Ledger ordering groups non-mainnet tags together and puts scripts first.
findWithdrawal :: Reward.RewardAddress -> Fields.Fields -> Maybe Word64
findWithdrawal :: RewardAddress -> Fields -> Maybe Word64
findWithdrawal RewardAddress
reward = ByteString -> [ByteString] -> Maybe Word64
forall a. Ord a => a -> [a] -> Maybe Word64
rank (RewardAddress -> ByteString
rewardKey RewardAddress
reward) ([ByteString] -> Maybe Word64)
-> (Fields -> [ByteString]) -> Fields -> Maybe Word64
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((RewardAddress, Word64) -> ByteString)
-> [(RewardAddress, Word64)] -> [ByteString]
forall a b. (a -> b) -> [a] -> [b]
map (RewardAddress -> ByteString
rewardKey (RewardAddress -> ByteString)
-> ((RewardAddress, Word64) -> RewardAddress)
-> (RewardAddress, Word64)
-> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (RewardAddress, Word64) -> RewardAddress
forall a b. (a, b) -> a
fst) ([(RewardAddress, Word64)] -> [ByteString])
-> (Fields -> [(RewardAddress, Word64)]) -> Fields -> [ByteString]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [(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 (Maybe (Entries RewardAddress Word64) -> [(RewardAddress, Word64)])
-> (Fields -> Maybe (Entries RewardAddress Word64))
-> Fields
-> [(RewardAddress, Word64)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Fields -> Maybe (Entries RewardAddress Word64)
Fields.fieldWithdrawals

rewardKey :: Reward.RewardAddress -> ByteString
rewardKey :: RewardAddress -> ByteString
rewardKey RewardAddress
reward = Word8 -> ByteString -> ByteString
B.cons (if RewardAddress -> NetworkId
Reward.networkId RewardAddress
reward NetworkId -> NetworkId -> Bool
forall a. Eq a => a -> a -> Bool
== NetworkId
Network.mainnet then Word8
1 else Word8
0) (Credential Stake -> ByteString
forall purpose. Credential purpose -> ByteString
credentialKey (RewardAddress -> Credential Stake
Reward.credential RewardAddress
reward))

credentialKey :: Credential.Credential purpose -> ByteString
credentialKey :: forall purpose. Credential purpose -> ByteString
credentialKey Credential purpose
authority = case Credential purpose
authority of
  Credential.ScriptCredential ScriptHash
hash -> Word8 -> ByteString -> ByteString
B.cons Word8
0 (ScriptHash -> ByteString
Credential.scriptHashBytes ScriptHash
hash)
  Credential.KeyCredential KeyHash purpose
hash -> Word8 -> ByteString -> ByteString
B.cons Word8
1 (KeyHash purpose -> ByteString
forall purpose. KeyHash purpose -> ByteString
Credential.keyHashBytes KeyHash purpose
hash)

findVote :: Voting.Voter -> Fields.Fields -> Maybe Word64
findVote :: Voter -> Fields -> Maybe Word64
findVote Voter
voter = ByteString -> [ByteString] -> Maybe Word64
forall a. Ord a => a -> [a] -> Maybe Word64
rank (Voter -> ByteString
voterKey Voter
voter) ([ByteString] -> Maybe Word64)
-> (Fields -> [ByteString]) -> Fields -> Maybe Word64
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Voter -> ByteString) -> [Voter] -> [ByteString]
forall a b. (a -> b) -> [a] -> [b]
map Voter -> ByteString
voterKey ([Voter] -> [ByteString])
-> (Fields -> [Voter]) -> Fields -> [ByteString]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Set Voter -> [Voter]
forall a. Set a -> [a]
Set.toList (Set Voter -> [Voter])
-> (Fields -> Set Voter) -> Fields -> [Voter]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Voter] -> Set Voter
forall a. Ord a => [a] -> Set a
Set.fromList ([Voter] -> Set Voter)
-> (Fields -> [Voter]) -> Fields -> Set Voter
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((Voter, ActionId, VotingProcedure) -> Voter)
-> [(Voter, ActionId, VotingProcedure)] -> [Voter]
forall a b. (a -> b) -> [a] -> [b]
map (\(Voter
authority, ActionId
_, VotingProcedure
_) -> Voter
authority) ([(Voter, ActionId, VotingProcedure)] -> [Voter])
-> (Fields -> [(Voter, ActionId, VotingProcedure)])
-> Fields
-> [Voter]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [(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 (Maybe VotingProcedures -> [(Voter, ActionId, VotingProcedure)])
-> (Fields -> Maybe VotingProcedures)
-> Fields
-> [(Voter, ActionId, VotingProcedure)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Fields -> Maybe VotingProcedures
Fields.fieldVotingProcedures

findProposal :: Proposal.Proposal -> Fields.Fields -> Maybe Word64
findProposal :: Proposal -> Fields -> Maybe Word64
findProposal Proposal
proposal = (Proposal -> Bool) -> [Proposal] -> Maybe Word64
forall a. (a -> Bool) -> [a] -> Maybe Word64
position ((ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== Proposal -> ByteString
Proposal.encodeCbor Proposal
proposal) (ByteString -> Bool)
-> (Proposal -> ByteString) -> Proposal -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Proposal -> ByteString
Proposal.encodeCbor) ([Proposal] -> Maybe Word64)
-> (Fields -> [Proposal]) -> Fields -> Maybe Word64
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Proposal]
-> (Proposals -> [Proposal]) -> Maybe Proposals -> [Proposal]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] Proposals -> [Proposal]
Proposal.toList (Maybe Proposals -> [Proposal])
-> (Fields -> Maybe Proposals) -> Fields -> [Proposal]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Fields -> Maybe Proposals
Fields.fieldProposalProcedures

voterKey :: Voting.Voter -> ByteString
voterKey :: Voter -> ByteString
voterKey Voter
voter = case Voter
voter of
  Voting.CommitteeVoter Credential CommitteeHot
authority -> Word8 -> ByteString -> ByteString
B.cons Word8
0 (Credential CommitteeHot -> ByteString
forall purpose. Credential purpose -> ByteString
credentialKey Credential CommitteeHot
authority)
  Voting.DRepVoter Credential DRep
authority -> Word8 -> ByteString -> ByteString
B.cons Word8
1 (Credential DRep -> ByteString
forall purpose. Credential purpose -> ByteString
credentialKey Credential DRep
authority)
  Voting.StakePoolVoter KeyHash StakePool
hash -> Word8 -> ByteString -> ByteString
B.cons Word8
2 (Word8 -> ByteString -> ByteString
B.cons Word8
1 (KeyHash StakePool -> ByteString
forall purpose. KeyHash purpose -> ByteString
Credential.keyHashBytes KeyHash StakePool
hash))

findRedeemer :: RedeemerId -> [Redeemer.Redeemer] -> Maybe Word64
findRedeemer :: RedeemerId -> [Redeemer] -> Maybe Word64
findRedeemer RedeemerId
identifier = RedeemerId -> [RedeemerId] -> Maybe Word64
forall a. Ord a => a -> [a] -> Maybe Word64
rank RedeemerId
identifier ([RedeemerId] -> Maybe Word64)
-> ([Redeemer] -> [RedeemerId]) -> [Redeemer] -> Maybe Word64
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Redeemer -> RedeemerId) -> [Redeemer] -> [RedeemerId]
forall a b. (a -> b) -> [a] -> [b]
map (\Redeemer
value -> Purpose -> Word32 -> RedeemerId
RedeemerId (Redeemer -> Purpose
Redeemer.purpose Redeemer
value) (Redeemer -> Word32
Redeemer.index Redeemer
value))

certificateBytes :: ByteString -> Maybe ByteString
certificateBytes :: ByteString -> Maybe ByteString
certificateBytes = Word64 -> ByteString -> Maybe ByteString
fieldBytes Word64
4

fieldBytes :: Word64 -> ByteString -> Maybe ByteString
fieldBytes :: Word64 -> ByteString -> Maybe ByteString
fieldBytes Word64
key ByteString
bytes = do
  Map Word64 ByteString
fields <- (Error -> Maybe (Map Word64 ByteString))
-> (Map Word64 ByteString -> Maybe (Map Word64 ByteString))
-> Either Error (Map Word64 ByteString)
-> Maybe (Map Word64 ByteString)
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Maybe (Map Word64 ByteString)
-> Error -> Maybe (Map Word64 ByteString)
forall a b. a -> b -> a
const Maybe (Map Word64 ByteString)
forall a. Maybe a
Nothing) Map Word64 ByteString -> Maybe (Map Word64 ByteString)
forall a. a -> Maybe a
Just ((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)
  Word64 -> Map Word64 ByteString -> Maybe ByteString
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Word64
key Map Word64 ByteString
fields

-- Native lookups count items strictly below the requested ledger key.
rank :: (Ord a) => a -> [a] -> Maybe Word64
rank :: forall a. Ord a => a -> [a] -> Maybe Word64
rank a
target [a]
values
  | a
target a -> [a] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [a]
values = Word64 -> Maybe Word64
forall a. a -> Maybe a
Just (Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([a] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ((a -> Bool) -> [a] -> [a]
forall a. (a -> Bool) -> [a] -> [a]
filter (a -> a -> Bool
forall a. Ord a => a -> a -> Bool
< a
target) [a]
values)))
  | Bool
otherwise = Maybe Word64
forall a. Maybe a
Nothing

position :: (a -> Bool) -> [a] -> Maybe Word64
position :: forall a. (a -> Bool) -> [a] -> Maybe Word64
position a -> Bool
matches = Word64 -> [a] -> Maybe Word64
forall {t}. Num t => t -> [a] -> Maybe t
go Word64
0
  where
    go :: t -> [a] -> Maybe t
go t
_ [] = Maybe t
forall a. Maybe a
Nothing
    go t
index (a
value : [a]
rest)
      | a -> Bool
matches a
value = t -> Maybe t
forall a. a -> Maybe a
Just t
index
      | Bool
otherwise = t -> [a] -> Maybe t
go (t
index t -> t -> t
forall a. Num a => a -> a -> a
+ t
1) [a]
rest