Browse Source

Merge #8772: [0.13] Backports

b70b4a2 Trivial: Fix typo (Marty Jones)
702fd2e [copyright] add MIT license headers to .sh scripts where missing (isle2983)
a60d7cc [copyright] Add missing copyright headers (isle2983)
ea2a6be [copyright] add MIT License copyright header to remaining Python files (isle2983)
9a903f9 [copyright] add MIT License copyright header to zmq_sub.py (isle2983)
084cae9 UndoReadFromDisk works on undo files (rev), not on block files. (Pavel Janík)
e34374e [qa] wallet: Check legacy wallet as well (MarcoFalke)
d31ac72 Specify Protobuf version 2 in paymentrequest.proto (fanquake)
5e15fce Minor change in section name (Anders Øyvind Urke-Sætre)
0e2c6bd [Doc] Target protobuf 2.6 in OS X build notes. (Michael Ford)
da94272 [qa] walletbackup: Sync blocks inside the loop (MarcoFalke)
42ea51a net: No longer send local address in addrMe (Wladimir J. van der Laan)
ea51b0f Berkeley DB v6 compatibility fix (Alexey Vesnin)
0a35573 [doc] - clarify statement about parallel jobs in rpc-tests.py (isle2983)
752fbae contrib: Make fix-copyright-headers.py more portable (MarcoFalke)
486650a [doc] Fix typos in comments, doxygen: Fix comment syntax (MarcoFalke)
c18a9ca [qa] pull-tester: Don't mute zmq ImportError (MarcoFalke)
9556745 init: Fix typo in help message for -whitelistforcerelay (Wladimir J. van der Laan)
4f84082 Set jonasschnellis dns-seeder filter flag (Jonas Schnelli)
863ae74 [doc] Update git-subtree-check.sh README (MarcoFalke)
c493f43 Trivial: Fix two VarInt examples in serialize.h (Christian Barcenas)
cb07f19 CDB: fix debug output (crowning-)
75d5484 Add copyright header to wallet_text_fixture.cpp (Wladimir J. van der Laan)
305d8ac Use __func__ to get function name for output printing (MarcoFalke)
464dedd [Wallet] Trivial cleanup of HD wallet changes (Jonas Schnelli)
b17a3f9 document return value of networkhashps for getmininginfo RPC endpoint (Jameson Lopp)
a27cdd8 [qa] abandonconflict: Use assert_equal (MarcoFalke)
befe654 various typos (leijurv)
4e5fc31 Fix a type error that would not compile on Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn) (Jeremy Rubin)
156e305 Corrected JSON typo on setban of net.cpp (Sev)
fa5b249 Bugfix: Allow building libbitcoinconsensus without any univalue (Luke Dashjr)
8b0bdd3 configure: Allow building bench_bitcoin by itself (Luke Dashjr)
749c8a5 [doc] typos, READMEs, comments (Justin Camarena)
fc34928 Do diskspace check before import thread is started (Pieter Wuille)
3b354d2 Add extra message to avoid a long 'Loading banlist' (Pieter Wuille)
30eac2d Use a signal to continue init after genesis activation (Pieter Wuille)
9b00979 Update README.md (Chris Stewart)
8bb1efd [qa] Rework hd wallet dump test (MarcoFalke)
a7aa3cc Enable size accounting in mining unit tests (Suhas Daftuar)
bea02dc [qa]: enable rpcbind_test (whythat)
e111904 [qa]: add parsing for '<host>:<port>' argument form to rpc_url() (whythat)
69d1cd2 net: Ignore `notfound` P2P messages (Wladimir J. van der Laan)
f70be14 [QA] Add walletdump RPC test (including HD- & encryption-tests) (Jonas Schnelli)
1f21d16 prepend license statement to indirectmap (Kaz Wesley)
03b0196 Fix obvious assignment/equality error in test (Jeremy Rubin)
8a7d7ff update name of file bitcoin.qrc (Gaurav Rana)
147003c Add configure check for -latomic (Anthony Towns)
091cdeb Clear witness with vin/vout in CWallet::CreateTransaction() (Suhas Daftuar)
8e03382 [Qt][CoinControl] fix UI bug that could result in paying unexpected fee (Jonas Schnelli)
6b07362 Fix SIGHASH_SINGLE bug in test_framework SignatureHash (Johnson Lau)
a114a02 p2psegwit.py transaction is rejected due to premature witness not size (instagibbs)
3606b6b Update p2p-segwit.py to reflect correct AskFor behavior (instagibbs)
733760a Update btcdrak signing key (BtcDrak)
c6a6291 add witness address to address book (instagibbs)
0.13
Wladimir J. van der Laan 8 years ago
parent
commit
254e990ce5
No known key found for this signature in database
GPG Key ID: 74810B012346C9A6
  1. 40
      build-aux/m4/l_atomic.m4
  2. 23
      configure.ac
  3. 3
      contrib/devtools/README.md
  4. 2
      contrib/devtools/fix-copyright-headers.py
  5. 3
      contrib/devtools/git-subtree-check.sh
  6. 3
      contrib/devtools/optimize-pngs.py
  7. 3
      contrib/devtools/security-check.py
  8. 3
      contrib/devtools/test-security-check.py
  9. BIN
      contrib/gitian-keys/btcdrak-key.pgp
  10. 4
      contrib/macdeploy/detached-sig-apply.sh
  11. 4
      contrib/macdeploy/detached-sig-create.sh
  12. 4
      contrib/qos/tc.sh
  13. 3
      contrib/qt_translations.py
  14. 3
      contrib/seeds/makeseeds.py
  15. 3
      contrib/spendfrom/setup.py
  16. 3
      contrib/spendfrom/spendfrom.py
  17. 3
      contrib/testgen/base58.py
  18. 3
      contrib/testgen/gen_base58_test_vectors.py
  19. 3
      contrib/tidy_datadir.sh
  20. 4
      contrib/verify-commits/gpg.sh
  21. 4
      contrib/verify-commits/pre-push-hook.sh
  22. 4
      contrib/verify-commits/verify-commits.sh
  23. 3
      contrib/verifybinaries/verify.sh
  24. 3
      contrib/zmq/zmq_sub.py
  25. 2
      doc/README_osx.md
  26. 2
      doc/build-osx.md
  27. 2
      doc/gitian-building.md
  28. 2
      doc/release-notes.md
  29. 4
      doc/translation_process.md
  30. 4
      qa/README.md
  31. 13
      qa/pull-tester/rpc-tests.py
  32. 26
      qa/rpc-tests/abandonconflict.py
  33. 10
      qa/rpc-tests/p2p-segwit.py
  34. 219
      qa/rpc-tests/rpcbind_test.py
  35. 3
      qa/rpc-tests/test_framework/blockstore.py
  36. 2
      qa/rpc-tests/test_framework/script.py
  37. 10
      qa/rpc-tests/test_framework/util.py
  38. 104
      qa/rpc-tests/wallet-dump.py
  39. 5
      qa/rpc-tests/wallet.py
  40. 7
      qa/rpc-tests/walletbackup.py
  41. 3
      share/qt/extract_strings_qt.py
  42. 2
      src/blockencodings.cpp
  43. 10
      src/chain.h
  44. 2
      src/chainparams.cpp
  45. 6
      src/consensus/validation.h
  46. 2
      src/httpserver.h
  47. 4
      src/indirectmap.h
  48. 50
      src/init.cpp
  49. 17
      src/main.cpp
  50. 2
      src/main.h
  51. 6
      src/net.cpp
  52. 2
      src/primitives/transaction.cpp
  53. 2
      src/qt/paymentrequest.proto
  54. 4
      src/qt/res/movies/makespinner.sh
  55. 5
      src/qt/sendcoinsdialog.cpp
  56. 7
      src/rpc/mining.cpp
  57. 2
      src/rpc/net.cpp
  58. 54
      src/rpc/protocol.h
  59. 2
      src/script/sign.h
  60. 4
      src/serialize.h
  61. 21
      src/test/README.md
  62. 2
      src/test/arith_uint256_tests.cpp
  63. 4
      src/test/miner_tests.cpp
  64. 5
      src/test/test_bitcoin.cpp
  65. 4
      src/wallet/db.cpp
  66. 2
      src/wallet/rpcwallet.cpp
  67. 4
      src/wallet/test/wallet_test_fixture.cpp
  68. 38
      src/wallet/wallet.cpp
  69. 4
      src/wallet/walletdb.cpp
  70. 2
      src/zmq/zmqpublishnotifier.h

40
build-aux/m4/l_atomic.m4

@ -0,0 +1,40 @@
# Some versions of gcc/libstdc++ require linking with -latomic if
# using the C++ atomic library.
#
# Sourced from http://bugs.debian.org/797228
m4_define([_CHECK_ATOMIC_testbody], [[
#include <atomic>
#include <cstdint>
int main() {
std::atomic<int64_t> a{};
int64_t v = 5;
int64_t r = a.fetch_add(v);
return static_cast<int>(r);
}
]])
AC_DEFUN([CHECK_ATOMIC], [
AC_LANG_PUSH(C++)
AC_MSG_CHECKING([whether std::atomic can be used without link library])
AC_LINK_IFELSE([AC_LANG_SOURCE([_CHECK_ATOMIC_testbody])],[
AC_MSG_RESULT([yes])
],[
AC_MSG_RESULT([no])
LIBS="$LIBS -latomic"
AC_MSG_CHECKING([whether std::atomic needs -latomic])
AC_LINK_IFELSE([AC_LANG_SOURCE([_CHECK_ATOMIC_testbody])],[
AC_MSG_RESULT([yes])
],[
AC_MSG_RESULT([no])
AC_MSG_FAILURE([cannot figure our how to use std::atomic])
])
])
AC_LANG_POP
])

23
configure.ac

@ -57,6 +57,9 @@ case $host in
esac esac
dnl Require C++11 compiler (no GNU extensions) dnl Require C++11 compiler (no GNU extensions)
AX_CXX_COMPILE_STDCXX([11], [noext], [mandatory]) AX_CXX_COMPILE_STDCXX([11], [noext], [mandatory])
dnl Check if -latomic is required for <std::atomic>
CHECK_ATOMIC
dnl Libtool init checks. dnl Libtool init checks.
LT_INIT([pic-only]) LT_INIT([pic-only])
@ -833,6 +836,12 @@ fi
dnl univalue check dnl univalue check
need_bundled_univalue=yes
if test x$build_bitcoin_utils$build_bitcoind$bitcoin_enable_qt$use_tests$use_bench = xnonononono; then
need_bundled_univalue=no
else
if test x$system_univalue != xno ; then if test x$system_univalue != xno ; then
found_univalue=no found_univalue=no
if test x$use_pkgconfig = xyes; then if test x$use_pkgconfig = xyes; then
@ -854,6 +863,7 @@ if test x$system_univalue != xno ; then
if test x$found_univalue = xyes ; then if test x$found_univalue = xyes ; then
system_univalue=yes system_univalue=yes
need_bundled_univalue=no
elif test x$system_univalue = xyes ; then elif test x$system_univalue = xyes ; then
AC_MSG_ERROR([univalue not found]) AC_MSG_ERROR([univalue not found])
else else
@ -861,11 +871,14 @@ if test x$system_univalue != xno ; then
fi fi
fi fi
if test x$system_univalue = xno ; then if test x$need_bundled_univalue = xyes ; then
UNIVALUE_CFLAGS='-I$(srcdir)/univalue/include' UNIVALUE_CFLAGS='-I$(srcdir)/univalue/include'
UNIVALUE_LIBS='univalue/libunivalue.la' UNIVALUE_LIBS='univalue/libunivalue.la'
fi fi
AM_CONDITIONAL([EMBEDDED_UNIVALUE],[test x$system_univalue = xno])
fi
AM_CONDITIONAL([EMBEDDED_UNIVALUE],[test x$need_bundled_univalue = xyes])
AC_SUBST(UNIVALUE_CFLAGS) AC_SUBST(UNIVALUE_CFLAGS)
AC_SUBST(UNIVALUE_LIBS) AC_SUBST(UNIVALUE_LIBS)
@ -1003,8 +1016,8 @@ else
AC_MSG_RESULT([no]) AC_MSG_RESULT([no])
fi fi
if test x$build_bitcoin_utils$build_bitcoin_libs$build_bitcoind$bitcoin_enable_qt$use_tests = xnonononono; then if test x$build_bitcoin_utils$build_bitcoin_libs$build_bitcoind$bitcoin_enable_qt$use_bench$use_tests = xnononononono; then
AC_MSG_ERROR([No targets! Please specify at least one of: --with-utils --with-libs --with-daemon --with-gui or --enable-tests]) AC_MSG_ERROR([No targets! Please specify at least one of: --with-utils --with-libs --with-daemon --with-gui --enable-bench or --enable-tests])
fi fi
AM_CONDITIONAL([TARGET_DARWIN], [test x$TARGET_OS = xdarwin]) AM_CONDITIONAL([TARGET_DARWIN], [test x$TARGET_OS = xdarwin])
@ -1096,7 +1109,7 @@ PKGCONFIG_LIBDIR_TEMP="$PKG_CONFIG_LIBDIR"
unset PKG_CONFIG_LIBDIR unset PKG_CONFIG_LIBDIR
PKG_CONFIG_LIBDIR="$PKGCONFIG_LIBDIR_TEMP" PKG_CONFIG_LIBDIR="$PKGCONFIG_LIBDIR_TEMP"
if test x$system_univalue = xno; then if test x$need_bundled_univalue = xyes; then
AC_CONFIG_SUBDIRS([src/univalue]) AC_CONFIG_SUBDIRS([src/univalue])
fi fi

