forked from dashpay/dash
-
Notifications
You must be signed in to change notification settings - Fork 716
/
wallet.h
1144 lines (944 loc) · 43.6 KB
/
wallet.h
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 developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2020 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_WALLET_H
#define BITCOIN_WALLET_H
#include "addressbook.h"
#include "amount.h"
#include "base58.h"
#include "consensus/tx_verify.h"
#include "consensus/validation.h"
#include "crypter.h"
#include "destination_io.h"
#include "kernel.h"
#include "key.h"
#include "keystore.h"
#include "pairresult.h"
#include "policy/feerate.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "sapling/address.h"
#include "guiinterface.h"
#include "util.h"
#include "util/memory.h"
#include "utilstrencodings.h"
#include "validationinterface.h"
#include "script/ismine.h"
#include "wallet/scriptpubkeyman.h"
#include "sapling/saplingscriptpubkeyman.h"
#include "validation.h"
#include "wallet/walletdb.h"
#include <algorithm>
#include <atomic>
#include <map>
#include <set>
#include <stdexcept>
#include <stdint.h>
#include <string>
#include <utility>
#include <vector>
extern CWallet* pwalletMain;
/**
* Settings
*/
extern CFeeRate payTxFee;
extern CAmount maxTxFee;
extern unsigned int nTxConfirmTarget;
extern bool bSpendZeroConfChange;
extern bool bdisableSystemnotifications;
extern bool fPayAtLeastCustomFee;
//! -paytxfee default
static const CAmount DEFAULT_TRANSACTION_FEE = 0;
//! -paytxfee will warn if called with a higher fee than this amount (in satoshis) per KB
static const CAmount nHighTransactionFeeWarning = 0.1 * COIN;
//! -maxtxfee default
static const CAmount DEFAULT_TRANSACTION_MAXFEE = 1 * COIN;
//! -maxtxfee will warn if called with a higher fee than this amount (in satoshis)
static const CAmount nHighTransactionMaxFeeWarning = 100 * nHighTransactionFeeWarning;
//! Largest (in bytes) free transaction we're willing to create
static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE = 1000;
//! -custombackupthreshold default
static const int DEFAULT_CUSTOMBACKUPTHRESHOLD = 1;
//! -minstakesplit default
static const CAmount DEFAULT_MIN_STAKE_SPLIT_THRESHOLD = 100 * COIN;
//! Default for -spendzeroconfchange
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
//! Default for -staking
static const bool DEFAULT_STAKING = true;
//! Default for -coldstaking
static const bool DEFAULT_COLDSTAKING = true;
//! Defaults for -gen and -genproclimit
static const bool DEFAULT_GENERATE = false;
static const unsigned int DEFAULT_GENERATE_PROCLIMIT = 1;
//! Default for -createwalletbackups
static const unsigned int DEFAULT_CREATEWALLETBACKUPS = 10;
//! Default for -disablewallet
static const bool DEFAULT_DISABLE_WALLET = false;
extern const char * DEFAULT_WALLET_DAT;
class CAddressBookIterator;
class CCoinControl;
class COutput;
class CStakeableOutput;
class CReserveKey;
class CScript;
class CScheduler;
class CWalletTx;
class ScriptPubKeyMan;
class SaplingScriptPubKeyMan;
class SaplingNoteData;
/** (client) version numbers for particular wallet features */
enum WalletFeature {
FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
FEATURE_WALLETCRYPT = 40000, // wallet encryption
FEATURE_COMPRPUBKEY = 60000, // compressed public keys
FEATURE_PRE_PIVX = 61000, // inherited version..
// The following features were implemented in BTC but not in our wallet, we can simply skip them.
// FEATURE_HD = 130000, Hierarchical key derivation after BIP32 (HD Wallet)
// FEATURE_HD_SPLIT = 139900, // Wallet with HD chain split (change outputs will use m/0'/1'/k)
FEATURE_PRE_SPLIT_KEYPOOL = 169900, // Upgraded to HD SPLIT and can have a pre-split keypool
FEATURE_SAPLING = 170000, // Upgraded to Saplings key manager.
FEATURE_LATEST = FEATURE_SAPLING
};
enum AvailableCoinsType {
ALL_COINS = 1,
ONLY_10000 = 5, // find masternode outputs including locked ones (use with caution)
STAKEABLE_COINS = 6 // UTXO's that are valid for staking
};
/** A key pool entry */
class CKeyPool
{
public:
//! The time at which the key was generated. Set in AddKeypoolPubKeyWithDB
int64_t nTime;
//! The public key
CPubKey vchPubKey;
//! Whether this keypool entry is in the internal, external or staking keypool.
uint8_t type;
//! Whether this key was generated for a keypool before the wallet was upgraded to HD-split
bool m_pre_split;
CKeyPool();
CKeyPool(const CPubKey& vchPubKeyIn, const uint8_t& type);
bool IsInternal() const { return type == HDChain::ChangeType::INTERNAL; }
bool IsExternal() const { return type == HDChain::ChangeType::EXTERNAL; }
bool IsStaking() const { return type == HDChain::ChangeType::STAKING; }
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action)
{
int nVersion = s.GetVersion();
if (!(s.GetType() & SER_GETHASH))
READWRITE(nVersion);
READWRITE(nTime);
READWRITE(vchPubKey);
if (ser_action.ForRead()) {
try {
READWRITE(FLATDATA(type));
READWRITE(m_pre_split);
} catch (std::ios_base::failure&) {
/* Set as external address if we can't read the type boolean
(this will be the case for any wallet before the HD chain) */
type = HDChain::ChangeType::EXTERNAL;
m_pre_split = true;
}
} else {
READWRITE(FLATDATA(type));
READWRITE(m_pre_split);
}
}
};
/** Record info about last stake attempt:
* - tipBlock index of the block on top of which last stake attempt was made
* - nTime time slot of last attempt
* - nTries number of UTXOs hashed during last attempt
* - nCoins number of stakeable utxos during last attempt
**/
class CStakerStatus
{
private:
const CBlockIndex* tipBlock{nullptr};
int64_t nTime{0};
int nTries{0};
int nCoins{0};
public:
// Get
const CBlockIndex* GetLastTip() const { return tipBlock; }
uint256 GetLastHash() const { return (GetLastTip() == nullptr ? UINT256_ZERO : GetLastTip()->GetBlockHash()); }
int GetLastHeight() const { return (GetLastTip() == nullptr ? 0 : GetLastTip()->nHeight); }
int GetLastCoins() const { return nCoins; }
int GetLastTries() const { return nTries; }
int64_t GetLastTime() const { return nTime; }
// Set
void SetLastCoins(const int coins) { nCoins = coins; }
void SetLastTries(const int tries) { nTries = tries; }
void SetLastTip(const CBlockIndex* lastTip) { tipBlock = lastTip; }
void SetLastTime(const uint64_t lastTime) { nTime = lastTime; }
void SetNull()
{
SetLastCoins(0);
SetLastTries(0);
SetLastTip(nullptr);
SetLastTime(0);
}
// Check whether staking status is active (last attempt earlier than 30 seconds ago)
bool IsActive() const { return (nTime + 30) >= GetTime(); }
};
struct CRecipient
{
CScript scriptPubKey;
CAmount nAmount;
bool fSubtractFeeFromAmount;
CRecipient(const CScript& _scriptPubKey, const CAmount& _nAmount, bool _fSubtractFeeFromAmount):
scriptPubKey(_scriptPubKey),
nAmount(_nAmount),
fSubtractFeeFromAmount(_fSubtractFeeFromAmount)
{}
};
class CAddressBookIterator
{
public:
explicit CAddressBookIterator(std::map<CWDestination, AddressBook::CAddressBookData>& _map) : map(_map), it(_map.begin()), itEnd(_map.end()) {}
const CWDestination* GetDestKey();
const CTxDestination* GetCTxDestKey();
const libzcash::SaplingPaymentAddress* GetShieldedDestKey();
AddressBook::CAddressBookData GetValue() { return it->second; }
bool IsValid() { return it != itEnd; }
bool Next() {
if (!IsValid()) return false;
it++;
return IsValid();
}
void SetFilter(CTxDestination& filter)
{
it = map.find(filter);
if (it != itEnd) {
itEnd = std::next(it);
}
}
private:
std::map<CWDestination, AddressBook::CAddressBookData>& map;
std::map<CWDestination, AddressBook::CAddressBookData>::iterator it;
std::map<CWDestination, AddressBook::CAddressBookData>::iterator itEnd;
};
template <class T>
using TxSpendMap = std::multimap<T, uint256>;
typedef std::map<SaplingOutPoint, SaplingNoteData> mapSaplingNoteData_t;
/**
* A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
* and provides the ability to create new transactions.
*/
class CWallet : public CCryptoKeyStore, public CValidationInterface
{
private:
static std::atomic<bool> fFlushScheduled;
//! keeps track of whether Unlock has run a thorough check before
bool fDecryptionThoroughlyChecked{false};
//! Key manager //
std::unique_ptr<ScriptPubKeyMan> m_spk_man = MakeUnique<ScriptPubKeyMan>(this);
std::unique_ptr<SaplingScriptPubKeyMan> m_sspk_man = MakeUnique<SaplingScriptPubKeyMan>(this);
//! the current wallet version: clients below this version are not able to load the wallet
int nWalletVersion;
//! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
int nWalletMaxVersion;
std::unique_ptr<CWalletDBWrapper> dbw;
int64_t nNextResend;
int64_t nLastResend;
/**
* Used to keep track of spent outpoints, and
* detect and report conflicts (double-spends or
* mutated transactions where the mutant gets mined).
*/
typedef TxSpendMap<COutPoint> TxSpends;
TxSpends mapTxSpends;
void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
void AddToSpends(const uint256& wtxid);
/* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
void MarkConflicted(const uint256& hashBlock, const uint256& hashTx);
template <class T>
void SyncMetaData(std::pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator> range);
void ChainTipAdded(const CBlockIndex *pindex, const CBlock *pblock, SaplingMerkleTree saplingTree);
/* Used by TransactionAddedToMemorypool/BlockConnected/Disconnected */
void SyncTransaction(const CTransactionRef& tx, const CBlockIndex *pindexBlockConnected, int posInBlock);
bool IsKeyUsed(const CPubKey& vchPubKey);
struct OutputAvailabilityResult
{
bool available{false};
bool solvable{false};
bool spendable{false};
};
OutputAvailabilityResult CheckOutputAvailability(const CTxOut& output,
const unsigned int outIndex,
const uint256& wtxid,
AvailableCoinsType nCoinType,
const CCoinControl* coinControl,
const bool fCoinsSelected,
const bool fIncludeColdStaking,
const bool fIncludeDelegated,
const bool fIncludeLocked) const;
//! Destination --> label/purpose mapping.
std::map<CWDestination, AddressBook::CAddressBookData> mapAddressBook;
public:
static const CAmount DEFAULT_STAKE_SPLIT_THRESHOLD = 500 * COIN;
//! Generates hd wallet //
bool SetupSPKM(bool newKeypool = true, bool memOnly = false);
//! Whether the wallet is hd or not //
bool IsHDEnabled() const;
//! Whether the wallet supports Sapling or not //
bool IsSaplingUpgradeEnabled() const;
/* SPKM Helpers */
const CKeyingMaterial& GetEncryptionKey() const;
bool HasEncryptionKeys() const;
//! Get spkm
ScriptPubKeyMan* GetScriptPubKeyMan() const;
SaplingScriptPubKeyMan* GetSaplingScriptPubKeyMan() const { return m_sspk_man.get(); }
bool HasSaplingSPKM() const;
/*
* Main wallet lock.
* This lock protects all the fields added by CWallet.
*/
mutable RecursiveMutex cs_wallet;
bool fWalletUnlockStaking;
CWalletDB* pwalletdbEncryption;
std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
MasterKeyMap mapMasterKeys;
unsigned int nMasterKeyMaxID;
// Stake split threshold
CAmount nStakeSplitThreshold;
// minimum value allowed for nStakeSplitThreshold (customizable with -minstakesplit flag)
static CAmount minStakeSplitThreshold;
// Staker status (last hashed block and time)
CStakerStatus* pStakerStatus = nullptr;
// User-defined fee PIV/kb
bool fUseCustomFee;
CAmount nCustomFee;
//MultiSend
std::vector<std::pair<std::string, int> > vMultiSend;
bool fMultiSendStake;
bool fMultiSendMasternodeReward;
bool fMultiSendNotify;
std::string strMultiSendChangeAddress;
int nLastMultiSendHeight;
std::vector<std::string> vDisabledAddresses;
//Auto Combine Inputs
bool fCombineDust;
CAmount nAutoCombineThreshold;
/** Get database handle used by this wallet. Ideally this function would
* not be necessary.
*/
CWalletDBWrapper& GetDBHandle() const
{
return *dbw;
}
/** Get a name for this wallet for logging/debugging purposes.
*/
std::string GetName() const
{
if (dbw) {
return dbw->GetName();
} else {
return "dummy";
}
}
// Create wallet with dummy database handle
CWallet();
// Create wallet with passed-in database handle
CWallet(std::unique_ptr<CWalletDBWrapper> dbw_in);
~CWallet();
void SetNull();
bool isMultiSendEnabled();
void setMultiSendDisabled();
std::map<uint256, CWalletTx> mapWallet;
typedef std::multimap<int64_t, CWalletTx*> TxItems;
TxItems wtxOrdered;
int64_t nOrderPosNext;
std::set<COutPoint> setLockedCoins;
int64_t nTimeFirstKey;
// Public SyncMetadata interface used for the sapling spent nullifier map.
void SyncMetaDataN(std::pair<TxSpendMap<uint256>::iterator, TxSpendMap<uint256>::iterator> range);
const CWalletTx* GetWalletTx(const uint256& hash) const;
std::vector<CWalletTx> getWalletTxs();
std::string GetUniqueWalletBackupName() const;
//! check whether we are allowed to upgrade (or already support) to the named feature
bool CanSupportFeature(enum WalletFeature wf);
struct AvailableCoinsFilter {
public:
AvailableCoinsFilter() {}
AvailableCoinsFilter(bool _fIncludeDelegated,
bool _fIncludeColdStaking,
AvailableCoinsType _nCoinType,
bool _fOnlyConfirmed,
bool _fOnlySpendable,
std::set<CTxDestination>* _onlyFilteredDest,
int _minDepth,
bool _fIncludeLocked = false) :
fIncludeDelegated(_fIncludeDelegated),
fIncludeColdStaking(_fIncludeColdStaking),
nCoinType(_nCoinType),
fOnlyConfirmed(_fOnlyConfirmed),
fOnlySpendable(_fOnlySpendable),
onlyFilteredDest(_onlyFilteredDest),
minDepth(_minDepth),
fIncludeLocked(_fIncludeLocked) {}
bool fIncludeDelegated{true};
bool fIncludeColdStaking{false};
AvailableCoinsType nCoinType{ALL_COINS};
bool fOnlyConfirmed{true};
bool fOnlySpendable{false};
std::set<CTxDestination>* onlyFilteredDest{nullptr};
int minDepth{0};
bool fIncludeLocked{false};
};
//! >> Available coins (generic)
bool AvailableCoins(std::vector<COutput>* pCoins, // --> populates when != nullptr
const CCoinControl* coinControl = nullptr,
AvailableCoinsFilter coinsFilter = AvailableCoinsFilter()
) const;
//! >> Available coins (spending)
bool SelectCoinsToSpend(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl = nullptr) const;
bool SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet) const;
//! >> Available coins (staking)
bool StakeableCoins(std::vector<CStakeableOutput>* pCoins = nullptr);
//! >> Available coins (P2CS)
void GetAvailableP2CSCoins(std::vector<COutput>& vCoins) const;
std::map<CTxDestination, std::vector<COutput> > AvailableCoinsByAddress(bool fConfirmed = true, CAmount maxCoinValue = 0);
/// Get 10000 PIV output and keys which can be used for the Masternode
bool GetMasternodeVinAndKeys(CTxIn& txinRet, CPubKey& pubKeyRet,
CKey& keyRet, std::string strTxHash, std::string strOutputIndex, std::string& strError);
/// Extract txin information and keys from output
bool GetVinAndKeysFromOutput(COutput out, CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet, bool fColdStake = false);
bool IsSpent(const COutPoint& outpoint) const;
bool IsSpent(const uint256& hash, unsigned int n) const;
bool IsLockedCoin(const uint256& hash, unsigned int n) const;
void LockCoin(const COutPoint& output);
void UnlockCoin(const COutPoint& output);
void UnlockAllCoins();
std::set<COutPoint> ListLockedCoins();
// keystore implementation
PairResult getNewAddress(CTxDestination& ret, const std::string addressLabel, const std::string purpose,
const CChainParams::Base58Type addrType = CChainParams::PUBKEY_ADDRESS);
PairResult getNewAddress(CTxDestination& ret, std::string label);
PairResult getNewStakingAddress(CTxDestination& ret, std::string label);
int64_t GetKeyCreationTime(const CWDestination& dest);
int64_t GetKeyCreationTime(CPubKey pubkey);
int64_t GetKeyCreationTime(const CTxDestination& address);
int64_t GetKeyCreationTime(const libzcash::SaplingPaymentAddress& address);
//////////// Sapling //////////////////
// Search for notes and addresses from this wallet in the tx, and add the addresses --> IVK mapping to the keystore if missing.
bool FindNotesDataAndAddMissingIVKToKeystore(const CTransaction& tx, Optional<mapSaplingNoteData_t>& saplingNoteData);
// Decrypt sapling output notes with the inputs ovk and updates saplingNoteDataMap
void AddExternalNotesDataToTx(CWalletTx& wtx) const;
//! Generates new Sapling key
libzcash::SaplingPaymentAddress GenerateNewSaplingZKey(std::string label = "");
//! pindex is the new tip being connected.
void IncrementNoteWitnesses(const CBlockIndex* pindex,
const CBlock* pblock,
SaplingMerkleTree& saplingTree);
//! pindex is the old tip being disconnected.
void DecrementNoteWitnesses(const CBlockIndex* pindex);
//! Adds Sapling spending key to the store, and saves it to disk
bool AddSaplingZKey(const libzcash::SaplingExtendedSpendingKey &key);
bool AddSaplingIncomingViewingKeyW(
const libzcash::SaplingIncomingViewingKey &ivk,
const libzcash::SaplingPaymentAddress &addr);
bool AddCryptedSaplingSpendingKeyW(
const libzcash::SaplingExtendedFullViewingKey &extfvk,
const std::vector<unsigned char> &vchCryptedSecret);
//! Returns true if the wallet contains the spending key
bool HaveSpendingKeyForPaymentAddress(const libzcash::SaplingPaymentAddress &zaddr) const;
//! Adds spending key to the store, without saving it to disk (used by LoadWallet)
bool LoadSaplingZKey(const libzcash::SaplingExtendedSpendingKey &key);
//! Load spending key metadata (used by LoadWallet)
bool LoadSaplingZKeyMetadata(const libzcash::SaplingIncomingViewingKey &ivk, const CKeyMetadata &meta);
//! Adds a Sapling payment address -> incoming viewing key map entry,
//! without saving it to disk (used by LoadWallet)
bool LoadSaplingPaymentAddress(
const libzcash::SaplingPaymentAddress &addr,
const libzcash::SaplingIncomingViewingKey &ivk);
//! Adds an encrypted spending key to the store, without saving it to disk (used by LoadWallet)
bool LoadCryptedSaplingZKey(const libzcash::SaplingExtendedFullViewingKey &extfvk,
const std::vector<unsigned char> &vchCryptedSecret);
//////////// End Sapling //////////////
//! Adds a key to the store, and saves it to disk.
bool AddKeyPubKey(const CKey& key, const CPubKey& pubkey) override;
//! Adds a key to the store, without saving it to disk (used by LoadWallet)
bool LoadKey(const CKey& key, const CPubKey& pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
//! Load metadata (used by LoadWallet)
bool LoadKeyMetadata(const CPubKey& pubkey, const CKeyMetadata& metadata);
bool LoadMinVersion(int nVersion);
//! Adds an encrypted key to the store, and saves it to disk.
bool AddCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret) override;
//! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
bool LoadCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret);
bool AddCScript(const CScript& redeemScript) override;
bool LoadCScript(const CScript& redeemScript);
//! Adds a destination data tuple to the store, and saves it to disk
bool AddDestData(const CTxDestination& dest, const std::string& key, const std::string& value);
//! Erases a destination data tuple in the store and on disk
bool EraseDestData(const CTxDestination& dest, const std::string& key);
//! Adds a destination data tuple to the store, without saving it to disk
bool LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value);
//! Adds a watch-only address to the store, and saves it to disk.
bool AddWatchOnly(const CScript& dest) override;
bool RemoveWatchOnly(const CScript& dest) override;
//! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
bool LoadWatchOnly(const CScript& dest);
//! Lock Wallet
bool Lock();
bool Unlock(const SecureString& strWalletPassphrase, bool anonimizeOnly = false);
bool Unlock(const CKeyingMaterial& vMasterKeyIn);
bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
bool EncryptWallet(const SecureString& strWalletPassphrase);
std::vector<CKeyID> GetAffectedKeys(const CScript& spk);
void GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const;
/**
* Increment the next transaction order id
* @return next transaction order id
*/
int64_t IncOrderPosNext(CWalletDB* pwalletdb = NULL);
void MarkDirty();
bool AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose = true);
bool LoadToWallet(const CWalletTx& wtxIn);
void TransactionAddedToMempool(const CTransactionRef& tx) override;
void BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) override;
void BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) override;
bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, const uint256& blockHash, int posInBlock, bool fUpdate);
void EraseFromWallet(const uint256& hash);
/**
* Upgrade wallet to HD and Sapling if needed. Does nothing if not.
*/
bool Upgrade(std::string& error, const int& prevVersion);
bool ActivateSaplingWallet(bool memOnly = false);
int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false, bool fromStartup = false);
void ReacceptWalletTransactions(bool fFirstLoad = false);
void ResendWalletTransactions(CConnman* connman) override;
CAmount loopTxsBalance(std::function<void(const uint256&, const CWalletTx&, CAmount&)>method) const;
CAmount GetAvailableBalance(bool fIncludeDelegated = true, bool fIncludeShielded = true) const;
CAmount GetAvailableBalance(isminefilter& filter, bool useCache = false, int minDepth = 1) const;
CAmount GetColdStakingBalance() const; // delegated coins for which we have the staking key
CAmount GetImmatureColdStakingBalance() const;
CAmount GetStakingBalance(const bool fIncludeColdStaking = true) const;
CAmount GetDelegatedBalance() const; // delegated coins for which we have the spending key
CAmount GetImmatureDelegatedBalance() const;
CAmount GetLockedCoins() const;
CAmount GetUnconfirmedBalance(isminetype filter = ISMINE_SPENDABLE_ALL) const;
CAmount GetImmatureBalance() const;
CAmount GetWatchOnlyBalance() const;
CAmount GetUnconfirmedWatchOnlyBalance() const;
CAmount GetImmatureWatchOnlyBalance() const;
CAmount GetLegacyBalance(const isminefilter& filter, int minDepth) const;
bool FundTransaction(CMutableTransaction& tx, CAmount &nFeeRet, bool overrideEstimatedFeeRate, const CFeeRate& specificFeeRate, int& nChangePosInOut, std::string& strFailReason, bool includeWatching, bool lockUnspents, const CTxDestination& destChange = CNoDestination());
/**
* Create a new transaction paying the recipients with a set of coins
* selected by SelectCoins(); Also create the change output, when needed
* @note passing nChangePosInOut as -1 will result in setting a random position
*/
bool CreateTransaction(const std::vector<CRecipient>& vecSend,
CWalletTx* wtxNew,
CReserveKey& reservekey,
CAmount& nFeeRet,
int& nChangePosInOut,
std::string& strFailReason,
const CCoinControl* coinControl = NULL,
AvailableCoinsType coin_type = ALL_COINS,
bool sign = true,
CAmount nFeePay = 0,
bool fIncludeDelegated = false);
bool CreateTransaction(CScript scriptPubKey, const CAmount& nValue, CWalletTx* wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl = NULL, AvailableCoinsType coin_type = ALL_COINS, CAmount nFeePay = 0, bool fIncludeDelegated = false);
// enumeration for CommitResult (return status of CommitTransaction)
enum CommitStatus
{
OK,
Abandoned, // Failed to accept to memory pool. Successfully removed from the wallet.
NotAccepted, // Failed to accept to memory pool. Unable to abandon.
};
struct CommitResult
{
CommitResult(): status(CommitStatus::NotAccepted) {}
CWallet::CommitStatus status;
CValidationState state;
uint256 hashTx = UINT256_ZERO;
// converts CommitResult in human-readable format
std::string ToString() const;
};
CWallet::CommitResult CommitTransaction(CWalletTx& wtxNew, CReserveKey& opReservekey, CConnman* connman);
CWallet::CommitResult CommitTransaction(CWalletTx& wtxNew, CReserveKey* reservekey, CConnman* connman);
bool CreateCoinStake(const CKeyStore& keystore,
const CBlockIndex* pindexPrev,
unsigned int nBits,
CMutableTransaction& txNew,
int64_t& nTxNewTime,
std::vector<CStakeableOutput>* availableCoins);
bool MultiSend();
void AutoCombineDust(CConnman* connman);
// Shielded balances
CAmount GetAvailableShieldedBalance(bool fUseCache = true) const;
CAmount GetUnconfirmedShieldedBalance() const;
static CFeeRate minTxFee;
/**
* Estimate the minimum fee considering user set parameters
* and the required fee
*/
static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool);
/**
* Return the minimum required fee taking into account the
* floating relay fee and user set minimum transaction fee
*/
static CAmount GetRequiredFee(unsigned int nTxBytes);
size_t KeypoolCountExternalKeys();
bool TopUpKeyPool(unsigned int kpSize = 0);
void KeepKey(int64_t nIndex);
void ReturnKey(int64_t nIndex, const bool& internal = false, const bool& staking = false);
bool GetKeyFromPool(CPubKey& key, const uint8_t& type = HDChain::ChangeType::EXTERNAL);
int64_t GetOldestKeyPoolTime();
std::set<std::set<CTxDestination> > GetAddressGroupings();
std::map<CTxDestination, CAmount> GetAddressBalances();
std::set<CTxDestination> GetLabelAddresses(const std::string& label) const;
bool CreateBudgetFeeTX(CWalletTx& tx, const uint256& hash, CReserveKey& keyChange, bool fFinalization);
bool IsUsed(const CTxDestination address) const;
isminetype IsMine(const CTxIn& txin) const;
CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
isminetype IsMine(const CTxOut& txout) const;
CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
bool IsChange(const CTxOut& txout) const;
bool IsChange(const CTxDestination& address) const;
CAmount GetChange(const CTxOut& txout) const;
bool IsMine(const CTransaction& tx) const;
/** should probably be renamed to IsRelevantToMe */
bool IsFromMe(const CTransaction& tx) const;
CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
CAmount GetCredit(const CWalletTx& tx, const isminefilter& filter) const;
CAmount GetChange(const CTransaction& tx) const;
//! Sapling merkle tree update
void ChainTip(const CBlockIndex *pindex,
const CBlock *pblock,
Optional<SaplingMerkleTree> added) override;
void SetBestChain(const CBlockLocator& loc) override;
void SetBestChainInternal(CWalletDB& walletdb, const CBlockLocator& loc); // only public for testing purposes, must never be called directly in any other situation
// Force balance recomputation if any transaction got conflicted
void MarkAffectedTransactionsDirty(const CTransaction& tx); // only public for testing purposes, must never be called directly in any other situation
DBErrors LoadWallet(bool& fFirstRunRet);
DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
static std::string ParseIntoAddress(const CWDestination& dest, const std::string& purpose);
bool SetAddressBook(const CWDestination& address, const std::string& strName, const std::string& purpose);
bool DelAddressBook(const CWDestination& address, const CChainParams::Base58Type addrType = CChainParams::PUBKEY_ADDRESS);
bool HasAddressBook(const CWDestination& address) const;
bool HasDelegator(const CTxOut& out) const;
int GetAddressBookSize() const { return mapAddressBook.size(); };
CAddressBookIterator NewAddressBookIterator() { return CAddressBookIterator(mapAddressBook); }
std::string GetPurposeForAddressBookEntry(const CWDestination& address) const;
std::string GetNameForAddressBookEntry(const CWDestination& address) const;
Optional<AddressBook::CAddressBookData> GetAddressBookEntry(const CWDestination& address) const;
void LoadAddressBookName(const CWDestination& dest, const std::string& strName);
void LoadAddressBookPurpose(const CWDestination& dest, const std::string& strPurpose);
bool UpdatedTransaction(const uint256& hashTx) override;
unsigned int GetKeyPoolSize();
unsigned int GetStakingKeyPoolSize();
//! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
//! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
bool SetMaxVersion(int nVersion);
//! get the current wallet format (the oldest client version guaranteed to understand this wallet)
int GetVersion();
//! Get wallet transactions that conflict with given transaction (spend same outputs)
std::set<uint256> GetConflicts(const uint256& txid) const;
//! Verify the wallet database and perform salvage if required
static bool Verify();
/* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
bool AbandonTransaction(const uint256& hashTx);
/* Returns the wallets help message */
static std::string GetWalletHelpString(bool showDebug);
/* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
static CWallet* CreateWalletFromFile(const std::string walletFile);
static bool InitLoadWallet();
/* Wallets parameter interaction */
static bool ParameterInteraction();
/**
* Wallet post-init setup
* Gives the wallet a chance to register repetitive tasks and complete post-init tasks
*/
void postInitProcess(CScheduler& scheduler);
/**
* Address book entry changed.
* @note called with lock cs_wallet held.
*/
boost::signals2::signal<void(CWallet* wallet, const CWDestination& address, const std::string& label, bool isMine, const std::string& purpose, ChangeType status)> NotifyAddressBookChanged;
/**
* Wallet transaction added, removed or updated.
* @note called with lock cs_wallet held.
*/
boost::signals2::signal<void(CWallet* wallet, const uint256& hashTx, ChangeType status)> NotifyTransactionChanged;
/** Show progress e.g. for rescan */
boost::signals2::signal<void(const std::string& title, int nProgress)> ShowProgress;
/** Watch-only address added */
boost::signals2::signal<void(bool fHaveWatchOnly)> NotifyWatchonlyChanged;
/** notify wallet file backed up */
boost::signals2::signal<void (const bool& fSuccess, const std::string& filename)> NotifyWalletBacked;
};
/** A key allocated from the key pool. */
class CReserveKey
{
protected:
CWallet* pwallet;
int64_t nIndex;
bool internal{false};
CPubKey vchPubKey;
public:
CReserveKey(CWallet* pwalletIn)
{
nIndex = -1;
pwallet = pwalletIn;
}
~CReserveKey()
{
ReturnKey();
}
void ReturnKey();
bool GetReservedKey(CPubKey& pubkey, bool internal = false);
void KeepKey();
};
typedef std::map<std::string, std::string> mapValue_t;
static inline void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
{
if (!mapValue.count("n")) {
nOrderPos = -1; // TODO: calculate elsewhere
return;
}
nOrderPos = atoi64(mapValue["n"].c_str());
}
static inline void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
{
if (nOrderPos == -1)
return;
mapValue["n"] = i64tostr(nOrderPos);
}
struct COutputEntry {
CTxDestination destination;
CAmount amount;
int vout;
};
/** A transaction with a merkle branch linking it to the block chain. */
class CMerkleTx : public CTransaction
{
private:
/** Constant used in hashBlock to indicate tx has been abandoned */
static const uint256 ABANDON_HASH;
public:
uint256 hashBlock;
/* An nIndex == -1 means that hashBlock (in nonzero) refers to the earliest
* block in the chain we know this or any in-wallet dependency conflicts
* with. Older clients interpret nIndex == -1 as unconfirmed for backward
* compatibility.
*/
int nIndex;
CMerkleTx()
{
Init();
}
CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
{
Init();
}
void Init()
{
hashBlock = UINT256_ZERO;
nIndex = -1;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action)
{
std::vector<uint256> vMerkleBranch; // For compatibility with older versions.
READWRITE(*(CTransaction*)this);
READWRITE(hashBlock);
READWRITE(vMerkleBranch);
READWRITE(nIndex);
}
void SetMerkleBranch(const uint256& blockHash, int posInBlock);
/**
* Return depth of transaction in blockchain:
* <0 : conflicts with a transaction this deep in the blockchain
* 0 : in memory pool, waiting to be included in a block
* >=1 : this many blocks deep in the main chain
*/
int GetDepthInMainChain(const CBlockIndex*& pindexRet) const;
int GetDepthInMainChain() const;
bool IsInMainChain() const;
bool IsInMainChainImmature() const;
int GetBlocksToMaturity() const;
bool AcceptToMemoryPool(bool fLimitFree = true, bool fRejectInsaneFee = true, bool ignoreFees = false);
bool hashUnset() const { return (hashBlock.IsNull() || hashBlock == ABANDON_HASH); }
bool isAbandoned() const { return (hashBlock == ABANDON_HASH); }
void setAbandoned() { hashBlock = ABANDON_HASH; }
};
/**
* A transaction with a bunch of additional info that only the owner cares about.
* It includes any unrecorded transactions needed to link it back to the block chain.
*/
class CWalletTx : public CMerkleTx
{
private:
const CWallet* pwallet;
public:
mapValue_t mapValue;
mapSaplingNoteData_t mapSaplingNoteData;
std::vector<std::pair<std::string, std::string> > vOrderForm;
unsigned int fTimeReceivedIsTxTime;
unsigned int nTimeReceived; //! time received by this node
/**
* Stable timestamp representing the block time, for a transaction included in a block,
* or else the time when the transaction was received if it isn't yet part of a block.
*/
unsigned int nTimeSmart;
char fFromMe;
int64_t nOrderPos; //! position in ordered transaction list
// memory only
enum AmountType { DEBIT, CREDIT, IMMATURE_CREDIT, AVAILABLE_CREDIT, AMOUNTTYPE_ENUM_ELEMENTS };
CAmount GetCachableAmount(AmountType type, const isminefilter& filter, bool recalculate = false) const;
bool IsAmountCached(AmountType type, const isminefilter& filter) const; // Only used in unit tests
mutable CachableAmount m_amounts[AMOUNTTYPE_ENUM_ELEMENTS];
mutable bool fStakeDelegationVoided;
mutable bool fChangeCached;
mutable CAmount nChangeCached;
mutable bool fShieldedChangeCached;
mutable CAmount nShieldedChangeCached;
CWalletTx();
CWalletTx(const CWallet* pwalletIn);
CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn);
CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn);
void Init(const CWallet* pwalletIn);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action)
{
if (ser_action.ForRead())
Init(NULL);
char fSpent = false;
if (!ser_action.ForRead()) {
mapValue["fromaccount"] = "";
WriteOrderPos(nOrderPos, mapValue);
if (nTimeSmart)
mapValue["timesmart"] = strprintf("%u", nTimeSmart);
}
READWRITE(*(CMerkleTx*)this);
std::vector<CMerkleTx> vUnused; //! Used to be vtxPrev
READWRITE(vUnused);
READWRITE(mapValue);
READWRITE(vOrderForm);
READWRITE(fTimeReceivedIsTxTime);
READWRITE(nTimeReceived);
READWRITE(fFromMe);
READWRITE(fSpent);