{-# LANGUAGE OverloadedRecordDot #-}
{-# OPTIONS_GHC -Wno-ambiguous-fields #-}

module Hydra.HeadLogic.OperationWorkflowSpec (spec) where

import Cardano.Binary (decodeFull', serialize')
import Data.Map.Strict qualified as Map
import Data.Sequence qualified as Seq
import Hydra.API.ClientInput qualified as Client
import Hydra.API.ServerOutput qualified as Server
import Hydra.Agda.OffChainReference qualified as Agda
import Hydra.Chain (ChainEvent (..), OnChainTx (..), PostChainTx (FinalPartialFanoutTx))
import Hydra.HeadLogic.Error (LogicError (AssertionFailed))
import Hydra.HeadLogic.Interpreter qualified as Interpreter
import Hydra.HeadLogic.Program (reject)
import Hydra.HeadLogic.Rules.Chain.Deposits qualified as Deposits
import Hydra.HeadLogic.Rules.Input qualified as Input
import Hydra.HeadLogic.Rules.Network.AckSn qualified as AckSn
import Hydra.HeadLogic.State (HeadState (FanoutProgress), OnChainFanoutDatum (DatumFanoutProgress), PartialFanoutState (distributedOutputs, fanoutDatum, remainingOutputs))
import Hydra.HeadLogic.Trace (TraceStep (..))
import Hydra.HeadLogic.Workflow qualified as Workflow
import Hydra.HeadLogicSpec (withAccumulators)
import Hydra.Ledger.Simple (SimpleTx (..), simpleLedger)
import Hydra.Network.Message (Message (ReqSn))
import Hydra.Node.Environment (Environment (depositActivation, depositPeriod))
import Hydra.Node.HeadLogic (CoordinatedHeadState (..), Effect (..), Input (..), OpenState (..), Outcome (..), StateChanged (..), aggregateState, mkSeenSnapshot, ruleEnvironment)
import Hydra.Node.State (Deposit (..), DepositStatus (..), NodeState (..), initialChainTime, trackedFromPending)
import Hydra.Prelude hiding (label, state, trace)
import Hydra.Tx.Crypto (aggregate, sign)
import Hydra.Tx.DepositPeriod qualified as DepositPeriod
import Hydra.Tx.Snapshot (Snapshot (..))
import Test.Hydra.HeadLogic.InputFixtures qualified as Inputs
import Test.Hydra.HeadLogic.Interpreter (testInterpreterConfig)
import Test.Hydra.HeadLogic.Scenario qualified as Scenario
import Test.Hydra.Ledger.Simple (utxoRef)
import Test.Hydra.Prelude (Spec, describe, it, shouldBe, shouldSatisfy)
import Test.Hydra.Tx.Fixture (alice, aliceSk, bob, bobSk, carol, carolSk)

spec :: Spec
spec :: Spec
spec = String -> Spec -> Spec
forall a. HasCallStack => String -> SpecWith a -> SpecWith a
describe String
"operation workflow boundaries" (Spec -> Spec) -> Spec -> Spec
forall a b. (a -> b) -> a -> b
$ do
  String -> IO () -> SpecWith (Arg (IO ()))
forall a.
(HasCallStack, Example a) =>
String -> a -> SpecWith (Arg a)
it String
"records fanout intent before posting and rejects an empty selection without intent" (IO () -> SpecWith (Arg (IO ())))
-> IO () -> SpecWith (Arg (IO ()))
forall a b. (a -> b) -> a -> b
$ do
    [Text] -> (Text -> IO ()) -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [Text
"fanout-request", Text
"fanout-selection"] ((Text -> IO ()) -> IO ()) -> (Text -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \Text
name -> do
      (Outcome SimpleTx
_, [TraceStep]
trace) <- Text -> IO (Outcome SimpleTx, [TraceStep])
fixture Text
name
      [TraceStep] -> [TraceStep]
signals [TraceStep]
trace [TraceStep] -> [TraceStep] -> IO ()
forall a. (HasCallStack, Show a, Eq a) => a -> a -> IO ()
`shouldBe` [Text -> TraceStep
Changed Text
"head fanout initiated", Text -> TraceStep
Emitted Text
"post full fanout"]
    (Outcome SimpleTx
refused, [TraceStep]
trace) <- Text -> IO (Outcome SimpleTx, [TraceStep])
fixture Text
"fanout-empty-selection"
    [TraceStep] -> [TraceStep]
signals [TraceStep]
trace [TraceStep] -> [TraceStep] -> IO ()
forall a. (HasCallStack, Show a, Eq a) => a -> a -> IO ()
`shouldBe` [Text -> TraceStep
Emitted Text
"client effect"]
    Outcome SimpleTx
refused Outcome SimpleTx -> (Outcome SimpleTx -> Bool) -> IO ()
forall a. (HasCallStack, Show a) => a -> (a -> Bool) -> IO ()
`shouldSatisfy` \case Continue [] [ClientEffect Server.CommandFailed{}] -> Bool
True; Outcome SimpleTx
_ -> Bool
False

  String -> IO () -> SpecWith (Arg (IO ()))
forall a.
(HasCallStack, Example a) =>
String -> a -> SpecWith (Arg a)
it String
"plans and reposts against the observed datum when distribution matches no local outputs" (IO () -> SpecWith (Arg (IO ())))
-> IO () -> SpecWith (Arg (IO ()))
forall a b. (a -> b) -> a -> b
$ do
    (NodeState SimpleTx
before, Input SimpleTx
input) <- Text -> IO (NodeState SimpleTx, Input SimpleTx)
example Text
"fanout-passive-observer"
    Input SimpleTx
observed <- case Input SimpleTx
input of
      ChainInput observation :: ChainEvent SimpleTx
observation@Observation{$sel:observedTx:Observation :: forall tx. ChainEvent tx -> OnChainTx tx
observedTx = tx :: OnChainTx SimpleTx
tx@OnPartialFanoutTx{}} ->
        Input SimpleTx -> IO (Input SimpleTx)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Input SimpleTx -> IO (Input SimpleTx))
-> Input SimpleTx -> IO (Input SimpleTx)
forall a b. (a -> b) -> a -> b
$ ChainEvent SimpleTx -> Input SimpleTx
forall tx. ChainEvent tx -> Input tx
ChainInput ChainEvent SimpleTx
observation{observedTx = tx{distributedOutputs = utxoRef 999}}
      Input SimpleTx
_ -> String -> IO (Input SimpleTx)
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"expected partial fanout observation"
    let node :: NodeState SimpleTx
node = NodeState SimpleTx -> Outcome SimpleTx -> NodeState SimpleTx
forall tx.
IsChainState tx =>
NodeState tx -> Outcome tx -> NodeState tx
aggregateState NodeState SimpleTx
before (Outcome SimpleTx -> NodeState SimpleTx)
-> Outcome SimpleTx -> NodeState SimpleTx
forall a b. (a -> b) -> a -> b
$ (Outcome SimpleTx, [TraceStep]) -> Outcome SimpleTx
forall a b. (a, b) -> a
fst ((Outcome SimpleTx, [TraceStep]) -> Outcome SimpleTx)
-> (Outcome SimpleTx, [TraceStep]) -> Outcome SimpleTx
forall a b. (a -> b) -> a -> b
$ NodeState SimpleTx
-> Input SimpleTx -> (Outcome SimpleTx, [TraceStep])
run NodeState SimpleTx
before Input SimpleTx
observed
    PartialFanoutState SimpleTx
progress <- case NodeState SimpleTx
node.headState of
      FanoutProgress PartialFanoutState SimpleTx
st -> PartialFanoutState SimpleTx -> IO (PartialFanoutState SimpleTx)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure PartialFanoutState SimpleTx
st
      HeadState SimpleTx
_ -> String -> IO (PartialFanoutState SimpleTx)
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"expected partial fanout state"
    PartialFanoutState SimpleTx
progress.distributedOutputs UTxOType SimpleTx -> UTxOType SimpleTx -> IO ()
forall a. (HasCallStack, Show a, Eq a) => a -> a -> IO ()
`shouldBe` UTxOType SimpleTx
forall a. Monoid a => a
mempty
    PartialFanoutState SimpleTx
progress.fanoutDatum OnChainFanoutDatum -> OnChainFanoutDatum -> IO ()
forall a. (HasCallStack, Show a, Eq a) => a -> a -> IO ()
`shouldBe` OnChainFanoutDatum
DatumFanoutProgress
    let (Outcome SimpleTx
planned, [TraceStep]
_) = NodeState SimpleTx
-> Input SimpleTx -> (Outcome SimpleTx, [TraceStep])
run NodeState SimpleTx
node (Input SimpleTx -> (Outcome SimpleTx, [TraceStep]))
-> Input SimpleTx -> (Outcome SimpleTx, [TraceStep])
forall a b. (a -> b) -> a -> b
$ ClientInput SimpleTx -> Input SimpleTx
forall tx. ClientInput tx -> Input tx
ClientInput (ClientInput SimpleTx -> Input SimpleTx)
-> ClientInput SimpleTx -> Input SimpleTx
forall a b. (a -> b) -> a -> b
$ UTxOType SimpleTx -> ClientInput SimpleTx
forall tx. UTxOType tx -> ClientInput tx
Client.PartialFanout PartialFanoutState SimpleTx
progress.remainingOutputs
        selected :: NodeState SimpleTx
selected = NodeState SimpleTx -> Outcome SimpleTx -> NodeState SimpleTx
forall tx.
IsChainState tx =>
NodeState tx -> Outcome tx -> NodeState tx
aggregateState NodeState SimpleTx
node Outcome SimpleTx
planned
    PostChainTx SimpleTx
transaction <- case Outcome SimpleTx
planned of
      Continue [StateChanged SimpleTx]
_ [OnChainEffect tx :: PostChainTx SimpleTx
tx@FinalPartialFanoutTx{}] -> PostChainTx SimpleTx -> IO (PostChainTx SimpleTx)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure PostChainTx SimpleTx
tx
      Outcome SimpleTx
_ -> String -> IO (PostChainTx SimpleTx)
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO (PostChainTx SimpleTx))
-> String -> IO (PostChainTx SimpleTx)
forall a b. (a -> b) -> a -> b
$ String
"expected final partial fanout, got " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Outcome SimpleTx -> String
forall b a. (Show a, IsString b) => a -> b
show Outcome SimpleTx
planned
    NodeState SimpleTx
restored <- (DecoderError -> IO (NodeState SimpleTx))
-> (NodeState SimpleTx -> IO (NodeState SimpleTx))
-> Either DecoderError (NodeState SimpleTx)
-> IO (NodeState SimpleTx)
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> IO (NodeState SimpleTx)
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO (NodeState SimpleTx))
-> (DecoderError -> String)
-> DecoderError
-> IO (NodeState SimpleTx)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. DecoderError -> String
forall b a. (Show a, IsString b) => a -> b
show) NodeState SimpleTx -> IO (NodeState SimpleTx)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either DecoderError (NodeState SimpleTx)
 -> IO (NodeState SimpleTx))