3
contrib/devtools/README.md

@ -51,8 +51,9 @@ maintained:
* for `src/secp256k1`: https://github.com/bitcoin-core/secp256k1.git (branch master) * for `src/secp256k1`: https://github.com/bitcoin-core/secp256k1.git (branch master)
* for `src/leveldb`: https://github.com/bitcoin-core/leveldb.git (branch bitcoin-fork) * for `src/leveldb`: https://github.com/bitcoin-core/leveldb.git (branch bitcoin-fork)
* for `src/univalue`: https://github.com/bitcoin-core/univalue.git (branch master) * for `src/univalue`: https://github.com/bitcoin-core/univalue.git (branch master)
* for `src/crypto/ctaes`: https://github.com/bitcoin-core/ctaes.git (branch master)
Usage: `git-subtree-check.sh DIR COMMIT` Usage: `git-subtree-check.sh DIR (COMMIT)`
`COMMIT` may be omitted, in which case `HEAD` is used. `COMMIT` may be omitted, in which case `HEAD` is used.

2
contrib/devtools/fix-copyright-headers.py

@ -16,7 +16,7 @@ import time
import re import re
year = time.gmtime()[0] year = time.gmtime()[0]
CMD_GIT_DATE = 'git log --format=@%%at -1 %s | date +"%%Y" -u -f -' CMD_GIT_DATE = 'git log --format=%%ad --date=short -1 %s | cut -d"-" -f 1'
CMD_REGEX= "perl -pi -e 's/(20\d\d)(?:-20\d\d)? The Bitcoin/$1-%s The Bitcoin/' %s" CMD_REGEX= "perl -pi -e 's/(20\d\d)(?:-20\d\d)? The Bitcoin/$1-%s The Bitcoin/' %s"
REGEX_CURRENT= re.compile("%s The Bitcoin" % year) REGEX_CURRENT= re.compile("%s The Bitcoin" % year)
CMD_LIST_FILES= "find %s | grep %s" CMD_LIST_FILES= "find %s | grep %s"

3
contrib/devtools/git-subtree-check.sh

@ -1,4 +1,7 @@
#!/bin/sh #!/bin/sh
# Copyright (c) 2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
DIR="$1" DIR="$1"
COMMIT="$2" COMMIT="$2"

3
contrib/devtools/optimize-pngs.py

@ -1,4 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
''' '''
Run this script every time you change one of the png files. Using pngcrush, it will optimize the png files, remove various color profiles, remove ancillary chunks (alla) and text chunks (text). Run this script every time you change one of the png files. Using pngcrush, it will optimize the png files, remove various color profiles, remove ancillary chunks (alla) and text chunks (text).
#pngcrush -brute -ow -rem gAMA -rem cHRM -rem iCCP -rem sRGB -rem alla -rem text #pngcrush -brute -ow -rem gAMA -rem cHRM -rem iCCP -rem sRGB -rem alla -rem text

3
contrib/devtools/security-check.py

@ -1,4 +1,7 @@
#!/usr/bin/python2 #!/usr/bin/python2
# Copyright (c) 2015-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.
''' '''
Perform basic ELF security checks on a series of executables. Perform basic ELF security checks on a series of executables.
Exit status will be 0 if successful, and the program will be silent. Exit status will be 0 if successful, and the program will be silent.

3
contrib/devtools/test-security-check.py

@ -1,4 +1,7 @@
#!/usr/bin/python2 #!/usr/bin/python2
# Copyright (c) 2015-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.
''' '''
Test script for security-check.py Test script for security-check.py
''' '''

BIN
contrib/gitian-keys/btcdrak-key.pgp

Binary file not shown.

4
contrib/macdeploy/detached-sig-apply.sh

@ -1,4 +1,8 @@
#!/bin/sh #!/bin/sh
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
set -e set -e
UNSIGNED="$1" UNSIGNED="$1"

4
contrib/macdeploy/detached-sig-create.sh

@ -1,4 +1,8 @@
#!/bin/sh #!/bin/sh
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
set -e set -e
ROOTDIR=dist ROOTDIR=dist

4
contrib/qos/tc.sh

@ -1,3 +1,7 @@
# Copyright (c) 2013 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#network interface on which to limit traffic #network interface on which to limit traffic
IF="eth0" IF="eth0"
#limit of the network interface in question #limit of the network interface in question

3
contrib/qt_translations.py

@ -1,4 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# Copyright (c) 2011 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Helpful little script that spits out a comma-separated list of # Helpful little script that spits out a comma-separated list of
# language codes for Qt icons that should be included # language codes for Qt icons that should be included

3
contrib/seeds/makeseeds.py

@ -1,4 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# Copyright (c) 2013-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# #
# Generate seeds.txt from Pieter's DNS seeder # Generate seeds.txt from Pieter's DNS seeder
# #

3
contrib/spendfrom/setup.py

