-
Notifications
You must be signed in to change notification settings - Fork 216
/
Wallet.hs
3459 lines (3193 loc) · 120 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 TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ViewPatterns #-}
-- |
-- 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@.
--
-- - @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
(
-- * Development
-- $Development
-- * WalletLayer
WalletLayer (..)
-- * Capabilities
-- $Capabilities
, HasDBLayer
, dbLayer
, HasLogger
, logger
, HasNetworkLayer
, networkLayer
, HasTransactionLayer
, transactionLayer
, HasGenesisData
, genesisData
-- * Interface
-- ** Wallet
, createWallet
, createIcarusWallet
, attachPrivateKeyFromPwd
, attachPrivateKeyFromPwdHash
, getWalletUtxoSnapshot
, listUtxoStatistics
, readWallet
, deleteWallet
, restoreWallet
, updateWallet
, updateWalletPassphrase
, walletSyncProgress
, fetchRewardBalance
, manageRewardBalance
, rollbackBlocks
, checkWalletIntegrity
, readNextWithdrawal
, readRewardAccount
, someRewardAccount
, queryRewardBalance
, ErrWalletAlreadyExists (..)
, ErrNoSuchWallet (..)
, ErrListUTxOStatistics (..)
, ErrUpdatePassphrase (..)
, ErrFetchRewards (..)
, ErrCheckWalletIntegrity (..)
, ErrWalletNotResponding (..)
, ErrReadRewardAccount (..)
-- * Shared Wallet
, updateCosigner
, ErrAddCosignerKey (..)
, ErrConstructSharedWallet (..)
, normalizeSharedAddress
-- ** Address
, createRandomAddress
, importRandomAddresses
, listAddresses
, normalizeDelegationAddress
, lookupTxIns
, lookupTxOuts
, ErrCreateRandomAddress(..)
, ErrImportRandomAddress(..)
, ErrImportAddress(..)
, ErrDecodeTx (..)
-- ** Payment
, getTxExpiry
, SelectAssetsParams (..)
, selectAssets
, readWalletUTxOIndex
, assignChangeAddresses
, assignChangeAddressesAndUpdateDb
, assignChangeAddressesWithoutDbUpdate
, selectionToUnsignedTx
, buildAndSignTransaction
, signTransaction
, constructTransaction
, constructTxMeta
, ErrSelectAssets(..)
, ErrSignPayment (..)
, ErrNotASequentialWallet (..)
, ErrWithdrawalNotWorth (..)
, ErrConstructTx (..)
, ErrMintBurnAssets (..)
, ErrBalanceTx (..)
, BalanceTxNotSupportedReason (..)
, ErrUpdateSealedTx (..)
, ErrCannotJoin (..)
, ErrCannotQuit (..)
, ErrSubmitTransaction (..)
-- ** Migration
, createMigrationPlan
, migrationPlanToSelectionWithdrawals
, SelectionWithoutChange
, ErrCreateMigrationPlan (..)
-- ** Delegation
, PoolRetirementEpochInfo (..)
, joinStakePool
, quitStakePool
, guardJoin
, guardQuit
, ErrStakePoolDelegation (..)
-- ** Fee Estimation
, FeeEstimation (..)
, estimateFee
, calcMinimumDeposit
, calcMinimumCoinValues
-- ** Transaction
, forgetTx
, listTransactions
, getTransaction
, submitExternalTx
, submitTx
, balanceTransaction
, PartialTx (..)
, LocalTxSubmissionConfig (..)
, defaultLocalTxSubmissionConfig
, runLocalTxSubmissionPool
, ErrMkTransaction (..)
, ErrSubmitTx (..)
, ErrRemoveTx (..)
, ErrPostTx (..)
, ErrListTransactions (..)
, ErrGetTransaction (..)
, ErrNoSuchTransaction (..)
, ErrStartTimeLaterThanEndTime (..)
, ErrWitnessTx (..)
-- ** Root Key
, withRootKey
, derivePublicKey
, getAccountPublicKeyAtIndex
, readAccountPublicKey
, signMetadataWith
, ErrWithRootKey (..)
, ErrWrongPassphrase (..)
, ErrSignMetadataWith (..)
, ErrDerivePublicKey(..)
, ErrReadAccountPublicKey(..)
, ErrInvalidDerivationIndex(..)
-- * Utilities
, throttle
, guardHardIndex
, withNoSuchWallet
-- * Logging
, WalletWorkerLog (..)
, WalletFollowLog (..)
, WalletLog (..)
, TxSubmitLog (..)
) where
import Prelude hiding
( log )
import Cardano.Address.Derivation
( XPrv, XPub )
import Cardano.Address.Script
( Cosigner (..) )
import Cardano.Api
( serialiseToCBOR )
import Cardano.BM.Data.Severity
( Severity (..) )
import Cardano.BM.Data.Tracer
( HasPrivacyAnnotation (..), HasSeverityAnnotation (..) )
import Cardano.Crypto.Wallet
( toXPub )
import Cardano.Slotting.Slot
( SlotNo (..) )
import Cardano.Wallet.DB
( DBLayer (..)
, ErrNoSuchTransaction (..)
, ErrNoSuchWallet (..)
, ErrPutLocalTxSubmission (..)
, ErrRemoveTx (..)
, ErrWalletAlreadyExists (..)
, SparseCheckpointsConfig (..)
, defaultSparseCheckpointsConfig
, sparseCheckpoints
)
import Cardano.Wallet.Logging
( BracketLog
, BracketLog' (..)
, bracketTracer
, formatResultMsg
, resultSeverity
, traceResult
, unliftIOTracer
)
import Cardano.Wallet.Network
( ChainFollowLog (..)
, ChainFollower (..)
, ErrPostTx (..)
, NetworkLayer (..)
)
import Cardano.Wallet.Primitive.AddressDerivation
( DelegationAddress (..)
, Depth (..)
, DerivationIndex (..)
, DerivationPrefix (..)
, DerivationType (..)
, ErrWrongPassphrase (..)
, HardDerivation (..)
, Index (..)
, MkKeyFingerprint (..)
, NetworkDiscriminant (..)
, Passphrase
, PaymentAddress (..)
, Role (..)
, SoftDerivation (..)
, ToRewardAccount (..)
, WalletKey (..)
, checkPassphrase
, deriveRewardAccount
, encryptPassphrase
, liftIndex
, preparePassphrase
, stakeDerivationPath
)
import Cardano.Wallet.Primitive.AddressDerivation.Byron
( ByronKey )
import Cardano.Wallet.Primitive.AddressDerivation.Icarus
( IcarusKey )
import Cardano.Wallet.Primitive.AddressDerivation.SharedKey
( SharedKey (..) )
import Cardano.Wallet.Primitive.AddressDerivation.Shelley
( ShelleyKey, deriveAccountPrivateKeyShelley )
import Cardano.Wallet.Primitive.AddressDiscovery
( CompareDiscovery (..)
, GenChange (..)
, GetAccount (..)
, GetPurpose (..)
, IsOurs (..)
, IsOwned (..)
, KnownAddresses (..)
)
import Cardano.Wallet.Primitive.AddressDiscovery.Random
( ErrImportAddress (..), RndStateLike )
import Cardano.Wallet.Primitive.AddressDiscovery.Sequential
( SeqState, defaultAddressPoolGap, mkSeqStateFromRootXPrv, purposeBIP44 )
import Cardano.Wallet.Primitive.AddressDiscovery.Shared
( CredentialType (..)
, ErrAddCosigner (..)
, ErrScriptTemplate (..)
, SharedState (..)
, addCosignerAccXPub
)
import Cardano.Wallet.Primitive.CoinSelection
( Selection
, SelectionCollateralRequirement (..)
, SelectionConstraints (..)
, SelectionError (..)
, SelectionOf (..)
, SelectionOutputInvalidError (..)
, SelectionParams (..)
, SelectionReportDetailed
, SelectionReportSummarized
, makeSelectionReportDetailed
, makeSelectionReportSummarized
, performSelection
, selectionDelta
)
import Cardano.Wallet.Primitive.CoinSelection.Balance
( SelectionSkeleton (..), emptySkeleton )
import Cardano.Wallet.Primitive.Collateral
( asCollateral )
import Cardano.Wallet.Primitive.Migration
( MigrationPlan (..) )
import Cardano.Wallet.Primitive.Model
( Wallet
, applyBlocks
, availableUTxO
, currentTip
, getState
, initWallet
, totalUTxO
, updateState
)
import Cardano.Wallet.Primitive.Slotting
( PastHorizonException (..)
, TimeInterpreter
, addRelTime
, ceilingSlotAt
, currentRelativeTime
, interpretQuery
, neverFails
, slotRangeFromTimeRange
, slotToUTCTime
, unsafeExtendSafeZone
)
import Cardano.Wallet.Primitive.SyncProgress
( SyncProgress, SyncTolerance (..) )
import Cardano.Wallet.Primitive.Types
( ActiveSlotCoefficient (..)
, Block (..)
, BlockHeader (..)
, ChainPoint (..)
, DelegationCertificate (..)
, FeePolicy (LinearFee)
, GenesisParameters (..)
, IsDelegatingTo (..)
, NetworkParameters (..)
, PassphraseScheme (..)
, PoolId (..)
, PoolLifeCycleStatus (..)
, ProtocolParameters (..)
, Range (..)
, Signature (..)
, Slot
, SlottingParameters (..)
, SortOrder (..)
, WalletDelegation (..)
, WalletDelegationStatus (..)
, WalletId (..)
, WalletMetadata (..)
, WalletName (..)
, WalletPassphraseInfo (..)
, dlgCertPoolId
, toSlot
, wholeRange
)
import Cardano.Wallet.Primitive.Types.Address
( Address (..), AddressState (..) )
import Cardano.Wallet.Primitive.Types.Coin
( Coin (..) )
import Cardano.Wallet.Primitive.Types.Hash
( Hash (..) )
import Cardano.Wallet.Primitive.Types.Redeemer
( Redeemer (..), redeemerData )
import Cardano.Wallet.Primitive.Types.RewardAccount
( RewardAccount (..) )
import Cardano.Wallet.Primitive.Types.TokenBundle
( TokenBundle )
import Cardano.Wallet.Primitive.Types.TokenMap
( TokenMap )
import Cardano.Wallet.Primitive.Types.Tx
( Direction (..)
, LocalTxSubmissionStatus
, SealedTx (..)
, TransactionInfo (..)
, Tx (..)
, TxChange (..)
, TxIn (..)
, TxMeta (..)
, TxMetadata (..)
, TxOut (..)
, TxStatus (..)
, UnsignedTx (..)
, fromTransactionInfo
, txOutAddCoin
, txOutCoin
, withdrawals
)
import Cardano.Wallet.Primitive.Types.UTxO
( UTxO (..), UTxOStatistics, computeUtxoStatistics, log10 )
import Cardano.Wallet.Primitive.Types.UTxOIndex
( UTxOIndex )
import Cardano.Wallet.Primitive.Types.UTxOSelection
( UTxOSelection )
import Cardano.Wallet.Transaction
( DelegationAction (..)
, ErrAssignRedeemers
, ErrCannotJoin (..)
, ErrCannotQuit (..)
, ErrMkTransaction (..)
, ErrSignTx (..)
, ErrUpdateSealedTx (..)
, TransactionCtx (..)
, TransactionLayer (..)
, TxFeeUpdate (..)
, TxUpdate (..)
, Withdrawal (..)
, defaultTransactionCtx
, withdrawalToCoin
)
import Cardano.Wallet.Util
( mapFirst )
import Control.Applicative
( (<|>) )
import Control.Arrow
( left )
import Control.DeepSeq
( NFData )
import Control.Monad
( forM, forM_, replicateM, unless, when )
import Control.Monad.Class.MonadTime
( DiffTime
, MonadMonotonicTime (..)
, MonadTime (..)
, Time
, diffTime
, getCurrentTime
)
import Control.Monad.IO.Unlift
( MonadIO (..), MonadUnliftIO )
import Control.Monad.Random.Class
( MonadRandom (..) )
import Control.Monad.Random.Extra
( StdGenSeed (..), stdGenFromSeed, stdGenSeed )
import Control.Monad.Random.Strict
( evalRand )
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
( evalState, runState, state )
import Control.Tracer
( Tracer, contramap, traceWith )
import Crypto.Hash
( Blake2b_256, hash )
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.IntCast
( intCast )
import Data.Kind
( Type )
import Data.List
( scanl' )
import Data.List.NonEmpty
( NonEmpty (..) )
import Data.Maybe
( fromMaybe, mapMaybe )
import Data.Proxy
( Proxy )
import Data.Quantity
( Quantity (..) )
import Data.Set
( Set )
import Data.Text
( Text )
import Data.Text.Class
( ToText (..) )
import Data.Time.Clock
( NominalDiffTime, UTCTime )
import Data.Type.Equality
( (:~:) (..), testEquality )
import Data.Void
( Void )
import Data.Word
( Word16, Word64 )
import Fmt
( Buildable
, Builder
, blockListF
, blockMapF
, build
, listF'
, nameF
, pretty
, unlinesF
, (+|)
, (+||)
, (|+)
, (||+)
)
import GHC.Generics
( Generic )
import Safe
( lastMay )
import Statistics.Quantile
( medianUnbiased, quantiles )
import Type.Reflection
( Typeable, typeRep )
import UnliftIO.Exception
( Exception, catch, throwIO )
import UnliftIO.MVar
( modifyMVar_, newMVar )
import qualified Cardano.Api.Shelley as Cardano
import qualified Cardano.Crypto.Wallet as CC
import qualified Cardano.Wallet.Primitive.AddressDiscovery.Random as Rnd
import qualified Cardano.Wallet.Primitive.AddressDiscovery.Sequential as Seq
import qualified Cardano.Wallet.Primitive.AddressDiscovery.Shared as Shared
import qualified Cardano.Wallet.Primitive.CoinSelection.Balance as Balance
import qualified Cardano.Wallet.Primitive.Migration as Migration
import qualified Cardano.Wallet.Primitive.Types as W
import qualified Cardano.Wallet.Primitive.Types.Coin as Coin
import qualified Cardano.Wallet.Primitive.Types.TokenBundle as TokenBundle
import qualified Cardano.Wallet.Primitive.Types.TokenMap as TokenMap
import qualified Cardano.Wallet.Primitive.Types.UTxO as UTxO
import qualified Cardano.Wallet.Primitive.Types.UTxOIndex as UTxOIndex
import qualified Cardano.Wallet.Primitive.Types.UTxOSelection as UTxOSelection
import qualified Data.ByteArray as BA
import qualified Data.ByteString as BS
import qualified Data.Foldable as F
import qualified Data.List as L
import qualified Data.List.NonEmpty as NE
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Vector as V
import Text.Pretty.Simple
( pShow )
-- $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@ for the 'NetworkLayer'.
-- - @tl = ctx ^. transactionLayer \\@k@ for the 'TransactionLayer'.
-- - @re = ctx ^. workerRegistry@ for the 'WorkerRegistry'.
--
-- __TroubleShooting__
--
-- @
-- • Overlapping instances for HasType (DBLayer IO s 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 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 m s (k :: Depth -> Type -> Type)
= WalletLayer
(Tracer m WalletWorkerLog)
(Block, NetworkParameters, SyncTolerance)
(NetworkLayer m Block)
(TransactionLayer k SealedTx)
(DBLayer m 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 k.
-- ( HasDBLayer s 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 m s k = HasType (DBLayer m s k)
type HasGenesisData = HasType (Block, NetworkParameters, SyncTolerance)
type HasLogger m msg = HasType (Tracer m msg)
-- | This module is only interested in one block-, and tx-type. This constraint
-- hides that choice, for some ease of use.
type HasNetworkLayer m = HasType (NetworkLayer m Block)
type HasTransactionLayer k = HasType (TransactionLayer k SealedTx)
dbLayer
:: forall m s k ctx. HasDBLayer m s k ctx
=> Lens' ctx (DBLayer m s k)
dbLayer =
typed @(DBLayer m s k)
genesisData
:: forall ctx. HasGenesisData ctx
=> Lens' ctx (Block, NetworkParameters, SyncTolerance)
genesisData =
typed @(Block, NetworkParameters, SyncTolerance)
logger
:: forall m msg ctx. HasLogger m msg ctx
=> Lens' ctx (Tracer m msg)
logger =
typed @(Tracer m msg)
networkLayer
:: forall m ctx. (HasNetworkLayer m ctx)
=> Lens' ctx (NetworkLayer m Block)
networkLayer =
typed @(NetworkLayer m Block)
transactionLayer
:: forall k ctx. (HasTransactionLayer k ctx)
=> Lens' ctx (TransactionLayer k SealedTx)
transactionLayer =
typed @(TransactionLayer k SealedTx)
{-------------------------------------------------------------------------------
Wallet
-------------------------------------------------------------------------------}
-- | Initialise and store a new wallet, returning its ID.
createWallet
:: forall ctx m s k.
( MonadUnliftIO m
, MonadTime m
, HasGenesisData ctx
, HasDBLayer m s k ctx
, IsOurs s Address
, IsOurs s RewardAccount
)
=> ctx
-> WalletId
-> WalletName
-> s
-> ExceptT ErrWalletAlreadyExists m WalletId
createWallet ctx wid wname s = db & \DBLayer{..} -> do
let (hist, cp) = initWallet block0 s
now <- lift getCurrentTime
let meta = WalletMetadata
{ name = wname
, creationTime = now
, passphraseInfo = Nothing
, delegation = WalletDelegation NotDelegating []
}
mapExceptT atomically $
initializeWallet wid cp meta hist gp $> wid
where
db = ctx ^. dbLayer @m @s @k
(block0, NetworkParameters gp _sp _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 IO s k ctx
, PaymentAddress n k
, k ~ IcarusKey
, s ~ SeqState n k
, Typeable n
)
=> ctx
-> WalletId
-> WalletName
-> (k 'RootK XPrv, Passphrase "encryption")
-> ExceptT ErrWalletAlreadyExists IO WalletId
createIcarusWallet ctx wid wname credentials = db & \DBLayer{..} -> do
let g = defaultAddressPoolGap
let s = mkSeqStateFromRootXPrv @n credentials purposeBIP44 g
let (hist, cp) = initWallet block0 s
now <- lift getCurrentTime
let meta = WalletMetadata
{ name = wname
, creationTime = now
, passphraseInfo = Nothing
, delegation = WalletDelegation NotDelegating []
}
mapExceptT atomically $
initializeWallet wid (updateState s cp) meta hist gp $> wid
where
db = ctx ^. dbLayer @IO @s @k
(block0, NetworkParameters gp _sp _pp, _) = ctx ^. genesisData
-- | Check whether a wallet is in good shape when restarting a worker.
checkWalletIntegrity
:: forall ctx s k. HasDBLayer IO s k ctx
=> ctx
-> WalletId
-> GenesisParameters
-> ExceptT ErrCheckWalletIntegrity IO ()
checkWalletIntegrity ctx wid gp = db & \DBLayer{..} -> mapExceptT atomically $ do
gp' <- withExceptT ErrCheckWalletIntegrityNoSuchWallet $ withNoSuchWallet wid $
readGenesisParameters wid
whenDifferentGenesis gp gp $ throwE $
ErrCheckIntegrityDifferentGenesis
(getGenesisBlockHash gp)
(getGenesisBlockHash gp')
where
db = ctx ^. dbLayer @IO @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 IO s k ctx
=> ctx
-> WalletId
-> ExceptT ErrNoSuchWallet IO (Wallet s, WalletMetadata, Set Tx)
readWallet ctx wid = db & \DBLayer{..} -> mapExceptT atomically $ do
cp <- withNoSuchWallet wid $ readCheckpoint wid
meta <- withNoSuchWallet wid $ readWalletMeta wid
pending <- lift $ readTxHistory wid Nothing Descending wholeRange (Just Pending)
pure (cp, meta, Set.fromList (fromTransactionInfo <$> pending))
where
db = ctx ^. dbLayer @IO @s @k
walletSyncProgress
:: forall ctx s. HasNetworkLayer IO ctx
=> ctx
-> Wallet s
-> IO SyncProgress
walletSyncProgress ctx w = do
let tip = view #slotNo $ currentTip w
syncProgress nl tip
where
nl = ctx ^. networkLayer
-- | Update a wallet's metadata with the given update function.
updateWallet
:: forall ctx s k.
( HasDBLayer IO s k ctx
)
=> ctx
-> WalletId
-> (WalletMetadata -> WalletMetadata)
-> ExceptT ErrNoSuchWallet IO ()
updateWallet ctx wid modify = db & \DBLayer{..} -> mapExceptT atomically $ do
meta <- withNoSuchWallet wid $ readWalletMeta wid
putWalletMeta wid (modify meta)
where
db = ctx ^. dbLayer @IO @s @k
-- | Change a wallet's passphrase to the given passphrase.
updateWalletPassphrase
:: forall ctx s k.
( HasDBLayer IO 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)
getWalletUtxoSnapshot
:: forall ctx s k.
( HasDBLayer IO s k ctx
, HasNetworkLayer IO ctx
, HasTransactionLayer k ctx
)
=> ctx
-> WalletId
-> ExceptT ErrNoSuchWallet IO [(TokenBundle, Coin)]
getWalletUtxoSnapshot ctx wid = do
(wallet, _, pending) <- withExceptT id (readWallet @ctx @s @k ctx wid)
pp <- liftIO $ currentProtocolParameters nl
let bundles = availableUTxO @s pending wallet
& unUTxO
& F.toList
& fmap (view #tokens)
pure $ pairBundleWithMinAdaQuantity pp <$> bundles
where
nl = ctx ^. networkLayer
tl = ctx ^. transactionLayer @k
pairBundleWithMinAdaQuantity
:: ProtocolParameters -> TokenBundle -> (TokenBundle, Coin)
pairBundleWithMinAdaQuantity pp bundle =
(bundle, computeMinAdaQuantity $ view #tokens bundle)
where
computeMinAdaQuantity :: TokenMap -> Coin
computeMinAdaQuantity =
view #txOutputMinimumAdaQuantity (view #constraints tl pp)
-- | List the wallet's UTxO statistics.
listUtxoStatistics
:: forall ctx s k. HasDBLayer IO 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.
--
-- After the wallet has been restored,
-- this action will continue to fetch newly created blocks
-- and apply them, or roll back to a previous point whenever
-- the chain switches.
restoreWallet
:: forall ctx s k.
( HasNetworkLayer IO ctx
, HasDBLayer IO s k ctx
, HasLogger IO WalletWorkerLog ctx
, IsOurs s Address
, IsOurs s RewardAccount
)
=> ctx
-> WalletId
-> ExceptT ErrNoSuchWallet IO ()
restoreWallet ctx wid = db & \DBLayer{..} -> do
catchFromIO $ chainSync nw (contramap MsgChainFollow tr) $ ChainFollower
{ readLocalTip = liftIO $ atomically $ listCheckpoints wid
, rollForward = \blocks tip -> throwInIO $
restoreBlocks @ctx @s @k
ctx (contramap MsgWalletFollow tr) wid blocks tip
, rollBackward =
throwInIO . rollbackBlocks @ctx @s @k ctx wid . toSlot
}
where
db = ctx ^. dbLayer @IO @s @k
nw = ctx ^. networkLayer @IO
tr = ctx ^. logger @_ @WalletWorkerLog
-- See Note [CheckedExceptionsAndCallbacks]
throwInIO :: ExceptT ErrNoSuchWallet IO a -> IO a
throwInIO x = runExceptT x >>= \case
Right a -> pure a
Left e -> throwIO $ UncheckErrNoSuchWallet e
catchFromIO :: IO a -> ExceptT ErrNoSuchWallet IO a
catchFromIO m = ExceptT $
(Right <$> m) `catch` (\(UncheckErrNoSuchWallet e) -> pure $ Left e)
newtype UncheckErrNoSuchWallet = UncheckErrNoSuchWallet ErrNoSuchWallet
deriving (Eq, Show)
instance Exception UncheckErrNoSuchWallet
{- NOTE [CheckedExceptionsAndCallbacks]
Callback functions (such as the fields of 'ChainFollower')
may throw exceptions. Such exceptions typically cause the thread
(such as 'chainSync') which calls the callbacks to exit and
to return control to its parent.
Ideally, we would like these exceptions to be \"checked exceptions\",
which means that they are visible on the type level.
In our codebase, we (should) make sure that exceptions which are checked
cannot be instances of the 'Exception' class -- in this way,
it is statically guaranteed that they cannot be thrown in the 'IO' monad.
On the flip side, visibility on the type level does imply that
the calling thread (here 'chainSync') needs to be either polymorphic
in the checked exceptions or aware of them.
Making 'chainSync' aware of the checked exception is currently
not a good idea, because this function is used in different contexts,
which have different checked exceptions.
So, it would need to be polymorophic in the the undelrying monad,
but at present, 'chainSync' is restricted to 'IO' beause some
of its constituents are also restricted to 'IO'.
As a workaround / solution, we wrap the checked exception into a new type
which can be thrown in the 'IO' monad.
When the calling thread exits, we catch the exception again
and present it as a checked exception.
-}
-- | 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.
( HasDBLayer IO s k ctx
)
=> ctx
-> WalletId
-> Slot
-> ExceptT ErrNoSuchWallet IO ChainPoint
rollbackBlocks ctx wid point = db & \DBLayer{..} -> do
mapExceptT atomically $ rollbackTo wid point
where
db = ctx ^. dbLayer @IO @s @k
-- | Apply the given blocks to the wallet and update the wallet state,
-- transaction history and corresponding metadata.
restoreBlocks
:: forall ctx s k.
( HasDBLayer IO s k ctx
, HasNetworkLayer IO ctx
, IsOurs s Address
, IsOurs s RewardAccount
)
=> ctx
-> Tracer IO WalletFollowLog
-> WalletId
-> NonEmpty Block
-> BlockHeader
-> ExceptT ErrNoSuchWallet IO ()
restoreBlocks ctx tr wid blocks nodeTip = db & \DBLayer{..} -> mapExceptT atomically $ do
cp <- withNoSuchWallet wid (readCheckpoint wid)
sp <- liftIO $ currentSlottingParameters nl