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