This repository was archived by the owner on Aug 18, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 631
/
Copy pathProc.hs
569 lines (528 loc) · 21.2 KB
/
Proc.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
{-# LANGUAGE ApplicativeDo #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}
module Command.Proc
( createCommandProcs
) where
import Universum
import Data.Constraint (Dict (..))
import Data.Default (def)
import Data.List ((!!))
import qualified Data.Map as Map
import Formatting (build, int, sformat, stext, (%))
import System.Wlog (CanLog, HasLoggerName, logError, logInfo,
logWarning)
import qualified Text.JSON.Canonical as CanonicalJSON
import Pos.Chain.Txp (TxpConfiguration)
import Pos.Chain.Update (BlockVersionModifier (..))
import Pos.Client.KeyStorage (addSecretKey, getSecretKeysPlain)
import Pos.Client.Txp.Balances (getBalance)
import Pos.Core as Core (AddrStakeDistribution (..), Address,
Config (..), StakeholderId, addressHash,
configGeneratedSecretsThrow, mkMultiKeyDistr,
unsafeGetCoin)
import Pos.Core.Common (AddrAttributes (..), AddrSpendingData (..),
makeAddress)
import Pos.Core.Delegation (HeavyDlgIndex (..))
import Pos.Core.Genesis (gsSecretKeys)
import Pos.Core.Txp (TxOut (..))
import Pos.Core.Update (SoftwareVersion (..))
import Pos.Crypto (PublicKey, emptyPassphrase, encToPublic,
fullPublicKeyF, hashHexF, noPassEncrypt, safeCreatePsk,
unsafeCheatingHashCoerce, withSafeSigner)
import Pos.DB.Class (MonadGState (..))
import Pos.Infra.Diffusion.Types (Diffusion (..))
import Pos.Util.UserSecret (WalletUserSecret (..), readUserSecret,
usKeys, usPrimKey, usWallet, userSecret)
import Pos.Util.Util (eitherToThrow)
import Command.BlockGen (generateBlocks)
import Command.Help (mkHelpMessage)
import qualified Command.Rollback as Rollback
import qualified Command.Tx as Tx
import Command.TyProjection (tyAddrDistrPart, tyAddrStakeDistr,
tyAddress, tyApplicationName, tyBlockVersion,
tyBlockVersionModifier, tyBool, tyByte, tyCoin,
tyCoinPortion, tyEither, tyEpochIndex, tyFilePath, tyHash,
tyInt, tyProposeUpdateSystem, tyPublicKey,
tyScriptVersion, tySecond, tySoftwareVersion,
tyStakeholderId, tySystemTag, tyTxOut, tyValue, tyWord,
tyWord32)
import qualified Command.Update as Update
import Lang.Argument (getArg, getArgMany, getArgOpt, getArgSome,
typeDirectedKwAnn)
import Lang.Command (CommandProc (..), UnavailableCommand (..))
import Lang.Name (Name)
import Lang.Value (AddKeyParams (..), AddrDistrPart (..),
GenBlocksParams (..), ProposeUpdateParams (..),
ProposeUpdateSystem (..), RollbackParams (..), Value (..))
import Mode (MonadAuxxMode, deriveHDAddressAuxx,
makePubKeyAddressAuxx)
import Repl (PrintAction)
createCommandProcs ::
forall m. (MonadIO m, CanLog m, HasLoggerName m)
=> Maybe Core.Config
-> Maybe TxpConfiguration
-> Maybe (Dict (MonadAuxxMode m))
-> PrintAction m
-> Maybe (Diffusion m)
-> [CommandProc m]
createCommandProcs mCoreConfig mTxpConfig hasAuxxMode printAction mDiffusion = rights . fix $ \commands -> [
return CommandProc
{ cpName = "L"
, cpArgumentPrepare = identity
, cpArgumentConsumer = getArgMany tyValue "elem"
, cpExec = return . ValueList
, cpHelp = "construct a list"
},
let name = "pk" in
needsAuxxMode name >>= \Dict ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer = getArg tyInt "i"
, cpExec = fmap ValuePublicKey . toLeft . Right
, cpHelp = "public key for secret #i"
},
let name = "s" in
needsAuxxMode name >>= \Dict ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer = getArg (tyPublicKey `tyEither` tyInt) "pk"
, cpExec = fmap ValueStakeholderId . toLeft . Right
, cpHelp = "stakeholder id (hash) of the specified public key"
},
let name = "addr" in
needsAuxxMode name >>= \Dict ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = map
$ typeDirectedKwAnn "distr" tyAddrStakeDistr
, cpArgumentConsumer =
(,) <$> getArg (tyPublicKey `tyEither` tyInt) "pk"
<*> getArgOpt tyAddrStakeDistr "distr"
, cpExec = \(pk', mDistr) -> do
pk <- toLeft pk'
addr <- case mDistr of
Nothing -> makePubKeyAddressAuxx pk
Just distr -> return $
makeAddress (PubKeyASD pk) (AddrAttributes Nothing distr)
return $ ValueAddress addr
, cpHelp = "address for the specified public key. a stake distribution \
\ can be specified manually (by default it uses the current epoch \
\ to determine whether we want to use bootstrap distr)"
},
let name = "addr-hd" in
needsAuxxMode name >>= \Dict ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer = getArg tyInt "i"
, cpExec = \i -> do
sks <- getSecretKeysPlain
sk <- evaluateWHNF (sks !! i) -- WHNF is sufficient to force possible errors
-- from using (!!). I'd use NF but there's no
-- NFData instance for secret keys.
addrHD <- deriveHDAddressAuxx sk
return $ ValueAddress addrHD
, cpHelp = "address of the HD wallet for the specified public key"
},
return CommandProc
{ cpName = "tx-out"
, cpArgumentPrepare = map
$ typeDirectedKwAnn "addr" tyAddress
, cpArgumentConsumer = do
txOutAddress <- getArg tyAddress "addr"
txOutValue <- getArg tyCoin "value"
return TxOut{..}
, cpExec = return . ValueTxOut
, cpHelp = "construct a transaction output"
},
let name = "dp" in
needsAuxxMode name >>= \Dict ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer = do
adpStakeholderId <- getArg (tyStakeholderId `tyEither` tyPublicKey `tyEither` tyInt) "s"
adpCoinPortion <- getArg tyCoinPortion "p"
return (adpStakeholderId, adpCoinPortion)
, cpExec = \(sId', cp) -> do
sId <- toLeft sId'
return $ ValueAddrDistrPart (AddrDistrPart sId cp)
, cpHelp = "construct an address distribution part"
},
let name = "distr" in
needsAuxxMode name >>= \Dict ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer = getArgSome tyAddrDistrPart "dp"
, cpExec = \parts -> do
distr <- case parts of
AddrDistrPart sId coinPortion :| []
| coinPortion == maxBound ->
return $ SingleKeyDistr sId
_ -> eitherToThrow $
mkMultiKeyDistr . Map.fromList $
map (\(AddrDistrPart s cp) -> (s, cp)) $
toList parts
return $ ValueAddrStakeDistribution distr
, cpHelp = "construct an address distribution (use 'dp' for each part)"
},
return . procConst "boot" $ ValueAddrStakeDistribution BootstrapEraDistr,
return . procConst "true" $ ValueBool True,
return . procConst "false" $ ValueBool False,
let name = "balance" in
needsAuxxMode name >>= \Dict ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer = getArg (tyAddress `tyEither` tyPublicKey `tyEither` tyInt) "addr"
, cpExec = \addr' -> do
addr <- toLeft addr'
balance <- getBalance addr
return $ ValueNumber (fromIntegral . unsafeGetCoin $ balance)
, cpHelp = "check the amount of coins on the specified address"
},
let name = "bvd" in
needsAuxxMode name >>= \Dict ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer = do pure ()
, cpExec = \() -> ValueBlockVersionData <$> gsAdoptedBVData
, cpHelp = "return current (adopted) BlockVersionData"
},
let name = "send-to-all-genesis" in
needsCoreConfig name >>= \coreConfig ->
needsDiffusion name >>= \diffusion ->
needsAuxxMode name >>= \Dict ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer = do
stagpGenesisTxsPerThread <- getArg tyInt "genesisTxsPerThread"
stagpTxsPerThread <- getArg tyInt "txsPerThread"
stagpConc <- getArg tyInt "conc"
stagpDelay <- getArg tyInt "delay"
stagpTpsSentFile <- getArg tyFilePath "file"
return Tx.SendToAllGenesisParams{..}
, cpExec = \stagp -> do
secretKeys <- gsSecretKeys <$> configGeneratedSecretsThrow coreConfig
Tx.sendToAllGenesis (configProtocolMagic coreConfig)
secretKeys
diffusion
stagp
return ValueUnit
, cpHelp = "create and send transactions from all genesis addresses \
\ for <duration> seconds, <delay> in ms. <conc> is the \
\ number of threads that send transactions concurrently."
},
let name = "send-from-file" in
needsDiffusion name >>= \diffusion ->
needsAuxxMode name >>= \Dict ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer = getArg tyFilePath "file"
, cpExec = \filePath -> do
Tx.sendTxsFromFile diffusion filePath
return ValueUnit
, cpHelp = ""
},
let name = "send" in
needsCoreConfig name >>= \coreConfig ->
needsDiffusion name >>= \diffusion ->
needsAuxxMode name >>= \Dict ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer =
(,) <$> getArg tyInt "i"
<*> getArgSome tyTxOut "out"
, cpExec = \(i, outputs) -> do
Tx.send (configProtocolMagic coreConfig) diffusion i outputs
return ValueUnit
, cpHelp = "send from #i to specified transaction outputs \
\ (use 'tx-out' to build them)"
},
let name = "vote" in
needsCoreConfig name >>= \coreConfig ->
needsDiffusion name >>= \diffusion ->
needsAuxxMode name >>= \Dict ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer =
(,,) <$> getArg tyInt "i"
<*> getArg tyBool "agree"
<*> getArg tyHash "up-id"
, cpExec = \(i, decision, upId) -> do
Update.vote (configProtocolMagic coreConfig) diffusion i decision upId
return ValueUnit
, cpHelp = "send vote for update proposal <up-id> and \
\ decision <agree> ('true' or 'false'), \
\ using secret key #i"
},
return CommandProc
{ cpName = "bvm"
, cpArgumentPrepare = identity
, cpArgumentConsumer = do
bvmScriptVersion <- getArgOpt tyScriptVersion "script-version"
bvmSlotDuration <- getArgOpt tySecond "slot-duration"
bvmMaxBlockSize <- getArgOpt tyByte "max-block-size"
bvmMaxHeaderSize <- getArgOpt tyByte "max-header-size"
bvmMaxTxSize <- getArgOpt tyByte "max-tx-size"
bvmMaxProposalSize <- getArgOpt tyByte "max-proposal-size"
bvmMpcThd <- getArgOpt tyCoinPortion "mpc-thd"
bvmHeavyDelThd <- getArgOpt tyCoinPortion "heavy-del-thd"
bvmUpdateVoteThd <- getArgOpt tyCoinPortion "update-vote-thd"
bvmUpdateProposalThd <- getArgOpt tyCoinPortion "update-proposal-thd"
let bvmUpdateImplicit = Nothing -- TODO
let bvmSoftforkRule = Nothing -- TODO
let bvmTxFeePolicy = Nothing -- TODO
bvmUnlockStakeEpoch <- getArgOpt tyEpochIndex "unlock-stake-epoch"
pure BlockVersionModifier{..}
, cpExec = return . ValueBlockVersionModifier
, cpHelp = "construct a BlockVersionModifier"
},
return CommandProc
{ cpName = "upd-bin"
, cpArgumentPrepare = identity
, cpArgumentConsumer = do
pusSystemTag <- getArg tySystemTag "system"
pusInstallerPath <- getArgOpt tyFilePath "installer-path"
pusBinDiffPath <- getArgOpt tyFilePath "bin-diff-path"
pure ProposeUpdateSystem{..}
, cpExec = return . ValueProposeUpdateSystem
, cpHelp = "construct a part of the update proposal for binary update"
},
let name = "software" in
return CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer = do
appName <- getArg tyApplicationName "name"
number <- getArg tyWord32 "n"
pure (appName, number)
, cpExec = \(svAppName, svNumber) -> do
return $ ValueSoftwareVersion SoftwareVersion{..}
, cpHelp = "Construct a software version from application name and number"
},
let name = "propose-update" in
needsCoreConfig name >>= \coreConfig ->
needsDiffusion name >>= \diffusion ->
needsAuxxMode name >>= \Dict ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = map
$ typeDirectedKwAnn "bvm" tyBlockVersionModifier
. typeDirectedKwAnn "update" tyProposeUpdateSystem
. typeDirectedKwAnn "block-version" tyBlockVersion
. typeDirectedKwAnn "software-version" tySoftwareVersion
, cpArgumentConsumer = do
puSecretKeyIdx <- getArg tyInt "i"
puVoteAll <- getArg tyBool "vote-all"
puBlockVersion <- getArg tyBlockVersion "block-version"
puSoftwareVersion <- getArg tySoftwareVersion "software-version"
puBlockVersionModifier <- fromMaybe def <$> getArgOpt tyBlockVersionModifier "bvm"
puUpdates <- getArgMany tyProposeUpdateSystem "update"
pure ProposeUpdateParams{..}
, cpExec = \params ->
-- FIXME: confuses existential/universal. A better solution
-- is to have two ValueHash constructors, one with universal and
-- one with existential (relevant via singleton-style GADT) quantification.
ValueHash . unsafeCheatingHashCoerce
<$> Update.propose (configProtocolMagic coreConfig) diffusion params
, cpHelp = "propose an update with one positive vote for it \
\ using secret key #i"
},
return CommandProc
{ cpName = "hash-installer"
, cpArgumentPrepare = identity
, cpArgumentConsumer = getArg tyFilePath "file"
, cpExec = \filePath -> do
Update.hashInstaller printAction filePath
return ValueUnit
, cpHelp = ""
},
let name = "delegate-heavy" in
needsCoreConfig name >>= \coreConfig ->
needsDiffusion name >>= \diffusion ->
needsAuxxMode name >>= \Dict ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer =
(,,,) <$> getArg tyInt "i"
<*> getArg tyPublicKey "pk"
<*> getArg tyEpochIndex "cur"
<*> getArg tyBool "dry"
, cpExec = \(i, delegatePk, curEpoch, dry) -> do
issuerSk <- (!! i) <$> getSecretKeysPlain
withSafeSigner issuerSk (pure emptyPassphrase) $ \case
Nothing -> logError "Invalid passphrase"
Just ss -> do
let psk = safeCreatePsk (configProtocolMagic coreConfig)
ss
delegatePk
(HeavyDlgIndex curEpoch)
if dry
then do
printAction $
sformat ("JSON: key "%hashHexF%", value "%stext)
(addressHash $ encToPublic issuerSk)
(decodeUtf8 $
CanonicalJSON.renderCanonicalJSON $
runIdentity $
CanonicalJSON.toJSON psk)
else do
sendPskHeavy diffusion psk
logInfo "Sent heavyweight cert"
return ValueUnit
, cpHelp = ""
},
let name = "generate-blocks" in
needsCoreConfig name >>= \coreConfig ->
needsAuxxMode name >>= \Dict ->
needsTxpConfig name >>= \txpConfig ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer = do
bgoBlockN <- getArg tyWord32 "n"
bgoSeed <- getArgOpt tyInt "seed"
return GenBlocksParams{..}
, cpExec = \params -> do
generateBlocks (configProtocolMagic coreConfig) txpConfig params
return ValueUnit
, cpHelp = "generate <n> blocks"
},
let name = "add-key-pool" in
needsCoreConfig name >>= \coreConfig ->
needsAuxxMode name >>= \Dict ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer = getArgMany tyInt "i"
, cpExec = \is -> do
when (null is) $ logWarning "Not adding keys from pool (list is empty)"
secretKeys <- gsSecretKeys <$> configGeneratedSecretsThrow coreConfig
forM_ is $ \i -> do
key <- evaluateNF $ secretKeys !! i
addSecretKey $ noPassEncrypt key
return ValueUnit
, cpHelp = ""
},
let name = "add-key" in
needsAuxxMode name >>= \Dict ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer = do
akpFile <- getArg tyFilePath "file"
akpPrimary <- getArg tyBool "primary"
return AddKeyParams {..}
, cpExec = \AddKeyParams {..} -> do
secret <- readUserSecret akpFile
if akpPrimary then do
let primSk = fromMaybe (error "Primary key not found") (secret ^. usPrimKey)
addSecretKey $ noPassEncrypt primSk
else do
let ks = secret ^. usKeys
printAction $ sformat ("Adding "%build%" secret keys") (length ks)
mapM_ addSecretKey ks
return ValueUnit
, cpHelp = ""
},
let name = "rollback" in
needsCoreConfig name >>= \coreConfig ->
needsAuxxMode name >>= \Dict ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer = do
rpNum <- getArg tyWord "n"
rpDumpPath <- getArg tyFilePath "dump-file"
pure RollbackParams{..}
, cpExec = \RollbackParams{..} -> do
Rollback.rollbackAndDump (configProtocolMagic coreConfig)
rpNum
rpDumpPath
return ValueUnit
, cpHelp = ""
},
let name = "listaddr" in
needsAuxxMode name >>= \Dict ->
return CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer = do pure ()
, cpExec = \() -> do
sks <- getSecretKeysPlain
printAction "Available addresses:"
for_ (zip [0 :: Int ..] sks) $ \(i, sk) -> do
let pk = encToPublic sk
addr <- makePubKeyAddressAuxx pk
addrHD <- deriveHDAddressAuxx sk
printAction $
sformat (" #"%int%": addr: "%build%"\n"%
" pk: "%fullPublicKeyF%"\n"%
" pk hash: "%hashHexF%"\n"%
" HD addr: "%build)
i addr pk (addressHash pk) addrHD
walletMB <- (^. usWallet) <$> (view userSecret >>= readTVarIO)
whenJust walletMB $ \wallet -> do
addrHD <- deriveHDAddressAuxx (_wusRootKey wallet)
printAction $
sformat (" Wallet address:\n"%
" HD addr: "%build)
addrHD
return ValueUnit
, cpHelp = ""
},
return CommandProc
{ cpName = "help"
, cpArgumentPrepare = identity
, cpArgumentConsumer = do pure ()
, cpExec = \() -> do
printAction (mkHelpMessage commands)
return ValueUnit
, cpHelp = "display this message"
}]
where
needsData :: Maybe a -> Text -> Name -> Either UnavailableCommand a
needsData mData msg name = maybe
(Left $ UnavailableCommand name (msg <> " is not available"))
Right
mData
needsAuxxMode = needsData hasAuxxMode "AuxxMode"
needsDiffusion = needsData mDiffusion "Diffusion layer"
needsCoreConfig = needsData mCoreConfig "Core.Config"
needsTxpConfig = needsData mTxpConfig "TxpConfiguration"
procConst :: Applicative m => Name -> Value -> CommandProc m
procConst name value =
CommandProc
{ cpName = name
, cpArgumentPrepare = identity
, cpArgumentConsumer = pure ()
, cpExec = \() -> pure value
, cpHelp = "constant"
}
class ToLeft m a b where
toLeft :: Either a b -> m a
instance (Monad m, ToLeft m a b, ToLeft m b c) => ToLeft m a (Either b c) where
toLeft = toLeft <=< traverse toLeft
instance MonadAuxxMode m => ToLeft m PublicKey Int where
toLeft = either return getPublicKeyFromIndex
instance MonadAuxxMode m => ToLeft m StakeholderId PublicKey where
toLeft = return . either identity addressHash
instance MonadAuxxMode m => ToLeft m Address PublicKey where
toLeft = either return makePubKeyAddressAuxx
getPublicKeyFromIndex :: MonadAuxxMode m => Int -> m PublicKey
getPublicKeyFromIndex i = do
sks <- getSecretKeysPlain
let sk = sks !! i
pk = encToPublic sk
evaluateNF pk