]>
Commit | Line | Data |
---|---|---|
b2120e22 | 1 | // Copyright (c) 2009-2010 Satoshi Nakamoto |
57702541 | 2 | // Copyright (c) 2009-2014 The Bitcoin developers |
e8ef3da7 | 3 | // Distributed under the MIT/X11 software license, see the accompanying |
3a25a2b9 | 4 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. |
e8ef3da7 | 5 | |
9eace6b1 | 6 | #include "wallet.h" |
51ed9ec9 | 7 | |
10254401 | 8 | #include "base58.h" |
3e1cf9b6 | 9 | #include "checkpoints.h" |
6a86c24d | 10 | #include "coincontrol.h" |
0689f46c | 11 | #include "net.h" |
e088d65a | 12 | #include "script/script.h" |
13 | #include "script/sign.h" | |
14f888ca | 14 | #include "timedata.h" |
ad49c256 WL |
15 | #include "util.h" |
16 | #include "utilmoneystr.h" | |
51ed9ec9 | 17 | |
cae686d3 | 18 | #include <boost/algorithm/string/replace.hpp> |
ad49c256 | 19 | #include <boost/thread.hpp> |
e8ef3da7 WL |
20 | |
21 | using namespace std; | |
22 | ||
cd7fa8bb | 23 | // Settings |
c6cb21d1 | 24 | CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE); |
b33d1f5e | 25 | unsigned int nTxConfirmTarget = 1; |
1bbca249 | 26 | bool bSpendZeroConfChange = true; |
e8ef3da7 | 27 | |
13fc83c7 GA |
28 | /** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */ |
29 | CFeeRate CWallet::minTxFee = CFeeRate(10000); // Override with -mintxfee | |
30 | ||
e8ef3da7 WL |
31 | ////////////////////////////////////////////////////////////////////////////// |
32 | // | |
33 | // mapWallet | |
34 | // | |
35 | ||
d650f96d CM |
36 | struct CompareValueOnly |
37 | { | |
a372168e MF |
38 | bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1, |
39 | const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const | |
d650f96d CM |
40 | { |
41 | return t1.first < t2.first; | |
42 | } | |
43 | }; | |
44 | ||
ad49c256 WL |
45 | std::string COutput::ToString() const |
46 | { | |
2c2cc5da | 47 | return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue)); |
ad49c256 WL |
48 | } |
49 | ||
93a18a36 GA |
50 | const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const |
51 | { | |
52 | LOCK(cs_wallet); | |
53 | std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash); | |
54 | if (it == mapWallet.end()) | |
55 | return NULL; | |
56 | return &(it->second); | |
57 | } | |
58 | ||
fd61d6f5 | 59 | CPubKey CWallet::GenerateNewKey() |
9976cf07 | 60 | { |
95691680 | 61 | AssertLockHeld(cs_wallet); // mapKeyMetadata |
439e1497 | 62 | bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets |
38067c18 | 63 | |
9976cf07 | 64 | RandAddSeedPerfmon(); |
dfa23b94 PW |
65 | CKey secret; |
66 | secret.MakeNewKey(fCompressed); | |
38067c18 PW |
67 | |
68 | // Compressed public keys were introduced in version 0.6.0 | |
69 | if (fCompressed) | |
439e1497 | 70 | SetMinVersion(FEATURE_COMPRPUBKEY); |
38067c18 | 71 | |
dfa23b94 | 72 | CPubKey pubkey = secret.GetPubKey(); |
4addb2c0 PW |
73 | |
74 | // Create new metadata | |
51ed9ec9 | 75 | int64_t nCreationTime = GetTime(); |
4addb2c0 PW |
76 | mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime); |
77 | if (!nTimeFirstKey || nCreationTime < nTimeFirstKey) | |
78 | nTimeFirstKey = nCreationTime; | |
79 | ||
dfa23b94 | 80 | if (!AddKeyPubKey(secret, pubkey)) |
9976cf07 | 81 | throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed"); |
dfa23b94 | 82 | return pubkey; |
9976cf07 | 83 | } |
e8ef3da7 | 84 | |
4addb2c0 | 85 | bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey) |
e8ef3da7 | 86 | { |
95691680 | 87 | AssertLockHeld(cs_wallet); // mapKeyMetadata |
dfa23b94 | 88 | if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) |
acd65016 | 89 | return false; |
ccca27a7 CL |
90 | |
91 | // check if we need to remove from watch-only | |
92 | CScript script; | |
93 | script = GetScriptForDestination(pubkey.GetID()); | |
94 | if (HaveWatchOnly(script)) | |
95 | RemoveWatchOnly(script); | |
96 | ||
e8ef3da7 WL |
97 | if (!fFileBacked) |
98 | return true; | |
dfa23b94 | 99 | if (!IsCrypted()) { |
3869fb89 JG |
100 | return CWalletDB(strWalletFile).WriteKey(pubkey, |
101 | secret.GetPrivKey(), | |
4addb2c0 | 102 | mapKeyMetadata[pubkey.GetID()]); |
dfa23b94 | 103 | } |
84c3c2eb | 104 | return true; |
4e87d341 MC |
105 | } |
106 | ||
3869fb89 | 107 | bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, |
4addb2c0 | 108 | const vector<unsigned char> &vchCryptedSecret) |
4e87d341 MC |
109 | { |
110 | if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret)) | |
111 | return false; | |
112 | if (!fFileBacked) | |
113 | return true; | |
96f34cd5 | 114 | { |
f8dcd5ca | 115 | LOCK(cs_wallet); |
96f34cd5 | 116 | if (pwalletdbEncryption) |
3869fb89 JG |
117 | return pwalletdbEncryption->WriteCryptedKey(vchPubKey, |
118 | vchCryptedSecret, | |
4addb2c0 | 119 | mapKeyMetadata[vchPubKey.GetID()]); |
96f34cd5 | 120 | else |
3869fb89 JG |
121 | return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, |
122 | vchCryptedSecret, | |
4addb2c0 | 123 | mapKeyMetadata[vchPubKey.GetID()]); |
96f34cd5 | 124 | } |
0767e691 | 125 | return false; |
4e87d341 MC |
126 | } |
127 | ||
4addb2c0 PW |
128 | bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta) |
129 | { | |
95691680 | 130 | AssertLockHeld(cs_wallet); // mapKeyMetadata |
4addb2c0 PW |
131 | if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey)) |
132 | nTimeFirstKey = meta.nCreateTime; | |
133 | ||
134 | mapKeyMetadata[pubkey.GetID()] = meta; | |
135 | return true; | |
136 | } | |
137 | ||
2f15e86a GA |
138 | bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) |
139 | { | |
140 | return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); | |
141 | } | |
142 | ||
922e8e29 | 143 | bool CWallet::AddCScript(const CScript& redeemScript) |
e679ec96 | 144 | { |
922e8e29 | 145 | if (!CCryptoKeyStore::AddCScript(redeemScript)) |
e679ec96 GA |
146 | return false; |
147 | if (!fFileBacked) | |
148 | return true; | |
922e8e29 | 149 | return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript); |
e679ec96 GA |
150 | } |
151 | ||
18116b06 WL |
152 | bool CWallet::LoadCScript(const CScript& redeemScript) |
153 | { | |
154 | /* A sanity check was added in pull #3843 to avoid adding redeemScripts | |
155 | * that never can be redeemed. However, old wallets may still contain | |
156 | * these. Do not add them to the wallet and warn. */ | |
157 | if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) | |
158 | { | |
159 | std::string strAddr = CBitcoinAddress(redeemScript.GetID()).ToString(); | |
160 | LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n", | |
161 | __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr); | |
162 | return true; | |
163 | } | |
164 | ||
165 | return CCryptoKeyStore::AddCScript(redeemScript); | |
166 | } | |
167 | ||
d5087d1b | 168 | bool CWallet::AddWatchOnly(const CScript &dest) |
c8988460 PW |
169 | { |
170 | if (!CCryptoKeyStore::AddWatchOnly(dest)) | |
171 | return false; | |
172 | nTimeFirstKey = 1; // No birthday information for watch-only keys. | |
939ed973 | 173 | NotifyWatchonlyChanged(true); |
c8988460 PW |
174 | if (!fFileBacked) |
175 | return true; | |
176 | return CWalletDB(strWalletFile).WriteWatchOnly(dest); | |
177 | } | |
178 | ||
ccca27a7 CL |
179 | bool CWallet::RemoveWatchOnly(const CScript &dest) |
180 | { | |
181 | AssertLockHeld(cs_wallet); | |
182 | if (!CCryptoKeyStore::RemoveWatchOnly(dest)) | |
183 | return false; | |
184 | if (!HaveWatchOnly()) | |
185 | NotifyWatchonlyChanged(false); | |
186 | if (fFileBacked) | |
187 | if (!CWalletDB(strWalletFile).EraseWatchOnly(dest)) | |
188 | return false; | |
189 | ||
190 | return true; | |
191 | } | |
192 | ||
d5087d1b | 193 | bool CWallet::LoadWatchOnly(const CScript &dest) |
c8988460 | 194 | { |
c8988460 PW |
195 | return CCryptoKeyStore::AddWatchOnly(dest); |
196 | } | |
197 | ||
94f778bd | 198 | bool CWallet::Unlock(const SecureString& strWalletPassphrase) |
4e87d341 | 199 | { |
6cc4a62c GA |
200 | CCrypter crypter; |
201 | CKeyingMaterial vMasterKey; | |
4e87d341 | 202 | |
f8dcd5ca PW |
203 | { |
204 | LOCK(cs_wallet); | |
4e87d341 MC |
205 | BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) |
206 | { | |
207 | if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) | |
208 | return false; | |
209 | if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) | |
92f2c1fe | 210 | continue; // try another master key |
4e87d341 MC |
211 | if (CCryptoKeyStore::Unlock(vMasterKey)) |
212 | return true; | |
213 | } | |
f8dcd5ca | 214 | } |
4e87d341 MC |
215 | return false; |
216 | } | |
217 | ||
94f778bd | 218 | bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase) |
4e87d341 | 219 | { |
6cc4a62c | 220 | bool fWasLocked = IsLocked(); |
4e87d341 | 221 | |
6cc4a62c | 222 | { |
f8dcd5ca | 223 | LOCK(cs_wallet); |
4e87d341 MC |
224 | Lock(); |
225 | ||
226 | CCrypter crypter; | |
227 | CKeyingMaterial vMasterKey; | |
228 | BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys) | |
229 | { | |
230 | if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) | |
231 | return false; | |
6cc4a62c | 232 | if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) |
4e87d341 MC |
233 | return false; |
234 | if (CCryptoKeyStore::Unlock(vMasterKey)) | |
235 | { | |
51ed9ec9 | 236 | int64_t nStartTime = GetTimeMillis(); |
ddebdd9a MC |
237 | crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); |
238 | pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))); | |
239 | ||
240 | nStartTime = GetTimeMillis(); | |
241 | crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); | |
242 | pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; | |
243 | ||
244 | if (pMasterKey.second.nDeriveIterations < 25000) | |
245 | pMasterKey.second.nDeriveIterations = 25000; | |
246 | ||
881a85a2 | 247 | LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations); |
ddebdd9a | 248 | |
4e87d341 MC |
249 | if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) |
250 | return false; | |
251 | if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey)) | |
252 | return false; | |
253 | CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second); | |
254 | if (fWasLocked) | |
255 | Lock(); | |
256 | return true; | |
257 | } | |
258 | } | |
259 | } | |
6cc4a62c | 260 | |
4e87d341 MC |
261 | return false; |
262 | } | |
263 | ||
ed6d0b5f PW |
264 | void CWallet::SetBestChain(const CBlockLocator& loc) |
265 | { | |
266 | CWalletDB walletdb(strWalletFile); | |
267 | walletdb.WriteBestBlock(loc); | |
268 | } | |
7414733b | 269 | |
439e1497 | 270 | bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit) |
0b807a41 | 271 | { |
ca4cf5cf | 272 | LOCK(cs_wallet); // nWalletVersion |
0b807a41 PW |
273 | if (nWalletVersion >= nVersion) |
274 | return true; | |
275 | ||
439e1497 PW |
276 | // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way |
277 | if (fExplicit && nVersion > nWalletMaxVersion) | |
278 | nVersion = FEATURE_LATEST; | |
279 | ||
0b807a41 PW |
280 | nWalletVersion = nVersion; |
281 | ||
439e1497 PW |
282 | if (nVersion > nWalletMaxVersion) |
283 | nWalletMaxVersion = nVersion; | |
284 | ||
0b807a41 PW |
285 | if (fFileBacked) |
286 | { | |
287 | CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile); | |
0b807a41 PW |
288 | if (nWalletVersion > 40000) |
289 | pwalletdb->WriteMinVersion(nWalletVersion); | |
290 | if (!pwalletdbIn) | |
291 | delete pwalletdb; | |
292 | } | |
293 | ||
294 | return true; | |
295 | } | |
296 | ||
439e1497 PW |
297 | bool CWallet::SetMaxVersion(int nVersion) |
298 | { | |
ca4cf5cf | 299 | LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion |
439e1497 PW |
300 | // cannot downgrade below current version |
301 | if (nWalletVersion > nVersion) | |
302 | return false; | |
303 | ||
304 | nWalletMaxVersion = nVersion; | |
305 | ||
306 | return true; | |
307 | } | |
308 | ||
3015e0bc | 309 | set<uint256> CWallet::GetConflicts(const uint256& txid) const |
731b89b8 GA |
310 | { |
311 | set<uint256> result; | |
312 | AssertLockHeld(cs_wallet); | |
313 | ||
314 | std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid); | |
315 | if (it == mapWallet.end()) | |
316 | return result; | |
317 | const CWalletTx& wtx = it->second; | |
318 | ||
93a18a36 | 319 | std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range; |
731b89b8 GA |
320 | |
321 | BOOST_FOREACH(const CTxIn& txin, wtx.vin) | |
322 | { | |
93a18a36 GA |
323 | if (mapTxSpends.count(txin.prevout) <= 1) |
324 | continue; // No conflict if zero or one spends | |
325 | range = mapTxSpends.equal_range(txin.prevout); | |
326 | for (TxSpends::const_iterator it = range.first; it != range.second; ++it) | |
3015e0bc | 327 | result.insert(it->second); |
731b89b8 GA |
328 | } |
329 | return result; | |
330 | } | |
331 | ||
93a18a36 | 332 | void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range) |
731b89b8 GA |
333 | { |
334 | // We want all the wallet transactions in range to have the same metadata as | |
335 | // the oldest (smallest nOrderPos). | |
336 | // So: find smallest nOrderPos: | |
337 | ||
338 | int nMinOrderPos = std::numeric_limits<int>::max(); | |
339 | const CWalletTx* copyFrom = NULL; | |
93a18a36 | 340 | for (TxSpends::iterator it = range.first; it != range.second; ++it) |
731b89b8 GA |
341 | { |
342 | const uint256& hash = it->second; | |
343 | int n = mapWallet[hash].nOrderPos; | |
344 | if (n < nMinOrderPos) | |
345 | { | |
346 | nMinOrderPos = n; | |
347 | copyFrom = &mapWallet[hash]; | |
348 | } | |
349 | } | |
350 | // Now copy data from copyFrom to rest: | |
93a18a36 | 351 | for (TxSpends::iterator it = range.first; it != range.second; ++it) |
731b89b8 GA |
352 | { |
353 | const uint256& hash = it->second; | |
354 | CWalletTx* copyTo = &mapWallet[hash]; | |
355 | if (copyFrom == copyTo) continue; | |
356 | copyTo->mapValue = copyFrom->mapValue; | |
357 | copyTo->vOrderForm = copyFrom->vOrderForm; | |
358 | // fTimeReceivedIsTxTime not copied on purpose | |
359 | // nTimeReceived not copied on purpose | |
360 | copyTo->nTimeSmart = copyFrom->nTimeSmart; | |
361 | copyTo->fFromMe = copyFrom->fFromMe; | |
362 | copyTo->strFromAccount = copyFrom->strFromAccount; | |
731b89b8 GA |
363 | // nOrderPos not copied on purpose |
364 | // cached members not copied on purpose | |
365 | } | |
366 | } | |
367 | ||
93a18a36 GA |
368 | // Outpoint is spent if any non-conflicted transaction |
369 | // spends it: | |
370 | bool CWallet::IsSpent(const uint256& hash, unsigned int n) const | |
731b89b8 | 371 | { |
93a18a36 GA |
372 | const COutPoint outpoint(hash, n); |
373 | pair<TxSpends::const_iterator, TxSpends::const_iterator> range; | |
374 | range = mapTxSpends.equal_range(outpoint); | |
731b89b8 | 375 | |
93a18a36 | 376 | for (TxSpends::const_iterator it = range.first; it != range.second; ++it) |
731b89b8 | 377 | { |
93a18a36 GA |
378 | const uint256& wtxid = it->second; |
379 | std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid); | |
380 | if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) | |
381 | return true; // Spent | |
731b89b8 | 382 | } |
93a18a36 GA |
383 | return false; |
384 | } | |
385 | ||
386 | void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid) | |
387 | { | |
388 | mapTxSpends.insert(make_pair(outpoint, wtxid)); | |
389 | ||
390 | pair<TxSpends::iterator, TxSpends::iterator> range; | |
391 | range = mapTxSpends.equal_range(outpoint); | |
392 | SyncMetaData(range); | |
393 | } | |
394 | ||
395 | ||
396 | void CWallet::AddToSpends(const uint256& wtxid) | |
397 | { | |
398 | assert(mapWallet.count(wtxid)); | |
399 | CWalletTx& thisTx = mapWallet[wtxid]; | |
400 | if (thisTx.IsCoinBase()) // Coinbases don't spend anything! | |
401 | return; | |
402 | ||
403 | BOOST_FOREACH(const CTxIn& txin, thisTx.vin) | |
404 | AddToSpends(txin.prevout, wtxid); | |
731b89b8 GA |
405 | } |
406 | ||
94f778bd | 407 | bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) |
4e87d341 | 408 | { |
6cc4a62c GA |
409 | if (IsCrypted()) |
410 | return false; | |
4e87d341 | 411 | |
6cc4a62c GA |
412 | CKeyingMaterial vMasterKey; |
413 | RandAddSeedPerfmon(); | |
4e87d341 | 414 | |
6cc4a62c | 415 | vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE); |
001a53d7 PK |
416 | if (!GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE)) |
417 | return false; | |
4e87d341 | 418 | |
6cc4a62c | 419 | CMasterKey kMasterKey; |
6cc4a62c | 420 | RandAddSeedPerfmon(); |
001a53d7 | 421 | |
6cc4a62c | 422 | kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE); |
001a53d7 PK |
423 | if (!GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE)) |
424 | return false; | |
4e87d341 | 425 | |
6cc4a62c | 426 | CCrypter crypter; |
51ed9ec9 | 427 | int64_t nStartTime = GetTimeMillis(); |
6cc4a62c GA |
428 | crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod); |
429 | kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime)); | |
ddebdd9a | 430 | |
6cc4a62c GA |
431 | nStartTime = GetTimeMillis(); |
432 | crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod); | |
433 | kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; | |
ddebdd9a | 434 | |
6cc4a62c GA |
435 | if (kMasterKey.nDeriveIterations < 25000) |
436 | kMasterKey.nDeriveIterations = 25000; | |
ddebdd9a | 437 | |
881a85a2 | 438 | LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations); |
ddebdd9a | 439 | |
6cc4a62c GA |
440 | if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod)) |
441 | return false; | |
442 | if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey)) | |
443 | return false; | |
4e87d341 | 444 | |
6cc4a62c | 445 | { |
f8dcd5ca | 446 | LOCK(cs_wallet); |
4e87d341 MC |
447 | mapMasterKeys[++nMasterKeyMaxID] = kMasterKey; |
448 | if (fFileBacked) | |
449 | { | |
96f34cd5 | 450 | pwalletdbEncryption = new CWalletDB(strWalletFile); |
0fb78eae JG |
451 | if (!pwalletdbEncryption->TxnBegin()) |
452 | return false; | |
96f34cd5 | 453 | pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey); |
4e87d341 MC |
454 | } |
455 | ||
456 | if (!EncryptKeys(vMasterKey)) | |
96f34cd5 MC |
457 | { |
458 | if (fFileBacked) | |
459 | pwalletdbEncryption->TxnAbort(); | |
460 | exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet. | |
461 | } | |
462 | ||
0b807a41 | 463 | // Encryption was introduced in version 0.4.0 |
439e1497 | 464 | SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true); |
0b807a41 | 465 | |
96f34cd5 MC |
466 | if (fFileBacked) |
467 | { | |
468 | if (!pwalletdbEncryption->TxnCommit()) | |
469 | exit(1); //We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet. | |
470 | ||
fcfd7ff8 | 471 | delete pwalletdbEncryption; |
96f34cd5 MC |
472 | pwalletdbEncryption = NULL; |
473 | } | |
4e87d341 | 474 | |
37971fcc GA |
475 | Lock(); |
476 | Unlock(strWalletPassphrase); | |
477 | NewKeyPool(); | |
4e87d341 | 478 | Lock(); |
6cc4a62c | 479 | |
d764d916 GA |
480 | // Need to completely rewrite the wallet file; if we don't, bdb might keep |
481 | // bits of the unencrypted private key in slack space in the database file. | |
b2d3b2d6 | 482 | CDB::Rewrite(strWalletFile); |
fe4a6550 | 483 | |
d764d916 | 484 | } |
ab1b288f | 485 | NotifyStatusChanged(this); |
9e9869d0 | 486 | |
4e87d341 | 487 | return true; |
e8ef3da7 WL |
488 | } |
489 | ||
51ed9ec9 | 490 | int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb) |
da7b8c12 | 491 | { |
95691680 | 492 | AssertLockHeld(cs_wallet); // nOrderPosNext |
51ed9ec9 | 493 | int64_t nRet = nOrderPosNext++; |
4291e8fe PW |
494 | if (pwalletdb) { |
495 | pwalletdb->WriteOrderPosNext(nOrderPosNext); | |
496 | } else { | |
497 | CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext); | |
498 | } | |
da7b8c12 LD |
499 | return nRet; |
500 | } | |
501 | ||
ddb709e9 | 502 | CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount) |
c3f95ef1 | 503 | { |
95691680 | 504 | AssertLockHeld(cs_wallet); // mapWallet |
c3f95ef1 LD |
505 | CWalletDB walletdb(strWalletFile); |
506 | ||
507 | // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap. | |
508 | TxItems txOrdered; | |
509 | ||
510 | // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry | |
511 | // would make this much faster for applications that do this a lot. | |
512 | for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) | |
513 | { | |
514 | CWalletTx* wtx = &((*it).second); | |
515 | txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0))); | |
516 | } | |
ddb709e9 | 517 | acentries.clear(); |
c3f95ef1 LD |
518 | walletdb.ListAccountCreditDebit(strAccount, acentries); |
519 | BOOST_FOREACH(CAccountingEntry& entry, acentries) | |
520 | { | |
521 | txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry))); | |
522 | } | |
523 | ||
524 | return txOrdered; | |
525 | } | |
526 | ||
95d888a6 PW |
527 | void CWallet::MarkDirty() |
528 | { | |
95d888a6 | 529 | { |
f8dcd5ca | 530 | LOCK(cs_wallet); |
95d888a6 PW |
531 | BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) |
532 | item.second.MarkDirty(); | |
533 | } | |
534 | } | |
535 | ||
731b89b8 | 536 | bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet) |
e8ef3da7 WL |
537 | { |
538 | uint256 hash = wtxIn.GetHash(); | |
731b89b8 GA |
539 | |
540 | if (fFromLoadWallet) | |
541 | { | |
542 | mapWallet[hash] = wtxIn; | |
09ec3af1 | 543 | mapWallet[hash].BindWallet(this); |
93a18a36 | 544 | AddToSpends(hash); |
731b89b8 GA |
545 | } |
546 | else | |
e8ef3da7 | 547 | { |
f8dcd5ca | 548 | LOCK(cs_wallet); |
e8ef3da7 WL |
549 | // Inserts only if not already there, returns tx inserted or tx found |
550 | pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn)); | |
551 | CWalletTx& wtx = (*ret.first).second; | |
4c6e2295 | 552 | wtx.BindWallet(this); |
e8ef3da7 WL |
553 | bool fInsertedNew = ret.second; |
554 | if (fInsertedNew) | |
9c7722b7 | 555 | { |
e8ef3da7 | 556 | wtx.nTimeReceived = GetAdjustedTime(); |
da7b8c12 | 557 | wtx.nOrderPos = IncOrderPosNext(); |
c3f95ef1 LD |
558 | |
559 | wtx.nTimeSmart = wtx.nTimeReceived; | |
560 | if (wtxIn.hashBlock != 0) | |
561 | { | |
562 | if (mapBlockIndex.count(wtxIn.hashBlock)) | |
563 | { | |
209377a7 | 564 | int64_t latestNow = wtx.nTimeReceived; |
565 | int64_t latestEntry = 0; | |
c3f95ef1 LD |
566 | { |
567 | // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future | |
51ed9ec9 | 568 | int64_t latestTolerated = latestNow + 300; |
ddb709e9 LD |
569 | std::list<CAccountingEntry> acentries; |
570 | TxItems txOrdered = OrderedTxItems(acentries); | |
c3f95ef1 LD |
571 | for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) |
572 | { | |
573 | CWalletTx *const pwtx = (*it).second.first; | |
574 | if (pwtx == &wtx) | |
575 | continue; | |
576 | CAccountingEntry *const pacentry = (*it).second.second; | |
51ed9ec9 | 577 | int64_t nSmartTime; |
c3f95ef1 LD |
578 | if (pwtx) |
579 | { | |
580 | nSmartTime = pwtx->nTimeSmart; | |
581 | if (!nSmartTime) | |
582 | nSmartTime = pwtx->nTimeReceived; | |
583 | } | |
584 | else | |
585 | nSmartTime = pacentry->nTime; | |
586 | if (nSmartTime <= latestTolerated) | |
587 | { | |
588 | latestEntry = nSmartTime; | |
589 | if (nSmartTime > latestNow) | |
590 | latestNow = nSmartTime; | |
591 | break; | |
592 | } | |
593 | } | |
594 | } | |
595 | ||
209377a7 | 596 | int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime(); |
c3f95ef1 LD |
597 | wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow)); |
598 | } | |
599 | else | |
881a85a2 | 600 | LogPrintf("AddToWallet() : found %s in block %s not in index\n", |
7d9d134b WL |
601 | wtxIn.GetHash().ToString(), |
602 | wtxIn.hashBlock.ToString()); | |
c3f95ef1 | 603 | } |
93a18a36 | 604 | AddToSpends(hash); |
9c7722b7 | 605 | } |
e8ef3da7 WL |
606 | |
607 | bool fUpdated = false; | |
608 | if (!fInsertedNew) | |
609 | { | |
610 | // Merge | |
611 | if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) | |
612 | { | |
613 | wtx.hashBlock = wtxIn.hashBlock; | |
614 | fUpdated = true; | |
615 | } | |
616 | if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex)) | |
617 | { | |
618 | wtx.vMerkleBranch = wtxIn.vMerkleBranch; | |
619 | wtx.nIndex = wtxIn.nIndex; | |
620 | fUpdated = true; | |
621 | } | |
622 | if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) | |
623 | { | |
624 | wtx.fFromMe = wtxIn.fFromMe; | |
625 | fUpdated = true; | |
626 | } | |
e8ef3da7 WL |
627 | } |
628 | ||
629 | //// debug print | |
7d9d134b | 630 | LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : "")); |
e8ef3da7 WL |
631 | |
632 | // Write to disk | |
633 | if (fInsertedNew || fUpdated) | |
634 | if (!wtx.WriteToDisk()) | |
635 | return false; | |
ee4b170c | 636 | |
93a18a36 GA |
637 | // Break debit/credit balance caches: |
638 | wtx.MarkDirty(); | |
e8ef3da7 | 639 | |
fe4a6550 WL |
640 | // Notify UI of new or updated transaction |
641 | NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED); | |
cae686d3 | 642 | |
643 | // notify an external script when a wallet transaction comes in or is updated | |
644 | std::string strCmd = GetArg("-walletnotify", ""); | |
645 | ||
646 | if ( !strCmd.empty()) | |
647 | { | |
648 | boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex()); | |
649 | boost::thread t(runCommand, strCmd); // thread runs free | |
650 | } | |
651 | ||
fe4a6550 | 652 | } |
e8ef3da7 WL |
653 | return true; |
654 | } | |
655 | ||
d825e6a3 PW |
656 | // Add a transaction to the wallet, or update it. |
657 | // pblock is optional, but should be provided if the transaction is known to be in a block. | |
658 | // If fUpdate is true, existing transactions will be updated. | |
d38da59b | 659 | bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate) |
e8ef3da7 | 660 | { |
e8ef3da7 | 661 | { |
53d56881 | 662 | AssertLockHeld(cs_wallet); |
8d657a65 | 663 | bool fExisted = mapWallet.count(tx.GetHash()) != 0; |
6cc4a62c | 664 | if (fExisted && !fUpdate) return false; |
3015e0bc | 665 | if (fExisted || IsMine(tx) || IsFromMe(tx)) |
6cc4a62c GA |
666 | { |
667 | CWalletTx wtx(this,tx); | |
668 | // Get merkle branch if transaction was found in a block | |
669 | if (pblock) | |
4b0deb3b | 670 | wtx.SetMerkleBranch(*pblock); |
6cc4a62c GA |
671 | return AddToWallet(wtx); |
672 | } | |
e8ef3da7 | 673 | } |
e8ef3da7 WL |
674 | return false; |
675 | } | |
676 | ||
d38da59b | 677 | void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock) |
93a18a36 | 678 | { |
55a1db4f | 679 | LOCK2(cs_main, cs_wallet); |
d38da59b | 680 | if (!AddToWalletIfInvolvingMe(tx, pblock, true)) |
93a18a36 GA |
681 | return; // Not one of ours |
682 | ||
683 | // If a transaction changes 'conflicted' state, that changes the balance | |
684 | // available of the outputs it spends. So force those to be | |
685 | // recomputed, also: | |
686 | BOOST_FOREACH(const CTxIn& txin, tx.vin) | |
687 | { | |
688 | if (mapWallet.count(txin.prevout.hash)) | |
689 | mapWallet[txin.prevout.hash].MarkDirty(); | |
690 | } | |
00588c3f PW |
691 | } |
692 | ||
693 | void CWallet::EraseFromWallet(const uint256 &hash) | |
e8ef3da7 WL |
694 | { |
695 | if (!fFileBacked) | |
00588c3f | 696 | return; |
e8ef3da7 | 697 | { |
f8dcd5ca | 698 | LOCK(cs_wallet); |
e8ef3da7 WL |
699 | if (mapWallet.erase(hash)) |
700 | CWalletDB(strWalletFile).EraseTx(hash); | |
701 | } | |
00588c3f | 702 | return; |
e8ef3da7 WL |
703 | } |
704 | ||
705 | ||
c8988460 | 706 | isminetype CWallet::IsMine(const CTxIn &txin) const |
e8ef3da7 | 707 | { |
e8ef3da7 | 708 | { |
f8dcd5ca | 709 | LOCK(cs_wallet); |
e8ef3da7 WL |
710 | map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); |
711 | if (mi != mapWallet.end()) | |
712 | { | |
713 | const CWalletTx& prev = (*mi).second; | |
714 | if (txin.prevout.n < prev.vout.size()) | |
c8988460 | 715 | return IsMine(prev.vout[txin.prevout.n]); |
e8ef3da7 WL |
716 | } |
717 | } | |
a3e192a3 | 718 | return ISMINE_NO; |
e8ef3da7 WL |
719 | } |
720 | ||
a372168e | 721 | CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const |
e8ef3da7 | 722 | { |
e8ef3da7 | 723 | { |
f8dcd5ca | 724 | LOCK(cs_wallet); |
e8ef3da7 WL |
725 | map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); |
726 | if (mi != mapWallet.end()) | |
727 | { | |
728 | const CWalletTx& prev = (*mi).second; | |
729 | if (txin.prevout.n < prev.vout.size()) | |
d4640d7d | 730 | if (IsMine(prev.vout[txin.prevout.n]) & filter) |
e8ef3da7 WL |
731 | return prev.vout[txin.prevout.n].nValue; |
732 | } | |
733 | } | |
734 | return 0; | |
735 | } | |
736 | ||
e679ec96 GA |
737 | bool CWallet::IsChange(const CTxOut& txout) const |
738 | { | |
2a45a494 | 739 | // TODO: fix handling of 'change' outputs. The assumption is that any |
d5087d1b | 740 | // payment to a script that is ours, but is not in the address book |
2a45a494 GA |
741 | // is change. That assumption is likely to break when we implement multisignature |
742 | // wallets that return change back into a multi-signature-protected address; | |
743 | // a better way of identifying which outputs are 'the send' and which are | |
744 | // 'the change' will need to be implemented (maybe extend CWalletTx to remember | |
745 | // which output, if any, was change). | |
d5087d1b | 746 | if (::IsMine(*this, txout.scriptPubKey)) |
f8dcd5ca | 747 | { |
d5087d1b PW |
748 | CTxDestination address; |
749 | if (!ExtractDestination(txout.scriptPubKey, address)) | |
750 | return true; | |
751 | ||
f8dcd5ca PW |
752 | LOCK(cs_wallet); |
753 | if (!mapAddressBook.count(address)) | |
754 | return true; | |
755 | } | |
e679ec96 GA |
756 | return false; |
757 | } | |
758 | ||
51ed9ec9 | 759 | int64_t CWalletTx::GetTxTime() const |
e8ef3da7 | 760 | { |
51ed9ec9 | 761 | int64_t n = nTimeSmart; |
c3f95ef1 | 762 | return n ? n : nTimeReceived; |
e8ef3da7 WL |
763 | } |
764 | ||
765 | int CWalletTx::GetRequestCount() const | |
766 | { | |
767 | // Returns -1 if it wasn't being tracked | |
768 | int nRequests = -1; | |
e8ef3da7 | 769 | { |
f8dcd5ca | 770 | LOCK(pwallet->cs_wallet); |
e8ef3da7 WL |
771 | if (IsCoinBase()) |
772 | { | |
773 | // Generated block | |
774 | if (hashBlock != 0) | |
775 | { | |
776 | map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); | |
777 | if (mi != pwallet->mapRequestCount.end()) | |
778 | nRequests = (*mi).second; | |
779 | } | |
780 | } | |
781 | else | |
782 | { | |
783 | // Did anyone request this transaction? | |
784 | map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash()); | |
785 | if (mi != pwallet->mapRequestCount.end()) | |
786 | { | |
787 | nRequests = (*mi).second; | |
788 | ||
789 | // How about the block it's in? | |
790 | if (nRequests == 0 && hashBlock != 0) | |
791 | { | |
792 | map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); | |
793 | if (mi != pwallet->mapRequestCount.end()) | |
794 | nRequests = (*mi).second; | |
795 | else | |
796 | nRequests = 1; // If it's in someone else's block it must have got out | |
797 | } | |
798 | } | |
799 | } | |
800 | } | |
801 | return nRequests; | |
802 | } | |
803 | ||
1b4568cb | 804 | void CWalletTx::GetAmounts(list<COutputEntry>& listReceived, |
a372168e | 805 | list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const |
e8ef3da7 | 806 | { |
e07c8e91 | 807 | nFee = 0; |
e8ef3da7 WL |
808 | listReceived.clear(); |
809 | listSent.clear(); | |
810 | strSentAccount = strFromAccount; | |
811 | ||
e8ef3da7 | 812 | // Compute fee: |
a372168e | 813 | CAmount nDebit = GetDebit(filter); |
e8ef3da7 WL |
814 | if (nDebit > 0) // debit>0 means we signed/sent this transaction |
815 | { | |
a372168e | 816 | CAmount nValueOut = GetValueOut(); |
e8ef3da7 WL |
817 | nFee = nDebit - nValueOut; |
818 | } | |
819 | ||
e679ec96 | 820 | // Sent/received. |
5bb76550 | 821 | for (unsigned int i = 0; i < vout.size(); ++i) |
e8ef3da7 | 822 | { |
1b4568cb | 823 | const CTxOut& txout = vout[i]; |
a5c6c5d6 | 824 | isminetype fIsMine = pwallet->IsMine(txout); |
96ed6821 LD |
825 | // Only need to handle txouts if AT LEAST one of these is true: |
826 | // 1) they debit from us (sent) | |
827 | // 2) the output is to us (received) | |
828 | if (nDebit > 0) | |
829 | { | |
830 | // Don't report 'change' txouts | |
831 | if (pwallet->IsChange(txout)) | |
832 | continue; | |
96ed6821 | 833 | } |
a5c6c5d6 | 834 | else if (!(fIsMine & filter)) |
96ed6821 LD |
835 | continue; |
836 | ||
837 | // In either case, we need to get the destination address | |
10254401 | 838 | CTxDestination address; |
10254401 | 839 | if (!ExtractDestination(txout.scriptPubKey, address)) |
e8ef3da7 | 840 | { |
881a85a2 | 841 | LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", |
7d9d134b | 842 | this->GetHash().ToString()); |
96ed6821 | 843 | address = CNoDestination(); |
e8ef3da7 WL |
844 | } |
845 | ||
5bb76550 | 846 | COutputEntry output = {address, txout.nValue, (int)i}; |
1b4568cb | 847 | |
96ed6821 | 848 | // If we are debited by the transaction, add the output as a "sent" entry |
e8ef3da7 | 849 | if (nDebit > 0) |
1b4568cb | 850 | listSent.push_back(output); |
e8ef3da7 | 851 | |
96ed6821 | 852 | // If we are receiving the output, add it as a "received" entry |
d512534c | 853 | if (fIsMine & filter) |
1b4568cb | 854 | listReceived.push_back(output); |
e8ef3da7 WL |
855 | } |
856 | ||
857 | } | |
858 | ||
a372168e MF |
859 | void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived, |
860 | CAmount& nSent, CAmount& nFee, const isminefilter& filter) const | |
e8ef3da7 | 861 | { |
e07c8e91 | 862 | nReceived = nSent = nFee = 0; |
e8ef3da7 | 863 | |
a372168e | 864 | CAmount allFee; |
e8ef3da7 | 865 | string strSentAccount; |
1b4568cb CL |
866 | list<COutputEntry> listReceived; |
867 | list<COutputEntry> listSent; | |
d4640d7d | 868 | GetAmounts(listReceived, listSent, allFee, strSentAccount, filter); |
e8ef3da7 | 869 | |
e8ef3da7 WL |
870 | if (strAccount == strSentAccount) |
871 | { | |
1b4568cb CL |
872 | BOOST_FOREACH(const COutputEntry& s, listSent) |
873 | nSent += s.amount; | |
e8ef3da7 WL |
874 | nFee = allFee; |
875 | } | |
e8ef3da7 | 876 | { |
f8dcd5ca | 877 | LOCK(pwallet->cs_wallet); |
1b4568cb | 878 | BOOST_FOREACH(const COutputEntry& r, listReceived) |
e8ef3da7 | 879 | { |
1b4568cb | 880 | if (pwallet->mapAddressBook.count(r.destination)) |
e8ef3da7 | 881 | { |
1b4568cb | 882 | map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination); |
61885513 | 883 | if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount) |
1b4568cb | 884 | nReceived += r.amount; |
e8ef3da7 WL |
885 | } |
886 | else if (strAccount.empty()) | |
887 | { | |
1b4568cb | 888 | nReceived += r.amount; |
e8ef3da7 WL |
889 | } |
890 | } | |
891 | } | |
892 | } | |
893 | ||
722fa283 | 894 | |
e8ef3da7 WL |
895 | bool CWalletTx::WriteToDisk() |
896 | { | |
897 | return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this); | |
898 | } | |
899 | ||
d825e6a3 PW |
900 | // Scan the block chain (starting in pindexStart) for transactions |
901 | // from or to us. If fUpdate is true, found transactions that already | |
902 | // exist in the wallet will be updated. | |
e8ef3da7 WL |
903 | int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) |
904 | { | |
905 | int ret = 0; | |
75b8953a | 906 | int64_t nNow = GetTime(); |
e8ef3da7 WL |
907 | |
908 | CBlockIndex* pindex = pindexStart; | |
e8ef3da7 | 909 | { |
55a1db4f | 910 | LOCK2(cs_main, cs_wallet); |
39278369 CL |
911 | |
912 | // no need to read and scan block, if block was created before | |
913 | // our wallet birthday (as adjusted for block time variability) | |
209377a7 | 914 | while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200))) |
39278369 CL |
915 | pindex = chainActive.Next(pindex); |
916 | ||
917 | ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup | |
918 | double dProgressStart = Checkpoints::GuessVerificationProgress(pindex, false); | |
919 | double dProgressTip = Checkpoints::GuessVerificationProgress(chainActive.Tip(), false); | |
e8ef3da7 WL |
920 | while (pindex) |
921 | { | |
39278369 CL |
922 | if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0) |
923 | ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100)))); | |
8da9dd07 | 924 | |
e8ef3da7 | 925 | CBlock block; |
7db120d5 | 926 | ReadBlockFromDisk(block, pindex); |
e8ef3da7 WL |
927 | BOOST_FOREACH(CTransaction& tx, block.vtx) |
928 | { | |
d38da59b | 929 | if (AddToWalletIfInvolvingMe(tx, &block, fUpdate)) |
e8ef3da7 WL |
930 | ret++; |
931 | } | |
4c6d41b8 | 932 | pindex = chainActive.Next(pindex); |
75b8953a B |
933 | if (GetTime() >= nNow + 60) { |
934 | nNow = GetTime(); | |
935 | LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(pindex)); | |
936 | } | |
e8ef3da7 | 937 | } |
39278369 | 938 | ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI |
e8ef3da7 WL |
939 | } |
940 | return ret; | |
941 | } | |
942 | ||
943 | void CWallet::ReacceptWalletTransactions() | |
944 | { | |
55a1db4f | 945 | LOCK2(cs_main, cs_wallet); |
93a18a36 | 946 | BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) |
e8ef3da7 | 947 | { |
93a18a36 GA |
948 | const uint256& wtxid = item.first; |
949 | CWalletTx& wtx = item.second; | |
950 | assert(wtx.GetHash() == wtxid); | |
e8ef3da7 | 951 | |
93a18a36 GA |
952 | int nDepth = wtx.GetDepthInMainChain(); |
953 | ||
3015e0bc | 954 | if (!wtx.IsCoinBase() && nDepth < 0) |
e8ef3da7 | 955 | { |
93a18a36 GA |
956 | // Try to add to memory pool |
957 | LOCK(mempool.cs); | |
958 | wtx.AcceptToMemoryPool(false); | |
e8ef3da7 WL |
959 | } |
960 | } | |
961 | } | |
962 | ||
ae8bfd12 | 963 | void CWalletTx::RelayWalletTransaction() |
e8ef3da7 | 964 | { |
e8ef3da7 WL |
965 | if (!IsCoinBase()) |
966 | { | |
5eaf91a4 | 967 | if (GetDepthInMainChain() == 0) { |
d38da59b PW |
968 | LogPrintf("Relaying wtx %s\n", GetHash().ToString()); |
969 | RelayTransaction((CTransaction)*this); | |
e8ef3da7 WL |
970 | } |
971 | } | |
972 | } | |
973 | ||
3015e0bc | 974 | set<uint256> CWalletTx::GetConflicts() const |
731b89b8 GA |
975 | { |
976 | set<uint256> result; | |
977 | if (pwallet != NULL) | |
978 | { | |
979 | uint256 myHash = GetHash(); | |
3015e0bc | 980 | result = pwallet->GetConflicts(myHash); |
731b89b8 GA |
981 | result.erase(myHash); |
982 | } | |
983 | return result; | |
984 | } | |
985 | ||
e8ef3da7 WL |
986 | void CWallet::ResendWalletTransactions() |
987 | { | |
988 | // Do this infrequently and randomly to avoid giving away | |
989 | // that these are our transactions. | |
203d1ae6 | 990 | if (GetTime() < nNextResend) |
e8ef3da7 | 991 | return; |
203d1ae6 LD |
992 | bool fFirst = (nNextResend == 0); |
993 | nNextResend = GetTime() + GetRand(30 * 60); | |
e8ef3da7 WL |
994 | if (fFirst) |
995 | return; | |
996 | ||
997 | // Only do it if there's been a new block since last time | |
203d1ae6 | 998 | if (nTimeBestReceived < nLastResend) |
e8ef3da7 | 999 | return; |
203d1ae6 | 1000 | nLastResend = GetTime(); |
e8ef3da7 WL |
1001 | |
1002 | // Rebroadcast any of our txes that aren't in a block yet | |
881a85a2 | 1003 | LogPrintf("ResendWalletTransactions()\n"); |
e8ef3da7 | 1004 | { |
f8dcd5ca | 1005 | LOCK(cs_wallet); |
e8ef3da7 WL |
1006 | // Sort them in chronological order |
1007 | multimap<unsigned int, CWalletTx*> mapSorted; | |
1008 | BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) | |
1009 | { | |
1010 | CWalletTx& wtx = item.second; | |
1011 | // Don't rebroadcast until it's had plenty of time that | |
1012 | // it should have gotten in already by now. | |
51ed9ec9 | 1013 | if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60) |
e8ef3da7 WL |
1014 | mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); |
1015 | } | |
1016 | BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted) | |
1017 | { | |
1018 | CWalletTx& wtx = *item.second; | |
ae8bfd12 | 1019 | wtx.RelayWalletTransaction(); |
e8ef3da7 WL |
1020 | } |
1021 | } | |
1022 | } | |
1023 | ||
1024 | ||
1025 | ||
1026 | ||
1027 | ||
1028 | ||
1029 | ////////////////////////////////////////////////////////////////////////////// | |
1030 | // | |
1031 | // Actions | |
1032 | // | |
1033 | ||
1034 | ||
a372168e | 1035 | CAmount CWallet::GetBalance() const |
e8ef3da7 | 1036 | { |
a372168e | 1037 | CAmount nTotal = 0; |
e8ef3da7 | 1038 | { |
55a1db4f | 1039 | LOCK2(cs_main, cs_wallet); |
e8ef3da7 WL |
1040 | for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) |
1041 | { | |
1042 | const CWalletTx* pcoin = &(*it).second; | |
0542619d | 1043 | if (pcoin->IsTrusted()) |
8fdb7e10 | 1044 | nTotal += pcoin->GetAvailableCredit(); |
e8ef3da7 WL |
1045 | } |
1046 | } | |
1047 | ||
e8ef3da7 WL |
1048 | return nTotal; |
1049 | } | |
1050 | ||
a372168e | 1051 | CAmount CWallet::GetUnconfirmedBalance() const |
df5ccbd2 | 1052 | { |
a372168e | 1053 | CAmount nTotal = 0; |
df5ccbd2 | 1054 | { |
55a1db4f | 1055 | LOCK2(cs_main, cs_wallet); |
df5ccbd2 WL |
1056 | for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) |
1057 | { | |
1058 | const CWalletTx* pcoin = &(*it).second; | |
731b89b8 | 1059 | if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) |
8fdb7e10 | 1060 | nTotal += pcoin->GetAvailableCredit(); |
1061 | } | |
1062 | } | |
1063 | return nTotal; | |
1064 | } | |
1065 | ||
a372168e | 1066 | CAmount CWallet::GetImmatureBalance() const |
8fdb7e10 | 1067 | { |
a372168e | 1068 | CAmount nTotal = 0; |
8fdb7e10 | 1069 | { |
55a1db4f | 1070 | LOCK2(cs_main, cs_wallet); |
8fdb7e10 | 1071 | for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) |
1072 | { | |
966a0e8c PK |
1073 | const CWalletTx* pcoin = &(*it).second; |
1074 | nTotal += pcoin->GetImmatureCredit(); | |
df5ccbd2 WL |
1075 | } |
1076 | } | |
1077 | return nTotal; | |
1078 | } | |
e8ef3da7 | 1079 | |
a372168e | 1080 | CAmount CWallet::GetWatchOnlyBalance() const |
ffd40da3 | 1081 | { |
a372168e | 1082 | CAmount nTotal = 0; |
ffd40da3 | 1083 | { |
39cc4922 | 1084 | LOCK2(cs_main, cs_wallet); |
ffd40da3 J |
1085 | for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) |
1086 | { | |
1087 | const CWalletTx* pcoin = &(*it).second; | |
1088 | if (pcoin->IsTrusted()) | |
1089 | nTotal += pcoin->GetAvailableWatchOnlyCredit(); | |
1090 | } | |
1091 | } | |
1092 | ||
1093 | return nTotal; | |
1094 | } | |
1095 | ||
a372168e | 1096 | CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const |
ffd40da3 | 1097 | { |
a372168e | 1098 | CAmount nTotal = 0; |
ffd40da3 | 1099 | { |
39cc4922 | 1100 | LOCK2(cs_main, cs_wallet); |
ffd40da3 J |
1101 | for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) |
1102 | { | |
1103 | const CWalletTx* pcoin = &(*it).second; | |
1104 | if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) | |
1105 | nTotal += pcoin->GetAvailableWatchOnlyCredit(); | |
1106 | } | |
1107 | } | |
1108 | return nTotal; | |
1109 | } | |
1110 | ||
a372168e | 1111 | CAmount CWallet::GetImmatureWatchOnlyBalance() const |
ffd40da3 | 1112 | { |
a372168e | 1113 | CAmount nTotal = 0; |
ffd40da3 | 1114 | { |
39cc4922 | 1115 | LOCK2(cs_main, cs_wallet); |
ffd40da3 J |
1116 | for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) |
1117 | { | |
1118 | const CWalletTx* pcoin = &(*it).second; | |
1119 | nTotal += pcoin->GetImmatureWatchOnlyCredit(); | |
1120 | } | |
1121 | } | |
1122 | return nTotal; | |
1123 | } | |
1124 | ||
c8988460 | 1125 | // populate vCoins with vector of available COutputs. |
6a86c24d | 1126 | void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const |
9b0369c7 CM |
1127 | { |
1128 | vCoins.clear(); | |
1129 | ||
1130 | { | |
ea3acaf3 | 1131 | LOCK2(cs_main, cs_wallet); |
9b0369c7 CM |
1132 | for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) |
1133 | { | |
93a18a36 | 1134 | const uint256& wtxid = it->first; |
9b0369c7 CM |
1135 | const CWalletTx* pcoin = &(*it).second; |
1136 | ||
05df3fc6 | 1137 | if (!IsFinalTx(*pcoin)) |
a2709fad GA |
1138 | continue; |
1139 | ||
0542619d | 1140 | if (fOnlyConfirmed && !pcoin->IsTrusted()) |
9b0369c7 CM |
1141 | continue; |
1142 | ||
1143 | if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) | |
1144 | continue; | |
1145 | ||
2b72d46f GA |
1146 | int nDepth = pcoin->GetDepthInMainChain(); |
1147 | if (nDepth < 0) | |
1148 | continue; | |
1149 | ||
fdbb537d | 1150 | for (unsigned int i = 0; i < pcoin->vout.size(); i++) { |
c8988460 | 1151 | isminetype mine = IsMine(pcoin->vout[i]); |
a3e192a3 | 1152 | if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO && |
6a86c24d CL |
1153 | !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue > 0 && |
1154 | (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) | |
8d657a65 | 1155 | vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO)); |
fdbb537d | 1156 | } |
9b0369c7 CM |
1157 | } |
1158 | } | |
1159 | } | |
1160 | ||
a372168e MF |
1161 | static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue, |
1162 | vector<char>& vfBest, CAmount& nBest, int iterations = 1000) | |
831f59ce CM |
1163 | { |
1164 | vector<char> vfIncluded; | |
1165 | ||
1166 | vfBest.assign(vValue.size(), true); | |
1167 | nBest = nTotalLower; | |
1168 | ||
907a2aa4 GM |
1169 | seed_insecure_rand(); |
1170 | ||
831f59ce CM |
1171 | for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) |
1172 | { | |
1173 | vfIncluded.assign(vValue.size(), false); | |
a372168e | 1174 | CAmount nTotal = 0; |
831f59ce CM |
1175 | bool fReachedTarget = false; |
1176 | for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) | |
1177 | { | |
1178 | for (unsigned int i = 0; i < vValue.size(); i++) | |
1179 | { | |
907a2aa4 GM |
1180 | //The solver here uses a randomized algorithm, |
1181 | //the randomness serves no real security purpose but is just | |
1182 | //needed to prevent degenerate behavior and it is important | |
1183 | //that the rng fast. We do not use a constant random sequence, | |
1184 | //because there may be some privacy improvement by making | |
1185 | //the selection random. | |
1186 | if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i]) | |
831f59ce CM |
1187 | { |
1188 | nTotal += vValue[i].first; | |
1189 | vfIncluded[i] = true; | |
1190 | if (nTotal >= nTargetValue) | |
1191 | { | |
1192 | fReachedTarget = true; | |
1193 | if (nTotal < nBest) | |
1194 | { | |
1195 | nBest = nTotal; | |
1196 | vfBest = vfIncluded; | |
1197 | } | |
1198 | nTotal -= vValue[i].first; | |
1199 | vfIncluded[i] = false; | |
1200 | } | |
1201 | } | |
1202 | } | |
1203 | } | |
1204 | } | |
1205 | } | |
1206 | ||
a372168e MF |
1207 | bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins, |
1208 | set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const | |
e8ef3da7 WL |
1209 | { |
1210 | setCoinsRet.clear(); | |
1211 | nValueRet = 0; | |
1212 | ||
1213 | // List of values less than target | |
a372168e MF |
1214 | pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger; |
1215 | coinLowestLarger.first = std::numeric_limits<CAmount>::max(); | |
e8ef3da7 | 1216 | coinLowestLarger.second.first = NULL; |
a372168e MF |
1217 | vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue; |
1218 | CAmount nTotalLower = 0; | |
e8ef3da7 | 1219 | |
e333ab56 CM |
1220 | random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); |
1221 | ||
c8988460 | 1222 | BOOST_FOREACH(const COutput &output, vCoins) |
e8ef3da7 | 1223 | { |
c8988460 PW |
1224 | if (!output.fSpendable) |
1225 | continue; | |
1226 | ||
9b0369c7 | 1227 | const CWalletTx *pcoin = output.tx; |
e8ef3da7 | 1228 | |
a3e192a3 | 1229 | if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs)) |
9b0369c7 | 1230 | continue; |
e8ef3da7 | 1231 | |
9b0369c7 | 1232 | int i = output.i; |
a372168e | 1233 | CAmount n = pcoin->vout[i].nValue; |
e8ef3da7 | 1234 | |
a372168e | 1235 | pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i)); |
e8ef3da7 | 1236 | |
9b0369c7 CM |
1237 | if (n == nTargetValue) |
1238 | { | |
1239 | setCoinsRet.insert(coin.second); | |
1240 | nValueRet += coin.first; | |
1241 | return true; | |
1242 | } | |
1243 | else if (n < nTargetValue + CENT) | |
1244 | { | |
1245 | vValue.push_back(coin); | |
1246 | nTotalLower += n; | |
1247 | } | |
1248 | else if (n < coinLowestLarger.first) | |
1249 | { | |
1250 | coinLowestLarger = coin; | |
e8ef3da7 WL |
1251 | } |
1252 | } | |
1253 | ||
831f59ce | 1254 | if (nTotalLower == nTargetValue) |
e8ef3da7 | 1255 | { |
c376ac35 | 1256 | for (unsigned int i = 0; i < vValue.size(); ++i) |
e8ef3da7 WL |
1257 | { |
1258 | setCoinsRet.insert(vValue[i].second); | |
1259 | nValueRet += vValue[i].first; | |
1260 | } | |
1261 | return true; | |
1262 | } | |
1263 | ||
831f59ce | 1264 | if (nTotalLower < nTargetValue) |
e8ef3da7 WL |
1265 | { |
1266 | if (coinLowestLarger.second.first == NULL) | |
1267 | return false; | |
1268 | setCoinsRet.insert(coinLowestLarger.second); | |
1269 | nValueRet += coinLowestLarger.first; | |
1270 | return true; | |
1271 | } | |
1272 | ||
e8ef3da7 | 1273 | // Solve subset sum by stochastic approximation |
d650f96d | 1274 | sort(vValue.rbegin(), vValue.rend(), CompareValueOnly()); |
831f59ce | 1275 | vector<char> vfBest; |
a372168e | 1276 | CAmount nBest; |
e8ef3da7 | 1277 | |
831f59ce CM |
1278 | ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000); |
1279 | if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT) | |
1280 | ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000); | |
e8ef3da7 | 1281 | |
831f59ce CM |
1282 | // If we have a bigger coin and (either the stochastic approximation didn't find a good solution, |
1283 | // or the next bigger coin is closer), return the bigger coin | |
1284 | if (coinLowestLarger.second.first && | |
1285 | ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest)) | |
e8ef3da7 WL |
1286 | { |
1287 | setCoinsRet.insert(coinLowestLarger.second); | |
1288 | nValueRet += coinLowestLarger.first; | |
1289 | } | |
1290 | else { | |
c376ac35 | 1291 | for (unsigned int i = 0; i < vValue.size(); i++) |
e8ef3da7 WL |
1292 | if (vfBest[i]) |
1293 | { | |
1294 | setCoinsRet.insert(vValue[i].second); | |
1295 | nValueRet += vValue[i].first; | |
1296 | } | |
1297 | ||
faaeae1e | 1298 | LogPrint("selectcoins", "SelectCoins() best subset: "); |
c376ac35 | 1299 | for (unsigned int i = 0; i < vValue.size(); i++) |
e8ef3da7 | 1300 | if (vfBest[i]) |
7d9d134b WL |
1301 | LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first)); |
1302 | LogPrint("selectcoins", "total %s\n", FormatMoney(nBest)); | |
e8ef3da7 WL |
1303 | } |
1304 | ||
1305 | return true; | |
1306 | } | |
1307 | ||
a372168e | 1308 | bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const |
e8ef3da7 | 1309 | { |
9b0369c7 | 1310 | vector<COutput> vCoins; |
6a86c24d CL |
1311 | AvailableCoins(vCoins, true, coinControl); |
1312 | ||
1313 | // coin control -> return all selected outputs (we want all selected to go into the transaction for sure) | |
1314 | if (coinControl && coinControl->HasSelected()) | |
1315 | { | |
1316 | BOOST_FOREACH(const COutput& out, vCoins) | |
1317 | { | |
2935b211 WL |
1318 | if(!out.fSpendable) |
1319 | continue; | |
6a86c24d CL |
1320 | nValueRet += out.tx->vout[out.i].nValue; |
1321 | setCoinsRet.insert(make_pair(out.tx, out.i)); | |
1322 | } | |
1323 | return (nValueRet >= nTargetValue); | |
1324 | } | |
9b0369c7 CM |
1325 | |
1326 | return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) || | |
1327 | SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) || | |
1bbca249 | 1328 | (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet))); |
e8ef3da7 WL |
1329 | } |
1330 | ||
1331 | ||
1332 | ||
1333 | ||
a372168e MF |
1334 | bool CWallet::CreateTransaction(const vector<pair<CScript, CAmount> >& vecSend, |
1335 | CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl) | |
e8ef3da7 | 1336 | { |
a372168e MF |
1337 | CAmount nValue = 0; |
1338 | BOOST_FOREACH (const PAIRTYPE(CScript, CAmount)& s, vecSend) | |
e8ef3da7 WL |
1339 | { |
1340 | if (nValue < 0) | |
1f00f4e9 GA |
1341 | { |
1342 | strFailReason = _("Transaction amounts must be positive"); | |
e8ef3da7 | 1343 | return false; |
1f00f4e9 | 1344 | } |
e8ef3da7 WL |
1345 | nValue += s.second; |
1346 | } | |
1347 | if (vecSend.empty() || nValue < 0) | |
1f00f4e9 GA |
1348 | { |
1349 | strFailReason = _("Transaction amounts must be positive"); | |
e8ef3da7 | 1350 | return false; |
1f00f4e9 | 1351 | } |
e8ef3da7 | 1352 | |
b33d1f5e | 1353 | wtxNew.fTimeReceivedIsTxTime = true; |
4c6e2295 | 1354 | wtxNew.BindWallet(this); |
4949004d | 1355 | CMutableTransaction txNew; |
e8ef3da7 | 1356 | |
e8ef3da7 | 1357 | { |
f8dcd5ca | 1358 | LOCK2(cs_main, cs_wallet); |
e8ef3da7 | 1359 | { |
c6cb21d1 | 1360 | nFeeRet = payTxFee.GetFeePerK(); |
050d2e95 | 1361 | while (true) |
e8ef3da7 | 1362 | { |
4949004d PW |
1363 | txNew.vin.clear(); |
1364 | txNew.vout.clear(); | |
e8ef3da7 WL |
1365 | wtxNew.fFromMe = true; |
1366 | ||
a372168e | 1367 | CAmount nTotalValue = nValue + nFeeRet; |
e8ef3da7 WL |
1368 | double dPriority = 0; |
1369 | // vouts to the payees | |
a372168e | 1370 | BOOST_FOREACH (const PAIRTYPE(CScript, CAmount)& s, vecSend) |
8de9bb53 GA |
1371 | { |
1372 | CTxOut txout(s.second, s.first); | |
13fc83c7 | 1373 | if (txout.IsDust(::minRelayTxFee)) |
1f00f4e9 GA |
1374 | { |
1375 | strFailReason = _("Transaction amount too small"); | |
8de9bb53 | 1376 | return false; |
1f00f4e9 | 1377 | } |
4949004d | 1378 | txNew.vout.push_back(txout); |
8de9bb53 | 1379 | } |
e8ef3da7 WL |
1380 | |
1381 | // Choose coins to use | |
1382 | set<pair<const CWalletTx*,unsigned int> > setCoins; | |
a372168e | 1383 | CAmount nValueIn = 0; |
6a86c24d | 1384 | if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl)) |
1f00f4e9 GA |
1385 | { |
1386 | strFailReason = _("Insufficient funds"); | |
e8ef3da7 | 1387 | return false; |
1f00f4e9 | 1388 | } |
e8ef3da7 WL |
1389 | BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) |
1390 | { | |
a372168e | 1391 | CAmount nCredit = pcoin.first->vout[pcoin.second].nValue; |
d7836552 GM |
1392 | //The priority after the next block (depth+1) is used instead of the current, |
1393 | //reflecting an assumption the user would accept a bit more delay for | |
1394 | //a chance at a free transaction. | |
1395 | dPriority += (double)nCredit * (pcoin.first->GetDepthInMainChain()+1); | |
e8ef3da7 WL |
1396 | } |
1397 | ||
a372168e | 1398 | CAmount nChange = nValueIn - nValue - nFeeRet; |
a7dd11c6 PW |
1399 | |
1400 | if (nChange > 0) | |
e8ef3da7 | 1401 | { |
bf798734 GA |
1402 | // Fill a vout to ourself |
1403 | // TODO: pass in scriptChange instead of reservekey so | |
1404 | // change transaction isn't always pay-to-bitcoin-address | |
e8ef3da7 | 1405 | CScript scriptChange; |
6a86c24d CL |
1406 | |
1407 | // coin control: send change to custom address | |
1408 | if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange)) | |
0be990ba | 1409 | scriptChange = GetScriptForDestination(coinControl->destChange); |
6a86c24d CL |
1410 | |
1411 | // no coin control: send change to newly generated address | |
1412 | else | |
1413 | { | |
1414 | // Note: We use a new key here to keep it from being obvious which side is the change. | |
1415 | // The drawback is that by not reusing a previous key, the change may be lost if a | |
1416 | // backup is restored, if the backup doesn't have the new private key for the change. | |
1417 | // If we reused the old key, it would be possible to add code to look for and | |
1418 | // rediscover unknown transactions that were written with keys of ours to recover | |
1419 | // post-backup change. | |
1420 | ||
1421 | // Reserve a new key pair from key pool | |
1422 | CPubKey vchPubKey; | |
9b59e3bd GM |
1423 | bool ret; |
1424 | ret = reservekey.GetReservedKey(vchPubKey); | |
1425 | assert(ret); // should never fail, as we just unlocked | |
6a86c24d | 1426 | |
0be990ba | 1427 | scriptChange = GetScriptForDestination(vchPubKey.GetID()); |
6a86c24d | 1428 | } |
e8ef3da7 | 1429 | |
8de9bb53 GA |
1430 | CTxOut newTxOut(nChange, scriptChange); |
1431 | ||
1432 | // Never create dust outputs; if we would, just | |
1433 | // add the dust to the fee. | |
13fc83c7 | 1434 | if (newTxOut.IsDust(::minRelayTxFee)) |
8de9bb53 GA |
1435 | { |
1436 | nFeeRet += nChange; | |
1437 | reservekey.ReturnKey(); | |
1438 | } | |
1439 | else | |
1440 | { | |
1441 | // Insert change txn at random position: | |
4949004d PW |
1442 | vector<CTxOut>::iterator position = txNew.vout.begin()+GetRandInt(txNew.vout.size()+1); |
1443 | txNew.vout.insert(position, newTxOut); | |
8de9bb53 | 1444 | } |
e8ef3da7 WL |
1445 | } |
1446 | else | |
1447 | reservekey.ReturnKey(); | |
1448 | ||
1449 | // Fill vin | |
1450 | BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) | |
4949004d | 1451 | txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second)); |
e8ef3da7 WL |
1452 | |
1453 | // Sign | |
1454 | int nIn = 0; | |
1455 | BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) | |
4949004d | 1456 | if (!SignSignature(*this, *coin.first, txNew, nIn++)) |
1f00f4e9 GA |
1457 | { |
1458 | strFailReason = _("Signing transaction failed"); | |
e8ef3da7 | 1459 | return false; |
1f00f4e9 | 1460 | } |
e8ef3da7 | 1461 | |
4949004d PW |
1462 | // Embed the constructed transaction data in wtxNew. |
1463 | *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew); | |
1464 | ||
e8ef3da7 | 1465 | // Limit size |
6b6aaa16 | 1466 | unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); |
41e1a0d7 | 1467 | if (nBytes >= MAX_STANDARD_TX_SIZE) |
1f00f4e9 GA |
1468 | { |
1469 | strFailReason = _("Transaction too large"); | |
e8ef3da7 | 1470 | return false; |
1f00f4e9 | 1471 | } |
4d707d51 | 1472 | dPriority = wtxNew.ComputePriority(dPriority, nBytes); |
e8ef3da7 | 1473 | |
a372168e | 1474 | CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool); |
b33d1f5e GA |
1475 | |
1476 | if (nFeeRet >= nFeeNeeded) | |
1477 | break; // Done, enough fee included. | |
1478 | ||
1479 | // Too big to send for free? Include more fee and try again: | |
1480 | if (nBytes > MAX_FREE_TRANSACTION_CREATE_SIZE) | |
e8ef3da7 | 1481 | { |
b33d1f5e | 1482 | nFeeRet = nFeeNeeded; |
e8ef3da7 WL |
1483 | continue; |
1484 | } | |
1485 | ||
b33d1f5e GA |
1486 | // Not enough fee: enough priority? |
1487 | double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget); | |
1488 | // Not enough mempool history to estimate: use hard-coded AllowFree. | |
1489 | if (dPriorityNeeded <= 0 && AllowFree(dPriority)) | |
1490 | break; | |
e8ef3da7 | 1491 | |
b33d1f5e | 1492 | // Small enough, and priority high enough, to send for free |
d88af560 | 1493 | if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded) |
b33d1f5e GA |
1494 | break; |
1495 | ||
1496 | // Include more fee and try again. | |
1497 | nFeeRet = nFeeNeeded; | |
1498 | continue; | |
e8ef3da7 WL |
1499 | } |
1500 | } | |
1501 | } | |
1502 | return true; | |
1503 | } | |
1504 | ||
a372168e MF |
1505 | bool CWallet::CreateTransaction(CScript scriptPubKey, const CAmount& nValue, |
1506 | CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl) | |
e8ef3da7 | 1507 | { |
a372168e | 1508 | vector< pair<CScript, CAmount> > vecSend; |
e8ef3da7 | 1509 | vecSend.push_back(make_pair(scriptPubKey, nValue)); |
6a86c24d | 1510 | return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl); |
e8ef3da7 WL |
1511 | } |
1512 | ||
1513 | // Call after CreateTransaction unless you want to abort | |
1514 | bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey) | |
1515 | { | |
e8ef3da7 | 1516 | { |
f8dcd5ca | 1517 | LOCK2(cs_main, cs_wallet); |
7d9d134b | 1518 | LogPrintf("CommitTransaction:\n%s", wtxNew.ToString()); |
e8ef3da7 WL |
1519 | { |
1520 | // This is only to keep the database open to defeat the auto-flush for the | |
1521 | // duration of this scope. This is the only place where this optimization | |
1522 | // maybe makes sense; please don't do it anywhere else. | |
1523 | CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL; | |
1524 | ||
1525 | // Take key pair from key pool so it won't be used again | |
1526 | reservekey.KeepKey(); | |
1527 | ||
1528 | // Add tx to wallet, because if it has change it's also ours, | |
1529 | // otherwise just for transaction history. | |
1530 | AddToWallet(wtxNew); | |
1531 | ||
93a18a36 | 1532 | // Notify that old coins are spent |
e8ef3da7 WL |
1533 | set<CWalletTx*> setCoins; |
1534 | BOOST_FOREACH(const CTxIn& txin, wtxNew.vin) | |
1535 | { | |
1536 | CWalletTx &coin = mapWallet[txin.prevout.hash]; | |
4c6e2295 | 1537 | coin.BindWallet(this); |
fe4a6550 | 1538 | NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED); |
e8ef3da7 WL |
1539 | } |
1540 | ||
1541 | if (fFileBacked) | |
1542 | delete pwalletdb; | |
1543 | } | |
1544 | ||
1545 | // Track how many getdata requests our transaction gets | |
6cc4a62c | 1546 | mapRequestCount[wtxNew.GetHash()] = 0; |
e8ef3da7 WL |
1547 | |
1548 | // Broadcast | |
b1f15b21 | 1549 | if (!wtxNew.AcceptToMemoryPool(false)) |
e8ef3da7 WL |
1550 | { |
1551 | // This must not fail. The transaction has already been signed and recorded. | |
881a85a2 | 1552 | LogPrintf("CommitTransaction() : Error: Transaction not valid"); |
e8ef3da7 WL |
1553 | return false; |
1554 | } | |
1555 | wtxNew.RelayWalletTransaction(); | |
1556 | } | |
e8ef3da7 WL |
1557 | return true; |
1558 | } | |
1559 | ||
1560 | ||
1561 | ||
1562 | ||
a372168e | 1563 | string CWallet::SendMoney(const CTxDestination &address, CAmount nValue, CWalletTx& wtxNew) |
e8ef3da7 | 1564 | { |
e832ab77 DK |
1565 | // Check amount |
1566 | if (nValue <= 0) | |
1567 | return _("Invalid amount"); | |
1568 | if (nValue > GetBalance()) | |
1569 | return _("Insufficient funds"); | |
6cc4a62c | 1570 | |
e832ab77 | 1571 | string strError; |
6cc4a62c | 1572 | if (IsLocked()) |
e8ef3da7 | 1573 | { |
e832ab77 | 1574 | strError = _("Error: Wallet locked, unable to create transaction!"); |
7d9d134b | 1575 | LogPrintf("SendMoney() : %s", strError); |
6cc4a62c GA |
1576 | return strError; |
1577 | } | |
e832ab77 DK |
1578 | |
1579 | // Parse Bitcoin address | |
0be990ba | 1580 | CScript scriptPubKey = GetScriptForDestination(address); |
e832ab77 DK |
1581 | |
1582 | // Create and send the transaction | |
1583 | CReserveKey reservekey(this); | |
a372168e | 1584 | CAmount nFeeRequired; |
1f00f4e9 | 1585 | if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired, strError)) |
6cc4a62c | 1586 | { |
6cc4a62c | 1587 | if (nValue + nFeeRequired > GetBalance()) |
7d9d134b WL |
1588 | strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!"), FormatMoney(nFeeRequired)); |
1589 | LogPrintf("SendMoney() : %s\n", strError); | |
6cc4a62c | 1590 | return strError; |
e8ef3da7 | 1591 | } |
e8ef3da7 | 1592 | if (!CommitTransaction(wtxNew, reservekey)) |
6b3783a9 | 1593 | return _("Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); |
e8ef3da7 | 1594 | |
e8ef3da7 WL |
1595 | return ""; |
1596 | } | |
1597 | ||
1598 | ||
1599 | ||
a372168e | 1600 | CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool) |
b33d1f5e GA |
1601 | { |
1602 | // payTxFee is user-set "I want to pay this much" | |
a372168e | 1603 | CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes); |
b33d1f5e GA |
1604 | // User didn't set: use -txconfirmtarget to estimate... |
1605 | if (nFeeNeeded == 0) | |
1606 | nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes); | |
1607 | // ... unless we don't have enough mempool data, in which case fall | |
1608 | // back to a hard-coded fee | |
1609 | if (nFeeNeeded == 0) | |
13fc83c7 | 1610 | nFeeNeeded = minTxFee.GetFee(nTxBytes); |
b33d1f5e GA |
1611 | return nFeeNeeded; |
1612 | } | |
1613 | ||
e8ef3da7 WL |
1614 | |
1615 | ||
1616 | ||
eed1785f | 1617 | DBErrors CWallet::LoadWallet(bool& fFirstRunRet) |
e8ef3da7 WL |
1618 | { |
1619 | if (!fFileBacked) | |
4f76be1d | 1620 | return DB_LOAD_OK; |
e8ef3da7 | 1621 | fFirstRunRet = false; |
eed1785f | 1622 | DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this); |
d764d916 | 1623 | if (nLoadWalletRet == DB_NEED_REWRITE) |
9e9869d0 | 1624 | { |
d764d916 GA |
1625 | if (CDB::Rewrite(strWalletFile, "\x04pool")) |
1626 | { | |
012ca1c9 | 1627 | LOCK(cs_wallet); |
d764d916 GA |
1628 | setKeyPool.clear(); |
1629 | // Note: can't top-up keypool here, because wallet is locked. | |
1630 | // User will be prompted to unlock wallet the next operation | |
1631 | // the requires a new key. | |
1632 | } | |
9e9869d0 PW |
1633 | } |
1634 | ||
7ec55267 MC |
1635 | if (nLoadWalletRet != DB_LOAD_OK) |
1636 | return nLoadWalletRet; | |
fd61d6f5 | 1637 | fFirstRunRet = !vchDefaultKey.IsValid(); |
e8ef3da7 | 1638 | |
39278369 CL |
1639 | uiInterface.LoadWallet(this); |
1640 | ||
116df55e | 1641 | return DB_LOAD_OK; |
e8ef3da7 WL |
1642 | } |
1643 | ||
ae3d0aba | 1644 | |
77cbd462 | 1645 | DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx) |
518f3bda JG |
1646 | { |
1647 | if (!fFileBacked) | |
1648 | return DB_LOAD_OK; | |
77cbd462 | 1649 | DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx); |
518f3bda JG |
1650 | if (nZapWalletTxRet == DB_NEED_REWRITE) |
1651 | { | |
1652 | if (CDB::Rewrite(strWalletFile, "\x04pool")) | |
1653 | { | |
1654 | LOCK(cs_wallet); | |
1655 | setKeyPool.clear(); | |
1656 | // Note: can't top-up keypool here, because wallet is locked. | |
1657 | // User will be prompted to unlock wallet the next operation | |
1658 | // the requires a new key. | |
1659 | } | |
1660 | } | |
1661 | ||
1662 | if (nZapWalletTxRet != DB_LOAD_OK) | |
1663 | return nZapWalletTxRet; | |
1664 | ||
1665 | return DB_LOAD_OK; | |
1666 | } | |
1667 | ||
1668 | ||
a41d5fe0 | 1669 | bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose) |
ae3d0aba | 1670 | { |
ca4cf5cf GA |
1671 | bool fUpdated = false; |
1672 | { | |
1673 | LOCK(cs_wallet); // mapAddressBook | |
1674 | std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address); | |
1675 | fUpdated = mi != mapAddressBook.end(); | |
1676 | mapAddressBook[address].name = strName; | |
1677 | if (!strPurpose.empty()) /* update purpose only if requested */ | |
1678 | mapAddressBook[address].purpose = strPurpose; | |
1679 | } | |
8d657a65 | 1680 | NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO, |
ca4cf5cf | 1681 | strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) ); |
ae3d0aba WL |
1682 | if (!fFileBacked) |
1683 | return false; | |
a41d5fe0 GA |
1684 | if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose)) |
1685 | return false; | |
10254401 | 1686 | return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName); |
ae3d0aba WL |
1687 | } |
1688 | ||
a41d5fe0 | 1689 | bool CWallet::DelAddressBook(const CTxDestination& address) |
ae3d0aba | 1690 | { |
b10e1470 | 1691 | { |
ca4cf5cf GA |
1692 | LOCK(cs_wallet); // mapAddressBook |
1693 | ||
1694 | if(fFileBacked) | |
b10e1470 | 1695 | { |
ca4cf5cf GA |
1696 | // Delete destdata tuples associated with address |
1697 | std::string strAddress = CBitcoinAddress(address).ToString(); | |
1698 | BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata) | |
1699 | { | |
1700 | CWalletDB(strWalletFile).EraseDestData(strAddress, item.first); | |
1701 | } | |
b10e1470 | 1702 | } |
ca4cf5cf | 1703 | mapAddressBook.erase(address); |
b10e1470 WL |
1704 | } |
1705 | ||
8d657a65 | 1706 | NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED); |
ca4cf5cf | 1707 | |
ae3d0aba WL |
1708 | if (!fFileBacked) |
1709 | return false; | |
a41d5fe0 | 1710 | CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString()); |
10254401 | 1711 | return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString()); |
ae3d0aba WL |
1712 | } |
1713 | ||
fd61d6f5 | 1714 | bool CWallet::SetDefaultKey(const CPubKey &vchPubKey) |
ae3d0aba WL |
1715 | { |
1716 | if (fFileBacked) | |
1717 | { | |
1718 | if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey)) | |
1719 | return false; | |
1720 | } | |
1721 | vchDefaultKey = vchPubKey; | |
1722 | return true; | |
1723 | } | |
1724 | ||
37971fcc GA |
1725 | // |
1726 | // Mark old keypool keys as used, | |
1727 | // and generate all new keys | |
1728 | // | |
1729 | bool CWallet::NewKeyPool() | |
1730 | { | |
37971fcc | 1731 | { |
f8dcd5ca | 1732 | LOCK(cs_wallet); |
37971fcc | 1733 | CWalletDB walletdb(strWalletFile); |
51ed9ec9 | 1734 | BOOST_FOREACH(int64_t nIndex, setKeyPool) |
37971fcc GA |
1735 | walletdb.ErasePool(nIndex); |
1736 | setKeyPool.clear(); | |
1737 | ||
1738 | if (IsLocked()) | |
1739 | return false; | |
1740 | ||
51ed9ec9 | 1741 | int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0); |
37971fcc GA |
1742 | for (int i = 0; i < nKeys; i++) |
1743 | { | |
51ed9ec9 | 1744 | int64_t nIndex = i+1; |
37971fcc GA |
1745 | walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey())); |
1746 | setKeyPool.insert(nIndex); | |
1747 | } | |
f48742c2 | 1748 | LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys); |
37971fcc GA |
1749 | } |
1750 | return true; | |
1751 | } | |
1752 | ||
13dd2d09 | 1753 | bool CWallet::TopUpKeyPool(unsigned int kpSize) |
e8ef3da7 | 1754 | { |
e8ef3da7 | 1755 | { |
f8dcd5ca PW |
1756 | LOCK(cs_wallet); |
1757 | ||
4e87d341 MC |
1758 | if (IsLocked()) |
1759 | return false; | |
1760 | ||
e8ef3da7 WL |
1761 | CWalletDB walletdb(strWalletFile); |
1762 | ||
1763 | // Top up key pool | |
13dd2d09 JG |
1764 | unsigned int nTargetSize; |
1765 | if (kpSize > 0) | |
1766 | nTargetSize = kpSize; | |
1767 | else | |
51ed9ec9 | 1768 | nTargetSize = max(GetArg("-keypool", 100), (int64_t) 0); |
13dd2d09 | 1769 | |
faf705a4 | 1770 | while (setKeyPool.size() < (nTargetSize + 1)) |
e8ef3da7 | 1771 | { |
51ed9ec9 | 1772 | int64_t nEnd = 1; |
e8ef3da7 WL |
1773 | if (!setKeyPool.empty()) |
1774 | nEnd = *(--setKeyPool.end()) + 1; | |
1775 | if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) | |
4e87d341 | 1776 | throw runtime_error("TopUpKeyPool() : writing generated key failed"); |
e8ef3da7 | 1777 | setKeyPool.insert(nEnd); |
783b182c | 1778 | LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size()); |
e8ef3da7 | 1779 | } |
4e87d341 MC |
1780 | } |
1781 | return true; | |
1782 | } | |
1783 | ||
51ed9ec9 | 1784 | void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool) |
4e87d341 MC |
1785 | { |
1786 | nIndex = -1; | |
fd61d6f5 | 1787 | keypool.vchPubKey = CPubKey(); |
4e87d341 | 1788 | { |
f8dcd5ca PW |
1789 | LOCK(cs_wallet); |
1790 | ||
4e87d341 MC |
1791 | if (!IsLocked()) |
1792 | TopUpKeyPool(); | |
e8ef3da7 WL |
1793 | |
1794 | // Get the oldest key | |
4e87d341 MC |
1795 | if(setKeyPool.empty()) |
1796 | return; | |
1797 | ||
1798 | CWalletDB walletdb(strWalletFile); | |
1799 | ||
e8ef3da7 WL |
1800 | nIndex = *(setKeyPool.begin()); |
1801 | setKeyPool.erase(setKeyPool.begin()); | |
1802 | if (!walletdb.ReadPool(nIndex, keypool)) | |
1803 | throw runtime_error("ReserveKeyFromKeyPool() : read failed"); | |
fd61d6f5 | 1804 | if (!HaveKey(keypool.vchPubKey.GetID())) |
e8ef3da7 | 1805 | throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool"); |
fd61d6f5 | 1806 | assert(keypool.vchPubKey.IsValid()); |
f48742c2 | 1807 | LogPrintf("keypool reserve %d\n", nIndex); |
e8ef3da7 WL |
1808 | } |
1809 | } | |
1810 | ||
51ed9ec9 | 1811 | void CWallet::KeepKey(int64_t nIndex) |
e8ef3da7 WL |
1812 | { |
1813 | // Remove from key pool | |
1814 | if (fFileBacked) | |
1815 | { | |
1816 | CWalletDB walletdb(strWalletFile); | |
6cc4a62c | 1817 | walletdb.ErasePool(nIndex); |
e8ef3da7 | 1818 | } |
f48742c2 | 1819 | LogPrintf("keypool keep %d\n", nIndex); |
e8ef3da7 WL |
1820 | } |
1821 | ||
51ed9ec9 | 1822 | void CWallet::ReturnKey(int64_t nIndex) |
e8ef3da7 WL |
1823 | { |
1824 | // Return to key pool | |
f8dcd5ca PW |
1825 | { |
1826 | LOCK(cs_wallet); | |
e8ef3da7 | 1827 | setKeyPool.insert(nIndex); |
f8dcd5ca | 1828 | } |
f48742c2 | 1829 | LogPrintf("keypool return %d\n", nIndex); |
e8ef3da7 WL |
1830 | } |
1831 | ||
71ac5052 | 1832 | bool CWallet::GetKeyFromPool(CPubKey& result) |
e8ef3da7 | 1833 | { |
51ed9ec9 | 1834 | int64_t nIndex = 0; |
e8ef3da7 | 1835 | CKeyPool keypool; |
7db3b75b | 1836 | { |
f8dcd5ca | 1837 | LOCK(cs_wallet); |
ed02c95d GA |
1838 | ReserveKeyFromKeyPool(nIndex, keypool); |
1839 | if (nIndex == -1) | |
7db3b75b | 1840 | { |
ed02c95d GA |
1841 | if (IsLocked()) return false; |
1842 | result = GenerateNewKey(); | |
7db3b75b GA |
1843 | return true; |
1844 | } | |
ed02c95d GA |
1845 | KeepKey(nIndex); |
1846 | result = keypool.vchPubKey; | |
7db3b75b | 1847 | } |
7db3b75b | 1848 | return true; |
e8ef3da7 WL |
1849 | } |
1850 | ||
51ed9ec9 | 1851 | int64_t CWallet::GetOldestKeyPoolTime() |
e8ef3da7 | 1852 | { |
51ed9ec9 | 1853 | int64_t nIndex = 0; |
e8ef3da7 WL |
1854 | CKeyPool keypool; |
1855 | ReserveKeyFromKeyPool(nIndex, keypool); | |
4e87d341 MC |
1856 | if (nIndex == -1) |
1857 | return GetTime(); | |
e8ef3da7 WL |
1858 | ReturnKey(nIndex); |
1859 | return keypool.nTime; | |
1860 | } | |
1861 | ||
a372168e | 1862 | std::map<CTxDestination, CAmount> CWallet::GetAddressBalances() |
22dfd735 | 1863 | { |
a372168e | 1864 | map<CTxDestination, CAmount> balances; |
22dfd735 | 1865 | |
1866 | { | |
1867 | LOCK(cs_wallet); | |
1868 | BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) | |
1869 | { | |
1870 | CWalletTx *pcoin = &walletEntry.second; | |
1871 | ||
0542619d | 1872 | if (!IsFinalTx(*pcoin) || !pcoin->IsTrusted()) |
22dfd735 | 1873 | continue; |
1874 | ||
1875 | if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) | |
1876 | continue; | |
1877 | ||
1878 | int nDepth = pcoin->GetDepthInMainChain(); | |
a3e192a3 | 1879 | if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1)) |
22dfd735 | 1880 | continue; |
1881 | ||
b1093efa | 1882 | for (unsigned int i = 0; i < pcoin->vout.size(); i++) |
22dfd735 | 1883 | { |
b1093efa | 1884 | CTxDestination addr; |
22dfd735 | 1885 | if (!IsMine(pcoin->vout[i])) |
1886 | continue; | |
b1093efa GM |
1887 | if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr)) |
1888 | continue; | |
22dfd735 | 1889 | |
a372168e | 1890 | CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue; |
22dfd735 | 1891 | |
22dfd735 | 1892 | if (!balances.count(addr)) |
1893 | balances[addr] = 0; | |
1894 | balances[addr] += n; | |
1895 | } | |
1896 | } | |
1897 | } | |
1898 | ||
1899 | return balances; | |
1900 | } | |
1901 | ||
b1093efa | 1902 | set< set<CTxDestination> > CWallet::GetAddressGroupings() |
22dfd735 | 1903 | { |
95691680 | 1904 | AssertLockHeld(cs_wallet); // mapWallet |
b1093efa GM |
1905 | set< set<CTxDestination> > groupings; |
1906 | set<CTxDestination> grouping; | |
22dfd735 | 1907 | |
1908 | BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) | |
1909 | { | |
1910 | CWalletTx *pcoin = &walletEntry.second; | |
1911 | ||
a3fad211 | 1912 | if (pcoin->vin.size() > 0) |
22dfd735 | 1913 | { |
a3fad211 | 1914 | bool any_mine = false; |
22dfd735 | 1915 | // group all input addresses with each other |
1916 | BOOST_FOREACH(CTxIn txin, pcoin->vin) | |
b1093efa GM |
1917 | { |
1918 | CTxDestination address; | |
a3fad211 GM |
1919 | if(!IsMine(txin)) /* If this input isn't mine, ignore it */ |
1920 | continue; | |
b1093efa GM |
1921 | if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address)) |
1922 | continue; | |
1923 | grouping.insert(address); | |
a3fad211 | 1924 | any_mine = true; |
b1093efa | 1925 | } |
22dfd735 | 1926 | |
1927 | // group change with input addresses | |
a3fad211 GM |
1928 | if (any_mine) |
1929 | { | |
1930 | BOOST_FOREACH(CTxOut txout, pcoin->vout) | |
1931 | if (IsChange(txout)) | |
1932 | { | |
1933 | CTxDestination txoutAddr; | |
1934 | if(!ExtractDestination(txout.scriptPubKey, txoutAddr)) | |
1935 | continue; | |
1936 | grouping.insert(txoutAddr); | |
1937 | } | |
1938 | } | |
1939 | if (grouping.size() > 0) | |
1940 | { | |
1941 | groupings.insert(grouping); | |
1942 | grouping.clear(); | |
1943 | } | |
22dfd735 | 1944 | } |
1945 | ||
1946 | // group lone addrs by themselves | |
b1093efa | 1947 | for (unsigned int i = 0; i < pcoin->vout.size(); i++) |
22dfd735 | 1948 | if (IsMine(pcoin->vout[i])) |
1949 | { | |
b1093efa GM |
1950 | CTxDestination address; |
1951 | if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address)) | |
1952 | continue; | |
1953 | grouping.insert(address); | |
22dfd735 | 1954 | groupings.insert(grouping); |
1955 | grouping.clear(); | |
1956 | } | |
1957 | } | |
1958 | ||
b1093efa GM |
1959 | set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses |
1960 | map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it | |
1961 | BOOST_FOREACH(set<CTxDestination> grouping, groupings) | |
22dfd735 | 1962 | { |
1963 | // make a set of all the groups hit by this new group | |
b1093efa GM |
1964 | set< set<CTxDestination>* > hits; |
1965 | map< CTxDestination, set<CTxDestination>* >::iterator it; | |
1966 | BOOST_FOREACH(CTxDestination address, grouping) | |
22dfd735 | 1967 | if ((it = setmap.find(address)) != setmap.end()) |
1968 | hits.insert((*it).second); | |
1969 | ||
1970 | // merge all hit groups into a new single group and delete old groups | |
b1093efa GM |
1971 | set<CTxDestination>* merged = new set<CTxDestination>(grouping); |
1972 | BOOST_FOREACH(set<CTxDestination>* hit, hits) | |
22dfd735 | 1973 | { |
1974 | merged->insert(hit->begin(), hit->end()); | |
1975 | uniqueGroupings.erase(hit); | |
1976 | delete hit; | |
1977 | } | |
1978 | uniqueGroupings.insert(merged); | |
1979 | ||
1980 | // update setmap | |
b1093efa | 1981 | BOOST_FOREACH(CTxDestination element, *merged) |
22dfd735 | 1982 | setmap[element] = merged; |
1983 | } | |
1984 | ||
b1093efa GM |
1985 | set< set<CTxDestination> > ret; |
1986 | BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings) | |
22dfd735 | 1987 | { |
1988 | ret.insert(*uniqueGrouping); | |
1989 | delete uniqueGrouping; | |
1990 | } | |
1991 | ||
1992 | return ret; | |
1993 | } | |
1994 | ||
3624356e GA |
1995 | set<CTxDestination> CWallet::GetAccountAddresses(string strAccount) const |
1996 | { | |
95691680 | 1997 | AssertLockHeld(cs_wallet); // mapWallet |
3624356e GA |
1998 | set<CTxDestination> result; |
1999 | BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook) | |
2000 | { | |
2001 | const CTxDestination& address = item.first; | |
2002 | const string& strName = item.second.name; | |
2003 | if (strName == strAccount) | |
2004 | result.insert(address); | |
2005 | } | |
2006 | return result; | |
2007 | } | |
2008 | ||
360cfe14 | 2009 | bool CReserveKey::GetReservedKey(CPubKey& pubkey) |
e8ef3da7 WL |
2010 | { |
2011 | if (nIndex == -1) | |
2012 | { | |
2013 | CKeyPool keypool; | |
2014 | pwallet->ReserveKeyFromKeyPool(nIndex, keypool); | |
0d7b28e5 MC |
2015 | if (nIndex != -1) |
2016 | vchPubKey = keypool.vchPubKey; | |
360cfe14 | 2017 | else { |
6c37f7fd | 2018 | return false; |
cee69980 | 2019 | } |
e8ef3da7 | 2020 | } |
fd61d6f5 | 2021 | assert(vchPubKey.IsValid()); |
360cfe14 PW |
2022 | pubkey = vchPubKey; |
2023 | return true; | |
e8ef3da7 WL |
2024 | } |
2025 | ||
2026 | void CReserveKey::KeepKey() | |
2027 | { | |
2028 | if (nIndex != -1) | |
2029 | pwallet->KeepKey(nIndex); | |
2030 | nIndex = -1; | |
fd61d6f5 | 2031 | vchPubKey = CPubKey(); |
e8ef3da7 WL |
2032 | } |
2033 | ||
2034 | void CReserveKey::ReturnKey() | |
2035 | { | |
2036 | if (nIndex != -1) | |
2037 | pwallet->ReturnKey(nIndex); | |
2038 | nIndex = -1; | |
fd61d6f5 | 2039 | vchPubKey = CPubKey(); |
e8ef3da7 | 2040 | } |
ae3d0aba | 2041 | |
434e4273 | 2042 | void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const |
30ab2c9c PW |
2043 | { |
2044 | setAddress.clear(); | |
2045 | ||
2046 | CWalletDB walletdb(strWalletFile); | |
2047 | ||
f8dcd5ca | 2048 | LOCK2(cs_main, cs_wallet); |
51ed9ec9 | 2049 | BOOST_FOREACH(const int64_t& id, setKeyPool) |
30ab2c9c PW |
2050 | { |
2051 | CKeyPool keypool; | |
2052 | if (!walletdb.ReadPool(id, keypool)) | |
2053 | throw runtime_error("GetAllReserveKeyHashes() : read failed"); | |
fd61d6f5 | 2054 | assert(keypool.vchPubKey.IsValid()); |
10254401 PW |
2055 | CKeyID keyID = keypool.vchPubKey.GetID(); |
2056 | if (!HaveKey(keyID)) | |
30ab2c9c | 2057 | throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool"); |
10254401 | 2058 | setAddress.insert(keyID); |
30ab2c9c PW |
2059 | } |
2060 | } | |
fe4a6550 WL |
2061 | |
2062 | void CWallet::UpdatedTransaction(const uint256 &hashTx) | |
2063 | { | |
2064 | { | |
2065 | LOCK(cs_wallet); | |
2066 | // Only notify UI if this transaction is in this wallet | |
2067 | map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx); | |
2068 | if (mi != mapWallet.end()) | |
2069 | NotifyTransactionChanged(this, hashTx, CT_UPDATED); | |
2070 | } | |
2071 | } | |
fdbb537d JG |
2072 | |
2073 | void CWallet::LockCoin(COutPoint& output) | |
2074 | { | |
95691680 | 2075 | AssertLockHeld(cs_wallet); // setLockedCoins |
fdbb537d JG |
2076 | setLockedCoins.insert(output); |
2077 | } | |
2078 | ||
2079 | void CWallet::UnlockCoin(COutPoint& output) | |
2080 | { | |
95691680 | 2081 | AssertLockHeld(cs_wallet); // setLockedCoins |
fdbb537d JG |
2082 | setLockedCoins.erase(output); |
2083 | } | |
2084 | ||
2085 | void CWallet::UnlockAllCoins() | |
2086 | { | |
95691680 | 2087 | AssertLockHeld(cs_wallet); // setLockedCoins |
fdbb537d JG |
2088 | setLockedCoins.clear(); |
2089 | } | |
2090 | ||
2091 | bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const | |
2092 | { | |
95691680 | 2093 | AssertLockHeld(cs_wallet); // setLockedCoins |
fdbb537d JG |
2094 | COutPoint outpt(hash, n); |
2095 | ||
2096 | return (setLockedCoins.count(outpt) > 0); | |
2097 | } | |
2098 | ||
2099 | void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) | |
2100 | { | |
95691680 | 2101 | AssertLockHeld(cs_wallet); // setLockedCoins |
fdbb537d JG |
2102 | for (std::set<COutPoint>::iterator it = setLockedCoins.begin(); |
2103 | it != setLockedCoins.end(); it++) { | |
2104 | COutPoint outpt = (*it); | |
2105 | vOutpts.push_back(outpt); | |
2106 | } | |
2107 | } | |
2108 | ||
8b59a3d3 | 2109 | |
2110 | class CAffectedKeysVisitor : public boost::static_visitor<void> { | |
2111 | private: | |
2112 | const CKeyStore &keystore; | |
2113 | std::vector<CKeyID> &vKeys; | |
2114 | ||
2115 | public: | |
2116 | CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {} | |
2117 | ||
2118 | void Process(const CScript &script) { | |
2119 | txnouttype type; | |
2120 | std::vector<CTxDestination> vDest; | |
2121 | int nRequired; | |
2122 | if (ExtractDestinations(script, type, vDest, nRequired)) { | |
2123 | BOOST_FOREACH(const CTxDestination &dest, vDest) | |
2124 | boost::apply_visitor(*this, dest); | |
2125 | } | |
2126 | } | |
2127 | ||
2128 | void operator()(const CKeyID &keyId) { | |
2129 | if (keystore.HaveKey(keyId)) | |
2130 | vKeys.push_back(keyId); | |
2131 | } | |
2132 | ||
2133 | void operator()(const CScriptID &scriptId) { | |
2134 | CScript script; | |
2135 | if (keystore.GetCScript(scriptId, script)) | |
2136 | Process(script); | |
2137 | } | |
2138 | ||
2139 | void operator()(const CNoDestination &none) {} | |
2140 | }; | |
2141 | ||
51ed9ec9 | 2142 | void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const { |
95691680 | 2143 | AssertLockHeld(cs_wallet); // mapKeyMetadata |
434e4273 PW |
2144 | mapKeyBirth.clear(); |
2145 | ||
2146 | // get birth times for keys with metadata | |
2147 | for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) | |
2148 | if (it->second.nCreateTime) | |
2149 | mapKeyBirth[it->first] = it->second.nCreateTime; | |
2150 | ||
2151 | // map in which we'll infer heights of other keys | |
4c6d41b8 | 2152 | CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin |
434e4273 PW |
2153 | std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock; |
2154 | std::set<CKeyID> setKeys; | |
2155 | GetKeys(setKeys); | |
2156 | BOOST_FOREACH(const CKeyID &keyid, setKeys) { | |
2157 | if (mapKeyBirth.count(keyid) == 0) | |
2158 | mapKeyFirstBlock[keyid] = pindexMax; | |
2159 | } | |
2160 | setKeys.clear(); | |
2161 | ||
2162 | // if there are no such keys, we're done | |
2163 | if (mapKeyFirstBlock.empty()) | |
2164 | return; | |
2165 | ||
2166 | // find first block that affects those keys, if there are any left | |
2167 | std::vector<CKeyID> vAffected; | |
2168 | for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) { | |
2169 | // iterate over all wallet transactions... | |
2170 | const CWalletTx &wtx = (*it).second; | |
145d5be8 | 2171 | BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock); |
4c6d41b8 | 2172 | if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) { |
434e4273 PW |
2173 | // ... which are already in a block |
2174 | int nHeight = blit->second->nHeight; | |
2175 | BOOST_FOREACH(const CTxOut &txout, wtx.vout) { | |
2176 | // iterate over all their outputs | |
8b59a3d3 | 2177 | CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey); |
434e4273 PW |
2178 | BOOST_FOREACH(const CKeyID &keyid, vAffected) { |
2179 | // ... and all their affected keys | |
2180 | std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid); | |
2181 | if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight) | |
2182 | rit->second = blit->second; | |
2183 | } | |
2184 | vAffected.clear(); | |
2185 | } | |
2186 | } | |
2187 | } | |
2188 | ||
2189 | // Extract block timestamps for those keys | |
2190 | for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++) | |
209377a7 | 2191 | mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off |
434e4273 | 2192 | } |
b10e1470 WL |
2193 | |
2194 | bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value) | |
2195 | { | |
8476d5d4 CL |
2196 | if (boost::get<CNoDestination>(&dest)) |
2197 | return false; | |
2198 | ||
b10e1470 WL |
2199 | mapAddressBook[dest].destdata.insert(std::make_pair(key, value)); |
2200 | if (!fFileBacked) | |
2201 | return true; | |
2202 | return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value); | |
2203 | } | |
2204 | ||
2205 | bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key) | |
2206 | { | |
2207 | if (!mapAddressBook[dest].destdata.erase(key)) | |
2208 | return false; | |
2209 | if (!fFileBacked) | |
2210 | return true; | |
2211 | return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key); | |
2212 | } | |
2213 | ||
2214 | bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value) | |
2215 | { | |
2216 | mapAddressBook[dest].destdata.insert(std::make_pair(key, value)); | |
2217 | return true; | |
2218 | } | |
2219 | ||
2220 | bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const | |
2221 | { | |
2222 | std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest); | |
2223 | if(i != mapAddressBook.end()) | |
2224 | { | |
2225 | CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key); | |
2226 | if(j != i->second.destdata.end()) | |
2227 | { | |
2228 | if(value) | |
2229 | *value = j->second; | |
2230 | return true; | |
2231 | } | |
2232 | } | |
2233 | return false; | |
2234 | } | |
af8297c0 WL |
2235 | |
2236 | CKeyPool::CKeyPool() | |
2237 | { | |
2238 | nTime = GetTime(); | |
2239 | } | |
2240 | ||
2241 | CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn) | |
2242 | { | |
2243 | nTime = GetTime(); | |
2244 | vchPubKey = vchPubKeyIn; | |
2245 | } | |
2246 | ||
2247 | CWalletKey::CWalletKey(int64_t nExpires) | |
2248 | { | |
2249 | nTimeCreated = (nExpires ? GetTime() : 0); | |
2250 | nTimeExpires = nExpires; | |
2251 | } | |
0101483f | 2252 | |
4b0deb3b | 2253 | int CMerkleTx::SetMerkleBranch(const CBlock& block) |
0101483f WL |
2254 | { |
2255 | AssertLockHeld(cs_main); | |
2256 | CBlock blockTmp; | |
2257 | ||
4b0deb3b DK |
2258 | // Update the tx's hashBlock |
2259 | hashBlock = block.GetHash(); | |
0101483f | 2260 | |
4b0deb3b DK |
2261 | // Locate the transaction |
2262 | for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++) | |
2263 | if (block.vtx[nIndex] == *(CTransaction*)this) | |
2264 | break; | |
2265 | if (nIndex == (int)block.vtx.size()) | |
2266 | { | |
2267 | vMerkleBranch.clear(); | |
2268 | nIndex = -1; | |
2269 | LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); | |
2270 | return 0; | |
0101483f WL |
2271 | } |
2272 | ||
4b0deb3b DK |
2273 | // Fill in merkle branch |
2274 | vMerkleBranch = block.GetMerkleBranch(nIndex); | |
2275 | ||
0101483f | 2276 | // Is the tx in a block that's in the main chain |
145d5be8 | 2277 | BlockMap::iterator mi = mapBlockIndex.find(hashBlock); |
0101483f WL |
2278 | if (mi == mapBlockIndex.end()) |
2279 | return 0; | |
4b0deb3b | 2280 | const CBlockIndex* pindex = (*mi).second; |
0101483f WL |
2281 | if (!pindex || !chainActive.Contains(pindex)) |
2282 | return 0; | |
2283 | ||
2284 | return chainActive.Height() - pindex->nHeight + 1; | |
2285 | } | |
2286 | ||
2287 | int CMerkleTx::GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const | |
2288 | { | |
2289 | if (hashBlock == 0 || nIndex == -1) | |
2290 | return 0; | |
2291 | AssertLockHeld(cs_main); | |
2292 | ||
2293 | // Find the block it claims to be in | |
145d5be8 | 2294 | BlockMap::iterator mi = mapBlockIndex.find(hashBlock); |
0101483f WL |
2295 | if (mi == mapBlockIndex.end()) |
2296 | return 0; | |
2297 | CBlockIndex* pindex = (*mi).second; | |
2298 | if (!pindex || !chainActive.Contains(pindex)) | |
2299 | return 0; | |
2300 | ||
2301 | // Make sure the merkle branch connects to this block | |
2302 | if (!fMerkleVerified) | |
2303 | { | |
2304 | if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) | |
2305 | return 0; | |
2306 | fMerkleVerified = true; | |
2307 | } | |
2308 | ||
2309 | pindexRet = pindex; | |
2310 | return chainActive.Height() - pindex->nHeight + 1; | |
2311 | } | |
2312 | ||
2313 | int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const | |
2314 | { | |
2315 | AssertLockHeld(cs_main); | |
2316 | int nResult = GetDepthInMainChainINTERNAL(pindexRet); | |
2317 | if (nResult == 0 && !mempool.exists(GetHash())) | |
2318 | return -1; // Not in chain, not in mempool | |
2319 | ||
2320 | return nResult; | |
2321 | } | |
2322 | ||
2323 | int CMerkleTx::GetBlocksToMaturity() const | |
2324 | { | |
2325 | if (!IsCoinBase()) | |
2326 | return 0; | |
2327 | return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain()); | |
2328 | } | |
2329 | ||
2330 | ||
2331 | bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectInsaneFee) | |
2332 | { | |
2333 | CValidationState state; | |
2334 | return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectInsaneFee); | |
2335 | } | |
2336 |