/*
Type-check arguments; throws JSONRPCError if wrong type given. Does not check that
the right number of arguments are passed, just that any passed are the correct type.
- Use like: RPCTypeCheck(params, boost::assign::list_of(str_type)(int_type)(obj_type));
+ Use like: RPCTypeCheck(params, {str_type, int_type, obj_type});
*/
void RPCTypeCheck(const json_spirit::Array& params,
const std::list<json_spirit::Value_type>& typesExpected, bool fAllowNull=false);
/*
Check for expected keys/value types in an Object.
- Use like: RPCTypeCheck(object, boost::assign::map_list_of("name", str_type)("value", int_type));
+ Use like: RPCTypeCheck(object, { {"name", str_type}, {"value", int_type });
*/
void RPCTypeCheck(const json_spirit::Object& o,
const std::map<std::string, json_spirit::Value_type>& typesExpected, bool fAllowNull=false);
return false;
CTxDB txdb;
- CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
+ auto pindexCheckpoint = mapBlockIndex[hashCheckpoint];
if (!pindexCheckpoint->IsInMainChain())
{
// checkpoint chain received but not yet main chain
// Scan given kernel for solution
bool ScanKernelForward(unsigned char *kernel, uint32_t nBits, uint32_t nInputTxTime, int64_t nValueIn, pair<uint32_t, uint32_t> &SearchInterval, vector<pair<uint256, uint32_t> > &solutions)
{
- // TODO: custom threads amount
-
- uint32_t nThreads = boost::thread::hardware_concurrency();
- uint32_t nPart = (SearchInterval.second - SearchInterval.first) / nThreads;
-
+ solutions.clear();
+ {
+ using namespace boost;
- KernelWorker *workers = new KernelWorker[nThreads];
+ auto nThreads = thread::hardware_concurrency();
+ auto vWorkers = vector<KernelWorker>(nThreads);
+ auto nPart = (SearchInterval.second - SearchInterval.first) / nThreads;
+ thread_group group;
- boost::thread_group group;
- for(size_t i = 0; i < nThreads; i++)
- {
- uint32_t nBegin = SearchInterval.first + nPart * i;
- uint32_t nEnd = SearchInterval.first + nPart * (i + 1);
- workers[i] = KernelWorker(kernel, nBits, nInputTxTime, nValueIn, nBegin, nEnd);
- boost::function<void()> workerFnc = boost::bind(&KernelWorker::Do, &workers[i]);
- group.create_thread(workerFnc);
- }
+ for(size_t i = 0; i < vWorkers.size(); i++)
+ {
+ auto nBegin = SearchInterval.first + nPart * i;
+ auto nEnd = SearchInterval.first + nPart * (i + 1);
- group.join_all();
- solutions.clear();
+ vWorkers[i] = KernelWorker(kernel, nBits, nInputTxTime, nValueIn, nBegin, nEnd);
+ auto workerFnc = bind(&KernelWorker::Do, &vWorkers[i]);
+ group.create_thread(workerFnc);
+ }
- for(size_t i = 0; i < nThreads; i++)
- {
- vector<pair<uint256, uint32_t> > ws = workers[i].GetSolutions();
- solutions.insert(solutions.end(), ws.begin(), ws.end());
- }
+ group.join_all();
- delete [] workers;
+ for(auto& worker : vWorkers)
+ {
+ auto ws = worker.GetSolutions();
+ solutions.insert(solutions.end(), ws.begin(), ws.end());
+ }
- if (solutions.size() == 0)
- {
- // no solutions
- return false;
+ return (solutions.size() != 0);
}
return true;
bool CheckStakeModifierCheckpoints(int nHeight, uint32_t nStakeModifierChecksum)
{
auto& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints);
-
if (checkpoints.count(nHeight))
return nStakeModifierChecksum == checkpoints[nHeight];
return true;
KernelWorker::KernelWorker(unsigned char *kernel, uint32_t nBits, uint32_t nInputTxTime, int64_t nValueIn, uint32_t nIntervalBegin, uint32_t nIntervalEnd)
: kernel(kernel), nBits(nBits), nInputTxTime(nInputTxTime), bnValueIn(nValueIn), nIntervalBegin(nIntervalBegin), nIntervalEnd(nIntervalEnd)
{
- solutions = vector<std::pair<uint256,uint32_t> >();
+ solutions = vector<pair<uint256,uint32_t> >();
}
void KernelWorker::Do_generic()
// Compute maximum possible target to filter out majority of obviously insufficient hashes
CBigNum bnTargetPerCoinDay;
bnTargetPerCoinDay.SetCompact(nBits);
- uint256 nMaxTarget = (bnTargetPerCoinDay * bnValueIn * nStakeMaxAge / COIN / nOneDay).getuint256();
+ auto nMaxTarget = (bnTargetPerCoinDay * bnValueIn * nStakeMaxAge / COIN / nOneDay).getuint256();
SHA256_CTX ctx, workerCtx;
// Init new sha256 context and update it
// Search forward in time from the given timestamp
// Stopping search in case of shutting down
- for (uint32_t nTimeTx=nIntervalBegin, nMaxTarget32 = nMaxTarget.Get32(7); nTimeTx<nIntervalEnd && !fShutdown; nTimeTx++)
+ for (auto nTimeTx=nIntervalBegin, nMaxTarget32 = nMaxTarget.Get32(7); nTimeTx<nIntervalEnd && !fShutdown; nTimeTx++)
{
// Complete first hashing iteration
uint256 hash1;
// Scan given kernel for solutions
-bool ScanKernelBackward(unsigned char *kernel, uint32_t nBits, uint32_t nInputTxTime, int64_t nValueIn, std::pair<uint32_t, uint32_t> &SearchInterval, std::pair<uint256, uint32_t> &solution)
+bool ScanKernelBackward(unsigned char *kernel, uint32_t nBits, uint32_t nInputTxTime, int64_t nValueIn, pair<uint32_t, uint32_t> &SearchInterval, pair<uint256, uint32_t> &solution)
{
CBigNum bnTargetPerCoinDay;
bnTargetPerCoinDay.SetCompact(nBits);
CBigNum bnValueIn(nValueIn);
// Get maximum possible target to filter out the majority of obviously insufficient hashes
- uint256 nMaxTarget = (bnTargetPerCoinDay * bnValueIn * nStakeMaxAge / COIN / nOneDay).getuint256();
+ auto nMaxTarget = (bnTargetPerCoinDay * bnValueIn * nStakeMaxAge / COIN / nOneDay).getuint256();
SHA256_CTX ctx, workerCtx;
// Init new sha256 context and update it
#include <vector>
+using namespace std;
+
class KernelWorker
{
public:
{ }
KernelWorker(unsigned char *kernel, uint32_t nBits, uint32_t nInputTxTime, int64_t nValueIn, uint32_t nIntervalBegin, uint32_t nIntervalEnd);
void Do();
- std::vector<std::pair<uint256,uint32_t> >& GetSolutions();
+ vector<pair<uint256,uint32_t> >& GetSolutions();
private:
// One way hashing.
void Do_generic();
// Kernel solutions.
- std::vector<std::pair<uint256,uint32_t> > solutions;
+ vector<pair<uint256,uint32_t> > solutions;
// Kernel metadata.
uint8_t *kernel;
};
// Scan given kernel for solutions
-bool ScanKernelBackward(unsigned char *kernel, uint32_t nBits, uint32_t nInputTxTime, int64_t nValueIn, std::pair<uint32_t, uint32_t> &SearchInterval, std::pair<uint256, uint32_t> &solution);
+bool ScanKernelBackward(unsigned char *kernel, uint32_t nBits, uint32_t nInputTxTime, int64_t nValueIn, pair<uint32_t, uint32_t> &SearchInterval, pair<uint256, uint32_t> &solution);
-#endif // NOVACOIN_KERNELWORKER_H
\ No newline at end of file
+#endif // NOVACOIN_KERNELWORKER_H
vector<KernelRecord> KernelRecord::decomposeOutput(const CWallet *wallet, const CWalletTx &wtx)
{
vector<KernelRecord> parts;
- int64_t nTime = wtx.GetTxTime();
- uint256 hash = wtx.GetHash();
- std::map<std::string, std::string> mapValue = wtx.mapValue;
- int64_t nDayWeight = (min((GetAdjustedTime() - nTime), (int64_t)(nStakeMaxAge+nStakeMinAge)) - nStakeMinAge); // DayWeight * 86400, чтобы был
+ auto nTime = wtx.GetTxTime();
+ auto hash = wtx.GetHash();
+ auto mapValue = wtx.mapValue;
+ auto nDayWeight = (min((GetAdjustedTime() - nTime), (int64_t)(nStakeMaxAge+nStakeMinAge)) - nStakeMinAge); // DayWeight * 86400, чтобы был
// правильный расчёт CoinAge
if (showTransaction(wtx))
{
CTxOut txOut = wtx.vout[nOut];
if( wallet->IsMine(txOut) ) {
CTxDestination address;
- std::string addrStr;
+ string addrStr;
- uint64_t coinAge = max( (txOut.nValue * nDayWeight) / (COIN * nOneDay), (int64_t)0);
+ auto coinAge = max( (txOut.nValue * nDayWeight) / (COIN * nOneDay), (int64_t)0);
if (ExtractDestination(txOut.scriptPubKey, address))
{
return parts;
}
-std::string KernelRecord::getTxID()
+string KernelRecord::getTxID()
{
return hash.ToString() + strprintf("-%03d", idx);
}
uint64_t KernelRecord::getCoinDay() const
{
- int64_t nWeight = GetAdjustedTime() - nTime - nStakeMinAge;
+ auto nWeight = GetAdjustedTime() - nTime - nStakeMinAge;
if( nWeight < 0)
return 0;
nWeight = min(nWeight, (int64_t)nStakeMaxAge);
- uint64_t coinAge = (nValue * nWeight ) / (COIN * nOneDay);
- return coinAge;
+ return (nValue * nWeight ) / (COIN * nOneDay);
}
int64_t KernelRecord::getPoSReward(int nBits, int minutes)
{
- int64_t PoSReward;
- int64_t nWeight = GetAdjustedTime() - nTime + minutes * 60;
+ auto nWeight = GetAdjustedTime() - nTime + minutes * 60;
if( nWeight < nStakeMinAge)
return 0;
- uint64_t coinAge = (nValue * nWeight ) / (COIN * nOneDay);
- PoSReward = GetProofOfStakeReward(coinAge, nBits, GetAdjustedTime() + minutes * 60);
- return PoSReward;
+ auto coinAge = (nValue * nWeight ) / (COIN * nOneDay);
+ return GetProofOfStakeReward(coinAge, nBits, GetAdjustedTime() + minutes * 60);
}
double KernelRecord::getProbToMintStake(double difficulty, int timeOffset) const
//int dayWeight = (min((GetAdjustedTime() - nTime) + timeOffset, (int64_t)(nStakeMinAge+nStakeMaxAge)) - nStakeMinAge) / 86400;
//uint64_t coinAge = max(nValue * dayWeight / COIN, (int64_t)0);
//return target * coinAge / pow(static_cast<double>(2), 256);
- int64_t Weight = (min((GetAdjustedTime() - nTime) + timeOffset, (int64_t)(nStakeMinAge+nStakeMaxAge)) - nStakeMinAge);
- uint64_t coinAge = max(nValue * Weight / (COIN * nOneDay), (int64_t)0);
+ auto Weight = (min((GetAdjustedTime() - nTime) + timeOffset, (int64_t)(nStakeMinAge+nStakeMaxAge)) - nStakeMinAge);
+ auto coinAge = max(nValue * Weight / (COIN * nOneDay), (int64_t)0);
return coinAge / (pow(static_cast<double>(2),32) * difficulty);
}
int static FormatHashBlocks(void* pbuffer, unsigned int len)
{
- unsigned char* pdata = (unsigned char*)pbuffer;
- unsigned int blocks = 1 + ((len + 8) / 64);
- unsigned char* pend = pdata + 64 * blocks;
+ auto pdata = (unsigned char*)pbuffer;
+ auto blocks = 1 + ((len + 8) / 64);
+ auto pend = pdata + 64 * blocks;
memset(pdata + len, 0, 64 * blocks - len);
pdata[len] = 0x80;
- unsigned int bits = len * 8;
+ auto bits = len * 8;
pend[-1] = (bits >> 0) & 0xff;
pend[-2] = (bits >> 8) & 0xff;
pend[-3] = (bits >> 16) & 0xff;
uint32_t nLastCoinStakeSearchInterval = 0;
// We want to sort transactions by priority and fee, so:
-typedef boost::tuple<double, double, CTransaction*> TxPriority;
+typedef tuple<double, double, CTransaction*> TxPriority;
class TxPriorityCompare
{
bool byFee;
{
if (byFee)
{
- if (a.get<1>() == b.get<1>())
- return a.get<0>() < b.get<0>();
- return a.get<1>() < b.get<1>();
+ if (get<1>(a) == get<1>(b))
+ return get<0>(a) < get<0>(b);
+ return get<1>(a) < get<1>(b);
}
else
{
- if (a.get<0>() == b.get<0>())
- return a.get<1>() < b.get<1>();
- return a.get<0>() < b.get<0>();
+ if (get<0>(a) == get<0>(b))
+ return get<1>(a) < get<1>(b);
+ return get<0>(a) < get<0>(b);
}
}
};
}
// Largest block you're willing to create:
- unsigned int nBlockMaxSize = GetArgUInt("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
+ auto nBlockMaxSize = GetArgUInt("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
// Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
- nBlockMaxSize = std::max(1000u, std::min(MAX_BLOCK_SIZE-1000u, nBlockMaxSize));
+ nBlockMaxSize = max(1000u, min(MAX_BLOCK_SIZE-1000u, nBlockMaxSize));
// How much of the block should be dedicated to high-priority transactions,
// included regardless of the fees they pay
- unsigned int nBlockPrioritySize = GetArgUInt("-blockprioritysize", 27000);
- nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
+ auto nBlockPrioritySize = GetArgUInt("-blockprioritysize", 27000);
+ nBlockPrioritySize = min(nBlockMaxSize, nBlockPrioritySize);
// Minimum block size you want to create; block will be filled with free transactions
// until there are no more or the block reaches this size:
- unsigned int nBlockMinSize = GetArgUInt("-blockminsize", 0);
- nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
+ auto nBlockMinSize = GetArgUInt("-blockminsize", 0);
+ nBlockMinSize = min(nBlockMaxSize, nBlockMinSize);
// Fee-per-kilobyte amount considered the same as "free"
// Be careful setting this: if you set it to zero then
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction.
- int64_t nMinTxFee = MIN_TX_FEE;
+ auto nMinTxFee = MIN_TX_FEE;
if (mapArgs.count("-mintxfee"))
ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
- CBlockIndex* pindexPrev = pindexBest;
+ auto pindexPrev = pindexBest;
pblock->nBits = GetNextTargetRequired(pindexPrev, fProofOfStake);
// This vector will be sorted into a priority queue:
vector<TxPriority> vecPriority;
vecPriority.reserve(mempool.mapTx.size());
- for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
+ for (auto mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
{
- CTransaction& tx = (*mi).second;
+ auto& tx = (*mi).second;
if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
continue;
double dPriority = 0;
int64_t nTotalIn = 0;
bool fMissingInputs = false;
- for(const CTxIn& txin : tx.vin)
+ for(const auto& txin : tx.vin)
{
// Read prev transaction
CTransaction txPrev;
nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
continue;
}
- int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
+ auto nValueIn = txPrev.vout[txin.prevout.n].nValue;
nTotalIn += nValueIn;
int nConf = txindex.GetDepthInMainChain();
if (fMissingInputs) continue;
// Priority is sum(valuein * age) / txsize
- unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
+ auto nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
dPriority /= nTxSize;
// This is a more accurate fee-per-kilobyte than is used by the client code, because the
// client code rounds up the size to the nearest 1K. That's good, because it gives an
// incentive to create smaller transactions.
- double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
+ auto dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
if (porphan)
{
bool fSortedByFee = (nBlockPrioritySize <= 0);
TxPriorityCompare comparer(fSortedByFee);
- std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
+ make_heap(vecPriority.begin(), vecPriority.end(), comparer);
while (!vecPriority.empty())
{
// Take highest priority transaction off the priority queue:
- double dPriority = vecPriority.front().get<0>();
- double dFeePerKb = vecPriority.front().get<1>();
- CTransaction& tx = *(vecPriority.front().get<2>());
+ auto dPriority = get<0>(vecPriority.front());
+ auto dFeePerKb = get<1>(vecPriority.front());
+ auto& tx = *(get<2>(vecPriority.front()));
- std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
+ pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
vecPriority.pop_back();
// Size limits
- unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
+ auto nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (nBlockSize + nTxSize >= nBlockMaxSize)
continue;
// Legacy limits on sigOps:
- unsigned int nTxSigOps = tx.GetLegacySigOpCount();
+ auto nTxSigOps = tx.GetLegacySigOpCount();
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
{
fSortedByFee = true;
comparer = TxPriorityCompare(fSortedByFee);
- std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
+ make_heap(vecPriority.begin(), vecPriority.end(), comparer);
}
// Connecting shouldn't fail due to dependency on other memory pool transactions
continue;
// Transaction fee
- int64_t nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
- int64_t nMinFee = tx.GetMinFee(nBlockSize, true, GMF_BLOCK, nTxSize);
+ auto nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
+ auto nMinFee = tx.GetMinFee(nBlockSize, true, GMF_BLOCK, nTxSize);
if (nTxFees < nMinFee)
continue;
auto hash = tx.GetHash();
if (mapDependers.count(hash))
{
- for(COrphan* porphan : mapDependers[hash])
+ for(auto porphan : mapDependers[hash])
{
if (!porphan->setDependsOn.empty())
{
if (porphan->setDependsOn.empty())
{
vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
- std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
+ push_heap(vecPriority.begin(), vecPriority.end(), comparer);
}
}
}
// Precalculated SHA256 contexts and metadata
// (txid, vout.n) => (kernel, (tx.nTime, nAmount))
-typedef std::map<std::pair<uint256, unsigned int>, std::pair<std::vector<unsigned char>, std::pair<uint32_t, uint64_t> > > MidstateMap;
+typedef map<pair<uint256, unsigned int>, pair<vector<unsigned char>, pair<uint32_t, uint64_t> > > MidstateMap;
// Fill the inputs map with precalculated contexts and metadata
bool FillMap(CWallet *pwallet, uint32_t nUpperTime, MidstateMap &inputsMap)
ssKernel << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << pcoin->first->nTime << pcoin->second;
// (txid, vout.n) => (kernel, (tx.nTime, nAmount))
- inputsMap[key] = make_pair(std::vector<unsigned char>(ssKernel.begin(), ssKernel.end()), make_pair(pcoin->first->nTime, pcoin->first->vout[pcoin->second].nValue));
+ inputsMap[key] = { vector<unsigned char>(ssKernel.begin(), ssKernel.end()), { pcoin->first->nTime, pcoin->first->vout[pcoin->second].nValue } };
}
nStakeInputsMapSize = inputsMap.size();
}
// Scan inputs map in order to find a solution
-bool ScanMap(const MidstateMap &inputsMap, uint32_t nBits, MidstateMap::key_type &LuckyInput, std::pair<uint256, uint32_t> &solution)
+bool ScanMap(const MidstateMap &inputsMap, uint32_t nBits, MidstateMap::key_type &LuckyInput, pair<uint256, uint32_t> &solution)
{
static uint32_t nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
uint32_t nSearchTime = GetAdjustedTime();
if (inputsMap.size() > 0 && nSearchTime > nLastCoinStakeSearchTime)
{
// Scanning interval (begintime, endtime)
- std::pair<uint32_t, uint32_t> interval;
-
- interval.first = nSearchTime;
- interval.second = nSearchTime - min(nSearchTime-nLastCoinStakeSearchTime, nMaxStakeSearchInterval);
+ pair<uint32_t, uint32_t> interval = { nSearchTime, nSearchTime - min(nSearchTime-nLastCoinStakeSearchTime, nMaxStakeSearchInterval) };
// (txid, nout) => (kernel, (tx.nTime, nAmount))
- for(MidstateMap::const_iterator input = inputsMap.begin(); input != inputsMap.end(); input++)
+ for(auto input = inputsMap.begin(); input != inputsMap.end(); input++)
{
- unsigned char *kernel = (unsigned char *) &input->second.first[0];
+ auto kernel = (unsigned char *) &input->second.first[0];
// scan(State, Bits, Time, Amount, ...)
if (ScanKernelBackward(kernel, nBits, input->second.second.first, input->second.second.second, interval, solution))
// Make this thread recognisable as the mining thread
RenameThread("novacoin-miner");
- CWallet* pwallet = (CWallet*)parg;
+ auto pwallet = (CWallet*)parg;
MidstateMap inputsMap;
if (!FillMap(pwallet, GetAdjustedTime(), inputsMap))
bool fTrySync = true;
- CBlockIndex* pindexPrev = pindexBest;
+ auto pindexPrev = pindexBest;
auto nBits = GetNextTargetRequired(pindexPrev, true);
printf("ThreadStakeMinter started\n");
vnThreadsRunning[THREAD_MINTER]++;
MidstateMap::key_type LuckyInput;
- std::pair<uint256, uint32_t> solution;
+ pair<uint256, uint32_t> solution;
// Main miner loop
do
}
// Now we have new coinstake, it's time to create the block ...
- CBlock* pblock;
- pblock = CreateNewBlock(pwallet, &txCoinStake);
+ auto pblock = CreateNewBlock(pwallet, &txCoinStake);
if (!pblock)
{
string strMessage = _("Warning: Unable to allocate memory for the new block object. Mining thread has been stopped.");
vnThreadsRunning[THREAD_MINTER]--;
}
- catch (std::exception& e) {
+ catch (exception& e) {
vnThreadsRunning[THREAD_MINTER]--;
PrintException(&e, "ThreadStakeMinter()");
} catch (...) {
#include "bitcoinrpc.h"
#include <boost/format.hpp>
-#include <boost/assign/list_of.hpp>
#include <boost/iterator/counting_iterator.hpp>
using namespace json_spirit;
" days - time window, 90 days by default.\n"
);
- RPCTypeCheck(params, boost::assign::list_of(obj_type));
+ RPCTypeCheck(params, { obj_type });
auto scanParams = params[0].get_obj();
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#include <boost/assign/list_of.hpp>
-
#include "base58.h"
#include "bitcoinrpc.h"
#include "txdb.h"
using namespace std;
using namespace boost;
-using namespace boost::assign;
using namespace json_spirit;
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex)
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}");
- RPCTypeCheck(params, list_of(int_type)(int_type)(array_type));
+ RPCTypeCheck(params, { int_type, int_type, array_type });
int nMinDepth = 1;
if (params.size() > 0)
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.");
- RPCTypeCheck(params, list_of(array_type)(obj_type));
+ RPCTypeCheck(params, { array_type, obj_type });
Array inputs = params[0].get_array();
Object sendTo = params[1].get_obj();
for(Value& input : inputs)
{
- const Object& o = input.get_obj();
-
- const Value& txid_v = find_value(o, "txid");
+ const auto& o = input.get_obj();
+ const auto& txid_v = find_value(o, "txid");
if (txid_v.type() != str_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
- string txid = txid_v.get_str();
+ auto txid = txid_v.get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
- const Value& vout_v = find_value(o, "vout");
+ const auto& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
else
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid output destination: ")+s.name_);
- int64_t nAmount = AmountFromValue(s.value_);
+ auto nAmount = AmountFromValue(s.value_);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
"decoderawtransaction <hex string>\n"
"Return a JSON object representing the serialized, hex-encoded transaction.");
- RPCTypeCheck(params, list_of(str_type));
+ RPCTypeCheck(params, { str_type });
- vector<unsigned char> txData(ParseHex(params[0].get_str()));
+ auto txData = ParseHex(params[0].get_str());
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
try {
"decodescript <hex string>\n"
"Decode a hex-encoded script.");
- RPCTypeCheck(params, list_of(str_type));
+ RPCTypeCheck(params, { str_type });
Object r;
CScript script;
if (params[0].get_str().size() > 0){
- vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
+ auto scriptData = ParseHexV(params[0], "argument");
script = CScript(scriptData.begin(), scriptData.end());
} else {
// Empty scripts are valid
" complete : 1 if transaction has a complete set of signature (0 if not)"
+ HelpRequiringPassphrase());
- RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true);
+ RPCTypeCheck(params, { str_type, array_type, array_type, str_type }, true);
- vector<unsigned char> txData(ParseHex(params[0].get_str()));
+ auto txData = ParseHex(params[0].get_str());
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CTransaction> txVariants;
while (!ssData.empty())
tempTx.FetchInputs(txdb, unused, false, false, mapPrevTx, fInvalid);
// Copy results into mapPrevOut:
- for(const CTxIn& txin : tempTx.vin)
+ for(const auto& txin : tempTx.vin)
{
- const uint256& prevHash = txin.prevout.hash;
+ const auto& prevHash = txin.prevout.hash;
if (mapPrevTx.count(prevHash) && mapPrevTx[prevHash].second.vout.size()>txin.prevout.n)
mapPrevOut[txin.prevout] = mapPrevTx[prevHash].second.vout[txin.prevout.n].scriptPubKey;
}
if (params.size() > 2 && params[2].type() != null_type)
{
fGivenKeys = true;
- Array keys = params[2].get_array();
- for(Value k : keys)
+ auto keys = params[2].get_array();
+ for(auto k : keys)
{
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key;
bool fCompressed;
- CSecret secret = vchSecret.GetSecret(fCompressed);
+ auto secret = vchSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed);
tempKeystore.AddKey(key);
}
// Add previous txouts given in the RPC call:
if (params.size() > 1 && params[1].type() != null_type)
{
- Array prevTxs = params[1].get_array();
- for(Value& p : prevTxs)
+ auto prevTxs = params[1].get_array();
+ for(auto& p : prevTxs)
{
if (p.type() != obj_type)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
- Object prevOut = p.get_obj();
+ auto prevOut = p.get_obj();
- RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type));
+ RPCTypeCheck(prevOut, { {"txid", str_type}, {"vout", int_type}, {"scriptPubKey", str_type} });
- string txidHex = find_value(prevOut, "txid").get_str();
+ auto txidHex = find_value(prevOut, "txid").get_str();
if (!IsHex(txidHex))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "txid must be hexadecimal");
uint256 txid;
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
- string pkHex = find_value(prevOut, "scriptPubKey").get_str();
+ auto pkHex = find_value(prevOut, "scriptPubKey").get_str();
if (!IsHex(pkHex))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "scriptPubKey must be hexadecimal");
- vector<unsigned char> pkData(ParseHex(pkHex));
+ auto pkData = ParseHex(pkHex);
CScript scriptPubKey(pkData.begin(), pkData.end());
-
COutPoint outpoint(txid, nOut);
if (mapPrevOut.count(outpoint))
{
// if redeemScript given and not using the local wallet (private keys
// given), add redeemScript to the tempKeystore so it can be signed:
- Value v = find_value(prevOut, "redeemScript");
if (fGivenKeys && scriptPubKey.IsPayToScriptHash())
{
- RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)("redeemScript",str_type));
- Value v = find_value(prevOut, "redeemScript");
+ RPCTypeCheck(prevOut, { {"txid", str_type}, {"vout", int_type}, {"scriptPubKey", str_type}, {"redeemScript",str_type} });
+ auto v = find_value(prevOut, "redeemScript");
if (!(v == Value::null))
{
- vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
+ auto rsData = ParseHexV(v, "redeemScript");
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
- const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain);
+ const auto& keystore = (fGivenKeys ? tempKeystore : *pwalletMain);
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && params[3].type() != null_type)
{
static map<string, int> mapSigHashValues =
- {
+ {
{"ALL", int(SIGHASH_ALL)},
{"ALL|ANYONECANPAY", int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
{"NONE", int(SIGHASH_NONE)},
{"NONE|ANYONECANPAY", int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},
{"SINGLE", int(SIGHASH_SINGLE)},
{"SINGLE|ANYONECANPAY", int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)}
- };
- string strHashType = params[3].get_str();
+ };
+ auto strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
{
- CTxIn& txin = mergedTx.vin[i];
+ auto& txin = mergedTx.vin[i];
if (mapPrevOut.count(txin.prevout) == 0)
{
fComplete = false;
continue;
}
- const CScript& prevPubKey = mapPrevOut[txin.prevout];
+ const auto& prevPubKey = mapPrevOut[txin.prevout];
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
"sendrawtransaction <hex string>\n"
"Submits raw transaction (serialized, hex-encoded) to local node and network.");
- RPCTypeCheck(params, list_of(str_type));
+ RPCTypeCheck(params, { str_type });
// parse hex string from parameter
- vector<unsigned char> txData(ParseHex(params[0].get_str()));
+ auto txData = ParseHex(params[0].get_str());
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
catch (const std::exception&) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
- uint256 hashTx = tx.GetHash();
+ auto hashTx = tx.GetHash();
// See if the transaction is already in a block
// or in the memory pool:
}
int nRequired = params[0].get_int();
- const Array& keys = params[1].get_array();
+ const auto& keys = params[1].get_array();
// Gather public keys
if (nRequired < 1)
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
- const std::string& ks = keys[i].get_str();
+ const auto& ks = keys[i].get_str();
// Case 1: Bitcoin address and we have full public key:
CBitcoinAddress address(ks);
throw runtime_error(
strprintf("redeemScript exceeds size limit: %" PRIszu " > %d", inner.size(), MAX_SCRIPT_ELEMENT_SIZE));
- CScriptID innerID = inner.GetID();
+ auto innerID = inner.GetID();
CBitcoinAddress address(innerID);
Object result;
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#include <boost/tuple/tuple.hpp>
-
-using namespace std;
-using namespace boost;
#include "script.h"
#include "keystore.h"
#include "sync.h"
#include "util.h"
+using namespace std;
+
bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, int flags);
static const valtype vchFalse(0);
{
private:
// sigdata_type is (signature hash, signature, public key):
- typedef boost::tuple<uint256, std::vector<unsigned char>, CPubKey > sigdata_type;
- std::set< sigdata_type> setValid;
+ typedef tuple<uint256, std::vector<unsigned char>, CPubKey > sigdata_type;
+ set< sigdata_type> setValid;
boost::shared_mutex cs_sigcache;
public:
boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
sigdata_type k(hash, vchSig, pubKey);
- std::set<sigdata_type>::iterator mi = setValid.find(k);
+ auto mi = setValid.find(k);
if (mi != setValid.end())
return true;
return false;
// than our cache size.
auto randomHash = GetRandHash();
std::vector<unsigned char> unused;
- std::set<sigdata_type>::iterator it =
- setValid.lower_bound(sigdata_type(randomHash, unused, unused));
+ auto it = setValid.lower_bound(sigdata_type(randomHash, unused, unused));
if (it == setValid.end())
it = setValid.begin();
setValid.erase(*it);
}
// Scan templates
- const CScript& script1 = scriptPubKey;
+ const auto& script1 = scriptPubKey;
for(const auto& tplate : mTemplates)
{
- const CScript& script2 = tplate.second;
+ const auto& script2 = tplate.second;
vSolutionsRet.clear();
opcodetype opcode1, opcode2;
if (typeRet == TX_MULTISIG)
{
// Additional checks for TX_MULTISIG:
- unsigned char m = vSolutionsRet.front()[0];
- unsigned char n = vSolutionsRet.back()[0];
+ auto m = vSolutionsRet.front()[0];
+ auto n = vSolutionsRet.back()[0];
if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
return false;
}
{
int nSigned = 0;
int nRequired = multisigdata.front()[0];
- for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
+ for (uint32_t i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
{
- const valtype& pubkey = multisigdata[i];
+ const auto& pubkey = multisigdata[i];
auto keyID = CPubKey(pubkey).GetID();
if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
++nSigned;
unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
{
- unsigned int nResult = 0;
- for(const valtype& pubkey : pubkeys)
+ uint32_t nResult = 0;
+ for(const auto& pubkey : pubkeys)
{
auto keyID = CPubKey(pubkey).GetID();
if (keystore.HaveKey(keyID))
bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
};
-/*
-isminetype IsMine(const CKeyStore &keystore, const CTxDestination& dest)
-{
- CScript script;
- script.SetDestination(dest);
- return IsMine(keystore, script);
-}*/
-
isminetype IsMine(const CKeyStore &keystore, const CBitcoinAddress& dest)
{
CScript script;
// an empty stack and the EvalScript above would return false.
assert(!stackCopy.empty());
- const valtype& pubKeySerialized = stackCopy.back();
+ const auto& pubKeySerialized = stackCopy.back();
CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
popstack(stackCopy);
auto hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
txnouttype subType;
- bool fSolved =
- Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
+ bool fSolved = Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
// Append serialized subscript whether or not it is completely signed:
txin.scriptSig << static_cast<valtype>(subscript);
if (!fSolved) return false;
auto& txin = txTo.vin[nIn];
assert(txin.prevout.n < txFrom.vout.size());
assert(txin.prevout.hash == txFrom.GetHash());
- const CTxOut& txout = txFrom.vout[txin.prevout.n];
+ const auto& txout = txFrom.vout[txin.prevout.n];
return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
}
static CScript PushAll(const vector<valtype>& values)
{
CScript result;
- for(const valtype& v : values)
+ for(const auto& v : values)
result << v;
return result;
}
{
// Combine all the signatures we've got:
set<valtype> allsigs;
- for(const valtype& v : sigs1)
+ for(const auto& v : sigs1)
{
if (!v.empty())
allsigs.insert(v);
}
- for(const valtype& v : sigs2)
+ for(const auto& v : sigs2)
{
if (!v.empty())
allsigs.insert(v);
// Build a map of pubkey -> signature by matching sigs to pubkeys:
assert(vSolutions.size() > 1);
- unsigned int nSigsRequired = vSolutions.front()[0];
- unsigned int nPubKeys = (unsigned int)(vSolutions.size()-2);
+ auto nSigsRequired = (uint32_t)vSolutions.front()[0];
+ auto nPubKeys = (uint32_t)(vSolutions.size()-2);
+
map<valtype, valtype> sigs;
- for(const valtype& sig : allsigs)
+ for(const auto& sig : allsigs)
{
for (unsigned int i = 0; i < nPubKeys; i++)
{
- const valtype& pubkey = vSolutions[i+1];
+ const auto& pubkey = vSolutions[i+1];
if (sigs.count(pubkey))
continue; // Already got a sig for this pubkey
}
}
// Now build a merged CScript:
- unsigned int nSigsHave = 0;
+ uint32_t nSigsHave = 0;
CScript result; result << OP_0; // pop-one-too-many workaround
- for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
+ for (uint32_t i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
{
if (sigs.count(vSolutions[i+1]))
{
}
}
// Fill any missing with OP_0:
- for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
+ for (auto i = nSigsHave; i < nSigsRequired; i++)
result << OP_0;
return result;
unsigned int CScript::GetSigOpCount(bool fAccurate) const
{
- unsigned int n = 0;
+ uint32_t n = 0;
auto pc = begin();
- opcodetype lastOpcode = OP_INVALIDOPCODE;
+ auto lastOpcode = OP_INVALIDOPCODE;
while (pc < end())
{
opcodetype opcode;