-> Either DecoderError (NodeState SimpleTx)
-> IO (NodeState SimpleTx)
forall a b. (a -> b) -> a -> b
$ ByteString -> Either DecoderError (NodeState SimpleTx)
forall a. FromCBOR a => ByteString -> Either DecoderError a
decodeFull' (ByteString -> Either DecoderError (NodeState SimpleTx))
-> ByteString -> Either DecoderError (NodeState SimpleTx)
forall a b. (a -> b) -> a -> b
$ NodeState SimpleTx -> ByteString
forall a. ToCBOR a => a -> ByteString
serialize' NodeState SimpleTx
selected
    -- Rollback retains the protocol phase; this checks the selected transaction
    -- kind without claiming to reconcile fanout against a divergent chain.
    case (Outcome SimpleTx, [TraceStep]) -> Outcome SimpleTx
forall a b. (a, b) -> a
fst ((Outcome SimpleTx, [TraceStep]) -> Outcome SimpleTx)
-> (Outcome SimpleTx, [TraceStep]) -> Outcome SimpleTx
forall a b. (a -> b) -> a -> b
$ NodeState SimpleTx
-> Input SimpleTx -> (Outcome SimpleTx, [TraceStep])
run NodeState SimpleTx
restored (Input SimpleTx -> (Outcome SimpleTx, [TraceStep]))
-> Input SimpleTx -> (Outcome SimpleTx, [TraceStep])
forall a b. (a -> b) -> a -> b
$ ChainEvent SimpleTx -> Input SimpleTx
forall tx. ChainEvent tx -> Input tx
ChainInput (ChainEvent SimpleTx -> Input SimpleTx)
-> ChainEvent SimpleTx -> Input SimpleTx
forall a b. (a -> b) -> a -> b
$ UTCTime -> ChainStateType SimpleTx -> ChainEvent SimpleTx
forall tx. UTCTime -> ChainStateType tx -> ChainEvent tx
Rollback UTCTime
initialChainTime ChainStateType SimpleTx
SimpleChainState
0 of
      Continue [StateChanged SimpleTx]