@ -1,3 +1,6 @@
# Copyright (c) 2013 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from distutils.core import setup from distutils.core import setup
setup(name='btcspendfrom', setup(name='btcspendfrom',
version='1.0', version='1.0',

3
contrib/spendfrom/spendfrom.py

@ -1,4 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# Copyright (c) 2013 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# #
# Use the raw transactions API to spend bitcoins received on particular addresses, # Use the raw transactions API to spend bitcoins received on particular addresses,
# and send any change back to that same address. # and send any change back to that same address.

3
contrib/testgen/base58.py

@ -1,3 +1,6 @@
# Copyright (c) 2012 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
''' '''
Bitcoin base58 encoding and decoding. Bitcoin base58 encoding and decoding.

3
contrib/testgen/gen_base58_test_vectors.py

@ -1,4 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# Copyright (c) 2012 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
''' '''
Generate valid and invalid base58 address and private key test vectors. Generate valid and invalid base58 address and private key test vectors.

3
contrib/tidy_datadir.sh

@ -1,4 +1,7 @@
#!/bin/bash #!/bin/bash
# Copyright (c) 2013 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
if [ -d "$1" ]; then if [ -d "$1" ]; then
cd "$1" cd "$1"

4
contrib/verify-commits/gpg.sh

@ -1,4 +1,8 @@
#!/bin/sh #!/bin/sh
# Copyright (c) 2014-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.
INPUT=$(cat /dev/stdin) INPUT=$(cat /dev/stdin)
VALID=false VALID=false
REVSIG=false REVSIG=false

4
contrib/verify-commits/pre-push-hook.sh

@ -1,4 +1,8 @@
#!/bin/bash #!/bin/bash
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
if ! [[ "$2" =~ ^(git@)?(www.)?github.com(:|/)bitcoin/bitcoin(.git)?$ ]]; then if ! [[ "$2" =~ ^(git@)?(www.)?github.com(:|/)bitcoin/bitcoin(.git)?$ ]]; then
exit 0 exit 0
fi fi

4
contrib/verify-commits/verify-commits.sh

@ -1,4 +1,8 @@
#!/bin/sh #!/bin/sh
# Copyright (c) 2014-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.
# Not technically POSIX-compliant due to use of "local", but almost every # Not technically POSIX-compliant due to use of "local", but almost every
# shell anyone uses today supports it, so its probably fine # shell anyone uses today supports it, so its probably fine

3
contrib/verifybinaries/verify.sh

@ -1,4 +1,7 @@
#!/bin/bash #!/bin/bash
# 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.
### This script attempts to download the signature file SHA256SUMS.asc from bitcoin.org ### This script attempts to download the signature file SHA256SUMS.asc from bitcoin.org
### It first checks if the signature passes, and then downloads the files specified in ### It first checks if the signature passes, and then downloads the files specified in

3
contrib/zmq/zmq_sub.py

@ -1,4 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# Copyright (c) 2014-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.
import array import array
import binascii import binascii

2
doc/README_osx.md

@ -22,7 +22,7 @@ These tools inject timestamps by default, which produce non-deterministic
binaries. The ZERO_AR_DATE environment variable is used to disable that. binaries. The ZERO_AR_DATE environment variable is used to disable that.
This version of cctools has been patched to use the current version of clang's This version of cctools has been patched to use the current version of clang's
headers and and its libLTO.so rather than those from llvmgcc, as it was headers and its libLTO.so rather than those from llvmgcc, as it was
originally done in toolchain4. originally done in toolchain4.
To complicate things further, all builds must target an Apple SDK. These SDKs To complicate things further, all builds must target an Apple SDK. These SDKs

2
doc/build-osx.md

@ -16,7 +16,7 @@ Then install [Homebrew](http://brew.sh).
Dependencies Dependencies
---------------------- ----------------------
brew install automake berkeley-db4 libtool boost --c++11 miniupnpc openssl pkg-config protobuf --c++11 qt5 libevent brew install automake berkeley-db4 libtool boost --c++11 miniupnpc openssl pkg-config homebrew/versions/protobuf260 --c++11 qt5 libevent
NOTE: Building with Qt4 is still supported, however, could result in a broken UI. Building with Qt5 is recommended. NOTE: Building with Qt4 is still supported, however, could result in a broken UI. Building with Qt5 is recommended.

2
doc/gitian-building.md

@ -337,7 +337,7 @@ Getting and building the inputs
-------------------------------- --------------------------------
Follow the instructions in [doc/release-process.md](release-process.md#fetch-and-build-inputs-first-time-or-when-dependency-versions-change) Follow the instructions in [doc/release-process.md](release-process.md#fetch-and-build-inputs-first-time-or-when-dependency-versions-change)
in the bitcoin repository under 'Fetch and build inputs' to install sources which require in the bitcoin repository under 'Fetch and create inputs' to install sources which require
manual intervention. Also optionally follow the next step: 'Seed the Gitian sources cache manual intervention. Also optionally follow the next step: 'Seed the Gitian sources cache
and offline git repositories' which will fetch the remaining files required for building and offline git repositories' which will fetch the remaining files required for building
offline. offline.

2
doc/release-notes.md

@ -28,7 +28,7 @@ libraries such as Qt are no longer being tested on XP.
We do not have time nor resources to provide support for an OS that is We do not have time nor resources to provide support for an OS that is
end-of-life. From 0.13.0 on, Windows XP is no longer supported. Users are end-of-life. From 0.13.0 on, Windows XP is no longer supported. Users are
suggested to upgrade to a newer verion of Windows, or install an alternative OS suggested to upgrade to a newer version of Windows, or install an alternative OS
that is supported. that is supported.
No attempt is made to prevent installing or running the software on Windows XP, No attempt is made to prevent installing or running the software on Windows XP,

4
doc/translation_process.md

@ -6,7 +6,7 @@ The Bitcoin-Core project has been designed to support multiple localisations. Th
### Helping to translate (using Transifex) ### Helping to translate (using Transifex)
Transifex is setup to monitor the Github repo for updates, and when code containing new translations is found, Transifex will process any changes. It may take several hours after a pull-request has been merged, to appear in the Transifex web interface. Transifex is setup to monitor the Github repo for updates, and when code containing new translations is found, Transifex will process any changes. It may take several hours after a pull-request has been merged, to appear in the Transifex web interface.
Multiple language support is critical in assisting Bitcoin’s global adoption, and growth. One of Bitcoin’s greatest strengths is cross-boarder money transfers, any help making that easier is greatly appreciated. Multiple language support is critical in assisting Bitcoin’s global adoption, and growth. One of Bitcoin’s greatest strengths is cross-border money transfers, any help making that easier is greatly appreciated.
See the [Transifex Bitcoin project](https://www.transifex.com/projects/p/bitcoin/) to assist in translations. You should also join the translation mailing list for announcements - see details below. See the [Transifex Bitcoin project](https://www.transifex.com/projects/p/bitcoin/) to assist in translations. You should also join the translation mailing list for announcements - see details below.
@ -94,7 +94,7 @@ When new plurals are added to the source file, it's important to do the followin
7. Save the source file 7. Save the source file
### Translating a new language ### Translating a new language
To create a new language template, you will need to edit the languages manifest file `src/qt/bitcoin.qrc` and add a new entry. Below is an example of the english language entry. To create a new language template, you will need to edit the languages manifest file `src/qt/bitcoin_locale.qrc` and add a new entry. Below is an example of the English language entry.
```xml ```xml
<qresource prefix="/translations"> <qresource prefix="/translations">

4
qa/README.md

@ -41,8 +41,8 @@ Run all possible tests with
qa/pull-tester/rpc-tests.py -extended qa/pull-tester/rpc-tests.py -extended
By default, tests will be run in parallel if you want to specify how many By default, tests will be run in parallel. To specify how many jobs to run,
tests should be run in parallel, append `-parallel=n` (default n=4). append `-parallel=n` (default n=4).
If you want to create a basic coverage report for the rpc test suite, append `--coverage`. If you want to create a basic coverage report for the rpc test suite, append `--coverage`.

13
qa/pull-tester/rpc-tests.py

@ -94,12 +94,12 @@ if not (ENABLE_WALLET == 1 and ENABLE_UTILS == 1 and ENABLE_BITCOIND == 1):
if ENABLE_ZMQ: if ENABLE_ZMQ:
try: try:
import zmq import zmq
except ImportError as e: except ImportError:
print("WARNING: \"import zmq\" failed. Set ENABLE_ZMQ=0 or " \ print("ERROR: \"import zmq\" failed. Set ENABLE_ZMQ=0 or "
"to run zmq tests, see dependency info in /qa/README.md.") "to run zmq tests, see dependency info in /qa/README.md.")
ENABLE_ZMQ=0 # ENABLE_ZMQ=0
raise
#Tests
testScripts = [ testScripts = [
# longest test should go first, to favor running tests in parallel # longest test should go first, to favor running tests in parallel
'p2p-fullblocktest.py', 'p2p-fullblocktest.py',
@ -107,6 +107,7 @@ testScripts = [
'bip68-112-113-p2p.py', 'bip68-112-113-p2p.py',
'wallet.py', 'wallet.py',
'wallet-hd.py', 'wallet-hd.py',
'wallet-dump.py',
'listtransactions.py', 'listtransactions.py',
'receivedby.py', 'receivedby.py',
'mempool_resurrect_test.py', 'mempool_resurrect_test.py',
@ -158,7 +159,7 @@ testScriptsExt = [
'txn_clone.py --mineblock', 'txn_clone.py --mineblock',
'forknotify.py', 'forknotify.py',
'invalidateblock.py', 'invalidateblock.py',
# 'rpcbind_test.py', #temporary, bug in libevent, see #6655 'rpcbind_test.py',
'smartfees.py', 'smartfees.py',
'maxblocksinflight.py', 'maxblocksinflight.py',
'p2p-acceptblock.py', 'p2p-acceptblock.py',

26
qa/rpc-tests/abandonconflict.py

@ -68,7 +68,7 @@ class AbandonConflictTest(BitcoinTestFramework):
# In mempool txs from self should increase balance from change # In mempool txs from self should increase balance from change
newbalance = self.nodes[0].getbalance() newbalance = self.nodes[0].getbalance()
assert(newbalance == balance - Decimal("30") + Decimal("24.9996")) assert_equal(newbalance, balance - Decimal("30") + Decimal("24.9996"))
balance = newbalance balance = newbalance
# Restart the node with a higher min relay fee so the parent tx is no longer in mempool # Restart the node with a higher min relay fee so the parent tx is no longer in mempool
@ -78,16 +78,16 @@ class AbandonConflictTest(BitcoinTestFramework):
self.nodes[0]=start_node(0, self.options.tmpdir, ["-debug","-logtimemicros","-minrelaytxfee=0.0001"]) self.nodes[0]=start_node(0, self.options.tmpdir, ["-debug","-logtimemicros","-minrelaytxfee=0.0001"])
# Verify txs no longer in mempool # Verify txs no longer in mempool
assert(len(self.nodes[0].getrawmempool()) == 0) assert_equal(len(self.nodes[0].getrawmempool()), 0)
# Not in mempool txs from self should only reduce balance # Not in mempool txs from self should only reduce balance
# inputs are still spent, but change not received # inputs are still spent, but change not received
newbalance = self.nodes[0].getbalance() newbalance = self.nodes[0].getbalance()
assert(newbalance == balance - Decimal("24.9996")) assert_equal(newbalance, balance - Decimal("24.9996"))
# Unconfirmed received funds that are not in mempool, also shouldn't show # Unconfirmed received funds that are not in mempool, also shouldn't show
# up in unconfirmed balance # up in unconfirmed balance
unconfbalance = self.nodes[0].getunconfirmedbalance() + self.nodes[0].getbalance() unconfbalance = self.nodes[0].getunconfirmedbalance() + self.nodes[0].getbalance()
assert(unconfbalance == newbalance) assert_equal(unconfbalance, newbalance)
# Also shouldn't show up in listunspent # Also shouldn't show up in listunspent
assert(not txABC2 in [utxo["txid"] for utxo in self.nodes[0].listunspent(0)]) assert(not txABC2 in [utxo["txid"] for utxo in self.nodes[0].listunspent(0)])
balance = newbalance balance = newbalance
@ -96,35 +96,35 @@ class AbandonConflictTest(BitcoinTestFramework):
# including that the child tx was also abandoned # including that the child tx was also abandoned
self.nodes[0].abandontransaction(txAB1) self.nodes[0].abandontransaction(txAB1)
newbalance = self.nodes[0].getbalance() newbalance = self.nodes[0].getbalance()
assert(newbalance == balance + Decimal("30")) assert_equal(newbalance, balance + Decimal("30"))
balance = newbalance balance = newbalance
# Verify that even with a low min relay fee, the tx is not reaccepted from wallet on startup once abandoned # Verify that even with a low min relay fee, the tx is not reaccepted from wallet on startup once abandoned
stop_node(self.nodes[0],0) stop_node(self.nodes[0],0)
self.nodes[0]=start_node(0, self.options.tmpdir, ["-debug","-logtimemicros","-minrelaytxfee=0.00001"]) self.nodes[0]=start_node(0, self.options.tmpdir, ["-debug","-logtimemicros","-minrelaytxfee=0.00001"])
assert(len(self.nodes[0].getrawmempool()) == 0) assert_equal(len(self.nodes[0].getrawmempool()), 0)
assert(self.nodes[0].getbalance() == balance) assert_equal(self.nodes[0].getbalance(), balance)
# But if its received again then it is unabandoned # But if its received again then it is unabandoned
# And since now in mempool, the change is available # And since now in mempool, the change is available
# But its child tx remains abandoned # But its child tx remains abandoned
self.nodes[0].sendrawtransaction(signed["hex"]) self.nodes[0].sendrawtransaction(signed["hex"])
newbalance = self.nodes[0].getbalance() newbalance = self.nodes[0].getbalance()
assert(newbalance == balance - Decimal("20") + Decimal("14.99998")) assert_equal(newbalance, balance - Decimal("20") + Decimal("14.99998"))
balance = newbalance balance = newbalance
# Send child tx again so its unabandoned # Send child tx again so its unabandoned
self.nodes[0].sendrawtransaction(signed2["hex"]) self.nodes[0].sendrawtransaction(signed2["hex"])
newbalance = self.nodes[0].getbalance() newbalance = self.nodes[0].getbalance()
assert(newbalance == balance - Decimal("10") - Decimal("14.99998") + Decimal("24.9996")) assert_equal(newbalance, balance - Decimal("10") - Decimal("14.99998") + Decimal("24.9996"))
balance = newbalance balance = newbalance
# Remove using high relay fee again # Remove using high relay fee again
stop_node(self.nodes[0],0) stop_node(self.nodes[0],0)
self.nodes[0]=start_node(0, self.options.tmpdir, ["-debug","-logtimemicros","-minrelaytxfee=0.0001"]) self.nodes[0]=start_node(0, self.options.tmpdir, ["-debug","-logtimemicros","-minrelaytxfee=0.0001"])
assert(len(self.nodes[0].getrawmempool()) == 0) assert_equal(len(self.nodes[0].getrawmempool()), 0)
newbalance = self.nodes[0].getbalance() newbalance = self.nodes[0].getbalance()
assert(newbalance == balance - Decimal("24.9996")) assert_equal(newbalance, balance - Decimal("24.9996"))
balance = newbalance balance = newbalance
# Create a double spend of AB1 by spending again from only A's 10 output # Create a double spend of AB1 by spending again from only A's 10 output
@ -143,7 +143,7 @@ class AbandonConflictTest(BitcoinTestFramework):
# Verify that B and C's 10 BTC outputs are available for spending again because AB1 is now conflicted # Verify that B and C's 10 BTC outputs are available for spending again because AB1 is now conflicted
newbalance = self.nodes[0].getbalance() newbalance = self.nodes[0].getbalance()
assert(newbalance == balance + Decimal("20")) assert_equal(newbalance, balance + Decimal("20"))
balance = newbalance balance = newbalance
# There is currently a minor bug around this and so this test doesn't work. See Issue #7315 # There is currently a minor bug around this and so this test doesn't work. See Issue #7315
@ -151,7 +151,7 @@ class AbandonConflictTest(BitcoinTestFramework):
# Don't think C's should either # Don't think C's should either
self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash())
newbalance = self.nodes[0].getbalance() newbalance = self.nodes[0].getbalance()
#assert(newbalance == balance - Decimal("10")) #assert_equal(newbalance, balance - Decimal("10"))
print("If balance has not declined after invalidateblock then out of mempool wallet tx which is no longer") print("If balance has not declined after invalidateblock then out of mempool wallet tx which is no longer")
print("conflicted has not resumed causing its inputs to be seen as spent. See Issue #7315") print("conflicted has not resumed causing its inputs to be seen as spent. See Issue #7315")
print(str(balance) + " -> " + str(newbalance) + " ?") print(str(balance) + " -> " + str(newbalance) + " ?")

10
qa/rpc-tests/p2p-segwit.py

@ -302,13 +302,18 @@ class SegWitTest(BitcoinTestFramework):
sync_blocks(self.nodes) sync_blocks(self.nodes)
# We'll add an unnecessary witness to this transaction that would cause # We'll add an unnecessary witness to this transaction that would cause
# it to be too large according to IsStandard. # it to be non-standard, to test that violating policy with a witness before
# segwit activation doesn't blind a node to a transaction. Transactions
# rejected for having a witness before segwit activation shouldn't be added
# to the rejection cache.
tx3 = CTransaction() tx3 = CTransaction()
tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), CScript([p2sh_program]))) tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), CScript([p2sh_program])))
tx3.vout.append(CTxOut(tx2.vout[0].nValue-1000, scriptPubKey)) tx3.vout.append(CTxOut(tx2.vout[0].nValue-1000, scriptPubKey))
tx3.wit.vtxinwit.append(CTxInWitness()) tx3.wit.vtxinwit.append(CTxInWitness())
tx3.wit.vtxinwit[0].scriptWitness.stack = [b'a'*400000] tx3.wit.vtxinwit[0].scriptWitness.stack = [b'a'*400000]
tx3.rehash() tx3.rehash()
# Note that this should be rejected for the premature witness reason,
# rather than a policy check, since segwit hasn't activated yet.
self.std_node.test_transaction_acceptance(tx3, True, False, b'no-witness-yet') self.std_node.test_transaction_acceptance(tx3, True, False, b'no-witness-yet')
# If we send without witness, it should be accepted. # If we send without witness, it should be accepted.
@ -946,8 +951,7 @@ class SegWitTest(BitcoinTestFramework):
self.test_node.test_transaction_acceptance(tx, with_witness=True, accepted=False) self.test_node.test_transaction_acceptance(tx, with_witness=True, accepted=False)
# Verify that removing the witness succeeds. # Verify that removing the witness succeeds.
# Re-announcing won't result in a getdata for ~2.5 minutes, so just self.test_node.announce_tx_and_wait_for_getdata(tx)
# deliver the modified transaction.
self.test_node.test_transaction_acceptance(tx, with_witness=False, accepted=True) self.test_node.test_transaction_acceptance(tx, with_witness=False, accepted=True)
# Now try to add extra witness data to a valid witness tx. # Now try to add extra witness data to a valid witness tx.

219
qa/rpc-tests/rpcbind_test.py

@ -5,143 +5,108 @@
# Test for -rpcbind, as well as -rpcallowip and -rpcconnect # Test for -rpcbind, as well as -rpcallowip and -rpcconnect
# TODO extend this test from the test framework (like all other tests)
import tempfile import tempfile
import traceback import traceback
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import *
from test_framework.netutil import * from test_framework.netutil import *
def run_bind_test(tmpdir, allow_ips, connect_to, addresses, expected): class RPCBindTest(BitcoinTestFramework):
'''
Start a node with requested rpcallowip and rpcbind parameters,
then try to connect, and check if the set of bound addresses
matches the expected set.
'''
expected = [(addr_to_hex(addr), port) for (addr, port) in expected]
base_args = ['-disablewallet', '-nolisten']
if allow_ips:
base_args += ['-rpcallowip=' + x for x in allow_ips]
binds = ['-rpcbind='+addr for addr in addresses]
nodes = start_nodes(self.num_nodes, tmpdir, [base_args + binds], connect_to)
try:
pid = bitcoind_processes[0].pid
assert_equal(set(get_bind_addrs(pid)), set(expected))
finally:
stop_nodes(nodes)
wait_bitcoinds()
def run_allowip_test(tmpdir, allow_ips, rpchost, rpcport):
'''
Start a node with rpcwallow IP, and request getinfo
at a non-localhost IP.
'''
base_args = ['-disablewallet', '-nolisten'] + ['-rpcallowip='+x for x in allow_ips]
nodes = start_nodes(self.num_nodes, tmpdir, [base_args])
try:
# connect to node through non-loopback interface
url = "http://rt:rt@%s:%d" % (rpchost, rpcport,)
node = get_rpc_proxy(url, 1)
node.getinfo()
finally:
node = None # make sure connection will be garbage collected and closed
stop_nodes(nodes)
wait_bitcoinds()
def run_test(tmpdir):
assert(sys.platform.startswith('linux')) # due to OS-specific network stats queries, this test works only on Linux
# find the first non-loopback interface for testing
non_loopback_ip = None
for name,ip in all_interfaces():
if ip != '127.0.0.1':
non_loopback_ip = ip
break
if non_loopback_ip is None:
assert(not 'This test requires at least one non-loopback IPv4 interface')
print("Using interface %s for testing" % non_loopback_ip)
defaultport = rpc_port(0) def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 1
# check default without rpcallowip (IPv4 and IPv6 localhost) def setup_network(self):
run_bind_test(tmpdir, None, '127.0.0.1', [],
[('127.0.0.1', defaultport), ('::1', defaultport)])
# check default with rpcallowip (IPv6 any)
run_bind_test(tmpdir, ['127.0.0.1'], '127.0.0.1', [],
[('::0', defaultport)])
# check only IPv4 localhost (explicit)
run_bind_test(tmpdir, ['127.0.0.1'], '127.0.0.1', ['127.0.0.1'],
[('127.0.0.1', defaultport)])
# check only IPv4 localhost (explicit) with alternative port
run_bind_test(tmpdir, ['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171'],
[('127.0.0.1', 32171)])
# check only IPv4 localhost (explicit) with multiple alternative ports on same host
run_bind_test(tmpdir, ['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171', '127.0.0.1:32172'],
[('127.0.0.1', 32171), ('127.0.0.1', 32172)])
# check only IPv6 localhost (explicit)
run_bind_test(tmpdir, ['[::1]'], '[::1]', ['[::1]'],
[('::1', defaultport)])
# check both IPv4 and IPv6 localhost (explicit)
run_bind_test(tmpdir, ['127.0.0.1'], '127.0.0.1', ['127.0.0.1', '[::1]'],
[('127.0.0.1', defaultport), ('::1', defaultport)])
# check only non-loopback interface
run_bind_test(tmpdir, [non_loopback_ip], non_loopback_ip, [non_loopback_ip],
[(non_loopback_ip, defaultport)])
# Check that with invalid rpcallowip, we are denied
run_allowip_test(tmpdir, [non_loopback_ip], non_loopback_ip, defaultport)
try:
run_allowip_test(tmpdir, ['1.1.1.1'], non_loopback_ip, defaultport)
assert(not 'Connection not denied by rpcallowip as expected')
except ValueError:
pass pass
def main(): def setup_nodes(self):
import optparse pass
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option("--nocleanup", dest="nocleanup", default=False, action="store_true",
help="Leave bitcoinds and test.* datadir on exit or error")
parser.add_option("--srcdir", dest="srcdir", default="../../src",
help="Source directory containing bitcoind/bitcoin-cli (default: %default%)")
parser.add_option("--tmpdir", dest="tmpdir", default=tempfile.mkdtemp(prefix="test"),
help="Root directory for datadirs")
(options, args) = parser.parse_args()
os.environ['PATH'] = options.srcdir+":"+os.environ['PATH']
check_json_precision()
success = False
nodes = []
try:
print("Initializing test directory "+options.tmpdir)
if not os.path.isdir(options.tmpdir):
os.makedirs(options.tmpdir)
initialize_chain(options.tmpdir)
run_test(options.tmpdir)
success = True
except AssertionError as e:
print("Assertion failed: "+e.message)
except Exception as e:
print("Unexpected exception caught during testing: "+str(e))
traceback.print_tb(sys.exc_info()[2])
if not options.nocleanup:
print("Cleaning up")
wait_bitcoinds()
shutil.rmtree(options.tmpdir)
if success: def run_bind_test(self, allow_ips, connect_to, addresses, expected):
print("Tests successful") '''
sys.exit(0) Start a node with requested rpcallowip and rpcbind parameters,
else: then try to connect, and check if the set of bound addresses
print("Failed") matches the expected set.
sys.exit(1) '''
expected = [(addr_to_hex(addr), port) for (addr, port) in expected]
base_args = ['-disablewallet', '-nolisten']
if allow_ips:
base_args += ['-rpcallowip=' + x for x in allow_ips]
binds = ['-rpcbind='+addr for addr in addresses]
self.nodes = start_nodes(self.num_nodes, self.options.tmpdir, [base_args + binds], connect_to)
try:
pid = bitcoind_processes[0].pid
assert_equal(set(get_bind_addrs(pid)), set(expected))
finally:
stop_nodes(self.nodes)
wait_bitcoinds()
def run_allowip_test(self, allow_ips, rpchost, rpcport):
'''
Start a node with rpcwallow IP, and request getinfo
at a non-localhost IP.
'''
base_args = ['-disablewallet', '-nolisten'] + ['-rpcallowip='+x for x in allow_ips]
self.nodes = start_nodes(self.num_nodes, self.options.tmpdir, [base_args])
try:
# connect to node through non-loopback interface
node = get_rpc_proxy(rpc_url(0, "%s:%d" % (rpchost, rpcport)), 0)
node.getinfo()
finally:
node = None # make sure connection will be garbage collected and closed
stop_nodes(self.nodes)
wait_bitcoinds()
def run_test(self):
# due to OS-specific network stats queries, this test works only on Linux
assert(sys.platform.startswith('linux'))
# find the first non-loopback interface for testing
non_loopback_ip = None
for name,ip in all_interfaces():
if ip != '127.0.0.1':
non_loopback_ip = ip
break
if non_loopback_ip is None:
assert(not 'This test requires at least one non-loopback IPv4 interface')
print("Using interface %s for testing" % non_loopback_ip)
defaultport = rpc_port(0)
# check default without rpcallowip (IPv4 and IPv6 localhost)
self.run_bind_test(None, '127.0.0.1', [],
[('127.0.0.1', defaultport), ('::1', defaultport)])
# check default with rpcallowip (IPv6 any)
self.run_bind_test(['127.0.0.1'], '127.0.0.1', [],
[('::0', defaultport)])
# check only IPv4 localhost (explicit)
self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1'],
[('127.0.0.1', defaultport)])
# check only IPv4 localhost (explicit) with alternative port
self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171'],
[('127.0.0.1', 32171)])
# check only IPv4 localhost (explicit) with multiple alternative ports on same host
self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171', '127.0.0.1:32172'],
[('127.0.0.1', 32171), ('127.0.0.1', 32172)])
# check only IPv6 localhost (explicit)
self.run_bind_test(['[::1]'], '[::1]', ['[::1]'],
[('::1', defaultport)])
# check both IPv4 and IPv6 localhost (explicit)
self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1', '[::1]'],
[('127.0.0.1', defaultport), ('::1', defaultport)])
# check only non-loopback interface
self.run_bind_test([non_loopback_ip], non_loopback_ip, [non_loopback_ip],
[(non_loopback_ip, defaultport)])
# Check that with invalid rpcallowip, we are denied
self.run_allowip_test([non_loopback_ip], non_loopback_ip, defaultport)
try:
self.run_allowip_test(['1.1.1.1'], non_loopback_ip, defaultport)
assert(not 'Connection not denied by rpcallowip as expected')
except JSONRPCException:
pass
if __name__ == '__main__': if __name__ == '__main__':
main() RPCBindTest ().main ()

