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 76KB

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