-
Notifications
You must be signed in to change notification settings - Fork 86
/
Scenarios.hs
671 lines (600 loc) · 27.1 KB
/
Scenarios.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
{-# LANGUAGE DuplicateRecordFields #-}
{-# OPTIONS_GHC -Wno-ambiguous-fields #-}
module Hydra.Cluster.Scenarios where
import Hydra.Prelude
import Test.Hydra.Prelude
import Cardano.Api.UTxO qualified as UTxO
import CardanoClient (
QueryPoint (QueryTip),
RunningNode (..),
buildTransaction,
queryTip,
queryUTxOFor,
submitTx,
)
import CardanoNode (NodeLog)
import Control.Concurrent.Async (mapConcurrently_)
import Control.Lens ((^..), (^?))
import Data.Aeson (Value, object, (.=))
import Data.Aeson qualified as Aeson
import Data.Aeson.Lens (key, values, _JSON)
import Data.Aeson.Types (parseMaybe)
import Data.ByteString (isInfixOf)
import Data.ByteString qualified as B
import Data.Set qualified as Set
import Hydra.API.HTTPServer (DraftCommitTxRequest (..), DraftCommitTxResponse (..), TransactionSubmitted (..))
import Hydra.Cardano.Api (Coin (..), File (File), Key (SigningKey), PaymentKey, Tx, TxId, UTxO, getVerificationKey, isVkTxOut, lovelaceToValue, makeSignedTransaction, mkVkAddress, selectLovelace, signTx, txOutAddress, txOutValue, writeFileTextEnvelope, pattern ReferenceScriptNone, pattern TxOut, pattern TxOutDatumNone)
import Hydra.Chain.Direct.Tx (verificationKeyToOnChainId)
import Hydra.Cluster.Faucet (FaucetLog, seedFromFaucet, seedFromFaucet_)
import Hydra.Cluster.Faucet qualified as Faucet
import Hydra.Cluster.Fixture (Actor (..), actorName, alice, aliceSk, aliceVk, bob, bobSk, bobVk, carol, carolSk)
import Hydra.Cluster.Mithril (MithrilLog)
import Hydra.Cluster.Options (Options)
import Hydra.Cluster.Util (chainConfigFor, keysFor, modifyConfig, setNetworkId)
import Hydra.ContestationPeriod (ContestationPeriod (UnsafeContestationPeriod), fromNominalDiffTime)
import Hydra.HeadId (HeadId)
import Hydra.Ledger (IsTx (balance), txId)
import Hydra.Ledger.Cardano (genKeyPair, mkSimpleTx)
import Hydra.Logging (Tracer, traceWith)
import Hydra.Options (networkId, startChainFrom)
import Hydra.Party (Party)
import HydraNode (
HydraClient (..),
HydraNodeLog,
input,
output,
requestCommitTx,
send,
waitFor,
waitForAllMatch,
waitForNodesConnected,
waitMatch,
withHydraCluster,
withHydraNode,
)
import Network.HTTP.Conduit qualified as L
import Network.HTTP.Req (
HttpException (VanillaHttpException),
JsonResponse,
POST (POST),
ReqBodyJson (ReqBodyJson),
defaultHttpConfig,
http,
port,
req,
responseBody,
runReq,
(/:),
)
import System.Directory (removeDirectoryRecursive)
import System.FilePath ((</>))
import Test.QuickCheck (choose, generate)
data EndToEndLog
= ClusterOptions {options :: Options}
| FromCardanoNode NodeLog
| FromFaucet FaucetLog
| FromHydraNode HydraNodeLog
| FromMithril MithrilLog
| StartingFunds {actor :: String, utxo :: UTxO}
| RefueledFunds {actor :: String, refuelingAmount :: Coin, utxo :: UTxO}
| RemainingFunds {actor :: String, utxo :: UTxO}
| PublishedHydraScriptsAt {hydraScriptsTxId :: TxId}
| UsingHydraScriptsAt {hydraScriptsTxId :: TxId}
| CreatedKey {keyPath :: FilePath}
deriving stock (Eq, Show, Generic)
deriving anyclass (ToJSON, FromJSON)
restartedNodeCanObserveCommitTx :: Tracer IO EndToEndLog -> FilePath -> RunningNode -> TxId -> IO ()
restartedNodeCanObserveCommitTx tracer workDir cardanoNode hydraScriptsTxId = do
let clients = [Alice, Bob]
[(aliceCardanoVk, _), (bobCardanoVk, _)] <- forM clients keysFor
seedFromFaucet_ cardanoNode aliceCardanoVk 100_000_000 (contramap FromFaucet tracer)
seedFromFaucet_ cardanoNode bobCardanoVk 100_000_000 (contramap FromFaucet tracer)
let contestationPeriod = UnsafeContestationPeriod 1
aliceChainConfig <-
chainConfigFor Alice workDir nodeSocket hydraScriptsTxId [Bob] contestationPeriod
<&> setNetworkId networkId
bobChainConfig <-
chainConfigFor Bob workDir nodeSocket hydraScriptsTxId [Alice] contestationPeriod
<&> setNetworkId networkId
let hydraTracer = contramap FromHydraNode tracer
withHydraNode hydraTracer bobChainConfig workDir 1 bobSk [aliceVk] [1, 2] $ \n1 -> do
headId <- withHydraNode hydraTracer aliceChainConfig workDir 2 aliceSk [bobVk] [1, 2] $ \n2 -> do
send n1 $ input "Init" []
-- XXX: might need to tweak the wait time
waitForAllMatch 10 [n1, n2] $ headIsInitializingWith (Set.fromList [alice, bob])
-- n1 does a commit while n2 is down
requestCommitTx n1 mempty >>= submitTx cardanoNode
waitFor hydraTracer 10 [n1] $
output "Committed" ["party" .= bob, "utxo" .= object mempty, "headId" .= headId]
-- n2 is back and does observe the commit
withHydraNode hydraTracer aliceChainConfig workDir 2 aliceSk [bobVk] [1, 2] $ \n2 -> do
waitFor hydraTracer 10 [n2] $
output "Committed" ["party" .= bob, "utxo" .= object mempty, "headId" .= headId]
where
RunningNode{nodeSocket, networkId} = cardanoNode
testPreventResumeReconfiguredPeer :: Tracer IO EndToEndLog -> FilePath -> RunningNode -> TxId -> IO ()
testPreventResumeReconfiguredPeer tracer workDir cardanoNode hydraScriptsTxId = do
let contestationPeriod = UnsafeContestationPeriod 1
aliceChainConfig <-
chainConfigFor Alice workDir nodeSocket hydraScriptsTxId [Bob] contestationPeriod
<&> setNetworkId networkId
aliceChainConfigWithoutBob <-
chainConfigFor Alice workDir nodeSocket hydraScriptsTxId [] contestationPeriod
<&> setNetworkId networkId
bobChainConfig <-
chainConfigFor Bob workDir nodeSocket hydraScriptsTxId [Alice] contestationPeriod
<&> setNetworkId networkId
let hydraTracer = contramap FromHydraNode tracer
aliceStartsWithoutKnowingBob =
withHydraNode hydraTracer aliceChainConfigWithoutBob workDir 2 aliceSk [] [1, 2]
aliceRestartsWithBobConfigured =
withHydraNode hydraTracer aliceChainConfig workDir 2 aliceSk [bobVk] [1, 2]
withHydraNode hydraTracer bobChainConfig workDir 1 bobSk [aliceVk] [1, 2] $ \n1 -> do
aliceStartsWithoutKnowingBob $ \n2 -> do
failToConnect hydraTracer [n1, n2]
threadDelay 1
aliceRestartsWithBobConfigured (const $ threadDelay 1)
`shouldThrow` aFailure
threadDelay 1
removeDirectoryRecursive $ workDir </> "state-2"
aliceRestartsWithBobConfigured $ \n2 -> do
waitForNodesConnected hydraTracer 10 [n1, n2]
where
RunningNode{nodeSocket, networkId} = cardanoNode
aFailure :: Selector HUnitFailure
aFailure = const True
failToConnect tr nodes = waitForNodesConnected tr 10 nodes `shouldThrow` anyException
restartedNodeCanAbort :: Tracer IO EndToEndLog -> FilePath -> RunningNode -> TxId -> IO ()
restartedNodeCanAbort tracer workDir cardanoNode hydraScriptsTxId = do
refuelIfNeeded tracer cardanoNode Alice 100_000_000
let contestationPeriod = UnsafeContestationPeriod 2
aliceChainConfig <-
chainConfigFor Alice workDir nodeSocket hydraScriptsTxId [] contestationPeriod
-- we delibelately do not start from a chain point here to highlight the
-- need for persistence
<&> modifyConfig (\config -> config{networkId, startChainFrom = Nothing})
let hydraTracer = contramap FromHydraNode tracer
headId1 <- withHydraNode hydraTracer aliceChainConfig workDir 1 aliceSk [] [1] $ \n1 -> do
send n1 $ input "Init" []
-- XXX: might need to tweak the wait time
waitMatch 10 n1 $ headIsInitializingWith (Set.fromList [alice])
withHydraNode hydraTracer aliceChainConfig workDir 1 aliceSk [] [1] $ \n1 -> do
-- Also expect to see past server outputs replayed
headId2 <- waitMatch 10 n1 $ headIsInitializingWith (Set.fromList [alice])
headId1 `shouldBe` headId2
send n1 $ input "Abort" []
waitFor hydraTracer 10 [n1] $
output "HeadIsAborted" ["utxo" .= object mempty, "headId" .= headId2]
where
RunningNode{nodeSocket, networkId} = cardanoNode
-- | Step through the full life cycle of a Hydra Head with only a single
-- participant. This scenario is also used by the smoke test run via the
-- `hydra-cluster` executable.
singlePartyHeadFullLifeCycle ::
Tracer IO EndToEndLog ->
FilePath ->
RunningNode ->
TxId ->
IO ()
singlePartyHeadFullLifeCycle tracer workDir node hydraScriptsTxId =
( `finally`
do
returnFundsToFaucet tracer node Alice
returnFundsToFaucet tracer node AliceFunds
)
$ do
refuelIfNeeded tracer node Alice 55_000_000
-- Start hydra-node on chain tip
tip <- queryTip networkId nodeSocket
contestationPeriod <- fromNominalDiffTime $ 10 * blockTime
aliceChainConfig <-
chainConfigFor Alice workDir nodeSocket hydraScriptsTxId [] contestationPeriod
<&> modifyConfig (\config -> config{networkId, startChainFrom = Just tip})
withHydraNode hydraTracer aliceChainConfig workDir 1 aliceSk [] [1] $ \n1 -> do
-- Initialize & open head
send n1 $ input "Init" []
headId <- waitMatch (10 * blockTime) n1 $ headIsInitializingWith (Set.fromList [alice])
-- Commit something from external key
(walletVk, walletSk) <- keysFor AliceFunds
amount <- Coin <$> generate (choose (10_000_000, 50_000_000))
utxoToCommit <- seedFromFaucet node walletVk amount (contramap FromFaucet tracer)
requestCommitTx n1 utxoToCommit <&> signTx walletSk >>= submitTx node
waitFor hydraTracer (10 * blockTime) [n1] $
output "HeadIsOpen" ["utxo" .= toJSON utxoToCommit, "headId" .= headId]
-- Close head
send n1 $ input "Close" []
deadline <- waitMatch (10 * blockTime) n1 $ \v -> do
guard $ v ^? key "tag" == Just "HeadIsClosed"
guard $ v ^? key "headId" == Just (toJSON headId)
v ^? key "contestationDeadline" . _JSON
remainingTime <- diffUTCTime deadline <$> getCurrentTime
waitFor hydraTracer (remainingTime + 3 * blockTime) [n1] $
output "ReadyToFanout" ["headId" .= headId]
send n1 $ input "Fanout" []
waitFor hydraTracer (10 * blockTime) [n1] $
output "HeadIsFinalized" ["utxo" .= toJSON utxoToCommit, "headId" .= headId]
traceRemainingFunds Alice
traceRemainingFunds AliceFunds
where
hydraTracer = contramap FromHydraNode tracer
RunningNode{networkId, nodeSocket, blockTime} = node
traceRemainingFunds actor = do
(actorVk, _) <- keysFor actor
utxo <- queryUTxOFor networkId nodeSocket QueryTip actorVk
traceWith tracer RemainingFunds{actor = actorName actor, utxo}
-- | Open a Hydra Head with only a single participant but some arbitrary UTxO
-- committed.
singlePartyOpenAHead ::
Tracer IO EndToEndLog ->
FilePath ->
RunningNode ->
TxId ->
-- | Continuation called when the head is open
(HydraClient -> SigningKey PaymentKey -> IO ()) ->
IO ()
singlePartyOpenAHead tracer workDir node hydraScriptsTxId callback =
(`finally` returnFundsToFaucet tracer node Alice) $ do
refuelIfNeeded tracer node Alice 25_000_000
-- Start hydra-node on chain tip
tip <- queryTip networkId nodeSocket
let contestationPeriod = UnsafeContestationPeriod 100
aliceChainConfig <-
chainConfigFor Alice workDir nodeSocket hydraScriptsTxId [] contestationPeriod
<&> modifyConfig (\config -> config{networkId, startChainFrom = Just tip})
(walletVk, walletSk) <- generate genKeyPair
let keyPath = workDir <> "/wallet.sk"
_ <- writeFileTextEnvelope (File keyPath) Nothing walletSk
traceWith tracer CreatedKey{keyPath}
utxoToCommit <- seedFromFaucet node walletVk 100_000_000 (contramap FromFaucet tracer)
let hydraTracer = contramap FromHydraNode tracer
withHydraNode hydraTracer aliceChainConfig workDir 1 aliceSk [] [1] $ \n1 -> do
-- Initialize & open head
send n1 $ input "Init" []
headId <- waitMatch (10 * blockTime) n1 $ headIsInitializingWith (Set.fromList [alice])
-- Commit nothing for now
requestCommitTx n1 utxoToCommit <&> signTx walletSk >>= submitTx node
waitFor hydraTracer (10 * blockTime) [n1] $
output "HeadIsOpen" ["utxo" .= toJSON utxoToCommit, "headId" .= headId]
callback n1 walletSk
where
RunningNode{networkId, nodeSocket, blockTime} = node
-- | Single hydra-node where the commit is done from an external UTxO owned by a
-- script which requires providing script, datum and redeemer instead of
-- signing the transaction.
singlePartyCommitsFromExternal ::
Tracer IO EndToEndLog ->
FilePath ->
RunningNode ->
TxId ->
IO ()
singlePartyCommitsFromExternal tracer workDir node hydraScriptsTxId =
( `finally`
do
returnFundsToFaucet tracer node Alice
returnFundsToFaucet tracer node AliceFunds
)
$ do
refuelIfNeeded tracer node Alice 25_000_000
aliceChainConfig <- chainConfigFor Alice workDir nodeSocket hydraScriptsTxId [] $ UnsafeContestationPeriod 100
let hydraNodeId = 1
let hydraTracer = contramap FromHydraNode tracer
withHydraNode hydraTracer aliceChainConfig workDir hydraNodeId aliceSk [] [1] $ \n1 -> do
send n1 $ input "Init" []
headId <- waitMatch (10 * blockTime) n1 $ headIsInitializingWith (Set.fromList [alice])
(walletVk, _) <- keysFor AliceFunds
utxoToCommit <- seedFromFaucet node walletVk 5_000_000 (contramap FromFaucet tracer)
-- Commit the script output using known witness
let clientPayload = SimpleCommitRequest{utxoToCommit}
res <-
runReq defaultHttpConfig $
req
POST
(http "127.0.0.1" /: "commit")
(ReqBodyJson clientPayload)
(Proxy :: Proxy (JsonResponse DraftCommitTxResponse))
(port $ 4000 + hydraNodeId)
let DraftCommitTxResponse{commitTx} = responseBody res
submitTx node commitTx
lockedUTxO <- waitMatch (10 * blockTime) n1 $ \v -> do
guard $ v ^? key "headId" == Just (toJSON headId)
guard $ v ^? key "tag" == Just "HeadIsOpen"
pure $ v ^? key "utxo"
lockedUTxO `shouldBe` Just (toJSON utxoToCommit)
where
RunningNode{nodeSocket, blockTime} = node
-- | Single hydra-node where the commit is done from a raw transaction
-- blueprint.
singlePartyCommitsFromExternalTxBlueprint ::
Tracer IO EndToEndLog ->
FilePath ->
RunningNode ->
TxId ->
IO ()
singlePartyCommitsFromExternalTxBlueprint tracer workDir node hydraScriptsTxId =
(`finally` returnFundsToFaucet tracer node Alice) $ do
refuelIfNeeded tracer node Alice 20_000_000
aliceChainConfig <- chainConfigFor Alice workDir nodeSocket hydraScriptsTxId [] $ UnsafeContestationPeriod 100
let hydraNodeId = 1
let hydraTracer = contramap FromHydraNode tracer
(someExternalVk, someExternalSk) <- generate genKeyPair
withHydraNode hydraTracer aliceChainConfig workDir hydraNodeId aliceSk [] [1] $ \n1 -> do
send n1 $ input "Init" []
headId <- waitMatch (10 * blockTime) n1 $ headIsInitializingWith (Set.fromList [alice])
someUTxO <- seedFromFaucet node someExternalVk 10_000_000 (contramap FromFaucet tracer)
utxoToCommit <- seedFromFaucet node someExternalVk 5_000_000 (contramap FromFaucet tracer)
let someAddress = mkVkAddress networkId someExternalVk
let someOutput =
TxOut
someAddress
(lovelaceToValue $ Coin 2_000_000)
TxOutDatumNone
ReferenceScriptNone
buildTransaction networkId nodeSocket someAddress utxoToCommit (fst <$> UTxO.pairs someUTxO) [someOutput] >>= \case
Left e -> failure $ show e
Right body -> do
let unsignedTx = makeSignedTransaction [] body
let clientPayload =
FullCommitRequest
{ blueprintTx = unsignedTx
, utxo = utxoToCommit
}
res <-
runReq defaultHttpConfig $
req
POST
(http "127.0.0.1" /: "commit")
(ReqBodyJson clientPayload)
(Proxy :: Proxy (JsonResponse DraftCommitTxResponse))
(port $ 4000 + hydraNodeId)
let DraftCommitTxResponse{commitTx} = responseBody res
let signedTx = signTx someExternalSk commitTx
submitTx node signedTx
lockedUTxO <- waitMatch (10 * blockTime) n1 $ \v -> do
guard $ v ^? key "headId" == Just (toJSON headId)
guard $ v ^? key "tag" == Just "HeadIsOpen"
pure $ v ^? key "utxo"
lockedUTxO `shouldBe` Just (toJSON utxoToCommit)
where
RunningNode{networkId, nodeSocket, blockTime} = node
-- | Initialize open and close a head on a real network and ensure contestation
-- period longer than the time horizon is possible. For this it is enough that
-- we can close a head and not wait for the deadline.
canCloseWithLongContestationPeriod ::
Tracer IO EndToEndLog ->
FilePath ->
RunningNode ->
TxId ->
IO ()
canCloseWithLongContestationPeriod tracer workDir node hydraScriptsTxId = do
refuelIfNeeded tracer node Alice 100_000_000
-- Start hydra-node on chain tip
tip <- queryTip networkId nodeSocket
let oneWeek = UnsafeContestationPeriod (60 * 60 * 24 * 7)
aliceChainConfig <-
chainConfigFor Alice workDir nodeSocket hydraScriptsTxId [] oneWeek
<&> modifyConfig (\config -> config{networkId, startChainFrom = Just tip})
let hydraTracer = contramap FromHydraNode tracer
withHydraNode hydraTracer aliceChainConfig workDir 1 aliceSk [] [1] $ \n1 -> do
-- Initialize & open head
send n1 $ input "Init" []
headId <- waitMatch (10 * blockTime) n1 $ headIsInitializingWith (Set.fromList [alice])
-- Commit nothing for now
requestCommitTx n1 mempty >>= submitTx node
waitFor hydraTracer (10 * blockTime) [n1] $
output "HeadIsOpen" ["utxo" .= object mempty, "headId" .= headId]
-- Close head
send n1 $ input "Close" []
void $
waitMatch (10 * blockTime) n1 $ \v -> do
guard $ v ^? key "tag" == Just "HeadIsClosed"
traceRemainingFunds Alice
where
RunningNode{networkId, nodeSocket, blockTime} = node
traceRemainingFunds actor = do
(actorVk, _) <- keysFor actor
utxo <- queryUTxOFor networkId nodeSocket QueryTip actorVk
traceWith tracer RemainingFunds{actor = actorName actor, utxo}
canSubmitTransactionThroughAPI ::
Tracer IO EndToEndLog ->
FilePath ->
RunningNode ->
TxId ->
IO ()
canSubmitTransactionThroughAPI tracer workDir node hydraScriptsTxId =
(`finally` returnFundsToFaucet tracer node Alice) $ do
refuelIfNeeded tracer node Alice 25_000_000
aliceChainConfig <- chainConfigFor Alice workDir nodeSocket hydraScriptsTxId [] $ UnsafeContestationPeriod 100
let hydraNodeId = 1
let hydraTracer = contramap FromHydraNode tracer
withHydraNode hydraTracer aliceChainConfig workDir hydraNodeId aliceSk [] [hydraNodeId] $ \_ -> do
-- let's prepare a _user_ transaction from Bob to Carol
(cardanoBobVk, cardanoBobSk) <- keysFor Bob
(cardanoCarolVk, _) <- keysFor Carol
-- create output for Bob to be sent to carol
bobUTxO <- seedFromFaucet node cardanoBobVk 5_000_000 (contramap FromFaucet tracer)
let carolsAddress = mkVkAddress networkId cardanoCarolVk
bobsAddress = mkVkAddress networkId cardanoBobVk
carolsOutput =
TxOut
carolsAddress
(lovelaceToValue $ Coin 2_000_000)
TxOutDatumNone
ReferenceScriptNone
-- prepare fully balanced tx body
buildTransaction networkId nodeSocket bobsAddress bobUTxO (fst <$> UTxO.pairs bobUTxO) [carolsOutput] >>= \case
Left e -> failure $ show e
Right body -> do
let unsignedTx = makeSignedTransaction [] body
let unsignedRequest = toJSON unsignedTx
sendRequest hydraNodeId unsignedRequest
`shouldThrow` expectErrorStatus 400 (Just "MissingVKeyWitnessesUTXOW")
let signedTx = signTx cardanoBobSk unsignedTx
let signedRequest = toJSON signedTx
(sendRequest hydraNodeId signedRequest <&> responseBody)
`shouldReturn` TransactionSubmitted
where
RunningNode{networkId, nodeSocket} = node
sendRequest hydraNodeId tx =
runReq defaultHttpConfig $
req
POST
(http "127.0.0.1" /: "cardano-transaction")
(ReqBodyJson tx)
(Proxy :: Proxy (JsonResponse TransactionSubmitted))
(port $ 4000 + hydraNodeId)
-- | Three hydra nodes open a head and we assert that none of them sees errors.
-- This was particularly misleading when everyone tries to post the collect
-- transaction concurrently.
threeNodesNoErrorsOnOpen :: Tracer IO EndToEndLog -> FilePath -> RunningNode -> TxId -> IO ()
threeNodesNoErrorsOnOpen tracer tmpDir node@RunningNode{nodeSocket} hydraScriptsTxId = do
aliceKeys@(aliceCardanoVk, _) <- generate genKeyPair
bobKeys@(bobCardanoVk, _) <- generate genKeyPair
carolKeys@(carolCardanoVk, _) <- generate genKeyPair
let cardanoKeys = [aliceKeys, bobKeys, carolKeys]
hydraKeys = [aliceSk, bobSk, carolSk]
let contestationPeriod = UnsafeContestationPeriod 2
let hydraTracer = contramap FromHydraNode tracer
withHydraCluster hydraTracer tmpDir nodeSocket 1 cardanoKeys hydraKeys hydraScriptsTxId contestationPeriod $ \(leader :| rest) -> do
let clients = leader : rest
waitForNodesConnected hydraTracer 20 clients
-- Funds to be used as fuel by Hydra protocol transactions
seedFromFaucet_ node aliceCardanoVk 100_000_000 (contramap FromFaucet tracer)
seedFromFaucet_ node bobCardanoVk 100_000_000 (contramap FromFaucet tracer)
seedFromFaucet_ node carolCardanoVk 100_000_000 (contramap FromFaucet tracer)
send leader $ input "Init" []
void . waitForAllMatch 10 clients $
headIsInitializingWith (Set.fromList [alice, bob, carol])
mapConcurrently_ (\n -> requestCommitTx n mempty >>= submitTx node) clients
mapConcurrently_ shouldNotReceivePostTxError clients
where
-- Fail if a 'PostTxOnChainFailed' message is received.
shouldNotReceivePostTxError client@HydraClient{hydraNodeId} = do
err <- waitMatch 10 client $ \v -> do
case v ^? key "tag" of
Just "PostTxOnChainFailed" -> pure $ Left $ v ^? key "postTxError"
Just "HeadIsOpen" -> pure $ Right ()
_ -> Nothing
case err of
Left receivedError ->
failure $ "node " <> show hydraNodeId <> " should not receive error: " <> show receivedError
Right _headIsOpen ->
pure ()
-- | Two hydra node setup where Alice is wrongly configured to use Carol's
-- cardano keys instead of Bob's which will prevent him to be notified the
-- `HeadIsInitializing` but he should still receive some notification.
initWithWrongKeys :: FilePath -> Tracer IO EndToEndLog -> RunningNode -> TxId -> IO ()
initWithWrongKeys workDir tracer node@RunningNode{nodeSocket} hydraScriptsTxId = do
(aliceCardanoVk, _) <- keysFor Alice
(carolCardanoVk, _) <- keysFor Carol
aliceChainConfig <- chainConfigFor Alice workDir nodeSocket hydraScriptsTxId [Carol] (UnsafeContestationPeriod 2)
bobChainConfig <- chainConfigFor Bob workDir nodeSocket hydraScriptsTxId [Alice] (UnsafeContestationPeriod 2)
let hydraTracer = contramap FromHydraNode tracer
withHydraNode hydraTracer aliceChainConfig workDir 3 aliceSk [bobVk] [3, 4] $ \n1 -> do
withHydraNode hydraTracer bobChainConfig workDir 4 bobSk [aliceVk] [3, 4] $ \n2 -> do
seedFromFaucet_ node aliceCardanoVk 100_000_000 (contramap FromFaucet tracer)
send n1 $ input "Init" []
headId <-
waitForAllMatch 10 [n1] $
headIsInitializingWith (Set.fromList [alice, bob])
let expectedParticipants =
verificationKeyToOnChainId
<$> [aliceCardanoVk, carolCardanoVk]
-- We want the client to observe headId being opened without bob (node 2)
-- being part of it
participants <- waitMatch 10 n2 $ \v -> do
guard $ v ^? key "tag" == Just (Aeson.String "IgnoredHeadInitializing")
guard $ v ^? key "headId" == Just (toJSON headId)
v ^? key "participants" . _JSON
participants `shouldMatchList` expectedParticipants
-- * L2 scenarios
-- | Finds UTxO owned by given key in the head and creates transactions
-- respending it to the same address as fast as possible, forever.
-- NOTE: This relies on zero-fee protocol parameters.
respendUTxO :: HydraClient -> SigningKey PaymentKey -> NominalDiffTime -> IO ()
respendUTxO client sk delay = do
utxo <- getUTxO
forever $ respend utxo
where
getUTxO = do
send client $ input "GetUTxO" []
waitMatch 10 client $ \v -> do
guard $ v ^? key "tag" == Just "GetUTxOResponse"
v ^? key "utxo" >>= parseMaybe parseJSON
vk = getVerificationKey sk
respend utxo =
case UTxO.find (isVkTxOut vk) utxo of
Nothing -> fail "no utxo left to spend"
Just (txIn, txOut) ->
case mkSimpleTx (txIn, txOut) (txOutAddress txOut, txOutValue txOut) sk of
Left err ->
fail $ "mkSimpleTx failed: " <> show err
Right tx -> do
utxo' <- submitToHead (signTx sk tx)
threadDelay $ realToFrac delay
respend utxo'
submitToHead tx = do
send client $ input "NewTx" ["transaction" .= tx]
waitMatch 10 client $ \v -> do
guard $ v ^? key "tag" == Just "SnapshotConfirmed"
guard $
toJSON (txId tx)
`elem` (v ^.. key "snapshot" . key "confirmedTransactions" . values)
v ^? key "snapshot" . key "utxo" >>= parseMaybe parseJSON
-- * Utilities
-- | Refuel given 'Actor' with given 'Lovelace' if current marked UTxO is below that amount.
refuelIfNeeded ::
Tracer IO EndToEndLog ->
RunningNode ->
Actor ->
Coin ->
IO ()
refuelIfNeeded tracer node actor amount = do
(actorVk, _) <- keysFor actor
existingUtxo <- queryUTxOFor networkId nodeSocket QueryTip actorVk
traceWith tracer $ StartingFunds{actor = actorName actor, utxo = existingUtxo}
let currentBalance = selectLovelace $ balance @Tx existingUtxo
when (currentBalance < amount) $ do
utxo <- seedFromFaucet node actorVk amount (contramap FromFaucet tracer)
traceWith tracer $ RefueledFunds{actor = actorName actor, refuelingAmount = amount, utxo}
where
RunningNode{networkId, nodeSocket} = node
-- | Return the remaining funds to the faucet
returnFundsToFaucet ::
Tracer IO EndToEndLog ->
RunningNode ->
Actor ->
IO ()
returnFundsToFaucet tracer =
Faucet.returnFundsToFaucet (contramap FromFaucet tracer)
headIsInitializingWith :: Set Party -> Value -> Maybe HeadId
headIsInitializingWith expectedParties v = do
guard $ v ^? key "tag" == Just "HeadIsInitializing"
parties <- v ^? key "parties" >>= parseMaybe parseJSON
guard $ parties == expectedParties
headId <- v ^? key "headId"
parseMaybe parseJSON headId
expectErrorStatus ::
-- | Expected http status code
Int ->
-- | Optional string expected to be present somewhere in the response body
Maybe ByteString ->
-- | Expected exception
HttpException ->
Bool
expectErrorStatus
stat
mbodyContains
( VanillaHttpException
( L.HttpExceptionRequest
_
(L.StatusCodeException response chunk)
)
) =
L.responseStatus response == toEnum stat && not (B.null chunk) && assertBodyContains mbodyContains chunk
where
-- NOTE: The documentation says: Response body parameter MAY include the beginning of the response body so this can be partial.
-- https://hackage.haskell.org/package/http-client-0.7.13.1/docs/Network-HTTP-Client.html#t:HttpExceptionContent
assertBodyContains :: Maybe ByteString -> ByteString -> Bool
assertBodyContains (Just bodyContains) bodyChunk = bodyContains `isInfixOf` bodyChunk
assertBodyContains Nothing _ = False
expectErrorStatus _ _ _ = False