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