-
Notifications
You must be signed in to change notification settings - Fork 212
/
cardano-wallet.hs
323 lines (300 loc) · 9.61 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
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# 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.Trace
( Trace, appendName, logDebug, logError, logInfo, logNotice )
import Cardano.CLI
( LogOutput (..)
, LoggingOptions
, cli
, cmdAddress
, cmdKey
, cmdMnemonic
, cmdNetwork
, cmdStakePool
, cmdTransaction
, cmdVersion
, cmdWallet
, cmdWalletCreate
, databaseOption
, enableWindowsANSI
, helperTracing
, hostPreferenceOption
, listenOption
, loggingMinSeverity
, loggingOptions
, loggingSeverityOrOffReader
, loggingTracers
, runCli
, setupDirectory
, shutdownHandlerFlag
, smashURLOption
, syncToleranceOption
, tlsOption
, withLogging
)
import Cardano.Startup
( ShutdownHandlerLog
, installSignalHandlers
, withShutdownHandler
, withUtf8Encoding
)
import Cardano.Wallet.Api.Client
( addressClient
, networkClient
, stakePoolClient
, transactionClient
, walletClient
)
import Cardano.Wallet.Api.Server
( HostPreference, Listen (..), TlsConfiguration )
import Cardano.Wallet.Api.Types
( ApiStakePool )
import Cardano.Wallet.Logging
( trMessage, transformTextTrace )
import Cardano.Wallet.Primitive.SyncProgress
( SyncTolerance )
import Cardano.Wallet.Shelley
( TracerSeverities
, Tracers
, Tracers' (..)
, serveWallet
, setupTracers
, tracerDescriptions
, tracerLabels
)
import Cardano.Wallet.Shelley.Launch
( NetworkConfiguration (..)
, networkConfigurationOption
, nodeSocketOption
, parseGenesisData
)
import Cardano.Wallet.Version
( GitRevision, Version, gitRevision, showFullVersion, version )
import Control.Applicative
( Const (..), optional )
import Control.Monad
( void )
import Control.Monad.Trans.Except
( runExceptT )
import Control.Tracer
( contramap )
import Data.Bifunctor
( second )
import Data.Text
( Text )
import Data.Text.Class
( ToText (..) )
import Network.Socket
( SockAddr )
import Network.URI
( URI )
import Options.Applicative
( CommandFields
, Mod
, Parser
, command
, helper
, info
, internal
, long
, metavar
, option
, progDesc
, value
)
import System.Environment
( getArgs, getExecutablePath )
import System.Exit
( ExitCode (..), exitWith )
import qualified Data.Text as T
{-------------------------------------------------------------------------------
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 @ApiStakePool stakePoolClient
<> cmdVersion
beforeMainLoop
:: Trace IO MainLog
-> SockAddr
-> IO ()
beforeMainLoop tr =
logInfo tr . MsgListenAddress
{-------------------------------------------------------------------------------
Command - 'serve'
-------------------------------------------------------------------------------}
-- | Arguments for the 'serve' command
data ServeArgs = ServeArgs
{ _hostPreference :: HostPreference
, _listen :: Listen
, _tlsConfig :: Maybe TlsConfiguration
, _nodeSocket :: FilePath
, _networkConfiguration :: NetworkConfiguration
, _database :: Maybe FilePath
, _syncTolerance :: SyncTolerance
, _enableShutdownHandler :: Bool
, _smashURL :: Maybe URI
, _logging :: LoggingOptions TracerSeverities
} deriving (Show)
cmdServe
:: Mod CommandFields (IO ())
cmdServe = command "serve" $ info (helper <*> helper' <*> cmd) $ mempty
<> progDesc "Serve API that listens for commands/actions."
where
helper' = helperTracing tracerDescriptions
cmd = fmap exec $ ServeArgs
<$> hostPreferenceOption
<*> listenOption
<*> optional tlsOption
<*> nodeSocketOption
<*> networkConfigurationOption
<*> optional databaseOption
<*> syncToleranceOption
<*> shutdownHandlerFlag
<*> optional smashURLOption
<*> loggingOptions tracerSeveritiesOption
exec
:: ServeArgs -> IO ()
exec args@(ServeArgs
host
listen
tlsConfig
nodeSocket
networkConfig
databaseDir
sTolerance
enableShutdownHandler
smashURL
logOpt) = do
withTracers logOpt $ \tr tracers -> do
installSignalHandlers (logNotice tr MsgSigTerm)
withShutdownHandlerMaybe tr enableShutdownHandler $ do
logDebug tr $ MsgServeArgs args
(discriminant, gp, vData, block0)
<- runExceptT (parseGenesisData networkConfig) >>= \case
Right x -> pure x
Left err -> do
logError tr (MsgFailedToParseGenesis $ T.pack err)
exitWith $ ExitFailure 33
whenJust databaseDir $ setupDirectory (logInfo tr . MsgSetupDatabases)
exitWith =<< serveWallet
discriminant
tracers
sTolerance
databaseDir
host
listen
tlsConfig
smashURL
nodeSocket
block0
(gp, vData)
(beforeMainLoop tr)
whenJust m fn = case m of
Nothing -> pure ()
Just a -> fn a
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
-------------------------------------------------------------------------------}
-- FIXME: reduce duplication. See 'cardano-wallet-jormungandr.hs'
data MainLog
= MsgCmdLine String [String]
| MsgVersion Version GitRevision
| MsgSetupStateDir Text
| MsgSetupDatabases Text
| MsgServeArgs ServeArgs
| MsgListenAddress SockAddr
| MsgSigTerm
| MsgShutdownHandler ShutdownHandlerLog
| MsgFailedToParseGenesis Text
deriving (Show)
instance ToText MainLog where
toText msg = case msg of
MsgCmdLine exe args ->
T.pack $ unwords ("Command line:":exe:args)
MsgVersion ver rev ->
"Running as v" <> T.pack (showFullVersion ver rev)
MsgSetupStateDir txt ->
"Wallet state: " <> txt
MsgSetupDatabases txt ->
"Wallet databases: " <> txt
MsgServeArgs args ->
T.pack $ show args
MsgListenAddress addr ->
"Wallet backend server listening on " <> T.pack (show addr)
MsgSigTerm ->
"Terminated by signal."
MsgShutdownHandler msg' ->
toText msg'
MsgFailedToParseGenesis hint -> T.unwords
[ "Failed to parse genesis configuration. You may want to check the"
, "filepath given via --genesis and make sure it points to a valid"
, "JSON genesis file. Here's (perhaps) some helpful hint:", hint
]
withTracers
:: LoggingOptions TracerSeverities
-> (Trace IO MainLog -> Tracers IO -> IO a)
-> IO a
withTracers logOpt action =
withLogging [LogToStdout (loggingMinSeverity logOpt)] $ \(_, tr) -> do
let trMain = appendName "main" (transformTextTrace tr)
let tracers = setupTracers (loggingTracers logOpt) tr
logInfo trMain $ MsgVersion version gitRevision
logInfo trMain =<< MsgCmdLine <$> getExecutablePath <*> getArgs
action trMain tracers
{-------------------------------------------------------------------------------
Options
-------------------------------------------------------------------------------}
tracerSeveritiesOption :: Parser TracerSeverities
tracerSeveritiesOption = Tracers
<$> traceOpt applicationTracer (Just Info)
<*> traceOpt apiServerTracer (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