_ [Effect SimpleTx]
effects -> [PostChainTx SimpleTx
tx | OnChainEffect PostChainTx SimpleTx
tx <- [Effect SimpleTx]
effects] [PostChainTx SimpleTx] -> [PostChainTx SimpleTx] -> IO ()
forall a. (HasCallStack, Show a, Eq a) => a -> a -> IO ()
`shouldBe` [PostChainTx SimpleTx
transaction]
      Outcome SimpleTx
other -> String -> IO ()
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
"expected fanout re-post, got " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Outcome SimpleTx -> String
forall b a. (Show a, IsString b) => a -> b
show Outcome SimpleTx
other

  String -> IO () -> SpecWith (Arg (IO ()))
forall a.
(HasCallStack, Example a) =>
String -> a -> SpecWith (Arg a)
it String
"verifies and adopts before clearing local work, reporting invalid side-loads as client refusals" (IO () -> SpecWith (Arg (IO ())))
-> IO () -> SpecWith (Arg (IO ()))
forall a b. (a -> b) -> a -> b
$ do
    (Outcome SimpleTx
_, [TraceStep]
trace) <- Text -> IO (Outcome SimpleTx, [TraceStep])
fixture Text
"side-load-current"
    [TraceStep] -> [TraceStep]
signals [TraceStep]
trace [TraceStep] -> [TraceStep] -> IO ()
forall a. (HasCallStack, Show a, Eq a) => a -> a -> IO ()
`shouldBe` [Text -> TraceStep
PrimitiveCalled Text
"verify multisignature", Text -> TraceStep
Changed Text
"snapshot confirmed", Text -> TraceStep
Changed Text
"local state cleared"]
    (Outcome SimpleTx
refused, [TraceStep]
invalidTrace) <- Text -> IO (Outcome SimpleTx, [TraceStep])
fixture Text
"side-load-invalid-signatures"
    [TraceStep] -> [TraceStep]
signals [TraceStep]
invalidTrace [TraceStep] -> [TraceStep] -> IO ()
forall a. (HasCallStack, Show a, Eq a) => a -> a -> IO ()
`shouldBe` [Text -> TraceStep
PrimitiveCalled Text
"verify multisignature", Text -> TraceStep
Emitted Text
"client effect"]
    Outcome SimpleTx
refused Outcome SimpleTx -> (Outcome SimpleTx -> Bool) -> IO ()
forall a. (HasCallStack, Show a) => a -> (a -> Bool) -> IO ()
`shouldSatisfy` \case Continue [] [ClientEffect Server.SideLoadSnapshotRejected{}] -> Bool
True; Outcome SimpleTx
_ -> Bool
False

  String -> IO () -> SpecWith (Arg (IO ()))
