What changed
Bitcoin v0.3.15 → v0.3.17
Release commit message: -- version 0.3.17 release
Previous diff: v0.3.14 → v0.3.15. Next: v0.3.17 → v0.3.18.
- build-unix.txt modified · +2 −1
- coding.txt added · +41 −0
- db.cpp modified · +80 −17
- db.h modified · +14 −4
- main.cpp modified · +315 −214
- main.h modified · +115 −14
- net.cpp modified · +23 −21
- rpc.cpp modified · +471 −92
- serialize.h modified · +1 −1
- setup.nsi modified · +3 −3
- sha256.cpp modified · +3 −3
- ui.cpp modified · +5 −2
- uibase.cpp modified · +21 −24
- uibase.h modified · +8 −7
- util.cpp modified · +13 −6
build-unix.txt (modified)
1--- v0.3.15/build-unix.txt2+++ v0.3.17/build-unix.txt3@@ -21,7 +21,8 @@4 5 If using Boost 1.37, append -mt to the boost libraries in the makefile.6 7-We're now using wxWidgets 2.9, which uses UTF-8. Don't try 2.8, it won't work.8+We're using wxWidgets 2.9.0, which uses UTF-8. Don't try 2.8, it won't work.9+The build hasn't been updated to work with wxWidgets 2.9.1 yet.10 11 You need to download wxWidgets from http://www.wxwidgets.org/downloads/12 and build it yourself. See the build instructions and configure parameters
coding.txt (added)
1--- /dev/null2+++ v0.3.17/coding.txt3@@ -1 +1,42 @@4+Please be consistent with the existing coding style.5 6+Block style:7+8+bool Function(char* psz, int n)9+{10+ // Comment summarising what this section of code does11+ for (int i = 0; i < n; i++)12+ {13+ // When something fails, return early14+ if (!Something())15+ return false;16+ ...17+ }18+19+ // Success return is usually at the end20+ return true;21+}22+23+- ANSI/Allman block style24+- 4 space indenting, no tabs25+- No extra spaces inside parenthesis; please don't do ( this )26+- No space after function names, one space after if, for and while27+28+Variable names begin with the type in lowercase, like nSomeVariable.29+Please don't put the first word of the variable name in lowercase like30+someVariable.31+32+Common types:33+n integer number: short, unsigned short, int, unsigned int,34+ int64, uint64, sometimes char if used as a number35+d double, float36+f flag37+hash uint25638+p pointer or array, one p for each level of indirection39+psz pointer to null terminated string40+str string object41+v vector or similar list objects42+map map or multimap43+set set or multiset44+bn CBigNum45+
db.cpp (modified)
1--- v0.3.15/db.cpp2+++ v0.3.17/db.cpp3@@ -8,7 +8,7 @@4 5 6 unsigned int nWalletDBUpdated;7-8+uint64 nAccountingEntryNumber = 0;9 10 11 12@@ -579,6 +579,66 @@13 static set<int64> setKeyPool;14 static CCriticalSection cs_setKeyPool;15 16+bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)17+{18+ account.SetNull();19+ return Read(make_pair(string("acc"), strAccount), account);20+}21+22+bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)23+{24+ return Write(make_pair(string("acc"), strAccount), account);25+}26+27+bool CWalletDB::WriteAccountingEntry(const string& strAccount, const CAccountingEntry& acentry)28+{29+ return Write(make_pair(string("acentry"), make_pair(strAccount, ++nAccountingEntryNumber)), acentry);30+}31+32+int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)33+{34+ int64 nCreditDebit = 0;35+36+ Dbc* pcursor = GetCursor();37+ if (!pcursor)38+ throw runtime_error("CWalletDB::GetAccountCreditDebit() : cannot create DB cursor");39+ unsigned int fFlags = DB_SET_RANGE;40+ loop41+ {42+ // Read next record43+ CDataStream ssKey;44+ if (fFlags == DB_SET_RANGE)45+ ssKey << make_pair(string("acentry"), make_pair(strAccount, uint64(0)));46+ CDataStream ssValue;47+ int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);48+ fFlags = DB_NEXT;49+ if (ret == DB_NOTFOUND)50+ break;51+ else if (ret != 0)52+ {53+ pcursor->close();54+ throw runtime_error("CWalletDB::GetAccountCreditDebit() : error scanning DB");55+ }56+57+ // Unserialize58+ string strType;59+ ssKey >> strType;60+ if (strType != "acentry")61+ break;62+ string strAccountName;63+ ssKey >> strAccountName;64+ if (strAccountName != strAccount)65+ break;66+67+ CAccountingEntry acentry;68+ ssValue >> acentry;69+ nCreditDebit += acentry.nCreditDebit;70+ }71+72+ pcursor->close();73+ return nCreditDebit;74+}75+76 bool CWalletDB::LoadWallet()77 {78 vchDefaultKey.clear();79@@ -639,6 +699,15 @@80 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),81 // wtx.hashBlock.ToString().substr(0,20).c_str(),82 // wtx.mapValue["message"].c_str());83+ }84+ else if (strType == "acentry")85+ {86+ string strAccount;87+ ssKey >> strAccount;88+ uint64 nNumber;89+ ssKey >> nNumber;90+ if (nNumber > nAccountingEntryNumber)91+ nAccountingEntryNumber = nNumber;92 }93 else if (strType == "key" || strType == "wkey")94 {95@@ -701,14 +770,6 @@96 printf("fUseProxy = %d\n", fUseProxy);97 printf("addrProxy = %s\n", addrProxy.ToString().c_str());98 99-100- // The transaction fee setting won't be needed for many years to come.101- // Setting it to zero here in case they set it to something in an earlier version.102- if (nTransactionFee != 0)103- {104- nTransactionFee = 0;105- WriteSetting("nTransactionFee", nTransactionFee);106- }107 108 // Upgrade109 if (nFileVersion < VERSION)110@@ -900,21 +961,23 @@111 printf("keypool return %"PRI64d"\n", nIndex);112 }113 114-vector<unsigned char> CWalletDB::GetKeyFromKeyPool()115-{116+vector<unsigned char> GetKeyFromKeyPool()117+{118+ CWalletDB walletdb;119 int64 nIndex = 0;120 CKeyPool keypool;121- ReserveKeyFromKeyPool(nIndex, keypool);122- KeepKey(nIndex);123+ walletdb.ReserveKeyFromKeyPool(nIndex, keypool);124+ walletdb.KeepKey(nIndex);125 return keypool.vchPubKey;126 }127 128-int64 CWalletDB::GetOldestKeyPoolTime()129-{130+int64 GetOldestKeyPoolTime()131+{132+ CWalletDB walletdb;133 int64 nIndex = 0;134 CKeyPool keypool;135- ReserveKeyFromKeyPool(nIndex, keypool);136- ReturnKey(nIndex);137+ walletdb.ReserveKeyFromKeyPool(nIndex, keypool);138+ walletdb.ReturnKey(nIndex);139 return keypool.nTime;140 }141
db.h (modified)
1--- v0.3.15/db.h2+++ v0.3.17/db.h3@@ -11,6 +11,8 @@4 class CReview;5 class CAddress;6 class CWalletTx;7+class CAccount;8+class CAccountingEntry;9 10 extern map<string, string> mapAddressBook;11 extern CCriticalSection cs_mapAddressBook;12@@ -24,6 +26,8 @@13 14 15 extern void DBFlush(bool fShutdown);16+extern vector<unsigned char> GetKeyFromKeyPool();17+extern int64 GetOldestKeyPoolTime();18 19 20 21@@ -341,7 +345,9 @@22 class CWalletDB : public CDB23 {24 public:25- CWalletDB(const char* pszMode="r+") : CDB("wallet.dat", pszMode) { }26+ CWalletDB(const char* pszMode="r+") : CDB("wallet.dat", pszMode)27+ {28+ }29 private:30 CWalletDB(const CWalletDB&);31 void operator=(const CWalletDB&);32@@ -424,6 +430,11 @@33 nWalletDBUpdated++;34 return Write(make_pair(string("setting"), strKey), value);35 }36+37+ bool ReadAccount(const string& strAccount, CAccount& account);38+ bool WriteAccount(const string& strAccount, const CAccount& account);39+ bool WriteAccountingEntry(const string& strAccount, const CAccountingEntry& acentry);40+ int64 GetAccountCreditDebit(const string& strAccount);41 42 bool LoadWallet();43 protected:44@@ -431,9 +442,8 @@45 void KeepKey(int64 nIndex);46 static void ReturnKey(int64 nIndex);47 friend class CReserveKey;48-public:49- vector<unsigned char> GetKeyFromKeyPool();50- int64 GetOldestKeyPoolTime();51+ friend vector<unsigned char> GetKeyFromKeyPool();52+ friend int64 GetOldestKeyPoolTime();53 };54 55 bool LoadWallet(bool& fFirstRunRet);
main.cpp (modified)
1--- v0.3.15/main.cpp2+++ v0.3.17/main.cpp3@@ -159,7 +159,7 @@4 if (txout.scriptPubKey == scriptDefaultKey)5 {6 CWalletDB walletdb;7- vchDefaultKey = walletdb.GetKeyFromKeyPool();8+ vchDefaultKey = GetKeyFromKeyPool();9 walletdb.WriteDefaultKey(vchDefaultKey);10 walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");11 }12@@ -598,6 +598,8 @@13 if (i != 0)14 return false;15 ptxOld = mapNextTx[outpoint].ptx;16+ if (ptxOld->IsFinal())17+ return false;18 if (!IsNewerThan(*ptxOld))19 return false;20 for (int i = 0; i < vin.size(); i++)21@@ -1555,31 +1557,25 @@22 23 // Preliminary checks24 if (!pblock->CheckBlock())25- {26- delete pblock;27 return error("ProcessBlock() : CheckBlock FAILED");28- }29 30 // If don't already have its previous block, shunt it off to holding area until we get it31 if (!mapBlockIndex.count(pblock->hashPrevBlock))32 {33 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());34- mapOrphanBlocks.insert(make_pair(hash, pblock));35- mapOrphanBlocksByPrev.insert(make_pair(pblock->hashPrevBlock, pblock));36+ CBlock* pblock2 = new CBlock(*pblock);37+ mapOrphanBlocks.insert(make_pair(hash, pblock2));38+ mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));39 40 // Ask this guy to fill in what we're missing41 if (pfrom)42- pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock));43+ pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));44 return true;45 }46 47 // Store to disk48 if (!pblock->AcceptBlock())49- {50- delete pblock;51 return error("ProcessBlock() : AcceptBlock FAILED");52- }53- delete pblock;54 55 // Recursively process any orphan blocks that depended on this one56 vector<uint256> vWorkQueue;57@@ -2502,7 +2498,7 @@58 CInv inv(MSG_BLOCK, pblock->GetHash());59 pfrom->AddInventoryKnown(inv);60 61- if (ProcessBlock(pfrom, pblock.release()))62+ if (ProcessBlock(pfrom, pblock.get()))63 mapAlreadyAskedFor.erase(inv);64 }65 66@@ -2547,7 +2543,7 @@67 68 // Keep giving the same key to the same ip until they use it69 if (!mapReuseKey.count(pfrom->addr.ip))70- mapReuseKey[pfrom->addr.ip] = CWalletDB().GetKeyFromKeyPool();71+ mapReuseKey[pfrom->addr.ip] = GetKeyFromKeyPool();72 73 // Send back approval of order and pubkey to use74 CScript scriptPubKey;75@@ -2998,19 +2994,19 @@76 // ScanHash scans nonces looking for a hash with at least some zero bits.77 // It operates on big endian data. Caller does the byte reversing.78 // All input buffers are 16-byte aligned. nNonce is usually preserved79-// between calls, but periodically or if nNonce is above 0xff000000,80+// between calls, but periodically or if nNonce is 0xffff0000 or above,81 // the block is rebuilt and nNonce starts over at zero.82 //83-unsigned int ScanHash_CryptoPP(char* pmidstate, char* pblock, char* phash1, char* phash, unsigned int& nHashesDone)84-{85- unsigned int& nNonce = *(unsigned int*)(pblock + 12);86+unsigned int ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)87+{88+ unsigned int& nNonce = *(unsigned int*)(pdata + 12);89 for (;;)90 {91 // Crypto++ SHA-25692- // Hash pblock using pmidstate as the starting state into93+ // Hash pdata using pmidstate as the starting state into94 // preformatted buffer phash1, then hash phash1 into phash95 nNonce++;96- SHA256Transform(phash1, pblock, pmidstate);97+ SHA256Transform(phash1, pdata, pmidstate);98 SHA256Transform(phash, phash1, pSHA256InitState);99 100 // Return the nonce if the hash has at least some zero bits,101@@ -3030,6 +3026,284 @@102 extern unsigned int ScanHash_4WaySSE2(char* pmidstate, char* pblock, char* phash1, char* phash, unsigned int& nHashesDone);103 104 105+106+class COrphan107+{108+public:109+ CTransaction* ptx;110+ set<uint256> setDependsOn;111+ double dPriority;112+113+ COrphan(CTransaction* ptxIn)114+ {115+ ptx = ptxIn;116+ dPriority = 0;117+ }118+119+ void print() const120+ {121+ printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);122+ foreach(uint256 hash, setDependsOn)123+ printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());124+ }125+};126+127+128+CBlock* CreateNewBlock(CReserveKey& reservekey)129+{130+ CBlockIndex* pindexPrev = pindexBest;131+132+ // Create new block133+ auto_ptr<CBlock> pblock(new CBlock());134+ if (!pblock.get())135+ return NULL;136+137+ // Create coinbase tx138+ CTransaction txNew;139+ txNew.vin.resize(1);140+ txNew.vin[0].prevout.SetNull();141+ txNew.vout.resize(1);142+ txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;143+144+ // Add our coinbase tx as first transaction145+ pblock->vtx.push_back(txNew);146+147+ // Collect memory pool transactions into the block148+ int64 nFees = 0;149+ CRITICAL_BLOCK(cs_main)150+ CRITICAL_BLOCK(cs_mapTransactions)151+ {152+ CTxDB txdb("r");153+154+ // Priority order to process transactions155+ list<COrphan> vOrphan; // list memory doesn't move156+ map<uint256, vector<COrphan*> > mapDependers;157+ multimap<double, CTransaction*> mapPriority;158+ for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)159+ {160+ CTransaction& tx = (*mi).second;161+ if (tx.IsCoinBase() || !tx.IsFinal())162+ continue;163+164+ COrphan* porphan = NULL;165+ double dPriority = 0;166+ foreach(const CTxIn& txin, tx.vin)167+ {168+ // Read prev transaction169+ CTransaction txPrev;170+ CTxIndex txindex;171+ if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))172+ {173+ // Has to wait for dependencies174+ if (!porphan)175+ {176+ // Use list for automatic deletion177+ vOrphan.push_back(COrphan(&tx));178+ porphan = &vOrphan.back();179+ }180+ mapDependers[txin.prevout.hash].push_back(porphan);181+ porphan->setDependsOn.insert(txin.prevout.hash);182+ continue;183+ }184+ int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;185+186+ // Read block header187+ int nConf = 0;188+ CBlock block;189+ if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))190+ {191+ map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(block.GetHash());192+ if (it != mapBlockIndex.end())193+ {194+ CBlockIndex* pindex = (*it).second;195+ if (pindex->IsInMainChain())196+ nConf = 1 + nBestHeight - pindex->nHeight;197+ }198+ }199+200+ dPriority += (double)nValueIn * nConf;201+202+ if (fDebug && mapArgs.count("-printpriority"))203+ printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);204+ }205+206+ // Priority is sum(valuein * age) / txsize207+ dPriority /= ::GetSerializeSize(tx, SER_NETWORK);208+209+ if (porphan)210+ porphan->dPriority = dPriority;211+ else212+ mapPriority.insert(make_pair(-dPriority, &(*mi).second));213+214+ if (fDebug && mapArgs.count("-printpriority"))215+ {216+ printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());217+ if (porphan)218+ porphan->print();219+ printf("\n");220+ }221+ }222+223+ // Collect transactions into block224+ map<uint256, CTxIndex> mapTestPool;225+ uint64 nBlockSize = 1000;226+ int nBlockSigOps = 100;227+ while (!mapPriority.empty())228+ {229+ // Take highest priority transaction off priority queue230+ double dPriority = -(*mapPriority.begin()).first;231+ CTransaction& tx = *(*mapPriority.begin()).second;232+ mapPriority.erase(mapPriority.begin());233+234+ // Size limits235+ unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);236+ if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)237+ continue;238+ int nTxSigOps = tx.GetSigOpCount();239+ if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)240+ continue;241+242+ // Transaction fee required depends on block size243+ bool fAllowFree = (nBlockSize + nTxSize < 4000 || dPriority > COIN * 144 / 250);244+ int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);245+246+ // Connecting shouldn't fail due to dependency on other memory pool transactions247+ // because we're already processing them in order of dependency248+ map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);249+ if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))250+ continue;251+ swap(mapTestPool, mapTestPoolTmp);252+253+ // Added254+ pblock->vtx.push_back(tx);255+ nBlockSize += nTxSize;256+ nBlockSigOps += nTxSigOps;257+258+ // Add transactions that depend on this one to the priority queue259+ uint256 hash = tx.GetHash();260+ if (mapDependers.count(hash))261+ {262+ foreach(COrphan* porphan, mapDependers[hash])263+ {264+ if (!porphan->setDependsOn.empty())265+ {266+ porphan->setDependsOn.erase(hash);267+ if (porphan->setDependsOn.empty())268+ mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));269+ }270+ }271+ }272+ }273+ }274+ pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);275+276+ // Fill in header277+ pblock->hashPrevBlock = pindexPrev->GetBlockHash();278+ pblock->hashMerkleRoot = pblock->BuildMerkleTree();279+ pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());280+ pblock->nBits = GetNextWorkRequired(pindexPrev);281+ pblock->nNonce = 0;282+283+ return pblock.release();284+}285+286+287+void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime)288+{289+ // Update nExtraNonce290+ int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());291+ if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)292+ {293+ nExtraNonce = 1;294+ nPrevTime = nNow;295+ }296+ pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);297+ pblock->hashMerkleRoot = pblock->BuildMerkleTree();298+}299+300+301+void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)302+{303+ //304+ // Prebuild hash buffers305+ //306+ struct307+ {308+ struct unnamed2309+ {310+ int nVersion;311+ uint256 hashPrevBlock;312+ uint256 hashMerkleRoot;313+ unsigned int nTime;314+ unsigned int nBits;315+ unsigned int nNonce;316+ }317+ block;318+ unsigned char pchPadding0[64];319+ uint256 hash1;320+ unsigned char pchPadding1[64];321+ }322+ tmp;323+ memset(&tmp, 0, sizeof(tmp));324+325+ tmp.block.nVersion = pblock->nVersion;326+ tmp.block.hashPrevBlock = pblock->hashPrevBlock;327+ tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;328+ tmp.block.nTime = pblock->nTime;329+ tmp.block.nBits = pblock->nBits;330+ tmp.block.nNonce = pblock->nNonce;331+332+ FormatHashBlocks(&tmp.block, sizeof(tmp.block));333+ FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));334+335+ // Byte swap all the input buffer336+ for (int i = 0; i < sizeof(tmp)/4; i++)337+ ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);338+339+ // Precalc the first half of the first hash, which stays constant340+ SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);341+342+ memcpy(pdata, &tmp.block, 128);343+ memcpy(phash1, &tmp.hash1, 64);344+}345+346+347+bool CheckWork(CBlock* pblock, CReserveKey& reservekey)348+{349+ uint256 hash = pblock->GetHash();350+ uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();351+352+ if (hash > hashTarget)353+ return false;354+355+ //// debug print356+ printf("BitcoinMiner:\n");357+ printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());358+ pblock->print();359+ printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());360+ printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());361+362+ // Found a solution363+ CRITICAL_BLOCK(cs_main)364+ {365+ if (pblock->hashPrevBlock != hashBestChain)366+ return error("BitcoinMiner : generated block is stale");367+368+ // Remove key from key pool369+ reservekey.KeepKey();370+371+ // Track how many getdata requests this block gets372+ CRITICAL_BLOCK(cs_mapRequestCount)373+ mapRequestCount[pblock->GetHash()] = 0;374+375+ // Process this block the same as if we had received it from another node376+ if (!ProcessBlock(NULL, pblock))377+ return error("BitcoinMiner : ProcessBlock, block not accepted");378+ }379+380+ Sleep(2000);381+ return true;382+}383 384 385 void BitcoinMiner()386@@ -3040,9 +3314,11 @@387 if (mapArgs.count("-4way"))388 f4WaySSE2 = (mapArgs["-4way"] != "0");389 390+ // Each thread has its own key and counter391 CReserveKey reservekey;392 unsigned int nExtraNonce = 0;393 int64 nPrevTime = 0;394+395 while (fGenerateBitcoins)396 {397 if (AffinityBugWorkaround(ThreadBitcoinMiner))398@@ -3058,183 +3334,32 @@399 return;400 }401 402- unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;403- CBlockIndex* pindexPrev = pindexBest;404- unsigned int nBits = GetNextWorkRequired(pindexPrev);405-406-407- //408- // Create coinbase tx409- //410- CTransaction txNew;411- txNew.vin.resize(1);412- txNew.vin[0].prevout.SetNull();413- int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());414- if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)415- {416- nExtraNonce = 1;417- nPrevTime = nNow;418- }419- txNew.vin[0].scriptSig << nBits << CBigNum(nExtraNonce);420- txNew.vout.resize(1);421- txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;422-423 424 //425 // Create new block426 //427- auto_ptr<CBlock> pblock(new CBlock());428+ unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;429+ CBlockIndex* pindexPrev = pindexBest;430+431+ auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));432 if (!pblock.get())433 return;434-435- // Add our coinbase tx as first transaction436- pblock->vtx.push_back(txNew);437-438- // Collect memory pool transactions into the block439- int64 nFees = 0;440- CRITICAL_BLOCK(cs_main)441- CRITICAL_BLOCK(cs_mapTransactions)442- {443- CTxDB txdb("r");444-445- // Priority order to process transactions446- multimap<double, CTransaction*> mapPriority;447- for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)448- {449- CTransaction& tx = (*mi).second;450- if (tx.IsCoinBase() || !tx.IsFinal())451- continue;452-453- double dPriority = 0;454- foreach(const CTxIn& txin, tx.vin)455- {456- // Read prev transaction457- CTransaction txPrev;458- CTxIndex txindex;459- if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))460- continue;461- int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;462-463- // Read block header464- int nConf = 0;465- CBlock block;466- if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))467- {468- map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(block.GetHash());469- if (it != mapBlockIndex.end())470- {471- CBlockIndex* pindex = (*it).second;472- if (pindex->IsInMainChain())473- nConf = 1 + nBestHeight - pindex->nHeight;474- }475- }476-477- dPriority += (double)nValueIn * nConf;478-479- if (fDebug && mapArgs.count("-printpriority"))480- printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);481- }482-483- // Priority is sum(valuein * age) / txsize484- dPriority /= ::GetSerializeSize(tx, SER_NETWORK);485-486- mapPriority.insert(make_pair(-dPriority, &(*mi).second));487-488- if (fDebug && mapArgs.count("-printpriority"))489- printf("priority %-20.1f %s\n%s\n", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());490- }491-492- // Collect transactions into block493- map<uint256, CTxIndex> mapTestPool;494- uint64 nBlockSize = 1000;495- int nBlockSigOps = 100;496- bool fFoundSomething = true;497- while (fFoundSomething)498- {499- fFoundSomething = false;500- for (multimap<double, CTransaction*>::iterator mi = mapPriority.begin(); mi != mapPriority.end();)501- {502- CTransaction& tx = *(*mi).second;503- unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);504- if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)505- {506- mapPriority.erase(mi++);507- continue;508- }509- int nTxSigOps = tx.GetSigOpCount();510- if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)511- {512- mapPriority.erase(mi++);513- continue;514- }515-516- // Transaction fee based on block size517- int64 nMinFee = tx.GetMinFee(nBlockSize);518-519- // Connecting can fail due to dependency on other memory pool transactions520- // that aren't in the block yet, so keep trying in later passes521- map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);522- if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))523- {524- mi++;525- continue;526- }527- swap(mapTestPool, mapTestPoolTmp);528-529- // Added530- pblock->vtx.push_back(tx);531- nBlockSize += nTxSize;532- nBlockSigOps += nTxSigOps;533- fFoundSomething = true;534- mapPriority.erase(mi++);535- }536- }537- }538- pblock->nBits = nBits;539- pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);540+ IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce, nPrevTime);541+542 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());543 544 545 //546- // Prebuild hash buffer547+ // Prebuild hash buffers548 //549- struct tmpworkspace550- {551- struct unnamed2552- {553- int nVersion;554- uint256 hashPrevBlock;555- uint256 hashMerkleRoot;556- unsigned int nTime;557- unsigned int nBits;558- unsigned int nNonce;559- }560- block;561- unsigned char pchPadding0[64];562- uint256 hash1;563- unsigned char pchPadding1[64];564- };565- char tmpbuf[sizeof(tmpworkspace)+16];566- tmpworkspace& tmp = *(tmpworkspace*)alignup<16>(tmpbuf);567-568- tmp.block.nVersion = pblock->nVersion;569- tmp.block.hashPrevBlock = pblock->hashPrevBlock = pindexPrev->GetBlockHash();570- tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();571- tmp.block.nTime = pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());572- tmp.block.nBits = pblock->nBits = nBits;573- tmp.block.nNonce = pblock->nNonce = 0;574-575- unsigned int nBlocks0 = FormatHashBlocks(&tmp.block, sizeof(tmp.block));576- unsigned int nBlocks1 = FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));577-578- // Byte swap all the input buffer579- for (int i = 0; i < sizeof(tmp)/4; i++)580- ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);581-582- // Precalc the first half of the first hash, which stays constant583- uint256 midstatebuf[2];584- uint256& midstate = *alignup<16>(midstatebuf);585- SHA256Transform(&midstate, &tmp.block, pSHA256InitState);586+ char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);587+ char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);588+ char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);589+590+ FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);591+592+ unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);593+ unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);594 595 596 //597@@ -3252,11 +3377,11 @@598 #ifdef FOURWAYSSE2599 if (f4WaySSE2)600 // tcatm's 4-way 128-bit SSE2 SHA-256601- nNonceFound = ScanHash_4WaySSE2((char*)&midstate, (char*)&tmp.block + 64, (char*)&tmp.hash1, (char*)&hash, nHashesDone);602+ nNonceFound = ScanHash_4WaySSE2(pmidstate, pdata + 64, phash1, (char*)&hash, nHashesDone);603 else604 #endif605 // Crypto++ SHA-256606- nNonceFound = ScanHash_CryptoPP((char*)&midstate, (char*)&tmp.block + 64, (char*)&tmp.hash1, (char*)&hash, nHashesDone);607+ nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1, (char*)&hash, nHashesDone);608 609 // Check if something found610 if (nNonceFound != -1)611@@ -3270,33 +3395,9 @@612 pblock->nNonce = ByteReverse(nNonceFound);613 assert(hash == pblock->GetHash());614 615- //// debug print616- printf("BitcoinMiner:\n");617- printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());618- pblock->print();619- printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());620- printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());621-622 SetThreadPriority(THREAD_PRIORITY_NORMAL);623- CRITICAL_BLOCK(cs_main)624- {625- if (pindexPrev == pindexBest)626- {627- // Remove key from key pool628- reservekey.KeepKey();629-630- // Track how many getdata requests this block gets631- CRITICAL_BLOCK(cs_mapRequestCount)632- mapRequestCount[pblock->GetHash()] = 0;633-634- // Process this block the same as if we had received it from another node635- if (!ProcessBlock(NULL, pblock.release()))636- printf("ERROR in BitcoinMiner, ProcessBlock, block not accepted\n");637- }638- }639+ CheckWork(pblock.get(), reservekey);640 SetThreadPriority(THREAD_PRIORITY_LOWEST);641-642- Sleep(500);643 break;644 }645 }646@@ -3342,7 +3443,7 @@647 return;648 if (vNodes.empty())649 break;650- if (tmp.block.nNonce >= 0xff000000)651+ if (nBlockNonce >= 0xffff0000)652 break;653 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)654 break;655@@ -3351,7 +3452,7 @@656 657 // Update nTime every few seconds658 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());659- tmp.block.nTime = ByteReverse(pblock->nTime);660+ nBlockTime = ByteReverse(pblock->nTime);661 }662 }663 }
main.h (modified)
1--- v0.3.15/main.h2+++ v0.3.17/main.h3@@ -83,6 +83,10 @@4 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);5 void GenerateBitcoins(bool fGenerate);6 void ThreadBitcoinMiner(void* parg);7+CBlock* CreateNewBlock(CReserveKey& reservekey);8+void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime);9+void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);10+bool CheckWork(CBlock* pblock, CReserveKey& reservekey);11 void BitcoinMiner();12 bool CheckProofOfWork(uint256 hash, unsigned int nBits);13 bool IsInitialBlockDownload();14@@ -528,21 +532,29 @@15 return nValueOut;16 }17 18- int64 GetMinFee(unsigned int nBlockSize=1) const19+ int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true) const20 {21 // Base fee is 1 cent per kilobyte22 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);23 unsigned int nNewBlockSize = nBlockSize + nBytes;24 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;25 26- // Transactions under 25K are free as long as block size is under 40K27- // (about 11,000bc if made of 50bc inputs)28- if (nBytes < 25000 && nNewBlockSize < 40000)29- nMinFee = 0;30-31- // Transactions under 3K are free as long as block size is under 50K32- if (nBytes < 3000 && nNewBlockSize < 50000)33- nMinFee = 0;34+ if (fAllowFree)35+ {36+ if (nBlockSize == 1)37+ {38+ // Transactions under 10K are free39+ // (about 4500bc if made of 50bc inputs)40+ if (nBytes < 10000)41+ nMinFee = 0;42+ }43+ else44+ {45+ // Free transaction area46+ if (nNewBlockSize < 27000)47+ nMinFee = 0;48+ }49+ }50 51 // To limit dust spam, require a 0.01 fee if any output is less than 0.0152 if (nMinFee < CENT)53@@ -709,11 +721,12 @@54 vector<CMerkleTx> vtxPrev;55 map<string, string> mapValue;56 vector<pair<string, string> > vOrderForm;57- unsigned int fTimeReceivedIsTxTime;58 unsigned int nTimeReceived; // time received by this node59 char fFromMe;60 char fSpent;61- //// probably need to sign the order info so know it came from payer62+ char fTimeReceivedIsTxTime;63+ char fUnused;64+ string strFromAccount;65 66 // memory only67 mutable char fDebitCached;68@@ -744,29 +757,44 @@69 70 void Init()71 {72- fTimeReceivedIsTxTime = false;73+ vtxPrev.clear();74+ mapValue.clear();75+ vOrderForm.clear();76 nTimeReceived = 0;77 fFromMe = false;78 fSpent = false;79+ fTimeReceivedIsTxTime = false;80+ fUnused = false;81+ strFromAccount.clear();82 fDebitCached = false;83 fCreditCached = false;84 nDebitCached = 0;85 nCreditCached = 0;86 nTimeDisplayed = 0;87 nLinesDisplayed = 0;88+ fConfirmedDisplayed = false;89 }90 91 IMPLEMENT_SERIALIZE92 (93+ if (fRead)94+ const_cast<CWalletTx*>(this)->Init();95 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);96- nVersion = this->nVersion;97 READWRITE(vtxPrev);98 READWRITE(mapValue);99 READWRITE(vOrderForm);100- READWRITE(fTimeReceivedIsTxTime);101+ READWRITE(nVersion);102+ if (fRead && nVersion < 100)103+ const_cast<CWalletTx*>(this)->fTimeReceivedIsTxTime = nVersion;104 READWRITE(nTimeReceived);105 READWRITE(fFromMe);106 READWRITE(fSpent);107+ if (nVersion >= 31404)108+ {109+ READWRITE(fTimeReceivedIsTxTime);110+ READWRITE(fUnused);111+ READWRITE(strFromAccount);112+ }113 )114 115 int64 GetDebit() const116@@ -1522,6 +1550,79 @@117 READWRITE(strComment);118 )119 };120+121+122+123+124+125+126+//127+// Account information.128+// Stored in wallet with key "acc"+string account name129+//130+class CAccount131+{132+public:133+ vector<unsigned char> vchPubKey;134+135+ CAccount()136+ {137+ SetNull();138+ }139+140+ void SetNull()141+ {142+ vchPubKey.clear();143+ }144+145+ IMPLEMENT_SERIALIZE146+ (147+ if (!(nType & SER_GETHASH))148+ READWRITE(nVersion);149+ READWRITE(vchPubKey);150+ )151+};152+153+154+155+//156+// Internal transfers.157+// Database key is acentry<account><counter>158+//159+class CAccountingEntry160+{161+public:162+ int64 nCreditDebit;163+ int64 nTime;164+ string strOtherAccount;165+ string strComment;166+167+ CAccountingEntry()168+ {169+ SetNull();170+ }171+172+ void SetNull()173+ {174+ nCreditDebit = 0;175+ nTime = 0;176+ strOtherAccount.clear();177+ strComment.clear();178+ }179+180+ IMPLEMENT_SERIALIZE181+ (182+ if (!(nType & SER_GETHASH))183+ READWRITE(nVersion);184+ READWRITE(nCreditDebit);185+ READWRITE(nTime);186+ READWRITE(strOtherAccount);187+ READWRITE(strComment);188+ )189+};190+191+192+193 194 195
net.cpp (modified)
1--- v0.3.15/net.cpp2+++ v0.3.17/net.cpp3@@ -128,7 +128,7 @@4 string strLine;5 while (RecvLine(hSocket, strLine))6 {7- if (strLine.empty())8+ if (strLine.empty()) // HTTP response is separated from headers by blank line9 {10 loop11 {12@@ -137,6 +137,8 @@13 closesocket(hSocket);14 return false;15 }16+ if (pszKeyword == NULL)17+ break;18 if (strLine.find(pszKeyword) != -1)19 {20 strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));21@@ -176,26 +178,7 @@22 {23 if (nHost == 1)24 {25- addrConnect = CAddress("70.86.96.218:80"); // www.ipaddressworld.com26-27- if (nLookup == 1)28- {29- struct hostent* phostent = gethostbyname("www.ipaddressworld.com");30- if (phostent && phostent->h_addr_list && phostent->h_addr_list[0])31- addrConnect = CAddress(*(u_long*)phostent->h_addr_list[0], htons(80));32- }33-34- pszGet = "GET /ip.php HTTP/1.1\r\n"35- "Host: www.ipaddressworld.com\r\n"36- "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"37- "Connection: close\r\n"38- "\r\n";39-40- pszKeyword = "IP:";41- }42- else if (nHost == 2)43- {44- addrConnect = CAddress("208.78.68.70:80"); // checkip.dyndns.org45+ addrConnect = CAddress("91.198.22.70:80"); // checkip.dyndns.org46 47 if (nLookup == 1)48 {49@@ -211,6 +194,25 @@50 "\r\n";51 52 pszKeyword = "Address:";53+ }54+ else if (nHost == 2)55+ {56+ addrConnect = CAddress("74.208.43.192:80"); // www.showmyip.com57+58+ if (nLookup == 1)59+ {60+ struct hostent* phostent = gethostbyname("www.showmyip.com");61+ if (phostent && phostent->h_addr_list && phostent->h_addr_list[0])62+ addrConnect = CAddress(*(u_long*)phostent->h_addr_list[0], htons(80));63+ }64+65+ pszGet = "GET /simple/ HTTP/1.1\r\n"66+ "Host: www.showmyip.com\r\n"67+ "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"68+ "Connection: close\r\n"69+ "\r\n";70+71+ pszKeyword = NULL; // Returns just IP address72 }73 74 if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
rpc.cpp (modified)
1--- v0.3.15/rpc.cpp2+++ v0.3.17/rpc.cpp3@@ -3,6 +3,7 @@4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.5 6 #include "headers.h"7+#include "cryptopp/sha.h"8 #undef printf9 #include <boost/asio.hpp>10 #include <boost/iostreams/concepts.hpp>11@@ -50,6 +51,7 @@12 ret = limit - 1;13 buffer[limit-1] = 0;14 }15+ printf("%s", buffer);16 #if defined(__WXMSW__) && defined(GUI)17 MyMessageBox(buffer, "Bitcoin", wxOK | wxICON_EXCLAMATION);18 #else19@@ -58,6 +60,17 @@20 }21 22 23+int64 AmountFromValue(const Value& value)24+{25+ double dAmount = value.get_real();26+ if (dAmount <= 0.0 || dAmount > 21000000.0)27+ throw JSONRPCError(-3, "Invalid amount");28+ int64 nAmount = roundint64(dAmount * 100.00) * CENT;29+ if (!MoneyRange(nAmount))30+ throw JSONRPCError(-3, "Invalid amount");31+ return nAmount;32+}33+34 35 36 37@@ -86,7 +99,8 @@38 string strMethod = (*mi).first;39 // We already filter duplicates, but these deprecated screw up the sort order40 if (strMethod == "getamountreceived" ||41- strMethod == "getallreceived")42+ strMethod == "getallreceived" ||43+ (strMethod.find("label") != string::npos))44 continue;45 if (strCommand != "" && strMethod != strCommand)46 continue;47@@ -180,17 +194,6 @@48 "Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");49 50 return GetDifficulty();51-}52-53-54-Value getbalance(const Array& params, bool fHelp)55-{56- if (fHelp || params.size() != 0)57- throw runtime_error(58- "getbalance\n"59- "Returns the server's available balance.");60-61- return ((double)GetBalance() / (double)COIN);62 }63 64 65@@ -262,7 +265,7 @@66 obj.push_back(Pair("difficulty", (double)GetDifficulty()));67 obj.push_back(Pair("hashespersec", gethashespersec(params, false)));68 obj.push_back(Pair("testnet", fTestNet));69- obj.push_back(Pair("keypoololdest", (boost::int64_t)CWalletDB().GetOldestKeyPoolTime()));70+ obj.push_back(Pair("keypoololdest", (boost::int64_t)GetOldestKeyPoolTime()));71 obj.push_back(Pair("paytxfee", (double)nTransactionFee / (double)COIN));72 obj.push_back(Pair("errors", GetWarnings("statusbar")));73 return obj;74@@ -273,71 +276,120 @@75 {76 if (fHelp || params.size() > 1)77 throw runtime_error(78- "getnewaddress [label]\n"79+ "getnewaddress [account]\n"80 "Returns a new bitcoin address for receiving payments. "81- "If [label] is specified (recommended), it is added to the address book "82- "so payments received with the address will be labeled.");83-84- // Parse the label first so we don't generate a key if there's an error85- string strLabel;86+ "If [account] is specified (recommended), it is added to the address book "87+ "so payments received with the address will be credited to [account].");88+89+ // Parse the account first so we don't generate a key if there's an error90+ string strAccount;91 if (params.size() > 0)92- strLabel = params[0].get_str();93+ strAccount = params[0].get_str();94 95 // Generate a new key that is added to wallet96- string strAddress = PubKeyToAddress(CWalletDB().GetKeyFromKeyPool());97-98- SetAddressBookName(strAddress, strLabel);99+ string strAddress = PubKeyToAddress(GetKeyFromKeyPool());100+101+ SetAddressBookName(strAddress, strAccount);102 return strAddress;103 }104 105 106-Value setlabel(const Array& params, bool fHelp)107+Value getaccountaddress(const Array& params, bool fHelp)108+{109+ if (fHelp || params.size() != 1)110+ throw runtime_error(111+ "getaccountaddress <account>\n"112+ "Returns the current bitcoin address for receiving payments to this account.");113+114+ // Parse the account first so we don't generate a key if there's an error115+ string strAccount = params[0].get_str();116+117+ CRITICAL_BLOCK(cs_mapWallet)118+ {119+ CWalletDB walletdb;120+ walletdb.TxnBegin();121+122+ CAccount account;123+ walletdb.ReadAccount(strAccount, account);124+125+ // Check if the current key has been used126+ if (!account.vchPubKey.empty())127+ {128+ CScript scriptPubKey;129+ scriptPubKey.SetBitcoinAddress(account.vchPubKey);130+ for (map<uint256, CWalletTx>::iterator it = mapWallet.begin();131+ it != mapWallet.end() && !account.vchPubKey.empty();132+ ++it)133+ {134+ const CWalletTx& wtx = (*it).second;135+ foreach(const CTxOut& txout, wtx.vout)136+ if (txout.scriptPubKey == scriptPubKey)137+ account.vchPubKey.clear();138+ }139+ }140+141+ // Generate a new key142+ if (account.vchPubKey.empty())143+ {144+ account.vchPubKey = GetKeyFromKeyPool();145+ string strAddress = PubKeyToAddress(account.vchPubKey);146+ SetAddressBookName(strAddress, strAccount);147+ walletdb.WriteAccount(strAccount, account);148+ }149+150+ walletdb.TxnCommit();151+ return PubKeyToAddress(account.vchPubKey);152+ }153+}154+155+156+Value setaccount(const Array& params, bool fHelp)157 {158 if (fHelp || params.size() < 1 || params.size() > 2)159 throw runtime_error(160- "setlabel <bitcoinaddress> <label>\n"161- "Sets the label associated with the given address.");162+ "setaccount <bitcoinaddress> <account>\n"163+ "Sets the account associated with the given address.");164 165 string strAddress = params[0].get_str();166- string strLabel;167+ string strAccount;168 if (params.size() > 1)169- strLabel = params[1].get_str();170-171- SetAddressBookName(strAddress, strLabel);172+ strAccount = params[1].get_str();173+174+ SetAddressBookName(strAddress, strAccount);175 return Value::null;176 }177 178 179-Value getlabel(const Array& params, bool fHelp)180+Value getaccount(const Array& params, bool fHelp)181 {182 if (fHelp || params.size() != 1)183 throw runtime_error(184- "getlabel <bitcoinaddress>\n"185- "Returns the label associated with the given address.");186+ "getaccount <bitcoinaddress>\n"187+ "Returns the account associated with the given address.");188 189 string strAddress = params[0].get_str();190 191- string strLabel;192+ string strAccount;193 CRITICAL_BLOCK(cs_mapAddressBook)194 {195 map<string, string>::iterator mi = mapAddressBook.find(strAddress);196 if (mi != mapAddressBook.end() && !(*mi).second.empty())197- strLabel = (*mi).second;198- }199- return strLabel;200-}201-202-203-Value getaddressesbylabel(const Array& params, bool fHelp)204+ strAccount = (*mi).second;205+ }206+ return strAccount;207+}208+209+210+Value getaddressesbyaccount(const Array& params, bool fHelp)211 {212 if (fHelp || params.size() != 1)213 throw runtime_error(214- "getaddressesbylabel <label>\n"215- "Returns the list of addresses with the given label.");216-217- string strLabel = params[0].get_str();218-219- // Find all addresses that have the given label220+ "getaddressesbyaccount <account>\n"221+ "Returns the list of addresses for the given account.");222+223+ string strAccount = params[0].get_str();224+225+ // Find all addresses that have the given account226 Array ret;227 CRITICAL_BLOCK(cs_mapAddressBook)228 {229@@ -345,7 +397,7 @@230 {231 const string& strAddress = item.first;232 const string& strName = item.second;233- if (strName == strLabel)234+ if (strName == strAccount)235 {236 // We're only adding valid bitcoin addresses and not ip addresses237 CScript scriptPubKey;238@@ -357,7 +409,6 @@239 return ret;240 }241 242-243 Value sendtoaddress(const Array& params, bool fHelp)244 {245 if (fHelp || params.size() < 2 || params.size() > 4)246@@ -368,9 +419,7 @@247 string strAddress = params[0].get_str();248 249 // Amount250- if (params[1].get_real() <= 0.0 || params[1].get_real() > 21000000.0)251- throw JSONRPCError(-3, "Invalid amount");252- int64 nAmount = roundint64(params[1].get_real() * 100.00) * CENT;253+ int64 nAmount = AmountFromValue(params[1]);254 255 // Wallet comments256 CWalletTx wtx;257@@ -382,7 +431,7 @@258 string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);259 if (strError != "")260 throw JSONRPCError(-4, strError);261- return "sent";262+ return wtx.GetHash().GetHex();263 }264 265 266@@ -448,15 +497,20 @@267 }268 269 270-Value getreceivedbylabel(const Array& params, bool fHelp)271+Value getreceivedbyaccount(const Array& params, bool fHelp)272 {273 if (fHelp || params.size() < 1 || params.size() > 2)274 throw runtime_error(275- "getreceivedbylabel <label> [minconf=1]\n"276- "Returns the total amount received by addresses with <label> in transactions with at least [minconf] confirmations.");277+ "getreceivedbyaccount <account> [minconf=1]\n"278+ "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");279+280+ // Minimum confirmations281+ int nMinDepth = 1;282+ if (params.size() > 1)283+ nMinDepth = params[1].get_int();284 285 // Get the set of pub keys that have the label286- string strLabel = params[0].get_str();287+ string strAccount = params[0].get_str();288 set<CScript> setPubKey;289 CRITICAL_BLOCK(cs_mapAddressBook)290 {291@@ -464,7 +518,7 @@292 {293 const string& strAddress = item.first;294 const string& strName = item.second;295- if (strName == strLabel)296+ if (strName == strAccount)297 {298 // We're only counting our own valid bitcoin addresses and not ip addresses299 CScript scriptPubKey;300@@ -475,11 +529,6 @@301 }302 }303 304- // Minimum confirmations305- int nMinDepth = 1;306- if (params.size() > 1)307- nMinDepth = params[1].get_int();308-309 // Tally310 int64 nAmount = 0;311 CRITICAL_BLOCK(cs_mapWallet)312@@ -501,6 +550,200 @@313 }314 315 316+int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)317+{318+ // Get the set of pub keys that have the account319+ set<CScript> setPubKey;320+ CRITICAL_BLOCK(cs_mapAddressBook)321+ {322+ foreach(const PAIRTYPE(string, string)& item, mapAddressBook)323+ {324+ const string& strAddress = item.first;325+ const string& strName = item.second;326+ if (strName == strAccount)327+ {328+ // We're only counting our own valid bitcoin addresses and not ip addresses329+ CScript scriptPubKey;330+ if (scriptPubKey.SetBitcoinAddress(strAddress))331+ if (IsMine(scriptPubKey))332+ setPubKey.insert(scriptPubKey);333+ }334+ }335+ }336+337+ int64 nBalance = 0;338+ CRITICAL_BLOCK(cs_mapWallet)339+ {340+ // Tally wallet transactions341+ for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)342+ {343+ const CWalletTx& wtx = (*it).second;344+ if (!wtx.IsFinal())345+ continue;346+347+ // Count generated blocks to account ""348+ if (wtx.IsCoinBase() && strAccount == "" && wtx.GetBlocksToMaturity() == 0)349+ {350+ nBalance += wtx.GetCredit();351+ continue;352+ }353+354+ // Tally received355+ foreach(const CTxOut& txout, wtx.vout)356+ if (setPubKey.count(txout.scriptPubKey))357+ if (wtx.GetDepthInMainChain() >= nMinDepth)358+ nBalance += txout.nValue;359+360+ // Tally sent361+ if (wtx.strFromAccount == strAccount)362+ {363+ int64 nNet = wtx.GetCredit() - wtx.GetDebit();364+ if (nNet < 0)365+ nBalance += nNet;366+ }367+ }368+369+ // Tally internal accounting entries370+ nBalance += walletdb.GetAccountCreditDebit(strAccount);371+ }372+373+ return nBalance;374+}375+376+int64 GetAccountBalance(const string& strAccount, int nMinDepth)377+{378+ CWalletDB walletdb;379+ return GetAccountBalance(walletdb, strAccount, nMinDepth);380+}381+382+383+Value getbalance(const Array& params, bool fHelp)384+{385+ if (fHelp || params.size() < 0 || params.size() > 2)386+ throw runtime_error(387+ "getbalance [account] [minconf=1]\n"388+ "If [account] is not specified, returns the server's total available balance.\n"389+ "If [account] is specified, returns the balance in the account.");390+391+ if (params.size() == 0)392+ return ((double)GetBalance() / (double)COIN);393+394+ throw runtime_error("under construction"); //// to be released soon395+396+ string strAccount = params[0].get_str();397+ int nMinDepth = 1;398+ if (params.size() > 1)399+ nMinDepth = params[1].get_int();400+401+ int64 nBalance = GetAccountBalance(strAccount, nMinDepth);402+403+ return (double)nBalance / (double)COIN;404+}405+406+407+Value movecmd(const Array& params, bool fHelp)408+{409+ if (fHelp || params.size() < 3 || params.size() > 5)410+ throw runtime_error(411+ "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"412+ "Move from one account in your wallet to another.");413+414+ throw runtime_error("under construction");415+416+ string strFrom = params[0].get_str();417+ string strTo = params[1].get_str();418+ int64 nAmount = AmountFromValue(params[2]);419+ int nMinDepth = 1;420+ if (params.size() > 3)421+ nMinDepth = params[3].get_int();422+ string strComment;423+ if (params.size() > 4)424+ strComment = params[4].get_str();425+426+ CRITICAL_BLOCK(cs_mapWallet)427+ {428+ CWalletDB walletdb;429+ walletdb.TxnBegin();430+431+ // Check funds432+ if (!strFrom.empty())433+ {434+ int64 nBalance = GetAccountBalance(walletdb, strFrom, nMinDepth);435+ if (nAmount > nBalance)436+ throw JSONRPCError(-6, "Account has insufficient funds");437+ }438+ else439+ {440+ // move from "" account special case441+ int64 nBalance = GetAccountBalance(walletdb, strTo, nMinDepth);442+ if (nAmount > GetBalance() - nBalance)443+ throw JSONRPCError(-6, "Account has insufficient funds");444+ }445+446+ int64 nNow = GetAdjustedTime();447+448+ // Debit449+ CAccountingEntry debit;450+ debit.nCreditDebit = -nAmount;451+ debit.nTime = nNow;452+ debit.strOtherAccount = strTo;453+ debit.strComment = strComment;454+ walletdb.WriteAccountingEntry(strFrom, debit);455+456+ // Credit457+ CAccountingEntry credit;458+ credit.nCreditDebit = nAmount;459+ credit.nTime = nNow;460+ credit.strOtherAccount = strFrom;461+ credit.strComment = strComment;462+ walletdb.WriteAccountingEntry(strTo, credit);463+464+ walletdb.TxnCommit();465+ }466+ return true;467+}468+469+470+Value sendfrom(const Array& params, bool fHelp)471+{472+ if (fHelp || params.size() < 3 || params.size() > 6)473+ throw runtime_error(474+ "sendfrom <fromaccount> <tobitcoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"475+ "<amount> is a real and is rounded to the nearest 0.01");476+477+ throw runtime_error("under construction");478+479+ string strAccount = params[0].get_str();480+ string strAddress = params[1].get_str();481+ int64 nAmount = AmountFromValue(params[2]);482+ int nMinDepth = 1;483+ if (params.size() > 3)484+ nMinDepth = params[3].get_int();485+486+ CWalletTx wtx;487+ wtx.strFromAccount = strAccount;488+ if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())489+ wtx.mapValue["message"] = params[4].get_str();490+ if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())491+ wtx.mapValue["to"] = params[5].get_str();492+493+ CRITICAL_BLOCK(cs_mapWallet)494+ {495+ // Check funds496+ int64 nBalance = GetAccountBalance(strAccount, nMinDepth);497+ if (nAmount > nBalance)498+ throw JSONRPCError(-6, "Account has insufficient funds");499+500+ // Send501+ string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);502+ if (strError != "")503+ throw JSONRPCError(-4, strError);504+ }505+506+ return wtx.GetHash().GetHex();507+}508+509+510 511 struct tallyitem512 {513@@ -513,7 +756,7 @@514 }515 };516 517-Value ListReceived(const Array& params, bool fByLabels)518+Value ListReceived(const Array& params, bool fByAccounts)519 {520 // Minimum confirmations521 int nMinDepth = 1;522@@ -555,13 +798,13 @@523 524 // Reply525 Array ret;526- map<string, tallyitem> mapLabelTally;527+ map<string, tallyitem> mapAccountTally;528 CRITICAL_BLOCK(cs_mapAddressBook)529 {530 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)531 {532 const string& strAddress = item.first;533- const string& strLabel = item.second;534+ const string& strAccount = item.second;535 uint160 hash160;536 if (!AddressToHash160(strAddress, hash160))537 continue;538@@ -577,9 +820,9 @@539 nConf = (*it).second.nConf;540 }541 542- if (fByLabels)543+ if (fByAccounts)544 {545- tallyitem& item = mapLabelTally[strLabel];546+ tallyitem& item = mapAccountTally[strAccount];547 item.nAmount += nAmount;548 item.nConf = min(item.nConf, nConf);549 }550@@ -587,7 +830,8 @@551 {552 Object obj;553 obj.push_back(Pair("address", strAddress));554- obj.push_back(Pair("label", strLabel));555+ obj.push_back(Pair("account", strAccount));556+ obj.push_back(Pair("label", strAccount)); // deprecated557 obj.push_back(Pair("amount", (double)nAmount / (double)COIN));558 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));559 ret.push_back(obj);560@@ -595,14 +839,15 @@561 }562 }563 564- if (fByLabels)565- {566- for (map<string, tallyitem>::iterator it = mapLabelTally.begin(); it != mapLabelTally.end(); ++it)567+ if (fByAccounts)568+ {569+ for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)570 {571 int64 nAmount = (*it).second.nAmount;572 int nConf = (*it).second.nConf;573 Object obj;574- obj.push_back(Pair("label", (*it).first));575+ obj.push_back(Pair("account", (*it).first));576+ obj.push_back(Pair("label", (*it).first)); // deprecated577 obj.push_back(Pair("amount", (double)nAmount / (double)COIN));578 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));579 ret.push_back(obj);580@@ -621,23 +866,23 @@581 "[includeempty] whether to include addresses that haven't received any payments.\n"582 "Returns an array of objects containing:\n"583 " \"address\" : receiving address\n"584- " \"label\" : the label of the receiving address\n"585+ " \"account\" : the account of the receiving address\n"586 " \"amount\" : total amount received by the address\n"587 " \"confirmations\" : number of confirmations of the most recent transaction included");588 589 return ListReceived(params, false);590 }591 592-Value listreceivedbylabel(const Array& params, bool fHelp)593+Value listreceivedbyaccount(const Array& params, bool fHelp)594 {595 if (fHelp || params.size() > 2)596 throw runtime_error(597- "listreceivedbylabel [minconf=1] [includeempty=false]\n"598+ "listreceivedbyaccount [minconf=1] [includeempty=false]\n"599 "[minconf] is the minimum number of confirmations before payments are included.\n"600- "[includeempty] whether to include labels that haven't received any payments.\n"601+ "[includeempty] whether to include accounts that haven't received any payments.\n"602 "Returns an array of objects containing:\n"603- " \"label\" : the label of the receiving addresses\n"604- " \"amount\" : total amount received by addresses with this label\n"605+ " \"account\" : the account of the receiving addresses\n"606+ " \"amount\" : total amount received by addresses with this account\n"607 " \"confirmations\" : number of confirmations of the most recent transaction included");608 609 return ListReceived(params, true);610@@ -675,10 +920,122 @@611 {612 // Call Hash160ToAddress() so we always return current ADDRESSVERSION613 // version of the address:614- ret.push_back(Pair("address", Hash160ToAddress(hash160)));615+ string currentAddress = Hash160ToAddress(hash160);616+ ret.push_back(Pair("address", currentAddress));617 ret.push_back(Pair("ismine", (mapPubKeys.count(hash160) > 0)));618+ CRITICAL_BLOCK(cs_mapAddressBook)619+ {620+ if (mapAddressBook.count(currentAddress))621+ ret.push_back(Pair("account", mapAddressBook[currentAddress]));622+ }623 }624 return ret;625+}626+627+628+Value getwork(const Array& params, bool fHelp)629+{630+ if (fHelp || params.size() > 1)631+ throw runtime_error(632+ "getwork [data]\n"633+ "If [data] is not specified, returns formatted hash data to work on:\n"634+ " \"midstate\" : precomputed hash state after hashing the first half of the data\n"635+ " \"data\" : block data\n"636+ " \"hash1\" : formatted hash buffer for second hash\n"637+ " \"target\" : little endian hash target\n"638+ "If [data] is specified, tries to solve the block and returns true if it was successful.");639+640+ if (vNodes.empty())641+ throw JSONRPCError(-9, "Bitcoin is not connected!");642+643+ if (IsInitialBlockDownload())644+ throw JSONRPCError(-10, "Bitcoin is downloading blocks...");645+646+ static map<uint256, pair<CBlock*, unsigned int> > mapNewBlock;647+ static vector<CBlock*> vNewBlock;648+ static CReserveKey reservekey;649+650+ if (params.size() == 0)651+ {652+ // Update block653+ static unsigned int nTransactionsUpdatedLast;654+ static CBlockIndex* pindexPrev;655+ static int64 nStart;656+ static CBlock* pblock;657+ if (pindexPrev != pindexBest ||658+ (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))659+ {660+ if (pindexPrev != pindexBest)661+ {662+ // Deallocate old blocks since they're obsolete now663+ mapNewBlock.clear();664+ foreach(CBlock* pblock, vNewBlock)665+ delete pblock;666+ vNewBlock.clear();667+ }668+ nTransactionsUpdatedLast = nTransactionsUpdated;669+ pindexPrev = pindexBest;670+ nStart = GetTime();671+672+ // Create new block673+ pblock = CreateNewBlock(reservekey);674+ if (!pblock)675+ throw JSONRPCError(-7, "Out of memory");676+ vNewBlock.push_back(pblock);677+ }678+679+ // Update nTime680+ pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());681+ pblock->nNonce = 0;682+683+ // Update nExtraNonce684+ static unsigned int nExtraNonce = 0;685+ static int64 nPrevTime = 0;686+ IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, nPrevTime);687+688+ // Save689+ mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, nExtraNonce);690+691+ // Prebuild hash buffers692+ char pmidstate[32];693+ char pdata[128];694+ char phash1[64];695+ FormatHashBuffers(pblock, pmidstate, pdata, phash1);696+697+ uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();698+699+ Object result;700+ result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate))));701+ result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));702+ result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1))));703+ result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));704+ return result;705+ }706+ else707+ {708+ // Parse parameters709+ vector<unsigned char> vchData = ParseHex(params[0].get_str());710+ if (vchData.size() != 128)711+ throw JSONRPCError(-8, "Invalid parameter");712+ CBlock* pdata = (CBlock*)&vchData[0];713+714+ // Byte reverse715+ for (int i = 0; i < 128/4; i++)716+ ((unsigned int*)pdata)[i] = CryptoPP::ByteReverse(((unsigned int*)pdata)[i]);717+718+ // Get saved block719+ if (!mapNewBlock.count(pdata->hashMerkleRoot))720+ return false;721+ CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;722+ unsigned int nExtraNonce = mapNewBlock[pdata->hashMerkleRoot].second;723+724+ pblock->nTime = pdata->nTime;725+ pblock->nNonce = pdata->nNonce;726+ pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);727+ pblock->hashMerkleRoot = pblock->BuildMerkleTree();728+729+ return CheckWork(pblock, reservekey);730+ }731 }732 733 734@@ -703,24 +1060,33 @@735 make_pair("getblocknumber", &getblocknumber),736 make_pair("getconnectioncount", &getconnectioncount),737 make_pair("getdifficulty", &getdifficulty),738- make_pair("getbalance", &getbalance),739 make_pair("getgenerate", &getgenerate),740 make_pair("setgenerate", &setgenerate),741 make_pair("gethashespersec", &gethashespersec),742 make_pair("getinfo", &getinfo),743 make_pair("getnewaddress", &getnewaddress),744- make_pair("setlabel", &setlabel),745- make_pair("getlabel", &getlabel),746- make_pair("getaddressesbylabel", &getaddressesbylabel),747+ make_pair("getaccountaddress", &getaccountaddress),748+ make_pair("setaccount", &setaccount),749+ make_pair("setlabel", &setaccount), // deprecated750+ make_pair("getaccount", &getaccount),751+ make_pair("getlabel", &getaccount), // deprecated752+ make_pair("getaddressesbyaccount", &getaddressesbyaccount),753+ make_pair("getaddressesbylabel", &getaddressesbyaccount), // deprecated754 make_pair("sendtoaddress", &sendtoaddress),755 make_pair("getamountreceived", &getreceivedbyaddress), // deprecated, renamed to getreceivedbyaddress756 make_pair("getallreceived", &listreceivedbyaddress), // deprecated, renamed to listreceivedbyaddress757 make_pair("getreceivedbyaddress", &getreceivedbyaddress),758- make_pair("getreceivedbylabel", &getreceivedbylabel),759+ make_pair("getreceivedbyaccount", &getreceivedbyaccount),760+ make_pair("getreceivedbylabel", &getreceivedbyaccount), // deprecated761 make_pair("listreceivedbyaddress", &listreceivedbyaddress),762- make_pair("listreceivedbylabel", &listreceivedbylabel),763+ make_pair("listreceivedbyaccount", &listreceivedbyaccount),764+ make_pair("listreceivedbylabel", &listreceivedbyaccount), // deprecated765 make_pair("backupwallet", &backupwallet),766 make_pair("validateaddress", &validateaddress),767+ make_pair("getbalance", &getbalance),768+ make_pair("move", &movecmd),769+ make_pair("sendfrom", &sendfrom),770+ make_pair("getwork", &getwork),771 };772 map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0]));773 774@@ -737,11 +1103,15 @@775 "gethashespersec",776 "getinfo",777 "getnewaddress",778+ "getaccountaddress",779 "setlabel",780- "getlabel",781- "getaddressesbylabel",782+ "getaccount",783+ "getlabel", // deprecated784+ "getaddressesbyaccount",785+ "getaddressesbylabel", // deprecated786 "backupwallet",787 "validateaddress",788+ "getwork",789 };790 set<string> setAllowInSafeMode(pAllowInSafeMode, pAllowInSafeMode + sizeof(pAllowInSafeMode)/sizeof(pAllowInSafeMode[0]));791 792@@ -1164,7 +1534,8 @@793 if (valMethod.type() != str_type)794 throw JSONRPCError(-32600, "Method must be a string");795 string strMethod = valMethod.get_str();796- printf("ThreadRPCServer method=%s\n", strMethod.c_str());797+ if (strMethod != "getwork")798+ printf("ThreadRPCServer method=%s\n", strMethod.c_str());799 800 // Parse params801 Value valParams = find_value(request, "params");802@@ -1339,13 +1710,21 @@803 if (strMethod == "listtransactions" && n > 1) ConvertTo<bool>(params[1]);804 if (strMethod == "getamountreceived" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated805 if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);806- if (strMethod == "getreceivedbylabel" && n > 1) ConvertTo<boost::int64_t>(params[1]);807+ if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);808+ if (strMethod == "getreceivedbylabel" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated809 if (strMethod == "getallreceived" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated810 if (strMethod == "getallreceived" && n > 1) ConvertTo<bool>(params[1]);811 if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);812 if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);813- if (strMethod == "listreceivedbylabel" && n > 0) ConvertTo<boost::int64_t>(params[0]);814- if (strMethod == "listreceivedbylabel" && n > 1) ConvertTo<bool>(params[1]);815+ if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);816+ if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);817+ if (strMethod == "listreceivedbylabel" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated818+ if (strMethod == "listreceivedbylabel" && n > 1) ConvertTo<bool>(params[1]); // deprecated819+ if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);820+ if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);821+ if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);822+ if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);823+ if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);824 825 // Execute826 Object reply = CallRPC(strMethod, params);
serialize.h (modified)
1--- v0.3.15/serialize.h2+++ v0.3.17/serialize.h3@@ -22,7 +22,7 @@4 class CAutoFile;5 static const unsigned int MAX_SIZE = 0x02000000;6 7-static const int VERSION = 31500;8+static const int VERSION = 31700;9 static const char* pszSubVer = "";10 11
setup.nsi (modified)
1--- v0.3.15/setup.nsi2+++ v0.3.17/setup.nsi3@@ -7,7 +7,7 @@4 5 # General Symbol Definitions6 !define REGKEY "SOFTWARE\$(^Name)"7-!define VERSION 0.3.158+!define VERSION 0.3.179 !define COMPANY "Bitcoin project"10 !define URL http://www.bitcoin.org/11 12@@ -42,12 +42,12 @@13 !insertmacro MUI_LANGUAGE English14 15 # Installer attributes16-OutFile bitcoin-0.3.15-win32-setup.exe17+OutFile bitcoin-0.3.17-win32-setup.exe18 InstallDir $PROGRAMFILES\Bitcoin19 CRCCheck on20 XPStyle on21 ShowInstDetails show22-VIProductVersion 0.3.15.023+VIProductVersion 0.3.17.024 VIAddVersionKey ProductName Bitcoin25 VIAddVersionKey ProductVersion "${VERSION}"26 VIAddVersionKey CompanyName "${COMPANY}"
sha256.cpp (modified)
1--- v0.3.15/sha256.cpp2+++ v0.3.17/sha256.cpp3@@ -110,15 +110,15 @@4 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};5 6 7-unsigned int ScanHash_4WaySSE2(char* pmidstate, char* pblock, char* phash1, char* phash, unsigned int& nHashesDone)8+unsigned int ScanHash_4WaySSE2(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)9 {10- unsigned int& nNonce = *(unsigned int*)(pblock + 12);11+ unsigned int& nNonce = *(unsigned int*)(pdata + 12);12 for (;;)13 {14 nNonce += NPAR;15 unsigned int thashbuf[9][NPAR];16 unsigned int (&thash)[9][NPAR] = *alignup<16>(&thashbuf);17- DoubleBlockSHA256(pblock, phash1, pmidstate, thash, pSHA256InitState);18+ DoubleBlockSHA256(pdata, phash1, pmidstate, thash, pSHA256InitState);19 20 for (int j = 0; j < NPAR; j++)21 {
ui.cpp (modified)
1--- v0.3.15/ui.cpp2+++ v0.3.17/ui.cpp3@@ -1171,7 +1171,7 @@4 string strName = dialog.GetValue();5 6 // Generate new key7- string strAddress = PubKeyToAddress(CWalletDB().GetKeyFromKeyPool());8+ string strAddress = PubKeyToAddress(GetKeyFromKeyPool());9 10 // Save11 SetAddressBookName(strAddress, strName);12@@ -1631,6 +1631,9 @@13 //m_listBox->Append(_("Test 2"));14 m_listBox->SetSelection(0);15 SelectPage(0);16+#ifndef __WXMSW__17+ SetSize(1.0 * GetSize().GetWidth(), 1.2 * GetSize().GetHeight());18+#endif19 #if defined(__WXGTK__) || defined(__WXMAC_OSX__)20 m_checkBoxStartOnSystemStartup->SetLabel(_("&Start Bitcoin on window system startup"));21 if (!mapArgs.count("-minimizetotray"))22@@ -2575,7 +2578,7 @@23 strName = dialog.GetValue();24 25 // Generate new key26- strAddress = PubKeyToAddress(CWalletDB().GetKeyFromKeyPool());27+ strAddress = PubKeyToAddress(GetKeyFromKeyPool());28 }29 30 // Add to list and select it
uibase.cpp (modified)
1--- v0.3.15/uibase.cpp2+++ v0.3.17/uibase.cpp3@@ -352,28 +352,6 @@4 5 bSizer69->Add( 0, 16, 0, wxEXPAND, 5 );6 7- m_staticText32 = new wxStaticText( m_panelMain, wxID_ANY, _("Optional transaction fee you give to the nodes that process your transactions."), wxDefaultPosition, wxDefaultSize, 0 );8- m_staticText32->Wrap( -1 );9- m_staticText32->Hide();10- 11- bSizer69->Add( m_staticText32, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );12- 13- wxBoxSizer* bSizer56;14- bSizer56 = new wxBoxSizer( wxHORIZONTAL );15- 16- m_staticText31 = new wxStaticText( m_panelMain, wxID_ANY, _("Transaction fee:"), wxDefaultPosition, wxDefaultSize, 0 );17- m_staticText31->Wrap( -1 );18- m_staticText31->Hide();19- 20- bSizer56->Add( m_staticText31, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 );21- 22- m_textCtrlTransactionFee = new wxTextCtrl( m_panelMain, wxID_TRANSACTIONFEE, wxEmptyString, wxDefaultPosition, wxSize( 70,-1 ), 0 );23- m_textCtrlTransactionFee->Hide();24- 25- bSizer56->Add( m_textCtrlTransactionFee, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );26- 27- bSizer69->Add( bSizer56, 0, wxEXPAND, 5 );28- 29 wxBoxSizer* bSizer71;30 bSizer71 = new wxBoxSizer( wxHORIZONTAL );31 32@@ -434,6 +412,25 @@33 bSizer103->Add( m_textCtrlProxyPort, 0, wxALIGN_CENTER_VERTICAL, 5 );34 35 bSizer69->Add( bSizer103, 1, wxEXPAND, 5 );36+ 37+ 38+ bSizer69->Add( 0, 1, 0, 0, 5 );39+ 40+ m_staticText32 = new wxStaticText( m_panelMain, wxID_ANY, _("Optional transaction fee per KB that helps make sure your transactions are processed quickly. Most transactions are 1KB. Fee 0.01 recommended."), wxDefaultPosition, wxDefaultSize, 0 );41+ m_staticText32->Wrap( 365 );42+ bSizer69->Add( m_staticText32, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxRIGHT|wxLEFT, 5 );43+ 44+ wxBoxSizer* bSizer56;45+ bSizer56 = new wxBoxSizer( wxHORIZONTAL );46+ 47+ m_staticText31 = new wxStaticText( m_panelMain, wxID_ANY, _("Pay transaction fee:"), wxDefaultPosition, wxDefaultSize, 0 );48+ m_staticText31->Wrap( -1 );49+ bSizer56->Add( m_staticText31, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 );50+ 51+ m_textCtrlTransactionFee = new wxTextCtrl( m_panelMain, wxID_TRANSACTIONFEE, wxEmptyString, wxDefaultPosition, wxSize( 70,-1 ), 0 );52+ bSizer56->Add( m_textCtrlTransactionFee, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );53+ 54+ bSizer69->Add( bSizer56, 0, wxEXPAND, 5 );55 56 m_panelMain->SetSizer( bSizer69 );57 m_panelMain->Layout();58@@ -486,12 +483,12 @@59 60 // Connect Events61 m_listBox->Connect( wxEVT_COMMAND_LISTBOX_SELECTED, wxCommandEventHandler( COptionsDialogBase::OnListBox ), NULL, this );62- m_textCtrlTransactionFee->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( COptionsDialogBase::OnKillFocusTransactionFee ), NULL, this );63 m_checkBoxLimitProcessors->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( COptionsDialogBase::OnCheckBoxLimitProcessors ), NULL, this );64 m_checkBoxMinimizeToTray->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( COptionsDialogBase::OnCheckBoxMinimizeToTray ), NULL, this );65 m_checkBoxUseProxy->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( COptionsDialogBase::OnCheckBoxUseProxy ), NULL, this );66 m_textCtrlProxyIP->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( COptionsDialogBase::OnKillFocusProxy ), NULL, this );67 m_textCtrlProxyPort->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( COptionsDialogBase::OnKillFocusProxy ), NULL, this );68+ m_textCtrlTransactionFee->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( COptionsDialogBase::OnKillFocusTransactionFee ), NULL, this );69 m_buttonOK->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( COptionsDialogBase::OnButtonOK ), NULL, this );70 m_buttonCancel->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( COptionsDialogBase::OnButtonCancel ), NULL, this );71 m_buttonApply->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( COptionsDialogBase::OnButtonApply ), NULL, this );72@@ -501,12 +498,12 @@73 {74 // Disconnect Events75 m_listBox->Disconnect( wxEVT_COMMAND_LISTBOX_SELECTED, wxCommandEventHandler( COptionsDialogBase::OnListBox ), NULL, this );76- m_textCtrlTransactionFee->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( COptionsDialogBase::OnKillFocusTransactionFee ), NULL, this );77 m_checkBoxLimitProcessors->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( COptionsDialogBase::OnCheckBoxLimitProcessors ), NULL, this );78 m_checkBoxMinimizeToTray->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( COptionsDialogBase::OnCheckBoxMinimizeToTray ), NULL, this );79 m_checkBoxUseProxy->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( COptionsDialogBase::OnCheckBoxUseProxy ), NULL, this );80 m_textCtrlProxyIP->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( COptionsDialogBase::OnKillFocusProxy ), NULL, this );81 m_textCtrlProxyPort->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( COptionsDialogBase::OnKillFocusProxy ), NULL, this );82+ m_textCtrlTransactionFee->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( COptionsDialogBase::OnKillFocusTransactionFee ), NULL, this );83 m_buttonOK->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( COptionsDialogBase::OnButtonOK ), NULL, this );84 m_buttonCancel->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( COptionsDialogBase::OnButtonCancel ), NULL, this );85 m_buttonApply->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( COptionsDialogBase::OnButtonApply ), NULL, this );
uibase.h (modified)
1--- v0.3.15/uibase.h2+++ v0.3.17/uibase.h3@@ -47,9 +47,9 @@4 #define wxID_TEXTCTRLADDRESS 10045 #define wxID_BUTTONNEW 10056 #define wxID_BUTTONCOPY 10067-#define wxID_TRANSACTIONFEE 10078-#define wxID_PROXYIP 10089-#define wxID_PROXYPORT 100910+#define wxID_PROXYIP 100711+#define wxID_PROXYPORT 100812+#define wxID_TRANSACTIONFEE 100913 #define wxID_TEXTCTRLPAYTO 101014 #define wxID_BUTTONPASTE 101115 #define wxID_BUTTONADDRESSBOOK 101216@@ -163,9 +163,6 @@17 wxScrolledWindow* m_scrolledWindow;18 wxPanel* m_panelMain;19 20- wxStaticText* m_staticText32;21- wxStaticText* m_staticText31;22- wxTextCtrl* m_textCtrlTransactionFee;23 wxCheckBox* m_checkBoxLimitProcessors;24 wxSpinCtrl* m_spinCtrlLimitProcessors;25 wxStaticText* m_staticText35;26@@ -178,6 +175,10 @@27 wxTextCtrl* m_textCtrlProxyIP;28 wxStaticText* m_staticTextProxyPort;29 wxTextCtrl* m_textCtrlProxyPort;30+ 31+ wxStaticText* m_staticText32;32+ wxStaticText* m_staticText31;33+ wxTextCtrl* m_textCtrlTransactionFee;34 wxPanel* m_panelTest2;35 36 wxStaticText* m_staticText321;37@@ -188,11 +189,11 @@38 39 // Virtual event handlers, overide them in your derived class40 virtual void OnListBox( wxCommandEvent& event ){ event.Skip(); }41- virtual void OnKillFocusTransactionFee( wxFocusEvent& event ){ event.Skip(); }42 virtual void OnCheckBoxLimitProcessors( wxCommandEvent& event ){ event.Skip(); }43 virtual void OnCheckBoxMinimizeToTray( wxCommandEvent& event ){ event.Skip(); }44 virtual void OnCheckBoxUseProxy( wxCommandEvent& event ){ event.Skip(); }45 virtual void OnKillFocusProxy( wxFocusEvent& event ){ event.Skip(); }46+ virtual void OnKillFocusTransactionFee( wxFocusEvent& event ){ event.Skip(); }47 virtual void OnButtonOK( wxCommandEvent& event ){ event.Skip(); }48 virtual void OnButtonCancel( wxCommandEvent& event ){ event.Skip(); }49 virtual void OnButtonApply( wxCommandEvent& event ){ event.Skip(); }
util.cpp (modified)
1--- v0.3.15/util.cpp2+++ v0.3.17/util.cpp3@@ -157,10 +157,16 @@4 else5 {6 // print to debug.log7- char pszFile[MAX_PATH+100];8- GetDataDir(pszFile);9- strlcat(pszFile, "/debug.log", sizeof(pszFile));10- FILE* fileout = fopen(pszFile, "a");11+ static FILE* fileout = NULL;12+13+ if (!fileout)14+ {15+ char pszFile[MAX_PATH+100];16+ GetDataDir(pszFile);17+ strlcat(pszFile, "/debug.log", sizeof(pszFile));18+ fileout = fopen(pszFile, "a");19+ setbuf(fileout, NULL); // unbuffered20+ }21 if (fileout)22 {23 //// Debug print useful for profiling24@@ -169,15 +175,16 @@25 va_start(arg_ptr, pszFormat);26 ret = vfprintf(fileout, pszFormat, arg_ptr);27 va_end(arg_ptr);28- fclose(fileout);29+ fflush(fileout);30 }31 }32 33 #ifdef __WXMSW__34 if (fPrintToDebugger)35 {36+ static CCriticalSection cs_OutputDebugStringF;37+38 // accumulate a line at a time39- static CCriticalSection cs_OutputDebugStringF;40 CRITICAL_BLOCK(cs_OutputDebugStringF)41 {42 static char pszBuffer[50000];
