/
upgrades.go
1712 lines (1488 loc) · 56.4 KB
/
upgrades.go
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
// Copyright (c) 2017-2021 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package udb
import (
"context"
"crypto/sha256"
"decred.org/dcrwallet/v2/errors"
"decred.org/dcrwallet/v2/internal/compat"
"decred.org/dcrwallet/v2/wallet/internal/snacl"
"decred.org/dcrwallet/v2/wallet/walletdb"
"github.com/decred/dcrd/blockchain/stake/v4"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/chaincfg/v3"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/decred/dcrd/gcs/v3/blockcf2"
"github.com/decred/dcrd/hdkeychain/v3"
"github.com/decred/dcrd/txscript/v4/stdscript"
"github.com/decred/dcrd/wire"
)
// Note: all manager functions always use the latest version of the database.
// Therefore it is extremely important when adding database upgrade code to
// never call any methods of the managers and instead only use the db primitives
// with the correct version passed as parameters.
const (
initialVersion = 1
// lastUsedAddressIndexVersion is the second version of the database. It
// adds indexes for the last used address of BIP0044 accounts, removes the
// next to use address indexes, removes all references to address pools, and
// removes all per-address usage tracking.
//
// See lastUsedAddressIndexUpgrade for the code that implements the upgrade
// path.
lastUsedAddressIndexVersion = 2
// votingPreferencesVersion is the third version of the database. It
// removes all per-ticket vote bits, replacing them with vote preferences
// for choices on individual agendas from the current stake version.
votingPreferencesVersion = 3
// noEncryptedSeedVersion is the fourth version of the database. It removes
// the encrypted seed that earlier versions may have saved in the database
// (or more commonly, encrypted zeros on mainnet wallets).
noEncryptedSeedVersion = 4
// lastReturnedAddressVersion is the fifth version of the database. It adds
// additional indexes to each BIP0044 account row that keep track of the
// index of the last returned child address in the internal and external
// account branches. This is used to prevent returning identical addresses
// across application restarts.
lastReturnedAddressVersion = 5
// ticketBucketVersion is the sixth version of the database. It adds a
// bucket for recording the hashes of all tickets and provides additional
// APIs to check the status of tickets and whether they are spent by a vote
// or revocation.
ticketBucketVersion = 6
// slip0044CoinTypeVersion is the seventh version of the database. It
// introduces the possibility of the BIP0044 coin type key being either the
// legacy coin type used by earlier versions of the wallet, or the coin type
// assigned to Decred in SLIP0044. The upgrade does not add or remove any
// required keys (the upgrade is done in a backwards-compatible way) but the
// database version is bumped to prevent older software from assuming that
// coin type 20 exists (the upgrade is not forwards-compatible).
slip0044CoinTypeVersion = 7
// hasExpiryVersion is the eight version of the database. It adds the
// hasExpiry field to the credit struct, adds fetchRawCreditHasExpiry
// helper func and extends sstxchange type utxo checks to only make sstchange
// with expiries set available to spend after coinbase maturity (16 blocks).
hasExpiryVersion = 8
// hasExpiryFixedVersion is the ninth version of the database. It corrects
// the previous upgrade by writing the has expiry bit to an unused bit flag
// rather than in the stake flags and fixes various UTXO selection issues
// caused by misinterpreting ticket outputs as spendable by regular
// transactions.
hasExpiryFixedVersion = 9
// cfVersion is the tenth version of the database. It adds a bucket to
// store compact filters, which are required for Decred's SPV
// implementation, and a txmgr namespace root key which tracks whether all
// main chain compact filters were saved. This version does not begin to
// save compact filter headers, since the SPV implementation is expected to
// use header commitments in a later release for validation.
cfVersion = 10
// lastProcessedTxsBlockVersion is the eleventh version of the database. It
// adds a txmgr namespace root key which records the final hash of all
// blocks since the genesis block which have been processed for relevant
// transactions. This is required to distinguish between the main chain tip
// (which is advanced during headers fetch) and the point at which a startup
// rescan should occur. During upgrade, the current tip block is recorded
// as this block to avoid an additional or extra long rescan from occurring
// from properly-synced wallets.
lastProcessedTxsBlockVersion = 11
// ticketCommitmentsVersion the twelfth version of the database. It adds
// the ticketCommitment bucket to the txmgr namespace. This bucket is meant
// to track outstanding ticket commitment outputs for the purposes of
// correct balance calculation: it allows non-voting wallets (eg: funding
// wallets in solo-voting setups or non-voter participants of split tickets)
// to track their proportional locked funds. In standard (single-voter) VSP
// setups, it also allows the wallet to discount the pool fee for correct
// accounting of total locked funds.
ticketCommitmentsVersion = 12
// importedXpubAccountVersion is the thirteenth version of the
// database. It introduces the ability to import and track child
// indexes of arbitrary HD extended public keys. Imported xpub accounts
// are associated with a uint32 value in the upper range (above
// ImportedAddrAccount). The upgrade does not add or remove any
// required keys (the upgrade is done in a backwards-compatible way) but
// the database version is bumped to prevent older software from using
// an upgraded database with account identifiers that would induce
// panics.
importedXpubAccountVersion = 13
// unencryptedRedeemScriptsVersion is the 14th version of the database.
// The goal of this upgrade is to make it possible to read P2SH redeem
// scripts through the address manager without needing the wallet to be
// unlocked. This is made possible by relying on the fact that since
// mainnet launch, dcrwallet has always recorded imported P2SH redeem
// scripts both encrypted in the address manager bucket, and unencrypted
// in the transaction store buckets. During this upgrade, a check is
// performed ensuring that no unencrypted scripts are missing.
// Unencrypted scripts are read from the transaction store buckets and
// the address manager values are rewritten with these plaintext
// scripts. The now-unnecessary transaction store scripts are removed
// in the upgrade.
unencryptedRedeemScriptsVersion = 14
// blockcf2Version is the 15th version of the databse. This upgrade
// drops the existing cfilter bucket and recreates it, triggering a
// re-download of missing cfilters. This is intended to switch the
// wallet to using the new, consensus-enforced version 2 committed
// filters.
blockcf2Version = 15
// perTicketVotingPreferencesVersion is the 16th version of the database.
// It creates a top-level ticketsagendaprefs bucket for storing voting
// preferences for individual tickets.
perTicketVotingPreferencesVersion = 16
// accountVariablesVersion is the 17th version of the database. It adds
// a bucket for each account which records individual key/value pairs
// for account metadata which can change over time (such as account
// names, last used child indexes, etc). This is more efficient than
// reserializing all account metadata into a single field when only some
// fields changed.
accountVariablesVersion = 17
// unpublishedTxsVersion is the 18th version of the database. It
// adds a bucket for recording unmined transactions which have not yet
// been published to the network, but still recording them to the
// database and not considering spent previous outputs to be UTXOs
// unless the transaction is abandoned.
unpublishedTxsVersion = 18
// tspendPolicyVersion is the 19th version of the database. It adds a
// top-level bucket for recording voting policy on treasury-spending
// transactions.
tspendPolicyVersion = 19
// vspBucketVersion is the 20th version of the database. It adds a
// a top-level bucket for recording vsp ticket hashes as key and its
// related fee txs hash.
vspBucketVersion = 20
// vspStatusVersion is the 21st version of the database. It adds a
// status field to tracked vspd tickets.
vspStatusVersion = 21
// tspendHashPolicyVersion is the 22nd version of the database. It adds a
// top-level bucket for recording voting policy on treasury-spending
// transactions by transaction hash, rather than by pi key.
tspendHashPolicyVersion = 22
// vspHostVersion is the 23nd version of the database. It adds a
// vsp host ane vsp pubkey buckets to the db.
vspHostVersion = 23
// vspTreasuryPoliciesVersion is the 24th version of the database. It
// adds top-level buckets for recording the voting policies
// treasury-spending transactions for specific customer's tickets served
// by a VSP.
vspTreasuryPoliciesVersion = 24
// importVotingAccount is the 25th version of the database. This version
// indicates that importing a new account type has been enabled. This
// account facilitates voting using a special account where the private
// key from indexes of the internal branch are shared with a vsp. The
// new type is not recognized by previous wallet versions. This version
// only updates the db version number so that previous versions will
// error on startup.
importVotingAccountVersion = 25
// DBVersion is the latest version of the database that is understood by the
// program. Databases with recorded versions higher than this will fail to
// open (meaning any upgrades prevent reverting to older software).
DBVersion = importVotingAccountVersion
)
// upgrades maps between old database versions and the upgrade function to
// upgrade the database to the next version. Note that there was never a
// version zero so upgrades[0] is nil.
var upgrades = [...]func(walletdb.ReadWriteTx, []byte, *chaincfg.Params) error{
lastUsedAddressIndexVersion - 1: lastUsedAddressIndexUpgrade,
votingPreferencesVersion - 1: votingPreferencesUpgrade,
noEncryptedSeedVersion - 1: noEncryptedSeedUpgrade,
lastReturnedAddressVersion - 1: lastReturnedAddressUpgrade,
ticketBucketVersion - 1: ticketBucketUpgrade,
slip0044CoinTypeVersion - 1: slip0044CoinTypeUpgrade,
hasExpiryVersion - 1: hasExpiryUpgrade,
hasExpiryFixedVersion - 1: hasExpiryFixedUpgrade,
cfVersion - 1: cfUpgrade,
lastProcessedTxsBlockVersion - 1: lastProcessedTxsBlockUpgrade,
ticketCommitmentsVersion - 1: ticketCommitmentsUpgrade,
importedXpubAccountVersion - 1: importedXpubAccountUpgrade,
unencryptedRedeemScriptsVersion - 1: unencryptedRedeemScriptsUpgrade,
blockcf2Version - 1: blockcf2Upgrade,
perTicketVotingPreferencesVersion - 1: perTicketVotingPreferencesUpgrade,
accountVariablesVersion - 1: accountVariablesUpgrade,
unpublishedTxsVersion - 1: unpublishedTxsUpgrade,
tspendPolicyVersion - 1: tspendPolicyUpgrade,
vspBucketVersion - 1: vspBucketUpgrade,
vspStatusVersion - 1: vspStatusUpgrade,
tspendHashPolicyVersion - 1: tspendHashPolicyUpgrade,
vspHostVersion - 1: vspHostVersionUpgrade,
vspTreasuryPoliciesVersion - 1: vspTreasuryPoliciesUpgrade,
importVotingAccountVersion - 1: importVotingAccountUpgrade,
}
func lastUsedAddressIndexUpgrade(tx walletdb.ReadWriteTx, publicPassphrase []byte, params *chaincfg.Params) error {
const oldVersion = 1
const newVersion = 2
metadataBucket := tx.ReadWriteBucket(unifiedDBMetadata{}.rootBucketKey())
addrmgrBucket := tx.ReadWriteBucket(waddrmgrBucketKey)
addressBucket := addrmgrBucket.NestedReadBucket(addrBucketName)
usedAddrBucket := addrmgrBucket.NestedReadBucket(usedAddrBucketName)
addressKey := func(hash160 []byte) []byte {
sha := sha256.Sum256(hash160)
return sha[:]
}
// Assert that this function is only called on version 1 databases.
dbVersion, err := unifiedDBMetadata{}.getVersion(metadataBucket)
if err != nil {
return err
}
if dbVersion != oldVersion {
return errors.E(errors.Invalid, "lastUsedAddressIndexUpgrade inappropriately called")
}
masterKeyPubParams, _, err := fetchMasterKeyParams(addrmgrBucket)
if err != nil {
return err
}
var masterKeyPub snacl.SecretKey
err = masterKeyPub.Unmarshal(masterKeyPubParams)
if err != nil {
return errors.E(errors.IO, errors.Errorf("unmarshal master pubkey params: %v", err))
}
err = masterKeyPub.DeriveKey(&publicPassphrase)
if err != nil {
return errors.E(errors.Passphrase, "incorrect public passphrase")
}
cryptoPubKeyEnc, _, err := fetchCryptoKeys(addrmgrBucket)
if err != nil {
return err
}
cryptoPubKeyCT, err := masterKeyPub.Decrypt(cryptoPubKeyEnc)
if err != nil {
return errors.E(errors.Crypto, errors.Errorf("decrypt public crypto key: %v", err))
}
cryptoPubKey := &cryptoKey{snacl.CryptoKey{}}
copy(cryptoPubKey.CryptoKey[:], cryptoPubKeyCT)
// Determine how many BIP0044 accounts have been created. Each of these
// accounts must be updated.
lastAccount, err := fetchLastAccount(addrmgrBucket)
if err != nil {
return err
}
// Perform account updates on all BIP0044 accounts created thus far.
for account := uint32(0); account <= lastAccount; account++ {
// Load the old account info.
row, err := fetchAccountInfo(addrmgrBucket, account, oldVersion)
if err != nil {
return err
}
// Use the crypto public key to decrypt the account public extended key
// and each branch key.
serializedKeyPub, err := cryptoPubKey.Decrypt(row.pubKeyEncrypted)
if err != nil {
return errors.E(errors.Crypto, errors.Errorf("decrypt extended pubkey: %v", err))
}
xpub, err := hdkeychain.NewKeyFromString(string(serializedKeyPub), params)
if err != nil {
return errors.E(errors.IO, err)
}
xpubExtBranch, err := xpub.Child(ExternalBranch)
if err != nil {
return err
}
xpubIntBranch, err := xpub.Child(InternalBranch)
if err != nil {
return err
}
// Determine the last used internal and external address indexes. The
// sentinel value ^uint32(0) means that there has been no usage at all.
lastUsedExtIndex := ^uint32(0)
lastUsedIntIndex := ^uint32(0)
for child := uint32(0); child < hdkeychain.HardenedKeyStart; child++ {
xpubChild, err := xpubExtBranch.Child(child)
if errors.Is(err, hdkeychain.ErrInvalidChild) {
continue
}
if err != nil {
return err
}
// This can't error because the function always passes good input to
// dcrutil.NewAddressPubKeyHash. Also, while it looks like a
// mistake to hardcode the mainnet parameters here, it doesn't make
// any difference since only the pubkey hash is used. (Why is there
// no exported method to just return the serialized public key?)
addr, _ := compat.HD2Address(xpubChild, params)
if addressBucket.Get(addressKey(addr.Hash160()[:])) == nil {
// No more recorded addresses for this account.
break
}
if usedAddrBucket.Get(addressKey(addr.Hash160()[:])) != nil {
lastUsedExtIndex = child
}
}
for child := uint32(0); child < hdkeychain.HardenedKeyStart; child++ {
// Same as above but search the internal branch.
xpubChild, err := xpubIntBranch.Child(child)
if errors.Is(err, hdkeychain.ErrInvalidChild) {
continue
}
if err != nil {
return err
}
addr, _ := compat.HD2Address(xpubChild, params)
if addressBucket.Get(addressKey(addr.Hash160()[:])) == nil {
break
}
if usedAddrBucket.Get(addressKey(addr.Hash160()[:])) != nil {
lastUsedIntIndex = child
}
}
// Convert account row values to the new serialization format that
// replaces the next to use indexes with the last used indexes.
row = bip0044AccountInfo(row.pubKeyEncrypted, row.privKeyEncrypted,
0, 0, lastUsedExtIndex, lastUsedIntIndex, 0, 0, row.name, newVersion)
err = putBIP0044AccountInfo(addrmgrBucket, account, row)
if err != nil {
return err
}
// Remove all data saved for address pool handling.
addrmgrMetaBucket := addrmgrBucket.NestedReadWriteBucket(metaBucketName)
err = addrmgrMetaBucket.Delete(accountNumberToAddrPoolKey(false, account))
if err != nil {
return err
}
err = addrmgrMetaBucket.Delete(accountNumberToAddrPoolKey(true, account))
if err != nil {
return err
}
}
// Remove the used address tracking bucket.
err = addrmgrBucket.DeleteNestedBucket(usedAddrBucketName)
if err != nil {
return errors.E(errors.IO, err)
}
// Write the new database version.
return unifiedDBMetadata{}.putVersion(metadataBucket, newVersion)
}
func votingPreferencesUpgrade(tx walletdb.ReadWriteTx, publicPassphrase []byte, params *chaincfg.Params) error {
const oldVersion = 2
const newVersion = 3
metadataBucket := tx.ReadWriteBucket(unifiedDBMetadata{}.rootBucketKey())
stakemgrBucket := tx.ReadWriteBucket(wstakemgrBucketKey)
ticketPurchasesBucket := stakemgrBucket.NestedReadWriteBucket(sstxRecordsBucketName)
// Assert that this function is only called on version 2 databases.
dbVersion, err := unifiedDBMetadata{}.getVersion(metadataBucket)
if err != nil {
return err
}
if dbVersion != oldVersion {
return errors.E(errors.Invalid, "votingPreferencesUpgrade inappropriately called")
}
// Update every ticket purchase with the new database version. This removes
// all per-ticket vote bits.
ticketPurchases := make(map[chainhash.Hash]*sstxRecord)
c := ticketPurchasesBucket.ReadCursor()
defer c.Close()
for k, _ := c.First(); k != nil; k, _ = c.Next() {
var hash chainhash.Hash
copy(hash[:], k)
ticketPurchase, err := fetchSStxRecord(stakemgrBucket, &hash, oldVersion)
if err != nil {
return err
}
ticketPurchases[hash] = ticketPurchase
}
for _, ticketPurchase := range ticketPurchases {
err := putSStxRecord(stakemgrBucket, ticketPurchase, newVersion)
if err != nil {
return err
}
}
// Create the top level bucket for agenda preferences.
_, err = tx.CreateTopLevelBucket(agendaPreferences.defaultBucketKey())
if err != nil {
return err
}
// Write the new database version.
return unifiedDBMetadata{}.putVersion(metadataBucket, newVersion)
}
func noEncryptedSeedUpgrade(tx walletdb.ReadWriteTx, publicPassphrase []byte, params *chaincfg.Params) error {
const oldVersion = 3
const newVersion = 4
metadataBucket := tx.ReadWriteBucket(unifiedDBMetadata{}.rootBucketKey())
addrmgrBucket := tx.ReadWriteBucket(waddrmgrBucketKey)
mainBucket := addrmgrBucket.NestedReadWriteBucket(mainBucketName)
// Assert that this function is only called on version 3 databases.
dbVersion, err := unifiedDBMetadata{}.getVersion(metadataBucket)
if err != nil {
return err
}
if dbVersion != oldVersion {
return errors.E(errors.Invalid, "noEncryptedSeedUpgrade inappropriately called")
}
// Remove encrypted seed (or encrypted zeros).
err = mainBucket.Delete(seedName)
if err != nil {
return err
}
// Write the new database version.
return unifiedDBMetadata{}.putVersion(metadataBucket, newVersion)
}
func lastReturnedAddressUpgrade(tx walletdb.ReadWriteTx, publicPassphrase []byte, params *chaincfg.Params) error {
const oldVersion = 4
const newVersion = 5
metadataBucket := tx.ReadWriteBucket(unifiedDBMetadata{}.rootBucketKey())
addrmgrBucket := tx.ReadWriteBucket(waddrmgrBucketKey)
// Assert that this function is only called on version 4 databases.
dbVersion, err := unifiedDBMetadata{}.getVersion(metadataBucket)
if err != nil {
return err
}
if dbVersion != oldVersion {
return errors.E(errors.Invalid, "accountAddressCursorsUpgrade inappropriately called")
}
upgradeAcct := func(account uint32) error {
// Load the old account info.
row, err := fetchAccountInfo(addrmgrBucket, account, oldVersion)
if err != nil {
return err
}
// Convert account row values to the new serialization format that adds
// the last returned indexes. Assume that the last used address is also
// the last returned address.
row = bip0044AccountInfo(row.pubKeyEncrypted, row.privKeyEncrypted,
0, 0, row.lastUsedExternalIndex, row.lastUsedInternalIndex,
row.lastUsedExternalIndex, row.lastUsedInternalIndex,
row.name, newVersion)
return putBIP0044AccountInfo(addrmgrBucket, account, row)
}
// Determine how many BIP0044 accounts have been created. Each of these
// accounts must be updated.
lastAccount, err := fetchLastAccount(addrmgrBucket)
if err != nil {
return err
}
// Perform account updates on all BIP0044 accounts created thus far.
for account := uint32(0); account <= lastAccount; account++ {
err := upgradeAcct(account)
if err != nil {
return err
}
}
// Perform upgrade on the imported account, which is also using the BIP0044
// row serialization. The last used and last returned indexes are not used
// by the imported account but the row must be upgraded regardless to avoid
// deserialization errors due to the row value length checks.
err = upgradeAcct(ImportedAddrAccount)
if err != nil {
return err
}
// Write the new database version.
return unifiedDBMetadata{}.putVersion(metadataBucket, newVersion)
}
func ticketBucketUpgrade(tx walletdb.ReadWriteTx, publicPassphrase []byte, params *chaincfg.Params) error {
const oldVersion = 5
const newVersion = 6
metadataBucket := tx.ReadWriteBucket(unifiedDBMetadata{}.rootBucketKey())
txmgrBucket := tx.ReadWriteBucket(wtxmgrBucketKey)
// Assert that this function is only called on version 5 databases.
dbVersion, err := unifiedDBMetadata{}.getVersion(metadataBucket)
if err != nil {
return err
}
if dbVersion != oldVersion {
return errors.E(errors.Invalid, "ticketBucketUpgrade inappropriately called")
}
// Create the tickets bucket.
_, err = txmgrBucket.CreateBucket(bucketTickets)
if err != nil {
return err
}
// Add an entry in the tickets bucket for every mined and unmined ticket
// purchase transaction. Use -1 as the selected height since this value is
// unknown at this time and the field is not yet being used.
ticketHashes := make(map[chainhash.Hash]struct{})
c := txmgrBucket.NestedReadBucket(bucketTxRecords).ReadCursor()
for k, v := c.First(); v != nil; k, v = c.Next() {
var hash chainhash.Hash
err := readRawTxRecordHash(k, &hash)
if err != nil {
c.Close()
return err
}
var rec TxRecord
err = readRawTxRecord(&hash, v, &rec)
if err != nil {
c.Close()
return err
}
if stake.IsSStx(&rec.MsgTx) {
ticketHashes[hash] = struct{}{}
}
}
c.Close()
c = txmgrBucket.NestedReadBucket(bucketUnmined).ReadCursor()
for k, v := c.First(); v != nil; k, v = c.Next() {
var hash chainhash.Hash
err := readRawUnminedHash(k, &hash)
if err != nil {
c.Close()
return err
}
var rec TxRecord
err = readRawTxRecord(&hash, v, &rec)
if err != nil {
c.Close()
return err
}
if stake.IsSStx(&rec.MsgTx) {
ticketHashes[hash] = struct{}{}
}
}
c.Close()
for ticketHash := range ticketHashes {
err := putTicketRecord(txmgrBucket, &ticketHash, -1)
if err != nil {
return err
}
}
// Remove previous stakebase input from the unmined inputs bucket, if any
// was recorded.
stakebaseOutpoint := canonicalOutPoint(&chainhash.Hash{}, ^uint32(0))
err = txmgrBucket.NestedReadWriteBucket(bucketUnminedInputs).Delete(stakebaseOutpoint)
if err != nil {
return err
}
// Write the new database version.
return unifiedDBMetadata{}.putVersion(metadataBucket, newVersion)
}
func slip0044CoinTypeUpgrade(tx walletdb.ReadWriteTx, publicPassphrase []byte, params *chaincfg.Params) error {
const oldVersion = 6
const newVersion = 7
metadataBucket := tx.ReadWriteBucket(unifiedDBMetadata{}.rootBucketKey())
// Assert that this function is only called on version 6 databases.
dbVersion, err := unifiedDBMetadata{}.getVersion(metadataBucket)
if err != nil {
return err
}
if dbVersion != oldVersion {
return errors.E(errors.Invalid, "slip0044CoinTypeUpgrade inappropriately called")
}
// Write the new database version.
return unifiedDBMetadata{}.putVersion(metadataBucket, newVersion)
}
func hasExpiryUpgrade(tx walletdb.ReadWriteTx, publicPassphrase []byte, params *chaincfg.Params) error {
const oldVersion = 7
const newVersion = 8
metadataBucket := tx.ReadWriteBucket(unifiedDBMetadata{}.rootBucketKey())
txmgrBucket := tx.ReadWriteBucket(wtxmgrBucketKey)
// Assert that this function is only called on version 7 databases.
dbVersion, err := unifiedDBMetadata{}.getVersion(metadataBucket)
if err != nil {
return err
}
if dbVersion != oldVersion {
return errors.E(errors.Invalid, "hasExpiryUpgrade inappropriately called")
}
// Iterate through all mined credits
creditsBucket := txmgrBucket.NestedReadWriteBucket(bucketCredits)
cursor := creditsBucket.ReadWriteCursor()
creditsKV := map[string][]byte{}
for k, v := cursor.First(); v != nil; k, v = cursor.Next() {
hash := extractRawCreditTxHash(k)
block, err := fetchBlockRecord(txmgrBucket, extractRawCreditHeight(k))
if err != nil {
cursor.Close()
return err
}
_, recV := existsTxRecord(txmgrBucket, &hash, &block.Block)
record := &TxRecord{}
err = readRawTxRecord(&hash, recV, record)
if err != nil {
cursor.Close()
return err
}
// Only save credits that need their hasExpiry flag updated
if record.MsgTx.Expiry != wire.NoExpiryValue {
vCpy := make([]byte, len(v))
copy(vCpy, v)
vCpy[8] |= 1 << 4
creditsKV[string(k)] = vCpy
}
}
cursor.Close()
for k, v := range creditsKV {
err = creditsBucket.Put([]byte(k), v)
if err != nil {
return err
}
}
// Iterate through all unmined credits
unminedCreditsBucket := txmgrBucket.NestedReadWriteBucket(bucketUnminedCredits)
unminedCursor := unminedCreditsBucket.ReadWriteCursor()
unminedCreditsKV := map[string][]byte{}
for k, v := unminedCursor.First(); v != nil; k, v = unminedCursor.Next() {
hash, err := chainhash.NewHash(extractRawUnminedCreditTxHash(k))
if err != nil {
unminedCursor.Close()
return err
}
recV := existsRawUnmined(txmgrBucket, hash[:])
record := &TxRecord{}
err = readRawTxRecord(hash, recV, record)
if err != nil {
unminedCursor.Close()
return err
}
// Only save credits that need their hasExpiry flag updated
if record.MsgTx.Expiry != wire.NoExpiryValue {
vCpy := make([]byte, len(v))
copy(vCpy, v)
vCpy[8] |= 1 << 4
unminedCreditsKV[string(k)] = vCpy
}
}
unminedCursor.Close()
for k, v := range unminedCreditsKV {
err = unminedCreditsBucket.Put([]byte(k), v)
if err != nil {
return err
}
}
// Write the new database version.
return unifiedDBMetadata{}.putVersion(metadataBucket, newVersion)
}
func hasExpiryFixedUpgrade(tx walletdb.ReadWriteTx, publicPassphrase []byte, params *chaincfg.Params) error {
const oldVersion = 8
const newVersion = 9
metadataBucket := tx.ReadWriteBucket(unifiedDBMetadata{}.rootBucketKey())
txmgrBucket := tx.ReadWriteBucket(wtxmgrBucketKey)
// Assert this function is only called on version 8 databases.
dbVersion, err := unifiedDBMetadata{}.getVersion(metadataBucket)
if err != nil {
return err
}
if dbVersion != oldVersion {
return errors.E(errors.Invalid, "hasExpiryFixedUpgrade inappropriately called")
}
// Iterate through all mined credits
creditsBucket := txmgrBucket.NestedReadWriteBucket(bucketCredits)
cursor := creditsBucket.ReadCursor()
creditsKV := map[string][]byte{}
for k, v := cursor.First(); v != nil; k, v = cursor.Next() {
hash := extractRawCreditTxHash(k)
block, err := fetchBlockRecord(txmgrBucket, extractRawCreditHeight(k))
if err != nil {
cursor.Close()
return err
}
_, recV := existsTxRecord(txmgrBucket, &hash, &block.Block)
record := &TxRecord{}
err = readRawTxRecord(&hash, recV, record)
if err != nil {
cursor.Close()
return err
}
// Only save credits that need their hasExpiry flag updated
if record.MsgTx.Expiry != wire.NoExpiryValue {
vCpy := make([]byte, len(v))
copy(vCpy, v)
vCpy[8] &^= 1 << 4 // Clear bad hasExpiry/OP_SSTXCHANGE flag
vCpy[8] |= 1 << 6 // Set correct hasExpiry flag
// Reset OP_SSTXCHANGE flag if this is a ticket purchase
// OP_SSTXCHANGE output.
out := record.MsgTx.TxOut[extractRawCreditIndex(k)]
if stake.IsSStx(&record.MsgTx) &&
(stdscript.IsStakeChangePubKeyHashScript(out.Version, out.PkScript) ||
stdscript.IsStakeChangeScriptHashScript(out.Version, out.PkScript)) {
vCpy[8] |= 1 << 4
}
creditsKV[string(k)] = vCpy
}
}
cursor.Close()
for k, v := range creditsKV {
err = creditsBucket.Put([]byte(k), v)
if err != nil {
return err
}
}
// Iterate through all unmined credits
unminedCreditsBucket := txmgrBucket.NestedReadWriteBucket(bucketUnminedCredits)
unminedCursor := unminedCreditsBucket.ReadCursor()
unminedCreditsKV := map[string][]byte{}
for k, v := unminedCursor.First(); v != nil; k, v = unminedCursor.Next() {
hash, err := chainhash.NewHash(extractRawUnminedCreditTxHash(k))
if err != nil {
unminedCursor.Close()
return err
}
recV := existsRawUnmined(txmgrBucket, hash[:])
record := &TxRecord{}
err = readRawTxRecord(hash, recV, record)
if err != nil {
unminedCursor.Close()
return err
}
// Only save credits that need their hasExpiry flag updated
if record.MsgTx.Expiry != wire.NoExpiryValue {
vCpy := make([]byte, len(v))
copy(vCpy, v)
vCpy[8] &^= 1 << 4 // Clear bad hasExpiry/OP_SSTXCHANGE flag
vCpy[8] |= 1 << 6 // Set correct hasExpiry flag
// Reset OP_SSTXCHANGE flag if this is a ticket purchase
// OP_SSTXCHANGE output.
idx, err := fetchRawUnminedCreditIndex(k)
if err != nil {
unminedCursor.Close()
return err
}
out := record.MsgTx.TxOut[idx]
if stake.IsSStx(&record.MsgTx) &&
(stdscript.IsStakeChangePubKeyHashScript(out.Version, out.PkScript) ||
stdscript.IsStakeChangeScriptHashScript(out.Version, out.PkScript)) {
vCpy[8] |= 1 << 4
}
unminedCreditsKV[string(k)] = vCpy
}
}
unminedCursor.Close()
for k, v := range unminedCreditsKV {
err = unminedCreditsBucket.Put([]byte(k), v)
if err != nil {
return err
}
}
return unifiedDBMetadata{}.putVersion(metadataBucket, newVersion)
}
func cfUpgrade(tx walletdb.ReadWriteTx, publicPassphrase []byte, params *chaincfg.Params) error {
const oldVersion = 9
const newVersion = 10
metadataBucket := tx.ReadWriteBucket(unifiedDBMetadata{}.rootBucketKey())
txmgrBucket := tx.ReadWriteBucket(wtxmgrBucketKey)
// Assert that this function is only called on version 9 databases.
dbVersion, err := unifiedDBMetadata{}.getVersion(metadataBucket)
if err != nil {
return err
}
if dbVersion != oldVersion {
return errors.E(errors.Invalid, "cfUpgrade inappropriately called")
}
err = txmgrBucket.Put(rootHaveCFilters, []byte{0})
if err != nil {
return errors.E(errors.IO, err)
}
_, err = txmgrBucket.CreateBucket(bucketCFilters)
if err != nil {
return errors.E(errors.IO, err)
}
// Record cfilter for genesis block.
//
// Note: This used to record the actual version 1 cfilter for the
// genesis block, but this was changed as packages were updated.
// Version 1 cfilters can no longer be created using the latest major
// version of the gcs module. Plus, version 1 cfilters are removed in a
// later database upgrade, because only version 2 cfilters are used now.
// So instead, this upgrade path has been modified to record nil bytes
// for this genesis block v1 cfilter.
err = putRawCFilter(txmgrBucket, params.GenesisHash[:], nil)
if err != nil {
return errors.E(errors.IO, err)
}
// Record all cfilters as saved when only the genesis block is saved.
var tipHash chainhash.Hash
copy(tipHash[:], txmgrBucket.Get(rootTipBlock))
if tipHash == params.GenesisHash {
err = txmgrBucket.Put(rootHaveCFilters, []byte{1})
if err != nil {
return errors.E(errors.IO, err)
}
}
// Write the new database version.
return unifiedDBMetadata{}.putVersion(metadataBucket, newVersion)
}
func lastProcessedTxsBlockUpgrade(tx walletdb.ReadWriteTx, publicPassphrase []byte, params *chaincfg.Params) error {
const oldVersion = 10
const newVersion = 11
metadataBucket := tx.ReadWriteBucket(unifiedDBMetadata{}.rootBucketKey())
txmgrBucket := tx.ReadWriteBucket(wtxmgrBucketKey)
// Assert that this function is only called on version 10 databases.
dbVersion, err := unifiedDBMetadata{}.getVersion(metadataBucket)
if err != nil {
return err
}
if dbVersion != oldVersion {
return errors.E(errors.Invalid, "lastProcessedTxsBlockUpgrade inappropriately called")
}
// Record the current tip block as the last block since genesis with
// processed transaction.
err = txmgrBucket.Put(rootLastTxsBlock, txmgrBucket.Get(rootTipBlock))
if err != nil {
return errors.E(errors.IO, err)
}
// Write the new database version.
return unifiedDBMetadata{}.putVersion(metadataBucket, newVersion)
}
func ticketCommitmentsUpgrade(tx walletdb.ReadWriteTx, publicPassphrase []byte, params *chaincfg.Params) error {
const oldVersion = 11
const newVersion = 12
metadataBucket := tx.ReadWriteBucket(unifiedDBMetadata{}.rootBucketKey())
txmgrBucket := tx.ReadWriteBucket(wtxmgrBucketKey)
addrmgrBucket := tx.ReadWriteBucket(waddrmgrBucketKey)
// Assert that this function is only called on version 11 databases.
dbVersion, err := unifiedDBMetadata{}.getVersion(metadataBucket)
if err != nil {
return err
}
if dbVersion != oldVersion {
return errors.E(errors.Invalid, "ticketCommitmentsUpgrade inappropriately called")
}
_, err = txmgrBucket.CreateBucket(bucketTicketCommitments)
if err != nil {
return errors.E(errors.IO, err)
}
_, err = txmgrBucket.CreateBucket(bucketTicketCommitmentsUsp)
if err != nil {
return errors.E(errors.IO, err)
}
// Helper function to handle the details of a single (mined or unmined)
// transaction.
handleTxRecCommitments := func(txrec *TxRecord, unmined bool) error {
for i, txo := range txrec.MsgTx.TxOut {
if txrec.TxType == stake.TxTypeSStx {
if i%2 != 1 {
// Ignore non ticket commitment outputs.
continue
}
// Decode the address stored in the commitment.
addr, err := stake.AddrFromSStxPkScrCommitment(txo.PkScript, params)
if err != nil {
return errors.E(errors.IO, err)
}
id, err := addressID(normalizeAddress(addr))
if err != nil {
return errors.E(errors.Bug, err)
}
acct, err := fetchAddrAccount(addrmgrBucket, id)
if err != nil && errors.Is(err, errors.NotExist) {
// If this address does not have an account associated
// with it, it means it's not owned by the wallet.
continue
} else if err != nil {
return errors.E(errors.IO, err)
}
// Decode the amount stored in the commitment.
amount, err := stake.AmountFromSStxPkScrCommitment(txo.PkScript)
if err != nil {
return errors.E(errors.IO, err)
}
log.Debugf("Adding ticket commitment %s:%d (%s) for account %d",
txrec.Hash, i, amount, acct)
// Store both the ticket commitment info and an entry in the
// unspent index.
k := keyTicketCommitment(txrec.Hash, uint32(i))
v := valueTicketCommitment(amount, acct)
err = putRawTicketCommitment(txmgrBucket, k, v)
if err != nil {
return errors.E(errors.IO, err)