forall a.
(HasCallStack, Example a) =>
String -> a -> SpecWith (Arg a)
it String
"retains close and contest observations after failed certificate verification" (IO () -> SpecWith (Arg (IO ())))
-> IO () -> SpecWith (Arg (IO ()))
forall a b. (a -> b) -> a -> b
$
    [(Text, Text)] -> ((Text, Text) -> IO ()) -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [(Text
"close-adopt", Text
"head closed"), (Text
"contest-adopt", Text
"head contested")] (((Text, Text) -> IO ()) -> IO ())
-> ((Text, Text) -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \(Text
name, Text
event) -> do
      (NodeState SimpleTx
before, Input SimpleTx
input) <- Text -> IO (NodeState SimpleTx, Input SimpleTx)
example Text
name
      let original :: (Outcome SimpleTx, [TraceStep])
original = NodeState SimpleTx
-> Input SimpleTx -> (Outcome SimpleTx, [TraceStep])
run NodeState SimpleTx
before Input SimpleTx
input
      [TraceStep] -> [TraceStep]
signals ((Outcome SimpleTx, [TraceStep]) -> [TraceStep]
forall a b. (a, b) -> b
snd (Outcome SimpleTx, [TraceStep])
original) [TraceStep] -> [TraceStep] -> IO ()
forall a. (HasCallStack, Show a, Eq a) => a -> a -> IO ()
`shouldBe` [Text -> TraceStep
PrimitiveCalled Text
"verify multisignature", Text -> TraceStep
Changed Text
"snapshot confirmed", Text -> TraceStep
Changed Text
event]
      Input SimpleTx
invalid <- case Input SimpleTx
input of
        ChainInput Observation{$sel:observedTx:Observation :: forall tx. ChainEvent tx -> OnChainTx tx
observedTx = OnCloseTx HeadId
hid SnapshotNumber
sn UTCTime
deadline MultiSignature (Snapshot SimpleTx)
_, ChainStateType SimpleTx
newChainState :: ChainStateType SimpleTx
$sel:newChainState:Observation :: forall tx. ChainEvent tx -> ChainStateType tx
newChainState} -> Input SimpleTx -> IO (Input SimpleTx)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Input SimpleTx -> IO (Input SimpleTx))
-> Input SimpleTx -> IO (Input SimpleTx)
forall a b. (a -> b) -> a -> b
$ ChainEvent SimpleTx -> Input SimpleTx
forall tx. ChainEvent tx -> Input tx
ChainInput (ChainEvent SimpleTx -> Input SimpleTx)
-> ChainEvent SimpleTx -> Input SimpleTx
forall a b. (a -> b) -> a -> b
$ OnChainTx SimpleTx
-> ChainStateType SimpleTx -> ChainEvent SimpleTx
forall tx. OnChainTx tx -> ChainStateType tx -> ChainEvent tx
Observation (HeadId
-> SnapshotNumber
-> UTCTime
-> MultiSignature (Snapshot SimpleTx)
-> OnChainTx SimpleTx
forall tx.
HeadId
-> SnapshotNumber
-> UTCTime
-> MultiSignature (Snapshot tx)
-> OnChainTx tx
OnCloseTx HeadId
hid SnapshotNumber
sn UTCTime
deadline (MultiSignature (Snapshot SimpleTx) -> OnChainTx SimpleTx)
-> MultiSignature (Snapshot SimpleTx) -> OnChainTx SimpleTx
forall a b. (a -> b) -> a -> b
$ [Signature (Snapshot SimpleTx)]
-> MultiSignature (Snapshot SimpleTx)
forall a. [Signature a] -> MultiSignature a
aggregate []) ChainStateType SimpleTx
newChainState
        ChainInput Observation{$sel:observedTx:Observation :: forall tx. ChainEvent tx -> OnChainTx tx
observedTx = OnContestTx HeadId
hid SnapshotNumber
sn UTCTime
deadline MultiSignature (Snapshot SimpleTx)
_, ChainStateType SimpleTx
$sel:newChainState:Observation :: forall tx. ChainEvent tx -> ChainStateType tx
newChainState :: ChainStateType SimpleTx
newChainState} -> Input SimpleTx -> IO (Input SimpleTx)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Input SimpleTx -> IO (Input SimpleTx))
-> Input SimpleTx -> IO (Input SimpleTx)
forall a b. (a -> b) -> a -> b
$ ChainEvent SimpleTx -> Input SimpleTx
forall tx. ChainEvent tx -> Input tx
ChainInput (ChainEvent SimpleTx -> Input SimpleTx)
-> ChainEvent SimpleTx -> Input SimpleTx
forall a b. (a -> b) -> a -> b
$ OnChainTx SimpleTx
-> ChainStateType SimpleTx -> ChainEvent SimpleTx
forall tx. OnChainTx tx -> ChainStateType tx -> ChainEvent tx
Observation (HeadId
-> SnapshotNumber
-> UTCTime
-> MultiSignature (Snapshot SimpleTx)
-> OnChainTx SimpleTx
forall tx.
HeadId
-> SnapshotNumber
-> UTCTime
-> MultiSignature (Snapshot tx)
-> OnChainTx tx
OnContestTx HeadId
hid SnapshotNumber
sn UTCTime
deadline (MultiSignature (Snapshot SimpleTx) -> OnChainTx SimpleTx)
-> MultiSignature (Snapshot SimpleTx) -> OnChainTx SimpleTx
forall a b. (a -> b) -> a -> b
$ [Signature (Snapshot SimpleTx)]
-> MultiSignature (Snapshot SimpleTx)
forall a. [Signature a] -> MultiSignature a
aggregate []) ChainStateType SimpleTx
newChainState
        Input SimpleTx
_ -> String -> IO (Input SimpleTx)
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"expected a close or contest observation"
      let (Outcome SimpleTx
outcome, [TraceStep]
trace) = NodeState SimpleTx
-> Input SimpleTx -> (Outcome SimpleTx, [TraceStep])
run NodeState SimpleTx
before Input SimpleTx
invalid
      [TraceStep] -> [TraceStep]
signals [TraceStep]
trace [TraceStep] -> [TraceStep] -> IO ()
forall a. (HasCallStack, Show a, Eq a) => a -> a -> IO ()
`shouldBe` [Text -> TraceStep
PrimitiveCalled Text
"verify multisignature", Text -> TraceStep
Changed Text
event]
      Outcome SimpleTx
outcome Outcome SimpleTx -> (Outcome SimpleTx -> Bool) -> IO ()
forall a. (HasCallStack, Show a) => a -> (a -> Bool) -> IO ()
`shouldSatisfy` \case Continue [StateChanged SimpleTx
_] [] -> Bool
True; Outcome SimpleTx
_ -> Bool
False

  String -> IO () -> SpecWith (Arg (IO ()))
