-
Notifications
You must be signed in to change notification settings - Fork 211
/
Sqlite.hs
1511 lines (1382 loc) · 54.4 KB
/
Sqlite.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 DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
{-# HLINT ignore "Redundant flip" #-}
-- |
-- Copyright: © 2018-2020 IOHK
-- License: Apache-2.0
--
-- An implementation of the DBLayer which uses Persistent and SQLite.
module Cardano.Wallet.DB.Sqlite
( newDBLayer
, newDBFactory
, findDatabases
, withDBLayer
-- * Interfaces
, PersistState (..)
-- * Migration Support
, DefaultFieldValues (..)
) where
import Prelude
import Cardano.Address.Derivation
( XPrv, XPub )
import Cardano.DB.Sqlite
( DBField (..)
, DBLog (..)
, ManualMigration (..)
, SqliteContext (..)
, chunkSize
, dbChunked
, destroyDBLayer
, fieldName
, fieldType
, handleConstraint
, startSqliteBackend
, tableName
)
import Cardano.DB.Sqlite.Delete
( deleteSqliteDatabase, newRefCount, waitForFree, withRef )
import Cardano.Wallet.DB
( DBFactory (..)
, DBLayer (..)
, ErrNoSuchWallet (..)
, ErrRemovePendingTx (..)
, ErrWalletAlreadyExists (..)
, PrimaryKey (..)
, sparseCheckpoints
)
import Cardano.Wallet.DB.Sqlite.TH
( Checkpoint (..)
, DelegationCertificate (..)
, DelegationReward (..)
, EntityField (..)
, Key (..)
, PrivateKey (..)
, ProtocolParameters (..)
, RndState (..)
, RndStateAddress (..)
, RndStatePendingAddress (..)
, SeqState (..)
, SeqStateAddress (..)
, SeqStatePendingIx (..)
, StakeKeyCertificate (..)
, TxIn (..)
, TxMeta (..)
, TxOut (..)
, UTxO (..)
, Wallet (..)
, migrateAll
, unWalletKey
)
import Cardano.Wallet.DB.Sqlite.Types
( BlockId (..), HDPassphrase (..), TxId (..) )
import Cardano.Wallet.Primitive.AddressDerivation
( Depth (..)
, DerivationType (..)
, Index (..)
, MkKeyFingerprint (..)
, NetworkDiscriminant (..)
, PaymentAddress (..)
, PersistPrivateKey (..)
, PersistPublicKey (..)
, SoftDerivation (..)
, WalletKey (..)
)
import Control.Arrow
( (***) )
import Control.Concurrent.MVar
( modifyMVar, modifyMVar_, newMVar, readMVar )
import Control.Exception
( Exception, bracket, throwIO )
import Control.Monad
( forM, unless, void, when )
import Control.Monad.Extra
( concatMapM )
import Control.Monad.IO.Class
( MonadIO (..) )
import Control.Monad.Trans.Class
( lift )
import Control.Monad.Trans.Except
( ExceptT (..) )
import Control.Monad.Trans.Maybe
( MaybeT (..) )
import Control.Tracer
( Tracer, contramap, traceWith )
import Data.Coerce
( coerce )
import Data.Either
( isRight )
import Data.Generics.Internal.VL.Lens
( (^.) )
import Data.List.Split
( chunksOf )
import Data.Map.Strict
( Map )
import Data.Maybe
( catMaybes )
import Data.Proxy
( Proxy (..) )
import Data.Quantity
( Quantity (..) )
import Data.Text.Class
( ToText (..), fromText )
import Data.Typeable
( Typeable )
import Data.Word
( Word32, Word64 )
import Database.Persist.Class
( toPersistValue )
import Database.Persist.Sql
( Entity (..)
, Filter
, SelectOpt (..)
, Update (..)
, deleteCascadeWhere
, deleteWhere
, insertMany_
, insert_
, rawExecute
, repsert
, repsertMany
, selectFirst
, selectKeysList
, selectList
, updateWhere
, (/<-.)
, (<-.)
, (<.)
, (<=.)
, (=.)
, (==.)
, (>.)
, (>=.)
)
import Database.Persist.Sqlite
( SqlPersistT )
import Database.Persist.Types
( PersistValue (PersistText), fromPersistValueText )
import Fmt
( pretty )
import System.Directory
( doesFileExist, listDirectory )
import System.FilePath
( (</>) )
import qualified Cardano.Wallet.Primitive.AddressDerivation as W
import qualified Cardano.Wallet.Primitive.AddressDiscovery.Random as Rnd
import qualified Cardano.Wallet.Primitive.AddressDiscovery.Sequential as Seq
import qualified Cardano.Wallet.Primitive.Model as W
import qualified Cardano.Wallet.Primitive.Types as W
import qualified Data.Map as Map
import qualified Data.Text as T
import qualified Database.Sqlite as Sqlite
-- | 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.
( PersistState s
, PersistPrivateKey (k 'RootK)
)
=> Tracer IO DBLog
-- ^ Logging object
-> DefaultFieldValues
-- ^ Default database field values, used during migration.
-> Maybe FilePath
-- ^ Path to database directory, or Nothing for in-memory database
-> ((SqliteContext, DBLayer IO s k) -> IO a)
-- ^ Action to run.
-> IO a
withDBLayer trace defaultFieldValues mDatabaseDir =
bracket before after
where
before = newDBLayer trace defaultFieldValues mDatabaseDir
after = destroyDBLayer . fst
-- | Instantiate a 'DBFactory' from a given directory
newDBFactory
:: forall s k.
( PersistState s
, PersistPrivateKey (k 'RootK)
, WalletKey k
)
=> Tracer IO DBLog
-- ^ Logging object
-> DefaultFieldValues
-- ^ Default database field values, used during migration.
-> Maybe FilePath
-- ^ Path to database directory, or Nothing for in-memory database
-> IO (DBFactory IO s k)
newDBFactory tr defaultFieldValues = \case
Nothing -> do
-- NOTE
-- 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!
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
(ctx, db) <-
newDBLayer tr defaultFieldValues Nothing
pure (Map.insert wid (ctx, 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
tr
defaultFieldValues
(Just $ databaseFile wid)
(action . snd)
, 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
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 DBLog
-> 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
-- | A data-type for capturing column status. Used to be represented as a
-- 'Maybe Bool' which is somewhat confusing to interpret.
data SqlColumnStatus
= TableMissing
| ColumnMissing
| ColumnPresent
-- | Executes any manual database migration steps that may be required on
-- startup.
--
migrateManually
:: Tracer IO DBLog
-> DefaultFieldValues
-> ManualMigration
migrateManually tr defaultFieldValues =
ManualMigration $ \conn -> do
assignDefaultPassphraseScheme conn
addActiveSlotCoefficientIfMissing conn
-- FIXME
-- Temporary migration to fix Daedalus flight wallets. This should
-- really be removed as soon as we have a fix for the cardano-sl:wallet
-- currently in production.
removeSoftRndAddresses conn
removeOldTxParametersTable conn
where
-- NOTE
-- Wallets created before the 'PassphraseScheme' was introduced have no
-- passphrase scheme set in the database. Yet, their passphrase is known
-- to use the default / new scheme (i.e. PBKDF2) and, it is impossible
-- to have a wallet with a scheme but no last update. Either they should
-- have both, or they should have none.
--
-- Creation Method | Scheme | Last Update
-- --- | --- | ---
-- Byron, from mnemonic | ✓ | ✓
-- Byron, from xprv | ✓ | ✓
-- Shelley, from mnemonic | ✓ | ✓
-- Shelley, from account pub key | ø | ø
assignDefaultPassphraseScheme :: Sqlite.Connection -> IO ()
assignDefaultPassphraseScheme conn = do
isFieldPresent conn passphraseScheme >>= \case
TableMissing -> do
traceWith tr $ MsgManualMigrationNotNeeded passphraseScheme
ColumnMissing -> do
traceWith tr $ MsgManualMigrationNotNeeded passphraseScheme
query <- Sqlite.prepare conn $ T.unwords
[ "ALTER TABLE", tableName passphraseScheme
, "ADD COLUMN", fieldName passphraseScheme
, fieldType passphraseScheme, " NULL"
, ";"
]
Sqlite.step query *> Sqlite.finalize query
assignDefaultPassphraseScheme conn -- loop to apply case below
ColumnPresent -> do
value <- either (fail . show) (\x -> pure $ "\"" <> x <> "\"") $
fromPersistValueText (toPersistValue W.EncryptWithPBKDF2)
traceWith tr $ MsgManualMigrationNeeded passphraseScheme value
query <- Sqlite.prepare conn $ T.unwords
[ "UPDATE", tableName passphraseScheme
, "SET", fieldName passphraseScheme, "=", value
, "WHERE", fieldName passphraseScheme, "IS NULL"
, "AND", fieldName passphraseLastUpdatedAt, "IS NOT NULL"
, ";"
]
Sqlite.step query *> Sqlite.finalize query
where
passphraseScheme = DBField WalPassphraseScheme
passphraseLastUpdatedAt = DBField WalPassphraseLastUpdatedAt
-- | Remove any addresses that were wrongly generated in previous releases.
-- See comment below in 'selectState' from 'RndState'.
--
-- Important: this _may_ remove USED addresses from the discovered set which
-- is _okay-ish_ for two reasons:
--
-- 1. Address will still be discovered in UTxOs and this won't affect
-- users' balance. But the address won't show up when in the listing.
-- This is a wanted behavior.
--
-- 2. The discovered list of address is really used internally to avoid
-- index clash when generating new change addresses. Since we'll
-- generate addresses from a completely different part of the HD tree
-- ANYWAY, there's no risk of clash.
removeSoftRndAddresses :: Sqlite.Connection -> IO ()
removeSoftRndAddresses conn = do
isFieldPresent conn rndAccountIx >>= \case
TableMissing -> do
traceWith tr $ MsgManualMigrationNotNeeded rndAccountIx
ColumnMissing -> do
traceWith tr $ MsgManualMigrationNotNeeded rndAccountIx
ColumnPresent -> do
traceWith tr $ MsgManualMigrationNeeded rndAccountIx hardLowerBound
stmt <- Sqlite.prepare conn $ T.unwords
[ "DELETE FROM", tableName rndAccountIx
, "WHERE", fieldName rndAccountIx, "<", hardLowerBound
, ";"
]
_ <- Sqlite.step stmt
Sqlite.finalize stmt
where
hardLowerBound = toText $ fromEnum $ minBound @(Index 'Hardened _)
rndAccountIx = DBField RndStateAddressAccountIndex
-- | Adds an 'active_slot_coeff' column to the 'checkpoint' table if
-- it is missing.
--
addActiveSlotCoefficientIfMissing :: Sqlite.Connection -> IO ()
addActiveSlotCoefficientIfMissing conn = do
isFieldPresent conn activeSlotCoeff >>= \case
TableMissing ->
traceWith tr $ MsgManualMigrationNotNeeded activeSlotCoeff
ColumnMissing -> do
traceWith tr $ MsgManualMigrationNeeded activeSlotCoeff value
addColumn <- Sqlite.prepare conn $ T.unwords
[ "ALTER TABLE", tableName activeSlotCoeff
, "ADD COLUMN", fieldName activeSlotCoeff
, fieldType activeSlotCoeff, "NOT NULL", "DEFAULT", value
, ";"
]
_ <- Sqlite.step addColumn
Sqlite.finalize addColumn
ColumnPresent ->
traceWith tr $ MsgManualMigrationNotNeeded activeSlotCoeff
where
activeSlotCoeff = DBField CheckpointActiveSlotCoeff
value = toText
$ W.unActiveSlotCoefficient
$ defaultActiveSlotCoefficient defaultFieldValues
-- | This table became @protocol_parameters@.
removeOldTxParametersTable :: Sqlite.Connection -> IO ()
removeOldTxParametersTable conn = do
dropTable <- Sqlite.prepare conn "DROP TABLE IF EXISTS tx_parameters;"
void $ Sqlite.stepConn conn dropTable
Sqlite.finalize dropTable
-- | Determines whether a field is present in its parent table.
isFieldPresent :: Sqlite.Connection -> DBField -> IO SqlColumnStatus
isFieldPresent conn field = do
getCheckpointTableInfo <- Sqlite.prepare conn $ mconcat
[ "SELECT sql FROM sqlite_master "
, "WHERE type = 'table' "
, "AND name = '" <> tableName field <> "';"
]
row <- Sqlite.step getCheckpointTableInfo
>> Sqlite.columns getCheckpointTableInfo
Sqlite.finalize getCheckpointTableInfo
pure $ case row of
[PersistText t]
| fieldName field `T.isInfixOf` t -> ColumnPresent
| otherwise -> ColumnMissing
_ -> TableMissing
-- | A set of default field values that can be consulted when performing a
-- database migration.
--
newtype DefaultFieldValues = DefaultFieldValues
{ defaultActiveSlotCoefficient :: W.ActiveSlotCoefficient }
-- | 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.
--
-- 'getDBLayer' will provide the actual 'DBLayer' implementation. The database
-- should be closed with 'destroyDBLayer'. If you use 'withDBLayer' then both of
-- these things will be handled for you.
newDBLayer
:: forall s k.
( PersistState s
, PersistPrivateKey (k 'RootK)
)
=> Tracer IO DBLog
-- ^ Logging object
-> DefaultFieldValues
-- ^ Default database field values, used during migration.
-> Maybe FilePath
-- ^ Path to database file, or Nothing for in-memory database
-> IO (SqliteContext, DBLayer IO s k)
newDBLayer trace defaultFieldValues mDatabaseFile = do
ctx@SqliteContext{runQuery} <-
either throwIO pure =<<
startSqliteBackend
(migrateManually trace defaultFieldValues)
migrateAll
trace
mDatabaseFile
return (ctx, DBLayer
{-----------------------------------------------------------------------
Wallets
-----------------------------------------------------------------------}
{ initializeWallet = \(PrimaryKey wid) cp meta txs pp -> ExceptT $ do
res <- handleConstraint (ErrWalletAlreadyExists wid) $
insert_ (mkWalletEntity wid meta)
when (isRight res) $ do
insertCheckpoint wid cp
let (metas, txins, txouts) = mkTxHistory wid txs
putTxMetas metas
putTxs txins txouts
insert_ (mkProtocolParametersEntity wid pp)
pure res
, removeWallet = \(PrimaryKey wid) -> ExceptT $ do
selectWallet wid >>= \case
Nothing -> pure $ Left $ ErrNoSuchWallet wid
Just _ -> Right <$> do
deleteCascadeWhere [WalId ==. wid]
deleteLooseTransactions
, listWallets =
map (PrimaryKey . unWalletKey) <$> selectKeysList [] [Asc WalId]
{-----------------------------------------------------------------------
Checkpoints
-----------------------------------------------------------------------}
, putCheckpoint = \(PrimaryKey wid) cp -> ExceptT $ do
selectWallet wid >>= \case
Nothing -> pure $ Left $ ErrNoSuchWallet wid
Just _ -> Right <$> insertCheckpoint wid cp
, readCheckpoint = \(PrimaryKey wid) -> do
selectLatestCheckpoint wid >>= \case
Nothing -> pure Nothing
Just cp -> do
utxo <- selectUTxO cp
s <- selectState (checkpointId cp)
pure (checkpointFromEntity @s cp utxo <$> s)
, listCheckpoints = \(PrimaryKey wid) -> do
map (blockHeaderFromEntity . entityVal) <$> selectList
[ CheckpointWalletId ==. wid ]
[ Asc CheckpointSlot ]
, rollbackTo = \(PrimaryKey wid) requestedPoint -> ExceptT $ do
findNearestPoint wid requestedPoint >>= \case
Nothing -> selectLatestCheckpoint wid >>= \case
Nothing ->
pure $ Left $ ErrNoSuchWallet wid
Just _ ->
lift $ throwIO (ErrNoOlderCheckpoint wid requestedPoint)
Just nearestPoint -> do
deleteCheckpoints wid
[ CheckpointSlot >. nearestPoint
]
deleteDelegationCertificates wid
[ CertSlot >. nearestPoint
]
updateTxMetas wid
[ TxMetaDirection ==. W.Outgoing
, TxMetaSlot >. nearestPoint
]
[ TxMetaStatus =. W.Pending
, TxMetaSlot =. nearestPoint
]
deleteTxMetas wid
[ TxMetaDirection ==. W.Incoming
, TxMetaSlot >. nearestPoint
]
deleteStakeKeyCerts wid
[ StakeKeyCertSlot >. nearestPoint
]
pure (Right nearestPoint)
, prune = \(PrimaryKey wid) -> ExceptT $ do
selectLatestCheckpoint wid >>= \case
Nothing -> pure $ Left $ ErrNoSuchWallet wid
Just cp -> Right <$> do
pruneCheckpoints wid cp
deleteLooseTransactions
{-----------------------------------------------------------------------
Wallet Metadata
-----------------------------------------------------------------------}
, putWalletMeta = \(PrimaryKey wid) meta -> ExceptT $ do
selectWallet wid >>= \case
Nothing -> pure $ Left $ ErrNoSuchWallet wid
Just _ -> do
updateWhere [WalId ==. wid]
(mkWalletMetadataUpdate meta)
pure $ Right ()
, readWalletMeta = \(PrimaryKey wid) -> do
selectLatestCheckpoint wid >>= \case
Nothing -> pure Nothing
Just cp -> do
let (W.SlotId currentEpoch _) = checkpointSlot cp
readWalletDelegation wid currentEpoch >>= readWalletMetadata wid
, putDelegationCertificate = \(PrimaryKey wid) cert sl -> ExceptT $ do
selectWallet wid >>= \case
Nothing -> pure $ Left $ ErrNoSuchWallet wid
Just _ -> case cert of
W.CertDelegateNone _ -> do
repsert
(DelegationCertificateKey wid sl)
(DelegationCertificate wid sl Nothing)
pure <$> repsert
(StakeKeyCertificateKey wid sl)
(StakeKeyCertificate wid sl False)
W.CertDelegateFull _ pool ->
pure <$> repsert
(DelegationCertificateKey wid sl)
(DelegationCertificate wid sl (Just pool))
W.CertRegisterKey _ ->
pure <$> repsert
(StakeKeyCertificateKey wid sl)
(StakeKeyCertificate wid sl True)
, readIsStakeKeyRegistered = \(PrimaryKey wid) -> ExceptT $ do
val <- fmap entityVal <$> selectFirst
[StakeKeyCertWalletId ==. wid]
[Desc StakeKeyCertSlot]
return $ case val of
Nothing -> Left $ ErrNoSuchWallet wid
Just (StakeKeyCertificate _ _ isReg) -> Right isReg
{-----------------------------------------------------------------------
Tx History
-----------------------------------------------------------------------}
, putTxHistory = \(PrimaryKey wid) txs -> ExceptT $ do
selectWallet wid >>= \case
Nothing -> pure $ Left $ ErrNoSuchWallet wid
Just _ -> do
let (metas, txins, txouts) = mkTxHistory wid txs
putTxMetas metas
putTxs txins txouts
pure $ Right ()
, readTxHistory = \(PrimaryKey wid) order range status -> do
selectTxHistory wid order $ catMaybes
[ (TxMetaSlot >=.) <$> W.inclusiveLowerBound range
, (TxMetaSlot <=.) <$> W.inclusiveUpperBound range
, (TxMetaStatus ==.) <$> status
]
, removePendingTx = \(PrimaryKey wid) tid -> ExceptT $ do
let errNoSuchWallet =
Left $ ErrRemovePendingTxNoSuchWallet $ ErrNoSuchWallet wid
let errNoMorePending =
Left $ ErrRemovePendingTxTransactionNoMorePending tid
let errNoSuchTransaction =
Left $ ErrRemovePendingTxNoSuchTransaction tid
selectWallet wid >>= \case
Nothing -> pure errNoSuchWallet
Just _ -> do
metas <- selectPendingTxs wid (TxId tid)
let isPending (TxMeta _ _ st _ _ _ _) = st == W.Pending
case metas of
[] -> pure errNoSuchTransaction
txs | any isPending txs -> do
deletePendingTx wid (TxId tid)
pure $ Right ()
_ -> pure errNoMorePending
, getTx = \(PrimaryKey wid) tid -> ExceptT $ do
selectWallet wid >>= \case
Nothing -> pure $ Left $ ErrNoSuchWallet wid
Just _ -> do
metas <- selectTxHistory wid W.Descending
[ TxMetaTxId ==. (TxId tid) ]
case metas of
[] -> pure (Right Nothing)
meta:_ -> pure (Right $ Just meta)
{-----------------------------------------------------------------------
Keystore
-----------------------------------------------------------------------}
, putPrivateKey = \(PrimaryKey wid) key -> ExceptT $ do
selectWallet wid >>= \case
Nothing -> pure $ Left $ ErrNoSuchWallet wid
Just _ -> Right <$> do
deleteWhere [PrivateKeyWalletId ==. wid]
insert_ (mkPrivateKeyEntity wid key)
, readPrivateKey = \(PrimaryKey wid) -> selectPrivateKey wid
{-----------------------------------------------------------------------
Blockchain Parameters
-----------------------------------------------------------------------}
, putProtocolParameters = \(PrimaryKey wid) pp -> ExceptT $ do
selectWallet wid >>= \case
Nothing -> pure $ Left $ ErrNoSuchWallet wid
Just _ -> Right <$> repsert
(ProtocolParametersKey wid)
(mkProtocolParametersEntity wid pp)
, readProtocolParameters =
\(PrimaryKey wid) -> selectProtocolParameters wid
{-----------------------------------------------------------------------
Delegation Rewards
-----------------------------------------------------------------------}
, putDelegationRewardBalance =
\(PrimaryKey wid) (Quantity amt) -> ExceptT $ do
selectWallet wid >>= \case
Nothing -> pure $ Left $ ErrNoSuchWallet wid
Just _ -> Right <$> repsert
(DelegationRewardKey wid)
(DelegationReward wid amt)
, readDelegationRewardBalance =
\(PrimaryKey wid) ->
maybe minBound (Quantity . rewardAccountBalance . entityVal) <$>
selectFirst [RewardWalletId ==. wid] []
{-----------------------------------------------------------------------
ACID Execution
-----------------------------------------------------------------------}
, atomically = runQuery
})
readWalletMetadata
:: W.WalletId
-> W.WalletDelegation
-> SqlPersistT IO (Maybe W.WalletMetadata)
readWalletMetadata wid walDel =
fmap (metadataFromEntity walDel . entityVal)
<$> selectFirst [WalId ==. wid] []
readWalletDelegation
:: W.WalletId
-> W.EpochNo
-> SqlPersistT IO W.WalletDelegation
readWalletDelegation wid epoch
| epoch == 0 = pure $ W.WalletDelegation W.NotDelegating []
| otherwise = do
active <- maybe W.NotDelegating toWalletDelegationStatus
<$> readDelegationCertificate wid
[ CertSlot <. W.SlotId (epoch - 1) 0
]
next <- catMaybes <$> sequence
[ fmap (W.WalletDelegationNext (epoch + 1) . toWalletDelegationStatus)
<$> readDelegationCertificate wid
[ CertSlot >=. W.SlotId (epoch - 1) 0
, CertSlot <. W.SlotId epoch 0
]
, fmap (W.WalletDelegationNext (epoch + 2) . toWalletDelegationStatus)
<$> readDelegationCertificate wid
[ CertSlot >=. W.SlotId epoch 0
]
]
pure $ W.WalletDelegation active next
readDelegationCertificate
:: W.WalletId
-> [Filter DelegationCertificate]
-> SqlPersistT IO (Maybe DelegationCertificate)
readDelegationCertificate wid filters = fmap entityVal
<$> selectFirst ((CertWalletId ==. wid) : filters) [Desc CertSlot]
toWalletDelegationStatus
:: DelegationCertificate
-> W.WalletDelegationStatus
toWalletDelegationStatus = \case
DelegationCertificate _ _ Nothing ->
W.NotDelegating
DelegationCertificate _ _ (Just pool) ->
W.Delegating pool
mkWalletEntity :: W.WalletId -> W.WalletMetadata -> Wallet
mkWalletEntity wid meta = Wallet
{ walId = wid
, walName = meta ^. #name . coerce
, walCreationTime = meta ^. #creationTime
, walPassphraseLastUpdatedAt = W.lastUpdatedAt <$> meta ^. #passphraseInfo
, walPassphraseScheme = W.passphraseScheme <$> meta ^. #passphraseInfo
}
mkWalletMetadataUpdate :: W.WalletMetadata -> [Update Wallet]
mkWalletMetadataUpdate meta =
[ WalName =. meta ^. #name . coerce
, WalCreationTime =. meta ^. #creationTime
, WalPassphraseLastUpdatedAt =.
W.lastUpdatedAt <$> meta ^. #passphraseInfo
, WalPassphraseScheme =.
W.passphraseScheme <$> meta ^. #passphraseInfo
]
blockHeaderFromEntity :: Checkpoint -> W.BlockHeader
blockHeaderFromEntity cp = W.BlockHeader
{ slotId = checkpointSlot cp
, blockHeight = Quantity (checkpointBlockHeight cp)
, headerHash = getBlockId (checkpointHeaderHash cp)
, parentHeaderHash = getBlockId (checkpointParentHash cp)
}
metadataFromEntity :: W.WalletDelegation -> Wallet -> W.WalletMetadata
metadataFromEntity walDelegation wal = W.WalletMetadata
{ name = W.WalletName (walName wal)
, creationTime = walCreationTime wal
, passphraseInfo = W.WalletPassphraseInfo
<$> walPassphraseLastUpdatedAt wal
<*> walPassphraseScheme wal
, delegation = walDelegation
}
mkPrivateKeyEntity
:: PersistPrivateKey (k 'RootK)
=> W.WalletId
-> (k 'RootK XPrv, W.Hash "encryption")
-> PrivateKey
mkPrivateKeyEntity wid kh = PrivateKey
{ privateKeyWalletId = wid
, privateKeyRootKey = root
, privateKeyHash = hash
}
where
(root, hash) = serializeXPrv kh
privateKeyFromEntity
:: PersistPrivateKey (k 'RootK)
=> PrivateKey
-> (k 'RootK XPrv, W.Hash "encryption")
privateKeyFromEntity (PrivateKey _ k h) =
unsafeDeserializeXPrv (k, h)
mkCheckpointEntity
:: W.WalletId
-> W.Wallet s
-> (Checkpoint, [UTxO])
mkCheckpointEntity wid wal =
(cp, utxo)
where
header = W.currentTip wal
sl = header ^. #slotId
(Quantity bh) = header ^. #blockHeight
gp = W.blockchainParameters wal
cp = Checkpoint
{ checkpointWalletId = wid
, checkpointSlot = sl
, checkpointParentHash = BlockId (header ^. #parentHeaderHash)
, checkpointHeaderHash = BlockId (header ^. #headerHash)
, checkpointBlockHeight = bh
, checkpointGenesisHash = BlockId (coerce (gp ^. #getGenesisBlockHash))
, checkpointGenesisStart = coerce (gp ^. #getGenesisBlockDate)
, checkpointSlotLength = coerceSlotLength $ gp ^. #getSlotLength
, checkpointEpochLength = coerce (gp ^. #getEpochLength)
, checkpointEpochStability = coerce (gp ^. #getEpochStability)
, checkpointActiveSlotCoeff =
W.unActiveSlotCoefficient (gp ^. #getActiveSlotCoefficient)
, checkpointFeePolicyUnused = ""
, checkpointTxMaxSizeUnused = 0
}
utxo =
[ UTxO wid sl (TxId input) ix addr coin
| (W.TxIn input ix, W.TxOut addr coin) <- utxoMap
]
utxoMap = Map.assocs (W.getUTxO (W.utxo wal))
coerceSlotLength :: W.SlotLength -> Word64
coerceSlotLength (W.SlotLength x) = toEnum (fromEnum x)
-- note: TxIn records must already be sorted by order
-- and TxOut records must already by sorted by index.
checkpointFromEntity
:: Checkpoint
-> [UTxO]
-> s
-> W.Wallet s
checkpointFromEntity cp utxo s =
W.unsafeInitWallet utxo' header s gp
where
(Checkpoint
_walletId
slot
(BlockId headerHash)
(BlockId parentHeaderHash)
bh
(BlockId genesisHash)
genesisStart
_feePolicyUnused
slotLength
epochLength
_txMaxSizeUnused
epochStability
activeSlotCoeff
) = cp
header = (W.BlockHeader slot (Quantity bh) headerHash parentHeaderHash)
utxo' = W.UTxO . Map.fromList $
[ (W.TxIn input ix, W.TxOut addr coin)
| UTxO _ _ (TxId input) ix addr coin <- utxo
]
gp = W.GenesisParameters
{ getGenesisBlockHash = coerce genesisHash
, getGenesisBlockDate = W.StartTime genesisStart
, getSlotLength = W.SlotLength (toEnum (fromEnum slotLength))
, getEpochLength = W.EpochLength epochLength
, getEpochStability = Quantity epochStability
, getActiveSlotCoefficient = W.ActiveSlotCoefficient activeSlotCoeff
}
mkTxHistory
:: W.WalletId
-> [(W.Tx, W.TxMeta)]
-> ([TxMeta], [TxIn], [TxOut])
mkTxHistory wid txs = flatTxHistory
[ (mkTxMetaEntity wid txid meta, mkTxInputsOutputs (txid, tx))
| (tx, meta) <- txs
, let txid = W.txId tx
]
where
-- | Make flat lists of entities from the result of 'mkTxHistory'.
flatTxHistory
:: [(TxMeta, ([TxIn], [TxOut]))] -> ([TxMeta], [TxIn], [TxOut])
flatTxHistory entities =
( map fst entities
, concatMap (fst . snd) entities
, concatMap (snd . snd) entities
)
mkTxInputsOutputs
:: (W.Hash "Tx", W.Tx)
-> ([TxIn], [TxOut])
mkTxInputsOutputs tx =
( (dist mkTxIn . ordered W.resolvedInputs) tx
, (dist mkTxOut . ordered W.outputs) tx )
where
mkTxIn tid (ix, (txIn, amt)) = TxIn
{ txInputTxId = TxId tid
, txInputOrder = ix
, txInputSourceTxId = TxId (W.inputId txIn)
, txInputSourceIndex = W.inputIx txIn
, txInputSourceAmount = amt
}
mkTxOut tid (ix, txOut) = TxOut
{ txOutputTxId = TxId tid
, txOutputIndex = ix
, txOutputAddress = W.address txOut
, txOutputAmount = W.coin txOut
}
ordered f = fmap (zip [0..] . f)
-- | Distribute `a` accross many `b`s using the given function.
-- >>> dist TxOut (addr, [Coin 1, Coin 42, Coin 14])
-- [TxOut addr (Coin 1), TxOut addr (Coin 42), TxOut addr (Coin 14)]
dist :: (a -> b -> c) -> (a, [b]) -> [c]
dist f (a, bs) = [f a b | b <- bs]
mkTxMetaEntity :: W.WalletId -> W.Hash "Tx" -> W.TxMeta -> TxMeta
mkTxMetaEntity wid txid meta = TxMeta
{ txMetaTxId = TxId txid
, txMetaWalletId = wid
, txMetaStatus = meta ^. #status
, txMetaDirection = meta ^. #direction
, txMetaSlot = meta ^. #slotId
, txMetaBlockHeight = getQuantity (meta ^. #blockHeight)
, txMetaAmount = getQuantity (meta ^. #amount)
}
-- note: TxIn records must already be sorted by order
-- and TxOut records must already be sorted by index
txHistoryFromEntity
:: W.SlotParameters
-> W.BlockHeader
-> [TxMeta]
-> [(TxIn, Maybe TxOut)]
-> [TxOut]
-> [W.TransactionInfo]
txHistoryFromEntity sp tip metas ins outs =
map mkItem metas
where
mkItem m = mkTxWith (txMetaTxId m) (mkTxMeta m)
mkTxWith txid meta = W.TransactionInfo
{ W.txInfoId =
getTxId txid
, W.txInfoInputs =
map mkTxIn $ filter ((== txid) . txInputTxId . fst) ins
, W.txInfoOutputs =
map mkTxOut $ filter ((== txid) . txOutputTxId) outs
, W.txInfoMeta =
meta
, W.txInfoDepth =