3
qa/rpc-tests/test_framework/blockstore.py

@ -1,4 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# Copyright (c) 2015-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.
# BlockStore: a helper class that keeps a map of blocks and implements # BlockStore: a helper class that keeps a map of blocks and implements
# helper functions for responding to getheaders and getdata, # helper functions for responding to getheaders and getdata,
# and for constructing a getheaders message # and for constructing a getheaders message

2
qa/rpc-tests/test_framework/script.py

@ -882,7 +882,7 @@ def SignatureHash(script, txTo, inIdx, hashtype):
tmp = txtmp.vout[outIdx] tmp = txtmp.vout[outIdx]
txtmp.vout = [] txtmp.vout = []
for i in range(outIdx): for i in range(outIdx):
txtmp.vout.append(CTxOut()) txtmp.vout.append(CTxOut(-1))
txtmp.vout.append(tmp) txtmp.vout.append(tmp)
for i in range(len(txtmp.vin)): for i in range(len(txtmp.vin)):

10
qa/rpc-tests/test_framework/util.py

@ -171,7 +171,15 @@ def rpc_auth_pair(n):
def rpc_url(i, rpchost=None): def rpc_url(i, rpchost=None):
rpc_u, rpc_p = rpc_auth_pair(i) rpc_u, rpc_p = rpc_auth_pair(i)
return "http://%s:%s@%s:%d" % (rpc_u, rpc_p, rpchost or '127.0.0.1', rpc_port(i)) host = '127.0.0.1'
port = rpc_port(i)
if rpchost:
parts = rpchost.split(':')
if len(parts) == 2:
host, port = parts
else:
host = rpchost
return "http://%s:%s@%s:%d" % (rpc_u, rpc_p, host, int(port))
def wait_for_bitcoind_start(process, url, i): def wait_for_bitcoind_start(process, url, i):
''' '''

104
qa/rpc-tests/wallet-dump.py

@ -0,0 +1,104 @@
#!/usr/bin/env python3
# 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.
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (start_nodes, start_node, assert_equal, bitcoind_processes)
def read_dump(file_name, addrs, hd_master_addr_old):
"""
Read the given dump, count the addrs that match, count change and reserve.
Also check that the old hd_master is inactive
"""
with open(file_name) as inputfile:
found_addr = 0
found_addr_chg = 0
found_addr_rsv = 0
hd_master_addr_ret = None
for line in inputfile:
# only read non comment lines
if line[0] != "#" and len(line) > 10:
# split out some data
key_label, comment = line.split("#")
# key = key_label.split(" ")[0]
keytype = key_label.split(" ")[2]
if len(comment) > 1:
addr_keypath = comment.split(" addr=")[1]
addr = addr_keypath.split(" ")[0]
keypath = None
if keytype == "inactivehdmaster=1":
# ensure the old master is still available
assert(hd_master_addr_old == addr)
elif keytype == "hdmaster=1":
# ensure we have generated a new hd master key
assert(hd_master_addr_old != addr)
hd_master_addr_ret = addr
else:
keypath = addr_keypath.rstrip().split("hdkeypath=")[1]
# count key types
for addrObj in addrs:
if addrObj['address'] == addr and addrObj['hdkeypath'] == keypath and keytype == "label=":
found_addr += 1
break
elif keytype == "change=1":
found_addr_chg += 1
break
elif keytype == "reserve=1":
found_addr_rsv += 1
break
return found_addr, found_addr_chg, found_addr_rsv, hd_master_addr_ret
class WalletDumpTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = False
self.num_nodes = 1
self.extra_args = [["-keypool=90"]]
def setup_network(self, split=False):
self.nodes = start_nodes(self.num_nodes, self.options.tmpdir, self.extra_args)
def run_test (self):
tmpdir = self.options.tmpdir
# generate 20 addresses to compare against the dump
test_addr_count = 20
addrs = []
for i in range(0,test_addr_count):
addr = self.nodes[0].getnewaddress()
vaddr= self.nodes[0].validateaddress(addr) #required to get hd keypath
addrs.append(vaddr)
# Should be a no-op:
self.nodes[0].keypoolrefill()
# dump unencrypted wallet
self.nodes[0].dumpwallet(tmpdir + "/node0/wallet.unencrypted.dump")
found_addr, found_addr_chg, found_addr_rsv, hd_master_addr_unenc = \
read_dump(tmpdir + "/node0/wallet.unencrypted.dump", addrs, None)
assert_equal(found_addr, test_addr_count) # all keys must be in the dump
assert_equal(found_addr_chg, 50) # 50 blocks where mined
assert_equal(found_addr_rsv, 90 + 1) # keypool size (TODO: fix off-by-one)
#encrypt wallet, restart, unlock and dump
self.nodes[0].encryptwallet('test')
bitcoind_processes[0].wait()
self.nodes[0] = start_node(0, self.options.tmpdir, self.extra_args[0])
self.nodes[0].walletpassphrase('test', 10)
# Should be a no-op:
self.nodes[0].keypoolrefill()
self.nodes[0].dumpwallet(tmpdir + "/node0/wallet.encrypted.dump")
found_addr, found_addr_chg, found_addr_rsv, hd_master_addr_enc = \
read_dump(tmpdir + "/node0/wallet.encrypted.dump", addrs, hd_master_addr_unenc)
assert_equal(found_addr, test_addr_count)
assert_equal(found_addr_chg, 90 + 1 + 50) # old reserve keys are marked as change now
assert_equal(found_addr_rsv, 90 + 1) # keypool size (TODO: fix off-by-one)
if __name__ == '__main__':
WalletDumpTest().main ()

