-
Notifications
You must be signed in to change notification settings - Fork 217
/
Wallet.hs
3738 lines (3465 loc) · 128 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 DerivingStrategies #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -Wno-redundant-constraints #-} -- suppress false warning
{-# OPTIONS_GHC -Wno-unticked-promoted-constructors #-}
-- |
-- 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 intrinsically 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
( WalletException (..)
-- * WalletLayer
, WalletLayer (..)
-- * Capabilities
-- $Capabilities
, HasDBLayer
, dbLayer
, HasLogger
, logger
, HasNetworkLayer
, networkLayer
, HasTransactionLayer
, transactionLayer
, HasGenesisData
, genesisData
-- * Interface
-- ** Wallet
, createWallet
, createIcarusWallet
, attachPrivateKeyFromPwd
, attachPrivateKeyFromPwdHashByron
, attachPrivateKeyFromPwdHashShelley
, getWalletUtxoSnapshot
, listUtxoStatistics
, readWallet
, restoreWallet
, updateWallet
, updateWalletPassphraseWithOldPassphrase
, updateWalletPassphraseWithMnemonic
, walletSyncProgress
, fetchRewardBalance
, manageRewardBalance
, manageSharedRewardBalance
, readSharedRewardAccount
, rollbackBlocks
, checkWalletIntegrity
, mkExternalWithdrawal
, mkSelfWithdrawal
, shelleyOnlyMkSelfWithdrawal
, readRewardAccount
, shelleyOnlyReadRewardAccount
, someRewardAccount
, readPolicyPublicKey
, writePolicyPublicKey
, ErrWalletAlreadyExists (..)
, ErrNoSuchWallet (..)
, ErrWalletNotInitialized (..)
, ErrUpdatePassphrase (..)
, ErrFetchRewards (..)
, ErrCheckWalletIntegrity (..)
, ErrWalletNotResponding (..)
, ErrReadRewardAccount (..)
, ErrReadPolicyPublicKey (..)
, ErrWritePolicyPublicKey (..)
, ErrGetPolicyId (..)
, readWalletMeta
-- * Shared Wallet
, updateCosigner
, ErrAddCosignerKey (..)
, ErrConstructSharedWallet (..)
, normalizeSharedAddress
, constructUnbalancedSharedTransaction
-- ** Address
, createRandomAddress
, importRandomAddresses
, listAddresses
, normalizeDelegationAddress
, lookupTxIns
, lookupTxOuts
, ErrCreateRandomAddress(..)
, ErrImportRandomAddress(..)
, ErrImportAddress(..)
-- ** Payment
, transactionExpirySlot
, buildCoinSelectionForTransaction
, CoinSelection (..)
, readWalletUTxO
, defaultChangeAddressGen
, dummyChangeAddressGen
, assignChangeAddressesAndUpdateDb
, assignChangeAddressesWithoutDbUpdate
, selectionToUnsignedTx
, buildSignSubmitTransaction
, buildTransaction
, buildTransactionPure
, buildAndSignTransactionPure
, buildAndSignTransaction
, BuiltTx (..)
, signTransaction
, constructTransaction
, constructTxMeta
, ErrSelectAssets(..)
, ErrSignPayment (..)
, ErrNotASequentialWallet (..)
, ErrWithdrawalNotBeneficial (..)
, ErrConstructTx (..)
, ErrUpdateSealedTx (..)
, ErrCannotJoin (..)
, ErrCannotQuit (..)
, ErrSubmitTransaction (..)
-- ** Migration
, createMigrationPlan
, migrationPlanToSelectionWithdrawals
, SelectionWithoutChange
, ErrCreateMigrationPlan (..)
-- ** Delegation
, PoolRetirementEpochInfo (..)
, ErrStakePoolDelegation (..)
-- ** Fee Estimation
, Fee (..)
, Percentile (..)
, DelegationFee (..)
, delegationFee
, transactionFee
, calculateFeePercentiles
, padFeePercentiles
, calcMinimumCoinValues
-- ** Transaction
, forgetTx
, listTransactions
, listAssets
, getTransaction
, submitExternalTx
, submitTx
, readLocalTxSubmissionPending
, LocalTxSubmissionConfig (..)
, defaultLocalTxSubmissionConfig
, runLocalTxSubmissionPool
, ErrMkTransaction (..)
, ErrSubmitTx (..)
, ErrRemoveTx (..)
, ErrPostTx (..)
, ErrListTransactions (..)
, ErrGetTransaction (..)
, ErrNoSuchTransaction (..)
, ErrStartTimeLaterThanEndTime (..)
, ErrWitnessTx (..)
, ErrWriteTxEra (..)
-- ** Root Key
, withRootKey
, derivePublicKey
, getAccountPublicKeyAtIndex
, readAccountPublicKey
, signMetadataWith
, ErrWithRootKey (..)
, ErrWrongPassphrase (..)
, ErrSignMetadataWith (..)
, ErrDerivePublicKey(..)
, ErrReadAccountPublicKey(..)
, ErrInvalidDerivationIndex(..)
-- * Utilities
, throttle
, guardHardIndex
, toBalanceTxPParams
, utxoAssumptionsForWallet
-- * Logging
, WalletWorkerLog (..)
, WalletFollowLog (..)
, WalletLog (..)
, TxSubmitLog (..)
) where
import Prelude hiding
( log )
import Cardano.Address.Derivation
( XPrv, XPub )
import Cardano.Address.Script
( Cosigner (..), KeyHash )
import Cardano.Api
( serialiseToCBOR )
import Cardano.Api.Extra
( inAnyCardanoEra )
import Cardano.BM.Data.Severity
( Severity (..) )
import Cardano.BM.Data.Tracer
( HasPrivacyAnnotation (..), HasSeverityAnnotation (..), nullTracer )
import Cardano.Crypto.Wallet
( toXPub )
import Cardano.Mnemonic
( SomeMnemonic )
import Cardano.Slotting.Slot
( SlotNo (..) )
import Cardano.Tx.Balance.Internal.CoinSelection
( Selection
, SelectionBalanceError (..)
, SelectionError (..)
, SelectionOf (..)
, UnableToConstructChangeError (..)
, emptySkeleton
)
import Cardano.Wallet.Address.Book
( AddressBookIso, Prologue (..), getDiscoveries, getPrologue )
import Cardano.Wallet.Address.Derivation
( DelegationAddress (..)
, Depth (..)
, DerivationIndex (..)
, DerivationPrefix (..)
, DerivationType (..)
, HardDerivation (..)
, Index (..)
, MkKeyFingerprint (..)
, PaymentAddress (..)
, Role (..)
, SoftDerivation (..)
, ToRewardAccount (..)
, deriveRewardAccount
, liftDelegationAddressS
, liftIndex
, stakeDerivationPath
)
import Cardano.Wallet.Address.Derivation.Byron
( ByronKey )
import Cardano.Wallet.Address.Derivation.Icarus
( IcarusKey )
import Cardano.Wallet.Address.Derivation.MintBurn
( derivePolicyPrivateKey, policyDerivationPath )
import Cardano.Wallet.Address.Derivation.SharedKey
( SharedKey (..), replaceCosignersWithVerKeys )
import Cardano.Wallet.Address.Derivation.Shelley
( ShelleyKey (..), deriveAccountPrivateKeyShelley )
import Cardano.Wallet.Address.Discovery
( CompareDiscovery (..)
, GenChange (..)
, GetAccount (..)
, GetPurpose (..)
, IsOurs (..)
, IsOwned (..)
, KnownAddresses (..)
, MaybeLight (..)
)
import Cardano.Wallet.Address.Discovery.Random
( ErrImportAddress (..), RndStateLike )
import Cardano.Wallet.Address.Discovery.Sequential
( SeqState (..), defaultAddressPoolGap, purposeBIP44 )
import Cardano.Wallet.Address.Discovery.Shared
( CredentialType (..)
, ErrAddCosigner (..)
, ErrScriptTemplate (..)
, SharedState (..)
, isShared
)
import Cardano.Wallet.Address.Keys.BoundedAddressLength
( maxLengthAddressFor )
import Cardano.Wallet.Address.Keys.SequentialAny
( mkSeqStateFromRootXPrv )
import Cardano.Wallet.Address.Keys.Shared
( addCosignerAccXPub )
import Cardano.Wallet.Address.Keys.WalletKey
( AfterByron
, afterByron
, changePassphraseNew
, getRawKey
, hashVerificationKey
, liftRawKey
)
import Cardano.Wallet.Checkpoints
( DeltaCheckpoints (..), extendCheckpoints, pruneCheckpoints )
import Cardano.Wallet.DB
( DBFresh (..)
, DBLayer (..)
, DBLayerParams (..)
, ErrNoSuchTransaction (..)
, ErrRemoveTx (..)
, ErrWalletAlreadyExists (..)
, ErrWalletNotInitialized (..)
)
import Cardano.Wallet.DB.Errors
( ErrNoSuchWallet (..) )
import Cardano.Wallet.DB.Store.Info.Store
( DeltaWalletInfo (..), WalletInfo (..) )
import Cardano.Wallet.DB.Store.Submissions.Layer
( mkLocalTxSubmission )
import Cardano.Wallet.DB.Store.Submissions.Operations
( TxSubmissionsStatus )
import Cardano.Wallet.DB.WalletState
( DeltaWalletState
, DeltaWalletState1 (..)
, WalletState (..)
, fromWallet
, getLatest
, getSlot
)
import Cardano.Wallet.Flavor
( CredFromOf
, Excluding
, KeyFlavorS (..)
, KeyOf
, WalletFlavor (..)
, WalletFlavorS (..)
, keyFlavorFromState
, keyOfWallet
)
import Cardano.Wallet.Logging
( BracketLog
, BracketLog' (..)
, bracketTracer
, formatResultMsg
, resultSeverity
, traceResult
, unliftIOTracer
)
import Cardano.Wallet.Network
( ChainFollowLog (..)
, ChainFollower (..)
, ErrPostTx (..)
, NetworkLayer (..)
)
import Cardano.Wallet.Primitive.BlockSummary
( ChainEvents )
import Cardano.Wallet.Primitive.Migration
( MigrationPlan (..) )
import Cardano.Wallet.Primitive.Model
( BlockData (..)
, Wallet
, applyBlocks
, applyOurTxToUTxO
, availableUTxO
, currentTip
, firstHeader
, getState
, initWallet
, totalUTxO
)
import Cardano.Wallet.Primitive.Passphrase
( ErrWrongPassphrase (..)
, Passphrase
, PassphraseHash
, PassphraseScheme (..)
, WalletPassphraseInfo (..)
, checkPassphrase
, currentPassphraseScheme
, encryptPassphrase'
, preparePassphrase
)
import Cardano.Wallet.Primitive.Slotting
( PastHorizonException (..)
, TimeInterpreter
, addRelTime
, ceilingSlotAt
, currentRelativeTime
, interpretQuery
, neverFails
, slotRangeFromTimeRange
, slotToUTCTime
, toTimeTranslation
, unsafeExtendSafeZone
)
import Cardano.Wallet.Primitive.SyncProgress
( SyncProgress )
import Cardano.Wallet.Primitive.Types
( ActiveSlotCoefficient (..)
, Block (..)
, BlockHeader (..)
, ChainPoint (..)
, DelegationCertificate (..)
, FeePolicy (..)
, GenesisParameters (..)
, LinearFunction (..)
, NetworkParameters (..)
, ProtocolParameters (..)
, Range (..)
, Signature (..)
, Slot
, SlottingParameters (..)
, SortOrder (..)
, WalletDelegation (..)
, WalletId (..)
, WalletMetadata (..)
, WalletName (..)
, WithOrigin (..)
, dlgCertPoolId
, stabilityWindowShelley
, 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.RewardAccount
( RewardAccount (..) )
import Cardano.Wallet.Primitive.Types.TokenBundle
( TokenBundle (..) )
import Cardano.Wallet.Primitive.Types.Tx
( Direction (..)
, LocalTxSubmissionStatus
, SealedTx (..)
, TransactionInfo (..)
, Tx (..)
, TxChange (..)
, TxMeta (..)
, TxMetadata (..)
, TxStatus (..)
, UnsignedTx (..)
, fromTransactionInfo
, sealedTxFromCardano
)
import Cardano.Wallet.Primitive.Types.Tx.TxIn
( TxIn (..) )
import Cardano.Wallet.Primitive.Types.Tx.TxOut
( TxOut (..) )
import Cardano.Wallet.Primitive.Types.UTxO
( UTxO (..) )
import Cardano.Wallet.Primitive.Types.UTxOStatistics
( UTxOStatistics )
import Cardano.Wallet.Read.NetworkId
( HasSNetworkId (..) )
import Cardano.Wallet.Read.Tx.CBOR
( TxCBOR )
import Cardano.Wallet.Shelley.Compatibility
( fromCardanoBlock
, fromCardanoLovelace
, fromCardanoTxIn
, fromCardanoTxOut
, fromCardanoWdrls
)
import Cardano.Wallet.Shelley.Compatibility.Ledger
( toWallet )
import Cardano.Wallet.Shelley.Transaction
( calculateMinimumFee, getFeePerByteFromWalletPParams )
import Cardano.Wallet.Transaction
( DelegationAction (..)
, ErrCannotJoin (..)
, ErrCannotQuit (..)
, ErrMkTransaction (..)
, ErrSignTx (..)
, ErrUpdateSealedTx (..)
, PreSelection (..)
, TransactionCtx (..)
, TransactionLayer (..)
, TxValidityInterval
, Withdrawal (..)
, WitnessCountCtx (..)
, defaultTransactionCtx
, withdrawalToCoin
)
import Cardano.Wallet.Transaction.Built
( BuiltTx (..) )
import Cardano.Wallet.TxWitnessTag
( TxWitnessTag )
import Cardano.Wallet.Write.Tx
( AnyRecentEra )
import Cardano.Wallet.Write.Tx.Balance
( BalanceTxLog (..)
, ChangeAddressGen (..)
, ErrBalanceTx (..)
, ErrBalanceTxInternalError (..)
, ErrSelectAssets (..)
, PartialTx (..)
, UTxOAssumptions (..)
, assignChangeAddresses
, balanceTransaction
, constructUTxOIndex
)
import Cardano.Wallet.Write.Tx.TimeTranslation
( TimeTranslation )
import Control.Arrow
( first, (>>>) )
import Control.DeepSeq
( NFData )
import Control.Monad
( forM, forM_, join, 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.Strict
( Rand, StdGen, evalRand, initStdGen )
import Control.Monad.State.Class
( MonadState (get, put) )
import Control.Monad.Trans.Class
( lift )
import Control.Monad.Trans.Except
( ExceptT (..)
, catchE
, except
, mapExceptT
, runExceptT
, throwE
, withExceptT
)
import Control.Monad.Trans.State
( StateT, evalState, runStateT, state )
import Control.Tracer
( Tracer, contramap, traceWith )
import Crypto.Hash
( Blake2b_256, hash )
import Data.ByteString
( ByteString )
import Data.DBVar
( DBVar, readDBVar )
import Data.Delta.Update
( onDBVar, update )
import Data.Either
( partitionEithers )
import Data.Either.Extra
( eitherToMaybe )
import Data.Function
( (&) )
import Data.Functor
( ($>), (<&>) )
import Data.Functor.Contravariant
( (>$<) )
import Data.Generics.Internal.VL.Lens
( Lens', view, (.~), (^.) )
import Data.Generics.Labels
()
import Data.Generics.Product.Typed
( HasType, typed )
import Data.List
( foldl' )
import Data.List.NonEmpty
( NonEmpty (..) )
import Data.Maybe
( fromMaybe, isJust, mapMaybe, maybeToList )
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.Void
( Void )
import Data.Word
( Word64 )
import Fmt
( Buildable
, blockListF
, blockMapF
, build
, nameF
, pretty
, unlinesF
, (+|)
, (+||)
, (|+)
, (||+)
)
import GHC.Generics
( Generic )
import GHC.Num
( Natural )
import GHC.TypeNats
( Nat )
import Statistics.Quantile
( medianUnbiased, quantiles )
import UnliftIO.Exception
( Exception, catch, evaluate, throwIO )
import UnliftIO.MVar
( modifyMVar_, newMVar )
import qualified Cardano.Address.Script as CA
import qualified Cardano.Address.Style.Shelley as CAShelley
import qualified Cardano.Api as Cardano
import qualified Cardano.Crypto.Wallet as CC
import qualified Cardano.Slotting.Slot as Slot
import qualified Cardano.Wallet.Address.Discovery.Random as Rnd
import qualified Cardano.Wallet.Address.Discovery.Sequential as Seq
import qualified Cardano.Wallet.Address.Discovery.Shared as Shared
import qualified Cardano.Wallet.Checkpoints.Policy as CP
import qualified Cardano.Wallet.DB.Store.Submissions.Layer as Submissions
import qualified Cardano.Wallet.DB.WalletState as WS
import qualified Cardano.Wallet.DB.WalletState as WalletState
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.Tx.TxOut as TxOut
import qualified Cardano.Wallet.Primitive.Types.UTxO as UTxO
import qualified Cardano.Wallet.Primitive.Types.UTxOStatistics as UTxOStatistics
import qualified Cardano.Wallet.Read as Read
import qualified Cardano.Wallet.Write.ProtocolParameters as Write
import qualified Cardano.Wallet.Write.Tx as Write
import qualified Data.ByteArray as BA
import qualified Data.Delta.Update as Delta
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
-- $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) 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
= WalletLayer
(Tracer m WalletWorkerLog)
(Block, NetworkParameters)
(NetworkLayer m Read.Block)
(TransactionLayer (KeyOf s) (CredFromOf s) SealedTx)
(DBLayer m s)
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 = HasType (DBLayer m s)
type HasGenesisData = HasType (Block, NetworkParameters)
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 Read.Block)
type HasTransactionLayer k ktype = HasType (TransactionLayer k ktype SealedTx)
dbLayer :: forall m s ctx. HasDBLayer m s ctx => Lens' ctx (DBLayer m s)
dbLayer = typed @(DBLayer m s)
genesisData ::
forall ctx. HasGenesisData ctx => Lens' ctx (Block, NetworkParameters)
genesisData = typed @(Block, NetworkParameters)
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 Read.Block)
networkLayer = typed @(NetworkLayer m Read.Block)
transactionLayer ::
forall k ktype ctx. (HasTransactionLayer k ktype ctx)
=> Lens' ctx (TransactionLayer k ktype SealedTx)
transactionLayer = typed @(TransactionLayer k ktype SealedTx)
-- | Convenience to apply an 'Update' to the 'WalletState' via the 'DBLayer'.
onWalletState
:: forall m s ctx r
. HasDBLayer m s ctx
=> ctx
-> Delta.Update (WalletState.DeltaWalletState s) r
-> m r
onWalletState ctx update' = db & \DBLayer{..} ->
atomically $ Delta.onDBVar walletState update'
where
db = ctx ^. dbLayer @m @s
{-------------------------------------------------------------------------------
Wallet
-------------------------------------------------------------------------------}
-- | Initialise and store a new wallet, returning its ID.
createWallet
:: forall m s
. ( MonadUnliftIO m
, MonadTime m
, IsOurs s Address
, IsOurs s RewardAccount
)
=> (Block, NetworkParameters)
-> DBFresh m s
-> WalletId
-> WalletName
-> s
-> ExceptT ErrWalletAlreadyExists m (DBLayer m s)
createWallet
(block0, NetworkParameters gp _sp _pp)
DBFresh{bootDBLayer}
wid
wname
s =
do
let (hist, cp) = initWallet block0 s
now <- lift getCurrentTime
let meta =
WalletMetadata
{ name = wname
, creationTime = now
, passphraseInfo = Nothing
}
withExceptT (const $ ErrWalletAlreadyExists wid)
$ bootDBLayer
$ DBLayerParams cp meta hist gp
-- | 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 s k n
. ( PaymentAddress k 'CredFromKeyK
, k ~ IcarusKey
, s ~ SeqState n k
, HasSNetworkId n
)
=> (Block, NetworkParameters)
-> DBFresh IO s
-> WalletId
-> WalletName
-> (k 'RootK XPrv, Passphrase "encryption")
-> ExceptT ErrWalletAlreadyExists IO (DBLayer IO s)
createIcarusWallet
(block0, NetworkParameters gp _sp _pp)
DBFresh{bootDBLayer}
wid
wname
credentials = do
let g = defaultAddressPoolGap
let s = mkSeqStateFromRootXPrv @n IcarusKeyS credentials purposeBIP44 g
let (hist, cp) = initWallet block0 s
now <- lift getCurrentTime
let meta =
WalletMetadata
{ name = wname
, creationTime = now
, passphraseInfo = Nothing
}
withExceptT (const $ ErrWalletAlreadyExists wid)
$ bootDBLayer
$ DBLayerParams cp meta hist gp
-- | Check whether a wallet is in good shape when restarting a worker.
checkWalletIntegrity :: DBLayer IO s -> GenesisParameters -> IO ()
checkWalletIntegrity db gp = db & \DBLayer{..} -> do
gp' <- atomically readGenesisParameters >>= do
maybe (throwIO ErrCheckWalletIntegrityNoGenesisParameters) pure
when ( (gp ^. #getGenesisBlockHash /= gp' ^. #getGenesisBlockHash) ||
(gp ^. #getGenesisBlockDate /= gp' ^. #getGenesisBlockDate) )
(throwIO $ ErrCheckIntegrityDifferentGenesis
(getGenesisBlockHash gp) (getGenesisBlockHash gp'))
readWalletMeta :: Functor f => DBVar f (DeltaWalletState s) -> f WalletMetadata
readWalletMeta walletState = walletMeta . info <$> readDBVar walletState
-- | Retrieve the wallet state for the wallet with the given ID.
readWallet
:: forall ctx s
. HasDBLayer IO s ctx
=> ctx
-> IO (Wallet s, (WalletMetadata, WalletDelegation), Set Tx)
readWallet ctx = db & \DBLayer{..} -> atomically $ do
cp <- readCheckpoint
meta <- readWalletMeta walletState
dele <- readDelegation
pending <- readTransactions
Nothing
Descending
wholeRange
(Just Pending)
Nothing
pure (cp, (meta, dele) , Set.fromList (fromTransactionInfo <$> pending))
where
db = ctx ^. dbLayer @IO @s
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
putWalletMeta
:: Monad stm
=> DBVar stm (DeltaWalletState s)
-> WalletMetadata
-> stm ()
putWalletMeta walletState wm = onDBVar walletState $ update $ \_ ->
[UpdateInfo $ UpdateWalletMetadata wm]
-- | Update a wallet's metadata with the given update function.
updateWallet
:: forall ctx s
. HasDBLayer IO s ctx
=> ctx
-> (WalletMetadata -> WalletMetadata)
-> IO ()
updateWallet ctx f = onWalletState @IO @s ctx $ update $ \s ->
[ UpdateInfo
$ UpdateWalletMetadata
$ f
$ s ^. #info . #walletMeta
]
-- | Change a wallet's passphrase to the given passphrase.
updateWalletPassphraseWithOldPassphrase
:: forall ctx s
. ( HasDBLayer IO s ctx
, WalletFlavor s
)
=> ctx
-> WalletId
-> (Passphrase "user", Passphrase "user")
-> ExceptT ErrUpdatePassphrase IO ()
updateWalletPassphraseWithOldPassphrase ctx wid (old, new) =
withRootKey @s db wid old ErrUpdatePassphraseWithRootKey
$ \xprv scheme -> do
-- IMPORTANT NOTE:
-- This use 'EncryptWithPBKDF2', regardless of the passphrase
-- current scheme, we'll re-encrypt it using the current scheme,
-- always.
let new' = (currentPassphraseScheme, new)
let xprv' = changePassphraseNew (keyFlavorFromState @s)
(scheme, old) new' xprv
lift $ attachPrivateKeyFromPwdScheme @ctx @s ctx (xprv', new')
where
db = ctx ^. typed
updateWalletPassphraseWithMnemonic
:: forall ctx s
. HasDBLayer IO s ctx
=> ctx
-> (KeyOf s 'RootK XPrv, Passphrase "user")
-> IO ()
updateWalletPassphraseWithMnemonic ctx (xprv, new) =
attachPrivateKeyFromPwdScheme @ctx @s ctx
(xprv, (currentPassphraseScheme , new))
getWalletUtxoSnapshot
:: forall ctx s
. ( HasDBLayer IO s ctx
, HasNetworkLayer IO ctx
, HasTransactionLayer (KeyOf s) (CredFromOf s) ctx
)
=> ctx
-> IO [(TokenBundle, Coin)]
getWalletUtxoSnapshot ctx = do
(wallet, _, pending) <- readWallet @ctx @s ctx
pp <- liftIO $ currentProtocolParameters nl
let txOuts = availableUTxO @s pending wallet
& unUTxO
& F.toList
pure $ first (view #tokens) . pairTxOutWithMinAdaQuantity pp <$> txOuts
where
nl = ctx ^. networkLayer
tl = ctx ^. transactionLayer @(KeyOf s) @(CredFromOf s)
pairTxOutWithMinAdaQuantity
:: ProtocolParameters
-> TxOut
-> (TxOut, Coin)
pairTxOutWithMinAdaQuantity pp out =
(out, computeMinAdaQuantity out)
where
computeMinAdaQuantity :: TxOut -> Coin
computeMinAdaQuantity (TxOut addr bundle) =
view #txOutputMinimumAdaQuantity
(constraints tl pp)
(addr)
(view #tokens bundle)
-- | List the wallet's UTxO statistics.
listUtxoStatistics
:: forall ctx s
. HasDBLayer IO s ctx
=> ctx
-> IO UTxOStatistics
listUtxoStatistics ctx = do
(wal, _, pending) <- readWallet @ctx @s ctx