/
Wallet.hs
2246 lines (2073 loc) · 76.1 KB
/
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
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 ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
-- |
-- Copyright: © 2018-2020 IOHK
-- License: Apache-2.0
--
-- Provides wallet layer functions that are used by API layer. Uses both
-- "Cardano.Wallet.DB" and "Cardano.Wallet.Network" to realize its role as
-- being intermediary between the three.
--
-- Functions of the wallet layer are often parameterized with variables
-- following the convention below:
--
-- - @s@: A __s__tate used to keep track of known addresses. Typically, possible
-- values for this parameter are described in 'Cardano.Wallet.AddressDiscovery' sub-modules.
-- For instance @SeqState@ or @Rnd State@.
--
-- - @t@: A __t__arget backend which captures details specific to a particular chain
-- producer (binary formats, fee policy, networking layer).
--
-- - @k@: A __k__ey derivation scheme intrisically connected to the underlying discovery
-- state @s@. This describes how the hierarchical structure of a wallet is
-- defined as well as the relationship between secret keys and public
-- addresses.
module Cardano.Wallet
(
-- * Developement
-- $Development
-- * WalletLayer
WalletLayer (..)
-- * Capabilities
-- $Capabilities
, HasDBLayer
, dbLayer
, HasLogger
, logger
, HasNetworkLayer
, networkLayer
, HasTransactionLayer
, transactionLayer
, HasGenesisData
, genesisData
-- * Interface
-- ** Wallet
, createWallet
, createIcarusWallet
, attachPrivateKeyFromPwd
, attachPrivateKeyFromPwdHash
, listUtxoStatistics
, readWallet
, deleteWallet
, restoreWallet
, updateWallet
, updateWalletPassphrase
, walletSyncProgress
, fetchRewardBalance
, manageRewardBalance
, rollbackBlocks
, checkWalletIntegrity
, readNextWithdrawal
, ErrWalletAlreadyExists (..)
, ErrNoSuchWallet (..)
, ErrListUTxOStatistics (..)
, ErrUpdatePassphrase (..)
, ErrFetchRewards (..)
, ErrCheckWalletIntegrity (..)
, ErrWalletNotResponding (..)
-- ** Address
, createRandomAddress
, importRandomAddress
, listAddresses
, normalizeDelegationAddress
, ErrCreateRandomAddress(..)
, ErrImportRandomAddress(..)
-- ** Payment
, selectCoinsExternal
, selectCoinsForPayment
, estimateFeeForPayment
, signPayment
, ErrSelectCoinsExternal (..)
, ErrSelectForPayment (..)
, ErrSignPayment (..)
, ErrCoinSelection (..)
, ErrAdjustForFee (..)
, ErrValidateSelection
, ErrNotASequentialWallet (..)
-- ** Migration
, selectCoinsForMigration
, ErrSelectForMigration (..)
-- ** Delegation
, joinStakePool
, quitStakePool
, selectCoinsForDelegation
, estimateFeeForDelegation
, signDelegation
, guardJoin
, guardQuit
, ErrJoinStakePool (..)
, ErrCannotJoin (..)
, ErrQuitStakePool (..)
, ErrCannotQuit (..)
, ErrSelectForDelegation (..)
, ErrSignDelegation (..)
-- ** Fee Estimation
, FeeEstimation (..)
, estimateFeeForCoinSelection
, feeOpts
, coinSelOpts
, handleCannotCover
-- ** Transaction
, forgetPendingTx
, listTransactions
, getTransaction
, submitExternalTx
, signTx
, submitTx
, ErrMkTx (..)
, ErrSubmitTx (..)
, ErrSubmitExternalTx (..)
, ErrRemovePendingTx (..)
, ErrPostTx (..)
, ErrDecodeSignedTx (..)
, ErrListTransactions (..)
, ErrGetTransaction (..)
, ErrNoSuchTransaction (..)
, ErrNetworkUnavailable (..)
, ErrCurrentNodeTip (..)
, ErrStartTimeLaterThanEndTime (..)
-- ** Root Key
, withRootKey
, ErrWithRootKey (..)
, ErrWrongPassphrase (..)
-- * Logging
, WalletLog (..)
) where
import Prelude hiding
( log )
import Cardano.Address.Derivation
( XPrv )
import Cardano.BM.Data.Severity
( Severity (..) )
import Cardano.BM.Data.Tracer
( HasPrivacyAnnotation (..), HasSeverityAnnotation (..) )
import Cardano.Wallet.DB
( DBLayer (..)
, ErrNoSuchWallet (..)
, ErrRemovePendingTx (..)
, ErrWalletAlreadyExists (..)
, PrimaryKey (..)
, sparseCheckpoints
)
import Cardano.Wallet.Network
( ErrCurrentNodeTip (..)
, ErrGetAccountBalance (..)
, ErrNetworkUnavailable (..)
, ErrPostTx (..)
, FollowAction (..)
, FollowExit (..)
, FollowLog (..)
, NetworkLayer (..)
, follow
)
import Cardano.Wallet.Primitive.AddressDerivation
( DelegationAddress (..)
, Depth (..)
, DerivationType (..)
, ErrWrongPassphrase (..)
, HardDerivation (..)
, Index (..)
, MkKeyFingerprint (..)
, Passphrase
, PaymentAddress (..)
, WalletKey (..)
, checkPassphrase
, deriveRewardAccount
, encryptPassphrase
, liftIndex
, preparePassphrase
)
import Cardano.Wallet.Primitive.AddressDerivation.Byron
( ByronKey )
import Cardano.Wallet.Primitive.AddressDerivation.Icarus
( IcarusKey )
import Cardano.Wallet.Primitive.AddressDiscovery
( CompareDiscovery (..)
, GenChange (..)
, HasRewardAccount (..)
, IsOurs (..)
, IsOwned (..)
, KnownAddresses (..)
)
import Cardano.Wallet.Primitive.AddressDiscovery.Random
( RndState )
import Cardano.Wallet.Primitive.AddressDiscovery.Sequential
( SeqState
, defaultAddressPoolGap
, mkSeqStateFromRootXPrv
, mkUnboundedAddressPoolGap
, shrinkPool
)
import Cardano.Wallet.Primitive.CoinSelection
( CoinSelection (..)
, CoinSelectionOptions (..)
, ErrCoinSelection (..)
, feeBalance
)
import Cardano.Wallet.Primitive.CoinSelection.Migration
( depleteUTxO, idealBatchSize )
import Cardano.Wallet.Primitive.Fee
( ErrAdjustForFee (..)
, Fee (..)
, FeeOptions (..)
, OnDanglingChange (..)
, adjustForFee
)
import Cardano.Wallet.Primitive.Model
( Wallet
, applyBlocks
, availableUTxO
, blockchainParameters
, currentTip
, getState
, initWallet
, updateState
)
import Cardano.Wallet.Primitive.Types
( Address (..)
, AddressState (..)
, Block (..)
, BlockHeader (..)
, ChimericAccount (..)
, Coin (..)
, DelegationCertificate (..)
, Direction (..)
, FeePolicy (LinearFee)
, GenesisParameters (..)
, Hash (..)
, IsDelegatingTo (..)
, NetworkParameters (..)
, PassphraseScheme (..)
, PoolId (..)
, ProtocolParameters (..)
, Range (..)
, SealedTx
, SlotId (..)
, SlotParameters (..)
, SortOrder (..)
, SyncProgress (..)
, SyncTolerance
, TransactionInfo (..)
, Tx
, TxMeta (..)
, TxOut (..)
, TxStatus (..)
, UTxO (..)
, UTxOStatistics
, UnsignedTx (..)
, WalletDelegation (..)
, WalletDelegationStatus (..)
, WalletId (..)
, WalletMetadata (..)
, WalletName (..)
, WalletPassphraseInfo (..)
, computeUtxoStatistics
, dlgCertPoolId
, fromTransactionInfo
, log10
, slotParams
, slotRangeFromTimeRange
, slotStartTime
, syncProgressRelativeToTime
, wholeRange
)
import Cardano.Wallet.Transaction
( DelegationAction (..)
, ErrDecodeSignedTx (..)
, ErrMkTx (..)
, ErrValidateSelection
, TransactionLayer (..)
)
import Control.Exception
( Exception )
import Control.Monad
( forM, forM_, replicateM, unless, when )
import Control.Monad.IO.Class
( MonadIO, liftIO )
import Control.Monad.Trans.Class
( lift )
import Control.Monad.Trans.Except
( ExceptT (..)
, catchE
, except
, mapExceptT
, runExceptT
, throwE
, withExceptT
)
import Control.Monad.Trans.Maybe
( MaybeT (..), maybeToExceptT )
import Control.Monad.Trans.State.Strict
( runStateT, state )
import Control.Tracer
( Tracer, contramap, traceWith )
import Data.ByteString
( ByteString )
import Data.Coerce
( coerce )
import Data.Either
( partitionEithers )
import Data.Either.Extra
( eitherToMaybe )
import Data.Foldable
( fold )
import Data.Function
( (&) )
import Data.Functor
( ($>) )
import Data.Generics.Internal.VL.Lens
( Lens', view, (^.) )
import Data.Generics.Labels
()
import Data.Generics.Product.Typed
( HasType, typed )
import Data.List.NonEmpty
( NonEmpty )
import Data.Maybe
( mapMaybe )
import Data.Quantity
( Quantity (..) )
import Data.Set
( Set )
import Data.Text.Class
( ToText (..) )
import Data.Time.Clock
( UTCTime, getCurrentTime )
import Data.Vector.Shuffle
( shuffle )
import Data.Word
( Word16, Word64 )
import Fmt
( blockListF, pretty, (+|), (|+) )
import GHC.Generics
( Generic )
import Numeric.Natural
( Natural )
import Safe
( lastMay )
import Statistics.Quantile
( medianUnbiased, quantiles )
import qualified Cardano.Wallet.Primitive.AddressDiscovery.Random as Rnd
import qualified Cardano.Wallet.Primitive.AddressDiscovery.Sequential as Seq
import qualified Cardano.Wallet.Primitive.CoinSelection.Random as CoinSelection
import qualified Cardano.Wallet.Primitive.Types as W
import qualified Data.List as L
import qualified Data.List.NonEmpty as NE
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Vector as V
-- $Development
-- __Naming Conventions__
--
-- Components inside a particular context `ctx` can be called via dedicated
-- lenses (see Cardano.Wallet#Capabilities). These components are extracted from the context
-- in a @where@ clause according to the following naming convention:
--
-- - @db = ctx ^. dbLayer \@s \\@k@ for the 'DBLayer'.
-- - @tr = ctx ^. logger@ for the Logger.
-- - @nw = ctx ^. networkLayer \@t@ for the 'NetworkLayer'.
-- - @tl = ctx ^. transactionLayer \\@k@ for the 'TransactionLayer'.
-- - @re = ctx ^. workerRegistry@ for the 'WorkerRegistry'.
--
-- __TroubleShooting__
--
-- @
-- • Overlapping instances for HasType (DBLayer IO s t k) ctx
-- arising from a use of ‘myFunction’
-- Matching instances:
-- @
--
-- Occurs when a particular function is missing a top-level constraint
-- (because it uses another function that demands such constraint). Here,
-- `myFunction` needs its surrounding context `ctx` to have a `DBLayer` but
-- the constraint is missing from its host function.
--
-- __Fix__: Add "@HasDBLayer s t k@" as a class-constraint to the surrounding function.
--
-- @
-- • Overlapping instances for HasType (DBLayer IO s t0 k0) ctx
-- arising from a use of ‘myFunction’
-- Matching givens (or their superclasses):
-- @
--
-- Occurs when a function is called in a context where type-level parameters
-- can be inferred. Here, `myFunction` is called but it is unclear
-- whether the parameter `t0` and `k0` of its context are the same as the ones
-- from the function at the call-site.
--
-- __Fix__: Add type-applications at the call-site "@myFunction \@ctx \@s \\@k@"
data WalletLayer s t (k :: Depth -> * -> *)
= WalletLayer
(Tracer IO WalletLog)
(Block, NetworkParameters, SyncTolerance)
(NetworkLayer IO t Block)
(TransactionLayer t k)
(DBLayer IO s k)
deriving (Generic)
{-------------------------------------------------------------------------------
Capabilities
-------------------------------------------------------------------------------}
-- $Capabilities
-- Each function in the wallet layer is defined in function of a non-specialized
-- context `ctx`. That context may require some extra capabilities via
-- class-constraints in the function signature. Capabilities are expressed in the
-- form of a "@HasXXX@" class-constraints sometimes with extra type parameters.
--
-- For example:
--
-- @
-- listWallets
-- :: forall ctx s t k.
-- ( HasDBLayer s t k ctx
-- )
-- => ctx
-- -> IO [WalletId]
-- @
--
-- Requires that the given context has an access to a database layer 'DBLayer'
-- parameterized over the wallet state, a network target and a key derivation
-- scheme. Components are pulled from the context generically (i.e. the concrete
-- `ctx` must derive 'Generic') using their associated type. The concrete `ctx`
-- is therefore expected to be a product-type of all the necessary components.
--
-- One can build an interface using only a subset of the wallet layer
-- capabilities and functions, for instance, something to fiddle with wallets
-- and their metadata does not require any networking layer.
type HasDBLayer s k = HasType (DBLayer IO s k)
type HasGenesisData = HasType (Block, NetworkParameters, SyncTolerance)
type HasLogger msg = HasType (Tracer IO msg)
-- | This module is only interested in one block-, and tx-type. This constraint
-- hides that choice, for some ease of use.
type HasNetworkLayer t = HasType (NetworkLayer IO t Block)
type HasTransactionLayer t k = HasType (TransactionLayer t k)
dbLayer
:: forall s k ctx. HasDBLayer s k ctx
=> Lens' ctx (DBLayer IO s k)
dbLayer =
typed @(DBLayer IO s k)
genesisData
:: forall ctx. HasGenesisData ctx
=> Lens' ctx (Block, NetworkParameters, SyncTolerance)
genesisData =
typed @(Block, NetworkParameters, SyncTolerance)
logger
:: forall msg ctx. HasLogger msg ctx
=> Lens' ctx (Tracer IO msg)
logger =
typed @(Tracer IO msg)
networkLayer
:: forall t ctx. (HasNetworkLayer t ctx)
=> Lens' ctx (NetworkLayer IO t Block)
networkLayer =
typed @(NetworkLayer IO t Block)
transactionLayer
:: forall t k ctx. (HasTransactionLayer t k ctx)
=> Lens' ctx (TransactionLayer t k)
transactionLayer =
typed @(TransactionLayer t k)
{-------------------------------------------------------------------------------
Wallet
-------------------------------------------------------------------------------}
-- | Initialise and store a new wallet, returning its ID.
createWallet
:: forall ctx s k.
( HasGenesisData ctx
, HasDBLayer s k ctx
, IsOurs s Address
, IsOurs s ChimericAccount
)
=> ctx
-> WalletId
-> WalletName
-> s
-> ExceptT ErrWalletAlreadyExists IO WalletId
createWallet ctx wid wname s = db & \DBLayer{..} -> do
let (hist, cp) = initWallet block0 gp s
now <- lift getCurrentTime
let meta = WalletMetadata
{ name = wname
, creationTime = now
, passphraseInfo = Nothing
, delegation = WalletDelegation NotDelegating []
}
mapExceptT atomically $
initializeWallet (PrimaryKey wid) cp meta hist pp $> wid
where
db = ctx ^. dbLayer @s @k
(block0, NetworkParameters gp pp, _) = ctx ^. genesisData
-- | Initialise and store a new legacy Icarus wallet. These wallets are
-- intrinsically sequential, but, in the incentivized testnet, we only have
-- access to the a snapshot of the MainNet.
--
-- To work-around this, we scan the genesis block with an arbitrary big gap and
-- resort to a default gap afterwards.
createIcarusWallet
:: forall ctx s k n.
( HasGenesisData ctx
, HasDBLayer s k ctx
, PaymentAddress n k
, k ~ IcarusKey
, s ~ SeqState n k
)
=> ctx
-> WalletId
-> WalletName
-> (k 'RootK XPrv, Passphrase "encryption")
-> ExceptT ErrWalletAlreadyExists IO WalletId
createIcarusWallet ctx wid wname credentials = db & \DBLayer{..} -> do
let s = mkSeqStateFromRootXPrv @n credentials $
mkUnboundedAddressPoolGap 10000
let (hist, cp) = initWallet block0 gp s
let addrs = map address . concatMap (view #outputs . fst) $ hist
let g = defaultAddressPoolGap
let s' = Seq.SeqState
(shrinkPool @n (liftPaymentAddress @n) addrs g (Seq.internalPool s))
(shrinkPool @n (liftPaymentAddress @n) addrs g (Seq.externalPool s))
(Seq.pendingChangeIxs s)
(Seq.rewardAccountKey s)
now <- lift getCurrentTime
let meta = WalletMetadata
{ name = wname
, creationTime = now
, passphraseInfo = Nothing
, delegation = WalletDelegation NotDelegating []
}
let pk = PrimaryKey wid
mapExceptT atomically $
initializeWallet pk (updateState s' cp) meta hist pp $> wid
where
db = ctx ^. dbLayer @s @k
(block0, NetworkParameters gp pp, _) = ctx ^. genesisData
-- | Check whether a wallet is in good shape when restarting a worker.
checkWalletIntegrity
:: forall ctx s k. HasDBLayer s k ctx
=> ctx
-> WalletId
-> GenesisParameters
-> ExceptT ErrCheckWalletIntegrity IO ()
checkWalletIntegrity ctx wid gp = db & \DBLayer{..} -> mapExceptT atomically $ do
cp <- withExceptT ErrCheckWalletIntegrityNoSuchWallet $ withNoSuchWallet wid $
readCheckpoint (PrimaryKey wid)
whenDifferentGenesis (blockchainParameters cp) gp $ throwE $
ErrCheckIntegrityDifferentGenesis
(getGenesisBlockHash gp)
(getGenesisBlockHash (blockchainParameters cp))
where
db = ctx ^. dbLayer @s @k
whenDifferentGenesis bp1 bp2 = when $
(bp1 ^. #getGenesisBlockHash /= bp2 ^. #getGenesisBlockHash) ||
(bp1 ^. #getGenesisBlockDate /= bp2 ^. #getGenesisBlockDate)
-- | Retrieve the wallet state for the wallet with the given ID.
readWallet
:: forall ctx s k. HasDBLayer s k ctx
=> ctx
-> WalletId
-> ExceptT ErrNoSuchWallet IO (Wallet s, WalletMetadata, Set Tx)
readWallet ctx wid = db & \DBLayer{..} -> mapExceptT atomically $ do
let pk = PrimaryKey wid
cp <- withNoSuchWallet wid $ readCheckpoint pk
meta <- withNoSuchWallet wid $ readWalletMeta pk
pending <- lift $ readTxHistory pk Descending wholeRange (Just Pending)
pure (cp, meta, Set.fromList (fromTransactionInfo <$> pending))
where
db = ctx ^. dbLayer @s @k
readWalletProtocolParameters
:: forall ctx s k. HasDBLayer s k ctx
=> ctx
-> WalletId
-> ExceptT ErrNoSuchWallet IO ProtocolParameters
readWalletProtocolParameters ctx wid = db & \DBLayer{..} ->
mapExceptT atomically $
withNoSuchWallet wid $
readProtocolParameters (PrimaryKey wid)
where
db = ctx ^. dbLayer @s @k
walletSyncProgress
:: forall ctx s.
( HasGenesisData ctx
)
=> ctx
-> Wallet s
-> IO SyncProgress
walletSyncProgress ctx w = do
let gp = blockchainParameters w
let h = currentTip w
syncProgressRelativeToTime st (slotParams gp) h <$> getCurrentTime
where
(_, _, st) = ctx ^. genesisData
-- | Update a wallet's metadata with the given update function.
updateWallet
:: forall ctx s k.
( HasDBLayer s k ctx
)
=> ctx
-> WalletId
-> (WalletMetadata -> WalletMetadata)
-> ExceptT ErrNoSuchWallet IO ()
updateWallet ctx wid modify = db & \DBLayer{..} -> mapExceptT atomically $ do
meta <- withNoSuchWallet wid $ readWalletMeta (PrimaryKey wid)
putWalletMeta (PrimaryKey wid) (modify meta)
where
db = ctx ^. dbLayer @s @k
-- | Change a wallet's passphrase to the given passphrase.
updateWalletPassphrase
:: forall ctx s k.
( HasDBLayer s k ctx
, WalletKey k
)
=> ctx
-> WalletId
-> (Passphrase "raw", Passphrase "raw")
-> ExceptT ErrUpdatePassphrase IO ()
updateWalletPassphrase ctx wid (old, new) =
withRootKey @ctx @s @k ctx wid (coerce old) ErrUpdatePassphraseWithRootKey
$ \xprv scheme -> withExceptT ErrUpdatePassphraseNoSuchWallet $ do
-- NOTE
-- /!\ Important /!\
-- attachPrivateKeyFromPwd does use 'EncryptWithPBKDF2', so
-- regardless of the passphrase current scheme, we'll re-encrypt
-- it using the new scheme, always.
let oldP = preparePassphrase scheme old
let newP = preparePassphrase EncryptWithPBKDF2 new
let xprv' = changePassphrase oldP newP xprv
attachPrivateKeyFromPwd @ctx @s @k ctx wid (xprv', newP)
-- | List the wallet's UTxO statistics.
listUtxoStatistics
:: forall ctx s k. HasDBLayer s k ctx
=> ctx
-> WalletId
-> ExceptT ErrListUTxOStatistics IO UTxOStatistics
listUtxoStatistics ctx wid = do
(wal, _, pending) <- withExceptT
ErrListUTxOStatisticsNoSuchWallet (readWallet @ctx @s @k ctx wid)
let utxo = availableUTxO @s pending wal
pure $ computeUtxoStatistics log10 utxo
-- | Restore a wallet from its current tip up to the network tip.
--
-- This function returns immediately, starting a worker thread in the
-- background that will fetch and apply remaining blocks until the
-- network tip is reached or until failure.
restoreWallet
:: forall ctx s t k.
( HasLogger WalletLog ctx
, HasNetworkLayer t ctx
, HasDBLayer s k ctx
, HasGenesisData ctx
, IsOurs s Address
, IsOurs s ChimericAccount
)
=> ctx
-> WalletId
-> ExceptT ErrNoSuchWallet IO ()
restoreWallet ctx wid = db & \DBLayer{..} -> do
cps <- liftIO $ atomically $ listCheckpoints (PrimaryKey wid)
let forward bs (h, ps) = run $ do
restoreBlocks @ctx @s @k ctx wid bs h
saveParams @ctx @s @k ctx wid ps
liftIO (follow nw tr cps forward (view #header)) >>= \case
FollowInterrupted -> pure ()
FollowFailure ->
restoreWallet @ctx @s @t @k ctx wid
FollowRollback point -> do
rollbackBlocks @ctx @s @k ctx wid point
restoreWallet @ctx @s @t @k ctx wid
where
db = ctx ^. dbLayer @s @k
nw = ctx ^. networkLayer @t
tr = contramap MsgFollow (ctx ^. logger @WalletLog)
run :: ExceptT ErrNoSuchWallet IO () -> IO (FollowAction ErrNoSuchWallet)
run = fmap (either ExitWith (const Continue)) . runExceptT
-- | Rewind the UTxO snapshots, transaction history and other information to a
-- the earliest point in the past that is before or is the point of rollback.
rollbackBlocks
:: forall ctx s k.
( HasLogger WalletLog ctx
, HasDBLayer s k ctx
)
=> ctx
-> WalletId
-> SlotId
-> ExceptT ErrNoSuchWallet IO ()
rollbackBlocks ctx wid point = db & \DBLayer{..} -> do
lift $ traceWith tr $ MsgTryingRollback point
point' <- mapExceptT atomically $ rollbackTo (PrimaryKey wid) point
lift $ traceWith tr $ MsgRolledBack point'
where
db = ctx ^. dbLayer @s @k
tr = ctx ^. logger @WalletLog
-- | Apply the given blocks to the wallet and update the wallet state,
-- transaction history and corresponding metadata.
restoreBlocks
:: forall ctx s k.
( HasLogger WalletLog ctx
, HasDBLayer s k ctx
, HasGenesisData ctx
, IsOurs s Address
, IsOurs s ChimericAccount
)
=> ctx
-> WalletId
-> NonEmpty Block
-> BlockHeader
-> ExceptT ErrNoSuchWallet IO ()
restoreBlocks ctx wid blocks nodeTip = db & \DBLayer{..} -> mapExceptT atomically $ do
cp <- withNoSuchWallet wid (readCheckpoint $ PrimaryKey wid)
meta <- withNoSuchWallet wid (readWalletMeta $ PrimaryKey wid)
let gp = blockchainParameters cp
unless (cp `isParentOf` NE.head blocks) $ fail $ T.unpack $ T.unwords
[ "restoreBlocks: given chain isn't a valid continuation."
, "Wallet is at:", pretty (currentTip cp)
, "but the given chain continues starting from:"
, pretty (header (NE.head blocks))
]
let (filteredBlocks, cps) = NE.unzip $ applyBlocks @s blocks cp
let slotPoolDelegations =
[ (slotId, cert)
| let slots = view #slotId . view #header <$> blocks
, let delegations = view #delegations <$> filteredBlocks
, (slotId, certs) <- NE.toList $ NE.zip slots delegations
, cert <- certs
]
let txs = fold $ view #transactions <$> filteredBlocks
let k = gp ^. #getEpochStability
let localTip = currentTip $ NE.last cps
putTxHistory (PrimaryKey wid) txs
forM_ slotPoolDelegations $ \delegation@(slotId, cert) -> do
liftIO $ logDelegation delegation
putDelegationCertificate (PrimaryKey wid) cert slotId
let unstable = sparseCheckpoints k (nodeTip ^. #blockHeight)
forM_ (NE.init cps) $ \cp' -> do
let (Quantity h) = currentTip cp' ^. #blockHeight
when (fromIntegral h `elem` unstable) $ do
liftIO $ logCheckpoint cp'
putCheckpoint (PrimaryKey wid) cp'
liftIO $ logCheckpoint (NE.last cps)
putCheckpoint (PrimaryKey wid) (NE.last cps)
prune (PrimaryKey wid)
liftIO $ do
progress <- walletSyncProgress @ctx ctx (NE.last cps)
traceWith tr $ MsgWalletMetadata meta
traceWith tr $ MsgSyncProgress progress
traceWith tr $ MsgDiscoveredTxs txs
traceWith tr $ MsgTip localTip
traceWith tr $ MsgBlocks blocks
traceWith tr $ MsgDiscoveredTxsContent txs
where
db = ctx ^. dbLayer @s @k
tr = ctx ^. logger @WalletLog
logCheckpoint :: Wallet s -> IO ()
logCheckpoint cp = traceWith tr $ MsgCheckpoint (currentTip cp)
logDelegation :: (SlotId, DelegationCertificate) -> IO ()
logDelegation (slotId, cert) = traceWith tr $ MsgDelegation slotId cert
isParentOf :: Wallet s -> Block -> Bool
isParentOf cp = (== parent) . parentHeaderHash . header
where parent = headerHash $ currentTip cp
-- | Store the node tip params into the wallet database
saveParams
:: forall ctx s k.
( HasDBLayer s k ctx
)
=> ctx
-> WalletId
-> ProtocolParameters
-> ExceptT ErrNoSuchWallet IO ()
saveParams ctx wid params = db & \DBLayer{..} ->
mapExceptT atomically $ putProtocolParameters (PrimaryKey wid) params
where
db = ctx ^. dbLayer @s @k
-- | Remove an existing wallet. Note that there's no particular work to
-- be done regarding the restoration worker as it will simply terminate
-- on the next tick when noticing that the corresponding wallet is gone.
deleteWallet
:: forall ctx s k.
( HasDBLayer s k ctx
)
=> ctx
-> WalletId
-> ExceptT ErrNoSuchWallet IO ()
deleteWallet ctx wid = db & \DBLayer{..} -> do
mapExceptT atomically $ removeWallet (PrimaryKey wid)
where
db = ctx ^. dbLayer @s @k
-- | Fetch the cached reward balance of a given wallet from the database.
fetchRewardBalance
:: forall ctx s k.
( HasDBLayer s k ctx
)
=> ctx
-> WalletId
-> IO (Quantity "lovelace" Word64)
fetchRewardBalance ctx wid = db & \DBLayer{..} ->
atomically $ readDelegationRewardBalance pk
where
pk = PrimaryKey wid
db = ctx ^. dbLayer @s @k
-- | Read the current withdrawal capacity of a wallet. Note that, this simply
-- returns 0 if:
--
-- a) There's no reward account for this type of wallet.
-- b) The current reward value is too small to be considered (adding it would
-- cost more than its value).
readNextWithdrawal
:: forall ctx s t k.
( HasDBLayer s k ctx
, HasTransactionLayer t k ctx
)
=> ctx
-> WalletId
-> IO (Quantity "lovelace" Word64)
readNextWithdrawal ctx wid = db & \DBLayer{..} -> do
(pp, withdrawal) <- atomically $ (,)
<$> readProtocolParameters pk
<*> fmap getQuantity (readDelegationRewardBalance pk)
case pp of
-- May happen if done very early, in which case, rewards are probably
-- not woth considering anyway.
Nothing -> pure (Quantity 0)
Just ProtocolParameters{txParameters} -> do
let policy = W.getFeePolicy txParameters
let costOfWithdrawal =
minFee policy (mempty { withdrawal })
-
minFee policy mempty
pure $ if toInteger withdrawal < 2 * costOfWithdrawal
then Quantity 0
else Quantity withdrawal
where
db = ctx ^. dbLayer @s @k
tl = ctx ^. transactionLayer @t @k
pk = PrimaryKey wid
minFee :: FeePolicy -> CoinSelection -> Integer
minFee policy = fromIntegral . getFee . minimumFee tl policy Nothing
-- | Query the node for the reward balance of a given wallet.
--
-- Rather than force all callers of 'readWallet' to wait for fetching the
-- account balance (via the 'NetworkLayer'), we expose this function for it.
queryRewardBalance
:: forall ctx s t k.
( HasDBLayer s k ctx
, HasNetworkLayer t ctx
, HasRewardAccount s k
)
=> ctx
-> WalletId
-> ExceptT ErrFetchRewards IO (Quantity "lovelace" Word64)
queryRewardBalance ctx wid = db & \DBLayer{..} -> do
cp <- withExceptT ErrFetchRewardsNoSuchWallet
. mapExceptT atomically
. withNoSuchWallet wid
$ readCheckpoint pk
mapExceptT (fmap handleErr)
. getAccountBalance nw
. toChimericAccount @s @k
. rewardAccountKey
$ getState cp
where
pk = PrimaryKey wid
db = ctx ^. dbLayer @s @k
nw = ctx ^. networkLayer @t
handleErr = \case
Right x -> Right x
Left (ErrGetAccountBalanceAccountNotFound _) ->
Right $ Quantity 0
Left (ErrGetAccountBalanceNetworkUnreachable e) ->
Left $ ErrFetchRewardsNetworkUnreachable e
manageRewardBalance
:: forall ctx s t k.
( HasLogger WalletLog ctx
, HasNetworkLayer t ctx
, HasDBLayer s k ctx
, HasRewardAccount s k
, ctx ~ WalletLayer s t k
)
=> ctx
-> WalletId
-> IO ()
manageRewardBalance ctx wid = db & \DBLayer{..} -> do
watchNodeTip $ \bh -> do
traceWith tr $ MsgRewardBalanceQuery bh
query <- runExceptT $ queryRewardBalance @ctx @s @t @k ctx wid
traceWith tr $ MsgRewardBalanceResult query
case query of
Right amt -> do
res <- atomically $ runExceptT $ putDelegationRewardBalance pk amt
-- It can happen that the wallet doesn't exist _yet_, whereas we
-- already have a reward balance. If that's the case, we log and
-- move on.
case res of
Left err -> traceWith tr $ MsgRewardBalanceNoSuchWallet err
Right () -> pure ()
Left _err ->
-- Occasionaly failing to query is generally not fatal. It will
-- just update the balance next time the tip changes.
pure ()
traceWith tr MsgRewardBalanceExited
where
pk = PrimaryKey wid
db = ctx ^. dbLayer @s @k
NetworkLayer{watchNodeTip} = ctx ^. networkLayer @t
tr = ctx ^. logger @WalletLog
{-------------------------------------------------------------------------------
Address
-------------------------------------------------------------------------------}
-- | List all addresses of a wallet with their metadata. Addresses
-- are ordered from the most-recently-discovered to the oldest known.
listAddresses
:: forall ctx s k.
( HasDBLayer s k ctx