-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathHeadLogic.hs
1698 lines (1588 loc) · 60.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
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 #-}
{-# OPTIONS_GHC -Wno-ambiguous-fields #-}
-- | 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,
) where
import Hydra.Prelude
import Data.List (elemIndex)
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 (DecommitInvalidReason (..))
import Hydra.API.ServerOutput qualified as ServerOutput
import Hydra.Chain (
ChainEvent (..),
ChainStateHistory,
OnChainTx (..),
PostChainTx (..),
pushNewState,
rollbackHistory,
)
import Hydra.Chain.ChainState (ChainSlot, IsChainState (..))
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.State (
ClosedState (..),
Committed,
CoordinatedHeadState (..),
HeadState (..),
IdleState (IdleState, chainState),
InitialState (..),
OpenState (..),
PendingCommits,
SeenSnapshot (..),
seenSnapshotNumber,
setChainState,
)
import Hydra.Ledger (
Ledger (..),
applyTransactions,
outputsOfTx,
)
import Hydra.Network.Message (Connectivity (..), HydraVersionedProtocolNumber (..), KnownHydraVersions (..), Message (..), NetworkEvent (..))
import Hydra.Tx (
HeadId,
HeadSeed,
IsTx (..),
TxIdType,
UTxOType,
mkHeadParameters,
txId,
utxoFromTx,
withoutUTxO,
)
import Hydra.Tx.Crypto (
Signature,
Verified (..),
aggregateInOrder,
sign,
verifyMultiSignature,
)
import Hydra.Tx.Environment (Environment (..))
import Hydra.Tx.HeadParameters (HeadParameters (..))
import Hydra.Tx.OnChainId (OnChainId)
import Hydra.Tx.Party (Party (vkey))
import Hydra.Tx.Snapshot (ConfirmedSnapshot (..), Snapshot (..), SnapshotNumber, SnapshotVersion, getSnapshot)
defaultTTL :: TTL
defaultTTL = 5
onConnectionEvent :: Connectivity -> Outcome tx
onConnectionEvent = \case
Connected{nodeId} ->
causes [ClientEffect (ServerOutput.PeerConnected nodeId)]
Disconnected{nodeId} ->
causes [ClientEffect (ServerOutput.PeerDisconnected nodeId)]
HandshakeFailure{remoteHost, ourVersion, theirVersions} ->
causes
[ ClientEffect
( ServerOutput.PeerHandshakeFailure
{ remoteHost
, ourVersion = getVersion ourVersion
, theirVersions = getKnownVersions theirVersions
}
)
]
where
getVersion MkHydraVersionedProtocolNumber{hydraVersionedProtocolNumber} = hydraVersionedProtocolNumber
getKnownVersions = \case
NoKnownHydraVersions -> []
KnownHydraVersions{fromKnownHydraVersions} -> getVersion <$> fromKnownHydraVersions
-- * 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 = mkHeadParameters env
Environment{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] ->
Outcome tx
onIdleChainInitTx env newChainState headId headSeed headParameters participants
| configuredParties == initializedParties
&& party `member` initializedParties
&& configuredContestationPeriod == contestationPeriod
&& Set.fromList configuredParticipants == Set.fromList participants =
newState
HeadInitialized
{ parameters = headParameters
, chainState = newChainState
, headId
, headSeed
}
<> 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 ->
Outcome tx
onInitialChainCommitTx st newChainState pt utxo =
newState CommittedUTxO{party = pt, committedUTxO = utxo, chainState = newChainState}
<> 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 ->
Outcome tx
onInitialChainAbortTx newChainState committed headId =
newState HeadAborted{chainState = newChainState}
<> 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 ->
Outcome tx
onInitialChainCollectTx st newChainState =
-- Spec: 𝑈₀ ← ⋃ⁿⱼ₌₁ 𝑈ⱼ
let u0 = fold committed
in -- Spec: L̂ ← 𝑈₀
-- ̅S ← snObj(0, 0, 𝑈₀, ∅, ∅)
-- v , ŝ ← 0
-- T̂ ← ∅
-- txω ← ⊥
-- 𝑈𝛼 ← ∅
newState HeadOpened{chainState = newChainState, initialUTxO = u0}
<> cause (ClientEffect $ ServerOutput.HeadIsOpen{headId, utxo = u0})
where
-- 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 ->
Outcome tx
onOpenNetworkReqTx env ledger st ttl tx =
-- Keep track of transactions by-id
(newState TransactionReceived{tx} <>) $
-- Spec: wait L̂ ◦ tx ≠ ⊥
waitApplyTx $ \newLocalUTxO ->
(cause (ClientEffect $ ServerOutput.TxValid headId (txId tx) tx) <>) $
-- Spec: T̂ ← T̂ ⋃ {tx}
-- L̂ ← L̂ ◦ tx
newState TransactionAppliedToLocalUTxO{tx, newLocalUTxO}
-- Spec: if ŝ = ̅S.s ∧ leader(̅S.s + 1) = i
-- multicast (reqSn, v, ̅S.s + 1, T̂ , 𝑈𝛼, txω )
& maybeRequestSnapshot (confirmedSn + 1)
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
maybeRequestSnapshot nextSn outcome =
if not snapshotInFlight && isLeader parameters party nextSn
then
outcome
-- 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}
<> cause (NetworkEffect $ ReqSn version nextSn (txId <$> localTxs') decommitTx pendingDeposit)
else outcome
Environment{party} = env
Ledger{applyTransactions} = ledger
pendingDeposit =
case Map.toList pendingDeposits of
[] -> Nothing
(_, depositUTxO) : _ -> Just depositUTxO
CoordinatedHeadState{localTxs, localUTxO, confirmedSnapshot, seenSnapshot, decommitTx, version, pendingDeposits} = coordinatedHeadState
Snapshot{number = confirmedSn} = getSnapshot confirmedSnapshot
OpenState{coordinatedHeadState, headId, currentSlot, parameters} = st
snapshotInFlight = case seenSnapshot of
NoSeenSnapshot -> False
LastSeenSnapshot{} -> False
RequestedSnapshot{} -> True
SeenSnapshot{} -> True
-- NOTE: Order of transactions is important here. See also
-- 'pruneTransactions'.
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 version.
SnapshotVersion ->
-- | Requested snapshot number.
SnapshotNumber ->
-- | List of transactions to snapshot.
[TxIdType tx] ->
-- | Optional decommit transaction of removing funds from the head.
Maybe tx ->
Maybe (UTxOType tx) ->
Outcome tx
onOpenNetworkReqSn env ledger st otherParty sv sn requestedTxIds mDecommitTx mIncrementUTxO =
-- Spec: require s = ŝ + 1 ∧ leader(s) = j
requireReqSn $
-- Spec: wait ŝ = ̅S.s
waitNoSnapshotInFlight $
-- Spec: wait v = v̂
waitOnSnapshotVersion $
-- Spec: require tx𝜔 = ⊥ ∨ 𝑈𝛼 = ∅
requireApplicableDecommitTx $ \(activeUTxOAfterDecommit, mUtxoToDecommit) ->
requireApplicableCommit activeUTxOAfterDecommit $ \(activeUTxO, mUtxoToCommit) ->
-- Resolve transactions by-id
waitResolvableTxs $ \requestedTxs -> do
-- Spec: require 𝑈_active ◦ Treq ≠ ⊥
-- 𝑈 ← 𝑈_active ◦ Treq
requireApplyTxs activeUTxO requestedTxs $ \u -> do
let snapshotUTxO = u `withoutUTxO` fromMaybe mempty mUtxoToCommit
-- Spec: ŝ ← ̅S.s + 1
-- NOTE: confSn == seenSn == sn here
let nextSnapshot =
Snapshot
{ headId
, version = version
, number = sn
, confirmed = requestedTxs
, utxo = snapshotUTxO
, utxoToCommit = mUtxoToCommit
, utxoToDecommit = mUtxoToDecommit
}
-- Spec: 𝜂 ← combine(𝑈)
-- 𝜂𝛼 ← combine(𝑈𝛼)
-- 𝜂𝜔 ← combine(outputs(tx𝜔 ))
-- σᵢ ← MS-Sign(kₕˢⁱᵍ, (cid‖v‖ŝ‖η‖η𝛼‖ηω))
let snapshotSignature = sign signingKey nextSnapshot
-- Spec: multicast (ackSn, ŝ, σᵢ)
(cause (NetworkEffect $ AckSn snapshotSignature sn) <>) $ do
-- Spec: ̂Σ ← ∅
-- L̂ ← 𝑈
-- 𝑋 ← T
-- T̂ ← ∅
-- for tx ∈ 𝑋 : L̂ ◦ tx ≠ ⊥
-- T̂ ← T̂ ⋃ {tx}
-- L̂ ← L̂ ◦ tx
let (newLocalTxs, newLocalUTxO) = pruneTransactions u
newState
SnapshotRequested
{ snapshot = nextSnapshot
, requestedTxIds
, newLocalUTxO
, newLocalTxs
}
where
requireReqSn continue
| sv /= version =
Error $ RequireFailed $ ReqSvNumberInvalid{requestedSv = sv, lastSeenSv = version}
| 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
waitOnSnapshotVersion continue
| version == sv =
continue
| otherwise =
wait $ WaitOnSnapshotVersion sv
waitResolvableTxs continue =
case toList (fromList requestedTxIds \\ Map.keysSet allTxs) of
[] -> continue $ mapMaybe (`Map.lookup` allTxs) requestedTxIds
unseen -> wait $ WaitOnTxs unseen
requireApplicableCommit activeUTxOAfterDecommit cont =
case mIncrementUTxO of
Nothing -> cont (activeUTxOAfterDecommit, Nothing)
Just utxo ->
-- NOTE: this makes the commits sequential in a sense that you can't
-- commit unless the previous commit is settled.
if sv == confVersion && isJust confUTxOToCommit
then
if confUTxOToCommit == Just utxo
then cont (activeUTxOAfterDecommit <> fromMaybe mempty confUTxOToCommit, confUTxOToCommit)
else Error $ RequireFailed ReqSnCommitNotSettled
else do
let activeUTxOAfterCommit = activeUTxOAfterDecommit <> utxo
cont (activeUTxOAfterCommit, Just utxo)
requireApplicableDecommitTx cont =
case mDecommitTx of
Nothing -> cont (confirmedUTxO, Nothing)
Just decommitTx ->
-- Spec:
-- require tx𝜔 = ⊥ ∨ 𝑈𝛼 = ∅
-- require 𝑣 = 𝑣 ̂ ∧ 𝑠 = 𝑠 ̂ + 1 ∧ leader(𝑠) = 𝑗
-- wait 𝑠 ̂ = 𝒮.𝑠
if sv == confVersion && isJust confUTxOToDecommit
then
if confUTxOToDecommit == Just (utxoFromTx decommitTx)
then cont (confirmedUTxO, confUTxOToDecommit)
else Error $ RequireFailed ReqSnDecommitNotSettled
else case applyTransactions ledger currentSlot confirmedUTxO [decommitTx] of
Left (_, err) ->
Error $ RequireFailed $ SnapshotDoesNotApply sn (txId decommitTx) err
Right newConfirmedUTxO -> do
let utxoToDecommit = utxoFromTx decommitTx
let activeUTxO = newConfirmedUTxO `withoutUTxO` utxoToDecommit
cont (activeUTxO, Just utxoToDecommit)
-- 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 utxo requestedTxs cont =
case applyTransactions ledger currentSlot utxo requestedTxs of
Left (tx, err) ->
Error $ RequireFailed $ SnapshotDoesNotApply sn (txId tx) err
Right u -> cont u
pruneTransactions utxo = do
-- NOTE: Using foldl' is important to apply transacations in the correct
-- order. That is, left-associative as new transactions are first validated
-- and then appended to `localTxs` (when aggregating
-- 'TransactionAppliedToLocalUTxO').
foldl' go ([], utxo) localTxs
where
go (txs, u) tx =
-- 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
Snapshot{version = confVersion} = getSnapshot confirmedSnapshot
confUTxOToCommit = case confirmedSnapshot of
InitialSnapshot{} -> Nothing
ConfirmedSnapshot{snapshot = Snapshot{utxoToCommit}} -> utxoToCommit
confUTxOToDecommit = case confirmedSnapshot of
InitialSnapshot{} -> Nothing
ConfirmedSnapshot{snapshot = Snapshot{utxoToDecommit}} -> utxoToDecommit
seenSn = seenSnapshotNumber seenSnapshot
confirmedUTxO = case confirmedSnapshot of
InitialSnapshot{initialUTxO} -> initialUTxO
ConfirmedSnapshot{snapshot = Snapshot{utxo, utxoToCommit}} -> utxo <> fromMaybe mempty utxoToCommit
CoordinatedHeadState{confirmedSnapshot, seenSnapshot, allTxs, localTxs, version} = 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 ->
Outcome tx
onOpenNetworkAckSn Environment{party} openState otherParty snapshotSignature sn =
-- Spec: require s ∈ {ŝ, ŝ + 1}
requireValidAckSn $ do
-- Spec: wait ŝ = s
waitOnSeenSnapshot $ \snapshot sigs -> do
-- Spec: require (j,⋅) ∉ ̂Σ
requireNotSignedYet sigs $ do
-- Spec: ̂Σ[j] ← σⱼ
(newState PartySignedSnapshot{snapshot, party = otherParty, signature = snapshotSignature} <>) $
-- if ∀k ∈ [1..n] : (k,·) ∈ ̂Σ
ifAllMembersHaveSigned snapshot sigs $ \sigs' -> do
-- Spec: σ̃ ← MS-ASig(kₕˢᵉᵗᵘᵖ,̂Σ)
let multisig = aggregateInOrder sigs' parties
-- Spec: η ← combine(𝑈ˆ)
-- 𝜂𝛼 ← combine(𝑈𝛼)
-- 𝑈𝜔 ← outputs(tx𝜔 )
-- ηω ← combine(𝑈𝜔)
-- require MS-Verify(k ̃H, (cid‖v̂‖ŝ‖η‖η𝛼‖ηω), σ̃)
requireVerifiedMultisignature multisig snapshot $
do
-- Spec: ̅S ← snObj(v̂, ŝ, Û, T̂, 𝑈𝛼, 𝑈𝜔)
-- ̅S.σ ← ̃σ
newState SnapshotConfirmed{snapshot, signatures = multisig}
<> cause (ClientEffect $ ServerOutput.SnapshotConfirmed headId snapshot multisig)
-- Spec: if η𝛼 ≠ ⊥
-- postTx (increment, v̂, ŝ, η, η𝛼, ηω)
& maybePostIncrementTx snapshot multisig
-- Spec: if txω ≠ ⊥
-- postTx (decrement, v̂, ŝ, η, η𝛼, ηω)
& maybePostDecrementTx snapshot multisig
-- Spec: if leader(s + 1) = i ∧ T̂ ≠ ∅
-- multicast (reqSn, v, ̅S.s + 1, T̂, 𝑈𝛼, txω)
& maybeRequestNextSnapshot (number snapshot + 1)
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
}
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}
maybeRequestNextSnapshot nextSn outcome =
if isLeader parameters party nextSn && not (null localTxs)
then
outcome
<> newState SnapshotRequestDecided{snapshotNumber = nextSn}
<> cause (NetworkEffect $ ReqSn version nextSn (txId <$> localTxs) decommitTx pendingDeposit)
else outcome
maybePostIncrementTx snapshot@Snapshot{utxoToCommit} signatures outcome =
case find (\(_, depositUTxO) -> Just depositUTxO == utxoToCommit) (Map.assocs pendingDeposits) of
Just (depositTxId, depositUTxO) ->
outcome
<> causes
[ ClientEffect $
ServerOutput.CommitApproved
{ headId
, utxoToCommit = depositUTxO
}
, OnChainEffect
{ postChainTx =
IncrementTx
{ headId
, headParameters = parameters
, incrementingSnapshot = ConfirmedSnapshot{snapshot, signatures}
, depositTxId
}
}
]
_ ->
cause
( ClientEffect $
ServerOutput.CommitIgnored
{ headId
, depositUTxO = Map.elems pendingDeposits
, snapshotUTxO = utxoToCommit
}
)
<> outcome
maybePostDecrementTx snapshot@Snapshot{utxoToDecommit} signatures outcome =
case (decommitTx, utxoToDecommit) of
(Just tx, Just utxo) ->
outcome
<> causes
[ ClientEffect $
ServerOutput.DecommitApproved
{ headId
, decommitTxId = txId tx
, utxoToDecommit = utxo
}
, OnChainEffect
{ postChainTx =
DecrementTx
{ headId
, headParameters = parameters
, decrementingSnapshot = ConfirmedSnapshot{snapshot, signatures}
}
}
]
_ -> outcome
vkeys = vkey <$> parties
OpenState
{ parameters = parameters@HeadParameters{parties}
, coordinatedHeadState
, headId
} = openState
pendingDeposit =
case Map.toList pendingDeposits of
[] -> Nothing
(_, depositUTxO) : _ -> Just depositUTxO
CoordinatedHeadState{seenSnapshot, localTxs, decommitTx, pendingDeposits, version} = coordinatedHeadState
-- | Client request to recover deposited UTxO.
--
-- __Transition__: 'OpenState' → 'OpenState'
onOpenClientRecover ::
IsTx tx =>
HeadId ->
ChainSlot ->
CoordinatedHeadState tx ->
TxIdType tx ->
Outcome tx
onOpenClientRecover headId currentSlot coordinatedHeadState recoverTxId =
case Map.lookup recoverTxId pendingDeposits of
Nothing ->
Error $ RequireFailed RecoverNotMatchingDeposit
Just _ ->
causes
[ OnChainEffect
{ postChainTx =
RecoverTx
{ headId
, recoverTxId = recoverTxId
, deadline = currentSlot
}
}
]
where
CoordinatedHeadState{pendingDeposits} = coordinatedHeadState
-- | Client request to decommit UTxO from the head.
--
-- Only possible if there is no decommit _in flight_ and if the tx applies
-- cleanly to the local ledger state.
--
-- __Transition__: 'OpenState' → 'OpenState'
onOpenClientDecommit ::
IsTx tx =>
HeadId ->
Ledger tx ->
ChainSlot ->
CoordinatedHeadState tx ->
-- | Decommit transaction.
tx ->
Outcome tx
onOpenClientDecommit headId ledger currentSlot coordinatedHeadState decommitTx =
checkNoDecommitInFlight $
checkValidDecommitTx $
cause (NetworkEffect ReqDec{transaction = decommitTx})
where
checkNoDecommitInFlight continue =
case mExistingDecommitTx of
Just existingDecommitTx ->
cause
( ClientEffect
ServerOutput.DecommitInvalid
{ headId
, decommitTx
, decommitInvalidReason =
ServerOutput.DecommitAlreadyInFlight
{ otherDecommitTxId = txId existingDecommitTx
}
}
)
Nothing -> continue
checkValidDecommitTx cont =
case applyTransactions ledger currentSlot localUTxO [decommitTx] of
Left (_, err) ->
cause
( ClientEffect
ServerOutput.DecommitInvalid
{ headId
, decommitTx
, decommitInvalidReason =
ServerOutput.DecommitTxInvalid
{ localUTxO
, validationError = err
}
}
)
Right _ -> cont
CoordinatedHeadState{decommitTx = mExistingDecommitTx, localUTxO} = coordinatedHeadState
-- | Process the request 'ReqDec' to decommit something from the Open head.
--
-- __Transition__: 'OpenState' → 'OpenState'
--
-- When node receives 'ReqDec' network message it should:
-- - Check there is no decommit in flight:
-- - Alter it's state to record what is to be decommitted
-- - Issue a server output 'DecommitRequested' with the relevant utxo
-- - Issue a 'ReqSn' since all parties need to agree in order for decommit to
-- be taken out of a Head.
-- - Check if we are the leader
onOpenNetworkReqDec ::
IsTx tx =>
Environment ->
Ledger tx ->
TTL ->
OpenState tx ->
tx ->
Outcome tx
onOpenNetworkReqDec env ledger ttl openState decommitTx =
-- Spec: wait 𝑈𝛼 = ∅ ^ txω =⊥ ∧ L̂ ◦ tx ≠ ⊥
waitOnApplicableDecommit $ \newLocalUTxO -> do
-- Spec: L̂ ← L̂ ◦ tx \ outputs(tx)
let decommitUTxO = utxoFromTx decommitTx
activeUTxO = newLocalUTxO `withoutUTxO` decommitUTxO
-- Spec: txω ← tx
newState DecommitRecorded{decommitTx, newLocalUTxO = activeUTxO}
<> cause
( ClientEffect $
ServerOutput.DecommitRequested
{ headId
, decommitTx = decommitTx
, utxoToDecommit = decommitUTxO
}
)
-- Spec: if ŝ = ̅S.s ∧ leader(̅S.s + 1) = i
-- multicast (reqSn, v, ̅S.s + 1, T̂ , 𝑈𝛼, txω )
<> maybeRequestSnapshot
where
waitOnApplicableDecommit cont =
case mExistingDecommitTx of
Nothing ->
case applyTransactions currentSlot localUTxO [decommitTx] of
Right utxo' -> cont utxo'
Left (_, validationError)
| ttl > 0 ->
wait $
WaitOnNotApplicableDecommitTx
ServerOutput.DecommitTxInvalid{localUTxO, validationError}
| otherwise ->
cause . ClientEffect $
ServerOutput.DecommitInvalid
{ headId
, decommitTx
, decommitInvalidReason =
ServerOutput.DecommitTxInvalid{localUTxO, validationError}
}
Just existingDecommitTx
| ttl > 0 ->
wait $
WaitOnNotApplicableDecommitTx
DecommitAlreadyInFlight{otherDecommitTxId = txId existingDecommitTx}
| otherwise ->
cause . ClientEffect $
ServerOutput.DecommitInvalid
{ headId
, decommitTx
, decommitInvalidReason =
DecommitAlreadyInFlight{otherDecommitTxId = txId existingDecommitTx}
}
maybeRequestSnapshot =
if not snapshotInFlight && isLeader parameters party nextSn
then cause (NetworkEffect (ReqSn version nextSn (txId <$> localTxs) (Just decommitTx) Nothing))
else noop
Environment{party} = env
Ledger{applyTransactions} = ledger
Snapshot{number} = getSnapshot confirmedSnapshot
nextSn = number + 1
snapshotInFlight = case seenSnapshot of
NoSeenSnapshot -> False
LastSeenSnapshot{} -> False
RequestedSnapshot{} -> True
SeenSnapshot{} -> True
CoordinatedHeadState
{ decommitTx = mExistingDecommitTx
, confirmedSnapshot
, localTxs
, localUTxO
, version
, seenSnapshot
} = coordinatedHeadState
OpenState
{ headId
, parameters
, coordinatedHeadState
, currentSlot
} = openState
onOpenChainDepositTx ::
IsTx tx =>
HeadId ->
Environment ->
OpenState tx ->
-- | Deposited UTxO
UTxOType tx ->
-- | Deposit 'TxId'
TxIdType tx ->
-- | Deposit deadline
UTCTime ->
Outcome tx
onOpenChainDepositTx headId env st deposited depositTxId deadline =
-- TODO: We should check for deadline and only request snapshots that have deadline further in the future so
-- we don't end up with a snapshot that is already outdated.
waitOnUnresolvedDecommit $
newState CommitRecorded{pendingDeposits = Map.singleton depositTxId deposited, newLocalUTxO = localUTxO <> deposited}
<> cause (ClientEffect $ ServerOutput.CommitRecorded{headId, utxoToCommit = deposited, pendingDeposit = depositTxId, deadline})
<> if not snapshotInFlight && isLeader parameters party nextSn
then
cause (NetworkEffect $ ReqSn version nextSn (txId <$> localTxs) Nothing (Just deposited))
else noop
where
waitOnUnresolvedDecommit cont =
case decommitTx of
Nothing -> cont
Just tx -> wait $ WaitOnUnresolvedDecommit{decommitTx = tx}
nextSn = confirmedSn + 1
Environment{party} = env
CoordinatedHeadState{localTxs, confirmedSnapshot, seenSnapshot, version, decommitTx, localUTxO} = coordinatedHeadState
Snapshot{number = confirmedSn} = getSnapshot confirmedSnapshot
OpenState{coordinatedHeadState, parameters} = st
snapshotInFlight = case seenSnapshot of
NoSeenSnapshot -> False
LastSeenSnapshot{} -> False
RequestedSnapshot{} -> True
SeenSnapshot{} -> True
onOpenChainRecoverTx ::
IsTx tx =>
HeadId ->
OpenState tx ->
TxIdType tx ->
Outcome tx
onOpenChainRecoverTx headId st recoveredTxId =
case Map.lookup recoveredTxId pendingDeposits of
Nothing -> Error $ RequireFailed RecoverNotMatchingDeposit