forked from dashpay/dash
-
Notifications
You must be signed in to change notification settings - Fork 717
/
wallet.h
1051 lines (869 loc) · 39 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 "crypter.h"
#include "kernel.h"
#include "key.h"
#include "keystore.h"
#include "main.h"
#include "pairresult.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "zpiv/zerocoin.h"
#include "guiinterface.h"
#include "util.h"
#include "validationinterface.h"
#include "wallet/wallet_ismine.h"
#include "wallet/walletdb.h"
#include "zpiv/zpivmodule.h"
#include "zpiv/zpivwallet.h"
#include "zpiv/zpivtracker.h"
#include <algorithm>
#include <map>
#include <set>
#include <stdexcept>
#include <stdint.h>
#include <string>
#include <utility>
#include <vector>
/**
* Settings
*/
extern CFeeRate payTxFee;
extern CAmount maxTxFee;
extern unsigned int nTxConfirmTarget;
extern bool bSpendZeroConfChange;
extern bool bdisableSystemnotifications;
extern bool fSendFreeTransactions;
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;
//! -enableautoconvertaddress default
static const bool DEFAULT_AUTOCONVERTADDRESS = true;
// Zerocoin denomination which creates exactly one of each denominations:
// 6666 = 1*5000 + 1*1000 + 1*500 + 1*100 + 1*50 + 1*10 + 1*5 + 1
static const int ZQ_6666 = 6666;
class CAccountingEntry;
class CCoinControl;
class COutput;
class CReserveKey;
class CScript;
class CWalletTx;
/** (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_LATEST = 61000
};
enum AvailableCoinsType {
ALL_COINS = 1,
ONLY_DENOMINATED = 2,
ONLY_NOT10000IFMN = 3,
ONLY_NONDENOMINATED_NOT10000IFMN = 4, // ONLY_NONDENOMINATED and not 10000 PIV at the same time
ONLY_10000 = 5, // find masternode outputs including locked ones (use with caution)
STAKABLE_COINS = 6 // UTXO's that are valid for staking
};
// Possible states for zPIV send
enum ZerocoinSpendStatus {
ZPIV_SPEND_OKAY = 0, // No error
ZPIV_SPEND_ERROR = 1, // Unspecified class of errors, more details are (hopefully) in the returning text
ZPIV_WALLET_LOCKED = 2, // Wallet was locked
ZPIV_COMMIT_FAILED = 3, // Commit failed, reset status
ZPIV_ERASE_SPENDS_FAILED = 4, // Erasing spends during reset failed
ZPIV_ERASE_NEW_MINTS_FAILED = 5, // Erasing new mints during reset failed
ZPIV_TRX_FUNDS_PROBLEMS = 6, // Everything related to available funds
ZPIV_TRX_CREATE = 7, // Everything related to create the transaction
ZPIV_TRX_CHANGE = 8, // Everything related to transaction change
ZPIV_TXMINT_GENERAL = 9, // General errors in MintToTxIn
ZPIV_INVALID_COIN = 10, // Selected mint coin is not valid
ZPIV_FAILED_ACCUMULATOR_INITIALIZATION = 11, // Failed to initialize witness
ZPIV_INVALID_WITNESS = 12, // Spend coin transaction did not verify
ZPIV_BAD_SERIALIZATION = 13, // Transaction verification failed
ZPIV_SPENT_USED_ZPIV = 14, // Coin has already been spend
ZPIV_TX_TOO_LARGE = 15, // The transaction is larger than the max tx size
ZPIV_SPEND_V1_SEC_LEVEL // Spend is V1 and security level is not set to 100
};
struct CompactTallyItem {
CBitcoinAddress address;
CAmount nAmount;
std::vector<CTxIn> vecTxIn;
CompactTallyItem()
{
nAmount = 0;
}
};
/** A key pool entry */
class CKeyPool
{
public:
int64_t nTime;
CPubKey vchPubKey;
CKeyPool();
CKeyPool(const CPubKey& vchPubKeyIn);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(nTime);
READWRITE(vchPubKey);
}
};
/** Record info about last kernel stake operation (time and chainTip)**/
class CStakerStatus {
private:
const CBlockIndex* tipLastStakeAttempt = nullptr;
int64_t timeLastStakeAttempt;
public:
const CBlockIndex* GetLastTip() const { return tipLastStakeAttempt; }
uint256 GetLastHash() const
{
return (tipLastStakeAttempt == nullptr ? 0 : tipLastStakeAttempt->GetBlockHash());
}
int64_t GetLastTime() const { return timeLastStakeAttempt; }
void SetLastTip(const CBlockIndex* lastTip) { tipLastStakeAttempt = lastTip; }
void SetLastTime(const uint64_t lastTime) { timeLastStakeAttempt = lastTime; }
void SetNull()
{
SetLastTip(nullptr);
SetLastTime(0);
}
bool IsActive() { return (timeLastStakeAttempt + 30) >= GetTime(); }
};
/**
* 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:
bool SelectCoins(const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl = NULL, AvailableCoinsType coin_type = ALL_COINS, bool useIX = true, bool fIncludeColdStaking=false, bool fIncludeDelegated=true) const;
//it was public bool SelectCoins(int64_t nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl *coinControl = NULL, AvailableCoinsType coin_type=ALL_COINS, bool useIX = true) const;
CWalletDB* pwalletdbEncryption;
//! 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;
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 std::multimap<COutPoint, uint256> 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);
void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>);
public:
static const int STAKE_SPLIT_THRESHOLD = 2000;
bool MintableCoins();
bool SelectStakeCoins(std::list<std::unique_ptr<CStakeInput> >& listInputs, CAmount nTargetAmount, int blockHeight);
bool IsCollateralAmount(CAmount nInputAmount) const;
// Zerocoin additions
bool CreateZerocoinMintTransaction(const CAmount nValue, CMutableTransaction& txNew, std::vector<CDeterministicMint>& vDMints, CReserveKey* reservekey, int64_t& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl = NULL, const bool isZCSpendChange = false);
bool CreateZerocoinSpendTransaction(
CAmount nValue,
CWalletTx& wtxNew,
CReserveKey& reserveKey,
CZerocoinSpendReceipt& receipt,
std::vector<CZerocoinMint>& vSelectedMints,
std::vector<CDeterministicMint>& vNewMints,
bool fMintChange,
bool fMinimizeChange,
std::list<std::pair<CBitcoinAddress*,CAmount>> addressesTo,
CBitcoinAddress* changeAddress = nullptr,
bool isPublicSpend = true);
bool CheckCoinSpend(libzerocoin::CoinSpend& spend, libzerocoin::Accumulator& accumulator, CZerocoinSpendReceipt& receipt);
bool MintToTxIn(CZerocoinMint zerocoinSelected, const uint256& hashTxOut, CTxIn& newTxIn, CZerocoinSpendReceipt& receipt, libzerocoin::SpendType spendType, CBlockIndex* pindexCheckpoint = nullptr, bool isPublicSpend = true);
bool MintsToInputVector(std::map<CBigNum, CZerocoinMint>& mapMintsSelected, const uint256& hashTxOut, std::vector<CTxIn>& vin,
CZerocoinSpendReceipt& receipt, libzerocoin::SpendType spendType, CBlockIndex* pindexCheckpoint = nullptr);
// Public coin spend input creation
bool MintsToInputVectorPublicSpend(std::map<CBigNum, CZerocoinMint>& mapMintsSelected, const uint256& hashTxOut, std::vector<CTxIn>& vin,
CZerocoinSpendReceipt& receipt, libzerocoin::SpendType spendType, CBlockIndex* pindexCheckpoint = nullptr);
std::string MintZerocoinFromOutPoint(CAmount nValue, CWalletTx& wtxNew, std::vector<CDeterministicMint>& vDMints, const std::vector<COutPoint> vOutpts);
std::string MintZerocoin(CAmount nValue, CWalletTx& wtxNew, std::vector<CDeterministicMint>& vDMints, const CCoinControl* coinControl = NULL);
bool SpendZerocoin(
CAmount nAmount,
CWalletTx& wtxNew,
CZerocoinSpendReceipt& receipt,
std::vector<CZerocoinMint>& vMintsSelected,
bool fMintChange,
bool fMinimizeChange,
std::list<std::pair<CBitcoinAddress*,CAmount>> addressesTo,
CBitcoinAddress* changeAddress = nullptr,
bool isPublicSpend = true
);
std::string ResetMintZerocoin();
std::string ResetSpentZerocoin();
void ReconsiderZerocoins(std::list<CZerocoinMint>& listMintsRestored, std::list<CDeterministicMint>& listDMintsRestored);
void ZPivBackupWallet();
bool GetZerocoinKey(const CBigNum& bnSerial, CKey& key);
bool CreateZPIVOutPut(libzerocoin::CoinDenomination denomination, CTxOut& outMint, CDeterministicMint& dMint);
bool GetMint(const uint256& hashSerial, CZerocoinMint& mint);
bool GetMintFromStakeHash(const uint256& hashStake, CZerocoinMint& mint);
bool DatabaseMint(CDeterministicMint& dMint);
bool SetMintUnspent(const CBigNum& bnSerial);
bool UpdateMint(const CBigNum& bnValue, const int& nHeight, const uint256& txid, const libzerocoin::CoinDenomination& denom);
std::string GetUniqueWalletBackupName(bool fzpivAuto) const;
void InitAutoConvertAddresses();
/** Zerocin entry changed.
* @note called with lock cs_wallet held.
*/
boost::signals2::signal<void(CWallet* wallet, const std::string& pubCoin, const std::string& isUsed, ChangeType status)> NotifyZerocoinChanged;
/*
* Main wallet lock.
* This lock protects all the fields added by CWallet
* except for:
* fFileBacked (immutable after instantiation)
* strWalletFile (immutable after instantiation)
*/
mutable CCriticalSection cs_wallet;
CzPIVWallet* zwalletMain;
std::set<CBitcoinAddress> setAutoConvertAddresses;
bool fFileBacked;
bool fWalletUnlockAnonymizeOnly;
std::string strWalletFile;
bool fBackupMints;
std::unique_ptr<CzPIVTracker> zpivTracker;
std::set<int64_t> setKeyPool;
std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
MasterKeyMap mapMasterKeys;
unsigned int nMasterKeyMaxID;
// Stake Settings
uint64_t nStakeSplitThreshold;
int nStakeSetUpdateTime;
CStakerStatus* pStakerStatus = nullptr;
//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;
CWallet();
CWallet(std::string strWalletFileIn);
~CWallet();
void SetNull();
int getZeromintPercentage();
void setZWallet(CzPIVWallet* zwallet);
CzPIVWallet* getZWallet();
bool isZeromintEnabled();
void setZPivAutoBackups(bool fEnabled);
bool isMultiSendEnabled();
void setMultiSendDisabled();
std::map<uint256, CWalletTx> mapWallet;
std::list<CAccountingEntry> laccentries;
typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef std::multimap<int64_t, TxPair > TxItems;
TxItems wtxOrdered;
int64_t nOrderPosNext;
std::map<uint256, int> mapRequestCount;
std::map<CTxDestination, AddressBook::CAddressBookData> mapAddressBook;
std::set<COutPoint> setLockedCoins;
int64_t nTimeFirstKey;
const CWalletTx* GetWalletTx(const uint256& hash) const;
std::vector<CWalletTx> getWalletTxs();
//! check whether we are allowed to upgrade (or already support) to the named feature
bool CanSupportFeature(enum WalletFeature wf);
void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed = true, const CCoinControl* coinControl = NULL, bool fIncludeZeroValue = false, AvailableCoinsType nCoinType = ALL_COINS, bool fUseIX = false, int nWatchonlyConfig = 1, bool fIncludeColdStaking=false, bool fIncludeDelegated=true) const;
// Get available p2cs utxo
void GetAvailableP2CSCoins(std::vector<COutput>& vCoins) const;
std::map<CBitcoinAddress, std::vector<COutput> > AvailableCoinsByAddress(bool fConfirmed = true, CAmount maxCoinValue = 0);
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;
/// 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 = "");
/// Extract txin information and keys from output
bool GetVinAndKeysFromOutput(COutput out, CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet, bool fColdStake = false);
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();
void ListLockedCoins(std::vector<COutPoint>& vOutpts);
// keystore implementation
// Generate a new key
CPubKey GenerateNewKey();
PairResult getNewAddress(CBitcoinAddress& ret, const std::string addressLabel, const std::string purpose,
const CChainParams::Base58Type addrType = CChainParams::PUBKEY_ADDRESS);
PairResult getNewAddress(CBitcoinAddress& ret, std::string label);
PairResult getNewStakingAddress(CBitcoinAddress& ret, std::string label);
CBitcoinAddress GenerateNewAutoMintKey();
int64_t GetKeyCreationTime(CPubKey pubkey);
int64_t GetKeyCreationTime(const CBitcoinAddress& address);
//! Adds a key to the store, and saves it to disk.
bool AddKeyPubKey(const CKey& key, const CPubKey& pubkey);
//! 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);
//! 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);
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);
bool RemoveWatchOnly(const CScript& dest);
//! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
bool LoadWatchOnly(const CScript& dest);
//! Adds a MultiSig address to the store, and saves it to disk.
bool AddMultiSig(const CScript& dest);
bool RemoveMultiSig(const CScript& dest);
//! Adds a MultiSig address to the store, without saving it to disk (used by LoadWallet)
bool LoadMultiSig(const CScript& dest);
bool Unlock(const SecureString& strWalletPassphrase, bool anonimizeOnly = false);
bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
bool EncryptWallet(const SecureString& strWalletPassphrase);
void GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const;
unsigned int ComputeTimeSmart(const CWalletTx& wtx) 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 fFromLoadWallet, CWalletDB* pwalletdb);
void SyncTransaction(const CTransaction& tx, const CBlock* pblock);
bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate);
void EraseFromWallet(const uint256& hash);
int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false, bool fromStartup = false);
void ReacceptWalletTransactions(bool fFirstLoad = false);
void ResendWalletTransactions();
CAmount loopTxsBalance(std::function<void(const uint256&, const CWalletTx&, CAmount&)>method) const;
CAmount GetBalance() 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 GetZerocoinBalance(bool fMatureOnly) const;
CAmount GetUnconfirmedZerocoinBalance() const;
CAmount GetImmatureZerocoinBalance() const;
CAmount GetLockedCoins() const;
CAmount GetUnlockedCoins() const;
std::map<libzerocoin::CoinDenomination, CAmount> GetMyZerocoinDistribution() const;
CAmount GetUnconfirmedBalance() const;
CAmount GetImmatureBalance() const;
CAmount GetWatchOnlyBalance() const;
CAmount GetUnconfirmedWatchOnlyBalance() const;
CAmount GetImmatureWatchOnlyBalance() const;
CAmount GetLockedWatchOnlyBalance() const;
bool CreateTransaction(const std::vector<std::pair<CScript, CAmount> >& vecSend,
CWalletTx& wtxNew,
CReserveKey& reservekey,
CAmount& nFeeRet,
std::string& strFailReason,
const CCoinControl* coinControl = NULL,
AvailableCoinsType coin_type = ALL_COINS,
bool useIX = false,
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, bool useIX = false, CAmount nFeePay = 0, bool fIncludeDelegated = false);
bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, std::string strCommand = "tx");
bool AddAccountingEntry(const CAccountingEntry&, CWalletDB & pwalletdb);
int GenerateObfuscationOutputs(int nTotalValue, std::vector<CTxOut>& vout);
bool CreateCoinStake(const CKeyStore& keystore, const CBlockIndex* pindexPrev, unsigned int nBits, CMutableTransaction& txNew, int64_t& nTxNewTime);
bool MultiSend();
void AutoCombineDust();
void AutoZeromint();
void AutoZeromintForAddress();
void CreateAutoMintTransaction(const CAmount& nMintAmount, CCoinControl* coinControl = nullptr);
static CFeeRate minTxFee;
static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool);
bool NewKeyPool();
bool TopUpKeyPool(unsigned int kpSize = 0);
void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
void KeepKey(int64_t nIndex);
void ReturnKey(int64_t nIndex);
bool GetKeyFromPool(CPubKey& key);
int64_t GetOldestKeyPoolTime();
void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
std::set<std::set<CTxDestination> > GetAddressGroupings();
std::map<CTxDestination, CAmount> GetAddressBalances();
std::set<CTxDestination> GetAccountAddresses(std::string strAccount) const;
bool GetBudgetSystemCollateralTX(CWalletTx& tx, uint256 hash, bool useIX);
bool GetBudgetFinalizationCollateralTX(CWalletTx& tx, uint256 hash, bool useIX); // Only used for budget finalization
bool IsDenominated(const CTxIn& txin) const;
bool IsDenominatedAmount(CAmount nInputAmount) const;
bool IsUsed(const CBitcoinAddress address) const;
isminetype IsMine(const CTxIn& txin) const;
CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
isminetype IsMine(const CTxOut& txout) const;
bool IsMyZerocoinSpend(const CBigNum& bnSerial) const;
bool IsMyMint(const CBigNum& bnValue) const;
CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
bool IsChange(const CTxOut& txout) 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 CTransaction& tx, const isminefilter& filter, const bool fUnspent = false) const;
CAmount GetChange(const CTransaction& tx) const;
void SetBestChain(const CBlockLocator& loc);
DBErrors LoadWallet(bool& fFirstRunRet);
DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
static CBitcoinAddress ParseIntoAddress(const CTxDestination& dest, const std::string& purpose);
bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
bool DelAddressBook(const CTxDestination& address, const CChainParams::Base58Type addrType = CChainParams::PUBKEY_ADDRESS);
bool HasAddressBook(const CTxDestination& address) const;
bool HasDelegator(const CTxOut& out) const;
std::string purposeForAddress(const CTxDestination& address) const;
bool UpdatedTransaction(const uint256& hashTx);
void Inventory(const uint256& hash);
unsigned int GetKeyPoolSize();
//! 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;
/* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
bool AbandonTransaction(const uint256& hashTx);
/**
* Address book entry changed.
* @note called with lock cs_wallet held.
*/
boost::signals2::signal<void(CWallet* wallet, const CTxDestination& 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;
/** MultiSig address added */
boost::signals2::signal<void(bool fHaveMultiSig)> NotifyMultiSigChanged;
/** zPIV reset */
boost::signals2::signal<void()> NotifyzPIVReset;
/** 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;
CPubKey vchPubKey;
public:
CReserveKey(CWallet* pwalletIn)
{
nIndex = -1;
pwallet = pwalletIn;
}
~CReserveKey()
{
ReturnKey();
}
void ReturnKey();
bool GetReservedKey(CPubKey& pubkey);
void KeepKey();
};
typedef std::map<std::string, std::string> mapValue_t;
static 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 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 = 0;
nIndex = -1;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
std::vector<uint256> vMerkleBranch; // For compatibility with older versions.
READWRITE(*(CTransaction*)this);
nVersion = this->nVersion;
READWRITE(hashBlock);
READWRITE(vMerkleBranch);
READWRITE(nIndex);
}
int SetMerkleBranch(const CBlock& block);
/**
* 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, bool enableIX = true) const;
int GetDepthInMainChain(bool enableIX = true) const
{
const CBlockIndex* pindexRet;
return GetDepthInMainChain(pindexRet, enableIX);
}
bool IsInMainChain() const
{
const CBlockIndex* pindexRet;
return GetDepthInMainChain(pindexRet, false) > 0;
}
int GetBlocksToMaturity() const;
bool AcceptToMemoryPool(bool fLimitFree = true, bool fRejectInsaneFee = true, bool ignoreFees = false);
int GetTransactionLockSignatures() const;
bool IsTransactionLockTimedOut() const;
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;
std::vector<std::pair<std::string, std::string> > vOrderForm;
unsigned int fTimeReceivedIsTxTime;
unsigned int nTimeReceived; //! time received by this node
unsigned int nTimeSmart;
char fFromMe;
std::string strFromAccount;
int64_t nOrderPos; //! position in ordered transaction list
// memory only
mutable bool fDebitCached;
mutable bool fCreditCached;
mutable bool fImmatureCreditCached;
mutable bool fAvailableCreditCached;
mutable bool fAnonymizableCreditCached;
mutable bool fAnonymizedCreditCached;
mutable bool fDenomUnconfCreditCached;
mutable bool fDenomConfCreditCached;
mutable bool fWatchDebitCached;
mutable bool fWatchCreditCached;
mutable bool fImmatureWatchCreditCached;
mutable bool fAvailableWatchCreditCached;
mutable bool fChangeCached;
mutable bool fColdDebitCached;
mutable bool fColdCreditCached;
mutable bool fDelegatedDebitCached;
mutable bool fDelegatedCreditCached;
mutable bool fStakeDelegationVoided;
mutable CAmount nDebitCached;
mutable CAmount nCreditCached;
mutable CAmount nImmatureCreditCached;
mutable CAmount nAvailableCreditCached;
mutable CAmount nAnonymizableCreditCached;
mutable CAmount nAnonymizedCreditCached;
mutable CAmount nDenomUnconfCreditCached;
mutable CAmount nDenomConfCreditCached;
mutable CAmount nWatchDebitCached;
mutable CAmount nWatchCreditCached;
mutable CAmount nImmatureWatchCreditCached;
mutable CAmount nAvailableWatchCreditCached;
mutable CAmount nChangeCached;
mutable CAmount nColdDebitCached;
mutable CAmount nColdCreditCached;
mutable CAmount nDelegatedDebitCached;
mutable CAmount nDelegatedCreditCached;
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, int nType, int nVersion)
{
if (ser_action.ForRead())
Init(NULL);
char fSpent = false;
if (!ser_action.ForRead()) {
mapValue["fromaccount"] = strFromAccount;
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);
if (ser_action.ForRead()) {
strFromAccount = mapValue["fromaccount"];
ReadOrderPos(nOrderPos, mapValue);
nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
}
mapValue.erase("fromaccount");
mapValue.erase("version");
mapValue.erase("spent");
mapValue.erase("n");
mapValue.erase("timesmart");
}
//! make sure balances are recalculated
void MarkDirty();
void BindWallet(CWallet* pwalletIn);
//! checks whether a tx has P2CS inputs or not
bool HasP2CSInputs() const;
int GetDepthAndMempool(bool& fConflicted, bool enableIX = true) const;
//! filter decides which addresses will count towards the debit
CAmount GetDebit(const isminefilter& filter) const;
CAmount GetCredit(const isminefilter& filter) const;
CAmount GetUnspentCredit(const isminefilter& filter) const;
CAmount GetImmatureCredit(bool fUseCache = true, const isminefilter& filter = ISMINE_SPENDABLE_ALL) const;
CAmount GetAvailableCredit(bool fUseCache = true) const;
// Return sum of unlocked coins
CAmount GetUnlockedCredit() const;
// Return sum of unlocked coins
CAmount GetLockedCredit() const;
CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache = true) const;
CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache = true) const;
CAmount GetLockedWatchOnlyCredit() const;
CAmount GetChange() const;
// Cold staking contracts credit/debit
CAmount GetColdStakingCredit(bool fUseCache = true) const;
CAmount GetColdStakingDebit(bool fUseCache = true) const;
CAmount GetStakeDelegationCredit(bool fUseCache = true) const;
CAmount GetStakeDelegationDebit(bool fUseCache = true) const;
// Helper method to update the amount and cacheFlag.
CAmount UpdateAmount(CAmount& amountToUpdate, bool& cacheFlagToUpdate, bool fUseCache, isminetype mimeType, bool fCredit = true) const;
void GetAmounts(std::list<COutputEntry>& listReceived,
std::list<COutputEntry>& listSent,
CAmount& nFee,
std::string& strSentAccount,
const isminefilter& filter) const;
void GetAccountAmounts(const std::string& strAccount, CAmount& nReceived, CAmount& nSent, CAmount& nFee, const isminefilter& filter) const;
bool IsFromMe(const isminefilter& filter) const;
bool InMempool() const;
// True if only scriptSigs are different
bool IsEquivalentTo(const CWalletTx& tx) const;
bool IsTrusted() const;
bool IsTrusted(int& nDepth, bool& fConflicted) const;
bool WriteToDisk(CWalletDB *pwalletdb);
int64_t GetTxTime() const;
int64_t GetComputedTxTime() const;
int GetRequestCount() const;
void RelayWalletTransaction(std::string strCommand = "tx");
std::set<uint256> GetConflicts() const;
};
class COutput
{
public:
const CWalletTx* tx;
int i;
int nDepth;
bool fSpendable;
COutput(const CWalletTx* txIn, int iIn, int nDepthIn, bool fSpendableIn)
{
tx = txIn;
i = iIn;
nDepth = nDepthIn;
fSpendable = fSpendableIn;
}
//Used with Obfuscation. Will return largest nondenom, then denominations, then very small inputs
int Priority() const
{
for (CAmount d : obfuScationDenominations)
if (tx->vout[i].nValue == d) return 10000;
if (tx->vout[i].nValue < 1 * COIN) return 20000;
//nondenom return largest first
return -(tx->vout[i].nValue / COIN);
}
CAmount Value() const
{
return tx->vout[i].nValue;
}
std::string ToString() const;
};
/** Private key that includes an expiration date in case it never gets used. */
class CWalletKey
{
public:
CPrivKey vchPrivKey;
int64_t nTimeCreated;
int64_t nTimeExpires;
std::string strComment;
//! todo: add something to note what created it (user, getnewaddress, change)
//! maybe should have a map<string, string> property map
CWalletKey(int64_t nExpires = 0);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vchPrivKey);
READWRITE(nTimeCreated);
READWRITE(nTimeExpires);
READWRITE(LIMITED_STRING(strComment, 65536));
}
};
/**
* Account information.
* Stored in wallet with key "acc"+string account name.
*/
class CAccount
{
public:
CPubKey vchPubKey;
CAccount()
{
SetNull();
}
void SetNull()
{
vchPubKey = CPubKey();
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vchPubKey);
}
};
/**
* Internal transfers.
* Database key is acentry<account><counter>.
*/
class CAccountingEntry
{
public:
std::string strAccount;
CAmount nCreditDebit;
int64_t nTime;
std::string strOtherAccount;
std::string strComment;
mapValue_t mapValue;
int64_t nOrderPos; //! position in ordered transaction list
uint64_t nEntryNo;
CAccountingEntry()
{
SetNull();
}
void SetNull()
{
nCreditDebit = 0;
nTime = 0;
strAccount.clear();
strOtherAccount.clear();
strComment.clear();