21 unsigned char* pdata = (
unsigned char*)pbuffer;
22 unsigned int blocks = 1 + ((len + 8) / 64);
23 unsigned char* pend = pdata + 64 * blocks;
24 memset(pdata + len, 0, 64 * blocks - len);
26 unsigned int bits = len * 8;
27 pend[-1] = (bits >> 0) & 0xff;
28 pend[-2] = (bits >> 8) & 0xff;
29 pend[-3] = (bits >> 16) & 0xff;
30 pend[-4] = (bits >> 24) & 0xff;
35 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
40 unsigned char data[64];
44 for (
int i = 0; i < 16; i++)
45 ((uint32_t*)data)[i] =
ByteReverse(((uint32_t*)pinput)[i]);
47 for (
int i = 0; i < 8; i++)
48 ctx.h[i] = ((uint32_t*)pinit)[i];
50 SHA256_Update(&ctx, data,
sizeof(data));
51 for (
int i = 0; i < 8; i++)
52 ((uint32_t*)pstate)[i] = ctx.h[i];
67 dPriority = dFeePerKb = 0;
72 LogPrintf(
"COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
74 BOOST_FOREACH(
uint256 hash, setDependsOn)
84 typedef boost::tuple<double, double, const CTransaction*>
TxPriority;
94 if (a.get<1>() == b.get<1>())
95 return a.get<0>() < b.get<0>();
96 return a.get<1>() < b.get<1>();
100 if (a.get<0>() == b.get<0>())
101 return a.get<1>() < b.get<1>();
102 return a.get<0>() < b.get<0>();
111 if(!pblocktemplate.get())
118 txNew.
vin[0].prevout.SetNull();
119 txNew.
vout.resize(1);
120 txNew.
vout[0].scriptPubKey = scriptPubKeyIn;
123 pblock->
vtx.push_back(txNew);
124 pblocktemplate->
vTxFees.push_back(-1);
130 nBlockMaxSize = std::max((
unsigned int)1000, std::min((
unsigned int)(
MAX_BLOCK_SIZE-1000), nBlockMaxSize));
135 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
140 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
150 list<COrphan> vOrphan;
151 map<uint256, vector<COrphan*> > mapDependers;
152 bool fPrintPriority =
GetBoolArg(
"-printpriority",
false);
155 vector<TxPriority> vecPriority;
157 for (map<uint256, CTxMemPoolEntry>::iterator mi =
mempool.
mapTx.begin();
165 double dPriority = 0;
166 int64_t nTotalIn = 0;
167 bool fMissingInputs =
false;
168 BOOST_FOREACH(
const CTxIn& txin, tx.
vin)
178 LogPrintf(
"ERROR: mempool transaction missing input\n");
179 if (
fDebug) assert(
"mempool transaction missing input" == 0);
180 fMissingInputs =
true;
190 vOrphan.push_back(
COrphan(&tx));
191 porphan = &vOrphan.back();
193 mapDependers[txin.
prevout.
hash].push_back(porphan);
201 nTotalIn += nValueIn;
205 dPriority += (double)nValueIn * nConf;
207 if (fMissingInputs)
continue;
216 double dFeePerKb = double(nTotalIn-tx.
GetValueOut()) / (
double(nTxSize)/1000.0);
224 vecPriority.push_back(
TxPriority(dPriority, dFeePerKb, &mi->second.GetTx()));
228 uint64_t nBlockSize = 1000;
229 uint64_t nBlockTx = 0;
230 int nBlockSigOps = 100;
231 bool fSortedByFee = (nBlockPrioritySize <= 0);
234 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
236 while (!vecPriority.empty())
239 double dPriority = vecPriority.front().get<0>();
240 double dFeePerKb = vecPriority.front().get<1>();
241 const CTransaction& tx = *(vecPriority.front().get<2>());
243 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
244 vecPriority.pop_back();
248 if (nBlockSize + nTxSize >= nBlockMaxSize)
263 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !
AllowFree(dPriority)))
267 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
288 pblock->
vtx.push_back(tx);
289 pblocktemplate->
vTxFees.push_back(nTxFees);
290 pblocktemplate->
vTxSigOps.push_back(nTxSigOps);
291 nBlockSize += nTxSize;
293 nBlockSigOps += nTxSigOps;
298 LogPrintf(
"priority %.1f feeperkb %.1f txid %s\n",
303 if (mapDependers.count(hash))
305 BOOST_FOREACH(
COrphan* porphan, mapDependers[hash])
313 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
322 LogPrintf(
"CreateNewBlock(): total size %u\n", nBlockSize);
325 pblocktemplate->
vTxFees[0] = -nFees;
336 indexDummy.
pprev = pindexPrev;
340 if (!
ConnectBlock(*pblock, state, &indexDummy, viewNew,
true))
341 throw std::runtime_error(
"CreateNewBlock() : ConnectBlock failed");
344 return pblocktemplate.release();
357 unsigned int nHeight = pindexPrev->
nHeight+1;
359 assert(pblock->
vtx[0].vin[0].scriptSig.size() <= 100);
382 unsigned char pchPadding0[64];
384 unsigned char pchPadding1[64];
387 memset(&tmp, 0,
sizeof(tmp));
389 tmp.block.nVersion = pblock->
nVersion;
392 tmp.block.nTime = pblock->
nTime;
393 tmp.block.nBits = pblock->
nBits;
394 tmp.block.nNonce = pblock->
nNonce;
400 for (
unsigned int i = 0; i <
sizeof(tmp)/4; i++)
401 ((
unsigned int*)&tmp)[i] =
ByteReverse(((
unsigned int*)&tmp)[i]);
406 memcpy(pdata, &tmp.block, 128);
407 memcpy(phash1, &tmp.hash1, 64);
425 unsigned int static ScanHash_CryptoPP(
char* pmidstate,
char* pdata,
char* phash1,
char* phash,
unsigned int& nHashesDone)
427 unsigned int& nNonce = *(
unsigned int*)(pdata + 12);
439 if (((
unsigned short*)phash)[14] == 0)
443 if ((nNonce & 0xffff) == 0)
445 nHashesDone = 0xffff+1;
446 return (
unsigned int) -1;
448 if ((nNonce & 0xfff) == 0)
449 boost::this_thread::interruption_point();
468 if (hash > hashTarget)
481 return error(
"BitcoinMiner : generated block is stale");
495 return error(
"BitcoinMiner : ProcessBlock, block not accepted");
501 void static BitcoinMiner(
CWallet *pwallet)
509 unsigned int nExtraNonce = 0;
526 if (!pblocktemplate.get())
528 CBlock *pblock = &pblocktemplate->block;
531 LogPrintf(
"Running BitcoinMiner with %u transactions in block (%u bytes)\n", pblock->
vtx.size(),
537 char pmidstatebuf[32+16];
char* pmidstate = alignup<16>(pmidstatebuf);
538 char pdatabuf[128+16];
char* pdata = alignup<16>(pdatabuf);
539 char phash1buf[64+16];
char* phash1 = alignup<16>(phash1buf);
543 unsigned int& nBlockTime = *(
unsigned int*)(pdata + 64 + 4);
544 unsigned int& nBlockBits = *(
unsigned int*)(pdata + 64 + 8);
545 unsigned int& nBlockNonce = *(
unsigned int*)(pdata + 64 + 12);
554 uint256& hash = *alignup<16>(hashbuf);
557 unsigned int nHashesDone = 0;
558 unsigned int nNonceFound;
561 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
562 (
char*)&hash, nHashesDone);
565 if (nNonceFound != (
unsigned int) -1)
567 for (
unsigned int i = 0; i <
sizeof(hash)/4; i++)
568 ((
unsigned int*)&hash)[i] =
ByteReverse(((
unsigned int*)&hash)[i]);
570 if (hash <= hashTarget)
574 assert(hash == pblock->
GetHash());
583 throw boost::thread_interrupted();
590 static int64_t nHashCounter;
597 nHashCounter += nHashesDone;
608 static int64_t nLogTime;
609 if (
GetTime() - nLogTime > 30 * 60)
619 boost::this_thread::interruption_point();
622 if (nBlockNonce >= 0xffff0000)
640 catch (boost::thread_interrupted)
649 static boost::thread_group* minerThreads = NULL;
655 nThreads = boost::thread::hardware_concurrency();
658 if (minerThreads != NULL)
660 minerThreads->interrupt_all();
665 if (nThreads == 0 || !fGenerate)
668 minerThreads =
new boost::thread_group();
669 for (
int i = 0; i < nThreads; i++)
670 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
int64_t GetValueOut() const
CBlockTemplate * CreateNewBlockWithKey(CReserveKey &reservekey)
void IncrementExtraNonce(CBlock *pblock, CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
static const unsigned int DEFAULT_BLOCK_MIN_SIZE
#define THREAD_PRIORITY_LOWEST
#define THREAD_PRIORITY_NORMAL
double ComputePriority(double dPriorityInputs, unsigned int nTxSize=0) const
std::vector< CTxOut > vout
uint256 getuint256() const
void GenerateBitcoins(bool fGenerate, CWallet *pwallet, int nThreads)
Run the miner threads.
CCriticalSection cs_wallet
Main wallet lock.
void MilliSleep(int64_t n)
static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE
Default for -blockprioritysize, maximum space for zero/low-fee transactions.
std::vector< int64_t > vTxFees
CBlockTemplate * CreateNewBlock(const CScript &scriptPubKeyIn)
Generate a new block, without valid proof-of-work.
pruned version of CTransaction: only retains metadata and unspent transaction outputs ...
bool AllowFree(double dPriority)
string FormatMoney(int64_t n, bool fPlus)
void RenameThread(const char *name)
CChain chainActive
The currently-connected chain of blocks.
static const unsigned int DEFAULT_BLOCK_MAX_SIZE
Default for -blockmaxsize and -blockminsize, which control the range of sizes the mining code will cr...
bool GetCoins(const uint256 &txid, CCoins &coins)
bool CheckWork(CBlock *pblock, CWallet &wallet, CReserveKey &reservekey)
Check mined block.
unsigned int GetTransactionsUpdated() const
uint256 BuildMerkleTree() const
void UpdateTime(CBlockHeader &block, const CBlockIndex *pindexPrev)
CBigNum & SetCompact(unsigned int nCompact)
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or NULL if none.
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
static const unsigned int MAX_BLOCK_SIGOPS
The maximum allowed number of signature check operations in a block (network rule) ...
unsigned int GetSerializeSize(char a, int, int=0)
bool HaveCoins(const uint256 &txid)
An input of a transaction.
bool HaveInputs(const CTransaction &tx)
std::vector< CTxOut > vout
void FormatHashBuffers(CBlock *pblock, char *pmidstate, char *pdata, char *phash1)
Do mining precalculation.
An encapsulated public key.
set< uint256 > setDependsOn
boost::tuple< double, double, const CTransaction * > TxPriority
static bool error(const char *format)
C++ wrapper for BIGNUM (OpenSSL bignum)
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock)
static const unsigned int MAX_BLOCK_SIZE
The maximum allowed size for a serialized block, in bytes (network rule)
std::map< uint256, CTxMemPoolEntry > mapTx
void UpdateCoins(const CTransaction &tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash)
bool GetReservedKey(CPubKey &pubkey)
bool ConnectBlock(CBlock &block, CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool fJustCheck)
std::map< uint256, int > mapRequestCount
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
std::string GetHex() const
void SetThreadPriority(int nPriority)
unsigned int GetP2SHSigOpCount(const CTransaction &tx, CCoinsViewCache &inputs)
Count ECDSA signature operations in pay-to-script-hash inputs.
Capture information about block/transaction validation.
int64_t GetBlockValue(int nHeight, int64_t nFees)
bool ProcessBlock(CValidationState &state, CNode *pfrom, CBlock *pblock, CDiskBlockPos *dbp)
Process an incoming block.
A key allocated from the key pool.
uint32_t ByteReverse(uint32_t value)
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Count ECDSA signature operations the old-fashioned (pre-0.6) way.
The block chain is a tree shaped structure starting with the genesis block at the root...
const CChainParams & Params()
Return the currently selected parameters.
bool CheckInputs(const CTransaction &tx, CValidationState &state, CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, std::vector< CScriptCheck > *pvChecks)
Serialized script, used inside transaction inputs and outputs.
Undo information for a CTransaction.
void * memcpy(void *a, const void *b, size_t c)
std::string ToString() const
static const int PROTOCOL_VERSION
std::vector< int64_t > vTxSigOps
static const unsigned int pSHA256InitState[8]
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
COrphan(const CTransaction *ptxIn)
int64_t GetValueIn(const CTransaction &tx)
Amount of bitcoins coming in to a transaction Note that lightweight clients may not know anything bes...
static int64_t nMinRelayTxFee
Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) ...
bool operator()(const TxPriority &a, const TxPriority &b)
std::vector< CTransaction > vtx
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
static int FormatHashBlocks(void *pbuffer, unsigned int len)
The basic transaction that is broadcasted on the network and contained in blocks. ...
static const CCheckpointData data
CCoinsView that adds a memory cache for transactions to another CCoinsView.
void SHA256Transform(void *pstate, void *pinput, const void *pinit)
Base sha256 mining transform.
TxPriorityCompare(bool _byFee)
virtual Network NetworkID() const =0
uint256 GetBlockHash() const