-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathHeadLogic.hs
956 lines (885 loc) · 32.5 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
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE UndecidableInstances #-}
-- | Implements the Head Protocol's /state machine/ as /pure functions/ in an event sourced manner.
--
-- More specifically, the 'update' will handle incoming 'Event' (or rather
-- "commands" in event sourcing speak) and convert that into a set of
-- side-'Effect's and internal '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.Event,
module Hydra.HeadLogic.Error,
module Hydra.HeadLogic.State,
module Hydra.HeadLogic.Outcome,
module Hydra.HeadLogic.SnapshotOutcome,
)
where
import Hydra.Prelude
import qualified Data.Map.Strict as Map
import Data.Set ((\\))
import qualified Data.Set as Set
import GHC.Records (getField)
import Hydra.API.ClientInput (ClientInput (..))
import qualified Hydra.API.ServerOutput as ServerOutput
import Hydra.Chain (
ChainEvent (..),
ChainStateHistory,
ChainStateType,
HeadId,
HeadParameters (..),
IsChainState (chainStateSlot),
OnChainTx (..),
PostChainTx (..),
initHistory,
pushNewState,
rollbackHistory,
)
import Hydra.ContestationPeriod (ContestationPeriod)
import Hydra.Crypto (
Signature,
Verified (..),
aggregateInOrder,
sign,
verifyMultiSignature,
)
import Hydra.HeadLogic.Error (
LogicError (..),
RequirementFailure (..),
)
import Hydra.HeadLogic.Event (
Event (..),
TTL,
)
import Hydra.HeadLogic.Outcome (
Effect (..),
Outcome (..),
StateChanged (..),
WaitReason (..),
collectEffects,
collectWaits,
)
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.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 =
Effects [OnChainEffect{postChainTx = InitTx parameters}]
where
parameters =
HeadParameters
{ contestationPeriod
, parties = party : otherParties
}
Environment{party, otherParties, contestationPeriod} = env
-- | Observe an init transaction, initialize parameters in an 'InitialState' and
-- notify clients that they can now commit.
--
-- __Transition__: 'IdleState' → 'InitialState'
onIdleChainInitTx ::
-- | New chain state.
ChainStateType tx ->
[Party] ->
ContestationPeriod ->
HeadId ->
Outcome tx
onIdleChainInitTx newChainState parties contestationPeriod headId =
StateChanged
( HeadInitialized
{ parameters = HeadParameters{contestationPeriod, parties}
, chainState = newChainState
, headId
}
)
<> Effects [ClientEffect $ ServerOutput.HeadIsInitializing headId (fromList parties)]
-- | 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 ->
Outcome tx
onInitialChainCommitTx st newChainState pt utxo =
StateChanged CommittedUTxO{party = pt, committedUTxO = utxo, chainState = newChainState}
<> Effects
( notifyClient
: [postCollectCom | canCollectCom]
)
where
newCommitted = Map.insert pt utxo committed
notifyClient = ClientEffect $ ServerOutput.Committed headId pt utxo
postCollectCom =
OnChainEffect
{ postChainTx = CollectComTx $ fold newCommitted
}
canCollectCom = null remainingParties
remainingParties = Set.delete pt pendingCommits
InitialState{pendingCommits, committed, headId} = 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 =
Effects [OnChainEffect{postChainTx = AbortTx{utxo = fold committed}}]
where
InitialState{committed} = 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 ->
Outcome tx
onInitialChainAbortTx newChainState committed headId =
StateChanged HeadAborted{chainState = newChainState}
<> Effects [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 ->
Outcome tx
onInitialChainCollectTx st newChainState =
StateChanged HeadOpened{chainState = newChainState, initialUTxO = u0}
<> Effects [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 =
Effects [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 ->
Outcome tx
onOpenNetworkReqTx env ledger st ttl tx =
-- Spec: Tall ← ̂Tall ∪ { (hash(tx), tx) }
(StateChanged TransactionReceived{tx} <>) $
-- 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
StateChanged (TransactionAppliedToLocalUTxO{tx = tx, newLocalUTxO})
-- 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.
<> StateChanged SnapshotRequestDecided{snapshotNumber = nextSn}
<> Effects [NetworkEffect (ReqSn nextSn (txId <$> localTxs'))]
else StateChanged (TransactionAppliedToLocalUTxO{tx, newLocalUTxO})
)
<> Effects [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.
Effects [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] ->
Outcome tx
onOpenNetworkReqSn env ledger st otherParty sn requestedTxIds =
-- 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 (confSn + 1) u requestedTxIds
-- Spec: σᵢ
let snapshotSignature = sign signingKey nextSnapshot
(Effects [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 }
StateChanged
SnapshotRequested
{ snapshot = nextSnapshot
, requestedTxIds
, newLocalUTxO
, newLocalTxs
}
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} = 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 ->
Outcome tx
onOpenNetworkAckSn Environment{party} openState otherParty snapshotSignature sn =
-- 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
Effects [ClientEffect $ ServerOutput.SnapshotConfirmed headId snapshot multisig]
<> StateChanged SnapshotConfirmed{snapshot, signatures = 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
StateChanged
PartySignedSnapshot
{ snapshot
, party = otherParty
, signature = snapshotSignature
}
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
<> StateChanged SnapshotRequestDecided{snapshotNumber = nextSn}
<> Effects [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 =
Effects [OnChainEffect{postChainTx = CloseTx confirmedSnapshot}]
where
CoordinatedHeadState{confirmedSnapshot} = coordinatedHeadState
OpenState{coordinatedHeadState} = 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 ->
Outcome tx
onOpenChainCloseTx openState newChainState closedSnapshotNumber contestationDeadline =
StateChanged HeadClosed{chainState = newChainState, contestationDeadline}
<> Effects
( notifyClient
: [ OnChainEffect
{ postChainTx = ContestTx{confirmedSnapshot}
}
| doContest
]
)
where
doContest =
number (getSnapshot confirmedSnapshot) > closedSnapshotNumber
notifyClient =
ClientEffect $
ServerOutput.HeadIsClosed
{ headId
, snapshotNumber = closedSnapshotNumber
, contestationDeadline
}
CoordinatedHeadState{confirmedSnapshot} = coordinatedHeadState
OpenState{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 ->
SnapshotNumber ->
Outcome tx
onClosedChainContestTx closedState snapshotNumber
| snapshotNumber < number (getSnapshot confirmedSnapshot) =
Effects
[ ClientEffect ServerOutput.HeadIsContested{snapshotNumber, headId}
, OnChainEffect{postChainTx = ContestTx{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!
Effects [ClientEffect ServerOutput.HeadIsContested{snapshotNumber, headId}]
| otherwise =
Effects [ClientEffect ServerOutput.HeadIsContested{snapshotNumber, headId}]
where
ClosedState{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 =
Effects
[ OnChainEffect
{ postChainTx =
FanoutTx{utxo, contestationDeadline}
}
]
where
Snapshot{utxo} = getSnapshot confirmedSnapshot
ClosedState{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 ->
Outcome tx
onClosedChainFanoutTx closedState newChainState =
StateChanged
HeadFannedOut{chainState = newChainState}
<> Effects [ClientEffect $ ServerOutput.HeadIsFinalized{headId, utxo}]
where
Snapshot{utxo} = getSnapshot confirmedSnapshot
ClosedState{confirmedSnapshot, headId} = closedState
-- | Handles commands and converts them into internal '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 ->
-- | Current HeadState to validate the command against.
HeadState tx ->
-- | Command sent to the HeadLogic to be processed.
Event tx ->
Outcome tx
update env ledger st ev = case (st, ev) of
(Idle _, ClientEvent Init) ->
onIdleClientInit env
(Idle _, OnChainEvent Observation{observedTx = OnInitTx{headId, contestationPeriod, parties}, newChainState}) ->
onIdleChainInitTx newChainState parties contestationPeriod headId
(Initial initialState, OnChainEvent Observation{observedTx = OnCommitTx{party = pt, committed = utxo}, newChainState}) ->
onInitialChainCommitTx initialState newChainState pt utxo
(Initial initialState, ClientEvent Abort) ->
onInitialClientAbort initialState
(Initial initialState, OnChainEvent Observation{observedTx = OnCollectComTx{}, newChainState}) ->
onInitialChainCollectTx initialState newChainState
(Initial InitialState{headId, committed}, OnChainEvent Observation{observedTx = OnAbortTx{}, newChainState}) ->
onInitialChainAbortTx newChainState committed headId
(Initial InitialState{committed, headId}, ClientEvent GetUTxO) ->
Effects [ClientEffect . ServerOutput.GetUTxOResponse headId $ fold committed]
-- Open
(Open openState, ClientEvent Close) ->
onOpenClientClose openState
(Open{}, ClientEvent (NewTx tx)) ->
onOpenClientNewTx tx
(Open openState, NetworkEvent ttl _ (ReqTx tx)) ->
onOpenNetworkReqTx env ledger openState ttl tx
(Open openState, NetworkEvent _ otherParty (ReqSn sn txIds)) ->
-- XXX: ttl == 0 not handled for ReqSn
onOpenNetworkReqSn env ledger openState otherParty sn txIds
(Open openState, NetworkEvent _ otherParty (AckSn snapshotSignature sn)) ->
-- XXX: ttl == 0 not handled for AckSn
onOpenNetworkAckSn env openState otherParty snapshotSignature sn
( Open openState@OpenState{headId = ourHeadId}
, OnChainEvent Observation{observedTx = OnCloseTx{headId, snapshotNumber = closedSnapshotNumber, contestationDeadline}, newChainState}
)
| ourHeadId == headId ->
onOpenChainCloseTx openState newChainState closedSnapshotNumber contestationDeadline
| otherwise ->
Error NotOurHead{ourHeadId, otherHeadId = headId}
(Open OpenState{coordinatedHeadState = CoordinatedHeadState{confirmedSnapshot}, headId}, ClientEvent GetUTxO) ->
-- TODO: Is it really intuitive that we respond from the confirmed ledger if
-- transactions are validated against the seen ledger?
Effects [ClientEffect . ServerOutput.GetUTxOResponse headId $ getField @"utxo" $ getSnapshot confirmedSnapshot]
-- Closed
(Closed closedState, OnChainEvent Observation{observedTx = OnContestTx{snapshotNumber}}) ->
onClosedChainContestTx closedState snapshotNumber
(Closed ClosedState{contestationDeadline, readyToFanoutSent, headId}, OnChainEvent Tick{chainTime})
| chainTime > contestationDeadline && not readyToFanoutSent ->
StateChanged
HeadIsReadyToFanout
<> Effects [ClientEffect $ ServerOutput.ReadyToFanout headId]
(Closed closedState, ClientEvent Fanout) ->
onClosedClientFanout closedState
(Closed closedState, OnChainEvent Observation{observedTx = OnFanoutTx{}, newChainState}) ->
onClosedChainFanoutTx closedState newChainState
-- General
(_, OnChainEvent Rollback{rolledBackChainState}) ->
StateChanged ChainRolledBack{chainState = rolledBackChainState}
(_, OnChainEvent Tick{chainSlot}) ->
StateChanged (TickObserved{chainSlot})
(_, PostTxError{postChainTx, postTxError}) ->
Effects [ClientEffect $ ServerOutput.PostTxOnChainFailed{postChainTx, postTxError}]
(_, ClientEvent{clientInput}) ->
Effects [ClientEffect $ ServerOutput.CommandFailed clientInput]
_ ->
Error $ InvalidEvent ev st
-- * 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, chainState} ->
Initial
InitialState
{ parameters = parameters
, pendingCommits = Set.fromList parties
, committed = mempty
, chainState
, headId
}
CommittedUTxO{committedUTxO, chainState, party} ->
case st of
Initial InitialState{parameters, pendingCommits, committed, headId} ->
Initial
InitialState
{ parameters
, pendingCommits = remainingParties
, committed = newCommitted
, chainState
, headId
}
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
} ->
Closed
ClosedState
{ parameters
, confirmedSnapshot
, contestationDeadline
, readyToFanoutSent = False
, chainState
, headId
}
_otherState -> st
HeadFannedOut{chainState} ->
case st of
Closed _ ->
Idle $
IdleState
{ chainState
}
_otherState -> st
HeadOpened{chainState, initialUTxO} ->
case st of
Initial InitialState{parameters, headId} ->
Open
OpenState
{ parameters
, coordinatedHeadState =
CoordinatedHeadState
{ localUTxO = initialUTxO
, allTxs = mempty
, localTxs = mempty
, confirmedSnapshot = InitialSnapshot{initialUTxO}
, seenSnapshot = NoSeenSnapshot
}
, chainState
, headId
, 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
aggregateState s outcome =
recoverState s $ collectStateChanged outcome
where
collectStateChanged = \case
Error{} -> []
Wait{} -> []
StateChanged change -> [change]
Effects{} -> []
Combined l r ->
collectStateChanged l <> collectStateChanged r
recoverChainStateHistory ::
(Foldable t, IsChainState tx) =>
ChainStateType tx ->
t (StateChanged tx) ->
ChainStateHistory tx
recoverChainStateHistory initialChainState =
foldl' aggregateChainStateHistory (initHistory initialChainState)
where
aggregateChainStateHistory history = \case
HeadInitialized{chainState} -> pushNewState chainState history
CommittedUTxO{chainState} -> pushNewState chainState history
HeadAborted{chainState} -> pushNewState chainState history
HeadOpened{chainState} -> pushNewState chainState history
TransactionAppliedToLocalUTxO{} -> history
SnapshotRequestDecided{} -> history
SnapshotRequested{} -> history
TransactionReceived{} -> history
PartySignedSnapshot{} -> history
SnapshotConfirmed{} -> history
HeadClosed{chainState} -> pushNewState chainState history
HeadIsReadyToFanout -> history
HeadFannedOut{chainState} -> pushNewState chainState history
ChainRolledBack{chainState} ->
rollbackHistory (chainStateSlot chainState) history
TickObserved{} -> history
recoverState ::
(Foldable t, IsChainState tx) =>
HeadState tx ->
t (StateChanged tx) ->
HeadState tx
recoverState = foldl' aggregate