forall a.
(HasCallStack, Example a) =>
String -> a -> SpecWith (Arg a)
it String
"publishes the incremental effect after confirmation and before requesting the next round" (IO () -> SpecWith (Arg (IO ())))
-> IO () -> SpecWith (Arg (IO ()))
forall a b. (a -> b) -> a -> b
$ do
    let tx :: SimpleTx
tx = SimpleTx
Scenario.transactionOne
        snapshot :: Snapshot SimpleTx
snapshot = Snapshot SimpleTx -> Snapshot SimpleTx
forall tx. IsTx tx => Snapshot tx -> Snapshot tx
withAccumulators (Snapshot SimpleTx -> Snapshot SimpleTx)
-> Snapshot SimpleTx -> Snapshot SimpleTx
forall a b. (a -> b) -> a -> b
$ Snapshot SimpleTx
Scenario.initialSnapshot{number = 1, utxoToCommit = Just (utxoRef 42), depositTxId = Just 42}
        base :: OpenState SimpleTx
base = NodeState SimpleTx -> OpenState SimpleTx
Scenario.openState NodeState SimpleTx
Scenario.initialNode
        state :: OpenState SimpleTx
state = OpenState SimpleTx
base{coordinatedHeadState = base.coordinatedHeadState{seenSnapshot = mkSeenSnapshot snapshot $ Map.fromList [(alice, sign aliceSk snapshot), (bob, sign bobSk snapshot)], localUTxO = utxoRef 2, localTxs = Seq.singleton tx, allTxs = Map.singleton 1 tx, currentDepositTxId = Just 42}}
        pending :: Map SimpleId (Deposit SimpleTx)
pending = SimpleId -> Deposit SimpleTx -> Map SimpleId (Deposit SimpleTx)
forall k a. k -> a -> Map k a
Map.singleton SimpleId
42 (Deposit SimpleTx -> Map SimpleId (Deposit SimpleTx))
-> Deposit SimpleTx -> Map SimpleId (Deposit SimpleTx)
forall a b. (a -> b) -> a -> b
$ HeadId
-> UTxOType SimpleTx
-> UTCTime
-> UTCTime
-> DepositStatus
-> Deposit SimpleTx
forall tx.
HeadId
-> UTxOType tx -> UTCTime -> UTCTime -> DepositStatus -> Deposit tx
Deposit OpenState SimpleTx
base.headId (SimpleId -> UTxOType SimpleTx
utxoRef SimpleId
42) UTCTime
initialChainTime (NominalDiffTime -> UTCTime -> UTCTime
addUTCTime NominalDiffTime
10000 UTCTime
initialChainTime) DepositStatus
Active
        program :: Program SimpleTx ()
program = Workflow SimpleTx AckTopology () -> Program SimpleTx ()
forall {vertex} tx (topology :: Topology vertex) result.
Workflow tx topology result -> Program tx result
Workflow.run (Workflow SimpleTx AckTopology () -> Program SimpleTx ())
-> Workflow SimpleTx AckTopology () -> Program SimpleTx ()
forall a b. (a -> b) -> a -> b
$ Args SimpleTx -> Workflow SimpleTx AckTopology ()
forall tx. IsChainState tx => Args tx -> Workflow tx AckTopology ()
AckSn.workflow AckSn.Args{$sel:env:Args :: RuleEnvironment
env = Environment -> RuleEnvironment
ruleEnvironment (Environment -> RuleEnvironment) -> Environment -> RuleEnvironment
forall a b. (a -> b) -> a -> b
$ Int -> Environment
Scenario.environment Int
1, $sel:chainPointTime:Args :: ChainPointTime
chainPointTime = NodeState SimpleTx
Scenario.initialNode.chainPointTime, $sel:pendingDeposits:Args :: PendingDeposits SimpleTx
pendingDeposits = Map SimpleId (Deposit SimpleTx)
PendingDeposits SimpleTx
pending, $sel:openState:Args :: OpenState SimpleTx
openState = OpenState SimpleTx
state, $sel:sender:Args :: Party
sender = Party
carol, $sel:signed:Args :: Signature (Snapshot SimpleTx)
signed = Secret (SigningKey HydraKey)
-> Snapshot SimpleTx -> Signature (Snapshot SimpleTx)
forall a.
SignableRepresentation a =>
Secret (SigningKey HydraKey) -> a -> Signature a
sign Secret (SigningKey HydraKey)
carolSk Snapshot SimpleTx
snapshot, $sel:snapshotNumber:Args :: SnapshotNumber
snapshotNumber = SnapshotNumber
1}
        (Outcome SimpleTx
outcome, [TraceStep]
trace) = InterpreterConfig SimpleTx
-> Program SimpleTx () -> (Outcome SimpleTx, [TraceStep])
forall tx.
InterpreterConfig tx -> Program tx () -> (Outcome tx, [TraceStep])
Interpreter.traceProgram (Ledger SimpleTx -> InterpreterConfig SimpleTx
forall tx. IsTx tx => Ledger tx -> InterpreterConfig tx
testInterpreterConfig Ledger SimpleTx
simpleLedger) Program SimpleTx ()
program
    Outcome SimpleTx
outcome Outcome SimpleTx -> (Outcome SimpleTx -> Bool) -> IO ()
forall a. (HasCallStack, Show a) => a -> (a -> Bool) -> IO ()
`shouldSatisfy` \case Continue [PartySignedSnapshot{}, SnapshotConfirmed{}, CommitApproved{}, SnapshotRequestDecided{}] [OnChainEffect{}, NetworkEffect ReqSn{}] -> Bool
True; Outcome SimpleTx
_ -> Bool
False
    [TraceStep] -> [TraceStep]
