-
Notifications
You must be signed in to change notification settings - Fork 211
/
DSL.hs
3163 lines (2918 loc) · 100 KB
/
DSL.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 DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-simplifiable-class-constraints #-}
module Test.Integration.Framework.DSL
( Context(..)
, MnemonicLength(..)
, TxDescription(..)
-- * Steps
, request
, rawRequest
, unsafeRequest
, unsafeResponse
-- * Decoding errors
, decodeErrorInfo
-- * Expectations
, expectPathEventuallyExist
, expectSuccess
, expectError
, expectErrorMessage
, expectField
, expectListField
, expectListSize
, expectListSizeSatisfy
, expectResponseCode
, expectValidJSON
, expectCliField
, expectCliListField
, expectWalletUTxO
, between
, counterexample
, (.>=)
, (.<=)
, (.>)
, (.<)
, verify
, verifyMsg
, Headers(..)
, Payload(..)
, RequestException(..)
-- * Lens
, walletId
-- * Constants
, minUTxOValue
, slotLengthValue
, securityParameterValue
, epochLengthValue
, defaultTxTTL
, maximumCollateralInputCountByEra
, minimumCollateralPercentageByEra
-- * Create wallets
, restoreWalletFromPubKey
, emptyRandomWallet
, emptyRandomWalletMws
, emptyRandomWalletWithPasswd
, emptyIcarusWallet
, emptyIcarusWalletMws
, emptyByronWalletWith
, postWallet
, postWallet'
, postByronWallet
, emptyWallet
, emptyWalletWith
, emptyWalletAndMnemonic
, emptyWalletAndMnemonicAndSndFactor
, emptyWalletAndMnemonicWith
, emptyByronWalletFromXPrvWith
, rewardWallet
, postSharedWallet
, deleteSharedWallet
, getSharedWallet
, patchSharedWallet
, getSharedWalletKey
, postAccountKeyShared
, getAccountKeyShared
, getSomeVerificationKey
-- * Wallet helpers
, listFilteredWallets
, listFilteredByronWallets
, listFilteredSharedWallets
, getWalletIdFromSharedWallet
-- * Helpers
, (</>)
, (!!)
, computeApiCoinSelectionFee
, isValidDerivationPath
, isValidRandomDerivationPath
, genMnemonics
, genMnemonics'
, getFromResponse
, getFromResponseList
, json
, joinStakePool
, joinStakePoolUnsigned
, delegationFee
, quitStakePool
, quitStakePoolUnsigned
, selectCoins
, selectCoinsWith
, listAddresses
, signTx
, signSharedTx
, submitTx
, submitTxWithWid
, getWallet
, listTransactions
, listAllTransactions
, deleteAllWallets
, fixtureRawTx
, fixtureRandomWallet
, fixtureRandomWalletMws
, fixtureRandomWalletAddrs
, fixtureRandomWalletWith
, fixtureIcarusWallet
, fixtureIcarusWalletMws
, fixtureIcarusWalletAddrs
, fixtureIcarusWalletWith
, fixtureWallet
, fixtureWalletWith
, fixtureWalletWithMnemonics
, fixtureMultiAssetWallet
, fixtureMultiAssetRandomWallet
, fixtureMultiAssetIcarusWallet
, constFixtureWalletNoWait
, faucetAmt
, faucetUtxoAmt
, proc'
, postTx
, pickAnAsset
, mkTxPayloadMA
, waitForServer
, for
, utcIso8601ToText
, eventually
, eventuallyUsingDelay
, fixturePassphrase
, fixturePassphraseEncrypted
, waitForNextEpoch
, waitForTxImmutability
, waitAllTxsInLedger
, toQueryString
, withMethod
, withPathParam
, addField
, icarusAddresses
, randomAddresses
, shelleyAddresses
, pubKeyFromMnemonics
, rootPrvKeyFromMnemonics
, unsafeGetTransactionTime
, getTxId
, oneSecond
, getTTLSlots
, updateMetadataSource
, bracketSettings
, verifyMetadataSource
, triggerMaintenanceAction
, verifyMaintenanceAction
, genXPubs
, genXPubsBech32
, hexText
, fromHexText
, bech32Text
, accPubKeyFromMnemonics
, sharedAccPubKeyFromMnemonics
, submitSharedTxWithWid
-- * Delegation helpers
, notDelegating
, delegating
, getSlotParams
, arbitraryStake
-- * CLI
, commandName
, command
, cardanoWalletCLI
, generateMnemonicsViaCLI
, createWalletViaCLI
, createWalletFromPublicKeyViaCLI
, deleteWalletViaCLI
, getWalletUtxoSnapshotViaCLI
, getWalletUtxoStatisticsViaCLI
, getWalletViaCLI
, createAddressViaCLI
, importAddressViaCLI
, listAddressesViaCLI
, listStakePoolsViaCLI
, listWalletsViaCLI
, updateWalletNameViaCLI
, updateWalletPassphraseViaCLI
, updateWalletPassphraseWithMnemonicViaCLI
, postTransactionViaCLI
, postTransactionFeeViaCLI
, listTransactionsViaCLI
, postExternalTransactionViaCLI
, deleteTransactionViaCLI
, getTransactionViaCLI
-- utilities
, getRetirementEpoch
, replaceStakeKey
-- * Re-exports
, runResourceT
, ResourceT
) where
import Prelude
import Cardano.Address.Derivation
( XPub, xpubFromBytes, xpubToBytes )
import Cardano.CLI
( Port (..) )
import Cardano.Mnemonic
( ConsistentEntropy
, EntropySize
, MkSomeMnemonic (..)
, Mnemonic
, MnemonicWords
, SomeMnemonic (..)
, entropyToMnemonic
, genEntropy
, mnemonicToText
)
import Cardano.Pool.Metadata.Types
( PoolMetadataGCStatus (..) )
import Cardano.Pool.Types
( PoolId (..) )
import Cardano.Wallet.Api.Types
( AddressAmount
, ApiAccountKeyShared
, ApiAccountSharedPublicKey (..)
, ApiActiveSharedWallet
, ApiAddress
, ApiBlockReference (..)
, ApiByronWallet
, ApiCoinSelection
, ApiEra (..)
, ApiFee
, ApiMaintenanceAction (..)
, ApiNetworkInformation
, ApiNetworkParameters (..)
, ApiPoolSpecifier
, ApiSerialisedTransaction
, ApiSharedWallet (..)
, ApiT (..)
, ApiTransaction
, ApiTxId (ApiTxId)
, ApiUtxoStatistics (..)
, ApiVerificationKeyShared
, ApiVerificationKeyShelley (..)
, ApiWallet
, ApiWalletDelegation (..)
, ApiWalletDelegationNext (..)
, ApiWalletDelegationStatus (..)
, DecodeAddress (..)
, DecodeStakeAddress (..)
, EncodeAddress (..)
, Iso8601Time (..)
, KeyFormat
, SettingsPutData (..)
, WalletStyle (..)
, insertedAt
)
import Cardano.Wallet.Api.Types.Error
( ApiErrorInfo (..) )
import Cardano.Wallet.Api.Types.SchemaMetadata
( TxMetadataSchema, toSimpleMetadataFlag )
import Cardano.Wallet.Compat
( (^?) )
import Cardano.Wallet.Pools
( EpochInfo, StakePool )
import Cardano.Wallet.Primitive.AddressDerivation
( Depth (..)
, DerivationIndex (..)
, DerivationType (..)
, HardDerivation (..)
, Index (..)
, NetworkDiscriminant (..)
, PaymentAddress (..)
, PersistPublicKey (..)
, Role (..)
, WalletKey (..)
, fromHex
, hex
)
import Cardano.Wallet.Primitive.AddressDerivation.Byron
( ByronKey (..) )
import Cardano.Wallet.Primitive.AddressDerivation.Icarus
( IcarusKey )
import Cardano.Wallet.Primitive.AddressDerivation.Shelley
( ShelleyKey )
import Cardano.Wallet.Primitive.AddressDiscovery.Sequential
( coinTypeAda )
import Cardano.Wallet.Primitive.AddressDiscovery.Shared
( CredentialType (..) )
import Cardano.Wallet.Primitive.Passphrase
( Passphrase (..), preparePassphrase )
import Cardano.Wallet.Primitive.Passphrase.Legacy
( encryptPassphraseTestingOnly )
import Cardano.Wallet.Primitive.SyncProgress
( SyncProgress (..) )
import Cardano.Wallet.Primitive.Types
( ActiveSlotCoefficient (..)
, EpochLength (..)
, EpochNo
, PoolMetadataSource
, Settings
, SlotLength (..)
, SlotNo (..)
, SlottingParameters (..)
, SortOrder (..)
, WalletId (..)
)
import Cardano.Wallet.Primitive.Types.Address
( Address (..) )
import Cardano.Wallet.Primitive.Types.Coin
( Coin (..) )
import Cardano.Wallet.Primitive.Types.Hash
( Hash (..) )
import Cardano.Wallet.Primitive.Types.Tx
( SealedTx (..), TxStatus (..) )
import Cardano.Wallet.Primitive.Types.Tx.Constraints
( txOutMaxCoin, txOutMinCoin )
import Cardano.Wallet.Primitive.Types.Tx.TxIn
( TxIn (..) )
import Cardano.Wallet.Primitive.Types.Tx.TxOut
( TxOut (..) )
import Cardano.Wallet.Primitive.Types.UTxO
( UTxO (..) )
import Cardano.Wallet.Primitive.Types.UTxOStatistics
( HistogramBar (..), UTxOStatistics (..) )
import "cardano-addresses" Codec.Binary.Encoding
( AbstractEncoding (..), encode )
import Control.Arrow
( second )
import Control.Monad
( forM_, join, replicateM, unless, void, (>=>) )
import Control.Monad.IO.Unlift
( MonadIO, MonadUnliftIO (..), liftIO )
import Control.Monad.Trans.Resource
( ResourceT, allocate, runResourceT )
import Control.Retry
( capDelay, constantDelay, retrying )
import Crypto.Hash
( Blake2b_160, Digest, digestFromByteString )
import Crypto.Hash.Utils
( blake2b224 )
import Data.Aeson
( FromJSON, ToJSON, Value, (.=) )
import Data.Aeson.QQ
( aesonQQ )
import Data.ByteString
( ByteString )
import Data.Either.Extra
( eitherToMaybe )
import Data.Foldable
( toList )
import Data.Function
( (&) )
import Data.Functor.Identity
( Identity (..) )
import Data.Generics.Internal.VL.Lens
( Lens', lens, set, view, (^.) )
import Data.Generics.Internal.VL.Traversal
( Traversal' )
import Data.Generics.Labels
()
import Data.Generics.Product.Typed
( HasType, typed )
import Data.IORef
( newIORef, readIORef, writeIORef )
import Data.List
( isPrefixOf )
import Data.List.NonEmpty
( NonEmpty )
import Data.Maybe
( fromJust, fromMaybe )
import Data.Monoid
( Sum (..) )
import Data.Proxy
( Proxy (..) )
import Data.Quantity
( Quantity (..) )
import Data.Set
( Set )
import Data.Text
( Text )
import Data.Text.Class
( FromText (..), ToText (..) )
import Data.Time
( NominalDiffTime, UTCTime )
import Data.Time.Text
( iso8601ExtendedUtc, utcTimeToText )
import Data.Word
( Word16, Word32 )
import Fmt
( indentF, (+|), (|+) )
import Language.Haskell.TH.Quote
( QuasiQuoter )
import Network.HTTP.Types.Method
( Method )
import Numeric.Natural
( Natural )
import System.Command
( CmdOption (..), CmdResult, Exit (..), Stderr, Stdout (..), command )
import System.Directory
( doesPathExist )
import System.Exit
( ExitCode (..) )
import System.IO
( hClose, hFlush, hPutStr )
import Test.Hspec
( Expectation, HasCallStack )
import Test.Hspec.Expectations.Lifted
( expectationFailure, shouldBe, shouldContain, shouldNotBe, shouldSatisfy )
import Test.Hspec.Extra
( appendFailureReason, counterexample )
import Test.HUnit.Lang
( HUnitFailure (..) )
import Test.Integration.Faucet
( NextWallet, nextTxBuilder, nextWallet, seqMnemonics )
import Test.Integration.Framework.Context
( Context (..), TxDescription (..) )
import Test.Integration.Framework.Request
( Headers (..)
, Payload (..)
, RequestException (..)
, rawRequest
, request
, unsafeRequest
)
import Test.Utils.Pretty
( Pretty (..), pShowBuilder )
import UnliftIO.Async
( async, race, wait )
import UnliftIO.Concurrent
( threadDelay )
import UnliftIO.Exception
( Exception (..), SomeException (..), catch, throwIO, throwString, try )
import UnliftIO.Process
( CreateProcess (..)
, StdStream (..)
, proc
, waitForProcess
, withCreateProcess
)
import Web.HttpApiData
( ToHttpApiData (..) )
import qualified Cardano.Wallet.Api.Link as Link
import qualified Cardano.Wallet.Primitive.AddressDerivation.Byron as Byron
import qualified Cardano.Wallet.Primitive.AddressDerivation.Icarus as Icarus
import qualified Cardano.Wallet.Primitive.AddressDerivation.Shared as Shared
import qualified Cardano.Wallet.Primitive.AddressDerivation.Shelley as Shelley
import qualified Cardano.Wallet.Primitive.Passphrase.Types as W
import qualified Cardano.Wallet.Primitive.Types.Coin as Coin
import qualified Cardano.Wallet.Primitive.Types.TokenBundle as TokenBundle
import qualified Cardano.Wallet.Primitive.Types.TokenMap as TokenMap
import qualified Cardano.Wallet.Primitive.Types.TokenQuantity as TokenQuantity
import qualified Cardano.Wallet.Primitive.Types.UTxOStatistics as UTxOStatistics
import qualified Codec.Binary.Bech32 as Bech32
import qualified Codec.Binary.Bech32.TH as Bech32
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Key as Aeson
import qualified Data.ByteArray as BA
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as BL8
import qualified Data.Foldable as F
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.IO as TIO
import qualified Network.HTTP.Types.Status as HTTP
--
-- API response expectations
--
-- | Expect a successful response, without any further assumptions.
expectSuccess :: MonadIO m => (s, Either RequestException a) -> m ()
expectSuccess = either wantedSuccessButError (const $ pure ()) . snd
-- | Expect an error response, without any further assumptions.
expectError :: (MonadIO m, Show a) => (s, Either RequestException a) -> m ()
expectError = either (const $ pure ()) wantedErrorButSuccess . snd
-- | Expect an error response, without any further assumptions.
expectErrorMessage
:: (HasCallStack, MonadIO m, Show a)
=> String
-> (s, Either RequestException a)
-> m ()
expectErrorMessage want = either expectation wantedErrorButSuccess . snd
where
expectation msg = fmt msg `shouldContain` want
fmt = \case
DecodeFailure res msg -> msg ++ "\n" ++ BL8.unpack res
ClientError val -> BL8.unpack $ Aeson.encode val
RawClientError val -> BL8.unpack val
HttpException err -> show err
-- | Decodes the information about an error into an 'ApiErrorInfo' value.
decodeErrorInfo
:: (HasCallStack, MonadIO m, Show a)
=> (s, Either RequestException a)
-> m ApiErrorInfo
decodeErrorInfo (_, response) =
case response of
Left (ClientError value) ->
maybe decodeFailure pure $ Aeson.decode $ Aeson.encode value
somethingElse ->
error $ unwords
[ "decodeErrorInfo:"
, "Expected a 'ClientError', but encountered something else:"
, show somethingElse
]
where
decodeFailure = error $ unwords
[ "decodeErrorInfo:"
, "Unable to decode 'ApiErrorInfo' value"
]
-- | Expect a given response code on the response.
expectResponseCode
:: (HasCallStack, MonadUnliftIO m, Show a)
=> HTTP.Status
-> (HTTP.Status, a)
-> m ()
expectResponseCode expected (actual, a) =
counterexample ("From the following response: " <> show (Pretty a)) $
if actual == expected
then pure ()
else actual `shouldBe` expected
expectField
:: (HasCallStack, MonadIO m)
=> Traversal' s a
-> (a -> Expectation)
-> (HTTP.Status, Either RequestException s)
-> m ()
expectField getter predicate (_, res) = case res of
Left e -> wantedSuccessButError e
Right s -> liftIO $ case s ^? getter of
Nothing -> expectationFailure
"could not traverse response to test expectations"
Just a -> predicate a
expectListField
:: (HasCallStack, MonadIO m)
=> Int
-> Traversal' s a
-> (a -> Expectation)
-> (HTTP.Status, Either RequestException [s])
-> m ()
expectListField i getter predicate (c, res) = liftIO $ case res of
Left e -> wantedSuccessButError e
Right xs
| length xs > i ->
expectField getter predicate (c, Right (xs !! i))
| otherwise -> expectationFailure $
"expectListField: trying to access the #" <> show i <>
" element from a list but there's none! "
-- | Expects data list returned by the API to be of certain length
expectListSize
:: (HasCallStack, MonadIO m, Foldable xs)
=> Int
-> (HTTP.Status, Either RequestException (xs a))
-> m ()
expectListSize l (_, res) = liftIO $ case res of
Left e -> wantedSuccessButError e
Right xs -> length (toList xs) `shouldBe` l
-- | Expects data list returned by the API to be of certain length
expectListSizeSatisfy
:: (HasCallStack, MonadIO m, Foldable xs)
=> (Int -> Bool)
-> (HTTP.Status, Either RequestException (xs a))
-> m ()
expectListSizeSatisfy cond (_, res) = liftIO $ case res of
Left e -> wantedSuccessButError e
Right xs -> length (toList xs) `shouldSatisfy` cond
-- | Expects wallet UTxO statistics from the request to be equal to
-- pre-calculated statistics.
expectWalletUTxO
:: (HasCallStack, MonadIO m)
=> [Natural]
-> Either RequestException ApiUtxoStatistics
-> m ()
expectWalletUTxO coins = \case
Left e -> wantedSuccessButError e
Right stats -> do
let addr = Address "ARBITRARY"
let constructUtxoEntry idx c =
( TxIn (Hash "ARBITRARY") idx
, TxOut addr (TokenBundle.fromCoin $ Coin c)
)
let utxo = UTxO $ Map.fromList $ zipWith constructUtxoEntry [0..] coins
let (UTxOStatistics hist stakes bType) = UTxOStatistics.compute utxo
let distr = Map.fromList $ map (\(HistogramBar k v)-> (k,v)) hist
(ApiUtxoStatistics (Quantity (fromIntegral stakes)) (ApiT bType) distr)
`shouldBe` stats
--
-- CLI output expectations
--
-- | Expects a given string to be a valid JSON output corresponding to some
-- given data-type 'a'. Returns this type if successful.
expectValidJSON
:: forall m a. (HasCallStack, FromJSON a, MonadIO m)
=> Proxy a
-> String
-> m a
expectValidJSON _ str = liftIO $
case Aeson.eitherDecode @a (BL.fromStrict $ T.encodeUtf8 $ T.pack str) of
Left e ->
expectationFailure' $ "expected valid JSON but failed decoding: " <> show e
Right a -> return a
expectCliListField
:: (HasCallStack, MonadIO m)
=> Int
-> Lens' s a
-> (a -> Expectation)
-> [s]
-> m ()
expectCliListField i getter predicate xs
| length xs > i = expectCliField getter predicate (xs !! i)
| otherwise = liftIO . expectationFailure $
"expectCliListField: trying to access the #" <> show i <>
" element from a list but there's none! "
expectCliField :: MonadIO m => Lens' s a -> (a -> Expectation) -> s -> m ()
expectCliField getter predicate out = do
let a = (view getter out)
liftIO $ predicate a
-- | A file is eventually created on the given location
expectPathEventuallyExist :: HasCallStack => FilePath -> IO ()
expectPathEventuallyExist filepath = do
handle <- async doesPathExistNow
winner <- race (threadDelay (60 * oneSecond)) (wait handle)
case winner of
Left _ -> expectationFailure $
"waited more than 60s for " <> filepath <> " to be created!"
Right _ ->
return ()
where
doesPathExistNow = do
doesPathExist filepath >>= \case
True ->
return ()
False ->
threadDelay (oneSecond `div` 2) >> doesPathExistNow
-- Lenses
--
walletId :: HasType (ApiT WalletId) s => Lens' s Text
walletId =
lens _get _set
where
_get :: HasType (ApiT WalletId) s => s -> Text
_get = T.pack . show . getWalletId . getApiT . view typed
_set :: HasType (ApiT WalletId) s => s -> Text -> s
_set s v = set typed (ApiT $ WalletId (unsafeCreateDigest v)) s
--
-- Constants
--
-- | Minimum UTxO parameter for the test cluster.
--
-- The value returned by this function is only appropriate for a very minimal
-- output, where:
--
-- - the output has no assets other than ada.
-- - the output uses a Shelley-era address of the length typically used in
-- the integration test suite.
-- - the output has no datum hash.
--
-- This value will almost certainly not be correct for outputs with non-ada
-- assets, for outputs with longer addresses, or outputs with a datum hash.
--
-- In those cases, a larger value will be required. The precise value can be
-- determined by calling one of the endpoints that returns an 'ApiFee' object,
-- and inspecting the 'minimumCoins' field.
--
minUTxOValue :: ApiEra -> Natural
minUTxOValue e
| e >= ApiBabbage = 978_370
| e >= ApiAlonzo = 999_978
| otherwise = 1_000_000
-- | Parameter in test cluster shelley genesis.
--
-- This space left blank intentionally.
slotLengthValue :: NominalDiffTime
slotLengthValue = 0.2
-- | Parameter in test cluster shelley genesis.
securityParameterValue :: Word32
securityParameterValue = 10
-- | Parameter in test cluster shelley genesis.
epochLengthValue :: Word32
epochLengthValue = 160
-- | Wallet server's chosen transaction TTL value (in seconds) when none is
-- given.
defaultTxTTL :: NominalDiffTime
defaultTxTTL = 7_200
maximumCollateralInputCountByEra :: ApiEra -> Word16
maximumCollateralInputCountByEra = \case
ApiByron -> 0
ApiShelley -> 0
ApiAllegra -> 0
ApiMary -> 0
-- value from alonzo-genesis.yaml:
ApiAlonzo -> 3
ApiBabbage -> 3
minimumCollateralPercentageByEra :: ApiEra -> Natural
minimumCollateralPercentageByEra = \case
ApiByron -> 0
ApiShelley -> 0
ApiAllegra -> 0
ApiMary -> 0
-- value from alonzo-genesis.yaml:
ApiAlonzo -> 150
ApiBabbage -> 150
--
-- Helpers
--
-- | Computes the effective fee for an `ApiCoinSelection` value.
--
-- The `ApiCoinSelection` type doesn't include a field to indicate the fee.
--
-- This function computes the effective fee by subtracting the total output
-- value from the total input value.
--
computeApiCoinSelectionFee :: ApiCoinSelection n -> Coin
computeApiCoinSelectionFee selection
| feeIsValid =
Coin $ fromIntegral fee
| otherwise =
error $ unlines
[ "Unable to compute fee of ApiCoinSelection:"
, "fee:"
, show fee
, "balanceOfInputs:"
, show balanceOfInputs
, "balanceOfOutputs:"
, show balanceOfOutputs
, "balanceOfChange:"
, show balanceOfChange
, "balanceOfRewardWithdrawals"
, show balanceOfRewardWithdrawals
, "balanceOfDeposits"
, show balanceOfDeposits
]
where
fee :: Integer
fee
= balanceOfInputs
+ balanceOfRewardWithdrawals
- balanceOfOutputs
- balanceOfChange
- balanceOfDeposits
feeIsValid :: Bool
feeIsValid = (&&)
(fee >= Coin.toInteger txOutMinCoin)
(fee <= Coin.toInteger txOutMaxCoin)
balanceOfInputs
= selection
& view #inputs
& F.foldMap (Sum . quantityToInteger . view #amount)
& getSum
balanceOfOutputs
= selection
& view #outputs
& F.foldMap (Sum . quantityToInteger . view #amount)
& getSum
balanceOfChange
= selection
& view #change
& F.foldMap (Sum . quantityToInteger . view #amount)
& getSum
balanceOfRewardWithdrawals
= selection
& view #withdrawals
& F.foldMap (Sum . quantityToInteger . view #amount)
& getSum
balanceOfDeposits
= selection
& view #depositsTaken
& F.foldMap (Sum . quantityToInteger)
& getSum
quantityToInteger :: Quantity "lovelace" Natural -> Integer
quantityToInteger (Quantity n) = fromIntegral n
isValidDerivationPath
:: Index 'Hardened 'PurposeK
-> NonEmpty (ApiT DerivationIndex)
-> Bool
isValidDerivationPath purpose path =
( length path == 5 )
&&
( [ ApiT $ DerivationIndex $ getIndex purpose
, ApiT $ DerivationIndex $ getIndex coinTypeAda
, ApiT $ DerivationIndex $ getIndex @'Hardened minBound
] `isPrefixOf` NE.toList path
)
isValidRandomDerivationPath :: NonEmpty (ApiT DerivationIndex) -> Bool
isValidRandomDerivationPath path =
( length path == 2 )
&&
( [ ApiT $ DerivationIndex $ getIndex @'Hardened minBound
] `isPrefixOf` NE.toList path
)
pickAnAsset :: TokenMap.TokenMap -> ((Text, Text), Natural)
pickAnAsset tm = case TokenMap.toFlatList tm of
(TokenBundle.AssetId pid an, TokenQuantity.TokenQuantity q):_ ->
((toText pid, toText an), q)
_ -> error "pickAnAsset: empty TokenMap"
-- Like mkTxPayload, except that assets are included in the payment.
-- Asset amounts are specified by ((PolicyId Hex, AssetName Hex), amount).
mkTxPayloadMA
:: forall n m.
( MonadUnliftIO m
, EncodeAddress n
)
=> (ApiT Address, Proxy n)
-> Natural
-> [((Text, Text), Natural)]
-> Text
-> m Payload
mkTxPayloadMA destination coin val passphrase = do
let assetJson ((pid, name), q) = [aesonQQ|{
"policy_id": #{pid},
"asset_name": #{name},
"quantity": #{q}
}|]
return $ Json [aesonQQ|{
"payments": [{
"address": #{destination},
"amount": {
"quantity": #{coin},
"unit": "lovelace"
},
"assets": #{map assetJson val}
}],
"passphrase": #{passphrase}
}|]
postTx
:: forall n w m.
( DecodeAddress n
, DecodeStakeAddress n
, EncodeAddress n
, MonadUnliftIO m
)
=> Context
-> (w, w -> (Method, Text), Text)
-> ApiWallet
-> Natural
-> m (HTTP.Status, Either RequestException (ApiTransaction n))
postTx ctx (wSrc, postTxEndp, pass) wDest amt = do
addrs <- listAddresses @n ctx wDest
let destination = (addrs !! 1) ^. #id
let payload = Json [aesonQQ|{
"payments": [{
"address": #{destination},
"amount": {
"quantity": #{amt},
"unit": "lovelace"
}
}],
"passphrase": #{pass}
}|]
r <- request @(ApiTransaction n) ctx (postTxEndp wSrc) Default payload
expectResponseCode HTTP.status202 r
return r
updateMetadataSource :: MonadUnliftIO m => Context -> Text -> m ()
updateMetadataSource ctx t = do
r <- request @SettingsPutData ctx Link.putSettings Default payload
expectResponseCode HTTP.status204 r
where
payload = Json [aesonQQ| {
"settings": {
"pool_metadata_source": #{t}
}
} |]
bracketSettings :: MonadUnliftIO m => Context -> m () -> m ()
bracketSettings ctx action = do
r@(_, response) <- request @(ApiT Settings) ctx Link.getSettings Default Empty
expectResponseCode HTTP.status200 r
case response of
Left e -> wantedSuccessButError e
Right s -> do
action
r' <- request @SettingsPutData ctx Link.putSettings Default
(Json $ Aeson.toJSON $ SettingsPutData s)
expectResponseCode HTTP.status204 r'
verifyMetadataSource
:: MonadUnliftIO m
=> Context
-> PoolMetadataSource
-> m ()
verifyMetadataSource ctx s = do
r <- request @(ApiT Settings) ctx Link.getSettings Default Empty
expectResponseCode HTTP.status200 r
expectField (#getApiT . #poolMetadataSource) (`shouldBe` s) r
triggerMaintenanceAction :: MonadUnliftIO m => Context -> Text -> m ()
triggerMaintenanceAction ctx a = do
r <- request @ApiMaintenanceAction ctx Link.postPoolMaintenance Default payload
expectResponseCode HTTP.status204 r
where
payload = Json [aesonQQ| { "maintenance_action": #{a} } |]
verifyMaintenanceAction
:: MonadUnliftIO m
=> Context
-> PoolMetadataGCStatus
-> m ()
verifyMaintenanceAction ctx s = do
r <- request @ApiMaintenanceAction ctx Link.getPoolMaintenance Default Empty
expectResponseCode HTTP.status200 r
expectField (#gcStakePools . #getApiT) (`shouldBe` s) r
data MnemonicLength = M9 | M12 | M15 | M18 | M21 | M24 deriving (Show)
genMnemonics :: MnemonicLength -> IO [Text]
genMnemonics M9 = genMnemonics' @9
genMnemonics M12 = genMnemonics' @12
genMnemonics M15 = genMnemonics' @15
genMnemonics M18 = genMnemonics' @18
genMnemonics M21 = genMnemonics' @21
genMnemonics M24 = genMnemonics' @24
genMnemonics'
:: forall mw ent csz m.
( ConsistentEntropy ent mw csz
, ent ~ EntropySize mw
, mw ~ MnemonicWords ent
, MonadIO m
)
=> m [Text]
genMnemonics' =
liftIO $ mnemonicToText . entropyToMnemonic @mw <$> genEntropy
accPubKeyFromMnemonics
:: SomeMnemonic
-> Maybe SomeMnemonic
-> Word32
-> Passphrase "encryption"
-> Text
accPubKeyFromMnemonics mnemonic1 mnemonic2 ix passphrase =
T.decodeUtf8 $ serializeXPub $ publicKey $
deriveAccountPrivateKey passphrase rootXPrv (Index $ 2_147_483_648 + ix)
where
rootXPrv = Shared.generateKeyFromSeed (mnemonic1, mnemonic2) passphrase