Projects : bitcoin : bitcoin_dumpblock_no_losers
1 | // Copyright (c) 2009-2010 Satoshi Nakamoto |
2 | // Copyright (c) 2011 The Bitcoin developers |
3 | // Distributed under the MIT/X11 software license, see the accompanying |
4 | // file license.txt or http://www.opensource.org/licenses/mit-license.php. |
5 | |
6 | #include "headers.h" |
7 | #include "db.h" |
8 | #include "crypter.h" |
9 | |
10 | using namespace std; |
11 | |
12 | |
13 | ////////////////////////////////////////////////////////////////////////////// |
14 | // |
15 | // mapWallet |
16 | // |
17 | |
18 | bool CWallet::AddKey(const CKey& key) |
19 | { |
20 | if (!CCryptoKeyStore::AddKey(key)) |
21 | return false; |
22 | if (!fFileBacked) |
23 | return true; |
24 | if (!IsCrypted()) |
25 | return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey()); |
26 | return true; |
27 | } |
28 | |
29 | bool CWallet::AddCryptedKey(const vector<unsigned char> &vchPubKey, const vector<unsigned char> &vchCryptedSecret) |
30 | { |
31 | if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret)) |
32 | return false; |
33 | if (!fFileBacked) |
34 | return true; |
35 | CRITICAL_BLOCK(cs_wallet) |
36 | { |
37 | if (pwalletdbEncryption) |
38 | return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret); |
39 | else |
40 | return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret); |
41 | } |
42 | return false; |
43 | } |
44 | |
45 | bool CWallet::Unlock(const SecureString& strWalletPassphrase) |
46 | { |
47 | if (!IsLocked()) |
48 | return false; |
49 | |
50 | CCrypter crypter; |
51 | CKeyingMaterial vMasterKey; |
52 | |
53 | CRITICAL_BLOCK(cs_wallet) |
54 | BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) |
55 | { |
56 | if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) |
57 | return false; |
58 | if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) |
59 | return false; |
60 | if (CCryptoKeyStore::Unlock(vMasterKey)) |
61 | return true; |
62 | } |
63 | return false; |
64 | } |
65 | |
66 | bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase) |
67 | { |
68 | bool fWasLocked = IsLocked(); |
69 | |
70 | CRITICAL_BLOCK(cs_wallet) |
71 | { |
72 | Lock(); |
73 | |
74 | CCrypter crypter; |
75 | CKeyingMaterial vMasterKey; |
76 | BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys) |
77 | { |
78 | if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) |
79 | return false; |
80 | if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) |
81 | return false; |
82 | if (CCryptoKeyStore::Unlock(vMasterKey)) |
83 | { |
84 | int64 nStartTime = GetTimeMillis(); |
85 | crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); |
86 | pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))); |
87 | |
88 | nStartTime = GetTimeMillis(); |
89 | crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); |
90 | pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; |
91 | |
92 | if (pMasterKey.second.nDeriveIterations < 25000) |
93 | pMasterKey.second.nDeriveIterations = 25000; |
94 | |
95 | printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations); |
96 | |
97 | if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) |
98 | return false; |
99 | if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey)) |
100 | return false; |
101 | CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second); |
102 | if (fWasLocked) |
103 | Lock(); |
104 | return true; |
105 | } |
106 | } |
107 | } |
108 | |
109 | return false; |
110 | } |
111 | |
112 | |
113 | // This class implements an addrIncoming entry that causes pre-0.4 |
114 | // clients to crash on startup if reading a private-key-encrypted wallet. |
115 | class CCorruptAddress |
116 | { |
117 | public: |
118 | IMPLEMENT_SERIALIZE |
119 | ( |
120 | if (nType & SER_DISK) |
121 | READWRITE(nVersion); |
122 | ) |
123 | }; |
124 | |
125 | bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) |
126 | { |
127 | if (IsCrypted()) |
128 | return false; |
129 | |
130 | CKeyingMaterial vMasterKey; |
131 | RandAddSeedPerfmon(); |
132 | |
133 | vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE); |
134 | RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE); |
135 | |
136 | CMasterKey kMasterKey; |
137 | |
138 | RandAddSeedPerfmon(); |
139 | kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE); |
140 | RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE); |
141 | |
142 | CCrypter crypter; |
143 | int64 nStartTime = GetTimeMillis(); |
144 | crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod); |
145 | kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime)); |
146 | |
147 | nStartTime = GetTimeMillis(); |
148 | crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod); |
149 | kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; |
150 | |
151 | if (kMasterKey.nDeriveIterations < 25000) |
152 | kMasterKey.nDeriveIterations = 25000; |
153 | |
154 | printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations); |
155 | |
156 | if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod)) |
157 | return false; |
158 | if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey)) |
159 | return false; |
160 | |
161 | CRITICAL_BLOCK(cs_wallet) |
162 | { |
163 | mapMasterKeys[++nMasterKeyMaxID] = kMasterKey; |
164 | if (fFileBacked) |
165 | { |
166 | pwalletdbEncryption = new CWalletDB(strWalletFile); |
167 | pwalletdbEncryption->TxnBegin(); |
168 | pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey); |
169 | } |
170 | |
171 | if (!EncryptKeys(vMasterKey)) |
172 | { |
173 | if (fFileBacked) |
174 | pwalletdbEncryption->TxnAbort(); |
175 | 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. |
176 | } |
177 | |
178 | if (fFileBacked) |
179 | { |
180 | CCorruptAddress corruptAddress; |
181 | pwalletdbEncryption->WriteSetting("addrIncoming", corruptAddress); |
182 | if (!pwalletdbEncryption->TxnCommit()) |
183 | 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. |
184 | |
185 | delete pwalletdbEncryption; |
186 | pwalletdbEncryption = NULL; |
187 | } |
188 | |
189 | Lock(); |
190 | Unlock(strWalletPassphrase); |
191 | NewKeyPool(); |
192 | Lock(); |
193 | |
194 | // Need to completely rewrite the wallet file; if we don't, bdb might keep |
195 | // bits of the unencrypted private key in slack space in the database file. |
196 | CDB::Rewrite(strWalletFile); |
197 | } |
198 | |
199 | return true; |
200 | } |
201 | |
202 | void CWallet::WalletUpdateSpent(const CTransaction &tx) |
203 | { |
204 | // Anytime a signature is successfully verified, it's proof the outpoint is spent. |
205 | // Update the wallet spent flag if it doesn't know due to wallet.dat being |
206 | // restored from backup or the user making copies of wallet.dat. |
207 | CRITICAL_BLOCK(cs_wallet) |
208 | { |
209 | BOOST_FOREACH(const CTxIn& txin, tx.vin) |
210 | { |
211 | map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash); |
212 | if (mi != mapWallet.end()) |
213 | { |
214 | CWalletTx& wtx = (*mi).second; |
215 | if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n])) |
216 | { |
217 | printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str()); |
218 | wtx.MarkSpent(txin.prevout.n); |
219 | wtx.WriteToDisk(); |
220 | vWalletUpdated.push_back(txin.prevout.hash); |
221 | } |
222 | } |
223 | } |
224 | } |
225 | } |
226 | |
227 | void CWallet::MarkDirty() |
228 | { |
229 | CRITICAL_BLOCK(cs_wallet) |
230 | { |
231 | BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) |
232 | item.second.MarkDirty(); |
233 | } |
234 | } |
235 | |
236 | bool CWallet::AddToWallet(const CWalletTx& wtxIn) |
237 | { |
238 | uint256 hash = wtxIn.GetHash(); |
239 | CRITICAL_BLOCK(cs_wallet) |
240 | { |
241 | // Inserts only if not already there, returns tx inserted or tx found |
242 | pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn)); |
243 | CWalletTx& wtx = (*ret.first).second; |
244 | wtx.pwallet = this; |
245 | bool fInsertedNew = ret.second; |
246 | if (fInsertedNew) |
247 | wtx.nTimeReceived = GetAdjustedTime(); |
248 | |
249 | bool fUpdated = false; |
250 | if (!fInsertedNew) |
251 | { |
252 | // Merge |
253 | if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) |
254 | { |
255 | wtx.hashBlock = wtxIn.hashBlock; |
256 | fUpdated = true; |
257 | } |
258 | if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex)) |
259 | { |
260 | wtx.vMerkleBranch = wtxIn.vMerkleBranch; |
261 | wtx.nIndex = wtxIn.nIndex; |
262 | fUpdated = true; |
263 | } |
264 | if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) |
265 | { |
266 | wtx.fFromMe = wtxIn.fFromMe; |
267 | fUpdated = true; |
268 | } |
269 | fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent); |
270 | } |
271 | |
272 | //// debug print |
273 | printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : "")); |
274 | |
275 | // Write to disk |
276 | if (fInsertedNew || fUpdated) |
277 | if (!wtx.WriteToDisk()) |
278 | return false; |
279 | // If default receiving address gets used, replace it with a new one |
280 | CScript scriptDefaultKey; |
281 | scriptDefaultKey.SetBitcoinAddress(vchDefaultKey); |
282 | BOOST_FOREACH(const CTxOut& txout, wtx.vout) |
283 | { |
284 | if (txout.scriptPubKey == scriptDefaultKey) |
285 | { |
286 | std::vector<unsigned char> newDefaultKey; |
287 | if (GetKeyFromPool(newDefaultKey, false)) |
288 | { |
289 | SetDefaultKey(newDefaultKey); |
290 | SetAddressBookName(CBitcoinAddress(vchDefaultKey), ""); |
291 | } |
292 | } |
293 | } |
294 | // Notify UI |
295 | vWalletUpdated.push_back(hash); |
296 | |
297 | // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins |
298 | WalletUpdateSpent(wtx); |
299 | } |
300 | |
301 | // Refresh UI |
302 | MainFrameRepaint(); |
303 | return true; |
304 | } |
305 | |
306 | // Add a transaction to the wallet, or update it. |
307 | // pblock is optional, but should be provided if the transaction is known to be in a block. |
308 | // If fUpdate is true, existing transactions will be updated. |
309 | bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate) |
310 | { |
311 | uint256 hash = tx.GetHash(); |
312 | CRITICAL_BLOCK(cs_wallet) |
313 | { |
314 | bool fExisted = mapWallet.count(hash); |
315 | if (fExisted && !fUpdate) return false; |
316 | if (fExisted || IsMine(tx) || IsFromMe(tx)) |
317 | { |
318 | CWalletTx wtx(this,tx); |
319 | // Get merkle branch if transaction was found in a block |
320 | if (pblock) |
321 | wtx.SetMerkleBranch(pblock); |
322 | return AddToWallet(wtx); |
323 | } |
324 | else |
325 | WalletUpdateSpent(tx); |
326 | } |
327 | return false; |
328 | } |
329 | |
330 | bool CWallet::EraseFromWallet(uint256 hash) |
331 | { |
332 | if (!fFileBacked) |
333 | return false; |
334 | CRITICAL_BLOCK(cs_wallet) |
335 | { |
336 | if (mapWallet.erase(hash)) |
337 | CWalletDB(strWalletFile).EraseTx(hash); |
338 | } |
339 | return true; |
340 | } |
341 | |
342 | |
343 | bool CWallet::IsMine(const CTxIn &txin) const |
344 | { |
345 | CRITICAL_BLOCK(cs_wallet) |
346 | { |
347 | map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); |
348 | if (mi != mapWallet.end()) |
349 | { |
350 | const CWalletTx& prev = (*mi).second; |
351 | if (txin.prevout.n < prev.vout.size()) |
352 | if (IsMine(prev.vout[txin.prevout.n])) |
353 | return true; |
354 | } |
355 | } |
356 | return false; |
357 | } |
358 | |
359 | int64 CWallet::GetDebit(const CTxIn &txin) const |
360 | { |
361 | CRITICAL_BLOCK(cs_wallet) |
362 | { |
363 | map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); |
364 | if (mi != mapWallet.end()) |
365 | { |
366 | const CWalletTx& prev = (*mi).second; |
367 | if (txin.prevout.n < prev.vout.size()) |
368 | if (IsMine(prev.vout[txin.prevout.n])) |
369 | return prev.vout[txin.prevout.n].nValue; |
370 | } |
371 | } |
372 | return 0; |
373 | } |
374 | |
375 | int64 CWalletTx::GetTxTime() const |
376 | { |
377 | return nTimeReceived; |
378 | } |
379 | |
380 | int CWalletTx::GetRequestCount() const |
381 | { |
382 | // Returns -1 if it wasn't being tracked |
383 | int nRequests = -1; |
384 | CRITICAL_BLOCK(pwallet->cs_wallet) |
385 | { |
386 | if (IsCoinBase()) |
387 | { |
388 | // Generated block |
389 | if (hashBlock != 0) |
390 | { |
391 | map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); |
392 | if (mi != pwallet->mapRequestCount.end()) |
393 | nRequests = (*mi).second; |
394 | } |
395 | } |
396 | else |
397 | { |
398 | // Did anyone request this transaction? |
399 | map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash()); |
400 | if (mi != pwallet->mapRequestCount.end()) |
401 | { |
402 | nRequests = (*mi).second; |
403 | |
404 | // How about the block it's in? |
405 | if (nRequests == 0 && hashBlock != 0) |
406 | { |
407 | map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); |
408 | if (mi != pwallet->mapRequestCount.end()) |
409 | nRequests = (*mi).second; |
410 | else |
411 | nRequests = 1; // If it's in someone else's block it must have got out |
412 | } |
413 | } |
414 | } |
415 | } |
416 | return nRequests; |
417 | } |
418 | |
419 | void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CBitcoinAddress, int64> >& listReceived, |
420 | list<pair<CBitcoinAddress, int64> >& listSent, int64& nFee, string& strSentAccount) const |
421 | { |
422 | nGeneratedImmature = nGeneratedMature = nFee = 0; |
423 | listReceived.clear(); |
424 | listSent.clear(); |
425 | strSentAccount = strFromAccount; |
426 | |
427 | if (IsCoinBase()) |
428 | { |
429 | if (GetBlocksToMaturity() > 0) |
430 | nGeneratedImmature = pwallet->GetCredit(*this); |
431 | else |
432 | nGeneratedMature = GetCredit(); |
433 | return; |
434 | } |
435 | |
436 | // Compute fee: |
437 | int64 nDebit = GetDebit(); |
438 | if (nDebit > 0) // debit>0 means we signed/sent this transaction |
439 | { |
440 | int64 nValueOut = GetValueOut(); |
441 | nFee = nDebit - nValueOut; |
442 | } |
443 | |
444 | // Sent/received. Standard client will never generate a send-to-multiple-recipients, |
445 | // but non-standard clients might (so return a list of address/amount pairs) |
446 | BOOST_FOREACH(const CTxOut& txout, vout) |
447 | { |
448 | CBitcoinAddress address; |
449 | vector<unsigned char> vchPubKey; |
450 | if (!ExtractAddress(txout.scriptPubKey, NULL, address)) |
451 | { |
452 | printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", |
453 | this->GetHash().ToString().c_str()); |
454 | address = " unknown "; |
455 | } |
456 | |
457 | // Don't report 'change' txouts |
458 | if (nDebit > 0 && pwallet->IsChange(txout)) |
459 | continue; |
460 | |
461 | if (nDebit > 0) |
462 | listSent.push_back(make_pair(address, txout.nValue)); |
463 | |
464 | if (pwallet->IsMine(txout)) |
465 | listReceived.push_back(make_pair(address, txout.nValue)); |
466 | } |
467 | |
468 | } |
469 | |
470 | void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived, |
471 | int64& nSent, int64& nFee) const |
472 | { |
473 | nGenerated = nReceived = nSent = nFee = 0; |
474 | |
475 | int64 allGeneratedImmature, allGeneratedMature, allFee; |
476 | allGeneratedImmature = allGeneratedMature = allFee = 0; |
477 | string strSentAccount; |
478 | list<pair<CBitcoinAddress, int64> > listReceived; |
479 | list<pair<CBitcoinAddress, int64> > listSent; |
480 | GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount); |
481 | |
482 | if (strAccount == "") |
483 | nGenerated = allGeneratedMature; |
484 | if (strAccount == strSentAccount) |
485 | { |
486 | BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& s, listSent) |
487 | nSent += s.second; |
488 | nFee = allFee; |
489 | } |
490 | CRITICAL_BLOCK(pwallet->cs_wallet) |
491 | { |
492 | BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& r, listReceived) |
493 | { |
494 | if (pwallet->mapAddressBook.count(r.first)) |
495 | { |
496 | map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first); |
497 | if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount) |
498 | nReceived += r.second; |
499 | } |
500 | else if (strAccount.empty()) |
501 | { |
502 | nReceived += r.second; |
503 | } |
504 | } |
505 | } |
506 | } |
507 | |
508 | void CWalletTx::AddSupportingTransactions(CTxDB& txdb) |
509 | { |
510 | vtxPrev.clear(); |
511 | |
512 | const int COPY_DEPTH = 3; |
513 | if (SetMerkleBranch() < COPY_DEPTH) |
514 | { |
515 | vector<uint256> vWorkQueue; |
516 | BOOST_FOREACH(const CTxIn& txin, vin) |
517 | vWorkQueue.push_back(txin.prevout.hash); |
518 | |
519 | // This critsect is OK because txdb is already open |
520 | CRITICAL_BLOCK(pwallet->cs_wallet) |
521 | { |
522 | map<uint256, const CMerkleTx*> mapWalletPrev; |
523 | set<uint256> setAlreadyDone; |
524 | for (int i = 0; i < vWorkQueue.size(); i++) |
525 | { |
526 | uint256 hash = vWorkQueue[i]; |
527 | if (setAlreadyDone.count(hash)) |
528 | continue; |
529 | setAlreadyDone.insert(hash); |
530 | |
531 | CMerkleTx tx; |
532 | map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash); |
533 | if (mi != pwallet->mapWallet.end()) |
534 | { |
535 | tx = (*mi).second; |
536 | BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev) |
537 | mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev; |
538 | } |
539 | else if (mapWalletPrev.count(hash)) |
540 | { |
541 | tx = *mapWalletPrev[hash]; |
542 | } |
543 | else if (!fClient && txdb.ReadDiskTx(hash, tx)) |
544 | { |
545 | ; |
546 | } |
547 | else |
548 | { |
549 | printf("ERROR: AddSupportingTransactions() : unsupported transaction\n"); |
550 | continue; |
551 | } |
552 | |
553 | int nDepth = tx.SetMerkleBranch(); |
554 | vtxPrev.push_back(tx); |
555 | |
556 | if (nDepth < COPY_DEPTH) |
557 | BOOST_FOREACH(const CTxIn& txin, tx.vin) |
558 | vWorkQueue.push_back(txin.prevout.hash); |
559 | } |
560 | } |
561 | } |
562 | |
563 | reverse(vtxPrev.begin(), vtxPrev.end()); |
564 | } |
565 | |
566 | bool CWalletTx::WriteToDisk() |
567 | { |
568 | return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this); |
569 | } |
570 | |
571 | // Scan the block chain (starting in pindexStart) for transactions |
572 | // from or to us. If fUpdate is true, found transactions that already |
573 | // exist in the wallet will be updated. |
574 | int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) |
575 | { |
576 | int ret = 0; |
577 | |
578 | CBlockIndex* pindex = pindexStart; |
579 | CRITICAL_BLOCK(cs_wallet) |
580 | { |
581 | while (pindex) |
582 | { |
583 | CBlock block; |
584 | block.ReadFromDisk(pindex, true); |
585 | BOOST_FOREACH(CTransaction& tx, block.vtx) |
586 | { |
587 | if (AddToWalletIfInvolvingMe(tx, &block, fUpdate)) |
588 | ret++; |
589 | } |
590 | pindex = pindex->pnext; |
591 | } |
592 | } |
593 | return ret; |
594 | } |
595 | |
596 | void CWallet::ReacceptWalletTransactions() |
597 | { |
598 | CTxDB txdb("r"); |
599 | bool fRepeat = true; |
600 | while (fRepeat) CRITICAL_BLOCK(cs_wallet) |
601 | { |
602 | fRepeat = false; |
603 | vector<CDiskTxPos> vMissingTx; |
604 | BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) |
605 | { |
606 | CWalletTx& wtx = item.second; |
607 | if (wtx.IsCoinBase() && wtx.IsSpent(0)) |
608 | continue; |
609 | |
610 | CTxIndex txindex; |
611 | bool fUpdated = false; |
612 | if (txdb.ReadTxIndex(wtx.GetHash(), txindex)) |
613 | { |
614 | // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat |
615 | if (txindex.vSpent.size() != wtx.vout.size()) |
616 | { |
617 | printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size()); |
618 | continue; |
619 | } |
620 | for (int i = 0; i < txindex.vSpent.size(); i++) |
621 | { |
622 | if (wtx.IsSpent(i)) |
623 | continue; |
624 | if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i])) |
625 | { |
626 | wtx.MarkSpent(i); |
627 | fUpdated = true; |
628 | vMissingTx.push_back(txindex.vSpent[i]); |
629 | } |
630 | } |
631 | if (fUpdated) |
632 | { |
633 | printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str()); |
634 | wtx.MarkDirty(); |
635 | wtx.WriteToDisk(); |
636 | } |
637 | } |
638 | else |
639 | { |
640 | // Reaccept any txes of ours that aren't already in a block |
641 | if (!wtx.IsCoinBase()) |
642 | wtx.AcceptWalletTransaction(txdb, false); |
643 | } |
644 | } |
645 | if (!vMissingTx.empty()) |
646 | { |
647 | // TODO: optimize this to scan just part of the block chain? |
648 | if (ScanForWalletTransactions(pindexGenesisBlock)) |
649 | fRepeat = true; // Found missing transactions: re-do Reaccept. |
650 | } |
651 | } |
652 | } |
653 | |
654 | void CWalletTx::RelayWalletTransaction(CTxDB& txdb) |
655 | { |
656 | BOOST_FOREACH(const CMerkleTx& tx, vtxPrev) |
657 | { |
658 | if (!tx.IsCoinBase()) |
659 | { |
660 | uint256 hash = tx.GetHash(); |
661 | if (!txdb.ContainsTx(hash)) |
662 | RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx); |
663 | } |
664 | } |
665 | if (!IsCoinBase()) |
666 | { |
667 | uint256 hash = GetHash(); |
668 | if (!txdb.ContainsTx(hash)) |
669 | { |
670 | printf("Relaying wtx %s\n", hash.ToString().c_str()); |
671 | RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this); |
672 | } |
673 | } |
674 | } |
675 | |
676 | void CWalletTx::RelayWalletTransaction() |
677 | { |
678 | CTxDB txdb("r"); |
679 | RelayWalletTransaction(txdb); |
680 | } |
681 | |
682 | void CWallet::ResendWalletTransactions() |
683 | { |
684 | // Do this infrequently and randomly to avoid giving away |
685 | // that these are our transactions. |
686 | static int64 nNextTime; |
687 | if (GetTime() < nNextTime) |
688 | return; |
689 | bool fFirst = (nNextTime == 0); |
690 | nNextTime = GetTime() + GetRand(30 * 60); |
691 | if (fFirst) |
692 | return; |
693 | |
694 | // Only do it if there's been a new block since last time |
695 | static int64 nLastTime; |
696 | if (nTimeBestReceived < nLastTime) |
697 | return; |
698 | nLastTime = GetTime(); |
699 | |
700 | // Rebroadcast any of our txes that aren't in a block yet |
701 | printf("ResendWalletTransactions()\n"); |
702 | CTxDB txdb("r"); |
703 | CRITICAL_BLOCK(cs_wallet) |
704 | { |
705 | // Sort them in chronological order |
706 | multimap<unsigned int, CWalletTx*> mapSorted; |
707 | BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) |
708 | { |
709 | CWalletTx& wtx = item.second; |
710 | // Don't rebroadcast until it's had plenty of time that |
711 | // it should have gotten in already by now. |
712 | if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60) |
713 | mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); |
714 | } |
715 | BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted) |
716 | { |
717 | CWalletTx& wtx = *item.second; |
718 | wtx.RelayWalletTransaction(txdb); |
719 | } |
720 | } |
721 | } |
722 | |
723 | |
724 | |
725 | |
726 | |
727 | |
728 | ////////////////////////////////////////////////////////////////////////////// |
729 | // |
730 | // Actions |
731 | // |
732 | |
733 | |
734 | int64 CWallet::GetBalance() const |
735 | { |
736 | int64 nTotal = 0; |
737 | CRITICAL_BLOCK(cs_wallet) |
738 | { |
739 | for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) |
740 | { |
741 | const CWalletTx* pcoin = &(*it).second; |
742 | if (!pcoin->IsFinal() || !pcoin->IsConfirmed()) |
743 | continue; |
744 | nTotal += pcoin->GetAvailableCredit(); |
745 | } |
746 | } |
747 | |
748 | return nTotal; |
749 | } |
750 | |
751 | int64 CWallet::GetUnconfirmedBalance() const |
752 | { |
753 | int64 nTotal = 0; |
754 | CRITICAL_BLOCK(cs_wallet) |
755 | { |
756 | for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) |
757 | { |
758 | const CWalletTx* pcoin = &(*it).second; |
759 | if (pcoin->IsFinal() && pcoin->IsConfirmed()) |
760 | continue; |
761 | nTotal += pcoin->GetAvailableCredit(); |
762 | } |
763 | } |
764 | return nTotal; |
765 | } |
766 | |
767 | bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const |
768 | { |
769 | setCoinsRet.clear(); |
770 | nValueRet = 0; |
771 | |
772 | // List of values less than target |
773 | pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger; |
774 | coinLowestLarger.first = INT64_MAX; |
775 | coinLowestLarger.second.first = NULL; |
776 | vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue; |
777 | int64 nTotalLower = 0; |
778 | |
779 | CRITICAL_BLOCK(cs_wallet) |
780 | { |
781 | vector<const CWalletTx*> vCoins; |
782 | vCoins.reserve(mapWallet.size()); |
783 | for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) |
784 | vCoins.push_back(&(*it).second); |
785 | random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); |
786 | |
787 | BOOST_FOREACH(const CWalletTx* pcoin, vCoins) |
788 | { |
789 | if (!pcoin->IsFinal() || !pcoin->IsConfirmed()) |
790 | continue; |
791 | |
792 | if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) |
793 | continue; |
794 | |
795 | int nDepth = pcoin->GetDepthInMainChain(); |
796 | if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs)) |
797 | continue; |
798 | |
799 | for (int i = 0; i < pcoin->vout.size(); i++) |
800 | { |
801 | if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i])) |
802 | continue; |
803 | |
804 | int64 n = pcoin->vout[i].nValue; |
805 | |
806 | if (n <= 0) |
807 | continue; |
808 | |
809 | pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i)); |
810 | |
811 | if (n == nTargetValue) |
812 | { |
813 | setCoinsRet.insert(coin.second); |
814 | nValueRet += coin.first; |
815 | return true; |
816 | } |
817 | else if (n < nTargetValue + CENT) |
818 | { |
819 | vValue.push_back(coin); |
820 | nTotalLower += n; |
821 | } |
822 | else if (n < coinLowestLarger.first) |
823 | { |
824 | coinLowestLarger = coin; |
825 | } |
826 | } |
827 | } |
828 | } |
829 | |
830 | if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT) |
831 | { |
832 | for (int i = 0; i < vValue.size(); ++i) |
833 | { |
834 | setCoinsRet.insert(vValue[i].second); |
835 | nValueRet += vValue[i].first; |
836 | } |
837 | return true; |
838 | } |
839 | |
840 | if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0)) |
841 | { |
842 | if (coinLowestLarger.second.first == NULL) |
843 | return false; |
844 | setCoinsRet.insert(coinLowestLarger.second); |
845 | nValueRet += coinLowestLarger.first; |
846 | return true; |
847 | } |
848 | |
849 | if (nTotalLower >= nTargetValue + CENT) |
850 | nTargetValue += CENT; |
851 | |
852 | // Solve subset sum by stochastic approximation |
853 | sort(vValue.rbegin(), vValue.rend()); |
854 | vector<char> vfIncluded; |
855 | vector<char> vfBest(vValue.size(), true); |
856 | int64 nBest = nTotalLower; |
857 | |
858 | for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++) |
859 | { |
860 | vfIncluded.assign(vValue.size(), false); |
861 | int64 nTotal = 0; |
862 | bool fReachedTarget = false; |
863 | for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) |
864 | { |
865 | for (int i = 0; i < vValue.size(); i++) |
866 | { |
867 | if (nPass == 0 ? rand() % 2 : !vfIncluded[i]) |
868 | { |
869 | nTotal += vValue[i].first; |
870 | vfIncluded[i] = true; |
871 | if (nTotal >= nTargetValue) |
872 | { |
873 | fReachedTarget = true; |
874 | if (nTotal < nBest) |
875 | { |
876 | nBest = nTotal; |
877 | vfBest = vfIncluded; |
878 | } |
879 | nTotal -= vValue[i].first; |
880 | vfIncluded[i] = false; |
881 | } |
882 | } |
883 | } |
884 | } |
885 | } |
886 | |
887 | // If the next larger is still closer, return it |
888 | if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue) |
889 | { |
890 | setCoinsRet.insert(coinLowestLarger.second); |
891 | nValueRet += coinLowestLarger.first; |
892 | } |
893 | else { |
894 | for (int i = 0; i < vValue.size(); i++) |
895 | if (vfBest[i]) |
896 | { |
897 | setCoinsRet.insert(vValue[i].second); |
898 | nValueRet += vValue[i].first; |
899 | } |
900 | |
901 | //// debug print |
902 | printf("SelectCoins() best subset: "); |
903 | for (int i = 0; i < vValue.size(); i++) |
904 | if (vfBest[i]) |
905 | printf("%s ", FormatMoney(vValue[i].first).c_str()); |
906 | printf("total %s\n", FormatMoney(nBest).c_str()); |
907 | } |
908 | |
909 | return true; |
910 | } |
911 | |
912 | bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const |
913 | { |
914 | return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) || |
915 | SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) || |
916 | SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet)); |
917 | } |
918 | |
919 | |
920 | |
921 | |
922 | bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet) |
923 | { |
924 | int64 nValue = 0; |
925 | BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend) |
926 | { |
927 | if (nValue < 0) |
928 | return false; |
929 | nValue += s.second; |
930 | } |
931 | if (vecSend.empty() || nValue < 0) |
932 | return false; |
933 | |
934 | wtxNew.pwallet = this; |
935 | |
936 | CRITICAL_BLOCK(cs_main) |
937 | CRITICAL_BLOCK(cs_wallet) |
938 | { |
939 | // txdb must be opened before the mapWallet lock |
940 | CTxDB txdb("r"); |
941 | { |
942 | nFeeRet = nTransactionFee; |
943 | loop |
944 | { |
945 | wtxNew.vin.clear(); |
946 | wtxNew.vout.clear(); |
947 | wtxNew.fFromMe = true; |
948 | |
949 | int64 nTotalValue = nValue + nFeeRet; |
950 | double dPriority = 0; |
951 | // vouts to the payees |
952 | BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend) |
953 | wtxNew.vout.push_back(CTxOut(s.second, s.first)); |
954 | |
955 | // Choose coins to use |
956 | set<pair<const CWalletTx*,unsigned int> > setCoins; |
957 | int64 nValueIn = 0; |
958 | if (!SelectCoins(nTotalValue, setCoins, nValueIn)) |
959 | return false; |
960 | BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) |
961 | { |
962 | int64 nCredit = pcoin.first->vout[pcoin.second].nValue; |
963 | dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain(); |
964 | } |
965 | |
966 | int64 nChange = nValueIn - nValue - nFeeRet; |
967 | // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE |
968 | // or until nChange becomes zero |
969 | if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT) |
970 | { |
971 | int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet); |
972 | nChange -= nMoveToFee; |
973 | nFeeRet += nMoveToFee; |
974 | } |
975 | |
976 | if (nChange > 0) |
977 | { |
978 | // Note: We use a new key here to keep it from being obvious which side is the change. |
979 | // The drawback is that by not reusing a previous key, the change may be lost if a |
980 | // backup is restored, if the backup doesn't have the new private key for the change. |
981 | // If we reused the old key, it would be possible to add code to look for and |
982 | // rediscover unknown transactions that were written with keys of ours to recover |
983 | // post-backup change. |
984 | |
985 | // Reserve a new key pair from key pool |
986 | vector<unsigned char> vchPubKey = reservekey.GetReservedKey(); |
987 | // assert(mapKeys.count(vchPubKey)); |
988 | |
989 | // Fill a vout to ourself, using same address type as the payment |
990 | CScript scriptChange; |
991 | if (vecSend[0].first.GetBitcoinAddress().IsValid()) |
992 | scriptChange.SetBitcoinAddress(vchPubKey); |
993 | else |
994 | scriptChange << vchPubKey << OP_CHECKSIG; |
995 | |
996 | // Insert change txn at random position: |
997 | vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size()); |
998 | wtxNew.vout.insert(position, CTxOut(nChange, scriptChange)); |
999 | } |
1000 | else |
1001 | reservekey.ReturnKey(); |
1002 | |
1003 | // Fill vin |
1004 | BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) |
1005 | wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second)); |
1006 | |
1007 | // Sign |
1008 | int nIn = 0; |
1009 | BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) |
1010 | if (!SignSignature(*this, *coin.first, wtxNew, nIn++)) |
1011 | return false; |
1012 | |
1013 | // Limit size |
1014 | unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK); |
1015 | if (nBytes >= MAX_BLOCK_SIZE_GEN/5) |
1016 | return false; |
1017 | dPriority /= nBytes; |
1018 | |
1019 | // Check that enough fee is included |
1020 | int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000); |
1021 | bool fAllowFree = CTransaction::AllowFree(dPriority); |
1022 | int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree); |
1023 | if (nFeeRet < max(nPayFee, nMinFee)) |
1024 | { |
1025 | nFeeRet = max(nPayFee, nMinFee); |
1026 | continue; |
1027 | } |
1028 | |
1029 | // Fill vtxPrev by copying from previous transactions vtxPrev |
1030 | wtxNew.AddSupportingTransactions(txdb); |
1031 | wtxNew.fTimeReceivedIsTxTime = true; |
1032 | |
1033 | break; |
1034 | } |
1035 | } |
1036 | } |
1037 | return true; |
1038 | } |
1039 | |
1040 | bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet) |
1041 | { |
1042 | vector< pair<CScript, int64> > vecSend; |
1043 | vecSend.push_back(make_pair(scriptPubKey, nValue)); |
1044 | return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet); |
1045 | } |
1046 | |
1047 | // Call after CreateTransaction unless you want to abort |
1048 | bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey) |
1049 | { |
1050 | CRITICAL_BLOCK(cs_main) |
1051 | CRITICAL_BLOCK(cs_wallet) |
1052 | { |
1053 | printf("CommitTransaction:\n%s", wtxNew.ToString().c_str()); |
1054 | { |
1055 | // This is only to keep the database open to defeat the auto-flush for the |
1056 | // duration of this scope. This is the only place where this optimization |
1057 | // maybe makes sense; please don't do it anywhere else. |
1058 | CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL; |
1059 | |
1060 | // Take key pair from key pool so it won't be used again |
1061 | reservekey.KeepKey(); |
1062 | |
1063 | // Add tx to wallet, because if it has change it's also ours, |
1064 | // otherwise just for transaction history. |
1065 | AddToWallet(wtxNew); |
1066 | |
1067 | // Mark old coins as spent |
1068 | set<CWalletTx*> setCoins; |
1069 | BOOST_FOREACH(const CTxIn& txin, wtxNew.vin) |
1070 | { |
1071 | CWalletTx &coin = mapWallet[txin.prevout.hash]; |
1072 | coin.pwallet = this; |
1073 | coin.MarkSpent(txin.prevout.n); |
1074 | coin.WriteToDisk(); |
1075 | vWalletUpdated.push_back(coin.GetHash()); |
1076 | } |
1077 | |
1078 | if (fFileBacked) |
1079 | delete pwalletdb; |
1080 | } |
1081 | |
1082 | // Track how many getdata requests our transaction gets |
1083 | mapRequestCount[wtxNew.GetHash()] = 0; |
1084 | |
1085 | // Broadcast |
1086 | if (!wtxNew.AcceptToMemoryPool()) |
1087 | { |
1088 | // This must not fail. The transaction has already been signed and recorded. |
1089 | printf("CommitTransaction() : Error: Transaction not valid"); |
1090 | return false; |
1091 | } |
1092 | wtxNew.RelayWalletTransaction(); |
1093 | } |
1094 | MainFrameRepaint(); |
1095 | return true; |
1096 | } |
1097 | |
1098 | |
1099 | |
1100 | |
1101 | string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee) |
1102 | { |
1103 | CReserveKey reservekey(this); |
1104 | int64 nFeeRequired; |
1105 | |
1106 | if (IsLocked()) |
1107 | { |
1108 | string strError = _("Error: Wallet locked, unable to create transaction "); |
1109 | printf("SendMoney() : %s", strError.c_str()); |
1110 | return strError; |
1111 | } |
1112 | if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired)) |
1113 | { |
1114 | string strError; |
1115 | if (nValue + nFeeRequired > GetBalance()) |
1116 | 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).c_str()); |
1117 | else |
1118 | strError = _("Error: Transaction creation failed "); |
1119 | printf("SendMoney() : %s", strError.c_str()); |
1120 | return strError; |
1121 | } |
1122 | |
1123 | if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL)) |
1124 | return "ABORTED"; |
1125 | |
1126 | if (!CommitTransaction(wtxNew, reservekey)) |
1127 | 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."); |
1128 | |
1129 | MainFrameRepaint(); |
1130 | return ""; |
1131 | } |
1132 | |
1133 | |
1134 | |
1135 | string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee) |
1136 | { |
1137 | // Check amount |
1138 | if (nValue <= 0) |
1139 | return _("Invalid amount"); |
1140 | if (nValue + nTransactionFee > GetBalance()) |
1141 | return _("Insufficient funds"); |
1142 | |
1143 | // Parse bitcoin address |
1144 | CScript scriptPubKey; |
1145 | scriptPubKey.SetBitcoinAddress(address); |
1146 | |
1147 | return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee); |
1148 | } |
1149 | |
1150 | |
1151 | |
1152 | |
1153 | int CWallet::LoadWallet(bool& fFirstRunRet) |
1154 | { |
1155 | if (!fFileBacked) |
1156 | return false; |
1157 | fFirstRunRet = false; |
1158 | int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this); |
1159 | if (nLoadWalletRet == DB_NEED_REWRITE) |
1160 | { |
1161 | if (CDB::Rewrite(strWalletFile, "\x04pool")) |
1162 | { |
1163 | setKeyPool.clear(); |
1164 | // Note: can't top-up keypool here, because wallet is locked. |
1165 | // User will be prompted to unlock wallet the next operation |
1166 | // the requires a new key. |
1167 | } |
1168 | nLoadWalletRet = DB_NEED_REWRITE; |
1169 | } |
1170 | |
1171 | if (nLoadWalletRet != DB_LOAD_OK) |
1172 | return nLoadWalletRet; |
1173 | fFirstRunRet = vchDefaultKey.empty(); |
1174 | |
1175 | if (!HaveKey(Hash160(vchDefaultKey))) |
1176 | { |
1177 | // Create new keyUser and set as default key |
1178 | RandAddSeedPerfmon(); |
1179 | |
1180 | std::vector<unsigned char> newDefaultKey; |
1181 | if (!GetKeyFromPool(newDefaultKey, false)) |
1182 | return DB_LOAD_FAIL; |
1183 | SetDefaultKey(newDefaultKey); |
1184 | if (!SetAddressBookName(CBitcoinAddress(vchDefaultKey), "")) |
1185 | return DB_LOAD_FAIL; |
1186 | } |
1187 | |
1188 | CreateThread(ThreadFlushWalletDB, &strWalletFile); |
1189 | return DB_LOAD_OK; |
1190 | } |
1191 | |
1192 | |
1193 | bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName) |
1194 | { |
1195 | mapAddressBook[address] = strName; |
1196 | if (!fFileBacked) |
1197 | return false; |
1198 | return CWalletDB(strWalletFile).WriteName(address.ToString(), strName); |
1199 | } |
1200 | |
1201 | bool CWallet::DelAddressBookName(const CBitcoinAddress& address) |
1202 | { |
1203 | mapAddressBook.erase(address); |
1204 | if (!fFileBacked) |
1205 | return false; |
1206 | return CWalletDB(strWalletFile).EraseName(address.ToString()); |
1207 | } |
1208 | |
1209 | |
1210 | void CWallet::PrintWallet(const CBlock& block) |
1211 | { |
1212 | CRITICAL_BLOCK(cs_wallet) |
1213 | { |
1214 | if (mapWallet.count(block.vtx[0].GetHash())) |
1215 | { |
1216 | CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()]; |
1217 | printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit()); |
1218 | } |
1219 | } |
1220 | printf("\n"); |
1221 | } |
1222 | |
1223 | bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx) |
1224 | { |
1225 | CRITICAL_BLOCK(cs_wallet) |
1226 | { |
1227 | map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx); |
1228 | if (mi != mapWallet.end()) |
1229 | { |
1230 | wtx = (*mi).second; |
1231 | return true; |
1232 | } |
1233 | } |
1234 | return false; |
1235 | } |
1236 | |
1237 | bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey) |
1238 | { |
1239 | if (fFileBacked) |
1240 | { |
1241 | if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey)) |
1242 | return false; |
1243 | } |
1244 | vchDefaultKey = vchPubKey; |
1245 | return true; |
1246 | } |
1247 | |
1248 | bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut) |
1249 | { |
1250 | if (!pwallet->fFileBacked) |
1251 | return false; |
1252 | strWalletFileOut = pwallet->strWalletFile; |
1253 | return true; |
1254 | } |
1255 | |
1256 | // |
1257 | // Mark old keypool keys as used, |
1258 | // and generate all new keys |
1259 | // |
1260 | bool CWallet::NewKeyPool() |
1261 | { |
1262 | CRITICAL_BLOCK(cs_wallet) |
1263 | { |
1264 | CWalletDB walletdb(strWalletFile); |
1265 | BOOST_FOREACH(int64 nIndex, setKeyPool) |
1266 | walletdb.ErasePool(nIndex); |
1267 | setKeyPool.clear(); |
1268 | |
1269 | if (IsLocked()) |
1270 | return false; |
1271 | |
1272 | int64 nKeys = max(GetArg("-keypool", 100), (int64)0); |
1273 | for (int i = 0; i < nKeys; i++) |
1274 | { |
1275 | int64 nIndex = i+1; |
1276 | walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey())); |
1277 | setKeyPool.insert(nIndex); |
1278 | } |
1279 | printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys); |
1280 | } |
1281 | return true; |
1282 | } |
1283 | |
1284 | bool CWallet::TopUpKeyPool() |
1285 | { |
1286 | CRITICAL_BLOCK(cs_wallet) |
1287 | { |
1288 | if (IsLocked()) |
1289 | return false; |
1290 | |
1291 | CWalletDB walletdb(strWalletFile); |
1292 | |
1293 | // Top up key pool |
1294 | int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0); |
1295 | while (setKeyPool.size() < nTargetSize+1) |
1296 | { |
1297 | int64 nEnd = 1; |
1298 | if (!setKeyPool.empty()) |
1299 | nEnd = *(--setKeyPool.end()) + 1; |
1300 | if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) |
1301 | throw runtime_error("TopUpKeyPool() : writing generated key failed"); |
1302 | setKeyPool.insert(nEnd); |
1303 | printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size()); |
1304 | } |
1305 | } |
1306 | return true; |
1307 | } |
1308 | |
1309 | void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool) |
1310 | { |
1311 | nIndex = -1; |
1312 | keypool.vchPubKey.clear(); |
1313 | CRITICAL_BLOCK(cs_wallet) |
1314 | { |
1315 | if (!IsLocked()) |
1316 | TopUpKeyPool(); |
1317 | |
1318 | // Get the oldest key |
1319 | if(setKeyPool.empty()) |
1320 | return; |
1321 | |
1322 | CWalletDB walletdb(strWalletFile); |
1323 | |
1324 | nIndex = *(setKeyPool.begin()); |
1325 | setKeyPool.erase(setKeyPool.begin()); |
1326 | if (!walletdb.ReadPool(nIndex, keypool)) |
1327 | throw runtime_error("ReserveKeyFromKeyPool() : read failed"); |
1328 | if (!HaveKey(Hash160(keypool.vchPubKey))) |
1329 | throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool"); |
1330 | assert(!keypool.vchPubKey.empty()); |
1331 | printf("keypool reserve %"PRI64d"\n", nIndex); |
1332 | } |
1333 | } |
1334 | |
1335 | void CWallet::KeepKey(int64 nIndex) |
1336 | { |
1337 | // Remove from key pool |
1338 | if (fFileBacked) |
1339 | { |
1340 | CWalletDB walletdb(strWalletFile); |
1341 | walletdb.ErasePool(nIndex); |
1342 | } |
1343 | printf("keypool keep %"PRI64d"\n", nIndex); |
1344 | } |
1345 | |
1346 | void CWallet::ReturnKey(int64 nIndex) |
1347 | { |
1348 | // Return to key pool |
1349 | CRITICAL_BLOCK(cs_wallet) |
1350 | setKeyPool.insert(nIndex); |
1351 | printf("keypool return %"PRI64d"\n", nIndex); |
1352 | } |
1353 | |
1354 | bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse) |
1355 | { |
1356 | int64 nIndex = 0; |
1357 | CKeyPool keypool; |
1358 | CRITICAL_BLOCK(cs_wallet) |
1359 | { |
1360 | ReserveKeyFromKeyPool(nIndex, keypool); |
1361 | if (nIndex == -1) |
1362 | { |
1363 | if (fAllowReuse && !vchDefaultKey.empty()) |
1364 | { |
1365 | result = vchDefaultKey; |
1366 | return true; |
1367 | } |
1368 | if (IsLocked()) return false; |
1369 | result = GenerateNewKey(); |
1370 | return true; |
1371 | } |
1372 | KeepKey(nIndex); |
1373 | result = keypool.vchPubKey; |
1374 | } |
1375 | return true; |
1376 | } |
1377 | |
1378 | int64 CWallet::GetOldestKeyPoolTime() |
1379 | { |
1380 | int64 nIndex = 0; |
1381 | CKeyPool keypool; |
1382 | ReserveKeyFromKeyPool(nIndex, keypool); |
1383 | if (nIndex == -1) |
1384 | return GetTime(); |
1385 | ReturnKey(nIndex); |
1386 | return keypool.nTime; |
1387 | } |
1388 | |
1389 | vector<unsigned char> CReserveKey::GetReservedKey() |
1390 | { |
1391 | if (nIndex == -1) |
1392 | { |
1393 | CKeyPool keypool; |
1394 | pwallet->ReserveKeyFromKeyPool(nIndex, keypool); |
1395 | if (nIndex != -1) |
1396 | vchPubKey = keypool.vchPubKey; |
1397 | else |
1398 | { |
1399 | printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool."); |
1400 | vchPubKey = pwallet->vchDefaultKey; |
1401 | } |
1402 | } |
1403 | assert(!vchPubKey.empty()); |
1404 | return vchPubKey; |
1405 | } |
1406 | |
1407 | void CReserveKey::KeepKey() |
1408 | { |
1409 | if (nIndex != -1) |
1410 | pwallet->KeepKey(nIndex); |
1411 | nIndex = -1; |
1412 | vchPubKey.clear(); |
1413 | } |
1414 | |
1415 | void CReserveKey::ReturnKey() |
1416 | { |
1417 | if (nIndex != -1) |
1418 | pwallet->ReturnKey(nIndex); |
1419 | nIndex = -1; |
1420 | vchPubKey.clear(); |
1421 | } |
1422 |