signals [TraceStep]
trace [TraceStep] -> [TraceStep] -> IO ()
forall a. (HasCallStack, Show a, Eq a) => a -> a -> IO ()
`shouldBe` [Text -> TraceStep
Changed Text
"party signed snapshot", Text -> TraceStep
PrimitiveCalled Text
"verify multisignature", Text -> TraceStep
Changed Text
"snapshot confirmed", Text -> TraceStep
Changed Text
"commit approved", Text -> TraceStep
Emitted Text
"post increment", Text -> TraceStep
Changed Text
"snapshot request decided", Text -> TraceStep
Emitted Text
"broadcast ReqSn"]

  String -> IO () -> SpecWith (Arg (IO ()))
forall a.
(HasCallStack, Example a) =>
String -> a -> SpecWith (Arg a)
it String
"returns the same deposit statuses that replay retains, including backwards time" (IO () -> SpecWith (Arg (IO ())))
-> IO () -> SpecWith (Arg (IO ()))
forall a b. (a -> b) -> a -> b
$
    [(DepositStatus, DepositStatus)]
-> ((DepositStatus, DepositStatus) -> IO ()) -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [(DepositStatus
old, DepositStatus
computed) | DepositStatus
old <- [DepositStatus
Inactive, DepositStatus
Active, DepositStatus
Expired], DepositStatus
computed <- [DepositStatus
Inactive, DepositStatus
Active, DepositStatus
Expired]] (((DepositStatus, DepositStatus) -> IO ()) -> IO ())
-> ((DepositStatus, DepositStatus) -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \(DepositStatus
old, DepositStatus
computed) -> do
      let now :: UTCTime
now = UTCTime
initialChainTime
          activation :: NominalDiffTime
activation = DepositPeriod -> NominalDiffTime
DepositPeriod.toNominalDiffTime Environment
env.depositActivation
          expiry :: NominalDiffTime
expiry = DepositPeriod -> NominalDiffTime
DepositPeriod.toNominalDiffTime Environment
env.depositPeriod
          created :: UTCTime
created = NominalDiffTime -> UTCTime -> UTCTime
addUTCTime (if DepositStatus
computed DepositStatus -> DepositStatus -> Bool
forall a. Eq a => a -> a -> Bool
== DepositStatus
Active then NominalDiffTime -> NominalDiffTime
forall a. Num a => a -> a
negate NominalDiffTime
activation NominalDiffTime -> NominalDiffTime -> NominalDiffTime
forall a. Num a => a -> a -> a
- NominalDiffTime
1 else NominalDiffTime
0) UTCTime
now
          deadline :: UTCTime
deadline = NominalDiffTime -> UTCTime -> UTCTime
addUTCTime (if DepositStatus
computed DepositStatus -> DepositStatus -> Bool
forall a. Eq a => a -> a -> Bool
== DepositStatus
Expired then NominalDiffTime
expiry NominalDiffTime -> NominalDiffTime -> NominalDiffTime
forall a. Num a => a -> a -> a
- NominalDiffTime
1 else NominalDiffTime
expiry NominalDiffTime -> NominalDiffTime -> NominalDiffTime
forall a. Num a => a -> a -> a
+ NominalDiffTime
100) UTCTime
now
          deposit :: Deposit SimpleTx
deposit = HeadId
-> UTxOType SimpleTx
-> UTCTime
-> UTCTime
-> DepositStatus
-> Deposit SimpleTx
forall tx.
HeadId
-> UTxOType tx -> UTCTime -> UTCTime -> DepositStatus -> Deposit tx
Deposit OpenState SimpleTx
open.headId (SimpleId -> UTxOType SimpleTx
utxoRef SimpleId
7) UTCTime
created UTCTime
deadline DepositStatus
old
          before :: NodeState SimpleTx
before = NodeState SimpleTx
Scenario.initialNode{deposits = trackedFromPending $ Map.singleton 7 deposit}
          expected :: HsDepositStatus
expected = HsDepositStatus -> HsDepositStatus -> HsDepositStatus
Agda.effectiveDepositStatusRef (DepositStatus -> HsDepositStatus
statusRef DepositStatus
old) (DepositStatus -> HsDepositStatus
statusRef DepositStatus
computed)
          program :: Program SimpleTx ()
program = do
            Map SimpleId (Deposit SimpleTx)
effective <- RuleEnvironment
-> PendingDeposits SimpleTx
-> UTCTime
-> Program SimpleTx (PendingDeposits SimpleTx)
forall tx.
IsTx tx =>
RuleEnvironment
-> PendingDeposits tx -> UTCTime -> Program tx (PendingDeposits tx)
Deposits.updateDepositStates (Environment -> RuleEnvironment
ruleEnvironment Environment
env) NodeState SimpleTx
before.pendingDeposits UTCTime
now
            Bool -> Program SimpleTx () -> Program SimpleTx ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ((DepositStatus -> HsDepositStatus
statusRef (DepositStatus -> HsDepositStatus)
-> (Deposit SimpleTx -> DepositStatus)
-> Deposit SimpleTx
-> HsDepositStatus
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (.status) (Deposit SimpleTx -> HsDepositStatus)
-> Maybe (Deposit SimpleTx) -> Maybe HsDepositStatus
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> SimpleId
-> Map SimpleId (Deposit SimpleTx) -> Maybe (Deposit SimpleTx)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup SimpleId
7 Map SimpleId (Deposit SimpleTx)
effective) Maybe HsDepositStatus -> Maybe HsDepositStatus -> Bool
forall a. Eq a => a -> a -> Bool
== HsDepositStatus -> Maybe HsDepositStatus
forall a. a -> Maybe a
Just HsDepositStatus
expected) (Program SimpleTx () -> Program SimpleTx ())
-> Program SimpleTx () -> Program SimpleTx ()
forall a b. (a -> b) -> a -> b
$
              LogicError SimpleTx -> Program SimpleTx ()
forall tx a. LogicError tx -> Program tx a
reject (LogicError SimpleTx -> Program SimpleTx ())
-> LogicError SimpleTx -> Program SimpleTx ()
forall a b. (a -> b) -> a -> b
$
                Text -> LogicError SimpleTx
forall tx. Text -> LogicError tx
AssertionFailed Text
"tick result differs from the retained status projection"
          outcome :: Outcome SimpleTx
outcome = InterpreterConfig SimpleTx
-> Program SimpleTx () -> Outcome SimpleTx
forall tx. InterpreterConfig tx -> Program tx () -> Outcome tx
Interpreter.runProgram (Ledger SimpleTx -> InterpreterConfig SimpleTx
forall tx. IsTx tx => Ledger tx -> InterpreterConfig tx
testInterpreterConfig Ledger SimpleTx
simpleLedger) Program SimpleTx ()
program
      Outcome SimpleTx
outcome Outcome SimpleTx -> (Outcome SimpleTx -> Bool) -> IO ()
forall a. (HasCallStack, Show a) => a -> (a -> Bool) -> IO ()
`shouldSatisfy` \case Continue [StateChanged SimpleTx]
_ [] -> Bool
True; Outcome SimpleTx
_ -> Bool
False
      (DepositStatus -> HsDepositStatus
statusRef (DepositStatus -> HsDepositStatus)
-> (Deposit SimpleTx -> DepositStatus)
-> Deposit SimpleTx
-> HsDepositStatus
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (.status) (Deposit SimpleTx -> HsDepositStatus)
-> Maybe (Deposit SimpleTx) -> Maybe HsDepositStatus
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> SimpleId
-> Map SimpleId (Deposit SimpleTx) -> Maybe (Deposit SimpleTx)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup SimpleId
7 (NodeState SimpleTx -> Outcome SimpleTx -> NodeState SimpleTx
forall tx.
IsChainState tx =>
NodeState tx -> Outcome tx -> NodeState tx
aggregateState NodeState SimpleTx
before Outcome SimpleTx
outcome).pendingDeposits) Maybe HsDepositStatus -> Maybe HsDepositStatus -> IO ()
forall a. (HasCallStack, Show a, Eq a) => a -> a -> IO ()
`shouldBe` HsDepositStatus -> Maybe HsDepositStatus
forall a. a -> Maybe a
Just HsDepositStatus
expected

  String -> IO () -> SpecWith (Arg (IO ()))
forall a.
(HasCallStack, Example a) =>
String -> a -> SpecWith (Arg a)
it String
"uses a retained active status when selecting work after time moves backwards" (IO () -> SpecWith (Arg (IO ())))
-> IO () -> SpecWith (Arg (IO ()))
forall a b. (a -> b) -> a -> b
$ do
    let deposit :: Deposit SimpleTx
deposit = HeadId
-> UTxOType SimpleTx
-> UTCTime
-> UTCTime
-> DepositStatus
-> Deposit SimpleTx
forall tx.
HeadId
-> UTxOType tx -> UTCTime -> UTCTime -> DepositStatus -> Deposit tx
Deposit OpenState SimpleTx
open.headId (SimpleId -> UTxOType SimpleTx
utxoRef SimpleId
7) UTCTime
initialChainTime (NominalDiffTime -> UTCTime -> UTCTime
addUTCTime NominalDiffTime
10000 UTCTime
initialChainTime) DepositStatus
Active
        before :: NodeState SimpleTx
before = NodeState SimpleTx
Scenario.initialNode{deposits = trackedFromPending $ Map.singleton 7 deposit}
        (Outcome SimpleTx
outcome, [TraceStep]
_) = NodeState SimpleTx
-> Input SimpleTx -> (Outcome SimpleTx, [TraceStep])
run NodeState SimpleTx
before (Input SimpleTx -> (Outcome SimpleTx, [TraceStep]))
-> Input SimpleTx -> (Outcome SimpleTx, [TraceStep])
forall a b. (a -> b) -> a -> b
$ ChainEvent SimpleTx -> Input SimpleTx
forall tx. ChainEvent tx -> Input tx
ChainInput (ChainEvent SimpleTx -> Input SimpleTx)
-> ChainEvent SimpleTx -> Input SimpleTx
forall a b. (a -> b) -> a -> b
$ UTCTime -> ChainPointType SimpleTx -> ChainEvent SimpleTx
forall tx. UTCTime -> ChainPointType tx -> ChainEvent tx
Tick UTCTime
initialChainTime ChainSlot
ChainPointType SimpleTx
0
    Outcome SimpleTx
outcome Outcome SimpleTx -> (Outcome SimpleTx -> Bool) -> IO ()
forall a. (HasCallStack, Show a) => a -> (a -> Bool) -> IO ()
`shouldSatisfy` \case
      Continue [TickObserved{}, SnapshotRequestDecided{}] [NetworkEffect (ReqSn SnapshotVersion
_ SnapshotNumber
_ [TxIdType SimpleTx]
_ Maybe SimpleTx
Nothing (Just TxIdType SimpleTx
7))] -> Bool
True
      Outcome SimpleTx
_ -> Bool
False
 where
  env :: Environment
env = Int -> Environment
Scenario.environment Int
0
  open :: OpenState SimpleTx
open = NodeState SimpleTx -> OpenState SimpleTx
Scenario.openState NodeState SimpleTx
Scenario.initialNode

example :: Text -> IO (NodeState SimpleTx, Input SimpleTx)
example :: Text -> IO (NodeState SimpleTx, Input SimpleTx)
example Text
name = case [(NodeState SimpleTx
before, Input SimpleTx
input) | (Text
label, NodeState SimpleTx
before, Input SimpleTx
input) <- [(Text, NodeState SimpleTx, Input SimpleTx)]
Inputs.examples, Text
name Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
label] of
  [(NodeState SimpleTx, Input SimpleTx)
value] -> (NodeState SimpleTx, Input SimpleTx)
-> IO (NodeState SimpleTx, Input SimpleTx)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (NodeState SimpleTx, Input SimpleTx)
value
  [(NodeState SimpleTx, Input SimpleTx)]
_ -> String -> IO (NodeState SimpleTx, Input SimpleTx)
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO (NodeState SimpleTx, Input SimpleTx))
-> String -> IO (NodeState SimpleTx, Input SimpleTx)
forall a b. (a -> b) -> a -> b
$ String
"missing or ambiguous input fixture: " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Text -> String
forall a. ToString a => a -> String
toString Text
name

