1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Distributed under the MIT/X11 software license, see the accompanying
3
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
6
#include "cryptopp/sha.h"
16
CCriticalSection cs_main;
18
map<uint256, CTransaction> mapTransactions;
19
CCriticalSection cs_mapTransactions;
20
unsigned int nTransactionsUpdated = 0;
21
map<COutPoint, CInPoint> mapNextTx;
23
map<uint256, CBlockIndex*> mapBlockIndex;
24
uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
25
CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
26
CBlockIndex* pindexGenesisBlock = NULL;
28
CBigNum bnBestChainWork = 0;
29
CBigNum bnBestInvalidWork = 0;
30
uint256 hashBestChain = 0;
31
CBlockIndex* pindexBest = NULL;
32
int64 nTimeBestReceived = 0;
34
map<uint256, CBlock*> mapOrphanBlocks;
35
multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
37
map<uint256, CDataStream*> mapOrphanTransactions;
38
multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
40
map<uint256, CWalletTx> mapWallet;
41
vector<uint256> vWalletUpdated;
42
CCriticalSection cs_mapWallet;
44
map<vector<unsigned char>, CPrivKey> mapKeys;
45
map<uint160, vector<unsigned char> > mapPubKeys;
46
CCriticalSection cs_mapKeys;
49
map<uint256, int> mapRequestCount;
50
CCriticalSection cs_mapRequestCount;
52
map<string, string> mapAddressBook;
53
CCriticalSection cs_mapAddressBook;
55
vector<unsigned char> vchDefaultKey;
61
int fGenerateBitcoins = false;
62
int64 nTransactionFee = 0;
63
CAddress addrIncoming;
64
int fLimitProcessors = false;
65
int nLimitProcessors = 1;
66
int fMinimizeToTray = true;
67
int fMinimizeOnClose = true;
74
//////////////////////////////////////////////////////////////////////////////
79
bool AddKey(const CKey& key)
81
CRITICAL_BLOCK(cs_mapKeys)
83
mapKeys[key.GetPubKey()] = key.GetPrivKey();
84
mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
86
return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());
89
vector<unsigned char> GenerateNewKey()
95
throw runtime_error("GenerateNewKey() : AddKey failed");
96
return key.GetPubKey();
102
//////////////////////////////////////////////////////////////////////////////
107
bool AddToWallet(const CWalletTx& wtxIn)
109
uint256 hash = wtxIn.GetHash();
110
CRITICAL_BLOCK(cs_mapWallet)
112
// Inserts only if not already there, returns tx inserted or tx found
113
pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
114
CWalletTx& wtx = (*ret.first).second;
115
bool fInsertedNew = ret.second;
117
wtx.nTimeReceived = GetAdjustedTime();
119
bool fUpdated = false;
123
if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
125
wtx.hashBlock = wtxIn.hashBlock;
128
if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
130
wtx.vMerkleBranch = wtxIn.vMerkleBranch;
131
wtx.nIndex = wtxIn.nIndex;
134
if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
136
wtx.fFromMe = wtxIn.fFromMe;
139
if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)
141
wtx.fSpent = wtxIn.fSpent;
147
printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
150
if (fInsertedNew || fUpdated)
151
if (!wtx.WriteToDisk())
154
// If default receiving address gets used, replace it with a new one
155
CScript scriptDefaultKey;
156
scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
157
foreach(const CTxOut& txout, wtx.vout)
159
if (txout.scriptPubKey == scriptDefaultKey)
162
vchDefaultKey = GetKeyFromKeyPool();
163
walletdb.WriteDefaultKey(vchDefaultKey);
164
walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
169
vWalletUpdated.push_back(hash);
177
bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)
179
if (tx.IsMine() || mapWallet.count(tx.GetHash()))
182
// Get merkle branch if transaction was found in a block
184
wtx.SetMerkleBranch(pblock);
185
return AddToWallet(wtx);
190
bool EraseFromWallet(uint256 hash)
192
CRITICAL_BLOCK(cs_mapWallet)
194
if (mapWallet.erase(hash))
195
CWalletDB().EraseTx(hash);
200
void WalletUpdateSpent(const COutPoint& prevout)
202
// Anytime a signature is successfully verified, it's proof the outpoint is spent.
203
// Update the wallet spent flag if it doesn't know due to wallet.dat being
204
// restored from backup or the user making copies of wallet.dat.
205
CRITICAL_BLOCK(cs_mapWallet)
207
map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
208
if (mi != mapWallet.end())
210
CWalletTx& wtx = (*mi).second;
211
if (!wtx.fSpent && wtx.vout[prevout.n].IsMine())
213
printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
216
vWalletUpdated.push_back(prevout.hash);
229
//////////////////////////////////////////////////////////////////////////////
231
// mapOrphanTransactions
234
void AddOrphanTx(const CDataStream& vMsg)
237
CDataStream(vMsg) >> tx;
238
uint256 hash = tx.GetHash();
239
if (mapOrphanTransactions.count(hash))
241
CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
242
foreach(const CTxIn& txin, tx.vin)
243
mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
246
void EraseOrphanTx(uint256 hash)
248
if (!mapOrphanTransactions.count(hash))
250
const CDataStream* pvMsg = mapOrphanTransactions[hash];
252
CDataStream(*pvMsg) >> tx;
253
foreach(const CTxIn& txin, tx.vin)
255
for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
256
mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
258
if ((*mi).second == pvMsg)
259
mapOrphanTransactionsByPrev.erase(mi++);
265
mapOrphanTransactions.erase(hash);
275
//////////////////////////////////////////////////////////////////////////////
280
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
283
if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
285
if (!ReadFromDisk(txindexRet.pos))
287
if (prevout.n >= vout.size())
295
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
298
return ReadFromDisk(txdb, prevout, txindex);
301
bool CTransaction::ReadFromDisk(COutPoint prevout)
305
return ReadFromDisk(txdb, prevout, txindex);
308
bool CTxIn::IsMine() const
310
CRITICAL_BLOCK(cs_mapWallet)
312
map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
313
if (mi != mapWallet.end())
315
const CWalletTx& prev = (*mi).second;
316
if (prevout.n < prev.vout.size())
317
if (prev.vout[prevout.n].IsMine())
324
int64 CTxIn::GetDebit() const
326
CRITICAL_BLOCK(cs_mapWallet)
328
map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
329
if (mi != mapWallet.end())
331
const CWalletTx& prev = (*mi).second;
332
if (prevout.n < prev.vout.size())
333
if (prev.vout[prevout.n].IsMine())
334
return prev.vout[prevout.n].nValue;
340
int64 CWalletTx::GetTxTime() const
342
if (!fTimeReceivedIsTxTime && hashBlock != 0)
344
// If we did not receive the transaction directly, we rely on the block's
345
// time to figure out when it happened. We use the median over a range
346
// of blocks to try to filter out inaccurate block times.
347
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
348
if (mi != mapBlockIndex.end())
350
CBlockIndex* pindex = (*mi).second;
352
return pindex->GetMedianTime();
355
return nTimeReceived;
358
int CWalletTx::GetRequestCount() const
360
// Returns -1 if it wasn't being tracked
362
CRITICAL_BLOCK(cs_mapRequestCount)
369
map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
370
if (mi != mapRequestCount.end())
371
nRequests = (*mi).second;
376
// Did anyone request this transaction?
377
map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
378
if (mi != mapRequestCount.end())
380
nRequests = (*mi).second;
382
// How about the block it's in?
383
if (nRequests == 0 && hashBlock != 0)
385
map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
386
if (mi != mapRequestCount.end())
387
nRequests = (*mi).second;
389
nRequests = 1; // If it's in someone else's block it must have got out
400
int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
412
// Load the block this tx is in
414
if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
416
if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
421
// Update the tx's hashBlock
422
hashBlock = pblock->GetHash();
424
// Locate the transaction
425
for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
426
if (pblock->vtx[nIndex] == *(CTransaction*)this)
428
if (nIndex == pblock->vtx.size())
430
vMerkleBranch.clear();
432
printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
436
// Fill in merkle branch
437
vMerkleBranch = pblock->GetMerkleBranch(nIndex);
440
// Is the tx in a block that's in the main chain
441
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
442
if (mi == mapBlockIndex.end())
444
CBlockIndex* pindex = (*mi).second;
445
if (!pindex || !pindex->IsInMainChain())
448
return pindexBest->nHeight - pindex->nHeight + 1;
453
void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
457
const int COPY_DEPTH = 3;
458
if (SetMerkleBranch() < COPY_DEPTH)
460
vector<uint256> vWorkQueue;
461
foreach(const CTxIn& txin, vin)
462
vWorkQueue.push_back(txin.prevout.hash);
464
// This critsect is OK because txdb is already open
465
CRITICAL_BLOCK(cs_mapWallet)
467
map<uint256, const CMerkleTx*> mapWalletPrev;
468
set<uint256> setAlreadyDone;
469
for (int i = 0; i < vWorkQueue.size(); i++)
471
uint256 hash = vWorkQueue[i];
472
if (setAlreadyDone.count(hash))
474
setAlreadyDone.insert(hash);
477
if (mapWallet.count(hash))
479
tx = mapWallet[hash];
480
foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
481
mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
483
else if (mapWalletPrev.count(hash))
485
tx = *mapWalletPrev[hash];
487
else if (!fClient && txdb.ReadDiskTx(hash, tx))
493
printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
497
int nDepth = tx.SetMerkleBranch();
498
vtxPrev.push_back(tx);
500
if (nDepth < COPY_DEPTH)
501
foreach(const CTxIn& txin, tx.vin)
502
vWorkQueue.push_back(txin.prevout.hash);
507
reverse(vtxPrev.begin(), vtxPrev.end());
520
bool CTransaction::CheckTransaction() const
522
// Basic checks that don't depend on any context
523
if (vin.empty() || vout.empty())
524
return error("CTransaction::CheckTransaction() : vin or vout empty");
527
if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
528
return error("CTransaction::CheckTransaction() : size limits failed");
530
// Check for negative or overflow output values
532
foreach(const CTxOut& txout, vout)
534
if (txout.nValue < 0)
535
return error("CTransaction::CheckTransaction() : txout.nValue negative");
536
if (txout.nValue > MAX_MONEY)
537
return error("CTransaction::CheckTransaction() : txout.nValue too high");
538
nValueOut += txout.nValue;
539
if (!MoneyRange(nValueOut))
540
return error("CTransaction::CheckTransaction() : txout total out of range");
545
if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
546
return error("CTransaction::CheckTransaction() : coinbase script size");
550
foreach(const CTxIn& txin, vin)
551
if (txin.prevout.IsNull())
552
return error("CTransaction::CheckTransaction() : prevout is null");
558
bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
561
*pfMissingInputs = false;
563
if (!CheckTransaction())
564
return error("AcceptToMemoryPool() : CheckTransaction failed");
566
// Coinbase is only valid in a block, not as a loose transaction
568
return error("AcceptToMemoryPool() : coinbase as individual tx");
570
// To help v0.1.5 clients who would see it as a negative number
571
if ((int64)nLockTime > INT_MAX)
572
return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
575
unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
576
if (GetSigOpCount() > 2 || nSize < 100)
577
return error("AcceptToMemoryPool() : nonstandard transaction");
579
// Rather not work on nonstandard transactions
581
return error("AcceptToMemoryPool() : nonstandard transaction type");
583
// Do we already have it?
584
uint256 hash = GetHash();
585
CRITICAL_BLOCK(cs_mapTransactions)
586
if (mapTransactions.count(hash))
589
if (txdb.ContainsTx(hash))
592
// Check for conflicts with in-memory transactions
593
CTransaction* ptxOld = NULL;
594
for (int i = 0; i < vin.size(); i++)
596
COutPoint outpoint = vin[i].prevout;
597
if (mapNextTx.count(outpoint))
599
// Disable replacement feature for now
602
// Allow replacing with a newer version of the same transaction
605
ptxOld = mapNextTx[outpoint].ptx;
606
if (ptxOld->IsFinal())
608
if (!IsNewerThan(*ptxOld))
610
for (int i = 0; i < vin.size(); i++)
612
COutPoint outpoint = vin[i].prevout;
613
if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
622
// Check against previous transactions
623
map<uint256, CTxIndex> mapUnused;
625
if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
628
*pfMissingInputs = true;
629
return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
632
// Don't accept it if it can't get into a block
633
if (nFees < GetMinFee(1000))
634
return error("AcceptToMemoryPool() : not enough fees");
636
// Limit free transactions per 10 minutes
637
if (nFees < CENT && GetBoolArg("-limitfreerelay"))
639
static int64 nNextReset;
640
static int64 nFreeCount;
641
if (GetTime() > nNextReset)
643
nNextReset = GetTime() + 10 * 60;
646
if (nFreeCount > 150000 && !IsFromMe())
647
return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
652
// Store transaction in memory
653
CRITICAL_BLOCK(cs_mapTransactions)
657
printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
658
ptxOld->RemoveFromMemoryPool();
660
AddToMemoryPoolUnchecked();
663
///// are we sure this is ok when loading transactions or restoring block txes
664
// If updated, erase old tx from wallet
666
EraseFromWallet(ptxOld->GetHash());
668
printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
673
bool CTransaction::AddToMemoryPoolUnchecked()
675
// Add to memory pool without checking anything. Don't call this directly,
676
// call AcceptToMemoryPool to properly check the transaction first.
677
CRITICAL_BLOCK(cs_mapTransactions)
679
uint256 hash = GetHash();
680
mapTransactions[hash] = *this;
681
for (int i = 0; i < vin.size(); i++)
682
mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
683
nTransactionsUpdated++;
689
bool CTransaction::RemoveFromMemoryPool()
691
// Remove transaction from memory pool
692
CRITICAL_BLOCK(cs_mapTransactions)
694
foreach(const CTxIn& txin, vin)
695
mapNextTx.erase(txin.prevout);
696
mapTransactions.erase(GetHash());
697
nTransactionsUpdated++;
707
int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
709
if (hashBlock == 0 || nIndex == -1)
712
// Find the block it claims to be in
713
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
714
if (mi == mapBlockIndex.end())
716
CBlockIndex* pindex = (*mi).second;
717
if (!pindex || !pindex->IsInMainChain())
720
// Make sure the merkle branch connects to this block
721
if (!fMerkleVerified)
723
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
725
fMerkleVerified = true;
728
nHeightRet = pindex->nHeight;
729
return pindexBest->nHeight - pindex->nHeight + 1;
733
int CMerkleTx::GetBlocksToMaturity() const
737
return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
741
bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
745
if (!IsInMainChain() && !ClientConnectInputs())
747
return CTransaction::AcceptToMemoryPool(txdb, false);
751
return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
757
bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
759
CRITICAL_BLOCK(cs_mapTransactions)
761
// Add previous supporting transactions first
762
foreach(CMerkleTx& tx, vtxPrev)
764
if (!tx.IsCoinBase())
766
uint256 hash = tx.GetHash();
767
if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
768
tx.AcceptToMemoryPool(txdb, fCheckInputs);
771
return AcceptToMemoryPool(txdb, fCheckInputs);
776
void ReacceptWalletTransactions()
779
CRITICAL_BLOCK(cs_mapWallet)
781
foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
783
CWalletTx& wtx = item.second;
784
if (wtx.fSpent && wtx.IsCoinBase())
788
if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
790
// Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
793
if (txindex.vSpent.size() != wtx.vout.size())
795
printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
798
for (int i = 0; i < txindex.vSpent.size(); i++)
800
if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
802
printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
812
// Reaccept any txes of ours that aren't already in a block
813
if (!wtx.IsCoinBase())
814
wtx.AcceptWalletTransaction(txdb, false);
821
void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
823
foreach(const CMerkleTx& tx, vtxPrev)
825
if (!tx.IsCoinBase())
827
uint256 hash = tx.GetHash();
828
if (!txdb.ContainsTx(hash))
829
RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
834
uint256 hash = GetHash();
835
if (!txdb.ContainsTx(hash))
837
printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
838
RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
843
void ResendWalletTransactions()
845
// Do this infrequently and randomly to avoid giving away
846
// that these are our transactions.
847
static int64 nNextTime;
848
if (GetTime() < nNextTime)
850
bool fFirst = (nNextTime == 0);
851
nNextTime = GetTime() + GetRand(30 * 60);
855
// Only do it if there's been a new block since last time
856
static int64 nLastTime;
857
if (nTimeBestReceived < nLastTime)
859
nLastTime = GetTime();
861
// Rebroadcast any of our txes that aren't in a block yet
862
printf("ResendWalletTransactions()\n");
864
CRITICAL_BLOCK(cs_mapWallet)
866
// Sort them in chronological order
867
multimap<unsigned int, CWalletTx*> mapSorted;
868
foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
870
CWalletTx& wtx = item.second;
871
// Don't rebroadcast until it's had plenty of time that
872
// it should have gotten in already by now.
873
if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
874
mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
876
foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
878
CWalletTx& wtx = *item.second;
879
wtx.RelayWalletTransaction(txdb);
893
//////////////////////////////////////////////////////////////////////////////
895
// CBlock and CBlockIndex
898
bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
900
if (!fReadTransactions)
902
*this = pindex->GetBlockHeader();
905
if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
907
if (GetHash() != pindex->GetBlockHash())
908
return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
912
uint256 GetOrphanRoot(const CBlock* pblock)
914
// Work back to the first block in the orphan chain
915
while (mapOrphanBlocks.count(pblock->hashPrevBlock))
916
pblock = mapOrphanBlocks[pblock->hashPrevBlock];
917
return pblock->GetHash();
920
int64 GetBlockValue(int nHeight, int64 nFees)
922
int64 nSubsidy = 50 * COIN;
924
// Subsidy is cut in half every 4 years
925
nSubsidy >>= (nHeight / 210000);
927
return nSubsidy + nFees;
930
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
932
const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
933
const int64 nTargetSpacing = 10 * 60;
934
const int64 nInterval = nTargetTimespan / nTargetSpacing;
937
if (pindexLast == NULL)
938
return bnProofOfWorkLimit.GetCompact();
940
// Only change once per interval
941
if ((pindexLast->nHeight+1) % nInterval != 0)
942
return pindexLast->nBits;
944
// Go back by what we want to be 14 days worth of blocks
945
const CBlockIndex* pindexFirst = pindexLast;
946
for (int i = 0; pindexFirst && i < nInterval-1; i++)
947
pindexFirst = pindexFirst->pprev;
950
// Limit adjustment step
951
int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
952
printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
953
if (nActualTimespan < nTargetTimespan/4)
954
nActualTimespan = nTargetTimespan/4;
955
if (nActualTimespan > nTargetTimespan*4)
956
nActualTimespan = nTargetTimespan*4;
960
bnNew.SetCompact(pindexLast->nBits);
961
bnNew *= nActualTimespan;
962
bnNew /= nTargetTimespan;
964
if (bnNew > bnProofOfWorkLimit)
965
bnNew = bnProofOfWorkLimit;
968
printf("GetNextWorkRequired RETARGET\n");
969
printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
970
printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
971
printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
973
return bnNew.GetCompact();
976
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
979
bnTarget.SetCompact(nBits);
982
if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
983
return error("CheckProofOfWork() : nBits below minimum work");
985
// Check proof of work matches claimed amount
986
if (hash > bnTarget.getuint256())
987
return error("CheckProofOfWork() : hash doesn't match nBits");
992
bool IsInitialBlockDownload()
994
if (pindexBest == NULL || (!fTestNet && nBestHeight < 74000))
996
static int64 nLastUpdate;
997
static CBlockIndex* pindexLastBest;
998
if (pindexBest != pindexLastBest)
1000
pindexLastBest = pindexBest;
1001
nLastUpdate = GetTime();
1003
return (GetTime() - nLastUpdate < 10 &&
1004
pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1007
void InvalidChainFound(CBlockIndex* pindexNew)
1009
if (pindexNew->bnChainWork > bnBestInvalidWork)
1011
bnBestInvalidWork = pindexNew->bnChainWork;
1012
CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
1015
printf("InvalidChainFound: invalid block=%s height=%d work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());
1016
printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1017
if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1018
printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
1031
bool CTransaction::DisconnectInputs(CTxDB& txdb)
1033
// Relinquish previous transactions' spent pointers
1036
foreach(const CTxIn& txin, vin)
1038
COutPoint prevout = txin.prevout;
1040
// Get prev txindex from disk
1042
if (!txdb.ReadTxIndex(prevout.hash, txindex))
1043
return error("DisconnectInputs() : ReadTxIndex failed");
1045
if (prevout.n >= txindex.vSpent.size())
1046
return error("DisconnectInputs() : prevout.n out of range");
1048
// Mark outpoint as not spent
1049
txindex.vSpent[prevout.n].SetNull();
1052
if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1053
return error("DisconnectInputs() : UpdateTxIndex failed");
1057
// Remove transaction from index
1058
if (!txdb.EraseTxIndex(*this))
1059
return error("DisconnectInputs() : EraseTxPos failed");
1065
bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
1066
CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
1068
// Take over previous transactions' spent pointers
1072
for (int i = 0; i < vin.size(); i++)
1074
COutPoint prevout = vin[i].prevout;
1079
if (fMiner && mapTestPool.count(prevout.hash))
1081
// Get txindex from current proposed changes
1082
txindex = mapTestPool[prevout.hash];
1086
// Read txindex from txdb
1087
fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1089
if (!fFound && (fBlock || fMiner))
1090
return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1093
CTransaction txPrev;
1094
if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1096
// Get prev tx from single transactions in memory
1097
CRITICAL_BLOCK(cs_mapTransactions)
1099
if (!mapTransactions.count(prevout.hash))
1100
return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1101
txPrev = mapTransactions[prevout.hash];
1104
txindex.vSpent.resize(txPrev.vout.size());
1108
// Get prev tx from disk
1109
if (!txPrev.ReadFromDisk(txindex.pos))
1110
return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1113
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1114
return error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str());
1116
// If prev is coinbase, check that it's matured
1117
if (txPrev.IsCoinBase())
1118
for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1119
if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1120
return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1123
if (!VerifySignature(txPrev, *this, i))
1124
return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1126
// Check for conflicts
1127
if (!txindex.vSpent[prevout.n].IsNull())
1128
return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
1130
// Check for negative or overflow input values
1131
nValueIn += txPrev.vout[prevout.n].nValue;
1132
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1133
return error("ConnectInputs() : txin values out of range");
1135
// Mark outpoints as spent
1136
txindex.vSpent[prevout.n] = posThisTx;
1141
if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1142
return error("ConnectInputs() : UpdateTxIndex failed");
1146
mapTestPool[prevout.hash] = txindex;
1150
if (nValueIn < GetValueOut())
1151
return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
1153
// Tally transaction fees
1154
int64 nTxFee = nValueIn - GetValueOut();
1156
return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
1157
if (nTxFee < nMinFee)
1160
if (!MoneyRange(nFees))
1161
return error("ConnectInputs() : nFees out of range");
1166
// Add transaction to disk index
1167
if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
1168
return error("ConnectInputs() : AddTxPos failed");
1172
// Add transaction to test pool
1173
mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1180
bool CTransaction::ClientConnectInputs()
1185
// Take over previous transactions' spent pointers
1186
CRITICAL_BLOCK(cs_mapTransactions)
1189
for (int i = 0; i < vin.size(); i++)
1191
// Get prev tx from single transactions in memory
1192
COutPoint prevout = vin[i].prevout;
1193
if (!mapTransactions.count(prevout.hash))
1195
CTransaction& txPrev = mapTransactions[prevout.hash];
1197
if (prevout.n >= txPrev.vout.size())
1201
if (!VerifySignature(txPrev, *this, i))
1202
return error("ConnectInputs() : VerifySignature failed");
1204
///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1205
///// this has to go away now that posNext is gone
1206
// // Check for conflicts
1207
// if (!txPrev.vout[prevout.n].posNext.IsNull())
1208
// return error("ConnectInputs() : prev tx already used");
1210
// // Flag outpoints as used
1211
// txPrev.vout[prevout.n].posNext = posThisTx;
1213
nValueIn += txPrev.vout[prevout.n].nValue;
1215
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1216
return error("ClientConnectInputs() : txin values out of range");
1218
if (GetValueOut() > nValueIn)
1228
bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1230
// Disconnect in reverse order
1231
for (int i = vtx.size()-1; i >= 0; i--)
1232
if (!vtx[i].DisconnectInputs(txdb))
1235
// Update block index on disk without changing it in memory.
1236
// The memory index structure will be changed after the db commits.
1239
CDiskBlockIndex blockindexPrev(pindex->pprev);
1240
blockindexPrev.hashNext = 0;
1241
if (!txdb.WriteBlockIndex(blockindexPrev))
1242
return error("DisconnectBlock() : WriteBlockIndex failed");
1248
bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1250
// Check it again in case a previous version let a bad block in
1254
//// issue here: it doesn't know the version
1255
unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1257
map<uint256, CTxIndex> mapUnused;
1259
foreach(CTransaction& tx, vtx)
1261
CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1262
nTxPos += ::GetSerializeSize(tx, SER_DISK);
1264
if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
1268
if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1271
// Update block index on disk without changing it in memory.
1272
// The memory index structure will be changed after the db commits.
1275
CDiskBlockIndex blockindexPrev(pindex->pprev);
1276
blockindexPrev.hashNext = pindex->GetBlockHash();
1277
if (!txdb.WriteBlockIndex(blockindexPrev))
1278
return error("ConnectBlock() : WriteBlockIndex failed");
1281
// Watch for transactions paying to me
1282
foreach(CTransaction& tx, vtx)
1283
AddToWalletIfMine(tx, this);
1290
bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1292
printf("REORGANIZE\n");
1295
CBlockIndex* pfork = pindexBest;
1296
CBlockIndex* plonger = pindexNew;
1297
while (pfork != plonger)
1299
while (plonger->nHeight > pfork->nHeight)
1300
if (!(plonger = plonger->pprev))
1301
return error("Reorganize() : plonger->pprev is null");
1302
if (pfork == plonger)
1304
if (!(pfork = pfork->pprev))
1305
return error("Reorganize() : pfork->pprev is null");
1308
// List of what to disconnect
1309
vector<CBlockIndex*> vDisconnect;
1310
for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1311
vDisconnect.push_back(pindex);
1313
// List of what to connect
1314
vector<CBlockIndex*> vConnect;
1315
for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1316
vConnect.push_back(pindex);
1317
reverse(vConnect.begin(), vConnect.end());
1319
// Disconnect shorter branch
1320
vector<CTransaction> vResurrect;
1321
foreach(CBlockIndex* pindex, vDisconnect)
1324
if (!block.ReadFromDisk(pindex))
1325
return error("Reorganize() : ReadFromDisk for disconnect failed");
1326
if (!block.DisconnectBlock(txdb, pindex))
1327
return error("Reorganize() : DisconnectBlock failed");
1329
// Queue memory transactions to resurrect
1330
foreach(const CTransaction& tx, block.vtx)
1331
if (!tx.IsCoinBase())
1332
vResurrect.push_back(tx);
1335
// Connect longer branch
1336
vector<CTransaction> vDelete;
1337
for (int i = 0; i < vConnect.size(); i++)
1339
CBlockIndex* pindex = vConnect[i];
1341
if (!block.ReadFromDisk(pindex))
1342
return error("Reorganize() : ReadFromDisk for connect failed");
1343
if (!block.ConnectBlock(txdb, pindex))
1347
return error("Reorganize() : ConnectBlock failed");
1350
// Queue memory transactions to delete
1351
foreach(const CTransaction& tx, block.vtx)
1352
vDelete.push_back(tx);
1354
if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1355
return error("Reorganize() : WriteHashBestChain failed");
1357
// Make sure it's successfully written to disk before changing memory structure
1358
if (!txdb.TxnCommit())
1359
return error("Reorganize() : TxnCommit failed");
1361
// Disconnect shorter branch
1362
foreach(CBlockIndex* pindex, vDisconnect)
1364
pindex->pprev->pnext = NULL;
1366
// Connect longer branch
1367
foreach(CBlockIndex* pindex, vConnect)
1369
pindex->pprev->pnext = pindex;
1371
// Resurrect memory transactions that were in the disconnected branch
1372
foreach(CTransaction& tx, vResurrect)
1373
tx.AcceptToMemoryPool(txdb, false);
1375
// Delete redundant memory transactions that are in the connected branch
1376
foreach(CTransaction& tx, vDelete)
1377
tx.RemoveFromMemoryPool();
1383
bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1385
uint256 hash = GetHash();
1388
if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1390
txdb.WriteHashBestChain(hash);
1391
if (!txdb.TxnCommit())
1392
return error("SetBestChain() : TxnCommit failed");
1393
pindexGenesisBlock = pindexNew;
1395
else if (hashPrevBlock == hashBestChain)
1397
// Adding to current best branch
1398
if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1401
InvalidChainFound(pindexNew);
1402
return error("SetBestChain() : ConnectBlock failed");
1404
if (!txdb.TxnCommit())
1405
return error("SetBestChain() : TxnCommit failed");
1407
// Add to current best branch
1408
pindexNew->pprev->pnext = pindexNew;
1410
// Delete redundant memory transactions
1411
foreach(CTransaction& tx, vtx)
1412
tx.RemoveFromMemoryPool();
1417
if (!Reorganize(txdb, pindexNew))
1420
InvalidChainFound(pindexNew);
1421
return error("SetBestChain() : Reorganize failed");
1426
hashBestChain = hash;
1427
pindexBest = pindexNew;
1428
nBestHeight = pindexBest->nHeight;
1429
bnBestChainWork = pindexNew->bnChainWork;
1430
nTimeBestReceived = GetTime();
1431
nTransactionsUpdated++;
1432
printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1438
bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1440
// Check for duplicate
1441
uint256 hash = GetHash();
1442
if (mapBlockIndex.count(hash))
1443
return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1445
// Construct new block index object
1446
CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1448
return error("AddToBlockIndex() : new CBlockIndex failed");
1449
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1450
pindexNew->phashBlock = &((*mi).first);
1451
map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1452
if (miPrev != mapBlockIndex.end())
1454
pindexNew->pprev = (*miPrev).second;
1455
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1457
pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1461
txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1462
if (!txdb.TxnCommit())
1466
if (pindexNew->bnChainWork > bnBestChainWork)
1467
if (!SetBestChain(txdb, pindexNew))
1472
if (pindexNew == pindexBest)
1474
// Notify UI to display prev block's coinbase if it was ours
1475
static uint256 hashPrevBestCoinBase;
1476
CRITICAL_BLOCK(cs_mapWallet)
1477
vWalletUpdated.push_back(hashPrevBestCoinBase);
1478
hashPrevBestCoinBase = vtx[0].GetHash();
1488
bool CBlock::CheckBlock() const
1490
// These are checks that are independent of context
1491
// that can be verified before saving an orphan block.
1494
if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1495
return error("CheckBlock() : size limits failed");
1497
// Check proof of work matches claimed amount
1498
if (!CheckProofOfWork(GetHash(), nBits))
1499
return error("CheckBlock() : proof of work failed");
1502
if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1503
return error("CheckBlock() : block timestamp too far in the future");
1505
// First transaction must be coinbase, the rest must not be
1506
if (vtx.empty() || !vtx[0].IsCoinBase())
1507
return error("CheckBlock() : first tx is not coinbase");
1508
for (int i = 1; i < vtx.size(); i++)
1509
if (vtx[i].IsCoinBase())
1510
return error("CheckBlock() : more than one coinbase");
1512
// Check transactions
1513
foreach(const CTransaction& tx, vtx)
1514
if (!tx.CheckTransaction())
1515
return error("CheckBlock() : CheckTransaction failed");
1517
// Check that it's not full of nonstandard transactions
1518
if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1519
return error("CheckBlock() : too many nonstandard transactions");
1522
if (hashMerkleRoot != BuildMerkleTree())
1523
return error("CheckBlock() : hashMerkleRoot mismatch");
1528
bool CBlock::AcceptBlock()
1530
// Check for duplicate
1531
uint256 hash = GetHash();
1532
if (mapBlockIndex.count(hash))
1533
return error("AcceptBlock() : block already in mapBlockIndex");
1535
// Get prev block index
1536
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1537
if (mi == mapBlockIndex.end())
1538
return error("AcceptBlock() : prev block not found");
1539
CBlockIndex* pindexPrev = (*mi).second;
1540
int nHeight = pindexPrev->nHeight+1;
1542
// Check proof of work
1543
if (nBits != GetNextWorkRequired(pindexPrev))
1544
return error("AcceptBlock() : incorrect proof of work");
1546
// Check timestamp against prev
1547
if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1548
return error("AcceptBlock() : block's timestamp is too early");
1550
// Check that all transactions are finalized
1551
foreach(const CTransaction& tx, vtx)
1552
if (!tx.IsFinal(nHeight, GetBlockTime()))
1553
return error("AcceptBlock() : contains a non-final transaction");
1555
// Check that the block chain matches the known block chain up to a checkpoint
1557
if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
1558
(nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
1559
(nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
1560
(nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
1561
(nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")))
1562
return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1564
// Write block to history file
1565
if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1566
return error("AcceptBlock() : out of disk space");
1567
unsigned int nFile = -1;
1568
unsigned int nBlockPos = 0;
1569
if (!WriteToDisk(nFile, nBlockPos))
1570
return error("AcceptBlock() : WriteToDisk failed");
1571
if (!AddToBlockIndex(nFile, nBlockPos))
1572
return error("AcceptBlock() : AddToBlockIndex failed");
1574
// Relay inventory, but don't relay old inventory during initial block download
1575
if (hashBestChain == hash)
1576
CRITICAL_BLOCK(cs_vNodes)
1577
foreach(CNode* pnode, vNodes)
1578
if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 55000))
1579
pnode->PushInventory(CInv(MSG_BLOCK, hash));
1584
bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1586
// Check for duplicate
1587
uint256 hash = pblock->GetHash();
1588
if (mapBlockIndex.count(hash))
1589
return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1590
if (mapOrphanBlocks.count(hash))
1591
return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1593
// Preliminary checks
1594
if (!pblock->CheckBlock())
1595
return error("ProcessBlock() : CheckBlock FAILED");
1597
// If don't already have its previous block, shunt it off to holding area until we get it
1598
if (!mapBlockIndex.count(pblock->hashPrevBlock))
1600
printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1601
CBlock* pblock2 = new CBlock(*pblock);
1602
mapOrphanBlocks.insert(make_pair(hash, pblock2));
1603
mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1605
// Ask this guy to fill in what we're missing
1607
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1612
if (!pblock->AcceptBlock())
1613
return error("ProcessBlock() : AcceptBlock FAILED");
1615
// Recursively process any orphan blocks that depended on this one
1616
vector<uint256> vWorkQueue;
1617
vWorkQueue.push_back(hash);
1618
for (int i = 0; i < vWorkQueue.size(); i++)
1620
uint256 hashPrev = vWorkQueue[i];
1621
for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1622
mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1625
CBlock* pblockOrphan = (*mi).second;
1626
if (pblockOrphan->AcceptBlock())
1627
vWorkQueue.push_back(pblockOrphan->GetHash());
1628
mapOrphanBlocks.erase(pblockOrphan->GetHash());
1629
delete pblockOrphan;
1631
mapOrphanBlocksByPrev.erase(hashPrev);
1634
printf("ProcessBlock: ACCEPTED\n");
1645
template<typename Stream>
1646
bool ScanMessageStart(Stream& s)
1648
// Scan ahead to the next pchMessageStart, which should normally be immediately
1649
// at the file pointer. Leaves file pointer at end of pchMessageStart.
1651
short prevmask = s.exceptions(0);
1652
const char* p = BEGIN(pchMessageStart);
1662
s.exceptions(prevmask);
1666
p = BEGIN(pchMessageStart);
1669
if (++p == END(pchMessageStart))
1672
s.exceptions(prevmask);
1681
s.exceptions(prevmask);
1686
bool CheckDiskSpace(uint64 nAdditionalBytes)
1688
uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1690
// Check for 15MB because database could create another 10MB log file at any time
1691
if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1694
string strMessage = _("Warning: Disk space is low ");
1695
strMiscWarning = strMessage;
1696
printf("*** %s\n", strMessage.c_str());
1697
ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1698
CreateThread(Shutdown, NULL);
1704
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1708
FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1711
if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1713
if (fseek(file, nBlockPos, SEEK_SET) != 0)
1722
static unsigned int nCurrentBlockFile = 1;
1724
FILE* AppendBlockFile(unsigned int& nFileRet)
1729
FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1732
if (fseek(file, 0, SEEK_END) != 0)
1734
// FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1735
if (ftell(file) < 0x7F000000 - MAX_SIZE)
1737
nFileRet = nCurrentBlockFile;
1741
nCurrentBlockFile++;
1745
bool LoadBlockIndex(bool fAllowNew)
1749
hashGenesisBlock = uint256("0x0000000224b1593e3ff16a0e3b61285bbc393a39f78c8aa48c456142671f7110");
1750
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1751
pchMessageStart[0] = 0xfa;
1752
pchMessageStart[1] = 0xbf;
1753
pchMessageStart[2] = 0xb5;
1754
pchMessageStart[3] = 0xda;
1761
if (!txdb.LoadBlockIndex())
1766
// Init with genesis block
1768
if (mapBlockIndex.empty())
1774
// CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1775
// CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1776
// CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1777
// CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1778
// vMerkleTree: 4a5e1e
1781
const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1783
txNew.vin.resize(1);
1784
txNew.vout.resize(1);
1785
txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1786
txNew.vout[0].nValue = 50 * COIN;
1787
txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1789
block.vtx.push_back(txNew);
1790
block.hashPrevBlock = 0;
1791
block.hashMerkleRoot = block.BuildMerkleTree();
1793
block.nTime = 1231006505;
1794
block.nBits = 0x1d00ffff;
1795
block.nNonce = 2083236893;
1799
block.nTime = 1279232055;
1800
block.nBits = 0x1d07fff8;
1801
block.nNonce = 81622180;
1805
printf("%s\n", block.GetHash().ToString().c_str());
1806
printf("%s\n", hashGenesisBlock.ToString().c_str());
1807
printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1808
assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1810
assert(block.GetHash() == hashGenesisBlock);
1812
// Start new block file
1814
unsigned int nBlockPos;
1815
if (!block.WriteToDisk(nFile, nBlockPos))
1816
return error("LoadBlockIndex() : writing genesis block to disk failed");
1817
if (!block.AddToBlockIndex(nFile, nBlockPos))
1818
return error("LoadBlockIndex() : genesis block not accepted");
1826
void PrintBlockTree()
1828
// precompute tree structure
1829
map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1830
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1832
CBlockIndex* pindex = (*mi).second;
1833
mapNext[pindex->pprev].push_back(pindex);
1835
//while (rand() % 3 == 0)
1836
// mapNext[pindex->pprev].push_back(pindex);
1839
vector<pair<int, CBlockIndex*> > vStack;
1840
vStack.push_back(make_pair(0, pindexGenesisBlock));
1843
while (!vStack.empty())
1845
int nCol = vStack.back().first;
1846
CBlockIndex* pindex = vStack.back().second;
1849
// print split or gap
1850
if (nCol > nPrevCol)
1852
for (int i = 0; i < nCol-1; i++)
1856
else if (nCol < nPrevCol)
1858
for (int i = 0; i < nCol; i++)
1865
for (int i = 0; i < nCol; i++)
1870
block.ReadFromDisk(pindex);
1871
printf("%d (%u,%u) %s %s tx %d",
1875
block.GetHash().ToString().substr(0,20).c_str(),
1876
DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1879
CRITICAL_BLOCK(cs_mapWallet)
1881
if (mapWallet.count(block.vtx[0].GetHash()))
1883
CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1884
printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1890
// put the main timechain first
1891
vector<CBlockIndex*>& vNext = mapNext[pindex];
1892
for (int i = 0; i < vNext.size(); i++)
1894
if (vNext[i]->pnext)
1896
swap(vNext[0], vNext[i]);
1902
for (int i = 0; i < vNext.size(); i++)
1903
vStack.push_back(make_pair(nCol+i, vNext[i]));
1916
//////////////////////////////////////////////////////////////////////////////
1921
map<uint256, CAlert> mapAlerts;
1922
CCriticalSection cs_mapAlerts;
1924
string GetWarnings(string strFor)
1927
string strStatusBar;
1929
if (GetBoolArg("-testsafemode"))
1932
// Misc warnings like out of disk space and clock is wrong
1933
if (strMiscWarning != "")
1936
strStatusBar = strMiscWarning;
1939
// Longer invalid proof-of-work chain
1940
if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1943
strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1947
CRITICAL_BLOCK(cs_mapAlerts)
1949
foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1951
const CAlert& alert = item.second;
1952
if (alert.AppliesToMe() && alert.nPriority > nPriority)
1954
nPriority = alert.nPriority;
1955
strStatusBar = alert.strStatusBar;
1960
if (strFor == "statusbar")
1961
return strStatusBar;
1962
else if (strFor == "rpc")
1964
assert(("GetWarnings() : invalid parameter", false));
1968
bool CAlert::ProcessAlert()
1970
if (!CheckSignature())
1975
CRITICAL_BLOCK(cs_mapAlerts)
1977
// Cancel previous alerts
1978
for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1980
const CAlert& alert = (*mi).second;
1983
printf("cancelling alert %d\n", alert.nID);
1984
mapAlerts.erase(mi++);
1986
else if (!alert.IsInEffect())
1988
printf("expiring alert %d\n", alert.nID);
1989
mapAlerts.erase(mi++);
1995
// Check if this alert has been cancelled
1996
foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1998
const CAlert& alert = item.second;
1999
if (alert.Cancels(*this))
2001
printf("alert already cancelled by %d\n", alert.nID);
2007
mapAlerts.insert(make_pair(GetHash(), *this));
2010
printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2022
//////////////////////////////////////////////////////////////////////////////
2028
bool AlreadyHave(CTxDB& txdb, const CInv& inv)
2032
case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
2033
case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
2035
// Don't know what it is, just say we already got one
2042
// The message start string is designed to be unlikely to occur in normal data.
2043
// The characters are rarely used upper ascii, not valid as UTF-8, and produce
2044
// a large 4-byte int at any alignment.
2045
char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2048
bool ProcessMessages(CNode* pfrom)
2050
CDataStream& vRecv = pfrom->vRecv;
2054
// printf("ProcessMessages(%u bytes)\n", vRecv.size());
2058
// (4) message start
2067
// Scan for message start
2068
CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2069
int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2070
if (vRecv.end() - pstart < nHeaderSize)
2072
if (vRecv.size() > nHeaderSize)
2074
printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2075
vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2079
if (pstart - vRecv.begin() > 0)
2080
printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2081
vRecv.erase(vRecv.begin(), pstart);
2084
vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2089
printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2092
string strCommand = hdr.GetCommand();
2095
unsigned int nMessageSize = hdr.nMessageSize;
2096
if (nMessageSize > MAX_SIZE)
2098
printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2101
if (nMessageSize > vRecv.size())
2103
// Rewind and wait for rest of message
2104
vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2109
if (vRecv.GetVersion() >= 209)
2111
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2112
unsigned int nChecksum = 0;
2113
memcpy(&nChecksum, &hash, sizeof(nChecksum));
2114
if (nChecksum != hdr.nChecksum)
2116
printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2117
strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2122
// Copy message to its own buffer
2123
CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2124
vRecv.ignore(nMessageSize);
2130
CRITICAL_BLOCK(cs_main)
2131
fRet = ProcessMessage(pfrom, strCommand, vMsg);
2135
catch (std::ios_base::failure& e)
2137
if (strstr(e.what(), "end of data"))
2139
// Allow exceptions from underlength message on vRecv
2140
printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
2142
else if (strstr(e.what(), "size too large"))
2144
// Allow exceptions from overlong size
2145
printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2149
PrintExceptionContinue(&e, "ProcessMessage()");
2152
catch (std::exception& e) {
2153
PrintExceptionContinue(&e, "ProcessMessage()");
2155
PrintExceptionContinue(NULL, "ProcessMessage()");
2159
printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2169
bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2171
static map<unsigned int, vector<unsigned char> > mapReuseKey;
2172
RandAddSeedPerfmon();
2174
printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2175
printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2176
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2178
printf("dropmessagestest DROPPING RECV MESSAGE\n");
2186
if (strCommand == "version")
2188
// Each connection can only send one version message
2189
if (pfrom->nVersion != 0)
2196
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2197
if (pfrom->nVersion == 10300)
2198
pfrom->nVersion = 300;
2199
if (pfrom->nVersion >= 106 && !vRecv.empty())
2200
vRecv >> addrFrom >> nNonce;
2201
if (pfrom->nVersion >= 106 && !vRecv.empty())
2202
vRecv >> pfrom->strSubVer;
2203
if (pfrom->nVersion >= 209 && !vRecv.empty())
2204
vRecv >> pfrom->nStartingHeight;
2206
if (pfrom->nVersion == 0)
2209
// Disconnect if we connected to ourself
2210
if (nNonce == nLocalHostNonce && nNonce > 1)
2212
printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2213
pfrom->fDisconnect = true;
2217
pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2219
AddTimeData(pfrom->addr.ip, nTime);
2222
if (pfrom->nVersion >= 209)
2223
pfrom->PushMessage("verack");
2224
pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2225
if (pfrom->nVersion < 209)
2226
pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2228
if (!pfrom->fInbound)
2230
// Advertise our address
2231
if (addrLocalHost.IsRoutable() && !fUseProxy)
2233
CAddress addr(addrLocalHost);
2234
addr.nTime = GetAdjustedTime();
2235
pfrom->PushAddress(addr);
2238
// Get recent addresses
2239
if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2241
pfrom->PushMessage("getaddr");
2242
pfrom->fGetAddr = true;
2246
// Ask the first connected node for block updates
2247
static int nAskedForBlocks;
2248
if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
2251
pfrom->PushGetBlocks(pindexBest, uint256(0));
2255
CRITICAL_BLOCK(cs_mapAlerts)
2256
foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2257
item.second.RelayTo(pfrom);
2259
pfrom->fSuccessfullyConnected = true;
2261
printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2265
else if (pfrom->nVersion == 0)
2267
// Must have a version message before anything else
2272
else if (strCommand == "verack")
2274
pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2278
else if (strCommand == "addr")
2280
vector<CAddress> vAddr;
2283
// Don't want addr from older versions unless seeding
2284
if (pfrom->nVersion < 209)
2286
if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2288
if (vAddr.size() > 1000)
2289
return error("message addr size() = %d", vAddr.size());
2291
// Store the new addresses
2292
int64 nNow = GetAdjustedTime();
2293
int64 nSince = nNow - 10 * 60;
2294
foreach(CAddress& addr, vAddr)
2298
// ignore IPv6 for now, since it isn't implemented anyway
2301
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2302
addr.nTime = nNow - 5 * 24 * 60 * 60;
2303
AddAddress(addr, 2 * 60 * 60);
2304
pfrom->AddAddressKnown(addr);
2305
if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2307
// Relay to a limited number of other nodes
2308
CRITICAL_BLOCK(cs_vNodes)
2310
// Use deterministic randomness to send to the same nodes for 24 hours
2311
// at a time so the setAddrKnowns of the chosen nodes prevent repeats
2312
static uint256 hashSalt;
2314
RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2315
uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2316
hashRand = Hash(BEGIN(hashRand), END(hashRand));
2317
multimap<uint256, CNode*> mapMix;
2318
foreach(CNode* pnode, vNodes)
2320
if (pnode->nVersion < 31402)
2322
unsigned int nPointer;
2323
memcpy(&nPointer, &pnode, sizeof(nPointer));
2324
uint256 hashKey = hashRand ^ nPointer;
2325
hashKey = Hash(BEGIN(hashKey), END(hashKey));
2326
mapMix.insert(make_pair(hashKey, pnode));
2328
int nRelayNodes = 2;
2329
for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2330
((*mi).second)->PushAddress(addr);
2334
if (vAddr.size() < 1000)
2335
pfrom->fGetAddr = false;
2339
else if (strCommand == "inv")
2343
if (vInv.size() > 50000)
2344
return error("message inv size() = %d", vInv.size());
2347
foreach(const CInv& inv, vInv)
2351
pfrom->AddInventoryKnown(inv);
2353
bool fAlreadyHave = AlreadyHave(txdb, inv);
2354
printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2358
else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2359
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2361
// Track requests for our stuff
2362
CRITICAL_BLOCK(cs_mapRequestCount)
2364
map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2365
if (mi != mapRequestCount.end())
2372
else if (strCommand == "getdata")
2376
if (vInv.size() > 50000)
2377
return error("message getdata size() = %d", vInv.size());
2379
foreach(const CInv& inv, vInv)
2383
printf("received getdata for: %s\n", inv.ToString().c_str());
2385
if (inv.type == MSG_BLOCK)
2387
// Send block from disk
2388
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2389
if (mi != mapBlockIndex.end())
2392
block.ReadFromDisk((*mi).second);
2393
pfrom->PushMessage("block", block);
2395
// Trigger them to send a getblocks request for the next batch of inventory
2396
if (inv.hash == pfrom->hashContinue)
2398
// Bypass PushInventory, this must send even if redundant,
2399
// and we want it right after the last block so they don't
2400
// wait for other stuff first.
2402
vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2403
pfrom->PushMessage("inv", vInv);
2404
pfrom->hashContinue = 0;
2408
else if (inv.IsKnownType())
2410
// Send stream from relay memory
2411
CRITICAL_BLOCK(cs_mapRelay)
2413
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2414
if (mi != mapRelay.end())
2415
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2419
// Track requests for our stuff
2420
CRITICAL_BLOCK(cs_mapRequestCount)
2422
map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2423
if (mi != mapRequestCount.end())
2430
else if (strCommand == "getblocks")
2432
CBlockLocator locator;
2434
vRecv >> locator >> hashStop;
2436
// Find the last block the caller has in the main chain
2437
CBlockIndex* pindex = locator.GetBlockIndex();
2439
// Send the rest of the chain
2441
pindex = pindex->pnext;
2442
int nLimit = 500 + locator.GetDistanceBack();
2443
printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2444
for (; pindex; pindex = pindex->pnext)
2446
if (pindex->GetBlockHash() == hashStop)
2448
printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2451
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2454
// When this block is requested, we'll send an inv that'll make them
2455
// getblocks the next batch of inventory.
2456
printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2457
pfrom->hashContinue = pindex->GetBlockHash();
2464
else if (strCommand == "getheaders")
2466
CBlockLocator locator;
2468
vRecv >> locator >> hashStop;
2470
CBlockIndex* pindex = NULL;
2471
if (locator.IsNull())
2473
// If locator is null, return the hashStop block
2474
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2475
if (mi == mapBlockIndex.end())
2477
pindex = (*mi).second;
2481
// Find the last block the caller has in the main chain
2482
pindex = locator.GetBlockIndex();
2484
pindex = pindex->pnext;
2487
vector<CBlock> vHeaders;
2488
int nLimit = 2000 + locator.GetDistanceBack();
2489
printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2490
for (; pindex; pindex = pindex->pnext)
2492
vHeaders.push_back(pindex->GetBlockHeader());
2493
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2496
pfrom->PushMessage("headers", vHeaders);
2500
else if (strCommand == "tx")
2502
vector<uint256> vWorkQueue;
2503
CDataStream vMsg(vRecv);
2507
CInv inv(MSG_TX, tx.GetHash());
2508
pfrom->AddInventoryKnown(inv);
2510
bool fMissingInputs = false;
2511
if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2513
AddToWalletIfMine(tx, NULL);
2514
RelayMessage(inv, vMsg);
2515
mapAlreadyAskedFor.erase(inv);
2516
vWorkQueue.push_back(inv.hash);
2518
// Recursively process any orphan transactions that depended on this one
2519
for (int i = 0; i < vWorkQueue.size(); i++)
2521
uint256 hashPrev = vWorkQueue[i];
2522
for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2523
mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2526
const CDataStream& vMsg = *((*mi).second);
2528
CDataStream(vMsg) >> tx;
2529
CInv inv(MSG_TX, tx.GetHash());
2531
if (tx.AcceptToMemoryPool(true))
2533
printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2534
AddToWalletIfMine(tx, NULL);
2535
RelayMessage(inv, vMsg);
2536
mapAlreadyAskedFor.erase(inv);
2537
vWorkQueue.push_back(inv.hash);
2542
foreach(uint256 hash, vWorkQueue)
2543
EraseOrphanTx(hash);
2545
else if (fMissingInputs)
2547
printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2553
else if (strCommand == "block")
2558
printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2561
CInv inv(MSG_BLOCK, block.GetHash());
2562
pfrom->AddInventoryKnown(inv);
2564
if (ProcessBlock(pfrom, &block))
2565
mapAlreadyAskedFor.erase(inv);
2569
else if (strCommand == "getaddr")
2571
// Nodes rebroadcast an addr every 24 hours
2572
pfrom->vAddrToSend.clear();
2573
int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2574
CRITICAL_BLOCK(cs_mapAddresses)
2576
unsigned int nCount = 0;
2577
foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2579
const CAddress& addr = item.second;
2580
if (addr.nTime > nSince)
2583
foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2585
const CAddress& addr = item.second;
2586
if (addr.nTime > nSince && GetRand(nCount) < 2500)
2587
pfrom->PushAddress(addr);
2593
else if (strCommand == "checkorder")
2598
if (!GetBoolArg("-allowreceivebyip"))
2600
pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2607
/// we have a chance to check the order here
2609
// Keep giving the same key to the same ip until they use it
2610
if (!mapReuseKey.count(pfrom->addr.ip))
2611
mapReuseKey[pfrom->addr.ip] = GetKeyFromKeyPool();
2613
// Send back approval of order and pubkey to use
2614
CScript scriptPubKey;
2615
scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2616
pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2620
else if (strCommand == "submitorder")
2625
if (!GetBoolArg("-allowreceivebyip"))
2627
pfrom->PushMessage("reply", hashReply, (int)2);
2633
wtxNew.fFromMe = false;
2636
if (!wtxNew.AcceptWalletTransaction())
2638
pfrom->PushMessage("reply", hashReply, (int)1);
2639
return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2641
wtxNew.fTimeReceivedIsTxTime = true;
2642
AddToWallet(wtxNew);
2643
wtxNew.RelayWalletTransaction();
2644
mapReuseKey.erase(pfrom->addr.ip);
2646
// Send back confirmation
2647
pfrom->PushMessage("reply", hashReply, (int)0);
2651
else if (strCommand == "reply")
2656
CRequestTracker tracker;
2657
CRITICAL_BLOCK(pfrom->cs_mapRequests)
2659
map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2660
if (mi != pfrom->mapRequests.end())
2662
tracker = (*mi).second;
2663
pfrom->mapRequests.erase(mi);
2666
if (!tracker.IsNull())
2667
tracker.fn(tracker.param1, vRecv);
2671
else if (strCommand == "ping")
2676
else if (strCommand == "alert")
2681
if (alert.ProcessAlert())
2684
pfrom->setKnown.insert(alert.GetHash());
2685
CRITICAL_BLOCK(cs_vNodes)
2686
foreach(CNode* pnode, vNodes)
2687
alert.RelayTo(pnode);
2694
// Ignore unknown commands for extensibility
2698
// Update the last seen time for this node's address
2699
if (pfrom->fNetworkNode)
2700
if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2701
AddressCurrentlyConnected(pfrom->addr);
2715
bool SendMessages(CNode* pto, bool fSendTrickle)
2717
CRITICAL_BLOCK(cs_main)
2719
// Don't send anything until we get their version message
2720
if (pto->nVersion == 0)
2724
if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2725
pto->PushMessage("ping");
2727
// Resend wallet transactions that haven't gotten in a block yet
2728
ResendWalletTransactions();
2730
// Address refresh broadcast
2731
static int64 nLastRebroadcast;
2732
if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2734
nLastRebroadcast = GetTime();
2735
CRITICAL_BLOCK(cs_vNodes)
2737
foreach(CNode* pnode, vNodes)
2739
// Periodically clear setAddrKnown to allow refresh broadcasts
2740
pnode->setAddrKnown.clear();
2742
// Rebroadcast our address
2743
if (addrLocalHost.IsRoutable() && !fUseProxy)
2745
CAddress addr(addrLocalHost);
2746
addr.nTime = GetAdjustedTime();
2747
pnode->PushAddress(addr);
2753
// Clear out old addresses periodically so it's not too much work at once
2754
static int64 nLastClear;
2755
if (nLastClear == 0)
2756
nLastClear = GetTime();
2757
if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2759
nLastClear = GetTime();
2760
CRITICAL_BLOCK(cs_mapAddresses)
2763
int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2764
for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2765
mi != mapAddresses.end();)
2767
const CAddress& addr = (*mi).second;
2768
if (addr.nTime < nSince)
2770
if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2772
addrdb.EraseAddress(addr);
2773
mapAddresses.erase(mi++);
2787
vector<CAddress> vAddr;
2788
vAddr.reserve(pto->vAddrToSend.size());
2789
foreach(const CAddress& addr, pto->vAddrToSend)
2791
// returns true if wasn't already contained in the set
2792
if (pto->setAddrKnown.insert(addr).second)
2794
vAddr.push_back(addr);
2795
// receiver rejects addr messages larger than 1000
2796
if (vAddr.size() >= 1000)
2798
pto->PushMessage("addr", vAddr);
2803
pto->vAddrToSend.clear();
2805
pto->PushMessage("addr", vAddr);
2810
// Message: inventory
2813
vector<CInv> vInvWait;
2814
CRITICAL_BLOCK(pto->cs_inventory)
2816
vInv.reserve(pto->vInventoryToSend.size());
2817
vInvWait.reserve(pto->vInventoryToSend.size());
2818
foreach(const CInv& inv, pto->vInventoryToSend)
2820
if (pto->setInventoryKnown.count(inv))
2823
// trickle out tx inv to protect privacy
2824
if (inv.type == MSG_TX && !fSendTrickle)
2826
// 1/4 of tx invs blast to all immediately
2827
static uint256 hashSalt;
2829
RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2830
uint256 hashRand = inv.hash ^ hashSalt;
2831
hashRand = Hash(BEGIN(hashRand), END(hashRand));
2832
bool fTrickleWait = ((hashRand & 3) != 0);
2834
// always trickle our own transactions
2837
TRY_CRITICAL_BLOCK(cs_mapWallet)
2839
map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
2840
if (mi != mapWallet.end())
2842
CWalletTx& wtx = (*mi).second;
2844
fTrickleWait = true;
2851
vInvWait.push_back(inv);
2856
// returns true if wasn't already contained in the set
2857
if (pto->setInventoryKnown.insert(inv).second)
2859
vInv.push_back(inv);
2860
if (vInv.size() >= 1000)
2862
pto->PushMessage("inv", vInv);
2867
pto->vInventoryToSend = vInvWait;
2870
pto->PushMessage("inv", vInv);
2876
vector<CInv> vGetData;
2877
int64 nNow = GetTime() * 1000000;
2879
while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2881
const CInv& inv = (*pto->mapAskFor.begin()).second;
2882
if (!AlreadyHave(txdb, inv))
2884
printf("sending getdata: %s\n", inv.ToString().c_str());
2885
vGetData.push_back(inv);
2886
if (vGetData.size() >= 1000)
2888
pto->PushMessage("getdata", vGetData);
2892
pto->mapAskFor.erase(pto->mapAskFor.begin());
2894
if (!vGetData.empty())
2895
pto->PushMessage("getdata", vGetData);
2914
//////////////////////////////////////////////////////////////////////////////
2919
void GenerateBitcoins(bool fGenerate)
2921
if (fGenerateBitcoins != fGenerate)
2923
fGenerateBitcoins = fGenerate;
2924
CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
2927
if (fGenerateBitcoins)
2929
int nProcessors = boost::thread::hardware_concurrency();
2930
printf("%d processors\n", nProcessors);
2931
if (nProcessors < 1)
2933
if (fLimitProcessors && nProcessors > nLimitProcessors)
2934
nProcessors = nLimitProcessors;
2935
int nAddThreads = nProcessors - vnThreadsRunning[3];
2936
printf("Starting %d BitcoinMiner threads\n", nAddThreads);
2937
for (int i = 0; i < nAddThreads; i++)
2939
if (!CreateThread(ThreadBitcoinMiner, NULL))
2940
printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
2946
void ThreadBitcoinMiner(void* parg)
2950
vnThreadsRunning[3]++;
2952
vnThreadsRunning[3]--;
2954
catch (std::exception& e) {
2955
vnThreadsRunning[3]--;
2956
PrintException(&e, "ThreadBitcoinMiner()");
2958
vnThreadsRunning[3]--;
2959
PrintException(NULL, "ThreadBitcoinMiner()");
2961
UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
2963
if (vnThreadsRunning[3] == 0)
2965
printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
2968
#if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE)
2969
void CallCPUID(int in, int& aret, int& cret)
2973
"mov %2, %%eax; " // in into eax
2975
"mov %%eax, %0;" // eax into a
2976
"mov %%ecx, %1;" // ecx into c
2977
:"=r"(a),"=r"(c) /* output */
2978
:"r"(in) /* input */
2979
:"%eax","%ecx" /* clobbered register */
2985
bool Detect128BitSSE2()
2988
CallCPUID(0, a, nBrand);
2989
bool fIntel = (nBrand == 0x6c65746e); // ntel
2990
bool fAMD = (nBrand == 0x444d4163); // cAMD
2994
unsigned int nStepping : 4;
2995
unsigned int nModel : 4;
2996
unsigned int nFamily : 4;
2997
unsigned int nProcessorType : 2;
2998
unsigned int nUnused : 2;
2999
unsigned int nExtendedModel : 4;
3000
unsigned int nExtendedFamily : 8;
3004
memcpy(&cpu, &a, sizeof(cpu));
3005
int nFamily = cpu.nExtendedFamily + cpu.nFamily;
3006
int nModel = cpu.nExtendedModel*16 + cpu.nModel;
3008
// We need Intel Nehalem or AMD K10 or better for 128bit SSE2
3009
// Nehalem = i3/i5/i7 and some Xeon
3010
// K10 = Opterons with 4 or more cores, Phenom, Phenom II, Athlon II
3011
// Intel Core i5 family 6, model 26 or 30
3012
// Intel Core i7 family 6, model 26 or 30
3013
// Intel Core i3 family 6, model 37
3014
// AMD Phenom family 16, model 10
3015
bool fUseSSE2 = ((fIntel && nFamily * 10000 + nModel >= 60026) ||
3016
(fAMD && nFamily * 10000 + nModel >= 160010));
3018
// AMD reports a lower model number in 64-bit mode
3019
if (fAMD && sizeof(void*) > 4 && nFamily * 10000 + nModel >= 160000)
3022
static bool fPrinted;
3026
printf("CPUID %08x family %d, model %d, stepping %d, fUseSSE2=%d\n", nBrand, nFamily, nModel, cpu.nStepping, fUseSSE2);
3031
bool Detect128BitSSE2() { return false; }
3034
int FormatHashBlocks(void* pbuffer, unsigned int len)
3036
unsigned char* pdata = (unsigned char*)pbuffer;
3037
unsigned int blocks = 1 + ((len + 8) / 64);
3038
unsigned char* pend = pdata + 64 * blocks;
3039
memset(pdata + len, 0, 64 * blocks - len);
3041
unsigned int bits = len * 8;
3042
pend[-1] = (bits >> 0) & 0xff;
3043
pend[-2] = (bits >> 8) & 0xff;
3044
pend[-3] = (bits >> 16) & 0xff;
3045
pend[-4] = (bits >> 24) & 0xff;
3049
using CryptoPP::ByteReverse;
3051
static const unsigned int pSHA256InitState[8] =
3052
{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3054
inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3056
memcpy(pstate, pinit, 32);
3057
CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
3061
// ScanHash scans nonces looking for a hash with at least some zero bits.
3062
// It operates on big endian data. Caller does the byte reversing.
3063
// All input buffers are 16-byte aligned. nNonce is usually preserved
3064
// between calls, but periodically or if nNonce is 0xffff0000 or above,
3065
// the block is rebuilt and nNonce starts over at zero.
3067
unsigned int ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3069
unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3073
// Hash pdata using pmidstate as the starting state into
3074
// preformatted buffer phash1, then hash phash1 into phash
3076
SHA256Transform(phash1, pdata, pmidstate);
3077
SHA256Transform(phash, phash1, pSHA256InitState);
3079
// Return the nonce if the hash has at least some zero bits,
3080
// caller will check if it has enough to reach the target
3081
if (((unsigned short*)phash)[14] == 0)
3084
// If nothing found after trying for a while, return -1
3085
if ((nNonce & 0xffff) == 0)
3087
nHashesDone = 0xffff+1;
3093
extern unsigned int ScanHash_4WaySSE2(char* pmidstate, char* pblock, char* phash1, char* phash, unsigned int& nHashesDone);
3101
set<uint256> setDependsOn;
3104
COrphan(CTransaction* ptxIn)
3112
printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3113
foreach(uint256 hash, setDependsOn)
3114
printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3119
CBlock* CreateNewBlock(CReserveKey& reservekey)
3121
CBlockIndex* pindexPrev = pindexBest;
3124
auto_ptr<CBlock> pblock(new CBlock());
3128
// Create coinbase tx
3130
txNew.vin.resize(1);
3131
txNew.vin[0].prevout.SetNull();
3132
txNew.vout.resize(1);
3133
txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3135
// Add our coinbase tx as first transaction
3136
pblock->vtx.push_back(txNew);
3138
// Collect memory pool transactions into the block
3140
CRITICAL_BLOCK(cs_main)
3141
CRITICAL_BLOCK(cs_mapTransactions)
3145
// Priority order to process transactions
3146
list<COrphan> vOrphan; // list memory doesn't move
3147
map<uint256, vector<COrphan*> > mapDependers;
3148
multimap<double, CTransaction*> mapPriority;
3149
for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
3151
CTransaction& tx = (*mi).second;
3152
if (tx.IsCoinBase() || !tx.IsFinal())
3155
COrphan* porphan = NULL;
3156
double dPriority = 0;
3157
foreach(const CTxIn& txin, tx.vin)
3159
// Read prev transaction
3160
CTransaction txPrev;
3162
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3164
// Has to wait for dependencies
3167
// Use list for automatic deletion
3168
vOrphan.push_back(COrphan(&tx));
3169
porphan = &vOrphan.back();
3171
mapDependers[txin.prevout.hash].push_back(porphan);
3172
porphan->setDependsOn.insert(txin.prevout.hash);
3175
int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3177
// Read block header
3180
if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
3182
map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(block.GetHash());
3183
if (it != mapBlockIndex.end())
3185
CBlockIndex* pindex = (*it).second;
3186
if (pindex->IsInMainChain())
3187
nConf = 1 + nBestHeight - pindex->nHeight;
3191
dPriority += (double)nValueIn * nConf;
3193
if (fDebug && GetBoolArg("-printpriority"))
3194
printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3197
// Priority is sum(valuein * age) / txsize
3198
dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
3201
porphan->dPriority = dPriority;
3203
mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3205
if (fDebug && GetBoolArg("-printpriority"))
3207
printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3214
// Collect transactions into block
3215
map<uint256, CTxIndex> mapTestPool;
3216
uint64 nBlockSize = 1000;
3217
int nBlockSigOps = 100;
3218
while (!mapPriority.empty())
3220
// Take highest priority transaction off priority queue
3221
double dPriority = -(*mapPriority.begin()).first;
3222
CTransaction& tx = *(*mapPriority.begin()).second;
3223
mapPriority.erase(mapPriority.begin());
3226
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3227
if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3229
int nTxSigOps = tx.GetSigOpCount();
3230
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3233
// Transaction fee required depends on block size
3234
bool fAllowFree = (nBlockSize + nTxSize < 4000 || dPriority > COIN * 144 / 250);
3235
int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);
3237
// Connecting shouldn't fail due to dependency on other memory pool transactions
3238
// because we're already processing them in order of dependency
3239
map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3240
if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
3242
swap(mapTestPool, mapTestPoolTmp);
3245
pblock->vtx.push_back(tx);
3246
nBlockSize += nTxSize;
3247
nBlockSigOps += nTxSigOps;
3249
// Add transactions that depend on this one to the priority queue
3250
uint256 hash = tx.GetHash();
3251
if (mapDependers.count(hash))
3253
foreach(COrphan* porphan, mapDependers[hash])
3255
if (!porphan->setDependsOn.empty())
3257
porphan->setDependsOn.erase(hash);
3258
if (porphan->setDependsOn.empty())
3259
mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3265
pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3268
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3269
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3270
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3271
pblock->nBits = GetNextWorkRequired(pindexPrev);
3274
return pblock.release();
3278
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime)
3280
// Update nExtraNonce
3281
int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3282
if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
3287
pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
3288
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3292
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3295
// Prebuild hash buffers
3302
uint256 hashPrevBlock;
3303
uint256 hashMerkleRoot;
3306
unsigned int nNonce;
3309
unsigned char pchPadding0[64];
3311
unsigned char pchPadding1[64];
3314
memset(&tmp, 0, sizeof(tmp));
3316
tmp.block.nVersion = pblock->nVersion;
3317
tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3318
tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3319
tmp.block.nTime = pblock->nTime;
3320
tmp.block.nBits = pblock->nBits;
3321
tmp.block.nNonce = pblock->nNonce;
3323
FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3324
FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3326
// Byte swap all the input buffer
3327
for (int i = 0; i < sizeof(tmp)/4; i++)
3328
((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3330
// Precalc the first half of the first hash, which stays constant
3331
SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3333
memcpy(pdata, &tmp.block, 128);
3334
memcpy(phash1, &tmp.hash1, 64);
3338
bool CheckWork(CBlock* pblock, CReserveKey& reservekey)
3340
uint256 hash = pblock->GetHash();
3341
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3343
if (hash > hashTarget)
3347
printf("BitcoinMiner:\n");
3348
printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3350
printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3351
printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3354
CRITICAL_BLOCK(cs_main)
3356
if (pblock->hashPrevBlock != hashBestChain)
3357
return error("BitcoinMiner : generated block is stale");
3359
// Remove key from key pool
3360
reservekey.KeepKey();
3362
// Track how many getdata requests this block gets
3363
CRITICAL_BLOCK(cs_mapRequestCount)
3364
mapRequestCount[pblock->GetHash()] = 0;
3366
// Process this block the same as if we had received it from another node
3367
if (!ProcessBlock(NULL, pblock))
3368
return error("BitcoinMiner : ProcessBlock, block not accepted");
3378
printf("BitcoinMiner started\n");
3379
SetThreadPriority(THREAD_PRIORITY_LOWEST);
3380
bool f4WaySSE2 = Detect128BitSSE2();
3381
if (mapArgs.count("-4way"))
3382
f4WaySSE2 = GetBoolArg(mapArgs["-4way"]);
3384
// Each thread has its own key and counter
3385
CReserveKey reservekey;
3386
unsigned int nExtraNonce = 0;
3387
int64 nPrevTime = 0;
3389
while (fGenerateBitcoins)
3391
if (AffinityBugWorkaround(ThreadBitcoinMiner))
3395
while (vNodes.empty() || IsInitialBlockDownload())
3400
if (!fGenerateBitcoins)
3408
unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3409
CBlockIndex* pindexPrev = pindexBest;
3411
auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3414
IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce, nPrevTime);
3416
printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3420
// Prebuild hash buffers
3422
char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3423
char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3424
char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3426
FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3428
unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3429
unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3435
int64 nStart = GetTime();
3436
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3438
uint256& hash = *alignup<16>(hashbuf);
3441
unsigned int nHashesDone = 0;
3442
unsigned int nNonceFound;
3446
// tcatm's 4-way 128-bit SSE2 SHA-256
3447
nNonceFound = ScanHash_4WaySSE2(pmidstate, pdata + 64, phash1, (char*)&hash, nHashesDone);
3451
nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1, (char*)&hash, nHashesDone);
3453
// Check if something found
3454
if (nNonceFound != -1)
3456
for (int i = 0; i < sizeof(hash)/4; i++)
3457
((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3459
if (hash <= hashTarget)
3462
pblock->nNonce = ByteReverse(nNonceFound);
3463
assert(hash == pblock->GetHash());
3465
SetThreadPriority(THREAD_PRIORITY_NORMAL);
3466
CheckWork(pblock.get(), reservekey);
3467
SetThreadPriority(THREAD_PRIORITY_LOWEST);
3473
static int64 nHashCounter;
3474
if (nHPSTimerStart == 0)
3476
nHPSTimerStart = GetTimeMillis();
3480
nHashCounter += nHashesDone;
3481
if (GetTimeMillis() - nHPSTimerStart > 4000)
3483
static CCriticalSection cs;
3486
if (GetTimeMillis() - nHPSTimerStart > 4000)
3488
dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3489
nHPSTimerStart = GetTimeMillis();
3491
string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3492
UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3493
static int64 nLogTime;
3494
if (GetTime() - nLogTime > 30 * 60)
3496
nLogTime = GetTime();
3497
printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3498
printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3504
// Check for stop or if block needs to be rebuilt
3507
if (!fGenerateBitcoins)
3509
if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3513
if (nBlockNonce >= 0xffff0000)
3515
if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3517
if (pindexPrev != pindexBest)
3520
// Update nTime every few seconds
3521
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3522
nBlockTime = ByteReverse(pblock->nTime);
3544
//////////////////////////////////////////////////////////////////////////////
3552
int64 nStart = GetTimeMillis();
3555
CRITICAL_BLOCK(cs_mapWallet)
3557
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3559
CWalletTx* pcoin = &(*it).second;
3560
if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())
3562
nTotal += pcoin->GetCredit();
3566
//printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
3571
bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<CWalletTx*>& setCoinsRet)
3573
setCoinsRet.clear();
3575
// List of values less than target
3576
int64 nLowestLarger = INT64_MAX;
3577
CWalletTx* pcoinLowestLarger = NULL;
3578
vector<pair<int64, CWalletTx*> > vValue;
3579
int64 nTotalLower = 0;
3581
CRITICAL_BLOCK(cs_mapWallet)
3583
vector<CWalletTx*> vCoins;
3584
vCoins.reserve(mapWallet.size());
3585
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3586
vCoins.push_back(&(*it).second);
3587
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
3589
foreach(CWalletTx* pcoin, vCoins)
3591
if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())
3594
int nDepth = pcoin->GetDepthInMainChain();
3595
if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
3598
int64 n = pcoin->GetCredit();
3601
if (n < nTargetValue)
3603
vValue.push_back(make_pair(n, pcoin));
3606
else if (n == nTargetValue)
3608
setCoinsRet.insert(pcoin);
3611
else if (n < nLowestLarger)
3614
pcoinLowestLarger = pcoin;
3619
if (nTotalLower < nTargetValue)
3621
if (pcoinLowestLarger == NULL)
3623
setCoinsRet.insert(pcoinLowestLarger);
3627
// Solve subset sum by stochastic approximation
3628
sort(vValue.rbegin(), vValue.rend());
3629
vector<char> vfIncluded;
3630
vector<char> vfBest(vValue.size(), true);
3631
int64 nBest = nTotalLower;
3633
for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
3635
vfIncluded.assign(vValue.size(), false);
3637
bool fReachedTarget = false;
3638
for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3640
for (int i = 0; i < vValue.size(); i++)
3642
if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
3644
nTotal += vValue[i].first;
3645
vfIncluded[i] = true;
3646
if (nTotal >= nTargetValue)
3648
fReachedTarget = true;
3652
vfBest = vfIncluded;
3654
nTotal -= vValue[i].first;
3655
vfIncluded[i] = false;
3662
// If the next larger is still closer, return it
3663
if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)
3664
setCoinsRet.insert(pcoinLowestLarger);
3667
for (int i = 0; i < vValue.size(); i++)
3669
setCoinsRet.insert(vValue[i].second);
3672
printf("SelectCoins() best subset: ");
3673
for (int i = 0; i < vValue.size(); i++)
3675
printf("%s ", FormatMoney(vValue[i].first).c_str());
3676
printf("total %s\n", FormatMoney(nBest).c_str());
3682
bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)
3684
return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet) ||
3685
SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet) ||
3686
SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet));
3692
bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
3694
CRITICAL_BLOCK(cs_main)
3696
// txdb must be opened before the mapWallet lock
3698
CRITICAL_BLOCK(cs_mapWallet)
3700
nFeeRet = nTransactionFee;
3704
wtxNew.vout.clear();
3705
wtxNew.fFromMe = true;
3708
int64 nValueOut = nValue;
3709
int64 nTotalValue = nValue + nFeeRet;
3711
// Choose coins to use
3712
set<CWalletTx*> setCoins;
3713
if (!SelectCoins(nTotalValue, setCoins))
3716
foreach(CWalletTx* pcoin, setCoins)
3717
nValueIn += pcoin->GetCredit();
3719
// Fill a vout to the payee
3720
bool fChangeFirst = GetRand(2);
3722
wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3724
// Fill a vout back to self with any change
3725
int64 nChange = nValueIn - nTotalValue;
3726
if (nChange >= CENT)
3728
// Note: We use a new key here to keep it from being obvious which side is the change.
3729
// The drawback is that by not reusing a previous key, the change may be lost if a
3730
// backup is restored, if the backup doesn't have the new private key for the change.
3731
// If we reused the old key, it would be possible to add code to look for and
3732
// rediscover unknown transactions that were written with keys of ours to recover
3733
// post-backup change.
3735
// Reserve a new key pair from key pool
3736
vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
3737
assert(mapKeys.count(vchPubKey));
3739
// Fill a vout to ourself, using same address type as the payment
3740
CScript scriptChange;
3741
if (scriptPubKey.GetBitcoinAddressHash160() != 0)
3742
scriptChange.SetBitcoinAddress(vchPubKey);
3744
scriptChange << vchPubKey << OP_CHECKSIG;
3745
wtxNew.vout.push_back(CTxOut(nChange, scriptChange));
3748
reservekey.ReturnKey();
3750
// Fill a vout to the payee
3752
wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3755
foreach(CWalletTx* pcoin, setCoins)
3756
for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3757
if (pcoin->vout[nOut].IsMine())
3758
wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));
3762
foreach(CWalletTx* pcoin, setCoins)
3763
for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3764
if (pcoin->vout[nOut].IsMine())
3765
if (!SignSignature(*pcoin, wtxNew, nIn++))
3769
unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
3770
if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
3773
// Check that enough fee is included
3774
int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
3775
int64 nMinFee = wtxNew.GetMinFee();
3776
if (nFeeRet < max(nPayFee, nMinFee))
3778
nFeeRet = max(nPayFee, nMinFee);
3782
// Fill vtxPrev by copying from previous transactions vtxPrev
3783
wtxNew.AddSupportingTransactions(txdb);
3784
wtxNew.fTimeReceivedIsTxTime = true;
3793
// Call after CreateTransaction unless you want to abort
3794
bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
3796
CRITICAL_BLOCK(cs_main)
3798
printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3799
CRITICAL_BLOCK(cs_mapWallet)
3801
// This is only to keep the database open to defeat the auto-flush for the
3802
// duration of this scope. This is the only place where this optimization
3803
// maybe makes sense; please don't do it anywhere else.
3804
CWalletDB walletdb("r");
3806
// Take key pair from key pool so it won't be used again
3807
reservekey.KeepKey();
3809
// Add tx to wallet, because if it has change it's also ours,
3810
// otherwise just for transaction history.
3811
AddToWallet(wtxNew);
3813
// Mark old coins as spent
3814
set<CWalletTx*> setCoins;
3815
foreach(const CTxIn& txin, wtxNew.vin)
3816
setCoins.insert(&mapWallet[txin.prevout.hash]);
3817
foreach(CWalletTx* pcoin, setCoins)
3819
pcoin->fSpent = true;
3820
pcoin->WriteToDisk();
3821
vWalletUpdated.push_back(pcoin->GetHash());
3825
// Track how many getdata requests our transaction gets
3826
CRITICAL_BLOCK(cs_mapRequestCount)
3827
mapRequestCount[wtxNew.GetHash()] = 0;
3830
if (!wtxNew.AcceptToMemoryPool())
3832
// This must not fail. The transaction has already been signed and recorded.
3833
printf("CommitTransaction() : Error: Transaction not valid");
3836
wtxNew.RelayWalletTransaction();
3845
string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3847
CRITICAL_BLOCK(cs_main)
3849
CReserveKey reservekey;
3851
if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
3854
if (nValue + nFeeRequired > GetBalance())
3855
strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s "), FormatMoney(nFeeRequired).c_str());
3857
strError = _("Error: Transaction creation failed ");
3858
printf("SendMoney() : %s", strError.c_str());
3862
if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
3865
if (!CommitTransaction(wtxNew, reservekey))
3866
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.");
3874
string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3878
return _("Invalid amount");
3879
if (nValue + nTransactionFee > GetBalance())
3880
return _("Insufficient funds");
3882
// Parse bitcoin address
3883
CScript scriptPubKey;
3884
if (!scriptPubKey.SetBitcoinAddress(strAddress))
3885
return _("Invalid bitcoin address");
3887
return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);