You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

wallet.cpp 36KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  1. // Copyright (c) 2009-2011 Satoshi Nakamoto & Bitcoin developers
  2. // Distributed under the MIT/X11 software license, see the accompanying
  3. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
  4. #include "headers.h"
  5. #include "db.h"
  6. #include "cryptopp/sha.h"
  7. using namespace std;
  8. //////////////////////////////////////////////////////////////////////////////
  9. //
  10. // mapWallet
  11. //
  12. bool CWallet::AddKey(const CKey& key)
  13. {
  14. this->CKeyStore::AddKey(key);
  15. if (!fFileBacked)
  16. return true;
  17. return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
  18. }
  19. void CWallet::WalletUpdateSpent(const CTransaction &tx)
  20. {
  21. // Anytime a signature is successfully verified, it's proof the outpoint is spent.
  22. // Update the wallet spent flag if it doesn't know due to wallet.dat being
  23. // restored from backup or the user making copies of wallet.dat.
  24. CRITICAL_BLOCK(cs_mapWallet)
  25. {
  26. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  27. {
  28. map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
  29. if (mi != mapWallet.end())
  30. {
  31. CWalletTx& wtx = (*mi).second;
  32. if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
  33. {
  34. printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
  35. wtx.MarkSpent(txin.prevout.n);
  36. wtx.WriteToDisk();
  37. vWalletUpdated.push_back(txin.prevout.hash);
  38. }
  39. }
  40. }
  41. }
  42. }
  43. bool CWallet::AddToWallet(const CWalletTx& wtxIn)
  44. {
  45. uint256 hash = wtxIn.GetHash();
  46. CRITICAL_BLOCK(cs_mapWallet)
  47. {
  48. // Inserts only if not already there, returns tx inserted or tx found
  49. pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
  50. CWalletTx& wtx = (*ret.first).second;
  51. wtx.pwallet = this;
  52. bool fInsertedNew = ret.second;
  53. if (fInsertedNew)
  54. wtx.nTimeReceived = GetAdjustedTime();
  55. bool fUpdated = false;
  56. if (!fInsertedNew)
  57. {
  58. // Merge
  59. if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
  60. {
  61. wtx.hashBlock = wtxIn.hashBlock;
  62. fUpdated = true;
  63. }
  64. if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
  65. {
  66. wtx.vMerkleBranch = wtxIn.vMerkleBranch;
  67. wtx.nIndex = wtxIn.nIndex;
  68. fUpdated = true;
  69. }
  70. if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
  71. {
  72. wtx.fFromMe = wtxIn.fFromMe;
  73. fUpdated = true;
  74. }
  75. fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
  76. }
  77. //// debug print
  78. printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
  79. // Write to disk
  80. if (fInsertedNew || fUpdated)
  81. if (!wtx.WriteToDisk())
  82. return false;
  83. #ifndef QT_GUI
  84. // If default receiving address gets used, replace it with a new one
  85. CScript scriptDefaultKey;
  86. scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
  87. BOOST_FOREACH(const CTxOut& txout, wtx.vout)
  88. {
  89. if (txout.scriptPubKey == scriptDefaultKey)
  90. SetDefaultKey(GetKeyFromKeyPool());
  91. }
  92. #endif
  93. // Notify UI
  94. vWalletUpdated.push_back(hash);
  95. // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
  96. WalletUpdateSpent(wtx);
  97. }
  98. // Refresh UI
  99. MainFrameRepaint();
  100. return true;
  101. }
  102. bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
  103. {
  104. uint256 hash = tx.GetHash();
  105. bool fExisted = mapWallet.count(hash);
  106. if (fExisted && !fUpdate) return false;
  107. if (fExisted || IsMine(tx) || IsFromMe(tx))
  108. {
  109. CWalletTx wtx(this,tx);
  110. // Get merkle branch if transaction was found in a block
  111. if (pblock)
  112. wtx.SetMerkleBranch(pblock);
  113. return AddToWallet(wtx);
  114. }
  115. else
  116. WalletUpdateSpent(tx);
  117. return false;
  118. }
  119. bool CWallet::EraseFromWallet(uint256 hash)
  120. {
  121. if (!fFileBacked)
  122. return false;
  123. CRITICAL_BLOCK(cs_mapWallet)
  124. {
  125. if (mapWallet.erase(hash))
  126. CWalletDB(strWalletFile).EraseTx(hash);
  127. }
  128. return true;
  129. }
  130. bool CWallet::IsMine(const CTxIn &txin) const
  131. {
  132. CRITICAL_BLOCK(cs_mapWallet)
  133. {
  134. map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
  135. if (mi != mapWallet.end())
  136. {
  137. const CWalletTx& prev = (*mi).second;
  138. if (txin.prevout.n < prev.vout.size())
  139. if (IsMine(prev.vout[txin.prevout.n]))
  140. return true;
  141. }
  142. }
  143. return false;
  144. }
  145. int64 CWallet::GetDebit(const CTxIn &txin) const
  146. {
  147. CRITICAL_BLOCK(cs_mapWallet)
  148. {
  149. map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
  150. if (mi != mapWallet.end())
  151. {
  152. const CWalletTx& prev = (*mi).second;
  153. if (txin.prevout.n < prev.vout.size())
  154. if (IsMine(prev.vout[txin.prevout.n]))
  155. return prev.vout[txin.prevout.n].nValue;
  156. }
  157. }
  158. return 0;
  159. }
  160. int64 CWalletTx::GetTxTime() const
  161. {
  162. if (!fTimeReceivedIsTxTime && hashBlock != 0)
  163. {
  164. // If we did not receive the transaction directly, we rely on the block's
  165. // time to figure out when it happened. We use the median over a range
  166. // of blocks to try to filter out inaccurate block times.
  167. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
  168. if (mi != mapBlockIndex.end())
  169. {
  170. CBlockIndex* pindex = (*mi).second;
  171. if (pindex)
  172. return pindex->GetMedianTime();
  173. }
  174. }
  175. return nTimeReceived;
  176. }
  177. int CWalletTx::GetRequestCount() const
  178. {
  179. // Returns -1 if it wasn't being tracked
  180. int nRequests = -1;
  181. CRITICAL_BLOCK(pwallet->cs_mapRequestCount)
  182. {
  183. if (IsCoinBase())
  184. {
  185. // Generated block
  186. if (hashBlock != 0)
  187. {
  188. map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
  189. if (mi != pwallet->mapRequestCount.end())
  190. nRequests = (*mi).second;
  191. }
  192. }
  193. else
  194. {
  195. // Did anyone request this transaction?
  196. map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
  197. if (mi != pwallet->mapRequestCount.end())
  198. {
  199. nRequests = (*mi).second;
  200. // How about the block it's in?
  201. if (nRequests == 0 && hashBlock != 0)
  202. {
  203. map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
  204. if (mi != pwallet->mapRequestCount.end())
  205. nRequests = (*mi).second;
  206. else
  207. nRequests = 1; // If it's in someone else's block it must have got out
  208. }
  209. }
  210. }
  211. }
  212. return nRequests;
  213. }
  214. void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string, int64> >& listReceived,
  215. list<pair<string, int64> >& listSent, int64& nFee, string& strSentAccount) const
  216. {
  217. nGeneratedImmature = nGeneratedMature = nFee = 0;
  218. listReceived.clear();
  219. listSent.clear();
  220. strSentAccount = strFromAccount;
  221. if (IsCoinBase())
  222. {
  223. if (GetBlocksToMaturity() > 0)
  224. nGeneratedImmature = pwallet->GetCredit(*this);
  225. else
  226. nGeneratedMature = GetCredit();
  227. return;
  228. }
  229. // Compute fee:
  230. int64 nDebit = GetDebit();
  231. if (nDebit > 0) // debit>0 means we signed/sent this transaction
  232. {
  233. int64 nValueOut = GetValueOut();
  234. nFee = nDebit - nValueOut;
  235. }
  236. // Sent/received. Standard client will never generate a send-to-multiple-recipients,
  237. // but non-standard clients might (so return a list of address/amount pairs)
  238. BOOST_FOREACH(const CTxOut& txout, vout)
  239. {
  240. string address;
  241. uint160 hash160;
  242. vector<unsigned char> vchPubKey;
  243. if (ExtractHash160(txout.scriptPubKey, hash160))
  244. address = Hash160ToAddress(hash160);
  245. else if (ExtractPubKey(txout.scriptPubKey, NULL, vchPubKey))
  246. address = PubKeyToAddress(vchPubKey);
  247. else
  248. {
  249. printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
  250. this->GetHash().ToString().c_str());
  251. address = " unknown ";
  252. }
  253. // Don't report 'change' txouts
  254. if (nDebit > 0 && pwallet->IsChange(txout))
  255. continue;
  256. if (nDebit > 0)
  257. listSent.push_back(make_pair(address, txout.nValue));
  258. if (pwallet->IsMine(txout))
  259. listReceived.push_back(make_pair(address, txout.nValue));
  260. }
  261. }
  262. void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
  263. int64& nSent, int64& nFee) const
  264. {
  265. nGenerated = nReceived = nSent = nFee = 0;
  266. int64 allGeneratedImmature, allGeneratedMature, allFee;
  267. allGeneratedImmature = allGeneratedMature = allFee = 0;
  268. string strSentAccount;
  269. list<pair<string, int64> > listReceived;
  270. list<pair<string, int64> > listSent;
  271. GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
  272. if (strAccount == "")
  273. nGenerated = allGeneratedMature;
  274. if (strAccount == strSentAccount)
  275. {
  276. BOOST_FOREACH(const PAIRTYPE(string,int64)& s, listSent)
  277. nSent += s.second;
  278. nFee = allFee;
  279. }
  280. CRITICAL_BLOCK(pwallet->cs_mapAddressBook)
  281. {
  282. BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
  283. {
  284. if (pwallet->mapAddressBook.count(r.first))
  285. {
  286. map<string, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
  287. if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
  288. nReceived += r.second;
  289. }
  290. else if (strAccount.empty())
  291. {
  292. nReceived += r.second;
  293. }
  294. }
  295. }
  296. }
  297. void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
  298. {
  299. vtxPrev.clear();
  300. const int COPY_DEPTH = 3;
  301. if (SetMerkleBranch() < COPY_DEPTH)
  302. {
  303. vector<uint256> vWorkQueue;
  304. BOOST_FOREACH(const CTxIn& txin, vin)
  305. vWorkQueue.push_back(txin.prevout.hash);
  306. // This critsect is OK because txdb is already open
  307. CRITICAL_BLOCK(pwallet->cs_mapWallet)
  308. {
  309. map<uint256, const CMerkleTx*> mapWalletPrev;
  310. set<uint256> setAlreadyDone;
  311. for (int i = 0; i < vWorkQueue.size(); i++)
  312. {
  313. uint256 hash = vWorkQueue[i];
  314. if (setAlreadyDone.count(hash))
  315. continue;
  316. setAlreadyDone.insert(hash);
  317. CMerkleTx tx;
  318. map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
  319. if (mi != pwallet->mapWallet.end())
  320. {
  321. tx = (*mi).second;
  322. BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
  323. mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
  324. }
  325. else if (mapWalletPrev.count(hash))
  326. {
  327. tx = *mapWalletPrev[hash];
  328. }
  329. else if (!fClient && txdb.ReadDiskTx(hash, tx))
  330. {
  331. ;
  332. }
  333. else
  334. {
  335. printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
  336. continue;
  337. }
  338. int nDepth = tx.SetMerkleBranch();
  339. vtxPrev.push_back(tx);
  340. if (nDepth < COPY_DEPTH)
  341. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  342. vWorkQueue.push_back(txin.prevout.hash);
  343. }
  344. }
  345. }
  346. reverse(vtxPrev.begin(), vtxPrev.end());
  347. }
  348. bool CWalletTx::WriteToDisk()
  349. {
  350. return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
  351. }
  352. int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
  353. {
  354. int ret = 0;
  355. CBlockIndex* pindex = pindexStart;
  356. CRITICAL_BLOCK(cs_mapWallet)
  357. {
  358. while (pindex)
  359. {
  360. CBlock block;
  361. block.ReadFromDisk(pindex, true);
  362. BOOST_FOREACH(CTransaction& tx, block.vtx)
  363. {
  364. if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
  365. ret++;
  366. }
  367. pindex = pindex->pnext;
  368. }
  369. }
  370. return ret;
  371. }
  372. void CWallet::ReacceptWalletTransactions()
  373. {
  374. CTxDB txdb("r");
  375. bool fRepeat = true;
  376. while (fRepeat) CRITICAL_BLOCK(cs_mapWallet)
  377. {
  378. fRepeat = false;
  379. vector<CDiskTxPos> vMissingTx;
  380. BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
  381. {
  382. CWalletTx& wtx = item.second;
  383. if (wtx.IsCoinBase() && wtx.IsSpent(0))
  384. continue;
  385. CTxIndex txindex;
  386. bool fUpdated = false;
  387. if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
  388. {
  389. // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
  390. if (txindex.vSpent.size() != wtx.vout.size())
  391. {
  392. printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
  393. continue;
  394. }
  395. for (int i = 0; i < txindex.vSpent.size(); i++)
  396. {
  397. if (wtx.IsSpent(i))
  398. continue;
  399. if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
  400. {
  401. wtx.MarkSpent(i);
  402. fUpdated = true;
  403. vMissingTx.push_back(txindex.vSpent[i]);
  404. }
  405. }
  406. if (fUpdated)
  407. {
  408. printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
  409. wtx.MarkDirty();
  410. wtx.WriteToDisk();
  411. }
  412. }
  413. else
  414. {
  415. // Reaccept any txes of ours that aren't already in a block
  416. if (!wtx.IsCoinBase())
  417. wtx.AcceptWalletTransaction(txdb, false);
  418. }
  419. }
  420. if (!vMissingTx.empty())
  421. {
  422. // TODO: optimize this to scan just part of the block chain?
  423. if (ScanForWalletTransactions(pindexGenesisBlock))
  424. fRepeat = true; // Found missing transactions: re-do Reaccept.
  425. }
  426. }
  427. }
  428. void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
  429. {
  430. BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
  431. {
  432. if (!tx.IsCoinBase())
  433. {
  434. uint256 hash = tx.GetHash();
  435. if (!txdb.ContainsTx(hash))
  436. RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
  437. }
  438. }
  439. if (!IsCoinBase())
  440. {
  441. uint256 hash = GetHash();
  442. if (!txdb.ContainsTx(hash))
  443. {
  444. printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
  445. RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
  446. }
  447. }
  448. }
  449. void CWalletTx::RelayWalletTransaction()
  450. {
  451. CTxDB txdb("r");
  452. RelayWalletTransaction(txdb);
  453. }
  454. void CWallet::ResendWalletTransactions()
  455. {
  456. // Do this infrequently and randomly to avoid giving away
  457. // that these are our transactions.
  458. static int64 nNextTime;
  459. if (GetTime() < nNextTime)
  460. return;
  461. bool fFirst = (nNextTime == 0);
  462. nNextTime = GetTime() + GetRand(30 * 60);
  463. if (fFirst)
  464. return;
  465. // Only do it if there's been a new block since last time
  466. static int64 nLastTime;
  467. if (nTimeBestReceived < nLastTime)
  468. return;
  469. nLastTime = GetTime();
  470. // Rebroadcast any of our txes that aren't in a block yet
  471. printf("ResendWalletTransactions()\n");
  472. CTxDB txdb("r");
  473. CRITICAL_BLOCK(cs_mapWallet)
  474. {
  475. // Sort them in chronological order
  476. multimap<unsigned int, CWalletTx*> mapSorted;
  477. BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
  478. {
  479. CWalletTx& wtx = item.second;
  480. // Don't rebroadcast until it's had plenty of time that
  481. // it should have gotten in already by now.
  482. if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
  483. mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
  484. }
  485. BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
  486. {
  487. CWalletTx& wtx = *item.second;
  488. wtx.RelayWalletTransaction(txdb);
  489. }
  490. }
  491. }
  492. //////////////////////////////////////////////////////////////////////////////
  493. //
  494. // Actions
  495. //
  496. int64 CWallet::GetBalance() const
  497. {
  498. int64 nStart = GetTimeMillis();
  499. int64 nTotal = 0;
  500. CRITICAL_BLOCK(cs_mapWallet)
  501. {
  502. for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
  503. {
  504. const CWalletTx* pcoin = &(*it).second;
  505. if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
  506. continue;
  507. nTotal += pcoin->GetAvailableCredit();
  508. }
  509. }
  510. //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
  511. return nTotal;
  512. }
  513. int64 CWallet::GetUnconfirmedBalance() const
  514. {
  515. int64 nTotal = 0;
  516. CRITICAL_BLOCK(cs_mapWallet)
  517. {
  518. for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
  519. {
  520. const CWalletTx* pcoin = &(*it).second;
  521. if (pcoin->IsFinal() && pcoin->IsConfirmed())
  522. continue;
  523. nTotal += pcoin->GetAvailableCredit();
  524. }
  525. }
  526. return nTotal;
  527. }
  528. bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
  529. {
  530. setCoinsRet.clear();
  531. nValueRet = 0;
  532. // List of values less than target
  533. pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
  534. coinLowestLarger.first = INT64_MAX;
  535. coinLowestLarger.second.first = NULL;
  536. vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
  537. int64 nTotalLower = 0;
  538. CRITICAL_BLOCK(cs_mapWallet)
  539. {
  540. vector<const CWalletTx*> vCoins;
  541. vCoins.reserve(mapWallet.size());
  542. for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
  543. vCoins.push_back(&(*it).second);
  544. random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
  545. BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
  546. {
  547. if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
  548. continue;
  549. if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
  550. continue;
  551. int nDepth = pcoin->GetDepthInMainChain();
  552. if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
  553. continue;
  554. for (int i = 0; i < pcoin->vout.size(); i++)
  555. {
  556. if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
  557. continue;
  558. int64 n = pcoin->vout[i].nValue;
  559. if (n <= 0)
  560. continue;
  561. pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
  562. if (n == nTargetValue)
  563. {
  564. setCoinsRet.insert(coin.second);
  565. nValueRet += coin.first;
  566. return true;
  567. }
  568. else if (n < nTargetValue + CENT)
  569. {
  570. vValue.push_back(coin);
  571. nTotalLower += n;
  572. }
  573. else if (n < coinLowestLarger.first)
  574. {
  575. coinLowestLarger = coin;
  576. }
  577. }
  578. }
  579. }
  580. if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
  581. {
  582. for (int i = 0; i < vValue.size(); ++i)
  583. {
  584. setCoinsRet.insert(vValue[i].second);
  585. nValueRet += vValue[i].first;
  586. }
  587. return true;
  588. }
  589. if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
  590. {
  591. if (coinLowestLarger.second.first == NULL)
  592. return false;
  593. setCoinsRet.insert(coinLowestLarger.second);
  594. nValueRet += coinLowestLarger.first;
  595. return true;
  596. }
  597. if (nTotalLower >= nTargetValue + CENT)
  598. nTargetValue += CENT;
  599. // Solve subset sum by stochastic approximation
  600. sort(vValue.rbegin(), vValue.rend());
  601. vector<char> vfIncluded;
  602. vector<char> vfBest(vValue.size(), true);
  603. int64 nBest = nTotalLower;
  604. for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
  605. {
  606. vfIncluded.assign(vValue.size(), false);
  607. int64 nTotal = 0;
  608. bool fReachedTarget = false;
  609. for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
  610. {
  611. for (int i = 0; i < vValue.size(); i++)
  612. {
  613. if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
  614. {
  615. nTotal += vValue[i].first;
  616. vfIncluded[i] = true;
  617. if (nTotal >= nTargetValue)
  618. {
  619. fReachedTarget = true;
  620. if (nTotal < nBest)
  621. {
  622. nBest = nTotal;
  623. vfBest = vfIncluded;
  624. }
  625. nTotal -= vValue[i].first;
  626. vfIncluded[i] = false;
  627. }
  628. }
  629. }
  630. }
  631. }
  632. // If the next larger is still closer, return it
  633. if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
  634. {
  635. setCoinsRet.insert(coinLowestLarger.second);
  636. nValueRet += coinLowestLarger.first;
  637. }
  638. else {
  639. for (int i = 0; i < vValue.size(); i++)
  640. if (vfBest[i])
  641. {
  642. setCoinsRet.insert(vValue[i].second);
  643. nValueRet += vValue[i].first;
  644. }
  645. //// debug print
  646. printf("SelectCoins() best subset: ");
  647. for (int i = 0; i < vValue.size(); i++)
  648. if (vfBest[i])
  649. printf("%s ", FormatMoney(vValue[i].first).c_str());
  650. printf("total %s\n", FormatMoney(nBest).c_str());
  651. }
  652. return true;
  653. }
  654. bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
  655. {
  656. return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
  657. SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
  658. SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
  659. }
  660. bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
  661. {
  662. int64 nValue = 0;
  663. BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
  664. {
  665. if (nValue < 0)
  666. return false;
  667. nValue += s.second;
  668. }
  669. if (vecSend.empty() || nValue < 0)
  670. return false;
  671. wtxNew.pwallet = this;
  672. CRITICAL_BLOCK(cs_main)
  673. {
  674. // txdb must be opened before the mapWallet lock
  675. CTxDB txdb("r");
  676. CRITICAL_BLOCK(cs_mapWallet)
  677. {
  678. nFeeRet = nTransactionFee;
  679. loop
  680. {
  681. wtxNew.vin.clear();
  682. wtxNew.vout.clear();
  683. wtxNew.fFromMe = true;
  684. int64 nTotalValue = nValue + nFeeRet;
  685. double dPriority = 0;
  686. // vouts to the payees
  687. BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
  688. wtxNew.vout.push_back(CTxOut(s.second, s.first));
  689. // Choose coins to use
  690. set<pair<const CWalletTx*,unsigned int> > setCoins;
  691. int64 nValueIn = 0;
  692. if (!SelectCoins(nTotalValue, setCoins, nValueIn))
  693. return false;
  694. BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
  695. {
  696. int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
  697. dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
  698. }
  699. // Fill a vout back to self with any change
  700. int64 nChange = nValueIn - nTotalValue;
  701. if (nChange >= CENT)
  702. {
  703. // Note: We use a new key here to keep it from being obvious which side is the change.
  704. // The drawback is that by not reusing a previous key, the change may be lost if a
  705. // backup is restored, if the backup doesn't have the new private key for the change.
  706. // If we reused the old key, it would be possible to add code to look for and
  707. // rediscover unknown transactions that were written with keys of ours to recover
  708. // post-backup change.
  709. // Reserve a new key pair from key pool
  710. vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
  711. assert(mapKeys.count(vchPubKey));
  712. // Fill a vout to ourself, using same address type as the payment
  713. CScript scriptChange;
  714. if (vecSend[0].first.GetBitcoinAddressHash160() != 0)
  715. scriptChange.SetBitcoinAddress(vchPubKey);
  716. else
  717. scriptChange << vchPubKey << OP_CHECKSIG;
  718. // Insert change txn at random position:
  719. vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
  720. wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
  721. }
  722. else
  723. reservekey.ReturnKey();
  724. // Fill vin
  725. BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
  726. wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
  727. // Sign
  728. int nIn = 0;
  729. BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
  730. if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
  731. return false;
  732. // Limit size
  733. unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
  734. if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
  735. return false;
  736. dPriority /= nBytes;
  737. // Check that enough fee is included
  738. int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
  739. bool fAllowFree = CTransaction::AllowFree(dPriority);
  740. int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);
  741. if (nFeeRet < max(nPayFee, nMinFee))
  742. {
  743. nFeeRet = max(nPayFee, nMinFee);
  744. continue;
  745. }
  746. // Fill vtxPrev by copying from previous transactions vtxPrev
  747. wtxNew.AddSupportingTransactions(txdb);
  748. wtxNew.fTimeReceivedIsTxTime = true;
  749. break;
  750. }
  751. }
  752. }
  753. return true;
  754. }
  755. bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
  756. {
  757. vector< pair<CScript, int64> > vecSend;
  758. vecSend.push_back(make_pair(scriptPubKey, nValue));
  759. return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
  760. }
  761. // Call after CreateTransaction unless you want to abort
  762. bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
  763. {
  764. CRITICAL_BLOCK(cs_main)
  765. {
  766. printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
  767. CRITICAL_BLOCK(cs_mapWallet)
  768. {
  769. // This is only to keep the database open to defeat the auto-flush for the
  770. // duration of this scope. This is the only place where this optimization
  771. // maybe makes sense; please don't do it anywhere else.
  772. CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
  773. // Take key pair from key pool so it won't be used again
  774. reservekey.KeepKey();
  775. // Add tx to wallet, because if it has change it's also ours,
  776. // otherwise just for transaction history.
  777. AddToWallet(wtxNew);
  778. // Mark old coins as spent
  779. set<CWalletTx*> setCoins;
  780. BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
  781. {
  782. CWalletTx &coin = mapWallet[txin.prevout.hash];
  783. coin.pwallet = this;
  784. coin.MarkSpent(txin.prevout.n);
  785. coin.WriteToDisk();
  786. vWalletUpdated.push_back(coin.GetHash());
  787. }
  788. if (fFileBacked)
  789. delete pwalletdb;
  790. }
  791. // Track how many getdata requests our transaction gets
  792. CRITICAL_BLOCK(cs_mapRequestCount)
  793. mapRequestCount[wtxNew.GetHash()] = 0;
  794. // Broadcast
  795. if (!wtxNew.AcceptToMemoryPool())
  796. {
  797. // This must not fail. The transaction has already been signed and recorded.
  798. printf("CommitTransaction() : Error: Transaction not valid");
  799. return false;
  800. }
  801. wtxNew.RelayWalletTransaction();
  802. }
  803. MainFrameRepaint();
  804. return true;
  805. }
  806. // requires cs_main lock
  807. string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
  808. {
  809. CReserveKey reservekey(this);
  810. int64 nFeeRequired;
  811. if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
  812. {
  813. string strError;
  814. if (nValue + nFeeRequired > GetBalance())
  815. strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str());
  816. else
  817. strError = _("Error: Transaction creation failed ");
  818. printf("SendMoney() : %s", strError.c_str());
  819. return strError;
  820. }
  821. if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
  822. return "ABORTED";
  823. if (!CommitTransaction(wtxNew, reservekey))
  824. 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.");
  825. MainFrameRepaint();
  826. return "";
  827. }
  828. // requires cs_main lock
  829. string CWallet::SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
  830. {
  831. // Check amount
  832. if (nValue <= 0)
  833. return _("Invalid amount");
  834. if (nValue + nTransactionFee > GetBalance())
  835. return _("Insufficient funds");
  836. // Parse bitcoin address
  837. CScript scriptPubKey;
  838. if (!scriptPubKey.SetBitcoinAddress(strAddress))
  839. return _("Invalid bitcoin address");
  840. return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
  841. }
  842. bool CWallet::LoadWallet(bool& fFirstRunRet)
  843. {
  844. if (!fFileBacked)
  845. return false;
  846. fFirstRunRet = false;
  847. if (!CWalletDB(strWalletFile,"cr+").LoadWallet(this))
  848. return false;
  849. fFirstRunRet = vchDefaultKey.empty();
  850. if (!mapKeys.count(vchDefaultKey))
  851. {
  852. // Create new default key
  853. RandAddSeedPerfmon();
  854. SetDefaultKey(GetKeyFromKeyPool());
  855. if (!SetAddressBookName(PubKeyToAddress(vchDefaultKey), ""))
  856. return false;
  857. }
  858. CreateThread(ThreadFlushWalletDB, &strWalletFile);
  859. return true;
  860. }
  861. bool CWallet::SetAddressBookName(const string& strAddress, const string& strName)
  862. {
  863. mapAddressBook[strAddress] = strName;
  864. if (!fFileBacked)
  865. return false;
  866. return CWalletDB(strWalletFile).WriteName(strAddress, strName);
  867. }
  868. bool CWallet::DelAddressBookName(const string& strAddress)
  869. {
  870. mapAddressBook.erase(strAddress);
  871. if (!fFileBacked)
  872. return false;
  873. return CWalletDB(strWalletFile).EraseName(strAddress);
  874. }
  875. void CWallet::PrintWallet(const CBlock& block)
  876. {
  877. CRITICAL_BLOCK(cs_mapWallet)
  878. {
  879. if (mapWallet.count(block.vtx[0].GetHash()))
  880. {
  881. CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
  882. printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
  883. }
  884. }
  885. printf("\n");
  886. }
  887. bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
  888. {
  889. CRITICAL_BLOCK(cs_mapWallet)
  890. {
  891. map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
  892. if (mi != mapWallet.end())
  893. {
  894. wtx = (*mi).second;
  895. return true;
  896. }
  897. }
  898. return false;
  899. }
  900. bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
  901. {
  902. if (fFileBacked)
  903. {
  904. if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
  905. return false;
  906. }
  907. vchDefaultKey = vchPubKey;
  908. return true;
  909. }
  910. bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
  911. {
  912. if (!pwallet->fFileBacked)
  913. return false;
  914. strWalletFileOut = pwallet->strWalletFile;
  915. return true;
  916. }
  917. void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
  918. {
  919. nIndex = -1;
  920. keypool.vchPubKey.clear();
  921. CRITICAL_BLOCK(cs_main)
  922. CRITICAL_BLOCK(cs_mapWallet)
  923. CRITICAL_BLOCK(cs_setKeyPool)
  924. {
  925. CWalletDB walletdb(strWalletFile);
  926. // Top up key pool
  927. int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
  928. while (setKeyPool.size() < nTargetSize+1)
  929. {
  930. int64 nEnd = 1;
  931. if (!setKeyPool.empty())
  932. nEnd = *(--setKeyPool.end()) + 1;
  933. if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
  934. throw runtime_error("ReserveKeyFromKeyPool() : writing generated key failed");
  935. setKeyPool.insert(nEnd);
  936. printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
  937. }
  938. // Get the oldest key
  939. assert(!setKeyPool.empty());
  940. nIndex = *(setKeyPool.begin());
  941. setKeyPool.erase(setKeyPool.begin());
  942. if (!walletdb.ReadPool(nIndex, keypool))
  943. throw runtime_error("ReserveKeyFromKeyPool() : read failed");
  944. if (!mapKeys.count(keypool.vchPubKey))
  945. throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
  946. assert(!keypool.vchPubKey.empty());
  947. printf("keypool reserve %"PRI64d"\n", nIndex);
  948. }
  949. }
  950. void CWallet::KeepKey(int64 nIndex)
  951. {
  952. // Remove from key pool
  953. if (fFileBacked)
  954. {
  955. CWalletDB walletdb(strWalletFile);
  956. CRITICAL_BLOCK(cs_main)
  957. {
  958. walletdb.ErasePool(nIndex);
  959. }
  960. }
  961. printf("keypool keep %"PRI64d"\n", nIndex);
  962. }
  963. void CWallet::ReturnKey(int64 nIndex)
  964. {
  965. // Return to key pool
  966. CRITICAL_BLOCK(cs_setKeyPool)
  967. setKeyPool.insert(nIndex);
  968. printf("keypool return %"PRI64d"\n", nIndex);
  969. }
  970. vector<unsigned char> CWallet::GetKeyFromKeyPool()
  971. {
  972. int64 nIndex = 0;
  973. CKeyPool keypool;
  974. ReserveKeyFromKeyPool(nIndex, keypool);
  975. KeepKey(nIndex);
  976. return keypool.vchPubKey;
  977. }
  978. int64 CWallet::GetOldestKeyPoolTime()
  979. {
  980. int64 nIndex = 0;
  981. CKeyPool keypool;
  982. ReserveKeyFromKeyPool(nIndex, keypool);
  983. ReturnKey(nIndex);
  984. return keypool.nTime;
  985. }
  986. vector<unsigned char> CReserveKey::GetReservedKey()
  987. {
  988. if (nIndex == -1)
  989. {
  990. CKeyPool keypool;
  991. pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
  992. vchPubKey = keypool.vchPubKey;
  993. }
  994. assert(!vchPubKey.empty());
  995. return vchPubKey;
  996. }
  997. void CReserveKey::KeepKey()
  998. {
  999. if (nIndex != -1)
  1000. pwallet->KeepKey(nIndex);
  1001. nIndex = -1;
  1002. vchPubKey.clear();
  1003. }
  1004. void CReserveKey::ReturnKey()
  1005. {
  1006. if (nIndex != -1)
  1007. pwallet->ReturnKey(nIndex);
  1008. nIndex = -1;
  1009. vchPubKey.clear();
  1010. }