fixture :: Text -> IO (Outcome SimpleTx, [TraceStep])
fixture :: Text -> IO (Outcome SimpleTx, [TraceStep])
fixture Text
name = do
  (NodeState SimpleTx
before, Input SimpleTx
input) <- Text -> IO (NodeState SimpleTx, Input SimpleTx)
example Text
name
  (Text -> IO (Outcome SimpleTx, [TraceStep]))
-> ((Outcome SimpleTx, [TraceStep])
    -> IO (Outcome SimpleTx, [TraceStep]))
-> Either Text (Outcome SimpleTx, [TraceStep])
-> IO (Outcome SimpleTx, [TraceStep])
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> IO (Outcome SimpleTx, [TraceStep])
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO (Outcome SimpleTx, [TraceStep]))
-> (Text -> String) -> Text -> IO (Outcome SimpleTx, [TraceStep])
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> String
forall a. ToString a => a -> String
toString) (Outcome SimpleTx, [TraceStep])
-> IO (Outcome SimpleTx, [TraceStep])
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Text (Outcome SimpleTx, [TraceStep])
 -> IO (Outcome SimpleTx, [TraceStep]))
-> Either Text (Outcome SimpleTx, [TraceStep])
-> IO (Outcome SimpleTx, [TraceStep])
forall a b. (a -> b) -> a -> b
$ Environment
-> UTCTime
-> NodeState SimpleTx
-> Input SimpleTx
-> Either Text (Outcome SimpleTx, [TraceStep])
Inputs.checkInput (Int -> Environment
Scenario.environment Int
0) UTCTime
initialChainTime NodeState SimpleTx
before Input SimpleTx
input