5
qa/rpc-tests/wallet.py

@ -18,9 +18,10 @@ class WalletTest (BitcoinTestFramework):
super().__init__() super().__init__()
self.setup_clean_chain = True self.setup_clean_chain = True
self.num_nodes = 4 self.num_nodes = 4
self.extra_args = [['-usehd={:d}'.format(i%2==0)] for i in range(4)]
def setup_network(self, split=False): def setup_network(self, split=False):
self.nodes = start_nodes(3, self.options.tmpdir) self.nodes = start_nodes(3, self.options.tmpdir, self.extra_args[:3])
connect_nodes_bi(self.nodes,0,1) connect_nodes_bi(self.nodes,0,1)
connect_nodes_bi(self.nodes,1,2) connect_nodes_bi(self.nodes,1,2)
connect_nodes_bi(self.nodes,0,2) connect_nodes_bi(self.nodes,0,2)
@ -154,7 +155,7 @@ class WalletTest (BitcoinTestFramework):
txid2 = self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 1) txid2 = self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 1)
sync_mempools(self.nodes) sync_mempools(self.nodes)
self.nodes.append(start_node(3, self.options.tmpdir)) self.nodes.append(start_node(3, self.options.tmpdir, self.extra_args[3]))
connect_nodes_bi(self.nodes, 0, 3) connect_nodes_bi(self.nodes, 0, 3)
sync_blocks(self.nodes) sync_blocks(self.nodes)

7
qa/rpc-tests/walletbackup.py

@ -45,12 +45,12 @@ class WalletBackupTest(BitcoinTestFramework):
super().__init__() super().__init__()
self.setup_clean_chain = True self.setup_clean_chain = True
self.num_nodes = 4 self.num_nodes = 4
# nodes 1, 2,3 are spenders, let's give them a keypool=100
self.extra_args = [["-keypool=100"], ["-keypool=100"], ["-keypool=100"], []]
# This mirrors how the network was setup in the bash test # This mirrors how the network was setup in the bash test
def setup_network(self, split=False): def setup_network(self, split=False):
# nodes 1, 2,3 are spenders, let's give them a keypool=100 self.nodes = start_nodes(self.num_nodes, self.options.tmpdir, self.extra_args)
extra_args = [["-keypool=100"], ["-keypool=100"], ["-keypool=100"], []]
self.nodes = start_nodes(self.num_nodes, self.options.tmpdir, extra_args)
connect_nodes(self.nodes[0], 3) connect_nodes(self.nodes[0], 3)
connect_nodes(self.nodes[1], 3) connect_nodes(self.nodes[1], 3)
connect_nodes(self.nodes[2], 3) connect_nodes(self.nodes[2], 3)
@ -79,6 +79,7 @@ class WalletBackupTest(BitcoinTestFramework):
# Must sync mempools before mining. # Must sync mempools before mining.
sync_mempools(self.nodes) sync_mempools(self.nodes)
self.nodes[3].generate(1) self.nodes[3].generate(1)
sync_blocks(self.nodes)
# As above, this mirrors the original bash test. # As above, this mirrors the original bash test.
def start_three(self): def start_three(self):

3
share/qt/extract_strings_qt.py

@ -1,4 +1,7 @@
#!/usr/bin/python #!/usr/bin/python
# Copyright (c) 2012-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.
''' '''
Extract _("...") strings for translation and convert to Qt stringdefs so that Extract _("...") strings for translation and convert to Qt stringdefs so that
they can be picked up by Qt linguist. they can be picked up by Qt linguist.

2
src/blockencodings.cpp

@ -75,7 +75,7 @@ ReadStatus PartiallyDownloadedBlock::InitData(const CBlockHeaderAndShortTxIDs& c
} }
prefilled_count = cmpctblock.prefilledtxn.size(); prefilled_count = cmpctblock.prefilledtxn.size();
// Calculate map of txids -> positions and check mempool to see what we have (or dont) // Calculate map of txids -> positions and check mempool to see what we have (or don't)
// Because well-formed cmpctblock messages will have a (relatively) uniform distribution // Because well-formed cmpctblock messages will have a (relatively) uniform distribution
// of short IDs, any highly-uneven distribution of elements can be safely treated as a // of short IDs, any highly-uneven distribution of elements can be safely treated as a
// READ_STATUS_FAILED. // READ_STATUS_FAILED.

10
src/chain.h

