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