run :: NodeState SimpleTx -> Input SimpleTx -> (Outcome SimpleTx, [TraceStep])
run :: NodeState SimpleTx
-> Input SimpleTx -> (Outcome SimpleTx, [TraceStep])
run NodeState SimpleTx
before Input SimpleTx
input = InterpreterConfig SimpleTx
-> Program SimpleTx () -> (Outcome SimpleTx, [TraceStep])
forall tx.
InterpreterConfig tx -> Program tx () -> (Outcome tx, [TraceStep])
Interpreter.traceProgram (Ledger SimpleTx -> InterpreterConfig SimpleTx
forall tx. IsTx tx => Ledger tx -> InterpreterConfig tx
testInterpreterConfig Ledger SimpleTx
simpleLedger) (Program SimpleTx () -> (Outcome SimpleTx, [TraceStep]))
-> Program SimpleTx () -> (Outcome SimpleTx, [TraceStep])
forall a b. (a -> b) -> a -> b
$ Workflow SimpleTx InputTopology () -> Program SimpleTx ()
forall {vertex} tx (topology :: Topology vertex) result.
Workflow tx topology result -> Program tx result
Workflow.run (Workflow SimpleTx InputTopology () -> Program SimpleTx ())
-> Workflow SimpleTx InputTopology () -> Program SimpleTx ()
forall a b. (a -> b) -> a -> b
$ Args SimpleTx -> Workflow SimpleTx InputTopology ()
forall tx.
IsChainState tx =>
Args tx -> Workflow tx InputTopology ()
Input.workflow Input.Args{$sel:env:Args :: RuleEnvironment
env = Environment -> RuleEnvironment
ruleEnvironment (Environment -> RuleEnvironment) -> Environment -> RuleEnvironment
forall a b. (a -> b) -> a -> b
$ Int -> Environment
Scenario.environment Int
0, $sel:now:Args :: UTCTime
now = UTCTime
initialChainTime, $sel:nodeState:Args :: NodeState SimpleTx
nodeState = NodeState SimpleTx
before, $sel:input:Args :: Input SimpleTx
input = Input SimpleTx
input}

signals :: [TraceStep] -> [TraceStep]
signals :: [TraceStep] -> [TraceStep]
signals = (TraceStep -> Bool) -> [TraceStep] -> [TraceStep]
forall a. (a -> Bool) -> [a] -> [a]
filter ((TraceStep -> Bool) -> [TraceStep] -> [TraceStep])
-> (TraceStep -> Bool) -> [TraceStep] -> [TraceStep]
forall a b. (a -> b) -> a -> b
$ \case Changed{} -> Bool
True; Emitted{} -> Bool
True; PrimitiveCalled{} -> Bool
True; TraceStep
_ -> Bool
False

statusRef :: DepositStatus -> Agda.HsDepositStatus
statusRef :: DepositStatus -> HsDepositStatus
statusRef = \case DepositStatus
Inactive -> HsDepositStatus
Agda.InactiveS; DepositStatus
Active -> HsDepositStatus
Agda.ActiveS; DepositStatus
Expired -> HsDepositStatus
Agda.ExpiredS