-
Notifications
You must be signed in to change notification settings - Fork 211
/
cardano-wallet.hs
371 lines (346 loc) · 12 KB
/
cardano-wallet.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
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
-- |
-- Copyright: © 2018-2020 IOHK
-- License: Apache-2.0
--
-- This module parses command line arguments for the wallet and executes
-- corresponding commands.
--
-- In essence, it's a proxy to the wallet server, which is required for most
-- commands. Commands are turned into corresponding API calls, and submitted
-- to an up-and-running server. Some commands do not require an active server
-- and can be run "offline".
module Main where
import Prelude
import Cardano.BM.Data.Severity
( Severity (..) )
import Cardano.BM.Plugin
( loadPlugin )
import Cardano.BM.Trace
( Trace, appendName, logDebug, logError, logInfo, logNotice )
import Cardano.CLI
( LogOutput (..)
, LoggingOptions
, cli
, cmdAddress
, cmdKey
, cmdMnemonic
, cmdNetwork
, cmdStakePool
, cmdTransaction
, cmdVersion
, cmdWallet
, cmdWalletCreate
, databaseOption
, ekgEnabled
, enableWindowsANSI
, helperTracing
, hostPreferenceOption
, listenOption
, loggingMinSeverity
, loggingOptions
, loggingSeverityOrOffReader
, loggingTracers
, poolMetadataSourceOption
, runCli
, setupDirectory
, shutdownHandlerFlag
, tlsOption
, tokenMetadataSourceOption
, withLogging
)
import Cardano.Startup
( ShutdownHandlerLog
, installSignalHandlers
, withShutdownHandler
, withUtf8Encoding
)
import Cardano.Wallet.Api.Client
( addressClient
, networkClient
, stakePoolClient
, transactionClient
, walletClient
)
import Cardano.Wallet.Api.Http.Shelley.Server
( HostPreference, Listen (..), TlsConfiguration )
import Cardano.Wallet.Launch
( Mode (Light, Normal)
, NetworkConfiguration (..)
, modeOption
, networkConfigurationOption
, parseGenesisData
)
import Cardano.Wallet.Logging
( trMessage, transformTextTrace )
import Cardano.Wallet.Primitive.Types
( PoolMetadataSource (..), Settings (..), TokenMetadataServer (..) )
import Cardano.Wallet.Shelley
( TracerSeverities
, Tracers
, Tracers' (..)
, serveWallet
, setupTracers
, tracerDescriptions
, tracerLabels
)
import Cardano.Wallet.Shelley.BlockchainSource
( BlockchainSource (..) )
import Cardano.Wallet.Version
( GitRevision, Version, showFullVersion )
import Control.Applicative
( Const (..), optional )
import Control.Exception.Base
( AsyncException (..) )
import Control.Monad
( void, when )
import Control.Monad.Trans.Except
( runExceptT )
import Control.Tracer
( contramap )
import Data.Bifunctor
( second )
import Data.Foldable
( forM_ )
import Data.Text
( Text )
import Data.Text.Class
( ToText (..) )
import Network.URI
( URI )
-- See ADP-1910
import "optparse-applicative" Options.Applicative
( CommandFields
, Mod
, Parser
, command
, helper
, info
, internal
, long
, metavar
, option
, progDesc
, value
)
import Ouroboros.Network.Client.Wallet
( tunedForMainnetPipeliningStrategy )
import System.Environment
( getArgs, getExecutablePath )
import System.Exit
( ExitCode (..), exitWith )
import UnliftIO.Exception
( catch, withException )
import qualified Cardano.BM.Backend.EKGView as EKG
import qualified Cardano.Wallet.Launch.Blockfrost as Blockfrost
import qualified Cardano.Wallet.Version as V
import qualified Data.Text as T
import qualified System.Info as I
{-------------------------------------------------------------------------------
Main entry point
-------------------------------------------------------------------------------}
main :: IO ()
main = withUtf8Encoding $ do
enableWindowsANSI
runCli $ cli $ mempty
<> cmdServe
<> cmdMnemonic
<> cmdKey
<> cmdWallet cmdWalletCreate walletClient
<> cmdAddress addressClient
<> cmdTransaction transactionClient walletClient
<> cmdNetwork networkClient
<> cmdStakePool stakePoolClient
<> cmdVersion
beforeMainLoop :: Trace IO MainLog -> URI -> IO ()
beforeMainLoop tr = logInfo tr . MsgListenAddress
{-------------------------------------------------------------------------------
Command - 'serve'
-------------------------------------------------------------------------------}
-- | Arguments for the 'serve' command
data ServeArgs = ServeArgs
{ _hostPreference :: HostPreference
, _mode :: Mode
, _listen :: Listen
, _tlsConfig :: Maybe TlsConfiguration
, _networkConfiguration :: NetworkConfiguration
, _database :: Maybe FilePath
, _enableShutdownHandler :: Bool
, _poolMetadataSourceOpt :: Maybe PoolMetadataSource
, _tokenMetadataSourceOpt :: Maybe TokenMetadataServer
, _logging :: LoggingOptions TracerSeverities
} deriving (Show)
cmdServe :: Mod CommandFields (IO ())
cmdServe = command "serve" $ info (helper <*> helper' <*> cmd) $
progDesc "Serve API that listens for commands/actions."
where
helper' = helperTracing tracerDescriptions
cmd = fmap exec $ ServeArgs
<$> hostPreferenceOption
<*> modeOption
<*> listenOption
<*> optional tlsOption
<*> networkConfigurationOption
<*> optional databaseOption
<*> shutdownHandlerFlag
<*> optional poolMetadataSourceOption
<*> optional tokenMetadataSourceOption
<*> loggingOptions tracerSeveritiesOption
exec :: ServeArgs -> IO ()
exec args@(ServeArgs
host
mode
listen
tlsConfig
networkConfig
databaseDir
enableShutdownHandler
poolMetadataFetching
tokenMetadataServerURI
logOpt) = withTracers logOpt $ \tr tracers -> do
withShutdownHandlerMaybe tr enableShutdownHandler $ do
logDebug tr $ MsgServeArgs args
(discriminant, netParams, vData, block0)
<- runExceptT (parseGenesisData networkConfig) >>= \case
Right x -> pure x
Left err -> do
logError tr (MsgFailedToParseGenesis $ T.pack err)
exitWith $ ExitFailure 33
forM_ databaseDir $
setupDirectory (logInfo tr . MsgSetupDatabases)
blockchainSource <- case mode of
Normal conn syncTolerance ->
pure $ NodeSource conn vData syncTolerance
Light token -> BlockfrostSource <$> Blockfrost.readToken token
`catch` \case
Blockfrost.BadTokenFile f -> do
logError tr $ MsgBlockfrostTokenFileError f
exitWith $ ExitFailure 1
Blockfrost.EmptyToken f -> do
logError tr $ MsgBlockfrostTokenError f
exitWith $ ExitFailure 1
Blockfrost.InvalidToken f -> do
logError tr $ MsgBlockfrostTokenError f
exitWith $ ExitFailure 1
exitWith =<< serveWallet
blockchainSource
netParams
tunedForMainnetPipeliningStrategy
discriminant
[]
tracers
databaseDir
Nothing
host
listen
tlsConfig
(Settings <$> poolMetadataFetching)
tokenMetadataServerURI
block0
(beforeMainLoop tr)
withShutdownHandlerMaybe :: Trace IO MainLog -> Bool -> IO () -> IO ()
withShutdownHandlerMaybe _ False = void
withShutdownHandlerMaybe tr True = void . withShutdownHandler trShutdown
where
trShutdown = trMessage $ contramap (second (fmap MsgShutdownHandler)) tr
{-------------------------------------------------------------------------------
Logging
-------------------------------------------------------------------------------}
data MainLog
= MsgCmdLine String [String]
| MsgVersion Version GitRevision String String
| MsgSetupStateDir Text
| MsgSetupDatabases Text
| MsgServeArgs ServeArgs
| MsgListenAddress URI
| MsgSigTerm
| MsgSigInt
| MsgShutdownHandler ShutdownHandlerLog
| MsgFailedToParseGenesis Text
| MsgBlockfrostTokenFileError FilePath
| MsgBlockfrostTokenError FilePath
deriving (Show)
instance ToText MainLog where
toText = \case
MsgCmdLine exe args ->
T.pack $ unwords ("Command line:":exe:args)
MsgVersion ver rev arch os ->
"Running as " <> T.pack (showFullVersion ver rev) <> " on " <>
T.pack arch <> "-" <> T.pack os
MsgSetupStateDir txt ->
"Wallet state: " <> txt
MsgSetupDatabases txt ->
"Wallet databases: " <> txt
MsgServeArgs args ->
T.pack $ show args
MsgListenAddress url ->
"Wallet backend server listening on " <> T.pack (show url)
MsgSigTerm ->
"Terminated by signal."
MsgSigInt ->
"Interrupted by user."
MsgShutdownHandler msg' ->
toText msg'
MsgFailedToParseGenesis hint -> T.unwords
[ "Failed to parse Byron genesis configuration. You may want to check"
, "the filepath given via --genesis and make sure it points to a "
, "valid JSON Byron genesis file. The genesis file must be Byron, not"
, "Shelley as it used to feed the wallet with the initial blockchain"
, "parameters."
, "Here's (perhaps) some helpful hint:", hint
]
MsgBlockfrostTokenFileError tokenFile -> T.unwords
[ "File"
, "'" <> T.pack tokenFile <> "'"
, "specified in the --blockfrost-token-file can't be read."
]
MsgBlockfrostTokenError tokenFile -> T.unwords
[ "File"
, "'" <> T.pack tokenFile <> "'"
, "specified in the --blockfrost-token-file\
\ argument doesn't contain a valid Blockfrost API token."
]
withTracers
:: LoggingOptions TracerSeverities
-> (Trace IO MainLog -> Tracers IO -> IO a)
-> IO a
withTracers logOpt action =
withLogging [LogToStdStreams (loggingMinSeverity logOpt)] $ \(sb, (cfg, tr)) -> do
ekgEnabled >>= flip when (EKG.plugin cfg tr sb >>= loadPlugin sb)
let trMain = appendName "main" (transformTextTrace tr)
let tracers = setupTracers (loggingTracers logOpt) tr
logInfo trMain $ MsgVersion V.version V.gitRevision I.arch I.os
logInfo trMain =<< MsgCmdLine <$> getExecutablePath <*> getArgs
installSignalHandlers (logNotice trMain MsgSigTerm)
let logInterrupt UserInterrupt = logNotice trMain MsgSigInt
logInterrupt _ = pure ()
action trMain tracers `withException` logInterrupt
{-------------------------------------------------------------------------------
Options
-------------------------------------------------------------------------------}
tracerSeveritiesOption :: Parser TracerSeverities
tracerSeveritiesOption = Tracers
<$> traceOpt applicationTracer (Just Info)
<*> traceOpt apiServerTracer (Just Info)
<*> traceOpt tokenMetadataTracer (Just Info)
<*> traceOpt walletEngineTracer (Just Info)
<*> traceOpt walletDbTracer (Just Info)
<*> traceOpt poolsEngineTracer (Just Info)
<*> traceOpt poolsDbTracer (Just Info)
<*> traceOpt ntpClientTracer (Just Info)
<*> traceOpt networkTracer (Just Info)
where
traceOpt field def = fmap Const . option loggingSeverityOrOffReader $ mempty
<> long ("trace-" <> T.unpack (getConst (field tracerLabels)))
<> value def
<> metavar "SEVERITY"
<> internal