/
Sqlite.hs
2380 lines (2172 loc) · 88.3 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 TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{- 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.Address.Script
( KeyHash, ScriptHash (..) )
import Cardano.DB.Sqlite
( DBField (..)
, DBLog (..)
, ManualMigration (..)
, SqliteContext (..)
, chunkSize
, dbChunked
, dbChunked'
, destroyDBLayer
, fieldName
, fieldType
, handleConstraint
, startSqliteBackend
, tableName
)
import Cardano.DB.Sqlite.Delete
( deleteSqliteDatabase, newRefCount, waitForFree, withRef )
import Cardano.Wallet.DB
( DBFactory (..)
, DBLayer (..)
, ErrNoSuchWallet (..)
, ErrRemoveTx (..)
, ErrWalletAlreadyExists (..)
, PrimaryKey (..)
, defaultSparseCheckpointsConfig
, sparseCheckpoints
)
import Cardano.Wallet.DB.Sqlite.TH
( Checkpoint (..)
, DelegationCertificate (..)
, DelegationReward (..)
, EntityField (..)
, Key (..)
, PrivateKey (..)
, ProtocolParameters (..)
, RndState (..)
, RndStateAddress (..)
, RndStatePendingAddress (..)
, SeqState (..)
, SeqStateAddress (..)
, SeqStateKeyHash (..)
, SeqStatePendingIx (..)
, SeqStateScriptHash (..)
, StakeKeyCertificate (..)
, TxIn (..)
, TxMeta (..)
, TxOut (..)
, TxOutToken (..)
, TxWithdrawal (..)
, UTxO (..)
, UTxOToken (..)
, 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 Cardano.Wallet.Primitive.AddressDerivation.Icarus
( IcarusKey )
import Cardano.Wallet.Primitive.AddressDerivation.Shelley
( ShelleyKey (..) )
import Cardano.Wallet.Primitive.Slotting
( TimeInterpreter
, epochOf
, firstSlotInEpoch
, interpretQuery
, slotToUTCTime
)
import Cardano.Wallet.Primitive.Types.TokenMap
( AssetId (..) )
import Control.Monad
( forM, 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.Functor
( (<&>) )
import Data.Generics.Internal.VL.Lens
( view, (^.) )
import Data.IORef
( modifyIORef', newIORef, readIORef )
import Data.List
( nub, sortOn, unzip3 )
import Data.List.Split
( chunksOf )
import Data.Map.Strict
( Map )
import Data.Maybe
( catMaybes, mapMaybe )
import Data.Ord
( Down (..) )
import Data.Proxy
( Proxy (..) )
import Data.Quantity
( Quantity (..) )
import Data.Text
( Text )
import Data.Text.Class
( ToText (..), fromText )
import Data.Typeable
( Typeable )
import Data.Word
( Word16, Word32 )
import Database.Persist.Class
( toPersistValue )
import Database.Persist.Sql
( Entity (..)
, Filter
, SelectOpt (..)
, Update (..)
, deleteCascadeWhere
, deleteWhere
, deleteWhereCount
, insertMany_
, insert_
, rawExecute
, repsert
, repsertMany
, selectFirst
, selectKeysList
, selectList
, updateWhere
, (/<-.)
, (<-.)
, (<.)
, (<=.)
, (=.)
, (==.)
, (>.)
, (>=.)
)
import Database.Persist.Sqlite
( SqlPersistT )
import Database.Persist.Types
( PersistValue (..), fromPersistValueText )
import Fmt
( pretty )
import Numeric.Natural
( Natural )
import System.Directory
( doesFileExist, listDirectory )
import System.FilePath
( (</>) )
import UnliftIO.Exception
( Exception, bracket, throwIO )
import UnliftIO.MVar
( modifyMVar, modifyMVar_, newMVar, readMVar )
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 Cardano.Wallet.Primitive.Types.Address as W
import qualified Cardano.Wallet.Primitive.Types.Coin as W
import qualified Cardano.Wallet.Primitive.Types.Hash as W
import qualified Cardano.Wallet.Primitive.Types.TokenBundle as TokenBundle
import qualified Cardano.Wallet.Primitive.Types.Tx as W
import qualified Cardano.Wallet.Primitive.Types.UTxO as W
import qualified Data.List as L
import qualified Data.Map.Strict 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)
, 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
-> TimeInterpreter IO
-> ((SqliteContext, DBLayer IO s k) -> IO a)
-- ^ Action to run.
-> IO a
withDBLayer trace defaultFieldValues mDatabaseDir ti =
bracket before after
where
before = newDBLayer trace defaultFieldValues mDatabaseDir ti
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.
-> TimeInterpreter IO
-> Maybe FilePath
-- ^ Path to database directory, or Nothing for in-memory database
-> IO (DBFactory IO s k)
newDBFactory tr defaultFieldValues ti = \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 ti
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)
ti
(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
deriving Eq
-- | Executes any manual database migration steps that may be required on
-- startup.
--
migrateManually
:: WalletKey k
=> Tracer IO DBLog
-> Proxy k
-> DefaultFieldValues
-> ManualMigration
migrateManually tr proxy defaultFieldValues =
ManualMigration $ \conn -> do
cleanupCheckpointTable conn
assignDefaultPassphraseScheme conn
addDesiredPoolNumberIfMissing conn
addMinimumUTxOValueIfMissing conn
addHardforkEpochIfMissing 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
addAddressStateIfMissing conn
addSeqStateDerivationPrefixIfMissing conn
renameRoleColumn conn
renameRoleFields conn
addScriptAddressGapIfMissing conn
updateFeeValueAndAddKeyDeposit conn
addFeeToTransaction conn
moveRndUnusedAddresses conn
where
-- NOTE
-- We originally stored protocol parameters in the 'Checkpoint' table, and
-- later moved them to a new dedicatd table. However, removing a column is
-- not something straightforward in SQLite, so we initially simply marked
-- most parameters as _unused. Later, we did rework how genesis and protocol
-- parameters were stored and shared between wallets and completely removed
-- them from the database. At the same time, we also introduced
-- 'genesis_hash' and 'genesis_start' in the 'Wallet' table which we use is
-- as a discriminator for the migration.
cleanupCheckpointTable :: Sqlite.Connection -> IO ()
cleanupCheckpointTable conn = do
let field = DBField WalGenesisHash
isFieldPresent conn field >>= \case
TableMissing ->
traceWith tr $ MsgManualMigrationNotNeeded field
ColumnPresent -> do
traceWith tr $ MsgManualMigrationNotNeeded field
ColumnMissing -> do
let orig = "checkpoint"
let tmp = orig <> "_tmp"
-- 1. Add genesis_hash and genesis_start to the 'wallet' table.
[defaults] <- runSql conn $ select ["genesis_hash", "genesis_start"] orig
let [PersistText genesisHash, PersistText genesisStart] = defaults
addColumn_ conn True (DBField WalGenesisHash) (quotes genesisHash)
addColumn_ conn True (DBField WalGenesisStart) (quotes genesisStart)
-- 2. Drop columns from the 'checkpoint' table
info <- runSql conn $ getTableInfo orig
let filtered = mapMaybe (filterColumn excluding) info
where
excluding =
[ "genesis_hash", "genesis_start", "fee_policy"
, "slot_length", "epoch_length", "tx_max_size"
, "epoch_stability", "active_slot_coeff"
]
_ <- runSql conn $ createTable tmp filtered
_ <- runSql conn $ copyTable orig tmp filtered
_ <- runSql conn $ dropTable orig
_ <- runSql conn $ renameTable tmp orig
return ()
where
select fields table = mconcat
[ "SELECT ", T.intercalate ", " fields
, " FROM ", table
, " ORDER BY slot ASC LIMIT 1;"
]
getTableInfo table = mconcat
[ "PRAGMA table_info(", table, ");"
]
createTable table cols = mconcat
[ "CREATE TABLE ", table, " ("
, T.intercalate ", " (mapMaybe createColumn cols)
, ");"
]
copyTable source destination cols = mconcat
[ "INSERT INTO ", destination, " SELECT "
, T.intercalate ", " (mapMaybe selectColumn cols)
, " FROM ", source
, ";"
]
dropTable table = mconcat
[ "DROP TABLE " <> table <> ";"
]
renameTable from to = mconcat
[ "ALTER TABLE ", from, " RENAME TO ", to, ";" ]
filterColumn :: [Text] -> [PersistValue] -> Maybe [PersistValue]
filterColumn excluding = \case
[ _, PersistText colName, PersistText colType, colNull, _, _] ->
if colName `elem` excluding then
Nothing
else
Just [PersistText colName, PersistText colType, colNull]
_ ->
Nothing
selectColumn :: [PersistValue] -> Maybe Text
selectColumn = \case
[ PersistText colName, _ , _ ] ->
Just colName
_ ->
Nothing
createColumn :: [PersistValue] -> Maybe Text
createColumn = \case
[ PersistText colName, PersistText colType, PersistInt64 1 ] ->
Just $ T.unwords [ colName, colType, "NOT NULL" ]
[ PersistText colName, PersistText colType, _ ] ->
Just $ T.unwords [ colName, colType ]
_ ->
Nothing
-- 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
-- | When we implemented the 'importAddress' and 'createAddress' features,
-- we mistakenly added all imported addresses in the discovered section and
-- table of the RndState. This makes them affected by rollbacks, which is
-- very much an issue. While fixing this, we can also take the opportunity
-- to move all existing 'unused' addresses from the 'RndStateAddress' to the
-- 'RndStatePendingAddress' table.
--
-- Arguably, the 'status' column is redundant on the 'RndStateAddress' table
-- because any address in that table must be 'Used', by construction.
moveRndUnusedAddresses :: Sqlite.Connection -> IO ()
moveRndUnusedAddresses conn = do
isFieldPresent conn rndStateAddressStatus >>= \case
TableMissing -> do
traceWith tr $ MsgManualMigrationNotNeeded rndStateAddressStatus
ColumnMissing -> do
traceWith tr $ MsgManualMigrationNotNeeded rndStateAddressStatus
ColumnPresent -> do
let unused = quotes $ toText W.Unused
[[PersistInt64 n]] <- runSql conn $ T.unwords
[ "SELECT COUNT(*)"
, "FROM", tableName rndStateAddressStatus
, "WHERE", fieldName rndStateAddressStatus, "=", unused
, ";"
]
if n > 0 then do
traceWith tr $ MsgManualMigrationNeeded rndStateAddressStatus "-"
void $ runSql conn $ T.unwords
[ "INSERT INTO", rndStatePendingTable
, "(wallet_id, account_ix, address_ix, address)"
, "SELECT wallet_id, account_ix, address_ix, address"
, "FROM", rndStateDiscoveredTable
, "WHERE", fieldName rndStateAddressStatus, "=", unused
, ";"
]
void $ runSql conn $ T.unwords
[ "DELETE FROM", rndStateDiscoveredTable
, "WHERE", fieldName rndStateAddressStatus, "=", unused
, ";"
]
else do
traceWith tr $ MsgManualMigrationNotNeeded rndStateAddressStatus
where
rndStateAddressStatus = DBField RndStateAddressStatus
rndStateDiscoveredTable = tableName $ DBField RndStateAddressWalletId
rndStatePendingTable = tableName $ DBField RndStatePendingAddressWalletId
-- | Adds an 'desired_pool_number' column to the 'protocol_parameters'
-- table if it is missing.
--
addDesiredPoolNumberIfMissing :: Sqlite.Connection -> IO ()
addDesiredPoolNumberIfMissing conn = do
addColumn_ conn True (DBField ProtocolParametersDesiredNumberOfPools) value
where
value = T.pack $ show $ defaultDesiredNumberOfPool defaultFieldValues
-- | Adds an 'minimum_utxo_value' column to the 'protocol_parameters'
-- table if it is missing.
--
addMinimumUTxOValueIfMissing :: Sqlite.Connection -> IO ()
addMinimumUTxOValueIfMissing conn = do
addColumn_ conn True (DBField ProtocolParametersMinimumUtxoValue) value
where
value = T.pack $ show $ W.unCoin $ defaultMinimumUTxOValue defaultFieldValues
-- | Adds an 'hardfork_epoch' column to the 'protocol_parameters'
-- table if it is missing.
--
addHardforkEpochIfMissing :: Sqlite.Connection -> IO ()
addHardforkEpochIfMissing conn = do
addColumn_ conn False (DBField ProtocolParametersHardforkEpoch) value
where
value = case defaultHardforkEpoch defaultFieldValues of
Nothing -> "NULL"
Just v -> T.pack $ show $ W.unEpochNo v
-- | Adds a 'key_deposit column to the 'protocol_parameters' table if it is
-- missing.
--
addKeyDepositIfMissing :: Sqlite.Connection -> Text -> IO ()
addKeyDepositIfMissing conn =
addColumn_ conn True (DBField ProtocolParametersKeyDeposit)
-- | 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
-- | In order to make listing addresses bearable for large wallet, we
-- altered the discovery process to mark addresses as used as they are
-- discovered. Existing databases don't have that pre-computed field.
addAddressStateIfMissing :: Sqlite.Connection -> IO ()
addAddressStateIfMissing conn = do
_ <- addColumn conn False (DBField SeqStateAddressStatus) (toText W.Unused)
st <- addColumn conn False (DBField RndStateAddressStatus) (toText W.Unused)
when (st == ColumnMissing) $ do
markAddressesAsUsed (DBField SeqStateAddressStatus)
markAddressesAsUsed (DBField RndStateAddressStatus)
where
markAddressesAsUsed field = do
query <- Sqlite.prepare conn $ T.unwords
[ "UPDATE", tableName field
, "SET status = '" <> toText W.Used <> "'"
, "WHERE", tableName field <> ".address", "IN"
, "(SELECT DISTINCT(address) FROM tx_out)"
]
_ <- Sqlite.step query
Sqlite.finalize query
addSeqStateDerivationPrefixIfMissing :: Sqlite.Connection -> IO ()
addSeqStateDerivationPrefixIfMissing conn
| isIcarusDatabase = do
addColumn_ conn True (DBField SeqStateDerivationPrefix) icarusPrefix
| isShelleyDatabase = do
addColumn_ conn True (DBField SeqStateDerivationPrefix) shelleyPrefix
| otherwise =
return ()
where
isIcarusDatabase =
keyTypeDescriptor proxy == keyTypeDescriptor (Proxy @IcarusKey)
icarusPrefix = T.pack $ show $ toText
$ Seq.DerivationPrefix (Seq.purposeBIP44, Seq.coinTypeAda, minBound)
isShelleyDatabase =
keyTypeDescriptor proxy == keyTypeDescriptor (Proxy @ShelleyKey)
shelleyPrefix = T.pack $ show $ toText
$ Seq.DerivationPrefix (Seq.purposeCIP1852, Seq.coinTypeAda, minBound)
--
-- - UTxOInternal
-- - UTxOExternal
--
-- (notice the mixed case here) and were serialized to text as:
--
-- - u_tx_o_internal
-- - u_tx_o_external
--
-- which is pretty lame. This was changed later on, but already
-- serialized data may subsist on for quite a while. Hence this little
-- pirouette here.
renameRoleFields :: Sqlite.Connection -> IO ()
renameRoleFields conn = do
renameColumnField conn (DBField SeqStateAddressRole)
"u_tx_o_internal" "utxo_internal"
renameColumnField conn (DBField SeqStateAddressRole)
"u_tx_o_external" "utxo_external"
-- | Rename column table of SeqStateAddress from 'accounting_style' to `role`
-- if needed.
renameRoleColumn :: Sqlite.Connection -> IO ()
renameRoleColumn conn =
isFieldPresent conn roleField >>= \case
TableMissing ->
traceWith tr $ MsgManualMigrationNotNeeded roleField
ColumnMissing -> do
traceWith tr $ MsgManualMigrationNeeded roleField "accounting_style"
query <- Sqlite.prepare conn $ T.unwords
[ "ALTER TABLE", tableName roleField
, "RENAME COLUMN accounting_style TO"
, fieldName roleField
, ";"
]
Sqlite.step query *> Sqlite.finalize query
ColumnPresent ->
traceWith tr $ MsgManualMigrationNotNeeded roleField
where
roleField = DBField SeqStateAddressRole
-- | Adds an 'script_gap' column to the 'SeqState'
-- table if it is missing.
--
addScriptAddressGapIfMissing :: Sqlite.Connection -> IO ()
addScriptAddressGapIfMissing conn =
addColumn_ conn True (DBField SeqStateScriptGap) value
where
value = T.pack $ show $ Seq.getAddressPoolGap Seq.defaultAddressPoolGap
-- This migration is rather delicate. Indeed, we need to introduce an
-- explicit 'fee' on known transactions, so only do we need to add the new
-- column (easy), but we also need to find the right value for that new
-- column (delicate).
--
-- Note that it is not possible to recover explicit fees on incoming
-- transactions without having access to the entire ledger (we do not know
-- the _amount_ from inputs of incoming transactions). Therefore, by
-- convention it has been decided that incoming transactions will have fee
-- equals to 0.
--
-- For outgoing transaction, it is possible to recalculate fees by
-- calculating the delta between the total input value minus the total
-- output value. The delta (inputs - output) is necessarily positive
-- (by definition of 'outgoing' transactions) and comprised of:
--
-- - Fees
-- - Total deposits if any
--
-- To substract deposit values from fees, we consider that any transaction
-- that has one or less output and fees greater than the key deposit (or min
-- utxo value) is a key registration transaction and the key deposit value
-- can be substracted from the delta to deduce the fees.
--
-- Note that ideally, we would do this in a single `UPDATE ... FROM` query
-- but the `FROM` syntax is only supported in SQLite >= 3.33 which is only
-- supported in the latest version of persistent-sqlite (2.11.0.0). So
-- instead, we query all transactions which require an update in memory,
-- and update them one by one. This may be quite long on some database but
-- it is in the end a one-time cost paid on start-up.
addFeeToTransaction :: Sqlite.Connection -> IO ()
addFeeToTransaction conn = do
isFieldPresent conn fieldFee >>= \case
TableMissing ->
traceWith tr $ MsgManualMigrationNotNeeded fieldFee
ColumnPresent ->
traceWith tr $ MsgManualMigrationNotNeeded fieldFee
ColumnMissing -> do
traceWith tr $ MsgManualMigrationNeeded fieldFee "NULL"
rows <- fmap unwrapRows (mkQuery >>= runSql conn)
_ <- runSql conn $ T.unwords
[ "ALTER TABLE", tableName fieldFee
, "ADD COLUMN", fieldName fieldFee
, fieldType fieldFee
, ";"
]
forM_ rows $ \(txid, nOuts, delta) -> do
let fee = T.pack $ show $
if isKeyRegistration nOuts delta
then delta - keyDepositValue
else delta
runSql conn $ T.unwords
[ "UPDATE", tableName fieldFee
, "SET", fieldName fieldFee, "=", quotes fee
, "WHERE", fieldName fieldTxId, "=", quotes txid
, ";"
]
where
fieldFee = DBField TxMetaFee
fieldTxId = DBField TxMetaTxId
unwrapRows = fmap $ \[PersistText txid, PersistInt64 nOuts, PersistInt64 delta] ->
(txid, nOuts, delta)
isKeyRegistration nOuts delta =
nOuts <= 1 && delta > max keyDepositValue minUtxoValue
minUtxoValue
= fromIntegral
$ W.unCoin
$ defaultMinimumUTxOValue defaultFieldValues
keyDepositValue
= fromIntegral
$ W.unCoin
$ defaultKeyDeposit defaultFieldValues
mkQuery = isFieldPresent conn (DBField TxWithdrawalTxId) <&> \case
-- On rather old databases, the tx_withdrawal table doesn't even exists.
TableMissing -> T.unwords
[ "SELECT tx_id, num_out, total_in - total_out FROM tx_meta"
, "JOIN (" <> resolvedInputsQuery <> ") USING (tx_id)"
, "JOIN (" <> outputsQuery <> ") USING (tx_id)"
, "WHERE direction = 0"
, ";"
]
_ -> T.unwords
[ "SELECT tx_id, num_out, total_in + IFNULL(total_wdrl, 0) - total_out FROM tx_meta"
, "JOIN (" <> resolvedInputsQuery <> ") USING (tx_id)"
, "LEFT JOIN (" <> withdrawalsQuery <> ") USING (tx_id)"
, "JOIN (" <> outputsQuery <> ") USING (tx_id)"
, "WHERE direction = 0"
, ";"
]
resolvedInputsQuery = T.unwords
[ "SELECT tx_in.tx_id, SUM(tx_out.amount) AS total_in FROM tx_in"
, "JOIN tx_out ON tx_out.tx_id = tx_in.source_tx_id AND tx_out.'index' = tx_in.source_index"
, "GROUP BY tx_in.tx_id"
]
withdrawalsQuery = T.unwords
[ "SELECT tx_id, SUM(amount) AS total_wdrl FROM tx_withdrawal"
, "GROUP BY tx_id"
]
outputsQuery = T.unwords
[ "SELECT tx_id, SUM(amount) AS total_out, COUNT(*) AS num_out FROM tx_out"
, "GROUP BY tx_id"
]
-- | Since key deposit and fee value are intertwined, we migrate them both
-- here.
updateFeeValueAndAddKeyDeposit :: Sqlite.Connection -> IO ()
updateFeeValueAndAddKeyDeposit conn = do
isFieldPresent conn fieldKeyDeposit >>= \case
ColumnMissing -> do
-- If the key deposit is missing, we need to add it, but also
-- and first, we also need to update the fee policy and drop
-- the third component of the fee policy which is now captured
-- by the stake key deposit.
feePolicyInfo <- Sqlite.prepare conn $ T.unwords
[ "SELECT", fieldName fieldFeePolicy
, "FROM", tableName fieldFeePolicy
, ";"
]
row <- Sqlite.step feePolicyInfo >> Sqlite.columns feePolicyInfo
Sqlite.finalize feePolicyInfo
case filter (/= PersistNull) row of
[PersistText t] -> case T.splitOn " + " t of
[a,b,c] -> do
traceWith tr $ MsgManualMigrationNeeded fieldFeePolicy t
-- update fee policy
let newVal = a <> " + " <> b
query <- Sqlite.prepare conn $ T.unwords
[ "UPDATE", tableName fieldFeePolicy
, "SET", fieldName fieldFeePolicy, "= '" <> newVal <> "'"
, ";"
]
Sqlite.step query *> Sqlite.finalize query
let (Right stakeKeyVal) = W.Coin . round <$> fromText @Double (T.dropEnd 1 c)
addKeyDepositIfMissing conn (toText stakeKeyVal)
_ ->
fail ("Unexpected row result when querying fee value: " <> T.unpack t)
_ ->
return ()
-- If the protocol_parameters table is missing, or if if the key
-- deposit exists, there's nothing to do in this migration.
_ -> do
traceWith tr $ MsgManualMigrationNotNeeded fieldFeePolicy
traceWith tr $ MsgManualMigrationNotNeeded fieldKeyDeposit
where
fieldFeePolicy = DBField ProtocolParametersFeePolicy
fieldKeyDeposit = DBField ProtocolParametersKeyDeposit
-- | Determines whether a field is present in its parent table.
isFieldPresent :: Sqlite.Connection -> DBField -> IO SqlColumnStatus
isFieldPresent conn field = do
getTableInfo <- Sqlite.prepare conn $ mconcat
[ "SELECT sql FROM sqlite_master "
, "WHERE type = 'table' "
, "AND name = '" <> tableName field <> "';"
]
row <- Sqlite.step getTableInfo
>> Sqlite.columns getTableInfo
Sqlite.finalize getTableInfo
pure $ case row of
[PersistText t]
| fieldName field `T.isInfixOf` t -> ColumnPresent
| otherwise -> ColumnMissing
_ -> TableMissing
addColumn_
:: Sqlite.Connection
-> Bool
-> DBField
-> Text
-> IO ()
addColumn_ a b c =
void . addColumn a b c
-- | A migration for adding a non-existing column to a table. Factor out as
-- it's a common use-case.
addColumn
:: Sqlite.Connection
-> Bool
-> DBField
-> Text
-> IO SqlColumnStatus
addColumn conn notNull field value = do
isFieldPresent conn field >>= \st -> st <$ case st of
TableMissing ->
traceWith tr $ MsgManualMigrationNotNeeded field
ColumnMissing -> do
traceWith tr $ MsgManualMigrationNeeded field value
query <- Sqlite.prepare conn $ T.unwords
[ "ALTER TABLE", tableName field
, "ADD COLUMN", fieldName field
, fieldType field, if notNull then "NOT NULL" else ""
, "DEFAULT", value
, ";"
]
_ <- Sqlite.step query
Sqlite.finalize query
ColumnPresent ->
traceWith tr $ MsgManualMigrationNotNeeded field
renameColumnField
:: Sqlite.Connection
-> DBField
-> Text -- Old Value
-> Text -- New Value
-> IO ()
renameColumnField conn field old new = do
isFieldPresent conn field >>= \case
TableMissing ->
traceWith tr $ MsgManualMigrationNotNeeded field
ColumnMissing -> do
traceWith tr $ MsgManualMigrationNotNeeded field
ColumnPresent -> do