forked from bitcoin/bitcoin
-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathhdwallet.cpp
14233 lines (11969 loc) · 497 KB
/
hdwallet.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) 2017-2024 The Particl Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <wallet/hdwallet.h>
#include <addresstype.h>
#include <anon.h>
#include <blind.h>
#include <common/args.h>
#include <consensus/merkle.h>
#include <consensus/validation.h>
#include <crypto/hmac_sha256.h>
#include <crypto/hmac_sha512.h>
#include <crypto/sha256.h>
#include <key/crypter.h>
#include <node/interface_ui.h>
#include <node/miner.h>
#include <policy/fees.h>
#include <policy/policy.h>
#include <policy/settings.h>
#include <pos/kernel.h>
#include <pos/miner.h>
#include <random.h>
#include <rpc/util.h>
#include <script/script.h>
#include <script/sign.h>
#include <script/solver.h>
#include <smsg/smessage.h>
#include <txdb.h>
#include <txmempool.h>
#include <common/messages.h>
#include <util/moneystr.h>
#include <util/rbf.h>
#include <util/translation.h>
#include <validation.h>
#include <wallet/coincontrol.h>
#include <wallet/fees.h>
#include <wallet/spend.h>
#if ENABLE_USBDEVICE
#include <usbdevice/usbdevice.h>
#endif
#include <univalue.h>
#include <secp256k1_mlsag.h>
#include <algorithm>
#include <thread>
using interfaces::FoundBlock;
static constexpr size_t OUTPUT_GROUP_MAX_ENTRIES{100};
static uint8_t GetOutputType(ChainstateManager *pchainman, const COutPoint &prevout)
{
if (!pchainman) {
return 0;
}
LOCK(cs_main);
Coin coin;
if (pchainman->ActiveChainstate().CoinsTip().GetCoin(prevout, coin)) {
return coin.nType;
}
uint256 hash_block;
const CTransactionRef tx = node::GetTransaction(nullptr, nullptr, prevout.hash, hash_block, pchainman->m_blockman);
if (tx) {
if (tx->vpout.size() > prevout.n) {
return tx->vpout[prevout.n]->GetType();
}
}
return 0;
}
static bool ExtractStealthPrefix(const std::vector<uint8_t> &vData, uint32_t &prefix, size_t offset = 33)
{
prefix = 0;
if (vData.size() >= offset + 5 // Have prefix
&& vData[offset] == DO_STEALTH_PREFIX) {
memcpy(&prefix, &vData[offset + 1], 4);
prefix = le32toh(prefix);
return true;
}
return false;
}
static void AppendKey(const CHDWallet *pw, CKey &key, uint32_t nChild, UniValue &derivedKeys) EXCLUSIVE_LOCKS_REQUIRED(pw->cs_wallet)
{
UniValue keyobj(UniValue::VOBJ);
CKeyID idk = key.GetPubKey().GetID();
bool fHardened = IsHardened(nChild);
ClearHardenedBit(nChild);
keyobj.pushKV("path", util::ToString((int64_t)nChild) + (fHardened ? "'" : ""));
keyobj.pushKV("address", EncodeDestination(PKHash(idk)));
keyobj.pushKV("privkey", CBitcoinSecret(key).ToString());
std::map<CTxDestination, CAddressBookData>::const_iterator mi = pw->m_address_book.find(PKHash(idk));
if (mi != pw->m_address_book.end()) {
// TODO: confirm vPath?
keyobj.pushKV("label", mi->second.GetLabel());
if (mi->second.purpose) {
keyobj.pushKV("purpose", PurposeToString(*mi->second.purpose));
}
UniValue objDestData(UniValue::VOBJ);
for (const auto &pair : mi->second.destdata) {
objDestData.pushKV(pair.first, pair.second);
}
if (objDestData.size() > 0) {
keyobj.pushKV("destdata", objDestData);
}
}
derivedKeys.push_back(keyobj);
return;
}
static bool HaveAnonOutputs(std::vector<CTempRecipient> &vecSend)
{
for (const auto &r : vecSend)
if (r.nType == OUTPUT_RINGCT) {
return true;
}
return false;
}
int CHDWallet::Finalise()
{
LOCK(cs_wallet);
LogPrint(BCLog::HDWALLET, "%s %s\n", GetDisplayName(), __func__);
FreeExtKeyMaps();
m_address_book.clear();
if (m_blind_scratch) {
secp256k1_scratch_space_destroy(secp256k1_ctx_blind, m_blind_scratch);
m_blind_scratch = nullptr;
}
return 0;
}
int CHDWallet::FreeExtKeyMaps()
{
LogPrint(BCLog::HDWALLET, "%s %s\n", GetDisplayName(), __func__);
for (auto it = mapExtAccounts.begin(); it != mapExtAccounts.end(); ++it) {
if (it->second) {
delete it->second;
}
}
mapExtAccounts.clear();
for (auto itl = mapExtKeys.begin(); itl != mapExtKeys.end(); ++itl) {
if (itl->second) {
delete itl->second;
}
}
mapExtKeys.clear();
mapLooseKeys.clear();
mapLooseLookAhead.clear();
return 0;
}
void CHDWallet::AddOptions(ArgsManager& argsman)
{
argsman.AddArg("-defaultlookaheadsize=<n>", strprintf("Number of keys to load into the lookahead pool per chain. (default: %u)", DEFAULT_LOOKAHEAD_SIZE), ArgsManager::ALLOW_ANY, OptionsCategory::PART_WALLET);
argsman.AddArg("-stealthv1lookaheadsize=<n>", strprintf("Number of V1 stealth keys to look ahead during a rescan. (default: %u)", DEFAULT_STEALTH_LOOKAHEAD_SIZE), ArgsManager::ALLOW_ANY, OptionsCategory::PART_WALLET);
argsman.AddArg("-stealthv2lookaheadsize=<n>", strprintf("Number of V2 stealth keys to look ahead during a rescan. (default: %u)", DEFAULT_STEALTH_LOOKAHEAD_SIZE), ArgsManager::ALLOW_ANY, OptionsCategory::PART_WALLET);
argsman.AddArg("-extkeysaveancestors", strprintf("On saving a key from the lookahead pool, save all unsaved keys leading up to it too. (default: %s)", "true"), ArgsManager::ALLOW_ANY, OptionsCategory::PART_WALLET);
argsman.AddArg("-createdefaultmasterkey", strprintf("Generate a random master key and main account if no master key exists. (default: %s)", "false"), ArgsManager::ALLOW_ANY, OptionsCategory::PART_WALLET);
argsman.AddArg("-staking", "Stake your coins to support network and gain reward (default: true)", ArgsManager::ALLOW_ANY, OptionsCategory::PART_STAKING);
argsman.AddArg("-stakingthreads", "Number of threads to start for staking, max 1 per active wallet, will divide wallets evenly between threads (default: 1)", ArgsManager::ALLOW_ANY, OptionsCategory::PART_STAKING);
argsman.AddArg("-stakethreadconddelayms", "Number of milliseconds to delay staking for on error condition (default: 60000)", ArgsManager::ALLOW_ANY, OptionsCategory::PART_STAKING);
argsman.AddArg("-minstakeinterval=<n>", "Minimum time in seconds between successful stakes (default: 0)", ArgsManager::ALLOW_ANY, OptionsCategory::PART_STAKING);
argsman.AddArg("-minersleep=<n>", "Milliseconds between stake attempts. Lowering this param will not result in more stakes. (default: 500)", ArgsManager::ALLOW_ANY, OptionsCategory::PART_STAKING);
argsman.AddArg("-reservebalance=<amount>", "Ensure available balance remains above reservebalance. (default: 0)", ArgsManager::ALLOW_ANY, OptionsCategory::PART_STAKING);
argsman.AddArg("-treasurydonationpercent=<n>", "Percentage of block reward donated to the treasury fund, overridden by system minimum. (default: 0)", ArgsManager::ALLOW_ANY, OptionsCategory::PART_STAKING);
return;
}
bool CHDWallet::ShouldRescan()
{
return mapExtAccounts.size() > 0 || CountKeys() > 0;
}
void CHDWallet::TransactionAddedToWallet(const CTransactionRef& ptx)
{
ChainstateManager *pchainman = chain().getChainman();
if (pchainman) {
if (pchainman->m_options.signals) {
pchainman->m_options.signals->TransactionAddedToWallet(GetName(), ptx);
}
}
}
void CHDWallet::SyncWithValidationInterfaceQueue()
{
ChainstateManager *pchainman = chain().getChainman();
if (pchainman) {
if (pchainman->m_options.signals) {
pchainman->m_options.signals->SyncWithValidationInterfaceQueue();
}
}
}
static void AppendError(std::string &sError, std::string s)
{
if (!sError.empty()) {
sError += "\n";
}
sError += s;
}
bool CHDWallet::ProcessStakingSettings(std::string &sError)
{
LogPrint(BCLog::HDWALLET, "%s ProcessStakingSettings\n", GetDisplayName());
// Set defaults
fStakingEnabled = true;
nStakeCombineThreshold = 1000 * COIN;
nStakeSplitThreshold = 2000 * COIN;
m_min_stakeable_value = 1;
nMaxStakeCombine = 3;
nWalletTreasuryFundCedePercent = gArgs.GetIntArg("-treasurydonationpercent", 0);
m_reward_address = CNoDestination();
m_smsg_fee_rate_target = 0;
m_smsg_difficulty_target = 0;
UniValue json;
if (GetSetting("stakingoptions", json)) {
if (!json["enabled"].isNull()) {
try { fStakingEnabled = GetBool(json["enabled"]);
} catch (std::exception &e) {
AppendError(sError, "Setting \"enabled\" failed.");
}
}
if (!json["stakecombinethreshold"].isNull()) {
try { nStakeCombineThreshold = AmountFromValue(json["stakecombinethreshold"]);
} catch (std::exception &e) {
AppendError(sError, "\"stakecombinethreshold\" not an amount.");
}
}
if (!json["stakesplitthreshold"].isNull()) {
try { nStakeSplitThreshold = AmountFromValue(json["stakesplitthreshold"]);
} catch (std::exception &e) {
AppendError(sError, "\"stakesplitthreshold\" not an amount.");
}
}
if (!json["minstakeablevalue"].isNull()) {
try { m_min_stakeable_value = AmountFromValue(json["minstakeablevalue"]);
} catch (std::exception &e) {
AppendError(sError, "\"minstakeablevalue\" not an amount.");
}
if (m_min_stakeable_value < 0) {
AppendError(sError, "\"minstakeablevalue\" must be >= 0.");
m_min_stakeable_value = 0;
}
}
if (!json["treasurydonationpercent"].isNull()) {
try { nWalletTreasuryFundCedePercent = json["treasurydonationpercent"].getInt<int>();
} catch (std::exception &e) {
AppendError(sError, "\"treasurydonationpercent\" not an integer.");
}
}
if (!json["rewardaddress"].isNull()) {
try { m_reward_address = DecodeDestination(json["rewardaddress"].get_str());
} catch (std::exception &e) {
AppendError(sError, "Setting \"rewardaddress\" failed.");
}
}
if (!json["smsgfeeratetarget"].isNull()) {
try { m_smsg_fee_rate_target = AmountFromValue(json["smsgfeeratetarget"]);
} catch (std::exception &e) {
AppendError(sError, "\"smsgfeeratetarget\" not an amount.");
}
}
if (!json["smsgdifficultytarget"].isNull()) {
try {
std::string s = json["smsgdifficultytarget"].get_str();
if (!IsHex(s) || !(s.size() == 64)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Must be 32 bytes and hex encoded.");
}
arith_uint256 target{UintToArith256(uint256S(s))};
m_smsg_difficulty_target = target.GetCompact();
} catch (std::exception &e) {
AppendError(sError, "\"smsgdifficultytarget\" not valid.");
}
}
}
if (nStakeCombineThreshold < 100 * COIN || nStakeCombineThreshold > 5000 * COIN) {
AppendError(sError, "\"stakecombinethreshold\" must be >= 100 and <= 5000.");
nStakeCombineThreshold = 1000 * COIN;
}
if (nStakeSplitThreshold < nStakeCombineThreshold * 2 || nStakeSplitThreshold > 10000 * COIN) {
AppendError(sError, "\"stakesplitthreshold\" must be >= 2x \"stakecombinethreshold\" and <= 10000.");
nStakeSplitThreshold = nStakeCombineThreshold * 2;
}
if (nWalletTreasuryFundCedePercent < 0) {
WalletLogPrintf("%s: Warning \"treasurydonationpercent\" out of range %d, clamped to %d\n", __func__, nWalletTreasuryFundCedePercent, 0);
nWalletTreasuryFundCedePercent = 0;
} else
if (nWalletTreasuryFundCedePercent > 100) {
WalletLogPrintf("%s: \"Warning treasurydonationpercent\" out of range %d, clamped to %d\n", __func__, nWalletTreasuryFundCedePercent, 100);
nWalletTreasuryFundCedePercent = 100;
}
return true;
}
bool CHDWallet::ProcessWalletSettings(std::string &sError)
{
LogPrint(BCLog::HDWALLET, "%s ProcessWalletSettings\n", GetDisplayName());
// Set defaults
m_collapse_spent_mode = 0;
m_min_collapse_depth = 3;
m_mixin_selection_mode_default = MIXIN_SEL_RECENT;
m_min_owned_value = 0;
UniValue json;
if (GetSetting("unloadspent", json)) {
if (!json["mode"].isNull()) {
try { m_collapse_spent_mode = json["mode"].getInt<int>();
} catch (std::exception &e) {
AppendError(sError, "\"mode\" not integer.");
}
}
if (!json["mindepth"].isNull()) {
try { m_min_collapse_depth = json["mindepth"].getInt<int>();
} catch (std::exception &e) {
AppendError(sError, "\"mode\" not integer.");
}
}
}
if (GetSetting("anonoptions", json)) {
if (!json["mixinselection"].isNull()) {
try { m_mixin_selection_mode_default = json["mixinselection"].getInt<int>();
} catch (std::exception &e) {
AppendError(sError, "\"mixinselection\" not integer.");
}
}
}
if (GetSetting("other", json)) {
if (!json["onlyinstance"].isNull()) {
try { m_is_only_instance = json["onlyinstance"].get_bool();
} catch (std::exception &e) {
AppendError(sError, "\"onlyinstance\" not boolean.");
}
}
if (!json["smsgenabled"].isNull()) {
try { m_smsg_enabled = json["smsgenabled"].get_bool();
} catch (std::exception &e) {
AppendError(sError, "\"smsgenabled\" not boolean.");
}
}
if (!json["minownedvalue"].isNull()) {
try { m_min_owned_value = AmountFromValue(json["minownedvalue"]);
} catch (std::exception &e) {
AppendError(sError, "\"minownedvalue\" not an amount.");
}
if (m_min_owned_value < 0) {
AppendError(sError, "\"minownedvalue\" must be >= 0.");
m_min_owned_value = 0;
}
}
}
if (m_min_collapse_depth < 2) {
AppendError(sError, "\"mindepth\" must be >= 2.");
m_min_collapse_depth = 2;
}
return true;
}
bool CHDWallet::IsInitialised() const
{
return pEKMaster || !idDefaultAccount.IsNull();
}
bool CHDWallet::IsHDEnabled() const
{
return mapExtAccounts.find(idDefaultAccount) != mapExtAccounts.end();
}
bool CHDWallet::CanGetAddresses(bool internal) const
{
if (!idDefaultAccount.IsNull()) {
return true;
}
if (CWallet::CanGetAddresses(internal)) {
return true;
}
if (IsHardwareLinkedWallet()) {
return true;
}
return false;
}
bool CHDWallet::IsHardwareLinkedWallet() const
{
LOCK(cs_wallet);
ExtKeyAccountMap::const_iterator mi = mapExtAccounts.find(idDefaultAccount);
if (mi == mapExtAccounts.end()) {
return false;
}
const CExtKeyAccount *pa = mi->second;
if (pa->nFlags & EAF_HAVE_SECRET) {
return false;
}
mapEKValue_t::const_iterator mvi = pa->mapValue.find(EKVT_HARDWARE_DEVICE);
if (mvi != pa->mapValue.end()) {
return true;
}
return false;
}
bool CHDWallet::UnsetWalletFlagRV(CHDWalletDB *pwdb, uint64_t flag)
{
LOCK(cs_wallet);
if (!IsWalletFlagSet(flag)) {
return true;
}
m_wallet_flags &= ~flag;
return pwdb->WriteWalletFlags(m_wallet_flags);
}
extern int ListLooseExtKeys(CHDWallet *pwallet, int nShowKeys, UniValue &ret, size_t &nKeys);
extern int ListAccountExtKeys(CHDWallet *pwallet, int nShowKeys, UniValue &ret, size_t &nKeys);
extern int ListLooseStealthAddresses(UniValue &arr, const CHDWallet *pwallet, bool fShowSecrets, bool fAddressBookInfo, bool show_pubkeys=false, bool bech32=false);
bool CHDWallet::DumpJson(UniValue &rv, std::string &sError)
{
WalletLogPrintf("Dumping wallet to JSON.\n");
if (IsLocked()) {
return wserrorN(false, sError, __func__, "Wallet must be unlocked.");
}
LOCK(cs_wallet);
CHDWalletDB wdb(*m_database);
size_t nKeys, nAcc;
UniValue extkeys(UniValue::VARR);
UniValue extaccs(UniValue::VARR);
ListLooseExtKeys(this, 2, extkeys, nKeys);
ListAccountExtKeys(this, 3, extaccs, nAcc);
CExtKey58 eKey58;
for (size_t k = 0; k < extaccs.size(); ++k) {
UniValue &acc = extaccs.get(k);
size_t nChains = acc["chains"].size();
std::vector<CExtKeyPair> vChains;
vChains.resize(nChains);
for (size_t c = 0; c < nChains; ++c) {
UniValue &chain = acc.get("chains").get(c);
const std::string &sEvkey = chain["evkey"].get_str();
uint32_t nDerives = 0;
uint32_t nDerivesH = 0;
if (chain["num_derives"].isStr()
&& !ParseUInt32(chain["num_derives"].get_str(), &nDerives)) {
return wserrorN(false, sError, __func__, "num_derives to int failed.");
}
if (chain["num_derives_h"].isStr()
&& !ParseUInt32(chain["num_derives_h"].get_str(), &nDerivesH)) {
return wserrorN(false, sError, __func__, "num_derives_h to int failed.");
}
eKey58.Set58(sEvkey.c_str());
CExtKeyPair kp = eKey58.GetKey();
vChains[c] = kp;
bool fIsStealth = false;
if (chain["use_type"].isStr() && chain["use_type"].get_str() == "stealth") {
fIsStealth = true;
}
UniValue derivedKeys(UniValue::VARR);
UniValue derivedKeysH(UniValue::VARR);
if (fIsStealth) {
// Dump from pack instead
} else {
CKey key;
uint32_t nChild = 0;
for (uint32_t k = 0; k < nDerives; ++k) {
if (kp.Derive(key, nChild)) {
AppendKey(this, key, nChild, derivedKeys);
}
nChild++;
}
chain.pushKV("derived_keys", derivedKeys);
for (uint32_t k = 0; k < nDerivesH; ++k) {
nChild = k;
SetHardenedBit(nChild);
if (kp.Derive(key, nChild)) {
AppendKey(this, key, nChild, derivedKeysH);
}
}
chain.pushKV("derived_keys_hardened", derivedKeysH);
}
}
// Read stealth keys from packs to keep metadata such as prefix
size_t nPackStealthAddrs = 0;
size_t nPackStealthKeys = 0;
if (acc["stealth_address_pack"].isNum()) {
nPackStealthAddrs = acc["stealth_address_pack"].getInt<int>();
}
if (acc["stealth_keys_received_pack"].isNum()) {
nPackStealthKeys = acc["stealth_keys_received_pack"].getInt<int>();
}
CKeyID idAcc;
CBitcoinAddress accIdAddr(acc["id"].get_str());
if (!accIdAddr.IsValid(CChainParams::EXT_ACC_HASH)) {
WalletLogPrintf("%s: ERROR - Invalid account id %s\n", __func__, acc["id"].get_str());
acc.pushKV("ERROR", "Invalid account id");
continue;
}
accIdAddr.GetKeyID(idAcc, CChainParams::EXT_ACC_HASH);
std::map<CKeyID, std::pair<CKey, std::string> > mapStealthKeySpend;
UniValue stealthAddresses(UniValue::VARR);
std::vector<CEKAStealthKeyPack> aksPak;
for (uint32_t i = 0; i <= nPackStealthAddrs; ++i) {
if (!wdb.ReadExtStealthKeyPack(idAcc, i, aksPak)) {
continue;
}
for (const auto &sxPacked : aksPak) {
UniValue sxAddr(UniValue::VOBJ);
if (!sxPacked.aks.sLabel.empty()) {
sxAddr.pushKV("label", sxPacked.aks.sLabel);
}
CStealthAddress sx;
sxPacked.aks.SetSxAddr(sx);
std::string sxStr = sx.ToString();
sxAddr.pushKV("address", sxStr);
sxAddr.pushKV("scan_priv", CBitcoinSecret(sxPacked.aks.skScan).ToString());
size_t p = sxPacked.aks.akSpend.nParent;
if (p >= vChains.size()+1) {
WalletLogPrintf("%s: ERROR - chain out of range %d\n", __func__, p);
acc.pushKV("ERROR", "Invalid chain offset.");
continue;
}
// Chain0 is the account key
CExtKeyPair &kp = vChains[p-1];
CKey kSpend;
uint32_t nChild = sxPacked.aks.akSpend.nKey;
if (kp.Derive(kSpend, nChild)) {
sxAddr.pushKV("spend_priv", CBitcoinSecret(kSpend).ToString());
} else {
WalletLogPrintf("%s: ERROR - Derive failed %u\n", __func__, nChild);
acc.pushKV("ERROR", "Derive spend key failed.");
}
mapStealthKeySpend[sxPacked.id] = std::make_pair(kSpend, sxStr);
sxAddr.pushKV("account_chain", (int)sxPacked.aks.akSpend.nParent);
uint32_t nScanKey = sxPacked.aks.nScanKey;
ClearHardenedBit(nScanKey);
sxAddr.pushKV("scan_key_offset", util::ToString((int64_t)nScanKey)+"'");
std::map<CTxDestination, CAddressBookData>::const_iterator mi = m_address_book.find(sx);
if (mi != m_address_book.end()) {
// TODO: confirm vPath?
if (mi->second.GetLabel() != sxPacked.aks.sLabel) {
sxAddr.pushKV("addr_book_label", mi->second.GetLabel());
}
if (mi->second.purpose) {
sxAddr.pushKV("purpose", PurposeToString(*mi->second.purpose));
}
UniValue objDestData(UniValue::VOBJ);
for (const auto &pair : mi->second.destdata) {
sxAddr.pushKV(pair.first, pair.second);
}
if (objDestData.size() > 0) {
sxAddr.pushKV("destdata", objDestData);
}
}
stealthAddresses.push_back(sxAddr);
}
}
acc.pushKV("stealth_addresses", stealthAddresses);
UniValue stealthReceivedKeys(UniValue::VARR);
std::vector<CEKASCKeyPack> asckPak;
for (uint32_t i = 0; i <= nPackStealthKeys; ++i) {
if (!wdb.ReadExtStealthKeyChildPack(idAcc, i, asckPak)) {
continue;
}
for (const auto &keyPacked : asckPak) {
UniValue obj(UniValue::VOBJ);
obj.pushKV("address", EncodeDestination(PKHash(keyPacked.id)));
CKey kOut, kSpend;
std::map<CKeyID, std::pair<CKey, std::string> >::const_iterator mi;
if ((mi = mapStealthKeySpend.find(keyPacked.asck.idStealthKey)) == mapStealthKeySpend.end()) {
WalletLogPrintf("%s: ERROR - Unknown stealth key %s\n", __func__, HexStr(keyPacked.asck.idStealthKey));
acc.pushKV("ERROR", "Unknown stealth key.");
} else {
obj.pushKV("stealth_address", mi->second.second);
if (0 != StealthSharedToSecretSpend(keyPacked.asck.sShared, mi->second.first, kOut)) {
WalletLogPrintf("%s: ERROR - StealthSharedToSecretSpend failed\n", __func__);
acc.pushKV("ERROR", "StealthSharedToSecretSpend failed.");
} else {
obj.pushKV("privkey", CBitcoinSecret(kOut).ToString());
}
}
stealthReceivedKeys.push_back(obj);
}
}
acc.pushKV("keys_received_on_stealth_addresses", stealthReceivedKeys);
}
rv.pushKV("loose_extkeys", extkeys);
rv.pushKV("accounts", extaccs);
UniValue stealthAddresses(UniValue::VARR);
ListLooseStealthAddresses(stealthAddresses, this, true, true);
rv.pushKV("imported_stealth_addresses", stealthAddresses);
return true;
}
bool CHDWallet::LoadJson(const UniValue &inj, std::string &sError)
{
WalletLogPrintf("Loading wallet from JSON.\n");
if (IsLocked()) {
return wserrorN(false, sError, __func__, "Wallet must be unlocked.");
}
LOCK(cs_wallet);
return wserrorN(false, sError, __func__, "TODO: LoadJson.");
return true;
}
bool CHDWallet::LoadAddressBook(CHDWalletDB *pwdb)
{
LogPrint(BCLog::HDWALLET, "Loading address book for %s.\n", GetName());
assert(pwdb);
LOCK(cs_wallet);
Dbc *pcursor;
if (!(pcursor = pwdb->GetCursor())) {
throw std::runtime_error(strprintf("%s: cannot create DB cursor", __func__).c_str());
}
DataStream ssKey{};
DataStream ssValue{};
std::string strType, strAddress, sPrefix = "abe";
size_t nCount = 0;
unsigned int fFlags = DB_SET_RANGE;
ssKey << sPrefix;
while (pwdb->ReadAtCursor(pcursor, ssKey, ssValue, fFlags) == 0) {
fFlags = DB_NEXT;
ssKey >> strType;
if (strType != sPrefix) {
break;
}
ssKey >> strAddress;
CAddressBookData data;
ssValue >> data;
// Can't use m_address_book.insert, loses &name
CTxDestination address = DecodeDestination(strAddress);
std::map<CTxDestination, CAddressBookData>::iterator mi = m_address_book.find(address);
bool fUpdated = (mi != m_address_book.end() && !mi->second.IsChange());
m_address_book[address].Set(data);
if (!fUpdated) {
nCount++;
}
}
LogPrint(BCLog::HDWALLET, "%s Loaded %d addresses.\n", GetDisplayName(), nCount);
pcursor->close();
return true;
}
bool CHDWallet::LoadVoteTokens(CHDWalletDB *pwdb)
{
LogPrint(BCLog::HDWALLET, "%s Loading vote tokens.\n", GetDisplayName());
vVoteTokens.clear();
std::vector<CVoteToken> vVoteTokensRead;
if (!pwdb->ReadVoteTokens(vVoteTokensRead)) {
return false;
}
int nBestHeight = m_last_block_processed_height > -1 ? GetLastBlockHeight() : 0;
for (const auto &v : vVoteTokensRead) {
if (v.nEnd > nBestHeight - 1000) { // 1000 block buffer in case of reorg etc
vVoteTokens.push_back(v);
if (LogAcceptCategory(BCLog::HDWALLET, BCLog::Level::Debug)) {
if ((v.nToken >> 16) < 1 ||
(v.nToken & 0xFFFF) < 1) {
WalletLogPrintf("Clearing vote from block %d to %d.\n",
v.nStart, v.nEnd);
} else {
WalletLogPrintf("Voting for option %u on proposal %u from block %d to %d.\n",
v.nToken >> 16, v.nToken & 0xFFFF, v.nStart, v.nEnd);
}
}
}
}
return true;
}
bool CHDWallet::GetVote(int nHeight, uint32_t &token)
{
for (auto i = vVoteTokens.crbegin(); i != vVoteTokens.crend(); ++i) {
if (i->nEnd < nHeight
|| i->nStart > nHeight) {
continue;
}
if ((i->nToken >> 16) < 1
|| (i->nToken & 0xFFFF) < 1) {
continue;
}
token = i->nToken;
return true;
}
return false;
}
bool CHDWallet::LoadTxRecords(CHDWalletDB *pwdb)
{
LogPrint(BCLog::HDWALLET, "Loading transaction records for %s.\n", GetName());
assert(pwdb);
LOCK(cs_wallet);
Dbc *pcursor;
if (!(pcursor = pwdb->GetCursor())) {
throw std::runtime_error(strprintf("%s: cannot create DB cursor", __func__).c_str());
}
DataStream ssKey{}, ssValue{};
std::string strType, sPrefix = "rtx";
uint256 txhash;
unsigned int fFlags = DB_SET_RANGE;
ssKey << sPrefix;
while (pwdb->ReadAtCursor(pcursor, ssKey, ssValue, fFlags) == 0) {
fFlags = DB_NEXT;
ssKey >> strType;
if (strType != sPrefix) {
break;
}
ssKey >> txhash;
CTransactionRecord data;
ssValue >> data;
LoadToWallet(txhash, data);
}
pcursor->close();
int32_t flag;
if (!pwdb->ReadFlag("anon_vin_v2", flag)) {
WalletLogPrintf("Upgrading TransactionRecord format.\n");
for (auto &ri : mapRecords) {
const uint256 &txhash = ri.first;
CTransactionRecord &rtx = ri.second;
std::vector<COutPoint> new_vin;
if (rtx.nFlags & ORF_ANON_IN) {
for (const auto &prevout : rtx.vin) {
CCmpPubKey ki;
memcpy(ki.ncbegin(), prevout.hash.begin(), 32);
*(ki.ncbegin()+32) = prevout.n;
COutPoint kiPrevout;
if (!pwdb->ReadAnonKeyImage(ki, kiPrevout)) {
WalletLogPrintf("Warning: Unknown keyimage %s.\n", HexStr(Span<const unsigned char>(ki.begin(), 33)));
continue;
}
new_vin.push_back(kiPrevout);
}
rtx.vin = new_vin;
pwdb->WriteTxRecord(txhash, rtx);
}
}
pwdb->WriteFlag("anon_vin_v2", 1);
}
// Must load all records before marking spent.
MapRecords_t::iterator mri;
MapWallet_t::iterator mwi;
for (const auto &ri : mapRecords) {
const uint256 &txhash = ri.first;
const CTransactionRecord &rtx = ri.second;
for (const auto &prevout : rtx.vin) {
AddToSpends(prevout, txhash);
if ((mri = mapRecords.find(prevout.hash)) != mapRecords.end()) {
CTransactionRecord &prevtx = mri->second;
if (prevtx.nIndex == -1 && !prevtx.HashUnset()) {
MarkConflicted(prevtx.blockHash, prevtx.block_height, txhash);
}
} else
if ((mwi = mapWallet.find(prevout.hash)) != mapWallet.end()) {
CWalletTx &prevtx = mwi->second;
if (auto* prev = prevtx.state<TxStateConflicted>()) {
MarkConflicted(prev->conflicting_block_hash, prev->conflicting_block_height, txhash);
}
}
}
}
WalletLogPrintf("mapRecords.size() = %u\n", mapRecords.size());
return true;
}
bool CHDWallet::LoadLockedUTXOs(CHDWalletDB *pwdb)
{
LogPrint(BCLog::HDWALLET, "Loading locked UTXO records for %s.\n", GetName());
assert(pwdb);
LOCK(cs_wallet);
Dbc *pcursor;
if (!(pcursor = pwdb->GetCursor())) {
throw std::runtime_error(strprintf("%s: cannot create DB cursor", __func__).c_str());
}
DataStream ssKey{}, ssValue{};
std::string strType, sPrefix = DBKeys::PART_LOCKEDUTXO;
COutPoint output;
unsigned int fFlags = DB_SET_RANGE;
ssKey << sPrefix;
while (pwdb->ReadAtCursor(pcursor, ssKey, ssValue, fFlags) == 0) {
fFlags = DB_NEXT;
ssKey >> strType;
if (strType != sPrefix) {
break;
}
ssKey >> output;
LockCoin(output);
}
pcursor->close();
return true;
}
bool CHDWallet::IsLocked() const
{
LOCK(cs_wallet); // Lock cs_wallet to ensure any CHDWallet::Unlock has completed
return CWallet::IsLocked();
}
bool CHDWallet::EncryptWallet(const SecureString &strWalletPassphrase)
{
LogPrint(BCLog::HDWALLET, "%s %s\n", GetDisplayName(), __func__);
if (IsCrypted()) {
return false;
}
CKeyingMaterial vMasterKey;
vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
GetStrongRandBytes2(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
CMasterKey kMasterKey;
kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
GetStrongRandBytes2(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
CCrypter crypter;
int64_t nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
if (kMasterKey.nDeriveIterations < 25000)
kMasterKey.nDeriveIterations = 25000;
WalletLogPrintf("Encrypting wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
return false;
if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
return false;
{
LOCK2(m_relock_mutex, cs_wallet);
mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
WalletBatch* encrypted_batch = new CHDWalletDB(*m_database);
if (!encrypted_batch->TxnBegin()) {
delete encrypted_batch;
encrypted_batch = nullptr;
return false;
}
encrypted_batch->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
for (const auto& spk_man_pair : m_spk_managers) {
if (!spk_man_pair.second->Encrypt(vMasterKey, encrypted_batch)) {
encrypted_batch->TxnAbort();
delete encrypted_batch;
encrypted_batch = nullptr;
// We now probably have half of our keys encrypted in memory, and half not...
// die and let the user reload the unencrypted wallet.
assert(false);
}
}
if (0 != ExtKeyEncryptAll((CHDWalletDB*)encrypted_batch, vMasterKey)) {
WalletLogPrintf("Terminating - Error: ExtKeyEncryptAll failed.\n");
//if (fFileBacked)
{
encrypted_batch->TxnAbort();
delete encrypted_batch;
}
assert(false); // die and let the user reload the unencrypted wallet.
}
// Encryption was introduced in version 0.4.0
SetMinVersion(FEATURE_WALLETCRYPT, encrypted_batch);
//if (fFileBacked)
{
if (!encrypted_batch->TxnCommit()) {
delete encrypted_batch;
// We now have keys encrypted in memory, but not on disk...
// die to avoid confusion and let the user reload the unencrypted wallet.
assert(false);