-
Notifications
You must be signed in to change notification settings - Fork 211
/
Layer.hs
1042 lines (955 loc) · 37.6 KB
/
Layer.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 DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
-- |
-- Copyright: © 2018-2020 IOHK
-- License: Apache-2.0
--
-- An implementation of the DBLayer which uses Persistent and SQLite.
module Cardano.Wallet.DB.Layer
( -- * Directory of single-file wallet databases
newDBFactory
, findDatabases
, DBFactoryLog (..)
-- * Internal implementation
, withDBLayer
, withDBLayerInMemory
, WalletDBLog (..)
, CacheBehavior (..)
-- * Unbracketed internal implementation
, newDBLayerWith
, newDBLayerInMemory
-- * Interfaces
, PersistAddressBook (..)
-- * Migration Support
, DefaultFieldValues (..)
) where
import Prelude
import Cardano.Address.Derivation
( XPrv )
import Cardano.BM.Data.Severity
( Severity (..) )
import Cardano.BM.Data.Tracer
( HasPrivacyAnnotation (..), HasSeverityAnnotation (..) )
import Cardano.DB.Sqlite
( DBLog (..)
, ForeignKeysSetting (ForeignKeysEnabled)
, SqliteContext (..)
, handleConstraint
, newInMemorySqliteContext
, newSqliteContext
, withConnectionPool
)
import Cardano.DB.Sqlite.Delete
( DeleteSqliteDatabaseLog
, deleteSqliteDatabase
, newRefCount
, waitForFree
, withRef
)
import Cardano.Slotting.Slot
( WithOrigin (..) )
import Cardano.Wallet.Checkpoints
( DeltaCheckpoints (..)
, defaultSparseCheckpointsConfig
, sparseCheckpoints
)
import Cardano.Wallet.DB
( DBCheckpoints (..)
, DBDelegation (..)
, DBFactory (..)
, DBLayer
, DBLayerCollection (..)
, DBPrivateKey (..)
, DBTxHistory (..)
, DBWalletMeta (..)
, DBWallets (..)
, ErrNoSuchWallet (..)
, ErrWalletAlreadyExists (..)
, mkDBLayerFromParts
)
import Cardano.Wallet.DB.Sqlite.Migration
( DefaultFieldValues (..), migrateManually )
import Cardano.Wallet.DB.Sqlite.Schema
( DelegationCertificate (..)
, DelegationReward (..)
, EntityField (..)
, Key (..)
, PrivateKey (..)
, StakeKeyCertificate (..)
, TxMeta (..)
, Wallet (..)
, migrateAll
, unWalletKey
)
import Cardano.Wallet.DB.Sqlite.Types
( BlockId (..), TxId (..) )
import Cardano.Wallet.DB.Store.Checkpoints
( PersistAddressBook (..), blockHeaderFromEntity, mkStoreWallets )
import Cardano.Wallet.DB.Store.QueryStore
( QueryStore (..) )
import Cardano.Wallet.DB.Store.Submissions.Layer
( pruneByFinality, rollBackSubmissions )
import Cardano.Wallet.DB.Store.Transactions.Decoration
( TxInDecorator
, decorateTxInsForReadTxFromLookupTxOut
, decorateTxInsForRelationFromLookupTxOut
)
import Cardano.Wallet.DB.Store.Transactions.Model
( TxRelation (..) )
import Cardano.Wallet.DB.Store.Transactions.TransactionInfo
( mkTransactionInfoFromRelation )
import Cardano.Wallet.DB.Store.Wallets.Layer
( QueryStoreTxWalletsHistory
, QueryTxWalletsHistory (..)
, newQueryStoreTxWalletsHistory
)
import Cardano.Wallet.DB.Store.Wallets.Store
( DeltaTxWalletsHistory (..) )
import Cardano.Wallet.DB.WalletState
( DeltaMap (..)
, DeltaWalletState1 (..)
, findNearestPoint
, fromGenesis
, fromWallet
, getBlockHeight
, getLatest
, getSlot
)
import Cardano.Wallet.Primitive.AddressDerivation
( Depth (..), PersistPrivateKey (..), WalletKey (..) )
import Cardano.Wallet.Primitive.Passphrase.Types
( PassphraseHash )
import Cardano.Wallet.Primitive.Slotting
( TimeInterpreter, firstSlotInEpoch, hoistTimeInterpreter, interpretQuery )
import Cardano.Wallet.Primitive.Types
( SortOrder (..) )
import Cardano.Wallet.Read.Eras
( EraValue )
import Control.DeepSeq
( force )
import Control.Exception
( evaluate, throw )
import Control.Monad
( forM, unless, when, (<=<) )
import Control.Monad.IO.Class
( MonadIO (..) )
import Control.Monad.Trans
( lift )
import Control.Monad.Trans.Except
( ExceptT (..) )
import Control.Tracer
( Tracer, contramap, traceWith )
import Data.Coerce
( coerce )
import Data.DBVar
( Store (..), loadDBVar, modifyDBMaybe, readDBVar, updateDBVar )
import Data.Either
( isRight )
import Data.Functor
( (<&>) )
import Data.Generics.Internal.VL.Lens
( view, (^.) )
import Data.List
( sortOn )
import Data.Maybe
( catMaybes, fromMaybe, isJust, maybeToList )
import Data.Ord
( Down (..) )
import Data.Proxy
( Proxy (..) )
import Data.Quantity
( Quantity (..) )
import Data.Text
( Text )
import Data.Text.Class
( ToText (..), fromText )
import Data.Word
( Word32 )
import Database.Persist.Sql
( Entity (..)
, Filter
, SelectOpt (..)
, Update (..)
, deleteWhere
, insert_
, repsert
, selectFirst
, selectKeysList
, selectList
, updateWhere
, (<.)
, (=.)
, (==.)
, (>.)
, (>=.)
)
import Database.Persist.Sqlite
( SqlPersistT )
import Fmt
( pretty, (+|), (|+) )
import GHC.Generics
( Generic )
import System.Directory
( doesFileExist, listDirectory )
import System.FilePath
( (</>) )
import UnliftIO.Exception
( Exception, bracket, throwIO )
import UnliftIO.MVar
( modifyMVar, modifyMVar_, newMVar, readMVar, withMVar )
import qualified Cardano.Wallet.DB.Sqlite.Schema as DB
import qualified Cardano.Wallet.Primitive.Model as W
import qualified Cardano.Wallet.Primitive.Passphrase as W
import qualified Cardano.Wallet.Primitive.Types as W
import qualified Cardano.Wallet.Primitive.Types.Coin as Coin
import qualified Cardano.Wallet.Primitive.Types.Hash as W
import qualified Cardano.Wallet.Primitive.Types.Tx as W
import qualified Cardano.Wallet.Primitive.Types.Tx.TxOut as W
import qualified Cardano.Wallet.Read.Tx as Read
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified Data.Text as T
{-------------------------------------------------------------------------------
Database "factory"
(a directory containing one database file per wallet)
-------------------------------------------------------------------------------}
-- | Instantiate a 'DBFactory' from a given directory, or in-memory for testing.
newDBFactory
:: forall s k.
( PersistAddressBook s
, PersistPrivateKey (k 'RootK)
, WalletKey k
)
=> Tracer IO DBFactoryLog
-- ^ Logging object
-> DefaultFieldValues
-- ^ Default database field values, used during migration.
-> TimeInterpreter IO
-- ^ Time interpreter for slot to time conversions
-> Maybe FilePath
-- ^ Path to database directory, or Nothing for in-memory database
-> IO (DBFactory IO s k)
newDBFactory tr defaultFieldValues ti = \case
Nothing -> do
-- NOTE1
-- For the in-memory database, we do actually preserve the database
-- after the 'action' is done. This allows for calling 'withDatabase'
-- several times within the same execution and get back the same
-- database. The memory is only cleaned up when calling
-- 'removeDatabase', to mimic the way the file database works!
--
-- NOTE2
-- The in-memory withDatabase will leak memory unless removeDatabase is
-- called after using the database. In practice, this is only a problem
-- for testing.
mvar <- newMVar mempty
pure DBFactory
{ withDatabase = \wid action -> do
db <- modifyMVar mvar $ \m -> case Map.lookup wid m of
Just db -> pure (m, db)
Nothing -> do
let tr' = contramap (MsgWalletDB "") tr
(_cleanup, db) <- newDBLayerInMemory tr' ti
pure (Map.insert wid db m, db)
action db
, removeDatabase = \wid -> do
traceWith tr $ MsgRemoving (pretty wid)
modifyMVar_ mvar (pure . Map.delete wid)
, listDatabases =
Map.keys <$> readMVar mvar
}
Just databaseDir -> do
refs <- newRefCount
pure DBFactory
{ withDatabase = \wid action -> withRef refs wid $ withDBLayer
(contramap (MsgWalletDB (databaseFile wid)) tr)
defaultFieldValues
(databaseFile wid)
ti
action
, removeDatabase = \wid -> do
let widp = pretty wid
-- try to wait for all 'withDatabase' calls to finish before
-- deleting database file.
let trWait = contramap (MsgWaitingForDatabase widp) tr
-- TODO: rather than refcounting, why not keep retrying the
-- delete until there are no file busy errors?
waitForFree trWait refs wid $ \inUse -> do
unless (inUse == 0) $
traceWith tr $ MsgRemovingInUse widp inUse
traceWith tr $ MsgRemoving widp
let trDel = contramap (MsgRemovingDatabaseFile widp) tr
deleteSqliteDatabase trDel (databaseFile wid)
, listDatabases =
findDatabases @k tr databaseDir
}
where
databaseFilePrefix = keyTypeDescriptor $ Proxy @k
databaseFile wid =
databaseDir </>
databaseFilePrefix <> "." <>
T.unpack (toText wid) <> ".sqlite"
-- | Return all wallet databases that match the specified key type within the
-- specified directory.
findDatabases
:: forall k. WalletKey k
=> Tracer IO DBFactoryLog
-> FilePath
-> IO [W.WalletId]
findDatabases tr dir = do
files <- listDirectory dir
fmap catMaybes $ forM files $ \file -> do
isFile <- doesFileExist (dir </> file)
case (isFile, T.splitOn "." $ T.pack file) of
(True, prefix : basename : ["sqlite"]) | prefix == expectedPrefix ->
case fromText basename of
Right wid -> do
traceWith tr $ MsgFoundDatabase (dir </> file) (toText wid)
return (Just wid)
_ -> do
traceWith tr $ MsgUnknownDBFile file
return Nothing
_ -> return Nothing
where
expectedPrefix = T.pack $ keyTypeDescriptor $ Proxy @k
data DBFactoryLog
= MsgFoundDatabase FilePath Text
| MsgUnknownDBFile FilePath
| MsgRemoving Text
| MsgRemovingInUse Text Int
| MsgRemovingDatabaseFile Text DeleteSqliteDatabaseLog
| MsgWaitingForDatabase Text (Maybe Int)
| MsgWalletDB FilePath WalletDBLog
deriving (Generic, Show, Eq)
instance HasPrivacyAnnotation DBFactoryLog
instance HasSeverityAnnotation DBFactoryLog where
getSeverityAnnotation ev = case ev of
MsgFoundDatabase _ _ -> Info
MsgUnknownDBFile _ -> Notice
MsgRemoving _ -> Info
MsgRemovingInUse _ _ -> Notice
MsgRemovingDatabaseFile _ msg -> getSeverityAnnotation msg
MsgWaitingForDatabase _ _ -> Info
MsgWalletDB _ msg -> getSeverityAnnotation msg
instance ToText DBFactoryLog where
toText = \case
MsgFoundDatabase _file wid ->
"Found existing wallet: " <> wid
MsgUnknownDBFile file -> mconcat
[ "Found something other than a database file in "
, "the database folder: ", T.pack file
]
MsgRemoving wid ->
"Removing wallet's database. Wallet id was " <> wid
MsgRemovingDatabaseFile wid msg ->
"Removing " <> wid <> ": " <> toText msg
MsgWaitingForDatabase wid Nothing ->
"Database "+|wid|+" is ready to be deleted"
MsgWaitingForDatabase wid (Just count) ->
"Waiting for "+|count|+" withDatabase "+|wid|+" call(s) to finish"
MsgRemovingInUse wid count ->
"Timed out waiting for "+|count|+" withDatabase "+|wid|+" call(s) to finish. " <>
"Attempting to remove the database anyway."
MsgWalletDB _file msg -> toText msg
{-------------------------------------------------------------------------------
Database layer
-------------------------------------------------------------------------------}
-- | Runs an action with a connection to the SQLite database.
--
-- Database migrations are run to create tables if necessary.
--
-- If the given file path does not exist, it will be created by the sqlite
-- library.
withDBLayer
:: forall s k a.
( PersistAddressBook s
, PersistPrivateKey (k 'RootK)
, WalletKey k
)
=> Tracer IO WalletDBLog
-- ^ Logging object
-> DefaultFieldValues
-- ^ Default database field values, used during migration.
-> FilePath
-- ^ Path to database file
-> TimeInterpreter IO
-- ^ Time interpreter for slot to time conversions
-> (DBLayer IO s k -> IO a)
-- ^ Action to run.
-> IO a
withDBLayer tr defaultFieldValues dbFile ti action = do
let trDB = contramap MsgDB tr
let manualMigrations = migrateManually trDB (Proxy @k) defaultFieldValues
let autoMigrations = migrateAll
withConnectionPool trDB dbFile $ \pool -> do
res <- newSqliteContext trDB pool manualMigrations autoMigrations
either throwIO (action <=< newDBLayerWith CacheLatestCheckpoint tr ti) res
newtype WalletDBLog
= MsgDB DBLog
deriving (Generic, Show, Eq)
instance HasPrivacyAnnotation WalletDBLog
instance HasSeverityAnnotation WalletDBLog where
getSeverityAnnotation = \case
MsgDB msg -> getSeverityAnnotation msg
instance ToText WalletDBLog where
toText = \case
MsgDB msg -> toText msg
-- | Runs an IO action with a new 'DBLayer' backed by a sqlite in-memory
-- database.
withDBLayerInMemory
:: forall s k a.
( PersistAddressBook s
, PersistPrivateKey (k 'RootK)
)
=> Tracer IO WalletDBLog
-- ^ Logging object
-> TimeInterpreter IO
-- ^ Time interpreter for slot to time conversions
-> (DBLayer IO s k -> IO a)
-> IO a
withDBLayerInMemory tr ti action = bracket (newDBLayerInMemory tr ti) fst (action . snd)
-- | Creates a 'DBLayer' backed by a sqlite in-memory database.
--
-- Returns a cleanup function which you should always use exactly once when
-- finished with the 'DBLayer'.
newDBLayerInMemory
:: forall s k.
( PersistAddressBook s
, PersistPrivateKey (k 'RootK)
)
=> Tracer IO WalletDBLog
-- ^ Logging object
-> TimeInterpreter IO
-- ^ Time interpreter for slot to time conversions
-> IO (IO (), DBLayer IO s k)
newDBLayerInMemory tr ti = do
let tr' = contramap MsgDB tr
(destroy, ctx) <-
newInMemorySqliteContext tr' [] migrateAll ForeignKeysEnabled
db <- newDBLayer tr ti ctx
pure (destroy, db)
-- | What to do with regards to caching. This is useful to disable caching in
-- database benchmarks.
data CacheBehavior
= NoCache
| CacheLatestCheckpoint
deriving (Eq, Show)
-- | Sets up a connection to the SQLite database.
--
-- Database migrations are run to create tables if necessary.
--
-- If the given file path does not exist, it will be created by the sqlite
-- library.
--
-- 'newDBLayer' will provide the actual 'DBLayer' implementation. It requires an
-- 'SqliteContext' which can be obtained from a database connection pool. This
-- is better initialized with 'withDBLayer'.
newDBLayer
:: forall s k.
( PersistAddressBook s
, PersistPrivateKey (k 'RootK)
)
=> Tracer IO WalletDBLog
-- ^ Logging
-> TimeInterpreter IO
-- ^ Time interpreter for slot to time conversions
-> SqliteContext
-- ^ A (thread-)safe wrapper for query execution.
-> IO (DBLayer IO s k)
newDBLayer = newDBLayerWith @s @k CacheLatestCheckpoint
{- HLINT ignore newDBLayerWith "Redundant <$>" -}
-- | Like 'newDBLayer', but allows to explicitly specify the caching behavior.
newDBLayerWith
:: forall s k.
( PersistAddressBook s
, PersistPrivateKey (k 'RootK)
)
=> CacheBehavior
-- ^ Option to disable caching.
-> Tracer IO WalletDBLog
-- ^ Logging
-> TimeInterpreter IO
-- ^ Time interpreter for slot to time conversions
-> SqliteContext
-- ^ A (thread-)safe wrapper for query execution.
-> IO (DBLayer IO s k)
newDBLayerWith _cacheBehavior _tr ti SqliteContext{runQuery} = mdo
-- FIXME LATER during ADP-1043:
-- Remove the 'NoCache' behavior, we cannot get it back.
-- This will affect read benchmarks, they will need to benchmark
-- 'loadDBVar' instead.
-- FIXME LATER during ADP-1043:
-- Handle the case where loading the database fails.
walletsDB <- runQuery $ loadDBVar mkStoreWallets
transactionsQS <- runQuery newQueryStoreTxWalletsHistory
-- NOTE
-- The cache will not work properly unless 'atomically' is protected by a
-- mutex (queryLock), which means no concurrent queries.
queryLock <- newMVar () -- fixme: ADP-586
-- Insert genesis checkpoint into the DBVar.
-- Throws an internal error if the checkpoint is not actually at genesis.
let insertCheckpointGenesis wid cp =
case fromGenesis cp of
Nothing -> throwIO $ ErrInitializeGenesisAbsent wid header
Just wallet ->
updateDBVar walletsDB $ Insert wid wallet
where
header = cp ^. #currentTip
-- Retrieve the latest checkpoint from the DBVar
let readCheckpoint
:: W.WalletId
-> SqlPersistT IO (Maybe (W.Wallet s))
readCheckpoint wid =
fmap getLatest . Map.lookup wid <$> readDBVar walletsDB
let pruneCheckpoints
:: W.WalletId
-> Quantity "block" Word32 -> W.BlockHeader
-> SqlPersistT IO ()
pruneCheckpoints wid epochStability tip = do
let heights = Set.fromList $ sparseCheckpoints
(defaultSparseCheckpointsConfig epochStability)
(tip ^. #blockHeight)
modifyDBMaybe walletsDB $ \ws ->
case Map.lookup wid ws of
Nothing -> (Nothing, ())
Just wal ->
let willKeep cp = getBlockHeight cp `Set.member` heights
slots = Map.filter willKeep (wal ^. #checkpoints . #checkpoints)
delta = Adjust wid
[ UpdateCheckpoints [ RestrictTo $ Map.keys slots ] ]
in (Just delta, ())
-- Delete the a wallet from the checkpoint DBVar
let deleteCheckpoints :: W.WalletId -> SqlPersistT IO ()
deleteCheckpoints wid = updateDBVar walletsDB $ Delete wid
{-----------------------------------------------------------------------
Wallets
-----------------------------------------------------------------------}
let
dbWallets = DBWallets
{ initializeWallet_ = \wid cp meta txs gp -> do
ExceptT $ do
res <- handleConstraint (ErrWalletAlreadyExists wid) $
insert_ (mkWalletEntity wid meta gp)
when (isRight res) $ do
insertCheckpointGenesis wid cp
updateS (store transactionsQS) Nothing $
ExpandTxWalletsHistory wid txs
pure res
, readGenesisParameters_ = selectGenesisParameters
, removeWallet_ = \wid -> do
ExceptT $ do
selectWallet wid >>= \case
Nothing -> pure $ Left $ ErrNoSuchWallet wid
Just _ -> Right <$> do
deleteWhere [WalId ==. wid]
deleteCheckpoints wid
updateS (store transactionsQS) Nothing
$ RemoveWallet wid
, listWallets_ = map unWalletKey <$> selectKeysList [] [Asc WalId]
, hasWallet_ = fmap isJust . selectWallet
}
{-----------------------------------------------------------------------
Checkpoints
-----------------------------------------------------------------------}
let
dbCheckpoints = DBCheckpoints
{ walletsDB_ = walletsDB
, putCheckpoint_ = \wid cp -> ExceptT $ do
modifyDBMaybe walletsDB $ \ws ->
case Map.lookup wid ws of
Nothing -> (Nothing, Left $ ErrNoSuchWallet wid)
Just _ ->
let (prologue, wcp) = fromWallet cp
slot = getSlot wcp
delta = Just $ Adjust wid
[ UpdateCheckpoints [ PutCheckpoint slot wcp ]
, ReplacePrologue prologue
]
in (delta, Right ())
, readCheckpoint_ = readCheckpoint
, listCheckpoints_ = \wid -> do
let toChainPoint = W.chainPointFromBlockHeader
map (toChainPoint . blockHeaderFromEntity . entityVal) <$> selectList
[ CheckpointWalletId ==. wid ]
[ Asc CheckpointSlot ]
}
{-----------------------------------------------------------------------
Tx History
-----------------------------------------------------------------------}
let
dbTxHistory = DBTxHistory
{ putTxHistory_ = \wid ->
updateS (store transactionsQS) Nothing
. ExpandTxWalletsHistory wid
, readTxHistory_ = \wid range tip mlimit order -> do
allTransactions <- queryS transactionsQS $ All wid
let whichMeta DB.TxMeta{..} = and $ catMaybes
[ (txMetaSlot >=) <$> W.inclusiveLowerBound range
, (txMetaSlot <=) <$> W.inclusiveUpperBound range
]
reorder = case order of
Ascending -> sortOn txMetaSlot
Descending -> sortOn $ Down . txMetaSlot
transactions
= maybe id (take . fromIntegral) mlimit
$ reorder
$ filter whichMeta allTransactions
lookupTx = queryS transactionsQS . GetByTxId
lookupTxOut = queryS transactionsQS . GetTxOut
forM transactions $
selectTransactionInfo ti tip lookupTx lookupTxOut
, getTx_ = \wid txid tip -> do
transactions <- queryS transactionsQS $ One wid (TxId txid)
let lookupTx = queryS transactionsQS . GetByTxId
lookupTxOut = queryS transactionsQS . GetTxOut
forM transactions $
selectTransactionInfo ti tip lookupTx lookupTxOut
, mkDecorator_ = mkDecorator transactionsQS
}
let rollbackTo_ wid requestedPoint = do
mNearestCheckpoint <-
ExceptT $ modifyDBMaybe walletsDB $ \ws ->
case Map.lookup wid ws of
Nothing ->
( Nothing
, pure Nothing
)
Just wal -> case findNearestPoint wal requestedPoint of
Nothing ->
( Nothing
, throw
$ ErrNoOlderCheckpoint wid requestedPoint
)
Just nearestPoint ->
( Just $ Adjust wid
[ UpdateCheckpoints
[ RollbackTo nearestPoint ]
, UpdateSubmissions
[ rollBackSubmissions $
case nearestPoint of
{ At s -> s; Origin -> 0 }
]
]
, pure $
Map.lookup nearestPoint
(wal ^. #checkpoints . #checkpoints)
)
case mNearestCheckpoint of
Nothing -> ExceptT $ pure $ Left $ ErrNoSuchWallet wid
Just wcp -> lift $ do
let nearestPoint = wcp ^. #currentTip . #slotNo
deleteDelegationCertificates wid
[ CertSlot >. nearestPoint
]
deleteStakeKeyCerts wid
[ StakeKeyCertSlot >. nearestPoint
]
updateS (store transactionsQS) Nothing $
RollbackTxWalletsHistory wid nearestPoint
pure
$ W.chainPointFromBlockHeader
$ view #currentTip wcp
let prune_ wid epochStability finalitySlot = do
ExceptT $ do
readCheckpoint wid >>= \case
Nothing -> pure $ Left $ ErrNoSuchWallet wid
Just cp -> Right <$> do
let tip = cp ^. #currentTip
pruneCheckpoints wid epochStability tip
lift $ updateDBVar walletsDB $ Adjust wid
[ UpdateSubmissions [pruneByFinality finalitySlot]
]
{-----------------------------------------------------------------------
Wallet Delegation
-----------------------------------------------------------------------}
let dbDelegation = mkDBDelegation ti
{-----------------------------------------------------------------------
Wallet Metadata
-----------------------------------------------------------------------}
let
dbWalletMeta = DBWalletMeta
{ putWalletMeta_ = \wid meta -> ExceptT $ do
selectWallet wid >>= \case
Nothing -> pure $ Left $ ErrNoSuchWallet wid
Just _ -> do
updateWhere [WalId ==. wid]
(mkWalletMetadataUpdate meta)
pure $ Right ()
, readWalletMeta_ = readWalletMetadata
}
{-----------------------------------------------------------------------
Keystore
-----------------------------------------------------------------------}
let dbPrivateKey = mkDBPrivateKey
{-----------------------------------------------------------------------
ACID Execution
-----------------------------------------------------------------------}
let atomically_ = withMVar queryLock . const . runQuery
pure $ mkDBLayerFromParts ti DBLayerCollection{..}
mkDecorator
:: QueryStoreTxWalletsHistory
-> TxInDecorator (EraValue Read.Tx) (SqlPersistT IO)
mkDecorator transactionsQS =
decorateTxInsForReadTxFromLookupTxOut lookupTxOut
where
lookupTxOut = queryS transactionsQS . GetTxOut
readWalletMetadata
:: W.WalletId
-> SqlPersistT IO (Maybe W.WalletMetadata)
readWalletMetadata wid =
fmap (metadataFromEntity . entityVal)
<$> selectFirst [WalId ==. wid] []
{-----------------------------------------------------------------------
Wallet Delegation
-----------------------------------------------------------------------}
mkDBDelegation ::
TimeInterpreter IO -> W.WalletId -> DBDelegation (SqlPersistT IO)
mkDBDelegation ti wid =
DBDelegation
{ isStakeKeyRegistered_
, putDelegationCertificate_
, putDelegationRewardBalance_
, readDelegationRewardBalance_
, readDelegation_
}
where
isStakeKeyRegistered_ :: SqlPersistT IO Bool
isStakeKeyRegistered_ = do
val <- fmap entityVal <$>
selectFirst [StakeKeyCertWalletId ==. wid] [Desc StakeKeyCertSlot]
pure $
case val of
Nothing -> False
Just (StakeKeyCertificate _ _ status) ->
status == W.StakeKeyRegistration
putDelegationCertificate_ ::
W.DelegationCertificate -> W.SlotNo -> SqlPersistT IO ()
putDelegationCertificate_ cert sl =
case cert of
W.CertDelegateNone _ -> do
repsert
(DelegationCertificateKey wid sl)
(DelegationCertificate wid sl Nothing)
repsert
(StakeKeyCertificateKey wid sl)
(StakeKeyCertificate wid sl W.StakeKeyDeregistration)
W.CertDelegateFull _ pool ->
repsert
(DelegationCertificateKey wid sl)
(DelegationCertificate wid sl (Just pool))
W.CertRegisterKey _ ->
repsert
(StakeKeyCertificateKey wid sl)
(StakeKeyCertificate wid sl W.StakeKeyRegistration)
putDelegationRewardBalance_ :: Coin.Coin -> SqlPersistT IO ()
putDelegationRewardBalance_ amount =
repsert
(DelegationRewardKey wid)
(DelegationReward wid (Coin.unsafeToWord64 amount))
readDelegationRewardBalance_ :: SqlPersistT IO Coin.Coin
readDelegationRewardBalance_ =
Coin.fromWord64 . maybe 0 (rewardAccountBalance . entityVal) <$>
selectFirst [RewardWalletId ==. wid] []
readDelegation_ :: W.EpochNo -> SqlPersistT IO W.WalletDelegation
readDelegation_ epoch = case epoch of
0 -> do
currEpochStartSlot <-
liftIO $ interpretQuery ti $ firstSlotInEpoch epoch
let nextDelegations =
readDelegationStatus [CertSlot >=. currEpochStartSlot]
<&> maybeToList . (<&> W.WalletDelegationNext (epoch + 2))
W.WalletDelegation W.NotDelegating <$> nextDelegations
_ -> do
(prevEpochStartSlot, currEpochStartSlot) <-
liftIO $ interpretQuery ti $
(,) <$> firstSlotInEpoch (epoch - 1)
<*> firstSlotInEpoch epoch
let currentDelegation =
readDelegationStatus [CertSlot <. prevEpochStartSlot]
<&> fromMaybe W.NotDelegating
let nextDelegations = catMaybes <$> sequence
[ readDelegationStatus
[ CertSlot >=. prevEpochStartSlot
, CertSlot <. currEpochStartSlot
] <&> (<&> W.WalletDelegationNext (epoch + 1))
, readDelegationStatus
[CertSlot >=. currEpochStartSlot]
<&> (<&> W.WalletDelegationNext (epoch + 2))
]
W.WalletDelegation <$> currentDelegation <*> nextDelegations
where
readDelegationStatus =
(fmap . fmap) toWalletDelegationStatus
. readDelegationCertificate wid
readDelegationCertificate
:: W.WalletId
-> [Filter DelegationCertificate]
-> SqlPersistT IO (Maybe DelegationCertificate)
readDelegationCertificate wid filters = fmap entityVal
<$> selectFirst ((CertWalletId ==. wid) : filters) [Desc CertSlot]
{-------------------------------------------------------------------------------
Conversion between types
from the `persistent` database (Cardano.Wallet.DB.Sqlite.Schema)
and from the wallet core ( Cardano.Wallet.Primitive.Types.*)
-------------------------------------------------------------------------------}
toWalletDelegationStatus
:: DelegationCertificate
-> W.WalletDelegationStatus
toWalletDelegationStatus = \case
DelegationCertificate _ _ Nothing ->
W.NotDelegating
DelegationCertificate _ _ (Just pool) ->
W.Delegating pool
mkWalletEntity :: W.WalletId -> W.WalletMetadata -> W.GenesisParameters -> Wallet
mkWalletEntity wid meta gp = Wallet
{ walId = wid
, walName = meta ^. #name . coerce
, walCreationTime = meta ^. #creationTime
, walPassphraseLastUpdatedAt = W.lastUpdatedAt <$> meta ^. #passphraseInfo
, walPassphraseScheme = W.passphraseScheme <$> meta ^. #passphraseInfo
, walGenesisHash = BlockId (coerce (gp ^. #getGenesisBlockHash))
, walGenesisStart = coerce (gp ^. #getGenesisBlockDate)
}
mkWalletMetadataUpdate :: W.WalletMetadata -> [Update Wallet]
mkWalletMetadataUpdate meta =
[ WalName =. meta ^. #name . coerce
, WalCreationTime =. meta ^. #creationTime
, WalPassphraseLastUpdatedAt =.
W.lastUpdatedAt <$> meta ^. #passphraseInfo
, WalPassphraseScheme =.
W.passphraseScheme <$> meta ^. #passphraseInfo
]
metadataFromEntity :: Wallet -> W.WalletMetadata
metadataFromEntity wal = W.WalletMetadata
{ name = W.WalletName (walName wal)
, creationTime = walCreationTime wal
, passphraseInfo = W.WalletPassphraseInfo
<$> walPassphraseLastUpdatedAt wal
<*> walPassphraseScheme wal
}
genesisParametersFromEntity
:: Wallet
-> W.GenesisParameters
genesisParametersFromEntity (Wallet _ _ _ _ _ hash startTime) =
W.GenesisParameters
{ W.getGenesisBlockHash = coerce (getBlockId hash)
, W.getGenesisBlockDate = W.StartTime startTime
}
{-----------------------------------------------------------------------
Private Key store
-----------------------------------------------------------------------}
mkDBPrivateKey
:: forall k. PersistPrivateKey (k 'RootK)
=> W.WalletId
-> DBPrivateKey (SqlPersistT IO) k
mkDBPrivateKey wid = DBPrivateKey
{ putPrivateKey_ = \key -> do
deleteWhere [PrivateKeyWalletId ==. wid]
insert_ (mkPrivateKeyEntity wid key)
, readPrivateKey_ = selectPrivateKey wid
}
mkPrivateKeyEntity
:: PersistPrivateKey (k 'RootK)
=> W.WalletId
-> (k 'RootK XPrv, W.PassphraseHash)
-> PrivateKey
mkPrivateKeyEntity wid kh = PrivateKey
{ privateKeyWalletId = wid
, privateKeyRootKey = root
, privateKeyHash = hash
}
where
(root, hash) = serializeXPrv kh
privateKeyFromEntity
:: PersistPrivateKey (k 'RootK)
=> PrivateKey
-> (k 'RootK XPrv, PassphraseHash)
privateKeyFromEntity (PrivateKey _ k h) =
unsafeDeserializeXPrv (k, h)
{-------------------------------------------------------------------------------
SQLite database operations
-------------------------------------------------------------------------------}
selectWallet :: MonadIO m => W.WalletId -> SqlPersistT m (Maybe Wallet)
selectWallet wid =
fmap entityVal <$> selectFirst [WalId ==. wid] []
-- | Delete stake key certificates for a wallet.
deleteStakeKeyCerts
:: W.WalletId
-> [Filter StakeKeyCertificate]
-> SqlPersistT IO ()
deleteStakeKeyCerts wid filters =
deleteWhere ((StakeKeyCertWalletId ==. wid) : filters)
-- | Delete all delegation certificates matching the given filter
deleteDelegationCertificates
:: W.WalletId
-> [Filter DelegationCertificate]
-> SqlPersistT IO ()
deleteDelegationCertificates wid filters = do
deleteWhere ((CertWalletId ==. wid) : filters)
-- | For a given 'TxMeta', read all necessary data to construct
-- the corresponding 'W.TransactionInfo'.
--
-- Assumption: The 'TxMeta' has a result when applying the given
-- lookup function.
--
-- Note: Transaction inputs are references to the outputs of
-- previous transactions. Given any input, the Ada quantity and
-- assets associated with it are unknown until we look them up.
-- Here, 'selectTransactionInfo' will try to look up those outputs that
-- are in the transaction history of the wallet,
-- but the function will not attempt to look up all possible outputs.
-- This approach typically provides enough information
-- for /outgoing/ payments, but less so for /ingoing/ payments.
selectTransactionInfo
:: MonadIO m
=> TimeInterpreter IO
-> W.BlockHeader
-> (TxId -> m (Maybe TxRelation))
-> ((TxId, Word32) -> m (Maybe W.TxOut))
-> TxMeta
-> m W.TransactionInfo