static constexpr bool DEFAULT_MEMPOOL_FULL_RBF{true}; vSeeds.emplace_back("seed.btc.petertodd.net."); // Peter Todd, only supports x1, x5, x9, and xd vSeeds.emplace_back("seed.tbtc.petertodd.net."); vSeeds.push_back(CDNSSeedData("petertodd.org", "seed.btc.petertodd.org", true)); // Peter Todd, only supports x1, x5, x9, and xd bool fOptIntoFullRbf = DEFAULT_OPT_INTO_FULL_RBF; // Note how the sequence number is set to non-maxint so that // the nLockTime set above actually works. std::numeric_limits::max() - (fOptIntoFullRbf ? 2 : 1))); strUsage += HelpMessageOpt("-optintofullrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_OPT_INTO_FULL_RBF)); fOptIntoFullRbf = GetBoolArg("-optintofullrbf", DEFAULT_OPT_INTO_FULL_RBF); extern bool fOptIntoFullRbf; //! -optintofullrbf default static const bool DEFAULT_OPT_INTO_FULL_RBF = false; vSeeds.push_back(CDNSSeedData("petertodd.org", "seed.tbtc.petertodd.org", true)); if (!(nLocalServices & NODE_BLOOM) && !pfrom->fWhitelisted) { LogPrint("net", "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom->GetId()); pfrom->fDisconnect = true; return true; } /** Context-dependent validity checks. * By "context", we mean only the previous block headers, but not the UTXO * set; UTXO-related validity checks are done in ConnectBlock(). */ /** Apply the effects of this block (with given index) on the UTXO set represented by coins. * Validity checks that depend on the UTXO set are also done; ConnectBlock() * can fail if those validity checks fail (among other reasons). */ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false); /** Undo the effects of this block (with given index) on the UTXO set represented by coins. * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean * will be true if no problems were found. Otherwise, the return value will be false in case * of problems. Note that in any case, coins may be modified. */ bool DisconnectBlock(const CBlock& block, CValidationState& state, const CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL); // Skip ECDSA signature verification when connecting blocks before the // last block chain checkpoint. Assuming the checkpoints are valid this // is safe because block merkle hashes are still computed and checked, // and any change will be caught at the next checkpoint. Of course, if // the checkpoint is for a chain that's invalid due to false scriptSigs // this optimisation would allow an invalid chain to be accepted. // Now that we know Tor is running setup the proxy for onion addresses // if -onion isn't set to something else. if (GetArg("-onion", "") == "") { proxyType addrOnion = proxyType(CService("127.0.0.1", 9050), true); SetProxy(NET_TOR, addrOnion); SetReachable(NET_TOR); } X(fRelayTxes); bool fRelayTxes; " \"relaytxes\":true|false, (boolean) Whether peer has asked us to relay transactions to it\n" obj.push_back(Pair("relaytxes", stats.fRelayTxes)); result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast())); result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast())); " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\": xxxxxx, (numeric) median time for the current best block\n" // BIP113 will require that time-locked transactions have nLockTime set to // less than the median time of the previous block they're contained in. // When the next block is created its previous block will be the current // chain tip, so we use that to calculate the median time passed to // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set. if (origTx.vout.size() == 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "TX must have at least one output"); includeWatching = params[1].get_bool(); obj.push_back(Pair("mediantime", (int64_t)chainActive.Tip()->GetMedianTimePast())); " \"fee\": n, (numeric) Fee the resulting transaction pays\n" // If we don't hold the lock allConflicting might be incomplete; the // subsequent RemoveStaged() and addUnchecked() calls don't guarantee // mempool consistency for us. LOCK(pool.cs); set setConflictsParents; BOOST_FOREACH(const CTxIn &txin, mi->GetTx().vin) { setConflictsParents.insert(txin.prevout.hash); } for (unsigned int j = 0; j < tx.vin.size(); j++) { // We don't want to accept replacements that require low // feerate junk to be mined first. Ideally we'd keep track of // the ancestor feerates and make the decision based on that, // but for now requiring all new inputs to be confirmed works. if (!setConflictsParents.count(tx.vin[j].prevout.hash)) { // Rather than check the UTXO set - potentially expensive - // it's cheaper to just check if the new input refers to a // tx that's in the mempool. if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end()) return state.DoS(0, error("AcceptToMemoryPool: replacement %s adds unconfirmed input, idx %d", hash.ToString(), j), REJECT_NONSTANDARD, "replacement-adds-unconfirmed"); } } CFeeRate newFeeRate(nFees, nSize); // Don't allow the replacement to reduce the feerate of the // mempool. // // We usually don't want to accept replacements with lower // feerates than what they replaced as that would lower the // feerate of the next block. Requiring that the feerate always // be increased is also an easy-to-reason about way to prevent // DoS attacks via replacements. // // The mining code doesn't (currently) take children into // account (CPFP) so we only consider the feerates of // transactions being directly replaced, not their indirect // descendants. While that does mean high feerate children are // ignored when deciding whether or not to replace, we do // require the replacement to pay more overall fees too, // mitigating most cases. CFeeRate oldFeeRate(mi->GetFee(), mi->GetTxSize()); if (newFeeRate <= oldFeeRate) { return state.DoS(0, error("AcceptToMemoryPool: rejecting replacement %s; new feerate %s <= old feerate %s", hash.ToString(), newFeeRate.ToString(), oldFeeRate.ToString()), REJECT_INSUFFICIENTFEE, "insufficient fee"); } // For efficiency we simply sum up the pre-calculated // fees/size-with-descendants values from the mempool package // tracking; this does mean the pathological case of diamond tx // graphs will be overcounted. // The replacement must pay greater fees than the transactions it // replaces - if we did the bandwidth used by those conflicting // transactions would not be paid for. // Finally in addition to paying more fees than the conflicts the // new transaction must pay for its own bandwidth. set setConflicts; BOOST_FOREACH(const CTxIn &txin, tx.vin) if (pool.mapNextTx.count(txin.prevout)) const CTransaction *ptxConflicting = pool.mapNextTx[txin.prevout].ptx; if (!setConflicts.count(ptxConflicting->GetHash())) { // Allow opt-out of transaction replacement by setting // nSequence >= maxint-1 on all inputs. // // maxint-1 is picked to still allow use of nLockTime by // non-replacable transactions. All inputs rather than just one // is for the sake of multi-party protocols, where we don't // want a single party to be able to disable replacement. // // The opt-out ignores descendants as anyone relying on // first-seen mempool behavior should be checking all // unconfirmed ancestors anyway; doing otherwise is hopelessly // insecure. bool fReplacementOptOut = true; BOOST_FOREACH(const CTxIn &txin, ptxConflicting->vin) { if (txin.nSequence < std::numeric_limits::max()-1) { fReplacementOptOut = false; break; } } if (fReplacementOptOut) return state.Invalid(false, REJECT_CONFLICT, "txn-mempool-conflict"); setConflicts.insert(ptxConflicting->GetHash()); } // A transaction that spends outputs that would be replaced by it is invalid. Now // that we have the set of all ancestors we can detect this // pathological case by making sure setConflicts and setAncestors don't // intersect. BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) { const uint256 &hashAncestor = ancestorIt->GetTx().GetHash(); if (setConflicts.count(hashAncestor)) { return state.DoS(10, error("AcceptToMemoryPool: %s spends conflicting transaction %s", hash.ToString(), hashAncestor.ToString()), REJECT_INVALID, "bad-txns-spends-conflicting-tx"); } } // Check if it's economically rational to mine this transaction rather // than the ones it replaces. CAmount nConflictingFees = 0; size_t nConflictingSize = 0; if (setConflicts.size()) { LOCK(pool.cs); // For efficiency we simply sum up the pre-calculated // fees/size-with-descendants values from the mempool package // tracking; this does mean the pathological case of diamond tx // graphs will be overcounted. BOOST_FOREACH(const uint256 hashConflicting, setConflicts) { CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting); if (mi == pool.mapTx.end()) continue; nConflictingFees += mi->GetFeesWithDescendants(); nConflictingSize += mi->GetSizeWithDescendants(); } // First of all we can't allow a replacement unless it pays greater // fees than the transactions it conflicts with - if we did the // bandwidth used by those conflicting transactions would not be // paid for if (nFees < nConflictingFees) { return state.DoS(0, error("AcceptToMemoryPool: rejecting replacement %s, less fees than conflicting txs; %s < %s", hash.ToString(), FormatMoney(nFees), FormatMoney(nConflictingFees)), REJECT_INSUFFICIENTFEE, "insufficient fee"); } // Secondly in addition to paying more fees than the conflicts the // new transaction must additionally pay for its own bandwidth. CAmount nDeltaFees = nFees - nConflictingFees; if (nDeltaFees < ::minRelayTxFee.GetFee(nSize)) { return state.DoS(0, error("AcceptToMemoryPool: rejecting replacement %s, not enough additional fees to relay; %s < %s", hash.ToString(), FormatMoney(nDeltaFees), FormatMoney(::minRelayTxFee.GetFee(nSize))), REJECT_INSUFFICIENTFEE, "insufficient fee"); } // Finally replace only if we end up with a larger fees-per-kb than // the replacements. CFeeRate oldFeeRate(nConflictingFees, nConflictingSize); CFeeRate newFeeRate(nFees, nSize); if (newFeeRate <= oldFeeRate) { return state.DoS(0, error("AcceptToMemoryPool: rejecting replacement %s; new feerate %s <= old feerate %s", hash.ToString(), newFeeRate.ToString(), oldFeeRate.ToString()), REJECT_INSUFFICIENTFEE, "insufficient fee"); } } // Remove conflicting transactions from the mempool list ltxConflicted; pool.removeConflicts(tx, ltxConflicted); BOOST_FOREACH(const CTransaction &txConflicted, ltxConflicted) { LogPrint("mempool", "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n", txConflicted.GetHash().ToString(), hash.ToString(), FormatMoney(nFees - nConflictingFees), (int)nSize - (int)nConflictingSize); } } else if (reply.code == 510) { // 510 Unrecognized command LogPrintf("[tor] Add onion failed with unrecognized command (You probably need to upgrade Tor)\n"); LogPrintf("[tor] Add onion failed; error code %d\n", reply.code); softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams)); // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks, // when 75% of the network has upgraded: // Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4 // blocks, when 75% of the network has upgraded: if (block.nVersion >= 4 && IsSuperMajority(4, pindex->pprev, chainparams.GetConsensus().nMajorityEnforceBlockUpgrade, chainparams.GetConsensus())) { flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY; } // Reject block.nVersion=3 blocks when 95% (75% on testnet) of the network has upgraded: if (block.nVersion < 4 && IsSuperMajority(4, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams)) return state.Invalid(error("%s : rejected nVersion=3 block", __func__), REJECT_OBSOLETE, "bad-version"); static const int32_t CURRENT_VERSION=4; bitcoinconsensus_SCRIPT_FLAGS_VERIFY_NONE = 0, bitcoinconsensus_SCRIPT_FLAGS_VERIFY_P2SH = (1U << 0), // evaluate P2SH (BIP16) subscripts bitcoinconsensus_SCRIPT_FLAGS_VERIFY_DERSIG = (1U << 2), // enforce strict DER (BIP66) compliance bitcoinconsensus_SCRIPT_FLAGS_VERIFY_CHECKLOCKTIMEVERIFY = (1U << 9), // enable CHECKLOCKTIMEVERIFY (BIP65) } else if (whichType == TX_NULL_DATA && (!GetBoolArg("-datacarrier", true) || scriptPubKey.size() > nMaxDatacarrierBytes)) return false; // The template matching params OP_SMALLINTEGER/etc are defined in opcodetype enum // Provably prunable, data-carrying output // // So long as script passes the IsUnspendable() test and all but the first // byte passes the IsPushOnly() test we don't care what exactly is in the // script. if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) { typeRet = TX_NULL_DATA; return true; } static const unsigned int MAX_OP_RETURN_RELAY = 83; //! bytes (+1 for OP_RETURN, +2 for the pushdata opcodes) // MAX_OP_RETURN_RELAY-byte TX_NULL_DATA (standard) BOOST_CHECK_EQUAL(MAX_OP_RETURN_RELAY, t.vout[0].scriptPubKey.size()); // MAX_OP_RETURN_RELAY+1-byte TX_NULL_DATA (non-standard) BOOST_CHECK_EQUAL(MAX_OP_RETURN_RELAY + 1, t.vout[0].scriptPubKey.size()); BOOST_CHECK(!IsStandardTx(t, reason)); // Data payload can be encoded in any way... t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex(""); BOOST_CHECK(IsStandardTx(t, reason)); t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("00") << ParseHex("01"); BOOST_CHECK(IsStandardTx(t, reason)); // OP_RESERVED *is* considered to be a PUSHDATA type opcode by IsPushOnly()! t.vout[0].scriptPubKey = CScript() << OP_RETURN << OP_RESERVED << -1 << 0 << ParseHex("01") << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10 << 11 << 12 << 13 << 14 << 15 << 16; BOOST_CHECK(IsStandardTx(t, reason)); t.vout[0].scriptPubKey = CScript() << OP_RETURN << 0 << ParseHex("01") << 2 << ParseHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); BOOST_CHECK(IsStandardTx(t, reason)); // ...so long as it only contains PUSHDATA's t.vout[0].scriptPubKey = CScript() << OP_RETURN << OP_RETURN; bool CScript::IsPushOnly(const_iterator pc) const bool CScript::IsPushOnly() const { return this->IsPushOnly(begin()); } bool IsPushOnly(const_iterator pc) const; vSolutionsRet.clear(); /** * Filter for transactions that were recently rejected by * AcceptToMemoryPool. These are not rerequested until the chain tip * changes, at which point the entire filter is reset. Protected by * cs_main. * * Without this filter we'd be re-requesting txs from each of our peers, * increasing bandwidth consumption considerably. For instance, with 100 * peers, half of which relay a tx we don't accept, that might be a 50x * bandwidth increase. A flooding attacker attempting to roll-over the * filter using minimum-sized, 60byte, transactions might manage to send * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a * two minute window to send invs to us. * * Decreasing the false positive rate is fairly cheap, so we pick one in a * million to make it highly unlikely for users to have issues with this * filter. * * Memory used: 1.7MB */ boost::scoped_ptr recentRejects; uint256 hashRecentRejectsChainTip; recentRejects.reset(NULL); // Initialize global variables that cannot be constructed at startup. recentRejects.reset(new CRollingBloomFilter(120000, 0.000001)); if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip) { // If the chain tip has changed previously rejected transactions // might be now valid, e.g. due to a nLockTime'd tx becoming valid, // or a double-spend. Reset the rejects filter and give those // txs a second chance. hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash(); recentRejects->reset(); } return recentRejects->contains(inv.hash) || mempool.exists(inv.hash) || mapOrphanTransactions.count(inv.hash) || pcoinsTip->HaveCoins(inv.hash); recentRejects->insert(orphanHash); } else { // AcceptToMemoryPool() returned false, possibly because the tx is // already in the mempool; if the tx isn't in the mempool that // means it was rejected and we shouldn't ask for it again. if (!mempool.exists(tx.GetHash())) { recentRejects->insert(tx.GetHash()); } if (pfrom->fWhitelisted) { // Always relay transactions received from whitelisted peers, even // if they were rejected from the mempool, allowing the node to // function as a gateway for nodes hidden behind it. // // FIXME: This includes invalid transactions, which means a // whitelisted peer could get us banned! We may want to change // that. RelayTransaction(tx); } #include "random.h" void CBloomFilter::reset(unsigned int nNewTweak) { clear(); nTweak = nNewTweak; } reset(nTweak); void CRollingBloomFilter::reset(unsigned int nNewTweak) if (!nNewTweak) nNewTweak = GetRand(std::numeric_limits::max()); b1.reset(nNewTweak); b2.reset(nNewTweak); void reset(unsigned int nNewTweak); * Construct it with the number of items to keep track of, and a false-positive * rate. Unlike CBloomFilter, by default nTweak is set to a cryptographically * secure random value for you. Similarly rather than clear() the method * reset() is provided, which also changes nTweak to decrease the impact of * false-positives. CRollingBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweak = 0); void reset(unsigned int nNewTweak = 0); pnode->addrKnown.reset(); addrKnown(5000, 0.001), CRollingBloomFilter rb1(100, 0.01, 1); rb1.reset(1); CRollingBloomFilter rb2(1000, 0.001, 1); void CRollingBloomFilter::insert(const uint256& hash) { if (nInsertions == 0) { b1.clear(); } else if (nInsertions == nBloomSize / 2) { b2.clear(); } b1.insert(hash); b2.insert(hash); if (++nInsertions == nBloomSize) { nInsertions = 0; } } bool CRollingBloomFilter::contains(const uint256& hash) const { if (nInsertions < nBloomSize / 2) { return b2.contains(hash); } return b1.contains(hash); } void insert(const uint256& hash); bool contains(const uint256& hash) const; SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY; break; case OP_CHECKLOCKTIMEVERIFY: { if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) { // not enabled; treat as a NOP2 if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) { return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS); } break; } if (stack.size() < 1) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); // Note that elsewhere numeric opcodes are limited to // operands in the range -2**31+1 to 2**31-1, however it is // legal for opcodes to produce results exceeding that // range. This limitation is implemented by CScriptNum's // default 4-byte limit. // // If we kept to that limit we'd have a year 2038 problem, // even though the nLockTime field in transactions // themselves is uint32 which only becomes meaningless // after the year 2106. // // Thus as a special case we tell CScriptNum to accept up // to 5-byte bignums, which are good until 2**39-1, well // beyond the 2**32-1 limit of the nLockTime field itself. const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5); // In the rare event that the argument may be < 0 due to // some arithmetic being done first, you can always use // 0 MAX CHECKLOCKTIMEVERIFY. if (nLockTime < 0) return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME); // Actually compare the specified lock time with the transaction. if (!checker.CheckLockTime(nLockTime)) return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME); break; } case OP_NOP1: case OP_NOP3: case OP_NOP4: case OP_NOP5: bool TransactionSignatureChecker::CheckLockTime(const CScriptNum& nLockTime) const { // There are two times of nLockTime: lock-by-blockheight // and lock-by-blocktime, distinguished by whether // nLockTime < LOCKTIME_THRESHOLD. // // We want to compare apples to apples, so fail the script // unless the type of nLockTime being tested is the same as // the nLockTime in the transaction. if (!( (txTo->nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) || (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD) )) return false; // Now that we know we're comparing apples-to-apples, the // comparison is a simple numeric one. if (nLockTime > (int64_t)txTo->nLockTime) return false; // Finally the nLockTime feature can be disabled and thus // CHECKLOCKTIMEVERIFY bypassed if every txin has been // finalized by setting nSequence to maxint. The // transaction would be allowed into the blockchain, making // the opcode ineffective. // // Testing if this vin is not final is sufficient to // prevent this condition. Alternatively we could test all // inputs, but testing just this input minimizes the data // required to prove correct CHECKLOCKTIMEVERIFY execution. if (txTo->vin[nIn].IsFinal()) return false; return true; } // Verify CHECKLOCKTIMEVERIFY // // See BIP65 for details. SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY = (1U << 9), virtual bool CheckLockTime(const CScriptNum& nLockTime) const { return false; } bool CheckLockTime(const CScriptNum& nLockTime) const; OP_CHECKLOCKTIMEVERIFY = OP_NOP2, case SCRIPT_ERR_NEGATIVE_LOCKTIME: return "Negative locktime"; case SCRIPT_ERR_UNSATISFIED_LOCKTIME: return "Locktime requirement not satisfied"; /* OP_CHECKLOCKTIMEVERIFY */ SCRIPT_ERR_NEGATIVE_LOCKTIME, SCRIPT_ERR_UNSATISFIED_LOCKTIME, (string("CLEANSTACK"), (unsigned int)SCRIPT_VERIFY_CLEANSTACK) (string("CHECKLOCKTIMEVERIFY"), (unsigned int)SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY); // For a large miner the value of the transactions in the best block and // the mempool can exceed the cost of delibrately attempting to mine two // blocks to orphan the current best block. By setting nLockTime such that // only the next block can include the transaction, we discourage this // practice as the height restricted and limited blocksize gives miners // considering fee sniping fewer options for pulling off this attack. // // A simple way to think about this is from the wallet's point of view we // always want the blockchain to move forward. By setting nLockTime this // way we're basically making the statement that we only want this // transaction to appear in the next block; we don't want to potentially // encourage reorgs by allowing transactions to appear at lower heights // than the next block in forks of the best chain. // // Of course, the subsidy is high enough, and transaction volume low // enough, that fee sniping isn't a problem yet, but by implementing a fix // now we ensure code won't be written that makes assumptions about // nLockTime that preclude a fix later. txNew.nLockTime = chainActive.Height(); UniValue blockheaderToJSON(const CBlockIndex* blockindex) { UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", blockindex->nVersion)); result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex())); result.push_back(Pair("time", (int64_t)blockindex->nTime)); result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce)); result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); return result; } UniValue getblockheader(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblockheader \"hash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n" "If verbose is true, returns an Object with information about blockheader .\n" "\nArguments:\n" "1. \"hash\" (string, required) The block hash\n" "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "{\n" " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n" "}\n" "\nResult (for verbose=false):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" "\nExamples:\n" + HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"") + HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"") ); LOCK(cs_main); std::string strHash = params[0].get_str(); uint256 hash(uint256S(strHash)); bool fVerbose = true; if (params.size() > 1) fVerbose = params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << pblockindex->GetBlockHeader(); std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockheaderToJSON(pblockindex); } { "getblockheader", 1 }, { "blockchain", "getblockheader", &getblockheader, true }, extern UniValue getblockheader(const UniValue& params, bool fHelp); /** No amount larger than this (in satoshi) is valid. * * Note that this constant is *not* the total money supply, which in Bitcoin * currently happens to be less than 21,000,000 BTC for various reasons, but * rather a sanity check. As this sanity check is used by consensus-critical * validation code, the exact value of the MAX_MONEY constant is consensus * critical; in unusual circumstances like a(nother) overflow bug that allowed * for the creation of coins out of thin air modification could lead to a fork. * */ bool CheckFinalTx(const CTransaction &tx) { AssertLockHeld(cs_main); return IsFinalTx(tx, chainActive.Height() + 1, GetAdjustedTime()); } if (!CheckFinalTx(tx)) return state.DoS(0, error("AcceptToMemoryPool: non-final"), /** * Check if transaction is final and can be included in a block with the * specified height and time. Consensus critical. */ bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime); /** * Check if transaction will be final in the next block to be created. * * Calls IsFinalTx() with current block height and appropriate block time. */ bool CheckFinalTx(const CTransaction &tx); pblock->nTime = GetAdjustedTime(); if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, pblock->nTime)) if (!CheckFinalTx(wtx)) if (!CheckFinalTx(wtx)) BOOST_CHECK(!CheckFinalTx(tx)); BOOST_CHECK(!CheckFinalTx(tx2)); // FIXME: we should *actually* create a new block so the following test // works; CheckFinalTx() isn't fooled by monkey-patching nHeight. //BOOST_CHECK(CheckFinalTx(tx)); //BOOST_CHECK(CheckFinalTx(tx2)); if (wtx.IsCoinBase() || !CheckFinalTx(wtx)) if (wtx.IsCoinBase() || !CheckFinalTx(wtx)) if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0) if (wtx.IsCoinBase() || !CheckFinalTx(wtx)) if (!CheckFinalTx(*this)) if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) if (!CheckFinalTx(*pcoin)) if (!CheckFinalTx(*pcoin) || !pcoin->IsTrusted()) static const size_t nDefaultMaxNumSize = 4; explicit CScriptNum(const std::vector& vch, bool fRequireMinimal, const size_t nMaxNumSize = nDefaultMaxNumSize) if (scriptnum.getvch().size() <= CScriptNum::nDefaultMaxNumSize) // Empty signature. Not strictly DER encoded, but allowed to provide a // compact way to provide an invalid signature for use with CHECK(MULTI)SIG if (vchSig.size() == 0) { return true; } // Only accept nLockTime-using transactions that can be mined in the next // block; we don't want our mempool filled up with transactions that can't // be mined yet. // // However, IsFinalTx() is confusing... Without arguments, it uses // chainActive.Height() to evaluate nLockTime; when a block is accepted, // chainActive.Height() is set to the value of nHeight in the block. // However, when IsFinalTx() is called within CBlock::AcceptBlock(), the // height of the block *being* evaluated is what is used. Thus if we want // to know if a transaction can be part of the *next* block, we need to // call IsFinalTx() with one more than chainActive.Height(). // // Timestamps on the other hand don't get any special treatment, because we // can't know what timestamp the next block will have, and there aren't // timestamp applications where it matters. if (!IsFinalTx(tx, chainActive.Height() + 1)) return state.DoS(0, error("AcceptToMemoryPool : non-final"), REJECT_NONSTANDARD, "non-final"); CScriptID::CScriptID(const CScript& in) : uint160(Hash160(in.begin(), in.end())) {} // Note how this makes the exact order of pubkey/signature evaluation // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set. // See the script_(in)valid tests for details. // then too many signatures have failed. Exit early, // without checking any further signatures. break; { if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS); } SCRIPT_VERIFY_MINIMALDATA = (1U << 6), // Discourage use of NOPs reserved for upgrades (NOP1-10) // // Provided so that nodes can avoid accepting or mining transactions // containing executed NOP's whose meaning may change after a soft-fork, // thus rendering the script invalid; with this flag set executing // discouraged NOPs fails the script. This verification flag will never be // a mandatory flag applied to scripts in a block. NOPs that are not // executed, e.g. within an unexecuted IF ENDIF block, are *not* rejected. SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS = (1U << 7) case SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS: return "NOPx reserved for soft-fork upgrades"; /* softfork safeness */ SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS, SCRIPT_VERIFY_NULLDUMMY | SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS; (string("NULLDUMMY"), (unsigned int)SCRIPT_VERIFY_NULLDUMMY) (string("DISCOURAGE_UPGRADABLE_NOPS"), (unsigned int)SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS); // Check again against just the consensus-critical mandatory script // verification flags, in case of bugs in the standard flags that cause // transactions to pass as valid when they're actually invalid. For // instance the STRICTENC flag was incorrectly allowing certain // CHECKSIG NOT scripts to pass, even though they were invalid. // // There is a similar check in CreateNewBlock() to prevent creating // invalid blocks, however allowing such transactions into the mempool // can be exploited as a DoS attack. if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true)) { return error("AcceptToMemoryPool: : BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString()); } if (fRequireMinimal && vch.size() > 0) { // Check that the number is encoded with the minimum possible // number of bytes. // // If the most-significant-byte - excluding the sign bit - is zero // then we're not minimal. Note how this test also rejects the // negative-zero encoding, 0x80. if ((vch.back() & 0x7f) == 0) { // One exception: if there's more than one byte and the most // significant bit of the second-most-significant-byte is set // it would conflict with the sign bit. An example of this case // is +-255, which encode to 0xff00 and 0xff80 respectively. // (big-endian). if (vch.size() <= 1 || (vch[vch.size() - 2] & 0x80) == 0) { throw scriptnum_error("non-minimally encoded script number"); } } // Discourage fee sniping. // // However because of a off-by-one-error in previous versions we need to // neuter it by setting nLockTime to at least one less than nBestHeight. // Secondly currently propagation of transactions created for block heights // corresponding to blocks that were just mined may be iffy - transactions // aren't re-accepted into the mempool - we additionally neuter the code by // going ten blocks back. Doesn't yet do anything for sniping, but does act // to shake out wallet bugs like not showing nLockTime'd transactions at // all. txNew.nLockTime = std::max(0, chainActive.Height() - 10); // Secondly occasionally randomly pick a nLockTime even further back, so // that transactions that are delayed after signing for whatever reason, // e.g. high-latency mix networks and some CoinJoin implementations, have // better privacy. if (GetRandInt(10) == 0) txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100)); assert(txNew.nLockTime <= (unsigned int)chainActive.Height()); assert(txNew.nLockTime < LOCKTIME_THRESHOLD); // // Note how the sequence number is set to max()-1 so that the // nLockTime set above actually works. txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(), std::numeric_limits::max()-1)); " \"scriptPubKey\" : \"hex\", (string) The hex encoded scriptPubKey generated by the address\n" CScript scriptPubKey = GetScriptForDestination(dest); ret.push_back(Pair("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); // WARNING! If you're reading this because you're learning about crypto // and/or designing a new system that will use merkle trees, keep in mind // that the following merkle tree algorithm has a serious flaw related to // duplicate txids, resulting in a vulnerability. (CVE-2012-2459) Bitcoin // has since worked around the flaw, but for new applications you should // use something different; don't just copy-and-paste this code without // understanding the problem first. return error("Non-canonical public key: neither compressed nor uncompressed"); // Note how a script with an invalid PUSHDATA returns False. BOOST_AUTO_TEST_CASE(script_IsPushOnly_on_invalid_scripts) { // IsPushOnly returns false when given a script containing only pushes that // are invalid due to truncation. IsPushOnly() is consensus critical // because P2SH evaluation uses it, although this specific behavior should // not be consensus critical as the P2SH evaluation would fail first due to // the invalid push. Still, it doesn't hurt to test it explicitly. static const unsigned char direct[] = { 1 }; BOOST_CHECK(!CScript(direct, direct+sizeof(direct)).IsPushOnly()); } // Check that the transaction doesn't have an excessive number of // sigops, making it impossible to mine. Since the coinbase transaction // itself can contain sigops MAX_TX_SIGOPS is less than // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than // merely non-standard transaction. unsigned int nSigOps = GetLegacySigOpCount(tx); nSigOps += GetP2SHSigOpCount(tx, view); if (nSigOps > MAX_TX_SIGOPS) return state.DoS(0, error("AcceptToMemoryPool : too many sigops %s, %d > %d", hash.ToString(), nSigOps, MAX_TX_SIGOPS), REJECT_NONSTANDARD, "bad-txns-too-many-sigops"); /** The maximum number of sigops we're willing to relay/mine in a single tx */ static const unsigned int MAX_TX_SIGOPS = MAX_BLOCK_SIGOPS/5; // Check that the transaction doesn't have an excessive number of // sigops, making it impossible to mine. Since the coinbase transaction // itself can contain sigops MAX_TX_SIGOPS is less than // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than // merely non-standard transaction. unsigned int nSigOps = GetLegacySigOpCount(tx); nSigOps += GetP2SHSigOpCount(tx, view); if (nSigOps > MAX_TX_SIGOPS) return state.DoS(0, error("AcceptToMemoryPool : too many sigops %s, %d > %d", hash.ToString(), nSigOps, MAX_TX_SIGOPS), REJECT_NONSTANDARD, "bad-txns-too-many-sigops"); /** The maximum number of sigops we're willing to relay/mine in a single tx */ static const unsigned int MAX_TX_SIGOPS = MAX_BLOCK_SIGOPS/5; // Bits 24-31 are reserved for temporary experiments. Just pick a bit that // isn't getting used, or one not being used much, and notify the // bitcoin-development mailing list. Remember that service bits are just // unauthenticated advertisements, so your code must be robust against // collisions and other cases where nodes may be advertising a service they // do not actually support. Other service bits should be allocated via the // BIP process. " \"services\":\"xxxxxxxxxxxxxxxx\", (string) The services offered\n" obj.push_back(Pair("services", strprintf("%016x", stats.nServices))); " \"localservices\": \"xxxxxxxxxxxxxxxx\", (string) the services we offer to the network\n" obj.push_back(Pair("localservices", strprintf("%016x", nLocalServices))); if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) return error("CBasicKeyStore::AddCScript() : redeemScripts > %i bytes are invalid", MAX_SCRIPT_ELEMENT_SIZE); CScript _createmultisig_redeemScript(const Array& params) if (result.size() > MAX_SCRIPT_ELEMENT_SIZE) throw runtime_error( strprintf("redeemScript exceeds size limit: %d > %d", result.size(), MAX_SCRIPT_ELEMENT_SIZE)); CScript inner = _createmultisig_redeemScript(params); extern CScript _createmultisig_redeemScript(const Array& params); CScript inner = _createmultisig_redeemScript(params); // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed // keys. (remember the 520 byte limit on redeemScript size) That works // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)=1624 // bytes of scriptSig, which we round off to 1650 bytes for some minor // future-proofing. That's also enough to spend a 20-of-20 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not // considered standard) if (txin.scriptSig.size() > 1650) { if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) { // Check whether the failure was caused by a // non-mandatory script verification check, such as // non-standard DER encodings or non-null dummy // arguments; if so, don't trigger DoS protection to // avoid splitting the network between upgraded and // non-upgraded nodes. CScriptCheck check(coins, tx, i, flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, 0); return state.Invalid(false, REJECT_NONSTANDARD, "non-mandatory-script-verify-flag"); // Failures of other flags indicate a transaction that is // invalid in new blocks, e.g. a invalid P2SH. We DoS ban // such nodes as they are not following the protocol. That // said during an upgrade careful thought should be taken // as to the correct behavior - we may want to continue // peering with non-upgraded nodes even after a soft-fork // super-majority vote has passed. return state.DoS(100,false, REJECT_INVALID, "mandatory-script-verify-flag-failed"); // // Failing one of these tests may trigger a DoS ban - see CheckInputs() for // details. // For convenience, standard but not mandatory verify flags. static const unsigned int STANDARD_NOT_MANDATORY_VERIFY_FLAGS = STANDARD_SCRIPT_VERIFY_FLAGS & ~MANDATORY_SCRIPT_VERIFY_FLAGS; // Clean up stack of actual arguments while (i-- > 1) // A bug causes CHECKMULTISIG to consume one extra argument // whose contents were not checked in any way. // // Unfortunately this is a potential source of mutability, // so optionally verify it is exactly equal to zero prior // to removing it from the stack. if (stack.size() < 1) return false; if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size()) return error("CHECKMULTISIG dummy argument not null"); popstack(stack); SCRIPT_VERIFY_NULLDUMMY = (1U << 4), // verify dummy stack item consumed by CHECKMULTISIG is of zero-length SCRIPT_VERIFY_STRICTENC | SCRIPT_VERIFY_NULLDUMMY; mapFlagNames["NULLDUMMY"] = SCRIPT_VERIFY_NULLDUMMY; #include #include using namespace boost::algorithm; unsigned int ParseFlags(string strFlags){ unsigned int flags = 0; vector words; split(words, strFlags, is_any_of(",")); // Note how NOCACHE is not included as it is a runtime-only flag. static map mapFlagNames; if (mapFlagNames.size() == 0) { mapFlagNames["NONE"] = SCRIPT_VERIFY_NONE; mapFlagNames["P2SH"] = SCRIPT_VERIFY_P2SH; mapFlagNames["STRICTENC"] = SCRIPT_VERIFY_STRICTENC; mapFlagNames["EVEN_S"] = SCRIPT_VERIFY_EVEN_S; } BOOST_FOREACH(string word, words) { if (!mapFlagNames.count(word)) BOOST_ERROR("Bad test: unknown verification flag '" << word << "'"); flags |= mapFlagNames[word]; } return flags; } // or [[[prevout hash, prevout index, prevout scriptPubKey], [input 2], ...],"], serializedTransaction, verifyFlags // // verifyFlags is a comma separated list of script verification flags to apply, or "NONE" if (test.size() != 3 || test[1].type() != str_type || test[2].type() != str_type) unsigned int verify_flags = ParseFlags(test[2].get_str()); BOOST_CHECK_MESSAGE(VerifyScript(tx.vin[i].scriptSig, mapprevOutScriptPubKeys[tx.vin[i].prevout], tx, i, verify_flags, 0), strTest); // or [[[prevout hash, prevout index, prevout scriptPubKey], [input 2], ...],"], serializedTransaction, verifyFlags // // verifyFlags is a comma separated list of script verification flags to apply, or "NONE" if (test.size() != 3 || test[1].type() != str_type || test[2].type() != str_type) unsigned int verify_flags = ParseFlags(test[2].get_str()); fValid = VerifyScript(tx.vin[i].scriptSig, mapprevOutScriptPubKeys[tx.vin[i].prevout], tx, i, verify_flags, 0); if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS)) unsigned int flags = STANDARD_SCRIPT_VERIFY_FLAGS, // Note that flags: we don't want to set mempool/IsStandard() // policy here, but we still have to ensure that the block we // create only contains transactions that are valid in new blocks. if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS)) if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, STANDARD_SCRIPT_VERIFY_FLAGS, 0)) return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STANDARD_SCRIPT_VERIFY_FLAGS, 0); // Mandatory script verification flags that all new blocks must comply with for // them to be valid. (but old blocks may not comply with) Currently just P2SH, // but in the future other flags may be added, such as a soft-fork to enforce // strict DER encoding. static const unsigned int MANDATORY_SCRIPT_VERIFY_FLAGS = SCRIPT_VERIFY_P2SH; // Standard script verification flags that standard transactions will comply // with. However scripts violating these flags may still be present in valid // blocks and we must accept those blocks. static const unsigned int STANDARD_SCRIPT_VERIFY_FLAGS = MANDATORY_SCRIPT_VERIFY_FLAGS | SCRIPT_VERIFY_STRICTENC; if (w.size() == 0) { // Empty string, ignore. (boost::split given '' will return one word) } else if (all(w, is_digit()) || // Check syntactic correctness. // // Note that this is consensus critical as CheckSig() calls it! // Treat non-final transactions as non-standard to prevent a specific type // of double-spend attack, as well as DoS attacks. (if the transaction // can't be mined, the attacker isn't expending resources broadcasting it) // Basically we don't want to propagate transactions that can't included in // the next block. // // However, IsFinalTx() is confusing... Without arguments, it uses // chainActive.Height() to evaluate nLockTime; when a block is accepted, chainActive.Height() // is set to the value of nHeight in the block. However, when IsFinalTx() // is called within CBlock::AcceptBlock(), the height of the block *being* // evaluated is what is used. Thus if we want to know if a transaction can // be part of the *next* block, we need to call IsFinalTx() with one more // than chainActive.Height(). // // Timestamps on the other hand don't get any special treatment, because we // can't know what timestamp the next block will have, and there aren't // timestamp applications where it matters. if (!IsFinalTx(tx, chainActive.Height() + 1)) { if (tx.IsCoinBase() || !IsFinalTx(tx, pindexPrev->nHeight + 1)) if (!IsFinalTx(wtx, chainActive.Height() + 1)) return tr("Open for %n more block(s)", "", wtx.nLockTime - chainActive.Height()); if (!IsFinalTx(wtx, chainActive.Height() + 1)) status.open_for = wtx.nLockTime - chainActive.Height(); CTransaction tx,tx2; // non-final txs in mempool SetMockTime(chainActive.Tip()->GetMedianTimePast()+1); // height locked tx.vin[0].prevout.hash = txFirst[0]->GetHash(); tx.vin[0].scriptSig = CScript() << OP_1; tx.vin[0].nSequence = 0; tx.vout[0].nValue = 4900000000LL; tx.vout[0].scriptPubKey = CScript() << OP_1; tx.nLockTime = chainActive.Tip()->nHeight+1; hash = tx.GetHash(); mempool.addUnchecked(hash, CTxMemPoolEntry(tx, 11, GetTime(), 111.0, 11)); BOOST_CHECK(!IsFinalTx(tx, chainActive.Tip()->nHeight + 1)); // time locked tx2.vin.resize(1); tx2.vin[0].prevout.hash = txFirst[1]->GetHash(); tx2.vin[0].prevout.n = 0; tx2.vin[0].scriptSig = CScript() << OP_1; tx2.vin[0].nSequence = 0; tx2.vout.resize(1); tx2.vout[0].nValue = 4900000000LL; tx2.vout[0].scriptPubKey = CScript() << OP_1; tx2.nLockTime = chainActive.Tip()->GetMedianTimePast()+1; hash = tx2.GetHash(); mempool.addUnchecked(hash, CTxMemPoolEntry(tx2, 11, GetTime(), 111.0, 11)); BOOST_CHECK(!IsFinalTx(tx2)); BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey)); // Neither tx should have make it into the template. BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 1); delete pblocktemplate; // However if we advance height and time by one, both will. chainActive.Tip()->nHeight++; SetMockTime(chainActive.Tip()->GetMedianTimePast()+2); BOOST_CHECK(IsFinalTx(tx, chainActive.Tip()->nHeight + 1)); BOOST_CHECK(IsFinalTx(tx2)); BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey)); BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 3); delete pblocktemplate; chainActive.Tip()->nHeight--; SetMockTime(0); out.push_back(Pair("type", GetTxnOutputType(type))); static multimap mTemplates; mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN)); return -1; if (typeRet == TX_NULL_DATA){ // This is data, not addresses return false; } // TX_NULL_DATA w/o PUSHDATA t.vout.resize(1); t.vout[0].scriptPubKey = CScript() << OP_RETURN; BOOST_CHECK(IsStandardTx(t, reason)); // Only one TX_NULL_DATA permitted in all cases t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"); t.vout[1].scriptPubKey = CScript() << OP_RETURN; BOOST_CHECK(!IsStandardTx(t, reason)); t.vout[0].scriptPubKey = CScript() << OP_RETURN; t.vout[1].scriptPubKey = CScript() << OP_RETURN; BOOST_CHECK(!IsStandardTx(t, reason)); obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end()))); { "decodescript", &decodescript, false, false }, extern json_spirit::Value decodescript(const json_spirit::Array& params, bool fHelp); void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex); ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o, true); void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex) if (fIncludeHex) out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); ScriptPubKeyToJSON(txout.scriptPubKey, o, false); Value decodescript(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decodescript \n" "Decode a hex-encoded script."); RPCTypeCheck(params, list_of(str_type)); Object r; CScript script; if (params[0].get_str().size() > 0){ vector scriptData(ParseHexV(params[0], "argument")); script = CScript(scriptData.begin(), scriptData.end()); } else { // Empty scripts are valid } ScriptPubKeyToJSON(script, r, false); r.push_back(Pair("p2sh", CBitcoinAddress(script.GetID()).ToString())); return r; } // Note how OP_RESERVED does not count towards the opcode limit. // Note that IsPushOnly() *does* consider OP_RESERVED to be a // push-type opcode, however execution of OP_RESERVED fails, so // it's not relevant to P2SH as the scriptSig would fail prior to // the P2SH special validation code being executed. for (int op = 0; op <= OP_NOP10; op++) // Allow OP_RESERVED to get into mapOpNames if (op < OP_NOP && op != OP_RESERVED) continue; // opcode, e.g. OP_ADD or ADD: #include #include #include "util.h" #include "hash.h" using namespace std; BOOST_AUTO_TEST_SUITE(hash_tests) BOOST_AUTO_TEST_CASE(murmurhash3) { #define T(expected, seed, data) BOOST_CHECK_EQUAL(MurmurHash3(seed, ParseHex(data)), expected) // Test MurmurHash3 with various inputs. Of course this is retested in the // bloom filter tests - they would fail if MurmurHash3() had any problems - // but is useful for those trying to implement Bitcoin libraries as a // source of test data for their MurmurHash3() primitive during // development. // // The magic number 0xFBA4C795 comes from CBloomFilter::Hash() T(0x00000000, 0x00000000, ""); T(0x6a396f08, 0xFBA4C795, ""); T(0x81f16f39, 0xffffffff, ""); T(0x514e28b7, 0x00000000, "00"); T(0xea3f0b17, 0xFBA4C795, "00"); T(0xfd6cf10d, 0x00000000, "ff"); T(0x16c6b7ab, 0x00000000, "0011"); T(0x8eb51c3d, 0x00000000, "001122"); T(0xb4471bf8, 0x00000000, "00112233"); T(0xe2301fa8, 0x00000000, "0011223344"); T(0xfc2e4a15, 0x00000000, "001122334455"); T(0xb074502c, 0x00000000, "00112233445566"); T(0x8034d2a0, 0x00000000, "0011223344556677"); T(0xb4698def, 0x00000000, "001122334455667788"); #undef T } BOOST_AUTO_TEST_SUITE_END() result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); // Truncate messages to the size of the tx in them unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); unsigned int oldSize = vMsg.size(); if (nSize < oldSize) { vMsg.resize(nSize); printf("truncating oversized TX %s (%u -> %u)\n", tx.GetHash().ToString().c_str(), oldSize, nSize); } static const char *strMainNetDNSSeed[][2] = { {NULL, NULL} }; static const char *strTestNetDNSSeed[][2] = { {"bitcoin.petertodd.org", "testnet-seed.bitcoin.petertodd.org"}, {NULL, NULL} static const char *(*strDNSSeed)[2] = fTestNet ? strTestNetDNSSeed : strMainNetDNSSeed; printf("Loading addresses from DNS seeds (could take a while)\n"); for (unsigned int seed_idx = 0; strDNSSeed[seed_idx][0] != NULL; seed_idx++) { if (HaveNameProxy()) { AddOneShot(strDNSSeed[seed_idx][1]); } else { vector vaddr; vector vAdd; if (LookupHost(strDNSSeed[seed_idx][1], vaddr)) { BOOST_FOREACH(CNetAddr& ip, vaddr) int nOneDay = 24*3600; CAddress addr = CAddress(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old vAdd.push_back(addr); found++; addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true)); obj.push_back(Pair("timeoffset", (boost::int64_t)GetTimeOffset())); int64 GetTimeOffset() { return nTimeOffset; } return GetTime() + GetTimeOffset(); int64 GetTimeOffset(); return tr("Open for %n more block(s)", "", wtx.nLockTime - nBestHeight + 1); status.open_for = wtx.nLockTime - nBestHeight + 1; int64 open_for; /**< Timestamp if status==OpenUntilDate, otherwise number of additional blocks that need to be mined before finalization */ status = tr("Open for %n more block(s)","",wtx->status.open_for); if (nRequired < 1) throw runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) strprintf("not enough keys supplied " "(got %d keys, but need at least %d to redeem)", keys.size(), nRequired));