-
Notifications
You must be signed in to change notification settings - Fork 212
/
Launch.hs
1704 lines (1557 loc) · 60.6 KB
/
Launch.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 DataKinds #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
-- NOTE Temporary until we can fully enable the cluster
{-# OPTIONS_GHC -fno-warn-unused-top-binds #-}
-- |
-- Copyright: © 2018-2020 IOHK
-- License: Apache-2.0
--
-- Provides a function to launch cardano-node for /testing/.
module Cardano.Wallet.Shelley.Launch
( -- * Integration Launcher
withCluster
, withBFTNode
, withStakePool
, NodeParams (..)
, singleNodeParams
, PoolConfig (..)
, RunningNode (..)
-- * Faucets
, sendFaucetFundsTo
, moveInstantaneousRewardsTo
, oneMillionAda
-- * Utils
, NetworkConfiguration (..)
, nodeSocketOption
, networkConfigurationOption
, parseGenesisData
, withTempDir
, withSystemTempDir
-- * Logging
, ClusterLog (..)
) where
import Prelude
import Cardano.Address.Derivation
( XPub, xpubPublicKey )
import Cardano.Api.Shelley.Genesis
( ShelleyGenesis (..) )
import Cardano.BM.Data.Output
( ScribeDefinition (..)
, ScribeFormat (..)
, ScribeKind (..)
, ScribePrivacy (..)
)
import Cardano.BM.Data.Severity
( Severity (..) )
import Cardano.BM.Data.Tracer
( HasPrivacyAnnotation (..), HasSeverityAnnotation (..) )
import Cardano.Chain.Genesis
( GenesisData (..), readGenesisData )
import Cardano.CLI
( optionT )
import Cardano.Launcher
( LauncherLog, ProcessHasExited (..) )
import Cardano.Launcher.Node
( CardanoNodeConfig (..)
, CardanoNodeConn (..)
, NodePort (..)
, withCardanoNode
)
import Cardano.Wallet.Logging
( BracketLog, bracketTracer )
import Cardano.Wallet.Network.Ports
( randomUnusedTCPPorts )
import Cardano.Wallet.Primitive.AddressDerivation
( NetworkDiscriminant (..), hex )
import Cardano.Wallet.Primitive.Types
( Block (..)
, Coin (..)
, EpochLength (..)
, EpochNo (..)
, GenesisParameters (..)
, NetworkParameters (..)
, PoolId (..)
, ProtocolMagic (..)
, SlotLength (..)
, TxOut
)
import Cardano.Wallet.Shelley
( SomeNetworkDiscriminant (..) )
import Cardano.Wallet.Shelley.Compatibility
( NodeVersionData )
import Cardano.Wallet.Unsafe
( unsafeFromHex, unsafeRunExceptT )
import Control.Arrow
( first, second )
import Control.Concurrent
( threadDelay )
import Control.Concurrent.Async
( async, link, race )
import Control.Concurrent.Chan
( newChan, readChan, writeChan )
import Control.Concurrent.MVar
( MVar, modifyMVar, newMVar, putMVar, takeMVar )
import Control.Exception
( SomeException, finally, handle, throwIO )
import Control.Monad
( forM, forM_, replicateM, replicateM_, unless, void, when, (>=>) )
import Control.Monad.Fail
( MonadFail )
import Control.Monad.Trans.Except
( ExceptT (..), withExceptT )
import Control.Retry
( constantDelay, limitRetriesByCumulativeDelay, retrying )
import Control.Tracer
( Tracer (..), contramap, traceWith )
import Crypto.Hash.Utils
( blake2b256 )
import Data.Aeson
( FromJSON (..), toJSON, (.:), (.=) )
import Data.ByteArray.Encoding
( Base (..), convertToBase )
import Data.ByteString
( ByteString )
import Data.ByteString.Base58
( bitcoinAlphabet, decodeBase58 )
import Data.Either
( isLeft, isRight )
import Data.Function
( (&) )
import Data.Functor
( ($>), (<&>) )
import Data.List
( isInfixOf, nub, permutations, sort )
import Data.Maybe
( catMaybes, fromMaybe )
import Data.Proxy
( Proxy (..) )
import Data.Text
( Text )
import Data.Text.Class
( ToText (..) )
import Data.Time.Clock
( NominalDiffTime, UTCTime, addUTCTime, getCurrentTime )
import Data.Time.Clock.POSIX
( posixSecondsToUTCTime, utcTimeToPOSIXSeconds )
import GHC.TypeLits
( KnownNat, Nat, SomeNat (..), someNatVal )
import Options.Applicative
( Parser, flag', help, long, metavar, (<|>) )
import Ouroboros.Consensus.Shelley.Node
( sgNetworkMagic )
import Ouroboros.Consensus.Shelley.Protocol
( TPraosStandardCrypto )
import Ouroboros.Network.Magic
( NetworkMagic (..) )
import Ouroboros.Network.NodeToClient
( NodeToClientVersionData (..), nodeToClientCodecCBORTerm )
import System.Directory
( copyFile, createDirectory, createDirectoryIfMissing )
import System.Environment
( lookupEnv, setEnv )
import System.Exit
( ExitCode (..) )
import System.FilePath
( (</>) )
import System.IO.Temp
( createTempDirectory, getCanonicalTemporaryDirectory, withTempDirectory )
import System.IO.Unsafe
( unsafePerformIO )
import System.Process
( readProcess, readProcessWithExitCode )
import Test.Utils.Paths
( getTestData )
import Test.Utils.StaticServer
( withStaticServer )
import qualified Cardano.Chain.Common as Byron
import qualified Cardano.Chain.UTxO as Legacy
import qualified Cardano.Wallet.Byron.Compatibility as Byron
import qualified Cardano.Wallet.Shelley.Compatibility as Shelley
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Types as Aeson
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.HashMap.Strict as HM
import qualified Data.Map.Strict as Map
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Vector as V
import qualified Data.Yaml as Yaml
-- | Shelley hard fork network configuration has two genesis datas.
-- As a special case for mainnet, we hardcode the byron genesis data.
data NetworkConfiguration where
-- | Mainnet does not have network discrimination.
MainnetConfig
:: NetworkConfiguration
-- | Testnet has network magic.
TestnetConfig
:: FilePath
-- ^ Genesis data in JSON format, for byron era.
-> NetworkConfiguration
-- | Staging does not have network discrimination.
StagingConfig
:: FilePath
-- ^ Genesis data in JSON format, for byron era.
-> NetworkConfiguration
deriving (Show, Eq)
-- | --node-socket=FILE
nodeSocketOption :: Parser FilePath
nodeSocketOption = optionT $ mempty
<> long "node-socket"
<> metavar "FILE"
<> help "Path to the node's domain socket."
-- | --mainnet --shelley-genesis=FILE
-- --testnet --byron-genesis=FILE --shelley-genesis=FILE
-- --staging --byron-genesis=FILE --shelley-genesis=FILE
networkConfigurationOption :: Parser NetworkConfiguration
networkConfigurationOption = mainnet <|> testnet <|> staging
where
mainnet = mainnetFlag
testnet = TestnetConfig <$> genesisFileOption "byron" "testnet"
staging = StagingConfig <$> genesisFileOption "byron" "staging"
mainnetFlag = flag' MainnetConfig $ mempty
<> long "mainnet"
<> help "Use Cardano mainnet protocol"
genesisFileOption :: String -> String -> Parser FilePath
genesisFileOption era net = optionT $ mempty
<> long net
<> metavar "FILE"
<> help ("Path to the " <> era <> " genesis data in JSON format.")
someCustomDiscriminant
:: (forall (pm :: Nat). KnownNat pm => Proxy pm -> SomeNetworkDiscriminant)
-> ProtocolMagic
-> (SomeNetworkDiscriminant, NodeVersionData)
someCustomDiscriminant mkSomeNetwork pm@(ProtocolMagic n) =
case someNatVal (fromIntegral n) of
Just (SomeNat proxy) ->
( mkSomeNetwork proxy
, Shelley.testnetVersionData pm
)
_ -> error "networkDiscriminantFlag: failed to convert \
\ProtocolMagic to SomeNat."
parseGenesisData
:: NetworkConfiguration
-> ExceptT String IO
(SomeNetworkDiscriminant, NetworkParameters, NodeVersionData, Block)
parseGenesisData = \case
MainnetConfig -> do
pure
( SomeNetworkDiscriminant $ Proxy @'Mainnet
, Byron.mainnetNetworkParameters
, Byron.mainnetVersionData
, Byron.emptyGenesis (genesisParameters Byron.mainnetNetworkParameters)
)
TestnetConfig byronGenesisFile -> do
(genesisData, genesisHash) <-
withExceptT show $ readGenesisData byronGenesisFile
let mkSomeNetwork
:: forall (pm :: Nat). KnownNat pm
=> Proxy pm
-> SomeNetworkDiscriminant
mkSomeNetwork _ = SomeNetworkDiscriminant $ Proxy @('Testnet pm)
let pm = Byron.fromProtocolMagicId $ gdProtocolMagicId genesisData
let (discriminant, vData) = someCustomDiscriminant mkSomeNetwork pm
let (np, outs) = Byron.fromGenesisData (genesisData, genesisHash)
let block0 = Byron.genesisBlockFromTxOuts (genesisParameters np) outs
pure
( discriminant
, np
, vData
, block0
)
StagingConfig byronGenesisFile -> do
(genesisData, genesisHash) <-
withExceptT show $ readGenesisData byronGenesisFile
let mkSomeNetwork
:: forall (pm :: Nat). KnownNat pm
=> Proxy pm
-> SomeNetworkDiscriminant
mkSomeNetwork _ = SomeNetworkDiscriminant $ Proxy @('Staging pm)
let pm = Byron.fromProtocolMagicId $ gdProtocolMagicId genesisData
let (discriminant, vData) = someCustomDiscriminant mkSomeNetwork pm
let (np, outs) = Byron.fromGenesisData (genesisData, genesisHash)
let block0 = Byron.genesisBlockFromTxOuts (genesisParameters np) outs
pure
( discriminant
, np
, vData
, block0
)
-- NOTE
-- Fixture wallets we use in integration tests comes from "initialFunds"
-- referenced in the genesis file. As of today, initial funds are declared as a
-- key-value map in JSON, and parsing libraries does not enforce any particular
-- ordering on the keys when parsing the map. Because this wallet uses sequential
-- derivation, it relies on addresses being discovered in a certain order.
newtype PreserveInitialFundsOrdering =
PreserveInitialFundsOrdering [TxOut]
deriving (Show)
instance FromJSON PreserveInitialFundsOrdering where
parseJSON source = do
initialFunds <- flip (Aeson.withObject "ByronGenesis") source $ \obj ->
obj .: "nonAvvmBalances"
let outs = mconcat (Map.toList <$> initialFunds)
& map (first unsafeMkAddress)
& map (second unsafeMkLovelace)
& map (Byron.fromTxOut . uncurry Legacy.TxOut)
pure $ PreserveInitialFundsOrdering outs
where
unsafeMkAddress =
either bomb id . Byron.decodeAddressBase58
where
bomb = error "PreserveInitialFundsOrdering: address not valid base58"
unsafeMkLovelace =
either bomb id . Byron.mkLovelace . read
where
bomb = error "PreserveInitialFundsOrdering: invalid lovelace value"
--------------------------------------------------------------------------------
-- For Integration
--------------------------------------------------------------------------------
-- | A quick helper to interact with the 'cardano-cli'. Assumes the cardano-cli
-- is available in PATH.
cli :: Tracer IO ClusterLog -> [String] -> IO String
cli tr args = do
traceWith tr $ MsgCLI args
readProcess "cardano-cli" args stdin
where
stdin = ""
-- | Runs a @cardano-cli@ command and retries for up to 30 seconds if the
-- command failed.
--
-- Assumes @cardano-cli@ is available in @PATH@ and that the env var
-- @CARDANO_NODE_SOCKET_PATH@ has already been set.
cliRetry
:: Tracer IO ClusterLog
-> String -- ^ message to print before running command
-> [String] -- ^ arguments to @cardano-cli@
-> IO String
cliRetry tr msg args = do
(st, out, err) <- retrying pol (const isFail) (const cmd)
traceWith tr $ MsgCLIStatus msg st out err
case st of
ExitSuccess -> pure out
ExitFailure _ -> throwIO $ ProcessHasExited
(unwords (prog:args) <> " failed: " <> err) st
where
prog = "cardano-cli"
cmd = do
traceWith tr $ MsgCLIRetry msg
(st, out, err) <- readProcessWithExitCode "cardano-cli" args mempty
case st of
ExitSuccess -> pure ()
ExitFailure code -> traceWith tr (MsgCLIRetryResult msg code err)
pure (st, out, err)
isFail (st, _, _) = pure (st /= ExitSuccess)
pol = limitRetriesByCumulativeDelay 30_000_000 $ constantDelay 1_000_000
newtype PoolConfig = PoolConfig
{ retirementEpoch :: Maybe EpochNo
-- ^ An optional retirement epoch. If specified, then a pool retirement
-- certificate will be published after the pool is initially registered.
}
deriving (Eq, Show)
data RunningNode = RunningNode
FilePath
-- ^ Socket path
Block
-- ^ Genesis block
(NetworkParameters, NodeVersionData)
-- | Execute an action after starting a cluster of stake pools. The cluster also
-- contains a single BFT node that is pre-configured with keys available in the
-- test data.
--
-- This BFT node is essential in order to bootstrap the chain and allow
-- registering pools. Passing `0` as a number of pool will simply start a single
-- BFT node.
--
-- The callback actions are not guaranteed to use the same node.
withCluster
:: Tracer IO ClusterLog
-- ^ Trace for subprocess control logging
-> Severity
-- ^ Minimum logging severity for @cardano-node@
-> [PoolConfig]
-- ^ The configurations of pools to spawn.
-> FilePath
-- ^ Parent state directory for cluster
-> Maybe (FilePath, Severity)
-> (RunningNode -> IO ())
-- ^ Action to run when Byron is up
-> (RunningNode -> IO ())
-- ^ Action to run when we have transitioned to shelley.
--
-- Can be used to transfer byron faucet funds to shelley faucets.
-> (RunningNode -> IO a)
-- ^ Action to run when stake pools are running
-> IO a
withCluster tr severity poolConfigs dir logFile onByron onFork onClusterStart =
bracketTracer' tr "withCluster" $ do
traceWith tr $ MsgStartingCluster dir
let poolCount = length poolConfigs
(port0:ports) <- randomUnusedTCPPorts (poolCount + 2)
systemStart <- addUTCTime 1 <$> getCurrentTime
let bftCfg = NodeParams severity systemStart (head $ rotate ports) logFile
withBFTNode tr dir bftCfg $ \bftSocket block0 params -> do
let runningBftNode = RunningNode bftSocket block0 params
waitForSocket tr bftSocket *> onByron runningBftNode
traceWith tr MsgWaitingForFork
updateVersion tr dir
waitForHardFork bftSocket (fst params) 1 *> onFork runningBftNode
setEnv "CARDANO_NODE_SOCKET_PATH" bftSocket
(rawTx, faucetPrv) <- prepareKeyRegistration tr dir
tx <- signTx tr dir rawTx [faucetPrv]
submitTx tr "pre-registered stake key" tx
waitGroup <- newChan
doneGroup <- newChan
let waitAll = do
traceWith tr $
MsgDebug "waiting for stake pools to register"
replicateM poolCount (readChan waitGroup)
let cancelAll = do
traceWith tr $ MsgDebug "stopping all stake pools"
replicateM_ poolCount (writeChan doneGroup ())
let onException :: SomeException -> IO ()
onException e = do
traceWith tr $
MsgDebug $ "exception while starting pool: " <>
T.pack (show e)
writeChan waitGroup (Left e)
let pledgeOf 0 = 2*oneMillionAda
pledgeOf _ = oneMillionAda
forM_ (zip3 [0..] poolConfigs $ tail $ rotate ports) $
\(idx, poolConfig, (port, peers)) -> do
link =<< async (handle onException $ do
let spCfg =
NodeParams severity systemStart (port, peers) logFile
withStakePool
tr dir idx spCfg (pledgeOf idx) poolConfig $ do
writeChan waitGroup $ Right port
readChan doneGroup)
traceWith tr $ MsgRegisteringStakePools poolCount
group <- waitAll
if length (filter isRight group) /= poolCount then do
cancelAll
let errors = show (filter isLeft group)
throwIO $ ProcessHasExited
("cluster didn't start correctly: " <> errors)
(ExitFailure 1)
else do
let cfg = NodeParams severity systemStart (port0, ports) logFile
withRelayNode tr dir cfg $ \socket -> do
let runningRelay = RunningNode socket block0 params
onClusterStart runningRelay `finally` cancelAll
where
-- | Get permutations of the size (n-1) for a list of n elements, alongside
-- with the element left aside. `[a]` is really expected to be `Set a`.
--
-- >>> rotate [1,2,3]
-- [(1,[2,3]), (2, [1,3]), (3, [1,2])]
rotate :: Ord a => [a] -> [(a, [a])]
rotate = nub . fmap (\(x:xs) -> (x, sort xs)) . permutations
waitForHardFork :: FilePath -> NetworkParameters -> Int -> IO ()
waitForHardFork _socket np epoch = threadDelay (ceiling (1e6 * delay))
where
delay :: NominalDiffTime
delay = slotDur * fromIntegral epLen * fromIntegral epoch + fuzz
EpochLength epLen = getEpochLength (genesisParameters np)
SlotLength slotDur = getSlotLength (genesisParameters np)
-- add two seconds just to make sure.
fuzz = 2
-- | Configuration parameters which update the @node.config@ test data file.
data NodeParams = NodeParams
{ minSeverity :: Severity
-- ^ Minimum logging severity
, systemStart :: UTCTime
-- ^ Genesis block start time
, nodePeers :: (Int, [Int])
-- ^ A list of ports used by peers and this node
, extraLogFile :: Maybe (FilePath, Severity)
-- ^ The node will always log to "cardano-node.log" relative to the
-- config. This option can be set for an additional output.
} deriving (Show)
singleNodeParams :: Severity -> Maybe (FilePath, Severity) -> IO NodeParams
singleNodeParams severity extraLogFile = do
systemStart <- getCurrentTime
pure $ NodeParams severity systemStart (0, []) extraLogFile
withBFTNode
:: Tracer IO ClusterLog
-- ^ Trace for subprocess control logging
-> FilePath
-- ^ Parent state directory. Node data will be created in a subdirectory of
-- this.
-> NodeParams
-- ^ Parameters used to generate config files.
-> (FilePath -> Block -> (NetworkParameters, NodeVersionData) -> IO a)
-- ^ Callback function with genesis parameters
-> IO a
withBFTNode tr baseDir params action =
bracketTracer' tr "withBFTNode" $ do
createDirectoryIfMissing False dir
[bftCert, bftPrv, vrfPrv, kesPrv, opCert] <- forM
[ "bft-leader" <> ".byron.cert"
, "bft-leader" <> ".byron.skey"
, "bft-leader" <> ".vrf.skey"
, "bft-leader" <> ".kes.skey"
, "bft-leader" <> ".opcert"
]
(\f -> copyFile (source </> f) (dir </> f) $> (dir </> f))
let extraLogFile = (fmap (first (</> (name ++ ".log"))) logDir)
(config, block0, networkParams, versionData)
<- genConfig dir severity extraLogFile systemStart
topology <- genTopology dir peers
let cfg = CardanoNodeConfig
{ nodeDir = dir
, nodeConfigFile = config
, nodeTopologyFile = topology
, nodeDatabaseDir = "db"
, nodeDlgCertFile = Just bftCert
, nodeSignKeyFile = Just bftPrv
, nodeOpCertFile = Just opCert
, nodeKesKeyFile = Just kesPrv
, nodeVrfKeyFile = Just vrfPrv
, nodePort = Just (NodePort port)
, nodeLoggingHostname = Just name
}
withCardanoNodeProcess tr name cfg $ \(CardanoNodeConn socket) -> do
action socket block0 (networkParams, versionData)
where
source :: FilePath
source = $(getTestData) </> "cardano-node-shelley"
name = "bft"
dir = baseDir </> name
NodeParams severity systemStart (port, peers) logDir = params
-- | Launches a @cardano-node@ with the given configuration which will not forge
-- blocks, but has every other cluster node as its peer. Any transactions
-- submitted to this node will be broadcast to every node in the cluster.
withRelayNode
:: Tracer IO ClusterLog
-- ^ Trace for subprocess control logging
-> FilePath
-- ^ Parent state directory. Node data will be created in a subdirectory of
-- this.
-> NodeParams
-- ^ Parameters used to generate config files.
-> (FilePath -> IO a)
-- ^ Callback function with socket path
-> IO a
withRelayNode tr baseDir (NodeParams severity systemStart (port, peers) logDir) act =
bracketTracer' tr "withRelayNode" $ do
createDirectory dir
let extraLogFile = (fmap (first (</> (name ++ ".log"))) logDir)
(config, _, _, _) <-
genConfig dir severity extraLogFile systemStart
topology <- genTopology dir peers
let cfg = CardanoNodeConfig
{ nodeDir = dir
, nodeConfigFile = config
, nodeTopologyFile = topology
, nodeDatabaseDir = "db"
, nodeDlgCertFile = Nothing
, nodeSignKeyFile = Nothing
, nodeOpCertFile = Nothing
, nodeKesKeyFile = Nothing
, nodeVrfKeyFile = Nothing
, nodePort = Just (NodePort port)
, nodeLoggingHostname = Just name
}
withCardanoNodeProcess tr name cfg $ \(CardanoNodeConn socket) ->
act socket
where
name = "node"
dir = baseDir </> name
-- | Populates the configuration directory of a stake pool @cardano-node@.
--
-- Returns a tuple with:
-- * A config for launching the stake pool node.
-- * The public operator certificate - used for verifying registration.
-- * A transaction which should be submitted to register the pool.
setupStakePoolData
:: Tracer IO ClusterLog
-- ^ Logging object.
-> FilePath
-- ^ Output directory.
-> String
-- ^ Short name of the stake pool.
-> NodeParams
-- ^ Parameters used for generating config files.
-> String
-- ^ Base URL of metadata server.
-> Integer
-- ^ Pledge (and stake) amount.
-> Maybe EpochNo
-- ^ Optional retirement epoch.
-> IO (CardanoNodeConfig, FilePath, FilePath)
setupStakePoolData tr dir name params url pledgeAmt mRetirementEpoch = do
let NodeParams severity systemStart (port, peers) logDir = params
(opPrv, opPub, opCount, metadata) <- genOperatorKeyPair tr dir
(vrfPrv, vrfPub) <- genVrfKeyPair tr dir
(kesPrv, kesPub) <- genKesKeyPair tr dir
(stakePrv, stakePub) <- genStakeAddrKeyPair tr dir
stakeCert <- issueStakeCert tr dir "stake-pool" stakePub
poolRegistrationCert <- issuePoolRegistrationCert
tr dir opPub vrfPub stakePub url metadata pledgeAmt
mPoolRetirementCert <- traverse
(issuePoolRetirementCert tr dir opPub) mRetirementEpoch
dlgCert <- issueDlgCert tr dir stakePub opPub
opCert <- issueOpCert tr dir kesPub opPrv opCount
let extraLogFile = (fmap (first (</> (name ++ ".log"))) logDir)
(config, _, _, _) <- genConfig dir severity extraLogFile systemStart
topology <- genTopology dir peers
-- In order to get a working stake pool we need to.
--
-- 1. Register a stake key for our pool.
-- 2. Register the stake pool
-- 3. Delegate funds to our pool's key.
--
-- We cheat a bit here by delegating to our stake address right away
-- in the transaction used to registered the stake key and the pool
-- itself. Thus, in a single transaction, we end up with a
-- registered pool with some stake!
let certificates = catMaybes
[ pure stakeCert
, pure poolRegistrationCert
, pure dlgCert
, mPoolRetirementCert
]
(rawTx, faucetPrv) <- preparePoolRegistration
tr dir stakePub certificates pledgeAmt
tx <- signTx tr dir rawTx [faucetPrv, stakePrv, opPrv]
let cfg = CardanoNodeConfig
{ nodeDir = dir
, nodeConfigFile = config
, nodeTopologyFile = topology
, nodeDatabaseDir = "db"
, nodeDlgCertFile = Nothing
, nodeSignKeyFile = Nothing
, nodeOpCertFile = Just opCert
, nodeKesKeyFile = Just kesPrv
, nodeVrfKeyFile = Just vrfPrv
, nodePort = Just (NodePort port)
, nodeLoggingHostname = Just name
}
pure (cfg, opPub, tx)
-- | Start a "stake pool node". The pool will register itself.
withStakePool
:: Tracer IO ClusterLog
-- ^ Trace for subprocess control logging
-> FilePath
-- ^ Parent state directory. Node and stake pool data will be created in a
-- subdirectory of this.
-> Int
-- ^ Stake pool index in the cluster
-> NodeParams
-- ^ Configuration for the underlying node
-> Integer
-- ^ Pledge amount / initial stake
-> PoolConfig
-- ^ Pool configuration
-> IO a
-- ^ Action to run with the stake pool running
-> IO a
withStakePool tr baseDir idx params pledgeAmt poolConfig action =
bracketTracer' tr "withStakePool" $ do
createDirectory dir
withStaticServer dir $ \url -> do
traceWith tr $ MsgStartedStaticServer dir url
(cfg, opPub, tx) <- setupStakePoolData
tr dir name params url pledgeAmt (retirementEpoch poolConfig)
withCardanoNodeProcess tr name cfg $ \_ -> do
submitTx tr name tx
timeout 120
("pool registration", waitUntilRegistered tr name opPub)
action
where
dir = baseDir </> name
name = "pool-" ++ show idx
updateVersion :: Tracer IO ClusterLog -> FilePath -> IO ()
updateVersion tr tmpDir = do
let updatePath = tmpDir </> "update-proposal"
let votePath = tmpDir </> "update-vote"
let network = "--mainnet"
void $ cli tr
[ "byron", "create-update-proposal"
, "--filepath", updatePath
, network
, "--signing-key", source </> "bft-leader.byron.skey"
, "--protocol-version-major", "1"
, "--protocol-version-minor", "0"
, "--protocol-version-alt", "0"
, "--application-name", "cardano-sl"
, "--software-version-num", "1"
, "--system-tag", "linux"
, "--installer-hash", "0"
]
void $ cli tr
[ "byron", "create-proposal-vote"
, "--proposal-filepath", updatePath
, network
, "--signing-key", source </> "bft-leader.byron.skey"
, "--vote-yes"
, "--output-filepath", votePath
]
void $ cli tr
[ "byron", "submit-update-proposal"
, network
, "--filepath", updatePath
]
void $ cli tr
[ "byron", "submit-proposal-vote"
, network
, "--filepath", votePath
]
where
source :: FilePath
source = $(getTestData) </> "cardano-node-shelley"
withCardanoNodeProcess
:: Tracer IO ClusterLog
-> String
-> CardanoNodeConfig
-> (CardanoNodeConn -> IO a)
-> IO a
withCardanoNodeProcess tr name cfg = withCardanoNode tr' cfg >=> throwErrs
where
tr' = contramap (MsgLauncher name) tr
throwErrs = either throwIO pure
genConfig
:: FilePath
-- ^ A top-level directory where to put the configuration.
-> Severity
-- ^ Minimum severity level for logging
-> Maybe (FilePath, Severity)
-- ^ Optional /extra/ logging output
-> UTCTime
-- ^ Genesis block start time
-> IO (FilePath, Block, NetworkParameters, NodeVersionData)
genConfig dir severity mExtraLogFile systemStart = do
let startTime = round @_ @Int . utcTimeToPOSIXSeconds $ systemStart
let systemStart' = posixSecondsToUTCTime . fromRational . toRational $ startTime
-- let stdoutScribe = ScribeDefinition
-- { scName = "stdout"
-- , scFormat = ScText
-- , scKind = StdoutSK
-- , scMinSev = severity
-- , scMaxSev = Critical
-- , scPrivacy = ScPublic
-- , scRotation = Nothing
-- }
let fileScribe (path, sev) = ScribeDefinition
{ scName = path
, scFormat = ScText
, scKind = FileSK
, scMinSev = sev
, scMaxSev = Critical
, scPrivacy = ScPublic
, scRotation = Nothing
}
let scribes = catMaybes
[ Just $ fileScribe ("cardano-node.log", severity)
-- , Just stdoutScribe
, fileScribe . first T.pack <$> mExtraLogFile
]
----
-- Configuration
Yaml.decodeFileThrow (source </> "node.config")
>>= withAddedKey "ShelleyGenesisFile" shelleyGenesisFile
>>= withAddedKey "ByronGenesisFile" byronGenesisFile
>>= withAddedKey "minSeverity" Debug
>>= withScribes scribes
>>= withObject (addMinSeverityStdout severity)
>>= Yaml.encodeFile (dir </> "node.config")
----
-- Byron Genesis
Yaml.decodeFileThrow @_ @Aeson.Value (source </> "byron-genesis.yaml")
>>= withAddedKey "startTime" startTime
>>= withObject transformInitialFunds
>>= Aeson.encodeFile byronGenesisFile
----
-- Shelley Genesis
Yaml.decodeFileThrow @_ @Aeson.Value (source </> "shelley-genesis.yaml")
>>= withObject (pure . updateSystemStart systemStart')
>>= Aeson.encodeFile shelleyGenesisFile
----
-- Initial Funds.
PreserveInitialFundsOrdering initialFunds <-
Yaml.decodeFileThrow @_ @Aeson.Value (source </> "byron-genesis.yaml")
>>= withAddedKey "startTime" startTime
>>= either fail pure . Aeson.parseEither parseJSON
(byronGenesisData, byronGenesisHash) <- unsafeRunExceptT
$ withExceptT show
$ readGenesisData byronGenesisFile
let (byronParams, _) = Byron.fromGenesisData (byronGenesisData, byronGenesisHash)
let gp = genesisParameters byronParams
let block0 = Byron.genesisBlockFromTxOuts gp initialFunds
----
-- Parameters
shelleyGenesis <- Yaml.decodeFileThrow
@_ @(ShelleyGenesis TPraosStandardCrypto) shelleyGenesisFile
let networkMagic = sgNetworkMagic shelleyGenesis
let shelleyParams = fst $ Shelley.fromGenesisData shelleyGenesis []
let versionData =
( NodeToClientVersionData $ NetworkMagic networkMagic
, nodeToClientCodecCBORTerm
)
pure
( dir </> "node.config"
, block0
, byronParams { protocolParameters = protocolParameters shelleyParams }
, versionData
)
where
source :: FilePath
source = $(getTestData) </> "cardano-node-shelley"
shelleyGenesisFile :: FilePath
shelleyGenesisFile = dir </> "shelley-genesis.json"
byronGenesisFile :: FilePath
byronGenesisFile = dir </> "byron-genesis.json"
withScribes scribes =
withAddedKey "setupScribes" scribes
>=> withAddedKey "defaultScribes"
(map (\s -> [toJSON $ scKind s, toJSON $ scName s]) scribes)
-- we need to specify genesis file location every run in tmp
withAddedKey k v = withObject (pure . HM.insert k (toJSON v))
-- | Generate a topology file from a list of peers.
genTopology :: FilePath -> [Int] -> IO FilePath
genTopology dir peers = do
let file = dir </> "node.topology"
Aeson.encodeFile file $ Aeson.object [ "Producers" .= map encodePeer peers ]
pure file
where
encodePeer :: Int -> Aeson.Value
encodePeer port = Aeson.object
[ "addr" .= ("127.0.0.1" :: String)
, "port" .= port
, "valency" .= (1 :: Int)
]
-- | Create a key pair for a node operator's offline key and a new certificate
-- issue counter
genOperatorKeyPair :: Tracer IO ClusterLog -> FilePath -> IO (FilePath, FilePath, FilePath, Aeson.Value)
genOperatorKeyPair tr dir = do
traceWith tr $ MsgGenOperatorKeyPair dir
(_poolId, pub, prv, count, metadata) <- takeMVar operators >>= \case
[] -> fail "genOperatorKeyPair: Awe crap! No more operators available!"
(op:q) -> putMVar operators q $> op
let opPub = dir </> "op.pub"
let opPrv = dir </> "op.prv"
let opCount = dir </> "op.count"
Aeson.encodeFile opPub pub
Aeson.encodeFile opPrv prv
Aeson.encodeFile opCount count
pure (opPrv, opPub, opCount, metadata)
-- | Create a key pair for a node KES operational key
genKesKeyPair :: Tracer IO ClusterLog -> FilePath -> IO (FilePath, FilePath)
genKesKeyPair tr dir = do
let kesPub = dir </> "kes.pub"
let kesPrv = dir </> "kes.prv"
void $ cli tr
[ "shelley", "node", "key-gen-KES"
, "--verification-key-file", kesPub
, "--signing-key-file", kesPrv
]
pure (kesPrv, kesPub)
-- | Create a key pair for a node VRF operational key
genVrfKeyPair :: Tracer IO ClusterLog -> FilePath -> IO (FilePath, FilePath)
genVrfKeyPair tr dir = do
let vrfPub = dir </> "vrf.pub"
let vrfPrv = dir </> "vrf.prv"
void $ cli tr
[ "shelley", "node", "key-gen-VRF"
, "--verification-key-file", vrfPub
, "--signing-key-file", vrfPrv
]
pure (vrfPrv, vrfPub)
-- | Create a stake address key pair
genStakeAddrKeyPair :: Tracer IO ClusterLog -> FilePath -> IO (FilePath, FilePath)
genStakeAddrKeyPair tr dir = do
let stakePub = dir </> "stake.pub"
let stakePrv = dir </> "stake.prv"
void $ cli tr
[ "shelley", "stake-address", "key-gen"
, "--verification-key-file", stakePub
, "--signing-key-file", stakePrv
]
pure (stakePrv, stakePub)
-- | Issue a node operational certificate
issueOpCert :: Tracer IO ClusterLog -> FilePath -> FilePath -> FilePath -> FilePath -> IO FilePath
issueOpCert tr dir kesPub opPrv opCount = do
let file = dir </> "op.cert"
void $ cli tr
[ "shelley", "node", "issue-op-cert"
, "--kes-verification-key-file", kesPub
, "--cold-signing-key-file", opPrv
, "--operational-certificate-issue-counter-file", opCount
, "--kes-period", "0"
, "--out-file", file
]
pure file
-- | Create a stake address registration certificate
issueStakeCert
:: Tracer IO ClusterLog
-> FilePath
-> String
-> FilePath
-> IO FilePath
issueStakeCert tr dir prefix stakePub = do
let file = dir </> prefix <> "-stake.cert"
void $ cli tr
[ "shelley", "stake-address", "registration-certificate"