aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.travis.yml2
-rw-r--r--build-aux/m4/bitcoin_qt.m444
-rw-r--r--configure.ac19
-rw-r--r--doc/build-unix.md12
-rw-r--r--doc/gitian-building.md8
-rw-r--r--doc/reducetraffic.md35
-rw-r--r--doc/release-notes.md2
-rwxr-xr-xqa/pull-tester/rpc-tests.py182
-rwxr-xr-xqa/rpc-tests/getblocktemplate_longpoll.py2
-rwxr-xr-xqa/rpc-tests/rpcbind_test.py2
-rw-r--r--qa/rpc-tests/test_framework/authproxy.py10
-rw-r--r--qa/rpc-tests/test_framework/coverage.py101
-rwxr-xr-xqa/rpc-tests/test_framework/test_framework.py28
-rw-r--r--qa/rpc-tests/test_framework/util.py62
-rw-r--r--src/Makefile.am41
-rw-r--r--src/Makefile.bench.include4
-rw-r--r--src/Makefile.qt.include6
-rw-r--r--src/Makefile.qttest.include3
-rw-r--r--src/Makefile.test.include3
-rw-r--r--src/chainparams.cpp6
-rw-r--r--src/consensus/params.h3
-rw-r--r--src/init.cpp3
-rw-r--r--src/main.cpp55
-rw-r--r--src/main.h1
-rw-r--r--src/script/sigcache.cpp91
-rw-r--r--src/script/sigcache.h4
26 files changed, 583 insertions, 146 deletions
diff --git a/.travis.yml b/.travis.yml
index 8e9684826f..d2fbfee6f2 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -69,6 +69,6 @@ script:
- make $MAKEJOBS $GOAL || ( echo "Build failure. Verbose build follows." && make $GOAL V=1 ; false )
- export LD_LIBRARY_PATH=$TRAVIS_BUILD_DIR/depends/$HOST/lib
- if [ "$RUN_TESTS" = "true" ]; then make check; fi
- - if [ "$RUN_TESTS" = "true" ]; then qa/pull-tester/rpc-tests.py; fi
+ - if [ "$RUN_TESTS" = "true" ]; then qa/pull-tester/rpc-tests.py --coverage; fi
after_script:
- if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then (echo "Upload goes here. Something like: scp -r $BASE_OUTDIR server" || echo "upload failed"); fi
diff --git a/build-aux/m4/bitcoin_qt.m4 b/build-aux/m4/bitcoin_qt.m4
index 4ea2e734e8..2480267dc1 100644
--- a/build-aux/m4/bitcoin_qt.m4
+++ b/build-aux/m4/bitcoin_qt.m4
@@ -106,7 +106,9 @@ AC_DEFUN([BITCOIN_QT_CONFIGURE],[
dnl results to QT_LIBS.
BITCOIN_QT_CHECK([
TEMP_CPPFLAGS=$CPPFLAGS
+ TEMP_CXXFLAGS=$CXXFLAGS
CPPFLAGS="$QT_INCLUDES $CPPFLAGS"
+ CXXFLAGS="$PIC_FLAGS $CXXFLAGS"
if test x$bitcoin_qt_got_major_vers = x5; then
_BITCOIN_QT_IS_STATIC
if test x$bitcoin_cv_static_qt = xyes; then
@@ -149,6 +151,7 @@ AC_DEFUN([BITCOIN_QT_CONFIGURE],[
fi
fi
CPPFLAGS=$TEMP_CPPFLAGS
+ CXXFLAGS=$TEMP_CXXFLAGS
])
if test x$use_pkgconfig$qt_bin_path = xyes; then
@@ -157,6 +160,43 @@ AC_DEFUN([BITCOIN_QT_CONFIGURE],[
fi
fi
+ if test x$use_hardening != xno; then
+ BITCOIN_QT_CHECK([
+ AC_MSG_CHECKING(whether -fPIE can be used with this Qt config)
+ TEMP_CPPFLAGS=$CPPFLAGS
+ TEMP_CXXFLAGS=$CXXFLAGS
+ CPPFLAGS="$QT_INCLUDES $CPPFLAGS"
+ CXXFLAGS="$PIE_FLAGS $CXXFLAGS"
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <QtCore/qconfig.h>]],
+ [[
+ #if defined(QT_REDUCE_RELOCATIONS)
+ choke;
+ #endif
+ ]])],
+ [ AC_MSG_RESULT(yes); QT_PIE_FLAGS=$PIE_FLAGS ],
+ [ AC_MSG_RESULT(no); QT_PIE_FLAGS=$PIC_FLAGS]
+ )
+ CPPFLAGS=$TEMP_CPPFLAGS
+ CXXFLAGS=$TEMP_CXXFLAGS
+ ])
+ else
+ BITCOIN_QT_CHECK([
+ AC_MSG_CHECKING(whether -fPIC is needed with this Qt config)
+ TEMP_CPPFLAGS=$CPPFLAGS
+ CPPFLAGS="$QT_INCLUDES $CPPFLAGS"
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <QtCore/qconfig.h>]],
+ [[
+ #if defined(QT_REDUCE_RELOCATIONS)
+ choke;
+ #endif
+ ]])],
+ [ AC_MSG_RESULT(no)],
+ [ AC_MSG_RESULT(yes); QT_PIE_FLAGS=$PIC_FLAGS]
+ )
+ CPPFLAGS=$TEMP_CPPFLAGS
+ ])
+ fi
+
BITCOIN_QT_PATH_PROGS([MOC], [moc-qt${bitcoin_qt_got_major_vers} moc${bitcoin_qt_got_major_vers} moc], $qt_bin_path)
BITCOIN_QT_PATH_PROGS([UIC], [uic-qt${bitcoin_qt_got_major_vers} uic${bitcoin_qt_got_major_vers} uic], $qt_bin_path)
BITCOIN_QT_PATH_PROGS([RCC], [rcc-qt${bitcoin_qt_got_major_vers} rcc${bitcoin_qt_got_major_vers} rcc], $qt_bin_path)
@@ -202,6 +242,7 @@ AC_DEFUN([BITCOIN_QT_CONFIGURE],[
])
AC_MSG_RESULT([$bitcoin_enable_qt (Qt${bitcoin_qt_got_major_vers})])
+ AC_SUBST(QT_PIE_FLAGS)
AC_SUBST(QT_INCLUDES)
AC_SUBST(QT_LIBS)
AC_SUBST(QT_LDFLAGS)
@@ -373,6 +414,8 @@ dnl Outputs: bitcoin_qt_got_major_vers is set to "4" or "5".
dnl Outputs: have_qt_test and have_qt_dbus are set (if applicable) to yes|no.
AC_DEFUN([_BITCOIN_QT_FIND_LIBS_WITHOUT_PKGCONFIG],[
TEMP_CPPFLAGS="$CPPFLAGS"
+ TEMP_CXXFLAGS="$CXXFLAGS"
+ CXXFLAGS="$PIC_FLAGS $CXXFLAGS"
TEMP_LIBS="$LIBS"
BITCOIN_QT_CHECK([
if test x$qt_include_path != x; then
@@ -442,6 +485,7 @@ AC_DEFUN([_BITCOIN_QT_FIND_LIBS_WITHOUT_PKGCONFIG],[
fi
])
CPPFLAGS="$TEMP_CPPFLAGS"
+ CXXFLAGS="$TEMP_CXXFLAGS"
LIBS="$TEMP_LIBS"
])
diff --git a/configure.ac b/configure.ac
index d94dd0c3dc..e8aea902ae 100644
--- a/configure.ac
+++ b/configure.ac
@@ -326,6 +326,7 @@ case $host in
AX_CHECK_LINK_FLAG([[-Wl,-headerpad_max_install_names]], [LDFLAGS="$LDFLAGS -Wl,-headerpad_max_install_names"])
CPPFLAGS="$CPPFLAGS -DMAC_OSX"
+ OBJCXXFLAGS="$CXXFLAGS"
;;
*linux*)
TARGET_OS=linux
@@ -424,6 +425,11 @@ if test x$use_glibc_compat != xno; then
fi
+if test x$TARGET_OS != xwindows; then
+ # All windows code is PIC, forcing it on just adds useless compile warnings
+ AX_CHECK_COMPILE_FLAG([-fPIC],[PIC_FLAGS="-fPIC"])
+fi
+
if test x$use_hardening != xno; then
AX_CHECK_COMPILE_FLAG([-Wstack-protector],[HARDENED_CXXFLAGS="$HARDENED_CXXFLAGS -Wstack-protector"])
AX_CHECK_COMPILE_FLAG([-fstack-protector-all],[HARDENED_CXXFLAGS="$HARDENED_CXXFLAGS -fstack-protector-all"])
@@ -441,8 +447,7 @@ if test x$use_hardening != xno; then
AX_CHECK_LINK_FLAG([[-Wl,-z,now]], [HARDENED_LDFLAGS="$HARDENED_LDFLAGS -Wl,-z,now"])
if test x$TARGET_OS != xwindows; then
- # All windows code is PIC, forcing it on just adds useless compile warnings
- AX_CHECK_COMPILE_FLAG([-fPIE],[HARDENED_CXXFLAGS="$HARDENED_CXXFLAGS -fPIE"])
+ AX_CHECK_COMPILE_FLAG([-fPIE],[PIE_FLAGS="-fPIE"])
AX_CHECK_LINK_FLAG([[-pie]], [HARDENED_LDFLAGS="$HARDENED_LDFLAGS -pie"])
fi
@@ -451,11 +456,6 @@ if test x$use_hardening != xno; then
AC_CHECK_LIB([ssp], [main],, AC_MSG_ERROR(lib missing))
;;
esac
-
- CXXFLAGS="$CXXFLAGS $HARDENED_CXXFLAGS"
- CPPFLAGS="$CPPFLAGS $HARDENED_CPPFLAGS"
- LDFLAGS="$LDFLAGS $HARDENED_LDFLAGS"
- OBJCXXFLAGS="$CXXFLAGS"
fi
dnl this flag screws up non-darwin gcc even when the check fails. special-case it.
@@ -915,6 +915,11 @@ AC_SUBST(CLIENT_VERSION_IS_RELEASE, _CLIENT_VERSION_IS_RELEASE)
AC_SUBST(COPYRIGHT_YEAR, _COPYRIGHT_YEAR)
AC_SUBST(RELDFLAGS)
+AC_SUBST(HARDENED_CXXFLAGS)
+AC_SUBST(HARDENED_CPPFLAGS)
+AC_SUBST(HARDENED_LDFLAGS)
+AC_SUBST(PIC_FLAGS)
+AC_SUBST(PIE_FLAGS)
AC_SUBST(LIBTOOL_APP_LDFLAGS)
AC_SUBST(USE_UPNP)
AC_SUBST(USE_QRCODE)
diff --git a/doc/build-unix.md b/doc/build-unix.md
index 57853a9c9d..e1f2ce54d3 100644
--- a/doc/build-unix.md
+++ b/doc/build-unix.md
@@ -61,15 +61,15 @@ Dependency Build Instructions: Ubuntu & Debian
----------------------------------------------
Build requirements:
- sudo apt-get install build-essential libtool autotools-dev autoconf pkg-config libssl-dev libevent-dev
+ sudo apt-get install build-essential libtool autotools-dev autoconf pkg-config libssl-dev libevent-dev bsdmainutils
-On Ubuntu 15.10+ there are generic names for the individual boost development
-packages, so the following can be used to only install necessary parts of
-boost:
+On at least Ubuntu 14.04+ and Debian 7+ there are generic names for the
+individual boost development packages, so the following can be used to only
+install necessary parts of boost:
- apt-get install libboost-system-dev libboost-filesystem-dev libboost-chrono-dev libboost-program-options-dev libboost-test-dev libboost-thread-dev libboost-base-dev
+ sudo apt-get install libboost-system-dev libboost-filesystem-dev libboost-chrono-dev libboost-program-options-dev libboost-test-dev libboost-thread-dev
-For Ubuntu before 15.10, or Debian 7 and later libboost-all-dev has to be installed:
+If that doesn't work, you can install all boost development packages with:
sudo apt-get install libboost-all-dev
diff --git a/doc/gitian-building.md b/doc/gitian-building.md
index 00fdce82e8..43de87d4ba 100644
--- a/doc/gitian-building.md
+++ b/doc/gitian-building.md
@@ -289,11 +289,11 @@ The rest of the steps in this guide will be performed as that user.
There is no `python-vm-builder` package in Debian, so we need to install it from source ourselves,
```bash
-wget http://archive.ubuntu.com/ubuntu/pool/universe/v/vm-builder/vm-builder_0.12.4+bzr489.orig.tar.gz
-echo "ec12e0070a007989561bfee5862c89a32c301992dd2771c4d5078ef1b3014f03 vm-builder_0.12.4+bzr489.orig.tar.gz" | sha256sum -c
+wget http://archive.ubuntu.com/ubuntu/pool/universe/v/vm-builder/vm-builder_0.12.4+bzr494.orig.tar.gz
+echo "76cbf8c52c391160b2641e7120dbade5afded713afaa6032f733a261f13e6a8e vm-builder_0.12.4+bzr494.orig.tar.gz" | sha256sum -c
# (verification -- must return OK)
-tar -zxvf vm-builder_0.12.4+bzr489.orig.tar.gz
-cd vm-builder-0.12.4+bzr489
+tar -zxvf vm-builder_0.12.4+bzr494.orig.tar.gz
+cd vm-builder-0.12.4+bzr494
sudo python setup.py install
cd ..
```
diff --git a/doc/reducetraffic.md b/doc/reducetraffic.md
new file mode 100644
index 0000000000..a79571913a
--- /dev/null
+++ b/doc/reducetraffic.md
@@ -0,0 +1,35 @@
+Reduce Traffic
+==============
+
+Some node operators need to deal with bandwith caps imposed by their ISPs.
+
+By default, bitcoin-core allows up to 125 connections to different peers, 8 of
+which are outbound. You can therefore, have at most 117 inbound connections.
+
+The default settings can result in relatively significant traffic consumption.
+
+Ways to reduce traffic:
+
+## 1. Use `-maxuploadtarget=<MiB per day>`
+
+A major component of the traffic is caused by serving historic blocks to other nodes
+during the initial blocks download phase (syncing up a new node).
+This option can be specified in MiB per day and is turned off by default.
+This is *not* a hard limit; only a threshold to minimize the outbound
+traffic. When the limit is about to be reached, the uploaded data is cut by no
+longer serving historic blocks (blocks older than one week).
+Keep in mind that new nodes require other nodes that are willing to serve
+historic blocks. **The recommended minimum is 144 blocks per day (max. 144MB
+per day)**
+
+## 2. Disable "listening" (`-listen=0`)
+
+Disabling listening will result in fewer nodes connected (remember the maximum of 8
+outbound peers). Fewer nodes will result in less traffic usage as you are relaying
+blocks and transactions to fewer nodes.
+
+## 3. Reduce maximum connections (`-maxconnections=<num>`)
+
+Reducing the maximum connected nodes to a miniumum could be desirable if traffic
+limits are tiny. Keep in mind that bitcoin's trustless model works best if you are
+connected to a handful of nodes.
diff --git a/doc/release-notes.md b/doc/release-notes.md
index 3d10a07912..31704ba47c 100644
--- a/doc/release-notes.md
+++ b/doc/release-notes.md
@@ -143,7 +143,7 @@ higher, it becomes mandatory for all blocks and blocks with versions less than
Bitcoin Core's block templates are now for version 4 blocks only, and any
mining software relying on its `getblocktemplate` must be updated in parallel
-to use either libblkmaker version FIXME or any version from 0.5.1 onward. If
+to use either libblkmaker version 0.4.3 or any version from 0.5.2 onward. If
you are solo mining, this will affect you the moment you upgrade Bitcoin Core,
which must be done prior to BIP65 achieving its 951/1001 status. If you are
mining with the stratum mining protocol: this does not affect you. If you are
diff --git a/qa/pull-tester/rpc-tests.py b/qa/pull-tester/rpc-tests.py
index c23dcbdb7c..83fc9b8f96 100755
--- a/qa/pull-tester/rpc-tests.py
+++ b/qa/pull-tester/rpc-tests.py
@@ -3,16 +3,32 @@
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#
-# Run Regression Test Suite
-#
+"""
+Run Regression Test Suite
+
+This module calls down into individual test cases via subprocess. It will
+forward all unrecognized arguments onto the individual test scripts, other
+than:
+
+ - `-extended`: run the "extended" test suite in addition to the basic one.
+ - `-win`: signal that this is running in a Windows environment, and we
+ should run the tests.
+ - `--coverage`: this generates a basic coverage report for the RPC
+ interface.
+
+For a description of arguments recognized by test scripts, see
+`qa/pull-tester/test_framework/test_framework.py:BitcoinTestFramework.main`.
+
+"""
import os
+import shutil
import sys
import subprocess
+import tempfile
import re
+
from tests_config import *
-from sets import Set
#If imported values are not defined then set to zero (or disabled)
if not vars().has_key('ENABLE_WALLET'):
@@ -24,15 +40,20 @@ if not vars().has_key('ENABLE_UTILS'):
if not vars().has_key('ENABLE_ZMQ'):
ENABLE_ZMQ=0
+ENABLE_COVERAGE=0
+
#Create a set to store arguments and create the passOn string
-opts = Set()
+opts = set()
passOn = ""
p = re.compile("^--")
-for i in range(1,len(sys.argv)):
- if (p.match(sys.argv[i]) or sys.argv[i] == "-h"):
- passOn += " " + sys.argv[i]
+
+for arg in sys.argv[1:]:
+ if arg == '--coverage':
+ ENABLE_COVERAGE = 1
+ elif (p.match(arg) or arg == "-h"):
+ passOn += " " + arg
else:
- opts.add(sys.argv[i])
+ opts.add(arg)
#Set env vars
buildDir = BUILDDIR
@@ -98,24 +119,125 @@ testScriptsExt = [
if ENABLE_ZMQ == 1:
testScripts.append('zmq_test.py')
-if(ENABLE_WALLET == 1 and ENABLE_UTILS == 1 and ENABLE_BITCOIND == 1):
- rpcTestDir = buildDir + '/qa/rpc-tests/'
- #Run Tests
- for i in range(len(testScripts)):
- if (len(opts) == 0 or (len(opts) == 1 and "-win" in opts ) or '-extended' in opts
- or testScripts[i] in opts or re.sub(".py$", "", testScripts[i]) in opts ):
- print "Running testscript " + testScripts[i] + "..."
- subprocess.check_call(rpcTestDir + testScripts[i] + " --srcdir " + buildDir + '/src ' + passOn,shell=True)
- #exit if help is called so we print just one set of instructions
- p = re.compile(" -h| --help")
- if p.match(passOn):
- sys.exit(0)
-
- #Run Extended Tests
- for i in range(len(testScriptsExt)):
- if ('-extended' in opts or testScriptsExt[i] in opts
- or re.sub(".py$", "", testScriptsExt[i]) in opts):
- print "Running 2nd level testscript " + testScriptsExt[i] + "..."
- subprocess.check_call(rpcTestDir + testScriptsExt[i] + " --srcdir " + buildDir + '/src ' + passOn,shell=True)
-else:
- print "No rpc tests to run. Wallet, utils, and bitcoind must all be enabled"
+
+def runtests():
+ coverage = None
+
+ if ENABLE_COVERAGE:
+ coverage = RPCCoverage()
+ print("Initializing coverage directory at %s" % coverage.dir)
+
+ if(ENABLE_WALLET == 1 and ENABLE_UTILS == 1 and ENABLE_BITCOIND == 1):
+ rpcTestDir = buildDir + '/qa/rpc-tests/'
+ run_extended = '-extended' in opts
+ cov_flag = coverage.flag if coverage else ''
+ flags = " --srcdir %s/src %s %s" % (buildDir, cov_flag, passOn)
+
+ #Run Tests
+ for i in range(len(testScripts)):
+ if (len(opts) == 0
+ or (len(opts) == 1 and "-win" in opts )
+ or run_extended
+ or testScripts[i] in opts
+ or re.sub(".py$", "", testScripts[i]) in opts ):
+ print("Running testscript " + testScripts[i] + "...")
+
+ subprocess.check_call(
+ rpcTestDir + testScripts[i] + flags, shell=True)
+
+ # exit if help is called so we print just one set of
+ # instructions
+ p = re.compile(" -h| --help")
+ if p.match(passOn):
+ sys.exit(0)
+
+ # Run Extended Tests
+ for i in range(len(testScriptsExt)):
+ if (run_extended or testScriptsExt[i] in opts
+ or re.sub(".py$", "", testScriptsExt[i]) in opts):
+ print(
+ "Running 2nd level testscript "
+ + testScriptsExt[i] + "...")
+
+ subprocess.check_call(
+ rpcTestDir + testScriptsExt[i] + flags, shell=True)
+
+ if coverage:
+ coverage.report_rpc_coverage()
+
+ print("Cleaning up coverage data")
+ coverage.cleanup()
+
+ else:
+ print "No rpc tests to run. Wallet, utils, and bitcoind must all be enabled"
+
+
+class RPCCoverage(object):
+ """
+ Coverage reporting utilities for pull-tester.
+
+ Coverage calculation works by having each test script subprocess write
+ coverage files into a particular directory. These files contain the RPC
+ commands invoked during testing, as well as a complete listing of RPC
+ commands per `bitcoin-cli help` (`rpc_interface.txt`).
+
+ After all tests complete, the commands run are combined and diff'd against
+ the complete list to calculate uncovered RPC commands.
+
+ See also: qa/rpc-tests/test_framework/coverage.py
+
+ """
+ def __init__(self):
+ self.dir = tempfile.mkdtemp(prefix="coverage")
+ self.flag = '--coveragedir %s' % self.dir
+
+ def report_rpc_coverage(self):
+ """
+ Print out RPC commands that were unexercised by tests.
+
+ """
+ uncovered = self._get_uncovered_rpc_commands()
+
+ if uncovered:
+ print("Uncovered RPC commands:")
+ print("".join((" - %s\n" % i) for i in sorted(uncovered)))
+ else:
+ print("All RPC commands covered.")
+
+ def cleanup(self):
+ return shutil.rmtree(self.dir)
+
+ def _get_uncovered_rpc_commands(self):
+ """
+ Return a set of currently untested RPC commands.
+
+ """
+ # This is shared from `qa/rpc-tests/test-framework/coverage.py`
+ REFERENCE_FILENAME = 'rpc_interface.txt'
+ COVERAGE_FILE_PREFIX = 'coverage.'
+
+ coverage_ref_filename = os.path.join(self.dir, REFERENCE_FILENAME)
+ coverage_filenames = set()
+ all_cmds = set()
+ covered_cmds = set()
+
+ if not os.path.isfile(coverage_ref_filename):
+ raise RuntimeError("No coverage reference found")
+
+ with open(coverage_ref_filename, 'r') as f:
+ all_cmds.update([i.strip() for i in f.readlines()])
+
+ for root, dirs, files in os.walk(self.dir):
+ for filename in files:
+ if filename.startswith(COVERAGE_FILE_PREFIX):
+ coverage_filenames.add(os.path.join(root, filename))
+
+ for filename in coverage_filenames:
+ with open(filename, 'r') as f:
+ covered_cmds.update([i.strip() for i in f.readlines()])
+
+ return all_cmds - covered_cmds
+
+
+if __name__ == '__main__':
+ runtests()
diff --git a/qa/rpc-tests/getblocktemplate_longpoll.py b/qa/rpc-tests/getblocktemplate_longpoll.py
index aab4562422..1ddff8a298 100755
--- a/qa/rpc-tests/getblocktemplate_longpoll.py
+++ b/qa/rpc-tests/getblocktemplate_longpoll.py
@@ -38,7 +38,7 @@ class LongpollThread(threading.Thread):
self.longpollid = templat['longpollid']
# create a new connection to the node, we can't use the same
# connection from two threads
- self.node = AuthServiceProxy(node.url, timeout=600)
+ self.node = get_rpc_proxy(node.url, 1, timeout=600)
def run(self):
self.node.getblocktemplate({'longpollid':self.longpollid})
diff --git a/qa/rpc-tests/rpcbind_test.py b/qa/rpc-tests/rpcbind_test.py
index 04110c2831..7a9da66787 100755
--- a/qa/rpc-tests/rpcbind_test.py
+++ b/qa/rpc-tests/rpcbind_test.py
@@ -47,7 +47,7 @@ def run_allowip_test(tmpdir, allow_ips, rpchost, rpcport):
try:
# connect to node through non-loopback interface
url = "http://rt:rt@%s:%d" % (rpchost, rpcport,)
- node = AuthServiceProxy(url)
+ node = get_rpc_proxy(url, 1)
node.getinfo()
finally:
node = None # make sure connection will be garbage collected and closed
diff --git a/qa/rpc-tests/test_framework/authproxy.py b/qa/rpc-tests/test_framework/authproxy.py
index 33014dc139..fba469a0dd 100644
--- a/qa/rpc-tests/test_framework/authproxy.py
+++ b/qa/rpc-tests/test_framework/authproxy.py
@@ -69,7 +69,7 @@ class AuthServiceProxy(object):
def __init__(self, service_url, service_name=None, timeout=HTTP_TIMEOUT, connection=None):
self.__service_url = service_url
- self.__service_name = service_name
+ self._service_name = service_name
self.__url = urlparse.urlparse(service_url)
if self.__url.port is None:
port = 80
@@ -102,8 +102,8 @@ class AuthServiceProxy(object):
if name.startswith('__') and name.endswith('__'):
# Python internal stuff
raise AttributeError
- if self.__service_name is not None:
- name = "%s.%s" % (self.__service_name, name)
+ if self._service_name is not None:
+ name = "%s.%s" % (self._service_name, name)
return AuthServiceProxy(self.__service_url, name, connection=self.__conn)
def _request(self, method, path, postdata):
@@ -129,10 +129,10 @@ class AuthServiceProxy(object):
def __call__(self, *args):
AuthServiceProxy.__id_count += 1
- log.debug("-%s-> %s %s"%(AuthServiceProxy.__id_count, self.__service_name,
+ log.debug("-%s-> %s %s"%(AuthServiceProxy.__id_count, self._service_name,
json.dumps(args, default=EncodeDecimal)))
postdata = json.dumps({'version': '1.1',
- 'method': self.__service_name,
+ 'method': self._service_name,
'params': args,
'id': AuthServiceProxy.__id_count}, default=EncodeDecimal)
response = self._request('POST', self.__url.path, postdata)
diff --git a/qa/rpc-tests/test_framework/coverage.py b/qa/rpc-tests/test_framework/coverage.py
new file mode 100644
index 0000000000..50f066a850
--- /dev/null
+++ b/qa/rpc-tests/test_framework/coverage.py
@@ -0,0 +1,101 @@
+"""
+This module contains utilities for doing coverage analysis on the RPC
+interface.
+
+It provides a way to track which RPC commands are exercised during
+testing.
+
+"""
+import os
+
+
+REFERENCE_FILENAME = 'rpc_interface.txt'
+
+
+class AuthServiceProxyWrapper(object):
+ """
+ An object that wraps AuthServiceProxy to record specific RPC calls.
+
+ """
+ def __init__(self, auth_service_proxy_instance, coverage_logfile=None):
+ """
+ Kwargs:
+ auth_service_proxy_instance (AuthServiceProxy): the instance
+ being wrapped.
+ coverage_logfile (str): if specified, write each service_name
+ out to a file when called.
+
+ """
+ self.auth_service_proxy_instance = auth_service_proxy_instance
+ self.coverage_logfile = coverage_logfile
+
+ def __getattr__(self, *args, **kwargs):
+ return_val = self.auth_service_proxy_instance.__getattr__(
+ *args, **kwargs)
+
+ return AuthServiceProxyWrapper(return_val, self.coverage_logfile)
+
+ def __call__(self, *args, **kwargs):
+ """
+ Delegates to AuthServiceProxy, then writes the particular RPC method
+ called to a file.
+
+ """
+ return_val = self.auth_service_proxy_instance.__call__(*args, **kwargs)
+ rpc_method = self.auth_service_proxy_instance._service_name
+
+ if self.coverage_logfile:
+ with open(self.coverage_logfile, 'a+') as f:
+ f.write("%s\n" % rpc_method)
+
+ return return_val
+
+ @property
+ def url(self):
+ return self.auth_service_proxy_instance.url
+
+
+def get_filename(dirname, n_node):
+ """
+ Get a filename unique to the test process ID and node.
+
+ This file will contain a list of RPC commands covered.
+ """
+ pid = str(os.getpid())
+ return os.path.join(
+ dirname, "coverage.pid%s.node%s.txt" % (pid, str(n_node)))
+
+
+def write_all_rpc_commands(dirname, node):
+ """
+ Write out a list of all RPC functions available in `bitcoin-cli` for
+ coverage comparison. This will only happen once per coverage
+ directory.
+
+ Args:
+ dirname (str): temporary test dir
+ node (AuthServiceProxy): client
+
+ Returns:
+ bool. if the RPC interface file was written.
+
+ """
+ filename = os.path.join(dirname, REFERENCE_FILENAME)
+
+ if os.path.isfile(filename):
+ return False
+
+ help_output = node.help().split('\n')
+ commands = set()
+
+ for line in help_output:
+ line = line.strip()
+
+ # Ignore blanks and headers
+ if line and not line.startswith('='):
+ commands.add("%s\n" % line.split()[0])
+
+ with open(filename, 'w') as f:
+ f.writelines(list(commands))
+
+ return True
diff --git a/qa/rpc-tests/test_framework/test_framework.py b/qa/rpc-tests/test_framework/test_framework.py
index 5671431f6e..ae2d91ab60 100755
--- a/qa/rpc-tests/test_framework/test_framework.py
+++ b/qa/rpc-tests/test_framework/test_framework.py
@@ -13,8 +13,20 @@ import shutil
import tempfile
import traceback
+from .util import (
+ initialize_chain,
+ assert_equal,
+ start_nodes,
+ connect_nodes_bi,
+ sync_blocks,
+ sync_mempools,
+ stop_nodes,
+ wait_bitcoinds,
+ enable_coverage,
+ check_json_precision,
+ initialize_chain_clean,
+)
from authproxy import AuthServiceProxy, JSONRPCException
-from util import *
class BitcoinTestFramework(object):
@@ -96,6 +108,8 @@ class BitcoinTestFramework(object):
help="Root directory for datadirs")
parser.add_option("--tracerpc", dest="trace_rpc", default=False, action="store_true",
help="Print out all RPC calls as they are made")
+ parser.add_option("--coveragedir", dest="coveragedir",
+ help="Write tested RPC commands into this directory")
self.add_options(parser)
(self.options, self.args) = parser.parse_args()
@@ -103,6 +117,9 @@ class BitcoinTestFramework(object):
import logging
logging.basicConfig(level=logging.DEBUG)
+ if self.options.coveragedir:
+ enable_coverage(self.options.coveragedir)
+
os.environ['PATH'] = self.options.srcdir+":"+os.environ['PATH']
check_json_precision()
@@ -173,7 +190,8 @@ class ComparisonTestFramework(BitcoinTestFramework):
initialize_chain_clean(self.options.tmpdir, self.num_nodes)
def setup_network(self):
- self.nodes = start_nodes(self.num_nodes, self.options.tmpdir,
- extra_args=[['-debug', '-whitelist=127.0.0.1']] * self.num_nodes,
- binary=[self.options.testbinary] +
- [self.options.refbinary]*(self.num_nodes-1))
+ self.nodes = start_nodes(
+ self.num_nodes, self.options.tmpdir,
+ extra_args=[['-debug', '-whitelist=127.0.0.1']] * self.num_nodes,
+ binary=[self.options.testbinary] +
+ [self.options.refbinary]*(self.num_nodes-1))
diff --git a/qa/rpc-tests/test_framework/util.py b/qa/rpc-tests/test_framework/util.py
index 3759cc8162..30dd5de585 100644
--- a/qa/rpc-tests/test_framework/util.py
+++ b/qa/rpc-tests/test_framework/util.py
@@ -17,8 +17,43 @@ import subprocess
import time
import re
-from authproxy import AuthServiceProxy, JSONRPCException
-from util import *
+from . import coverage
+from .authproxy import AuthServiceProxy, JSONRPCException
+
+COVERAGE_DIR = None
+
+
+def enable_coverage(dirname):
+ """Maintain a log of which RPC calls are made during testing."""
+ global COVERAGE_DIR
+ COVERAGE_DIR = dirname
+
+
+def get_rpc_proxy(url, node_number, timeout=None):
+ """
+ Args:
+ url (str): URL of the RPC server to call
+ node_number (int): the node number (or id) that this calls to
+
+ Kwargs:
+ timeout (int): HTTP timeout in seconds
+
+ Returns:
+ AuthServiceProxy. convenience object for making RPC calls.
+
+ """
+ proxy_kwargs = {}
+ if timeout is not None:
+ proxy_kwargs['timeout'] = timeout
+
+ proxy = AuthServiceProxy(url, **proxy_kwargs)
+ proxy.url = url # store URL on proxy for info
+
+ coverage_logfile = coverage.get_filename(
+ COVERAGE_DIR, node_number) if COVERAGE_DIR else None
+
+ return coverage.AuthServiceProxyWrapper(proxy, coverage_logfile)
+
def p2p_port(n):
return 11000 + n + os.getpid()%999
@@ -79,13 +114,13 @@ def initialize_chain(test_dir):
"""
if (not os.path.isdir(os.path.join("cache","node0"))
- or not os.path.isdir(os.path.join("cache","node1"))
- or not os.path.isdir(os.path.join("cache","node2"))
+ or not os.path.isdir(os.path.join("cache","node1"))
+ or not os.path.isdir(os.path.join("cache","node2"))
or not os.path.isdir(os.path.join("cache","node3"))):
#find and delete old cache directories if any exist
for i in range(4):
- if os.path.isdir(os.path.join("cache","node"+str(i))):
+ if os.path.isdir(os.path.join("cache","node"+str(i))):
shutil.rmtree(os.path.join("cache","node"+str(i)))
devnull = open(os.devnull, "w")
@@ -103,11 +138,13 @@ def initialize_chain(test_dir):
if os.getenv("PYTHON_DEBUG", ""):
print "initialize_chain: bitcoin-cli -rpcwait getblockcount completed"
devnull.close()
+
rpcs = []
+
for i in range(4):
try:
- url = "http://rt:rt@127.0.0.1:%d"%(rpc_port(i),)
- rpcs.append(AuthServiceProxy(url))
+ url = "http://rt:rt@127.0.0.1:%d" % (rpc_port(i),)
+ rpcs.append(get_rpc_proxy(url, i))
except:
sys.stderr.write("Error connecting to "+url+"\n")
sys.exit(1)
@@ -190,11 +227,12 @@ def start_node(i, dirname, extra_args=None, rpchost=None, timewait=None, binary=
print "start_node: calling bitcoin-cli -rpcwait getblockcount returned"
devnull.close()
url = "http://rt:rt@%s:%d" % (rpchost or '127.0.0.1', rpc_port(i))
- if timewait is not None:
- proxy = AuthServiceProxy(url, timeout=timewait)
- else:
- proxy = AuthServiceProxy(url)
- proxy.url = url # store URL on proxy for info
+
+ proxy = get_rpc_proxy(url, i, timeout=timewait)
+
+ if COVERAGE_DIR:
+ coverage.write_all_rpc_commands(COVERAGE_DIR, proxy)
+
return proxy
def start_nodes(num_nodes, dirname, extra_args=None, rpchost=None, binary=None):
diff --git a/src/Makefile.am b/src/Makefile.am
index c96541d22e..834c3dc891 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -1,6 +1,8 @@
DIST_SUBDIRS = secp256k1 univalue
-AM_LDFLAGS = $(PTHREAD_CFLAGS) $(LIBTOOL_LDFLAGS)
+AM_LDFLAGS = $(PTHREAD_CFLAGS) $(LIBTOOL_LDFLAGS) $(HARDENED_LDFLAGS)
+AM_CXXFLAGS = $(HARDENED_CXXFLAGS)
+AM_CPPFLAGS = $(HARDENED_CPPFLAGS)
if EMBEDDED_LEVELDB
LEVELDB_CPPFLAGS += -I$(srcdir)/leveldb/include
@@ -14,7 +16,7 @@ $(LIBLEVELDB): $(LIBMEMENV)
$(LIBLEVELDB) $(LIBMEMENV):
@echo "Building LevelDB ..." && $(MAKE) -C $(@D) $(@F) CXX="$(CXX)" \
CC="$(CC)" PLATFORM=$(TARGET_OS) AR="$(AR)" $(LEVELDB_TARGET_FLAGS) \
- OPT="$(CXXFLAGS) $(CPPFLAGS) -D__STDC_LIMIT_MACROS"
+ OPT="$(AM_CXXFLAGS) $(PIE_FLAGS) $(CXXFLAGS) $(AM_CPPFLAGS) $(CPPFLAGS) -D__STDC_LIMIT_MACROS"
endif
BITCOIN_CONFIG_INCLUDES=-I$(builddir)/config
@@ -179,7 +181,8 @@ obj/build.h: FORCE
libbitcoin_util_a-clientversion.$(OBJEXT): obj/build.h
# server: shared between bitcoind and bitcoin-qt
-libbitcoin_server_a_CPPFLAGS = $(BITCOIN_INCLUDES) $(MINIUPNPC_CPPFLAGS) $(EVENT_CFLAGS) $(EVENT_PTHREADS_CFLAGS)
+libbitcoin_server_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(MINIUPNPC_CPPFLAGS) $(EVENT_CFLAGS) $(EVENT_PTHREADS_CFLAGS)
+libbitcoin_server_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
libbitcoin_server_a_SOURCES = \
addrman.cpp \
alert.cpp \
@@ -217,6 +220,7 @@ if ENABLE_ZMQ
LIBBITCOIN_ZMQ=libbitcoin_zmq.a
libbitcoin_zmq_a_CPPFLAGS = $(BITCOIN_INCLUDES) $(ZMQ_CFLAGS)
+libbitcoin_zmq_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
libbitcoin_zmq_a_SOURCES = \
zmq/zmqabstractnotifier.cpp \
zmq/zmqnotificationinterface.cpp \
@@ -226,7 +230,8 @@ endif
# wallet: shared between bitcoind and bitcoin-qt, but only linked
# when wallet enabled
-libbitcoin_wallet_a_CPPFLAGS = $(BITCOIN_INCLUDES)
+libbitcoin_wallet_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES)
+libbitcoin_wallet_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
libbitcoin_wallet_a_SOURCES = \
wallet/crypter.cpp \
wallet/db.cpp \
@@ -238,7 +243,8 @@ libbitcoin_wallet_a_SOURCES = \
$(BITCOIN_CORE_H)
# crypto primitives library
-crypto_libbitcoin_crypto_a_CPPFLAGS = $(BITCOIN_CONFIG_INCLUDES)
+crypto_libbitcoin_crypto_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_CONFIG_INCLUDES)
+crypto_libbitcoin_crypto_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
crypto_libbitcoin_crypto_a_SOURCES = \
crypto/common.h \
crypto/hmac_sha256.cpp \
@@ -255,7 +261,8 @@ crypto_libbitcoin_crypto_a_SOURCES = \
crypto/sha512.h
# common: shared between bitcoind, and bitcoin-qt and non-server tools
-libbitcoin_common_a_CPPFLAGS = $(BITCOIN_INCLUDES)
+libbitcoin_common_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES)
+libbitcoin_common_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
libbitcoin_common_a_SOURCES = \
amount.cpp \
arith_uint256.cpp \
@@ -286,7 +293,8 @@ libbitcoin_common_a_SOURCES = \
# util: shared between all executables.
# This library *must* be included to make sure that the glibc
# backward-compatibility objects and their sanity checks are linked.
-libbitcoin_util_a_CPPFLAGS = $(BITCOIN_INCLUDES)
+libbitcoin_util_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES)
+libbitcoin_util_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
libbitcoin_util_a_SOURCES = \
support/pagelocker.cpp \
chainparamsbase.cpp \
@@ -310,7 +318,8 @@ libbitcoin_util_a_SOURCES += compat/glibc_compat.cpp
endif
# cli: shared between bitcoin-cli and bitcoin-qt
-libbitcoin_cli_a_CPPFLAGS = $(BITCOIN_INCLUDES)
+libbitcoin_cli_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES)
+libbitcoin_cli_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
libbitcoin_cli_a_SOURCES = \
rpcclient.cpp \
$(BITCOIN_CORE_H)
@@ -320,7 +329,8 @@ nodist_libbitcoin_util_a_SOURCES = $(srcdir)/obj/build.h
# bitcoind binary #
bitcoind_SOURCES = bitcoind.cpp
-bitcoind_CPPFLAGS = $(BITCOIN_INCLUDES)
+bitcoind_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES)
+bitcoind_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
bitcoind_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS)
if TARGET_WINDOWS
@@ -349,7 +359,8 @@ bitcoind_LDADD += $(BOOST_LIBS) $(BDB_LIBS) $(SSL_LIBS) $(CRYPTO_LIBS) $(MINIUPN
# bitcoin-cli binary #
bitcoin_cli_SOURCES = bitcoin-cli.cpp
-bitcoin_cli_CPPFLAGS = $(BITCOIN_INCLUDES) $(EVENT_CFLAGS)
+bitcoin_cli_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(EVENT_CFLAGS)
+bitcoin_cli_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
bitcoin_cli_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS)
if TARGET_WINDOWS
@@ -366,7 +377,8 @@ bitcoin_cli_LDADD += $(BOOST_LIBS) $(SSL_LIBS) $(CRYPTO_LIBS) $(EVENT_LIBS)
# bitcoin-tx binary #
bitcoin_tx_SOURCES = bitcoin-tx.cpp
-bitcoin_tx_CPPFLAGS = $(BITCOIN_INCLUDES)
+bitcoin_tx_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES)
+bitcoin_tx_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
bitcoin_tx_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS)
if TARGET_WINDOWS
@@ -407,9 +419,10 @@ if GLIBC_BACK_COMPAT
libbitcoinconsensus_la_SOURCES += compat/glibc_compat.cpp
endif
-libbitcoinconsensus_la_LDFLAGS = -no-undefined $(RELDFLAGS)
+libbitcoinconsensus_la_LDFLAGS = $(AM_LDFLAGS) -no-undefined $(RELDFLAGS)
libbitcoinconsensus_la_LIBADD = $(CRYPTO_LIBS)
-libbitcoinconsensus_la_CPPFLAGS = $(CRYPTO_CFLAGS) -I$(builddir)/obj -DBUILD_BITCOIN_INTERNAL
+libbitcoinconsensus_la_CPPFLAGS = $(AM_CPPFLAGS) $(CRYPTO_CFLAGS) -I$(builddir)/obj -DBUILD_BITCOIN_INTERNAL
+libbitcoinconsensus_la_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
endif
#
@@ -445,7 +458,7 @@ clean-local:
.mm.o:
$(AM_V_CXX) $(OBJCXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
- $(CPPFLAGS) $(AM_CXXFLAGS) $(QT_INCLUDES) $(CXXFLAGS) -c -o $@ $<
+ $(CPPFLAGS) $(AM_CXXFLAGS) $(QT_INCLUDES) $(AM_CXXFLAGS) $(PIE_FLAGS) $(CXXFLAGS) -c -o $@ $<
%.pb.cc %.pb.h: %.proto
@test -f $(PROTOC)
diff --git a/src/Makefile.bench.include b/src/Makefile.bench.include
index 61fe9e287d..d660a3a747 100644
--- a/src/Makefile.bench.include
+++ b/src/Makefile.bench.include
@@ -9,7 +9,8 @@ bench_bench_bitcoin_SOURCES = \
bench/bench.h \
bench/Examples.cpp
-bench_bench_bitcoin_CPPFLAGS = $(BITCOIN_INCLUDES) $(EVENT_CLFAGS) $(EVENT_PTHREADS_CFLAGS) -I$(builddir)/bench/
+bench_bench_bitcoin_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(EVENT_CLFAGS) $(EVENT_PTHREADS_CFLAGS) -I$(builddir)/bench/
+bench_bench_bitcoin_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
bench_bench_bitcoin_LDADD = \
$(LIBBITCOIN_SERVER) \
$(LIBBITCOIN_COMMON) \
@@ -31,7 +32,6 @@ endif
bench_bench_bitcoin_LDADD += $(BOOST_LIBS) $(BDB_LIBS) $(SSL_LIBS) $(CRYPTO_LIBS) $(MINIUPNPC_LIBS) $(EVENT_PTHREADS_LIBS) $(EVENT_LIBS)
bench_bench_bitcoin_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS)
-
CLEAN_BITCOIN_BENCH = bench/*.gcda bench/*.gcno
CLEANFILES += $(CLEAN_BITCOIN_BENCH)
diff --git a/src/Makefile.qt.include b/src/Makefile.qt.include
index 67fd7c1076..e62003a513 100644
--- a/src/Makefile.qt.include
+++ b/src/Makefile.qt.include
@@ -327,8 +327,9 @@ BITCOIN_RC = qt/res/bitcoin-qt-res.rc
BITCOIN_QT_INCLUDES = -I$(builddir)/qt -I$(srcdir)/qt -I$(srcdir)/qt/forms \
-I$(builddir)/qt/forms -DQT_NO_KEYWORDS
-qt_libbitcoinqt_a_CPPFLAGS = $(BITCOIN_INCLUDES) $(BITCOIN_QT_INCLUDES) \
+qt_libbitcoinqt_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(BITCOIN_QT_INCLUDES) \
$(QT_INCLUDES) $(QT_DBUS_INCLUDES) $(PROTOBUF_CFLAGS) $(QR_CFLAGS)
+qt_libbitcoinqt_a_CXXFLAGS = $(AM_CXXFLAGS) $(QT_PIE_FLAGS)
qt_libbitcoinqt_a_SOURCES = $(BITCOIN_QT_CPP) $(BITCOIN_QT_H) $(QT_FORMS_UI) \
$(QT_QRC) $(QT_QRC_LOCALE) $(QT_TS) $(PROTOBUF_PROTO) $(RES_ICONS) $(RES_IMAGES) $(RES_MOVIES)
@@ -350,8 +351,9 @@ $(QT_MOC): $(PROTOBUF_H)
$(QT_MOC_CPP): $(PROTOBUF_H)
# bitcoin-qt binary #
-qt_bitcoin_qt_CPPFLAGS = $(BITCOIN_INCLUDES) $(BITCOIN_QT_INCLUDES) \
+qt_bitcoin_qt_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(BITCOIN_QT_INCLUDES) \
$(QT_INCLUDES) $(PROTOBUF_CFLAGS) $(QR_CFLAGS)
+qt_bitcoin_qt_CXXFLAGS = $(AM_CXXFLAGS) $(QT_PIE_FLAGS)
qt_bitcoin_qt_SOURCES = qt/bitcoin.cpp
if TARGET_DARWIN
diff --git a/src/Makefile.qttest.include b/src/Makefile.qttest.include
index b8725c872d..ede3fac4c3 100644
--- a/src/Makefile.qttest.include
+++ b/src/Makefile.qttest.include
@@ -12,7 +12,7 @@ TEST_QT_H = \
qt/test/paymentrequestdata.h \
qt/test/paymentservertests.h
-qt_test_test_bitcoin_qt_CPPFLAGS = $(BITCOIN_INCLUDES) $(BITCOIN_QT_INCLUDES) \
+qt_test_test_bitcoin_qt_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(BITCOIN_QT_INCLUDES) \
$(QT_INCLUDES) $(QT_TEST_INCLUDES) $(PROTOBUF_CFLAGS)
qt_test_test_bitcoin_qt_SOURCES = \
@@ -38,6 +38,7 @@ qt_test_test_bitcoin_qt_LDADD += $(LIBBITCOIN_CLI) $(LIBBITCOIN_COMMON) $(LIBBIT
$(QR_LIBS) $(PROTOBUF_LIBS) $(BDB_LIBS) $(SSL_LIBS) $(CRYPTO_LIBS) $(MINIUPNPC_LIBS) $(LIBSECP256K1) \
$(EVENT_PTHREADS_LIBS) $(EVENT_LIBS)
qt_test_test_bitcoin_qt_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(QT_LDFLAGS) $(LIBTOOL_APP_LDFLAGS)
+qt_test_test_bitcoin_qt_CXXFLAGS = $(AM_CXXFLAGS) $(QT_PIE_FLAGS)
CLEAN_BITCOIN_QT_TEST = $(TEST_QT_MOC_CPP) qt/test/*.gcda qt/test/*.gcno
diff --git a/src/Makefile.test.include b/src/Makefile.test.include
index f23a8f41fc..2328d0b4cc 100644
--- a/src/Makefile.test.include
+++ b/src/Makefile.test.include
@@ -93,9 +93,10 @@ BITCOIN_TESTS += \
endif
test_test_bitcoin_SOURCES = $(BITCOIN_TESTS) $(JSON_TEST_FILES) $(RAW_TEST_FILES)
-test_test_bitcoin_CPPFLAGS = $(BITCOIN_INCLUDES) -I$(builddir)/test/ $(TESTDEFS)
+test_test_bitcoin_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) -I$(builddir)/test/ $(TESTDEFS)
test_test_bitcoin_LDADD = $(LIBBITCOIN_SERVER) $(LIBBITCOIN_CLI) $(LIBBITCOIN_COMMON) $(LIBBITCOIN_UTIL) $(LIBBITCOIN_CRYPTO) $(LIBUNIVALUE) $(LIBLEVELDB) $(LIBMEMENV) \
$(BOOST_LIBS) $(BOOST_UNIT_TEST_FRAMEWORK_LIB) $(LIBSECP256K1)
+test_test_bitcoin_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
if ENABLE_WALLET
test_test_bitcoin_LDADD += $(LIBBITCOIN_WALLET)
endif
diff --git a/src/chainparams.cpp b/src/chainparams.cpp
index dd26c3b31a..5d6d1ef9d8 100644
--- a/src/chainparams.cpp
+++ b/src/chainparams.cpp
@@ -73,6 +73,8 @@ public:
consensus.nMajorityEnforceBlockUpgrade = 750;
consensus.nMajorityRejectBlockOutdated = 950;
consensus.nMajorityWindow = 1000;
+ consensus.BIP34Height = 227931;
+ consensus.BIP34Hash = uint256S("0x000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8");
consensus.powLimit = uint256S("00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.nPowTargetTimespan = 14 * 24 * 60 * 60; // two weeks
consensus.nPowTargetSpacing = 10 * 60;
@@ -153,6 +155,8 @@ public:
consensus.nMajorityEnforceBlockUpgrade = 51;
consensus.nMajorityRejectBlockOutdated = 75;
consensus.nMajorityWindow = 100;
+ consensus.BIP34Height = 21111;
+ consensus.BIP34Hash = uint256S("0x0000000023b3a96d3484e5abb3755c413e7d41500f8e2a5c3f0dd01299cd8ef8");
consensus.powLimit = uint256S("00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.nPowTargetTimespan = 14 * 24 * 60 * 60; // two weeks
consensus.nPowTargetSpacing = 10 * 60;
@@ -216,6 +220,8 @@ public:
consensus.nMajorityEnforceBlockUpgrade = 750;
consensus.nMajorityRejectBlockOutdated = 950;
consensus.nMajorityWindow = 1000;
+ consensus.BIP34Height = -1; // BIP34 has not necessarily activated on regtest
+ consensus.BIP34Hash = uint256();
consensus.powLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.nPowTargetTimespan = 14 * 24 * 60 * 60; // two weeks
consensus.nPowTargetSpacing = 10 * 60;
diff --git a/src/consensus/params.h b/src/consensus/params.h
index efbbbed352..5ebc48a8df 100644
--- a/src/consensus/params.h
+++ b/src/consensus/params.h
@@ -19,6 +19,9 @@ struct Params {
int nMajorityEnforceBlockUpgrade;
int nMajorityRejectBlockOutdated;
int nMajorityWindow;
+ /** Block height and hash at which BIP34 becomes active */
+ int BIP34Height;
+ uint256 BIP34Hash;
/** Proof of work parameters */
uint256 powLimit;
bool fPowAllowMinDifficultyBlocks;
diff --git a/src/init.cpp b/src/init.cpp
index 024355f7c1..87a23deab7 100644
--- a/src/init.cpp
+++ b/src/init.cpp
@@ -25,6 +25,7 @@
#include "policy/policy.h"
#include "rpcserver.h"
#include "script/standard.h"
+#include "script/sigcache.h"
#include "scheduler.h"
#include "txdb.h"
#include "txmempool.h"
@@ -443,7 +444,7 @@ std::string HelpMessage(HelpMessageMode mode)
strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS));
strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", 15));
strUsage += HelpMessageOpt("-relaypriority", strprintf("Require high priority for relaying free or low-fee transactions (default: %u)", 1));
- strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> entries (default: %u)", 50000));
+ strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
}
strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"),
CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)));
diff --git a/src/main.cpp b/src/main.cpp
index 8afb7ddcdd..5208fbb031 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -1711,6 +1711,8 @@ void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const
}
}
+static int64_t nTimeCheck = 0;
+static int64_t nTimeForks = 0;
static int64_t nTimeVerify = 0;
static int64_t nTimeConnect = 0;
static int64_t nTimeIndex = 0;
@@ -1721,6 +1723,9 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin
{
const CChainParams& chainparams = Params();
AssertLockHeld(cs_main);
+
+ int64_t nTimeStart = GetTimeMicros();
+
// Check it again in case a previous version let a bad block in
if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
return false;
@@ -1746,6 +1751,9 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin
}
}
+ int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
+ LogPrint("bench", " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001);
+
// Do not allow blocks that contain transactions which 'overwrite' older transactions,
// unless those are already completely spent.
// If such overwrites are allowed, coinbases and transactions depending upon those
@@ -1761,6 +1769,17 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin
bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
!((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
(pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
+
+ // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
+ // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
+ // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
+ // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
+ // duplicate transactions descending from the known pairs either.
+ // If we're on the known chain at height greater than where BIP34 activated, we can save the db accesses needed for the BIP30 check.
+ CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
+ //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
+ fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
+
if (fEnforceBIP30) {
BOOST_FOREACH(const CTransaction& tx, block.vtx) {
const CCoins* coins = view.AccessCoins(tx.GetHash());
@@ -1788,11 +1807,13 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin
flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
}
+ int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
+ LogPrint("bench", " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001);
+
CBlockUndo blockundo;
CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
- int64_t nTimeStart = GetTimeMicros();
CAmount nFees = 0;
int nInputs = 0;
unsigned int nSigOps = 0;
@@ -1830,7 +1851,8 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin
nFees += view.GetValueIn(tx)-tx.GetValueOut();
std::vector<CScriptCheck> vChecks;
- if (!CheckInputs(tx, state, view, fScriptChecks, flags, false, nScriptCheckThreads ? &vChecks : NULL))
+ bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
+ if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, nScriptCheckThreads ? &vChecks : NULL))
return error("ConnectBlock(): CheckInputs on %s failed with %s",
tx.GetHash().ToString(), FormatStateMessage(state));
control.Add(vChecks);
@@ -1845,8 +1867,8 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin
vPos.push_back(std::make_pair(tx.GetHash(), pos));
pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
}
- int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
- LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime1 - nTimeStart) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime1 - nTimeStart) / (nInputs-1), nTimeConnect * 0.000001);
+ int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
+ LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime3 - nTime2), 0.001 * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * 0.000001);
CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
if (block.vtx[0].GetValueOut() > blockReward)
@@ -1857,8 +1879,8 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin
if (!control.Wait())
return state.DoS(100, false);
- int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
- LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime2 - nTimeStart), nInputs <= 1 ? 0 : 0.001 * (nTime2 - nTimeStart) / (nInputs-1), nTimeVerify * 0.000001);
+ int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
+ LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime4 - nTime2), nInputs <= 1 ? 0 : 0.001 * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * 0.000001);
if (fJustCheck)
return true;
@@ -1889,16 +1911,16 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin
// add this block to the view's block chain
view.SetBestBlock(pindex->GetBlockHash());
- int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
- LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
+ int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
+ LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001);
// Watch for changes to the previous coinbase transaction.
static uint256 hashPrevBestCoinBase;
GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
hashPrevBestCoinBase = block.vtx[0].GetHash();
- int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
- LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
+ int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
+ LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001);
return true;
}
@@ -2781,9 +2803,8 @@ bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIn
return true;
}
-bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
+static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex=NULL)
{
- const CChainParams& chainparams = Params();
AssertLockHeld(cs_main);
// Check for duplicate
uint256 hash = block.GetHash();
@@ -2836,7 +2857,7 @@ bool AcceptBlock(const CBlock& block, CValidationState& state, CBlockIndex** ppi
CBlockIndex *&pindex = *ppindex;
- if (!AcceptBlockHeader(block, state, &pindex))
+ if (!AcceptBlockHeader(block, state, chainparams, &pindex))
return false;
// Try to process all requested blocks that we don't have, but only
@@ -4310,10 +4331,10 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
vRecv >> locator >> hashStop;
LOCK(cs_main);
-
- if (IsInitialBlockDownload())
+ if (IsInitialBlockDownload() && !pfrom->fWhitelisted) {
+ LogPrint("net", "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom->id);
return true;
-
+ }
CBlockIndex* pindex = NULL;
if (locator.IsNull())
{
@@ -4500,7 +4521,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
Misbehaving(pfrom->GetId(), 20);
return error("non-continuous headers sequence");
}
- if (!AcceptBlockHeader(header, state, &pindexLast)) {
+ if (!AcceptBlockHeader(header, state, chainparams, &pindexLast)) {
int nDoS;
if (state.IsInvalid(nDoS)) {
if (nDoS > 0)
diff --git a/src/main.h b/src/main.h
index a82e3faa45..7a136075ac 100644
--- a/src/main.h
+++ b/src/main.h
@@ -382,7 +382,6 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex
/** Store block on disk. If dbp is non-NULL, the file is known to already reside on disk */
bool AcceptBlock(const CBlock& block, CValidationState& state, CBlockIndex **pindex, bool fRequested, CDiskBlockPos* dbp);
-bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, CBlockIndex **ppindex= NULL);
class CBlockFileInfo
diff --git a/src/script/sigcache.cpp b/src/script/sigcache.cpp
index 099b4ad0e3..eee96e7c2d 100644
--- a/src/script/sigcache.cpp
+++ b/src/script/sigcache.cpp
@@ -5,17 +5,30 @@
#include "sigcache.h"
+#include "memusage.h"
#include "pubkey.h"
#include "random.h"
#include "uint256.h"
#include "util.h"
#include <boost/thread.hpp>
-#include <boost/tuple/tuple_comparison.hpp>
+#include <boost/unordered_set.hpp>
namespace {
/**
+ * We're hashing a nonce into the entries themselves, so we don't need extra
+ * blinding in the set hash computation.
+ */
+class CSignatureCacheHasher
+{
+public:
+ size_t operator()(const uint256& key) const {
+ return key.GetCheapHash();
+ }
+};
+
+/**
* Valid signature cache, to avoid doing expensive ECDSA signature checking
* twice for every transaction (once when accepted into memory pool, and
* again when accepted into the block chain)
@@ -23,52 +36,54 @@ namespace {
class CSignatureCache
{
private:
- //! sigdata_type is (signature hash, signature, public key):
- typedef boost::tuple<uint256, std::vector<unsigned char>, CPubKey> sigdata_type;
- std::set< sigdata_type> setValid;
+ //! Entries are SHA256(nonce || signature hash || public key || signature):
+ uint256 nonce;
+ typedef boost::unordered_set<uint256, CSignatureCacheHasher> map_type;
+ map_type setValid;
boost::shared_mutex cs_sigcache;
+
public:
+ CSignatureCache()
+ {
+ GetRandBytes(nonce.begin(), 32);
+ }
+
+ void
+ ComputeEntry(uint256& entry, const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubkey)
+ {
+ CSHA256().Write(nonce.begin(), 32).Write(hash.begin(), 32).Write(&pubkey[0], pubkey.size()).Write(&vchSig[0], vchSig.size()).Finalize(entry.begin());
+ }
+
bool
- Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
+ Get(const uint256& entry)
{
boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
+ return setValid.count(entry);
+ }
- sigdata_type k(hash, vchSig, pubKey);
- std::set<sigdata_type>::iterator mi = setValid.find(k);
- if (mi != setValid.end())
- return true;
- return false;
+ void Erase(const uint256& entry)
+ {
+ boost::unique_lock<boost::shared_mutex> lock(cs_sigcache);
+ setValid.erase(entry);
}
- void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
+ void Set(const uint256& entry)
{
- // DoS prevention: limit cache size to less than 10MB
- // (~200 bytes per cache entry times 50,000 entries)
- // Since there are a maximum of 20,000 signature operations per block
- // 50,000 is a reasonable default.
- int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
+ size_t nMaxCacheSize = GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
if (nMaxCacheSize <= 0) return;
boost::unique_lock<boost::shared_mutex> lock(cs_sigcache);
-
- while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
+ while (memusage::DynamicUsage(setValid) > nMaxCacheSize)
{
- // Evict a random entry. Random because that helps
- // foil would-be DoS attackers who might try to pre-generate
- // and re-use a set of valid signatures just-slightly-greater
- // than our cache size.
- uint256 randomHash = GetRandHash();
- std::vector<unsigned char> unused;
- std::set<sigdata_type>::iterator it =
- setValid.lower_bound(sigdata_type(randomHash, unused, unused));
- if (it == setValid.end())
- it = setValid.begin();
- setValid.erase(*it);
+ map_type::size_type s = GetRand(setValid.bucket_count());
+ map_type::local_iterator it = setValid.begin(s);
+ if (it != setValid.end(s)) {
+ setValid.erase(*it);
+ }
}
- sigdata_type k(hash, vchSig, pubKey);
- setValid.insert(k);
+ setValid.insert(entry);
}
};
@@ -78,13 +93,21 @@ bool CachingTransactionSignatureChecker::VerifySignature(const std::vector<unsig
{
static CSignatureCache signatureCache;
- if (signatureCache.Get(sighash, vchSig, pubkey))
+ uint256 entry;
+ signatureCache.ComputeEntry(entry, sighash, vchSig, pubkey);
+
+ if (signatureCache.Get(entry)) {
+ if (!store) {
+ signatureCache.Erase(entry);
+ }
return true;
+ }
if (!TransactionSignatureChecker::VerifySignature(vchSig, pubkey, sighash))
return false;
- if (store)
- signatureCache.Set(sighash, vchSig, pubkey);
+ if (store) {
+ signatureCache.Set(entry);
+ }
return true;
}
diff --git a/src/script/sigcache.h b/src/script/sigcache.h
index b299038daa..2269972560 100644
--- a/src/script/sigcache.h
+++ b/src/script/sigcache.h
@@ -10,6 +10,10 @@
#include <vector>
+// DoS prevention: limit cache size to less than 40MB (over 500000
+// entries on 64-bit systems).
+static const unsigned int DEFAULT_MAX_SIG_CACHE_SIZE = 40;
+
class CPubKey;
class CachingTransactionSignatureChecker : public TransactionSignatureChecker