]> Git Repo - VerusCoin.git/blame - src/wallet.h
Move SendMoney() to rpcwallet.cpp.
[VerusCoin.git] / src / wallet.h
CommitLineData
b2120e22 1// Copyright (c) 2009-2010 Satoshi Nakamoto
5b40d886
MF
2// Copyright (c) 2009-2014 The Bitcoin developers
3// Distributed under the MIT software license, see the accompanying
3a25a2b9 4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
093303a8 5
e8ef3da7
WL
6#ifndef BITCOIN_WALLET_H
7#define BITCOIN_WALLET_H
8
eda37330 9#include "amount.h"
99f41b9c 10#include "core/block.h"
4a3587d8 11#include "core/transaction.h"
51ed9ec9 12#include "crypter.h"
e8ef3da7 13#include "key.h"
2a45a494 14#include "keystore.h"
51ed9ec9 15#include "main.h"
ab1b288f 16#include "ui_interface.h"
611116d4 17#include "wallet_ismine.h"
51ed9ec9
BD
18#include "walletdb.h"
19
20#include <algorithm>
21#include <map>
22#include <set>
23#include <stdexcept>
24#include <stdint.h>
25#include <string>
26#include <utility>
27#include <vector>
e8ef3da7 28
5b40d886
MF
29/**
30 * Settings
31 */
c6cb21d1 32extern CFeeRate payTxFee;
b33d1f5e 33extern unsigned int nTxConfirmTarget;
1bbca249 34extern bool bSpendZeroConfChange;
0ed9675b 35extern bool fSendFreeTransactions;
ed3e5e46 36extern bool fPayAtLeastCustomFee;
cd7fa8bb 37
5b40d886 38//! -paytxfee default
a372168e 39static const CAmount DEFAULT_TRANSACTION_FEE = 0;
5b40d886 40//! -paytxfee will warn if called with a higher fee than this amount (in satoshis) per KB
a372168e 41static const CAmount nHighTransactionFeeWarning = 0.01 * COIN;
5b40d886 42//! Largest (in bytes) free transaction we're willing to create
b33d1f5e 43static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE = 1000;
ffeb4736 44
c3f95ef1 45class CAccountingEntry;
0689f46c 46class CCoinControl;
9b0369c7 47class COutput;
51ed9ec9
BD
48class CReserveKey;
49class CScript;
50class CWalletTx;
e8ef3da7 51
6b8de05d 52/** (client) version numbers for particular wallet features */
439e1497
PW
53enum WalletFeature
54{
55 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
56
57 FEATURE_WALLETCRYPT = 40000, // wallet encryption
58 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
59
60 FEATURE_LATEST = 60000
61};
62
ed6d0b5f
PW
63
64/** A key pool entry */
65class CKeyPool
66{
67public:
51ed9ec9 68 int64_t nTime;
fd61d6f5 69 CPubKey vchPubKey;
ed6d0b5f 70
af8297c0
WL
71 CKeyPool();
72 CKeyPool(const CPubKey& vchPubKeyIn);
ed6d0b5f 73
3f6540ad 74 ADD_SERIALIZE_METHODS;
3d796f89 75
84881f8c 76 template <typename Stream, typename Operation>
31e9a838 77 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
ed6d0b5f
PW
78 if (!(nType & SER_GETHASH))
79 READWRITE(nVersion);
80 READWRITE(nTime);
81 READWRITE(vchPubKey);
3d796f89 82 }
ed6d0b5f
PW
83};
84
61885513
GA
85/** Address book data */
86class CAddressBookData
87{
88public:
89 std::string name;
a41d5fe0 90 std::string purpose;
61885513
GA
91
92 CAddressBookData()
93 {
a41d5fe0 94 purpose = "unknown";
61885513 95 }
b10e1470
WL
96
97 typedef std::map<std::string, std::string> StringMap;
98 StringMap destdata;
61885513
GA
99};
100
5b40d886
MF
101/**
102 * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
6b8de05d
PW
103 * and provides the ability to create new transactions.
104 */
a96d1139 105class CWallet : public CCryptoKeyStore, public CValidationInterface
e8ef3da7
WL
106{
107private:
a372168e 108 bool SelectCoins(const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = NULL) const;
e8ef3da7 109
96f34cd5 110 CWalletDB *pwalletdbEncryption;
e8ef3da7 111
5b40d886 112 //! the current wallet version: clients below this version are not able to load the wallet
0b807a41
PW
113 int nWalletVersion;
114
5b40d886 115 //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
439e1497
PW
116 int nWalletMaxVersion;
117
51ed9ec9
BD
118 int64_t nNextResend;
119 int64_t nLastResend;
203d1ae6 120
5b40d886
MF
121 /**
122 * Used to keep track of spent outpoints, and
123 * detect and report conflicts (double-spends or
124 * mutated transactions where the mutant gets mined).
125 */
93a18a36
GA
126 typedef std::multimap<COutPoint, uint256> TxSpends;
127 TxSpends mapTxSpends;
128 void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
129 void AddToSpends(const uint256& wtxid);
130
131 void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>);
731b89b8 132
e8ef3da7 133public:
5b40d886
MF
134 /*
135 * Main wallet lock.
136 * This lock protects all the fields added by CWallet
137 * except for:
138 * fFileBacked (immutable after instantiation)
139 * strWalletFile (immutable after instantiation)
140 */
6cc4a62c
GA
141 mutable CCriticalSection cs_wallet;
142
e8ef3da7
WL
143 bool fFileBacked;
144 std::string strWalletFile;
145
51ed9ec9 146 std::set<int64_t> setKeyPool;
4addb2c0 147 std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
0b807a41 148
4e87d341
MC
149 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
150 MasterKeyMap mapMasterKeys;
151 unsigned int nMasterKeyMaxID;
152
e8ef3da7
WL
153 CWallet()
154 {
d04fd3e2 155 SetNull();
e8ef3da7 156 }
870da77d 157
e8ef3da7
WL
158 CWallet(std::string strWalletFileIn)
159 {
d04fd3e2
JG
160 SetNull();
161
e8ef3da7
WL
162 strWalletFile = strWalletFileIn;
163 fFileBacked = true;
d04fd3e2 164 }
870da77d
PK
165
166 ~CWallet()
167 {
168 delete pwalletdbEncryption;
169 pwalletdbEncryption = NULL;
170 }
171
d04fd3e2
JG
172 void SetNull()
173 {
174 nWalletVersion = FEATURE_BASE;
175 nWalletMaxVersion = FEATURE_BASE;
176 fFileBacked = false;
4e87d341 177 nMasterKeyMaxID = 0;
96f34cd5 178 pwalletdbEncryption = NULL;
da7b8c12 179 nOrderPosNext = 0;
c4316fef
PW
180 nNextResend = 0;
181 nLastResend = 0;
d04fd3e2 182 nTimeFirstKey = 0;
e8ef3da7
WL
183 }
184
e8ef3da7 185 std::map<uint256, CWalletTx> mapWallet;
731b89b8 186
51ed9ec9 187 int64_t nOrderPosNext;
e8ef3da7 188 std::map<uint256, int> mapRequestCount;
e8ef3da7 189
61885513 190 std::map<CTxDestination, CAddressBookData> mapAddressBook;
e8ef3da7 191
fd61d6f5 192 CPubKey vchDefaultKey;
e8ef3da7 193
fdbb537d
JG
194 std::set<COutPoint> setLockedCoins;
195
51ed9ec9 196 int64_t nTimeFirstKey;
3869fb89 197
93a18a36
GA
198 const CWalletTx* GetWalletTx(const uint256& hash) const;
199
5b40d886 200 //! check whether we are allowed to upgrade (or already support) to the named feature
95691680 201 bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
439e1497 202
0689f46c 203 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl = NULL) const;
a372168e 204 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;
95691680 205
93a18a36
GA
206 bool IsSpent(const uint256& hash, unsigned int n) const;
207
fdbb537d
JG
208 bool IsLockedCoin(uint256 hash, unsigned int n) const;
209 void LockCoin(COutPoint& output);
210 void UnlockCoin(COutPoint& output);
211 void UnlockAllCoins();
212 void ListLockedCoins(std::vector<COutPoint>& vOutpts);
9b0369c7 213
5b40d886
MF
214 /**
215 * keystore implementation
216 * Generate a new key
217 */
fd61d6f5 218 CPubKey GenerateNewKey();
5b40d886 219 //! Adds a key to the store, and saves it to disk.
4addb2c0 220 bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey);
5b40d886 221 //! Adds a key to the store, without saving it to disk (used by LoadWallet)
dfa23b94 222 bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
5b40d886 223 //! Load metadata (used by LoadWallet)
4addb2c0 224 bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
d825e6a3 225
95691680 226 bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
0b807a41 227
5b40d886 228 //! Adds an encrypted key to the store, and saves it to disk.
4addb2c0 229 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
5b40d886 230 //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
2f15e86a 231 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
922e8e29 232 bool AddCScript(const CScript& redeemScript);
18116b06 233 bool LoadCScript(const CScript& redeemScript);
4e87d341 234
5b40d886 235 //! Adds a destination data tuple to the store, and saves it to disk
b10e1470 236 bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
5b40d886 237 //! Erases a destination data tuple in the store and on disk
b10e1470 238 bool EraseDestData(const CTxDestination &dest, const std::string &key);
5b40d886 239 //! Adds a destination data tuple to the store, without saving it to disk
b10e1470 240 bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
5b40d886 241 //! Look up a destination data tuple in the store, return true if found false otherwise
b10e1470
WL
242 bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
243
5b40d886 244 //! Adds a watch-only address to the store, and saves it to disk.
d5087d1b 245 bool AddWatchOnly(const CScript &dest);
ccca27a7 246 bool RemoveWatchOnly(const CScript &dest);
5b40d886 247 //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
d5087d1b 248 bool LoadWatchOnly(const CScript &dest);
c8988460 249
94f778bd
DN
250 bool Unlock(const SecureString& strWalletPassphrase);
251 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
252 bool EncryptWallet(const SecureString& strWalletPassphrase);
acd65016 253
51ed9ec9 254 void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const;
434e4273 255
5b40d886
MF
256 /**
257 * Increment the next transaction order id
258 * @return next transaction order id
da7b8c12 259 */
51ed9ec9 260 int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
da7b8c12 261
c3f95ef1 262 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
51ed9ec9 263 typedef std::multimap<int64_t, TxPair > TxItems;
ddb709e9 264
5b40d886
MF
265 /**
266 * Get the wallet's activity log
267 * @return multimap of ordered transactions and accounting entries
268 * @warning Returned pointers are *only* valid within the scope of passed acentries
ddb709e9
LD
269 */
270 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
c3f95ef1 271
95d888a6 272 void MarkDirty();
731b89b8 273 bool AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet=false);
d38da59b
PW
274 void SyncTransaction(const CTransaction& tx, const CBlock* pblock);
275 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate);
00588c3f 276 void EraseFromWallet(const uint256 &hash);
e8ef3da7
WL
277 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
278 void ReacceptWalletTransactions();
279 void ResendWalletTransactions();
a372168e
MF
280 CAmount GetBalance() const;
281 CAmount GetUnconfirmedBalance() const;
282 CAmount GetImmatureBalance() const;
283 CAmount GetWatchOnlyBalance() const;
284 CAmount GetUnconfirmedWatchOnlyBalance() const;
285 CAmount GetImmatureWatchOnlyBalance() const;
286 bool CreateTransaction(const std::vector<std::pair<CScript, CAmount> >& vecSend,
287 CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl *coinControl = NULL);
288 bool CreateTransaction(CScript scriptPubKey, const CAmount& nValue,
289 CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl *coinControl = NULL);
e8ef3da7 290 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
e8ef3da7 291
13fc83c7 292 static CFeeRate minTxFee;
a372168e 293 static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool);
b33d1f5e 294
37971fcc 295 bool NewKeyPool();
13dd2d09 296 bool TopUpKeyPool(unsigned int kpSize = 0);
51ed9ec9
BD
297 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
298 void KeepKey(int64_t nIndex);
299 void ReturnKey(int64_t nIndex);
71ac5052 300 bool GetKeyFromPool(CPubKey &key);
51ed9ec9 301 int64_t GetOldestKeyPoolTime();
434e4273 302 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
e8ef3da7 303
b1093efa 304 std::set< std::set<CTxDestination> > GetAddressGroupings();
a372168e 305 std::map<CTxDestination, CAmount> GetAddressBalances();
22dfd735 306
3624356e
GA
307 std::set<CTxDestination> GetAccountAddresses(std::string strAccount) const;
308
c8988460 309 isminetype IsMine(const CTxIn& txin) const;
a372168e 310 CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
c8988460 311 isminetype IsMine(const CTxOut& txout) const
e8ef3da7
WL
312 {
313 return ::IsMine(*this, txout.scriptPubKey);
314 }
a372168e 315 CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const
e8ef3da7
WL
316 {
317 if (!MoneyRange(txout.nValue))
318 throw std::runtime_error("CWallet::GetCredit() : value out of range");
ffd40da3 319 return ((IsMine(txout) & filter) ? txout.nValue : 0);
e8ef3da7 320 }
e679ec96 321 bool IsChange(const CTxOut& txout) const;
a372168e 322 CAmount GetChange(const CTxOut& txout) const
e8ef3da7
WL
323 {
324 if (!MoneyRange(txout.nValue))
325 throw std::runtime_error("CWallet::GetChange() : value out of range");
326 return (IsChange(txout) ? txout.nValue : 0);
327 }
328 bool IsMine(const CTransaction& tx) const
329 {
330 BOOST_FOREACH(const CTxOut& txout, tx.vout)
331 if (IsMine(txout))
332 return true;
333 return false;
334 }
5b40d886
MF
335 /** should probably be renamed to IsRelevantToMe */
336 bool IsFromMe(const CTransaction& tx) const
e8ef3da7 337 {
a3e192a3 338 return (GetDebit(tx, ISMINE_ALL) > 0);
e8ef3da7 339 }
a372168e 340 CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const
e8ef3da7 341 {
a372168e 342 CAmount nDebit = 0;
e8ef3da7
WL
343 BOOST_FOREACH(const CTxIn& txin, tx.vin)
344 {
d4640d7d 345 nDebit += GetDebit(txin, filter);
e8ef3da7
WL
346 if (!MoneyRange(nDebit))
347 throw std::runtime_error("CWallet::GetDebit() : value out of range");
348 }
349 return nDebit;
350 }
a372168e 351 CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const
e8ef3da7 352 {
a372168e 353 CAmount nCredit = 0;
e8ef3da7
WL
354 BOOST_FOREACH(const CTxOut& txout, tx.vout)
355 {
ffd40da3 356 nCredit += GetCredit(txout, filter);
e8ef3da7
WL
357 if (!MoneyRange(nCredit))
358 throw std::runtime_error("CWallet::GetCredit() : value out of range");
359 }
360 return nCredit;
361 }
a372168e 362 CAmount GetChange(const CTransaction& tx) const
e8ef3da7 363 {
a372168e 364 CAmount nChange = 0;
e8ef3da7
WL
365 BOOST_FOREACH(const CTxOut& txout, tx.vout)
366 {
367 nChange += GetChange(txout);
368 if (!MoneyRange(nChange))
369 throw std::runtime_error("CWallet::GetChange() : value out of range");
370 }
371 return nChange;
372 }
ed6d0b5f 373 void SetBestChain(const CBlockLocator& loc);
e8ef3da7 374
eed1785f 375 DBErrors LoadWallet(bool& fFirstRunRet);
77cbd462 376 DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
ae3d0aba 377
a41d5fe0 378 bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
ae3d0aba 379
a41d5fe0 380 bool DelAddressBook(const CTxDestination& address);
e8ef3da7 381
fe4a6550 382 void UpdatedTransaction(const uint256 &hashTx);
e8ef3da7 383
e8ef3da7
WL
384 void Inventory(const uint256 &hash)
385 {
e8ef3da7 386 {
f8dcd5ca 387 LOCK(cs_wallet);
e8ef3da7
WL
388 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
389 if (mi != mapRequestCount.end())
390 (*mi).second++;
391 }
392 }
393
13dd2d09 394 unsigned int GetKeyPoolSize()
4e87d341 395 {
95691680 396 AssertLockHeld(cs_wallet); // setKeyPool
4e87d341
MC
397 return setKeyPool.size();
398 }
399
fd61d6f5 400 bool SetDefaultKey(const CPubKey &vchPubKey);
0b807a41 401
5b40d886 402 //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
439e1497
PW
403 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
404
5b40d886 405 //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
439e1497
PW
406 bool SetMaxVersion(int nVersion);
407
5b40d886 408 //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
ca4cf5cf 409 int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
ab1b288f 410
5b40d886 411 //! Get wallet transactions that conflict with given transaction (spend same outputs)
3015e0bc 412 std::set<uint256> GetConflicts(const uint256& txid) const;
731b89b8 413
5b40d886
MF
414 /**
415 * Address book entry changed.
ab1b288f
WL
416 * @note called with lock cs_wallet held.
417 */
dcd0b077
WL
418 boost::signals2::signal<void (CWallet *wallet, const CTxDestination
419 &address, const std::string &label, bool isMine,
420 const std::string &purpose,
421 ChangeType status)> NotifyAddressBookChanged;
ab1b288f 422
5b40d886
MF
423 /**
424 * Wallet transaction added, removed or updated.
ab1b288f
WL
425 * @note called with lock cs_wallet held.
426 */
dcd0b077
WL
427 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
428 ChangeType status)> NotifyTransactionChanged;
39278369
CL
429
430 /** Show progress e.g. for rescan */
431 boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
939ed973
CL
432
433 /** Watch-only address added */
434 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
e8ef3da7
WL
435};
436
6b8de05d 437/** A key allocated from the key pool. */
e8ef3da7
WL
438class CReserveKey
439{
440protected:
441 CWallet* pwallet;
51ed9ec9 442 int64_t nIndex;
fd61d6f5 443 CPubKey vchPubKey;
e8ef3da7
WL
444public:
445 CReserveKey(CWallet* pwalletIn)
446 {
447 nIndex = -1;
448 pwallet = pwalletIn;
449 }
450
451 ~CReserveKey()
452 {
b31499ec 453 ReturnKey();
e8ef3da7
WL
454 }
455
456 void ReturnKey();
360cfe14 457 bool GetReservedKey(CPubKey &pubkey);
e8ef3da7
WL
458 void KeepKey();
459};
460
461
9c7722b7
LD
462typedef std::map<std::string, std::string> mapValue_t;
463
464
51ed9ec9 465static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
9c7722b7
LD
466{
467 if (!mapValue.count("n"))
468 {
469 nOrderPos = -1; // TODO: calculate elsewhere
470 return;
471 }
472 nOrderPos = atoi64(mapValue["n"].c_str());
473}
474
475
51ed9ec9 476static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
9c7722b7
LD
477{
478 if (nOrderPos == -1)
479 return;
480 mapValue["n"] = i64tostr(nOrderPos);
481}
482
1b4568cb
CL
483struct COutputEntry
484{
485 CTxDestination destination;
a372168e 486 CAmount amount;
1b4568cb
CL
487 int vout;
488};
9c7722b7 489
0101483f
WL
490/** A transaction with a merkle branch linking it to the block chain. */
491class CMerkleTx : public CTransaction
492{
493private:
a31e8bad 494 int GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const;
0101483f
WL
495
496public:
497 uint256 hashBlock;
498 std::vector<uint256> vMerkleBranch;
499 int nIndex;
500
501 // memory only
502 mutable bool fMerkleVerified;
503
504
505 CMerkleTx()
506 {
507 Init();
508 }
509
510 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
511 {
512 Init();
513 }
514
515 void Init()
516 {
517 hashBlock = 0;
518 nIndex = -1;
519 fMerkleVerified = false;
520 }
521
3f6540ad 522 ADD_SERIALIZE_METHODS;
0101483f 523
84881f8c 524 template <typename Stream, typename Operation>
31e9a838
PW
525 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
526 READWRITE(*(CTransaction*)this);
0101483f
WL
527 nVersion = this->nVersion;
528 READWRITE(hashBlock);
529 READWRITE(vMerkleBranch);
530 READWRITE(nIndex);
3d796f89 531 }
0101483f 532
4b0deb3b 533 int SetMerkleBranch(const CBlock& block);
0101483f 534
5b40d886
MF
535
536 /**
537 * Return depth of transaction in blockchain:
538 * -1 : not in blockchain, and not in memory pool (conflicted transaction)
539 * 0 : in memory pool, waiting to be included in a block
540 * >=1 : this many blocks deep in the main chain
541 */
a31e8bad
DK
542 int GetDepthInMainChain(const CBlockIndex* &pindexRet) const;
543 int GetDepthInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
544 bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; }
0101483f
WL
545 int GetBlocksToMaturity() const;
546 bool AcceptToMemoryPool(bool fLimitFree=true, bool fRejectInsaneFee=true);
547};
548
5b40d886
MF
549/**
550 * A transaction with a bunch of additional info that only the owner cares about.
6b8de05d
PW
551 * It includes any unrecorded transactions needed to link it back to the block chain.
552 */
e8ef3da7
WL
553class CWalletTx : public CMerkleTx
554{
4c6e2295 555private:
e8ef3da7
WL
556 const CWallet* pwallet;
557
4c6e2295 558public:
9c7722b7 559 mapValue_t mapValue;
e8ef3da7
WL
560 std::vector<std::pair<std::string, std::string> > vOrderForm;
561 unsigned int fTimeReceivedIsTxTime;
5b40d886 562 unsigned int nTimeReceived; //! time received by this node
c3f95ef1 563 unsigned int nTimeSmart;
e8ef3da7
WL
564 char fFromMe;
565 std::string strFromAccount;
5b40d886 566 int64_t nOrderPos; //! position in ordered transaction list
e8ef3da7
WL
567
568 // memory only
cdcc319c
WL
569 mutable bool fDebitCached;
570 mutable bool fCreditCached;
966a0e8c 571 mutable bool fImmatureCreditCached;
cdcc319c 572 mutable bool fAvailableCreditCached;
d4640d7d
J
573 mutable bool fWatchDebitCached;
574 mutable bool fWatchCreditCached;
ffd40da3
J
575 mutable bool fImmatureWatchCreditCached;
576 mutable bool fAvailableWatchCreditCached;
cdcc319c 577 mutable bool fChangeCached;
a372168e
MF
578 mutable CAmount nDebitCached;
579 mutable CAmount nCreditCached;
580 mutable CAmount nImmatureCreditCached;
581 mutable CAmount nAvailableCreditCached;
582 mutable CAmount nWatchDebitCached;
583 mutable CAmount nWatchCreditCached;
584 mutable CAmount nImmatureWatchCreditCached;
585 mutable CAmount nAvailableWatchCreditCached;
586 mutable CAmount nChangeCached;
e8ef3da7 587
e8ef3da7
WL
588 CWalletTx()
589 {
590 Init(NULL);
591 }
592
593 CWalletTx(const CWallet* pwalletIn)
594 {
595 Init(pwalletIn);
596 }
597
598 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
599 {
600 Init(pwalletIn);
601 }
602
603 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
604 {
605 Init(pwalletIn);
606 }
607
608 void Init(const CWallet* pwalletIn)
609 {
610 pwallet = pwalletIn;
e8ef3da7
WL
611 mapValue.clear();
612 vOrderForm.clear();
613 fTimeReceivedIsTxTime = false;
614 nTimeReceived = 0;
c3f95ef1 615 nTimeSmart = 0;
e8ef3da7
WL
616 fFromMe = false;
617 strFromAccount.clear();
e8ef3da7
WL
618 fDebitCached = false;
619 fCreditCached = false;
966a0e8c 620 fImmatureCreditCached = false;
e8ef3da7 621 fAvailableCreditCached = false;
d4640d7d
J
622 fWatchDebitCached = false;
623 fWatchCreditCached = false;
ffd40da3
J
624 fImmatureWatchCreditCached = false;
625 fAvailableWatchCreditCached = false;
e8ef3da7
WL
626 fChangeCached = false;
627 nDebitCached = 0;
628 nCreditCached = 0;
966a0e8c 629 nImmatureCreditCached = 0;
e8ef3da7 630 nAvailableCreditCached = 0;
d4640d7d
J
631 nWatchDebitCached = 0;
632 nWatchCreditCached = 0;
ffd40da3
J
633 nAvailableWatchCreditCached = 0;
634 nImmatureWatchCreditCached = 0;
e8ef3da7 635 nChangeCached = 0;
9c7722b7 636 nOrderPos = -1;
e8ef3da7
WL
637 }
638
3f6540ad 639 ADD_SERIALIZE_METHODS;
3d796f89 640
84881f8c 641 template <typename Stream, typename Operation>
31e9a838 642 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
47eb7659
PW
643 if (ser_action.ForRead())
644 Init(NULL);
e8ef3da7
WL
645 char fSpent = false;
646
47eb7659 647 if (!ser_action.ForRead())
e8ef3da7 648 {
47eb7659 649 mapValue["fromaccount"] = strFromAccount;
e8ef3da7 650
47eb7659 651 WriteOrderPos(nOrderPos, mapValue);
c3f95ef1
LD
652
653 if (nTimeSmart)
47eb7659 654 mapValue["timesmart"] = strprintf("%u", nTimeSmart);
e8ef3da7
WL
655 }
656
31e9a838 657 READWRITE(*(CMerkleTx*)this);
5b40d886 658 std::vector<CMerkleTx> vUnused; //! Used to be vtxPrev
93a18a36 659 READWRITE(vUnused);
e8ef3da7
WL
660 READWRITE(mapValue);
661 READWRITE(vOrderForm);
662 READWRITE(fTimeReceivedIsTxTime);
663 READWRITE(nTimeReceived);
664 READWRITE(fFromMe);
665 READWRITE(fSpent);
666
47eb7659 667 if (ser_action.ForRead())
e8ef3da7 668 {
47eb7659 669 strFromAccount = mapValue["fromaccount"];
e8ef3da7 670
47eb7659 671 ReadOrderPos(nOrderPos, mapValue);
9c7722b7 672
47eb7659 673 nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
c3f95ef1
LD
674 }
675
31e9a838
PW
676 mapValue.erase("fromaccount");
677 mapValue.erase("version");
678 mapValue.erase("spent");
679 mapValue.erase("n");
680 mapValue.erase("timesmart");
3d796f89 681 }
e8ef3da7 682
5b40d886 683 //! make sure balances are recalculated
e8ef3da7
WL
684 void MarkDirty()
685 {
686 fCreditCached = false;
687 fAvailableCreditCached = false;
d4640d7d
J
688 fWatchDebitCached = false;
689 fWatchCreditCached = false;
ffd40da3
J
690 fAvailableWatchCreditCached = false;
691 fImmatureWatchCreditCached = false;
e8ef3da7
WL
692 fDebitCached = false;
693 fChangeCached = false;
694 }
695
4c6e2295
PW
696 void BindWallet(CWallet *pwalletIn)
697 {
698 pwallet = pwalletIn;
699 MarkDirty();
700 }
701
5b40d886 702 //! filter decides which addresses will count towards the debit
a372168e 703 CAmount GetDebit(const isminefilter& filter) const
e8ef3da7
WL
704 {
705 if (vin.empty())
706 return 0;
d4640d7d 707
a372168e 708 CAmount debit = 0;
a3e192a3 709 if(filter & ISMINE_SPENDABLE)
d4640d7d
J
710 {
711 if (fDebitCached)
712 debit += nDebitCached;
713 else
714 {
a3e192a3 715 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
d4640d7d
J
716 fDebitCached = true;
717 debit += nDebitCached;
718 }
719 }
a3e192a3 720 if(filter & ISMINE_WATCH_ONLY)
d4640d7d
J
721 {
722 if(fWatchDebitCached)
723 debit += nWatchDebitCached;
724 else
725 {
a3e192a3 726 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
d4640d7d
J
727 fWatchDebitCached = true;
728 debit += nWatchDebitCached;
729 }
730 }
731 return debit;
e8ef3da7
WL
732 }
733
ccca27a7 734 CAmount GetCredit(const isminefilter& filter) const
e8ef3da7
WL
735 {
736 // Must wait until coinbase is safely deep enough in the chain before valuing it
737 if (IsCoinBase() && GetBlocksToMaturity() > 0)
738 return 0;
739
ccca27a7
CL
740 int64_t credit = 0;
741 if (filter & ISMINE_SPENDABLE)
742 {
743 // GetBalance can assume transactions in mapWallet won't change
744 if (fCreditCached)
745 credit += nCreditCached;
746 else
747 {
748 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
749 fCreditCached = true;
750 credit += nCreditCached;
751 }
752 }
753 if (filter & ISMINE_WATCH_ONLY)
754 {
755 if (fWatchCreditCached)
756 credit += nWatchCreditCached;
757 else
758 {
759 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
760 fWatchCreditCached = true;
761 credit += nWatchCreditCached;
762 }
763 }
764 return credit;
e8ef3da7
WL
765 }
766
a372168e 767 CAmount GetImmatureCredit(bool fUseCache=true) const
966a0e8c
PK
768 {
769 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
770 {
771 if (fUseCache && fImmatureCreditCached)
772 return nImmatureCreditCached;
a3e192a3 773 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
966a0e8c
PK
774 fImmatureCreditCached = true;
775 return nImmatureCreditCached;
776 }
777
778 return 0;
779 }
780
a372168e 781 CAmount GetAvailableCredit(bool fUseCache=true) const
e8ef3da7 782 {
93a18a36
GA
783 if (pwallet == 0)
784 return 0;
785
e8ef3da7
WL
786 // Must wait until coinbase is safely deep enough in the chain before valuing it
787 if (IsCoinBase() && GetBlocksToMaturity() > 0)
788 return 0;
789
790 if (fUseCache && fAvailableCreditCached)
791 return nAvailableCreditCached;
792
a372168e 793 CAmount nCredit = 0;
a60ab0ba 794 uint256 hashTx = GetHash();
c376ac35 795 for (unsigned int i = 0; i < vout.size(); i++)
e8ef3da7 796 {
a60ab0ba 797 if (!pwallet->IsSpent(hashTx, i))
e8ef3da7
WL
798 {
799 const CTxOut &txout = vout[i];
a3e192a3 800 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
e8ef3da7
WL
801 if (!MoneyRange(nCredit))
802 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
803 }
804 }
805
806 nAvailableCreditCached = nCredit;
807 fAvailableCreditCached = true;
808 return nCredit;
809 }
810
a372168e 811 CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const
ffd40da3
J
812 {
813 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
814 {
815 if (fUseCache && fImmatureWatchCreditCached)
816 return nImmatureWatchCreditCached;
a3e192a3 817 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
ffd40da3
J
818 fImmatureWatchCreditCached = true;
819 return nImmatureWatchCreditCached;
820 }
821
822 return 0;
823 }
824
a372168e 825 CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const
ffd40da3
J
826 {
827 if (pwallet == 0)
828 return 0;
829
830 // Must wait until coinbase is safely deep enough in the chain before valuing it
831 if (IsCoinBase() && GetBlocksToMaturity() > 0)
832 return 0;
833
834 if (fUseCache && fAvailableWatchCreditCached)
835 return nAvailableWatchCreditCached;
836
a372168e 837 CAmount nCredit = 0;
ffd40da3
J
838 for (unsigned int i = 0; i < vout.size(); i++)
839 {
840 if (!pwallet->IsSpent(GetHash(), i))
841 {
842 const CTxOut &txout = vout[i];
a3e192a3 843 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
ffd40da3
J
844 if (!MoneyRange(nCredit))
845 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
846 }
847 }
848
849 nAvailableWatchCreditCached = nCredit;
850 fAvailableWatchCreditCached = true;
851 return nCredit;
852 }
e8ef3da7 853
a372168e 854 CAmount GetChange() const
e8ef3da7
WL
855 {
856 if (fChangeCached)
857 return nChangeCached;
858 nChangeCached = pwallet->GetChange(*this);
859 fChangeCached = true;
860 return nChangeCached;
861 }
862
1b4568cb 863 void GetAmounts(std::list<COutputEntry>& listReceived,
a372168e 864 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
e8ef3da7 865
a372168e
MF
866 void GetAccountAmounts(const std::string& strAccount, CAmount& nReceived,
867 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const;
e8ef3da7 868
80dda36a 869 bool IsFromMe(const isminefilter& filter) const
e8ef3da7 870 {
952877e0 871 return (GetDebit(filter) > 0);
e8ef3da7
WL
872 }
873
0542619d 874 bool IsTrusted() const
e8ef3da7
WL
875 {
876 // Quick answer in most cases
05df3fc6 877 if (!IsFinalTx(*this))
e8ef3da7 878 return false;
2b72d46f
GA
879 int nDepth = GetDepthInMainChain();
880 if (nDepth >= 1)
e8ef3da7 881 return true;
2b72d46f
GA
882 if (nDepth < 0)
883 return false;
a3e192a3 884 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
e8ef3da7
WL
885 return false;
886
93a18a36
GA
887 // Trusted if all inputs are from us and are in the mempool:
888 BOOST_FOREACH(const CTxIn& txin, vin)
e8ef3da7 889 {
93a18a36
GA
890 // Transactions not sent by us: not trusted
891 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
ba51c7da
CL
892 if (parent == NULL)
893 return false;
93a18a36 894 const CTxOut& parentOut = parent->vout[txin.prevout.n];
a3e192a3 895 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
e8ef3da7 896 return false;
e8ef3da7
WL
897 }
898 return true;
899 }
900
901 bool WriteToDisk();
902
51ed9ec9 903 int64_t GetTxTime() const;
e8ef3da7
WL
904 int GetRequestCount() const;
905
e8ef3da7 906 void RelayWalletTransaction();
731b89b8 907
3015e0bc 908 std::set<uint256> GetConflicts() const;
e8ef3da7
WL
909};
910
911
9b0369c7
CM
912
913
914class COutput
915{
916public:
917 const CWalletTx *tx;
918 int i;
919 int nDepth;
c8988460 920 bool fSpendable;
9b0369c7 921
c8988460 922 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
9b0369c7 923 {
c8988460 924 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
9b0369c7
CM
925 }
926
ad49c256 927 std::string ToString() const;
9b0369c7
CM
928};
929
930
931
932
6b8de05d 933/** Private key that includes an expiration date in case it never gets used. */
e8ef3da7
WL
934class CWalletKey
935{
936public:
937 CPrivKey vchPrivKey;
51ed9ec9
BD
938 int64_t nTimeCreated;
939 int64_t nTimeExpires;
e8ef3da7 940 std::string strComment;
5b40d886
MF
941 //! todo: add something to note what created it (user, getnewaddress, change)
942 //! maybe should have a map<string, string> property map
e8ef3da7 943
af8297c0 944 CWalletKey(int64_t nExpires=0);
e8ef3da7 945
3f6540ad 946 ADD_SERIALIZE_METHODS;
3d796f89 947
84881f8c 948 template <typename Stream, typename Operation>
31e9a838 949 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
e8ef3da7
WL
950 if (!(nType & SER_GETHASH))
951 READWRITE(nVersion);
952 READWRITE(vchPrivKey);
953 READWRITE(nTimeCreated);
954 READWRITE(nTimeExpires);
216e9a44 955 READWRITE(LIMITED_STRING(strComment, 65536));
3d796f89 956 }
e8ef3da7
WL
957};
958
959
960
961
962
963
5b40d886
MF
964/**
965 * Account information.
6b8de05d
PW
966 * Stored in wallet with key "acc"+string account name.
967 */
e8ef3da7
WL
968class CAccount
969{
970public:
fd61d6f5 971 CPubKey vchPubKey;
e8ef3da7
WL
972
973 CAccount()
974 {
975 SetNull();
976 }
977
978 void SetNull()
979 {
fd61d6f5 980 vchPubKey = CPubKey();
e8ef3da7
WL
981 }
982
3f6540ad 983 ADD_SERIALIZE_METHODS;
3d796f89 984
84881f8c 985 template <typename Stream, typename Operation>
31e9a838 986 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
e8ef3da7
WL
987 if (!(nType & SER_GETHASH))
988 READWRITE(nVersion);
989 READWRITE(vchPubKey);
3d796f89 990 }
e8ef3da7
WL
991};
992
993
994
5b40d886
MF
995/**
996 * Internal transfers.
6b8de05d
PW
997 * Database key is acentry<account><counter>.
998 */
e8ef3da7
WL
999class CAccountingEntry
1000{
1001public:
1002 std::string strAccount;
a372168e 1003 CAmount nCreditDebit;
51ed9ec9 1004 int64_t nTime;
e8ef3da7
WL
1005 std::string strOtherAccount;
1006 std::string strComment;
9c7722b7 1007 mapValue_t mapValue;
5b40d886 1008 int64_t nOrderPos; //! position in ordered transaction list
51ed9ec9 1009 uint64_t nEntryNo;
e8ef3da7
WL
1010
1011 CAccountingEntry()
1012 {
1013 SetNull();
1014 }
1015
1016 void SetNull()
1017 {
1018 nCreditDebit = 0;
1019 nTime = 0;
1020 strAccount.clear();
1021 strOtherAccount.clear();
1022 strComment.clear();
9c7722b7 1023 nOrderPos = -1;
8bdd2877 1024 nEntryNo = 0;
e8ef3da7
WL
1025 }
1026
3f6540ad 1027 ADD_SERIALIZE_METHODS;
3d796f89 1028
84881f8c 1029 template <typename Stream, typename Operation>
31e9a838 1030 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
e8ef3da7
WL
1031 if (!(nType & SER_GETHASH))
1032 READWRITE(nVersion);
5b40d886 1033 //! Note: strAccount is serialized as part of the key, not here.
e8ef3da7
WL
1034 READWRITE(nCreditDebit);
1035 READWRITE(nTime);
216e9a44 1036 READWRITE(LIMITED_STRING(strOtherAccount, 65536));
9c7722b7 1037
47eb7659 1038 if (!ser_action.ForRead())
9c7722b7 1039 {
47eb7659 1040 WriteOrderPos(nOrderPos, mapValue);
9c7722b7
LD
1041
1042 if (!(mapValue.empty() && _ssExtra.empty()))
1043 {
1044 CDataStream ss(nType, nVersion);
1045 ss.insert(ss.begin(), '\0');
1046 ss << mapValue;
1047 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
47eb7659 1048 strComment.append(ss.str());
9c7722b7
LD
1049 }
1050 }
1051
216e9a44 1052 READWRITE(LIMITED_STRING(strComment, 65536));
9c7722b7
LD
1053
1054 size_t nSepPos = strComment.find("\0", 0, 1);
47eb7659 1055 if (ser_action.ForRead())
9c7722b7 1056 {
47eb7659 1057 mapValue.clear();
9c7722b7
LD
1058 if (std::string::npos != nSepPos)
1059 {
1060 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
47eb7659
PW
1061 ss >> mapValue;
1062 _ssExtra = std::vector<char>(ss.begin(), ss.end());
9c7722b7 1063 }
47eb7659 1064 ReadOrderPos(nOrderPos, mapValue);
9c7722b7
LD
1065 }
1066 if (std::string::npos != nSepPos)
47eb7659 1067 strComment.erase(nSepPos);
9c7722b7 1068
31e9a838 1069 mapValue.erase("n");
3d796f89 1070 }
9c7722b7
LD
1071
1072private:
1073 std::vector<char> _ssExtra;
e8ef3da7
WL
1074};
1075
093303a8 1076#endif // BITCOIN_WALLET_H
This page took 0.349156 seconds and 4 git commands to generate.