-
Notifications
You must be signed in to change notification settings - Fork 85
/
Tx.hs
1200 lines (1064 loc) · 41.8 KB
/
Tx.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 AllowAmbiguousTypes #-}
{-# LANGUAGE DuplicateRecordFields #-}
-- | Smart constructors for creating Hydra protocol transactions to be used in
-- the 'Hydra.Chain.Direct' way of talking to the main-chain.
--
-- This module also encapsulates the transaction format used when talking to the
-- cardano-node, which is currently different from the 'Hydra.Ledger.Cardano',
-- thus we have not yet "reached" 'isomorphism'.
module Hydra.Chain.Direct.Tx where
import Hydra.Cardano.Api hiding (hashScript)
import Hydra.Prelude
import Cardano.Api.UTxO qualified as UTxO
import Cardano.Ledger.Alonzo.Scripts (ExUnits (..))
import Cardano.Ledger.Alonzo.TxAuxData (AlonzoTxAuxData (..), hashAlonzoTxAuxData)
import Cardano.Ledger.Api (
AlonzoPlutusPurpose (..),
AsIndex (..),
Data,
Redeemers (..),
auxDataHashTxBodyL,
auxDataTxL,
bodyTxL,
inputsTxBodyL,
mkAlonzoTxAuxData,
outputsTxBodyL,
rdmrsTxWitsL,
referenceInputsTxBodyL,
reqSignerHashesTxBodyL,
unRedeemers,
witsTxL,
)
import Cardano.Ledger.Api.Tx.In qualified as Ledger
import Cardano.Ledger.BaseTypes (StrictMaybe (..))
import Control.Lens ((.~), (<>~), (^.))
import Data.Aeson qualified as Aeson
import Data.ByteString qualified as BS
import Data.ByteString.Base16 qualified as Base16
import Data.Map qualified as Map
import Data.Sequence.Strict qualified as StrictSeq
import Data.Set qualified as Set
import Hydra.Cardano.Api.Network (networkIdToNetwork)
import Hydra.Cardano.Api.Prelude (toShelleyMetadata)
import Hydra.Chain (HeadParameters (..))
import Hydra.Chain.Direct.ScriptRegistry (ScriptRegistry (..))
import Hydra.Chain.Direct.TimeHandle (PointInTime)
import Hydra.ContestationPeriod (ContestationPeriod, fromChain, toChain)
import Hydra.Contract.Commit qualified as Commit
import Hydra.Contract.Head qualified as Head
import Hydra.Contract.HeadState qualified as Head
import Hydra.Contract.HeadTokens qualified as HeadTokens
import Hydra.Contract.Initial qualified as Initial
import Hydra.Contract.MintAction (MintAction (Burn, Mint))
import Hydra.Contract.Util (hydraHeadV1)
import Hydra.Crypto (MultiSignature, toPlutusSignatures)
import Hydra.Data.ContestationPeriod (addContestationPeriod)
import Hydra.Data.ContestationPeriod qualified as OnChain
import Hydra.Data.Party qualified as OnChain
import Hydra.HeadId (HeadId (..), HeadSeed (..))
import Hydra.Ledger (IsTx (hashUTxO))
import Hydra.Ledger.Cardano (addReferenceInputs)
import Hydra.Ledger.Cardano.Builder (
addExtraRequiredSigners,
addInputs,
addOutputs,
addVkInputs,
burnTokens,
emptyTxBody,
mintTokens,
setValidityLowerBound,
setValidityUpperBound,
unsafeBuildTransaction,
)
import Hydra.OnChainId (OnChainId (..))
import Hydra.Party (Party, partyFromChain, partyToChain)
import Hydra.Plutus.Extras (posixFromUTCTime, posixToUTCTime)
import Hydra.Plutus.Orphans ()
import Hydra.Snapshot (Snapshot (..), SnapshotNumber, fromChainSnapshot)
import PlutusLedgerApi.V2 (CurrencySymbol (CurrencySymbol), fromBuiltin, getPubKeyHash, toBuiltin)
import PlutusLedgerApi.V2 qualified as Plutus
import Test.QuickCheck (vectorOf)
-- | Needed on-chain data to create Head transactions.
type UTxOWithScript = (TxIn, TxOut CtxUTxO, HashableScriptData)
newtype UTxOHash = UTxOHash ByteString
deriving stock (Eq, Show, Generic)
instance ToJSON UTxOHash where
toJSON (UTxOHash bytes) =
Aeson.String . decodeUtf8 $ Base16.encode bytes
instance FromJSON UTxOHash where
parseJSON = Aeson.withText "UTxOHash" $ \cborText ->
case Base16.decode $ encodeUtf8 cborText of
Left e -> fail e
Right bs -> pure $ UTxOHash bs
instance Arbitrary UTxOHash where
arbitrary = UTxOHash . BS.pack <$> vectorOf 32 arbitrary
-- | Representation of the Head output after an Init transaction.
data InitialThreadOutput = InitialThreadOutput
{ initialThreadUTxO :: (TxIn, TxOut CtxUTxO)
, initialContestationPeriod :: OnChain.ContestationPeriod
, initialParties :: [OnChain.Party]
}
deriving stock (Eq, Show, Generic)
deriving anyclass (ToJSON, FromJSON)
instance Arbitrary InitialThreadOutput where
arbitrary = genericArbitrary
shrink = genericShrink
-- | Representation of the Head output after a CollectCom transaction.
data OpenThreadOutput = OpenThreadOutput
{ openThreadUTxO :: (TxIn, TxOut CtxUTxO)
, openContestationPeriod :: OnChain.ContestationPeriod
, openParties :: [OnChain.Party]
}
deriving stock (Eq, Show, Generic)
deriving anyclass (ToJSON, FromJSON)
instance Arbitrary OpenThreadOutput where
arbitrary = genericArbitrary
shrink = genericShrink
data ClosedThreadOutput = ClosedThreadOutput
{ closedThreadUTxO :: (TxIn, TxOut CtxUTxO)
, closedParties :: [OnChain.Party]
, closedContestationDeadline :: Plutus.POSIXTime
, closedContesters :: [Plutus.PubKeyHash]
}
deriving stock (Eq, Show, Generic)
deriving anyclass (ToJSON, FromJSON)
instance Arbitrary ClosedThreadOutput where
arbitrary = genericArbitrary
shrink = genericShrink
hydraHeadV1AssetName :: AssetName
hydraHeadV1AssetName = AssetName (fromBuiltin hydraHeadV1)
-- | The metadata label used for identifying Hydra protocol transactions. As
-- suggested by a friendly large language model: The number most commonly
-- associated with "Hydra" is 5, as in the mythological creature Hydra, which
-- had multiple heads, and the number 5 often symbolizes multiplicity or
-- diversity. However, there is no specific numerical association for Hydra
-- smaller than 10000 beyond this mythological reference.
hydraMetadataLabel :: Word64
hydraMetadataLabel = 55555
-- | Create a transaction metadata entry to identify Hydra transactions (for
-- informational purposes).
mkHydraHeadV1TxName :: Text -> TxMetadata
mkHydraHeadV1TxName name =
TxMetadata $ Map.fromList [(hydraMetadataLabel, TxMetaText $ "HydraV1/" <> name)]
-- | Get the metadata entry to identify Hydra transactions (for informational
-- purposes).
getHydraHeadV1TxName :: Tx -> Maybe Text
getHydraHeadV1TxName =
lookupName . txMetadata . getTxBodyContent . getTxBody
where
lookupName = \case
TxMetadataNone -> Nothing
TxMetadataInEra (TxMetadata m) ->
case Map.lookup hydraMetadataLabel m of
Just (TxMetaText name) -> Just name
_ -> Nothing
-- * Create Hydra Head transactions
-- | Create the init transaction from some 'HeadParameters' and a single TxIn
-- which will be used as unique parameter for minting NFTs.
initTx ::
NetworkId ->
-- | Seed input.
TxIn ->
-- | Verification key hashes of all participants.
[OnChainId] ->
HeadParameters ->
Tx
initTx networkId seedTxIn participants parameters =
unsafeBuildTransaction $
emptyTxBody
& addVkInputs [seedTxIn]
& addOutputs
( mkHeadOutputInitial networkId seedTxIn parameters
: map (mkInitialOutput networkId seedTxIn) participants
)
& mintTokens (HeadTokens.mkHeadTokenScript seedTxIn) Mint ((hydraHeadV1AssetName, 1) : participationTokens)
& setTxMetadata (TxMetadataInEra $ mkHydraHeadV1TxName "InitTx")
where
participationTokens =
[(onChainIdToAssetName oid, 1) | oid <- participants]
mkHeadOutput :: NetworkId -> PolicyId -> TxOutDatum ctx -> TxOut ctx
mkHeadOutput networkId tokenPolicyId datum =
TxOut
(mkScriptAddress @PlutusScriptV2 networkId headScript)
(valueFromList [(AssetId tokenPolicyId hydraHeadV1AssetName, 1)])
datum
ReferenceScriptNone
where
headScript = fromPlutusScript Head.validatorScript
mkHeadOutputInitial :: NetworkId -> TxIn -> HeadParameters -> TxOut CtxTx
mkHeadOutputInitial networkId seedTxIn HeadParameters{contestationPeriod, parties} =
mkHeadOutput networkId tokenPolicyId headDatum
where
tokenPolicyId = HeadTokens.headPolicyId seedTxIn
headDatum =
mkTxOutDatumInline $
Head.Initial
{ contestationPeriod = toChain contestationPeriod
, parties = map partyToChain parties
, headId = toPlutusCurrencySymbol tokenPolicyId
, seed = toPlutusTxOutRef seedTxIn
}
mkInitialOutput :: NetworkId -> TxIn -> OnChainId -> TxOut CtxTx
mkInitialOutput networkId seedTxIn participant =
TxOut initialAddress initialValue initialDatum ReferenceScriptNone
where
tokenPolicyId = HeadTokens.headPolicyId seedTxIn
initialValue =
valueFromList [(AssetId tokenPolicyId (onChainIdToAssetName participant), 1)]
initialAddress =
mkScriptAddress @PlutusScriptV2 networkId initialScript
initialScript =
fromPlutusScript Initial.validatorScript
initialDatum =
mkTxOutDatumInline $ Initial.datum (toPlutusCurrencySymbol tokenPolicyId)
-- | Craft a commit transaction which includes the "committed" utxo as a datum.
commitTx ::
NetworkId ->
-- | Published Hydra scripts to reference.
ScriptRegistry ->
HeadId ->
Party ->
-- | The UTxO inputs to commit to the Head.
UTxO ->
-- | _Blueprint_ transaction.
Tx ->
-- | The initial output (sent to each party) which should contain the PT and is
-- locked by initial script
(TxIn, TxOut CtxUTxO, Hash PaymentKey) ->
Tx
commitTx networkId scriptRegistry headId party utxo blueprintTx (initialInput, out, vkh) =
let
ledgerBlueprintTx =
toLedgerTx blueprintTx
& bodyTxL . inputsTxBodyL <>~ Set.singleton (toLedgerTxIn initialInput)
& bodyTxL . inputsTxBodyL <>~ Set.fromList (toLedgerTxIn <$> committedTxIns)
& bodyTxL . referenceInputsTxBodyL <>~ Set.fromList [toLedgerTxIn initialScriptRef]
& bodyTxL . outputsTxBodyL .~ StrictSeq.singleton (toLedgerTxOut commitOutput)
& bodyTxL . reqSignerHashesTxBodyL <>~ Set.singleton (toLedgerKeyHash vkh)
& bodyTxL . auxDataHashTxBodyL .~ SJust (hashAlonzoTxAuxData txAuxMetadata)
& auxDataTxL .~ addMetadata txAuxMetadata
existingWits = ledgerBlueprintTx ^. witsTxL
currentInputs = ledgerBlueprintTx ^. bodyTxL . inputsTxBodyL
commitInputs = Set.map toLedgerTxIn (UTxO.inputSet utxo)
blueprintRedeemers = unRedeemers $ toLedgerTx blueprintTx ^. witsTxL . rdmrsTxWitsL
wits =
witsTxL
.~ ( existingWits
& rdmrsTxWitsL .~ rebuildSpendingRedeemers currentInputs commitInputs blueprintRedeemers
)
in
fromLedgerTx $ ledgerBlueprintTx & wits
where
-- can we combine language maps like this?
addMetadata newMetadata@(AlonzoTxAuxData metadata' timeLocks' languageMap') =
case toLedgerTx blueprintTx ^. auxDataTxL of
SNothing -> SJust newMetadata
SJust (AlonzoTxAuxData metadata timeLocks languageMap) ->
SJust $
AlonzoTxAuxData
(Map.union metadata metadata')
(timeLocks StrictSeq.>< timeLocks')
(Map.union languageMap languageMap')
-- Re-Associate the redeemer indices present in some tx with the same inputs but different
-- indices in the current (commit) tx.
--
-- We need this in order to be able to find the the _old_ tx redeemer and re-add
-- it to the tx witnesses using the appropriate index of the _new_ tx input
-- because of the 'TxIn' re-ordering.
-- NOTE: Only deals with spending redeemers. What about the rest like minting
-- etc.?
rebuildSpendingRedeemers ::
Set (Ledger.TxIn StandardCrypto) ->
Set (Ledger.TxIn StandardCrypto) ->
Map (AlonzoPlutusPurpose AsIndex LedgerEra) (Data LedgerEra, ExUnits) ->
Redeemers LedgerEra
rebuildSpendingRedeemers newInputs oldInputs oldTxRedeemers =
Redeemers $ Map.fromList $ mapMaybe reassociate (toList newInputs)
where
reassociate txin =
let currentIndex = Set.findIndex txin newInputs
key = AlonzoSpending (AsIndex $ fromIntegral currentIndex)
in case txin `Set.lookupIndex` oldInputs of
-- if txin was not found in the old inputs this is the initial input
-- we need to add
Nothing ->
Just
( key
, (toLedgerData @LedgerEra initialRedeemer, ExUnits 0 0)
)
Just ix ->
Map.lookup (AlonzoSpending (AsIndex $ fromIntegral ix)) oldTxRedeemers >>= Just . (key,)
initialScript =
fromPlutusScript @PlutusScriptV2 Initial.validatorScript
initialScriptRef =
fst (initialReference scriptRegistry)
initialRedeemer =
toScriptData . Initial.redeemer $
Initial.ViaCommit (toPlutusTxOutRef <$> committedTxIns)
committedTxIns =
fst <$> UTxO.pairs utxo
commitOutput =
TxOut commitAddress commitValue commitDatum ReferenceScriptNone
commitScript =
fromPlutusScript Commit.validatorScript
commitAddress =
mkScriptAddress @PlutusScriptV2 networkId commitScript
commitValue =
txOutValue out <> foldMap txOutValue utxo
commitDatum =
mkTxOutDatumInline $ mkCommitDatum party utxo (headIdToCurrencySymbol headId)
TxMetadata metadataMap = mkHydraHeadV1TxName "CommitTx"
txAuxMetadata = mkAlonzoTxAuxData @[] @LedgerEra (toShelleyMetadata metadataMap) [toLedgerScript initialScript]
mkCommitDatum :: Party -> UTxO -> CurrencySymbol -> Plutus.Datum
mkCommitDatum party utxo headId =
Commit.datum (partyToChain party, commits, headId)
where
commits =
mapMaybe Commit.serializeCommit $ UTxO.pairs utxo
-- | Create a transaction collecting all "committed" utxo and opening a Head,
-- i.e. driving the Head script state.
collectComTx ::
NetworkId ->
-- | Published Hydra scripts to reference.
ScriptRegistry ->
-- | Party who's authorizing this transaction
VerificationKey PaymentKey ->
-- | Head identifier
HeadId ->
-- | Parameters of the head to collect .
HeadParameters ->
-- | Everything needed to spend the Head state-machine output.
(TxIn, TxOut CtxUTxO) ->
-- | Data needed to spend the commit output produced by each party.
-- Should contain the PT and is locked by @ν_commit@ script.
Map TxIn (TxOut CtxUTxO) ->
-- | UTxO to be used to collect.
-- Should match whatever is recorded in the commit inputs.
UTxO ->
Tx
collectComTx networkId scriptRegistry vk headId headParameters (headInput, initialHeadOutput) commits utxoToCollect =
unsafeBuildTransaction $
emptyTxBody
& addInputs ((headInput, headWitness) : (mkCommit <$> Map.keys commits))
& addReferenceInputs [commitScriptRef, headScriptRef]
& addOutputs [headOutput]
& addExtraRequiredSigners [verificationKeyHash vk]
& setTxMetadata (TxMetadataInEra $ mkHydraHeadV1TxName "CollectComTx")
where
HeadParameters{parties, contestationPeriod} = headParameters
headWitness =
BuildTxWith $
ScriptWitness scriptWitnessInCtx $
mkScriptReference headScriptRef headScript InlineScriptDatum headRedeemer
headScript = fromPlutusScript @PlutusScriptV2 Head.validatorScript
headScriptRef = fst (headReference scriptRegistry)
headRedeemer = toScriptData Head.CollectCom
headOutput =
TxOut
(mkScriptAddress @PlutusScriptV2 networkId headScript)
(txOutValue initialHeadOutput <> commitValue)
headDatumAfter
ReferenceScriptNone
headDatumAfter =
mkTxOutDatumInline
Head.Open
{ Head.parties = partyToChain <$> parties
, utxoHash
, contestationPeriod = toChain contestationPeriod
, headId = headIdToCurrencySymbol headId
}
utxoHash = toBuiltin $ hashUTxO @Tx utxoToCollect
mkCommit commitTxIn = (commitTxIn, commitWitness)
commitWitness =
BuildTxWith $
ScriptWitness scriptWitnessInCtx $
mkScriptReference commitScriptRef commitScript InlineScriptDatum commitRedeemer
commitScriptRef =
fst (commitReference scriptRegistry)
commitValue =
mconcat $ txOutValue <$> Map.elems commits
commitScript =
fromPlutusScript @PlutusScriptV2 Commit.validatorScript
commitRedeemer =
toScriptData $ Commit.redeemer Commit.ViaCollectCom
-- | Low-level data type of a snapshot to close the head with. This is different
-- to the 'ConfirmedSnasphot', which is provided to `CloseTx` as it also
-- contains relevant chain state like the 'openUtxoHash'.
data ClosingSnapshot
= CloseWithInitialSnapshot {openUtxoHash :: UTxOHash}
| CloseWithConfirmedSnapshot
{ snapshotNumber :: SnapshotNumber
, closeUtxoHash :: UTxOHash
, -- XXX: This is a bit of a wart and stems from the fact that our
-- SignableRepresentation of 'Snapshot' is in fact the snapshotNumber
-- and the closeUtxoHash as also included above
signatures :: MultiSignature (Snapshot Tx)
}
data CloseTxError
= InvalidHeadIdInClose {headId :: HeadId}
| CannotFindHeadOutputToClose
deriving stock (Show)
-- | Create a transaction closing a head with either the initial snapshot or
-- with a multi-signed confirmed snapshot.
closeTx ::
-- | Published Hydra scripts to reference.
ScriptRegistry ->
-- | Party who's authorizing this transaction
VerificationKey PaymentKey ->
-- | The snapshot to close with, can be either initial or confirmed one.
ClosingSnapshot ->
-- | Lower validity slot number, usually a current or quite recent slot number.
SlotNo ->
-- | Upper validity slot and UTC time to compute the contestation deadline time.
PointInTime ->
-- | Everything needed to spend the Head state-machine output.
OpenThreadOutput ->
-- | Head identifier
HeadId ->
Tx
closeTx scriptRegistry vk closing startSlotNo (endSlotNo, utcTime) openThreadOutput headId =
unsafeBuildTransaction $
emptyTxBody
& addInputs [(headInput, headWitness)]
& addReferenceInputs [headScriptRef]
& addOutputs [headOutputAfter]
& addExtraRequiredSigners [verificationKeyHash vk]
& setValidityLowerBound startSlotNo
& setValidityUpperBound endSlotNo
& setTxMetadata (TxMetadataInEra $ mkHydraHeadV1TxName "CloseTx")
where
OpenThreadOutput
{ openThreadUTxO = (headInput, headOutputBefore)
, openContestationPeriod
, openParties
} = openThreadOutput
headWitness =
BuildTxWith $
ScriptWitness scriptWitnessInCtx $
mkScriptReference headScriptRef headScript InlineScriptDatum headRedeemer
headScriptRef =
fst (headReference scriptRegistry)
headScript =
fromPlutusScript @PlutusScriptV2 Head.validatorScript
headRedeemer =
toScriptData
Head.Close
{ signature
}
headOutputAfter =
modifyTxOutDatum (const headDatumAfter) headOutputBefore
headDatumAfter =
mkTxOutDatumInline
Head.Closed
{ snapshotNumber
, utxoHash = toBuiltin utxoHashBytes
, parties = openParties
, contestationDeadline
, contestationPeriod = openContestationPeriod
, headId = headIdToCurrencySymbol headId
, contesters = []
}
snapshotNumber = toInteger $ case closing of
CloseWithInitialSnapshot{} -> 0
CloseWithConfirmedSnapshot{snapshotNumber = sn} -> sn
UTxOHash utxoHashBytes = case closing of
CloseWithInitialSnapshot{openUtxoHash} -> openUtxoHash
CloseWithConfirmedSnapshot{closeUtxoHash} -> closeUtxoHash
signature = case closing of
CloseWithInitialSnapshot{} -> mempty
CloseWithConfirmedSnapshot{signatures = s} -> toPlutusSignatures s
contestationDeadline =
addContestationPeriod (posixFromUTCTime utcTime) openContestationPeriod
data ContestTxError
= InvalidHeadIdInContest {headId :: HeadId}
| CannotFindHeadOutputToContest
| MissingHeadDatumInContest
| MissingHeadRedeemerInContest
| WrongDatumInContest
| FailedToConvertFromScriptDataInContest
deriving stock (Show)
-- XXX: This function is VERY similar to the 'closeTx' function (only notable
-- difference being the redeemer, which is in itself also the same structure as
-- the close's one. We could potentially refactor this to avoid repetition or do
-- something more principled at the protocol level itself and "merge" close and
-- contest as one operation.
contestTx ::
-- | Published Hydra scripts to reference.
ScriptRegistry ->
-- | Party who's authorizing this transaction
VerificationKey PaymentKey ->
-- | Contested snapshot number (i.e. the one we contest to)
Snapshot Tx ->
-- | Multi-signature of the whole snapshot
MultiSignature (Snapshot Tx) ->
-- | Current slot and posix time to be used as the contestation time.
PointInTime ->
-- | Everything needed to spend the Head state-machine output.
ClosedThreadOutput ->
HeadId ->
ContestationPeriod ->
Tx
contestTx scriptRegistry vk Snapshot{number, utxo} sig (slotNo, _) closedThreadOutput headId contestationPeriod =
unsafeBuildTransaction $
emptyTxBody
& addInputs [(headInput, headWitness)]
& addReferenceInputs [headScriptRef]
& addOutputs [headOutputAfter]
& addExtraRequiredSigners [verificationKeyHash vk]
& setValidityUpperBound slotNo
& setTxMetadata (TxMetadataInEra $ mkHydraHeadV1TxName "ContestTx")
where
ClosedThreadOutput
{ closedThreadUTxO = (headInput, headOutputBefore)
, closedParties
, closedContestationDeadline
, closedContesters
} = closedThreadOutput
headWitness =
BuildTxWith $
ScriptWitness scriptWitnessInCtx $
mkScriptReference headScriptRef headScript InlineScriptDatum headRedeemer
headScriptRef =
fst (headReference scriptRegistry)
headScript =
fromPlutusScript @PlutusScriptV2 Head.validatorScript
headRedeemer =
toScriptData
Head.Contest
{ signature = toPlutusSignatures sig
}
headOutputAfter =
modifyTxOutDatum (const headDatumAfter) headOutputBefore
contester = toPlutusKeyHash (verificationKeyHash vk)
onChainConstestationPeriod = toChain contestationPeriod
newContestationDeadline =
if length (contester : closedContesters) == length closedParties
then closedContestationDeadline
else addContestationPeriod closedContestationDeadline onChainConstestationPeriod
headDatumAfter =
mkTxOutDatumInline
Head.Closed
{ snapshotNumber = toInteger number
, utxoHash
, parties = closedParties
, contestationDeadline = newContestationDeadline
, contestationPeriod = onChainConstestationPeriod
, headId = headIdToCurrencySymbol headId
, contesters = contester : closedContesters
}
utxoHash = toBuiltin $ hashUTxO @Tx utxo
data FanoutTxError
= CannotFindHeadOutputToFanout
| MissingHeadDatumInFanout
| WrongDatumInFanout
| FailedToConvertFromScriptDataInFanout
deriving stock (Show)
-- | Create the fanout transaction, which distributes the closed state
-- accordingly. The head validator allows fanout only > deadline, so we need
-- to set the lower bound to be deadline + 1 slot.
fanoutTx ::
-- | Published Hydra scripts to reference.
ScriptRegistry ->
-- | Snapshotted UTxO to fanout on layer 1
UTxO ->
-- | Everything needed to spend the Head state-machine output.
(TxIn, TxOut CtxUTxO) ->
-- | Contestation deadline as SlotNo, used to set lower tx validity bound.
SlotNo ->
-- | Minting Policy script, made from initial seed
PlutusScript ->
Tx
fanoutTx scriptRegistry utxo (headInput, headOutput) deadlineSlotNo headTokenScript =
unsafeBuildTransaction $
emptyTxBody
& addInputs [(headInput, headWitness)]
& addReferenceInputs [headScriptRef]
& addOutputs orderedTxOutsToFanout
& burnTokens headTokenScript Burn headTokens
& setValidityLowerBound (deadlineSlotNo + 1)
& setTxMetadata (TxMetadataInEra $ mkHydraHeadV1TxName "FanoutTx")
where
headWitness =
BuildTxWith $
ScriptWitness scriptWitnessInCtx $
mkScriptReference headScriptRef headScript InlineScriptDatum headRedeemer
headScriptRef =
fst (headReference scriptRegistry)
headScript =
fromPlutusScript @PlutusScriptV2 Head.validatorScript
headRedeemer =
toScriptData (Head.Fanout $ fromIntegral $ length utxo)
headTokens =
headTokensFromValue headTokenScript (txOutValue headOutput)
orderedTxOutsToFanout =
toTxContext <$> toList utxo
data AbortTxError
= OverlappingInputs
| CannotFindHeadOutputToAbort
deriving stock (Show)
-- | Create transaction which aborts a head by spending the Head output and all
-- other "initial" outputs.
abortTx ::
-- | Committed UTxOs to reimburse.
UTxO ->
-- | Published Hydra scripts to reference.
ScriptRegistry ->
-- | Party who's authorizing this transaction
VerificationKey PaymentKey ->
-- | Everything needed to spend the Head state-machine output.
(TxIn, TxOut CtxUTxO) ->
-- | Script for monetary policy to burn tokens
PlutusScript ->
-- | Data needed to spend the initial output sent to each party to the Head.
-- Should contain the PT and is locked by initial script.
Map TxIn (TxOut CtxUTxO) ->
-- | Data needed to spend commit outputs.
-- Should contain the PT and is locked by commit script.
Map TxIn (TxOut CtxUTxO) ->
Either AbortTxError Tx
abortTx committedUTxO scriptRegistry vk (headInput, initialHeadOutput) headTokenScript initialsToAbort commitsToAbort
| isJust (lookup headInput initialsToAbort) =
Left OverlappingInputs
| otherwise =
Right $
unsafeBuildTransaction $
emptyTxBody
& addInputs ((headInput, headWitness) : initialInputs <> commitInputs)
& addReferenceInputs [initialScriptRef, commitScriptRef, headScriptRef]
& addOutputs reimbursedOutputs
& burnTokens headTokenScript Burn headTokens
& addExtraRequiredSigners [verificationKeyHash vk]
where
headWitness =
BuildTxWith $
ScriptWitness scriptWitnessInCtx $
mkScriptReference headScriptRef headScript InlineScriptDatum headRedeemer
headScriptRef =
fst (headReference scriptRegistry)
headScript =
fromPlutusScript @PlutusScriptV2 Head.validatorScript
headRedeemer =
toScriptData Head.Abort
initialInputs = mkAbortInitial <$> Map.keys initialsToAbort
commitInputs = mkAbortCommit <$> Map.keys commitsToAbort
headTokens =
headTokensFromValue headTokenScript $
mconcat
[ txOutValue initialHeadOutput
, foldMap txOutValue initialsToAbort
, foldMap txOutValue commitsToAbort
]
mkAbortInitial initialInput = (initialInput, abortInitialWitness)
abortInitialWitness =
BuildTxWith $
ScriptWitness scriptWitnessInCtx $
mkScriptReference initialScriptRef initialScript InlineScriptDatum initialRedeemer
initialScriptRef =
fst (initialReference scriptRegistry)
initialScript =
fromPlutusScript @PlutusScriptV2 Initial.validatorScript
initialRedeemer =
toScriptData $ Initial.redeemer Initial.ViaAbort
mkAbortCommit commitInput = (commitInput, abortCommitWitness)
abortCommitWitness =
BuildTxWith $
ScriptWitness scriptWitnessInCtx $
mkScriptReference commitScriptRef commitScript InlineScriptDatum commitRedeemer
commitScriptRef =
fst (commitReference scriptRegistry)
commitScript =
fromPlutusScript @PlutusScriptV2 Commit.validatorScript
commitRedeemer =
toScriptData (Commit.redeemer Commit.ViaAbort)
reimbursedOutputs = toTxContext . snd <$> UTxO.pairs committedUTxO
-- * Observe Hydra Head transactions
-- | Generalised type for arbitrary Head observations on-chain.
data HeadObservation
= NoHeadTx
| Init InitObservation
| Abort AbortObservation
| Commit CommitObservation
| CollectCom CollectComObservation
| Close CloseObservation
| Contest ContestObservation
| Fanout FanoutObservation
deriving stock (Eq, Show, Generic)
instance Arbitrary HeadObservation where
arbitrary = genericArbitrary
-- | Observe any Hydra head transaction.
observeHeadTx :: NetworkId -> UTxO -> Tx -> HeadObservation
observeHeadTx networkId utxo tx =
fromMaybe NoHeadTx $
either (const Nothing) (Just . Init) (observeInitTx tx)
<|> Abort <$> observeAbortTx utxo tx
<|> Commit <$> observeCommitTx networkId utxo tx
<|> CollectCom <$> observeCollectComTx utxo tx
<|> Close <$> observeCloseTx utxo tx
<|> Contest <$> observeContestTx utxo tx
<|> Fanout <$> observeFanoutTx utxo tx
-- | Data which can be observed from an `initTx`.
data InitObservation = InitObservation
{ initialThreadUTxO :: (TxIn, TxOut CtxUTxO)
, initials :: [(TxIn, TxOut CtxUTxO)]
, headId :: HeadId
, -- XXX: This is cardano-specific, while headId, parties and
-- contestationPeriod are already generic here. Check which is more
-- convenient and consistent!
seedTxIn :: TxIn
, contestationPeriod :: ContestationPeriod
, parties :: [Party]
, -- XXX: Improve naming
participants :: [OnChainId]
}
deriving stock (Show, Eq, Generic)
instance Arbitrary InitObservation where
arbitrary = genericArbitrary
data NotAnInitReason
= NoHeadOutput
| NotAHeadDatum
| NoSTFound
| NotAHeadPolicy
deriving stock (Show, Eq, Generic)
deriving anyclass (ToJSON, FromJSON)
instance Arbitrary NotAnInitReason where
arbitrary = genericArbitrary
-- | Identify a init tx by checking the output value for holding tokens that are
-- valid head tokens (checked by seed + policy).
observeInitTx ::
Tx ->
Either NotAnInitReason InitObservation
observeInitTx tx = do
-- XXX: Lots of redundant information here
(ix, headOut, headState) <-
maybeLeft NoHeadOutput $
findFirst matchHeadOutput indexedOutputs
-- check that we have a proper head
(pid, contestationPeriod, onChainParties, seedTxIn) <- case headState of
(Head.Initial cp ps cid outRef) -> do
pid <- fromPlutusCurrencySymbol cid ?> NotAHeadPolicy
pure (pid, fromChain cp, ps, fromPlutusTxOutRef outRef)
_ -> Left NotAHeadDatum
let stQuantity = selectAsset (txOutValue headOut) (AssetId pid hydraHeadV1AssetName)
-- check that ST is present in the head output
unless (stQuantity == 1) $
Left NoSTFound
-- check that we are using the same seed and headId matches
unless (pid == HeadTokens.headPolicyId seedTxIn) $
Left NotAHeadPolicy
pure $
InitObservation
{ headId = mkHeadId pid
, seedTxIn
, initialThreadUTxO = (mkTxIn tx ix, toCtxUTxOTxOut headOut)
, initials
, contestationPeriod
, parties = mapMaybe partyFromChain onChainParties
, participants = assetNameToOnChainId <$> mintedTokenNames pid
}
where
maybeLeft e = maybe (Left e) Right
matchHeadOutput (ix, out) = do
guard $ isScriptTxOut headScript out
(ix,out,) <$> (fromScriptData =<< txOutScriptData out)
headScript = fromPlutusScript @PlutusScriptV2 Head.validatorScript
indexedOutputs = zip [0 ..] (txOuts' tx)
initialOutputs = filter (isInitial . snd) indexedOutputs
initials =
map
(bimap (mkTxIn tx) toCtxUTxOTxOut)
initialOutputs
isInitial = isScriptTxOut initialScript
initialScript = fromPlutusScript @PlutusScriptV2 Initial.validatorScript
mintedTokenNames pid =
[ assetName
| (AssetId policyId assetName, q) <- txMintAssets tx
, q == 1 -- NOTE: Only consider unique tokens
, policyId == pid
, assetName /= hydraHeadV1AssetName
]
-- | Full observation of a commit transaction.
data CommitObservation = CommitObservation
{ commitOutput :: (TxIn, TxOut CtxUTxO)
, party :: Party
-- ^ Hydra participant who committed the UTxO.
, committed :: UTxO
, headId :: HeadId
}
deriving stock (Eq, Show, Generic)
instance Arbitrary CommitObservation where
arbitrary = genericArbitrary
-- | Identify a commit tx by:
--
-- - Check that its spending from the init validator,
-- - Find the outputs which pays to the commit validator,
-- - Using the datum of that output, deserialize the committed output,
-- - Reconstruct the committed UTxO from both values (tx input and output).
observeCommitTx ::
NetworkId ->
-- | A UTxO set to lookup tx inputs. Should at least contain the input
-- spending from νInitial.
UTxO ->
Tx ->
Maybe CommitObservation
observeCommitTx networkId utxo tx = do
-- NOTE: Instead checking to spend from initial we could be looking at the
-- seed:
--
-- - We must check that participation token in output satisfies
-- policyId = hash(mu_head(seed))
--
-- - This allows us to assume (by induction) the output datum at the commit
-- script is legit
--
-- - Further, we need to assert / assume that only one script is spent = onle
-- one redeemer matches the InitialRedeemer, as we do not have information
-- which of the inputs is spending from the initial script otherwise.
--
-- Right now we only have the headId in the datum, so we use that in place of
-- the seed -> THIS CAN NOT BE TRUSTED.
guard isSpendingFromInitial
(commitIn, commitOut) <- findTxOutByAddress commitAddress tx
dat <- txOutScriptData commitOut
(onChainParty, onChainCommits, headId) :: Commit.DatumType <- fromScriptData dat
party <- partyFromChain onChainParty
-- NOTE: If we have the resolved inputs (utxo) then we could avoid putting
-- the commit into the datum (+ changing the hashing strategy of
-- collect/fanout)
committed <- do
committedUTxO <- traverse (Commit.deserializeCommit (networkIdToNetwork networkId)) onChainCommits
pure . UTxO.fromPairs $ committedUTxO
policyId <- fromPlutusCurrencySymbol headId
pure
CommitObservation
{ commitOutput = (commitIn, toUTxOContext commitOut)
, party
, committed
, headId = mkHeadId policyId
}
where
isSpendingFromInitial :: Bool
isSpendingFromInitial =
any (\o -> txOutAddress o == initialAddress) (resolveInputsUTxO utxo tx)
initialAddress = mkScriptAddress @PlutusScriptV2 networkId initialScript
initialScript = fromPlutusScript Initial.validatorScript
commitAddress = mkScriptAddress @PlutusScriptV2 networkId commitScript
commitScript = fromPlutusScript Commit.validatorScript
data CollectComObservation = CollectComObservation
{ threadOutput :: OpenThreadOutput
, headId :: HeadId
, utxoHash :: UTxOHash
}
deriving stock (Show, Eq, Generic)
instance Arbitrary CollectComObservation where
arbitrary = genericArbitrary
-- | Identify a collectCom tx by lookup up the input spending the Head output
-- and decoding its redeemer.
observeCollectComTx ::
-- | A UTxO set to lookup tx inputs
UTxO ->
Tx ->
Maybe CollectComObservation
observeCollectComTx utxo tx = do
let inputUTxO = resolveInputsUTxO utxo tx
(headInput, headOutput) <- findTxOutByScript @PlutusScriptV2 inputUTxO headScript
redeemer <- findRedeemerSpending tx headInput
oldHeadDatum <- txOutScriptData $ toTxContext headOutput
datum <- fromScriptData oldHeadDatum
headId <- findStateToken headOutput
case (datum, redeemer) of
(Head.Initial{parties, contestationPeriod}, Head.CollectCom) -> do
(newHeadInput, newHeadOutput) <- findTxOutByScript @PlutusScriptV2 (utxoFromTx tx) headScript
newHeadDatum <- txOutScriptData $ toTxContext newHeadOutput
utxoHash <- UTxOHash <$> decodeUtxoHash newHeadDatum
pure
CollectComObservation
{ threadOutput =
OpenThreadOutput
{ openThreadUTxO = (newHeadInput, newHeadOutput)
, openParties = parties
, openContestationPeriod = contestationPeriod
}
, headId
, utxoHash
}
_ -> Nothing
where
headScript = fromPlutusScript Head.validatorScript
decodeUtxoHash datum =
case fromScriptData datum of
Just Head.Open{utxoHash} -> Just $ fromBuiltin utxoHash
_ -> Nothing
data CloseObservation = CloseObservation