forked from cardano-scaling/hydra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeadLogic.hs
1041 lines (966 loc) · 36.4 KB
/
HeadLogic.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE UndecidableInstances #-}
-- | Implements the Head Protocol's /state machine/ as /pure functions/ in an event sourced manner.
--
-- More specifically, the 'update' will handle 'Input's (or rather "commands" in
-- event sourcing speak) and convert that into a list of side-'Effect's and
-- 'StateChanged' events, which in turn are 'aggregate'd into a single
-- 'HeadState'.
--
-- As the specification is using a more imperative way of specifying the protocl
-- behavior, one would find the decision logic in 'update' while state updates
-- can be found in the corresponding 'aggregate' branch.
module Hydra.HeadLogic (
module Hydra.HeadLogic,
module Hydra.HeadLogic.Input,
module Hydra.HeadLogic.Error,
module Hydra.HeadLogic.State,
module Hydra.HeadLogic.Outcome,
module Hydra.HeadLogic.SnapshotOutcome,
) where
import Hydra.Prelude
import Data.Map.Strict qualified as Map
import Data.Set ((\\))
import Data.Set qualified as Set
import GHC.Records (getField)
import Hydra.API.ClientInput (ClientInput (..))
import Hydra.API.ServerOutput qualified as ServerOutput
import Hydra.Chain (
ChainEvent (..),
ChainStateHistory,
ChainStateType,
HeadParameters (..),
IsChainState (chainStateSlot),
OnChainTx (..),
PostChainTx (..),
initHistory,
pushNewState,
rollbackHistory,
)
import Hydra.Crypto (
Signature,
Verified (..),
aggregateInOrder,
sign,
verifyMultiSignature,
)
import Hydra.HeadId (HeadId, HeadSeed)
import Hydra.HeadLogic.Error (
LogicError (..),
RequirementFailure (..),
)
import Hydra.HeadLogic.Input (Input (..), TTL)
import Hydra.HeadLogic.Outcome (
Effect (..),
Outcome (..),
StateChanged (..),
WaitReason (..),
cause,
causes,
newState,
noop,
wait,
)
import Hydra.HeadLogic.SnapshotOutcome (isLeader)
import Hydra.HeadLogic.State (
ClosedState (..),
Committed,
CoordinatedHeadState (..),
Environment (..),
HeadState (..),
IdleState (IdleState, chainState),
InitialState (..),
OpenState (..),
PendingCommits,
SeenSnapshot (..),
seenSnapshotNumber,
setChainState,
)
import Hydra.Ledger (
IsTx,
Ledger (..),
TxIdType,
UTxOType,
applyTransactions,
txId,
)
import Hydra.Network.Message (Message (..))
import Hydra.OnChainId (OnChainId)
import Hydra.Party (Party (vkey))
import Hydra.Snapshot (ConfirmedSnapshot (..), Snapshot (..), SnapshotNumber, getSnapshot)
defaultTTL :: TTL
defaultTTL = 5
-- * The Coordinated Head protocol
-- ** On-Chain Protocol
-- | Client request to init the head. This leads to an init transaction on chain,
-- containing the head parameters.
--
-- __Transition__: 'IdleState' → 'IdleState'
onIdleClientInit ::
Environment ->
Outcome tx
onIdleClientInit env =
cause OnChainEffect{postChainTx = InitTx{participants, headParameters}}
where
headParameters =
HeadParameters
{ contestationPeriod
, parties = party : otherParties
}
Environment{party, otherParties, contestationPeriod, participants} = env
-- | Observe an init transaction, initialize parameters in an 'InitialState' and
-- notify clients that they can now commit.
--
-- __Transition__: 'IdleState' → 'InitialState'
onIdleChainInitTx ::
Environment ->
-- | New chain state.
ChainStateType tx ->
HeadId ->
HeadSeed ->
HeadParameters ->
[OnChainId] ->
Word64 ->
Outcome tx
onIdleChainInitTx env newChainState headId headSeed headParameters participants nextStateChangeID
| configuredParties == initializedParties
&& party `member` initializedParties
&& configuredContestationPeriod == contestationPeriod
&& Set.fromList configuredParticipants == Set.fromList participants =
newState
HeadInitialized
{ parameters = headParameters
, chainState = newChainState
, headId
, headSeed
, stateChangeID = nextStateChangeID
}
<> cause (ClientEffect $ ServerOutput.HeadIsInitializing{headId, parties})
| otherwise =
cause
. ClientEffect
$ ServerOutput.IgnoredHeadInitializing
{ headId
, contestationPeriod
, parties
, participants
}
where
initializedParties = Set.fromList parties
configuredParties = Set.fromList (party : otherParties)
HeadParameters{parties, contestationPeriod} = headParameters
Environment
{ party
, otherParties
, contestationPeriod = configuredContestationPeriod
, participants = configuredParticipants
} = env
-- | Observe a commit transaction and record the committed UTxO in the state.
-- Also, if this is the last commit to be observed, post a collect-com
-- transaction on-chain.
--
-- __Transition__: 'InitialState' → 'InitialState'
onInitialChainCommitTx ::
Monoid (UTxOType tx) =>
InitialState tx ->
-- | New chain state
ChainStateType tx ->
-- | Comitting party
Party ->
-- | Committed UTxO
UTxOType tx ->
Word64 ->
Outcome tx
onInitialChainCommitTx st newChainState pt utxo nextStateChangeID =
newState CommittedUTxO{party = pt, committedUTxO = utxo, chainState = newChainState, stateChangeID = nextStateChangeID}
<> causes
( notifyClient
: [postCollectCom | canCollectCom]
)
where
notifyClient = ClientEffect $ ServerOutput.Committed{headId, party = pt, utxo}
postCollectCom =
OnChainEffect
{ postChainTx =
CollectComTx
{ utxo = fold newCommitted
, headId
, headParameters = parameters
}
}
canCollectCom = null remainingParties
remainingParties = Set.delete pt pendingCommits
newCommitted = Map.insert pt utxo committed
InitialState{pendingCommits, committed, headId, parameters} = st
-- | Client request to abort the head. This leads to an abort transaction on
-- chain, reimbursing already committed UTxOs.
--
-- __Transition__: 'InitialState' → 'InitialState'
onInitialClientAbort ::
Monoid (UTxOType tx) =>
InitialState tx ->
Outcome tx
onInitialClientAbort st =
cause OnChainEffect{postChainTx = AbortTx{utxo = fold committed, headSeed}}
where
InitialState{committed, headSeed} = st
-- | Observe an abort transaction by switching the state and notifying clients
-- about it.
--
-- __Transition__: 'InitialState' → 'IdleState'
onInitialChainAbortTx ::
Monoid (UTxOType tx) =>
-- | New chain state
ChainStateType tx ->
Committed tx ->
HeadId ->
Word64 ->
Outcome tx
onInitialChainAbortTx newChainState committed headId nextStateChangeID =
newState HeadAborted{chainState = newChainState, stateChangeID = nextStateChangeID}
<> cause (ClientEffect $ ServerOutput.HeadIsAborted{headId, utxo = fold committed})
-- | Observe a collectCom transaction. We initialize the 'OpenState' using the
-- head parameters from 'IdleState' and construct an 'InitialSnapshot' holding
-- @u0@ from the committed UTxOs.
--
-- __Transition__: 'InitialState' → 'OpenState'
onInitialChainCollectTx ::
IsChainState tx =>
InitialState tx ->
-- | New chain state
ChainStateType tx ->
Word64 ->
Outcome tx
onInitialChainCollectTx st newChainState nextStateChangeID =
newState HeadOpened{chainState = newChainState, initialUTxO = u0, stateChangeID = nextStateChangeID}
<> cause (ClientEffect $ ServerOutput.HeadIsOpen{headId, utxo = u0})
where
u0 = fold committed
-- TODO: Do we want to check whether this even matches our local state? For
-- example, we do expect `null remainingParties` but what happens if it's
-- untrue?
InitialState{committed, headId} = st
-- ** Off-chain protocol
-- | Client request to ingest a new transaction into the head.
--
-- __Transition__: 'OpenState' → 'OpenState'
onOpenClientNewTx ::
-- | The transaction to be submitted to the head.
tx ->
Outcome tx
onOpenClientNewTx tx =
cause . NetworkEffect $ ReqTx tx
-- | Process a transaction request ('ReqTx') from a party.
--
-- We apply this transaction to the seen utxo (ledger state). If not applicable,
-- we wait and retry later. If it applies, this yields an updated seen ledger
-- state. Then, we check whether we are the leader for the next snapshot and
-- emit a snapshot request 'ReqSn' including this transaction if needed.
--
-- __Transition__: 'OpenState' → 'OpenState'
onOpenNetworkReqTx ::
IsTx tx =>
Environment ->
Ledger tx ->
OpenState tx ->
TTL ->
-- | The transaction to be submitted to the head.
tx ->
Word64 ->
Outcome tx
onOpenNetworkReqTx env ledger st ttl tx nextStateChangeID =
-- Spec: Tall ← ̂Tall ∪ { (hash(tx), tx) }
(newState TransactionReceived{tx, stateChangeID = nextStateChangeID} <>) $
-- Spec: wait L̂ ◦ tx ≠ ⊥ combined with L̂ ← L̂ ◦ tx
waitApplyTx $ \newLocalUTxO ->
-- Spec: if ŝ = s̄ ∧ leader(s̄ + 1) = i
( if not snapshotInFlight && isLeader parameters party nextSn
then
newState TransactionAppliedToLocalUTxO{tx = tx, newLocalUTxO, stateChangeID = nextStateChangeID}
<>
-- XXX: This state update has no equivalence in the
-- spec. Do we really need to store that we have
-- requested a snapshot? If yes, should update spec.
newState SnapshotRequestDecided{snapshotNumber = nextSn, stateChangeID = nextStateChangeID}
<> cause (NetworkEffect $ ReqSn nextSn (txId <$> localTxs'))
else newState TransactionAppliedToLocalUTxO{tx, newLocalUTxO, stateChangeID = nextStateChangeID}
)
<> cause (ClientEffect $ ServerOutput.TxValid headId tx)
where
waitApplyTx cont =
case applyTransactions currentSlot localUTxO [tx] of
Right utxo' -> cont utxo'
Left (_, err)
| ttl > 0 ->
wait (WaitOnNotApplicableTx err)
| otherwise ->
-- XXX: We might want to remove invalid txs from allTxs here to
-- prevent them piling up infinitely. However, this is not really
-- covered by the spec and this could be problematic in case of
-- conflicting transactions paired with network latency and/or
-- message resubmission. For example: Assume tx2 depends on tx1, but
-- only tx2 is seen by a participant and eventually times out
-- because of network latency when receiving tx1. The leader,
-- however, saw both as valid and requests a snapshot including
-- both. This is a valid request and if we would have removed tx2
-- from allTxs, we would make the head stuck.
cause . ClientEffect $ ServerOutput.TxInvalid headId localUTxO tx err
Environment{party} = env
Ledger{applyTransactions} = ledger
CoordinatedHeadState{localTxs, localUTxO, confirmedSnapshot, seenSnapshot} = coordinatedHeadState
Snapshot{number = confirmedSn} = getSnapshot confirmedSnapshot
OpenState{coordinatedHeadState, headId, currentSlot, parameters} = st
snapshotInFlight = case seenSnapshot of
NoSeenSnapshot -> False
LastSeenSnapshot{} -> False
RequestedSnapshot{} -> True
SeenSnapshot{} -> True
nextSn = confirmedSn + 1
localTxs' = localTxs <> [tx]
-- | Process a snapshot request ('ReqSn') from party.
--
-- This checks that s is the next snapshot number and that the party is
-- responsible for leading that snapshot. Then, we potentially wait until the
-- previous snapshot is confirmed (no snapshot is in flight), before we apply
-- (or wait until applicable) the requested transactions to the last confirmed
-- snapshot. Only then, we start tracking this new "seen" snapshot, compute a
-- signature of it and send the corresponding 'AckSn' to all parties. Finally,
-- the pending transaction set gets pruned to only contain still applicable
-- transactions.
--
-- __Transition__: 'OpenState' → 'OpenState'
onOpenNetworkReqSn ::
IsTx tx =>
Environment ->
Ledger tx ->
OpenState tx ->
-- | Party which sent the ReqSn.
Party ->
-- | Requested snapshot number.
SnapshotNumber ->
-- | List of transactions to snapshot.
[TxIdType tx] ->
Word64 ->
Outcome tx
onOpenNetworkReqSn env ledger st otherParty sn requestedTxIds nextStateChangeID =
-- TODO: Verify the request is signed by (?) / comes from the leader
-- (Can we prove a message comes from a given peer, without signature?)
-- Spec: require s = ŝ + 1 and leader(s) = j
requireReqSn $
-- Spec: wait s̅ = ŝ
waitNoSnapshotInFlight $
-- Spec: wait ∀h ∈ Treq : (h, ·) ∈ Tall
waitResolvableTxs $ do
-- Spec: Treq ← {Tall [h] | h ∈ Treq#}
let requestedTxs = mapMaybe (`Map.lookup` allTxs) requestedTxIds
-- Spec: require U̅ ◦ Treq /= ⊥ combined with Û ← Ū̅ ◦ Treq
requireApplyTxs requestedTxs $ \u -> do
-- NOTE: confSn == seenSn == sn here
let nextSnapshot = Snapshot headId (confSn + 1) u requestedTxIds
-- Spec: σᵢ
let snapshotSignature = sign signingKey nextSnapshot
(cause (NetworkEffect $ AckSn snapshotSignature sn) <>) $
do
-- Spec: for loop which updates T̂ and L̂
let (newLocalTxs, newLocalUTxO) = pruneTransactions u
-- Spec (in aggregate): Tall ← {tx | ∀tx ∈ Tall : tx ∉ Treq }
newState
SnapshotRequested
{ snapshot = nextSnapshot
, requestedTxIds
, newLocalUTxO
, newLocalTxs
, stateChangeID = nextStateChangeID
}
where
requireReqSn continue
| sn /= seenSn + 1 =
Error $ RequireFailed $ ReqSnNumberInvalid{requestedSn = sn, lastSeenSn = seenSn}
| not (isLeader parameters otherParty sn) =
Error $ RequireFailed $ ReqSnNotLeader{requestedSn = sn, leader = otherParty}
| otherwise =
continue
waitNoSnapshotInFlight continue
| confSn == seenSn =
continue
| otherwise =
wait $ WaitOnSnapshotNumber seenSn
waitResolvableTxs continue =
case toList (fromList requestedTxIds \\ Map.keysSet allTxs) of
[] -> continue
unseen -> wait $ WaitOnTxs unseen
-- NOTE: at this point we know those transactions apply on the localUTxO because they
-- are part of the localTxs. The snapshot can contain less transactions than the ones
-- we have seen at this stage, but they all _must_ apply correctly to the latest
-- snapshot's UTxO set, eg. it's illegal for a snapshot leader to request a snapshot
-- containing transactions that do not apply cleanly.
requireApplyTxs requestedTxs cont =
case applyTransactions ledger currentSlot confirmedUTxO requestedTxs of
Left (tx, err) ->
Error $ RequireFailed $ SnapshotDoesNotApply sn (txId tx) err
Right u -> cont u
pruneTransactions utxo = do
foldr go ([], utxo) localTxs
where
go tx (txs, u) =
-- XXX: We prune transactions on any error, while only some of them are
-- actually expected.
-- For example: `OutsideValidityIntervalUTxO` ledger errors are expected
-- here when a tx becomes invalid.
case applyTransactions ledger currentSlot u [tx] of
Left (_, _) -> (txs, u)
Right u' -> (txs <> [tx], u')
confSn = case confirmedSnapshot of
InitialSnapshot{} -> 0
ConfirmedSnapshot{snapshot = Snapshot{number}} -> number
seenSn = seenSnapshotNumber seenSnapshot
confirmedUTxO = case confirmedSnapshot of
InitialSnapshot{initialUTxO} -> initialUTxO
ConfirmedSnapshot{snapshot = Snapshot{utxo}} -> utxo
CoordinatedHeadState{confirmedSnapshot, seenSnapshot, allTxs, localTxs} = coordinatedHeadState
OpenState{parameters, coordinatedHeadState, currentSlot, headId} = st
Environment{signingKey} = env
-- | Process a snapshot acknowledgement ('AckSn') from a party.
--
-- We do require that the is from the last seen or next expected snapshot, and
-- potentially wait wait for the corresponding 'ReqSn' before proceeding. If the
-- party hasn't sent us a signature yet, we store it. Once a signature from each
-- party has been collected, we aggregate a multi-signature and verify it is
-- correct. If everything is fine, the snapshot can be considered as the latest
-- confirmed one. Similar to processing a 'ReqTx', we check whether we are
-- leading the next snapshot and craft a corresponding 'ReqSn' if needed.
--
-- __Transition__: 'OpenState' → 'OpenState'
onOpenNetworkAckSn ::
IsTx tx =>
Environment ->
OpenState tx ->
-- | Party which sent the AckSn.
Party ->
-- | Signature from other party.
Signature (Snapshot tx) ->
-- | Snapshot number of this AckSn.
SnapshotNumber ->
Word64 ->
Outcome tx
onOpenNetworkAckSn Environment{party} openState otherParty snapshotSignature sn nextStateChangeID =
-- TODO: verify authenticity of message and whether otherParty is part of the head
-- Spec: require s ∈ {ŝ, ŝ + 1}
requireValidAckSn $ do
-- Spec: wait ŝ = s
waitOnSeenSnapshot $ \snapshot sigs -> do
-- Spec: (j,.) ∉ ̂Σ
requireNotSignedYet sigs $ do
ifAllMembersHaveSigned snapshot sigs $ \sigs' -> do
-- Spec: σ̃ ← MS-ASig(k_H, ̂Σ̂)
let multisig = aggregateInOrder sigs' parties
requireVerifiedMultisignature multisig snapshot $
do
newState SnapshotConfirmed{snapshot, signatures = multisig, stateChangeID = nextStateChangeID}
<> cause (ClientEffect $ ServerOutput.SnapshotConfirmed headId snapshot multisig)
& maybeEmitSnapshot
where
seenSn = seenSnapshotNumber seenSnapshot
requireValidAckSn continue =
if sn `elem` [seenSn, seenSn + 1]
then continue
else Error $ RequireFailed $ AckSnNumberInvalid{requestedSn = sn, lastSeenSn = seenSn}
waitOnSeenSnapshot continue =
case seenSnapshot of
SeenSnapshot snapshot sigs
| seenSn == sn -> continue snapshot sigs
_ -> wait WaitOnSeenSnapshot
requireNotSignedYet sigs continue =
if not (Map.member otherParty sigs)
then continue
else Error $ RequireFailed $ SnapshotAlreadySigned{knownSignatures = Map.keys sigs, receivedSignature = otherParty}
ifAllMembersHaveSigned snapshot sigs cont =
let sigs' = Map.insert otherParty snapshotSignature sigs
in if Map.keysSet sigs' == Set.fromList parties
then cont sigs'
else
newState
PartySignedSnapshot
{ snapshot
, party = otherParty
, signature = snapshotSignature
, stateChangeID = nextStateChangeID
}
requireVerifiedMultisignature multisig msg cont =
case verifyMultiSignature vkeys multisig msg of
Verified -> cont
FailedKeys failures ->
Error $
RequireFailed $
InvalidMultisignature{multisig = show multisig, vkeys = failures}
KeyNumberMismatch ->
Error $
RequireFailed $
InvalidMultisignature{multisig = show multisig, vkeys}
maybeEmitSnapshot outcome =
if isLeader parameters party nextSn && not (null localTxs)
then
outcome
<> newState SnapshotRequestDecided{snapshotNumber = nextSn, stateChangeID = nextStateChangeID}
<> cause (NetworkEffect $ ReqSn nextSn (txId <$> localTxs))
else outcome
nextSn = sn + 1
vkeys = vkey <$> parties
OpenState
{ parameters = parameters@HeadParameters{parties}
, coordinatedHeadState
, headId
} = openState
CoordinatedHeadState{seenSnapshot, localTxs} = coordinatedHeadState
-- ** Closing the Head
-- | Client request to close the head. This leads to a close transaction on
-- chain using the latest confirmed snaphshot of the 'OpenState'.
--
-- __Transition__: 'OpenState' → 'OpenState'
onOpenClientClose ::
OpenState tx ->
Outcome tx
onOpenClientClose st =
cause OnChainEffect{postChainTx = CloseTx headId parameters confirmedSnapshot}
where
CoordinatedHeadState{confirmedSnapshot} = coordinatedHeadState
OpenState{coordinatedHeadState, headId, parameters} = st
-- | Observe a close transaction. If the closed snapshot number is smaller than
-- our last confirmed, we post a contest transaction. Also, we do schedule a
-- notification for clients to fanout at the deadline.
--
-- __Transition__: 'OpenState' → 'ClosedState'
onOpenChainCloseTx ::
OpenState tx ->
-- | New chain state.
ChainStateType tx ->
-- | Closed snapshot number.
SnapshotNumber ->
-- | Contestation deadline.
UTCTime ->
Word64 ->
Outcome tx
onOpenChainCloseTx openState newChainState closedSnapshotNumber contestationDeadline nextStateChangeID =
newState HeadClosed{chainState = newChainState, contestationDeadline, stateChangeID = nextStateChangeID}
<> causes
( notifyClient
: [ OnChainEffect
{ postChainTx = ContestTx{headId, headParameters, confirmedSnapshot}
}
| doContest
]
)
where
doContest =
number (getSnapshot confirmedSnapshot) > closedSnapshotNumber
notifyClient =
ClientEffect $
ServerOutput.HeadIsClosed
{ headId
, snapshotNumber = closedSnapshotNumber
, contestationDeadline
}
CoordinatedHeadState{confirmedSnapshot} = coordinatedHeadState
OpenState{parameters = headParameters, headId, coordinatedHeadState} = openState
-- | Observe a contest transaction. If the contested snapshot number is smaller
-- than our last confirmed snapshot, we post a contest transaction.
--
-- __Transition__: 'ClosedState' → 'ClosedState'
onClosedChainContestTx ::
ClosedState tx ->
-- | New chain state.
ChainStateType tx ->
SnapshotNumber ->
-- | Contestation deadline.
UTCTime ->
Word64 ->
Outcome tx
onClosedChainContestTx closedState newChainState snapshotNumber contestationDeadline nextStateChangeID =
newState HeadContested{chainState = newChainState, contestationDeadline, stateChangeID = nextStateChangeID}
<> if
| snapshotNumber < number (getSnapshot confirmedSnapshot) ->
cause notifyClients
<> cause OnChainEffect{postChainTx = ContestTx{headId, headParameters, confirmedSnapshot}}
| snapshotNumber > number (getSnapshot confirmedSnapshot) ->
-- TODO: A more recent snapshot number was succesfully contested, we will
-- not be able to fanout! We might want to communicate that to the client!
cause notifyClients
| otherwise ->
cause notifyClients
where
notifyClients =
ClientEffect
ServerOutput.HeadIsContested
{ snapshotNumber
, headId
, contestationDeadline
}
ClosedState{parameters = headParameters, confirmedSnapshot, headId} = closedState
-- | Client request to fanout leads to a fanout transaction on chain using the
-- latest confirmed snapshot from 'ClosedState'.
--
-- __Transition__: 'ClosedState' → 'ClosedState'
onClosedClientFanout ::
ClosedState tx ->
Outcome tx
onClosedClientFanout closedState =
cause OnChainEffect{postChainTx = FanoutTx{utxo, headSeed, contestationDeadline}}
where
Snapshot{utxo} = getSnapshot confirmedSnapshot
ClosedState{headSeed, confirmedSnapshot, contestationDeadline} = closedState
-- | Observe a fanout transaction by finalize the head state and notifying
-- clients about it.
--
-- __Transition__: 'ClosedState' → 'IdleState'
onClosedChainFanoutTx ::
ClosedState tx ->
-- | New chain state
ChainStateType tx ->
Word64 ->
Outcome tx
onClosedChainFanoutTx closedState newChainState nextStateChangeID =
newState HeadFannedOut{chainState = newChainState, stateChangeID = nextStateChangeID}
<> cause (ClientEffect $ ServerOutput.HeadIsFinalized{headId, utxo})
where
Snapshot{utxo} = getSnapshot confirmedSnapshot
ClosedState{confirmedSnapshot, headId} = closedState
-- | Handles inputs and converts them into 'StateChanged' events along with
-- 'Effect's, in case it is processed succesfully. Later, the Node will
-- 'aggregate' the events, resulting in a new 'HeadState'.
update ::
IsChainState tx =>
Environment ->
Ledger tx ->
Word64 ->
-- | Current HeadState to validate the command against.
HeadState tx ->
-- | Input to be processed.
Input tx ->
Outcome tx
update env ledger nextStateChangeID st ev = case (st, ev) of
(Idle _, ClientInput Init) ->
onIdleClientInit env
(Idle _, ChainInput Observation{observedTx = OnInitTx{headId, headSeed, headParameters, participants}, newChainState}) ->
onIdleChainInitTx env newChainState headId headSeed headParameters participants nextStateChangeID
(Initial initialState@InitialState{headId = ourHeadId}, ChainInput Observation{observedTx = OnCommitTx{headId, party = pt, committed = utxo}, newChainState})
| ourHeadId == headId -> onInitialChainCommitTx initialState newChainState pt utxo nextStateChangeID
| otherwise -> Error NotOurHead{ourHeadId, otherHeadId = headId}
(Initial initialState, ClientInput Abort) ->
onInitialClientAbort initialState
(Initial initialState@InitialState{headId = ourHeadId}, ChainInput Observation{observedTx = OnCollectComTx{headId}, newChainState})
| ourHeadId == headId -> onInitialChainCollectTx initialState newChainState nextStateChangeID
| otherwise -> Error NotOurHead{ourHeadId, otherHeadId = headId}
(Initial InitialState{headId = ourHeadId, committed}, ChainInput Observation{observedTx = OnAbortTx{headId}, newChainState})
| ourHeadId == headId -> onInitialChainAbortTx newChainState committed headId nextStateChangeID
| otherwise -> Error NotOurHead{ourHeadId, otherHeadId = headId}
(Initial InitialState{committed, headId}, ClientInput GetUTxO) ->
cause (ClientEffect . ServerOutput.GetUTxOResponse headId $ fold committed)
-- Open
(Open openState, ClientInput Close) ->
onOpenClientClose openState
(Open{}, ClientInput (NewTx tx)) ->
onOpenClientNewTx tx
(Open openState, NetworkInput ttl _ (ReqTx tx)) ->
onOpenNetworkReqTx env ledger openState ttl tx nextStateChangeID
(Open openState, NetworkInput _ otherParty (ReqSn sn txIds)) ->
-- XXX: ttl == 0 not handled for ReqSn
onOpenNetworkReqSn env ledger openState otherParty sn txIds nextStateChangeID
(Open openState, NetworkInput _ otherParty (AckSn snapshotSignature sn)) ->
-- XXX: ttl == 0 not handled for AckSn
onOpenNetworkAckSn env openState otherParty snapshotSignature sn nextStateChangeID
( Open openState@OpenState{headId = ourHeadId}
, ChainInput Observation{observedTx = OnCloseTx{headId, snapshotNumber = closedSnapshotNumber, contestationDeadline}, newChainState}
)
| ourHeadId == headId ->
onOpenChainCloseTx openState newChainState closedSnapshotNumber contestationDeadline nextStateChangeID
| otherwise ->
Error NotOurHead{ourHeadId, otherHeadId = headId}
(Open OpenState{coordinatedHeadState = CoordinatedHeadState{confirmedSnapshot}, headId}, ClientInput GetUTxO) ->
-- TODO: Is it really intuitive that we respond from the confirmed ledger if
-- transactions are validated against the seen ledger?
cause (ClientEffect . ServerOutput.GetUTxOResponse headId $ getField @"utxo" $ getSnapshot confirmedSnapshot)
-- NOTE: If posting the collectCom transaction failed in the open state, then
-- another party likely opened the head before us and it's okay to ignore.
(Open{}, ChainInput PostTxError{postChainTx = CollectComTx{}}) ->
noop
-- Closed
(Closed closedState@ClosedState{headId = ourHeadId}, ChainInput Observation{observedTx = OnContestTx{headId, snapshotNumber, contestationDeadline}, newChainState})
| ourHeadId == headId ->
onClosedChainContestTx closedState newChainState snapshotNumber contestationDeadline nextStateChangeID
| otherwise ->
Error NotOurHead{ourHeadId, otherHeadId = headId}
(Closed ClosedState{contestationDeadline, readyToFanoutSent, headId}, ChainInput Tick{chainTime})
| chainTime > contestationDeadline && not readyToFanoutSent ->
newState HeadIsReadyToFanout{stateChangeID = nextStateChangeID}
<> cause (ClientEffect $ ServerOutput.ReadyToFanout headId)
(Closed closedState, ClientInput Fanout) ->
onClosedClientFanout closedState
(Closed closedState@ClosedState{headId = ourHeadId}, ChainInput Observation{observedTx = OnFanoutTx{headId}, newChainState})
| ourHeadId == headId ->
onClosedChainFanoutTx closedState newChainState nextStateChangeID
| otherwise ->
Error NotOurHead{ourHeadId, otherHeadId = headId}
-- General
(_, ChainInput Rollback{rolledBackChainState}) ->
newState ChainRolledBack{chainState = rolledBackChainState, stateChangeID}
(_, ChainInput Tick{chainSlot}) ->
newState TickObserved{chainSlot, stateChangeID}
-- FIXME(Elaine): should this bump the stateChangeID as well?
(_, ChainInput PostTxError{postChainTx, postTxError}) ->
cause . ClientEffect $ ServerOutput.PostTxOnChainFailed{postChainTx, postTxError}
(_, ClientInput{clientInput}) ->
cause . ClientEffect $ ServerOutput.CommandFailed clientInput st
_ ->
Error $ UnhandledInput ev st
where
stateChangeID = nextStateChangeID
-- * HeadState aggregate
-- | Reflect 'StateChanged' events onto the 'HeadState' aggregate.
aggregate :: IsChainState tx => HeadState tx -> StateChanged tx -> HeadState tx
aggregate st = \case
HeadInitialized{parameters = parameters@HeadParameters{parties}, headId, headSeed, chainState} ->
Initial
InitialState
{ parameters = parameters
, pendingCommits = Set.fromList parties
, committed = mempty
, chainState
, headId
, headSeed
}
CommittedUTxO{committedUTxO, chainState, party} ->
case st of
Initial InitialState{parameters, pendingCommits, committed, headId, headSeed} ->
Initial
InitialState
{ parameters
, pendingCommits = remainingParties
, committed = newCommitted
, chainState
, headId
, headSeed
}
where
newCommitted = Map.insert party committedUTxO committed
remainingParties = Set.delete party pendingCommits
_otherState -> st
TransactionReceived{tx} ->
case st of
Open os@OpenState{coordinatedHeadState} ->
Open
os
{ coordinatedHeadState =
-- Spec: Tall ← ̂Tall ∪ { (hash(tx), tx) }
coordinatedHeadState
{ allTxs = allTxs <> fromList [(txId tx, tx)]
}
}
where
CoordinatedHeadState{allTxs} = coordinatedHeadState
_otherState -> st
TransactionAppliedToLocalUTxO{tx, newLocalUTxO} ->
case st of
Open os@OpenState{coordinatedHeadState} ->
Open
os
{ coordinatedHeadState =
coordinatedHeadState
{ localUTxO = newLocalUTxO
, localTxs = localTxs <> [tx]
}
}
where
CoordinatedHeadState{localTxs} = coordinatedHeadState
_otherState -> st
SnapshotRequestDecided{snapshotNumber} ->
case st of
Open os@OpenState{coordinatedHeadState} ->
Open
os
{ coordinatedHeadState =
coordinatedHeadState
{ seenSnapshot =
RequestedSnapshot
{ lastSeen = seenSnapshotNumber seenSnapshot
, requested = snapshotNumber
}
}
}
where
CoordinatedHeadState{seenSnapshot} = coordinatedHeadState
_otherState -> st
SnapshotRequested{snapshot, requestedTxIds, newLocalUTxO, newLocalTxs} ->
case st of
Open os@OpenState{coordinatedHeadState} ->
Open
os
{ coordinatedHeadState =
coordinatedHeadState
{ seenSnapshot = SeenSnapshot snapshot mempty
, localTxs = newLocalTxs
, localUTxO = newLocalUTxO
, allTxs = foldr Map.delete allTxs requestedTxIds
}
}
where
CoordinatedHeadState{allTxs} = coordinatedHeadState
_otherState -> st
HeadAborted{chainState} ->
Idle $
IdleState
{ chainState
}
HeadClosed{chainState, contestationDeadline} ->
case st of
Open
OpenState
{ parameters
, coordinatedHeadState =
CoordinatedHeadState
{ confirmedSnapshot
}
, headId
, headSeed
} ->
Closed
ClosedState
{ parameters
, confirmedSnapshot
, contestationDeadline
, readyToFanoutSent = False
, chainState
, headId
, headSeed
}
_otherState -> st
HeadContested{chainState, contestationDeadline} ->
case st of
Closed ClosedState{parameters, confirmedSnapshot, readyToFanoutSent, headId, headSeed} ->
Closed
ClosedState
{ parameters
, confirmedSnapshot
, contestationDeadline
, readyToFanoutSent
, chainState
, headId
, headSeed
}
_otherState -> st
HeadFannedOut{chainState} ->
case st of
Closed _ ->
Idle $
IdleState
{ chainState
}
_otherState -> st
HeadOpened{chainState, initialUTxO} ->
case st of
Initial InitialState{parameters, headId, headSeed} ->
Open
OpenState
{ parameters
, coordinatedHeadState =
CoordinatedHeadState
{ localUTxO = initialUTxO
, allTxs = mempty
, localTxs = mempty
, confirmedSnapshot = InitialSnapshot{headId, initialUTxO}
, seenSnapshot = NoSeenSnapshot
}
, chainState
, headId
, headSeed
, currentSlot = chainStateSlot chainState
}
_otherState -> st
SnapshotConfirmed{snapshot, signatures} ->
case st of
Open os@OpenState{coordinatedHeadState} ->
Open
os
{ coordinatedHeadState =
coordinatedHeadState
{ confirmedSnapshot =
ConfirmedSnapshot
{ snapshot
, signatures
}
, seenSnapshot = LastSeenSnapshot number
}
}
where
Snapshot{number} = snapshot
_otherState -> st
PartySignedSnapshot{snapshot, party, signature} ->
case st of
Open
os@OpenState
{ coordinatedHeadState =
chs@CoordinatedHeadState
{ seenSnapshot = SeenSnapshot{signatories}
}
} ->
Open
os
{ coordinatedHeadState =
chs{seenSnapshot = SeenSnapshot snapshot sigs}
}
where
sigs = Map.insert party signature signatories
_otherState -> st
HeadIsReadyToFanout{} ->
case st of
Closed cst -> Closed cst{readyToFanoutSent = True}
_otherState -> st
ChainRolledBack{chainState} ->
setChainState chainState st
TickObserved{chainSlot} ->
case st of
Open ost@OpenState{} -> Open ost{currentSlot = chainSlot}
_otherState -> st
aggregateState ::
IsChainState tx =>
HeadState tx ->
Outcome tx ->
HeadState tx