@ -137,15 +137,15 @@ enum BlockStatus: uint32_t {
BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS | BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS |
BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS, BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS,
BLOCK_HAVE_DATA = 8, //! full block available in blk*.dat BLOCK_HAVE_DATA = 8, //!< full block available in blk*.dat
BLOCK_HAVE_UNDO = 16, //! undo data available in rev*.dat BLOCK_HAVE_UNDO = 16, //!< undo data available in rev*.dat
BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO, BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO,
BLOCK_FAILED_VALID = 32, //! stage after last reached validness failed BLOCK_FAILED_VALID = 32, //!< stage after last reached validness failed
BLOCK_FAILED_CHILD = 64, //! descends from failed block BLOCK_FAILED_CHILD = 64, //!< descends from failed block
BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD, BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD,
BLOCK_OPT_WITNESS = 128, //! block data in blk*.data was received with a witness-enforcing client BLOCK_OPT_WITNESS = 128, //!< block data in blk*.data was received with a witness-enforcing client
}; };
/** The block chain is a tree shaped structure starting with the /** The block chain is a tree shaped structure starting with the

2
src/chainparams.cpp

@ -119,7 +119,7 @@ public:
vSeeds.push_back(CDNSSeedData("dashjr.org", "dnsseed.bitcoin.dashjr.org")); // Luke Dashjr vSeeds.push_back(CDNSSeedData("dashjr.org", "dnsseed.bitcoin.dashjr.org")); // Luke Dashjr
vSeeds.push_back(CDNSSeedData("bitcoinstats.com", "seed.bitcoinstats.com")); // Christian Decker vSeeds.push_back(CDNSSeedData("bitcoinstats.com", "seed.bitcoinstats.com")); // Christian Decker
vSeeds.push_back(CDNSSeedData("xf2.org", "bitseed.xf2.org")); // Jeff Garzik vSeeds.push_back(CDNSSeedData("xf2.org", "bitseed.xf2.org")); // Jeff Garzik
vSeeds.push_back(CDNSSeedData("bitcoin.jonasschnelli.ch", "seed.bitcoin.jonasschnelli.ch")); // Jonas Schnelli vSeeds.push_back(CDNSSeedData("bitcoin.jonasschnelli.ch", "seed.bitcoin.jonasschnelli.ch", true)); // Jonas Schnelli
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,0); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,0);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,5); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,5);

6
src/consensus/validation.h

@ -22,9 +22,9 @@ static const unsigned char REJECT_CHECKPOINT = 0x43;
class CValidationState { class CValidationState {
private: private:
enum mode_state { enum mode_state {
MODE_VALID, //! everything ok MODE_VALID, //!< everything ok
MODE_INVALID, //! network rule violation (DoS value may be set) MODE_INVALID, //!< network rule violation (DoS value may be set)
MODE_ERROR, //! run-time error MODE_ERROR, //!< run-time error
} mode; } mode;
int nDoS; int nDoS;
std::string strRejectReason; std::string strRejectReason;

2
src/httpserver.h

@ -35,7 +35,7 @@ void InterruptHTTPServer();
void StopHTTPServer(); void StopHTTPServer();
/** Handler for requests to a certain HTTP path */ /** Handler for requests to a certain HTTP path */
typedef boost::function<void(HTTPRequest* req, const std::string &)> HTTPRequestHandler; typedef boost::function<bool(HTTPRequest* req, const std::string &)> HTTPRequestHandler;
/** Register handler for prefix. /** Register handler for prefix.
* If multiple handlers match a prefix, the first-registered one will * If multiple handlers match a prefix, the first-registered one will
* be invoked. * be invoked.

4
src/indirectmap.h

@ -1,3 +1,7 @@
// 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_INDIRECTMAP_H #ifndef BITCOIN_INDIRECTMAP_H
#define BITCOIN_INDIRECTMAP_H #define BITCOIN_INDIRECTMAP_H

50
src/init.cpp

@ -379,7 +379,7 @@ std::string HelpMessage(HelpMessageMode mode)
strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") + strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") +
" " + _("Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway")); " " + _("Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway"));
strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY)); strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY));
strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY)); strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY));
strUsage += HelpMessageOpt("-maxuploadtarget=<n>", strprintf(_("Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)"), DEFAULT_MAX_UPLOAD_TARGET)); strUsage += HelpMessageOpt("-maxuploadtarget=<n>", strprintf(_("Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)"), DEFAULT_MAX_UPLOAD_TARGET));
#ifdef ENABLE_WALLET #ifdef ENABLE_WALLET
@ -510,6 +510,21 @@ static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex
boost::thread t(runCommand, strCmd); // thread runs free boost::thread t(runCommand, strCmd); // thread runs free
} }
static bool fHaveGenesis = false;
static boost::mutex cs_GenesisWait;
static CConditionVariable condvar_GenesisWait;
static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
{
if (pBlockIndex != NULL) {
{
boost::unique_lock<boost::mutex> lock_GenesisWait(cs_GenesisWait);
fHaveGenesis = true;
}
condvar_GenesisWait.notify_all();
}
}
struct CImportingNow struct CImportingNow
{ {
CImportingNow() { CImportingNow() {
@ -1216,7 +1231,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
// cache size calculations // cache size calculations
int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20); int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greated than nMaxDbcache nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
int64_t nBlockTreeDBCache = nTotalCache / 8; int64_t nBlockTreeDBCache = nTotalCache / 8;
nBlockTreeDBCache = std::min(nBlockTreeDBCache, (GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20); nBlockTreeDBCache = std::min(nBlockTreeDBCache, (GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20);
nTotalCache -= nBlockTreeDBCache; nTotalCache -= nBlockTreeDBCache;
@ -1286,7 +1301,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
break; break;
} }
if (!fReindex) { if (!fReindex && chainActive.Tip() != NULL) {
uiInterface.InitMessage(_("Rewinding blocks...")); uiInterface.InitMessage(_("Rewinding blocks..."));
if (!RewindBlockIndex(chainparams)) { if (!RewindBlockIndex(chainparams)) {
strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain"); strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain");
@ -1403,6 +1418,17 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
// ********************************************************* Step 10: import blocks // ********************************************************* Step 10: import blocks
if (!CheckDiskSpace())
return false;
// Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
// No locking, as this happens before any background thread is started.
if (chainActive.Tip() == NULL) {
uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait);
} else {
fHaveGenesis = true;
}
if (mapArgs.count("-blocknotify")) if (mapArgs.count("-blocknotify"))
uiInterface.NotifyBlockTip.connect(BlockNotifyCallback); uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
@ -1412,26 +1438,20 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
BOOST_FOREACH(const std::string& strFile, mapMultiArgs["-loadblock"]) BOOST_FOREACH(const std::string& strFile, mapMultiArgs["-loadblock"])
vImportFiles.push_back(strFile); vImportFiles.push_back(strFile);
} }
threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles)); threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
// Wait for genesis block to be processed // Wait for genesis block to be processed
bool fHaveGenesis = false; {
while (!fHaveGenesis && !fRequestShutdown) { boost::unique_lock<boost::mutex> lock(cs_GenesisWait);
{ while (!fHaveGenesis) {
LOCK(cs_main); condvar_GenesisWait.wait(lock);
fHaveGenesis = (chainActive.Tip() != NULL);
}
if (!fHaveGenesis) {
MilliSleep(10);
} }
uiInterface.NotifyBlockTip.disconnect(BlockNotifyGenesisWait);
} }
// ********************************************************* Step 11: start node // ********************************************************* Step 11: start node
if (!CheckDiskSpace())
return false;
if (!strErrors.str().empty()) if (!strErrors.str().empty())
return InitError(strErrors.str()); return InitError(strErrors.str());

17
src/main.cpp

@ -1183,7 +1183,7 @@ bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const C
// nSequence >= maxint-1 on all inputs. // nSequence >= maxint-1 on all inputs.
// //
// maxint-1 is picked to still allow use of nLockTime by // maxint-1 is picked to still allow use of nLockTime by
// non-replacable transactions. All inputs rather than just one // non-replaceable transactions. All inputs rather than just one
// is for the sake of multi-party protocols, where we don't // is for the sake of multi-party protocols, where we don't
// want a single party to be able to disable replacement. // want a single party to be able to disable replacement.
// //
@ -1998,7 +1998,7 @@ bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsVi
// is safe because block merkle hashes are still computed and checked, // is safe because block merkle hashes are still computed and checked,
// and any change will be caught at the next checkpoint. Of course, if // and any change will be caught at the next checkpoint. Of course, if
// the checkpoint is for a chain that's invalid due to false scriptSigs // the checkpoint is for a chain that's invalid due to false scriptSigs
// this optimisation would allow an invalid chain to be accepted. // this optimization would allow an invalid chain to be accepted.
if (fScriptChecks) { if (fScriptChecks) {
for (unsigned int i = 0; i < tx.vin.size(); i++) { for (unsigned int i = 0; i < tx.vin.size(); i++) {
const COutPoint &prevout = tx.vin[i].prevout; const COutPoint &prevout = tx.vin[i].prevout;
@ -2073,7 +2073,7 @@ bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uin
// Open history file to read // Open history file to read
CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION); CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
if (filein.IsNull()) if (filein.IsNull())
return error("%s: OpenBlockFile failed", __func__); return error("%s: OpenUndoFile failed", __func__);
// Read block // Read block
uint256 hashChecksum; uint256 hashChecksum;
@ -3962,7 +3962,7 @@ CBlockIndex * InsertBlockIndex(uint256 hash)
// Create new // Create new
CBlockIndex* pindexNew = new CBlockIndex(); CBlockIndex* pindexNew = new CBlockIndex();
if (!pindexNew) if (!pindexNew)
throw runtime_error("LoadBlockIndex(): new CBlockIndex failed"); throw runtime_error(std::string(__func__) + ": new CBlockIndex failed");
mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first); pindexNew->phashBlock = &((*mi).first);
@ -4339,8 +4339,6 @@ bool InitBlockIndex(const CChainParams& chainparams)
CBlockIndex *pindex = AddToBlockIndex(block); CBlockIndex *pindex = AddToBlockIndex(block);
if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
return error("LoadBlockIndex(): genesis block not accepted"); return error("LoadBlockIndex(): genesis block not accepted");
if (!ActivateBestChain(state, chainparams, &block))
return error("LoadBlockIndex(): genesis block cannot be activated");
// Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
return FlushStateToDisk(state, FLUSH_STATE_ALWAYS); return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
} catch (const std::runtime_error& e) { } catch (const std::runtime_error& e) {
@ -4831,7 +4829,7 @@ void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParam
{ {
// If a peer is asking for old blocks, we're almost guaranteed // If a peer is asking for old blocks, we're almost guaranteed
// they wont have a useful mempool to match against a compact block, // they wont have a useful mempool to match against a compact block,
// and we dont feel like constructing the object for them, so // and we don't feel like constructing the object for them, so
// instead we respond with the full, non-compact block. // instead we respond with the full, non-compact block.
if (mi->second->nHeight >= chainActive.Height() - 10) { if (mi->second->nHeight >= chainActive.Height() - 10) {
CBlockHeaderAndShortTxIDs cmpctblock(block); CBlockHeaderAndShortTxIDs cmpctblock(block);
@ -6161,6 +6159,11 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
} }
} }
else if (strCommand == NetMsgType::NOTFOUND) {
// We do not care about the NOTFOUND message, but logging an Unknown Command
// message would be undesirable as we transmit it ourselves.
}
else { else {
// Ignore unknown commands for extensibility // Ignore unknown commands for extensibility
LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id); LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);

2
src/main.h

@ -215,7 +215,7 @@ void UnregisterNodeSignals(CNodeSignals& nodeSignals);
* block is made active. Note that it does not, however, guarantee that the * block is made active. Note that it does not, however, guarantee that the
* specific block passed to it has been checked for validity! * specific block passed to it has been checked for validity!
* *
* @param[out] state This may be set to an Error state if any error occurred processing it, including during validation/connection/etc of otherwise unrelated blocks during reorganisation; or it may be set to an Invalid state if pblock is itself invalid (but this is not guaranteed even when the block is checked). If you want to *possibly* get feedback on whether pblock is valid, you must also install a CValidationInterface (see validationinterface.h) - this will have its BlockChecked method called whenever *any* block completes validation. * @param[out] state This may be set to an Error state if any error occurred processing it, including during validation/connection/etc of otherwise unrelated blocks during reorganization; or it may be set to an Invalid state if pblock is itself invalid (but this is not guaranteed even when the block is checked). If you want to *possibly* get feedback on whether pblock is valid, you must also install a CValidationInterface (see validationinterface.h) - this will have its BlockChecked method called whenever *any* block completes validation.
* @param[in] pfrom The node which we are receiving the block from; it is added to mapBlockSource and may be penalised if the block is invalid. * @param[in] pfrom The node which we are receiving the block from; it is added to mapBlockSource and may be penalised if the block is invalid.
* @param[in] pblock The block we want to process. * @param[in] pblock The block we want to process.
* @param[in] fForceProcessing Process this block even if unrequested; used for non-network block sources and whitelisted peers. * @param[in] fForceProcessing Process this block even if unrequested; used for non-network block sources and whitelisted peers.

6
src/net.cpp

@ -499,7 +499,7 @@ void CNode::PushVersion()
int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime()); int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0", 0), addr.nServices)); CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0", 0), addr.nServices));
CAddress addrMe = GetLocalAddress(&addr); CAddress addrMe = CAddress(CService(), nLocalServices);
GetRandBytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce)); GetRandBytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
if (fLogIPs) if (fLogIPs)
LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), id); LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), id);
@ -1707,7 +1707,7 @@ void ThreadOpenConnections()
if (nANow - addr.nLastTry < 600 && nTries < 30) if (nANow - addr.nLastTry < 600 && nTries < 30)
continue; continue;
// only consider nodes missing relevant services after 40 failed attemps // only consider nodes missing relevant services after 40 failed attempts
if ((addr.nServices & nRelevantServices) != nRelevantServices && nTries < 40) if ((addr.nServices & nRelevantServices) != nRelevantServices && nTries < 40)
continue; continue;
@ -2092,6 +2092,8 @@ void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler)
DumpBanlist(); DumpBanlist();
} }
uiInterface.InitMessage(_("Starting network threads..."));
fAddressesInitialized = true; fAddressesInitialized = true;
if (semOutbound == NULL) { if (semOutbound == NULL) {

2
src/primitives/transaction.cpp

@ -100,7 +100,7 @@ CAmount CTransaction::GetValueOut() const
{ {
nValueOut += it->nValue; nValueOut += it->nValue;
if (!MoneyRange(it->nValue) || !MoneyRange(nValueOut)) if (!MoneyRange(it->nValue) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut(): value out of range"); throw std::runtime_error(std::string(__func__) + ": value out of range");
} }
return nValueOut; return nValueOut;
} }

2
src/qt/paymentrequest.proto

@ -6,6 +6,8 @@
// https://en.bitcoin.it/wiki/Payment_Request // https://en.bitcoin.it/wiki/Payment_Request
// //
syntax = "proto2";
package payments; package payments;
option java_package = "org.bitcoin.protocols.payments"; option java_package = "org.bitcoin.protocols.payments";
option java_outer_classname = "Protos"; option java_outer_classname = "Protos";

4
src/qt/res/movies/makespinner.sh

@ -1,3 +1,7 @@
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
FRAMEDIR=$(dirname $0) FRAMEDIR=$(dirname $0)
for i in {0..35} for i in {0..35}
do do

5
src/qt/sendcoinsdialog.cpp

@ -592,6 +592,9 @@ void SendCoinsDialog::updateGlobalFeeVariables()
{ {
nTxConfirmTarget = defaultConfirmTarget - ui->sliderSmartFee->value(); nTxConfirmTarget = defaultConfirmTarget - ui->sliderSmartFee->value();
payTxFee = CFeeRate(0); payTxFee = CFeeRate(0);
// set nMinimumTotalFee to 0 to not accidentally pay a custom fee
CoinControlDialog::coinControl->nMinimumTotalFee = 0;
} }
else else
{ {
@ -790,7 +793,7 @@ void SendCoinsDialog::coinControlUpdateLabels()
ui->radioCustomAtLeast->setVisible(true); ui->radioCustomAtLeast->setVisible(true);
// only enable the feature if inputs are selected // only enable the feature if inputs are selected
ui->radioCustomAtLeast->setEnabled(CoinControlDialog::coinControl->HasSelected()); ui->radioCustomAtLeast->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked() &&CoinControlDialog::coinControl->HasSelected());
} }
else else
{ {

7
src/rpc/mining.cpp

@ -227,10 +227,11 @@ UniValue getmininginfo(const UniValue& params, bool fHelp)
" \"currentblockweight\": nnn, (numeric) The last block weight\n" " \"currentblockweight\": nnn, (numeric) The last block weight\n"
" \"currentblocktx\": nnn, (numeric) The last block transaction\n" " \"currentblocktx\": nnn, (numeric) The last block transaction\n"
" \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n" " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
" \"errors\": \"...\" (string) Current errors\n" " \"errors\": \"...\" (string) Current errors\n"
" \"networkhashps\": nnn, (numeric) The network hashes per second\n"
" \"pooledtx\": n (numeric) The size of the mem pool\n" " \"pooledtx\": n (numeric) The size of the mem pool\n"
" \"testnet\": true|false (boolean) If using testnet or not\n" " \"testnet\": true|false (boolean) If using testnet or not\n"
" \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n" " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
"}\n" "}\n"
"\nExamples:\n" "\nExamples:\n"
+ HelpExampleCli("getmininginfo", "") + HelpExampleCli("getmininginfo", "")
@ -650,7 +651,7 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp)
if (nMaxVersionPreVB >= 2) { if (nMaxVersionPreVB >= 2) {
// If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here // If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here
// Because BIP 34 changed how the generation transaction is serialised, we can only use version/force back to v2 blocks // Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks
// This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated // This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated
// Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated // Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated
aMutable.push_back("version/force"); aMutable.push_back("version/force");

2
src/rpc/net.cpp

@ -484,7 +484,7 @@ UniValue setban(const UniValue& params, bool fHelp)
"\nExamples:\n" "\nExamples:\n"
+ HelpExampleCli("setban", "\"192.168.0.6\" \"add\" 86400") + HelpExampleCli("setban", "\"192.168.0.6\" \"add\" 86400")
+ HelpExampleCli("setban", "\"192.168.0.0/24\" \"add\"") + HelpExampleCli("setban", "\"192.168.0.0/24\" \"add\"")
+ HelpExampleRpc("setban", "\"192.168.0.6\", \"add\" 86400") + HelpExampleRpc("setban", "\"192.168.0.6\", \"add\", 86400")
); );
CSubNet subNet; CSubNet subNet;

54
src/rpc/protocol.h

@ -38,18 +38,18 @@ enum RPCErrorCode
RPC_PARSE_ERROR = -32700, RPC_PARSE_ERROR = -32700,
//! General application defined errors //! General application defined errors
RPC_MISC_ERROR = -1, //! std::exception thrown in command handling RPC_MISC_ERROR = -1, //!< std::exception thrown in command handling
RPC_FORBIDDEN_BY_SAFE_MODE = -2, //! Server is in safe mode, and command is not allowed in safe mode RPC_FORBIDDEN_BY_SAFE_MODE = -2, //!< Server is in safe mode, and command is not allowed in safe mode
RPC_TYPE_ERROR = -3, //! Unexpected type was passed as parameter RPC_TYPE_ERROR = -3, //!< Unexpected type was passed as parameter
RPC_INVALID_ADDRESS_OR_KEY = -5, //! Invalid address or key RPC_INVALID_ADDRESS_OR_KEY = -5, //!< Invalid address or key
RPC_OUT_OF_MEMORY = -7, //! Ran out of memory during operation RPC_OUT_OF_MEMORY = -7, //!< Ran out of memory during operation
RPC_INVALID_PARAMETER = -8, //! Invalid, missing or duplicate parameter RPC_INVALID_PARAMETER = -8, //!< Invalid, missing or duplicate parameter
RPC_DATABASE_ERROR = -20, //! Database error RPC_DATABASE_ERROR = -20, //!< Database error
RPC_DESERIALIZATION_ERROR = -22, //! Error parsing or validating structure in raw format RPC_DESERIALIZATION_ERROR = -22, //!< Error parsing or validating structure in raw format
RPC_VERIFY_ERROR = -25, //! General error during transaction or block submission RPC_VERIFY_ERROR = -25, //!< General error during transaction or block submission
RPC_VERIFY_REJECTED = -26, //! Transaction or block was rejected by network rules RPC_VERIFY_REJECTED = -26, //!< Transaction or block was rejected by network rules
RPC_VERIFY_ALREADY_IN_CHAIN = -27, //! Transaction already in chain RPC_VERIFY_ALREADY_IN_CHAIN = -27, //!< Transaction already in chain
RPC_IN_WARMUP = -28, //! Client still warming up RPC_IN_WARMUP = -28, //!< Client still warming up
//! Aliases for backward compatibility //! Aliases for backward compatibility
RPC_TRANSACTION_ERROR = RPC_VERIFY_ERROR, RPC_TRANSACTION_ERROR = RPC_VERIFY_ERROR,
@ -57,23 +57,23 @@ enum RPCErrorCode
RPC_TRANSACTION_ALREADY_IN_CHAIN= RPC_VERIFY_ALREADY_IN_CHAIN, RPC_TRANSACTION_ALREADY_IN_CHAIN= RPC_VERIFY_ALREADY_IN_CHAIN,
//! P2P client errors //! P2P client errors
RPC_CLIENT_NOT_CONNECTED = -9, //! Bitcoin is not connected RPC_CLIENT_NOT_CONNECTED = -9, //!< Bitcoin is not connected
RPC_CLIENT_IN_INITIAL_DOWNLOAD = -10, //! Still downloading initial blocks RPC_CLIENT_IN_INITIAL_DOWNLOAD = -10, //!< Still downloading initial blocks
RPC_CLIENT_NODE_ALREADY_ADDED = -23, //! Node is already added RPC_CLIENT_NODE_ALREADY_ADDED = -23, //!< Node is already added
RPC_CLIENT_NODE_NOT_ADDED = -24, //! Node has not been added before RPC_CLIENT_NODE_NOT_ADDED = -24, //!< Node has not been added before
RPC_CLIENT_NODE_NOT_CONNECTED = -29, //! Node to disconnect not found in connected nodes RPC_CLIENT_NODE_NOT_CONNECTED = -29, //!< Node to disconnect not found in connected nodes
RPC_CLIENT_INVALID_IP_OR_SUBNET = -30, //! Invalid IP/Subnet RPC_CLIENT_INVALID_IP_OR_SUBNET = -30, //!< Invalid IP/Subnet
//! Wallet errors //! Wallet errors
RPC_WALLET_ERROR = -4, //! Unspecified problem with wallet (key not found etc.) RPC_WALLET_ERROR = -4, //!< Unspecified problem with wallet (key not found etc.)
RPC_WALLET_INSUFFICIENT_FUNDS = -6, //! Not enough funds in wallet or account RPC_WALLET_INSUFFICIENT_FUNDS = -6, //!< Not enough funds in wallet or account
RPC_WALLET_INVALID_ACCOUNT_NAME = -11, //! Invalid account name RPC_WALLET_INVALID_ACCOUNT_NAME = -11, //!< Invalid account name
RPC_WALLET_KEYPOOL_RAN_OUT = -12, //! Keypool ran out, call keypoolrefill first RPC_WALLET_KEYPOOL_RAN_OUT = -12, //!< Keypool ran out, call keypoolrefill first
RPC_WALLET_UNLOCK_NEEDED = -13, //! Enter the wallet passphrase with walletpassphrase first RPC_WALLET_UNLOCK_NEEDED = -13, //!< Enter the wallet passphrase with walletpassphrase first
RPC_WALLET_PASSPHRASE_INCORRECT = -14, //! The wallet passphrase entered was incorrect RPC_WALLET_PASSPHRASE_INCORRECT = -14, //!< The wallet passphrase entered was incorrect
RPC_WALLET_WRONG_ENC_STATE = -15, //! Command given in wrong wallet encryption state (encrypting an encrypted wallet etc.) RPC_WALLET_WRONG_ENC_STATE = -15, //!< Command given in wrong wallet encryption state (encrypting an encrypted wallet etc.)
RPC_WALLET_ENCRYPTION_FAILED = -16, //! Failed to encrypt the wallet RPC_WALLET_ENCRYPTION_FAILED = -16, //!< Failed to encrypt the wallet
RPC_WALLET_ALREADY_UNLOCKED = -17, //! Wallet is already unlocked RPC_WALLET_ALREADY_UNLOCKED = -17, //!< Wallet is already unlocked
}; };
std::string JSONRPCRequest(const std::string& strMethod, const UniValue& params, const UniValue& id); std::string JSONRPCRequest(const std::string& strMethod, const UniValue& params, const UniValue& id);

2
src/script/sign.h

@ -51,7 +51,7 @@ public:
MutableTransactionSignatureCreator(const CKeyStore* keystoreIn, const CMutableTransaction* txToIn, unsigned int nInIn, const CAmount& amount, int nHashTypeIn) : TransactionSignatureCreator(keystoreIn, &tx, nInIn, amount, nHashTypeIn), tx(*txToIn) {} MutableTransactionSignatureCreator(const CKeyStore* keystoreIn, const CMutableTransaction* txToIn, unsigned int nInIn, const CAmount& amount, int nHashTypeIn) : TransactionSignatureCreator(keystoreIn, &tx, nInIn, amount, nHashTypeIn), tx(*txToIn) {}
}; };
/** A signature creator that just produces 72-byte empty signatyres. */ /** A signature creator that just produces 72-byte empty signatures. */
class DummySignatureCreator : public BaseSignatureCreator { class DummySignatureCreator : public BaseSignatureCreator {
public: public:
DummySignatureCreator(const CKeyStore* keystoreIn) : BaseSignatureCreator(keystoreIn) {} DummySignatureCreator(const CKeyStore* keystoreIn) : BaseSignatureCreator(keystoreIn) {}

4
src/serialize.h

@ -322,8 +322,8 @@ uint64_t ReadCompactSize(Stream& is)
* 0: [0x00] 256: [0x81 0x00] * 0: [0x00] 256: [0x81 0x00]
* 1: [0x01] 16383: [0xFE 0x7F] * 1: [0x01] 16383: [0xFE 0x7F]
* 127: [0x7F] 16384: [0xFF 0x00] * 127: [0x7F] 16384: [0xFF 0x00]
* 128: [0x80 0x00] 16511: [0x80 0xFF 0x7F] * 128: [0x80 0x00] 16511: [0xFF 0x7F]
* 255: [0x80 0x7F] 65535: [0x82 0xFD 0x7F] * 255: [0x80 0x7F] 65535: [0x82 0xFE 0x7F]
* 2^32: [0x8E 0xFE 0xFE 0xFF 0x00] * 2^32: [0x8E 0xFE 0xFE 0xFF 0x00]
*/ */

21
src/test/README.md

@ -5,18 +5,15 @@ sense to simply use this framework rather than require developers to
configure some other framework (we want as few impediments to creating configure some other framework (we want as few impediments to creating
unit tests as possible). unit tests as possible).
The build system is setup to compile an executable called "test_bitcoin" The build system is setup to compile an executable called `test_bitcoin`
that runs all of the unit tests. The main source file is called that runs all of the unit tests. The main source file is called
test_bitcoin.cpp, which simply includes other files that contain the test_bitcoin.cpp. To add a new unit test file to our test suite you need
actual unit tests (outside of a couple required preprocessor to add the file to `src/Makefile.test.include`. The pattern is to create
directives). The pattern is to create one test file for each class or one test file for each class or source file for which you want to create
source file for which you want to create unit tests. The file naming unit tests. The file naming convention is `<source_filename>_tests.cpp`
convention is "<source_filename>_tests.cpp" and such files should wrap and such files should wrap their tests in a test suite
their tests in a test suite called "<source_filename>_tests". For an called `<source_filename>_tests`. For an example of this pattern,
examples of this pattern, examine uint160_tests.cpp and examine `uint256_tests.cpp`.
uint256_tests.cpp.
Add the source files to /src/Makefile.test.include to add them to the build.
For further reading, I found the following website to be helpful in For further reading, I found the following website to be helpful in
explaining how the boost unit test framework works: explaining how the boost unit test framework works:
@ -31,5 +28,5 @@ example, to run just the getarg_tests verbosely:
test_bitcoin --run_test=getarg_tests/doubledash test_bitcoin --run_test=getarg_tests/doubledash
Run test_bitcoin --help for the full list. Run `test_bitcoin --help` for the full list.

2
src/test/arith_uint256_tests.cpp

@ -112,7 +112,7 @@ BOOST_AUTO_TEST_CASE( basics ) // constructors, equality, inequality
BOOST_CHECK( (R1L & arith_uint256("0xffffffffffffffff")) == arith_uint256(R1LLow64)); BOOST_CHECK( (R1L & arith_uint256("0xffffffffffffffff")) == arith_uint256(R1LLow64));
BOOST_CHECK(ZeroL == arith_uint256(0)); BOOST_CHECK(ZeroL == arith_uint256(0));
BOOST_CHECK(OneL == arith_uint256(1)); BOOST_CHECK(OneL == arith_uint256(1));
BOOST_CHECK(arith_uint256("0xffffffffffffffff") = arith_uint256(0xffffffffffffffffULL)); BOOST_CHECK(arith_uint256("0xffffffffffffffff") == arith_uint256(0xffffffffffffffffULL));
// Assignment (from base_uint) // Assignment (from base_uint)
arith_uint256 tmpL = ~ZeroL; BOOST_CHECK(tmpL == ~ZeroL); arith_uint256 tmpL = ~ZeroL; BOOST_CHECK(tmpL == ~ZeroL);

4
src/test/miner_tests.cpp

@ -181,9 +181,7 @@ void TestPackageSelection(const CChainParams& chainparams, CScript scriptPubKey,
// NOTE: These tests rely on CreateNewBlock doing its own self-validation! // NOTE: These tests rely on CreateNewBlock doing its own self-validation!
BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
{ {
// Disable size accounting (CPFP does not support it) // Note that by default, these tests run with size accounting enabled.
mapArgs["-blockmaxsize"] = strprintf("%u", MAX_BLOCK_SERIALIZED_SIZE);
const CChainParams& chainparams = Params(CBaseChainParams::MAIN); const CChainParams& chainparams = Params(CBaseChainParams::MAIN);
CScript scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG; CScript scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
CBlockTemplate *pblocktemplate; CBlockTemplate *pblocktemplate;

5
src/test/test_bitcoin.cpp

@ -60,6 +60,11 @@ TestingSetup::TestingSetup(const std::string& chainName) : BasicTestingSetup(cha
pcoinsdbview = new CCoinsViewDB(1 << 23, true); pcoinsdbview = new CCoinsViewDB(1 << 23, true);
pcoinsTip = new CCoinsViewCache(pcoinsdbview); pcoinsTip = new CCoinsViewCache(pcoinsdbview);
InitBlockIndex(chainparams); InitBlockIndex(chainparams);
{
CValidationState state;
bool ok = ActivateBestChain(state, chainparams);
BOOST_CHECK(ok);
}
nScriptCheckThreads = 3; nScriptCheckThreads = 3;
for (int i=0; i < nScriptCheckThreads-1; i++) for (int i=0; i < nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck); threadGroup.create_thread(&ThreadScriptCheck);

4
src/wallet/db.cpp

@ -43,7 +43,7 @@ void CDBEnv::EnvShutdown()
if (ret != 0) if (ret != 0)
LogPrintf("CDBEnv::EnvShutdown: Error %d shutting down database environment: %s\n", ret, DbEnv::strerror(ret)); LogPrintf("CDBEnv::EnvShutdown: Error %d shutting down database environment: %s\n", ret, DbEnv::strerror(ret));
if (!fMockDb) if (!fMockDb)
DbEnv(0).remove(strPath.c_str(), 0); DbEnv((u_int32_t)0).remove(strPath.c_str(), 0);
} }
void CDBEnv::Reset() void CDBEnv::Reset()
@ -284,7 +284,7 @@ CDB::CDB(const std::string& strFilename, const char* pszMode, bool fFlushOnClose
pdb = NULL; pdb = NULL;
--bitdb.mapFileUseCount[strFile]; --bitdb.mapFileUseCount[strFile];
strFile = ""; strFile = "";
throw runtime_error(strprintf("CDB: Error %d, can't open database %s", ret, strFile)); throw runtime_error(strprintf("CDB: Error %d, can't open database %s", ret, strFilename));
} }
if (fCreate && !Exists(string("version"))) { if (fCreate && !Exists(string("version"))) {

2
src/wallet/rpcwallet.cpp

@ -1088,6 +1088,8 @@ UniValue addwitnessaddress(const UniValue& params, bool fHelp)
throw JSONRPCError(RPC_WALLET_ERROR, "Public key or redeemscript not known to wallet"); throw JSONRPCError(RPC_WALLET_ERROR, "Public key or redeemscript not known to wallet");
} }
pwalletMain->SetAddressBook(w.result, "", "receive");
return CBitcoinAddress(w.result).ToString(); return CBitcoinAddress(w.result).ToString();
} }

4
src/wallet/test/wallet_test_fixture.cpp

@ -1,3 +1,7 @@
// 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 "wallet/test/wallet_test_fixture.h" #include "wallet/test/wallet_test_fixture.h"
#include "rpc/server.h" #include "rpc/server.h"

38
src/wallet/wallet.cpp

@ -108,7 +108,7 @@ CPubKey CWallet::GenerateNewKey()
// try to get the master key // try to get the master key
if (!GetKey(hdChain.masterKeyID, key)) if (!GetKey(hdChain.masterKeyID, key))
throw std::runtime_error("CWallet::GenerateNewKey(): Master key not found"); throw std::runtime_error(std::string(__func__) + ": Master key not found");
masterKey.SetMaster(key.begin(), key.size()); masterKey.SetMaster(key.begin(), key.size());
@ -135,7 +135,7 @@ CPubKey CWallet::GenerateNewKey()
// update the chain model in the database // update the chain model in the database
if (!CWalletDB(strWalletFile).WriteHDChain(hdChain)) if (!CWalletDB(strWalletFile).WriteHDChain(hdChain))
throw std::runtime_error("CWallet::GenerateNewKey(): Writing HD chain model failed"); throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
} else { } else {
secret.MakeNewKey(fCompressed); secret.MakeNewKey(fCompressed);
} }
@ -152,7 +152,7 @@ CPubKey CWallet::GenerateNewKey()
nTimeFirstKey = nCreationTime; nTimeFirstKey = nCreationTime;
if (!AddKeyPubKey(secret, pubkey)) if (!AddKeyPubKey(secret, pubkey))
throw std::runtime_error("CWallet::GenerateNewKey(): AddKey failed"); throw std::runtime_error(std::string(__func__) + ": AddKey failed");
return pubkey; return pubkey;
} }
@ -1093,7 +1093,7 @@ isminetype CWallet::IsMine(const CTxOut& txout) const
CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
{ {
if (!MoneyRange(txout.nValue)) if (!MoneyRange(txout.nValue))
throw std::runtime_error("CWallet::GetCredit(): value out of range"); throw std::runtime_error(std::string(__func__) + ": value out of range");
return ((IsMine(txout) & filter) ? txout.nValue : 0); return ((IsMine(txout) & filter) ? txout.nValue : 0);
} }
@ -1122,7 +1122,7 @@ bool CWallet::IsChange(const CTxOut& txout) const
CAmount CWallet::GetChange(const CTxOut& txout) const CAmount CWallet::GetChange(const CTxOut& txout) const
{ {
if (!MoneyRange(txout.nValue)) if (!MoneyRange(txout.nValue))
throw std::runtime_error("CWallet::GetChange(): value out of range"); throw std::runtime_error(std::string(__func__) + ": value out of range");
return (IsChange(txout) ? txout.nValue : 0); return (IsChange(txout) ? txout.nValue : 0);
} }
@ -1146,7 +1146,7 @@ CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) co
{ {
nDebit += GetDebit(txin, filter); nDebit += GetDebit(txin, filter);
if (!MoneyRange(nDebit)) if (!MoneyRange(nDebit))
throw std::runtime_error("CWallet::GetDebit(): value out of range"); throw std::runtime_error(std::string(__func__) + ": value out of range");
} }
return nDebit; return nDebit;
} }
@ -1158,7 +1158,7 @@ CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) c
{ {
nCredit += GetCredit(txout, filter); nCredit += GetCredit(txout, filter);
if (!MoneyRange(nCredit)) if (!MoneyRange(nCredit))
throw std::runtime_error("CWallet::GetCredit(): value out of range"); throw std::runtime_error(std::string(__func__) + ": value out of range");
} }
return nCredit; return nCredit;
} }
@ -1170,7 +1170,7 @@ CAmount CWallet::GetChange(const CTransaction& tx) const
{ {
nChange += GetChange(txout); nChange += GetChange(txout);
if (!MoneyRange(nChange)) if (!MoneyRange(nChange))
throw std::runtime_error("CWallet::GetChange(): value out of range"); throw std::runtime_error(std::string(__func__) + ": value out of range");
} }
return nChange; return nChange;
} }
@ -1199,7 +1199,7 @@ CPubKey CWallet::GenerateNewHDMasterKey()
// write the key&metadata to the database // write the key&metadata to the database
if (!AddKeyPubKey(key, pubkey)) if (!AddKeyPubKey(key, pubkey))
throw std::runtime_error("CWallet::GenerateNewKey(): AddKey failed"); throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
} }
return pubkey; return pubkey;
@ -1226,7 +1226,7 @@ bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
{ {
LOCK(cs_wallet); LOCK(cs_wallet);
if (!memonly && !CWalletDB(strWalletFile).WriteHDChain(chain)) if (!memonly && !CWalletDB(strWalletFile).WriteHDChain(chain))
throw runtime_error("AddHDChain(): writing chain failed"); throw runtime_error(std::string(__func__) + ": writing chain failed");
hdChain = chain; hdChain = chain;
return true; return true;
@ -2202,6 +2202,7 @@ bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wt
nChangePosInOut = nChangePosRequest; nChangePosInOut = nChangePosRequest;
txNew.vin.clear(); txNew.vin.clear();
txNew.vout.clear(); txNew.vout.clear();
txNew.wit.SetNull();
wtxNew.fFromMe = true; wtxNew.fFromMe = true;
bool fFirst = true; bool fFirst = true;
@ -2713,7 +2714,7 @@ bool CWallet::TopUpKeyPool(unsigned int kpSize)
if (!setKeyPool.empty()) if (!setKeyPool.empty())
nEnd = *(--setKeyPool.end()) + 1; nEnd = *(--setKeyPool.end()) + 1;
if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
throw runtime_error("TopUpKeyPool(): writing generated key failed"); throw runtime_error(std::string(__func__) + ": writing generated key failed");
setKeyPool.insert(nEnd); setKeyPool.insert(nEnd);
LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size()); LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
} }
@ -2740,9 +2741,9 @@ void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
nIndex = *(setKeyPool.begin()); nIndex = *(setKeyPool.begin());
setKeyPool.erase(setKeyPool.begin()); setKeyPool.erase(setKeyPool.begin());
if (!walletdb.ReadPool(nIndex, keypool)) if (!walletdb.ReadPool(nIndex, keypool))
throw runtime_error("ReserveKeyFromKeyPool(): read failed"); throw runtime_error(std::string(__func__) + ": read failed");
if (!HaveKey(keypool.vchPubKey.GetID())) if (!HaveKey(keypool.vchPubKey.GetID()))
throw runtime_error("ReserveKeyFromKeyPool(): unknown key in key pool"); throw runtime_error(std::string(__func__) + ": unknown key in key pool");
assert(keypool.vchPubKey.IsValid()); assert(keypool.vchPubKey.IsValid());
LogPrintf("keypool reserve %d\n", nIndex); LogPrintf("keypool reserve %d\n", nIndex);
} }
@ -2801,7 +2802,7 @@ int64_t CWallet::GetOldestKeyPoolTime()
CWalletDB walletdb(strWalletFile); CWalletDB walletdb(strWalletFile);
int64_t nIndex = *(setKeyPool.begin()); int64_t nIndex = *(setKeyPool.begin());
if (!walletdb.ReadPool(nIndex, keypool)) if (!walletdb.ReadPool(nIndex, keypool))
throw runtime_error("GetOldestKeyPoolTime(): read oldest key in keypool failed"); throw runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
assert(keypool.vchPubKey.IsValid()); assert(keypool.vchPubKey.IsValid());
return keypool.nTime; return keypool.nTime;
} }
@ -3028,11 +3029,11 @@ void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
{ {
CKeyPool keypool; CKeyPool keypool;
if (!walletdb.ReadPool(id, keypool)) if (!walletdb.ReadPool(id, keypool))
throw runtime_error("GetAllReserveKeyHashes(): read failed"); throw runtime_error(std::string(__func__) + ": read failed");
assert(keypool.vchPubKey.IsValid()); assert(keypool.vchPubKey.IsValid());
CKeyID keyID = keypool.vchPubKey.GetID(); CKeyID keyID = keypool.vchPubKey.GetID();
if (!HaveKey(keyID)) if (!HaveKey(keyID))
throw runtime_error("GetAllReserveKeyHashes(): unknown key in key pool"); throw runtime_error(std::string(__func__) + ": unknown key in key pool");
setAddress.insert(keyID); setAddress.insert(keyID);
} }
} }
@ -3139,7 +3140,7 @@ void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
mapKeyBirth[it->first] = it->second.nCreateTime; mapKeyBirth[it->first] = it->second.nCreateTime;
// map in which we'll infer heights of other keys // map in which we'll infer heights of other keys
CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock; std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
std::set<CKeyID> setKeys; std::set<CKeyID> setKeys;
GetKeys(setKeys); GetKeys(setKeys);
@ -3330,10 +3331,9 @@ bool CWallet::InitLoadWallet()
// Create new keyUser and set as default key // Create new keyUser and set as default key
if (GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && walletInstance->hdChain.masterKeyID.IsNull()) { if (GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && walletInstance->hdChain.masterKeyID.IsNull()) {
// generate a new master key // generate a new master key
CKey key;
CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey(); CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
if (!walletInstance->SetHDMasterKey(masterPubKey)) if (!walletInstance->SetHDMasterKey(masterPubKey))
throw std::runtime_error("CWallet::GenerateNewKey(): Storing master key failed"); throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
} }
CPubKey newDefaultKey; CPubKey newDefaultKey;
if (walletInstance->GetKeyFromPool(newDefaultKey)) { if (walletInstance->GetKeyFromPool(newDefaultKey)) {

4
src/wallet/walletdb.cpp

@ -215,7 +215,7 @@ void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountin
Dbc* pcursor = GetCursor(); Dbc* pcursor = GetCursor();
if (!pcursor) if (!pcursor)
throw runtime_error("CWalletDB::ListAccountCreditDebit(): cannot create DB cursor"); throw runtime_error(std::string(__func__) + ": cannot create DB cursor");
unsigned int fFlags = DB_SET_RANGE; unsigned int fFlags = DB_SET_RANGE;
while (true) while (true)
{ {
@ -231,7 +231,7 @@ void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountin
else if (ret != 0) else if (ret != 0)
{ {
pcursor->close(); pcursor->close();
throw runtime_error("CWalletDB::ListAccountCreditDebit(): error scanning DB"); throw runtime_error(std::string(__func__) + ": error scanning DB");
} }
// Unserialize // Unserialize

2
src/zmq/zmqpublishnotifier.h

@ -12,7 +12,7 @@ class CBlockIndex;
class CZMQAbstractPublishNotifier : public CZMQAbstractNotifier class CZMQAbstractPublishNotifier : public CZMQAbstractNotifier
{ {
private: private:
uint32_t nSequence; //! upcounting per message sequence number uint32_t nSequence; //!< upcounting per message sequence number
public: public:

Loading…
Cancel
Save