forked from zcash/zcash
-
Notifications
You must be signed in to change notification settings - Fork 18
/
wallet.cpp
8224 lines (7255 loc) · 316 KB
/
wallet.cpp
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) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Copyright (c) 2016-2023 The Zcash developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or https://www.opensource.org/licenses/mit-license.php .
#include "wallet/wallet.h"
#include "asyncrpcqueue.h"
#include "checkpoints.h"
#include "coincontrol.h"
#include "core_io.h"
#include "consensus/upgrades.h"
#include "consensus/validation.h"
#include "consensus/consensus.h"
#include "fs.h"
#include "init.h"
#include "key_io.h"
#include "main.h"
#include "net.h"
#include "policy/policy.h"
#include "random.h"
#include "rpc/protocol.h"
#include "rpc/server.h"
#include "script/script.h"
#include "script/sign.h"
#include "timedata.h"
#include "util/moneystr.h"
#include "util/match.h"
#include "zcash/Address.hpp"
#include "zcash/JoinSplit.hpp"
#include "zcash/Note.hpp"
#include "crypter.h"
#include "wallet/asyncrpcoperation_saplingmigration.h"
#include <algorithm>
#include <assert.h>
#include <numeric>
#include <variant>
#include <boost/algorithm/string/replace.hpp>
#include <boost/thread.hpp>
using namespace std;
using namespace libzcash;
CWallet* pwalletMain = NULL;
/** Transaction fee set by the user */
CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
bool bSpendZeroConfChange = DEFAULT_SPEND_ZEROCONF_CHANGE;
bool fSendFreeTransactions = DEFAULT_SEND_FREE_TRANSACTIONS;
bool fPayAtLeastCustomFee = true;
unsigned int nAnchorConfirmations = DEFAULT_ANCHOR_CONFIRMATIONS;
unsigned int nOrchardActionLimit = DEFAULT_ORCHARD_ACTION_LIMIT;
const char * DEFAULT_WALLET_DAT = "wallet.dat";
/**
* Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
* Override with -mintxfee
*/
CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
std::set<ReceiverType> CWallet::DefaultReceiverTypes(int nHeight) {
// For now, just ignore the height information because the default
// is always the same.
return {ReceiverType::P2PKH, ReceiverType::Sapling, ReceiverType::Orchard};
}
/** @defgroup mapWallet
*
* @{
*/
struct CompareValueOnly
{
bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
{
return t1.first < t2.first;
}
};
std::string JSOutPoint::ToString() const
{
return strprintf("JSOutPoint(%s, %d, %d)", hash.ToString().substr(0,10), js, n);
}
std::string COutput::ToString() const
{
return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
}
const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
if (it == mapWallet.end())
return NULL;
return &(it->second);
}
// Generate a new spending key and return its public payment address
libzcash::SproutPaymentAddress CWallet::GenerateNewSproutZKey()
{
AssertLockHeld(cs_wallet); // mapSproutZKeyMetadata
auto k = SproutSpendingKey::random();
auto addr = k.address();
// Check for collision, even though it is unlikely to ever occur
if (CCryptoKeyStore::HaveSproutSpendingKey(addr))
throw std::runtime_error("CWallet::GenerateNewSproutZKey(): Collision detected");
// Create new metadata
int64_t nCreationTime = GetTime();
mapSproutZKeyMetadata[addr] = CKeyMetadata(nCreationTime);
if (!AddSproutZKey(k))
throw std::runtime_error("CWallet::GenerateNewSproutZKey(): AddSproutZKey failed");
return addr;
}
// Generates a new Sapling spending key as a child of the legacy Sapling account,
// and returns its public payment address.
//
// The z_getnewaddress API must use the mnemonic HD seed, and fail if that seed
// is not present. The account index is determined by trial of values of
// mnemonicHDChain.GetLegacySaplingKeyCounter() until one is found that produces
// a valid Sapling key.
SaplingPaymentAddress CWallet::GenerateNewLegacySaplingZKey() {
AssertLockHeld(cs_wallet);
if (!mnemonicHDChain.has_value()) {
throw std::runtime_error(
"CWallet::GenerateNewLegacySaplingZKey(): Wallet is missing mnemonic seed metadata.");
}
CHDChain& hdChain = mnemonicHDChain.value();
// loop until we find an unused address index
while (true) {
auto generated = GenerateLegacySaplingZKey(hdChain.GetLegacySaplingKeyCounter());
// advance the address index counter so that the next time we need to generate
// a key we're pointing at a free index.
hdChain.IncrementLegacySaplingKeyCounter();
if (!generated.second) {
// the key already existed, so try the next one
continue;
} else {
// Update the persisted chain information
if (fFileBacked && !CWalletDB(strWalletFile).WriteMnemonicHDChain(hdChain)) {
throw std::runtime_error(
"CWallet::GenerateNewLegacySaplingZKey(): Writing HD chain model failed");
}
return generated.first;
}
}
}
std::pair<SaplingPaymentAddress, bool> CWallet::GenerateLegacySaplingZKey(uint32_t addrIndex) {
auto seedOpt = GetMnemonicSeed();
if (!seedOpt.has_value()) {
throw std::runtime_error(
"CWallet::GenerateLegacySaplingZKey(): Wallet does not have a mnemonic seed.");
}
auto seed = seedOpt.value();
auto xsk = libzcash::SaplingExtendedSpendingKey::Legacy(seed, BIP44CoinType(), addrIndex);
auto extfvk = xsk.first.ToXFVK();
if (!HaveSaplingSpendingKey(extfvk)) {
auto ivk = extfvk.ToIncomingViewingKey();
CKeyMetadata keyMeta(GetTime());
keyMeta.hdKeypath = xsk.second;
keyMeta.seedFp = seed.Fingerprint();
mapSaplingZKeyMetadata[ivk] = keyMeta;
if (!AddSaplingZKey(xsk.first)) {
throw std::runtime_error("CWallet::GenerateLegacySaplingZKey(): AddSaplingZKey failed.");
}
auto addr = extfvk.DefaultAddress();
if (!AddSaplingPaymentAddress(ivk, addr)) {
throw std::runtime_error("CWallet::GenerateLegacySaplingZKey(): AddSaplingPaymentAddress failed.");
};
return std::make_pair(addr, true) ;
} else {
return std::make_pair(extfvk.DefaultAddress(), false);
}
}
// Add spending key to keystore
bool CWallet::AddSaplingZKey(const libzcash::SaplingExtendedSpendingKey &sk)
{
AssertLockHeld(cs_wallet); // mapSaplingZKeyMetadata
if (!CCryptoKeyStore::AddSaplingSpendingKey(sk)) {
return false;
}
if (!fFileBacked) {
return true;
}
if (!IsCrypted()) {
auto ivk = sk.expsk.full_viewing_key().in_viewing_key();
return CWalletDB(strWalletFile).WriteSaplingZKey(ivk, sk, mapSaplingZKeyMetadata[ivk]);
}
return true;
}
bool CWallet::AddSaplingFullViewingKey(const libzcash::SaplingExtendedFullViewingKey &extfvk)
{
AssertLockHeld(cs_wallet);
if (!CCryptoKeyStore::AddSaplingFullViewingKey(extfvk)) {
return false;
}
if (!fFileBacked) {
return true;
}
return CWalletDB(strWalletFile).WriteSaplingExtendedFullViewingKey(extfvk);
}
// Add payment address -> incoming viewing key map entry
bool CWallet::AddSaplingPaymentAddress(
const libzcash::SaplingIncomingViewingKey &ivk,
const libzcash::SaplingPaymentAddress &addr)
{
AssertLockHeld(cs_wallet); // mapSaplingZKeyMetadata
if (!CCryptoKeyStore::AddSaplingPaymentAddress(ivk, addr)) {
return false;
}
if (!fFileBacked) {
return true;
}
return CWalletDB(strWalletFile).WriteSaplingPaymentAddress(addr, ivk);
}
// Add spending key to keystore
bool CWallet::AddOrchardZKey(const libzcash::OrchardSpendingKey &sk)
{
AssertLockHeld(cs_wallet); // orchardWallet
if (IsCrypted()) {
// encrypted storage of Orchard spending keys is not supported
return false;
}
orchardWallet.AddSpendingKey(sk);
if (!fFileBacked) {
return true;
}
return true; // TODO ORCHARD: persist spending key
}
bool CWallet::AddOrchardFullViewingKey(const libzcash::OrchardFullViewingKey &fvk)
{
AssertLockHeld(cs_wallet); // orchardWallet
orchardWallet.AddFullViewingKey(fvk);
if (!fFileBacked) {
return true;
}
return true; // TODO ORCHARD: persist fvk
}
// Add Orchard payment address -> incoming viewing key map entry
bool CWallet::AddOrchardRawAddress(
const libzcash::OrchardIncomingViewingKey &ivk,
const libzcash::OrchardRawAddress &addr)
{
AssertLockHeld(cs_wallet); // orchardWallet
if (!orchardWallet.AddRawAddress(addr, ivk)) {
// We should never add an Orchard raw address for which we don't know
// the corresponding FVK.
return false;
};
if (!fFileBacked) {
return true;
}
return true; // TODO ORCHARD: ensure mapping will be recreated on wallet load
}
// Loads a payment address -> incoming viewing key map entry
// to the in-memory wallet's keystore.
bool CWallet::LoadOrchardRawAddress(
const libzcash::OrchardRawAddress &addr,
const libzcash::OrchardIncomingViewingKey &ivk)
{
AssertLockHeld(cs_wallet); // orchardWallet
return orchardWallet.AddRawAddress(addr, ivk);
}
// Returns a loader that can be used to read an Orchard note commitment
// tree from a stream into the Orchard wallet.
OrchardWalletNoteCommitmentTreeLoader CWallet::GetOrchardNoteCommitmentTreeLoader() {
return OrchardWalletNoteCommitmentTreeLoader(orchardWallet);
}
// Add spending key to keystore and persist to disk
bool CWallet::AddSproutZKey(const libzcash::SproutSpendingKey &key)
{
AssertLockHeld(cs_wallet); // mapSproutZKeyMetadata
auto addr = key.address();
if (!CCryptoKeyStore::AddSproutSpendingKey(key))
return false;
// check if we need to remove from viewing keys
if (HaveSproutViewingKey(addr))
RemoveSproutViewingKey(key.viewing_key());
if (!fFileBacked)
return true;
if (!IsCrypted()) {
return CWalletDB(strWalletFile).WriteZKey(addr, key, mapSproutZKeyMetadata[addr]);
}
return true;
}
CPubKey CWallet::GenerateNewKey(bool external)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
if (!mnemonicHDChain.has_value()) {
throw std::runtime_error(
"CWallet::GenerateNewKey(): Wallet is missing mnemonic seed metadata.");
}
CHDChain& hdChain = mnemonicHDChain.value();
transparent::AccountKey accountKey = this->GetLegacyAccountKey();
std::optional<CPubKey> pubkey = std::nullopt;
do {
auto index = hdChain.GetLegacyTKeyCounter(external);
auto key = external ?
accountKey.DeriveExternalSpendingKey(index) :
accountKey.DeriveInternalSpendingKey(index);
hdChain.IncrementLegacyTKeyCounter(external);
if (key.has_value()) {
pubkey = AddTransparentSecretKey(
hdChain.GetSeedFingerprint(),
key.value(),
transparent::AccountKey::KeyPath(BIP44CoinType(), ZCASH_LEGACY_ACCOUNT, external, index)
);
}
// if we did not successfully generate a key, try again.
} while (!pubkey.has_value());
// Update the persisted chain information
if (fFileBacked && !CWalletDB(strWalletFile).WriteMnemonicHDChain(hdChain)) {
throw std::runtime_error("CWallet::GenerateNewKey(): Writing HD chain model failed");
}
return pubkey.value();
}
CPubKey CWallet::AddTransparentSecretKey(
const uint256& seedFingerprint,
const CKey& secret,
const HDKeyPath& keyPath)
{
CPubKey pubkey = secret.GetPubKey();
assert(secret.VerifyPubKey(pubkey));
// Create new metadata
CKeyMetadata keyMeta(GetTime());
keyMeta.hdKeypath = keyPath;
keyMeta.seedFp = seedFingerprint;
mapKeyMetadata[pubkey.GetID()] = keyMeta;
if (nTimeFirstKey == 0 || keyMeta.nCreateTime < nTimeFirstKey)
nTimeFirstKey = keyMeta.nCreateTime;
if (!AddKeyPubKey(secret, pubkey))
throw std::runtime_error("CWallet::GenerateNewKey(): AddKeyPubKey failed");
return pubkey;
}
bool CWallet::AddKeyPubKey(
const CKey& secret,
const CPubKey &pubkey)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
return false;
// check if we need to remove from watch-only
CScript script;
script = GetScriptForDestination(pubkey.GetID());
if (HaveWatchOnly(script))
RemoveWatchOnly(script);
script = GetScriptForRawPubKey(pubkey);
if (HaveWatchOnly(script))
RemoveWatchOnly(script);
if (!fFileBacked)
return true;
if (!IsCrypted()) {
return CWalletDB(strWalletFile).WriteKey(pubkey,
secret.GetPrivKey(),
mapKeyMetadata[pubkey.GetID()]);
}
return true;
}
bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
const vector<unsigned char> &vchCryptedSecret)
{
if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
if (!fFileBacked)
return true;
{
LOCK(cs_wallet);
if (pwalletdbEncryption)
return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
vchCryptedSecret,
mapKeyMetadata[vchPubKey.GetID()]);
else
return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
vchCryptedSecret,
mapKeyMetadata[vchPubKey.GetID()]);
}
return false;
}
bool CWallet::AddCryptedSproutSpendingKey(
const libzcash::SproutPaymentAddress &address,
const libzcash::ReceivingKey &rk,
const std::vector<unsigned char> &vchCryptedSecret)
{
if (!CCryptoKeyStore::AddCryptedSproutSpendingKey(address, rk, vchCryptedSecret))
return false;
if (!fFileBacked)
return true;
{
LOCK(cs_wallet);
if (pwalletdbEncryption) {
return pwalletdbEncryption->WriteCryptedZKey(address,
rk,
vchCryptedSecret,
mapSproutZKeyMetadata[address]);
} else {
return CWalletDB(strWalletFile).WriteCryptedZKey(address,
rk,
vchCryptedSecret,
mapSproutZKeyMetadata[address]);
}
}
return false;
}
bool CWallet::AddCryptedSaplingSpendingKey(const libzcash::SaplingExtendedFullViewingKey &extfvk,
const std::vector<unsigned char> &vchCryptedSecret)
{
if (!CCryptoKeyStore::AddCryptedSaplingSpendingKey(extfvk, vchCryptedSecret))
return false;
if (!fFileBacked)
return true;
{
LOCK(cs_wallet);
if (pwalletdbEncryption) {
return pwalletdbEncryption->WriteCryptedSaplingZKey(extfvk,
vchCryptedSecret,
mapSaplingZKeyMetadata[extfvk.ToIncomingViewingKey()]);
} else {
return CWalletDB(strWalletFile).WriteCryptedSaplingZKey(extfvk,
vchCryptedSecret,
mapSaplingZKeyMetadata[extfvk.ToIncomingViewingKey()]);
}
}
return false;
}
libzcash::transparent::AccountKey CWallet::GetLegacyAccountKey() const {
auto seedOpt = GetMnemonicSeed();
if (!seedOpt.has_value()) {
throw std::runtime_error(
"CWallet::GenerateNewKey(): Wallet does not have a mnemonic seed.");
}
auto seed = seedOpt.value();
// All mnemonic seeds are checked at construction to ensure that we can obtain
// a valid spending key for the account ZCASH_LEGACY_ACCOUNT;
// therefore, the `value()` call here is safe.
return transparent::AccountKey::ForAccount(
seed,
BIP44CoinType(),
ZCASH_LEGACY_ACCOUNT).value();
}
std::pair<UnifiedFullViewingKey, libzcash::AccountId> CWallet::GenerateNewUnifiedSpendingKey() {
AssertLockHeld(cs_wallet);
if (!mnemonicHDChain.has_value()) {
throw std::runtime_error(
"CWallet::GenerateNewUnifiedSpendingKey(): Wallet is missing mnemonic seed metadata.");
}
CHDChain& hdChain = mnemonicHDChain.value();
while (true) {
auto accountId = hdChain.GetAccountCounter();
auto generated = GenerateUnifiedSpendingKeyForAccount(accountId);
auto account = hdChain.IncrementAccountCounter();
if (!account.has_value()) {
throw std::runtime_error(
"CWallet::GenerateNewUnifiedSpendingKey(): Already generated the maximum number of accounts (2^31 - 2) for this wallet's mnemonic phrase. Congratulations, you need to create a new wallet!");
}
if (generated.has_value()) {
// Update the persisted chain information
if (fFileBacked && !CWalletDB(strWalletFile).WriteMnemonicHDChain(hdChain)) {
throw std::runtime_error(
"CWallet::GenerateNewUnifiedSpendingKey(): Writing HD chain model failed");
}
return std::make_pair(generated.value().ToFullViewingKey(), accountId);
}
}
}
std::optional<libzcash::ZcashdUnifiedSpendingKey>
CWallet::GenerateUnifiedSpendingKeyForAccount(libzcash::AccountId accountId) {
AssertLockHeld(cs_wallet); // mapUnifiedAccountKeys
auto seed = GetMnemonicSeed();
if (!seed.has_value()) {
throw std::runtime_error(std::string(__func__) + ": Wallet has no mnemonic HD seed.");
}
auto usk = ZcashdUnifiedSpendingKey::ForAccount(seed.value(), BIP44CoinType(), accountId);
if (usk.has_value()) {
auto ufvk = usk.value().ToFullViewingKey();
auto ufvkid = ufvk.GetKeyID(Params());
ZcashdUnifiedAccountMetadata skmeta(seed.value().Fingerprint(), BIP44CoinType(), accountId, ufvkid);
// We don't store the spending key directly; instead, we store each of
// the spending key's components, in order to not violate invariants
// with respect to the encryption of the wallet. We store each
// component in the appropriate wallet subsystem, and store the
// metadata that can be used to re-derive the spending key along with
// the fingerprint of the associated full viewing key.
// Set up the bidirectional maps between the account ID and the UFVK ID.
auto metaKey = std::make_pair(skmeta.GetSeedFingerprint(), skmeta.GetAccountId());
const auto [it, is_new_key] = mapUnifiedAccountKeys.insert({metaKey, skmeta.GetKeyID()});
if (!is_new_key) {
// key was already present, so just return the USK.
return usk.value();
}
// We set up the UFVKAddressMetadata with the correct account ID (so we identify
// the UFVK as corresponding to this account) and empty receivers data (as we
// haven't generated any addresses yet). We don't need to persist this directly,
// because we persist skmeta below, and mapUfvkAddressMetadata is populated in
// LoadUnifiedAccountMetadata().
mapUfvkAddressMetadata.insert({ufvkid, UFVKAddressMetadata(accountId)});
// We do not explicitly add any transparent component to the keystore;
// the secret keys that we need to store are the child spending keys
// that are produced whenever we create a transparent address.
// Create the function that we'll use to add Sapling keys
// to the wallet.
auto addSaplingKey = AddSpendingKeyToWallet(
this, Params().GetConsensus(), GetTime(),
libzcash::Zip32AccountKeyPath(BIP44CoinType(), accountId),
skmeta.GetSeedFingerprint().GetHex(), true, false
);
// Add the Sapling spending key to the wallet
auto saplingEsk = usk.value().GetSaplingKey();
if (addSaplingKey(saplingEsk) == KeyNotAdded) {
// If adding the Sapling key to the wallet failed, abort the process.
throw std::runtime_error("CWalletDB::GenerateUnifiedSpendingKeyForAccount(): Unable to add Sapling spending key to the wallet.");
}
// Add the Sapling change spending key to the wallet
auto saplingChangeEsk = saplingEsk.DeriveInternalKey();
if (addSaplingKey(saplingChangeEsk) == KeyNotAdded) {
// If adding the Sapling change key to the wallet failed, abort the process.
throw std::runtime_error("CWalletDB::GenerateUnifiedSpendingKeyForAccount(): Unable to add Sapling change key to the wallet.");
}
// Associate the Sapling default change address with its IVK. We do this
// here because there is only ever a single Sapling change receiver, and
// it is never exposed to the user. External Sapling receivers are added
// when the user calls z_getaddressforaccount.
auto saplingXFVK = saplingEsk.ToXFVK();
if (!AddSaplingPaymentAddress(saplingXFVK.GetChangeIVK(), saplingXFVK.GetChangeAddress())) {
throw std::runtime_error("CWallet::GenerateUnifiedSpendingKeyForAccount(): Failed to add Sapling change address to the wallet.");
};
// Add Orchard spending key to the wallet
auto orchardSk = usk.value().GetOrchardKey();
orchardWallet.AddSpendingKey(orchardSk);
// Associate the Orchard default change address with its IVK. We do this
// here because there is only ever a single Orchard change receiver, and
// it is never exposed to the user. External Orchard receivers are added
// when the user calls z_getaddressforaccount.
auto orchardInternalFvk = orchardSk.ToFullViewingKey().ToInternalIncomingViewingKey();
if (!AddOrchardRawAddress(orchardInternalFvk, orchardInternalFvk.Address(0))) {
throw std::runtime_error("CWallet::GenerateUnifiedSpendingKeyForAccount(): Failed to add Orchard change address to the wallet.");
};
auto zufvk = ZcashdUnifiedFullViewingKey::FromUnifiedFullViewingKey(Params(), ufvk);
if (!CCryptoKeyStore::AddUnifiedFullViewingKey(zufvk)) {
throw std::runtime_error("CWalletDB::GenerateUnifiedSpendingKeyForAccount(): Failed to add UFVK to the keystore.");
}
if (fFileBacked) {
auto walletdb = CWalletDB(strWalletFile);
if (!( walletdb.WriteUnifiedFullViewingKey(ufvk) &&
walletdb.WriteUnifiedAccountMetadata(skmeta)
)) {
throw std::runtime_error("CWalletDB::GenerateUnifiedSpendingKeyForAccount(): walletdb write failed.");
}
}
return usk;
} else {
return std::nullopt;
}
}
bool CWallet::AddUnifiedFullViewingKey(const libzcash::UnifiedFullViewingKey &ufvk)
{
AssertLockHeld(cs_wallet);
auto zufvk = ZcashdUnifiedFullViewingKey::FromUnifiedFullViewingKey(Params(), ufvk);
auto keyId = ufvk.GetKeyID(Params());
if (!CCryptoKeyStore::AddUnifiedFullViewingKey(zufvk)) {
return false;
}
if (!fFileBacked) {
return true;
}
return CWalletDB(strWalletFile).WriteUnifiedFullViewingKey(ufvk);
}
std::optional<ZcashdUnifiedFullViewingKey> CWallet::GetUnifiedFullViewingKeyByAccount(libzcash::AccountId accountId) const {
if (!mnemonicHDChain.has_value()) {
throw std::runtime_error(
"CWallet::GetUnifiedFullViewingKeyByAccount(): Wallet is missing mnemonic seed metadata.");
}
auto seedfp = mnemonicHDChain.value().GetSeedFingerprint();
auto entry = mapUnifiedAccountKeys.find(std::make_pair(seedfp, accountId));
if (entry != mapUnifiedAccountKeys.end()) {
return CCryptoKeyStore::GetUnifiedFullViewingKey(entry->second);
} else {
return std::nullopt;
}
}
WalletUAGenerationResult ToWalletUAGenerationResult(UnifiedAddressGenerationResult result) {
return std::visit(match {
[](const UnifiedAddressGenerationError& err) {
return WalletUAGenerationResult(err);
},
[](const std::pair<UnifiedAddress, diversifier_index_t>& addrPair) {
return WalletUAGenerationResult(addrPair);
}
}, result);
}
WalletUAGenerationResult CWallet::GenerateUnifiedAddress(
const libzcash::AccountId& accountId,
const std::set<libzcash::ReceiverType>& receiverTypes,
std::optional<libzcash::diversifier_index_t> j)
{
bool searchDiversifiers = !j.has_value();
if (!libzcash::HasShielded(receiverTypes)) {
return UnifiedAddressGenerationError::ShieldedReceiverNotFound;
}
// The wallet must be unlocked in order to generate new transparent UA
// receivers, because we need to be able to add the secret key for the
// external child address at the diversifier index to the wallet's
// transparent backend in order to be able to detect transactions as
// ours rather than considering them as watch-only.
bool hasTransparent = receiverTypes.find(ReceiverType::P2PKH) != receiverTypes.end();
if (hasTransparent) {
// A preemptive check to ensure that the user has not specified an
// invalid transparent child index. If we search from a valid transparent
// child index into invalid child index space.
if (j.has_value() && !j.value().ToTransparentChildIndex().has_value()) {
return UnifiedAddressGenerationError::InvalidTransparentChildIndex;
}
if (IsCrypted() || !GetMnemonicSeed().has_value()) {
return WalletUAGenerationError::WalletEncrypted;
}
}
auto ufvk = GetUnifiedFullViewingKeyByAccount(accountId);
if (ufvk.has_value()) {
auto ufvkid = ufvk.value().GetKeyID();
// Check whether an address has already been generated for any provided
// diversifier index. Return that address, or set the diversifier index
// at which we'll begin searching for the next available diversified
// address.
auto metadata = mapUfvkAddressMetadata.find(ufvkid);
if (metadata != mapUfvkAddressMetadata.end()) {
if (j.has_value()) {
auto receivers = metadata->second.GetReceivers(j.value());
if (receivers.has_value()) {
// Ensure that the set of receiver types being requested is
// the same as the set of receiver types that was previously
// generated. If they match, simply return that address.
if (receivers.value() == receiverTypes) {
return ToWalletUAGenerationResult(ufvk.value().Address(j.value(), receiverTypes));
} else {
return WalletUAGenerationError::ExistingAddressMismatch;
}
}
} else {
// Set the diversifier index to one greater than the last used
// diversifier
j = metadata->second.GetNextDiversifierIndex();
if (!j.has_value()) {
return UnifiedAddressGenerationError::DiversifierSpaceExhausted;
}
}
} else {
// Begin searching from the zero diversifier index if we haven't
// yet generated an address from the specified UFVK and no
// diversifier index has been specified.
if (!j.has_value()) {
j = libzcash::diversifier_index_t(0);
}
}
// Find a working diversifier and construct the associated address.
// At this point, we know that `j` will contain a value.
auto addressGenerationResult = searchDiversifiers ?
ufvk.value().FindAddress(j.value(), receiverTypes) :
ufvk.value().Address(j.value(), receiverTypes);
if (std::holds_alternative<UnifiedAddressGenerationError>(addressGenerationResult)) {
return std::get<UnifiedAddressGenerationError>(addressGenerationResult);
}
auto address = std::get<std::pair<UnifiedAddress, diversifier_index_t>>(addressGenerationResult);
assert(mapUfvkAddressMetadata[ufvkid].SetReceivers(address.second, receiverTypes));
if (hasTransparent) {
// We must construct and add the transparent spending key associated
// with the external and internal transparent child addresses to the
// transparent keystore. This call to `value` will succeed because
// this key must have been previously generated.
auto usk = GenerateUnifiedSpendingKeyForAccount(accountId).value();
auto accountKey = usk.GetTransparentKey();
// this .value is known to be safe from the earlier check
auto childIndex = address.second.ToTransparentChildIndex().value();
auto externalKey = accountKey.DeriveExternalSpendingKey(childIndex);
if (!externalKey.has_value()) {
return UnifiedAddressGenerationError::NoAddressForDiversifier;
}
AddTransparentSecretKey(
mnemonicHDChain.value().GetSeedFingerprint(),
externalKey.value(),
transparent::AccountKey::KeyPath(BIP44CoinType(), accountId, true, childIndex)
);
// We do not add the change address for the transparent key, because
// we do not send transparent change when using unified accounts.
// Writing this data is handled by `CWalletDB::WriteUnifiedAddressMetadata` below.
assert(
CCryptoKeyStore::AddTransparentReceiverForUnifiedAddress(
ufvkid, address.second, address.first
)
);
}
// If the address has a Sapling component, add an association between
// that address and the Sapling IVK corresponding to the ufvk
auto hasSapling = receiverTypes.find(ReceiverType::Sapling) != receiverTypes.end();
if (hasSapling) {
auto dfvk = ufvk.value().GetSaplingKey();
auto saplingAddress = address.first.GetSaplingReceiver();
assert (dfvk.has_value() && saplingAddress.has_value());
AddSaplingPaymentAddress(dfvk.value().ToIncomingViewingKey(), saplingAddress.value());
}
// If the address has an Orchard component, add an association between
// that address and the Orchard IVK corresponding to the ufvk
auto hasOrchard = receiverTypes.find(ReceiverType::Orchard) != receiverTypes.end();
if (hasOrchard) {
auto fvk = ufvk.value().GetOrchardKey();
auto orchardReceiver = address.first.GetOrchardReceiver();
assert (fvk.has_value() && orchardReceiver.has_value());
AddOrchardRawAddress(fvk.value().ToIncomingViewingKey(), orchardReceiver.value());
}
// Save the metadata for the generated address so that we can re-derive
// it in the future.
ZcashdUnifiedAddressMetadata addrmeta(ufvkid, address.second, receiverTypes);
if (fFileBacked && !CWalletDB(strWalletFile).WriteUnifiedAddressMetadata(addrmeta)) {
throw std::runtime_error(
"CWallet::AddUnifiedAddress(): Writing unified address metadata failed");
}
return address;
} else {
return WalletUAGenerationError::NoSuchAccount;
}
}
bool CWallet::LoadUnifiedFullViewingKey(const libzcash::UnifiedFullViewingKey &key)
{
return CCryptoKeyStore::AddUnifiedFullViewingKey(
ZcashdUnifiedFullViewingKey::FromUnifiedFullViewingKey(Params(), key)
);
}
bool CWallet::LoadUnifiedAccountMetadata(const ZcashdUnifiedAccountMetadata &skmeta)
{
AssertLockHeld(cs_wallet); // mapUnifiedAccountKeys
auto metaKey = std::make_pair(skmeta.GetSeedFingerprint(), skmeta.GetAccountId());
mapUnifiedAccountKeys.insert({metaKey, skmeta.GetKeyID()});
return mapUfvkAddressMetadata[skmeta.GetKeyID()].SetAccountId(skmeta.GetAccountId());
}
bool CWallet::LoadUnifiedAddressMetadata(const ZcashdUnifiedAddressMetadata &addrmeta)
{
AssertLockHeld(cs_wallet);
return mapUfvkAddressMetadata[addrmeta.GetKeyID()].SetReceivers(
addrmeta.GetDiversifierIndex(),
addrmeta.GetReceiverTypes());
}
std::pair<PaymentAddress, RecipientType> CWallet::GetPaymentAddressForRecipient(
const uint256& txid,
const libzcash::RecipientAddress& recipient) const
{
AssertLockHeld(cs_main);
AssertLockHeld(cs_wallet);
auto self = this;
int nHeight = chainActive.Height();
auto wtxPtr = mapWallet.find(txid);
if (wtxPtr != mapWallet.end()) {
const CBlockIndex* pTxIndex{nullptr};
if (wtxPtr->second.GetDepthInMainChain(pTxIndex, std::nullopt) > 0) {
nHeight = pTxIndex->nHeight;
}
}
auto ufvk = self->GetUFVKForReceiver(RecipientAddressToReceiver(recipient));
std::pair<PaymentAddress, RecipientType> defaultAddress = std::visit(match {
[&](const CKeyID& addr) {
auto ua = self->FindUnifiedAddressByReceiver(addr);
if (ua.has_value()) {
// we do not generate unified addresses for change keys
return std::make_pair(PaymentAddress{ua.value()}, RecipientType::WalletExternalAddress);
}
// If it's in the address book, it's a legacy external address
if (mapAddressBook.count(addr)) {
return std::make_pair(PaymentAddress{addr}, RecipientType::WalletExternalAddress);
}
if (::IsMine(*this, addr)) {
// For keys that are ours, check if they are legacy change keys. Anything that has an
// internal BIP-44 keypath is a post-mnemonic internal address.
auto keyMeta = mapKeyMetadata.find(addr);
if (keyMeta == mapKeyMetadata.end() || keyMeta->second.hdKeypath == "") {
return std::make_pair(PaymentAddress{addr}, RecipientType::LegacyChangeAddress);
} else if (IsInternalKeyPath(44, BIP44CoinType(), keyMeta->second.hdKeypath)) {
return std::make_pair(PaymentAddress{addr}, RecipientType::WalletInternalAddress);
} else {
return std::make_pair(PaymentAddress{addr}, RecipientType::WalletExternalAddress);
}
}
// It really doesn't appear to be ours, so treat it as a counterparty address.
return std::make_pair(PaymentAddress{addr}, RecipientType::CounterpartyAddress);
},
[&](const CScriptID& addr) {
auto ua = self->FindUnifiedAddressByReceiver(addr);
if (ua.has_value()) {
return std::make_pair(PaymentAddress{ua.value()}, RecipientType::WalletExternalAddress);
} else if (HaveCScript(addr)) {
// we never generate internal p2sh addresses, so all are wallet external
return std::make_pair(PaymentAddress{addr}, RecipientType::WalletExternalAddress);
}
return std::make_pair(PaymentAddress{addr}, RecipientType::CounterpartyAddress);
},
[&](const SaplingPaymentAddress& addr) {
auto ua = self->FindUnifiedAddressByReceiver(addr);
if (ua.has_value()) {
// UAs are always external addresses
return std::make_pair(PaymentAddress{ua.value()}, RecipientType::WalletExternalAddress);
}
if (ufvk.has_value() && ufvk->GetSaplingKey().has_value()) {
auto saplingKey = ufvk->GetSaplingKey().value();
auto j = saplingKey.DecryptDiversifier(addr);
if (j.has_value()) {
// external addresses correspond to UAs.
if (j.value().second) {
// std::get is safe here because we know we have a valid Sapling diversifier index
auto defaultUA = std::get<std::pair<UnifiedAddress, diversifier_index_t>>(
ufvk->Address(j.value().first, CWallet::DefaultReceiverTypes(nHeight)));
return std::make_pair(PaymentAddress{defaultUA.first}, RecipientType::WalletExternalAddress);
} else {
return std::make_pair(PaymentAddress{addr}, RecipientType::WalletInternalAddress);
}
}
}
// legacy Sapling keys that we recognize are all external addresses
libzcash::SaplingIncomingViewingKey ivk;
if (GetSaplingIncomingViewingKey(addr, ivk)) {
return std::make_pair(PaymentAddress{addr}, RecipientType::WalletExternalAddress);
}
// We don't produce internal change addresses for legacy Sapling
// addresses, so this must be a counterparty address
return std::make_pair(PaymentAddress{addr}, RecipientType::CounterpartyAddress);
},
[&](const OrchardRawAddress& addr) {
auto ua = self->FindUnifiedAddressByReceiver(addr);
if (ua.has_value()) {
// UAs are always external addresses
return std::make_pair(PaymentAddress{ua.value()}, RecipientType::WalletExternalAddress);
} else if (ufvk.has_value() && ufvk->GetOrchardKey().has_value()) {
auto orchardKey = ufvk->GetOrchardKey().value();
auto j = orchardKey.DecryptDiversifier(addr);
if (j.has_value()) {
if (j.value().second) {
// Attempt to reproduce the original unified address
auto genResult = ufvk->Address(j.value().first, CWallet::DefaultReceiverTypes(nHeight));
auto defaultUA = std::get_if<std::pair<UnifiedAddress, diversifier_index_t>>(&genResult);
if (defaultUA != nullptr) {
return std::make_pair(PaymentAddress{defaultUA->first}, RecipientType::WalletExternalAddress);
}
} else {
return std::make_pair(PaymentAddress{UnifiedAddress::ForSingleReceiver(addr)}, RecipientType::WalletInternalAddress);
}
}
}
return std::make_pair(PaymentAddress{UnifiedAddress::ForSingleReceiver(addr)}, RecipientType::CounterpartyAddress);
}
}, recipient);
auto recipientsPtr = sendRecipients.find(txid);
if (recipientsPtr == sendRecipients.end()) {
// we haven't sent to this address, so look up internally what kind
// it is & attempt to reproduce the address as the user originally
// saw it.
return defaultAddress;
} else {
// search the list of recipient mappings for one corresponding to
// our recipient, and return the known UA if it exists; otherwise
// just use the default.
for (const auto& mapping : recipientsPtr->second) {
if (mapping.address == recipient && mapping.ua.has_value()) {
// use the recipient type from the default address, but ensure that we use
// the cached address value to which we actually sent the funds
return std::make_pair(PaymentAddress{mapping.ua.value()}, defaultAddress.second);
}
}