aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--configure.ac7
-rw-r--r--contrib/linearize/README.md45
-rw-r--r--contrib/linearize/example-linearize.cfg4
-rwxr-xr-xcontrib/linearize/linearize-data.py43
-rwxr-xr-xcontrib/linearize/linearize-hashes.py42
-rwxr-xr-xqa/rpc-tests/wallet.py33
-rw-r--r--src/Makefile.am1
-rw-r--r--src/Makefile.test.include5
-rw-r--r--src/bench/bench.cpp14
-rw-r--r--src/bench/coin_selection.cpp8
-rw-r--r--src/bitcoin-cli.cpp32
-rw-r--r--src/coins.cpp37
-rw-r--r--src/coins.h5
-rw-r--r--src/init.cpp3
-rw-r--r--src/qt/paymentrequestplus.cpp4
-rw-r--r--src/qt/sendcoinsdialog.cpp13
-rw-r--r--src/rpc/blockchain.cpp10
-rw-r--r--src/rpc/mining.cpp6
-rw-r--r--src/support/events.h56
-rw-r--r--src/test/addrman_tests.cpp12
-rw-r--r--src/test/bloom_tests.cpp56
-rw-r--r--src/test/coins_tests.cpp199
-rw-r--r--src/test/dbwrapper_tests.cpp34
-rw-r--r--src/test/hash_tests.cpp2
-rw-r--r--src/test/key_tests.cpp24
-rw-r--r--src/test/multisig_tests.cpp22
-rw-r--r--src/test/net_tests.cpp4
-rw-r--r--src/test/netbase_tests.cpp8
-rw-r--r--src/test/pmt_tests.cpp2
-rw-r--r--src/test/pow_tests.cpp2
-rw-r--r--src/test/raii_event_tests.cpp88
-rw-r--r--src/test/rpc_tests.cpp138
-rw-r--r--src/test/script_P2SH_tests.cpp16
-rw-r--r--src/test/script_tests.cpp40
-rw-r--r--src/test/serialize_tests.cpp5
-rw-r--r--src/test/sigopcount_tests.cpp22
-rw-r--r--src/test/streams_tests.cpp3
-rw-r--r--src/test/timedata_tests.cpp2
-rw-r--r--src/test/transaction_tests.cpp80
-rw-r--r--src/test/univalue_tests.cpp37
-rw-r--r--src/test/util_tests.cpp4
-rw-r--r--src/txmempool.h2
-rw-r--r--src/util.h17
-rw-r--r--src/validation.cpp13
-rw-r--r--src/validation.h2
-rw-r--r--src/wallet/rpcwallet.cpp2
-rw-r--r--src/wallet/wallet.cpp77
47 files changed, 813 insertions, 468 deletions
diff --git a/configure.ac b/configure.ac
index 73414c633d..4723c69d5d 100644
--- a/configure.ac
+++ b/configure.ac
@@ -835,6 +835,13 @@ else
fi
fi
+save_CXXFLAGS="${CXXFLAGS}"
+CXXFLAGS="${CXXFLAGS} ${CRYPTO_CFLAGS} ${SSL_CFLAGS}"
+AC_CHECK_DECLS([EVP_MD_CTX_new],,,[AC_INCLUDES_DEFAULT
+#include <openssl/x509_vfy.h>
+])
+CXXFLAGS="${save_CXXFLAGS}"
+
dnl univalue check
need_bundled_univalue=yes
diff --git a/contrib/linearize/README.md b/contrib/linearize/README.md
index 06f278f3b3..adc9a559cc 100644
--- a/contrib/linearize/README.md
+++ b/contrib/linearize/README.md
@@ -1,33 +1,48 @@
# Linearize
-Construct a linear, no-fork, best version of the blockchain.
+Construct a linear, no-fork, best version of the Bitcoin blockchain. The scripts
+run using Python 3 but are compatible with Python 2.
## Step 1: Download hash list
$ ./linearize-hashes.py linearize.cfg > hashlist.txt
Required configuration file settings for linearize-hashes:
-* RPC: rpcuser, rpcpassword
+* RPC: `rpcuser`, `rpcpassword`
Optional config file setting for linearize-hashes:
-* RPC: host, port
-* Block chain: min_height, max_height
+* RPC: `host` (Default: `127.0.0.1`)
+* RPC: `port` (Default: `8332`)
+* Blockchain: `min_height`, `max_height`
+* `rev_hash_bytes`: If true, the written block hash list will be
+byte-reversed. (In other words, the hash returned by getblockhash will have its
+bytes reversed.) False by default. Intended for generation of
+standalone hash lists but safe to use with linearize-data.py, which will output
+the same data no matter which byte format is chosen.
+
+The `linearize-hashes` script requires a connection, local or remote, to a
+JSON-RPC server. Running `bitcoind` or `bitcoin-qt -server` will be sufficient.
## Step 2: Copy local block data
$ ./linearize-data.py linearize.cfg
Required configuration file settings:
-* "input": bitcoind blocks/ directory containing blkNNNNN.dat
-* "hashlist": text file containing list of block hashes, linearized-hashes.py
-output.
-* "output_file": bootstrap.dat
+* `output_file`: The file that will contain the final blockchain.
or
-* "output": output directory for linearized blocks/blkNNNNN.dat output
+* `output`: Output directory for linearized `blocks/blkNNNNN.dat` output.
Optional config file setting for linearize-data:
-* "netmagic": network magic number
-* "max_out_sz": maximum output file size (default `1000*1000*1000`)
-* "split_timestamp": Split files when a new month is first seen, in addition to
-reaching a maximum file size.
-* "file_timestamp": Set each file's last-modified time to that of the
-most recent block in that file.
+* `file_timestamp`: Set each file's last-modified time to that of the most
+recent block in that file.
+* `genesis`: The hash of the genesis block in the blockchain.
+* `input`: bitcoind blocks/ directory containing blkNNNNN.dat
+* `hashlist`: text file containing list of block hashes created by
+linearize-hashes.py.
+* `max_out_sz`: Maximum size for files created by the `output_file` option.
+(Default: `1000*1000*1000 bytes`)
+* `netmagic`: Network magic number.
+* `rev_hash_bytes`: If true, the block hash list written by linearize-hashes.py
+will be byte-reversed when read by linearize-data.py. See the linearize-hashes
+entry for more information.
+* `split_timestamp`: Split blockchain files when a new month is first seen, in
+addition to reaching a maximum file size (`max_out_sz`).
diff --git a/contrib/linearize/example-linearize.cfg b/contrib/linearize/example-linearize.cfg
index 38da02e66c..cccdd79213 100644
--- a/contrib/linearize/example-linearize.cfg
+++ b/contrib/linearize/example-linearize.cfg
@@ -23,7 +23,9 @@ input=/home/example/.bitcoin/blocks
output_file=/home/example/Downloads/bootstrap.dat
hashlist=hashlist.txt
-split_year=1
# Maxmimum size in bytes of out-of-order blocks cache in memory
out_of_order_cache_sz = 100000000
+
+# Do we want the reverse the hash bytes coming from getblockhash?
+rev_hash_bytes = False
diff --git a/contrib/linearize/linearize-data.py b/contrib/linearize/linearize-data.py
index d0417748fc..043bf2e814 100755
--- a/contrib/linearize/linearize-data.py
+++ b/contrib/linearize/linearize-data.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
#
# linearize-data.py: Construct a linear, no-fork version of the chain.
#
@@ -8,23 +8,33 @@
#
from __future__ import print_function, division
+try: # Python 3
+ import http.client as httplib
+except ImportError: # Python 2
+ import httplib
import json
import struct
import re
import os
import os.path
import base64
-import httplib
import sys
import hashlib
import datetime
import time
from collections import namedtuple
+from binascii import hexlify, unhexlify
settings = {}
+##### Switch endian-ness #####
+def hex_switchEndian(s):
+ """ Switches the endianness of a hex string (in pairs of hex chars) """
+ pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)]
+ return b''.join(pairList[::-1]).decode()
+
def uint32(x):
- return x & 0xffffffffL
+ return x & 0xffffffff
def bytereverse(x):
return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) |
@@ -35,14 +45,14 @@ def bufreverse(in_buf):
for i in range(0, len(in_buf), 4):
word = struct.unpack('@I', in_buf[i:i+4])[0]
out_words.append(struct.pack('@I', bytereverse(word)))
- return ''.join(out_words)
+ return b''.join(out_words)
def wordreverse(in_buf):
out_words = []
for i in range(0, len(in_buf), 4):
out_words.append(in_buf[i:i+4])
out_words.reverse()
- return ''.join(out_words)
+ return b''.join(out_words)
def calc_hdr_hash(blk_hdr):
hash1 = hashlib.sha256()
@@ -59,7 +69,7 @@ def calc_hash_str(blk_hdr):
hash = calc_hdr_hash(blk_hdr)
hash = bufreverse(hash)
hash = wordreverse(hash)
- hash_str = hash.encode('hex')
+ hash_str = hexlify(hash).decode('utf-8')
return hash_str
def get_blk_dt(blk_hdr):
@@ -69,17 +79,21 @@ def get_blk_dt(blk_hdr):
dt_ym = datetime.datetime(dt.year, dt.month, 1)
return (dt_ym, nTime)
+# When getting the list of block hashes, undo any byte reversals.
def get_block_hashes(settings):
blkindex = []
f = open(settings['hashlist'], "r")
for line in f:
line = line.rstrip()
+ if settings['rev_hash_bytes'] == 'true':
+ line = hex_switchEndian(line)
blkindex.append(line)
print("Read " + str(len(blkindex)) + " hashes")
return blkindex
+# The block map shouldn't give or receive byte-reversed hashes.
def mkblockmap(blkindex):
blkmap = {}
for height,hash in enumerate(blkindex):
@@ -207,7 +221,7 @@ class BlockDataCopier:
inMagic = inhdr[:4]
if (inMagic != self.settings['netmagic']):
- print("Invalid magic: " + inMagic.encode('hex'))
+ print("Invalid magic: " + hexlify(inMagic).decode('utf-8'))
return
inLenLE = inhdr[4:]
su = struct.unpack("<I", inLenLE)
@@ -265,6 +279,12 @@ if __name__ == '__main__':
settings[m.group(1)] = m.group(2)
f.close()
+ # Force hash byte format setting to be lowercase to make comparisons easier.
+ # Also place upfront in case any settings need to know about it.
+ if 'rev_hash_bytes' not in settings:
+ settings['rev_hash_bytes'] = 'false'
+ settings['rev_hash_bytes'] = settings['rev_hash_bytes'].lower()
+
if 'netmagic' not in settings:
settings['netmagic'] = 'f9beb4d9'
if 'genesis' not in settings:
@@ -278,14 +298,14 @@ if __name__ == '__main__':
if 'split_timestamp' not in settings:
settings['split_timestamp'] = 0
if 'max_out_sz' not in settings:
- settings['max_out_sz'] = 1000L * 1000 * 1000
+ settings['max_out_sz'] = 1000 * 1000 * 1000
if 'out_of_order_cache_sz' not in settings:
settings['out_of_order_cache_sz'] = 100 * 1000 * 1000
- settings['max_out_sz'] = long(settings['max_out_sz'])
+ settings['max_out_sz'] = int(settings['max_out_sz'])
settings['split_timestamp'] = int(settings['split_timestamp'])
settings['file_timestamp'] = int(settings['file_timestamp'])
- settings['netmagic'] = settings['netmagic'].decode('hex')
+ settings['netmagic'] = unhexlify(settings['netmagic'].encode('utf-8'))
settings['out_of_order_cache_sz'] = int(settings['out_of_order_cache_sz'])
if 'output_file' not in settings and 'output' not in settings:
@@ -295,9 +315,8 @@ if __name__ == '__main__':
blkindex = get_block_hashes(settings)
blkmap = mkblockmap(blkindex)
+ # Block hash map won't be byte-reversed. Neither should the genesis hash.
if not settings['genesis'] in blkmap:
print("Genesis block not found in hashlist")
else:
BlockDataCopier(settings, blkindex, blkmap).run()
-
-
diff --git a/contrib/linearize/linearize-hashes.py b/contrib/linearize/linearize-hashes.py
index ba8d6f8a04..f749da5396 100755
--- a/contrib/linearize/linearize-hashes.py
+++ b/contrib/linearize/linearize-hashes.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
#
# linearize-hashes.py: List blocks in a linear, no-fork version of the chain.
#
@@ -8,32 +8,47 @@
#
from __future__ import print_function
+try: # Python 3
+ import http.client as httplib
+except ImportError: # Python 2
+ import httplib
import json
import struct
import re
import base64
-import httplib
import sys
settings = {}
+##### Switch endian-ness #####
+def hex_switchEndian(s):
+ """ Switches the endianness of a hex string (in pairs of hex chars) """
+ pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)]
+ return b''.join(pairList[::-1]).decode()
+
class BitcoinRPC:
def __init__(self, host, port, username, password):
authpair = "%s:%s" % (username, password)
- self.authhdr = "Basic %s" % (base64.b64encode(authpair))
- self.conn = httplib.HTTPConnection(host, port, False, 30)
+ authpair = authpair.encode('utf-8')
+ self.authhdr = b"Basic " + base64.b64encode(authpair)
+ self.conn = httplib.HTTPConnection(host, port=port, timeout=30)
def execute(self, obj):
- self.conn.request('POST', '/', json.dumps(obj),
- { 'Authorization' : self.authhdr,
- 'Content-type' : 'application/json' })
+ try:
+ self.conn.request('POST', '/', json.dumps(obj),
+ { 'Authorization' : self.authhdr,
+ 'Content-type' : 'application/json' })
+ except ConnectionRefusedError:
+ print('RPC connection refused. Check RPC settings and the server status.',
+ file=sys.stderr)
+ return None
resp = self.conn.getresponse()
if resp is None:
print("JSON-RPC: no response", file=sys.stderr)
return None
- body = resp.read()
+ body = resp.read().decode('utf-8')
resp_obj = json.loads(body)
return resp_obj
@@ -64,12 +79,17 @@ def get_block_hashes(settings, max_blocks_per_call=10000):
batch.append(rpc.build_request(x, 'getblockhash', [height + x]))
reply = rpc.execute(batch)
+ if reply is None:
+ print('Cannot continue. Program will halt.')
+ return None
for x,resp_obj in enumerate(reply):
if rpc.response_is_error(resp_obj):
print('JSON-RPC: error at height', height+x, ': ', resp_obj['error'], file=sys.stderr)
exit(1)
assert(resp_obj['id'] == x) # assume replies are in-sequence
+ if settings['rev_hash_bytes'] == 'true':
+ resp_obj['result'] = hex_switchEndian(resp_obj['result'])
print(resp_obj['result'])
height += num_blocks
@@ -101,6 +121,8 @@ if __name__ == '__main__':
settings['min_height'] = 0
if 'max_height' not in settings:
settings['max_height'] = 313000
+ if 'rev_hash_bytes' not in settings:
+ settings['rev_hash_bytes'] = 'false'
if 'rpcuser' not in settings or 'rpcpassword' not in settings:
print("Missing username and/or password in cfg file", file=stderr)
sys.exit(1)
@@ -109,5 +131,7 @@ if __name__ == '__main__':
settings['min_height'] = int(settings['min_height'])
settings['max_height'] = int(settings['max_height'])
- get_block_hashes(settings)
+ # Force hash byte format setting to be lowercase to make comparisons easier.
+ settings['rev_hash_bytes'] = settings['rev_hash_bytes'].lower()
+ get_block_hashes(settings)
diff --git a/qa/rpc-tests/wallet.py b/qa/rpc-tests/wallet.py
index 992fb8a2d6..f325ecb4a3 100755
--- a/qa/rpc-tests/wallet.py
+++ b/qa/rpc-tests/wallet.py
@@ -363,11 +363,42 @@ class WalletTest (BitcoinTestFramework):
self.nodes[0].generate(1)
# Make a long chain of unconfirmed payments without hitting mempool limit
+ # Each tx we make leaves only one output of change on a chain 1 longer
+ # Since the amount to send is always much less than the outputs, we only ever need one output
+ # So we should be able to generate exactly chainlimit txs for each original output
+ sending_addr = self.nodes[1].getnewaddress()
txid_list = []
for i in range(chainlimit*2):
- txid_list.append(self.nodes[0].sendtoaddress(chain_addrs[0], Decimal('0.0001')))
+ txid_list.append(self.nodes[0].sendtoaddress(sending_addr, Decimal('0.0001')))
assert_equal(self.nodes[0].getmempoolinfo()['size'], chainlimit*2)
assert_equal(len(txid_list), chainlimit*2)
+ # Without walletrejectlongchains, we will still generate a txid
+ # The tx will be stored in the wallet but not accepted to the mempool
+ extra_txid = self.nodes[0].sendtoaddress(sending_addr, Decimal('0.0001'))
+ assert(extra_txid not in self.nodes[0].getrawmempool())
+ assert(extra_txid in [tx["txid"] for tx in self.nodes[0].listtransactions()])
+ self.nodes[0].abandontransaction(extra_txid)
+ total_txs = len(self.nodes[0].listtransactions("*",99999))
+
+ # Try with walletrejectlongchains
+ # Double chain limit but require combining inputs, so we pass SelectCoinsMinConf
+ stop_node(self.nodes[0],0)
+ self.nodes[0] = start_node(0, self.options.tmpdir, ["-walletrejectlongchains", "-limitancestorcount="+str(2*chainlimit)])
+
+ # wait for loadmempool
+ timeout = 10
+ while (timeout > 0 and len(self.nodes[0].getrawmempool()) < chainlimit*2):
+ time.sleep(0.5)
+ timeout -= 0.5
+ assert_equal(len(self.nodes[0].getrawmempool()), chainlimit*2)
+
+ node0_balance = self.nodes[0].getbalance()
+ # With walletrejectlongchains we will not create the tx and store it in our wallet.
+ assert_raises_message(JSONRPCException, "mempool chain", self.nodes[0].sendtoaddress, sending_addr, node0_balance - Decimal('0.01'))
+
+ # Verify nothing new in wallet
+ assert_equal(total_txs, len(self.nodes[0].listtransactions("*",99999)))
+
if __name__ == '__main__':
WalletTest().main()
diff --git a/src/Makefile.am b/src/Makefile.am
index 3428d4613d..a2072865a3 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -135,6 +135,7 @@ BITCOIN_CORE_H = \
support/allocators/secure.h \
support/allocators/zeroafterfree.h \
support/cleanse.h \
+ support/events.h \
support/lockedpool.h \
sync.h \
threadsafety.h \
diff --git a/src/Makefile.test.include b/src/Makefile.test.include
index c1971213a4..27b456240e 100644
--- a/src/Makefile.test.include
+++ b/src/Makefile.test.include
@@ -88,6 +88,7 @@ BITCOIN_TESTS =\
test/policyestimator_tests.cpp \
test/pow_tests.cpp \
test/prevector_tests.cpp \
+ test/raii_event_tests.cpp \
test/reverselock_tests.cpp \
test/rpc_tests.cpp \
test/sanity_tests.cpp \
@@ -123,9 +124,9 @@ BITCOIN_TESTS += \
endif
test_test_bitcoin_SOURCES = $(BITCOIN_TESTS) $(JSON_TEST_FILES) $(RAW_TEST_FILES)
-test_test_bitcoin_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) -I$(builddir)/test/ $(TESTDEFS)
+test_test_bitcoin_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) -I$(builddir)/test/ $(TESTDEFS) $(EVENT_CFLAGS)
test_test_bitcoin_LDADD = $(LIBBITCOIN_SERVER) $(LIBBITCOIN_CLI) $(LIBBITCOIN_COMMON) $(LIBBITCOIN_UTIL) $(LIBBITCOIN_CONSENSUS) $(LIBBITCOIN_CRYPTO) $(LIBUNIVALUE) $(LIBLEVELDB) $(LIBMEMENV) \
- $(BOOST_LIBS) $(BOOST_UNIT_TEST_FRAMEWORK_LIB) $(LIBSECP256K1)
+ $(BOOST_LIBS) $(BOOST_UNIT_TEST_FRAMEWORK_LIB) $(LIBSECP256K1) $(EVENT_LIBS)
test_test_bitcoin_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
if ENABLE_WALLET
test_test_bitcoin_LDADD += $(LIBBITCOIN_WALLET)
diff --git a/src/bench/bench.cpp b/src/bench/bench.cpp
index aa9dfef577..1bd9d06b80 100644
--- a/src/bench/bench.cpp
+++ b/src/bench/bench.cpp
@@ -9,9 +9,7 @@
#include <iomanip>
#include <sys/time.h>
-using namespace benchmark;
-
-std::map<std::string, BenchFunction> BenchRunner::benchmarks;
+std::map<std::string, benchmark::BenchFunction> benchmark::BenchRunner::benchmarks;
static double gettimedouble(void) {
struct timeval tv;
@@ -19,29 +17,29 @@ static double gettimedouble(void) {
return tv.tv_usec * 0.000001 + tv.tv_sec;
}
-BenchRunner::BenchRunner(std::string name, BenchFunction func)
+benchmark::BenchRunner::BenchRunner(std::string name, benchmark::BenchFunction func)
{
benchmarks.insert(std::make_pair(name, func));
}
void
-BenchRunner::RunAll(double elapsedTimeForOne)
+benchmark::BenchRunner::RunAll(double elapsedTimeForOne)
{
perf_init();
std::cout << "#Benchmark" << "," << "count" << "," << "min" << "," << "max" << "," << "average" << ","
<< "min_cycles" << "," << "max_cycles" << "," << "average_cycles" << "\n";
- for (std::map<std::string,BenchFunction>::iterator it = benchmarks.begin();
+ for (std::map<std::string,benchmark::BenchFunction>::iterator it = benchmarks.begin();
it != benchmarks.end(); ++it) {
State state(it->first, elapsedTimeForOne);
- BenchFunction& func = it->second;
+ benchmark::BenchFunction& func = it->second;
func(state);
}
perf_fini();
}
-bool State::KeepRunning()
+bool benchmark::State::KeepRunning()
{
if (count & countMask) {
++count;
diff --git a/src/bench/coin_selection.cpp b/src/bench/coin_selection.cpp
index c961151f53..29fbd34631 100644
--- a/src/bench/coin_selection.cpp
+++ b/src/bench/coin_selection.cpp
@@ -8,9 +8,7 @@
#include <boost/foreach.hpp>
#include <set>
-using namespace std;
-
-static void addCoin(const CAmount& nValue, const CWallet& wallet, vector<COutput>& vCoins)
+static void addCoin(const CAmount& nValue, const CWallet& wallet, std::vector<COutput>& vCoins)
{
int nInput = 0;
@@ -36,7 +34,7 @@ static void addCoin(const CAmount& nValue, const CWallet& wallet, vector<COutput
static void CoinSelection(benchmark::State& state)
{
const CWallet wallet;
- vector<COutput> vCoins;
+ std::vector<COutput> vCoins;
LOCK(wallet.cs_wallet);
while (state.KeepRunning()) {
@@ -50,7 +48,7 @@ static void CoinSelection(benchmark::State& state)
addCoin(1000 * COIN, wallet, vCoins);
addCoin(3 * COIN, wallet, vCoins);
- set<pair<const CWalletTx*, unsigned int> > setCoinsRet;
+ std::set<std::pair<const CWalletTx*, unsigned int> > setCoinsRet;
CAmount nValueRet;
bool success = wallet.SelectCoinsMinConf(1003 * COIN, 1, 6, 0, vCoins, setCoinsRet, nValueRet);
assert(success);
diff --git a/src/bitcoin-cli.cpp b/src/bitcoin-cli.cpp
index 776fe65925..e9b530114c 100644
--- a/src/bitcoin-cli.cpp
+++ b/src/bitcoin-cli.cpp
@@ -17,10 +17,9 @@
#include <boost/filesystem/operations.hpp>
#include <stdio.h>
-#include <event2/event.h>
-#include <event2/http.h>
#include <event2/buffer.h>
#include <event2/keyvalq_struct.h>
+#include "support/events.h"
#include <univalue.h>
@@ -190,23 +189,19 @@ UniValue CallRPC(const std::string& strMethod, const UniValue& params)
std::string host = GetArg("-rpcconnect", DEFAULT_RPCCONNECT);
int port = GetArg("-rpcport", BaseParams().RPCPort());
- // Create event base
- struct event_base *base = event_base_new(); // TODO RAII
- if (!base)
- throw std::runtime_error("cannot create event_base");
+ // Obtain event base
+ raii_event_base base = obtain_event_base();
// Synchronously look up hostname
- struct evhttp_connection *evcon = evhttp_connection_base_new(base, NULL, host.c_str(), port); // TODO RAII
- if (evcon == NULL)
- throw std::runtime_error("create connection failed");
- evhttp_connection_set_timeout(evcon, GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT));
+ raii_evhttp_connection evcon = obtain_evhttp_connection_base(base.get(), host, port);
+ evhttp_connection_set_timeout(evcon.get(), GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT));
HTTPReply response;
- struct evhttp_request *req = evhttp_request_new(http_request_done, (void*)&response); // TODO RAII
+ raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response);
if (req == NULL)
throw std::runtime_error("create http request failed");
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
- evhttp_request_set_error_cb(req, http_error_cb);
+ evhttp_request_set_error_cb(req.get(), http_error_cb);
#endif
// Get credentials
@@ -223,7 +218,7 @@ UniValue CallRPC(const std::string& strMethod, const UniValue& params)
strRPCUserColonPass = GetArg("-rpcuser", "") + ":" + GetArg("-rpcpassword", "");
}
- struct evkeyvalq *output_headers = evhttp_request_get_output_headers(req);
+ struct evkeyvalq* output_headers = evhttp_request_get_output_headers(req.get());
assert(output_headers);
evhttp_add_header(output_headers, "Host", host.c_str());
evhttp_add_header(output_headers, "Connection", "close");
@@ -231,20 +226,17 @@ UniValue CallRPC(const std::string& strMethod, const UniValue& params)
// Attach request data
std::string strRequest = JSONRPCRequestObj(strMethod, params, 1).write() + "\n";
- struct evbuffer * output_buffer = evhttp_request_get_output_buffer(req);
+ struct evbuffer* output_buffer = evhttp_request_get_output_buffer(req.get());
assert(output_buffer);
evbuffer_add(output_buffer, strRequest.data(), strRequest.size());
- int r = evhttp_make_request(evcon, req, EVHTTP_REQ_POST, "/");
+ int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, "/");
+ req.release(); // ownership moved to evcon in above call
if (r != 0) {
- evhttp_connection_free(evcon);
- event_base_free(base);
throw CConnectionFailed("send http request failed");
}
- event_base_dispatch(base);
- evhttp_connection_free(evcon);
- event_base_free(base);
+ event_base_dispatch(base.get());
if (response.status == 0)
throw CConnectionFailed(strprintf("couldn't connect to server: %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)", http_errorstring(response.error), response.error));
diff --git a/src/coins.cpp b/src/coins.cpp
index 04b3a6f23d..68f32a9da4 100644
--- a/src/coins.cpp
+++ b/src/coins.cpp
@@ -117,17 +117,37 @@ CCoinsModifier CCoinsViewCache::ModifyCoins(const uint256 &txid) {
return CCoinsModifier(*this, ret.first, cachedCoinUsage);
}
-// ModifyNewCoins has to know whether the new outputs its creating are for a
-// coinbase or not. If they are for a coinbase, it can not mark them as fresh.
-// This is to ensure that the historical duplicate coinbases before BIP30 was
-// in effect will still be properly overwritten when spent.
+/* ModifyNewCoins allows for faster coin modification when creating the new
+ * outputs from a transaction. It assumes that BIP 30 (no duplicate txids)
+ * applies and has already been tested for (or the test is not required due to
+ * BIP 34, height in coinbase). If we can assume BIP 30 then we know that any
+ * non-coinbase transaction we are adding to the UTXO must not already exist in
+ * the utxo unless it is fully spent. Thus we can check only if it exists DIRTY
+ * at the current level of the cache, in which case it is not safe to mark it
+ * FRESH (b/c then its spentness still needs to flushed). If it's not dirty and
+ * doesn't exist or is pruned in the current cache, we know it either doesn't
+ * exist or is pruned in parent caches, which is the definition of FRESH. The
+ * exception to this is the two historical violations of BIP 30 in the chain,
+ * both of which were coinbases. We do not mark these fresh so we we can ensure
+ * that they will still be properly overwritten when spent.
+ */
CCoinsModifier CCoinsViewCache::ModifyNewCoins(const uint256 &txid, bool coinbase) {
assert(!hasModifier);
std::pair<CCoinsMap::iterator, bool> ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry()));
- ret.first->second.coins.Clear();
if (!coinbase) {
- ret.first->second.flags = CCoinsCacheEntry::FRESH;
+ // New coins must not already exist.
+ if (!ret.first->second.coins.IsPruned())
+ throw std::logic_error("ModifyNewCoins should not find pre-existing coins on a non-coinbase unless they are pruned!");
+
+ if (!(ret.first->second.flags & CCoinsCacheEntry::DIRTY)) {
+ // If the coin is known to be pruned (have no unspent outputs) in
+ // the current view and the cache entry is not dirty, we know the
+ // coin also must be pruned in the parent view as well, so it is safe
+ // to mark this fresh.
+ ret.first->second.flags |= CCoinsCacheEntry::FRESH;
+ }
}
+ ret.first->second.coins.Clear();
ret.first->second.flags |= CCoinsCacheEntry::DIRTY;
return CCoinsModifier(*this, ret.first, 0);
}
@@ -200,6 +220,11 @@ bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn
itUs->second.coins.swap(it->second.coins);
cachedCoinsUsage += itUs->second.coins.DynamicMemoryUsage();
itUs->second.flags |= CCoinsCacheEntry::DIRTY;
+ // NOTE: It is possible the child has a FRESH flag here in
+ // the event the entry we found in the parent is pruned. But
+ // we must not copy that FRESH flag to the parent as that
+ // pruned state likely still needs to be communicated to the
+ // grandparent.
}
}
}
diff --git a/src/coins.h b/src/coins.h
index b1a2c08845..902cb57f69 100644
--- a/src/coins.h
+++ b/src/coins.h
@@ -269,6 +269,11 @@ struct CCoinsCacheEntry
enum Flags {
DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
FRESH = (1 << 1), // The parent view does not have this entry (or it is pruned).
+ /* Note that FRESH is a performance optimization with which we can
+ * erase coins that are fully spent if we know we do not need to
+ * flush the changes to the parent cache. It is always safe to
+ * not mark FRESH if that condition is not guaranteed.
+ */
};
CCoinsCacheEntry() : coins(), flags(0) {}
diff --git a/src/init.cpp b/src/init.cpp
index f0334a08e3..eb191ab7b8 100644
--- a/src/init.cpp
+++ b/src/init.cpp
@@ -1340,10 +1340,11 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
nTotalCache -= nCoinDBCache;
nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
+ int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
LogPrintf("Cache configuration:\n");
LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
- LogPrintf("* Using %.1fMiB for in-memory UTXO set\n", nCoinCacheUsage * (1.0 / 1024 / 1024));
+ LogPrintf("* Using %.1fMiB for in-memory UTXO set (plus up to %.1fMiB of unused mempool space)\n", nCoinCacheUsage * (1.0 / 1024 / 1024), nMempoolSizeMax * (1.0 / 1024 / 1024));
bool fLoaded = false;
while (!fLoaded) {
diff --git a/src/qt/paymentrequestplus.cpp b/src/qt/paymentrequestplus.cpp
index 5101e4e0ee..01ec416613 100644
--- a/src/qt/paymentrequestplus.cpp
+++ b/src/qt/paymentrequestplus.cpp
@@ -159,7 +159,7 @@ bool PaymentRequestPlus::getMerchant(X509_STORE* certStore, QString& merchant) c
std::string data_to_verify; // Everything but the signature
rcopy.SerializeToString(&data_to_verify);
-#if OPENSSL_VERSION_NUMBER >= 0x10100000L
+#if HAVE_DECL_EVP_MD_CTX_NEW
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
if (!ctx) throw SSLVerifyError("Error allocating OpenSSL context.");
#else
@@ -174,7 +174,7 @@ bool PaymentRequestPlus::getMerchant(X509_STORE* certStore, QString& merchant) c
!EVP_VerifyFinal(ctx, (const unsigned char*)paymentRequest.signature().data(), (unsigned int)paymentRequest.signature().size(), pubkey)) {
throw SSLVerifyError("Bad signature, invalid payment request.");
}
-#if OPENSSL_VERSION_NUMBER >= 0x10100000L
+#if HAVE_DECL_EVP_MD_CTX_NEW
EVP_MD_CTX_free(ctx);
#endif
diff --git a/src/qt/sendcoinsdialog.cpp b/src/qt/sendcoinsdialog.cpp
index cb8978fc81..5aeda7a30d 100644
--- a/src/qt/sendcoinsdialog.cpp
+++ b/src/qt/sendcoinsdialog.cpp
@@ -772,6 +772,19 @@ void SendCoinsDialog::coinControlChangeEdited(const QString& text)
if (!model->havePrivKey(keyid)) // Unknown change address
{
ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address"));
+
+ // confirmation dialog
+ QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm custom change address"), tr("The address you selected for change is not part of this wallet. Any or all funds in your wallet may be sent to this address. Are you sure?"),
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
+
+ if(btnRetVal == QMessageBox::Yes)
+ CoinControlDialog::coinControl->destChange = addr.Get();
+ else
+ {
+ ui->lineEditCoinControlChange->setText("");
+ ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}");
+ ui->labelCoinControlChangeLabel->setText("");
+ }
}
else // Known change address
{
diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp
index a127f10b8b..538e488bdf 100644
--- a/src/rpc/blockchain.cpp
+++ b/src/rpc/blockchain.cpp
@@ -331,7 +331,7 @@ UniValue getdifficulty(const JSONRPCRequest& request)
std::string EntryDescriptionString()
{
- return " \"size\" : n, (numeric) transaction size in bytes\n"
+ return " \"size\" : n, (numeric) virtual transaction size as defined in BIP 141. This is different from actual serialized size for witness transactions as witness data is discounted.\n"
" \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n"
" \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority\n"
" \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n"
@@ -339,10 +339,10 @@ std::string EntryDescriptionString()
" \"startingpriority\" : n, (numeric) priority when transaction entered pool\n"
" \"currentpriority\" : n, (numeric) transaction priority now\n"
" \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n"
- " \"descendantsize\" : n, (numeric) size of in-mempool descendants (including this one)\n"
+ " \"descendantsize\" : n, (numeric) virtual transaction size of in-mempool descendants (including this one)\n"
" \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one)\n"
" \"ancestorcount\" : n, (numeric) number of in-mempool ancestor transactions (including this one)\n"
- " \"ancestorsize\" : n, (numeric) size of in-mempool ancestors (including this one)\n"
+ " \"ancestorsize\" : n, (numeric) virtual transaction size of in-mempool ancestors (including this one)\n"
" \"ancestorfees\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one)\n"
" \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n"
" \"transactionid\", (string) parent transaction id\n"
@@ -703,7 +703,7 @@ UniValue getblock(const JSONRPCRequest& request)
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"size\" : n, (numeric) The block size\n"
" \"strippedsize\" : n, (numeric) The block size excluding witness data\n"
- " \"weight\" : n (numeric) The block weight (BIP 141)\n"
+ " \"weight\" : n (numeric) The block weight as defined in BIP 141\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
@@ -1240,7 +1240,7 @@ UniValue getmempoolinfo(const JSONRPCRequest& request)
"\nResult:\n"
"{\n"
" \"size\": xxxxx, (numeric) Current tx count\n"
- " \"bytes\": xxxxx, (numeric) Sum of all tx sizes\n"
+ " \"bytes\": xxxxx, (numeric) Sum of all virtual transaction sizes as defined in BIP 141. Differs from actual serialized size because witness data is discounted\n"
" \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n"
" \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n"
" \"mempoolminfee\": xxxxx (numeric) Minimum fee for tx to be accepted\n"
diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp
index fa79d20734..3796a18fec 100644
--- a/src/rpc/mining.cpp
+++ b/src/rpc/mining.cpp
@@ -779,7 +779,8 @@ UniValue estimatefee(const JSONRPCRequest& request)
throw runtime_error(
"estimatefee nblocks\n"
"\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
- "confirmation within nblocks blocks.\n"
+ "confirmation within nblocks blocks. Uses virtual transaction size of transaction\n"
+ "as defined in BIP 141 (witness data is discounted).\n"
"\nArguments:\n"
"1. nblocks (numeric)\n"
"\nResult:\n"
@@ -841,7 +842,8 @@ UniValue estimatesmartfee(const JSONRPCRequest& request)
"\nWARNING: This interface is unstable and may disappear or change!\n"
"\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
"confirmation within nblocks blocks if possible and return the number of blocks\n"
- "for which the estimate is valid.\n"
+ "for which the estimate is valid. Uses virtual transaction size as defined\n"
+ "in BIP 141 (witness data is discounted).\n"
"\nArguments:\n"
"1. nblocks (numeric)\n"
"\nResult:\n"
diff --git a/src/support/events.h b/src/support/events.h
new file mode 100644
index 0000000000..4f2f3cf9ef
--- /dev/null
+++ b/src/support/events.h
@@ -0,0 +1,56 @@
+// Copyright (c) 2016 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_SUPPORT_EVENTS_H
+#define BITCOIN_SUPPORT_EVENTS_H
+
+#include <ios>
+#include <memory>
+
+#include <event2/event.h>
+#include <event2/http.h>
+
+#define MAKE_RAII(type) \
+/* deleter */\
+struct type##_deleter {\
+ void operator()(struct type* ob) {\
+ type##_free(ob);\
+ }\
+};\
+/* unique ptr typedef */\
+typedef std::unique_ptr<struct type, type##_deleter> raii_##type
+
+MAKE_RAII(event_base);
+MAKE_RAII(event);
+MAKE_RAII(evhttp);
+MAKE_RAII(evhttp_request);
+MAKE_RAII(evhttp_connection);
+
+raii_event_base obtain_event_base() {
+ auto result = raii_event_base(event_base_new());
+ if (!result.get())
+ throw std::runtime_error("cannot create event_base");
+ return result;
+}
+
+raii_event obtain_event(struct event_base* base, evutil_socket_t s, short events, event_callback_fn cb, void* arg) {
+ return raii_event(event_new(base, s, events, cb, arg));
+}
+
+raii_evhttp obtain_evhttp(struct event_base* base) {
+ return raii_evhttp(evhttp_new(base));
+}
+
+raii_evhttp_request obtain_evhttp_request(void(*cb)(struct evhttp_request *, void *), void *arg) {
+ return raii_evhttp_request(evhttp_request_new(cb, arg));
+}
+
+raii_evhttp_connection obtain_evhttp_connection_base(struct event_base* base, std::string host, uint16_t port) {
+ auto result = raii_evhttp_connection(evhttp_connection_base_new(base, NULL, host.c_str(), port));
+ if (!result.get())
+ throw std::runtime_error("create connection failed");
+ return result;
+}
+
+#endif // BITCOIN_SUPPORT_EVENTS_H
diff --git a/src/test/addrman_tests.cpp b/src/test/addrman_tests.cpp
index 078c5bbf2d..48313915e7 100644
--- a/src/test/addrman_tests.cpp
+++ b/src/test/addrman_tests.cpp
@@ -10,8 +10,6 @@
#include "netbase.h"
#include "random.h"
-using namespace std;
-
class CAddrManTest : public CAddrMan
{
uint64_t state;
@@ -365,7 +363,7 @@ BOOST_AUTO_TEST_CASE(addrman_getaddr)
// Test 22: Sanity check, GetAddr should never return anything if addrman
// is empty.
BOOST_CHECK(addrman.size() == 0);
- vector<CAddress> vAddr1 = addrman.GetAddr();
+ std::vector<CAddress> vAddr1 = addrman.GetAddr();
BOOST_CHECK(vAddr1.size() == 0);
CAddress addr1 = CAddress(ResolveService("250.250.2.1", 8333), NODE_NONE);
@@ -401,7 +399,7 @@ BOOST_AUTO_TEST_CASE(addrman_getaddr)
int octet1 = i % 256;
int octet2 = (i / 256) % 256;
int octet3 = (i / (256 * 2)) % 256;
- string strAddr = boost::to_string(octet1) + "." + boost::to_string(octet2) + "." + boost::to_string(octet3) + ".23";
+ std::string strAddr = boost::to_string(octet1) + "." + boost::to_string(octet2) + "." + boost::to_string(octet3) + ".23";
CAddress addr = CAddress(ResolveService(strAddr), NODE_NONE);
// Ensure that for all addrs in addrman, isTerrible == false.
@@ -410,7 +408,7 @@ BOOST_AUTO_TEST_CASE(addrman_getaddr)
if (i % 8 == 0)
addrman.Good(addr);
}
- vector<CAddress> vAddr = addrman.GetAddr();
+ std::vector<CAddress> vAddr = addrman.GetAddr();
size_t percent23 = (addrman.size() * 23) / 100;
BOOST_CHECK(vAddr.size() == percent23);
@@ -452,7 +450,7 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_tried_bucket)
BOOST_CHECK(info1.GetKey() != info2.GetKey());
BOOST_CHECK(info1.GetTriedBucket(nKey1) != info2.GetTriedBucket(nKey1));
- set<int> buckets;
+ std::set<int> buckets;
for (int i = 0; i < 255; i++) {
CAddrInfo infoi = CAddrInfo(
CAddress(ResolveService("250.1.1." + boost::to_string(i)), NODE_NONE),
@@ -505,7 +503,7 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_new_bucket)
BOOST_CHECK(info1.GetKey() != info2.GetKey());
BOOST_CHECK(info1.GetNewBucket(nKey1) == info2.GetNewBucket(nKey1));
- set<int> buckets;
+ std::set<int> buckets;
for (int i = 0; i < 255; i++) {
CAddrInfo infoi = CAddrInfo(
CAddress(ResolveService("250.1.1." + boost::to_string(i)), NODE_NONE),
diff --git a/src/test/bloom_tests.cpp b/src/test/bloom_tests.cpp
index a67b292378..27bc92d670 100644
--- a/src/test/bloom_tests.cpp
+++ b/src/test/bloom_tests.cpp
@@ -21,8 +21,6 @@
#include <boost/test/unit_test.hpp>
#include <boost/tuple/tuple.hpp>
-using namespace std;
-
BOOST_FIXTURE_TEST_SUITE(bloom_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(bloom_create_insert_serialize)
@@ -43,8 +41,8 @@ BOOST_AUTO_TEST_CASE(bloom_create_insert_serialize)
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << filter;
- vector<unsigned char> vch = ParseHex("03614e9b050000000000000001");
- vector<char> expected(vch.size());
+ std::vector<unsigned char> vch = ParseHex("03614e9b050000000000000001");
+ std::vector<char> expected(vch.size());
for (unsigned int i = 0; i < vch.size(); i++)
expected[i] = (char)vch[i];
@@ -75,8 +73,8 @@ BOOST_AUTO_TEST_CASE(bloom_create_insert_serialize_with_tweak)
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << filter;
- vector<unsigned char> vch = ParseHex("03ce4299050000000100008001");
- vector<char> expected(vch.size());
+ std::vector<unsigned char> vch = ParseHex("03ce4299050000000100008001");
+ std::vector<char> expected(vch.size());
for (unsigned int i = 0; i < vch.size(); i++)
expected[i] = (char)vch[i];
@@ -86,24 +84,24 @@ BOOST_AUTO_TEST_CASE(bloom_create_insert_serialize_with_tweak)
BOOST_AUTO_TEST_CASE(bloom_create_insert_key)
{
- string strSecret = string("5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C");
+ std::string strSecret = std::string("5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C");
CBitcoinSecret vchSecret;
BOOST_CHECK(vchSecret.SetString(strSecret));
CKey key = vchSecret.GetKey();
CPubKey pubkey = key.GetPubKey();
- vector<unsigned char> vchPubKey(pubkey.begin(), pubkey.end());
+ std::vector<unsigned char> vchPubKey(pubkey.begin(), pubkey.end());
CBloomFilter filter(2, 0.001, 0, BLOOM_UPDATE_ALL);
filter.insert(vchPubKey);
uint160 hash = pubkey.GetID();
- filter.insert(vector<unsigned char>(hash.begin(), hash.end()));
+ filter.insert(std::vector<unsigned char>(hash.begin(), hash.end()));
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << filter;
- vector<unsigned char> vch = ParseHex("038fc16b080000000000000001");
- vector<char> expected(vch.size());
+ std::vector<unsigned char> vch = ParseHex("038fc16b080000000000000001");
+ std::vector<char> expected(vch.size());
for (unsigned int i = 0; i < vch.size(); i++)
expected[i] = (char)vch[i];
@@ -119,7 +117,7 @@ BOOST_AUTO_TEST_CASE(bloom_match)
// and one which spends it (e2769b09e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436)
unsigned char ch[] = {0x01, 0x00, 0x00, 0x00, 0x01, 0x6b, 0xff, 0x7f, 0xcd, 0x4f, 0x85, 0x65, 0xef, 0x40, 0x6d, 0xd5, 0xd6, 0x3d, 0x4f, 0xf9, 0x4f, 0x31, 0x8f, 0xe8, 0x20, 0x27, 0xfd, 0x4d, 0xc4, 0x51, 0xb0, 0x44, 0x74, 0x01, 0x9f, 0x74, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x8c, 0x49, 0x30, 0x46, 0x02, 0x21, 0x00, 0xda, 0x0d, 0xc6, 0xae, 0xce, 0xfe, 0x1e, 0x06, 0xef, 0xdf, 0x05, 0x77, 0x37, 0x57, 0xde, 0xb1, 0x68, 0x82, 0x09, 0x30, 0xe3, 0xb0, 0xd0, 0x3f, 0x46, 0xf5, 0xfc, 0xf1, 0x50, 0xbf, 0x99, 0x0c, 0x02, 0x21, 0x00, 0xd2, 0x5b, 0x5c, 0x87, 0x04, 0x00, 0x76, 0xe4, 0xf2, 0x53, 0xf8, 0x26, 0x2e, 0x76, 0x3e, 0x2d, 0xd5, 0x1e, 0x7f, 0xf0, 0xbe, 0x15, 0x77, 0x27, 0xc4, 0xbc, 0x42, 0x80, 0x7f, 0x17, 0xbd, 0x39, 0x01, 0x41, 0x04, 0xe6, 0xc2, 0x6e, 0xf6, 0x7d, 0xc6, 0x10, 0xd2, 0xcd, 0x19, 0x24, 0x84, 0x78, 0x9a, 0x6c, 0xf9, 0xae, 0xa9, 0x93, 0x0b, 0x94, 0x4b, 0x7e, 0x2d, 0xb5, 0x34, 0x2b, 0x9d, 0x9e, 0x5b, 0x9f, 0xf7, 0x9a, 0xff, 0x9a, 0x2e, 0xe1, 0x97, 0x8d, 0xd7, 0xfd, 0x01, 0xdf, 0xc5, 0x22, 0xee, 0x02, 0x28, 0x3d, 0x3b, 0x06, 0xa9, 0xd0, 0x3a, 0xcf, 0x80, 0x96, 0x96, 0x8d, 0x7d, 0xbb, 0x0f, 0x91, 0x78, 0xff, 0xff, 0xff, 0xff, 0x02, 0x8b, 0xa7, 0x94, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xba, 0xde, 0xec, 0xfd, 0xef, 0x05, 0x07, 0x24, 0x7f, 0xc8, 0xf7, 0x42, 0x41, 0xd7, 0x3b, 0xc0, 0x39, 0x97, 0x2d, 0x7b, 0x88, 0xac, 0x40, 0x94, 0xa8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xc1, 0x09, 0x32, 0x48, 0x3f, 0xec, 0x93, 0xed, 0x51, 0xf5, 0xfe, 0x95, 0xe7, 0x25, 0x59, 0xf2, 0xcc, 0x70, 0x43, 0xf9, 0x88, 0xac, 0x00, 0x00, 0x00, 0x00, 0x00};
- vector<unsigned char> vch(ch, ch + sizeof(ch) -1);
+ std::vector<unsigned char> vch(ch, ch + sizeof(ch) -1);
CDataStream spendStream(vch, SER_DISK, CLIENT_VERSION);
CTransaction spendingTx(deserialize, spendStream);
@@ -156,7 +154,7 @@ BOOST_AUTO_TEST_CASE(bloom_match)
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
COutPoint prevOutPoint(uint256S("0x90c122d70786e899529d71dbeba91ba216982fb6ba58f3bdaab65e73b7e9260b"), 0);
{
- vector<unsigned char> data(32 + sizeof(unsigned int));
+ std::vector<unsigned char> data(32 + sizeof(unsigned int));
memcpy(&data[0], prevOutPoint.hash.begin(), 32);
memcpy(&data[32], &prevOutPoint.n, sizeof(unsigned int));
filter.insert(data);
@@ -196,13 +194,13 @@ BOOST_AUTO_TEST_CASE(merkle_block_1)
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1);
- pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0];
+ std::pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0];
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0x74d681e0e03bafa802c8aa084379aa98d9fcd632ddc2ed9782b586ec87451f20"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 8);
- vector<uint256> vMatched;
- vector<unsigned int> vIndex;
+ std::vector<uint256> vMatched;
+ std::vector<unsigned int> vIndex;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
@@ -242,13 +240,13 @@ BOOST_AUTO_TEST_CASE(merkle_block_2)
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1);
- pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0];
+ std::pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0];
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0xe980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0);
- vector<uint256> vMatched;
- vector<unsigned int> vIndex;
+ std::vector<uint256> vMatched;
+ std::vector<unsigned int> vIndex;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
@@ -297,13 +295,13 @@ BOOST_AUTO_TEST_CASE(merkle_block_2_with_update_none)
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1);
- pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0];
+ std::pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0];
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0xe980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0);
- vector<uint256> vMatched;
- vector<unsigned int> vIndex;
+ std::vector<uint256> vMatched;
+ std::vector<unsigned int> vIndex;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
@@ -353,8 +351,8 @@ BOOST_AUTO_TEST_CASE(merkle_block_3_and_serialize)
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0x63194f18be0af63f2c6bc9dc0f777cbefed3d9415c4af83f3ee3a3d669c00cb5"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0);
- vector<uint256> vMatched;
- vector<unsigned int> vIndex;
+ std::vector<uint256> vMatched;
+ std::vector<unsigned int> vIndex;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
@@ -363,8 +361,8 @@ BOOST_AUTO_TEST_CASE(merkle_block_3_and_serialize)
CDataStream merkleStream(SER_NETWORK, PROTOCOL_VERSION);
merkleStream << merkleBlock;
- vector<unsigned char> vch = ParseHex("0100000079cda856b143d9db2c1caff01d1aecc8630d30625d10e8b4b8b0000000000000b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f196367291b4d4c86041b8fa45d630100000001b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f19630101");
- vector<char> expected(vch.size());
+ std::vector<unsigned char> vch = ParseHex("0100000079cda856b143d9db2c1caff01d1aecc8630d30625d10e8b4b8b0000000000000b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f196367291b4d4c86041b8fa45d630100000001b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f19630101");
+ std::vector<char> expected(vch.size());
for (unsigned int i = 0; i < vch.size(); i++)
expected[i] = (char)vch[i];
@@ -388,13 +386,13 @@ BOOST_AUTO_TEST_CASE(merkle_block_4)
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1);
- pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0];
+ std::pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0];
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0x0a2a92f0bda4727d0a13eaddf4dd9ac6b5c61a1429e6b2b818f19b15df0ac154"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 6);
- vector<uint256> vMatched;
- vector<unsigned int> vIndex;
+ std::vector<uint256> vMatched;
+ std::vector<unsigned int> vIndex;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
diff --git a/src/test/coins_tests.cpp b/src/test/coins_tests.cpp
index 2f8857953c..70b958c296 100644
--- a/src/test/coins_tests.cpp
+++ b/src/test/coins_tests.cpp
@@ -5,6 +5,7 @@
#include "coins.h"
#include "script/standard.h"
#include "uint256.h"
+#include "undo.h"
#include "utilstrencodings.h"
#include "test/test_bitcoin.h"
#include "test/test_random.h"
@@ -16,6 +17,9 @@
#include <boost/test/unit_test.hpp>
+bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out);
+void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight);
+
namespace
{
class CCoinsViewTest : public CCoinsView
@@ -213,6 +217,22 @@ BOOST_AUTO_TEST_CASE(coins_cache_simulation_test)
BOOST_CHECK(missed_an_entry);
}
+typedef std::tuple<CTransaction,CTxUndo,CCoins> TxData;
+// Store of all necessary tx and undo data for next test
+std::map<uint256, TxData> alltxs;
+
+TxData &FindRandomFrom(const std::set<uint256> &txidset) {
+ assert(txidset.size());
+ std::set<uint256>::iterator txIt = txidset.lower_bound(GetRandHash());
+ if (txIt == txidset.end()) {
+ txIt = txidset.begin();
+ }
+ std::map<uint256, TxData>::iterator txdit = alltxs.find(*txIt);
+ assert(txdit != alltxs.end());
+ return txdit->second;
+}
+
+
// This test is similar to the previous test
// except the emphasis is on testing the functionality of UpdateCoins
// random txs are created and UpdateCoins is used to update the cache stack
@@ -229,77 +249,139 @@ BOOST_AUTO_TEST_CASE(updatecoins_simulation_test)
std::vector<CCoinsViewCacheTest*> stack; // A stack of CCoinsViewCaches on top.
stack.push_back(new CCoinsViewCacheTest(&base)); // Start with one cache.
- // Track the txids we've used and whether they have been spent or not
- std::map<uint256, CAmount> coinbaseids;
- std::set<uint256> alltxids;
+ // Track the txids we've used in various sets
+ std::set<uint256> coinbaseids;
+ std::set<uint256> disconnectedids;
std::set<uint256> duplicateids;
+ std::set<uint256> utxoset;
for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {
- {
+ uint32_t randiter = insecure_rand();
+
+ // 19/20 txs add a new transaction
+ if (randiter % 20 < 19) {
CMutableTransaction tx;
tx.vin.resize(1);
tx.vout.resize(1);
tx.vout[0].nValue = i; //Keep txs unique unless intended to duplicate
unsigned int height = insecure_rand();
+ CCoins oldcoins;
- // 1/10 times create a coinbase
- if (insecure_rand() % 10 == 0 || coinbaseids.size() < 10) {
- // 1/100 times create a duplicate coinbase
+ // 2/20 times create a new coinbase
+ if (randiter % 20 < 2 || coinbaseids.size() < 10) {
+ // 1/10 of those times create a duplicate coinbase
if (insecure_rand() % 10 == 0 && coinbaseids.size()) {
- std::map<uint256, CAmount>::iterator coinbaseIt = coinbaseids.lower_bound(GetRandHash());
- if (coinbaseIt == coinbaseids.end()) {
- coinbaseIt = coinbaseids.begin();
- }
- //Use same random value to have same hash and be a true duplicate
- tx.vout[0].nValue = coinbaseIt->second;
- assert(tx.GetHash() == coinbaseIt->first);
- duplicateids.insert(coinbaseIt->first);
+ TxData &txd = FindRandomFrom(coinbaseids);
+ // Reuse the exact same coinbase
+ tx = std::get<0>(txd);
+ // shouldn't be available for reconnection if its been duplicated
+ disconnectedids.erase(tx.GetHash());
+
+ duplicateids.insert(tx.GetHash());
}
else {
- coinbaseids[tx.GetHash()] = tx.vout[0].nValue;
+ coinbaseids.insert(tx.GetHash());
}
assert(CTransaction(tx).IsCoinBase());
}
- // 9/10 times create a regular tx
+
+ // 17/20 times reconnect previous or add a regular tx
else {
+
uint256 prevouthash;
- // equally likely to spend coinbase or non coinbase
- std::set<uint256>::iterator txIt = alltxids.lower_bound(GetRandHash());
- if (txIt == alltxids.end()) {
- txIt = alltxids.begin();
+ // 1/20 times reconnect a previously disconnected tx
+ if (randiter % 20 == 2 && disconnectedids.size()) {
+ TxData &txd = FindRandomFrom(disconnectedids);
+ tx = std::get<0>(txd);
+ prevouthash = tx.vin[0].prevout.hash;
+ if (!CTransaction(tx).IsCoinBase() && !utxoset.count(prevouthash)) {
+ disconnectedids.erase(tx.GetHash());
+ continue;
+ }
+
+ // If this tx is already IN the UTXO, then it must be a coinbase, and it must be a duplicate
+ if (utxoset.count(tx.GetHash())) {
+ assert(CTransaction(tx).IsCoinBase());
+ assert(duplicateids.count(tx.GetHash()));
+ }
+ disconnectedids.erase(tx.GetHash());
}
- prevouthash = *txIt;
- // Construct the tx to spend the coins of prevouthash
- tx.vin[0].prevout.hash = prevouthash;
- tx.vin[0].prevout.n = 0;
+ // 16/20 times create a regular tx
+ else {
+ TxData &txd = FindRandomFrom(utxoset);
+ prevouthash = std::get<0>(txd).GetHash();
+ // Construct the tx to spend the coins of prevouthash
+ tx.vin[0].prevout.hash = prevouthash;
+ tx.vin[0].prevout.n = 0;
+ assert(!CTransaction(tx).IsCoinBase());
+ }
+ // In this simple test coins only have two states, spent or unspent, save the unspent state to restore
+ oldcoins = result[prevouthash];
// Update the expected result of prevouthash to know these coins are spent
- CCoins& oldcoins = result[prevouthash];
- oldcoins.Clear();
+ result[prevouthash].Clear();
- // It is of particular importance here that once we spend a coinbase tx hash
- // it is no longer available to be duplicated (or spent again)
- // BIP 34 in conjunction with enforcing BIP 30 (at least until BIP 34 was active)
- // results in the fact that no coinbases were duplicated after they were already spent
- alltxids.erase(prevouthash);
- coinbaseids.erase(prevouthash);
+ utxoset.erase(prevouthash);
// The test is designed to ensure spending a duplicate coinbase will work properly
// if that ever happens and not resurrect the previously overwritten coinbase
if (duplicateids.count(prevouthash))
spent_a_duplicate_coinbase = true;
- assert(!CTransaction(tx).IsCoinBase());
}
- // Track this tx to possibly spend later
- alltxids.insert(tx.GetHash());
-
// Update the expected result to know about the new output coins
- CCoins &coins = result[tx.GetHash()];
- coins.FromTx(tx, height);
+ result[tx.GetHash()].FromTx(tx, height);
+
+ // Call UpdateCoins on the top cache
+ CTxUndo undo;
+ UpdateCoins(tx, *(stack.back()), undo, height);
- UpdateCoins(tx, *(stack.back()), height);
+ // Update the utxo set for future spends
+ utxoset.insert(tx.GetHash());
+
+ // Track this tx and undo info to use later
+ alltxs.insert(std::make_pair(tx.GetHash(),std::make_tuple(tx,undo,oldcoins)));
+ }
+
+ //1/20 times undo a previous transaction
+ else if (utxoset.size()) {
+ TxData &txd = FindRandomFrom(utxoset);
+
+ CTransaction &tx = std::get<0>(txd);
+ CTxUndo &undo = std::get<1>(txd);
+ CCoins &origcoins = std::get<2>(txd);
+
+ uint256 undohash = tx.GetHash();
+
+ // Update the expected result
+ // Remove new outputs
+ result[undohash].Clear();
+ // If not coinbase restore prevout
+ if (!tx.IsCoinBase()) {
+ result[tx.vin[0].prevout.hash] = origcoins;
+ }
+
+ // Disconnect the tx from the current UTXO
+ // See code in DisconnectBlock
+ // remove outputs
+ {
+ CCoinsModifier outs = stack.back()->ModifyCoins(undohash);
+ outs->Clear();
+ }
+ // restore inputs
+ if (!tx.IsCoinBase()) {
+ const COutPoint &out = tx.vin[0].prevout;
+ const CTxInUndo &undoin = undo.vprevout[0];
+ ApplyTxInUndo(undoin, *(stack.back()), out);
+ }
+ // Store as a candidate for reconnection
+ disconnectedids.insert(undohash);
+
+ // Update the utxoset
+ utxoset.erase(undohash);
+ if (!tx.IsCoinBase())
+ utxoset.insert(tx.vin[0].prevout.hash);
}
// Once every 1000 iterations and at the end, verify the full cache.
@@ -308,9 +390,9 @@ BOOST_AUTO_TEST_CASE(updatecoins_simulation_test)
const CCoins* coins = stack.back()->AccessCoins(it->first);
if (coins) {
BOOST_CHECK(*coins == it->second);
- } else {
+ } else {
BOOST_CHECK(it->second.IsPruned());
- }
+ }
}
}
@@ -334,7 +416,7 @@ BOOST_AUTO_TEST_CASE(updatecoins_simulation_test)
tip = stack.back();
}
stack.push_back(new CCoinsViewCacheTest(tip));
- }
+ }
}
}
@@ -420,6 +502,7 @@ BOOST_AUTO_TEST_CASE(ccoins_serialization)
const static uint256 TXID;
const static CAmount PRUNED = -1;
const static CAmount ABSENT = -2;
+const static CAmount FAIL = -3;
const static CAmount VALUE1 = 100;
const static CAmount VALUE2 = 200;
const static CAmount VALUE3 = 300;
@@ -630,11 +713,17 @@ BOOST_AUTO_TEST_CASE(ccoins_modify)
void CheckModifyNewCoinsBase(CAmount base_value, CAmount cache_value, CAmount modify_value, CAmount expected_value, char cache_flags, char expected_flags, bool coinbase)
{
SingleEntryCacheTest test(base_value, cache_value, cache_flags);
- SetCoinsValue(modify_value, *test.cache.ModifyNewCoins(TXID, coinbase));
CAmount result_value;
char result_flags;
- GetCoinsMapEntry(test.cache.map(), result_value, result_flags);
+ try {
+ SetCoinsValue(modify_value, *test.cache.ModifyNewCoins(TXID, coinbase));
+ GetCoinsMapEntry(test.cache.map(), result_value, result_flags);
+ } catch (std::logic_error& e) {
+ result_value = FAIL;
+ result_flags = NO_ENTRY;
+ }
+
BOOST_CHECK_EQUAL(result_value, expected_value);
BOOST_CHECK_EQUAL(result_flags, expected_flags);
}
@@ -669,7 +758,7 @@ BOOST_AUTO_TEST_CASE(ccoins_modify_new)
CheckModifyNewCoins(PRUNED, PRUNED, PRUNED, 0 , DIRTY , true );
CheckModifyNewCoins(PRUNED, PRUNED, ABSENT, FRESH , NO_ENTRY , false);
CheckModifyNewCoins(PRUNED, PRUNED, ABSENT, FRESH , NO_ENTRY , true );
- CheckModifyNewCoins(PRUNED, PRUNED, ABSENT, DIRTY , NO_ENTRY , false);
+ CheckModifyNewCoins(PRUNED, PRUNED, PRUNED, DIRTY , DIRTY , false);
CheckModifyNewCoins(PRUNED, PRUNED, PRUNED, DIRTY , DIRTY , true );
CheckModifyNewCoins(PRUNED, PRUNED, ABSENT, DIRTY|FRESH, NO_ENTRY , false);
CheckModifyNewCoins(PRUNED, PRUNED, ABSENT, DIRTY|FRESH, NO_ENTRY , true );
@@ -677,25 +766,25 @@ BOOST_AUTO_TEST_CASE(ccoins_modify_new)
CheckModifyNewCoins(PRUNED, VALUE3, VALUE3, 0 , DIRTY , true );
CheckModifyNewCoins(PRUNED, VALUE3, VALUE3, FRESH , DIRTY|FRESH, false);
CheckModifyNewCoins(PRUNED, VALUE3, VALUE3, FRESH , DIRTY|FRESH, true );
- CheckModifyNewCoins(PRUNED, VALUE3, VALUE3, DIRTY , DIRTY|FRESH, false);
+ CheckModifyNewCoins(PRUNED, VALUE3, VALUE3, DIRTY , DIRTY , false);
CheckModifyNewCoins(PRUNED, VALUE3, VALUE3, DIRTY , DIRTY , true );
CheckModifyNewCoins(PRUNED, VALUE3, VALUE3, DIRTY|FRESH, DIRTY|FRESH, false);
CheckModifyNewCoins(PRUNED, VALUE3, VALUE3, DIRTY|FRESH, DIRTY|FRESH, true );
- CheckModifyNewCoins(VALUE2, PRUNED, ABSENT, 0 , NO_ENTRY , false);
+ CheckModifyNewCoins(VALUE2, PRUNED, FAIL , 0 , NO_ENTRY , false);
CheckModifyNewCoins(VALUE2, PRUNED, PRUNED, 0 , DIRTY , true );
- CheckModifyNewCoins(VALUE2, PRUNED, ABSENT, FRESH , NO_ENTRY , false);
+ CheckModifyNewCoins(VALUE2, PRUNED, FAIL , FRESH , NO_ENTRY , false);
CheckModifyNewCoins(VALUE2, PRUNED, ABSENT, FRESH , NO_ENTRY , true );
- CheckModifyNewCoins(VALUE2, PRUNED, ABSENT, DIRTY , NO_ENTRY , false);
+ CheckModifyNewCoins(VALUE2, PRUNED, FAIL , DIRTY , NO_ENTRY , false);
CheckModifyNewCoins(VALUE2, PRUNED, PRUNED, DIRTY , DIRTY , true );
- CheckModifyNewCoins(VALUE2, PRUNED, ABSENT, DIRTY|FRESH, NO_ENTRY , false);
+ CheckModifyNewCoins(VALUE2, PRUNED, FAIL , DIRTY|FRESH, NO_ENTRY , false);
CheckModifyNewCoins(VALUE2, PRUNED, ABSENT, DIRTY|FRESH, NO_ENTRY , true );
- CheckModifyNewCoins(VALUE2, VALUE3, VALUE3, 0 , DIRTY|FRESH, false);
+ CheckModifyNewCoins(VALUE2, VALUE3, FAIL , 0 , NO_ENTRY , false);
CheckModifyNewCoins(VALUE2, VALUE3, VALUE3, 0 , DIRTY , true );
- CheckModifyNewCoins(VALUE2, VALUE3, VALUE3, FRESH , DIRTY|FRESH, false);
+ CheckModifyNewCoins(VALUE2, VALUE3, FAIL , FRESH , NO_ENTRY , false);
CheckModifyNewCoins(VALUE2, VALUE3, VALUE3, FRESH , DIRTY|FRESH, true );
- CheckModifyNewCoins(VALUE2, VALUE3, VALUE3, DIRTY , DIRTY|FRESH, false);
+ CheckModifyNewCoins(VALUE2, VALUE3, FAIL , DIRTY , NO_ENTRY , false);
CheckModifyNewCoins(VALUE2, VALUE3, VALUE3, DIRTY , DIRTY , true );
- CheckModifyNewCoins(VALUE2, VALUE3, VALUE3, DIRTY|FRESH, DIRTY|FRESH, false);
+ CheckModifyNewCoins(VALUE2, VALUE3, FAIL , DIRTY|FRESH, NO_ENTRY , false);
CheckModifyNewCoins(VALUE2, VALUE3, VALUE3, DIRTY|FRESH, DIRTY|FRESH, true );
}
diff --git a/src/test/dbwrapper_tests.cpp b/src/test/dbwrapper_tests.cpp
index a0e1ed0505..e5cb48ffcf 100644
--- a/src/test/dbwrapper_tests.cpp
+++ b/src/test/dbwrapper_tests.cpp
@@ -10,13 +10,9 @@
#include <boost/assign/std/vector.hpp> // for 'operator+=()'
#include <boost/assert.hpp>
#include <boost/test/unit_test.hpp>
-
-using namespace std;
-using namespace boost::assign; // bring 'operator+=()' into scope
-using namespace boost::filesystem;
-
+
// Test if a string consists entirely of null characters
-bool is_null_key(const vector<unsigned char>& key) {
+bool is_null_key(const std::vector<unsigned char>& key) {
bool isnull = true;
for (unsigned int i = 0; i < key.size(); i++)
@@ -32,7 +28,7 @@ BOOST_AUTO_TEST_CASE(dbwrapper)
// Perform tests both obfuscated and non-obfuscated.
for (int i = 0; i < 2; i++) {
bool obfuscate = (bool)i;
- path ph = temp_directory_path() / unique_path();
+ boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate);
char key = 'k';
uint256 in = GetRandHash();
@@ -53,7 +49,7 @@ BOOST_AUTO_TEST_CASE(dbwrapper_batch)
// Perform tests both obfuscated and non-obfuscated.
for (int i = 0; i < 2; i++) {
bool obfuscate = (bool)i;
- path ph = temp_directory_path() / unique_path();
+ boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate);
char key = 'i';
@@ -90,7 +86,7 @@ BOOST_AUTO_TEST_CASE(dbwrapper_iterator)
// Perform tests both obfuscated and non-obfuscated.
for (int i = 0; i < 2; i++) {
bool obfuscate = (bool)i;
- path ph = temp_directory_path() / unique_path();
+ boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate);
// The two keys are intentionally chosen for ordering
@@ -129,8 +125,8 @@ BOOST_AUTO_TEST_CASE(dbwrapper_iterator)
// Test that we do not obfuscation if there is existing data.
BOOST_AUTO_TEST_CASE(existing_data_no_obfuscate)
{
- // We're going to share this path between two wrappers
- path ph = temp_directory_path() / unique_path();
+ // We're going to share this boost::filesystem::path between two wrappers
+ boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
create_directories(ph);
// Set up a non-obfuscated wrapper to write some initial data.
@@ -170,8 +166,8 @@ BOOST_AUTO_TEST_CASE(existing_data_no_obfuscate)
// Ensure that we start obfuscating during a reindex.
BOOST_AUTO_TEST_CASE(existing_data_reindex)
{
- // We're going to share this path between two wrappers
- path ph = temp_directory_path() / unique_path();
+ // We're going to share this boost::filesystem::path between two wrappers
+ boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
create_directories(ph);
// Set up a non-obfuscated wrapper to write some initial data.
@@ -206,7 +202,7 @@ BOOST_AUTO_TEST_CASE(existing_data_reindex)
BOOST_AUTO_TEST_CASE(iterator_ordering)
{
- path ph = temp_directory_path() / unique_path();
+ boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false, false);
for (int x=0x00; x<256; ++x) {
uint8_t key = x;
@@ -241,11 +237,11 @@ BOOST_AUTO_TEST_CASE(iterator_ordering)
struct StringContentsSerializer {
// Used to make two serialized objects the same while letting them have a different lengths
// This is a terrible idea
- string str;
+ std::string str;
StringContentsSerializer() {}
- StringContentsSerializer(const string& inp) : str(inp) {}
+ StringContentsSerializer(const std::string& inp) : str(inp) {}
- StringContentsSerializer& operator+=(const string& s) {
+ StringContentsSerializer& operator+=(const std::string& s) {
str += s;
return *this;
}
@@ -277,7 +273,7 @@ BOOST_AUTO_TEST_CASE(iterator_string_ordering)
{
char buf[10];
- path ph = temp_directory_path() / unique_path();
+ boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false, false);
for (int x=0x00; x<10; ++x) {
for (int y = 0; y < 10; y++) {
@@ -303,7 +299,7 @@ BOOST_AUTO_TEST_CASE(iterator_string_ordering)
for (int x=seek_start; x<10; ++x) {
for (int y = 0; y < 10; y++) {
sprintf(buf, "%d", x);
- string exp_key(buf);
+ std::string exp_key(buf);
for (int z = 0; z < y; z++)
exp_key += exp_key;
StringContentsSerializer key;
diff --git a/src/test/hash_tests.cpp b/src/test/hash_tests.cpp
index b265cf93b7..d8de765db1 100644
--- a/src/test/hash_tests.cpp
+++ b/src/test/hash_tests.cpp
@@ -10,8 +10,6 @@
#include <boost/test/unit_test.hpp>
-using namespace std;
-
BOOST_FIXTURE_TEST_SUITE(hash_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(murmurhash3)
diff --git a/src/test/key_tests.cpp b/src/test/key_tests.cpp
index 4978c95130..40a7fdf11d 100644
--- a/src/test/key_tests.cpp
+++ b/src/test/key_tests.cpp
@@ -16,19 +16,17 @@
#include <boost/test/unit_test.hpp>
-using namespace std;
-
-static const string strSecret1 ("5HxWvvfubhXpYYpS3tJkw6fq9jE9j18THftkZjHHfmFiWtmAbrj");
-static const string strSecret2 ("5KC4ejrDjv152FGwP386VD1i2NYc5KkfSMyv1nGy1VGDxGHqVY3");
-static const string strSecret1C ("Kwr371tjA9u2rFSMZjTNun2PXXP3WPZu2afRHTcta6KxEUdm1vEw");
-static const string strSecret2C ("L3Hq7a8FEQwJkW1M2GNKDW28546Vp5miewcCzSqUD9kCAXrJdS3g");
+static const std::string strSecret1 ("5HxWvvfubhXpYYpS3tJkw6fq9jE9j18THftkZjHHfmFiWtmAbrj");
+static const std::string strSecret2 ("5KC4ejrDjv152FGwP386VD1i2NYc5KkfSMyv1nGy1VGDxGHqVY3");
+static const std::string strSecret1C ("Kwr371tjA9u2rFSMZjTNun2PXXP3WPZu2afRHTcta6KxEUdm1vEw");
+static const std::string strSecret2C ("L3Hq7a8FEQwJkW1M2GNKDW28546Vp5miewcCzSqUD9kCAXrJdS3g");
static const CBitcoinAddress addr1 ("1QFqqMUD55ZV3PJEJZtaKCsQmjLT6JkjvJ");
static const CBitcoinAddress addr2 ("1F5y5E5FMc5YzdJtB9hLaUe43GDxEKXENJ");
static const CBitcoinAddress addr1C("1NoJrossxPBKfCHuJXT4HadJrXRE9Fxiqs");
static const CBitcoinAddress addr2C("1CRj2HyM1CXWzHAXLQtiGLyggNT9WQqsDs");
-static const string strAddressBad("1HV9Lc3sNHZxwj4Zk6fB38tEmBryq2cBiF");
+static const std::string strAddressBad("1HV9Lc3sNHZxwj4Zk6fB38tEmBryq2cBiF");
#ifdef KEY_TESTS_DUMPINFO
@@ -37,7 +35,7 @@ void dumpKeyInfo(uint256 privkey)
CKey key;
key.resize(32);
memcpy(&secret[0], &privkey, 32);
- vector<unsigned char> sec;
+ std::vector<unsigned char> sec;
sec.resize(32);
memcpy(&sec[0], &secret[0], 32);
printf(" * secret (hex): %s\n", HexStr(sec).c_str());
@@ -51,7 +49,7 @@ void dumpKeyInfo(uint256 privkey)
printf(" * secret (base58): %s\n", bsecret.ToString().c_str());
CKey key;
key.SetSecret(secret, fCompressed);
- vector<unsigned char> vchPubKey = key.GetPubKey();
+ std::vector<unsigned char> vchPubKey = key.GetPubKey();
printf(" * pubkey (hex): %s\n", HexStr(vchPubKey).c_str());
printf(" * address (base58): %s\n", CBitcoinAddress(vchPubKey).ToString().c_str());
}
@@ -111,12 +109,12 @@ BOOST_AUTO_TEST_CASE(key_test1)
for (int n=0; n<16; n++)
{
- string strMsg = strprintf("Very secret message %i: 11", n);
+ std::string strMsg = strprintf("Very secret message %i: 11", n);
uint256 hashMsg = Hash(strMsg.begin(), strMsg.end());
// normal signatures
- vector<unsigned char> sign1, sign2, sign1C, sign2C;
+ std::vector<unsigned char> sign1, sign2, sign1C, sign2C;
BOOST_CHECK(key1.Sign (hashMsg, sign1));
BOOST_CHECK(key2.Sign (hashMsg, sign2));
@@ -145,7 +143,7 @@ BOOST_AUTO_TEST_CASE(key_test1)
// compact signatures (with key recovery)
- vector<unsigned char> csign1, csign2, csign1C, csign2C;
+ std::vector<unsigned char> csign1, csign2, csign1C, csign2C;
BOOST_CHECK(key1.SignCompact (hashMsg, csign1));
BOOST_CHECK(key2.SignCompact (hashMsg, csign2));
@@ -168,7 +166,7 @@ BOOST_AUTO_TEST_CASE(key_test1)
// test deterministic signing
std::vector<unsigned char> detsig, detsigc;
- string strMsg = "Very deterministic message";
+ std::string strMsg = "Very deterministic message";
uint256 hashMsg = Hash(strMsg.begin(), strMsg.end());
BOOST_CHECK(key1.Sign(hashMsg, detsig));
BOOST_CHECK(key1C.Sign(hashMsg, detsigc));
diff --git a/src/test/multisig_tests.cpp b/src/test/multisig_tests.cpp
index e949bf7620..dd5678ea6e 100644
--- a/src/test/multisig_tests.cpp
+++ b/src/test/multisig_tests.cpp
@@ -17,14 +17,12 @@
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
-using namespace std;
-
-typedef vector<unsigned char> valtype;
+typedef std::vector<unsigned char> valtype;
BOOST_FIXTURE_TEST_SUITE(multisig_tests, BasicTestingSetup)
CScript
-sign_multisig(CScript scriptPubKey, vector<CKey> keys, CTransaction transaction, int whichIn)
+sign_multisig(CScript scriptPubKey, std::vector<CKey> keys, CTransaction transaction, int whichIn)
{
uint256 hash = SignatureHash(scriptPubKey, transaction, whichIn, SIGHASH_ALL, 0, SIGVERSION_BASE);
@@ -32,7 +30,7 @@ sign_multisig(CScript scriptPubKey, vector<CKey> keys, CTransaction transaction,
result << OP_0; // CHECKMULTISIG bug workaround
BOOST_FOREACH(const CKey &key, keys)
{
- vector<unsigned char> vchSig;
+ std::vector<unsigned char> vchSig;
BOOST_CHECK(key.Sign(hash, vchSig));
vchSig.push_back((unsigned char)SIGHASH_ALL);
result << vchSig;
@@ -75,7 +73,7 @@ BOOST_AUTO_TEST_CASE(multisig_verify)
txTo[i].vout[0].nValue = 1;
}
- vector<CKey> keys;
+ std::vector<CKey> keys;
CScript s;
// Test a AND b:
@@ -200,7 +198,7 @@ BOOST_AUTO_TEST_CASE(multisig_Solver1)
partialkeystore.AddKey(key[0]);
{
- vector<valtype> solutions;
+ std::vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << ToByteVector(key[0].GetPubKey()) << OP_CHECKSIG;
@@ -213,7 +211,7 @@ BOOST_AUTO_TEST_CASE(multisig_Solver1)
BOOST_CHECK(!IsMine(emptykeystore, s));
}
{
- vector<valtype> solutions;
+ std::vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << OP_DUP << OP_HASH160 << ToByteVector(key[0].GetPubKey().GetID()) << OP_EQUALVERIFY << OP_CHECKSIG;
@@ -226,7 +224,7 @@ BOOST_AUTO_TEST_CASE(multisig_Solver1)
BOOST_CHECK(!IsMine(emptykeystore, s));
}
{
- vector<valtype> solutions;
+ std::vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
@@ -239,13 +237,13 @@ BOOST_AUTO_TEST_CASE(multisig_Solver1)
BOOST_CHECK(!IsMine(partialkeystore, s));
}
{
- vector<valtype> solutions;
+ std::vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK(Solver(s, whichType, solutions));
BOOST_CHECK_EQUAL(solutions.size(), 4U);
- vector<CTxDestination> addrs;
+ std::vector<CTxDestination> addrs;
int nRequired;
BOOST_CHECK(ExtractDestinations(s, whichType, addrs, nRequired));
BOOST_CHECK(addrs[0] == keyaddr[0]);
@@ -256,7 +254,7 @@ BOOST_AUTO_TEST_CASE(multisig_Solver1)
BOOST_CHECK(!IsMine(partialkeystore, s));
}
{
- vector<valtype> solutions;
+ std::vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
diff --git a/src/test/net_tests.cpp b/src/test/net_tests.cpp
index 87cb38daac..0bd7869f32 100644
--- a/src/test/net_tests.cpp
+++ b/src/test/net_tests.cpp
@@ -12,8 +12,6 @@
#include "netbase.h"
#include "chainparams.h"
-using namespace std;
-
class CAddrManSerializationMock : public CAddrMan
{
public:
@@ -68,7 +66,7 @@ CDataStream AddrmanToStream(CAddrManSerializationMock& _addrman)
ssPeersIn << FLATDATA(Params().MessageStart());
ssPeersIn << _addrman;
std::string str = ssPeersIn.str();
- vector<unsigned char> vchData(str.begin(), str.end());
+ std::vector<unsigned char> vchData(str.begin(), str.end());
return CDataStream(vchData, SER_DISK, CLIENT_VERSION);
}
diff --git a/src/test/netbase_tests.cpp b/src/test/netbase_tests.cpp
index b0ad93e6f2..1afef5b1ce 100644
--- a/src/test/netbase_tests.cpp
+++ b/src/test/netbase_tests.cpp
@@ -10,8 +10,6 @@
#include <boost/assign/list_of.hpp>
#include <boost/test/unit_test.hpp>
-using namespace std;
-
BOOST_FIXTURE_TEST_SUITE(netbase_tests, BasicTestingSetup)
static CNetAddr ResolveIP(const char* ip)
@@ -64,9 +62,9 @@ BOOST_AUTO_TEST_CASE(netbase_properties)
}
-bool static TestSplitHost(string test, string host, int port)
+bool static TestSplitHost(std::string test, std::string host, int port)
{
- string hostOut;
+ std::string hostOut;
int portOut = -1;
SplitHostPort(test, portOut, hostOut);
return hostOut == host && port == portOut;
@@ -91,7 +89,7 @@ BOOST_AUTO_TEST_CASE(netbase_splithost)
BOOST_CHECK(TestSplitHost("", "", -1));
}
-bool static TestParse(string src, string canon)
+bool static TestParse(std::string src, std::string canon)
{
CService addr(LookupNumeric(src.c_str(), 65535));
return canon == addr.ToString();
diff --git a/src/test/pmt_tests.cpp b/src/test/pmt_tests.cpp
index da05385c80..a1cb32019a 100644
--- a/src/test/pmt_tests.cpp
+++ b/src/test/pmt_tests.cpp
@@ -17,8 +17,6 @@
#include <boost/assign/list_of.hpp>
#include <boost/test/unit_test.hpp>
-using namespace std;
-
class CPartialMerkleTreeTester : public CPartialMerkleTree
{
public:
diff --git a/src/test/pow_tests.cpp b/src/test/pow_tests.cpp
index b6eb39bc38..4ca6f1caf0 100644
--- a/src/test/pow_tests.cpp
+++ b/src/test/pow_tests.cpp
@@ -11,8 +11,6 @@
#include <boost/test/unit_test.hpp>
-using namespace std;
-
BOOST_FIXTURE_TEST_SUITE(pow_tests, BasicTestingSetup)
/* Test calculation of next difficulty target with no constraints applying */
diff --git a/src/test/raii_event_tests.cpp b/src/test/raii_event_tests.cpp
new file mode 100644
index 0000000000..87d25c0e2c
--- /dev/null
+++ b/src/test/raii_event_tests.cpp
@@ -0,0 +1,88 @@
+// Copyright (c) 2016 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#include <event2/event.h>
+#include <map>
+#include <stdlib.h>
+
+#include "support/events.h"
+
+#include "test/test_bitcoin.h"
+
+#include <vector>
+
+#include <boost/test/unit_test.hpp>
+
+static std::map<void*, short> tags;
+static std::map<void*, uint16_t> orders;
+static uint16_t tagSequence = 0;
+
+static void* tag_malloc(size_t sz) {
+ void* mem = malloc(sz);
+ if (!mem) return mem;
+ tags[mem]++;
+ orders[mem] = tagSequence++;
+ return mem;
+}
+
+static void tag_free(void* mem) {
+ tags[mem]--;
+ orders[mem] = tagSequence++;
+ free(mem);
+}
+
+BOOST_FIXTURE_TEST_SUITE(raii_event_tests, BasicTestingSetup)
+
+BOOST_AUTO_TEST_CASE(raii_event_creation)
+{
+ event_set_mem_functions(tag_malloc, realloc, tag_free);
+
+ void* base_ptr = NULL;
+ {
+ auto base = obtain_event_base();
+ base_ptr = (void*)base.get();
+ BOOST_CHECK(tags[base_ptr] == 1);
+ }
+ BOOST_CHECK(tags[base_ptr] == 0);
+
+ void* event_ptr = NULL;
+ {
+ auto base = obtain_event_base();
+ auto event = obtain_event(base.get(), -1, 0, NULL, NULL);
+
+ base_ptr = (void*)base.get();
+ event_ptr = (void*)event.get();
+
+ BOOST_CHECK(tags[base_ptr] == 1);
+ BOOST_CHECK(tags[event_ptr] == 1);
+ }
+ BOOST_CHECK(tags[base_ptr] == 0);
+ BOOST_CHECK(tags[event_ptr] == 0);
+
+ event_set_mem_functions(malloc, realloc, free);
+}
+
+BOOST_AUTO_TEST_CASE(raii_event_order)
+{
+ event_set_mem_functions(tag_malloc, realloc, tag_free);
+
+ void* base_ptr = NULL;
+ void* event_ptr = NULL;
+ {
+ auto base = obtain_event_base();
+ auto event = obtain_event(base.get(), -1, 0, NULL, NULL);
+
+ base_ptr = (void*)base.get();
+ event_ptr = (void*)event.get();
+
+ // base should have allocated before event
+ BOOST_CHECK(orders[base_ptr] < orders[event_ptr]);
+ }
+ // base should be freed after event
+ BOOST_CHECK(orders[base_ptr] > orders[event_ptr]);
+
+ event_set_mem_functions(malloc, realloc, free);
+}
+
+BOOST_AUTO_TEST_SUITE_END()
diff --git a/src/test/rpc_tests.cpp b/src/test/rpc_tests.cpp
index 36a29867ba..399bdbc811 100644
--- a/src/test/rpc_tests.cpp
+++ b/src/test/rpc_tests.cpp
@@ -16,13 +16,11 @@
#include <univalue.h>
-using namespace std;
-
-UniValue CallRPC(string args)
+UniValue CallRPC(std::string args)
{
- vector<string> vArgs;
+ std::vector<std::string> vArgs;
boost::split(vArgs, args, boost::is_any_of(" \t"));
- string strMethod = vArgs[0];
+ std::string strMethod = vArgs[0];
vArgs.erase(vArgs.begin());
JSONRPCRequest request;
request.strMethod = strMethod;
@@ -35,7 +33,7 @@ UniValue CallRPC(string args)
return result;
}
catch (const UniValue& objError) {
- throw runtime_error(find_value(objError, "message").get_str());
+ throw std::runtime_error(find_value(objError, "message").get_str());
}
}
@@ -47,41 +45,41 @@ BOOST_AUTO_TEST_CASE(rpc_rawparams)
// Test raw transaction API argument handling
UniValue r;
- BOOST_CHECK_THROW(CallRPC("getrawtransaction"), runtime_error);
- BOOST_CHECK_THROW(CallRPC("getrawtransaction not_hex"), runtime_error);
- BOOST_CHECK_THROW(CallRPC("getrawtransaction a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed not_int"), runtime_error);
+ BOOST_CHECK_THROW(CallRPC("getrawtransaction"), std::runtime_error);
+ BOOST_CHECK_THROW(CallRPC("getrawtransaction not_hex"), std::runtime_error);
+ BOOST_CHECK_THROW(CallRPC("getrawtransaction a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed not_int"), std::runtime_error);
- BOOST_CHECK_THROW(CallRPC("createrawtransaction"), runtime_error);
- BOOST_CHECK_THROW(CallRPC("createrawtransaction null null"), runtime_error);
- BOOST_CHECK_THROW(CallRPC("createrawtransaction not_array"), runtime_error);
- BOOST_CHECK_THROW(CallRPC("createrawtransaction [] []"), runtime_error);
- BOOST_CHECK_THROW(CallRPC("createrawtransaction {} {}"), runtime_error);
+ BOOST_CHECK_THROW(CallRPC("createrawtransaction"), std::runtime_error);
+ BOOST_CHECK_THROW(CallRPC("createrawtransaction null null"), std::runtime_error);
+ BOOST_CHECK_THROW(CallRPC("createrawtransaction not_array"), std::runtime_error);
+ BOOST_CHECK_THROW(CallRPC("createrawtransaction [] []"), std::runtime_error);
+ BOOST_CHECK_THROW(CallRPC("createrawtransaction {} {}"), std::runtime_error);
BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [] {}"));
- BOOST_CHECK_THROW(CallRPC("createrawtransaction [] {} extra"), runtime_error);
+ BOOST_CHECK_THROW(CallRPC("createrawtransaction [] {} extra"), std::runtime_error);
- BOOST_CHECK_THROW(CallRPC("decoderawtransaction"), runtime_error);
- BOOST_CHECK_THROW(CallRPC("decoderawtransaction null"), runtime_error);
- BOOST_CHECK_THROW(CallRPC("decoderawtransaction DEADBEEF"), runtime_error);
- string rawtx = "0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000";
- BOOST_CHECK_NO_THROW(r = CallRPC(string("decoderawtransaction ")+rawtx));
+ BOOST_CHECK_THROW(CallRPC("decoderawtransaction"), std::runtime_error);
+ BOOST_CHECK_THROW(CallRPC("decoderawtransaction null"), std::runtime_error);
+ BOOST_CHECK_THROW(CallRPC("decoderawtransaction DEADBEEF"), std::runtime_error);
+ std::string rawtx = "0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000";
+ BOOST_CHECK_NO_THROW(r = CallRPC(std::string("decoderawtransaction ")+rawtx));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "size").get_int(), 193);
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "version").get_int(), 1);
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "locktime").get_int(), 0);
- BOOST_CHECK_THROW(r = CallRPC(string("decoderawtransaction ")+rawtx+" extra"), runtime_error);
+ BOOST_CHECK_THROW(r = CallRPC(std::string("decoderawtransaction ")+rawtx+" extra"), std::runtime_error);
- BOOST_CHECK_THROW(CallRPC("signrawtransaction"), runtime_error);
- BOOST_CHECK_THROW(CallRPC("signrawtransaction null"), runtime_error);
- BOOST_CHECK_THROW(CallRPC("signrawtransaction ff00"), runtime_error);
- BOOST_CHECK_NO_THROW(CallRPC(string("signrawtransaction ")+rawtx));
- BOOST_CHECK_NO_THROW(CallRPC(string("signrawtransaction ")+rawtx+" null null NONE|ANYONECANPAY"));
- BOOST_CHECK_NO_THROW(CallRPC(string("signrawtransaction ")+rawtx+" [] [] NONE|ANYONECANPAY"));
- BOOST_CHECK_THROW(CallRPC(string("signrawtransaction ")+rawtx+" null null badenum"), runtime_error);
+ BOOST_CHECK_THROW(CallRPC("signrawtransaction"), std::runtime_error);
+ BOOST_CHECK_THROW(CallRPC("signrawtransaction null"), std::runtime_error);
+ BOOST_CHECK_THROW(CallRPC("signrawtransaction ff00"), std::runtime_error);
+ BOOST_CHECK_NO_THROW(CallRPC(std::string("signrawtransaction ")+rawtx));
+ BOOST_CHECK_NO_THROW(CallRPC(std::string("signrawtransaction ")+rawtx+" null null NONE|ANYONECANPAY"));
+ BOOST_CHECK_NO_THROW(CallRPC(std::string("signrawtransaction ")+rawtx+" [] [] NONE|ANYONECANPAY"));
+ BOOST_CHECK_THROW(CallRPC(std::string("signrawtransaction ")+rawtx+" null null badenum"), std::runtime_error);
// Only check failure cases for sendrawtransaction, there's no network to send to...
- BOOST_CHECK_THROW(CallRPC("sendrawtransaction"), runtime_error);
- BOOST_CHECK_THROW(CallRPC("sendrawtransaction null"), runtime_error);
- BOOST_CHECK_THROW(CallRPC("sendrawtransaction DEADBEEF"), runtime_error);
- BOOST_CHECK_THROW(CallRPC(string("sendrawtransaction ")+rawtx+" extra"), runtime_error);
+ BOOST_CHECK_THROW(CallRPC("sendrawtransaction"), std::runtime_error);
+ BOOST_CHECK_THROW(CallRPC("sendrawtransaction null"), std::runtime_error);
+ BOOST_CHECK_THROW(CallRPC("sendrawtransaction DEADBEEF"), std::runtime_error);
+ BOOST_CHECK_THROW(CallRPC(std::string("sendrawtransaction ")+rawtx+" extra"), std::runtime_error);
}
BOOST_AUTO_TEST_CASE(rpc_togglenetwork)
@@ -110,18 +108,18 @@ BOOST_AUTO_TEST_CASE(rpc_rawsign)
{
UniValue r;
// input is a 1-of-2 multisig (so is output):
- string prevout =
+ std::string prevout =
"[{\"txid\":\"b4cc287e58f87cdae59417329f710f3ecd75a4ee1d2872b7248f50977c8493f3\","
"\"vout\":1,\"scriptPubKey\":\"a914b10c9df5f7edf436c697f02f1efdba4cf399615187\","
"\"redeemScript\":\"512103debedc17b3df2badbcdd86d5feb4562b86fe182e5998abd8bcd4f122c6155b1b21027e940bb73ab8732bfdf7f9216ecefca5b94d6df834e77e108f68e66f126044c052ae\"}]";
- r = CallRPC(string("createrawtransaction ")+prevout+" "+
+ r = CallRPC(std::string("createrawtransaction ")+prevout+" "+
"{\"3HqAe9LtNBjnsfM4CyYaWTnvCaUYT7v4oZ\":11}");
- string notsigned = r.get_str();
- string privkey1 = "\"KzsXybp9jX64P5ekX1KUxRQ79Jht9uzW7LorgwE65i5rWACL6LQe\"";
- string privkey2 = "\"Kyhdf5LuKTRx4ge69ybABsiUAWjVRK4XGxAKk2FQLp2HjGMy87Z4\"";
- r = CallRPC(string("signrawtransaction ")+notsigned+" "+prevout+" "+"[]");
+ std::string notsigned = r.get_str();
+ std::string privkey1 = "\"KzsXybp9jX64P5ekX1KUxRQ79Jht9uzW7LorgwE65i5rWACL6LQe\"";
+ std::string privkey2 = "\"Kyhdf5LuKTRx4ge69ybABsiUAWjVRK4XGxAKk2FQLp2HjGMy87Z4\"";
+ r = CallRPC(std::string("signrawtransaction ")+notsigned+" "+prevout+" "+"[]");
BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == false);
- r = CallRPC(string("signrawtransaction ")+notsigned+" "+prevout+" "+"["+privkey1+","+privkey2+"]");
+ r = CallRPC(std::string("signrawtransaction ")+notsigned+" "+prevout+" "+"["+privkey1+","+privkey2+"]");
BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == true);
}
@@ -133,11 +131,11 @@ BOOST_AUTO_TEST_CASE(rpc_createraw_op_return)
BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"68656c6c6f776f726c64\",\"data\":\"68656c6c6f776f726c64\"}"));
// Key not "data" (bad address)
- BOOST_CHECK_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"somedata\":\"68656c6c6f776f726c64\"}"), runtime_error);
+ BOOST_CHECK_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"somedata\":\"68656c6c6f776f726c64\"}"), std::runtime_error);
// Bad hex encoding of data output
- BOOST_CHECK_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"12345\"}"), runtime_error);
- BOOST_CHECK_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"12345g\"}"), runtime_error);
+ BOOST_CHECK_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"12345\"}"), std::runtime_error);
+ BOOST_CHECK_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"12345g\"}"), std::runtime_error);
// Data 81 bytes long
BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081\"}"));
@@ -241,23 +239,23 @@ BOOST_AUTO_TEST_CASE(json_parse_errors)
BOOST_AUTO_TEST_CASE(rpc_ban)
{
- BOOST_CHECK_NO_THROW(CallRPC(string("clearbanned")));
-
+ BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned")));
+
UniValue r;
- BOOST_CHECK_NO_THROW(r = CallRPC(string("setban 127.0.0.0 add")));
- BOOST_CHECK_THROW(r = CallRPC(string("setban 127.0.0.0:8334")), runtime_error); //portnumber for setban not allowed
- BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned")));
+ BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 127.0.0.0 add")));
+ BOOST_CHECK_THROW(r = CallRPC(std::string("setban 127.0.0.0:8334")), std::runtime_error); //portnumber for setban not allowed
+ BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned")));
UniValue ar = r.get_array();
UniValue o1 = ar[0].get_obj();
UniValue adr = find_value(o1, "address");
BOOST_CHECK_EQUAL(adr.get_str(), "127.0.0.0/32");
- BOOST_CHECK_NO_THROW(CallRPC(string("setban 127.0.0.0 remove")));
- BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned")));
+ BOOST_CHECK_NO_THROW(CallRPC(std::string("setban 127.0.0.0 remove")));
+ BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned")));
ar = r.get_array();
BOOST_CHECK_EQUAL(ar.size(), 0);
- BOOST_CHECK_NO_THROW(r = CallRPC(string("setban 127.0.0.0/24 add 1607731200 true")));
- BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned")));
+ BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 127.0.0.0/24 add 1607731200 true")));
+ BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned")));
ar = r.get_array();
o1 = ar[0].get_obj();
adr = find_value(o1, "address");
@@ -265,10 +263,10 @@ BOOST_AUTO_TEST_CASE(rpc_ban)
BOOST_CHECK_EQUAL(adr.get_str(), "127.0.0.0/24");
BOOST_CHECK_EQUAL(banned_until.get_int64(), 1607731200); // absolute time check
- BOOST_CHECK_NO_THROW(CallRPC(string("clearbanned")));
+ BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned")));
- BOOST_CHECK_NO_THROW(r = CallRPC(string("setban 127.0.0.0/24 add 200")));
- BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned")));
+ BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 127.0.0.0/24 add 200")));
+ BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned")));
ar = r.get_array();
o1 = ar[0].get_obj();
adr = find_value(o1, "address");
@@ -279,43 +277,43 @@ BOOST_AUTO_TEST_CASE(rpc_ban)
BOOST_CHECK(banned_until.get_int64()-now <= 200);
// must throw an exception because 127.0.0.1 is in already banned suubnet range
- BOOST_CHECK_THROW(r = CallRPC(string("setban 127.0.0.1 add")), runtime_error);
+ BOOST_CHECK_THROW(r = CallRPC(std::string("setban 127.0.0.1 add")), std::runtime_error);
- BOOST_CHECK_NO_THROW(CallRPC(string("setban 127.0.0.0/24 remove")));
- BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned")));
+ BOOST_CHECK_NO_THROW(CallRPC(std::string("setban 127.0.0.0/24 remove")));
+ BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned")));
ar = r.get_array();
BOOST_CHECK_EQUAL(ar.size(), 0);
- BOOST_CHECK_NO_THROW(r = CallRPC(string("setban 127.0.0.0/255.255.0.0 add")));
- BOOST_CHECK_THROW(r = CallRPC(string("setban 127.0.1.1 add")), runtime_error);
+ BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 127.0.0.0/255.255.0.0 add")));
+ BOOST_CHECK_THROW(r = CallRPC(std::string("setban 127.0.1.1 add")), std::runtime_error);
- BOOST_CHECK_NO_THROW(CallRPC(string("clearbanned")));
- BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned")));
+ BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned")));
+ BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned")));
ar = r.get_array();
BOOST_CHECK_EQUAL(ar.size(), 0);
- BOOST_CHECK_THROW(r = CallRPC(string("setban test add")), runtime_error); //invalid IP
+ BOOST_CHECK_THROW(r = CallRPC(std::string("setban test add")), std::runtime_error); //invalid IP
//IPv6 tests
- BOOST_CHECK_NO_THROW(r = CallRPC(string("setban FE80:0000:0000:0000:0202:B3FF:FE1E:8329 add")));
- BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned")));
+ BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban FE80:0000:0000:0000:0202:B3FF:FE1E:8329 add")));
+ BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned")));
ar = r.get_array();
o1 = ar[0].get_obj();
adr = find_value(o1, "address");
BOOST_CHECK_EQUAL(adr.get_str(), "fe80::202:b3ff:fe1e:8329/128");
- BOOST_CHECK_NO_THROW(CallRPC(string("clearbanned")));
- BOOST_CHECK_NO_THROW(r = CallRPC(string("setban 2001:db8::/ffff:fffc:0:0:0:0:0:0 add")));
- BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned")));
+ BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned")));
+ BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 2001:db8::/ffff:fffc:0:0:0:0:0:0 add")));
+ BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned")));
ar = r.get_array();
o1 = ar[0].get_obj();
adr = find_value(o1, "address");
BOOST_CHECK_EQUAL(adr.get_str(), "2001:db8::/30");
- BOOST_CHECK_NO_THROW(CallRPC(string("clearbanned")));
- BOOST_CHECK_NO_THROW(r = CallRPC(string("setban 2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63/128 add")));
- BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned")));
+ BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned")));
+ BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63/128 add")));
+ BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned")));
ar = r.get_array();
o1 = ar[0].get_obj();
adr = find_value(o1, "address");
diff --git a/src/test/script_P2SH_tests.cpp b/src/test/script_P2SH_tests.cpp
index 85da90c75d..f8fd8cc30c 100644
--- a/src/test/script_P2SH_tests.cpp
+++ b/src/test/script_P2SH_tests.cpp
@@ -17,8 +17,6 @@
#include <boost/test/unit_test.hpp>
-using namespace std;
-
// Helpers:
static std::vector<unsigned char>
Serialize(const CScript& s)
@@ -80,7 +78,7 @@ BOOST_AUTO_TEST_CASE(sign)
}
CMutableTransaction txFrom; // Funding transaction:
- string reason;
+ std::string reason;
txFrom.vout.resize(8);
for (int i = 0; i < 4; i++)
{
@@ -178,7 +176,7 @@ BOOST_AUTO_TEST_CASE(set)
}
CMutableTransaction txFrom; // Funding transaction:
- string reason;
+ std::string reason;
txFrom.vout.resize(4);
for (int i = 0; i < 4; i++)
{
@@ -263,7 +261,7 @@ BOOST_AUTO_TEST_CASE(AreInputsStandard)
CCoinsViewCache coins(&coinsDummy);
CBasicKeyStore keystore;
CKey key[6];
- vector<CPubKey> keys;
+ std::vector<CPubKey> keys;
for (int i = 0; i < 6; i++)
{
key[i].MakeNewKey(true);
@@ -335,8 +333,8 @@ BOOST_AUTO_TEST_CASE(AreInputsStandard)
// SignSignature doesn't know how to sign these. We're
// not testing validating signatures, so just create
// dummy signatures that DO include the correct P2SH scripts:
- txTo.vin[3].scriptSig << OP_11 << OP_11 << vector<unsigned char>(oneAndTwo.begin(), oneAndTwo.end());
- txTo.vin[4].scriptSig << vector<unsigned char>(fifteenSigops.begin(), fifteenSigops.end());
+ txTo.vin[3].scriptSig << OP_11 << OP_11 << std::vector<unsigned char>(oneAndTwo.begin(), oneAndTwo.end());
+ txTo.vin[4].scriptSig << std::vector<unsigned char>(fifteenSigops.begin(), fifteenSigops.end());
BOOST_CHECK(::AreInputsStandard(txTo, coins));
// 22 P2SH sigops for all inputs (1 for vin[0], 6 for vin[3], 15 for vin[4]
@@ -349,7 +347,7 @@ BOOST_AUTO_TEST_CASE(AreInputsStandard)
txToNonStd1.vin.resize(1);
txToNonStd1.vin[0].prevout.n = 5;
txToNonStd1.vin[0].prevout.hash = txFrom.GetHash();
- txToNonStd1.vin[0].scriptSig << vector<unsigned char>(sixteenSigops.begin(), sixteenSigops.end());
+ txToNonStd1.vin[0].scriptSig << std::vector<unsigned char>(sixteenSigops.begin(), sixteenSigops.end());
BOOST_CHECK(!::AreInputsStandard(txToNonStd1, coins));
BOOST_CHECK_EQUAL(GetP2SHSigOpCount(txToNonStd1, coins), 16U);
@@ -361,7 +359,7 @@ BOOST_AUTO_TEST_CASE(AreInputsStandard)
txToNonStd2.vin.resize(1);
txToNonStd2.vin[0].prevout.n = 6;
txToNonStd2.vin[0].prevout.hash = txFrom.GetHash();
- txToNonStd2.vin[0].scriptSig << vector<unsigned char>(twentySigops.begin(), twentySigops.end());
+ txToNonStd2.vin[0].scriptSig << std::vector<unsigned char>(twentySigops.begin(), twentySigops.end());
BOOST_CHECK(!::AreInputsStandard(txToNonStd2, coins));
BOOST_CHECK_EQUAL(GetP2SHSigOpCount(txToNonStd2, coins), 20U);
diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index deb2919f14..6f057f43b4 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -29,15 +29,13 @@
#include <univalue.h>
-using namespace std;
-
// Uncomment if you want to output updated JSON tests.
// #define UPDATE_JSON_TESTS
static const unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC;
-unsigned int ParseScriptFlags(string strFlags);
-string FormatScriptFlags(unsigned int flags);
+unsigned int ParseScriptFlags(std::string strFlags);
+std::string FormatScriptFlags(unsigned int flags);
UniValue
read_json(const std::string& jsondata)
@@ -800,7 +798,7 @@ BOOST_AUTO_TEST_CASE(script_build)
CScript witscript = CScript() << ToByteVector(keys.pubkey0);
uint256 hash;
CSHA256().Write(&witscript[0], witscript.size()).Finalize(hash.begin());
- vector<unsigned char> hashBytes = ToByteVector(hash);
+ std::vector<unsigned char> hashBytes = ToByteVector(hash);
hashBytes.pop_back();
tests.push_back(TestBuilder(CScript() << OP_0 << hashBytes,
"P2WPKH with wrong witness program length", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false
@@ -965,7 +963,7 @@ BOOST_AUTO_TEST_CASE(script_json_test)
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
- string strTest = test.write();
+ std::string strTest = test.write();
CScriptWitness witness;
CAmount nValue = 0;
unsigned int pos = 0;
@@ -984,9 +982,9 @@ BOOST_AUTO_TEST_CASE(script_json_test)
}
continue;
}
- string scriptSigString = test[pos++].get_str();
+ std::string scriptSigString = test[pos++].get_str();
CScript scriptSig = ParseScript(scriptSigString);
- string scriptPubKeyString = test[pos++].get_str();
+ std::string scriptPubKeyString = test[pos++].get_str();
CScript scriptPubKey = ParseScript(scriptPubKeyString);
unsigned int scriptflags = ParseScriptFlags(test[pos++].get_str());
int scriptError = ParseScriptError(test[pos++].get_str());
@@ -1005,21 +1003,21 @@ BOOST_AUTO_TEST_CASE(script_PushData)
static const unsigned char pushdata4[] = { OP_PUSHDATA4, 1, 0, 0, 0, 0x5a };
ScriptError err;
- vector<vector<unsigned char> > directStack;
+ std::vector<std::vector<unsigned char> > directStack;
BOOST_CHECK(EvalScript(directStack, CScript(&direct[0], &direct[sizeof(direct)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SIGVERSION_BASE, &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
- vector<vector<unsigned char> > pushdata1Stack;
+ std::vector<std::vector<unsigned char> > pushdata1Stack;
BOOST_CHECK(EvalScript(pushdata1Stack, CScript(&pushdata1[0], &pushdata1[sizeof(pushdata1)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SIGVERSION_BASE, &err));
BOOST_CHECK(pushdata1Stack == directStack);
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
- vector<vector<unsigned char> > pushdata2Stack;
+ std::vector<std::vector<unsigned char> > pushdata2Stack;
BOOST_CHECK(EvalScript(pushdata2Stack, CScript(&pushdata2[0], &pushdata2[sizeof(pushdata2)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SIGVERSION_BASE, &err));
BOOST_CHECK(pushdata2Stack == directStack);
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
- vector<vector<unsigned char> > pushdata4Stack;
+ std::vector<std::vector<unsigned char> > pushdata4Stack;
BOOST_CHECK(EvalScript(pushdata4Stack, CScript(&pushdata4[0], &pushdata4[sizeof(pushdata4)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SIGVERSION_BASE, &err));
BOOST_CHECK(pushdata4Stack == directStack);
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
@@ -1042,7 +1040,7 @@ sign_multisig(CScript scriptPubKey, std::vector<CKey> keys, CTransaction transac
result << OP_0;
BOOST_FOREACH(const CKey &key, keys)
{
- vector<unsigned char> vchSig;
+ std::vector<unsigned char> vchSig;
BOOST_CHECK(key.Sign(hash, vchSig));
vchSig.push_back((unsigned char)SIGHASH_ALL);
result << vchSig;
@@ -1161,8 +1159,8 @@ BOOST_AUTO_TEST_CASE(script_combineSigs)
// Test the CombineSignatures function
CAmount amount = 0;
CBasicKeyStore keystore;
- vector<CKey> keys;
- vector<CPubKey> pubkeys;
+ std::vector<CKey> keys;
+ std::vector<CPubKey> pubkeys;
for (int i = 0; i < 3; i++)
{
CKey key;
@@ -1223,15 +1221,15 @@ BOOST_AUTO_TEST_CASE(script_combineSigs)
BOOST_CHECK(combined.scriptSig == scriptSig);
// A couple of partially-signed versions:
- vector<unsigned char> sig1;
+ std::vector<unsigned char> sig1;
uint256 hash1 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_ALL, 0, SIGVERSION_BASE);
BOOST_CHECK(keys[0].Sign(hash1, sig1));
sig1.push_back(SIGHASH_ALL);
- vector<unsigned char> sig2;
+ std::vector<unsigned char> sig2;
uint256 hash2 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_NONE, 0, SIGVERSION_BASE);
BOOST_CHECK(keys[1].Sign(hash2, sig2));
sig2.push_back(SIGHASH_NONE);
- vector<unsigned char> sig3;
+ std::vector<unsigned char> sig3;
uint256 hash3 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_SINGLE, 0, SIGVERSION_BASE);
BOOST_CHECK(keys[2].Sign(hash3, sig3));
sig3.push_back(SIGHASH_SINGLE);
@@ -1305,9 +1303,9 @@ BOOST_AUTO_TEST_CASE(script_GetScriptAsm)
BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_NOP2));
BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_CHECKLOCKTIMEVERIFY));
- string derSig("304502207fa7a6d1e0ee81132a269ad84e68d695483745cde8b541e3bf630749894e342a022100c1f7ab20e13e22fb95281a870f3dcf38d782e53023ee313d741ad0cfbc0c5090");
- string pubKey("03b0da749730dc9b4b1f4a14d6902877a92541f5368778853d9c4a0cb7802dcfb2");
- vector<unsigned char> vchPubKey = ToByteVector(ParseHex(pubKey));
+ std::string derSig("304502207fa7a6d1e0ee81132a269ad84e68d695483745cde8b541e3bf630749894e342a022100c1f7ab20e13e22fb95281a870f3dcf38d782e53023ee313d741ad0cfbc0c5090");
+ std::string pubKey("03b0da749730dc9b4b1f4a14d6902877a92541f5368778853d9c4a0cb7802dcfb2");
+ std::vector<unsigned char> vchPubKey = ToByteVector(ParseHex(pubKey));
BOOST_CHECK_EQUAL(derSig + "00 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "00")) << vchPubKey, true));
BOOST_CHECK_EQUAL(derSig + "80 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "80")) << vchPubKey, true));
diff --git a/src/test/serialize_tests.cpp b/src/test/serialize_tests.cpp
index 5c192a1f41..2d54668eaf 100644
--- a/src/test/serialize_tests.cpp
+++ b/src/test/serialize_tests.cpp
@@ -10,7 +10,6 @@
#include <stdint.h>
#include <boost/test/unit_test.hpp>
-using namespace std;
BOOST_FIXTURE_TEST_SUITE(serialize_tests, BasicTestingSetup)
@@ -227,7 +226,7 @@ BOOST_AUTO_TEST_CASE(varints_bitpatterns)
BOOST_AUTO_TEST_CASE(compactsize)
{
CDataStream ss(SER_DISK, 0);
- vector<char>::size_type i, j;
+ std::vector<char>::size_type i, j;
for (i = 1; i <= MAX_SIZE; i *= 2)
{
@@ -260,7 +259,7 @@ BOOST_AUTO_TEST_CASE(noncanonical)
// Write some non-canonical CompactSize encodings, and
// make sure an exception is thrown when read back.
CDataStream ss(SER_DISK, 0);
- vector<char>::size_type n;
+ std::vector<char>::size_type n;
// zero encoded with three bytes:
ss.write("\xfd\x00\x00", 3);
diff --git a/src/test/sigopcount_tests.cpp b/src/test/sigopcount_tests.cpp
index edafb76c43..13d8911f03 100644
--- a/src/test/sigopcount_tests.cpp
+++ b/src/test/sigopcount_tests.cpp
@@ -15,8 +15,6 @@
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
-using namespace std;
-
// Helpers:
static std::vector<unsigned char>
Serialize(const CScript& s)
@@ -160,8 +158,8 @@ BOOST_AUTO_TEST_CASE(GetTxSigOpCost)
CScript scriptPubKey = GetScriptForWitness(p2pk);
CScript scriptSig = CScript();
CScriptWitness scriptWitness;
- scriptWitness.stack.push_back(vector<unsigned char>(0));
- scriptWitness.stack.push_back(vector<unsigned char>(0));
+ scriptWitness.stack.push_back(std::vector<unsigned char>(0));
+ scriptWitness.stack.push_back(std::vector<unsigned char>(0));
BuildTxs(spendingTx, coins, creationTx, scriptPubKey, scriptSig, scriptWitness);
@@ -190,8 +188,8 @@ BOOST_AUTO_TEST_CASE(GetTxSigOpCost)
CScript scriptPubKey = GetScriptForDestination(CScriptID(scriptSig));
scriptSig = CScript() << ToByteVector(scriptSig);
CScriptWitness scriptWitness;
- scriptWitness.stack.push_back(vector<unsigned char>(0));
- scriptWitness.stack.push_back(vector<unsigned char>(0));
+ scriptWitness.stack.push_back(std::vector<unsigned char>(0));
+ scriptWitness.stack.push_back(std::vector<unsigned char>(0));
BuildTxs(spendingTx, coins, creationTx, scriptPubKey, scriptSig, scriptWitness);
assert(GetTransactionSigOpCost(CTransaction(spendingTx), coins, flags) == 1);
@@ -204,9 +202,9 @@ BOOST_AUTO_TEST_CASE(GetTxSigOpCost)
CScript scriptPubKey = GetScriptForWitness(witnessScript);
CScript scriptSig = CScript();
CScriptWitness scriptWitness;
- scriptWitness.stack.push_back(vector<unsigned char>(0));
- scriptWitness.stack.push_back(vector<unsigned char>(0));
- scriptWitness.stack.push_back(vector<unsigned char>(witnessScript.begin(), witnessScript.end()));
+ scriptWitness.stack.push_back(std::vector<unsigned char>(0));
+ scriptWitness.stack.push_back(std::vector<unsigned char>(0));
+ scriptWitness.stack.push_back(std::vector<unsigned char>(witnessScript.begin(), witnessScript.end()));
BuildTxs(spendingTx, coins, creationTx, scriptPubKey, scriptSig, scriptWitness);
assert(GetTransactionSigOpCost(CTransaction(spendingTx), coins, flags) == 2);
@@ -221,9 +219,9 @@ BOOST_AUTO_TEST_CASE(GetTxSigOpCost)
CScript scriptPubKey = GetScriptForDestination(CScriptID(redeemScript));
CScript scriptSig = CScript() << ToByteVector(redeemScript);
CScriptWitness scriptWitness;
- scriptWitness.stack.push_back(vector<unsigned char>(0));
- scriptWitness.stack.push_back(vector<unsigned char>(0));
- scriptWitness.stack.push_back(vector<unsigned char>(witnessScript.begin(), witnessScript.end()));
+ scriptWitness.stack.push_back(std::vector<unsigned char>(0));
+ scriptWitness.stack.push_back(std::vector<unsigned char>(0));
+ scriptWitness.stack.push_back(std::vector<unsigned char>(witnessScript.begin(), witnessScript.end()));
BuildTxs(spendingTx, coins, creationTx, scriptPubKey, scriptSig, scriptWitness);
assert(GetTransactionSigOpCost(CTransaction(spendingTx), coins, flags) == 2);
diff --git a/src/test/streams_tests.cpp b/src/test/streams_tests.cpp
index 31bcebe919..94b5cc119b 100644
--- a/src/test/streams_tests.cpp
+++ b/src/test/streams_tests.cpp
@@ -9,8 +9,7 @@
#include <boost/assign/std/vector.hpp> // for 'operator+=()'
#include <boost/assert.hpp>
#include <boost/test/unit_test.hpp>
-
-using namespace std;
+
using namespace boost::assign; // bring 'operator+=()' into scope
BOOST_FIXTURE_TEST_SUITE(streams_tests, BasicTestingSetup)
diff --git a/src/test/timedata_tests.cpp b/src/test/timedata_tests.cpp
index 1224ff8454..34863fd9d0 100644
--- a/src/test/timedata_tests.cpp
+++ b/src/test/timedata_tests.cpp
@@ -7,8 +7,6 @@
#include <boost/test/unit_test.hpp>
-using namespace std;
-
BOOST_FIXTURE_TEST_SUITE(timedata_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(util_MedianFilter)
diff --git a/src/test/transaction_tests.cpp b/src/test/transaction_tests.cpp
index cd9294c7a9..8c9aaef02f 100644
--- a/src/test/transaction_tests.cpp
+++ b/src/test/transaction_tests.cpp
@@ -32,42 +32,40 @@
#include <univalue.h>
-using namespace std;
-
-typedef vector<unsigned char> valtype;
+typedef std::vector<unsigned char> valtype;
// In script_tests.cpp
extern UniValue read_json(const std::string& jsondata);
-static std::map<string, unsigned int> mapFlagNames = boost::assign::map_list_of
- (string("NONE"), (unsigned int)SCRIPT_VERIFY_NONE)
- (string("P2SH"), (unsigned int)SCRIPT_VERIFY_P2SH)
- (string("STRICTENC"), (unsigned int)SCRIPT_VERIFY_STRICTENC)
- (string("DERSIG"), (unsigned int)SCRIPT_VERIFY_DERSIG)
- (string("LOW_S"), (unsigned int)SCRIPT_VERIFY_LOW_S)
- (string("SIGPUSHONLY"), (unsigned int)SCRIPT_VERIFY_SIGPUSHONLY)
- (string("MINIMALDATA"), (unsigned int)SCRIPT_VERIFY_MINIMALDATA)
- (string("NULLDUMMY"), (unsigned int)SCRIPT_VERIFY_NULLDUMMY)
- (string("DISCOURAGE_UPGRADABLE_NOPS"), (unsigned int)SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
- (string("CLEANSTACK"), (unsigned int)SCRIPT_VERIFY_CLEANSTACK)
- (string("MINIMALIF"), (unsigned int)SCRIPT_VERIFY_MINIMALIF)
- (string("NULLFAIL"), (unsigned int)SCRIPT_VERIFY_NULLFAIL)
- (string("CHECKLOCKTIMEVERIFY"), (unsigned int)SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)
- (string("CHECKSEQUENCEVERIFY"), (unsigned int)SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)
- (string("WITNESS"), (unsigned int)SCRIPT_VERIFY_WITNESS)
- (string("DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM"), (unsigned int)SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM)
- (string("WITNESS_PUBKEYTYPE"), (unsigned int)SCRIPT_VERIFY_WITNESS_PUBKEYTYPE);
-
-unsigned int ParseScriptFlags(string strFlags)
+static std::map<std::string, unsigned int> mapFlagNames = boost::assign::map_list_of
+ (std::string("NONE"), (unsigned int)SCRIPT_VERIFY_NONE)
+ (std::string("P2SH"), (unsigned int)SCRIPT_VERIFY_P2SH)
+ (std::string("STRICTENC"), (unsigned int)SCRIPT_VERIFY_STRICTENC)
+ (std::string("DERSIG"), (unsigned int)SCRIPT_VERIFY_DERSIG)
+ (std::string("LOW_S"), (unsigned int)SCRIPT_VERIFY_LOW_S)
+ (std::string("SIGPUSHONLY"), (unsigned int)SCRIPT_VERIFY_SIGPUSHONLY)
+ (std::string("MINIMALDATA"), (unsigned int)SCRIPT_VERIFY_MINIMALDATA)
+ (std::string("NULLDUMMY"), (unsigned int)SCRIPT_VERIFY_NULLDUMMY)
+ (std::string("DISCOURAGE_UPGRADABLE_NOPS"), (unsigned int)SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
+ (std::string("CLEANSTACK"), (unsigned int)SCRIPT_VERIFY_CLEANSTACK)
+ (std::string("MINIMALIF"), (unsigned int)SCRIPT_VERIFY_MINIMALIF)
+ (std::string("NULLFAIL"), (unsigned int)SCRIPT_VERIFY_NULLFAIL)
+ (std::string("CHECKLOCKTIMEVERIFY"), (unsigned int)SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)
+ (std::string("CHECKSEQUENCEVERIFY"), (unsigned int)SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)
+ (std::string("WITNESS"), (unsigned int)SCRIPT_VERIFY_WITNESS)
+ (std::string("DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM"), (unsigned int)SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM)
+ (std::string("WITNESS_PUBKEYTYPE"), (unsigned int)SCRIPT_VERIFY_WITNESS_PUBKEYTYPE);
+
+unsigned int ParseScriptFlags(std::string strFlags)
{
if (strFlags.empty()) {
return 0;
}
unsigned int flags = 0;
- vector<string> words;
+ std::vector<std::string> words;
boost::algorithm::split(words, strFlags, boost::algorithm::is_any_of(","));
- BOOST_FOREACH(string word, words)
+ BOOST_FOREACH(std::string word, words)
{
if (!mapFlagNames.count(word))
BOOST_ERROR("Bad test: unknown verification flag '" << word << "'");
@@ -77,13 +75,13 @@ unsigned int ParseScriptFlags(string strFlags)
return flags;
}
-string FormatScriptFlags(unsigned int flags)
+std::string FormatScriptFlags(unsigned int flags)
{
if (flags == 0) {
return "";
}
- string ret;
- std::map<string, unsigned int>::const_iterator it = mapFlagNames.begin();
+ std::string ret;
+ std::map<std::string, unsigned int>::const_iterator it = mapFlagNames.begin();
while (it != mapFlagNames.end()) {
if (flags & it->second) {
ret += it->first + ",";
@@ -109,7 +107,7 @@ BOOST_AUTO_TEST_CASE(tx_valid)
ScriptError err;
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
- string strTest = test.write();
+ std::string strTest = test.write();
if (test[0].isArray())
{
if (test.size() != 3 || !test[1].isStr() || !test[2].isStr())
@@ -118,8 +116,8 @@ BOOST_AUTO_TEST_CASE(tx_valid)
continue;
}
- map<COutPoint, CScript> mapprevOutScriptPubKeys;
- map<COutPoint, int64_t> mapprevOutValues;
+ std::map<COutPoint, CScript> mapprevOutScriptPubKeys;
+ std::map<COutPoint, int64_t> mapprevOutValues;
UniValue inputs = test[0].get_array();
bool fValid = true;
for (unsigned int inpIdx = 0; inpIdx < inputs.size(); inpIdx++) {
@@ -148,7 +146,7 @@ BOOST_AUTO_TEST_CASE(tx_valid)
continue;
}
- string transaction = test[1].get_str();
+ std::string transaction = test[1].get_str();
CDataStream stream(ParseHex(transaction), SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx(deserialize, stream);
@@ -194,7 +192,7 @@ BOOST_AUTO_TEST_CASE(tx_invalid)
ScriptError err;
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
- string strTest = test.write();
+ std::string strTest = test.write();
if (test[0].isArray())
{
if (test.size() != 3 || !test[1].isStr() || !test[2].isStr())
@@ -203,8 +201,8 @@ BOOST_AUTO_TEST_CASE(tx_invalid)
continue;
}
- map<COutPoint, CScript> mapprevOutScriptPubKeys;
- map<COutPoint, int64_t> mapprevOutValues;
+ std::map<COutPoint, CScript> mapprevOutScriptPubKeys;
+ std::map<COutPoint, int64_t> mapprevOutValues;
UniValue inputs = test[0].get_array();
bool fValid = true;
for (unsigned int inpIdx = 0; inpIdx < inputs.size(); inpIdx++) {
@@ -233,7 +231,7 @@ BOOST_AUTO_TEST_CASE(tx_invalid)
continue;
}
- string transaction = test[1].get_str();
+ std::string transaction = test[1].get_str();
CDataStream stream(ParseHex(transaction), SER_NETWORK, PROTOCOL_VERSION );
CTransaction tx(deserialize, stream);
@@ -268,7 +266,7 @@ BOOST_AUTO_TEST_CASE(basic_transaction_tests)
{
// Random real transaction (e2769b09e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436)
unsigned char ch[] = {0x01, 0x00, 0x00, 0x00, 0x01, 0x6b, 0xff, 0x7f, 0xcd, 0x4f, 0x85, 0x65, 0xef, 0x40, 0x6d, 0xd5, 0xd6, 0x3d, 0x4f, 0xf9, 0x4f, 0x31, 0x8f, 0xe8, 0x20, 0x27, 0xfd, 0x4d, 0xc4, 0x51, 0xb0, 0x44, 0x74, 0x01, 0x9f, 0x74, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x8c, 0x49, 0x30, 0x46, 0x02, 0x21, 0x00, 0xda, 0x0d, 0xc6, 0xae, 0xce, 0xfe, 0x1e, 0x06, 0xef, 0xdf, 0x05, 0x77, 0x37, 0x57, 0xde, 0xb1, 0x68, 0x82, 0x09, 0x30, 0xe3, 0xb0, 0xd0, 0x3f, 0x46, 0xf5, 0xfc, 0xf1, 0x50, 0xbf, 0x99, 0x0c, 0x02, 0x21, 0x00, 0xd2, 0x5b, 0x5c, 0x87, 0x04, 0x00, 0x76, 0xe4, 0xf2, 0x53, 0xf8, 0x26, 0x2e, 0x76, 0x3e, 0x2d, 0xd5, 0x1e, 0x7f, 0xf0, 0xbe, 0x15, 0x77, 0x27, 0xc4, 0xbc, 0x42, 0x80, 0x7f, 0x17, 0xbd, 0x39, 0x01, 0x41, 0x04, 0xe6, 0xc2, 0x6e, 0xf6, 0x7d, 0xc6, 0x10, 0xd2, 0xcd, 0x19, 0x24, 0x84, 0x78, 0x9a, 0x6c, 0xf9, 0xae, 0xa9, 0x93, 0x0b, 0x94, 0x4b, 0x7e, 0x2d, 0xb5, 0x34, 0x2b, 0x9d, 0x9e, 0x5b, 0x9f, 0xf7, 0x9a, 0xff, 0x9a, 0x2e, 0xe1, 0x97, 0x8d, 0xd7, 0xfd, 0x01, 0xdf, 0xc5, 0x22, 0xee, 0x02, 0x28, 0x3d, 0x3b, 0x06, 0xa9, 0xd0, 0x3a, 0xcf, 0x80, 0x96, 0x96, 0x8d, 0x7d, 0xbb, 0x0f, 0x91, 0x78, 0xff, 0xff, 0xff, 0xff, 0x02, 0x8b, 0xa7, 0x94, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xba, 0xde, 0xec, 0xfd, 0xef, 0x05, 0x07, 0x24, 0x7f, 0xc8, 0xf7, 0x42, 0x41, 0xd7, 0x3b, 0xc0, 0x39, 0x97, 0x2d, 0x7b, 0x88, 0xac, 0x40, 0x94, 0xa8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xc1, 0x09, 0x32, 0x48, 0x3f, 0xec, 0x93, 0xed, 0x51, 0xf5, 0xfe, 0x95, 0xe7, 0x25, 0x59, 0xf2, 0xcc, 0x70, 0x43, 0xf9, 0x88, 0xac, 0x00, 0x00, 0x00, 0x00, 0x00};
- vector<unsigned char> vch(ch, ch + sizeof(ch) -1);
+ std::vector<unsigned char> vch(ch, ch + sizeof(ch) -1);
CDataStream stream(vch, SER_DISK, CLIENT_VERSION);
CMutableTransaction tx;
stream >> tx;
@@ -390,7 +388,7 @@ void CheckWithFlag(const CTransactionRef& output, const CMutableTransaction& inp
assert(ret == success);
}
-static CScript PushAll(const vector<valtype>& values)
+static CScript PushAll(const std::vector<valtype>& values)
{
CScript result;
BOOST_FOREACH(const valtype& v, values) {
@@ -407,7 +405,7 @@ static CScript PushAll(const vector<valtype>& values)
void ReplaceRedeemScript(CScript& script, const CScript& redeemScript)
{
- vector<valtype> stack;
+ std::vector<valtype> stack;
EvalScript(stack, script, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SIGVERSION_BASE);
assert(stack.size() > 0);
stack.back() = std::vector<unsigned char>(redeemScript.begin(), redeemScript.end());
@@ -425,7 +423,7 @@ BOOST_AUTO_TEST_CASE(test_big_witness_transaction) {
CKeyID hash = key.GetPubKey().GetID();
CScript scriptPubKey = CScript() << OP_0 << std::vector<unsigned char>(hash.begin(), hash.end());
- vector<int> sigHashes;
+ std::vector<int> sigHashes;
sigHashes.push_back(SIGHASH_NONE | SIGHASH_ANYONECANPAY);
sigHashes.push_back(SIGHASH_SINGLE | SIGHASH_ANYONECANPAY);
sigHashes.push_back(SIGHASH_ALL | SIGHASH_ANYONECANPAY);
@@ -688,7 +686,7 @@ BOOST_AUTO_TEST_CASE(test_IsStandard)
key.MakeNewKey(true);
t.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID());
- string reason;
+ std::string reason;
BOOST_CHECK(IsStandardTx(t, reason));
// Check dust with default relay fee:
diff --git a/src/test/univalue_tests.cpp b/src/test/univalue_tests.cpp
index 05876aae04..dffe8e55a8 100644
--- a/src/test/univalue_tests.cpp
+++ b/src/test/univalue_tests.cpp
@@ -12,8 +12,6 @@
#include <boost/test/unit_test.hpp>
-using namespace std;
-
BOOST_FIXTURE_TEST_SUITE(univalue_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(univalue_constructor)
@@ -53,7 +51,7 @@ BOOST_AUTO_TEST_CASE(univalue_constructor)
BOOST_CHECK(v7.isNum());
BOOST_CHECK_EQUAL(v7.getValStr(), "-7.21");
- string vs("yawn");
+ std::string vs("yawn");
UniValue v8(vs);
BOOST_CHECK(v8.isStr());
BOOST_CHECK_EQUAL(v8.getValStr(), "yawn");
@@ -69,41 +67,41 @@ BOOST_AUTO_TEST_CASE(univalue_typecheck)
UniValue v1;
BOOST_CHECK(v1.setNumStr("1"));
BOOST_CHECK(v1.isNum());
- BOOST_CHECK_THROW(v1.get_bool(), runtime_error);
+ BOOST_CHECK_THROW(v1.get_bool(), std::runtime_error);
UniValue v2;
BOOST_CHECK(v2.setBool(true));
BOOST_CHECK_EQUAL(v2.get_bool(), true);
- BOOST_CHECK_THROW(v2.get_int(), runtime_error);
+ BOOST_CHECK_THROW(v2.get_int(), std::runtime_error);
UniValue v3;
BOOST_CHECK(v3.setNumStr("32482348723847471234"));
- BOOST_CHECK_THROW(v3.get_int64(), runtime_error);
+ BOOST_CHECK_THROW(v3.get_int64(), std::runtime_error);
BOOST_CHECK(v3.setNumStr("1000"));
BOOST_CHECK_EQUAL(v3.get_int64(), 1000);
UniValue v4;
BOOST_CHECK(v4.setNumStr("2147483648"));
BOOST_CHECK_EQUAL(v4.get_int64(), 2147483648);
- BOOST_CHECK_THROW(v4.get_int(), runtime_error);
+ BOOST_CHECK_THROW(v4.get_int(), std::runtime_error);
BOOST_CHECK(v4.setNumStr("1000"));
BOOST_CHECK_EQUAL(v4.get_int(), 1000);
- BOOST_CHECK_THROW(v4.get_str(), runtime_error);
+ BOOST_CHECK_THROW(v4.get_str(), std::runtime_error);
BOOST_CHECK_EQUAL(v4.get_real(), 1000);
- BOOST_CHECK_THROW(v4.get_array(), runtime_error);
- BOOST_CHECK_THROW(v4.getKeys(), runtime_error);
- BOOST_CHECK_THROW(v4.getValues(), runtime_error);
- BOOST_CHECK_THROW(v4.get_obj(), runtime_error);
+ BOOST_CHECK_THROW(v4.get_array(), std::runtime_error);
+ BOOST_CHECK_THROW(v4.getKeys(), std::runtime_error);
+ BOOST_CHECK_THROW(v4.getValues(), std::runtime_error);
+ BOOST_CHECK_THROW(v4.get_obj(), std::runtime_error);
UniValue v5;
BOOST_CHECK(v5.read("[true, 10]"));
BOOST_CHECK_NO_THROW(v5.get_array());
std::vector<UniValue> vals = v5.getValues();
- BOOST_CHECK_THROW(vals[0].get_int(), runtime_error);
+ BOOST_CHECK_THROW(vals[0].get_int(), std::runtime_error);
BOOST_CHECK_EQUAL(vals[0].get_bool(), true);
BOOST_CHECK_EQUAL(vals[1].get_int(), 10);
- BOOST_CHECK_THROW(vals[1].get_bool(), runtime_error);
+ BOOST_CHECK_THROW(vals[1].get_bool(), std::runtime_error);
}
BOOST_AUTO_TEST_CASE(univalue_set)
@@ -172,13 +170,13 @@ BOOST_AUTO_TEST_CASE(univalue_array)
UniValue v((int64_t)1023LL);
BOOST_CHECK(arr.push_back(v));
- string vStr("zippy");
+ std::string vStr("zippy");
BOOST_CHECK(arr.push_back(vStr));
const char *s = "pippy";
BOOST_CHECK(arr.push_back(s));
- vector<UniValue> vec;
+ std::vector<UniValue> vec;
v.setStr("boing");
vec.push_back(v);
@@ -206,7 +204,7 @@ BOOST_AUTO_TEST_CASE(univalue_array)
BOOST_AUTO_TEST_CASE(univalue_object)
{
UniValue obj(UniValue::VOBJ);
- string strKey, strVal;
+ std::string strKey, strVal;
UniValue v;
strKey = "age";
@@ -266,7 +264,7 @@ BOOST_AUTO_TEST_CASE(univalue_object)
BOOST_CHECK(!obj.exists("nyuknyuknyuk"));
- map<string, UniValue::VType> objTypes;
+ std::map<std::string, UniValue::VType> objTypes;
objTypes["age"] = UniValue::VNUM;
objTypes["first"] = UniValue::VSTR;
objTypes["last"] = UniValue::VSTR;
@@ -294,7 +292,7 @@ BOOST_AUTO_TEST_CASE(univalue_readwrite)
UniValue v;
BOOST_CHECK(v.read(json1));
- string strJson1(json1);
+ std::string strJson1(json1);
BOOST_CHECK(v.read(strJson1));
BOOST_CHECK(v.isArray());
@@ -333,4 +331,3 @@ BOOST_AUTO_TEST_CASE(univalue_readwrite)
}
BOOST_AUTO_TEST_SUITE_END()
-
diff --git a/src/test/util_tests.cpp b/src/test/util_tests.cpp
index fc42748d34..641655621c 100644
--- a/src/test/util_tests.cpp
+++ b/src/test/util_tests.cpp
@@ -17,9 +17,7 @@
#include <boost/test/unit_test.hpp>
-using namespace std;
-
-extern map<string, string> mapArgs;
+extern std::map<std::string, std::string> mapArgs;
BOOST_FIXTURE_TEST_SUITE(util_tests, BasicTestingSetup)
diff --git a/src/txmempool.h b/src/txmempool.h
index b4f52e6473..6a00b540a5 100644
--- a/src/txmempool.h
+++ b/src/txmempool.h
@@ -420,7 +420,7 @@ private:
unsigned int nTransactionsUpdated;
CBlockPolicyEstimator* minerPolicyEstimator;
- uint64_t totalTxSize; //!< sum of all mempool tx' byte sizes
+ uint64_t totalTxSize; //!< sum of all mempool tx's virtual sizes. Differs from serialized tx size since witness data is discounted. Defined in BIP 141.
uint64_t cachedInnerUsage; //!< sum of dynamic memory usage of all the map elements (NOT the maps themselves)
CFeeRate minReasonableRelayFee;
diff --git a/src/util.h b/src/util.h
index 97d2723bc4..e27ce121c8 100644
--- a/src/util.h
+++ b/src/util.h
@@ -73,14 +73,15 @@ bool LogAcceptCategory(const char* category);
/** Send a string to the log output */
int LogPrintStr(const std::string &str);
-#define LogPrintf(...) LogPrint(NULL, __VA_ARGS__)
-
-template<typename... Args>
-static inline int LogPrint(const char* category, const char* fmt, const Args&... args)
-{
- if(!LogAcceptCategory(category)) return 0; \
- return LogPrintStr(tfm::format(fmt, args...));
-}
+#define LogPrint(category, ...) do { \
+ if (LogAcceptCategory((category))) { \
+ LogPrintStr(tfm::format(__VA_ARGS__)); \
+ } \
+} while(0)
+
+#define LogPrintf(...) do { \
+ LogPrintStr(tfm::format(__VA_ARGS__)); \
+} while(0)
template<typename... Args>
bool error(const char* fmt, const Args&... args)
diff --git a/src/validation.cpp b/src/validation.cpp
index 264fdd83d6..648fed8bc6 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -1517,7 +1517,7 @@ bool AbortNode(CValidationState& state, const std::string& strMessage, const std
* @param out The out point that corresponds to the tx input.
* @return True on success.
*/
-static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
+bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
{
bool fClean = true;
@@ -1935,6 +1935,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin
* or always and in all cases if we're in prune mode and are deleting files.
*/
bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
+ int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
const CChainParams& chainparams = Params();
LOCK2(cs_main, cs_LastBlockFile);
static int64_t nLastWrite = 0;
@@ -1965,11 +1966,13 @@ bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
if (nLastSetChain == 0) {
nLastSetChain = nNow;
}
- size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
- // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
- bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
+ int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
+ int64_t cacheSize = pcoinsTip->DynamicMemoryUsage();
+ int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
+ // The cache is large and we're within 10% and 100 MiB of the limit, but we have time now (not in the middle of a block processing).
+ bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - 100 * 1024 * 1024);
// The cache is over the limit, we have to write now.
- bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
+ bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
// It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
// It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
diff --git a/src/validation.h b/src/validation.h
index b41fa8aad8..631602a701 100644
--- a/src/validation.h
+++ b/src/validation.h
@@ -73,7 +73,7 @@ static const unsigned int DEFAULT_DESCENDANT_LIMIT = 25;
/** Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants */
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT = 101;
/** Default for -mempoolexpiry, expiration time for mempool transactions in hours */
-static const unsigned int DEFAULT_MEMPOOL_EXPIRY = 72;
+static const unsigned int DEFAULT_MEMPOOL_EXPIRY = 336;
/** The maximum size of a blk?????.dat file (since 0.8) */
static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
/** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp
index 11d69ac194..936140cf44 100644
--- a/src/wallet/rpcwallet.cpp
+++ b/src/wallet/rpcwallet.cpp
@@ -757,7 +757,7 @@ UniValue movecmd(const JSONRPCRequest& request)
"1. \"fromaccount\" (string, required) The name of the account to move funds from. May be the default account using \"\".\n"
"2. \"toaccount\" (string, required) The name of the account to move funds to. May be the default account using \"\".\n"
"3. amount (numeric) Quantity of " + CURRENCY_UNIT + " to move between accounts.\n"
- "4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
+ "4. (dummy) (numeric, optional) Ignored. Remains for backward compatibility.\n"
"5. \"comment\" (string, optional) An optional comment, stored in the wallet only.\n"
"\nResult:\n"
"true|false (boolean) true if successful.\n"
diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp
index 0b13c2ba74..ff7a03bc55 100644
--- a/src/wallet/wallet.cpp
+++ b/src/wallet/wallet.cpp
@@ -2245,7 +2245,7 @@ bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wt
CAmount nValue = 0;
int nChangePosRequest = nChangePosInOut;
unsigned int nSubtractFeeFromAmount = 0;
- BOOST_FOREACH (const CRecipient& recipient, vecSend)
+ for (const auto& recipient : vecSend)
{
if (nValue < 0 || recipient.nAmount < 0)
{
@@ -2300,6 +2300,7 @@ bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wt
assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
{
+ set<pair<const CWalletTx*,unsigned int> > setCoins;
LOCK2(cs_main, cs_wallet);
{
std::vector<COutput> vAvailableCoins;
@@ -2320,7 +2321,7 @@ bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wt
nValueToSelect += nFeeRet;
double dPriority = 0;
// vouts to the payees
- BOOST_FOREACH (const CRecipient& recipient, vecSend)
+ for (const auto& recipient : vecSend)
{
CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
@@ -2352,14 +2353,14 @@ bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wt
}
// Choose coins to use
- set<pair<const CWalletTx*,unsigned int> > setCoins;
CAmount nValueIn = 0;
+ setCoins.clear();
if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, coinControl))
{
strFailReason = _("Insufficient funds");
return false;
}
- BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
+ for (const auto& pcoin : setCoins)
{
CAmount nCredit = pcoin.first->tx->vout[pcoin.second].nValue;
//The coin age after the next block (depth+1) is used instead of the current,
@@ -2470,24 +2471,18 @@ bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wt
// to avoid conflicting with other possible uses of nSequence,
// and in the spirit of "smallest posible change from prior
// behavior."
- BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
+ for (const auto& coin : setCoins)
txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
std::numeric_limits<unsigned int>::max() - (fWalletRbf ? 2 : 1)));
- // Sign
+ // Fill in dummy signatures for fee calculation.
int nIn = 0;
- CTransaction txNewConst(txNew);
- BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
+ for (const auto& coin : setCoins)
{
- bool signSuccess;
const CScript& scriptPubKey = coin.first->tx->vout[coin.second].scriptPubKey;
SignatureData sigdata;
- if (sign)
- signSuccess = ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.first->tx->vout[coin.second].nValue, SIGHASH_ALL), scriptPubKey, sigdata);
- else
- signSuccess = ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata);
- if (!signSuccess)
+ if (!ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata))
{
strFailReason = _("Signing transaction failed");
return false;
@@ -2500,26 +2495,15 @@ bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wt
unsigned int nBytes = GetVirtualTransactionSize(txNew);
- // Remove scriptSigs if we used dummy signatures for fee calculation
- if (!sign) {
- BOOST_FOREACH (CTxIn& vin, txNew.vin) {
- vin.scriptSig = CScript();
- vin.scriptWitness.SetNull();
- }
- }
-
- // Embed the constructed transaction data in wtxNew.
- wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
+ CTransaction txNewConst(txNew);
+ dPriority = txNewConst.ComputePriority(dPriority, nBytes);
- // Limit size
- if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
- {
- strFailReason = _("Transaction too large");
- return false;
+ // Remove scriptSigs to eliminate the fee calculation dummy signatures
+ for (auto& vin : txNew.vin) {
+ vin.scriptSig = CScript();
+ vin.scriptWitness.SetNull();
}
- dPriority = wtxNew.tx->ComputePriority(dPriority, nBytes);
-
// Allow to override the default confirmation target over the CoinControl instance
int currentConfirmationTarget = nTxConfirmTarget;
if (coinControl && coinControl->nConfirmTarget > 0)
@@ -2558,6 +2542,37 @@ bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wt
continue;
}
}
+
+ if (sign)
+ {
+ CTransaction txNewConst(txNew);
+ int nIn = 0;
+ for (const auto& coin : setCoins)
+ {
+ const CScript& scriptPubKey = coin.first->tx->vout[coin.second].scriptPubKey;
+ SignatureData sigdata;
+
+ if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.first->tx->vout[coin.second].nValue, SIGHASH_ALL), scriptPubKey, sigdata))
+ {
+ strFailReason = _("Signing transaction failed");
+ return false;
+ } else {
+ UpdateTransaction(txNew, nIn, sigdata);
+ }
+
+ nIn++;
+ }
+ }
+
+ // Embed the constructed transaction data in wtxNew.
+ wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
+
+ // Limit size
+ if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
+ {
+ strFailReason = _("Transaction too large");
+ return false;
+ }
}
if (GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {