-
Notifications
You must be signed in to change notification settings - Fork 86
/
HeadLogic.hs
1138 lines (1015 loc) · 39.7 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 TypeApplications #-}
{-# LANGUAGE UndecidableInstances #-}
-- | Implements the Head Protocol's /state machine/ as a /pure function/.
--
-- The protocol is described in two parts in the [Hydra paper](https://iohk.io/en/research/library/papers/hydrafast-isomorphic-state-channels/)
--
-- * One part detailing how the Head deals with /client input/.
-- * Another part describing how the Head reacts to /network messages/ from peers.
-- * A third part detailing the /On-Chain Verification (OCV)/ protocol, i.e. the abstract "smart contracts" that are need to provide on-chain security.
--
-- This module is about the first two parts, while the "Hydra.Contract.Head" module in 'hydra-plutus' covers the third part.
module Hydra.HeadLogic where
import Hydra.Prelude
import Data.List (elemIndex)
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import GHC.Records (getField)
import Hydra.API.ClientInput (ClientInput (..))
import Hydra.API.ServerOutput (ServerOutput (..))
import Hydra.Chain (
ChainEvent (..),
ChainSlot,
ChainStateType,
HeadId,
HeadParameters (..),
IsChainState (chainStateSlot),
OnChainTx (..),
PostChainTx (..),
PostTxError,
)
import Hydra.ContestationPeriod
import Hydra.Crypto (
HydraKey,
Signature,
SigningKey,
aggregateInOrder,
sign,
verifyMultiSignature,
)
import Hydra.Ledger (
IsTx,
Ledger (..),
UTxOType,
ValidationError,
applyTransactions,
)
import Hydra.Network.Message (Message (..))
import Hydra.Party (Party (vkey))
import Hydra.Snapshot (ConfirmedSnapshot (..), Snapshot (..), SnapshotNumber, getSnapshot)
import Test.QuickCheck (oneof)
-- * Types
-- TODO: Move logic up and types down or re-organize using explicit exports
-- | The different events which are processed by the head logic (the "core").
-- Corresponding to each of the "shell" layers, we distinguish between events
-- from the client, the network and the chain.
data Event tx
= -- | Event received from clients via the "Hydra.API".
ClientEvent {clientInput :: ClientInput tx}
| -- | Event received from peers via a "Hydra.Network".
--
-- * `ttl` is a simple counter that's decreased every time the event is
-- reenqueued due to a wait. It's default value is `defaultTTL`
NetworkEvent {ttl :: TTL, message :: Message tx}
| -- | Event received from the chain via a "Hydra.Chain".
OnChainEvent {chainEvent :: ChainEvent tx}
| -- | Event to re-ingest errors from 'postTx' for further processing.
PostTxError {postChainTx :: PostChainTx tx, postTxError :: PostTxError tx}
deriving stock (Generic)
deriving instance (IsTx tx, IsChainState tx) => Eq (Event tx)
deriving instance (IsTx tx, IsChainState tx) => Show (Event tx)
deriving instance (IsTx tx, IsChainState tx) => ToJSON (Event tx)
deriving instance (IsTx tx, IsChainState tx) => FromJSON (Event tx)
instance
( IsTx tx
, Arbitrary (ChainStateType tx)
) =>
Arbitrary (Event tx)
where
arbitrary = genericArbitrary
-- | Analogous to events, the pure head logic "core" can have effects emited to
-- the "shell" layers and we distinguish the same: effects onto the client, the
-- network and the chain.
data Effect tx
= -- | Effect to be handled by the "Hydra.API", results in sending this 'ServerOutput'.
ClientEffect {serverOutput :: ServerOutput tx}
| -- | Effect to be handled by a "Hydra.Network", results in a 'Hydra.Network.broadcast'.
NetworkEffect {message :: Message tx}
| -- | Effect to be handled by a "Hydra.Chain", results in a 'Hydra.Chain.postTx'.
OnChainEffect {chainState :: ChainStateType tx, postChainTx :: PostChainTx tx}
deriving stock (Generic)
deriving instance (IsTx tx, IsChainState tx) => Eq (Effect tx)
deriving instance (IsTx tx, IsChainState tx) => Show (Effect tx)
deriving instance (IsTx tx, IsChainState tx) => ToJSON (Effect tx)
deriving instance (IsTx tx, IsChainState tx) => FromJSON (Effect tx)
instance
( IsTx tx
, Arbitrary (ChainStateType tx)
) =>
Arbitrary (Effect tx)
where
arbitrary = genericArbitrary
-- | The main state of the Hydra protocol state machine. It holds both, the
-- overall protocol state, but also the off-chain 'CoordinatedHeadState'.
--
-- It is a recursive data structure, where 'previousRecoverableState' fields
-- record the state before the latest 'OnChainEvent' that has been observed.
-- On-Chain events are indeed only __eventually__ immutable and the application
-- state may be rolled back at any time (with a decreasing probability as the
-- time pass).
--
-- Thus, leverage functional immutable data-structure, we build a recursive
-- structure of states which we can easily navigate backwards when needed (see
-- 'Rollback' and 'rollback').
--
-- Note that currently, rolling back to a previous recoverable state eliminates
-- any off-chain events (e.g. transactions) that happened after that state. This
-- is particularly important for anything following the transition to
-- 'OpenState' since this is where clients may start submitting transactions. In
-- practice, clients should not send transactions right way but wait for a
-- certain grace period to minimize the risk.
data HeadState tx
= Idle (IdleState tx)
| Initial (InitialState tx)
| Open (OpenState tx)
| Closed (ClosedState tx)
deriving stock (Generic)
instance (IsTx tx, Arbitrary (ChainStateType tx)) => Arbitrary (HeadState tx) where
arbitrary = genericArbitrary
deriving instance (IsTx tx, Eq (ChainStateType tx)) => Eq (HeadState tx)
deriving instance (IsTx tx, Show (ChainStateType tx)) => Show (HeadState tx)
deriving instance (IsTx tx, ToJSON (ChainStateType tx)) => ToJSON (HeadState tx)
deriving instance (IsTx tx, FromJSON (ChainStateType tx)) => FromJSON (HeadState tx)
-- | Get the chain state in any 'HeadState'.
getChainState :: HeadState tx -> ChainStateType tx
getChainState = \case
Idle IdleState{chainState} -> chainState
Initial InitialState{chainState} -> chainState
Open OpenState{chainState} -> chainState
Closed ClosedState{chainState} -> chainState
-- | Update the chain state in any 'HeadState'.
setChainState :: ChainStateType tx -> HeadState tx -> HeadState tx
setChainState chainState = \case
Idle st -> Idle st{chainState}
Initial st -> Initial st{chainState}
Open st -> Open st{chainState}
Closed st -> Closed st{chainState}
-- ** Idle
-- | An 'Idle' head only having a chain state with things seen on chain so far.
newtype IdleState tx = IdleState {chainState :: ChainStateType tx}
deriving (Generic)
deriving instance Eq (ChainStateType tx) => Eq (IdleState tx)
deriving instance Show (ChainStateType tx) => Show (IdleState tx)
deriving anyclass instance ToJSON (ChainStateType tx) => ToJSON (IdleState tx)
deriving anyclass instance FromJSON (ChainStateType tx) => FromJSON (IdleState tx)
instance (Arbitrary (ChainStateType tx)) => Arbitrary (IdleState tx) where
arbitrary = genericArbitrary
-- ** Initial
-- | An 'Initial' head which already has an identity and is collecting commits.
data InitialState tx = InitialState
{ parameters :: HeadParameters
, pendingCommits :: PendingCommits
, committed :: Committed tx
, chainState :: ChainStateType tx
, headId :: HeadId
, previousRecoverableState :: HeadState tx
}
deriving (Generic)
deriving instance (IsTx tx, Eq (ChainStateType tx)) => Eq (InitialState tx)
deriving instance (IsTx tx, Show (ChainStateType tx)) => Show (InitialState tx)
deriving instance (IsTx tx, ToJSON (ChainStateType tx)) => ToJSON (InitialState tx)
deriving instance (IsTx tx, FromJSON (ChainStateType tx)) => FromJSON (InitialState tx)
instance (IsTx tx, Arbitrary (ChainStateType tx)) => Arbitrary (InitialState tx) where
arbitrary = do
InitialState
<$> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> oneof
[ Idle <$> arbitrary
, Initial <$> arbitrary
]
type PendingCommits = Set Party
type Committed tx = Map Party (UTxOType tx)
-- ** Open
-- | An 'Open' head with a 'CoordinatedHeadState' tracking off-chain
-- transactions.
data OpenState tx = OpenState
{ parameters :: HeadParameters
, coordinatedHeadState :: CoordinatedHeadState tx
, chainState :: ChainStateType tx
, headId :: HeadId
, previousRecoverableState :: HeadState tx
}
deriving (Generic)
deriving instance (IsTx tx, Eq (ChainStateType tx)) => Eq (OpenState tx)
deriving instance (IsTx tx, Show (ChainStateType tx)) => Show (OpenState tx)
deriving instance (IsTx tx, ToJSON (ChainStateType tx)) => ToJSON (OpenState tx)
deriving instance (IsTx tx, FromJSON (ChainStateType tx)) => FromJSON (OpenState tx)
instance (IsTx tx, Arbitrary (ChainStateType tx)) => Arbitrary (OpenState tx) where
arbitrary =
OpenState
<$> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> (Initial <$> arbitrary)
-- | Off-chain state of the Coordinated Head protocol.
data CoordinatedHeadState tx = CoordinatedHeadState
{ seenUTxO :: UTxOType tx
-- ^ The latest UTxO resulting from applying 'seenTxs' to
-- 'confirmedSnapshot'. Spec: L̂
, seenTxs :: [tx]
-- ^ List of seen transactions pending inclusion in a snapshot. Spec: T̂
, confirmedSnapshot :: ConfirmedSnapshot tx
-- ^ The latest confirmed snapshot. Spec: U̅, s̅ and σ̅
, seenSnapshot :: SeenSnapshot tx
-- ^ Last seen snapshot and signatures accumulator. Spec: Û, ŝ and Σ̂
}
deriving stock (Generic)
deriving instance IsTx tx => Eq (CoordinatedHeadState tx)
deriving instance IsTx tx => Show (CoordinatedHeadState tx)
deriving instance IsTx tx => ToJSON (CoordinatedHeadState tx)
deriving instance IsTx tx => FromJSON (CoordinatedHeadState tx)
instance IsTx tx => Arbitrary (CoordinatedHeadState tx) where
arbitrary = genericArbitrary
-- | Data structure to help in tracking whether we have seen or requested a
-- ReqSn already and if seen, the signatures we collected already.
data SeenSnapshot tx
= -- | Never saw a ReqSn.
NoSeenSnapshot
| -- | No snapshot in flight with last seen snapshot number as given.
LastSeenSnapshot {lastSeen :: SnapshotNumber}
| -- | ReqSn was sent out and it should be considered already in flight.
RequestedSnapshot
{ lastSeen :: SnapshotNumber
, requested :: SnapshotNumber
}
| -- | ReqSn for given snapshot was received.
SeenSnapshot
{ snapshot :: Snapshot tx
, signatories :: Map Party (Signature (Snapshot tx))
-- ^ Collected signatures and so far.
}
deriving stock (Generic)
instance IsTx tx => Arbitrary (SeenSnapshot tx) where
arbitrary = genericArbitrary
deriving instance IsTx tx => Eq (SeenSnapshot tx)
deriving instance IsTx tx => Show (SeenSnapshot tx)
deriving instance IsTx tx => ToJSON (SeenSnapshot tx)
deriving instance IsTx tx => FromJSON (SeenSnapshot tx)
-- | Get the last seen snapshot number given a 'SeenSnapshot'.
seenSnapshotNumber :: SeenSnapshot tx -> SnapshotNumber
seenSnapshotNumber = \case
NoSeenSnapshot -> 0
LastSeenSnapshot{lastSeen} -> lastSeen
RequestedSnapshot{lastSeen} -> lastSeen
SeenSnapshot{snapshot = Snapshot{number}} -> number
-- ** Closed
-- | An 'Closed' head with an current candidate 'ConfirmedSnapshot', which may
-- be contested before the 'contestationDeadline'.
data ClosedState tx = ClosedState
{ parameters :: HeadParameters
, confirmedSnapshot :: ConfirmedSnapshot tx
, contestationDeadline :: UTCTime
, readyToFanoutSent :: Bool
-- ^ Tracks whether we have informed clients already about being
-- 'ReadyToFanout'.
, chainState :: ChainStateType tx
, headId :: HeadId
, previousRecoverableState :: HeadState tx
}
deriving (Generic)
deriving instance (IsTx tx, Eq (ChainStateType tx)) => Eq (ClosedState tx)
deriving instance (IsTx tx, Show (ChainStateType tx)) => Show (ClosedState tx)
deriving instance (IsTx tx, ToJSON (ChainStateType tx)) => ToJSON (ClosedState tx)
deriving instance (IsTx tx, FromJSON (ChainStateType tx)) => FromJSON (ClosedState tx)
instance (IsTx tx, Arbitrary (ChainStateType tx)) => Arbitrary (ClosedState tx) where
arbitrary =
ClosedState
<$> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> oneof
[ Open <$> arbitrary
, Closed <$> arbitrary
]
-- ** Other types
type TTL = Natural
defaultTTL :: TTL
defaultTTL = 5
-- | Preliminary type for collecting errors occurring during 'update'.
-- TODO: Try to merge this (back) into 'Outcome'.
data LogicError tx
= InvalidEvent (Event tx) (HeadState tx)
| InvalidState (HeadState tx)
| InvalidSnapshot {expected :: SnapshotNumber, actual :: SnapshotNumber}
| LedgerError ValidationError
| RequireFailed Text
deriving stock (Generic)
instance (Typeable tx, Show (Event tx), Show (HeadState tx)) => Exception (LogicError tx)
instance (Arbitrary (Event tx), Arbitrary (HeadState tx)) => Arbitrary (LogicError tx) where
arbitrary = genericArbitrary
deriving instance (Eq (HeadState tx), Eq (Event tx)) => Eq (LogicError tx)
deriving instance (Show (HeadState tx), Show (Event tx)) => Show (LogicError tx)
deriving instance (ToJSON (Event tx), ToJSON (HeadState tx)) => ToJSON (LogicError tx)
deriving instance (FromJSON (Event tx), FromJSON (HeadState tx)) => FromJSON (LogicError tx)
data Outcome tx
= OnlyEffects {effects :: [Effect tx]}
| NewState {headState :: HeadState tx, effects :: [Effect tx]}
| Wait {reason :: WaitReason}
| Error {error :: LogicError tx}
deriving stock (Generic)
deriving instance (IsTx tx, IsChainState tx) => Eq (Outcome tx)
deriving instance (IsTx tx, IsChainState tx) => Show (Outcome tx)
deriving instance (IsTx tx, IsChainState tx) => ToJSON (Outcome tx)
deriving instance (IsTx tx, IsChainState tx) => FromJSON (Outcome tx)
instance (IsTx tx, Arbitrary (ChainStateType tx)) => Arbitrary (Outcome tx) where
arbitrary = genericArbitrary
data WaitReason
= WaitOnNotApplicableTx {validationError :: ValidationError}
| WaitOnSnapshotNumber {waitingFor :: SnapshotNumber}
| WaitOnSeenSnapshot
| WaitOnContestationDeadline
deriving stock (Generic, Eq, Show)
deriving anyclass (ToJSON, FromJSON)
instance Arbitrary WaitReason where
arbitrary = genericArbitrary
data Environment = Environment
{ party :: Party
-- ^ This is the p_i from the paper
, -- NOTE(MB): In the long run we would not want to keep the signing key in
-- memory, i.e. have an 'Effect' for signing or so.
signingKey :: SigningKey HydraKey
, otherParties :: [Party]
, contestationPeriod :: ContestationPeriod
}
-- * The Coordinated Head protocol
-- ** Opening the Head
-- | Client request to init the head. This leads to an init transaction on chain,
-- containing the head parameters.
--
-- __Transition__: 'IdleState' → 'IdleState'
onIdleClientInit ::
Environment ->
IdleState tx ->
Outcome tx
onIdleClientInit env st =
OnlyEffects [OnChainEffect{chainState, postChainTx = InitTx parameters}]
where
parameters =
HeadParameters
{ contestationPeriod
, parties = party : otherParties
}
Environment{party, otherParties, contestationPeriod} = env
IdleState{chainState} = st
-- | Observe an init transaction, initialize parameters in an 'InitialState' and
-- notify clients that they can now commit.
--
-- __Transition__: 'IdleState' → 'InitialState'
onIdleChainInitTx ::
IdleState tx ->
-- | New chain state.
ChainStateType tx ->
[Party] ->
ContestationPeriod ->
HeadId ->
Outcome tx
onIdleChainInitTx idleState newChainState parties contestationPeriod headId =
NewState
( Initial
InitialState
{ parameters = HeadParameters{contestationPeriod, parties}
, pendingCommits = Set.fromList parties
, committed = mempty
, previousRecoverableState = Idle idleState
, chainState = newChainState
, headId
}
)
[ClientEffect $ HeadIsInitializing headId (fromList parties)]
-- | Client request to commit a UTxO entry to the head. Provided the client
-- hasn't committed yet, this leads to a commit transaction on-chain containing
-- that UTxO entry.
--
-- __Transition__: 'InitialState' → 'InitialState'
onInitialClientCommit ::
Environment ->
InitialState tx ->
ClientInput tx ->
Outcome tx
onInitialClientCommit env st clientInput =
case clientInput of
(Commit utxo)
-- REVIEW: Is 'canCommit' something we want to handle here or have the OCV
-- deal with it?
| canCommit -> OnlyEffects [OnChainEffect{chainState, postChainTx = CommitTx party utxo}]
_ -> OnlyEffects [ClientEffect $ CommandFailed clientInput]
where
canCommit = party `Set.member` pendingCommits
InitialState{pendingCommits, chainState} = st
Environment{party} = 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 ->
Outcome tx
onInitialChainCommitTx st newChainState pt utxo =
NewState newState $
notifyClient
: [postCollectCom | canCollectCom]
where
newState =
Initial
InitialState
{ parameters
, pendingCommits = remainingParties
, committed = newCommitted
, previousRecoverableState = Initial st
, chainState = newChainState
, headId
}
newCommitted = Map.insert pt utxo committed
notifyClient = ClientEffect $ Committed headId pt utxo
postCollectCom =
OnChainEffect
{ chainState = newChainState
, postChainTx = CollectComTx $ fold newCommitted
}
canCollectCom = null remainingParties
remainingParties = Set.delete pt pendingCommits
InitialState{parameters, 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 =
OnlyEffects [OnChainEffect{chainState, postChainTx = AbortTx{utxo = fold committed}}]
where
InitialState{chainState, 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 =
NewState
(Idle IdleState{chainState = newChainState})
[ClientEffect $ 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 ::
(Monoid (UTxOType tx)) =>
InitialState tx ->
-- | New chain state
ChainStateType tx ->
Outcome tx
onInitialChainCollectTx st newChainState =
NewState
( Open
OpenState
{ parameters
, coordinatedHeadState =
CoordinatedHeadState u0 mempty initialSnapshot NoSeenSnapshot
, previousRecoverableState = Initial st
, chainState = newChainState
, headId
}
)
[ClientEffect $ HeadIsOpen{headId, utxo = u0}]
where
u0 = fold committed
initialSnapshot = InitialSnapshot u0
-- 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{parameters, committed, headId} = st
-- ** Off-chain protocol
-- | Client request to ingest a new transaction into the head.
--
-- __Transition__: 'OpenState' → 'OpenState'
onOpenClientNewTx ::
Environment ->
-- | The transaction to be submitted to the head.
tx ->
Outcome tx
onOpenClientNewTx env tx =
OnlyEffects [NetworkEffect $ ReqTx party tx]
where
Environment{party} = env
-- | 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 ::
Environment ->
Ledger tx ->
OpenState tx ->
TTL ->
-- | The transaction to be submitted to the head.
tx ->
Outcome tx
onOpenNetworkReqTx env ledger st ttl tx =
-- Spec: wait L̂ ◦ tx ̸= ⊥ combined with L̂ ← L̂ ◦ tx
case applyTransactions seenUTxO [tx] of
Left (_, err)
| ttl <= 0 ->
OnlyEffects [ClientEffect $ TxInvalid headId seenUTxO tx err]
| otherwise -> Wait $ WaitOnNotApplicableTx err
Right utxo' ->
NewState
( Open
st
{ coordinatedHeadState =
coordinatedHeadState
{ seenTxs = seenTxs <> [tx]
, seenUTxO = utxo'
}
}
)
[ClientEffect $ TxValid headId tx]
& emitSnapshot env
where
Ledger{applyTransactions} = ledger
CoordinatedHeadState{seenTxs, seenUTxO} = coordinatedHeadState
OpenState{coordinatedHeadState, headId} = st
-- | 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.
[tx] ->
Outcome tx
onOpenNetworkReqSn env ledger st otherParty sn requestedTxs =
-- 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 U̅ ◦ T /= ⊥ combined with Û ← Ū̅ ◦ T
waitApplyTxs $ \u -> do
-- NOTE: confSn == seenSn == sn here
let nextSnapshot = Snapshot (confSn + 1) u requestedTxs
-- Spec: σᵢ
let snapshotSignature = sign signingKey nextSnapshot
-- Spec: T̂ ← {tx | ∀tx ∈ T̂ , Û ◦ tx ≠ ⊥} and L̂ ← Û ◦ T̂
let (seenTxs', seenUTxO') = pruneTransactions u
NewState
( Open
st
{ coordinatedHeadState =
coordinatedHeadState
{ seenSnapshot = SeenSnapshot nextSnapshot mempty
, seenTxs = seenTxs'
, seenUTxO = seenUTxO'
}
}
)
[NetworkEffect $ AckSn party snapshotSignature sn]
where
requireReqSn continue =
if sn == seenSn + 1 && isLeader parameters otherParty sn
then continue
else Error $ RequireFailed "requireReqSn"
waitNoSnapshotInFlight continue =
if confSn == seenSn
then continue
else Wait $ WaitOnSnapshotNumber seenSn
-- XXX: Wait for these transactions to apply is actually not needed. They must
-- be applicable already. This is a bit of a precursor for only submitting
-- transaction ids/hashes .. which we really should do.
waitApplyTxs cont =
case applyTransactions ledger confirmedUTxO requestedTxs of
Left (_, err) ->
Wait $ WaitOnNotApplicableTx err
Right u -> cont u
pruneTransactions utxo = do
foldr go ([], utxo) seenTxs
where
go tx (txs, u) =
case applyTransactions ledger 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, seenTxs} = coordinatedHeadState
OpenState{parameters, coordinatedHeadState} = st
Environment{party, 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 env 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
let sigs' = Map.insert otherParty snapshotSignature sigs
ifAllMembersHaveSigned snapshot sigs' $ do
-- Spec: σ̃ ← MS-ASig(k_H, ̂Σ̂)
let multisig = aggregateInOrder sigs' parties
requireVerifiedMultisignature multisig snapshot $ do
NewState
( onlyUpdateCoordinatedHeadState $
coordinatedHeadState
{ confirmedSnapshot =
ConfirmedSnapshot
{ snapshot
, signatures = multisig
}
, seenSnapshot = LastSeenSnapshot (number snapshot)
}
)
[ClientEffect $ SnapshotConfirmed headId snapshot multisig]
& emitSnapshot env
where
seenSn = seenSnapshotNumber seenSnapshot
requireValidAckSn continue =
if sn `elem` [seenSn, seenSn + 1]
then continue
else Error $ RequireFailed "requireValidAckSn"
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 "requireNotSignedYet"
ifAllMembersHaveSigned snapshot sigs' cont =
if Map.keysSet sigs' == Set.fromList parties
then cont
else
NewState
( onlyUpdateCoordinatedHeadState $
coordinatedHeadState
{ seenSnapshot = SeenSnapshot snapshot sigs'
}
)
[]
requireVerifiedMultisignature multisig msg cont =
if verifyMultiSignature (vkey <$> parties) multisig msg
then cont
else Error $ RequireFailed "requireVerifiedMultisignature"
-- XXX: Data structures become unwieldy -> helper functions or lenses
onlyUpdateCoordinatedHeadState chs' =
Open openState{coordinatedHeadState = chs'}
CoordinatedHeadState{seenSnapshot} = coordinatedHeadState
OpenState
{ parameters = HeadParameters{parties}
, coordinatedHeadState
, headId
} = openState
-- ** 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 =
OnlyEffects [OnChainEffect{chainState, postChainTx = CloseTx confirmedSnapshot}]
where
CoordinatedHeadState{confirmedSnapshot} = coordinatedHeadState
OpenState{chainState, 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 =
NewState closedState $
notifyClient
: [ OnChainEffect
{ -- REVIEW: Was using "old" chainState before
chainState = newChainState
, postChainTx = ContestTx{confirmedSnapshot}
}
| doContest
]
where
doContest =
number (getSnapshot confirmedSnapshot) > closedSnapshotNumber
closedState =
Closed
ClosedState
{ parameters
, confirmedSnapshot
, contestationDeadline
, readyToFanoutSent = False
, previousRecoverableState = Open openState
, chainState = newChainState
, headId
}
notifyClient =
ClientEffect $
HeadIsClosed
{ headId
, snapshotNumber = closedSnapshotNumber
, contestationDeadline
}
CoordinatedHeadState{confirmedSnapshot} = coordinatedHeadState
OpenState{parameters, 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) =
OnlyEffects
[ ClientEffect HeadIsContested{snapshotNumber, headId}
, OnChainEffect{chainState, 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!
OnlyEffects [ClientEffect HeadIsContested{snapshotNumber, headId}]
| otherwise =
OnlyEffects [ClientEffect HeadIsContested{snapshotNumber, headId}]
where
ClosedState{chainState, 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 =
OnlyEffects
[ OnChainEffect
{ chainState
, postChainTx =
FanoutTx{utxo, contestationDeadline}
}
]
where
Snapshot{utxo} = getSnapshot confirmedSnapshot
ClosedState{chainState, 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 =
NewState
(Idle IdleState{chainState = newChainState})
[ ClientEffect $ HeadIsFinalized{headId, utxo}
]
where
Snapshot{utxo} = getSnapshot confirmedSnapshot
ClosedState{confirmedSnapshot, headId} = closedState
-- | Observe a chain rollback and transition to corresponding previous
-- recoverable state.
--
-- __Transition__: 'OpenState' → 'HeadState'
onCurrentChainRollback ::
(IsChainState tx) =>
HeadState tx ->
ChainSlot ->
Outcome tx
onCurrentChainRollback currentState slot =
NewState (rollback slot currentState) [ClientEffect RolledBack]
where
rollback rollbackSlot hs
| chainStateSlot (getChainState hs) <= rollbackSlot = hs
| otherwise =
case hs of
Idle{} -> hs
Initial InitialState{previousRecoverableState} ->
rollback rollbackSlot previousRecoverableState
Open OpenState{previousRecoverableState} ->
rollback rollbackSlot previousRecoverableState
Closed ClosedState{previousRecoverableState} ->
rollback rollbackSlot previousRecoverableState
-- | The "pure core" of the Hydra node, which handles the 'Event' against a
-- current 'HeadState'. Resulting new 'HeadState's are retained and 'Effect'
-- outcomes handled by the "Hydra.Node".
update ::
(IsTx tx, IsChainState tx) =>
Environment ->
Ledger tx ->
HeadState tx ->
Event tx ->
Outcome tx
update env ledger st ev = case (st, ev) of
(Idle idleState, ClientEvent Init) ->
onIdleClientInit env idleState
(Idle idleState, OnChainEvent Observation{observedTx = OnInitTx{headId, contestationPeriod, parties}, newChainState}) ->