diff --git a/.gitignore b/.gitignore index b2cb8c8..93a5b03 100644 --- a/.gitignore +++ b/.gitignore @@ -173,3 +173,4 @@ src/ohmcoin-cli src/ohmcoin-tx src/ohmcoind doc/Doxyfile +doc/Doxyfile diff --git a/.travis.yml b/.travis.yml index 02a9e5a..cf641a9 100755 --- a/.travis.yml +++ b/.travis.yml @@ -7,12 +7,13 @@ cache: - depends/built - depends/sdk-sources - $HOME/.ccache +stages: + - lint + - test env: global: - MAKEJOBS=-j3 - RUN_TESTS=true - - CHECK_DOC=1 - - CHECK_LOGPRINT=1 - BOOST_TEST_RANDOM=1$TRAVIS_BUILD_ID - CCACHE_SIZE=100M - CCACHE_TEMPDIR=/tmp/.ccache-temp @@ -22,7 +23,7 @@ env: - WINEDEBUG=fixme-all matrix: # ARM - - HOST=arm-linux-gnueabihf PACKAGES="g++-arm-linux-gnueabihf" CHECK_DOC=1 CHECK_LOGPRINT=1 GOAL="install" BITCOIN_CONFIG="--enable-glibc-back-compat --enable-reduce-exports" + - HOST=arm-linux-gnueabihf PACKAGES="g++-arm-linux-gnueabihf" GOAL="install" BITCOIN_CONFIG="--enable-glibc-back-compat --enable-reduce-exports" # Win32 - HOST=i686-w64-mingw32 DPKG_ADD_ARCH="i386" DEP_OPTS="NO_QT=1" PACKAGES="python3 nsis g++-mingw-w64-i686 wine1.6 bc" RUN_TESTS=true GOAL="install" BITCOIN_CONFIG="--enable-reduce-exports" # 32-bit + dash @@ -34,7 +35,7 @@ env: # No wallet # - HOST=x86_64-unknown-linux-gnu PACKAGES="python3" DEP_OPTS="NO_WALLET=1" RUN_TESTS=true GOAL="install" BITCOIN_CONFIG="--enable-glibc-back-compat --enable-reduce-exports" # Cross-Mac - - HOST=x86_64-apple-darwin11 PACKAGES="cmake imagemagick libcap-dev librsvg2-bin libz-dev libbz2-dev libtiff-tools python-dev" BITCOIN_CONFIG="--enable-gui --enable-reduce-exports" OSX_SDK=10.11 GOAL="deploy" + - HOST=x86_64-apple-darwin14 PACKAGES="cmake imagemagick libcap-dev librsvg2-bin libz-dev libbz2-dev libtiff-tools python3-dev python3-setuptools" BITCOIN_CONFIG="--enable-gui --enable-reduce-exports" OSX_SDK=10.11 GOAL="deploy"BITCOIN_CONFIG="--enable-gui --enable-reduce-exports" OSX_SDK=10.11 GOAL="deploy" before_install: - export PATH=$(echo $PATH | tr ':' "\n" | sed '/\/opt\/python/d' | tr "\n" ":" | sed "s|::|:|g") @@ -44,8 +45,6 @@ install: - if [ -n "$PACKAGES" ]; then travis_retry sudo apt-get update; fi - if [ -n "$PACKAGES" ]; then travis_retry sudo apt-get install --no-install-recommends --no-upgrade -qq $PACKAGES; fi before_script: - - if [ "$CHECK_DOC" = 1 ]; then contrib/devtools/check-doc.py; fi - - if [ "$CHECK_LOGPRINT" = 1 ]; then contrib/devtools/logprint-scanner.py; fi - unset CC; unset CXX - mkdir -p depends/SDKs depends/sdk-sources - if [ -n "$OSX_SDK" -a ! -f depends/sdk-sources/MacOSX${OSX_SDK}.sdk.tar.gz ]; then curl --location --fail $SDK_URL/MacOSX${OSX_SDK}.sdk.tar.gz -o depends/sdk-sources/MacOSX${OSX_SDK}.sdk.tar.gz; fi @@ -68,6 +67,25 @@ script: after_script: - echo $TRAVIS_COMMIT_RANGE - echo $TRAVIS_COMMIT_LOG -notifications: - slack: - secure: w22XjHoG/3xplxWzddS9Ma7i99Q/hq4FA3Q56xS+RtO2vlFgDT+eDzCppstdx96mn2/4e+/V1aiQ4E6GVEvJMeldqSUhPv9OBnKR0KJVAOwu4haNXt+0ZeQFt8lIndKB5cMVyOJkoq6peGoHNXslClM0lGuBn7g7VC2QPQYNWrJNrrGL7IiVb6fNOIKHWcC4URkzSvXAhO/WIqSSlmKxAAx0B2oEsM8LhdAbcjbp7Sm7zH87TIVGBZ7iTVuMc6B9+SfClbE8bBuRtvjTX57Q4UUZzn0zDtKdPdCte0oXdaQF4RdVim9mDodBGIpDo+avW4WL7EE+AK33fs94pwH5bu0LEandR/aeEvVpbSpQ2XsEKSe+6woizgl5i4GXFVZduJF62y/o1f+S/zC3qW9lIEEpiZc4PpX7pDy30X3p6S5nMrW7T/zNh+SjLhS1VP6XKdQtpD3WRCY4GKZYammZhk5RbOy3jTXAahIXuttWdhl/Q3Rb5VqfFJWlrG/qQXt73qOk2/DgJnABxXE6gnWO4MpHAq+kdomNR+nod4HeXI3DOk1wRuQRVoW1rSjiqQd6Db+TP56RKYgt4M4csOD0DG9G+W0AOtZkuKHTeoEtmQfkKFPZLYAQumv41cDN2UE9gKIECmvJSevj4sMCDTWtozKWqay/W4n2+cmhbzmGflY= +jobs: + include: + - stage: lint + sudo: false + cache: false + addons: + apt: + packages: + - python3-pip + - shellcheck + install: + - travis_retry pip3 install flake8 --user + before_script: + - git fetch --unshallow + script: + - contrib/devtools/git-subtree-check.sh src/univalue + # Remove this comment and the `#` from the following two lines when we merge proper subtree implementations for secp256k1 and leveldb + #- contrib/devtools/git-subtree-check.sh src/secp256k1 + #- contrib/devtools/git-subtree-check.sh src/leveldb + - contrib/devtools/check-doc.py + - contrib/devtools/logprint-scanner.py + - if [ "$TRAVIS_EVENT_TYPE" = "pull_request" ]; then contrib/devtools/lint-whitespace.sh; fi diff --git a/Makefile.am b/Makefile.am index 1800903..af520d9 100755 --- a/Makefile.am +++ b/Makefile.am @@ -225,5 +225,24 @@ CLEANFILES = $(OSX_DMG) $(BITCOIN_WIN_INSTALLER) .INTERMEDIATE: $(COVERAGE_INFO) -clean-local: - rm -rf test_ohmcoin.coverage/ total.coverage/ $(OSX_APP) +DISTCHECK_CONFIGURE_FLAGS = --enable-man + +doc/doxygen/.stamp: doc/Doxyfile FORCE + $(MKDIR_P) $(@D) + $(DOXYGEN) $^ + $(AM_V_at) touch $@ + +if HAVE_DOXYGEN +docs: doc/doxygen/.stamp +else +docs: + @echo "error: doxygen not found" +endif + +clean-docs: + rm -rf doc/doxygen + +clean-local: clean-docs + rm -rf coverage_percent.txt test_bitcoin.coverage/ total.coverage/ fuzz.coverage/ test/tmp/ cache/ $(OSX_APP) + rm -rf test/functional/__pycache__ test/functional/test_framework/__pycache__ test/cache share/rpcauth/__pycache__ + rm -rf osx_volname dist/ dpi36.background.tiff dpi72.background.tiff background.tiff background.tiff.png background.tiff@2x.png diff --git a/build-aux/m4/bitcoin_qt.m4 b/build-aux/m4/bitcoin_qt.m4 index e32135d..25e1cb5 100755 --- a/build-aux/m4/bitcoin_qt.m4 +++ b/build-aux/m4/bitcoin_qt.m4 @@ -53,8 +53,8 @@ dnl CAUTION: Do not use this inside of a conditional. AC_DEFUN([BITCOIN_QT_INIT],[ dnl enable qt support AC_ARG_WITH([gui], - [AS_HELP_STRING([--with-gui@<:@=no|qt4|qt5|auto@:>@], - [build ohmcoin-qt GUI (default=auto, qt5 tried first)])], + [AS_HELP_STRING([--with-gui@<:@=no|qt5|auto@:>@], + [build ohmcoin-qt GUI (default=auto)])], [ bitcoin_qt_want_version=$withval if test "x$bitcoin_qt_want_version" = xyes; then @@ -63,19 +63,17 @@ AC_DEFUN([BITCOIN_QT_INIT],[ fi ], [bitcoin_qt_want_version=auto]) - AC_ARG_WITH([qt-incdir],[AS_HELP_STRING([--with-qt-incdir=INC_DIR],[specify qt include path (overridden by pkgconfig)])], [qt_include_path=$withval], []) AC_ARG_WITH([qt-libdir],[AS_HELP_STRING([--with-qt-libdir=LIB_DIR],[specify qt lib path (overridden by pkgconfig)])], [qt_lib_path=$withval], []) AC_ARG_WITH([qt-plugindir],[AS_HELP_STRING([--with-qt-plugindir=PLUGIN_DIR],[specify qt plugin path (overridden by pkgconfig)])], [qt_plugin_path=$withval], []) AC_ARG_WITH([qt-translationdir],[AS_HELP_STRING([--with-qt-translationdir=PLUGIN_DIR],[specify qt translation path (overridden by pkgconfig)])], [qt_translation_path=$withval], []) + AC_ARG_WITH([qt-svgdir],[AS_HELP_STRING([--with-qt-svgdir=PLUGIN_DIR],[specify qt svg path (overridden by pkgconfig)])], [qt_svg_path=$withval], []) AC_ARG_WITH([qt-bindir],[AS_HELP_STRING([--with-qt-bindir=BIN_DIR],[specify qt bin path])], [qt_bin_path=$withval], []) - AC_ARG_WITH([qtdbus], [AS_HELP_STRING([--with-qtdbus], [enable DBus support (default is yes if qt is enabled and QtDBus is found)])], [use_dbus=$withval], [use_dbus=auto]) - AC_SUBST(QT_TRANSLATION_DIR,$qt_translation_path) ]) @@ -88,24 +86,20 @@ dnl Outputs: Sets variables for all qt-related tools. dnl Outputs: bitcoin_enable_qt, bitcoin_enable_qt_dbus, bitcoin_enable_qt_test AC_DEFUN([BITCOIN_QT_CONFIGURE],[ use_pkgconfig=$1 - if test "x$use_pkgconfig" = x; then use_pkgconfig=yes fi - if test "x$use_pkgconfig" = xyes; then - BITCOIN_QT_CHECK([_BITCOIN_QT_FIND_LIBS_WITH_PKGCONFIG([$2])]) + BITCOIN_QT_CHECK([_BITCOIN_QT_FIND_LIBS_WITH_PKGCONFIG]) else BITCOIN_QT_CHECK([_BITCOIN_QT_FIND_LIBS_WITHOUT_PKGCONFIG]) fi - dnl This is ugly and complicated. Yuck. Works as follows: - dnl We can't discern whether Qt4 builds are static or not. For Qt5, we can - dnl check a header to find out. When Qt is built statically, some plugins must - dnl be linked into the final binary as well. These plugins have changed between - dnl Qt4 and Qt5. With Qt5, languages moved into core and the WindowsIntegration - dnl plugin was added. Since we can't tell if Qt4 is static or not, it is - dnl assumed for windows builds. + dnl For Qt5, we can check a header to find out whether Qt is build + dnl statically. When Qt is built statically, some plugins must be linked into + dnl the final binary as well. + dnl With Qt5, languages moved into core and the WindowsIntegration plugin was + dnl added. dnl _BITCOIN_QT_CHECK_STATIC_PLUGINS does a quick link-check and appends the dnl results to QT_LIBS. BITCOIN_QT_CHECK([ @@ -113,66 +107,50 @@ AC_DEFUN([BITCOIN_QT_CONFIGURE],[ TEMP_CXXFLAGS=$CXXFLAGS CPPFLAGS="$QT_INCLUDES $CPPFLAGS" CXXFLAGS="$PIC_FLAGS $CXXFLAGS" - if test "x$bitcoin_qt_got_major_vers" = x5; then - TEMP_CPPFLAGS="$TEMP_CPPFLAGS -DHAVE_QT5" - _BITCOIN_QT_IS_STATIC - if test "x$bitcoin_cv_static_qt" = xyes; then - _BITCOIN_QT_FIND_STATIC_PLUGINS - AC_DEFINE(QT_STATICPLUGIN, 1, [Define this symbol if qt plugins are static]) - AC_CACHE_CHECK(for Qt < 5.4, bitcoin_cv_need_acc_widget,[ - AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ - #include - #ifndef QT_VERSION - # include - #endif - ]], - [[ - #if QT_VERSION >= 0x050400 - choke - #endif - ]])], - [bitcoin_cv_need_acc_widget=yes], - [bitcoin_cv_need_acc_widget=no]) - ]) - if test "x$bitcoin_cv_need_acc_widget" = xyes; then - _BITCOIN_QT_CHECK_STATIC_PLUGINS([Q_IMPORT_PLUGIN(AccessibleFactory)], [-lqtaccessiblewidgets]) - fi - _BITCOIN_QT_CHECK_STATIC_PLUGINS([Q_IMPORT_PLUGIN(QMinimalIntegrationPlugin)],[-lqminimal]) - AC_DEFINE(QT_QPA_PLATFORM_MINIMAL, 1, [Define this symbol if the minimal qt platform exists]) - if test "x$TARGET_OS" = xwindows; then - _BITCOIN_QT_CHECK_STATIC_PLUGINS([Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)],[-lqwindows]) - AC_DEFINE(QT_QPA_PLATFORM_WINDOWS, 1, [Define this symbol if the qt platform is windows]) - elif test "x$TARGET_OS" = xlinux; then - _BITCOIN_QT_CHECK_STATIC_PLUGINS([Q_IMPORT_PLUGIN(QXcbIntegrationPlugin)],[-lqxcb -lxcb-static]) - AC_DEFINE(QT_QPA_PLATFORM_XCB, 1, [Define this symbol if the qt platform is xcb]) - elif test "x$TARGET_OS" = xdarwin; then - AX_CHECK_LINK_FLAG([[-framework IOKit]],[QT_LIBS="$QT_LIBS -framework IOKit"],[AC_MSG_ERROR(could not iokit framework)]) - _BITCOIN_QT_CHECK_STATIC_PLUGINS([Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin)],[-lqcocoa]) - AC_DEFINE(QT_QPA_PLATFORM_COCOA, 1, [Define this symbol if the qt platform is cocoa]) - fi + _BITCOIN_QT_IS_STATIC + if test "x$bitcoin_cv_static_qt" = xyes; then + _BITCOIN_QT_FIND_STATIC_PLUGINS + AC_DEFINE(QT_STATICPLUGIN, 1, [Define this symbol if qt plugins are static]) + AC_CACHE_CHECK(for Qt < 5.4, bitcoin_cv_need_acc_widget,[ + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ + #include + #ifndef QT_VERSION + # include + #endif + ]], + [[ + #if QT_VERSION >= 0x050400 + choke + #endif + ]])], + [bitcoin_cv_need_acc_widget=yes], + [bitcoin_cv_need_acc_widget=no]) + ]) + if test "x$bitcoin_cv_need_acc_widget" = xyes; then + _BITCOIN_QT_CHECK_STATIC_PLUGINS([Q_IMPORT_PLUGIN(AccessibleFactory)], [-lqtaccessiblewidgets]) fi - else + _BITCOIN_QT_CHECK_STATIC_PLUGINS([Q_IMPORT_PLUGIN(QMinimalIntegrationPlugin)],[-lqminimal]) + AC_DEFINE(QT_QPA_PLATFORM_MINIMAL, 1, [Define this symbol if the minimal qt platform exists]) + _BITCOIN_QT_CHECK_STATIC_PLUGINS([Q_IMPORT_PLUGIN(QSvgPlugin)],[-lqsvg]) + _BITCOIN_QT_CHECK_STATIC_PLUGINS([Q_IMPORT_PLUGIN(QSvgIconPlugin)],[-lqsvgicon]) if test "x$TARGET_OS" = xwindows; then - AC_DEFINE(QT_STATICPLUGIN, 1, [Define this symbol if qt plugins are static]) - _BITCOIN_QT_CHECK_STATIC_PLUGINS([ - Q_IMPORT_PLUGIN(qcncodecs) - Q_IMPORT_PLUGIN(qjpcodecs) - Q_IMPORT_PLUGIN(qtwcodecs) - Q_IMPORT_PLUGIN(qkrcodecs) - Q_IMPORT_PLUGIN(AccessibleFactory)], - [-lqcncodecs -lqjpcodecs -lqtwcodecs -lqkrcodecs -lqtaccessiblewidgets]) + _BITCOIN_QT_CHECK_STATIC_PLUGINS([Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)],[-lqwindows]) + AC_DEFINE(QT_QPA_PLATFORM_WINDOWS, 1, [Define this symbol if the qt platform is windows]) + elif test "x$TARGET_OS" = xlinux; then + _BITCOIN_QT_CHECK_STATIC_PLUGINS([Q_IMPORT_PLUGIN(QXcbIntegrationPlugin)],[-lqxcb -lxcb-static]) + AC_DEFINE(QT_QPA_PLATFORM_XCB, 1, [Define this symbol if the qt platform is xcb]) + elif test "x$TARGET_OS" = xdarwin; then + AX_CHECK_LINK_FLAG([[-framework IOKit]],[QT_LIBS="$QT_LIBS -framework IOKit"],[AC_MSG_ERROR(could not iokit framework)]) + _BITCOIN_QT_CHECK_STATIC_PLUGINS([Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin)],[-lqcocoa]) + AC_DEFINE(QT_QPA_PLATFORM_COCOA, 1, [Define this symbol if the qt platform is cocoa]) fi fi CPPFLAGS=$TEMP_CPPFLAGS CXXFLAGS=$TEMP_CXXFLAGS ]) - if test "x$use_pkgconfig$qt_bin_path" = xyes; then - if test "x$bitcoin_qt_got_major_vers" = x5; then - qt_bin_path="`$PKG_CONFIG --variable=host_bins Qt5Core 2>/dev/null`" - fi + qt_bin_path="`$PKG_CONFIG --variable=host_bins Qt5Core 2>/dev/null`" fi - if test "x$use_hardening" != xno; then BITCOIN_QT_CHECK([ AC_MSG_CHECKING(whether -fPIE can be used with this Qt config) @@ -219,13 +197,11 @@ AC_DEFUN([BITCOIN_QT_CONFIGURE],[ CPPFLAGS=$TEMP_CPPFLAGS ]) fi - - BITCOIN_QT_PATH_PROGS([MOC], [moc-qt${bitcoin_qt_got_major_vers} moc${bitcoin_qt_got_major_vers} moc], $qt_bin_path) - BITCOIN_QT_PATH_PROGS([UIC], [uic-qt${bitcoin_qt_got_major_vers} uic${bitcoin_qt_got_major_vers} uic], $qt_bin_path) - BITCOIN_QT_PATH_PROGS([RCC], [rcc-qt${bitcoin_qt_got_major_vers} rcc${bitcoin_qt_got_major_vers} rcc], $qt_bin_path) - BITCOIN_QT_PATH_PROGS([LRELEASE], [lrelease-qt${bitcoin_qt_got_major_vers} lrelease${bitcoin_qt_got_major_vers} lrelease], $qt_bin_path) - BITCOIN_QT_PATH_PROGS([LUPDATE], [lupdate-qt${bitcoin_qt_got_major_vers} lupdate${bitcoin_qt_got_major_vers} lupdate],$qt_bin_path, yes) - + BITCOIN_QT_PATH_PROGS([MOC], [moc-qt5 moc5 moc], $qt_bin_path) + BITCOIN_QT_PATH_PROGS([UIC], [uic-qt5 uic5 uic], $qt_bin_path) + BITCOIN_QT_PATH_PROGS([RCC], [rcc-qt5 rcc5 rcc], $qt_bin_path) + BITCOIN_QT_PATH_PROGS([LRELEASE], [lrelease-qt5 lrelease5 lrelease], $qt_bin_path) + BITCOIN_QT_PATH_PROGS([LUPDATE], [lupdate-qt5 lupdate5 lupdate],$qt_bin_path, yes) MOC_DEFS='-DHAVE_CONFIG_H -I$(srcdir)' case $host in *darwin*) @@ -240,8 +216,6 @@ AC_DEFUN([BITCOIN_QT_CONFIGURE],[ AX_CHECK_LINK_FLAG([[-mwindows]],[QT_LDFLAGS="$QT_LDFLAGS -mwindows"],[AC_MSG_WARN(-mwindows linker support not detected)]) ]) esac - - dnl enable qt support AC_MSG_CHECKING(whether to build ]AC_PACKAGE_NAME[ GUI) BITCOIN_QT_CHECK([ @@ -263,8 +237,7 @@ AC_DEFUN([BITCOIN_QT_CONFIGURE],[ ],[ bitcoin_enable_qt=no ]) - AC_MSG_RESULT([$bitcoin_enable_qt (Qt${bitcoin_qt_got_major_vers})]) - + AC_MSG_RESULT([$bitcoin_enable_qt (Qt5)]) AC_SUBST(QT_PIE_FLAGS) AC_SUBST(QT_INCLUDES) AC_SUBST(QT_LIBS) @@ -273,14 +246,12 @@ AC_DEFUN([BITCOIN_QT_CONFIGURE],[ AC_SUBST(QT_DBUS_LIBS) AC_SUBST(QT_TEST_INCLUDES) AC_SUBST(QT_TEST_LIBS) - AC_SUBST(QT_SELECT, qt${bitcoin_qt_got_major_vers}) + AC_SUBST(QT_SELECT, qt5) AC_SUBST(MOC_DEFS) ]) - dnl All macros below are internal and should _not_ be used from the main dnl configure.ac. dnl ---- - dnl Internal. Check if the included version of Qt is Qt5. dnl Requires: INCLUDES must be populated as necessary. dnl Output: bitcoin_cv_qt5=yes|no @@ -293,21 +264,18 @@ AC_DEFUN([_BITCOIN_QT_CHECK_QT5],[ #endif ]], [[ - #if QT_VERSION < 0x050000 + #if QT_VERSION < 0x050000 || QT_VERSION_MAJOR < 5 choke #endif ]])], [bitcoin_cv_qt5=yes], [bitcoin_cv_qt5=no]) ])]) - -dnl Internal. Check if the linked version of Qt was built as static libs. -dnl Requires: Qt5. This check cannot determine if Qt4 is static. -dnl Requires: INCLUDES and LIBS must be populated as necessary. -dnl Output: bitcoin_cv_static_qt=yes|no -dnl Output: Defines QT_STATICPLUGIN if plugins are static. -AC_DEFUN([_BITCOIN_QT_IS_STATIC],[ - AC_CACHE_CHECK(for static Qt, bitcoin_cv_static_qt,[ +dnl Internal. Check if the included version of Qt is greater than Qt58. +dnl Requires: INCLUDES must be populated as necessary. +dnl Output: bitcoin_cv_qt5=yes|no +AC_DEFUN([_BITCOIN_QT_CHECK_QT58],[ + AC_CACHE_CHECK(for > Qt 5.7, bitcoin_cv_qt58,[ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include #ifndef QT_VERSION @@ -315,18 +283,38 @@ AC_DEFUN([_BITCOIN_QT_IS_STATIC],[ #endif ]], [[ - #if !defined(QT_STATIC) + #if QT_VERSION_MINOR < 8 choke #endif ]])], - [bitcoin_cv_static_qt=yes], - [bitcoin_cv_static_qt=no]) - ]) + [bitcoin_cv_qt58=yes], + [bitcoin_cv_qt58=no]) +])]) +dnl Internal. Check if the linked version of Qt was built as static libs. +dnl Requires: Qt5. +dnl Requires: INCLUDES and LIBS must be populated as necessary. +dnl Output: bitcoin_cv_static_qt=yes|no +dnl Output: Defines QT_STATICPLUGIN if plugins are static. +AC_DEFUN([_BITCOIN_QT_IS_STATIC],[ + AC_CACHE_CHECK(for static Qt, bitcoin_cv_static_qt,[ + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ + #include + #ifndef QT_VERSION OR QT_VERSION_STR + # include + #endif + ]], + [[ + #if !defined(QT_STATIC) + choke + #endif + ]])], + [bitcoin_cv_static_qt=yes], + [bitcoin_cv_static_qt=no]) + ]) if test "x$bitcoin_cv_static_qt" = xyes; then AC_DEFINE(QT_STATICPLUGIN, 1, [Define this symbol for static Qt plugins]) fi ]) - dnl Internal. Check if the link-requirements for static plugins are met. dnl Requires: INCLUDES and LIBS must be populated as necessary. dnl Inputs: $1: A series of Q_IMPORT_PLUGIN(). @@ -345,31 +333,39 @@ AC_DEFUN([_BITCOIN_QT_CHECK_STATIC_PLUGINS],[ [AC_MSG_RESULT(no); BITCOIN_QT_FAIL(Could not resolve: $2)]) LIBS="$CHECK_STATIC_PLUGINS_TEMP_LIBS" ]) - dnl Internal. Find paths necessary for linking qt static plugins -dnl Inputs: bitcoin_qt_got_major_vers. 4 or 5. dnl Inputs: qt_plugin_path. optional. dnl Outputs: QT_LIBS is appended AC_DEFUN([_BITCOIN_QT_FIND_STATIC_PLUGINS],[ - if test "x$bitcoin_qt_got_major_vers" = x5; then - if test "x$qt_plugin_path" != x; then - QT_LIBS="$QT_LIBS -L$qt_plugin_path/platforms" - if test -d "$qt_plugin_path/accessible"; then - QT_LIBS="$QT_LIBS -L$qt_plugin_path/accessible" - fi + if test "x$qt_plugin_path" != x; then + QT_LIBS="$QT_LIBS -L$qt_plugin_path/platforms -L$qt_plugin_path/imageformats -L$qt_plugin_path/iconengines" + if test -d "$qt_plugin_path/accessible"; then + QT_LIBS="$QT_LIBS -L$qt_plugin_path/accessible" fi if test "x$use_pkgconfig" = xyes; then : dnl m4_ifdef([PKG_CHECK_MODULES],[ - PKG_CHECK_MODULES([QTPLATFORM], [Qt5PlatformSupport], [QT_LIBS="$QTPLATFORM_LIBS $QT_LIBS"]) + if test x$bitcoin_cv_qt58 = xno; then + PKG_CHECK_MODULES([QTPLATFORM], [Qt5PlatformSupport], [QT_LIBS="$QTPLATFORM_LIBS $QT_LIBS"]) + else + PKG_CHECK_MODULES([QTFONTDATABASE], [Qt5FontDatabaseSupport], [QT_LIBS="-lQt5FontDatabaseSupport $QT_LIBS"]) + PKG_CHECK_MODULES([QTEVENTDISPATCHER], [Qt5EventDispatcherSupport], [QT_LIBS="-lQt5EventDispatcherSupport $QT_LIBS"]) + PKG_CHECK_MODULES([QTTHEME], [Qt5ThemeSupport], [QT_LIBS="-lQt5ThemeSupport $QT_LIBS"]) + PKG_CHECK_MODULES([QTDEVICEDISCOVERY], [Qt5DeviceDiscoverySupport], [QT_LIBS="-lQt5DeviceDiscoverySupport $QT_LIBS"]) + PKG_CHECK_MODULES([QTACCESSIBILITY], [Qt5AccessibilitySupport], [QT_LIBS="-lQt5AccessibilitySupport $QT_LIBS"]) + PKG_CHECK_MODULES([QTFB], [Qt5FbSupport], [QT_LIBS="-lQt5FbSupport $QT_LIBS"]) + fi if test "x$TARGET_OS" = xlinux; then PKG_CHECK_MODULES([X11XCB], [x11-xcb], [QT_LIBS="$X11XCB_LIBS $QT_LIBS"]) if ${PKG_CONFIG} --exists "Qt5Core >= 5.5" 2>/dev/null; then PKG_CHECK_MODULES([QTXCBQPA], [Qt5XcbQpa], [QT_LIBS="$QTXCBQPA_LIBS $QT_LIBS"]) fi elif test "x$TARGET_OS" = xdarwin; then - PKG_CHECK_MODULES([QTPRINT], [Qt5PrintSupport], [QT_LIBS="$QTPRINT_LIBS $QT_LIBS"]) + PKG_CHECK_MODULES([QTCLIPBOARD], [Qt5ClipboardSupport], [QT_LIBS="-lQt5ClipboardSupport $QT_LIBS"]) + PKG_CHECK_MODULES([QTGRAPHICS], [Qt5GraphicsSupport], [QT_LIBS="-lQt5GraphicsSupport $QT_LIBS"]) + PKG_CHECK_MODULES([QTCGL], [Qt5CglSupport], [QT_LIBS="-lQt5CglSupport $QT_LIBS"]) fi + @echo "QT_LIBS: $(QT_LIBS)" ]) else if test "x$TARGET_OS" = xwindows; then @@ -381,7 +377,7 @@ AC_DEFUN([_BITCOIN_QT_FIND_STATIC_PLUGINS],[ #endif ]], [[ - #if QT_VERSION < 0x050600 + #if QT_VERSION < 0x050600 || QT_VERSION_MINOR < 6 choke #endif ]])], @@ -389,56 +385,35 @@ AC_DEFUN([_BITCOIN_QT_FIND_STATIC_PLUGINS],[ [bitcoin_cv_need_platformsupport=no]) ]) if test "x$bitcoin_cv_need_platformsupport" = xyes; then - BITCOIN_QT_CHECK(AC_CHECK_LIB([${QT_LIB_PREFIX}PlatformSupport],[main],,BITCOIN_QT_FAIL(lib${QT_LIB_PREFIX}PlatformSupport not found))) + if test x$bitcoin_cv_qt58 = xno; then + BITCOIN_QT_CHECK(AC_CHECK_LIB([${QT_LIB_PREFIX}PlatformSupport],[main],,BITCOIN_QT_FAIL(lib$QT_LIB_PREFIXPlatformSupport not found))) + else + BITCOIN_QT_CHECK(AC_CHECK_LIB([${QT_LIB_PREFIX}FontDatabaseSupport],[main],,BITCOIN_QT_FAIL(lib$QT_LIB_PREFIXFontDatabaseSupport not found))) + BITCOIN_QT_CHECK(AC_CHECK_LIB([${QT_LIB_PREFIX}EventDispatcherSupport],[main],,BITCOIN_QT_FAIL(lib$QT_LIB_PREFIXEventDispatcherSupport not found))) + BITCOIN_QT_CHECK(AC_CHECK_LIB([${QT_LIB_PREFIX}ThemeSupport],[main],,BITCOIN_QT_FAIL(lib$QT_LIB_PREFIXThemeSupport not found))) + BITCOIN_QT_CHECK(AC_CHECK_LIB([${QT_LIB_PREFIX}FbSupport],[main],,BITCOIN_QT_FAIL(lib$QT_LIB_PREFIXFbSupport not found))) + BITCOIN_QT_CHECK(AC_CHECK_LIB([${QT_LIB_PREFIX}DeviceDiscoverySupport],[main],,BITCOIN_QT_FAIL(lib$QT_LIB_PREFIXDeviceDiscoverySupport not found))) + BITCOIN_QT_CHECK(AC_CHECK_LIB([${QT_LIB_PREFIX}AccessibilitySupport],[main],,BITCOIN_QT_FAIL(lib$QT_LIB_PREFIXAccessibilitySupport not found))) + QT_LIBS="$QT_LIBS -lversion -ldwmapi -luxtheme" + fi fi fi fi - else - if test "x$qt_plugin_path" != x; then - QT_LIBS="$QT_LIBS -L$qt_plugin_path/accessible" - QT_LIBS="$QT_LIBS -L$qt_plugin_path/codecs" - fi - fi + fi ]) - dnl Internal. Find Qt libraries using pkg-config. dnl Inputs: bitcoin_qt_want_version (from --with-gui=). The version to check dnl first. dnl Inputs: $1: If bitcoin_qt_want_version is "auto", check for this version dnl first. dnl Outputs: All necessary QT_* variables are set. -dnl Outputs: bitcoin_qt_got_major_vers is set to "4" or "5". dnl Outputs: have_qt_test and have_qt_dbus are set (if applicable) to yes|no. AC_DEFUN([_BITCOIN_QT_FIND_LIBS_WITH_PKGCONFIG],[ m4_ifdef([PKG_CHECK_MODULES],[ - auto_priority_version=$1 - if test "x$auto_priority_version" = x; then - auto_priority_version=qt5 - fi - if test "x$bitcoin_qt_want_version" = xqt5 || ( test "x$bitcoin_qt_want_version" = xauto && test "x$auto_priority_version" = xqt5 ); then - QT_LIB_PREFIX=Qt5 - bitcoin_qt_got_major_vers=5 - else - QT_LIB_PREFIX=Qt - bitcoin_qt_got_major_vers=4 - fi - qt5_modules="Qt5Core Qt5Gui Qt5Network Qt5Widgets Qt5Svg Qt5Concurrent" - qt4_modules="QtCore QtGui QtNetwork" + QT_LIB_PREFIX=Qt5 + qt5_modules="Qt5Core Qt5Gui Qt5Network Qt5Widgets Qt5Svg" BITCOIN_QT_CHECK([ - if test "x$bitcoin_qt_want_version" = xqt5 || ( test "x$bitcoin_qt_want_version" = xauto && test "x$auto_priority_version" = xqt5 ); then - PKG_CHECK_MODULES([QT5], [$qt5_modules], [QT_INCLUDES="$QT5_CFLAGS"; QT_LIBS="$QT5_LIBS" have_qt=yes],[have_qt=no]) - elif test "x$bitcoin_qt_want_version" = xqt4 || ( test "x$bitcoin_qt_want_version" = xauto && test "x$auto_priority_version" = xqt4 ); then - PKG_CHECK_MODULES([QT4], [$qt4_modules], [QT_INCLUDES="$QT4_CFLAGS"; QT_LIBS="$QT4_LIBS" ; have_qt=yes], [have_qt=no]) - fi - - dnl qt version is set to 'auto' and the preferred version wasn't found. Now try the other. - if test "x$have_qt" = xno && test "x$bitcoin_qt_want_version" = xauto; then - if test "x$auto_priority_version" = xqt5; then - PKG_CHECK_MODULES([QT4], [$qt4_modules], [QT_INCLUDES="$QT4_CFLAGS"; QT_LIBS="$QT4_LIBS" ; have_qt=yes; QT_LIB_PREFIX=Qt; bitcoin_qt_got_major_vers=4], [have_qt=no]) - else - PKG_CHECK_MODULES([QT5], [$qt5_modules], [QT_INCLUDES="$QT5_CFLAGS"; QT_LIBS="$QT5_LIBS" ; have_qt=yes; QT_LIB_PREFIX=Qt5; bitcoin_qt_got_major_vers=5], [have_qt=no]) - fi - fi + PKG_CHECK_MODULES([QT5], [$qt5_modules], [QT_INCLUDES="$QT5_CFLAGS"; QT_LIBS="$QT5_LIBS" have_qt=yes],[have_qt=no]) if test "x$have_qt" != xyes; then have_qt=no BITCOIN_QT_FAIL([Qt dependencies not found]) @@ -453,13 +428,11 @@ AC_DEFUN([_BITCOIN_QT_FIND_LIBS_WITH_PKGCONFIG],[ ]) true; dnl ]) - dnl Internal. Find Qt libraries without using pkg-config. Version is deduced dnl from the discovered headers. dnl Inputs: bitcoin_qt_want_version (from --with-gui=). The version to use. dnl If "auto", the version will be discovered by _BITCOIN_QT_CHECK_QT5. dnl Outputs: All necessary QT_* variables are set. -dnl Outputs: bitcoin_qt_got_major_vers is set to "4" or "5". dnl Outputs: have_qt_test and have_qt_dbus are set (if applicable) to yes|no. AC_DEFUN([_BITCOIN_QT_FIND_LIBS_WITHOUT_PKGCONFIG],[ TEMP_CPPFLAGS="$CPPFLAGS" @@ -468,53 +441,48 @@ AC_DEFUN([_BITCOIN_QT_FIND_LIBS_WITHOUT_PKGCONFIG],[ TEMP_LIBS="$LIBS" BITCOIN_QT_CHECK([ if test "x$qt_include_path" != x; then - QT_INCLUDES="-I$qt_include_path -I$qt_include_path/QtCore -I$qt_include_path/QtGui -I$qt_include_path/QtWidgets -I$qt_include_path/QtNetwork -I$qt_include_path/QtTest -I$qt_include_path/QtDBus" + QT_INCLUDES="-I$qt_include_path -I$qt_include_path/QtCore -I$qt_include_path/QtGui -I$qt_include_path/QtWidgets -I$qt_include_path/QtNetwork -I$qt_include_path/QtTest -I$qt_include_path/QtDBus -I$qt_include_path/QtSvg" CPPFLAGS="$QT_INCLUDES $CPPFLAGS" fi ]) - BITCOIN_QT_CHECK([AC_CHECK_HEADER([QtPlugin],,BITCOIN_QT_FAIL(QtCore headers missing))]) BITCOIN_QT_CHECK([AC_CHECK_HEADER([QApplication],, BITCOIN_QT_FAIL(QtGui headers missing))]) BITCOIN_QT_CHECK([AC_CHECK_HEADER([QLocalSocket],, BITCOIN_QT_FAIL(QtNetwork headers missing))]) - + BITCOIN_QT_CHECK([AC_CHECK_HEADER([QtSvg],, BITCOIN_QT_FAIL(QtSVG headers missing))]) BITCOIN_QT_CHECK([ if test "x$bitcoin_qt_want_version" = xauto; then _BITCOIN_QT_CHECK_QT5 + _BITCOIN_QT_CHECK_QT58 fi - if test "x$bitcoin_cv_qt5" = xyes || test "x$bitcoin_qt_want_version" = xqt5; then - QT_LIB_PREFIX=Qt5 - bitcoin_qt_got_major_vers=5 - else - QT_LIB_PREFIX=Qt - bitcoin_qt_got_major_vers=4 - fi + QT_LIB_PREFIX=Qt5 ]) - BITCOIN_QT_CHECK([ LIBS= if test "x$qt_lib_path" != x; then LIBS="$LIBS -L$qt_lib_path" fi - if test "x$TARGET_OS" = xwindows; then AC_CHECK_LIB([imm32], [main],, BITCOIN_QT_FAIL(libimm32 not found)) fi ]) - BITCOIN_QT_CHECK(AC_CHECK_LIB([z] ,[main],,AC_MSG_WARN([zlib not found. Assuming qt has it built-in]))) - BITCOIN_QT_CHECK(AC_SEARCH_LIBS([png_error] ,[qtpng png],,AC_MSG_WARN([libpng not found. Assuming qt has it built-in]))) BITCOIN_QT_CHECK(AC_SEARCH_LIBS([jpeg_create_decompress] ,[qtjpeg jpeg],,AC_MSG_WARN([libjpeg not found. Assuming qt has it built-in]))) - BITCOIN_QT_CHECK(AC_SEARCH_LIBS([pcre16_exec], [qtpcre pcre16],,AC_MSG_WARN([libpcre16 not found. Assuming qt has it built-in]))) - BITCOIN_QT_CHECK(AC_SEARCH_LIBS([hb_ot_tags_from_script] ,[qtharfbuzzng harfbuzz],,AC_MSG_WARN([libharfbuzz not found. Assuming qt has it built-in or support is disabled]))) + if test x$bitcoin_cv_qt58 = xno; then + BITCOIN_QT_CHECK(AC_SEARCH_LIBS([png_error] ,[qtpng png],,AC_MSG_WARN([libpng not found. Assuming qt has it built-in]))) + BITCOIN_QT_CHECK(AC_SEARCH_LIBS([pcre16_exec], [qtpcre pcre16],,AC_MSG_WARN([libpcre16 not found. Assuming qt has it built-in]))) + else + BITCOIN_QT_CHECK(AC_SEARCH_LIBS([png_error] ,[qtlibpng png],,AC_MSG_WARN([libpng not found. Assuming qt has it built-in]))) + BITCOIN_QT_CHECK(AC_SEARCH_LIBS([pcre2_match_16], [qtpcre2 libqtpcre2],,AC_MSG_WARN([libqtpcre2 not found. Assuming qt has it built-in]))) + fi + BITCOIN_QT_CHECK(AC_SEARCH_LIBS([svg_error] ,[qtlibsvg svg],,BITCOIN_QT_FAIL([libsvg not found. Assuming qt has it built-in]))) + BITCOIN_QT_CHECK(AC_SEARCH_LIBS([hb_ot_tags_from_script] ,[qtharfbuzzng qtharfbuzz harfbuzz],,AC_MSG_WARN([libharfbuzz not found. Assuming qt has it built-in or support is disabled]))) BITCOIN_QT_CHECK(AC_CHECK_LIB([${QT_LIB_PREFIX}Core] ,[main],,BITCOIN_QT_FAIL(lib${QT_LIB_PREFIX}Core not found))) BITCOIN_QT_CHECK(AC_CHECK_LIB([${QT_LIB_PREFIX}Gui] ,[main],,BITCOIN_QT_FAIL(lib${QT_LIB_PREFIX}Gui not found))) BITCOIN_QT_CHECK(AC_CHECK_LIB([${QT_LIB_PREFIX}Network],[main],,BITCOIN_QT_FAIL(lib${QT_LIB_PREFIX}Network not found))) - if test "x$bitcoin_qt_got_major_vers" = x5; then - BITCOIN_QT_CHECK(AC_CHECK_LIB([${QT_LIB_PREFIX}Widgets],[main],,BITCOIN_QT_FAIL(lib${QT_LIB_PREFIX}Widgets not found))) - fi + BITCOIN_QT_CHECK(AC_CHECK_LIB([${QT_LIB_PREFIX}Widgets],[main],,BITCOIN_QT_FAIL(lib${QT_LIB_PREFIX}Widgets not found))) + BITCOIN_QT_CHECK(AC_CHECK_LIB([${QT_LIB_PREFIX}Svg],[main],,BITCOIN_QT_FAIL(lib${QT_LIB_PREFIX}Svg not found))) QT_LIBS="$LIBS" LIBS="$TEMP_LIBS" - BITCOIN_QT_CHECK([ LIBS= if test "x$qt_lib_path" != x; then @@ -537,4 +505,3 @@ AC_DEFUN([_BITCOIN_QT_FIND_LIBS_WITHOUT_PKGCONFIG],[ CXXFLAGS="$TEMP_CXXFLAGS" LIBS="$TEMP_LIBS" ]) - diff --git a/configure.ac b/configure.ac index 072664f..289e594 100755 --- a/configure.ac +++ b/configure.ac @@ -2,7 +2,7 @@ dnl require autoconf 2.60 (AS_ECHO/AS_ECHO_N) AC_PREREQ([2.60]) define(_CLIENT_VERSION_MAJOR, 3) define(_CLIENT_VERSION_MINOR, 0) -define(_CLIENT_VERSION_REVISION, 2) +define(_CLIENT_VERSION_REVISION, 3) define(_CLIENT_VERSION_BUILD, 0) define(_CLIENT_VERSION_IS_RELEASE, true) define(_COPYRIGHT_YEAR, 2020) @@ -91,6 +91,8 @@ AC_PATH_PROG(HEXDUMP,hexdump) AC_PATH_TOOL(READELF, readelf) AC_PATH_TOOL(CPPFILT, c++filt) AC_PATH_TOOL(OBJCOPY, objcopy) +AC_PATH_PROG(DOXYGEN, doxygen) +AM_CONDITIONAL([HAVE_DOXYGEN], [test -n "$DOXYGEN"]) AC_ARG_VAR(PYTHONPATH, Augments the default search path for python module files) @@ -644,7 +646,7 @@ fi BITCOIN_QT_INIT dnl sets $bitcoin_enable_qt, $bitcoin_enable_qt_test, $bitcoin_enable_qt_dbus -BITCOIN_QT_CONFIGURE([$use_pkgconfig], [qt5]) +BITCOIN_QT_CONFIGURE([$use_pkgconfig]) if test x$build_bitcoin_utils$build_bitcoind$bitcoin_enable_qt$use_tests = xnononono; then use_boost=no @@ -1203,7 +1205,6 @@ echo "Options used to compile and link:" echo " with wallet = $enable_wallet" echo " with gui / qt = $bitcoin_enable_qt" if test x$bitcoin_enable_qt != xno; then - echo " qt version = $bitcoin_qt_got_major_vers" echo " with qr = $use_qr" fi echo " with zmq = $use_zmq" diff --git a/contrib/devtools/git-subtree-check.sh b/contrib/devtools/git-subtree-check.sh new file mode 100755 index 0000000..85e8b84 --- /dev/null +++ b/contrib/devtools/git-subtree-check.sh @@ -0,0 +1,95 @@ +#!/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. + +export LC_ALL=C +DIR="$1" +COMMIT="$2" +if [ -z "$COMMIT" ]; then + COMMIT=HEAD +fi + +# Taken from git-subtree (Copyright (C) 2009 Avery Pennarun ) +find_latest_squash() +{ + dir="$1" + sq= + main= + sub= + git log --grep="^git-subtree-dir: $dir/*\$" \ + --pretty=format:'START %H%n%s%n%n%b%nEND%n' "$COMMIT" | + while read a b _; do + case "$a" in + START) sq="$b" ;; + git-subtree-mainline:) main="$b" ;; + git-subtree-split:) sub="$b" ;; + END) + if [ -n "$sub" ]; then + if [ -n "$main" ]; then + # a rejoin commit? + # Pretend its sub was a squash. + sq="$sub" + fi + echo "$sq" "$sub" + break + fi + sq= + main= + sub= + ;; + esac + done +} + +# find latest subtree update +latest_squash="$(find_latest_squash "$DIR")" +if [ -z "$latest_squash" ]; then + echo "ERROR: $DIR is not a subtree" >&2 + exit 2 +fi +set $latest_squash +old=$1 +rev=$2 + +# get the tree in the current commit +tree_actual=$(git ls-tree -d "$COMMIT" "$DIR" | head -n 1) +if [ -z "$tree_actual" ]; then + echo "FAIL: subtree directory $DIR not found in $COMMIT" >&2 + exit 1 +fi +set $tree_actual +tree_actual_type=$2 +tree_actual_tree=$3 +echo "$DIR in $COMMIT currently refers to $tree_actual_type $tree_actual_tree" +if [ "d$tree_actual_type" != "dtree" ]; then + echo "FAIL: subtree directory $DIR is not a tree in $COMMIT" >&2 + exit 1 +fi + +# get the tree at the time of the last subtree update +tree_commit=$(git show -s --format="%T" $old) +echo "$DIR in $COMMIT was last updated in commit $old (tree $tree_commit)" + +# ... and compare the actual tree with it +if [ "$tree_actual_tree" != "$tree_commit" ]; then + git diff $tree_commit $tree_actual_tree >&2 + echo "FAIL: subtree directory was touched without subtree merge" >&2 + exit 1 +fi + +# get the tree in the subtree commit referred to +if [ "d$(git cat-file -t $rev 2>/dev/null)" != dcommit ]; then + echo "subtree commit $rev unavailable: cannot compare" >&2 + exit +fi +tree_subtree=$(git show -s --format="%T" $rev) +echo "$DIR in $COMMIT was last updated to upstream commit $rev (tree $tree_subtree)" + +# ... and compare the actual tree with it +if [ "$tree_actual_tree" != "$tree_subtree" ]; then + echo "FAIL: subtree update commit differs from upstream tree!" >&2 + exit 1 +fi + +echo "GOOD" diff --git a/contrib/devtools/lint-whitespace.sh b/contrib/devtools/lint-whitespace.sh new file mode 100644 index 0000000..128aa10 --- /dev/null +++ b/contrib/devtools/lint-whitespace.sh @@ -0,0 +1,113 @@ +#!/bin/bash +# +# Copyright (c) 2017 The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. +# +# Check for new lines in diff that introduce trailing whitespace. + +# We can't run this check unless we know the commit range for the PR. + +export LC_ALL=C +while getopts "?" opt; do + case $opt in + ?) + echo "Usage: .lint-whitespace.sh [N]" + echo " TRAVIS_COMMIT_RANGE='' .lint-whitespace.sh" + echo " .lint-whitespace.sh -?" + echo "Checks unstaged changes, the previous N commits, or a commit range." + echo "TRAVIS_COMMIT_RANGE='47ba2c3...ee50c9e' .lint-whitespace.sh" + exit 0 + ;; + esac +done + +if [ -z "${TRAVIS_COMMIT_RANGE}" ]; then + if [ "$1" ]; then + TRAVIS_COMMIT_RANGE="HEAD~$1...HEAD" + else + TRAVIS_COMMIT_RANGE="HEAD" + fi +fi + +showdiff() { + if ! git diff -U0 "${TRAVIS_COMMIT_RANGE}" -- "." ":(exclude)depends/patches/" ":(exclude)src/leveldb/" ":(exclude)src/secp256k1/" ":(exclude)src/univalue/" ":(exclude)doc/release-notes/"; then + echo "Failed to get a diff" + exit 1 + fi +} + +showcodediff() { + if ! git diff -U0 "${TRAVIS_COMMIT_RANGE}" -- *.cpp *.h *.md *.py *.sh ":(exclude)src/leveldb/" ":(exclude)src/secp256k1/" ":(exclude)src/univalue/" ":(exclude)doc/release-notes/"; then + echo "Failed to get a diff" + exit 1 + fi +} + +RET=0 + +# Check if trailing whitespace was found in the diff. +if showdiff | grep -E -q '^\+.*\s+$'; then + echo "This diff appears to have added new lines with trailing whitespace." + echo "The following changes were suspected:" + FILENAME="" + SEEN=0 + SEENLN=0 + while read -r line; do + if [[ "$line" =~ ^diff ]]; then + FILENAME="$line" + SEEN=0 + elif [[ "$line" =~ ^@@ ]]; then + LINENUMBER="$line" + SEENLN=0 + else + if [ "$SEEN" -eq 0 ]; then + # The first time a file is seen with trailing whitespace, we print the + # filename (preceded by a newline). + echo + echo "$FILENAME" + SEEN=1 + fi + if [ "$SEENLN" -eq 0 ]; then + echo "$LINENUMBER" + SEENLN=1 + fi + echo "$line" + fi + done < <(showdiff | grep -E '^(diff --git |@@|\+.*\s+$)') + RET=1 +fi + +# Check if tab characters were found in the diff. +if showcodediff | perl -nle '$MATCH++ if m{^\+.*\t}; END{exit 1 unless $MATCH>0}' > /dev/null; then + echo "This diff appears to have added new lines with tab characters instead of spaces." + echo "The following changes were suspected:" + FILENAME="" + SEEN=0 + SEENLN=0 + while read -r line; do + if [[ "$line" =~ ^diff ]]; then + FILENAME="$line" + SEEN=0 + elif [[ "$line" =~ ^@@ ]]; then + LINENUMBER="$line" + SEENLN=0 + else + if [ "$SEEN" -eq 0 ]; then + # The first time a file is seen with a tab character, we print the + # filename (preceded by a newline). + echo + echo "$FILENAME" + SEEN=1 + fi + if [ "$SEENLN" -eq 0 ]; then + echo "$LINENUMBER" + SEENLN=1 + fi + echo "$line" + fi + done < <(showcodediff | perl -nle 'print if m{^(diff --git |@@|\+.*\t)}') + RET=1 +fi + +exit $RET diff --git a/contrib/devtools/logprint-scanner.py b/contrib/devtools/logprint-scanner.py index 74c36e7..678b209 100644 --- a/contrib/devtools/logprint-scanner.py +++ b/contrib/devtools/logprint-scanner.py @@ -1,4 +1,9 @@ #!/usr/bin/env python2 +# Copyright (c) 2017-2018 The PIVX developers +# Copyright (c) 2018-2020 The Ohmcoin developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php + import os, sys from subprocess import check_output diff --git a/depends/Makefile b/depends/Makefile index 0ddd348..7f993bd 100644 --- a/depends/Makefile +++ b/depends/Makefile @@ -166,6 +166,12 @@ $(host_prefix)/share/config.site: check-packages check-packages: check-sources +clean-all: clean + @rm -rf $(SOURCES_PATH) x86_64* i686* mips* arm* aarch64* riscv32* riscv64* + +clean: + @rm -rf $(WORK_PATH) $(BASE_CACHE) $(BUILD) + install: check-packages $(host_prefix)/share/config.site diff --git a/depends/hosts/darwin.mk b/depends/hosts/darwin.mk index 4e58bec..a1c943d 100755 --- a/depends/hosts/darwin.mk +++ b/depends/hosts/darwin.mk @@ -1,4 +1,4 @@ -OSX_MIN_VERSION=10.8 +OSX_MIN_VERSION=10.10 OSX_SDK_VERSION=10.11 OSX_SDK=$(SDK_PATH)/MacOSX$(OSX_SDK_VERSION).sdk LD64_VERSION=253.9 diff --git a/depends/packages/libICE.mk b/depends/packages/libICE.mk deleted file mode 100755 index fc60323..0000000 --- a/depends/packages/libICE.mk +++ /dev/null @@ -1,23 +0,0 @@ -package=libICE -$(package)_version=1.0.9 -$(package)_download_path=http://xorg.freedesktop.org/releases/individual/lib/ -$(package)_file_name=$(package)-$($(package)_version).tar.bz2 -$(package)_sha256_hash=8f7032f2c1c64352b5423f6b48a8ebdc339cc63064af34d66a6c9aa79759e202 -$(package)_dependencies=xtrans xproto - -define $(package)_set_vars - $(package)_config_opts=--disable-static --disable-docs --disable-specs --without-xsltproc - $(package)_config_opts_linux=--with-pic -endef - -define $(package)_config_cmds - $($(package)_autoconf) -endef - -define $(package)_build_cmds - $(MAKE) -endef - -define $(package)_stage_cmds - $(MAKE) DESTDIR=$($(package)_staging_dir) install -endef diff --git a/depends/packages/libSM.mk b/depends/packages/libSM.mk deleted file mode 100755 index 0f9307c..0000000 --- a/depends/packages/libSM.mk +++ /dev/null @@ -1,23 +0,0 @@ -package=libSM -$(package)_version=1.2.2 -$(package)_download_path=http://xorg.freedesktop.org/releases/individual/lib/ -$(package)_file_name=$(package)-$($(package)_version).tar.bz2 -$(package)_sha256_hash=0baca8c9f5d934450a70896c4ad38d06475521255ca63b717a6510fdb6e287bd -$(package)_dependencies=xtrans xproto libICE - -define $(package)_set_vars - $(package)_config_opts=--without-libuuid --without-xsltproc --disable-docs --disable-static - $(package)_config_opts_linux=--with-pic -endef - -define $(package)_config_cmds - $($(package)_autoconf) -endef - -define $(package)_build_cmds - $(MAKE) -endef - -define $(package)_stage_cmds - $(MAKE) DESTDIR=$($(package)_staging_dir) install -endef diff --git a/depends/packages/qt.mk b/depends/packages/qt.mk index dee95a9..9582f28 100755 --- a/depends/packages/qt.mk +++ b/depends/packages/qt.mk @@ -127,6 +127,7 @@ endef define $(package)_preprocess_cmds + sed -i.old "s|FT_Get_Font_Format|FT_Get_X11_Font_Format|" qtbase/src/platformsupport/fontdatabases/freetype/qfontengine_ft.cpp && \ sed -i.old "s|updateqm.commands = \$$$$\$$$$LRELEASE|updateqm.commands = $($(package)_extract_dir)/qttools/bin/lrelease|" qttranslations/translations/translations.pro && \ sed -i.old "/updateqm.depends =/d" qttranslations/translations/translations.pro && \ sed -i.old "s/src_plugins.depends = src_sql src_xml src_network/src_plugins.depends = src_xml src_network/" qtbase/src/src.pro && \ diff --git a/depends/packages/qt46.mk b/depends/packages/qt46.mk deleted file mode 100644 index 8fb30a5..0000000 --- a/depends/packages/qt46.mk +++ /dev/null @@ -1,66 +0,0 @@ -PACKAGE=qt46 -$(package)_version=4.6.4 -$(package)_download_path=http://download.qt-project.org/archive/qt/4.6/ -$(package)_file_name=qt-everywhere-opensource-src-$($(package)_version).tar.gz -$(package)_sha256_hash=9ad4d46c721b53a429ed5a2eecfd3c239a9ab566562f183f99d3125f1a234250 -$(package)_dependencies=openssl freetype dbus libX11 xproto libXext libICE libSM -$(package)_patches=stlfix.patch - -define $(package)_set_vars -$(package)_config_opts = -prefix $(host_prefix) -headerdir $(host_prefix)/include/qt4 -bindir $(build_prefix)/bin -$(package)_config_opts += -release -no-separate-debug-info -opensource -confirm-license -$(package)_config_opts += -stl -qt-zlib - -$(package)_config_opts += -nomake examples -nomake tests -nomake tools -nomake translations -nomake demos -nomake docs -$(package)_config_opts += -no-audio-backend -no-glib -no-nis -no-cups -no-iconv -no-gif -no-pch -$(package)_config_opts += -no-xkb -no-xrender -no-xrandr -no-xfixes -no-xcursor -no-xinerama -no-xsync -no-xinput -no-mitshm -no-xshape -$(package)_config_opts += -no-libtiff -no-fontconfig -openssl-linked -$(package)_config_opts += -no-sql-db2 -no-sql-ibase -no-sql-oci -no-sql-tds -no-sql-mysql -$(package)_config_opts += -no-sql-odbc -no-sql-psql -no-sql-sqlite -no-sql-sqlite2 -$(package)_config_opts += -no-xmlpatterns -no-multimedia -no-phonon -no-scripttools -no-declarative -$(package)_config_opts += -no-phonon-backend -no-webkit -no-javascript-jit -no-script -$(package)_config_opts += -no-svg -no-libjpeg -no-libtiff -no-libpng -no-libmng -no-qt3support -no-opengl - -$(package)_config_opts_x86_64_linux += -platform linux-g++-64 -$(package)_config_opts_i686_linux = -platform linux-g++-32 -$(package)_build_env = QT_RCC_TEST=1 -endef - -define $(package)_preprocess_cmds - sed -i.old "s|/include /usr/include||" config.tests/unix/freetype/freetype.pri && \ - sed -i.old "s|src_plugins.depends = src_gui src_sql src_svg|src_plugins.depends = src_gui src_sql|" src/src.pro && \ - sed -i.old "s|\.lower(|\.toLower(|g" src/network/ssl/qsslsocket_openssl.cpp && \ - sed -i.old "s|Key_BackSpace|Key_Backspace|" src/gui/itemviews/qabstractitemview.cpp && \ - sed -i.old "s|/usr/X11R6/lib64|$(host_prefix)/lib|" mkspecs/*/*.conf && \ - sed -i.old "s|/usr/X11R6/lib|$(host_prefix)/lib|" mkspecs/*/*.conf && \ - sed -i.old "s|/usr/X11R6/include|$(host_prefix)/include|" mkspecs/*/*.conf && \ - sed -i.old "s|QMAKE_LFLAGS_SHLIB\t+= -shared|QMAKE_LFLAGS_SHLIB\t+= -shared -Wl,--exclude-libs,ALL|" mkspecs/common/g++.conf && \ - sed -i.old "/SSLv2_client_method/d" src/network/ssl/qsslsocket_openssl.cpp src/network/ssl/qsslsocket_openssl_symbols.cpp && \ - sed -i.old "/SSLv2_server_method/d" src/network/ssl/qsslsocket_openssl.cpp src/network/ssl/qsslsocket_openssl_symbols.cpp && \ - patch -p1 < $($(package)_patch_dir)/stlfix.patch -endef - -define $(package)_config_cmds - export PKG_CONFIG_SYSROOT_DIR=/ && \ - export PKG_CONFIG_LIBDIR=$(host_prefix)/lib/pkgconfig && \ - export PKG_CONFIG_PATH=$(host_prefix)/share/pkgconfig && \ - export CPATH=$(host_prefix)/include && \ - OPENSSL_LIBS='-L$(host_prefix)/lib -lssl -lcrypto' ./configure $($(package)_config_opts) && \ - cd tools/linguist/lrelease; ../../../bin/qmake -o Makefile lrelease.pro -endef - -define $(package)_build_cmds - export CPATH=$(host_prefix)/include && \ - $(MAKE) -C src && \ - $(MAKE) -C tools/linguist/lrelease -endef - -define $(package)_stage_cmds - $(MAKE) -C src INSTALL_ROOT=$($(package)_staging_dir) install && \ - $(MAKE) -C tools/linguist/lrelease INSTALL_ROOT=$($(package)_staging_dir) install -endef - -define $(package)_postprocess_cmds - rm -rf mkspecs/ lib/cmake/ lib/*.prl lib/*.la && \ - find native/bin -type f -exec mv {} {}-qt4 \; -endef diff --git a/doc/Doxyfile b/doc/Doxyfile index 203b649..68ef59a 100644 --- a/doc/Doxyfile +++ b/doc/Doxyfile @@ -38,7 +38,7 @@ PROJECT_NAME = "Ohmcoin Core" # could be handy for archiving the generated documentation or if some version # control system is used. -PROJECT_NUMBER = 3.0.0 +PROJECT_NUMBER = 3.0.3 # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a diff --git a/doc/build-osx.md b/doc/build-osx.md index 90e5dcd..50e9ce9 100755 --- a/doc/build-osx.md +++ b/doc/build-osx.md @@ -50,7 +50,7 @@ Instructions: Homebrew cd Ohmcoin 2. Make the Homebrew OpenSSL headers visible to the configure script (do ```brew info openssl``` to find out why this is necessary, or if you use Homebrew with installation folders different from the default). - export LDFLAGS+=-L/usr/local/opt/openssl/lib + export LDFLAGS+=-L/usr/local/opt/openssl/lib export CPPFLAGS+=-I/usr/local/opt/openssl/include 3. Build ohmcoind: @@ -215,4 +215,4 @@ And there you have your wallet – you can start it by running: You can move the wallet app to another more permanent location. If you have not moved it and want to start your wallet in the future, open Terminal and run this command: -~/Downloads/Ohmcoin/src/qt/ohmcoin-qt \ No newline at end of file +~/Downloads/Ohmcoin/src/qt/ohmcoin-qt diff --git a/doc/dependencies.md b/doc/dependencies.md new file mode 100755 index 0000000..40caa19 --- /dev/null +++ b/doc/dependencies.md @@ -0,0 +1,30 @@ +Dependencies +============ + +These are the dependencies currently used by Bitcoin Core. You can find instructions for installing them in the `build-*.md` file for your platform. + +| Dependency | Version used | Minimum required | CVEs | Shared | [Bundled Qt library](https://doc.qt.io/qt-5/configure-options.html) | +| --- | --- | --- | --- | --- | --- | +| Berkeley DB | [4.8.30](http://www.oracle.com/technetwork/database/database-technologies/berkeleydb/downloads/index.html) | 4.8.x | No | | | +| Boost | [1.64.0](http://www.boost.org/users/download/) | [1.47.0](https://github.com/bitcoin/bitcoin/pull/8920) | No | | | +| Clang | | [3.3+](http://llvm.org/releases/download.html) (C++11 support) | | | | +| D-Bus | [1.10.18](https://cgit.freedesktop.org/dbus/dbus/tree/NEWS?h=dbus-1.10) | | No | Yes | | +| Expat | [2.2.5](https://libexpat.github.io/) | | No | Yes | | +| fontconfig | [2.12.1](https://www.freedesktop.org/software/fontconfig/release/) | | No | Yes | | +| FreeType | [2.7.1](http://download.savannah.gnu.org/releases/freetype) | | No | | | +| GCC | | [4.8+](https://gcc.gnu.org/) | | | | +| HarfBuzz-NG | | | | | | +| libevent | [2.1.8-stable](https://github.com/libevent/libevent/releases) | 2.0.22 | No | | | +| libjpeg | | | | | [Yes](https://github.com/theohmproject/ohmcoin/blob/master/depends/packages/qt.mk#L75) | +| libpng | | | | | [Yes](https://github.com/theohmproject/ohmcoin/blob/master/depends/packages/qt.mk#L74) | +| MiniUPnPc | [2.0.20180203](http://miniupnp.free.fr/files) | | No | | | +| OpenSSL | [1.0.1k](https://www.openssl.org/source) | | Yes | | | +| PCRE | | | | | [Yes](https://github.com/theohmproject/ohmcoin/blob/master/depends/packages/qt.mk#L76) | +| protobuf | [2.6.3](https://github.com/google/protobuf/releases) | | No | | | +| Python (tests) | | [3.4](https://www.python.org/downloads) | | | | +| qrencode | [3.4.4](https://fukuchi.org/works/qrencode) | | No | | | +| Qt | [5.7.1](https://download.qt.io/official_releases/qt/) | 5.x | No | | | +| XCB | | | | | [Yes](https://github.com/theohmproject/ohmcoin/blob/master/depends/packages/qt.mk#L94) (Linux only) | +| xkbcommon | | | | | [Yes](https://github.com/theohmproject/ohmcoin/blob/master/depends/packages/qt.mk#L93) (Linux only) | +| ZeroMQ | [4.2.3](https://github.com/zeromq/libzmq/releases) | | No | | | +| zlib | [1.2.11](http://zlib.net/) | | | | No | diff --git a/doc/release-process.md b/doc/release-process.md index a96f8e6..799a8bd 100755 --- a/doc/release-process.md +++ b/doc/release-process.md @@ -115,7 +115,7 @@ The gbuild invocations below DO NOT DO THIS by default. mv build/out/ohmcoin-*.tar.gz build/out/ohmcoin-*.dmg ../ ./bin/gbuild --memory 3000 --commit ohmcoin=v${VERSION} ../ohmcoin/contrib/gitian-descriptors/gitian-aarch64.yml - ./bin/gsign --signer $SIGNER --release ${VERSION}-linux --destination ../gitian.sigs/ ../ohmcoin/contrib/gitian-descriptors/gitian-aarch64.yml + ./bin/gsign --signer $SIGNER --release ${VERSION}-aarch64 --destination ../gitian.sigs/ ../ohmcoin/contrib/gitian-descriptors/gitian-aarch64.yml mv build/out/ohmcoin-*.tar.gz build/out/src/ohmcoin-*.tar.gz ../ popd diff --git a/pkg.m4 b/pkg.m4 deleted file mode 100755 index c5b26b5..0000000 --- a/pkg.m4 +++ /dev/null @@ -1,214 +0,0 @@ -# pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*- -# serial 1 (pkg-config-0.24) -# -# Copyright © 2004 Scott James Remnant . -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -# -# As a special exception to the GNU General Public License, if you -# distribute this file as part of a program that contains a -# configuration script generated by Autoconf, you may include it under -# the same distribution terms that you use for the rest of that program. - -# PKG_PROG_PKG_CONFIG([MIN-VERSION]) -# ---------------------------------- -AC_DEFUN([PKG_PROG_PKG_CONFIG], -[m4_pattern_forbid([^_?PKG_[A-Z_]+$]) -m4_pattern_allow([^PKG_CONFIG(_(PATH|LIBDIR|SYSROOT_DIR|ALLOW_SYSTEM_(CFLAGS|LIBS)))?$]) -m4_pattern_allow([^PKG_CONFIG_(DISABLE_UNINSTALLED|TOP_BUILD_DIR|DEBUG_SPEW)$]) -AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility]) -AC_ARG_VAR([PKG_CONFIG_PATH], [directories to add to pkg-config's search path]) -AC_ARG_VAR([PKG_CONFIG_LIBDIR], [path overriding pkg-config's built-in search path]) - -if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then - AC_PATH_TOOL([PKG_CONFIG], [pkg-config]) -fi -if test -n "$PKG_CONFIG"; then - _pkg_min_version=m4_default([$1], [0.9.0]) - AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version]) - if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then - AC_MSG_RESULT([yes]) - else - AC_MSG_RESULT([no]) - PKG_CONFIG="" - fi -fi[]dnl -])# PKG_PROG_PKG_CONFIG - -# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]) -# -# Check to see whether a particular set of modules exists. Similar -# to PKG_CHECK_MODULES(), but does not set variables or print errors. -# -# Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG]) -# only at the first occurence in configure.ac, so if the first place -# it's called might be skipped (such as if it is within an "if", you -# have to call PKG_CHECK_EXISTS manually -# -------------------------------------------------------------- -AC_DEFUN([PKG_CHECK_EXISTS], -[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl -if test -n "$PKG_CONFIG" && \ - AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then - m4_default([$2], [:]) -m4_ifvaln([$3], [else - $3])dnl -fi]) - -# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES]) -# --------------------------------------------- -m4_define([_PKG_CONFIG], -[if test -n "$$1"; then - pkg_cv_[]$1="$$1" - elif test -n "$PKG_CONFIG"; then - PKG_CHECK_EXISTS([$3], - [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null` - test "x$?" != "x0" && pkg_failed=yes ], - [pkg_failed=yes]) - else - pkg_failed=untried -fi[]dnl -])# _PKG_CONFIG - -# _PKG_SHORT_ERRORS_SUPPORTED -# ----------------------------- -AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED], -[AC_REQUIRE([PKG_PROG_PKG_CONFIG]) -if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then - _pkg_short_errors_supported=yes -else - _pkg_short_errors_supported=no -fi[]dnl -])# _PKG_SHORT_ERRORS_SUPPORTED - - -# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND], -# [ACTION-IF-NOT-FOUND]) -# -# -# Note that if there is a possibility the first call to -# PKG_CHECK_MODULES might not happen, you should be sure to include an -# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac -# -# -# -------------------------------------------------------------- -AC_DEFUN([PKG_CHECK_MODULES], -[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl -AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl -AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl - -pkg_failed=no -AC_MSG_CHECKING([for $1]) - -_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2]) -_PKG_CONFIG([$1][_LIBS], [libs], [$2]) - -m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS -and $1[]_LIBS to avoid the need to call pkg-config. -See the pkg-config man page for more details.]) - -if test $pkg_failed = yes; then - AC_MSG_RESULT([no]) - _PKG_SHORT_ERRORS_SUPPORTED - if test $_pkg_short_errors_supported = yes; then - $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "$2" 2>&1` - else - $1[]_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "$2" 2>&1` - fi - # Put the nasty error message in config.log where it belongs - echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD - - m4_default([$4], [AC_MSG_ERROR( -[Package requirements ($2) were not met: - -$$1_PKG_ERRORS - -Consider adjusting the PKG_CONFIG_PATH environment variable if you -installed software in a non-standard prefix. - -_PKG_TEXT])[]dnl - ]) -elif test $pkg_failed = untried; then - AC_MSG_RESULT([no]) - m4_default([$4], [AC_MSG_FAILURE( -[The pkg-config script could not be found or is too old. Make sure it -is in your PATH or set the PKG_CONFIG environment variable to the full -path to pkg-config. - -_PKG_TEXT - -To get pkg-config, see .])[]dnl - ]) -else - $1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS - $1[]_LIBS=$pkg_cv_[]$1[]_LIBS - AC_MSG_RESULT([yes]) - $3 -fi[]dnl -])# PKG_CHECK_MODULES - - -# PKG_INSTALLDIR(DIRECTORY) -# ------------------------- -# Substitutes the variable pkgconfigdir as the location where a module -# should install pkg-config .pc files. By default the directory is -# $libdir/pkgconfig, but the default can be changed by passing -# DIRECTORY. The user can override through the --with-pkgconfigdir -# parameter. -AC_DEFUN([PKG_INSTALLDIR], -[m4_pushdef([pkg_default], [m4_default([$1], ['${libdir}/pkgconfig'])]) -m4_pushdef([pkg_description], - [pkg-config installation directory @<:@]pkg_default[@:>@]) -AC_ARG_WITH([pkgconfigdir], - [AS_HELP_STRING([--with-pkgconfigdir], pkg_description)],, - [with_pkgconfigdir=]pkg_default) -AC_SUBST([pkgconfigdir], [$with_pkgconfigdir]) -m4_popdef([pkg_default]) -m4_popdef([pkg_description]) -]) dnl PKG_INSTALLDIR - - -# PKG_NOARCH_INSTALLDIR(DIRECTORY) -# ------------------------- -# Substitutes the variable noarch_pkgconfigdir as the location where a -# module should install arch-independent pkg-config .pc files. By -# default the directory is $datadir/pkgconfig, but the default can be -# changed by passing DIRECTORY. The user can override through the -# --with-noarch-pkgconfigdir parameter. -AC_DEFUN([PKG_NOARCH_INSTALLDIR], -[m4_pushdef([pkg_default], [m4_default([$1], ['${datadir}/pkgconfig'])]) -m4_pushdef([pkg_description], - [pkg-config arch-independent installation directory @<:@]pkg_default[@:>@]) -AC_ARG_WITH([noarch-pkgconfigdir], - [AS_HELP_STRING([--with-noarch-pkgconfigdir], pkg_description)],, - [with_noarch_pkgconfigdir=]pkg_default) -AC_SUBST([noarch_pkgconfigdir], [$with_noarch_pkgconfigdir]) -m4_popdef([pkg_default]) -m4_popdef([pkg_description]) -]) dnl PKG_NOARCH_INSTALLDIR - - -# PKG_CHECK_VAR(VARIABLE, MODULE, CONFIG-VARIABLE, -# [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]) -# ------------------------------------------- -# Retrieves the value of the pkg-config variable for the given module. -AC_DEFUN([PKG_CHECK_VAR], -[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl -AC_ARG_VAR([$1], [value of $3 for $2, overriding pkg-config])dnl - -_PKG_CONFIG([$1], [variable="][$3]["], [$2]) -AS_VAR_COPY([$1], [pkg_cv_][$1]) - -AS_VAR_IF([$1], [""], [$5], [$4])dnl -])# PKG_CHECK_VAR diff --git a/src/.clang-format b/src/.clang-format index fc53509..9a700b7 100755 --- a/src/.clang-format +++ b/src/.clang-format @@ -23,7 +23,6 @@ ContinuationIndentWidth: 4 Cpp11BracedListStyle: true DerivePointerAlignment: false DisableFormat: false -ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH, BOOST_REVERSE_FOREACH ] IndentCaseLabels: false IndentFunctionDeclarationAfterType: false IndentWidth: 4 diff --git a/src/Makefile.am b/src/Makefile.am index 0c3c36a..0c59a59 100755 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -128,7 +128,7 @@ BITCOIN_CORE_H = \ denomination_functions.h \ obfuscation.h \ obfuscation-relay.h \ - db.h \ + wallet/db.h \ eccryptoverify.h \ ecwrapper.h \ hash.h \ @@ -143,6 +143,7 @@ BITCOIN_CORE_H = \ leveldbwrapper.h \ limitedmap.h \ main.h \ + memusage.h \ karmanode.h \ karmanode-payments.h \ karmanode-budget.h \ @@ -160,11 +161,12 @@ BITCOIN_CORE_H = \ protocol.h \ pubkey.h \ random.h \ + reverse_iterator.h \ reverselock.h \ reverse_iterate.h \ - rpcclient.h \ - rpcprotocol.h \ - rpcserver.h \ + rpc/client.h \ + rpc/protocol.h \ + rpc/server.h \ scheduler.h \ script/interpreter.h \ script/script.h \ @@ -194,9 +196,9 @@ BITCOIN_CORE_H = \ utiltime.h \ validationinterface.h \ version.h \ - wallet.h \ - wallet_ismine.h \ - walletdb.h \ + wallet/wallet.h \ + wallet/wallet_ismine.h \ + wallet/walletdb.h \ zohmctracker.h \ zohmcwallet.h \ zmq/zmqabstractnotifier.h \ @@ -232,14 +234,14 @@ libbitcoin_server_a_SOURCES = \ noui.cpp \ pow.cpp \ rest.cpp \ - rpcblockchain.cpp \ - rpckarmanode.cpp \ - rpckarmanode-budget.cpp \ - rpcmining.cpp \ - rpcmisc.cpp \ - rpcnet.cpp \ - rpcrawtransaction.cpp \ - rpcserver.cpp \ + rpc/blockchain.cpp \ + rpc/karmanode.cpp \ + rpc/budget.cpp \ + rpc/mining.cpp \ + rpc/misc.cpp \ + rpc/net.cpp \ + rpc/rawtransaction.cpp \ + rpc/server.cpp \ script/sigcache.cpp \ sporkdb.cpp \ timedata.cpp \ @@ -268,7 +270,7 @@ libbitcoin_wallet_a_SOURCES = \ denomination_functions.cpp \ obfuscation.cpp \ obfuscation-relay.cpp \ - db.cpp \ + wallet/db.cpp \ crypter.cpp \ swifttx.cpp \ karmanode.cpp \ @@ -278,14 +280,14 @@ libbitcoin_wallet_a_SOURCES = \ karmanodeconfig.cpp \ karmanodeman.cpp \ mintpool.cpp \ - rpcdump.cpp \ + wallet/rpcdump.cpp \ + wallet/rpcwallet.cpp \ + kernel.cpp \ + wallet/wallet.cpp \ + wallet/wallet_ismine.cpp \ + wallet/walletdb.cpp \ primitives/deterministicmint.cpp \ primitives/zerocoin.cpp \ - rpcwallet.cpp \ - kernel.cpp \ - wallet.cpp \ - wallet_ismine.cpp \ - walletdb.cpp \ zohmcwallet.cpp \ zohmctracker.cpp \ $(BITCOIN_CORE_H) @@ -327,7 +329,7 @@ crypto_libbitcoin_crypto_a_SOURCES = \ crypto/sph_types.h # libzerocoin library -libzerocoin_libbitcoin_zerocin_a_CPPFLAGS = $(AM_CPPFLAGS) +libzerocoin_libbitcoin_zerocin_a_CPPFLAGS = $(AM_CPPFLAGS) $(BOOST_CPPFLAGS) libzerocoin_libbitcoin_zerocin_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) libzerocoin_libbitcoin_zerocoin_a_SOURCES = \ libzerocoin/Accumulator.h \ @@ -407,7 +409,7 @@ libbitcoin_util_a_SOURCES = \ chainparamsbase.cpp \ clientversion.cpp \ random.cpp \ - rpcprotocol.cpp \ + rpc/protocol.cpp \ sync.cpp \ uint256.cpp \ util.cpp \ @@ -424,7 +426,7 @@ endif libbitcoin_cli_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) libbitcoin_cli_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) libbitcoin_cli_a_SOURCES = \ - rpcclient.cpp \ + rpc/client.cpp \ $(BITCOIN_CORE_H) nodist_libbitcoin_util_a_SOURCES = $(srcdir)/obj/build.h diff --git a/src/Makefile.qt.include b/src/Makefile.qt.include index 0a40af4..71c98a1 100755 --- a/src/Makefile.qt.include +++ b/src/Makefile.qt.include @@ -82,9 +82,9 @@ QT_MOC_CPP = \ qt/moc_editaddressdialog.cpp \ qt/moc_guiutil.cpp \ qt/moc_intro.cpp \ + qt/moc_karmanodelist.cpp \ qt/moc_macdockiconhandler.cpp \ qt/moc_macnotificationhandler.cpp \ - qt/moc_karmanodelist.cpp \ qt/moc_multisenddialog.cpp \ qt/moc_multisigdialog.cpp\ qt/moc_notificator.cpp \ @@ -156,15 +156,16 @@ BITCOIN_QT_H = \ qt/clientmodel.h \ qt/coincontroldialog.h \ qt/coincontroltreewidget.h \ + qt/configurekarmanodepage.h \ qt/csvmodelwriter.h \ qt/obfuscationconfig.h \ qt/editaddressdialog.h \ qt/guiconstants.h \ qt/guiutil.h \ qt/intro.h \ + qt/karmanodelist.h \ qt/macdockiconhandler.h \ qt/macnotificationhandler.h \ - qt/karmanodelist.h \ qt/multisenddialog.h \ qt/multisigdialog.h\ qt/networkstyle.h \ @@ -192,7 +193,6 @@ BITCOIN_QT_H = \ qt/rpcconsole.h \ qt/sendcoinsdialog.h \ qt/sendcoinsentry.h \ - qt/configurekarmanodepage.h \ qt/signverifymessagedialog.h \ qt/splashscreen.h \ qt/trafficgraphwidget.h \ @@ -243,11 +243,12 @@ RES_ICONS = \ qt/res/icons/filesave.png \ qt/res/icons/history.png \ qt/res/icons/history_off.png \ + qt/res/icons/karmanodes.png \ + qt/res/icons/karmanodes_off.png \ qt/res/icons/key.png \ qt/res/icons/lock_closed.png \ qt/res/icons/lock_open.png \ - qt/res/icons/karmanodes.png \ - qt/res/icons/karmanodes_off.png \ + qt/res/icons/onion.png \ qt/res/icons/overview.png \ qt/res/icons/overview_off.png \ qt/res/icons/qrcode.png \ @@ -401,7 +402,7 @@ qt_libbitcoinqt_a_CXXFLAGS = $(AM_CXXFLAGS) $(QT_PIE_FLAGS) qt_libbitcoinqt_a_OBJCXXFLAGS = $(AM_OBJCXXFLAGS) $(QT_PIE_FLAGS) qt_libbitcoinqt_a_SOURCES = $(BITCOIN_QT_CPP) $(BITCOIN_QT_H) $(QT_FORMS_UI) \ - $(QT_QRC) $(QT_QRC_LOCALE) $(QT_TS) $(PROTOBUF_PROTO) $(RES_ICONS) $(RES_IMAGES) $(RES_CSS) $(RES_TEXT) $(RES_MOVIES) + $(QT_QRC) $(QT_QRC_LOCALE) $(QT_TS) $(PROTOBUF_PROTO) $(RES_ICONS) $(RES_IMAGES) $(RES_CSS) $(RES_TEXT) $(RES_MOVIES) nodist_qt_libbitcoinqt_a_SOURCES = $(QT_MOC_CPP) $(QT_MOC) $(PROTOBUF_CC) \ $(PROTOBUF_H) $(QT_QRC_CPP) $(QT_QRC_LOCALE_CPP) @@ -495,4 +496,4 @@ moc_%.cpp: %.h %.qm: %.ts @test -f $(LRELEASE) @$(MKDIR_P) $(@D) - $(AM_V_GEN) QT_SELECT=$(QT_SELECT) $(LRELEASE) -silent $< -qm $@ \ No newline at end of file + $(AM_V_GEN) QT_SELECT=$(QT_SELECT) $(LRELEASE) -silent $< -qm $@ diff --git a/src/Makefile.test.include b/src/Makefile.test.include index 0a3d1da..f5a82e5 100755 --- a/src/Makefile.test.include +++ b/src/Makefile.test.include @@ -85,7 +85,8 @@ BITCOIN_TESTS =\ if ENABLE_WALLET BITCOIN_TESTS += \ test/accounting_tests.cpp \ - test/wallet_tests.cpp + wallet/test/wallet_tests.cpp \ + test/rpc_wallet_tests.cpp endif test_test_ohmcoin_SOURCES = $(BITCOIN_TESTS) $(JSON_TEST_FILES) $(RAW_TEST_FILES) diff --git a/src/activekarmanode.cpp b/src/activekarmanode.cpp index 88dfa71..2e4b64c 100755 --- a/src/activekarmanode.cpp +++ b/src/activekarmanode.cpp @@ -218,7 +218,7 @@ bool CActiveKarmanode::SendKarmanodePing(std::string& errorMessage) LogPrint("karmanode", "dseep - relaying from active mn, %s \n", vin.ToString().c_str()); LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodes) + for (CNode* pnode : vNodes) pnode->PushMessage(NetMsgType::DSEEP, vin, vchMasterNodeSignature, masterNodeSignatureTime, false); /* @@ -326,7 +326,7 @@ bool CActiveKarmanode::CreateBroadcast(CTxIn vin, CService service, CKey keyColl } LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodes) + for (CNode* pnode : vNodes) pnode->PushMessage("dsee", vin, service, vchMasterNodeSignature, masterNodeSignatureTime, pubKeyCollateralAddress, pubKeyKarmanode, -1, -1, masterNodeSignatureTime, PROTOCOL_VERSION, donationAddress, donationPercantage); /* @@ -363,7 +363,7 @@ bool CActiveKarmanode::GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secre } bool found = false; - BOOST_FOREACH (COutput& out, possibleCoins) { + for (COutput& out : possibleCoins) { if (out.tx->GetHash() == txHash && out.i == outputIndex) { selectedOutput = &out; found = true; @@ -425,7 +425,7 @@ vector CActiveKarmanode::SelectCoinsKarmanode() // Temporary unlock MN coins from karmanode.conf if (GetBoolArg("-mnconflock", true)) { uint256 mnTxHash; - BOOST_FOREACH (CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { + for (CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { mnTxHash.SetHex(mne.getTxHash()); int nIndex; @@ -443,12 +443,12 @@ vector CActiveKarmanode::SelectCoinsKarmanode() // Lock MN coins from karmanode.conf back if they where temporary unlocked if (!confLockedCoins.empty()) { - BOOST_FOREACH (COutPoint outpoint, confLockedCoins) + for (COutPoint outpoint : confLockedCoins) pwalletMain->LockCoin(outpoint); } // Filter - BOOST_FOREACH (const COutput& out, vCoins) { + for (const COutput& out : vCoins) { if (out.tx->vout[out.i].nValue == MASTER_NODE_AMOUNT * COIN) { //exactly filteredCoins.push_back(out); } diff --git a/src/activekarmanode.h b/src/activekarmanode.h index 075d2c0..894bc68 100755 --- a/src/activekarmanode.h +++ b/src/activekarmanode.h @@ -12,7 +12,7 @@ #include "net.h" #include "obfuscation.h" #include "sync.h" -#include "wallet.h" +#include "wallet/wallet.h" #define ACTIVE_KARMANODE_INITIAL 0 // initial state #define ACTIVE_KARMANODE_SYNC_IN_PROCESS 1 diff --git a/src/alert.cpp b/src/alert.cpp index 7722f36..668a5cc 100755 --- a/src/alert.cpp +++ b/src/alert.cpp @@ -20,7 +20,6 @@ #include #include -#include #include using namespace std; @@ -52,7 +51,7 @@ std::string CUnsignedAlert::ToString() const for (auto& n: setCancel) strSetCancel += strprintf("%d ", n); std::string strSetSubVer; - BOOST_FOREACH (std::string str, setSubVer) + for (std::string str : setSubVer) strSetSubVer += "\"" + str + "\" "; return strprintf( "CAlert(\n" @@ -213,7 +212,7 @@ bool CAlert::ProcessAlert(bool fThread) } // Check if this alert has been cancelled - BOOST_FOREACH (PAIRTYPE(const uint256, CAlert) & item, mapAlerts) { + for (std::pair & item : mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { LogPrint("alert", "alert already cancelled by %d\n", alert.nID); diff --git a/src/bloom.cpp b/src/bloom.cpp index eb6ec01..a7196f0 100755 --- a/src/bloom.cpp +++ b/src/bloom.cpp @@ -13,15 +13,13 @@ #include #include -#include - #define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455 #define LN2 0.6931471805599453094172321214581765680755001343602552 using namespace std; CBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweakIn, unsigned char nFlagsIn) : - /** + /** * The ideal size for a bloom filter with a given number of elements and false positive rate is: * - nElements * log(fp rate) / ln(2)^2 * We ignore filter parameters which will create a bloom filter larger than the protocol limits @@ -157,7 +155,7 @@ bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx) if (fFound) return true; - BOOST_FOREACH (const CTxIn& txin, tx.vin) { + for (const CTxIn& txin : tx.vin) { // Match if the filter contains an outpoint tx spends if (contains(txin.prevout)) return true; diff --git a/src/chain.h b/src/chain.h index d733d71..6349032 100755 --- a/src/chain.h +++ b/src/chain.h @@ -16,8 +16,6 @@ #include -#include - struct CDiskBlockPos { int nFile; unsigned int nPos; @@ -178,11 +176,11 @@ class CBlockIndex //! (memory only) Sequential id assigned to distinguish order in which blocks are received. uint32_t nSequenceId; - + //! zerocoin specific fields std::map mapZerocoinSupply; std::vector vMintDenominationsInBlock; - + void SetNull() { phashBlock = NULL; @@ -254,7 +252,7 @@ class CBlockIndex nStakeTime = 0; } } - + CDiskBlockPos GetBlockPos() const { @@ -375,7 +373,7 @@ class CBlockIndex /** * Returns true if there are nRequired or more blocks of minVersion or above - * in the last Params().ToCheckBlockUpgradeMajority() blocks, starting at pstart + * in the last Params().ToCheckBlockUpgradeMajority() blocks, starting at pstart * and going backwards. */ static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired); diff --git a/src/chainparams.cpp b/src/chainparams.cpp index a2f0348..1d94c0d 100755 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -15,7 +15,6 @@ #include #include "crypto/scrypt.h" -//#include "util.h" #include #include #include @@ -326,14 +325,17 @@ static Checkpoints::MapCheckpoints mapCheckpoints = (462146, uint256("0xb0ffff92a2933dd8bafba722d7c6ea6413840a863ba0ef22794561e4f944ff6f")) (618641, uint256("0x247f41f60b4fd8de2727d6745c544f6b399d6712c1cdc7f00a8a909b830bf015")) (831256, uint256("0x3913ccd8359e7d7f81df2fc2b5f68848b6aa3663f84c87899691eb0e43454eec")) - (2848716, uint256("0x19dfab7fbb6dd6ff84fed0bda251632376d70054376da4469f5498dc3e575fb6")); + (2848716, uint256("0x19dfab7fbb6dd6ff84fed0bda251632376d70054376da4469f5498dc3e575fb6")) + (2967145, uint256("0x389fc6e4ee47eee73ffdc77727d3235be1095c23c071933fb7e343f7b6e544e2")) + (2977932, uint256("0x9d17db9fd8034fd02cf24f85cd1e68b2a09553b422ac14f8ef83c5ec171af4d3")) + (2991900, uint256("0xa13a332af480005d03bb4e72c32a84637d2b47e6de9689c52db1a03112ca5858")); static const Checkpoints::CCheckpointData data = { &mapCheckpoints, - 1597086644, // * UNIX timestamp of last checkpoint block - 5749439, // * total number of transactions between genesis and last checkpoint + 1604285153, // * UNIX timestamp of last checkpoint block + 6047912, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) - 2880 // * estimated number of transactions per day after checkpoint + 500 // * estimated number of transactions per day after checkpoint }; static Checkpoints::MapCheckpoints mapCheckpointsTestnet = @@ -492,17 +494,25 @@ class CMainParams : public CChainParams // Network upgrades consensus.vUpgrades[Consensus::BASE_NETWORK].nActivationHeight = - Consensus::NetworkUpgrade::ALWAYS_ACTIVE; + Consensus::NetworkUpgrade::ALWAYS_ACTIVE; consensus.vUpgrades[Consensus::UPGRADE_TESTDUMMY].nActivationHeight = - Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT; + Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT; + // Version 3.0.2 upgrade consensus.vUpgrades[Consensus::UPGRADE_V3_0_BLOCKTIME].nActivationHeight = 2977924; consensus.vUpgrades[Consensus::UPGRADE_V3_0_BLOCKTIME].nProtocolVersion = 71020; consensus.vUpgrades[Consensus::UPGRADE_V3_0_BLOCKREWARD].nActivationHeight = 2977924; consensus.vUpgrades[Consensus::UPGRADE_V3_0_BLOCKREWARD].nProtocolVersion = 71020; + // Next version dummy consensus.vUpgrades[Consensus::UPGRADE_V3_1_DUMMY].nActivationHeight = - Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT; + Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT; consensus.vUpgrades[Consensus::UPGRADE_V3_2_DUMMY].nActivationHeight = - Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT; + Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT; + + // Version 3.0.2 block activated at + consensus.vUpgrades[Consensus::UPGRADE_V3_0_BLOCKTIME].hashActivationBlock = + uint256S("0xce02f419dcac41e3a94c4284eee1d6525b1f5c0129a4242be8f01699df965157"); + consensus.vUpgrades[Consensus::UPGRADE_V3_0_BLOCKREWARD].hashActivationBlock = + uint256S("0xce02f419dcac41e3a94c4284eee1d6525b1f5c0129a4242be8f01699df965157"); } diff --git a/src/checkpoints.cpp b/src/checkpoints.cpp index 7c5cd13..d1917ab 100755 --- a/src/checkpoints.cpp +++ b/src/checkpoints.cpp @@ -6,15 +6,13 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "checkpoints.h" - #include "chainparams.h" +#include "reverse_iterator.h" #include "main.h" #include "uint256.h" #include -#include - namespace Checkpoints { /** @@ -91,7 +89,7 @@ CBlockIndex* GetLastCheckpoint() const MapCheckpoints& checkpoints = *Params().Checkpoints().mapCheckpoints; - BOOST_REVERSE_FOREACH (const MapCheckpoints::value_type& i, checkpoints) { + for (const MapCheckpoints::value_type& i : reverse_iterate (checkpoints)) { const uint256& hash = i.second; BlockMap::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) diff --git a/src/checkqueue.h b/src/checkqueue.h index 9648347..485efa0 100755 --- a/src/checkqueue.h +++ b/src/checkqueue.h @@ -16,7 +16,7 @@ template class CCheckQueueControl; -/** +/** * Queue for verifications that have to be performed. * The verifications are represented by a type T, which must provide an * operator(), returning a bool. @@ -119,7 +119,7 @@ class CCheckQueue fOk = fAllOk; } // execute work - BOOST_FOREACH (T& check, vChecks) + for (T& check : vChecks) if (fOk) fOk = check(); vChecks.clear(); @@ -146,7 +146,7 @@ class CCheckQueue void Add(std::vector& vChecks) { boost::unique_lock lock(mutex); - BOOST_FOREACH (T& check, vChecks) { + for (T& check : vChecks) { queue.push_back(T()); check.swap(queue.back()); } @@ -168,7 +168,7 @@ class CCheckQueue } }; -/** +/** * RAII-style controller object for a CCheckQueue that guarantees the passed * queue is finished before continuing. */ diff --git a/src/coins.h b/src/coins.h index 90ba08b..35e562f 100755 --- a/src/coins.h +++ b/src/coins.h @@ -15,10 +15,9 @@ #include #include -#include #include -/** +/** ****Note - for Ohmcoin we added fCoinStake to the 2nd bit. Keep in mind when reading the following and adjust as needed. * Pruned version of CTransaction: only retains metadata and unspent transaction outputs @@ -127,7 +126,7 @@ class CCoins void ClearUnspendable() { - BOOST_FOREACH (CTxOut& txout, vout) { + for (CTxOut& txout : vout) { if (txout.scriptPubKey.IsUnspendable()) txout.SetNull(); } @@ -278,7 +277,7 @@ class CCoins //! note that only !IsPruned() CCoins can be serialized bool IsPruned() const { - BOOST_FOREACH (const CTxOut& out, vout) + for (const CTxOut& out : vout) if (!out.IsNull()) return false; return true; @@ -388,10 +387,10 @@ enum { static const unsigned int STANDARD_LOCKTIME_VERIFY_FLAGS = LOCKTIME_VERIFY_SEQUENCE | LOCKTIME_MEDIAN_TIME_PAST; -/** +/** * A reference to a mutable cache entry. Encapsulating it allows us to run * cleanup code after the modification is finished, and keeping track of - * concurrent modifications. + * concurrent modifications. */ class CCoinsModifier { @@ -416,7 +415,7 @@ class CCoinsViewCache : public CCoinsViewBacked /** * Make mutable so that we can "fill the cache" even from Get-methods - * declared as "const". + * declared as "const". */ mutable uint256 hashBlock; mutable CCoinsMap cacheCoins; @@ -456,7 +455,7 @@ class CCoinsViewCache : public CCoinsViewBacked //! Calculate the size of the cache (in number of transactions) unsigned int GetCacheSize() const; - /** + /** * Amount of ohmcoin coming in to a transaction * Note that lightweight clients may not know anything besides the hash of previous transactions, * so may not be able to calculate this. diff --git a/src/core_write.cpp b/src/core_write.cpp index 574008d..878c6f3 100755 --- a/src/core_write.cpp +++ b/src/core_write.cpp @@ -6,7 +6,7 @@ #include "base58.h" #include "primitives/transaction.h" -#include "rpcprotocol.h" +#include "rpc/protocol.h" #include "script/script.h" #include "script/standard.h" #include "serialize.h" @@ -16,8 +16,6 @@ #include "utilmoneystr.h" #include "utilstrencodings.h" -#include - using namespace std; string FormatScript(const CScript& script) @@ -83,7 +81,7 @@ void ScriptPubKeyToUniv(const CScript& scriptPubKey, out.pushKV("type", GetTxnOutputType(type)); UniValue a(UniValue::VARR); - BOOST_FOREACH (const CTxDestination& addr, addresses) + for (const CTxDestination& addr : addresses) a.push_back(EncodeDestination(addr)); out.pushKV("addresses", a); } @@ -95,7 +93,7 @@ void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry) entry.pushKV("locktime", (int64_t)tx.nLockTime); UniValue vin(UniValue::VARR); - BOOST_FOREACH (const CTxIn& txin, tx.vin) { + for (const CTxIn& txin : tx.vin) { UniValue in(UniValue::VOBJ); if (tx.IsCoinBase()) in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); diff --git a/src/crypter.cpp b/src/crypter.cpp index e179356..94456a3 100755 --- a/src/crypter.cpp +++ b/src/crypter.cpp @@ -10,10 +10,9 @@ #include "init.h" #include "uint256.h" -#include #include #include -#include "wallet.h" +#include "wallet/wallet.h" bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod) { @@ -424,7 +423,7 @@ bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn) return false; fUseCrypto = true; - BOOST_FOREACH (KeyMap::value_type& mKey, mapKeys) { + for (KeyMap::value_type& mKey : mapKeys) { const CKey& key = mKey.second; CPubKey vchPubKey = key.GetPubKey(); CKeyingMaterial vchSecret(key.begin(), key.end()); diff --git a/src/httprpc.cpp b/src/httprpc.cpp index 98ac750..9441151 100644 --- a/src/httprpc.cpp +++ b/src/httprpc.cpp @@ -3,8 +3,8 @@ #include "base58.h" #include "chainparams.h" #include "httpserver.h" -#include "rpcprotocol.h" -#include "rpcserver.h" +#include "rpc/protocol.h" +#include "rpc/server.h" #include "random.h" #include "sync.h" #include "util.h" diff --git a/src/httpserver.cpp b/src/httpserver.cpp index 6baaeff..6b8646b 100644 --- a/src/httpserver.cpp +++ b/src/httpserver.cpp @@ -8,7 +8,7 @@ #include "compat.h" #include "util.h" #include "netbase.h" -#include "rpcprotocol.h" // For HTTP status codes +#include "rpc/protocol.h" // For HTTP status codes #include "sync.h" #include "ui_interface.h" @@ -35,7 +35,6 @@ #endif #include // for to_lower() -#include #include /** Maximum size of http request (request line + headers) */ @@ -195,7 +194,7 @@ static bool ClientAllowed(const CNetAddr& netaddr) { if (!netaddr.IsValid()) return false; - BOOST_FOREACH (const CSubNet& subnet, rpc_allow_subnets) + for (const CSubNet& subnet : rpc_allow_subnets) if (subnet.Match(netaddr)) return true; return false; @@ -209,7 +208,7 @@ static bool InitHTTPAllowList() rpc_allow_subnets.push_back(CSubNet("::1")); // always allow IPv6 localhost if (mapMultiArgs.count("-rpcallowip")) { const std::vector& vAllow = mapMultiArgs["-rpcallowip"]; - BOOST_FOREACH (std::string strAllow, vAllow) { + for (std::string strAllow : vAllow) { CSubNet subnet(strAllow); if (!subnet.IsValid()) { uiInterface.ThreadSafeMessageBox( @@ -221,7 +220,7 @@ static bool InitHTTPAllowList() } } std::string strAllowed; - BOOST_FOREACH (const CSubNet& subnet, rpc_allow_subnets) + for (const CSubNet& subnet : rpc_allow_subnets) strAllowed += subnet.ToString() + " "; LogPrint("http", "Allowing HTTP connections from: %s\n", strAllowed); return true; @@ -458,7 +457,7 @@ void InterruptHTTPServer() { LogPrint("http", "Interrupting HTTP server\n"); if (eventHTTP) { - BOOST_FOREACH (evhttp_bound_socket *socket, boundSockets) { + for (evhttp_bound_socket *socket : boundSockets) { evhttp_del_accept_socket(eventHTTP, socket); } evhttp_set_gencb(eventHTTP, http_reject_request_cb, NULL); @@ -474,6 +473,7 @@ void StopHTTPServer() LogPrint("http", "Waiting for HTTP worker threads to exit\n"); workQueue->WaitExit(); delete workQueue; + workQueue = nullptr; } MilliSleep(500); // Avoid race condition while the last HTTP-thread is exiting if (eventBase) { diff --git a/src/init.cpp b/src/init.cpp index 4ca0252..235ef5e 100755 --- a/src/init.cpp +++ b/src/init.cpp @@ -30,7 +30,8 @@ #include "karmanodeman.h" #include "miner.h" #include "net.h" -#include "rpcserver.h" +#include "reverse_iterator.h" +#include "rpc/server.h" #include "script/standard.h" #include "scheduler.h" #include "spork.h" @@ -42,9 +43,9 @@ #include "utilmoneystr.h" #include "validationinterface.h" #ifdef ENABLE_WALLET -#include "db.h" -#include "wallet.h" -#include "walletdb.h" +#include "wallet/db.h" +#include "wallet/wallet.h" +#include "wallet/walletdb.h" #include "accumulators.h" #endif @@ -172,14 +173,15 @@ class CCoinsViewErrorCatcher : public CCoinsViewBacked static CCoinsViewDB* pcoinsdbview = NULL; static CCoinsViewErrorCatcher* pcoinscatcher = NULL; -void Interrupt(boost::thread_group& threadGroup) +static boost::thread_group threadGroup; +static CScheduler scheduler; +void Interrupt() { InterruptHTTPServer(); InterruptHTTPRPC(); InterruptRPC(); InterruptREST(); InterruptTorControl(); - threadGroup.interrupt_all(); } /** Preparing steps before shutting down or restarting the wallet */ @@ -214,6 +216,11 @@ void PrepareShutdown() DumpKarmanodePayments(); UnregisterNodeSignals(GetNodeSignals()); + // After everything has been shut down, but before things get flushed, stop the + // CScheduler/checkqueue threadGroup + threadGroup.interrupt_all(); + threadGroup.join_all(); + if (fFeeEstimatesInitialized) { boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME; CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION); @@ -299,7 +306,7 @@ void Shutdown() */ void HandleSIGTERM(int) { - fRequestShutdown = true; + StartShutdown(); } void HandleSIGHUP(int) @@ -307,6 +314,17 @@ void HandleSIGHUP(int) fReopenDebugLog = true; } +#ifndef WIN32 +static void registerSignalHandler(int signal, void(*handler)(int)) +{ + struct sigaction sa; + sa.sa_handler = handler; + sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; + sigaction(signal, &sa, nullptr); +} +#endif + bool static InitError(const std::string& str) { uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR); @@ -679,7 +697,7 @@ void ThreadImport(std::vector vImportFiles) } // -loadblock= - BOOST_FOREACH (boost::filesystem::path& path, vImportFiles) { + for (boost::filesystem::path& path : vImportFiles) { FILE* file = fopen(path.string().c_str(), "rb"); if (file) { CImportingNow imp; @@ -713,7 +731,7 @@ bool InitSanityCheck(void) return true; } -bool AppInitServers(boost::thread_group& threadGroup) +bool AppInitServers() { RPCServer::OnStopped(&OnRPCStopped); RPCServer::OnPreCommand(&OnRPCPreCommand); @@ -766,10 +784,21 @@ bool InitNUParams() return true; } -/** Initialize ohmcoin. - * @pre Parameters should be parsed and config file should be read. - */ -bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) +[[noreturn]] static void new_handler_terminate() +{ + // Rather than throwing std::bad-alloc if allocation fails, terminate + // immediately to (try to) avoid chain corruption. + // Since LogPrintf may itself allocate memory, set the handler directly + // to terminate first. + std::set_new_handler(std::terminate); + LogPrintf("Error: Out of memory. Terminating.\n"); + + // The log was successful, terminate now. + std::terminate(); +}; + +bool AppInitBasicSetup() + { // ********************************************************* Step 1: setup #ifdef _MSC_VER @@ -809,25 +838,31 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) } - // Clean shutdown on SIGTERM - struct sigaction sa; - sa.sa_handler = HandleSIGTERM; - sigemptyset(&sa.sa_mask); - sa.sa_flags = 0; - sigaction(SIGTERM, &sa, NULL); - sigaction(SIGINT, &sa, NULL); + // Clean shutdown on SIGTERMx + registerSignalHandler(SIGTERM, HandleSIGTERM); + registerSignalHandler(SIGINT, HandleSIGTERM); // Reopen debug.log on SIGHUP - struct sigaction sa_hup; - sa_hup.sa_handler = HandleSIGHUP; - sigemptyset(&sa_hup.sa_mask); - sa_hup.sa_flags = 0; - sigaction(SIGHUP, &sa_hup, NULL); + registerSignalHandler(SIGHUP, HandleSIGHUP); // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly signal(SIGPIPE, SIG_IGN); #endif + std::set_new_handler(new_handler_terminate); + + return true; +} + +/** Initialize pivx. + * @pre Parameters should be parsed and config file should be read. + */ +bool AppInit2() +{ + // ********************************************************* Step 1: setup + if (!AppInitBasicSetup()) + return false; + // ********************************************************* Step 2: parameter interactions // Set this early so that parameter interactions go to console fPrintToConsole = GetBoolArg("-printtoconsole", false); @@ -950,7 +985,6 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS) nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS; - fServer = GetBoolArg("-server", false); setvbuf(stdout, NULL, _IOLBF, 0); /// ***TODO*** do we still need this after -printtoconsole is gone? // Staking needs a CWallet instance, so make sure wallet is enabled @@ -1101,14 +1135,12 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) * that the server is there and will be ready later). Warmup mode will * be disabled when initialisation is finished. */ - if (fServer) { + if (GetBoolArg("-server", false)) { uiInterface.InitMessage.connect(SetRPCWarmupStatus); - if (!AppInitServers(threadGroup)) + if (!AppInitServers()) return InitError(_("Unable to start HTTP server. See debug log for details.")); } - int64_t nStart; - // ********************************************************* Step 5: Backup wallet and verify wallet database integrity #ifdef ENABLE_WALLET if (!fDisableWallet) { @@ -1165,7 +1197,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) } // Loop backward through backup files and keep the N newest ones (1 <= N <= 10) int counter = 0; - BOOST_REVERSE_FOREACH (PAIRTYPE(const std::time_t, boost::filesystem::path) file, folder_set) { + for (std::pair file : reverse_iterate ( folder_set)) { counter++; if (counter > nWalletBackups) { // More than nWalletBackups backups: delete oldest one(s) @@ -1271,7 +1303,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) if (mapArgs.count("-onlynet")) { std::set nets; - BOOST_FOREACH (std::string snet, mapMultiArgs["-onlynet"]) { + for (std::string snet : mapMultiArgs["-onlynet"]) { enum Network net = ParseNetwork(snet); if (net == NET_UNROUTABLE) return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet)); @@ -1285,7 +1317,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) } if (mapArgs.count("-whitelist")) { - BOOST_FOREACH (const std::string& net, mapMultiArgs["-whitelist"]) { + for (const std::string& net : mapMultiArgs["-whitelist"]) { CSubNet subnet(net); if (!subnet.IsValid()) return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net)); @@ -1345,13 +1377,13 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) bool fBound = false; if (fListen) { if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) { - BOOST_FOREACH (std::string strBind, mapMultiArgs["-bind"]) { + for (std::string strBind : mapMultiArgs["-bind"]) { CService addrBind; if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind)); fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR)); } - BOOST_FOREACH (std::string strBind, mapMultiArgs["-whitebind"]) { + for (std::string strBind : mapMultiArgs["-whitebind"]) { CService addrBind; if (!Lookup(strBind.c_str(), addrBind, 0, false)) return InitError(strprintf(_("Cannot resolve -whitebind address: '%s'"), strBind)); @@ -1370,7 +1402,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) } if (mapArgs.count("-externalip")) { - BOOST_FOREACH (string strAddr, mapMultiArgs["-externalip"]) { + for (string strAddr : mapMultiArgs["-externalip"]) { CService addrLocal(strAddr, GetListenPort()); if (!addrLocal.IsValid()) return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr)); @@ -1378,7 +1410,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) } } - BOOST_FOREACH (string strDest, mapMultiArgs["-seednode"]) + for (string strDest : mapMultiArgs["-seednode"]) AddOneShot(strDest); #if ENABLE_ZMQ @@ -1441,8 +1473,9 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) uiInterface.InitMessage(_("Loading block index...")); - nStart = GetTimeMillis(); do { + const int64_t load_block_index_start_time = GetTimeMillis(); + try { UnloadBlockIndex(); delete pcoinsTip; @@ -1610,6 +1643,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) fVerifyingBlocks = false; fLoaded = true; + LogPrintf(" block index %15dms\n", GetTimeMillis() - load_block_index_start_time); } while (false); if (!fLoaded) { @@ -1638,7 +1672,6 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) LogPrintf("Shutdown requested. Exiting.\n"); return false; } - LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart); boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME; CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION); @@ -1674,7 +1707,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) uiInterface.InitMessage(_("Loading wallet...")); fVerifyingBlocks = true; - nStart = GetTimeMillis(); + const int64_t nWalletStartTime = GetTimeMillis(); bool fFirstRun = true; pwalletMain = new CWallet(strWalletFile); DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun); @@ -1722,7 +1755,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) } LogPrintf("%s", strErrors.str()); - LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart); + LogPrintf("Wallet completed loading in %15dms\n", GetTimeMillis() - nWalletStartTime); zwalletMain = new CzOHMCWallet(pwalletMain->strWalletFile); pwalletMain->setZWallet(zwalletMain); @@ -1743,15 +1776,17 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) if (chainActive.Tip() && chainActive.Tip() != pindexRescan) { uiInterface.InitMessage(_("Rescanning...")); LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight); - nStart = GetTimeMillis(); - pwalletMain->ScanForWalletTransactions(pindexRescan, true); - LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart); + const int64_t nWalletRescanTime = GetTimeMillis(); + if (pwalletMain->ScanForWalletTransactions(pindexRescan, true, true) == -1) { + return error("Shutdown requested over the txs scan. Exiting."); + } + LogPrintf("Rescan completed in %15dms\n", GetTimeMillis() - nWalletRescanTime); pwalletMain->SetBestChain(chainActive.GetLocator()); nWalletDBUpdated++; // Restore wallet transaction metadata after -zapwallettxes=1 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2") { - BOOST_FOREACH (const CWalletTx& wtxOld, vWtx) { + for (const CWalletTx& wtxOld : vWtx) { uint256 hash = wtxOld.GetHash(); std::map::iterator mi = pwalletMain->mapWallet.find(hash); if (mi != pwalletMain->mapWallet.end()) { @@ -1822,7 +1857,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) std::vector vImportFiles; if (mapArgs.count("-loadblock")) { - BOOST_FOREACH (string strFile, mapMultiArgs["-loadblock"]) + for (string strFile : mapMultiArgs["-loadblock"]) vImportFiles.push_back(strFile); } threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles)); @@ -1928,7 +1963,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) LOCK(pwalletMain->cs_wallet); LogPrintf("Locking Karmanodes:\n"); uint256 mnTxHash; - BOOST_FOREACH (CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { + for (CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { LogPrintf(" %s %s\n", mne.getTxHash(), mne.getOutputIndex()); mnTxHash.SetHex(mne.getTxHash()); COutPoint outpoint = COutPoint(mnTxHash, boost::lexical_cast(mne.getOutputIndex())); diff --git a/src/init.h b/src/init.h index 02c1a84..f8ef10e 100755 --- a/src/init.h +++ b/src/init.h @@ -23,10 +23,16 @@ extern CzOHMCWallet* zwalletMain; void StartShutdown(); bool ShutdownRequested(); /** Interrupt threads */ -void Interrupt(boost::thread_group& threadGroup); +void Interrupt(); void Shutdown(); void PrepareShutdown(); -bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler); +bool AppInit2(); + +/** Initialize Ohmcoin core: Basic context setup. + * @note This can be done before daemonization. Do not call Shutdown() if this function fails. + * @pre Parameters should be parsed and config file should be read. + */ +bool AppInitBasicSetup(); /** The help message mode determines what help message to show */ enum HelpMessageMode { diff --git a/src/karmanode-budget.cpp b/src/karmanode-budget.cpp index b026782..c94c2d9 100755 --- a/src/karmanode-budget.cpp +++ b/src/karmanode-budget.cpp @@ -60,7 +60,7 @@ bool IsBudgetCollateralValid(uint256 nTxCollateralHash, uint256 nExpectedHash, s findScript << OP_RETURN << ToByteVector(nExpectedHash); bool foundOpReturn = false; - BOOST_FOREACH (const CTxOut o, txCollateral.vout) { + for (const CTxOut o : txCollateral.vout) { if (!o.scriptPubKey.IsNormalPaymentScript() && !o.scriptPubKey.IsUnspendable()) { strError = strprintf("Invalid Script %s", txCollateral.ToString()); LogPrint("knbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); @@ -973,7 +973,7 @@ void CBudgetManager::NewBlock() } LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodes) + for (CNode* pnode : vNodes) if (pnode->nVersion >= ActiveProtocol()) Sync(pnode, 0, true); @@ -1991,7 +1991,7 @@ std::string CFinalizedBudget::GetProposals() LOCK(cs); std::string ret = ""; - BOOST_FOREACH (CTxBudgetPayment& budgetPayment, vecBudgetPayments) { + for (CTxBudgetPayment& budgetPayment : vecBudgetPayments) { CBudgetProposal* pbudgetProposal = budget.FindProposal(budgetPayment.nProposalHash); std::string token = budgetPayment.nProposalHash.ToString(); @@ -2158,7 +2158,7 @@ TrxValidationStatus CFinalizedBudget::IsTransactionValid(const CTransaction& txN } bool paid = false; - BOOST_FOREACH (CTxOut out, txNew.vout) { + for (CTxOut out : txNew.vout) { LogPrint("knbudget","CFinalizedBudget::IsTransactionValid - nCurrentBudgetPayment=%d, payee=%s == out.scriptPubKey=%s, amount=%ld == out.nValue=%ld\n", nCurrentBudgetPayment, vecBudgetPayments[nCurrentBudgetPayment].payee.ToString().c_str(), out.scriptPubKey.ToString().c_str(), vecBudgetPayments[nCurrentBudgetPayment].nAmount, out.nValue); @@ -2235,7 +2235,7 @@ CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast(const CFinalizedBudget& oth { strBudgetName = other.strBudgetName; nBlockStart = other.nBlockStart; - BOOST_FOREACH (CTxBudgetPayment out, other.vecBudgetPayments) + for (CTxBudgetPayment out : other.vecBudgetPayments) vecBudgetPayments.push_back(out); mapVotes = other.mapVotes; nFeeTXHash = other.nFeeTXHash; @@ -2245,7 +2245,7 @@ CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast(std::string strBudgetNameIn { strBudgetName = strBudgetNameIn; nBlockStart = nBlockStartIn; - BOOST_FOREACH (CTxBudgetPayment out, vecBudgetPaymentsIn) + for (CTxBudgetPayment out : vecBudgetPaymentsIn) vecBudgetPayments.push_back(out); mapVotes.clear(); nFeeTXHash = nFeeTXHashIn; diff --git a/src/karmanode-payments.cpp b/src/karmanode-payments.cpp index 3fe83a3..c0bebe0 100755 --- a/src/karmanode-payments.cpp +++ b/src/karmanode-payments.cpp @@ -225,7 +225,7 @@ bool IsBlockValueValid(const CBlock& block, CAmount nExpectedValue, CAmount nMin bool IsBlockPayeeValid(const CBlock& block, int nBlockHeight) { TrxValidationStatus transactionStatus = TrxValidationStatus::Invalid; - + if (!karmanodeSync.IsSynced()) { //there is no budget data to use to check anything -- find the longest chain LogPrint("mnpayments", "Client not synced, skipping block payee checks\n"); return true; @@ -330,7 +330,20 @@ void CKarmanodePayments::FillBlockPayee(CMutableTransaction& txNew, int64_t nFee txNew.vout[i].nValue = karmanodePayment; //subtract mn payment from the stake reward - txNew.vout[i - 1].nValue -= karmanodePayment; + if (i == 2) { + // Majority of cases; do it quick and move on + txNew.vout[i - 1].nValue -= karmanodePayment; + } else if (i > 2) { + // special case, stake is split between (i-1) outputs + unsigned int outputs = i-1; + CAmount knPaymentSplit = karmanodePayment / outputs; + CAmount knPaymentRemainder = karmanodePayment - (knPaymentSplit * outputs); + for (unsigned int j=1; j<=outputs; j++) { + txNew.vout[j].nValue -= knPaymentSplit; + } + // in case it's not an even division, take the last bit of dust from the last one + txNew.vout[outputs].nValue -= knPaymentRemainder; + } } else { txNew.vout.resize(2); txNew.vout[1].scriptPubKey = payee; @@ -539,16 +552,16 @@ bool CKarmanodeBlockPayees::IsTransactionValid(const CTransaction& txNew) CAmount requiredKarmanodePayment = GetKarmanodePayment(nBlockHeight, nReward, nKarmanode_Drift_Count); //require at least 6 signatures - BOOST_FOREACH (CKarmanodePayee& payee, vecPayments) + for (CKarmanodePayee& payee : vecPayments) if (payee.nVotes >= nMaxSignatures && payee.nVotes >= MNPAYMENTS_SIGNATURES_REQUIRED) nMaxSignatures = payee.nVotes; // if we don't have at least 6 signatures on a payee, approve whichever is the longest chain if (nMaxSignatures < MNPAYMENTS_SIGNATURES_REQUIRED) return true; - BOOST_FOREACH (CKarmanodePayee& payee, vecPayments) { + for (CKarmanodePayee& payee : vecPayments) { bool found = false; - BOOST_FOREACH (CTxOut out, txNew.vout) { + for (CTxOut out : txNew.vout) { if (payee.scriptPubKey == out.scriptPubKey) { if(out.nValue >= requiredKarmanodePayment) found = true; @@ -581,7 +594,7 @@ std::string CKarmanodeBlockPayees::GetRequiredPaymentsString() std::string ret = "Unknown"; - BOOST_FOREACH (CKarmanodePayee& payee, vecPayments) { + for (CKarmanodePayee& payee : vecPayments) { CTxDestination address; ExtractDestination(payee.scriptPubKey, address); diff --git a/src/karmanode-payments.h b/src/karmanode-payments.h index 76cee0a..727ff25 100755 --- a/src/karmanode-payments.h +++ b/src/karmanode-payments.h @@ -107,7 +107,7 @@ class CKarmanodeBlockPayees { LOCK(cs_vecPayments); - BOOST_FOREACH (CKarmanodePayee& payee, vecPayments) { + for (CKarmanodePayee& payee : vecPayments) { if (payee.scriptPubKey == payeeIn) { payee.nVotes += nIncrement; return; @@ -123,7 +123,7 @@ class CKarmanodeBlockPayees LOCK(cs_vecPayments); int nVotes = -1; - BOOST_FOREACH (CKarmanodePayee& p, vecPayments) { + for (CKarmanodePayee& p : vecPayments) { if (p.nVotes > nVotes) { payee = p.scriptPubKey; nVotes = p.nVotes; @@ -137,7 +137,7 @@ class CKarmanodeBlockPayees { LOCK(cs_vecPayments); - BOOST_FOREACH (CKarmanodePayee& p, vecPayments) { + for (CKarmanodePayee& p : vecPayments) { if (p.nVotes >= nVotesReq && p.scriptPubKey == payee) return true; } diff --git a/src/karmanode-sync.cpp b/src/karmanode-sync.cpp index 6718bb2..cf379cc 100755 --- a/src/karmanode-sync.cpp +++ b/src/karmanode-sync.cpp @@ -222,7 +222,7 @@ void CKarmanodeSync::ClearFulfilledRequest() TRY_LOCK(cs_vNodes, lockRecv); if (!lockRecv) return; - BOOST_FOREACH (CNode* pnode, vNodes) { + for (CNode* pnode : vNodes) { pnode->ClearFulfilledRequest(NetMsgType::GETSPORK); pnode->ClearFulfilledRequest("knsync"); pnode->ClearFulfilledRequest("knwsync"); @@ -237,7 +237,7 @@ void CKarmanodeSync::Process() if (tick++ % KARMANODE_SYNC_TIMEOUT != 0) return; if (IsSynced()) { - /* + /* Resync if we lose all karmanodes from sleep/wake or failure to sync originally */ if (mnodeman.CountEnabled() == 0) { @@ -264,7 +264,7 @@ void CKarmanodeSync::Process() TRY_LOCK(cs_vNodes, lockRecv); if (!lockRecv) return; - BOOST_FOREACH (CNode* pnode, vNodes) { + for (CNode* pnode : vNodes) { if (Params().NetworkID() == CBaseChainParams::REGTEST) { if (RequestedKarmanodeAttempt <= 2) { pnode->PushMessage(NetMsgType::GETSPORKS); //get current network sporks @@ -290,7 +290,7 @@ void CKarmanodeSync::Process() pnode->PushMessage("getsporks"); //get current network sporks if (RequestedKarmanodeAttempt >= 2) GetNextAsset(); RequestedKarmanodeAttempt++; - + return; } @@ -367,10 +367,10 @@ void CKarmanodeSync::Process() if (pnode->nVersion >= ActiveProtocol()) { if (RequestedKarmanodeAssets == KARMANODE_SYNC_BUDGET) { - + // We'll start rejecting votes if we accidentally get set as synced too soon if (lastBudgetItem > 0 && lastBudgetItem < GetTime() - KARMANODE_SYNC_TIMEOUT * 2 && RequestedKarmanodeAttempt >= KARMANODE_SYNC_THRESHOLD) { - + // Hasn't received a new item in the last five seconds, so we'll move to the GetNextAsset(); diff --git a/src/karmanode.h b/src/karmanode.h index 7eaf11e..0442dfa 100755 --- a/src/karmanode.h +++ b/src/karmanode.h @@ -222,13 +222,6 @@ class CKarmanode bool UpdateFromNewBroadcast(CKarmanodeBroadcast& mnb); - inline uint64_t SliceHash(uint256& hash, int slice) - { - uint64_t n = 0; - memcpy(&n, &hash + slice * 64, 64); - return n; - } - void Check(bool forceCheck = false); bool IsBroadcastedWithin(int seconds) diff --git a/src/karmanodeconfig.cpp b/src/karmanodeconfig.cpp index e98cb63..cdbc2a4 100755 --- a/src/karmanodeconfig.cpp +++ b/src/karmanodeconfig.cpp @@ -4,7 +4,7 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. // clang-format off -#include "net.h" +#include "netbase.h" #include "karmanodeconfig.h" #include "util.h" #include "ui_interface.h" @@ -60,15 +60,25 @@ bool CKarmanodeConfig::read(std::string& strErr) } } + int port = 0; + std::string hostname = ""; + SplitHostPort(ip, port, hostname); + if(port == 0 || hostname == "") { + strErr = _("Failed to parse host:port string") + "\n"+ + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\""; + streamConfig.close(); + return false; + } + if (Params().NetworkID() == CBaseChainParams::MAIN) { - if (CService(ip).GetPort() != 52020) { + if (port != 52020) { strErr = _("Invalid port detected in karmanode.conf") + "\n" + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" + _("(must be 52020 for mainnet)"); streamConfig.close(); return false; } - } else if (CService(ip).GetPort() == 52020) { + } else if (port == 52020) { strErr = _("Invalid port detected in karmanode.conf") + "\n" + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" + _("(52020 could be used only on mainnet)"); @@ -122,7 +132,7 @@ void CKarmanodeConfig::writeToKarmanodeConf() std::string karmanodeAliasBase = ""; - BOOST_FOREACH (CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { + for (CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { // Orders configs in proper strings std::string karmanodeAliasLine = mne.getAlias() + " " + mne.getIp() + " " + mne.getPrivKey() + " " + mne.getTxHash() + " " + mne.getOutputIndex() + "\n"; karmanodeAliasBase = karmanodeAliasBase + karmanodeAliasLine; @@ -134,4 +144,4 @@ void CKarmanodeConfig::writeToKarmanodeConf() clear(); std::string strErr; read(strErr); -} \ No newline at end of file +} diff --git a/src/karmanodeconfig.h b/src/karmanodeconfig.h index 604ec92..3ba29d8 100755 --- a/src/karmanodeconfig.h +++ b/src/karmanodeconfig.h @@ -109,7 +109,7 @@ class CKarmanodeConfig int getCount() { int c = -1; - BOOST_FOREACH (CKarmanodeEntry e, entries) { + for (CKarmanodeEntry e : entries) { if (e.getAlias() != "") c++; } return c; diff --git a/src/karmanodeman.cpp b/src/karmanodeman.cpp index 901ec79..3263267 100755 --- a/src/karmanodeman.cpp +++ b/src/karmanodeman.cpp @@ -235,7 +235,7 @@ void CKarmanodeMan::Check() { LOCK(cs); - BOOST_FOREACH (CKarmanode& mn, vKarmanodes) { + for (CKarmanode& mn : vKarmanodes) { mn.Check(); } } @@ -355,7 +355,7 @@ int CKarmanodeMan::stable_size () int64_t nKarmanode_Min_Age = MN_WINNER_MINIMUM_AGE; int64_t nKarmanode_Age = 0; - BOOST_FOREACH (CKarmanode& mn, vKarmanodes) { + for (CKarmanode& mn : vKarmanodes) { if (mn.protocolVersion < nMinProtocol) { continue; // Skip obsolete versions } @@ -380,7 +380,7 @@ int CKarmanodeMan::CountEnabled(int protocolVersion) int i = 0; protocolVersion = protocolVersion == -1 ? karmanodePayments.GetMinKarmanodePaymentsProto() : protocolVersion; - BOOST_FOREACH (CKarmanode& mn, vKarmanodes) { + for (CKarmanode& mn : vKarmanodes) { mn.Check(); if (mn.protocolVersion < protocolVersion || !mn.IsEnabled()) continue; i++; @@ -393,7 +393,7 @@ void CKarmanodeMan::CountNetworks(int protocolVersion, int& ipv4, int& ipv6, int { protocolVersion = protocolVersion == -1 ? karmanodePayments.GetMinKarmanodePaymentsProto() : protocolVersion; - BOOST_FOREACH (CKarmanode& mn, vKarmanodes) { + for (CKarmanode& mn : vKarmanodes) { mn.Check(); std::string strHost; int port; @@ -440,7 +440,7 @@ CKarmanode* CKarmanodeMan::Find(const CScript& payee) LOCK(cs); CScript payee2; - BOOST_FOREACH (CKarmanode& mn, vKarmanodes) { + for (CKarmanode& mn : vKarmanodes) { payee2 = GetScriptForDestination(mn.pubKeyCollateralAddress.GetID()); if (payee2 == payee) return &mn; @@ -452,7 +452,7 @@ CKarmanode* CKarmanodeMan::Find(const CTxIn& vin) { LOCK(cs); - BOOST_FOREACH (CKarmanode& mn, vKarmanodes) { + for (CKarmanode& mn : vKarmanodes) { if (mn.vin.prevout == vin.prevout) return &mn; } @@ -464,7 +464,7 @@ CKarmanode* CKarmanodeMan::Find(const CPubKey& pubKeyKarmanode) { LOCK(cs); - BOOST_FOREACH (CKarmanode& mn, vKarmanodes) { + for (CKarmanode& mn : vKarmanodes) { if (mn.pubKeyKarmanode == pubKeyKarmanode) return &mn; } @@ -486,7 +486,7 @@ CKarmanode* CKarmanodeMan::GetNextKarmanodeInQueueForPayment(int nBlockHeight, b */ int nMnCount = CountEnabled(); - BOOST_FOREACH (CKarmanode& mn, vKarmanodes) { + for (CKarmanode& mn : vKarmanodes) { mn.Check(); if (!mn.IsEnabled()) continue; @@ -520,7 +520,7 @@ CKarmanode* CKarmanodeMan::GetNextKarmanodeInQueueForPayment(int nBlockHeight, b int nTenthNetwork = CountEnabled() / 10; int nCountTenth = 0; uint256 nHigh = 0; - BOOST_FOREACH (PAIRTYPE(int64_t, CTxIn) & s, vecKarmanodeLastPaid) { + for (std::pair & s : vecKarmanodeLastPaid) { CKarmanode* pmn = Find(s.second); if (!pmn) break; @@ -549,10 +549,10 @@ CKarmanode* CKarmanodeMan::FindRandomNotInVec(std::vector& vecToExclude, LogPrint("karmanode", "CKarmanodeMan::FindRandomNotInVec - rand %d\n", rand); bool found; - BOOST_FOREACH (CKarmanode& mn, vKarmanodes) { + for (CKarmanode& mn : vKarmanodes) { if (mn.protocolVersion < protocolVersion || !mn.IsEnabled()) continue; found = false; - BOOST_FOREACH (CTxIn& usedVin, vecToExclude) { + for (CTxIn& usedVin : vecToExclude) { if (mn.vin.prevout == usedVin.prevout) { found = true; break; @@ -573,7 +573,7 @@ CKarmanode* CKarmanodeMan::GetCurrentMasterNode(int mod, int64_t nBlockHeight, i CKarmanode* winner = NULL; // scan for winner - BOOST_FOREACH (CKarmanode& mn, vKarmanodes) { + for (CKarmanode& mn : vKarmanodes) { mn.Check(); if (mn.protocolVersion < minProtocol || !mn.IsEnabled()) continue; @@ -602,7 +602,7 @@ int CKarmanodeMan::GetKarmanodeRank(const CTxIn& vin, int64_t nBlockHeight, int if (!GetBlockHash(hash, nBlockHeight)) return -1; // scan for winner - BOOST_FOREACH (CKarmanode& mn, vKarmanodes) { + for (CKarmanode& mn : vKarmanodes) { if (mn.protocolVersion < minProtocol) { LogPrint("karmanode","Skipping Karmanode with obsolete version %d\n", mn.protocolVersion); continue; // Skip obsolete versions @@ -628,7 +628,7 @@ int CKarmanodeMan::GetKarmanodeRank(const CTxIn& vin, int64_t nBlockHeight, int sort(vecKarmanodeScores.rbegin(), vecKarmanodeScores.rend(), CompareScoreTxIn()); int rank = 0; - BOOST_FOREACH (PAIRTYPE(int64_t, CTxIn) & s, vecKarmanodeScores) { + for (std::pair & s : vecKarmanodeScores) { rank++; if (s.second.prevout == vin.prevout) { return rank; @@ -648,7 +648,7 @@ std::vector > CKarmanodeMan::GetKarmanodeRanks(int64_t nBl if (!GetBlockHash(hash, nBlockHeight)) return vecKarmanodeRanks; // scan for winner - BOOST_FOREACH (CKarmanode& mn, vKarmanodes) { + for (CKarmanode& mn : vKarmanodes) { mn.Check(); if (mn.protocolVersion < minProtocol) continue; @@ -667,7 +667,7 @@ std::vector > CKarmanodeMan::GetKarmanodeRanks(int64_t nBl sort(vecKarmanodeScores.rbegin(), vecKarmanodeScores.rend(), CompareScoreMN()); int rank = 0; - BOOST_FOREACH (PAIRTYPE(int64_t, CKarmanode) & s, vecKarmanodeScores) { + for (std::pair & s : vecKarmanodeScores) { rank++; vecKarmanodeRanks.push_back(make_pair(rank, s.second)); } @@ -680,7 +680,7 @@ CKarmanode* CKarmanodeMan::GetKarmanodeByRank(int nRank, int64_t nBlockHeight, i std::vector > vecKarmanodeScores; // scan for winner - BOOST_FOREACH (CKarmanode& mn, vKarmanodes) { + for (CKarmanode& mn : vKarmanodes) { if (mn.protocolVersion < minProtocol) continue; if (fOnlyActive) { mn.Check(); @@ -696,7 +696,7 @@ CKarmanode* CKarmanodeMan::GetKarmanodeByRank(int nRank, int64_t nBlockHeight, i sort(vecKarmanodeScores.rbegin(), vecKarmanodeScores.rend(), CompareScoreTxIn()); int rank = 0; - BOOST_FOREACH (PAIRTYPE(int64_t, CTxIn) & s, vecKarmanodeScores) { + for (std::pair & s : vecKarmanodeScores) { rank++; if (rank == nRank) { return Find(s.second); @@ -712,7 +712,7 @@ void CKarmanodeMan::ProcessKarmanodeConnections() if (Params().NetworkID() == CBaseChainParams::REGTEST) return; LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodes) { + for (CNode* pnode : vNodes) { if (pnode->fObfuScationMaster) { if (obfuScationPool.pSubmittedToKarmanode != NULL && pnode->addr == obfuScationPool.pSubmittedToKarmanode->addr) continue; LogPrint("karmanode","Closing Karmanode connection peer=%i \n", pnode->GetId()); @@ -823,7 +823,7 @@ void CKarmanodeMan::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataS int nInvCount = 0; - BOOST_FOREACH (CKarmanode& mn, vKarmanodes) { + for (CKarmanode& mn : vKarmanodes) { if (mn.addr.IsRFC1918()) continue; //local network if (mn.IsEnabled()) { @@ -956,7 +956,7 @@ void CKarmanodeMan::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataS if (pmn->IsEnabled()) { TRY_LOCK(cs_vNodes, lockNodes); if (!lockNodes) return; - BOOST_FOREACH (CNode* pnode, vNodes) + for (CNode* pnode : vNodes) if (pnode->nVersion >= karmanodePayments.GetMinKarmanodePaymentsProto()) pnode->PushMessage(NetMsgType::DSEE, vin, addr, vchSig, sigTime, pubkey, pubkey2, count, current, lastUpdated, protocolVersion, donationAddress, donationPercentage); } @@ -1045,7 +1045,7 @@ void CKarmanodeMan::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataS if (mn.IsEnabled()) { TRY_LOCK(cs_vNodes, lockNodes); if (!lockNodes) return; - BOOST_FOREACH (CNode* pnode, vNodes) + for (CNode* pnode : vNodes) if (pnode->nVersion >= karmanodePayments.GetMinKarmanodePaymentsProto()) pnode->PushMessage(NetMsgType::DSEE, vin, addr, vchSig, sigTime, pubkey, pubkey2, count, current, lastUpdated, protocolVersion, donationAddress, donationPercentage); } @@ -1115,7 +1115,7 @@ void CKarmanodeMan::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataS TRY_LOCK(cs_vNodes, lockNodes); if (!lockNodes) return; LogPrint("karmanode", "dseep - relaying %s \n", vin.prevout.hash.ToString()); - BOOST_FOREACH (CNode* pnode, vNodes) + for (CNode* pnode : vNodes) if (pnode->nVersion >= karmanodePayments.GetMinKarmanodePaymentsProto()) pnode->PushMessage(NetMsgType::DSEEP, vin, vchSig, sigTime, stop); } diff --git a/src/kernel.cpp b/src/kernel.cpp index da8d5cb..0c6040a 100755 --- a/src/kernel.cpp +++ b/src/kernel.cpp @@ -86,7 +86,7 @@ static bool SelectBlockFromCandidates( bool fSelected = false; uint256 hashBest = 0; *pindexSelected = (const CBlockIndex*)0; - BOOST_FOREACH (const PAIRTYPE(int64_t, uint256) & item, vSortedByTimestamp) { + for (const std::pair & item : vSortedByTimestamp) { if (!mapBlockIndex.count(item.second)) return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str()); @@ -224,7 +224,7 @@ bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64_t& nStakeMod strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "="); pindex = pindex->pprev; } - BOOST_FOREACH (const PAIRTYPE(uint256, const CBlockIndex*) & item, mapSelectedBlocks) { + for (const std::pair & item : mapSelectedBlocks) { // 'S' indicates selected proof-of-stake blocks // 'W' indicates selected proof-of-work blocks strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake() ? "S" : "W"); diff --git a/src/keystore.cpp b/src/keystore.cpp index 03dae1e..265236a 100755 --- a/src/keystore.cpp +++ b/src/keystore.cpp @@ -11,8 +11,6 @@ #include "script/standard.h" #include "util.h" -#include - static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut) { //TODO: Use Solver to extract this? diff --git a/src/leveldb/port/atomic_pointer.h b/src/leveldb/port/atomic_pointer.h index 9bf091f..83b0b38 100755 --- a/src/leveldb/port/atomic_pointer.h +++ b/src/leveldb/port/atomic_pointer.h @@ -42,6 +42,31 @@ namespace leveldb { namespace port { +// AtomicPointer based on if available +#if defined(LEVELDB_ATOMIC_PRESENT) +class AtomicPointer { + private: + std::atomic rep_; + public: + AtomicPointer() { } + explicit AtomicPointer(void* v) : rep_(v) { } + inline void* Acquire_Load() const { + return rep_.load(std::memory_order_acquire); + } + inline void Release_Store(void* v) { + rep_.store(v, std::memory_order_release); + } + inline void* NoBarrier_Load() const { + return rep_.load(std::memory_order_relaxed); + } + inline void NoBarrier_Store(void* v) { + rep_.store(v, std::memory_order_relaxed); + } +}; + +#else + + // Define MemoryBarrier() if available // Windows on x86 #if defined(OS_WIN) && defined(COMPILER_MSVC) && defined(ARCH_CPU_X86_FAMILY) @@ -124,28 +149,6 @@ class AtomicPointer { } }; -// AtomicPointer based on -#elif defined(LEVELDB_ATOMIC_PRESENT) -class AtomicPointer { - private: - std::atomic rep_; - public: - AtomicPointer() { } - explicit AtomicPointer(void* v) : rep_(v) { } - inline void* Acquire_Load() const { - return rep_.load(std::memory_order_acquire); - } - inline void Release_Store(void* v) { - rep_.store(v, std::memory_order_release); - } - inline void* NoBarrier_Load() const { - return rep_.load(std::memory_order_relaxed); - } - inline void NoBarrier_Store(void* v) { - rep_.store(v, std::memory_order_relaxed); - } -}; - // Atomic pointer based on sparc memory barriers #elif defined(__sparcv9) && defined(__GNUC__) class AtomicPointer { @@ -210,6 +213,7 @@ class AtomicPointer { #else #error Please implement AtomicPointer for this platform. +#endif #endif #undef LEVELDB_HAVE_MEMORY_BARRIER diff --git a/src/main.cpp b/src/main.cpp index efc4df0..9414e17 100755 --- a/src/main.cpp +++ b/src/main.cpp @@ -29,6 +29,7 @@ #include "obfuscation.h" #include "protocol.h" #include "pow.h" +#include "reverse_iterator.h" #include "spork.h" #include "sporkdb.h" #include "swifttx.h" @@ -324,7 +325,7 @@ namespace AddressCurrentlyConnected(state->address); } - BOOST_FOREACH (const QueuedBlock& entry, state->vBlocksInFlight) + for (const QueuedBlock& entry : state->vBlocksInFlight) mapBlocksInFlight.erase(entry.hash); EraseOrphansFor(nodeid); nPreferredDownload -= state->fPreferredDownload; @@ -471,7 +472,7 @@ namespace // Iterate over those blocks in vToFetch (in forward direction), adding the ones that // are not yet downloaded and not in flight to vBlocks. In the mean time, update // pindexLastCommonBlock as long as all ancestors are already downloaded. - BOOST_FOREACH (CBlockIndex* pindex, vToFetch) { + for (CBlockIndex* pindex : vToFetch) { if (!pindex->IsValid(BLOCK_VALID_TREE)) { // We consider the chain that this peer is on invalid. return; @@ -512,7 +513,7 @@ bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) stats.nMisbehavior = state->nMisbehavior; stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1; stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1; - BOOST_FOREACH (const QueuedBlock& queue, state->vBlocksInFlight) { + for (const QueuedBlock& queue : state->vBlocksInFlight) { if (queue.pindex) stats.vHeightInFlight.push_back(queue.pindex->nHeight); } @@ -540,7 +541,7 @@ void UnregisterNodeSignals(CNodeSignals& nodeSignals) CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator) { // Find the first block the caller has in the main chain - BOOST_FOREACH (const uint256& hash, locator.vHave) { + for (const uint256& hash : locator.vHave) { BlockMap::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; @@ -585,7 +586,7 @@ bool AddOrphanTx(const CTransaction& tx, NodeId peer) mapOrphanTransactions[hash].tx = tx; mapOrphanTransactions[hash].fromPeer = peer; - BOOST_FOREACH (const CTxIn& txin, tx.vin) + for (const CTxIn& txin : tx.vin) mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash); LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(), @@ -598,7 +599,7 @@ void static EraseOrphanTx(uint256 hash) map::iterator it = mapOrphanTransactions.find(hash); if (it == mapOrphanTransactions.end()) return; - BOOST_FOREACH (const CTxIn& txin, it->second.tx.vin) { + for (const CTxIn& txin : it->second.tx.vin) { map >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash); if (itPrev == mapOrphanTransactionsByPrev.end()) continue; @@ -701,7 +702,7 @@ bool IsStandardTx(const CTransaction& tx, string& reason) unsigned int nDataOut = 0; txnouttype whichType; - BOOST_FOREACH (const CTxOut& txout, tx.vout) { + for (const CTxOut& txout : tx.vout) { if (!::IsStandard(txout.scriptPubKey, whichType)) { reason = "scriptpubkey"; return false; @@ -739,7 +740,7 @@ bool IsFinalTx(const CTransaction& tx, int nBlockHeight, int64_t nBlockTime) nBlockTime = GetAdjustedTime(); if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime)) return true; - BOOST_FOREACH (const CTxIn& txin, tx.vin) + for (const CTxIn& txin : tx.vin) if (!txin.IsFinal()) return false; return true; @@ -800,10 +801,10 @@ int64_t GetVirtualTransactionSize(const CTransaction& tx) unsigned int GetLegacySigOpCount(const CTransaction& tx) { unsigned int nSigOps = 0; - BOOST_FOREACH (const CTxIn& txin, tx.vin) { + for (const CTxIn& txin : tx.vin) { nSigOps += txin.scriptSig.GetSigOpCount(false); } - BOOST_FOREACH (const CTxOut& txout, tx.vout) { + for (const CTxOut& txout : tx.vout) { nSigOps += txout.scriptPubKey.GetSigOpCount(false); } return nSigOps; @@ -908,7 +909,7 @@ bool GetCoinAge(const CTransaction& tx, const unsigned int nTxTime, uint64_t& nC nCoinAge = 0; CBlockIndex* pindex = NULL; - BOOST_FOREACH (const CTxIn& txin, tx.vin) { + for (const CTxIn& txin : tx.vin) { // First try finding the previous transaction in database CTransaction txPrev; uint256 hashBlockPrev; @@ -1381,7 +1382,7 @@ bool CheckTransaction(const CTransaction& tx, bool fZerocoinActive, bool fReject // Check for negative or overflow output values CAmount nValueOut = 0; int nZCSpendCount = 0; - BOOST_FOREACH (const CTxOut& txout, tx.vout) { + for (const CTxOut& txout : tx.vout) { if (txout.nValue < 0) return state.DoS(100, error("CheckTransaction() : txout.nValue negative"), REJECT_INVALID, "bad-txns-vout-negative"); @@ -1434,13 +1435,13 @@ bool CheckTransaction(const CTransaction& tx, bool fZerocoinActive, bool fReject if (tx.IsCoinBase()) { if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 150) - return state.DoS(100, error("CheckTransaction() : coinbase script size=%d", tx.vin[0].scriptSig.size()), + return state.DoS(100, error("CheckTransaction(), coinbase script size=%d", tx.vin[0].scriptSig.size()), REJECT_INVALID, "bad-cb-length"); } else if (fZerocoinActive && tx.IsZerocoinSpend()) { if(tx.vin.size() < 1 || static_cast(tx.vin.size()) > Params().Zerocoin_MaxSpendsPerTransaction()) return state.DoS(10, error("CheckTransaction() : Zerocoin Spend has more than allowed txin's"), REJECT_INVALID, "bad-zerocoinspend"); } else { - BOOST_FOREACH (const CTxIn& txin, tx.vin) + for (const CTxIn& txin : tx.vin) if (txin.prevout.IsNull() && (fZerocoinActive && !txin.scriptSig.IsZerocoinSpend())) return state.DoS(10, error("CheckTransaction() : prevout is null"), REJECT_INVALID, "bad-txns-prevout-null"); @@ -1541,7 +1542,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState& state, const CTransa // ----------- swiftTX transaction scanning ----------- string reason; - BOOST_FOREACH (const CTxIn& in, tx.vin) { + for (const CTxIn& in : tx.vin) { if (mapLockedInputs.count(in.prevout)) { if (mapLockedInputs[in.prevout] != tx.GetHash()) { return state.DoS(0, @@ -1843,7 +1844,7 @@ bool AcceptableInputs(CTxMemPool& pool, CValidationState& state, const CTransact // ----------- swiftTX transaction scanning ----------- - BOOST_FOREACH (const CTxIn& in, tx.vin) { + for (const CTxIn& in : tx.vin) { if (mapLockedInputs.count(in.prevout)) { if (mapLockedInputs[in.prevout] != tx.GetHash()) { return state.DoS(0, @@ -2072,7 +2073,7 @@ bool GetTransaction(const uint256& hash, CTransaction& txOut, uint256& hashBlock if (pindexSlow) { CBlock block; if (ReadBlockFromDisk(block, pindexSlow)) { - BOOST_FOREACH (const CTransaction& tx, block.vtx) { + for (const CTransaction& tx : block.vtx) { if (tx.GetHash() == hash) { txOut = tx; hashBlock = pindexSlow->GetBlockHash(); @@ -2619,7 +2620,7 @@ void UpdateCoins(const CTransaction& tx, CValidationState& state, CCoinsViewCach // mark inputs spent if (!tx.IsCoinBase() && !tx.IsZerocoinSpend()) { txundo.vprevout.reserve(tx.vin.size()); - BOOST_FOREACH (const CTxIn& txin, tx.vin) { + for (const CTxIn& txin : tx.vin) { txundo.vprevout.push_back(CTxInUndo()); bool ret = inputs.ModifyCoins(txin.prevout.hash)->Spend(txin.prevout, txundo.vprevout.back()); assert(ret); @@ -2825,7 +2826,7 @@ bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex if (!tx.IsCoinBase() && !tx.IsZerocoinSpend()) { // not coinbases or zerocoinspend because they dont have traditional inputs const CTxUndo& txundo = blockUndo.vtxundo[i - 1]; if (txundo.vprevout.size() != tx.vin.size()) - return error("DisconnectBlock() : transaction and undo data inconsistent - txundo.vprevout.siz=%d tx.vin.siz=%d", txundo.vprevout.size(), tx.vin.size()); + return error("DisconnectBlock(), transaction and undo data inconsistent - txundo.vprevout.siz=%d tx.vin.siz=%d", txundo.vprevout.size(), tx.vin.size()); for (unsigned int j = tx.vin.size(); j-- > 0;) { const COutPoint& out = tx.vin[j].prevout; const CTxInUndo& undo = txundo.vprevout[j]; @@ -3217,7 +3218,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin !((pindex->nHeight == 91842 && pindex->GetBlockHash() == uint256("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) || (pindex->nHeight == 91880 && pindex->GetBlockHash() == uint256("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721"))); if (fEnforceBIP30) { - BOOST_FOREACH (const CTransaction& tx, block.vtx) { + for (const CTransaction& tx : block.vtx) { const CCoins* coins = view.AccessCoins(tx.GetHash()); if (coins && !coins->IsPruned()) return state.DoS(100, error("ConnectBlock() : tried to overwrite transaction"), @@ -3374,7 +3375,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin vPosTxid.push_back(std::make_pair(tx.GetHash(), pos)); if (fAddrIndex) { if (!tx.IsCoinBase()) { - BOOST_FOREACH(const CTxIn &txin, tx.vin) { + for(const CTxIn &txin : tx.vin) { CCoins coins; view.GetCoins(txin.prevout.hash, coins); if (coins.IsAvailable(txin.prevout.n)) { @@ -3382,7 +3383,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin } } } - BOOST_FOREACH(const CTxOut &txout, tx.vout) + for(const CTxOut &txout : tx.vout) BuildAddrIndex(txout.scriptPubKey, pos, vPosAddrid); } @@ -3674,7 +3675,7 @@ bool static DisconnectTip(CValidationState& state, bool fBare) if (!fBare) { // Resurrect mempool transactions from the disconnected block. - BOOST_FOREACH (const CTransaction& tx, block.vtx) { + for (const CTransaction& tx : block.vtx) { // ignore validation errors in resurrected transactions list removed; CValidationState stateDummy; @@ -3689,7 +3690,7 @@ bool static DisconnectTip(CValidationState& state, bool fBare) UpdateTip(pindexDelete->pprev); // Let wallets know transactions went from 1-confirmed to // 0-confirmed or conflicted: - BOOST_FOREACH (const CTransaction& tx, block.vtx) { + for (const CTransaction& tx : block.vtx) { SyncWithWallets(tx, NULL); } return true; @@ -3764,11 +3765,11 @@ bool static ConnectTip(CValidationState& state, CBlockIndex* pindexNew, CBlock* UpdateTip(pindexNew); // Tell wallet about transactions that went from mempool // to conflicted: - BOOST_FOREACH (const CTransaction& tx, txConflicted) { + for (const CTransaction& tx : txConflicted) { SyncWithWallets(tx, NULL); } // ... and about transactions that got confirmed: - BOOST_FOREACH (const CTransaction& tx, pblock->vtx) { + for (const CTransaction& tx : pblock->vtx) { SyncWithWallets(tx, pblock); } @@ -3830,10 +3831,10 @@ bool DisconnectBlockAndInputs(CValidationState& state, CTransaction txLock) // Queue memory transactions to resurrect. // We only do this for blocks after the last checkpoint (reorganisation before that // point should only happen with -reindex/-loadblock, or a misbehaving peer. - BOOST_FOREACH (const CTransaction& tx, block.vtx) { + for (const CTransaction& tx : block.vtx) { if (!tx.IsCoinBase()) { - BOOST_FOREACH (const CTxIn& in1, txLock.vin) { - BOOST_FOREACH (const CTxIn& in2, tx.vin) { + for (const CTxIn& in1 : txLock.vin) { + for (const CTxIn& in2 : tx.vin) { if (in1.prevout == in2.prevout) foundConflictingTx = true; } } @@ -3854,7 +3855,7 @@ bool DisconnectBlockAndInputs(CValidationState& state, CTransaction txLock) if (vDisconnect.size() > 0) { LogPrintf("REORGANIZE: Disconnect Conflicting Blocks %lli blocks; %s..\n", vDisconnect.size(), pindexNew->GetBlockHash().ToString()); - BOOST_FOREACH (CBlockIndex* pindex, vDisconnect) { + for (CBlockIndex* pindex : vDisconnect) { LogPrintf(" -- disconnect %s\n", pindex->GetBlockHash().ToString()); DisconnectTip(state, false); } @@ -3973,7 +3974,7 @@ static bool ActivateBestChainStep(CValidationState& state, CBlockIndex* pindexMo nHeight = nTargetHeight; // Connect new blocks. - BOOST_REVERSE_FOREACH (CBlockIndex* pindexConnect, vpindexToConnect) { + for (CBlockIndex* pindexConnect : reverse_iterate (vpindexToConnect)) { if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL, fAlreadyChecked)) { if (state.IsInvalid()) { // The block violates a consensus rule. @@ -4049,7 +4050,7 @@ bool ActivateBestChain(CValidationState& state, CBlock* pblock, bool fAlreadyChe int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(); { LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodes) + for (CNode* pnode : vNodes) if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip)); } @@ -4435,10 +4436,10 @@ bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bo // ----------- swiftTX transaction scanning ----------- if (IsSporkActive(SPORK_3_SWIFTTX_BLOCK_FILTERING)) { - BOOST_FOREACH (const CTransaction& tx, block.vtx) { + for (const CTransaction& tx : block.vtx) { if (!tx.IsCoinBase()) { //only reject blocks when it's based on complete consensus - BOOST_FOREACH (const CTxIn& in, tx.vin) { + for (const CTxIn& in : tx.vin) { if (mapLockedInputs.count(in.prevout)) { if (mapLockedInputs[in.prevout] != tx.GetHash()) { mapRejectedBlocks.insert(make_pair(block.GetHash(), GetTime())); @@ -4486,7 +4487,7 @@ bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bo unsigned int nSigOps = 0; - BOOST_FOREACH (const CTransaction& tx, block.vtx) { + for (const CTransaction& tx : block.vtx) { nSigOps += GetLegacySigOpCount(tx); } if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST) @@ -4709,7 +4710,7 @@ bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIn } // Check that all transactions are finalized - BOOST_FOREACH (const CTransaction& tx, block.vtx) + for (const CTransaction& tx : block.vtx) if (!IsFinalTx(tx, nHeight, block.GetBlockTime())) { return state.DoS(10, error("%s : contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal"); } @@ -5233,12 +5234,15 @@ bool static LoadBlockIndexDB(string& strError) // Calculate nChainWork vector > vSortedByHeight; vSortedByHeight.reserve(mapBlockIndex.size()); - for (const PAIRTYPE(uint256, CBlockIndex*) & item : mapBlockIndex) { + for (const std::pair & item : mapBlockIndex) { CBlockIndex* pindex = item.second; vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex)); } sort(vSortedByHeight.begin(), vSortedByHeight.end()); - BOOST_FOREACH (const PAIRTYPE(int, CBlockIndex*) & item, vSortedByHeight) { + for (const std::pair & item : vSortedByHeight) { + // Stop if shutdown was requested + if (ShutdownRequested()) return false; + CBlockIndex* pindex = item.second; pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex); if (pindex->nStatus & BLOCK_HAVE_DATA) { @@ -5283,7 +5287,7 @@ bool static LoadBlockIndexDB(string& strError) // Check presence of blk files LogPrintf("Checking all blk files are present...\n"); set setBlkDataFiles; - for (const PAIRTYPE(uint256, CBlockIndex*) & item : mapBlockIndex) { + for (const std::pair & item : mapBlockIndex) { CBlockIndex* pindex = item.second; if (pindex->nStatus & BLOCK_HAVE_DATA) { setBlkDataFiles.insert(pindex->nFile); @@ -5825,7 +5829,7 @@ string GetWarnings(string strFor) // Alerts { LOCK(cs_mapAlerts); - BOOST_FOREACH (PAIRTYPE(const uint256, CAlert) & item, mapAlerts) { + for (std::pair & item : mapAlerts) { const CAlert& alert = item.second; if (alert.AppliesToMe() && alert.nPriority > nPriority) { nPriority = alert.nPriority; @@ -5972,7 +5976,7 @@ void static ProcessGetData(CNode* pfrom) // Thus, the protocol spec specified allows for us to provide duplicate txn here, // however we MUST always provide at least what the remote peer needs typedef std::pair PairType; - BOOST_FOREACH (PairType& pair, merkleBlock.vMatchedTxn) + for (PairType& pair : merkleBlock.vMatchedTxn) if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second))) pfrom->PushMessageWithFlag(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::TX, block.vtx[pair.first]); } @@ -6268,7 +6272,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, // Relay alerts { LOCK(cs_mapAlerts); - BOOST_FOREACH (PAIRTYPE(const uint256, CAlert) & item, mapAlerts) + for (std::pair & item : mapAlerts) item.second.RelayTo(pfrom); } @@ -6325,7 +6329,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, vector vAddrOk; int64_t nNow = GetAdjustedTime(); int64_t nSince = nNow - 10 * 60; - BOOST_FOREACH (CAddress& addr, vAddr) { + for (CAddress& addr : vAddr) { boost::this_thread::interruption_point(); if (!(addr.nServices & NODE_NETWORK)) @@ -6348,7 +6352,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, uint256 hashRand = hashSalt ^ (hashAddr << 32) ^ ((GetTime() + hashAddr) / (24 * 60 * 60)); hashRand = Hash(BEGIN(hashRand), END(hashRand)); multimap mapMix; - BOOST_FOREACH (CNode* pnode, vNodes) { + for (CNode* pnode : vNodes) { if (pnode->nVersion < CADDR_TIME_VERSION) continue; unsigned int nPointer; @@ -6646,7 +6650,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, } } - BOOST_FOREACH (uint256 hash, vEraseQueue)EraseOrphanTx(hash); + for (uint256 hash : vEraseQueue)EraseOrphanTx(hash); } else if (tx.IsZerocoinSpend() && AcceptToMemoryPool(mempool, state, tx, true, &fMissingZerocoinInputs, false, ignoreFees)) { //Presstab: ZCoin has a bunch of code commented out here. Is this something that should have more going on? //Also there is nothing that handles fMissingZerocoinInputs. Does there need to be? @@ -6726,7 +6730,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, return true; } CBlockIndex* pindexLast = NULL; - BOOST_FOREACH (const CBlockHeader& header, headers) { + for (const CBlockHeader& header : headers) { CValidationState state; if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) { LOCK(cs_main); @@ -6813,7 +6817,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, else if ((strCommand == NetMsgType::GETADDR) && (pfrom->fInbound)) { pfrom->vAddrToSend.clear(); vector vAddr = addrman.GetAddr(); - BOOST_FOREACH (const CAddress& addr, vAddr) + for (const CAddress& addr : vAddr) pfrom->PushAddress(addr); } @@ -6824,7 +6828,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, std::vector vtxid; mempool.queryHashes(vtxid); vector vInv; - BOOST_FOREACH (uint256& hash, vtxid) { + for (uint256& hash : vtxid) { CInv inv(MSG_TX, hash); CTransaction tx; bool fInMemPool = mempool.lookup(hash, tx); @@ -6928,7 +6932,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, pfrom->setKnown.insert(alertHash); { LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodes) + for (CNode* pnode : vNodes) alert.RelayTo(pnode); } } else { @@ -7222,7 +7226,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) static int64_t nLastRebroadcast; if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) { LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodes) { + for (CNode* pnode : vNodes) { // Periodically clear setAddrKnown to allow refresh broadcasts if (nLastRebroadcast) pnode->setAddrKnown.clear(); @@ -7240,7 +7244,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) if (fSendTrickle) { vector vAddr; vAddr.reserve(pto->vAddrToSend.size()); - BOOST_FOREACH (const CAddress& addr, pto->vAddrToSend) { + for (const CAddress& addr : pto->vAddrToSend) { // returns true if wasn't already contained in the set if (pto->setAddrKnown.insert(addr).second) { vAddr.push_back(addr); @@ -7271,7 +7275,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) state.fShouldBan = false; } - BOOST_FOREACH (const CBlockReject& reject, state.rejects) + for (const CBlockReject& reject : state.rejects) pto->PushMessage(NetMsgType::REJECT, (string) "block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock); state.rejects.clear(); @@ -7307,7 +7311,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) LOCK(pto->cs_inventory); vInv.reserve(pto->vInventoryToSend.size()); vInvWait.reserve(pto->vInventoryToSend.size()); - BOOST_FOREACH (const CInv& inv, pto->vInventoryToSend) { + for (const CInv& inv : pto->vInventoryToSend) { if ((inv.type == MSG_TX || inv.type == MSG_WITNESS_TX) && pto->setInventoryKnown.count(inv)) continue; @@ -7368,7 +7372,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) vector vToDownload; NodeId staller = -1; FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller); - BOOST_FOREACH(CBlockIndex *pindex, vToDownload) { + for(CBlockIndex *pindex : vToDownload) { if (State(pto->GetId())->fHaveWitness || GetSporkValue(SPORK_20_SEGWIT_ACTIVATION) > pindex->pprev->nTime) { vGetData.push_back(CInv(State(staller)->fHaveWitness ? MSG_WITNESS_BLOCK : MSG_BLOCK, pindex->GetBlockHash())); MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex); diff --git a/src/memusage.h b/src/memusage.h new file mode 100755 index 0000000..9f7de9e --- /dev/null +++ b/src/memusage.h @@ -0,0 +1,111 @@ +// Copyright (c) 2015 The Bitcoin developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_MEMUSAGE_H +#define BITCOIN_MEMUSAGE_H + +#include + +#include +#include +#include + +#include +#include + +namespace memusage +{ + +/** Compute the total memory used by allocating alloc bytes. */ +static size_t MallocUsage(size_t alloc); + +/** Compute the memory used for dynamically allocated but owned data structures. + * For generic data types, this is *not* recursive. DynamicUsage(vector >) + * will compute the memory used for the vector's, but not for the ints inside. + * This is for efficiency reasons, as these functions are intended to be fast. If + * application data structures require more accurate inner accounting, they should + * do the recursion themselves, or use more efficient caching + updating on modification. + */ +template static size_t DynamicUsage(const std::vector& v); +template static size_t DynamicUsage(const std::set& s); +template static size_t DynamicUsage(const std::map& m); +template static size_t DynamicUsage(const boost::unordered_set& s); +template static size_t DynamicUsage(const boost::unordered_map& s); +template static size_t DynamicUsage(const X& x); + +static inline size_t MallocUsage(size_t alloc) +{ + // Measured on libc6 2.19 on Linux. + if (sizeof(void*) == 8) { + return ((alloc + 31) >> 4) << 4; + } else if (sizeof(void*) == 4) { + return ((alloc + 15) >> 3) << 3; + } else { + assert(0); + } +} + +// STL data structures + +template +struct stl_tree_node +{ +private: + int color; + void* parent; + void* left; + void* right; + X x; +}; + +template +static inline size_t DynamicUsage(const std::vector& v) +{ + return MallocUsage(v.capacity() * sizeof(X)); +} + +template +static inline size_t DynamicUsage(const std::set& s) +{ + return MallocUsage(sizeof(stl_tree_node)) * s.size(); +} + +template +static inline size_t DynamicUsage(const std::map& m) +{ + return MallocUsage(sizeof(stl_tree_node >)) * m.size(); +} + +// Boost data structures + +template +struct boost_unordered_node : private X +{ +private: + void* ptr; +}; + +template +static inline size_t DynamicUsage(const boost::unordered_set& s) +{ + return MallocUsage(sizeof(boost_unordered_node)) * s.size() + MallocUsage(sizeof(void*) * s.bucket_count()); +} + +template +static inline size_t DynamicUsage(const boost::unordered_map& m) +{ + return MallocUsage(sizeof(boost_unordered_node >)) * m.size() + MallocUsage(sizeof(void*) * m.bucket_count()); +} + +// Dispatch to class method as fallback + +template +static inline size_t DynamicUsage(const X& x) +{ + return x.DynamicMemoryUsage(); +} + +} + +#endif diff --git a/src/miner.cpp b/src/miner.cpp index bce77db..6d99d95 100755 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -22,7 +22,7 @@ #include "util.h" #include "utilmoneystr.h" #ifdef ENABLE_WALLET -#include "wallet.h" +#include "wallet/wallet.h" #endif #include "validationinterface.h" #include "karmanode-payments.h" @@ -441,7 +441,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn, CWallet* pwallet, // Add transactions that depend on this one to the priority queue if (mapDependers.count(hash)) { - BOOST_FOREACH (COrphan* porphan, mapDependers[hash]) { + for (COrphan* porphan : mapDependers[hash]) { if (!porphan->setDependsOn.empty()) { porphan->setDependsOn.erase(hash); if (porphan->setDependsOn.empty()) { diff --git a/src/net.cpp b/src/net.cpp index 9dd00b3..840acde 100755 --- a/src/net.cpp +++ b/src/net.cpp @@ -570,7 +570,7 @@ void CNode::Ban(const CSubNet& subNet, const BanReason &banReason, int64_t banti uiInterface.BannedListChanged(); { LOCK(cs_vNodes); - BOOST_FOREACH(CNode* pnode, vNodes) { + for(CNode* pnode : vNodes) { if (subNet.Match((CNetAddr)pnode->addr)) pnode->fDisconnect = true; } @@ -659,7 +659,7 @@ CCriticalSection CNode::cs_vWhitelistedRange; bool CNode::IsWhitelistedRange(const CNetAddr& addr) { LOCK(cs_vWhitelistedRange); - BOOST_FOREACH (const CSubNet& subnet, vWhitelistedRange) { + for (const CSubNet& subnet : vWhitelistedRange) { if (subnet.Match(addr)) return true; } @@ -852,7 +852,7 @@ void ThreadSocketHandler() LOCK(cs_vNodes); // Disconnect unused nodes vector vNodesCopy = vNodes; - BOOST_FOREACH (CNode* pnode, vNodesCopy) { + for (CNode* pnode : vNodesCopy) { if (pnode->fDisconnect || (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) { // remove from vNodes @@ -874,7 +874,7 @@ void ThreadSocketHandler() { // Delete disconnected nodes list vNodesDisconnectedCopy = vNodesDisconnected; - BOOST_FOREACH (CNode* pnode, vNodesDisconnectedCopy) { + for (CNode* pnode : vNodesDisconnectedCopy) { // wait until threads are done using it if (pnode->GetRefCount() <= 0) { bool fDelete = false; @@ -922,7 +922,7 @@ void ThreadSocketHandler() SOCKET hSocketMax = 0; bool have_fds = false; - BOOST_FOREACH (const ListenSocket& hListenSocket, vhListenSocket) { + for (const ListenSocket& hListenSocket : vhListenSocket) { FD_SET(hListenSocket.socket, &fdsetRecv); hSocketMax = max(hSocketMax, hListenSocket.socket); have_fds = true; @@ -930,7 +930,7 @@ void ThreadSocketHandler() { LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodes) { + for (CNode* pnode : vNodes) { if (pnode->hSocket == INVALID_SOCKET) continue; FD_SET(pnode->hSocket, &fdsetError); @@ -987,7 +987,7 @@ void ThreadSocketHandler() // // Accept new connections // - BOOST_FOREACH (const ListenSocket& hListenSocket, vhListenSocket) { + for (const ListenSocket& hListenSocket : vhListenSocket) { if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv)) { struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); @@ -1002,7 +1002,7 @@ void ThreadSocketHandler() bool whitelisted = hListenSocket.whitelisted || CNode::IsWhitelistedRange(addr); { LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodes) + for (CNode* pnode : vNodes) if (pnode->fInbound) nInbound++; } @@ -1040,10 +1040,10 @@ void ThreadSocketHandler() { LOCK(cs_vNodes); vNodesCopy = vNodes; - BOOST_FOREACH (CNode* pnode, vNodesCopy) + for (CNode* pnode : vNodesCopy) pnode->AddRef(); } - BOOST_FOREACH (CNode* pnode, vNodesCopy) { + for (CNode* pnode : vNodesCopy) { boost::this_thread::interruption_point(); // @@ -1115,7 +1115,7 @@ void ThreadSocketHandler() } { LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodesCopy) + for (CNode* pnode : vNodesCopy) pnode->Release(); } } @@ -1250,14 +1250,14 @@ void ThreadDNSAddressSeed() LogPrintf("Loading addresses from DNS seeds (could take a while)\n"); - BOOST_FOREACH (const CDNSSeedData& seed, vSeeds) { + for (const CDNSSeedData& seed : vSeeds) { if (HaveNameProxy()) { AddOneShot(seed.host); } else { vector vIPs; vector vAdd; if (LookupHost(seed.host.c_str(), vIPs, 256, true)) { - BOOST_FOREACH (CNetAddr& ip, vIPs) { + for (CNetAddr& ip : vIPs) { int nOneDay = 24 * 3600; CAddress addr = CAddress(CService(ip, Params().GetDefaultPort())); addr.nTime = GetTime() - 3 * nOneDay - GetRand(4 * nOneDay); // use a random age between 3 and 7 days old @@ -1314,7 +1314,7 @@ void ThreadOpenConnections() if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { for (int64_t nLoop = 0;; nLoop++) { ProcessOneShot(); - BOOST_FOREACH (string strAddr, mapMultiArgs["-connect"]) { + for (string strAddr : mapMultiArgs["-connect"]) { CAddress addr; OpenNetworkConnection(addr, NULL, strAddr.c_str()); for (int i = 0; i < 10 && i < nLoop; i++) { @@ -1356,7 +1356,7 @@ void ThreadOpenConnections() set > setConnected; { LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodes) { + for (CNode* pnode : vNodes) { if (!pnode->fInbound) { setConnected.insert(pnode->addr.GetGroup()); nOutbound++; @@ -1421,10 +1421,10 @@ void ThreadOpenAddedConnections() list lAddresses(0); { LOCK(cs_vAddedNodes); - BOOST_FOREACH (string& strAddNode, vAddedNodes) + for (string& strAddNode : vAddedNodes) lAddresses.push_back(strAddNode); } - BOOST_FOREACH (string& strAddNode, lAddresses) { + for (string& strAddNode : lAddresses) { CAddress addr; CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(addr, &grant, strAddNode.c_str()); @@ -1438,18 +1438,18 @@ void ThreadOpenAddedConnections() list lAddresses(0); { LOCK(cs_vAddedNodes); - BOOST_FOREACH (string& strAddNode, vAddedNodes) + for (string& strAddNode : vAddedNodes) lAddresses.push_back(strAddNode); } list > lservAddressesToAdd(0); - BOOST_FOREACH (string& strAddNode, lAddresses) { + for (string& strAddNode : lAddresses) { vector vservNode(0); if (Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) { lservAddressesToAdd.push_back(vservNode); { LOCK(cs_setservAddNodeAddresses); - BOOST_FOREACH (CService& serv, vservNode) + for (CService& serv : vservNode) setservAddNodeAddresses.insert(serv); } } @@ -1458,16 +1458,16 @@ void ThreadOpenAddedConnections() // (keeping in mind that addnode entries can have many IPs if fNameLookup) { LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodes) + for (CNode* pnode : vNodes) for (list >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++) - BOOST_FOREACH (CService& addrNode, *(it)) + for (CService& addrNode : *(it)) if (pnode->addr == addrNode) { it = lservAddressesToAdd.erase(it); it--; break; } } - BOOST_FOREACH (vector& vserv, lservAddressesToAdd) { + for (vector& vserv : lservAddressesToAdd) { CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant); MilliSleep(500); @@ -1517,7 +1517,7 @@ void ThreadMessageHandler() { LOCK(cs_vNodes); vNodesCopy = vNodes; - BOOST_FOREACH (CNode* pnode, vNodesCopy) { + for (CNode* pnode : vNodesCopy) { pnode->AddRef(); } } @@ -1529,7 +1529,7 @@ void ThreadMessageHandler() bool fSleep = true; - BOOST_FOREACH (CNode* pnode, vNodesCopy) { + for (CNode* pnode : vNodesCopy) { if (pnode->fDisconnect) continue; @@ -1561,7 +1561,7 @@ void ThreadMessageHandler() { LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodesCopy) + for (CNode* pnode : vNodesCopy) pnode->Release(); } @@ -1669,7 +1669,7 @@ void static Discover(boost::thread_group& threadGroup) if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { vector vaddr; if (LookupHost(pszHostName, vaddr, 0, false)) { - BOOST_FOREACH (const CNetAddr& addr, vaddr) { + for (const CNetAddr& addr : vaddr) { if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString()); } @@ -1789,18 +1789,18 @@ class CNetCleanup ~CNetCleanup() { // Close sockets - BOOST_FOREACH (CNode* pnode, vNodes) + for (CNode* pnode : vNodes) if (pnode->hSocket != INVALID_SOCKET) CloseSocket(pnode->hSocket); - BOOST_FOREACH (ListenSocket& hListenSocket, vhListenSocket) + for (ListenSocket& hListenSocket : vhListenSocket) if (hListenSocket.socket != INVALID_SOCKET) if (!CloseSocket(hListenSocket.socket)) LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError())); // clean up some globals (to help leak detection) - BOOST_FOREACH (CNode* pnode, vNodes) + for (CNode* pnode : vNodes) delete pnode; - BOOST_FOREACH (CNode* pnode, vNodesDisconnected) + for (CNode* pnode : vNodesDisconnected) delete pnode; vNodes.clear(); vNodesDisconnected.clear(); @@ -1849,7 +1849,7 @@ void RelayTransaction(const CTransaction& tx, const CDataStream& ss) vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv)); } LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodes) { + for (CNode* pnode : vNodes) { if (!pnode->fRelayTxes) continue; LOCK(pnode->cs_filter); @@ -1867,7 +1867,7 @@ void RelayTransactionLockReq(const CTransaction& tx, bool relayToAll) //broadcast the new lock LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodes) { + for (CNode* pnode : vNodes) { if (!relayToAll && !pnode->fRelayTxes) continue; @@ -1878,7 +1878,7 @@ void RelayTransactionLockReq(const CTransaction& tx, bool relayToAll) void RelayInv(CInv& inv) { LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodes){ + for (CNode* pnode : vNodes){ if((pnode->nServices==NODE_BLOOM_WITHOUT_MN) && inv.IsMasterNodeType())continue; if (pnode->nVersion >= ActiveProtocol()) pnode->PushInventory(inv); diff --git a/src/net.h b/src/net.h index 4160168..f620bf8 100755 --- a/src/net.h +++ b/src/net.h @@ -28,7 +28,6 @@ #endif #include -#include #include #include @@ -404,7 +403,7 @@ class CNode unsigned int GetTotalRecvSize() { unsigned int total = 0; - BOOST_FOREACH (const CNetMessage& msg, vRecvMsg) + for (const CNetMessage& msg : vRecvMsg) total += msg.vRecv.size() + 24; return total; } @@ -416,7 +415,7 @@ class CNode void SetRecvVersion(int nVersionIn) { nRecvVersion = nVersionIn; - BOOST_FOREACH (CNetMessage& msg, vRecvMsg) + for (CNetMessage& msg : vRecvMsg) msg.SetVersion(nVersionIn); } @@ -670,7 +669,7 @@ class CNode bool HasFulfilledRequest(std::string strRequest) { - BOOST_FOREACH (std::string& type, vecRequestsFulfilled) { + for (std::string& type : vecRequestsFulfilled) { if (type == strRequest) return true; } return false; diff --git a/src/obfuscation.cpp b/src/obfuscation.cpp index e42ff92..6501014 100644 --- a/src/obfuscation.cpp +++ b/src/obfuscation.cpp @@ -9,6 +9,7 @@ #include "init.h" #include "main.h" #include "karmanodeman.h" +#include "reverse_iterator.h" #include "script/sign.h" #include "swifttx.h" #include "ui_interface.h" @@ -132,7 +133,7 @@ void CObfuscationPool::ProcessMessageObfuscation(CNode* pfrom, std::string& strC PrepareObfuscationDenominate(); } } else { - BOOST_FOREACH (CObfuscationQueue q, vecObfuscationQueue) { + for (CObfuscationQueue q : vecObfuscationQueue) { if (q.vin == dsq.vin) return; } @@ -203,7 +204,7 @@ void CObfuscationPool::ProcessMessageObfuscation(CNode* pfrom, std::string& strC CValidationState state; CMutableTransaction tx; - BOOST_FOREACH (const CTxOut o, out) { + for (const CTxOut o : out) { nValueOut += o.nValue; tx.vout.push_back(o); @@ -221,7 +222,7 @@ void CObfuscationPool::ProcessMessageObfuscation(CNode* pfrom, std::string& strC } } - BOOST_FOREACH (const CTxIn i, in) { + for (const CTxIn i : in) { tx.vin.push_back(i); LogPrint("obfuscation", "dsi -- tx in %s\n", i.ToString()); @@ -317,7 +318,7 @@ void CObfuscationPool::ProcessMessageObfuscation(CNode* pfrom, std::string& strC bool success = false; int count = 0; - BOOST_FOREACH (const CTxIn item, sigs) { + for (const CTxIn item : sigs) { if (AddScriptSig(item)) success = true; LogPrint("obfuscation", " -- sigs count %d %d\n", (int)sigs.size(), count); count++; @@ -437,7 +438,7 @@ void CObfuscationPool::UnlockCoins() MilliSleep(50); continue; } - BOOST_FOREACH (CTxIn v, lockedCoins) + for (CTxIn v : lockedCoins) pwalletMain->UnlockCoin(v.prevout); break; } @@ -539,10 +540,10 @@ void CObfuscationPool::Check() // make our new transaction for (unsigned int i = 0; i < entries.size(); i++) { - BOOST_FOREACH (const CTxOut& v, entries[i].vout) + for (const CTxOut& v : entries[i].vout) txNew.vout.push_back(v); - BOOST_FOREACH (const CTxDSIn& s, entries[i].sev) + for (const CTxDSIn& s : entries[i].sev) txNew.vin.push_back(s); } @@ -671,9 +672,9 @@ void CObfuscationPool::ChargeFees() if (r > 33) return; if (state == POOL_STATUS_ACCEPTING_ENTRIES) { - BOOST_FOREACH (const CTransaction& txCollateral, vecSessionCollateral) { + for (const CTransaction& txCollateral : vecSessionCollateral) { bool found = false; - BOOST_FOREACH (const CObfuScationEntry& v, entries) { + for (const CObfuScationEntry& v : entries) { if (v.collateral == txCollateral) { found = true; } @@ -689,8 +690,8 @@ void CObfuscationPool::ChargeFees() if (state == POOL_STATUS_SIGNING) { // who didn't sign? - BOOST_FOREACH (const CObfuScationEntry v, entries) { - BOOST_FOREACH (const CTxDSIn s, v.sev) { + for (const CObfuScationEntry v : entries) { + for (const CTxDSIn s : v.sev) { if (!s.fHasSig) { LogPrintf("CObfuscationPool::ChargeFees -- found uncooperative node (didn't sign). Found offence\n"); offences++; @@ -715,9 +716,9 @@ void CObfuscationPool::ChargeFees() r = rand() % 100; if (state == POOL_STATUS_ACCEPTING_ENTRIES) { - BOOST_FOREACH (const CTransaction& txCollateral, vecSessionCollateral) { + for (const CTransaction& txCollateral : vecSessionCollateral) { bool found = false; - BOOST_FOREACH (const CObfuScationEntry& v, entries) { + for (const CObfuScationEntry& v : entries) { if (v.collateral == txCollateral) { found = true; } @@ -742,8 +743,8 @@ void CObfuscationPool::ChargeFees() if (state == POOL_STATUS_SIGNING) { // who didn't sign? - BOOST_FOREACH (const CObfuScationEntry v, entries) { - BOOST_FOREACH (const CTxDSIn s, v.sev) { + for (const CObfuScationEntry v : entries) { + for (const CTxDSIn s : v.sev) { if (!s.fHasSig && r > target) { LogPrintf("CObfuscationPool::ChargeFees -- found uncooperative node (didn't sign). charging fees.\n"); @@ -769,7 +770,7 @@ void CObfuscationPool::ChargeRandomFees() if (fMasterNode) { int i = 0; - BOOST_FOREACH (const CTransaction& txCollateral, vecSessionCollateral) { + for (const CTransaction& txCollateral : vecSessionCollateral) { int r = rand() % 100; /* @@ -920,11 +921,11 @@ bool CObfuscationPool::SignatureValid(const CScript& newSig, const CTxIn& newVin CAmount zeroAmount = 0; - BOOST_FOREACH (CObfuScationEntry& e, entries) { - BOOST_FOREACH (const CTxOut& out, e.vout) + for (CObfuScationEntry& e : entries) { + for (const CTxOut& out : e.vout) txNew.vout.push_back(out); - BOOST_FOREACH (const CTxDSIn& s, e.sev) { + for (const CTxDSIn& s : e.sev) { txNew.vin.push_back(s); if (s == newVin) { @@ -959,7 +960,7 @@ bool CObfuscationPool::IsCollateralValid(const CTransaction& txCollateral) int64_t nValueOut = 0; bool missingTx = false; - BOOST_FOREACH (const CTxOut o, txCollateral.vout) { + for (const CTxOut o : txCollateral.vout) { nValueOut += o.nValue; if (!o.scriptPubKey.IsNormalPaymentScript()) { @@ -968,7 +969,7 @@ bool CObfuscationPool::IsCollateralValid(const CTransaction& txCollateral) } } - BOOST_FOREACH (const CTxIn i, txCollateral.vin) { + for (const CTxIn i : txCollateral.vin) { CTransaction tx2; uint256 hash; if (GetTransaction(i.prevout.hash, tx2, hash, true)) { @@ -1013,7 +1014,7 @@ bool CObfuscationPool::AddEntry(const std::vector& newInput, const CAmoun { if (!fMasterNode) return false; - BOOST_FOREACH (CTxIn in, newInput) { + for (CTxIn in : newInput) { if (in.prevout.IsNull() || nAmount < 0) { LogPrint("obfuscation", "CObfuscationPool::AddEntry - input not valid!\n"); errorID = ERR_INVALID_INPUT; @@ -1036,10 +1037,10 @@ bool CObfuscationPool::AddEntry(const std::vector& newInput, const CAmoun return false; } - BOOST_FOREACH (CTxIn in, newInput) { + for (CTxIn in : newInput) { LogPrint("obfuscation", "looking for vin -- %s\n", in.ToString()); - BOOST_FOREACH (const CObfuScationEntry& v, entries) { - BOOST_FOREACH (const CTxDSIn& s, v.sev) { + for (const CObfuScationEntry& v : entries) { + for (const CTxDSIn& s : v.sev) { if ((CTxIn)s == in) { LogPrint("obfuscation", "CObfuscationPool::AddEntry - found in vin\n"); errorID = ERR_ALREADY_HAVE; @@ -1065,8 +1066,8 @@ bool CObfuscationPool::AddScriptSig(const CTxIn& newVin) LogPrint("obfuscation", "CObfuscationPool::AddScriptSig -- new sig %s\n", newVin.scriptSig.ToString().substr(0, 24)); - BOOST_FOREACH (const CObfuScationEntry& v, entries) { - BOOST_FOREACH (const CTxDSIn& s, v.sev) { + for (const CObfuScationEntry& v : entries) { + for (const CTxDSIn& s : v.sev) { if (s.scriptSig == newVin.scriptSig) { LogPrint("obfuscation", "CObfuscationPool::AddScriptSig - already exists\n"); return false; @@ -1081,7 +1082,7 @@ bool CObfuscationPool::AddScriptSig(const CTxIn& newVin) LogPrint("obfuscation", "CObfuscationPool::AddScriptSig -- sig %s\n", newVin.ToString()); - BOOST_FOREACH (CTxIn& vin, finalTransaction.vin) { + for (CTxIn& vin : finalTransaction.vin) { if (newVin.prevout == vin.prevout && vin.nSequence == newVin.nSequence) { vin.scriptSig = newVin.scriptSig; vin.prevPubKey = newVin.prevPubKey; @@ -1102,8 +1103,8 @@ bool CObfuscationPool::AddScriptSig(const CTxIn& newVin) // Check to make sure everything is signed bool CObfuscationPool::SignaturesComplete() { - BOOST_FOREACH (const CObfuScationEntry& v, entries) { - BOOST_FOREACH (const CTxDSIn& s, v.sev) { + for (const CObfuScationEntry& v : entries) { + for (const CTxDSIn& s : v.sev) { if (!s.fHasSig) return false; } } @@ -1127,13 +1128,13 @@ void CObfuscationPool::SendObfuscationDenominate(std::vector& vin, std::v } // lock the funds we're going to use - BOOST_FOREACH (CTxIn in, txCollateral.vin) + for (CTxIn in : txCollateral.vin) lockedCoins.push_back(in); - BOOST_FOREACH (CTxIn in, vin) + for (CTxIn in : vin) lockedCoins.push_back(in); - //BOOST_FOREACH(CTxOut o, vout) + //for (CTxOut o : vout) // LogPrintf(" vout - %s\n", o.ToString()); @@ -1166,12 +1167,12 @@ void CObfuscationPool::SendObfuscationDenominate(std::vector& vin, std::v CValidationState state; CMutableTransaction tx; - BOOST_FOREACH (const CTxOut& o, vout) { + for (const CTxOut& o : vout) { nValueOut += o.nValue; tx.vout.push_back(o); } - BOOST_FOREACH (const CTxIn& i, vin) { + for (const CTxIn& i : vin) { tx.vin.push_back(i); LogPrint("obfuscation", "dsi -- tx in %s\n", i.ToString()); @@ -1267,8 +1268,8 @@ bool CObfuscationPool::SignFinalTransaction(CTransaction& finalTransactionNew, C vector sigs; //make sure my inputs/outputs are present, otherwise refuse to sign - BOOST_FOREACH (const CObfuScationEntry e, entries) { - BOOST_FOREACH (const CTxDSIn s, e.sev) { + for (const CObfuScationEntry e : entries) { + for (const CTxDSIn s : e.sev) { /* Sign my transaction and all outputs */ int mine = -1; CScript prevPubKey = CScript(); @@ -1289,7 +1290,7 @@ bool CObfuscationPool::SignFinalTransaction(CTransaction& finalTransactionNew, C CAmount nValue2 = 0; for (unsigned int i = 0; i < finalTransaction.vout.size(); i++) { - BOOST_FOREACH (const CTxOut& o, e.vout) { + for (const CTxOut& o : e.vout) { if (finalTransaction.vout[i] == o) { foundOutputs++; nValue1 += finalTransaction.vout[i].nValue; @@ -1297,7 +1298,7 @@ bool CObfuscationPool::SignFinalTransaction(CTransaction& finalTransactionNew, C } } - BOOST_FOREACH (const CTxOut o, e.vout) + for (const CTxOut o : e.vout) nValue2 += o.nValue; int targetOuputs = e.vout.size(); @@ -1533,7 +1534,7 @@ bool CObfuscationPool::DoAutomaticDenominating(bool fDryRun) //don't use the queues all of the time for mixing if (nUseQueue > 33) { // Look through the queues and see if anything matches - BOOST_FOREACH (CObfuscationQueue& dsq, vecObfuscationQueue) { + for (CObfuscationQueue& dsq : vecObfuscationQueue) { CService addr; if (dsq.time == 0) continue; @@ -1549,7 +1550,7 @@ bool CObfuscationPool::DoAutomaticDenominating(bool fDryRun) bool fUsed = false; //don't reuse Karmanodes - BOOST_FOREACH (CTxIn usedVin, vecKarmanodesUsed) { + for (CTxIn usedVin : vecKarmanodesUsed) { if (dsq.vin == usedVin) { fUsed = true; break; @@ -1789,7 +1790,7 @@ bool CObfuscationPool::CreateDenominated(CAmount nTotalValue) } // ****** Add denoms ************ / - BOOST_REVERSE_FOREACH (CAmount v, obfuScationDenominations) { + for (CAmount v : reverse_iterate (obfuScationDenominations)) { int nOutputs = 0; // add each output up to 10 times until it can't be added again @@ -1844,13 +1845,13 @@ bool CObfuscationPool::IsCompatibleWithEntries(std::vector& vout) { if (GetDenominations(vout) == 0) return false; - BOOST_FOREACH (const CObfuScationEntry v, entries) { + for (const CObfuScationEntry v : entries) { LogPrintf(" IsCompatibleWithEntries %d %d\n", GetDenominations(vout), GetDenominations(v.vout)); /* - BOOST_FOREACH(CTxOut o1, vout) + for (CTxOut o1 : vout) LogPrintf(" vout 1 - %s\n", o1.ToString()); - BOOST_FOREACH(CTxOut o2, v.vout) + for (CTxOut o2 : v.vout) LogPrintf(" vout 2 - %s\n", o2.ToString()); */ if (GetDenominations(vout) != GetDenominations(v.vout)) return false; @@ -1954,7 +1955,7 @@ int CObfuscationPool::GetDenominations(const std::vector& vout) { std::vector vout2; - BOOST_FOREACH (CTxDSOut out, vout) + for (CTxDSOut out : vout) vout2.push_back(out); return GetDenominations(vout2); @@ -1966,13 +1967,13 @@ int CObfuscationPool::GetDenominations(const std::vector& vout, bool fSi std::vector > denomUsed; // make a list of denominations, with zero uses - BOOST_FOREACH (int64_t d, obfuScationDenominations) + for (int64_t d : obfuScationDenominations) denomUsed.push_back(make_pair(d, 0)); // look for denominations and update uses to 1 - BOOST_FOREACH (CTxOut out, vout) { + for (CTxOut out : vout) { bool found = false; - BOOST_FOREACH (PAIRTYPE(int64_t, int) & s, denomUsed) { + for (std::pair & s : denomUsed) { if (out.nValue == s.first) { s.second = 1; found = true; @@ -1985,7 +1986,7 @@ int CObfuscationPool::GetDenominations(const std::vector& vout, bool fSi int c = 0; // if the denomination is used, shift the bit on. // then move to the next - BOOST_FOREACH (PAIRTYPE(int64_t, int) & s, denomUsed) { + for (std::pair & s : denomUsed) { int bit = (fSingleRandomDenom ? rand() % 2 : 1) * s.second; denom |= bit << c++; if (fSingleRandomDenom && bit) break; // use just one random denomination @@ -2008,7 +2009,7 @@ int CObfuscationPool::GetDenominationsByAmounts(std::vector& vecAmount) std::vector vout1; // Make outputs by looping through denominations, from small to large - BOOST_REVERSE_FOREACH (CAmount v, vecAmount) { + for (CAmount v : reverse_iterate (vecAmount)) { CTxOut o(v, e); vout1.push_back(o); } @@ -2024,7 +2025,7 @@ int CObfuscationPool::GetDenominationsByAmount(CAmount nAmount, int nDenomTarget std::vector vout1; // Make outputs by looping through denominations, from small to large - BOOST_REVERSE_FOREACH (CAmount v, obfuScationDenominations) { + for (CAmount v : reverse_iterate (obfuScationDenominations)) { if (nDenomTarget != 0) { bool fAccepted = false; if ((nDenomTarget & (1 << 0)) && v == ((100 * COIN) + 100000)) { @@ -2113,7 +2114,7 @@ bool CObfuScationSigner::IsVinAssociatedWithPubkey(CTxIn& vin, CPubKey& pubkey) CTransaction txVin; uint256 hash; if (GetTransaction(vin.prevout.hash, txVin, hash, true)) { - BOOST_FOREACH (CTxOut out, txVin.vout) { + for (CTxOut out : txVin.vout) { if (out.nValue == MASTER_NODE_AMOUNT * COIN) { if (out.scriptPubKey == payee2) return true; } @@ -2214,7 +2215,7 @@ bool CObfuscationQueue::Sign() bool CObfuscationQueue::Relay() { LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodes) { + for (CNode* pnode : vNodes) { // always relay to everyone pnode->PushMessage(NetMsgType::DSQ, (*this)); } @@ -2244,7 +2245,7 @@ bool CObfuscationQueue::CheckSignature() void CObfuscationPool::RelayFinalTransaction(const int sessionID, const CTransaction& txNew) { LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodes) { + for (CNode* pnode : vNodes) { pnode->PushMessage(NetMsgType::DSF, sessionID, txNew); } } @@ -2256,10 +2257,10 @@ void CObfuscationPool::RelayIn(const std::vector& vin, const int64_t& n std::vector vin2; std::vector vout2; - BOOST_FOREACH (CTxDSIn in, vin) + for (CTxDSIn in : vin) vin2.push_back(in); - BOOST_FOREACH (CTxDSOut out, vout) + for (CTxDSOut out : vout) vout2.push_back(out); CNode* pnode = FindNode(pSubmittedToKarmanode->addr); @@ -2272,14 +2273,14 @@ void CObfuscationPool::RelayIn(const std::vector& vin, const int64_t& n void CObfuscationPool::RelayStatus(const int sessionID, const int newState, const int newEntriesCount, const int newAccepted, const int errorID) { LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodes) + for (CNode* pnode : vNodes) pnode->PushMessage(NetMsgType::DSSU, sessionID, newState, newEntriesCount, newAccepted, errorID); } void CObfuscationPool::RelayCompletedTransaction(const int sessionID, const bool error, const int errorID) { LOCK(cs_vNodes); - BOOST_FOREACH (CNode* pnode, vNodes) + for (CNode* pnode : vNodes) pnode->PushMessage(NetMsgType::DSC, sessionID, error, errorID); } diff --git a/src/obfuscation.h b/src/obfuscation.h index 9134f15..6e5aa99 100644 --- a/src/obfuscation.h +++ b/src/obfuscation.h @@ -116,10 +116,10 @@ class CObfuScationEntry return false; } - BOOST_FOREACH (const CTxIn& in, vinIn) + for (const CTxIn& in : vinIn) sev.push_back(in); - BOOST_FOREACH (const CTxOut& out, voutIn) + for (const CTxOut& out : voutIn) vout.push_back(out); amount = amountIn; @@ -132,7 +132,7 @@ class CObfuScationEntry bool AddSig(const CTxIn& vin) { - BOOST_FOREACH (CTxDSIn& s, sev) { + for (CTxDSIn& s : sev) { if (s.prevout == vin.prevout && s.nSequence == vin.nSequence) { if (s.fHasSig) { return false; diff --git a/src/ohmcoin-cli.cpp b/src/ohmcoin-cli.cpp index 5a59e61..091d64a 100644 --- a/src/ohmcoin-cli.cpp +++ b/src/ohmcoin-cli.cpp @@ -8,8 +8,8 @@ #include "chainparamsbase.h" #include "clientversion.h" -#include "rpcclient.h" -#include "rpcprotocol.h" +#include "rpc/client.h" +#include "rpc/protocol.h" #include "util.h" #include "utilstrencodings.h" diff --git a/src/ohmcoin-tx.cpp b/src/ohmcoin-tx.cpp index 06bbc55..98ca193 100644 --- a/src/ohmcoin-tx.cpp +++ b/src/ohmcoin-tx.cpp @@ -447,7 +447,7 @@ static void MutateTxSign(CMutableTransaction& tx, const string& flagStr) ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata); // ... and merge in other signatures: - BOOST_FOREACH(const CTransaction& txv, txVariants) + for(const CTransaction& txv : txVariants) sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i)); UpdateTransaction(mergedTx, i, sigdata); diff --git a/src/ohmcoind.cpp b/src/ohmcoind.cpp index 2663bf0..b1a0530 100644 --- a/src/ohmcoind.cpp +++ b/src/ohmcoind.cpp @@ -10,13 +10,11 @@ #include "init.h" #include "main.h" #include "noui.h" -#include "scheduler.h" -#include "rpcserver.h" +#include "rpc/server.h" #include "ui_interface.h" #include "util.h" #include "httpserver.h" #include "httprpc.h" -#include "rpcserver.h" #include #include @@ -42,7 +40,7 @@ static bool fDaemon; -void WaitForShutdown(boost::thread_group* threadGroup) +void WaitForShutdown() { bool fShutdown = ShutdownRequested(); // Tell the main threads to shutdown. @@ -50,10 +48,7 @@ void WaitForShutdown(boost::thread_group* threadGroup) MilliSleep(200); fShutdown = ShutdownRequested(); } - if (threadGroup) { - Interrupt(*threadGroup); - threadGroup->join_all(); - } + Interrupt(); } ////////////////////////////////////////////////////////////////////////////// @@ -62,9 +57,6 @@ void WaitForShutdown(boost::thread_group* threadGroup) // bool AppInit(int argc, char* argv[]) { - boost::thread_group threadGroup; - CScheduler scheduler; - bool fRet = false; // @@ -141,7 +133,7 @@ bool AppInit(int argc, char* argv[]) #endif SoftSetBoolArg("-server", true); - fRet = AppInit2(threadGroup, scheduler); + fRet = AppInit2(); } catch (std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { @@ -149,12 +141,9 @@ bool AppInit(int argc, char* argv[]) } if (!fRet) { - Interrupt(threadGroup); - // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of - // the startup-failure cases to make sure they don't result in a hang due to some - // thread-blocking-waiting-for-another-thread-during-startup case + Interrupt(); } else { - WaitForShutdown(&threadGroup); + WaitForShutdown(); } Shutdown(); diff --git a/src/primitives/transaction.cpp b/src/primitives/transaction.cpp index 2c9de77..19874a3 100755 --- a/src/primitives/transaction.cpp +++ b/src/primitives/transaction.cpp @@ -14,8 +14,6 @@ #include "utilstrencodings.h" #include "transaction.h" -#include - extern bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow); std::string COutPoint::ToString() const diff --git a/src/qt/addressbookpage.cpp b/src/qt/addressbookpage.cpp index f9dfd6f..095200a 100755 --- a/src/qt/addressbookpage.cpp +++ b/src/qt/addressbookpage.cpp @@ -249,7 +249,7 @@ void AddressBookPage::done(int retval) // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); - foreach (QModelIndex index, indexes) { + for (QModelIndex index : indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } diff --git a/src/qt/addresstablemodel.cpp b/src/qt/addresstablemodel.cpp index 1b2ec41..c5f3d07 100755 --- a/src/qt/addresstablemodel.cpp +++ b/src/qt/addresstablemodel.cpp @@ -10,7 +10,8 @@ #include "walletmodel.h" #include "base58.h" -#include "wallet.h" +#include "wallet/wallet.h" +#include "askpassphrasedialog.h" #include #include @@ -81,7 +82,7 @@ class AddressTablePriv cachedAddressTable.clear(); { LOCK(wallet->cs_wallet); - BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, wallet->mapAddressBook) { + for (const std::pair & item : wallet->mapAddressBook) { const CTxDestination& address = item.first; const CScript redeemDestination = GetScriptForDestination(address); bool fMine = IsMine(*wallet, redeemDestination); @@ -141,7 +142,7 @@ class AddressTablePriv break; } } - + void updateEntry(const QString &pubCoin, const QString &isUsed, int status) { // Find address / label in model @@ -152,7 +153,7 @@ class AddressTablePriv int lowerIndex = (lower - cachedAddressTable.begin()); bool inModel = (lower != upper); AddressTableEntry::Type newEntryType = AddressTableEntry::Zerocoin; - + switch(status) { case CT_NEW: @@ -175,7 +176,7 @@ class AddressTablePriv parent->emitDataChanged(lowerIndex); break; } - + } @@ -384,7 +385,7 @@ QString AddressTableModel::addRow(const QString& type, const QString& label, con // Generate a new address to associate with given label CPubKey newKey; if (!wallet->GetKeyFromPool(newKey)) { - WalletModel::UnlockContext ctx(walletModel->requestUnlock(true)); + WalletModel::UnlockContext ctx(walletModel->requestUnlock(AskPassphraseDialog::Context::Unlock_Full, true)); if (!ctx.isValid()) { // Unlock wallet failed or was cancelled editStatus = WALLET_UNLOCK_FAILURE; diff --git a/src/qt/askpassphrasedialog.cpp b/src/qt/askpassphrasedialog.cpp index beaec60..4551d36 100755 --- a/src/qt/askpassphrasedialog.cpp +++ b/src/qt/askpassphrasedialog.cpp @@ -17,11 +17,14 @@ #include #include -AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget* parent, WalletModel* model) : QDialog(parent), - ui(new Ui::AskPassphraseDialog), - mode(mode), - model(model), - fCapsLock(false) +#include + +AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget* parent, WalletModel* model, Context context) : QDialog(parent), + ui(new Ui::AskPassphraseDialog), + mode(mode), + model(model), + context(context), + fCapsLock(false) { ui->setupUi(this); this->setStyleSheet(GUIUtil::loadStyleSheet()); @@ -46,16 +49,15 @@ AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget* parent, WalletModel this->model = model; switch (mode) { - case Encrypt: // Ask passphrase x2 + case Mode::Encrypt: // Ask passphrase x2 ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.
Please use a passphrase of ten or more random characters, or eight or more words.")); ui->passLabel1->hide(); ui->passEdit1->hide(); setWindowTitle(tr("Encrypt wallet")); break; - case UnlockAnonymize: - ui->anonymizationCheckBox->setChecked(true); + case Mode::UnlockAnonymize: ui->anonymizationCheckBox->show(); - case Unlock: // Ask passphrase + case Mode::Unlock: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); @@ -63,7 +65,7 @@ AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget* parent, WalletModel ui->passEdit3->hide(); setWindowTitle(tr("Unlock wallet")); break; - case Decrypt: // Ask passphrase + case Mode::Decrypt: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); @@ -71,13 +73,24 @@ AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget* parent, WalletModel ui->passEdit3->hide(); setWindowTitle(tr("Decrypt wallet")); break; - case ChangePass: // Ask old passphrase + new passphrase x2 + case Mode::ChangePass: // Ask old passphrase + new passphrase x2 setWindowTitle(tr("Change passphrase")); ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet.")); break; } - ui->anonymizationCheckBox->setChecked(model->isAnonymizeOnlyUnlocked()); + // Set checkbox "For anonymization, automint, and staking only" depending on from where we were called + if (context == Context::Unlock_Menu || context == Context::Mint_zOHMC || context == Context::BIP_38) { + ui->anonymizationCheckBox->setChecked(true); + } + else { + ui->anonymizationCheckBox->setChecked(false); + } + + // It doesn't make sense to show the checkbox for sending Ohmcoin because you wouldn't check it anyway. + if (context == Context::Send_OHMC || context == Context::Send_zOHMC) { + ui->anonymizationCheckBox->hide(); + } textChanged(); connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); @@ -109,7 +122,7 @@ void AskPassphraseDialog::accept() newpass2.assign(ui->passEdit3->text().toStdString().c_str()); switch (mode) { - case Encrypt: { + case Mode::Encrypt: { if (newpass1.empty() || newpass2.empty()) { // Cannot encrypt with empty passphrase break; @@ -146,8 +159,8 @@ void AskPassphraseDialog::accept() QDialog::reject(); // Cancelled } } break; - case UnlockAnonymize: - case Unlock: + case Mode::UnlockAnonymize: + case Mode::Unlock: if (!model->setWalletLocked(false, oldpass, ui->anonymizationCheckBox->isChecked())) { QMessageBox::critical(this, tr("Wallet unlock failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); @@ -155,7 +168,7 @@ void AskPassphraseDialog::accept() QDialog::accept(); // Success } break; - case Decrypt: + case Mode::Decrypt: if (!model->setWalletEncrypted(false, oldpass)) { QMessageBox::critical(this, tr("Wallet decryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); @@ -163,7 +176,7 @@ void AskPassphraseDialog::accept() QDialog::accept(); // Success } break; - case ChangePass: + case Mode::ChangePass: if (newpass1 == newpass2) { if (model->changePassphrase(oldpass, newpass1)) { QMessageBox::information(this, tr("Wallet encrypted"), @@ -186,15 +199,15 @@ void AskPassphraseDialog::textChanged() // Validate input, set Ok button to enabled when acceptable bool acceptable = false; switch (mode) { - case Encrypt: // New passphrase x2 + case Mode::Encrypt: // New passphrase x2 acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; - case UnlockAnonymize: // Old passphrase x1 - case Unlock: // Old passphrase x1 - case Decrypt: + case Mode::UnlockAnonymize: // Old passphrase x1 + case Mode::Unlock: // Old passphrase x1 + case Mode::Decrypt: acceptable = !ui->passEdit1->text().isEmpty(); break; - case ChangePass: // Old passphrase x1, new passphrase x2 + case Mode::ChangePass: // Old passphrase x1, new passphrase x2 acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; } diff --git a/src/qt/askpassphrasedialog.h b/src/qt/askpassphrasedialog.h index 655ba32..19e4841 100755 --- a/src/qt/askpassphrasedialog.h +++ b/src/qt/askpassphrasedialog.h @@ -21,7 +21,7 @@ class AskPassphraseDialog : public QDialog Q_OBJECT public: - enum Mode { + enum class Mode { Encrypt, /**< Ask passphrase twice and encrypt */ UnlockAnonymize, /**< Ask passphrase and unlock only for anonymization */ Unlock, /**< Ask passphrase and unlock */ @@ -29,7 +29,23 @@ class AskPassphraseDialog : public QDialog Decrypt /**< Ask passphrase and decrypt wallet */ }; - explicit AskPassphraseDialog(Mode mode, QWidget* parent, WalletModel* model); + // Context from where / for what the passphrase dialog was called to set the status of the checkbox + // Partly redundant to Mode above, but offers more flexibility for future enhancements + enum class Context { + Unlock_Menu, /** Unlock wallet from menu */ + Unlock_Full, /** Wallet needs to be fully unlocked */ + Encrypt, /** Encrypt unencrypted wallet */ + ToggleLock, /** Toggle wallet lock state */ + ChangePass, /** Change passphrase */ + Send_OHMC, /** Send OHMC */ + Send_zOHMC, /** Send zOHMC */ + Mint_zOHMC, /** Mint zOHMC */ + BIP_38, /** BIP38 menu */ + Multi_Sig, /** Multi-Signature dialog */ + Sign_Message /** Sign/verify message dialog */ + }; + + explicit AskPassphraseDialog(Mode mode, QWidget* parent, WalletModel* model, Context context); ~AskPassphraseDialog(); void accept(); @@ -38,6 +54,7 @@ class AskPassphraseDialog : public QDialog Ui::AskPassphraseDialog* ui; Mode mode; WalletModel* model; + Context context; bool fCapsLock; private slots: diff --git a/src/qt/bantablemodel.cpp b/src/qt/bantablemodel.cpp index 7707ce7..67ea7dc 100644 --- a/src/qt/bantablemodel.cpp +++ b/src/qt/bantablemodel.cpp @@ -51,9 +51,7 @@ class BanTablePriv CNode::GetBanned(banMap); cachedBanlist.clear(); -#if QT_VERSION >= 0x040700 cachedBanlist.reserve(banMap.size()); -#endif for (banmap_t::iterator it = banMap.begin(); it != banMap.end(); it++) { CCombinedBan banEntry; diff --git a/src/qt/bip38tooldialog.cpp b/src/qt/bip38tooldialog.cpp index adf6393..25d5bd4 100755 --- a/src/qt/bip38tooldialog.cpp +++ b/src/qt/bip38tooldialog.cpp @@ -14,7 +14,8 @@ #include "base58.h" #include "bip38.h" #include "init.h" -#include "wallet.h" +#include "wallet/wallet.h" +#include "askpassphrasedialog.h" #include #include @@ -145,7 +146,7 @@ void Bip38ToolDialog::on_encryptKeyButton_ENC_clicked() return; } - WalletModel::UnlockContext ctx(model->requestUnlock(true)); + WalletModel::UnlockContext ctx(model->requestUnlock(AskPassphraseDialog::Context::BIP_38, true)); if (!ctx.isValid()) { ui->statusLabel_ENC->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_ENC->setText(tr("Wallet unlock was cancelled.")); @@ -208,7 +209,7 @@ void Bip38ToolDialog::on_decryptKeyButton_DEC_clicked() void Bip38ToolDialog::on_importAddressButton_DEC_clicked() { - WalletModel::UnlockContext ctx(model->requestUnlock(true)); + WalletModel::UnlockContext ctx(model->requestUnlock(AskPassphraseDialog::Context::BIP_38, true)); if (!ctx.isValid()) { ui->statusLabel_DEC->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_DEC->setText(tr("Wallet unlock was cancelled.")); diff --git a/src/qt/bitcoingui.cpp b/src/qt/bitcoingui.cpp index c4eea4e..d690b27 100755 --- a/src/qt/bitcoingui.cpp +++ b/src/qt/bitcoingui.cpp @@ -57,13 +57,7 @@ #include #include #include - -#if QT_VERSION < 0x050000 -#include -#include -#else #include -#endif const QString BitcoinGUI::DEFAULT_WALLET = "~Default"; @@ -75,6 +69,7 @@ BitcoinGUI::BitcoinGUI(const NetworkStyle* networkStyle, QWidget* parent) : QMai labelEncryptionIcon(0), labelConnectionsIcon(0), labelBlocksIcon(0), + labelTorIcon(0), progressBarLabel(0), progressBar(0), progressDialog(0), @@ -147,12 +142,6 @@ BitcoinGUI::BitcoinGUI(const NetworkStyle* networkStyle, QWidget* parent) : QMai #endif setWindowTitle(windowTitle); -#if defined(Q_OS_MAC) && QT_VERSION < 0x050000 - // This property is not implemented in Qt 5. Setting it has no effect. - // A replacement API (QtMacUnifiedToolBar) is available in QtMacExtras. - setUnifiedTitleAndToolBarOnMac(true); -#endif - rpcConsole = new RPCConsole(enableWallet ? this : 0); #ifdef ENABLE_WALLET if (enableWallet) { @@ -201,6 +190,7 @@ BitcoinGUI::BitcoinGUI(const NetworkStyle* networkStyle, QWidget* parent) : QMai labelEncryptionIcon->setFlat(true); // Make the button look like a label, but clickable labelEncryptionIcon->setStyleSheet(".QPushButton { background-color: rgba(255, 255, 255, 0);}"); labelEncryptionIcon->setMaximumSize(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE); + labelTorIcon = new QLabel(); labelConnectionsIcon = new QPushButton(); labelConnectionsIcon->setObjectName("labelConnectionsIcon"); labelConnectionsIcon->setFlat(true); // Make the button look like a label, but clickable @@ -217,6 +207,8 @@ BitcoinGUI::BitcoinGUI(const NetworkStyle* networkStyle, QWidget* parent) : QMai frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelStakingIcon); frameBlocksLayout->addStretch(); + frameBlocksLayout->addWidget(labelTorIcon); + frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelConnectionsIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelBlocksIcon); @@ -232,7 +224,7 @@ BitcoinGUI::BitcoinGUI(const NetworkStyle* networkStyle, QWidget* parent) : QMai // Override style sheet for progress bar for styles that have a segmented progress bar, // as they make the text unreadable (workaround for issue #1071) - // See https://qt-project.org/doc/qt-4.8/gallery.html + // See https://doc.qt.io/qt-5/gallery.html QString curStyle = QApplication::style()->metaObject()->className(); if (curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle") { progressBar->setStyleSheet("QProgressBar { background-color: #F8F8F8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #00CCFF, stop: 1 #33CCFF); border-radius: 7px; margin: 0px; }"); @@ -520,7 +512,7 @@ void BitcoinGUI::createActions(const NetworkStyle* networkStyle) connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool))); connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet())); connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase())); - connect(unlockWalletAction, SIGNAL(triggered()), walletFrame, SLOT(unlockWallet())); + connect(unlockWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(unlockWallet(bool))); connect(lockWalletAction, SIGNAL(triggered()), walletFrame, SLOT(lockWallet())); connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab())); connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab())); @@ -614,7 +606,7 @@ void BitcoinGUI::createToolBars() spacer->setMaximumHeight(20); //spacer->setSizePolicy(QSizePolicy::Fixed); toolbar->addWidget(spacer); - + toolbar->addAction(overviewAction); toolbar->addAction(sendCoinsAction); @@ -669,6 +661,9 @@ void BitcoinGUI::setClientModel(ClientModel* clientModel) connect(clientModel, SIGNAL(showProgress(QString, int)), this, SLOT(showProgress(QString, int))); rpcConsole->setClientModel(clientModel); + + updateTorIcon(); + #ifdef ENABLE_WALLET if (walletFrame) { walletFrame->setClientModel(clientModel); @@ -1208,7 +1203,7 @@ void BitcoinGUI::dragEnterEvent(QDragEnterEvent* event) void BitcoinGUI::dropEvent(QDropEvent* event) { if (event->mimeData()->hasUrls()) { - foreach (const QUrl& uri, event->mimeData()->urls()) { + for (const QUrl& uri : event->mimeData()->urls()) { emit receivedURI(uri.toString()); } } @@ -1299,6 +1294,24 @@ void BitcoinGUI::setEncryptionStatus(int status) } #endif // ENABLE_WALLET +void BitcoinGUI::updateTorIcon() +{ + std::string ip_port; + bool tor_enabled = clientModel->getTorInfo(ip_port); + + if (tor_enabled) { + if (labelTorIcon->pixmap() == 0) { + QString ip_port_q = QString::fromStdString(ip_port); + labelTorIcon->setPixmap(QIcon(":/icons/onion").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); + labelTorIcon->setToolTip(tr("Tor is enabled: %1").arg(ip_port_q)); + } else { + labelTorIcon->show(); + } + } else { + labelTorIcon->hide(); + } +} + void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden) { if (!clientModel) @@ -1403,7 +1416,7 @@ void UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent* event) void UnitDisplayStatusBarControl::createContextMenu() { menu = new QMenu(); - foreach (BitcoinUnits::Unit u, BitcoinUnits::availableUnits()) { + for (BitcoinUnits::Unit u : BitcoinUnits::availableUnits()) { QAction* menuAction = new QAction(QString(BitcoinUnits::name(u)), this); menuAction->setData(QVariant(u)); menu->addAction(menuAction); diff --git a/src/qt/bitcoingui.h b/src/qt/bitcoingui.h index 216230c..0e9ff52 100755 --- a/src/qt/bitcoingui.h +++ b/src/qt/bitcoingui.h @@ -86,6 +86,7 @@ class BitcoinGUI : public QMainWindow UnitDisplayStatusBarControl* unitDisplayControl; QLabel* labelStakingIcon; QPushButton* labelEncryptionIcon; + QLabel* labelTorIcon; QPushButton* labelConnectionsIcon; QLabel* labelBlocksIcon; QLabel* progressBarLabel; @@ -199,6 +200,10 @@ public slots: void incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address); #endif // ENABLE_WALLET +private: + /** Set the Tor-enabled icon as shown in the UI. */ + void updateTorIcon(); + private slots: #ifdef ENABLE_WALLET /** Switch to overview (home) page */ diff --git a/src/qt/blockexplorer.cpp b/src/qt/blockexplorer.cpp index 5d41415..401b4bd 100755 --- a/src/qt/blockexplorer.cpp +++ b/src/qt/blockexplorer.cpp @@ -400,7 +400,7 @@ std::string AddressToString(const CTxDestination& dest) { std::vector Txs; paddressmap->GetTxs(Txs, AddressScript.GetID()); - BOOST_FOREACH (const CDiskTxPos& pos, Txs) + for (const CDiskTxPos& pos : Txs) { CTransaction tx; CBlock block; @@ -433,7 +433,7 @@ BlockExplorer::BlockExplorer(QWidget* parent) : QMainWindow(parent), ui->setupUi(this); this->setStyleSheet(GUIUtil::loadStyleSheet()); - + connect(ui->pushSearch, SIGNAL(released()), this, SLOT(onSearch())); connect(ui->content, SIGNAL(linkActivated(const QString&)), this, SLOT(goTo(const QString&))); connect(ui->back, SIGNAL(released()), this, SLOT(back())); diff --git a/src/qt/clientmodel.cpp b/src/qt/clientmodel.cpp index 69cee99..a2fbe9a 100755 --- a/src/qt/clientmodel.cpp +++ b/src/qt/clientmodel.cpp @@ -18,6 +18,7 @@ #include "karmanode-sync.h" #include "karmanodeman.h" #include "net.h" +#include "netbase.h" #include "ui_interface.h" #include "util.h" @@ -64,7 +65,7 @@ int ClientModel::getNumConnections(unsigned int flags) const return vNodes.size(); int nNum = 0; - BOOST_FOREACH (CNode* pnode, vNodes) + for (CNode* pnode : vNodes) if (flags & (pnode->fInbound ? CONNECTIONS_IN : CONNECTIONS_OUT)) nNum++; @@ -299,3 +300,21 @@ void ClientModel::unsubscribeFromCoreSignals() uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2)); uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this)); } + +bool ClientModel::getTorInfo(std::string& ip_port) const +{ + proxyType onion; + if (GetProxy((Network) 3, onion) && IsReachable((Network) 3)) { + { + LOCK(cs_mapLocalHost); + for (const std::pair &item : mapLocalHost) { + if (item.first.IsTor()) { + CService addrOnion = CService(item.first.ToString(), item.second.nPort); + ip_port = addrOnion.ToStringIPPort(); + return true; + } + } + } + } + return false; +} diff --git a/src/qt/clientmodel.h b/src/qt/clientmodel.h index 8ed2ecf..40ba9c6 100755 --- a/src/qt/clientmodel.h +++ b/src/qt/clientmodel.h @@ -76,6 +76,8 @@ class ClientModel : public QObject QString clientName() const; QString formatClientStartupTime() const; + bool getTorInfo(std::string& ip_port) const; + private: OptionsModel* optionsModel; PeerTableModel* peerTableModel; diff --git a/src/qt/coincontroldialog.cpp b/src/qt/coincontroldialog.cpp index 80447c6..36f507c 100755 --- a/src/qt/coincontroldialog.cpp +++ b/src/qt/coincontroldialog.cpp @@ -17,7 +17,7 @@ #include "coincontrol.h" #include "main.h" #include "obfuscation.h" -#include "wallet.h" +#include "wallet/wallet.h" #include "multisigdialog.h" #include // for 'map_list_of()' @@ -111,11 +111,8 @@ CoinControlDialog::CoinControlDialog(QWidget* parent, bool fMultisigEnabled) : Q connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(viewItemChanged(QTreeWidgetItem*, int))); // click on header -#if QT_VERSION < 0x050000 - ui->treeWidget->header()->setClickable(true); -#else ui->treeWidget->header()->setSectionsClickable(true); -#endif + connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int))); // ok button @@ -127,10 +124,6 @@ CoinControlDialog::CoinControlDialog(QWidget* parent, bool fMultisigEnabled) : Q // Toggle lock state connect(ui->pushButtonToggleLock, SIGNAL(clicked()), this, SLOT(buttonToggleLockClicked())); - // change coin control first column label due Qt4 bug. - // see https://github.com/bitcoin/bitcoin/issues/5716 - ui->treeWidget->headerItem()->setText(COLUMN_CHECKBOX, QString()); - ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84); ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 100); ui->treeWidget->setColumnWidth(COLUMN_LABEL, 170); @@ -449,12 +442,11 @@ void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column) // including all childs are partially selected. But the parent node should be fully selected // as well as the childs. Childs should never be partially selected in the first place. // Please remove this ugly fix, once the bug is solved upstream. -#if QT_VERSION >= 0x050000 + else if (column == COLUMN_CHECKBOX && item->childCount() > 0) { if (item->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked && item->child(0)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked) item->setCheckState(COLUMN_CHECKBOX, Qt::Checked); } -#endif } // return human readable label for priority number @@ -542,7 +534,7 @@ void CoinControlDialog::updateLabels(WalletModel* model, QDialog* dialog) CAmount nPayAmount = 0; bool fDust = false; CMutableTransaction txDummy; - foreach (const CAmount& amount, CoinControlDialog::payAmounts) { + for (const CAmount& amount : CoinControlDialog::payAmounts) { nPayAmount += amount; if (amount > 0) { @@ -572,7 +564,7 @@ void CoinControlDialog::updateLabels(WalletModel* model, QDialog* dialog) coinControl->ListSelected(vCoinControl); model->getOutputs(vCoinControl, vOutputs); - BOOST_FOREACH (const COutput& out, vOutputs) { + for (const COutput& out : vOutputs) { // unselect already spent, very unlikely scenario, this could happen // when selected are spent elsewhere, like rpc or another computer uint256 txhash = out.tx->GetHash(); @@ -767,7 +759,7 @@ void CoinControlDialog::updateView() map> mapCoins; model->listCoins(mapCoins); - BOOST_FOREACH (PAIRTYPE(QString, vector) coins, mapCoins) { + for (std::pair> coins : mapCoins) { QTreeWidgetItem* itemWalletAddress = new QTreeWidgetItem(); itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); QString sWalletAddress = coins.first; diff --git a/src/qt/configurekarmanodepage.cpp b/src/qt/configurekarmanodepage.cpp index 5d6a171..c99795a 100644 --- a/src/qt/configurekarmanodepage.cpp +++ b/src/qt/configurekarmanodepage.cpp @@ -20,7 +20,7 @@ #include "karmanodeconfig.h" #include "karmanodeman.h" #include "karmanodelist.h" -#include "wallet.h" +#include "wallet/wallet.h" #include #include @@ -132,7 +132,7 @@ void ConfigureKarmanodePage::accept() void ConfigureKarmanodePage::updateAlias(std::string Alias, std::string IP, std::string PrivKey, std::string TxHash, std::string OutputIndex, std::string mnAlias) { - BOOST_FOREACH (CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { + for (CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { if(mnAlias == mne.getAlias()) { int count = 0; count = getCounters(); @@ -170,10 +170,10 @@ void ConfigureKarmanodePage::on_AutoFillOutputs_clicked() // Find possible candidates vector possibleCoins = activeKarmanode.SelectCoinsKarmanode(); int test = 0; - BOOST_FOREACH (COutput& out, possibleCoins) { + for (COutput& out : possibleCoins) { std::string TXHash = out.tx->GetHash().ToString(); std::string OutputID = std::to_string(out.i); - BOOST_FOREACH (CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { + for (CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { if(OutputID == mne.getOutputIndex() && TXHash == mne.getTxHash()) { test = 1; diff --git a/src/qt/configurekarmanodepage.h b/src/qt/configurekarmanodepage.h index a1f09b4..521f032 100644 --- a/src/qt/configurekarmanodepage.h +++ b/src/qt/configurekarmanodepage.h @@ -7,7 +7,7 @@ #define BITCOIN_QT_CONFIGUREKARMANODEPAGE_H #include "karmanodelist.h" -#include "wallet.h" +#include "wallet/wallet.h" #include #include @@ -59,17 +59,17 @@ class ConfigureKarmanodePage : public QDialog { return counters; } - + int setCounters(int counter) { counters = counter; } - + QString getMnAliasCache() { return mnAliasCache; } - + void setMnAliasCache(QString mnAliasCaches) { mnAliasCache = mnAliasCaches; diff --git a/src/qt/guiutil.cpp b/src/qt/guiutil.cpp index 390de83..ebf9a7c 100755 --- a/src/qt/guiutil.cpp +++ b/src/qt/guiutil.cpp @@ -56,12 +56,8 @@ #include #include // for Qt::mightBeRichText #include - -#if QT_VERSION < 0x050000 -#include -#else #include -#endif +#include #if BOOST_FILESYSTEM_VERSION >= 3 static boost::filesystem::detail::utf8_codecvt_facet utf8; @@ -94,11 +90,7 @@ QString dateTimeStr(qint64 nTime) QFont bitcoinAddressFont() { QFont font("Monospace"); -#if QT_VERSION >= 0x040800 font.setStyleHint(QFont::Monospace); -#else - font.setStyleHint(QFont::TypeWriter); -#endif return font; } @@ -107,11 +99,9 @@ void setupAddressWidget(QValidatedLineEdit* widget, QWidget* parent) parent->setFocusProxy(widget); widget->setFont(bitcoinAddressFont()); -#if QT_VERSION >= 0x040700 // We don't want translators to use own addresses in translations // and this is the only place, where this address is supplied. widget->setPlaceholderText(QObject::tr("Enter a Ohmcoin address (e.g. %1)").arg("Z0hmc0InF23ak1nGR0cksjRnhaYf6AJ2Mp")); -#endif widget->setValidator(new BitcoinAddressEntryValidator(parent)); widget->setCheckValidator(new BitcoinAddressCheckValidator(parent)); } @@ -199,12 +189,8 @@ bool parseBitcoinURI(const QUrl& uri, SendCoinsRecipient* out) } rv.amount = 0; -#if QT_VERSION < 0x050000 - QList > items = uri.queryItems(); -#else QUrlQuery uriQuery(uri); QList > items = uriQuery.queryItems(); -#endif for (QList >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { @@ -285,11 +271,7 @@ bool isDust(const QString& address, const CAmount& amount) QString HtmlEscape(const QString& str, bool fMultiLine) { -#if QT_VERSION < 0x050000 - QString escaped = Qt::escape(str); -#else QString escaped = str.toHtmlEscaped(); -#endif escaped = escaped.replace(" ", " "); if (fMultiLine) { escaped = escaped.replace("\n", "
\n"); @@ -333,11 +315,7 @@ QString getSaveFileName(QWidget* parent, const QString& caption, const QString& QString myDir; if (dir.isEmpty()) // Default to user documents location { -#if QT_VERSION < 0x050000 - myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); -#else myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); -#endif } else { myDir = dir; } @@ -375,11 +353,7 @@ QString getOpenFileName(QWidget* parent, const QString& caption, const QString& QString myDir; if (dir.isEmpty()) // Default to user documents location { -#if QT_VERSION < 0x050000 - myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); -#else myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); -#endif } else { myDir = dir; } diff --git a/src/qt/guiutil.h b/src/qt/guiutil.h index 3a1bd89..c707ce8 100755 --- a/src/qt/guiutil.h +++ b/src/qt/guiutil.h @@ -232,7 +232,7 @@ QString formatPingTime(double dPingTime); /* Format a CNodeCombinedStats.nTimeOffset into a user-readable string. */ QString formatTimeOffset(int64_t nTimeOffset); -#if defined(Q_OS_MAC) && QT_VERSION >= 0x050000 +#if defined(Q_OS_MAC) // workaround for Qt OSX Bug: // https://bugreports.qt-project.org/browse/QTBUG-15631 // QProgressBar uses around 10% CPU even when app is in background diff --git a/src/qt/karmanodelist.cpp b/src/qt/karmanodelist.cpp index fca53bd..ddc956c 100755 --- a/src/qt/karmanodelist.cpp +++ b/src/qt/karmanodelist.cpp @@ -9,6 +9,7 @@ #include "configurekarmanodepage.h" #include "activekarmanode.h" +#include "askpassphrasedialog.h" #include "clientmodel.h" #include "guiutil.h" #include "init.h" @@ -16,7 +17,7 @@ #include "karmanodeconfig.h" #include "karmanodeman.h" #include "sync.h" -#include "wallet.h" +#include "wallet/wallet.h" #include "walletmodel.h" #include "util.h" @@ -59,21 +60,21 @@ KarmanodeList::KarmanodeList(QWidget* parent) : QWidget(parent), QAction* startAliasAction = new QAction(tr("Start alias"), this); QAction* copyAliasAction = new QAction(tr("Copy alias"), this); QAction* editAliasAction = new QAction(tr("Edit alias"), this); - QAction* deleteAliasAction = new QAction(tr("Delete"), this); + QAction* deleteAliasAction = new QAction(tr("Delete"), this); contextMenu = new QMenu(); contextMenu->addAction(startAliasAction); contextMenu->addAction(copyAliasAction); contextMenu->addAction(editAliasAction); - contextMenu->addAction(deleteAliasAction); - + contextMenu->addAction(deleteAliasAction); + connect(ui->tableWidgetMyKarmanodes, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showContextMenu(const QPoint&))); - connect(startAliasAction, SIGNAL(triggered()), this, SLOT(on_startButton_clicked())); - connect(copyAliasAction, SIGNAL(triggered()), this, SLOT(copyAlias())); + connect(startAliasAction, SIGNAL(triggered()), this, SLOT(on_startButton_clicked())); + connect(copyAliasAction, SIGNAL(triggered()), this, SLOT(copyAlias())); connect(editAliasAction, SIGNAL(triggered()), this, SLOT(on_editConfigureKarmanode_clicked())); - connect(deleteAliasAction, SIGNAL(triggered()), this, SLOT(deleteAlias())); - - + connect(deleteAliasAction, SIGNAL(triggered()), this, SLOT(deleteAlias())); + + timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updateMyNodeList())); timer->start(1000); @@ -109,7 +110,7 @@ void KarmanodeList::StartAlias(std::string strAlias) std::string strStatusHtml; strStatusHtml += "
Alias: " + strAlias; - BOOST_FOREACH (CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { + for (CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { if (mne.getAlias() == strAlias) { std::string strError; CKarmanodeBroadcast mnb; @@ -141,7 +142,7 @@ void KarmanodeList::StartAll(std::string strCommand) int nCountFailed = 0; std::string strFailedHtml; - BOOST_FOREACH (CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { + for (CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { std::string strError; CKarmanodeBroadcast mnb; @@ -186,7 +187,7 @@ void KarmanodeList::updateMyKarmanodeInfo(QString strAlias, QString strAddr, CKa bool fOldRowFound = false; int nNewRow = 0; - + for (int i = 0; i < ui->tableWidgetMyKarmanodes->rowCount(); i++) { if (ui->tableWidgetMyKarmanodes->item(i, 0)->text() == strAlias) { fOldRowFound = true; @@ -230,7 +231,7 @@ void KarmanodeList::updateMyNodeList(bool fForce) nTimeMyListUpdated = GetTime(); ui->tableWidgetMyKarmanodes->setSortingEnabled(false); - BOOST_FOREACH (CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { + for (CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { int nIndex; if(!mne.castOutputIndex(nIndex)) continue; @@ -268,7 +269,7 @@ void KarmanodeList::on_startButton_clicked() WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); if (encStatus == walletModel->Locked || encStatus == walletModel->UnlockedForAnonymizationOnly) { - WalletModel::UnlockContext ctx(walletModel->requestUnlock()); + WalletModel::UnlockContext ctx(walletModel->requestUnlock(AskPassphraseDialog::Context::Unlock_Full)); if (!ctx.isValid()) return; // Unlock wallet was cancelled @@ -292,34 +293,34 @@ void KarmanodeList::on_editConfigureKarmanode_clicked() std::string strAlias = ui->tableWidgetMyKarmanodes->item(nSelectedRow, 0)->text().toStdString(); int count = 0; - BOOST_FOREACH (CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { + for (CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { count = count + 1; if(strAlias == mne.getAlias()) { KarmanodeList::openEditConfigureKarmanodePage(QString::fromStdString(mne.getAlias()), QString::fromStdString(mne.getIp()), QString::fromStdString(mne.getPrivKey()), QString::fromStdString(mne.getTxHash()), QString::fromStdString(mne.getOutputIndex()), count); break; - + } } } void KarmanodeList::on_configureKarmanodeButton_clicked() { - + ConfigureKarmanodePage dlg(ConfigureKarmanodePage::NewConfigureKarmanode, this); if ( QDialog::Accepted == dlg.exec() ) { while (ui->tableWidgetMyKarmanodes->rowCount() > 0) { ui->tableWidgetMyKarmanodes->removeRow(0); - } - + } + // clear cache karmanodeConfig.clear(); // parse karmanode.conf std::string strErr; if (!karmanodeConfig.read(strErr)) { LogPrintf("Error reading karmanode configuration file: \n"); - } + } updateMyNodeList(true); } } @@ -339,15 +340,15 @@ void KarmanodeList::openEditConfigureKarmanodePage(QString strAlias, QString str while (ui->tableWidgetMyKarmanodes->rowCount() > 0) { ui->tableWidgetMyKarmanodes->removeRow(0); - } - + } + // clear cache karmanodeConfig.clear(); // parse karmanode.conf std::string strErr; if (!karmanodeConfig.read(strErr)) { LogPrintf("Error reading karmanode configuration file: \n"); - } + } updateMyNodeList(true); } } @@ -364,7 +365,7 @@ void KarmanodeList::deleteAlias() int nSelectedRow = index.row(); std::string strAlias = ui->tableWidgetMyKarmanodes->item(nSelectedRow, 0)->text().toStdString(); int count = 0; - BOOST_FOREACH (CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { + for (CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { count = count + 1; if(strAlias == mne.getAlias()) { vector confLockedCoins; @@ -382,18 +383,18 @@ void KarmanodeList::deleteAlias() while (ui->tableWidgetMyKarmanodes->rowCount() > 0) { ui->tableWidgetMyKarmanodes->removeRow(0); - } - + } + // clear cache karmanodeConfig.clear(); // parse karmanode.conf std::string strErr; if (!karmanodeConfig.read(strErr)) { LogPrintf("Error reading karmanode configuration file: \n"); - } + } updateMyNodeList(true); break; - + } } } @@ -410,14 +411,14 @@ void KarmanodeList::copyAlias() int nSelectedRow = index.row(); std::string strAlias = ui->tableWidgetMyKarmanodes->item(nSelectedRow, 0)->text().toStdString(); - BOOST_FOREACH (CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { - + for (CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { + if(strAlias == mne.getAlias()) { - + std::string fullAliasCopy = mne.getAlias() + " " + mne.getIp() + " " + mne.getPrivKey() + " " + mne.getTxHash() + " " + mne.getOutputIndex(); GUIUtil::setClipboard(QString::fromStdString(fullAliasCopy)); break; - + } } } @@ -435,7 +436,7 @@ void KarmanodeList::on_startAllButton_clicked() WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); if (encStatus == walletModel->Locked || encStatus == walletModel->UnlockedForAnonymizationOnly) { - WalletModel::UnlockContext ctx(walletModel->requestUnlock()); + WalletModel::UnlockContext ctx(walletModel->requestUnlock(AskPassphraseDialog::Context::Unlock_Full)); if (!ctx.isValid()) return; // Unlock wallet was cancelled @@ -466,7 +467,7 @@ void KarmanodeList::on_startMissingButton_clicked() WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); if (encStatus == walletModel->Locked || encStatus == walletModel->UnlockedForAnonymizationOnly) { - WalletModel::UnlockContext ctx(walletModel->requestUnlock()); + WalletModel::UnlockContext ctx(walletModel->requestUnlock(AskPassphraseDialog::Context::Unlock_Full)); if (!ctx.isValid()) return; // Unlock wallet was cancelled diff --git a/src/qt/karmanodelist.h b/src/qt/karmanodelist.h index b71e9d8..d53f0e9 100755 --- a/src/qt/karmanodelist.h +++ b/src/qt/karmanodelist.h @@ -10,7 +10,7 @@ #include "platformstyle.h" #include "sync.h" #include "util.h" -#include "wallet.h" +#include "wallet/wallet.h" #include #include diff --git a/src/qt/macdockiconhandler.mm b/src/qt/macdockiconhandler.mm index a86ccfd..f8bb1c5 100755 --- a/src/qt/macdockiconhandler.mm +++ b/src/qt/macdockiconhandler.mm @@ -14,10 +14,6 @@ #include #include -#if QT_VERSION < 0x050000 -extern void qt_mac_set_dock_menu(QMenu *); -#endif - static MacDockIconHandler *s_instance = NULL; bool dockClickHandler(id self,SEL _cmd,...) { @@ -49,9 +45,7 @@ void setupDockClickHandler() { this->m_dummyWidget = new QWidget(); this->m_dockMenu = new QMenu(this->m_dummyWidget); this->setMainWindow(NULL); -#if QT_VERSION < 0x050000 - qt_mac_set_dock_menu(this->m_dockMenu); -#elif QT_VERSION >= 0x050200 +#if QT_VERSION >= 0x050200 this->m_dockMenu->setAsDockMenu(); #endif [pool release]; diff --git a/src/qt/multisigdialog.cpp b/src/qt/multisigdialog.cpp index 5acec9f..1619d8d 100644 --- a/src/qt/multisigdialog.cpp +++ b/src/qt/multisigdialog.cpp @@ -16,7 +16,7 @@ #include "coins.h" #include "keystore.h" #include "init.h" -#include "wallet.h" +#include "wallet/wallet.h" #include "script/sign.h" #include "script/interpreter.h" #include "utilmoneystr.h" @@ -527,7 +527,7 @@ void MultisigDialog::on_signButton_clicked() CCoinsViewMemPool viewMempool(&viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view - BOOST_FOREACH (const CTxIn& txin, tx.vin) { + for (const CTxIn& txin : tx.vin) { const uint256& prevHash = txin.prevout.hash; CCoins coins; view.AccessCoins(prevHash); // this is certainly allowed to fail @@ -668,7 +668,7 @@ bool MultisigDialog::signMultisigTx(CMutableTransaction& tx, string& errorOut, Q } }else{ if (model->getEncryptionStatus() == model->Locked) { - if (!model->requestUnlock(true).isValid()) { + if (!model->requestUnlock(AskPassphraseDialog::Context::Multi_Sig, true).isValid()) { // Unlock wallet was cancelled throw runtime_error("Error: Your wallet is locked. Please enter the wallet passphrase first."); } diff --git a/src/qt/ohmcoin.cpp b/src/qt/ohmcoin.cpp index 9994570..0240d65 100644 --- a/src/qt/ohmcoin.cpp +++ b/src/qt/ohmcoin.cpp @@ -28,13 +28,12 @@ #include "init.h" #include "main.h" -#include "rpcserver.h" -#include "scheduler.h" +#include "rpc/server.h" #include "ui_interface.h" #include "util.h" #ifdef ENABLE_WALLET -#include "wallet.h" +#include "wallet/wallet.h" #endif #include @@ -55,13 +54,6 @@ #if defined(QT_STATICPLUGIN) #include -#if QT_VERSION < 0x050000 -Q_IMPORT_PLUGIN(qcncodecs) -Q_IMPORT_PLUGIN(qjpcodecs) -Q_IMPORT_PLUGIN(qtwcodecs) -Q_IMPORT_PLUGIN(qkrcodecs) -Q_IMPORT_PLUGIN(qtaccessiblewidgets) -#else #if QT_VERSION < 0x050400 Q_IMPORT_PLUGIN(AccessibleFactory) #endif @@ -73,11 +65,6 @@ Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin); Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin); #endif #endif -#endif - -#if QT_VERSION < 0x050000 -#include -#endif // Declare meta types used for QMetaObject::invokeMethod Q_DECLARE_METATYPE(bool*) @@ -180,14 +167,11 @@ public slots: void restart(QStringList args); signals: - void initializeResult(int retval); - void shutdownResult(int retval); + void initializeResult(bool success); + void shutdownResult(); void runawayException(const QString& message); private: - boost::thread_group threadGroup; - CScheduler scheduler; - /// Flag indicating a restart bool execute_restart; @@ -226,8 +210,8 @@ class BitcoinApplication : public QApplication WId getMainWinId() const; public slots: - void initializeResult(int retval); - void shutdownResult(int retval); + void initializeResult(bool success); + void shutdownResult(); /// Handle runaway exceptions. Shows a message box with the problem and quits the program. void handleRunawayException(const QString& message); @@ -271,7 +255,7 @@ void BitcoinCore::initialize() try { qDebug() << __func__ << ": Running AppInit2 in thread"; - int rv = AppInit2(threadGroup, scheduler); + bool rv = AppInit2(); emit initializeResult(rv); } catch (std::exception& e) { handleRunawayException(&e); @@ -286,11 +270,10 @@ void BitcoinCore::restart(QStringList args) execute_restart = false; try { qDebug() << __func__ << ": Running Restart in thread"; - Interrupt(threadGroup); - threadGroup.join_all(); + Interrupt(); PrepareShutdown(); qDebug() << __func__ << ": Shutdown finished"; - emit shutdownResult(1); + Q_EMIT shutdownResult(); CExplicitNetCleanup::callCleanup(); QProcess::startDetached(QApplication::applicationFilePath(), args); qDebug() << __func__ << ": Restart initiated..."; @@ -307,11 +290,10 @@ void BitcoinCore::shutdown() { try { qDebug() << __func__ << ": Running Shutdown in thread"; - Interrupt(threadGroup); - threadGroup.join_all(); + Interrupt(); Shutdown(); qDebug() << __func__ << ": Shutdown finished"; - emit shutdownResult(1); + Q_EMIT shutdownResult(); } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { @@ -399,8 +381,8 @@ void BitcoinApplication::startThread() executor->moveToThread(coreThread); /* communication to and from thread */ - connect(executor, SIGNAL(initializeResult(int)), this, SLOT(initializeResult(int))); - connect(executor, SIGNAL(shutdownResult(int)), this, SLOT(shutdownResult(int))); + connect(executor, SIGNAL(initializeResult(bool)), this, SLOT(initializeResult(bool))); + connect(executor, SIGNAL(shutdownResult()), this, SLOT(shutdownResult())); connect(executor, SIGNAL(runawayException(QString)), this, SLOT(handleRunawayException(QString))); connect(this, SIGNAL(requestedInitialize()), executor, SLOT(initialize())); connect(this, SIGNAL(requestedShutdown()), executor, SLOT(shutdown())); @@ -442,12 +424,13 @@ void BitcoinApplication::requestShutdown() emit requestedShutdown(); } -void BitcoinApplication::initializeResult(int retval) +void BitcoinApplication::initializeResult(bool success) { - qDebug() << __func__ << ": Initialization result: " << retval; - // Set exit result: 0 if successful, 1 if failure - returnValue = retval ? 0 : 1; - if (retval) { + qDebug() << __func__ << ": Initialization result: " << success; + // Set exit result. + returnValue = success ? EXIT_SUCCESS : EXIT_FAILURE; + if(success) + { #ifdef ENABLE_WALLET PaymentServer::LoadRootCAs(); paymentServer->setOptionsModel(optionsModel); @@ -492,9 +475,8 @@ void BitcoinApplication::initializeResult(int retval) } } -void BitcoinApplication::shutdownResult(int retval) +void BitcoinApplication::shutdownResult() { - qDebug() << __func__ << ": Shutdown result: " << retval; quit(); // Exit main loop after shutdown finished } @@ -517,33 +499,27 @@ int main(int argc, char* argv[]) { SetupEnvironment(); - /// 1. Parse command-line options. These take precedence over anything else. - // Command-line options take precedence: +/// 1. Parse command-line options. These take precedence over anything else. +// Command-line options take precedence: ParseParameters(argc, argv); // Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory /// 2. Basic Qt initialization (not dependent on parameters or configuration) -#if QT_VERSION < 0x050000 - // Internal string conversion is all UTF-8 - QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); - QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); -#endif - Q_INIT_RESOURCE(ohmcoin_locale); Q_INIT_RESOURCE(ohmcoin); - BitcoinApplication app(argc, argv); #if QT_VERSION > 0x050100 // Generate high-dpi pixmaps QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #endif #if QT_VERSION >= 0x050600 - QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); + QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif #ifdef Q_OS_MAC QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif + BitcoinApplication app(argc, argv); // Register meta types used for QMetaObject::invokeMethod qRegisterMetaType(); @@ -634,14 +610,9 @@ int main(int argc, char* argv[]) /// 9. Main GUI initialization // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); -#if QT_VERSION < 0x050000 - // Install qDebug() message handler to route to debug.log - qInstallMsgHandler(DebugMessageHandler); -#else #if defined(Q_OS_WIN) // Install global event filter for processing Windows session related Windows messages (WM_QUERYENDSESSION and WM_ENDSESSION) qApp->installNativeEventFilter(new WinShutdownMonitor()); -#endif // Install qDebug() message handler to route to debug.log qInstallMessageHandler(DebugMessageHandler); #endif @@ -657,7 +628,7 @@ int main(int argc, char* argv[]) try { app.createWindow(networkStyle.data()); app.requestInitialize(); -#if defined(Q_OS_WIN) && QT_VERSION >= 0x050000 +#if defined(Q_OS_WIN) WinShutdownMonitor::registerShutdownBlockReason(QObject::tr("Ohmcoin Core didn't yet exit safely..."), (HWND)app.getMainWinId()); #endif app.exec(); diff --git a/src/qt/ohmcoin.qrc b/src/qt/ohmcoin.qrc index 01d0c71..0831e33 100644 --- a/src/qt/ohmcoin.qrc +++ b/src/qt/ohmcoin.qrc @@ -64,6 +64,7 @@ res/icons/browse.png res/icons/staking_active.png res/icons/staking_inactive.png + res/icons/onion.png res/css/default.css @@ -86,7 +87,7 @@ res/images/splash@2x.png res/images/splash_testnet.png res/images/splash_testnet@2x.png - + res/movies/spinner-000.png @@ -133,4 +134,4 @@ res/fonts/Hind-SemiBold.ttf res/fonts/Montserrat-Bold.ttf - \ No newline at end of file + diff --git a/src/qt/openuridialog.cpp b/src/qt/openuridialog.cpp index 5024182..836e6ce 100755 --- a/src/qt/openuridialog.cpp +++ b/src/qt/openuridialog.cpp @@ -18,9 +18,7 @@ OpenURIDialog::OpenURIDialog(QWidget* parent) : QDialog(parent), { ui->setupUi(this); ui->uriEdit->setAttribute(Qt::WA_MacShowFocusRect, 0); -#if QT_VERSION >= 0x040700 ui->uriEdit->setPlaceholderText("ohmcoin:"); -#endif } OpenURIDialog::~OpenURIDialog() diff --git a/src/qt/optionsdialog.cpp b/src/qt/optionsdialog.cpp index d88a6be..a65e3cf 100755 --- a/src/qt/optionsdialog.cpp +++ b/src/qt/optionsdialog.cpp @@ -19,7 +19,7 @@ #include "txdb.h" // for -dbcache defaults #ifdef ENABLE_WALLET -#include "wallet.h" // for CWallet::minTxFee +#include "wallet/wallet.h" // for CWallet::minTxFee #endif #include @@ -83,10 +83,10 @@ OptionsDialog::OptionsDialog(QWidget* parent, bool enableWallet) : QDialog(paren ui->connectSocks->setAttribute(Qt::WA_MacShowFocusRect, 0); ui->proxyIp->setAttribute(Qt::WA_MacShowFocusRect, 0); ui->proxyPort->setAttribute(Qt::WA_MacShowFocusRect, 0); - + ui->thirdPartyTxUrls->setAttribute(Qt::WA_MacShowFocusRect, 0); - + #endif /* remove Wallet tab in case of -disablewallet */ @@ -102,7 +102,7 @@ OptionsDialog::OptionsDialog(QWidget* parent, bool enableWallet) : QDialog(paren digits.setNum(index); ui->digits->addItem(digits, digits); } - + /* Theme selector static themes */ ui->theme->addItem(QString("Default"), QVariant("default")); @@ -131,31 +131,21 @@ OptionsDialog::OptionsDialog(QWidget* parent, bool enableWallet) : QDialog(paren /* Language selector */ QDir translations(":translations"); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); - foreach (const QString& langStr, translations.entryList()) { + for (const QString& langStr : translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if (langStr.contains("_")) { -#if QT_VERSION >= 0x040800 /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); -#else - /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */ - ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); -#endif - } else { -#if QT_VERSION >= 0x040800 + } + else + { /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); -#else - /** display language strings as "language (locale name)", e.g. "German (de)" */ - ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); -#endif } } -#if QT_VERSION >= 0x040700 ui->thirdPartyTxUrls->setPlaceholderText("https://example.com/tx/%s"); -#endif ui->unit->setModel(new BitcoinUnits(this)); diff --git a/src/qt/optionsmodel.cpp b/src/qt/optionsmodel.cpp index 65045a1..8fc14d7 100755 --- a/src/qt/optionsmodel.cpp +++ b/src/qt/optionsmodel.cpp @@ -22,8 +22,8 @@ #ifdef ENABLE_WALLET #include "karmanodeconfig.h" -#include "wallet.h" -#include "walletdb.h" +#include "wallet/wallet.h" +#include "wallet/walletdb.h" #endif #include @@ -84,7 +84,7 @@ void OptionsModel::Init() if (!settings.contains("nZeromintPercentage")) settings.setValue("nZeromintPercentage", 10); nZeromintPercentage = settings.value("nZeromintPercentage").toLongLong(); - + if (!settings.contains("nPreferredDenom")) settings.setValue("nPreferredDenom", 0); nPreferredDenom = settings.value("nPreferredDenom", "0").toLongLong(); diff --git a/src/qt/overviewpage.cpp b/src/qt/overviewpage.cpp index bf7c882..fad4ebd 100755 --- a/src/qt/overviewpage.cpp +++ b/src/qt/overviewpage.cpp @@ -185,13 +185,13 @@ void OverviewPage::getPercentage(CAmount nUnlockedBalance, CAmount nZerocoinBala } double dPercentage = 100.0 - dzPercentage; - + szOHMCPercentage = "(" + QLocale(QLocale::system()).toString(dzPercentage, 'f', nPrecision) + " %)"; sOHMCPercentage = "(" + QLocale(QLocale::system()).toString(dPercentage, 'f', nPrecision) + " %)"; - + } -void OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, +void OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& zerocoinBalance, const CAmount& unconfirmedZerocoinBalance, const CAmount& immatureZerocoinBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance) { @@ -213,8 +213,8 @@ void OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmed } // OHMC Balance CAmount nTotalBalance = balance + unconfirmedBalance; - CAmount ohmcAvailableBalance = balance - immatureBalance - nLockedBalance; - CAmount nTotalWatchBalance = watchOnlyBalance + watchUnconfBalance + watchImmatureBalance; + CAmount ohmcAvailableBalance = balance - immatureBalance + nLockedBalance; + CAmount nTotalWatchBalance = watchOnlyBalance + watchUnconfBalance + watchImmatureBalance; CAmount nUnlockedBalance = nTotalBalance - nLockedBalance; // zOHMC Balance CAmount matureZerocoinBalance = zerocoinBalance - unconfirmedZerocoinBalance - immatureZerocoinBalance; @@ -363,9 +363,9 @@ void OverviewPage::setWalletModel(WalletModel* model) // Keep up to date with wallet setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), - model->getZerocoinBalance(), model->getUnconfirmedZerocoinBalance(), model->getImmatureZerocoinBalance(), + model->getZerocoinBalance(), model->getUnconfirmedZerocoinBalance(), model->getImmatureZerocoinBalance(), model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance()); - connect(model, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this, + connect(model, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this, SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); diff --git a/src/qt/paymentrequestplus.cpp b/src/qt/paymentrequestplus.cpp index a8c9bbe..78e5f46 100755 --- a/src/qt/paymentrequestplus.cpp +++ b/src/qt/paymentrequestplus.cpp @@ -100,12 +100,10 @@ bool PaymentRequestPlus::getMerchant(X509_STORE* certStore, QString& merchant) c qWarning() << "PaymentRequestPlus::getMerchant : Payment request: certificate expired or not yet active: " << qCert; return false; } -#if QT_VERSION >= 0x050000 if (qCert.isBlacklisted()) { qWarning() << "PaymentRequestPlus::getMerchant : Payment request: certificate blacklisted: " << qCert; return false; } -#endif const unsigned char* data = (const unsigned char*)certChain.certificate(i).data(); X509* cert = d2i_X509(NULL, &data, certChain.certificate(i).size()); if (cert) diff --git a/src/qt/paymentserver.cpp b/src/qt/paymentserver.cpp index fb4c003..6dcfeae 100755 --- a/src/qt/paymentserver.cpp +++ b/src/qt/paymentserver.cpp @@ -15,7 +15,7 @@ #include "chainparams.h" #include "ui_interface.h" #include "util.h" -#include "wallet.h" +#include "wallet/wallet.h" #include @@ -42,12 +42,7 @@ #include #include #include - -#if QT_VERSION < 0x050000 -#include -#else #include -#endif using namespace boost; using namespace std; @@ -142,17 +137,17 @@ void PaymentServer::LoadRootCAs(X509_STORE* _store) int nRootCerts = 0; const QDateTime currentTime = QDateTime::currentDateTime(); - foreach (const QSslCertificate& cert, certList) { + for (const QSslCertificate& cert : certList) { if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate()) { ReportInvalidCertificate(cert); continue; } -#if QT_VERSION >= 0x050000 + if (cert.isBlacklisted()) { ReportInvalidCertificate(cert); continue; } -#endif + QByteArray certData = cert.toDer(); const unsigned char* data = (const unsigned char*)certData.data(); @@ -239,7 +234,7 @@ void PaymentServer::ipcParseCommandLine(int argc, char* argv[]) bool PaymentServer::ipcSendCommandLine() { bool fResult = false; - foreach (const QString& r, savedPaymentRequests) { + for (const QString& r : savedPaymentRequests) { QLocalSocket* socket = new QLocalSocket(); socket->connectToServer(ipcServerName(), QIODevice::WriteOnly); if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT)) { @@ -358,7 +353,7 @@ void PaymentServer::uiReady() initNetManager(); saveURIs = false; - foreach (const QString& s, savedPaymentRequests) { + for (const QString& s : savedPaymentRequests) { handleURIOrFile(s); } savedPaymentRequests.clear(); @@ -373,11 +368,7 @@ void PaymentServer::handleURIOrFile(const QString& s) if (s.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // ohmcoin: URI { -#if QT_VERSION < 0x050000 - QUrl uri(s); -#else QUrlQuery uri((QUrl(s))); -#endif if (uri.hasQueryItem("r")) // payment request URI { QByteArray temp; @@ -517,7 +508,7 @@ bool PaymentServer::processPaymentRequest(PaymentRequestPlus& request, SendCoins QList > sendingTos = request.getPayTo(); QStringList addresses; - foreach (const PAIRTYPE(CScript, CAmount) & sendingTo, sendingTos) { + for (const std::pair& sendingTo : sendingTos) { // Extract and check destination addresses CTxDestination dest; if (ExtractDestination(sendingTo.first, dest)) { @@ -677,7 +668,7 @@ void PaymentServer::reportSslErrors(QNetworkReply* reply, const QList Q_UNUSED(reply); QString errString; - foreach (const QSslError& err, errs) { + for (const QSslError& err : errs) { qWarning() << "PaymentServer::reportSslErrors : " << err; errString += err.errorString() + "\n"; } diff --git a/src/qt/peertablemodel.cpp b/src/qt/peertablemodel.cpp index aa45959..e981e41 100755 --- a/src/qt/peertablemodel.cpp +++ b/src/qt/peertablemodel.cpp @@ -58,10 +58,8 @@ class PeerTablePriv return; } cachedNodeStats.clear(); -#if QT_VERSION >= 0x040700 cachedNodeStats.reserve(vNodes.size()); -#endif - foreach (CNode* pnode, vNodes) { + for (CNode* pnode : vNodes) { CNodeCombinedStats stats; stats.nodeStateStats.nMisbehavior = 0; stats.nodeStateStats.nSyncHeight = -1; @@ -76,7 +74,7 @@ class PeerTablePriv { TRY_LOCK(cs_main, lockMain); if (lockMain) { - BOOST_FOREACH (CNodeCombinedStats& stats, cachedNodeStats) + for (CNodeCombinedStats& stats : cachedNodeStats) stats.fNodeStateStatsAvailable = GetNodeStateStats(stats.nodeStats.nodeid, stats.nodeStateStats); } } @@ -88,7 +86,7 @@ class PeerTablePriv // build index map mapNodeRows.clear(); int row = 0; - foreach (const CNodeCombinedStats& stats, cachedNodeStats) + for(const CNodeCombinedStats& stats : cachedNodeStats) mapNodeRows.insert(std::pair(stats.nodeStats.nodeid, row++)); } diff --git a/src/qt/platformstyle.cpp b/src/qt/platformstyle.cpp index 93bca92..09e33b5 100755 --- a/src/qt/platformstyle.cpp +++ b/src/qt/platformstyle.cpp @@ -47,7 +47,7 @@ QIcon ColorizeIcon(const QIcon& ico, const QColor& colorbase) { QIcon new_ico; QSize sz; - Q_FOREACH (sz, ico.availableSizes()) { + for (const QSize& sz : ico.availableSizes()) { QImage img(ico.pixmap(sz).toImage()); MakeSingleColorImage(img, colorbase); new_ico.addPixmap(QPixmap::fromImage(img)); diff --git a/src/qt/privacydialog.cpp b/src/qt/privacydialog.cpp index 7a5b346..3163c74 100755 --- a/src/qt/privacydialog.cpp +++ b/src/qt/privacydialog.cpp @@ -7,6 +7,7 @@ #include "addressbookpage.h" #include "addresstablemodel.h" +#include "askpassphrasedialog.h" #include "bitcoinunits.h" #include "coincontroldialog.h" #include "libzerocoin/Denominations.h" @@ -175,7 +176,7 @@ void PrivacyDialog::on_pushButtonMintzOHMC_clicked() // Request unlock if wallet was locked or unlocked for mixing: WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); if (encStatus == walletModel->Locked) { - WalletModel::UnlockContext ctx(walletModel->requestUnlock(true)); + WalletModel::UnlockContext ctx(walletModel->requestUnlock(AskPassphraseDialog::Context::Mint_zOHMC, true)); if (!ctx.isValid()) { // Unlock wallet was cancelled ui->TEMintStatus->setPlainText(tr("Error: Your wallet is locked. Please enter the wallet passphrase first.")); @@ -281,7 +282,7 @@ void PrivacyDialog::on_pushButtonSpendzOHMC_clicked() // Request unlock if wallet was locked or unlocked for mixing: WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); if (encStatus == walletModel->Locked || encStatus == walletModel->UnlockedForAnonymizationOnly) { - WalletModel::UnlockContext ctx(walletModel->requestUnlock(true)); + WalletModel::UnlockContext ctx(walletModel->requestUnlock(AskPassphraseDialog::Context::Send_zOHMC, true)); if (!ctx.isValid()) { // Unlock wallet was cancelled return; @@ -757,4 +758,4 @@ void PrivacyDialog::updateSPORK18Status() ui->pushButtonSpendzOHMC->setEnabled(true); ui->pushButtonSpendzOHMC->setToolTip(tr("Spend Zerocoin. Without 'Pay To:' address creates payments to yourself.")); } -} \ No newline at end of file +} diff --git a/src/qt/proposaldialog.cpp b/src/qt/proposaldialog.cpp index 8051281..e065d59 100644 --- a/src/qt/proposaldialog.cpp +++ b/src/qt/proposaldialog.cpp @@ -22,7 +22,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/qt/proposaldialog.h b/src/qt/proposaldialog.h index edcb9d8..a059d23 100644 --- a/src/qt/proposaldialog.h +++ b/src/qt/proposaldialog.h @@ -9,7 +9,7 @@ #include #include #include -#include +#include #include #include @@ -27,7 +27,7 @@ QT_BEGIN_NAMESPACE class QDataWidgetMapper; QT_END_NAMESPACE -/** +/** * Dialog for creating a proposal. */ class ProposalDialog : public QDialog diff --git a/src/qt/proposallist.cpp b/src/qt/proposallist.cpp index c3c786b..15bcfde 100644 --- a/src/qt/proposallist.cpp +++ b/src/qt/proposallist.cpp @@ -20,11 +20,10 @@ #include "karmanode-payments.h" #include "karmanodeconfig.h" #include "karmanodeman.h" -#include "rpcserver.h" +#include "rpc/server.h" #include "ui_interface.h" #include "utilmoneystr.h" -#include "rpcserver.h" #include "util.h" #include @@ -534,4 +533,4 @@ void ProposalList::resizeEvent(QResizeEvent* event) { QWidget::resizeEvent(event); columnResizingFixer->stretchColumnWidth(ProposalTableModel::Proposal); -} \ No newline at end of file +} diff --git a/src/qt/proposaltablemodel.cpp b/src/qt/proposaltablemodel.cpp index dcf9db7..8f61111 100644 --- a/src/qt/proposaltablemodel.cpp +++ b/src/qt/proposaltablemodel.cpp @@ -14,7 +14,7 @@ #include "karmanode-payments.h" #include "karmanodeconfig.h" #include "karmanodeman.h" -#include "rpcserver.h" +#include "rpc/server.h" #include "obfuscation.h" //#include "governance-vote.h" @@ -321,4 +321,4 @@ QModelIndex ProposalTableModel::index(int row, int column, const QModelIndex &pa } return QModelIndex(); -} \ No newline at end of file +} diff --git a/src/qt/proposaltablemodel.h b/src/qt/proposaltablemodel.h index a73ab86..8d61735 100644 --- a/src/qt/proposaltablemodel.h +++ b/src/qt/proposaltablemodel.h @@ -23,7 +23,7 @@ #include "karmanode-payments.h" #include "karmanodeconfig.h" #include "karmanodeman.h" -#include "rpcserver.h" +#include "rpc/server.h" #include "obfuscation.h" @@ -87,4 +87,4 @@ public Q_SLOTS: void onResult(QNetworkReply *result); }; -#endif // BITCOIN_QT_PROPOSALTABLEMODEL_H \ No newline at end of file +#endif // BITCOIN_QT_PROPOSALTABLEMODEL_H diff --git a/src/qt/receivecoinsdialog.cpp b/src/qt/receivecoinsdialog.cpp index eaa395c..eac698a 100755 --- a/src/qt/receivecoinsdialog.cpp +++ b/src/qt/receivecoinsdialog.cpp @@ -13,7 +13,7 @@ #include "receiverequestdialog.h" #include "recentrequeststablemodel.h" #include "walletmodel.h" -#include "wallet.h" +#include "wallet/wallet.h" #include #include @@ -37,7 +37,7 @@ ReceiveCoinsDialog::ReceiveCoinsDialog(QWidget* parent) : QDialog(parent), //ui->reqAmount->setAttribute(Qt::WA_MacShowFocusRect, 0); //needs to be handled within bitcoinamountfield.cpp ui->reqMessage->setAttribute(Qt::WA_MacShowFocusRect, 0); - + #endif // configure bech32 checkbox, disable if launched with legacy as default: @@ -155,7 +155,7 @@ void ReceiveCoinsDialog::on_receiveButton_clicked() if (address_type != OUTPUT_TYPE_LEGACY) { address_type = ui->useBech32->isChecked() ? OUTPUT_TYPE_BECH32 : OUTPUT_TYPE_DEFAULT; } - address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, "", address_type); + address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, "", address_type); } SendCoinsRecipient info(address, label, ui->reqAmount->value(), ui->reqMessage->text()); @@ -194,7 +194,7 @@ void ReceiveCoinsDialog::on_showRequestButton_clicked() return; QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows(); - foreach (QModelIndex index, selection) { + for (QModelIndex index : selection) { on_recentRequestsView_doubleClicked(index); } } diff --git a/src/qt/receiverequestdialog.cpp b/src/qt/receiverequestdialog.cpp index af90ca4..f24dad9 100755 --- a/src/qt/receiverequestdialog.cpp +++ b/src/qt/receiverequestdialog.cpp @@ -17,9 +17,6 @@ #include #include #include -#if QT_VERSION < 0x050000 -#include -#endif #if defined(HAVE_CONFIG_H) #include "config/ohmcoin-config.h" /* for USE_QRCODE */ diff --git a/src/qt/recentrequeststablemodel.cpp b/src/qt/recentrequeststablemodel.cpp index 96f6881..eb7ec80 100755 --- a/src/qt/recentrequeststablemodel.cpp +++ b/src/qt/recentrequeststablemodel.cpp @@ -10,8 +10,6 @@ #include "optionsmodel.h" #include "streams.h" -#include - RecentRequestsTableModel::RecentRequestsTableModel(CWallet* wallet, WalletModel* parent) : walletModel(parent) { Q_UNUSED(wallet); @@ -20,7 +18,7 @@ RecentRequestsTableModel::RecentRequestsTableModel(CWallet* wallet, WalletModel* // Load entries from wallet std::vector vReceiveRequests; parent->loadReceiveRequests(vReceiveRequests); - BOOST_FOREACH (const std::string& request, vReceiveRequests) + for (const std::string& request : vReceiveRequests) addNewRequest(request); /* These columns must match the indices in the ColumnIndex enumeration */ diff --git a/src/qt/res/icons/onion.png b/src/qt/res/icons/onion.png new file mode 100644 index 0000000..bc7edfc Binary files /dev/null and b/src/qt/res/icons/onion.png differ diff --git a/src/qt/rpcconsole.cpp b/src/qt/rpcconsole.cpp index 6990d91..c76402f 100755 --- a/src/qt/rpcconsole.cpp +++ b/src/qt/rpcconsole.cpp @@ -14,11 +14,11 @@ #include "chainparams.h" #include "main.h" -#include "rpcclient.h" -#include "rpcserver.h" +#include "rpc/client.h" +#include "rpc/server.h" #include "util.h" #ifdef ENABLE_WALLET -#include "wallet.h" +#include "wallet/wallet.h" #endif // ENABLE_WALLET #include @@ -39,10 +39,6 @@ #include #include -#if QT_VERSION < 0x050000 -#include -#endif - // TODO: add a scrollback limit, as there is currently none // TODO: make it possible to filter out categories (esp debug messages when implemented) // TODO: receive errors and debug messages through ClientModel @@ -144,7 +140,7 @@ bool parseCommandLine(std::vector& args, const std::string& strComm STATE_ESCAPE_DOUBLEQUOTED } state = STATE_EATING_SPACES; std::string curarg; - foreach (char ch, strCommand) { + for (char ch : strCommand) { switch (state) { case STATE_ARGUMENT: // In or after argument case STATE_EATING_SPACES: // Handle runs of whitespace diff --git a/src/qt/sendcoinsdialog.cpp b/src/qt/sendcoinsdialog.cpp index e46c9b5..492686f 100755 --- a/src/qt/sendcoinsdialog.cpp +++ b/src/qt/sendcoinsdialog.cpp @@ -21,7 +21,7 @@ #include "coincontrol.h" #include "ui_interface.h" #include "utilmoneystr.h" -#include "wallet.h" +#include "wallet/wallet.h" #include #include @@ -42,7 +42,7 @@ SendCoinsDialog::SendCoinsDialog(QWidget* parent) : QDialog(parent), ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); ui->lineEditCoinControlChange->setAttribute(Qt::WA_MacShowFocusRect, 0); - ui->splitBlockLineEdit->setAttribute(Qt::WA_MacShowFocusRect, 0); + ui->splitBlockLineEdit->setAttribute(Qt::WA_MacShowFocusRect, 0); #endif GUIUtil::setupAddressWidget(ui->lineEditCoinControlChange, this); @@ -164,7 +164,7 @@ void SendCoinsDialog::setModel(WalletModel* model) setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getZerocoinBalance (), model->getUnconfirmedZerocoinBalance (), model->getImmatureZerocoinBalance (), model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance()); - connect(model, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this, + connect(model, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this, SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); updateDisplayUnit(); @@ -279,7 +279,7 @@ void SendCoinsDialog::on_sendButton_clicked() // Format confirmation message QStringList formatted; - foreach (const SendCoinsRecipient& rcp, recipients) { + for (const SendCoinsRecipient& rcp : recipients) { // generate bold amount string QString amount = "" + BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount); amount.append(" ").append(strFunds); @@ -323,7 +323,7 @@ void SendCoinsDialog::on_sendButton_clicked() // will call relock WalletModel::EncryptionStatus encStatus = model->getEncryptionStatus(); if (encStatus == model->Locked || encStatus == model->UnlockedForAnonymizationOnly) { - WalletModel::UnlockContext ctx(model->requestUnlock(true)); + WalletModel::UnlockContext ctx(model->requestUnlock(AskPassphraseDialog::Context::Send_OHMC, true)); if (!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; @@ -376,7 +376,7 @@ void SendCoinsDialog::send(QList recipients, QString strFee, questionString.append("
"); CAmount totalAmount = currentTransaction.getTotalTransactionAmount() + txFee; QStringList alternativeUnits; - foreach (BitcoinUnits::Unit u, BitcoinUnits::availableUnits()) { + for (BitcoinUnits::Unit u : BitcoinUnits::availableUnits()) { if (u != model->getOptionsModel()->getDisplayUnit()) alternativeUnits.append(BitcoinUnits::formatHtmlWithUnit(u, totalAmount)); } @@ -545,7 +545,7 @@ bool SendCoinsDialog::handlePaymentRequest(const SendCoinsRecipient& rv) return true; } -void SendCoinsDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, +void SendCoinsDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& zerocoinBalance, const CAmount& unconfirmedZerocoinBalance, const CAmount& immatureZerocoinBalance, const CAmount& watchBalance, const CAmount& watchUnconfirmedBalance, const CAmount& watchImmatureBalance) { @@ -570,7 +570,7 @@ void SendCoinsDialog::updateDisplayUnit() TRY_LOCK(cs_main, lockMain); if (!lockMain) return; - setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), + setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getZerocoinBalance (), model->getUnconfirmedZerocoinBalance (), model->getImmatureZerocoinBalance (), model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance()); coinControlUpdateLabels(); @@ -590,7 +590,7 @@ void SendCoinsDialog::updateSwiftTX() void SendCoinsDialog::processSendCoinsReturn(const WalletModel::SendCoinsReturn& sendCoinsReturn, const QString& msgArg, bool fPrepare) { bool fAskForUnlock = false; - + QPair msgParams; // Default to a warning message, override if error message is needed msgParams.second = CClientUIInterface::MSG_WARNING; @@ -641,7 +641,7 @@ void SendCoinsDialog::processSendCoinsReturn(const WalletModel::SendCoinsReturn& // Unlock wallet if it wasn't fully unlocked already if(fAskForUnlock) { - model->requestUnlock(false); + model->requestUnlock(AskPassphraseDialog::Context::Unlock_Full, false); if(model->getEncryptionStatus () != WalletModel::Unlocked) { msgParams.first = tr("Error: The wallet was unlocked only to anonymize coins. Unlock canceled."); } @@ -893,9 +893,9 @@ void SendCoinsDialog::coinControlChangeEdited(const QString& text) ui->labelCoinControlChangeLabel->setText(tr("Warning: Invalid Ohmcoin address")); return; } - + CPubKey pubkey; - + if (!model->getPubKey(*keyid, pubkey)) // Unknown change address { ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address")); diff --git a/src/qt/sendcoinsentry.cpp b/src/qt/sendcoinsentry.cpp index 88e1ccf..4fc2354 100755 --- a/src/qt/sendcoinsentry.cpp +++ b/src/qt/sendcoinsentry.cpp @@ -30,8 +30,6 @@ SendCoinsEntry::SendCoinsEntry(QWidget* parent) : QStackedWidget(parent), ui->payTo->setAttribute(Qt::WA_MacShowFocusRect, 0); ui->addAsLabel->setAttribute(Qt::WA_MacShowFocusRect, 0); ui->payAmount->setAttribute(Qt::WA_MacShowFocusRect, 0); -#endif -#if QT_VERSION >= 0x040700 ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); #endif diff --git a/src/qt/signverifymessagedialog.cpp b/src/qt/signverifymessagedialog.cpp index 2b53ff1..f76f139 100755 --- a/src/qt/signverifymessagedialog.cpp +++ b/src/qt/signverifymessagedialog.cpp @@ -9,12 +9,13 @@ #include "ui_signverifymessagedialog.h" #include "addressbookpage.h" +#include "askpassphrasedialog.h" #include "guiutil.h" #include "walletmodel.h" #include "base58.h" #include "init.h" -#include "wallet.h" +#include "wallet/wallet.h" #include #include @@ -27,9 +28,7 @@ SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget* parent) : QDialog(pare { ui->setupUi(this); -#if QT_VERSION >= 0x040700 ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature")); -#endif GUIUtil::setupAddressWidget(ui->addressIn_SM, this); GUIUtil::setupAddressWidget(ui->addressIn_VM, this); @@ -51,7 +50,7 @@ SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget* parent) : QDialog(pare ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont()); ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont()); - + } SignVerifyMessageDialog::~SignVerifyMessageDialog() @@ -131,7 +130,7 @@ void SignVerifyMessageDialog::on_signMessageButton_SM_clicked() return; } - WalletModel::UnlockContext ctx(model->requestUnlock(true)); + WalletModel::UnlockContext ctx(model->requestUnlock(AskPassphraseDialog::Context::Sign_Message, true)); if (!ctx.isValid()) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled.")); diff --git a/src/qt/splashscreen.cpp b/src/qt/splashscreen.cpp index 8607e70..234a1df 100755 --- a/src/qt/splashscreen.cpp +++ b/src/qt/splashscreen.cpp @@ -14,7 +14,7 @@ #include "version.h" #ifdef ENABLE_WALLET -#include "wallet.h" +#include "wallet/wallet.h" #endif #include @@ -44,9 +44,9 @@ SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle* networkStyle) QString font = QApplication::font().toString(); // load the bitmap for writing some text over it - + pixmap = networkStyle->getSplashImage(); - // pixmap = pixmap.scaled(QSize(400,400), Qt::KeepAspectRatio,Qt::SmoothTransformation); + // pixmap = pixmap.scaled(QSize(400,400), Qt::KeepAspectRatio,Qt::SmoothTransformation); QPainter pixPaint(&pixmap); pixPaint.setRenderHint(QPainter::Antialiasing); diff --git a/src/qt/trafficgraphwidget.cpp b/src/qt/trafficgraphwidget.cpp index 135eeba..139417c 100755 --- a/src/qt/trafficgraphwidget.cpp +++ b/src/qt/trafficgraphwidget.cpp @@ -139,10 +139,10 @@ void TrafficGraphWidget::updateRates() } float tmax = 0.0f; - foreach (float f, vSamplesIn) { + for (float f : vSamplesIn) { if (f > tmax) tmax = f; } - foreach (float f, vSamplesOut) { + for (float f : vSamplesOut) { if (f > tmax) tmax = f; } fMax = tmax; diff --git a/src/qt/transactiondesc.cpp b/src/qt/transactiondesc.cpp index 72912df..1863f37 100755 --- a/src/qt/transactiondesc.cpp +++ b/src/qt/transactiondesc.cpp @@ -18,7 +18,7 @@ #include "timedata.h" #include "ui_interface.h" #include "util.h" -#include "wallet.h" +#include "wallet/wallet.h" #include #include @@ -159,7 +159,7 @@ QString TransactionDesc::toHTML(CWallet* wallet, CWalletTx& wtx, TransactionReco // Coinbase // CAmount nUnmatured = 0; - BOOST_FOREACH (const CTxOut& txout, wtx.vout) + for (const CTxOut& txout : wtx.vout) nUnmatured += wallet->GetCredit(txout, ISMINE_ALL); strHTML += "" + tr("Credit") + ": "; if (wtx.IsInMainChain()) @@ -174,13 +174,13 @@ QString TransactionDesc::toHTML(CWallet* wallet, CWalletTx& wtx, TransactionReco strHTML += "" + tr("Credit") + ": " + BitcoinUnits::formatHtmlWithUnit(unit, nNet) + "
"; } else { isminetype fAllFromMe = ISMINE_SPENDABLE; - BOOST_FOREACH (const CTxIn& txin, wtx.vin) { + for (const CTxIn& txin : wtx.vin) { isminetype mine = wallet->IsMine(txin); if (fAllFromMe > mine) fAllFromMe = mine; } isminetype fAllToMe = ISMINE_SPENDABLE; - BOOST_FOREACH (const CTxOut& txout, wtx.vout) { + for (const CTxOut& txout : wtx.vout) { isminetype mine = wallet->IsMine(txout); if (fAllToMe > mine) fAllToMe = mine; } @@ -192,7 +192,7 @@ QString TransactionDesc::toHTML(CWallet* wallet, CWalletTx& wtx, TransactionReco // // Debit // - BOOST_FOREACH (const CTxOut& txout, wtx.vout) { + for (const CTxOut& txout : wtx.vout) { // Ignore change isminetype toSelf = wallet->IsMine(txout); if ((toSelf == ISMINE_SPENDABLE) && (fAllFromMe == ISMINE_SPENDABLE)) @@ -234,10 +234,10 @@ QString TransactionDesc::toHTML(CWallet* wallet, CWalletTx& wtx, TransactionReco // // Mixed debit transaction // - BOOST_FOREACH (const CTxIn& txin, wtx.vin) + for (const CTxIn& txin : wtx.vin) if (wallet->IsMine(txin)) strHTML += "" + tr("Debit") + ": " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "
"; - BOOST_FOREACH (const CTxOut& txout, wtx.vout) + for (const CTxOut& txout : wtx.vout) if (wallet->IsMine(txout)) strHTML += "" + tr("Credit") + ": " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "
"; } @@ -257,14 +257,14 @@ QString TransactionDesc::toHTML(CWallet* wallet, CWalletTx& wtx, TransactionReco strHTML += "" + tr("Output index") + ": " + QString::number(rec->getOutputIndex()) + "
"; // Message from normal ohmcoin:URI (ohmcoin:XyZ...?message=example) - foreach (const PAIRTYPE(string, string) & r, wtx.vOrderForm) + for (const std::pair & r : wtx.vOrderForm) if (r.first == "Message") strHTML += "
" + tr("Message") + ":
" + GUIUtil::HtmlEscape(r.second, true) + "
"; // // PaymentRequest info: // - foreach (const PAIRTYPE(string, string) & r, wtx.vOrderForm) { + for (const std::pair & r : wtx.vOrderForm) { if (r.first == "PaymentRequest") { PaymentRequestPlus req; req.parse(QByteArray::fromRawData(r.second.data(), r.second.size())); @@ -284,10 +284,10 @@ QString TransactionDesc::toHTML(CWallet* wallet, CWalletTx& wtx, TransactionReco // if (fDebug) { strHTML += "

" + tr("Debug information") + "

"; - BOOST_FOREACH (const CTxIn& txin, wtx.vin) + for (const CTxIn& txin : wtx.vin) if (wallet->IsMine(txin)) strHTML += "" + tr("Debit") + ": " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "
"; - BOOST_FOREACH (const CTxOut& txout, wtx.vout) + for (const CTxOut& txout : wtx.vout) if (wallet->IsMine(txout)) strHTML += "" + tr("Credit") + ": " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "
"; @@ -297,7 +297,7 @@ QString TransactionDesc::toHTML(CWallet* wallet, CWalletTx& wtx, TransactionReco strHTML += "
" + tr("Inputs") + ":"; strHTML += "
    "; - BOOST_FOREACH (const CTxIn& txin, wtx.vin) { + for (const CTxIn& txin : wtx.vin) { COutPoint prevout = txin.prevout; CCoins prev; diff --git a/src/qt/transactionrecord.cpp b/src/qt/transactionrecord.cpp index 5df675d..48ca219 100755 --- a/src/qt/transactionrecord.cpp +++ b/src/qt/transactionrecord.cpp @@ -10,7 +10,7 @@ #include "obfuscation.h" #include "swifttx.h" #include "timedata.h" -#include "wallet.h" +#include "wallet/wallet.h" #include @@ -141,7 +141,7 @@ QList TransactionRecord::decomposeTransaction(const CWallet* // // Credit // - BOOST_FOREACH (const CTxOut& txout, wtx.vout) { + for (const CTxOut& txout : wtx.vout) { isminetype mine = wallet->IsMine(txout); if (mine) { TransactionRecord sub(hash, nTime); @@ -171,7 +171,7 @@ QList TransactionRecord::decomposeTransaction(const CWallet* int nFromMe = 0; bool involvesWatchAddress = false; isminetype fAllFromMe = ISMINE_SPENDABLE; - BOOST_FOREACH (const CTxIn& txin, wtx.vin) { + for (const CTxIn& txin : wtx.vin) { if (wallet->IsMine(txin)) { fAllFromMeDenom = fAllFromMeDenom && wallet->IsDenominated(txin); nFromMe++; @@ -184,7 +184,7 @@ QList TransactionRecord::decomposeTransaction(const CWallet* isminetype fAllToMe = ISMINE_SPENDABLE; bool fAllToMeDenom = true; int nToMe = 0; - BOOST_FOREACH (const CTxOut& txout, wtx.vout) { + for (const CTxOut& txout : wtx.vout) { if (wallet->IsMine(txout)) { fAllToMeDenom = fAllToMeDenom && wallet->IsDenominatedAmount(txout.nValue); nToMe++; diff --git a/src/qt/transactiontablemodel.cpp b/src/qt/transactiontablemodel.cpp index 7ba95c7..46d53b8 100755 --- a/src/qt/transactiontablemodel.cpp +++ b/src/qt/transactiontablemodel.cpp @@ -18,7 +18,7 @@ #include "sync.h" #include "uint256.h" #include "util.h" -#include "wallet.h" +#include "wallet/wallet.h" #include #include @@ -227,7 +227,7 @@ class TransactionTablePriv { parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex + toInsert.size() - 1); int insert_idx = lowerIndex; - foreach (const TransactionRecord& rec, toInsert) { + for (const TransactionRecord& rec : toInsert) { cachedWallet.insert(insert_idx, rec); insert_idx += 1; } @@ -743,7 +743,7 @@ QModelIndex TransactionTableModel::index(int row, int column, const QModelIndex& Q_UNUSED(parent); TransactionRecord* data = priv->index(row); if (data) { - return createIndex(row, column, priv->index(row)); + return createIndex(row, column, data); } return QModelIndex(); } diff --git a/src/qt/transactionview.cpp b/src/qt/transactionview.cpp index 672ab47..285e8cd 100755 --- a/src/qt/transactionview.cpp +++ b/src/qt/transactionview.cpp @@ -88,7 +88,7 @@ TransactionView::TransactionView(QWidget* parent) : QWidget(parent), model(0), t typeWidget->addItem(tr("Sent to"), TransactionFilterProxy::TYPE(TransactionRecord::SendToAddress) | TransactionFilterProxy::TYPE(TransactionRecord::SendToOther)); /* Obsolete Obfuscation entries. Remove once the corresponding TYPES are removed: - * + * typeWidget->addItem(tr("Obfuscated"), TransactionFilterProxy::TYPE(TransactionRecord::Obfuscated)); typeWidget->addItem(tr("Obfuscation Make Collateral Inputs"), TransactionFilterProxy::TYPE(TransactionRecord::ObfuscationMakeCollaterals)); typeWidget->addItem(tr("Obfuscation Create Denominations"), TransactionFilterProxy::TYPE(TransactionRecord::ObfuscationCreateDenominations)); @@ -112,16 +112,12 @@ TransactionView::TransactionView(QWidget* parent) : QWidget(parent), model(0), t addressWidget = new QLineEdit(this); addressWidget->setAttribute(Qt::WA_MacShowFocusRect, 0); -#if QT_VERSION >= 0x040700 addressWidget->setPlaceholderText(tr("Enter address or label to search")); -#endif hlayout->addWidget(addressWidget); amountWidget = new QLineEdit(this); amountWidget->setAttribute(Qt::WA_MacShowFocusRect, 0); -#if QT_VERSION >= 0x040700 amountWidget->setPlaceholderText(tr("Min amount")); -#endif #ifdef Q_OS_MAC amountWidget->setFixedWidth(97); #else @@ -387,7 +383,7 @@ void TransactionView::exportClicked() if (fExport) { emit message(tr("Exporting Successful"), tr("The transaction history was successfully saved to %1.").arg(filename), CClientUIInterface::MSG_INFORMATION); - } + } else { emit message(tr("Exporting Failed"), tr("There was an error trying to save the transaction history to %1.").arg(filename), CClientUIInterface::MSG_ERROR); @@ -481,7 +477,7 @@ void TransactionView::computeSum() return; QModelIndexList selection = transactionView->selectionModel()->selectedRows(); - foreach (QModelIndex index, selection) { + for (QModelIndex index : selection) { amount += index.data(TransactionTableModel::AmountRole).toLongLong(); } QString strAmount(BitcoinUnits::formatWithUnit(nDisplayUnit, amount, true, BitcoinUnits::separatorAlways)); diff --git a/src/qt/utilitydialog.cpp b/src/qt/utilitydialog.cpp index 4ea7e60..0b8173d 100755 --- a/src/qt/utilitydialog.cpp +++ b/src/qt/utilitydialog.cpp @@ -95,7 +95,7 @@ HelpMessageDialog::HelpMessageDialog(QWidget* parent, bool about) : QDialog(pare QTextCharFormat bold; bold.setFontWeight(QFont::Bold); - Q_FOREACH (const QString &line, coreOptions.split("\n")) { + for (const QString &line : coreOptions.split("\n")) { if (line.startsWith(" -")) { cursor.currentTable()->appendRows(1); diff --git a/src/qt/walletframe.cpp b/src/qt/walletframe.cpp index 1285a31..202aab8 100755 --- a/src/qt/walletframe.cpp +++ b/src/qt/walletframe.cpp @@ -218,11 +218,21 @@ void WalletFrame::changePassphrase() walletView->changePassphrase(); } -void WalletFrame::unlockWallet() +void WalletFrame::unlockWallet(bool setContext) +{ + if (setContext) { + unlockWallet(AskPassphraseDialog::Context::Unlock_Full); + } + else { + unlockWallet(AskPassphraseDialog::Context::Unlock_Menu); + } +} + +void WalletFrame::unlockWallet(AskPassphraseDialog::Context context) { WalletView* walletView = currentWalletView(); if (walletView) - walletView->unlockWallet(); + walletView->unlockWallet(context); } void WalletFrame::lockWallet() diff --git a/src/qt/walletframe.h b/src/qt/walletframe.h index c1a2b1f..71b8838 100755 --- a/src/qt/walletframe.h +++ b/src/qt/walletframe.h @@ -5,6 +5,8 @@ #ifndef BITCOIN_QT_WALLETFRAME_H #define BITCOIN_QT_WALLETFRAME_H +#include "askpassphrasedialog.h" + #include #include @@ -88,7 +90,8 @@ public slots: /** Change encrypted wallet passphrase */ void changePassphrase(); /** Ask for passphrase to unlock wallet temporarily */ - void unlockWallet(); + void unlockWallet(AskPassphraseDialog::Context context); + void unlockWallet(bool setContext); /** Lock wallet */ void lockWallet(); /** Toggle Wallet Lock State */ diff --git a/src/qt/walletmodel.cpp b/src/qt/walletmodel.cpp index 7cc4910..97f0bab 100755 --- a/src/qt/walletmodel.cpp +++ b/src/qt/walletmodel.cpp @@ -18,8 +18,8 @@ #include "spork.h" #include "sync.h" #include "ui_interface.h" -#include "wallet.h" -#include "walletdb.h" // for BackupWallet +#include "wallet/wallet.h" +#include "wallet/walletdb.h" // for BackupWallet #include #include @@ -63,7 +63,7 @@ CAmount WalletModel::getBalance(const CCoinControl* coinControl) const CAmount nBalance = 0; std::vector vCoins; wallet->AvailableCoins(vCoins, true, coinControl); - BOOST_FOREACH (const COutput& out, vCoins) + for (const COutput& out : vCoins) if (out.fSpendable) nBalance += out.tx->vout[out.i].nValue; @@ -273,7 +273,7 @@ WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransact int nAddresses = 0; // Pre-check input data for validity - foreach (const SendCoinsRecipient& rcp, recipients) { + for (const SendCoinsRecipient& rcp : recipients) { if (rcp.paymentRequest.IsInitialized()) { // PaymentRequest... CAmount subtotal = 0; const payments::PaymentDetails& details = rcp.paymentRequest.getDetails(); @@ -372,7 +372,7 @@ WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction& tran QList recipients = transaction.getRecipients(); // Store PaymentRequests in wtx.vOrderForm in wallet. - foreach (const SendCoinsRecipient& rcp, recipients) { + for (const SendCoinsRecipient& rcp : recipients) { if (rcp.paymentRequest.IsInitialized()) { std::string key("PaymentRequest"); std::string value; @@ -399,7 +399,7 @@ WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction& tran // Add addresses / update labels that we've sent to to the address book, // and emit coinsSent signal for each recipient - foreach (const SendCoinsRecipient& rcp, transaction.getRecipients()) { + for (const SendCoinsRecipient& rcp : transaction.getRecipients()) { // Don't touch the address book when we have a payment request if (!rcp.paymentRequest.IsInitialized()) { @@ -622,7 +622,7 @@ void WalletModel::unsubscribeFromCoreSignals() } // WalletModel::UnlockContext implementation -WalletModel::UnlockContext WalletModel::requestUnlock(bool relock) +WalletModel::UnlockContext WalletModel::requestUnlock(AskPassphraseDialog::Context context, bool relock) { bool was_locked = getEncryptionStatus() == Locked; @@ -634,7 +634,7 @@ WalletModel::UnlockContext WalletModel::requestUnlock(bool relock) if (was_locked) { // Request UI to unlock wallet - emit requireUnlock(); + emit requireUnlock(context); } // If wallet is still locked, unlock was failed or cancelled, mark context as invalid bool valid = getEncryptionStatus() != Locked; @@ -672,7 +672,7 @@ bool WalletModel::getPubKey(const CKeyID& address, CPubKey& vchPubKeyOut) const void WalletModel::getOutputs(const std::vector& vOutpoints, std::vector& vOutputs) { LOCK2(cs_main, wallet->cs_wallet); - BOOST_FOREACH (const COutPoint& outpoint, vOutpoints) { + for (const COutPoint& outpoint : vOutpoints) { if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; @@ -698,7 +698,7 @@ void WalletModel::listCoins(std::map >& mapCoins) wallet->ListLockedCoins(vLockedCoins); // add locked coins - BOOST_FOREACH (const COutPoint& outpoint, vLockedCoins) { + for (const COutPoint& outpoint : vLockedCoins) { if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; @@ -707,7 +707,7 @@ void WalletModel::listCoins(std::map >& mapCoins) vCoins.push_back(out); } - BOOST_FOREACH (const COutput& out, vCoins) { + for (const COutput& out : vCoins) { COutput cout = out; while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0])) { @@ -756,8 +756,8 @@ void WalletModel::listZerocoinMints(std::set& setMints, bool fUnusedO void WalletModel::loadReceiveRequests(std::vector& vReceiveRequests) { LOCK(wallet->cs_wallet); - BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, wallet->mapAddressBook) - BOOST_FOREACH (const PAIRTYPE(std::string, std::string) & item2, item.second.destdata) + for (const std::pair & item : wallet->mapAddressBook) + for (const std::pair & item2 : item.second.destdata) if (item2.first.size() > 2 && item2.first.substr(0, 2) == "rr") // receive request vReceiveRequests.push_back(item2.second); } @@ -785,4 +785,4 @@ bool WalletModel::isMine(CTxDestination address) OutputType WalletModel::getDefaultAddressType() const { return g_address_type; -} \ No newline at end of file +} diff --git a/src/qt/walletmodel.h b/src/qt/walletmodel.h index 3164685..b527e83 100755 --- a/src/qt/walletmodel.h +++ b/src/qt/walletmodel.h @@ -5,12 +5,13 @@ #ifndef BITCOIN_QT_WALLETMODEL_H #define BITCOIN_QT_WALLETMODEL_H +#include "askpassphrasedialog.h" #include "paymentrequestplus.h" #include "walletmodeltransaction.h" #include "allocators.h" /* for SecureString */ #include "swifttx.h" -#include "wallet.h" +#include "wallet/wallet.h" #include #include @@ -197,7 +198,7 @@ class WalletModel : public QObject void CopyFrom(const UnlockContext& rhs); }; - UnlockContext requestUnlock(bool relock = false); + UnlockContext requestUnlock(AskPassphraseDialog::Context context, bool relock = false); bool getPubKey(const CKeyID& address, CPubKey& vchPubKeyOut) const; bool isMine(CTxDestination address); @@ -265,7 +266,7 @@ class WalletModel : public QObject // Signal emitted when wallet needs to be unlocked // It is valid behaviour for listeners to keep the wallet locked after this signal; // this means that the unlocking failed or was cancelled. - void requireUnlock(); + void requireUnlock(AskPassphraseDialog::Context context); // Fired when a message should be reported to the user void message(const QString& title, const QString& message, unsigned int style); @@ -300,4 +301,4 @@ public slots: void updateAddressBookLabels(const CTxDestination& address, const string& strName, const string& strPurpose); }; -#endif // BITCOIN_QT_WALLETMODEL_H \ No newline at end of file +#endif // BITCOIN_QT_WALLETMODEL_H diff --git a/src/qt/walletmodeltransaction.cpp b/src/qt/walletmodeltransaction.cpp index df993a2..4a1896e 100755 --- a/src/qt/walletmodeltransaction.cpp +++ b/src/qt/walletmodeltransaction.cpp @@ -4,7 +4,7 @@ #include "walletmodeltransaction.h" -#include "wallet.h" +#include "wallet/wallet.h" WalletModelTransaction::WalletModelTransaction(const QList& recipients) : recipients(recipients), walletTransaction(0), @@ -48,7 +48,7 @@ void WalletModelTransaction::setTransactionFee(const CAmount& newFee) CAmount WalletModelTransaction::getTotalTransactionAmount() { CAmount totalTransactionAmount = 0; - foreach (const SendCoinsRecipient& rcp, recipients) { + for (const SendCoinsRecipient& rcp : recipients) { totalTransactionAmount += rcp.amount; } return totalTransactionAmount; diff --git a/src/qt/walletview.cpp b/src/qt/walletview.cpp index d496e7d..7903ee4 100755 --- a/src/qt/walletview.cpp +++ b/src/qt/walletview.cpp @@ -5,7 +5,6 @@ #include "walletview.h" #include "addressbookpage.h" -#include "askpassphrasedialog.h" #include "bip38tooldialog.h" #include "bitcoingui.h" #include "blockexplorer.h" @@ -222,7 +221,7 @@ void WalletView::setWalletModel(WalletModel* walletModel) this, SLOT(processNewTransaction(QModelIndex, int, int))); // Ask for passphrase if needed - connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet())); + connect(walletModel, SIGNAL(requireUnlock(AskPassphraseDialog::Context)), this, SLOT(unlockWallet(AskPassphraseDialog::Context))); // Show progress dialog connect(walletModel, SIGNAL(showProgress(QString, int)), this, SLOT(showProgress(QString, int))); @@ -365,7 +364,8 @@ void WalletView::encryptWallet(bool status) { if (!walletModel) return; - AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt : AskPassphraseDialog::Decrypt, this, walletModel); + AskPassphraseDialog dlg(status ? AskPassphraseDialog::Mode::Encrypt : AskPassphraseDialog::Mode::Decrypt, this, + walletModel, AskPassphraseDialog::Context::Encrypt); dlg.exec(); updateEncryptionStatus(); @@ -391,18 +391,18 @@ void WalletView::backupWallet() void WalletView::changePassphrase() { - AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this, walletModel); + AskPassphraseDialog dlg(AskPassphraseDialog::Mode::ChangePass, this, walletModel, AskPassphraseDialog::Context::ChangePass); dlg.exec(); } -void WalletView::unlockWallet() +void WalletView::unlockWallet(AskPassphraseDialog::Context context) { if (!walletModel) return; // Unlock wallet when requested by wallet model if (walletModel->getEncryptionStatus() == WalletModel::Locked || walletModel->getEncryptionStatus() == WalletModel::UnlockedForAnonymizationOnly) { - AskPassphraseDialog dlg(AskPassphraseDialog::UnlockAnonymize, this, walletModel); + AskPassphraseDialog dlg(AskPassphraseDialog::Mode::UnlockAnonymize, this, walletModel, context); dlg.exec(); } } @@ -424,7 +424,7 @@ void WalletView::toggleLockWallet() // Unlock the wallet when requested if (encStatus == walletModel->Locked) { - AskPassphraseDialog dlg(AskPassphraseDialog::UnlockAnonymize, this, walletModel); + AskPassphraseDialog dlg(AskPassphraseDialog::Mode::UnlockAnonymize, this, walletModel, AskPassphraseDialog::Context::ToggleLock); dlg.exec(); } @@ -475,4 +475,4 @@ void WalletView::showProgress(const QString& title, int nProgress) void WalletView::trxAmount(QString amount) { transactionSum->setText(amount); -} \ No newline at end of file +} diff --git a/src/qt/walletview.h b/src/qt/walletview.h index bb31465..dbcc82a 100755 --- a/src/qt/walletview.h +++ b/src/qt/walletview.h @@ -6,6 +6,7 @@ #define BITCOIN_QT_WALLETVIEW_H #include "amount.h" +#include "askpassphrasedialog.h" #include "karmanodelist.h" #include "proposallist.h" @@ -117,7 +118,7 @@ public slots: /** Change encrypted wallet passphrase */ void changePassphrase(); /** Ask for passphrase to unlock wallet temporarily */ - void unlockWallet(); + void unlockWallet(AskPassphraseDialog::Context context); /** Lock wallet */ void lockWallet(); /** Toggle wallet lock state */ @@ -148,4 +149,4 @@ public slots: void incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address); }; -#endif // BITCOIN_QT_WALLETVIEW_H \ No newline at end of file +#endif // BITCOIN_QT_WALLETVIEW_H diff --git a/src/qt/winshutdownmonitor.cpp b/src/qt/winshutdownmonitor.cpp index 3190d92..e960037 100755 --- a/src/qt/winshutdownmonitor.cpp +++ b/src/qt/winshutdownmonitor.cpp @@ -4,7 +4,7 @@ #include "winshutdownmonitor.h" -#if defined(Q_OS_WIN) && QT_VERSION >= 0x050000 +#if defined(Q_OS_WIN) #include "init.h" #include "util.h" diff --git a/src/qt/winshutdownmonitor.h b/src/qt/winshutdownmonitor.h index f24f47e..d0afb2a 100755 --- a/src/qt/winshutdownmonitor.h +++ b/src/qt/winshutdownmonitor.h @@ -8,8 +8,6 @@ #ifdef WIN32 #include #include - -#if QT_VERSION >= 0x050000 #include // for HWND #include @@ -24,6 +22,5 @@ class WinShutdownMonitor : public QAbstractNativeEventFilter static void registerShutdownBlockReason(const QString& strReason, const HWND& mainWinId); }; #endif -#endif #endif // BITCOIN_QT_WINSHUTDOWNMONITOR_H diff --git a/src/rest.cpp b/src/rest.cpp index f7fbc63..db4ece1 100755 --- a/src/rest.cpp +++ b/src/rest.cpp @@ -8,7 +8,7 @@ #include "primitives/transaction.h" #include "main.h" #include "httpserver.h" -#include "rpcserver.h" +#include "rpc/server.h" #include "streams.h" #include "sync.h" #include "txmempool.h" @@ -152,13 +152,12 @@ static bool rest_headers(HTTPRequest* req, } } - CDataStream ssHeader(SER_NETWORK, PROTOCOL_VERSION); - BOOST_FOREACH(const CBlockIndex *pindex, headers) { - ssHeader << pindex->GetBlockHeader(); - } - switch (rf) { case RF_BINARY: { + CDataStream ssHeader(SER_NETWORK, PROTOCOL_VERSION); + for (const CBlockIndex *pindex : headers) { + ssHeader << pindex->GetBlockHeader(); + } string binaryHeader = ssHeader.str(); req->WriteHeader("Content-Type", "application/octet-stream"); req->WriteReply(HTTP_OK, binaryHeader); @@ -166,6 +165,10 @@ static bool rest_headers(HTTPRequest* req, } case RF_HEX: { + CDataStream ssHeader(SER_NETWORK, PROTOCOL_VERSION); + for (const CBlockIndex *pindex : headers) { + ssHeader << pindex->GetBlockHeader(); + } string strHex = HexStr(ssHeader.begin(), ssHeader.end()) + "\n"; req->WriteHeader("Content-Type", "text/plain"); req->WriteReply(HTTP_OK, strHex); @@ -173,7 +176,7 @@ static bool rest_headers(HTTPRequest* req, } case RF_JSON: { UniValue jsonHeaders(UniValue::VARR); - BOOST_FOREACH(const CBlockIndex *pindex, headers) { + for(const CBlockIndex *pindex : headers) { jsonHeaders.push_back(blockheaderToJSON(pindex)); } string strJSON = jsonHeaders.write() + "\n"; @@ -219,11 +222,10 @@ static bool rest_block(HTTPRequest* req, return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found"); } - CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags()); - ssBlock << block; - switch (rf) { case RF_BINARY: { + CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags()); + ssBlock << block; string binaryBlock = ssBlock.str(); req->WriteHeader("Content-Type", "application/octet-stream"); req->WriteReply(HTTP_OK, binaryBlock); @@ -231,6 +233,8 @@ static bool rest_block(HTTPRequest* req, } case RF_HEX: { + CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags()); + ssBlock << block; string strHex = HexStr(ssBlock.begin(), ssBlock.end()) + "\n"; req->WriteHeader("Content-Type", "text/plain"); req->WriteReply(HTTP_OK, strHex); @@ -356,11 +360,10 @@ static bool rest_tx(HTTPRequest* req, const std::string& strURIPart) if (!GetTransaction(hash, tx, hashBlock, true)) return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found"); - CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags()); - ssTx << tx; - switch (rf) { case RF_BINARY: { + CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags()); + ssTx << tx; string binaryTx = ssTx.str(); req->WriteHeader("Content-Type", "application/octet-stream"); req->WriteReply(HTTP_OK, binaryTx); @@ -368,6 +371,8 @@ static bool rest_tx(HTTPRequest* req, const std::string& strURIPart) } case RF_HEX: { + CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags()); + ssTx << tx; string strHex = HexStr(ssTx.begin(), ssTx.end()) + "\n"; req->WriteHeader("Content-Type", "text/plain"); req->WriteReply(HTTP_OK, strHex); @@ -559,7 +564,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart) objGetUTXOResponse.push_back(Pair("bitmap", bitmapStringRepresentation)); UniValue utxos(UniValue::VARR); - BOOST_FOREACH (const CCoin& coin, outs) { + for (const CCoin& coin : outs) { UniValue utxo(UniValue::VOBJ); utxo.push_back(Pair("txvers", (int32_t)coin.nTxVer)); utxo.push_back(Pair("height", (int32_t)coin.nHeight)); diff --git a/src/reverse_iterator.h b/src/reverse_iterator.h new file mode 100644 index 0000000..b4d8502 --- /dev/null +++ b/src/reverse_iterator.h @@ -0,0 +1,39 @@ +// Taken from https://gist.github.com/arvidsson/7231973 + +#ifndef BITCOIN_REVERSE_ITERATOR_HPP +#define BITCOIN_REVERSE_ITERATOR_HPP + +/** + * Template used for reverse iteration in C++11 range-based for loops. + * + * std::vector v = {1, 2, 3, 4, 5}; + * for (auto x : reverse_iterate(v)) + * std::cout << x << " "; + */ + +template +class reverse_range +{ + T &x; + +public: + reverse_range(T &x) : x(x) {} + + auto begin() const -> decltype(this->x.rbegin()) + { + return x.rbegin(); + } + + auto end() const -> decltype(this->x.rend()) + { + return x.rend(); + } +}; + +template +reverse_range reverse_iterate(T &x) +{ + return reverse_range(x); +} + +#endif // BITCOIN_REVERSE_ITERATOR_HPP diff --git a/src/rpcblockchain.cpp b/src/rpc/blockchain.cpp similarity index 96% rename from src/rpcblockchain.cpp rename to src/rpc/blockchain.cpp index 9056ea8..2cc9c3e 100755 --- a/src/rpcblockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -11,12 +11,14 @@ #include "consensus/validation.h" #include "consensus/upgrades.h" #include "main.h" -#include "rpcserver.h" +#include "rpc/server.h" #include "sync.h" #include "txdb.h" #include "util.h" #include "utilmoneystr.h" #include "kernel.h" +#include "accumulatormap.h" +#include "accumulators.h" #include #include @@ -104,7 +106,7 @@ UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool tx result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); result.push_back(Pair("acc_checkpoint", block.nAccumulatorCheckpoint.GetHex())); UniValue txs(UniValue::VARR); - BOOST_FOREACH (const CTransaction& tx, block.vtx) { + for (const CTransaction& tx : block.vtx) { if (txDetails) { UniValue objTx(UniValue::VOBJ); TxToJSON(tx, uint256(0), objTx, true, RPCSerializationFlags()); @@ -198,7 +200,7 @@ UniValue mempoolToJSON(bool fVerbose = false) if (fVerbose) { LOCK(mempool.cs); UniValue o(UniValue::VOBJ); - BOOST_FOREACH (const PAIRTYPE(uint256, CTxMemPoolEntry) & entry, mempool.mapTx) { + for (const std::pair & entry : mempool.mapTx) { const uint256& hash = entry.first; const CTxMemPoolEntry& e = entry.second; UniValue info(UniValue::VOBJ); @@ -210,13 +212,13 @@ UniValue mempoolToJSON(bool fVerbose = false) info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height()))); const CTransaction& tx = e.GetTx(); set setDepends; - BOOST_FOREACH (const CTxIn& txin, tx.vin) { + for (const CTxIn& txin : tx.vin) { if (mempool.exists(txin.prevout.hash)) setDepends.insert(txin.prevout.hash.ToString()); } UniValue depends(UniValue::VARR); - BOOST_FOREACH(const string& dep, setDepends) { + for(const string& dep : setDepends) { depends.push_back(dep); } @@ -229,7 +231,7 @@ UniValue mempoolToJSON(bool fVerbose = false) mempool.queryHashes(vtxid); UniValue a(UniValue::VARR); - BOOST_FOREACH (const uint256& hash, vtxid) + for (const uint256& hash : vtxid) a.push_back(hash.ToString()); return a; @@ -744,9 +746,9 @@ UniValue getchaintips(const UniValue& params, bool fHelp) known blocks, and successively remove blocks that appear as pprev of another block. */ std::set setTips; - BOOST_FOREACH (const PAIRTYPE(const uint256, CBlockIndex*) & item, mapBlockIndex) + for (const std::pair & item : mapBlockIndex) setTips.insert(item.second); - BOOST_FOREACH (const PAIRTYPE(const uint256, CBlockIndex*) & item, mapBlockIndex) { + for (const std::pair & item : mapBlockIndex) { const CBlockIndex* pprev = item.second->pprev; if (pprev) setTips.erase(pprev); @@ -757,7 +759,7 @@ UniValue getchaintips(const UniValue& params, bool fHelp) /* Construct the output array. */ UniValue res(UniValue::VARR); - BOOST_FOREACH (const CBlockIndex* block, setTips) { + for (const CBlockIndex* block : setTips) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("height", block->nHeight)); obj.push_back(Pair("hash", block->phashBlock->GetHex())); @@ -1005,3 +1007,36 @@ UniValue findserial(const UniValue& params, bool fHelp) return ret; } + +UniValue getaccumulatorvalues(const UniValue& params, bool fHelp) +{ + if (fHelp || params.size() != 1) + throw runtime_error( + "getaccumulatorvalues \"height\"\n" + "\nReturns the accumulator values associated with a block height\n" + + "\nArguments:\n" + "1. height (numeric, required) the height of the checkpoint.\n" + + "\nExamples:\n" + + HelpExampleCli("getaccumulatorvalues", "\"height\"") + HelpExampleRpc("getaccumulatorvalues", "\"height\"")); + + int nHeight = params[0].get_int(); + + CBlockIndex* pindex = chainActive[nHeight]; + if (!pindex) + throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid block height"); + + UniValue ret(UniValue::VARR); + for (libzerocoin::CoinDenomination denom : libzerocoin::zerocoinDenomList) { + CBigNum bnValue; + if(!GetAccumulatorValueFromDB(pindex->nAccumulatorCheckpoint, denom, bnValue)) + throw JSONRPCError(RPC_DATABASE_ERROR, "failed to find value in database"); + + UniValue obj(UniValue::VOBJ); + obj.push_back(Pair(std::to_string(denom), bnValue.GetHex())); + ret.push_back(obj); + } + + return ret; +} diff --git a/src/rpckarmanode-budget.cpp b/src/rpc/budget.cpp similarity index 98% rename from src/rpckarmanode-budget.cpp rename to src/rpc/budget.cpp index a8a52bb..274e563 100755 --- a/src/rpckarmanode-budget.cpp +++ b/src/rpc/budget.cpp @@ -9,7 +9,7 @@ #include "karmanode-payments.h" #include "karmanodeconfig.h" #include "karmanodeman.h" -#include "rpcserver.h" +#include "rpc/server.h" #include "utilmoneystr.h" #include @@ -209,7 +209,7 @@ UniValue preparebudget(const UniValue& params, bool fHelp) if (!IsValidDestinationString(params[4].get_str())) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Ohmcoin address"); - + CTxDestination address = DecodeDestination(params[4].get_str()); // Parse Ohmcoin address @@ -454,7 +454,7 @@ UniValue knbudgetvote(const UniValue& params, bool fHelp) } if (strCommand == "many") { - BOOST_FOREACH (CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { + for (CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { std::string errorMessage; std::vector vchMasterNodeSignature; std::string strMasterNodeSignMessage; @@ -525,7 +525,7 @@ UniValue knbudgetvote(const UniValue& params, bool fHelp) std::vector mnEntries; mnEntries = karmanodeConfig.getEntries(); - BOOST_FOREACH(CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { + for(CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { if( strAlias != mne.getAlias()) continue; @@ -708,7 +708,7 @@ UniValue getbudgetprojection(const UniValue& params, bool fHelp) CAmount nTotalAllotted = 0; std::vector winningProps = budget.GetBudget(); - BOOST_FOREACH (CBudgetProposal* pbudgetProposal, winningProps) { + for (CBudgetProposal* pbudgetProposal : winningProps) { nTotalAllotted += pbudgetProposal->GetAllotted(); UniValue bObj(UniValue::VOBJ); @@ -774,7 +774,7 @@ UniValue getbudgetinfo(const UniValue& params, bool fHelp) } std::vector winningProps = budget.GetAllProposals(); - BOOST_FOREACH (CBudgetProposal* pbudgetProposal, winningProps) { + for (CBudgetProposal* pbudgetProposal : winningProps) { if (strShow == "valid" && !pbudgetProposal->fValid) continue; UniValue bObj(UniValue::VOBJ); @@ -878,7 +878,7 @@ UniValue knfinalbudget(const UniValue& params, bool fHelp) UniValue resultsObj(UniValue::VOBJ); - BOOST_FOREACH (CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { + for (CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { std::string errorMessage; std::vector vchMasterNodeSignature; std::string strMasterNodeSignMessage; @@ -976,7 +976,7 @@ UniValue knfinalbudget(const UniValue& params, bool fHelp) UniValue resultObj(UniValue::VOBJ); std::vector winningFbs = budget.GetFinalizedBudgets(); - BOOST_FOREACH(CFinalizedBudget* finalizedBudget, winningFbs) + for(CFinalizedBudget* finalizedBudget : winningFbs) { // Ignore old finalized budgets to avoid displaying misleading error // messages about missing proposals. Include the previous final budget cycle. diff --git a/src/rpcclient.cpp b/src/rpc/client.cpp similarity index 98% rename from src/rpcclient.cpp rename to src/rpc/client.cpp index ce420bb..e81c908 100755 --- a/src/rpcclient.cpp +++ b/src/rpc/client.cpp @@ -5,9 +5,9 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include "rpcclient.h" +#include "rpc/client.h" -#include "rpcprotocol.h" +#include "rpc/protocol.h" #include "ui_interface.h" #include "util.h" @@ -139,6 +139,7 @@ static const CRPCConvertParam vRPCConvertParams[] = {"exportzerocoins", 1}, {"resetmintzerocoin", 0}, {"getspentzerocoinamount", 1}, + {"getaccumulatorvalues", 0}, {"getfeeinfo", 0}, { "addwitnessaddress", 1} }; diff --git a/src/rpcclient.h b/src/rpc/client.h similarity index 100% rename from src/rpcclient.h rename to src/rpc/client.h diff --git a/src/rpckarmanode.cpp b/src/rpc/karmanode.cpp similarity index 98% rename from src/rpckarmanode.cpp rename to src/rpc/karmanode.cpp index e9e66c1..c9bb4af 100755 --- a/src/rpckarmanode.cpp +++ b/src/rpc/karmanode.cpp @@ -11,7 +11,7 @@ #include "karmanode-payments.h" #include "karmanodeconfig.h" #include "karmanodeman.h" -#include "rpcserver.h" +#include "rpc/server.h" #include "utilmoneystr.h" #include @@ -228,7 +228,7 @@ UniValue listkarmanodes(const UniValue& params, bool fHelp) nHeight = pindex->nHeight; } std::vector > vKarmanodeRanks = mnodeman.GetKarmanodeRanks(nHeight); - BOOST_FOREACH (PAIRTYPE(int, CKarmanode) & s, vKarmanodeRanks) { + for (std::pair & s : vKarmanodeRanks) { UniValue obj(UniValue::VOBJ); std::string strVin = s.second.vin.prevout.ToStringShort(); std::string strTxHash = s.second.vin.prevout.hash.ToString(); @@ -464,7 +464,7 @@ UniValue startkarmanode (const UniValue& params, bool fHelp) UniValue resultsObj(UniValue::VARR); - BOOST_FOREACH (CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { + for (CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { std::string errorMessage; int nIndex; if(!mne.castOutputIndex(nIndex)) @@ -515,7 +515,7 @@ UniValue startkarmanode (const UniValue& params, bool fHelp) UniValue statusObj(UniValue::VOBJ); statusObj.push_back(Pair("alias", alias)); - BOOST_FOREACH (CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { + for (CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { if (mne.getAlias() == alias) { found = true; std::string errorMessage; @@ -598,7 +598,7 @@ UniValue getkarmanodeoutputs (const UniValue& params, bool fHelp) vector possibleCoins = activeKarmanode.SelectCoinsKarmanode(); UniValue ret(UniValue::VARR); - BOOST_FOREACH (COutput& out, possibleCoins) { + for (COutput& out : possibleCoins) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("txhash", out.tx->GetHash().ToString())); obj.push_back(Pair("outputidx", out.i)); @@ -643,7 +643,7 @@ UniValue listkarmanodeconf (const UniValue& params, bool fHelp) UniValue ret(UniValue::VARR); - BOOST_FOREACH (CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { + for (CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { int nIndex; if(!mne.castOutputIndex(nIndex)) continue; @@ -778,7 +778,7 @@ UniValue getkarmanodewinners (const UniValue& params, bool fHelp) UniValue winner(UniValue::VARR); boost::char_separator sep(","); boost::tokenizer< boost::char_separator > tokens(strPayment, sep); - BOOST_FOREACH (const string& t, tokens) { + for (const string& t : tokens) { UniValue addr(UniValue::VOBJ); std::size_t pos = t.find(":"); std::string strAddress = t.substr(0,pos); @@ -842,7 +842,7 @@ UniValue getkarmanodescores (const UniValue& params, bool fHelp) for (int nHeight = chainActive.Tip()->nHeight - nLast; nHeight < chainActive.Tip()->nHeight + 20; nHeight++) { uint256 nHigh = 0; CKarmanode* pBestKarmanode = NULL; - BOOST_FOREACH (CKarmanode& mn, vKarmanodes) { + for (CKarmanode& mn : vKarmanodes) { uint256 n = mn.CalculateScore(1, nHeight - 100); if (n > nHigh) { nHigh = n; @@ -927,7 +927,7 @@ UniValue createkarmanodebroadcast(const UniValue& params, bool fHelp) UniValue statusObj(UniValue::VOBJ); statusObj.push_back(Pair("alias", alias)); - BOOST_FOREACH(CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { + for(CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { if(mne.getAlias() == alias) { found = true; std::string errorMessage; @@ -970,7 +970,7 @@ UniValue createkarmanodebroadcast(const UniValue& params, bool fHelp) UniValue resultsObj(UniValue::VARR); - BOOST_FOREACH(CKarmanodeConfig::CKarmanodeEntry mne, karmanodeConfig.getEntries()) { + for(CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) { std::string errorMessage; CTxIn vin = CTxIn(uint256S(mne.getTxHash()), uint32_t(atoi(mne.getOutputIndex().c_str()))); diff --git a/src/rpcmining.cpp b/src/rpc/mining.cpp similarity index 99% rename from src/rpcmining.cpp rename to src/rpc/mining.cpp index 9226a18..4eae15e 100755 --- a/src/rpcmining.cpp +++ b/src/rpc/mining.cpp @@ -15,12 +15,12 @@ #include "miner.h" #include "net.h" #include "pow.h" -#include "rpcserver.h" +#include "rpc/server.h" #include "util.h" #include "validationinterface.h" #ifdef ENABLE_WALLET -#include "db.h" -#include "wallet.h" +#include "wallet/db.h" +#include "wallet/wallet.h" #endif #include @@ -521,7 +521,7 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp) UniValue transactions(UniValue::VARR); map setTxIndex; int i = 0; - BOOST_FOREACH (CTransaction& tx, pblock->vtx) { + for (CTransaction& tx : pblock->vtx) { uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; @@ -535,7 +535,7 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp) entry.push_back(Pair("hash", tx.GetWitnessHash().GetHex())); UniValue deps(UniValue::VARR); - BOOST_FOREACH (const CTxIn& in, tx.vin) { + for (const CTxIn& in : tx.vin) { if (setTxIndex.count(in.prevout.hash)) deps.push_back(setTxIndex[in.prevout.hash]); } diff --git a/src/rpcmisc.cpp b/src/rpc/misc.cpp similarity index 99% rename from src/rpcmisc.cpp rename to src/rpc/misc.cpp index 7dbfb40..2cf7c16 100755 --- a/src/rpcmisc.cpp +++ b/src/rpc/misc.cpp @@ -13,13 +13,13 @@ #include "karmanode-sync.h" #include "net.h" #include "netbase.h" -#include "rpcserver.h" +#include "rpc/server.h" #include "spork.h" #include "timedata.h" #include "util.h" #ifdef ENABLE_WALLET -#include "wallet.h" -#include "walletdb.h" +#include "wallet/wallet.h" +#include "wallet/walletdb.h" #endif #include @@ -127,7 +127,7 @@ UniValue getinfo(const UniValue& params, bool fHelp) } zohmcObj.push_back(Pair("total", ValueFromAmount(chainActive.Tip()->GetZerocoinSupply()))); obj.push_back(Pair("zOHMCsupply", zohmcObj)); - + #ifdef ENABLE_WALLET if (pwalletMain) { obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime())); @@ -576,7 +576,7 @@ UniValue verifymessage(const UniValue& params, bool fHelp) if (!IsValidDestinationString(strAddress)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); - + CTxDestination addr = DecodeDestination(strAddress); CKeyID *keyID = boost::get(&addr); diff --git a/src/rpcnet.cpp b/src/rpc/net.cpp similarity index 97% rename from src/rpcnet.cpp rename to src/rpc/net.cpp index 3b81c54..b20e78c 100755 --- a/src/rpcnet.cpp +++ b/src/rpc/net.cpp @@ -4,7 +4,7 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include "rpcserver.h" +#include "rpc/server.h" #include "clientversion.h" #include "main.h" @@ -17,8 +17,6 @@ #include "util.h" #include "version.h" -#include - #include using namespace std; @@ -53,7 +51,7 @@ UniValue ping(const UniValue& params, bool fHelp) // Request that each node send a ping during next message processing pass LOCK2(cs_main, cs_vNodes); - BOOST_FOREACH (CNode* pNode, vNodes) { + for (CNode* pNode : vNodes) { pNode->fPingQueued = true; } @@ -66,7 +64,7 @@ static void CopyNodeStats(std::vector& vstats) LOCK(cs_vNodes); vstats.reserve(vNodes.size()); - BOOST_FOREACH (CNode* pnode, vNodes) { + for (CNode* pnode : vNodes) { CNodeStats stats; pnode->copyStats(stats); vstats.push_back(stats); @@ -118,7 +116,7 @@ UniValue getpeerinfo(const UniValue& params, bool fHelp) UniValue ret(UniValue::VARR); - BOOST_FOREACH (const CNodeStats& stats, vstats) { + for (const CNodeStats& stats : vstats) { UniValue obj(UniValue::VOBJ); CNodeStateStats statestats; bool fStateStats = GetNodeStateStats(stats.nodeid, statestats); @@ -148,7 +146,7 @@ UniValue getpeerinfo(const UniValue& params, bool fHelp) obj.push_back(Pair("synced_headers", statestats.nSyncHeight)); obj.push_back(Pair("synced_blocks", statestats.nCommonHeight)); UniValue heights(UniValue::VARR); - BOOST_FOREACH (int height, statestats.vHeightInFlight) { + for (int height : statestats.vHeightInFlight) { heights.push_back(height); } obj.push_back(Pair("inflight", heights)); @@ -262,12 +260,12 @@ UniValue getaddednodeinfo(const UniValue& params, bool fHelp) list laddedNodes(0); if (params.size() == 1) { LOCK(cs_vAddedNodes); - BOOST_FOREACH (string& strAddNode, vAddedNodes) + for (string& strAddNode : vAddedNodes) laddedNodes.push_back(strAddNode); } else { string strNode = params[1].get_str(); LOCK(cs_vAddedNodes); - BOOST_FOREACH (string& strAddNode, vAddedNodes) + for (string& strAddNode : vAddedNodes) if (strAddNode == strNode) { laddedNodes.push_back(strAddNode); break; @@ -278,7 +276,7 @@ UniValue getaddednodeinfo(const UniValue& params, bool fHelp) UniValue ret(UniValue::VARR); if (!fDns) { - BOOST_FOREACH (string& strAddNode, laddedNodes) { + for (string& strAddNode : laddedNodes) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("addednode", strAddNode)); ret.push_back(obj); @@ -287,7 +285,7 @@ UniValue getaddednodeinfo(const UniValue& params, bool fHelp) } list > > laddedAddreses(0); - BOOST_FOREACH (string& strAddNode, laddedNodes) { + for (string& strAddNode : laddedNodes) { vector vservNode(0); if (Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) laddedAddreses.push_back(make_pair(strAddNode, vservNode)); @@ -307,11 +305,11 @@ UniValue getaddednodeinfo(const UniValue& params, bool fHelp) UniValue addresses(UniValue::VARR); bool fConnected = false; - BOOST_FOREACH (CService& addrNode, it->second) { + for (CService& addrNode : it->second) { bool fFound = false; UniValue node(UniValue::VOBJ); node.push_back(Pair("address", addrNode.ToString())); - BOOST_FOREACH (CNode* pnode, vNodes) + for (CNode* pnode : vNodes) if (pnode->addr == addrNode) { fFound = true; fConnected = true; @@ -424,7 +422,7 @@ UniValue getnetworkinfo(const UniValue& params, bool fHelp) UniValue localAddresses(UniValue::VARR); { LOCK(cs_mapLocalHost); - BOOST_FOREACH (const PAIRTYPE(CNetAddr, LocalServiceInfo) & item, mapLocalHost) { + for (const std::pair & item : mapLocalHost) { UniValue rec(UniValue::VOBJ); rec.push_back(Pair("address", item.first.ToString())); rec.push_back(Pair("port", item.second.nPort)); diff --git a/src/rpcprotocol.cpp b/src/rpc/protocol.cpp similarity index 99% rename from src/rpcprotocol.cpp rename to src/rpc/protocol.cpp index bcdf1b4..fa721ea 100755 --- a/src/rpcprotocol.cpp +++ b/src/rpc/protocol.cpp @@ -7,7 +7,7 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "httpserver.h" -#include "rpcprotocol.h" +#include "rpc/protocol.h" #include "random.h" #include "tinyformat.h" #include "primitives/transaction.h" @@ -136,4 +136,4 @@ int RPCSerializationFlags() if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) == 0) flag |= SERIALIZE_TRANSACTION_NO_WITNESS; return flag; -} \ No newline at end of file +} diff --git a/src/rpcprotocol.h b/src/rpc/protocol.h similarity index 100% rename from src/rpcprotocol.h rename to src/rpc/protocol.h diff --git a/src/rpcrawtransaction.cpp b/src/rpc/rawtransaction.cpp similarity index 99% rename from src/rpcrawtransaction.cpp rename to src/rpc/rawtransaction.cpp index dbd632b..f18fef8 100755 --- a/src/rpcrawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -14,7 +14,7 @@ #include "main.h" #include "net.h" #include "primitives/transaction.h" -#include "rpcserver.h" +#include "rpc/server.h" #include "script/script.h" #include "script/script_error.h" #include "script/sign.h" @@ -23,7 +23,7 @@ #include "uint256.h" #include "utilmoneystr.h" #ifdef ENABLE_WALLET -#include "wallet.h" +#include "wallet/wallet.h" #endif #include @@ -55,7 +55,7 @@ void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fInclud out.push_back(Pair("type", GetTxnOutputType(type))); UniValue a(UniValue::VARR); - BOOST_FOREACH (const CTxDestination& addr, addresses) + for (const CTxDestination& addr : addresses) a.push_back(EncodeDestination(addr)); out.push_back(Pair("addresses", a)); } @@ -134,19 +134,19 @@ UniValue searchrawtransactions(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 4) throw runtime_error("searchrawtransactions
    [verbose=1] [skip=0] [count=100]\n"); - + if (!fAddrIndex) throw JSONRPCError(RPC_MISC_ERROR, "Address index not enabled"); - + if (!IsValidDestinationString(params[0].get_str())) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address"); CTxDestination dest = DecodeDestination(params[0].get_str()); - + std::set setpos; if (!FindTransactionsByDestination(dest, setpos)) throw JSONRPCError(RPC_DATABASE_ERROR, "Cannot search for address"); - + int nSkip = 0; int nCount = 100; bool fVerbose = true; @@ -156,17 +156,17 @@ UniValue searchrawtransactions(const UniValue& params, bool fHelp) nSkip = params[2].get_int(); if (params.size() > 3) nCount = params[3].get_int(); - + if (nSkip < 0) nSkip += setpos.size(); if (nSkip < 0) nSkip = 0; if (nCount < 0) nCount = 0; - + std::set::const_iterator it = setpos.begin(); while (it != setpos.end() && nSkip--) it++; - + UniValue result(UniValue::VARR); while (it != setpos.end() && nCount--) { CTransaction tx; @@ -269,7 +269,7 @@ UniValue getrawtransaction(const UniValue& params, bool fHelp) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); if (!fVerbose) { - string strHex = EncodeHexTx(tx, PROTOCOL_VERSION | RPCSerializationFlags()); + string strHex = EncodeHexTx(tx, PROTOCOL_VERSION | RPCSerializationFlags()); return strHex; } @@ -332,7 +332,7 @@ UniValue listunspent(const UniValue& params, bool fHelp) const UniValue& input = inputs[inx]; if (!IsValidDestinationString(input.get_str())) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Ohmcoin address: ") + input.get_str()); - + CTxDestination address = DecodeDestination(input.get_str()); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ") + input.get_str()); @@ -352,7 +352,7 @@ UniValue listunspent(const UniValue& params, bool fHelp) assert(pwalletMain != NULL); LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->AvailableCoins(vecOutputs, false, NULL, false, ALL_COINS, false, nWatchonlyConfig); - BOOST_FOREACH (const COutput& out, vecOutputs) { + for (const COutput& out : vecOutputs) { if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth) continue; @@ -454,10 +454,10 @@ UniValue createrawtransaction(const UniValue& params, bool fHelp) set setAddress; vector addrList = sendTo.getKeys(); - BOOST_FOREACH(const string& name_, addrList) { + for(const string& name_ : addrList) { if (!IsValidDestinationString(name_)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Ohmcoin address: ")+name_); - + CTxDestination address = DecodeDestination(name_); if (setAddress.count(address)) @@ -691,7 +691,7 @@ UniValue signrawtransaction(const UniValue& params, bool fHelp) CCoinsViewMemPool viewMempool(&viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view - BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) { + for(const CTxIn& txin : mergedTx.vin) { const uint256& prevHash = txin.prevout.hash; CCoins coins; view.AccessCoins(prevHash); // this is certainly allowed to fail @@ -834,7 +834,7 @@ UniValue signrawtransaction(const UniValue& params, bool fHelp) ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata); // ... and merge in other signatures: - BOOST_FOREACH(const CMutableTransaction& txv, txVariants) { + for(const CMutableTransaction& txv : txVariants) { sigdata = CombineSignatures(prevPubKey, TransactionSignatureChecker(&txConst, i, amount), sigdata, DataFromTransaction(txv, i)); } diff --git a/src/rpcserver.cpp b/src/rpc/server.cpp similarity index 98% rename from src/rpcserver.cpp rename to src/rpc/server.cpp index 245ad88..0bfb35b 100755 --- a/src/rpcserver.cpp +++ b/src/rpc/server.cpp @@ -6,7 +6,7 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include "rpcserver.h" +#include "rpc/server.h" #include "base58.h" #include "init.h" @@ -19,7 +19,6 @@ #include #include -#include #include #include #include @@ -76,7 +75,7 @@ void RPCTypeCheck(const UniValue& params, bool fAllowNull) { unsigned int i = 0; - BOOST_FOREACH(UniValue::VType t, typesExpected) { + for(UniValue::VType t : typesExpected) { if (params.size() <= i) break; @@ -94,7 +93,7 @@ void RPCTypeCheckObj(const UniValue& o, const map& typesExpected, bool fAllowNull) { - BOOST_FOREACH(const PAIRTYPE(string, UniValue::VType)& t, typesExpected) { + for (const std::pair & t : typesExpected) { const UniValue& v = find_value(o, t.first); if (!fAllowNull && v.isNull()) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first)); @@ -197,7 +196,7 @@ string CRPCTable::help(string strCommand) const vCommands.push_back(make_pair(mi->second->category + mi->first, mi->second)); sort(vCommands.begin(), vCommands.end()); - BOOST_FOREACH (const PAIRTYPE(string, const CRPCCommand*) & command, vCommands) { + for (const std::pair & command : vCommands) { const CRPCCommand* pcmd = command.second; string strMethod = pcmd->name; // We already filter duplicates, but these deprecated screw up the sort order @@ -299,6 +298,7 @@ static const CRPCCommand vRPCCommands[] = /* Block chain and UTXO */ {"blockchain", "findserial", &findserial, true, false, false}, + {"blockchain", "getaccumulatorvalues", &getaccumulatorvalues, true, false, false}, {"blockchain", "getblockchaininfo", &getblockchaininfo, true, false, false}, {"blockchain", "getbestblockhash", &getbestblockhash, true, false, false}, {"blockchain", "getblockcount", &getblockcount, true, false, false}, @@ -653,4 +653,4 @@ void RPCRunLater(const std::string& name, boost::function func, int6 deadlineTimers.insert(std::make_pair(name, boost::shared_ptr(timerInterface->NewTimer(func, nSeconds*1000)))); } -const CRPCTable tableRPC; \ No newline at end of file +const CRPCTable tableRPC; diff --git a/src/rpcserver.h b/src/rpc/server.h similarity index 97% rename from src/rpcserver.h rename to src/rpc/server.h index d82a81a..2f0d3a2 100755 --- a/src/rpcserver.h +++ b/src/rpc/server.h @@ -8,7 +8,7 @@ #define BITCOIN_RPCSERVER_H #include "amount.h" -#include "rpcprotocol.h" +#include "rpc/protocol.h" #include "uint256.h" #include @@ -177,7 +177,7 @@ extern std::string HelpExampleRpc(std::string methodname, std::string args); extern void EnsureWalletIsUnlocked(bool fAllowAnonOnly = false); -extern UniValue getconnectioncount(const UniValue& params, bool fHelp); // in rpcnet.cpp +extern UniValue getconnectioncount(const UniValue& params, bool fHelp); // in rpc/net.cpp extern UniValue getpeerinfo(const UniValue& params, bool fHelp); extern UniValue ping(const UniValue& params, bool fHelp); extern UniValue addnode(const UniValue& params, bool fHelp); @@ -188,7 +188,7 @@ extern UniValue setban(const UniValue& params, bool fHelp); extern UniValue listbanned(const UniValue& params, bool fHelp); extern UniValue clearbanned(const UniValue& params, bool fHelp); -extern UniValue dumpprivkey(const UniValue& params, bool fHelp); // in rpcdump.cpp +extern UniValue dumpprivkey(const UniValue& params, bool fHelp); // in rpc/dump.cpp extern UniValue importprivkey(const UniValue& params, bool fHelp); extern UniValue importpubkey(const UniValue& params, bool fHelp); extern UniValue importaddress(const UniValue& params, bool fHelp); @@ -198,7 +198,7 @@ extern UniValue importwallet(const UniValue& params, bool fHelp); extern UniValue bip38encrypt(const UniValue& params, bool fHelp); extern UniValue bip38decrypt(const UniValue& params, bool fHelp); -extern UniValue getgenerate(const UniValue& params, bool fHelp); // in rpcmining.cpp +extern UniValue getgenerate(const UniValue& params, bool fHelp); // in rpc/mining.cpp extern UniValue setgenerate(const UniValue& params, bool fHelp); extern UniValue getnetworkhashps(const UniValue& params, bool fHelp); extern UniValue gethashespersec(const UniValue& params, bool fHelp); @@ -209,7 +209,7 @@ extern UniValue submitblock(const UniValue& params, bool fHelp); extern UniValue estimatefee(const UniValue& params, bool fHelp); extern UniValue estimatepriority(const UniValue& params, bool fHelp); -extern UniValue getnewaddress(const UniValue& params, bool fHelp); // in rpcwallet.cpp +extern UniValue getnewaddress(const UniValue& params, bool fHelp); // in rpc/wallet.cpp extern UniValue getaccountaddress(const UniValue& params, bool fHelp); extern UniValue getrawchangeaddress(const UniValue& params, bool fHelp); extern UniValue setaccount(const UniValue& params, bool fHelp); @@ -265,7 +265,7 @@ extern UniValue setzohmcseed(const UniValue& params, bool fHelp); extern UniValue getzohmcseed(const UniValue& params, bool fHelp); extern UniValue makekeypair(const UniValue& params, bool fHelp); -extern UniValue getrawtransaction(const UniValue& params, bool fHelp); // in rcprawtransaction.cpp +extern UniValue getrawtransaction(const UniValue& params, bool fHelp); // in rpc/rawtransaction.cpp extern UniValue listunspent(const UniValue& params, bool fHelp); extern UniValue lockunspent(const UniValue& params, bool fHelp); extern UniValue listlockunspent(const UniValue& params, bool fHelp); @@ -277,7 +277,7 @@ extern UniValue sendrawtransaction(const UniValue& params, bool fHelp); extern UniValue searchrawtransactions(const UniValue& params, bool fHelp); -extern UniValue findserial(const UniValue& params, bool fHelp); // in rpcblockchain.cpp +extern UniValue findserial(const UniValue& params, bool fHelp); // in rpc/blockchain.cpp extern UniValue getblockcount(const UniValue& params, bool fHelp); extern UniValue getbestblockhash(const UniValue& params, bool fHelp); extern UniValue getdifficulty(const UniValue& params, bool fHelp); @@ -294,8 +294,9 @@ extern UniValue verifychain(const UniValue& params, bool fHelp); extern UniValue getchaintips(const UniValue& params, bool fHelp); extern UniValue invalidateblock(const UniValue& params, bool fHelp); extern UniValue reconsiderblock(const UniValue& params, bool fHelp); +extern UniValue getaccumulatorvalues(const UniValue& params, bool fHelp); -extern UniValue obfuscation(const UniValue& params, bool fHelp); // in rpckarmanode.cpp +extern UniValue obfuscation(const UniValue& params, bool fHelp); // in rpc/karmanode.cpp extern UniValue getpoolinfo(const UniValue& params, bool fHelp); extern UniValue karmanode(const UniValue& params, bool fHelp); extern UniValue listkarmanodes(const UniValue& params, bool fHelp); @@ -314,7 +315,7 @@ extern UniValue getkarmanodestatus(const UniValue& params, bool fHelp); extern UniValue getkarmanodewinners(const UniValue& params, bool fHelp); extern UniValue getkarmanodescores(const UniValue& params, bool fHelp); -extern UniValue knbudget(const UniValue& params, bool fHelp); // in rpckarmanode-budget.cpp +extern UniValue knbudget(const UniValue& params, bool fHelp); // in rpc/karmanode-budget.cpp extern UniValue preparebudget(const UniValue& params, bool fHelp); extern UniValue submitbudget(const UniValue& params, bool fHelp); extern UniValue knbudgetvote(const UniValue& params, bool fHelp); @@ -326,7 +327,7 @@ extern UniValue knbudgetrawvote(const UniValue& params, bool fHelp); extern UniValue knfinalbudget(const UniValue& params, bool fHelp); extern UniValue checkbudgets(const UniValue& params, bool fHelp); -extern UniValue getinfo(const UniValue& params, bool fHelp); // in rpcmisc.cpp +extern UniValue getinfo(const UniValue& params, bool fHelp); // in rpc/misc.cpp extern UniValue knsync(const UniValue& params, bool fHelp); extern UniValue spork(const UniValue& params, bool fHelp); extern UniValue validateaddress(const UniValue& params, bool fHelp); @@ -341,4 +342,4 @@ void InterruptRPC(); void StopRPC(); std::string JSONRPCExecBatch(const UniValue& vReq); -#endif // BITCOIN_RPCSERVER_H \ No newline at end of file +#endif // BITCOIN_RPCSERVER_H diff --git a/src/script/sign.cpp b/src/script/sign.cpp index ba08608..5d9d939 100755 --- a/src/script/sign.cpp +++ b/src/script/sign.cpp @@ -12,8 +12,6 @@ #include "uint256.h" #include "util.h" -#include - using namespace std; typedef vector valtype; @@ -23,7 +21,7 @@ TransactionSignatureCreator::TransactionSignatureCreator(const CKeyStore* keysto bool TransactionSignatureCreator::CreateSig(std::vector& vchSig, const CKeyID& address, const CScript& scriptCode, SigVersion sigversion) const { CKey key; - if (!keystore->GetKey(address, key)) + if (!keystore->GetKey(address, key)) return false; // Signing with uncompressed keys is disabled in witness scripts @@ -132,7 +130,7 @@ static bool SignStep(const BaseSignatureCreator& creator, const CScript& scriptP static CScript PushAll(const vector& values) { CScript result; - BOOST_FOREACH(const valtype& v, values) { + for (const valtype& v : values) { if (v.size() == 0) { result << OP_0; } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) { @@ -243,12 +241,12 @@ static vector CombineMultisig(const CScript& scriptPubKey, const BaseSi { // Combine all the signatures we've got: set allsigs; - BOOST_FOREACH(const valtype& v, sigs1) + for (const valtype& v : sigs1) { if (!v.empty()) allsigs.insert(v); } - BOOST_FOREACH(const valtype& v, sigs2) + for (const valtype& v : sigs2) { if (!v.empty()) allsigs.insert(v); @@ -259,7 +257,7 @@ static vector CombineMultisig(const CScript& scriptPubKey, const BaseSi unsigned int nSigsRequired = vSolutions.front()[0]; unsigned int nPubKeys = vSolutions.size()-2; map sigs; - BOOST_FOREACH(const valtype& sig, allsigs) + for (const valtype& sig : allsigs) { for (unsigned int i = 0; i < nPubKeys; i++) { diff --git a/src/script/standard.cpp b/src/script/standard.cpp index d255108..eb1ff0f 100755 --- a/src/script/standard.cpp +++ b/src/script/standard.cpp @@ -13,8 +13,6 @@ #include "util.h" #include "utilstrencodings.h" -#include - using namespace std; typedef vector valtype; @@ -80,7 +78,7 @@ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector witnessprogram; if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) { @@ -115,7 +113,7 @@ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector & tplate : mTemplates) { const CScript& script2 = tplate.second; vSolutionsRet.clear(); @@ -447,7 +445,7 @@ CScript GetScriptForMultisig(int nRequired, const std::vector& keys) CScript script; script << CScript::EncodeOP_N(nRequired); - BOOST_FOREACH(const CPubKey& key, keys) + for (const CPubKey& key : keys) script << ToByteVector(key); script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG; return script; @@ -478,4 +476,4 @@ CScript GetScriptForRawPubKey(const CPubKey& pubKey) bool IsValidDestination(const CTxDestination& dest) { return dest.which() != 0; -} \ No newline at end of file +} diff --git a/src/swifttx.cpp b/src/swifttx.cpp index 1dafbc3..ca0f325 100755 --- a/src/swifttx.cpp +++ b/src/swifttx.cpp @@ -13,6 +13,7 @@ #include "net.h" #include "obfuscation.h" #include "protocol.h" +#include "reverse_iterator.h" #include "spork.h" #include "sync.h" #include "util.h" @@ -60,7 +61,7 @@ void ProcessMessageSwiftTX(CNode* pfrom, std::string& strCommand, CDataStream& v return; } - BOOST_FOREACH (const CTxOut o, tx.vout) { + for (const CTxOut o : tx.vout) { // IX supports normal scripts and unspendable scripts (used in DS collateral and Budget collateral). // TODO: Look into other script types that are normal and can be included if (!o.scriptPubKey.IsNormalPaymentScript() && !o.scriptPubKey.IsUnspendable()) { @@ -105,7 +106,7 @@ void ProcessMessageSwiftTX(CNode* pfrom, std::string& strCommand, CDataStream& v pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(), tx.GetHash().ToString().c_str()); - BOOST_FOREACH (const CTxIn& in, tx.vin) { + for (const CTxIn& in : tx.vin) { if (!mapLockedInputs.count(in.prevout)) { mapLockedInputs.insert(make_pair(in.prevout, tx.GetHash())); } @@ -184,10 +185,10 @@ bool IsIXTXValid(const CTransaction& txCollateral) CAmount nValueOut = 0; bool missingTx = false; - BOOST_FOREACH (const CTxOut o, txCollateral.vout) + for (const CTxOut o : txCollateral.vout) nValueOut += o.nValue; - BOOST_FOREACH (const CTxIn i, txCollateral.vin) { + for (const CTxIn i : txCollateral.vin) { CTransaction tx2; uint256 hash; if (GetTransaction(i.prevout.hash, tx2, hash, true)) { @@ -225,7 +226,7 @@ bool IsIXTXValid(const CTransaction& txCollateral) int64_t CreateNewLock(CTransaction tx) { int64_t nTxAge = 0; - BOOST_REVERSE_FOREACH (CTxIn i, tx.vin) { + for (CTxIn i : reverse_iterate (tx.vin)) { nTxAge = GetInputAge(i); if (nTxAge < 5) //1 less than the "send IX" gui requires, incase of a block propagating the network at the time { @@ -369,7 +370,7 @@ bool ProcessConsensusVote(CNode* pnode, CConsensusVote& ctx) #endif if (mapTxLockReq.count(ctx.txHash)) { - BOOST_FOREACH (const CTxIn& in, tx.vin) { + for (const CTxIn& in : tx.vin) { if (!mapLockedInputs.count(in.prevout)) { mapLockedInputs.insert(make_pair(in.prevout, ctx.txHash)); } @@ -401,7 +402,7 @@ bool CheckForConflictingLocks(CTransaction& tx) Blocks could have been rejected during this time, which is OK. After they cancel out, the client will rescan the blocks and find they're acceptable and then take the chain with the most work. */ - BOOST_FOREACH (const CTxIn& in, tx.vin) { + for (const CTxIn& in : tx.vin) { if (mapLockedInputs.count(in.prevout)) { if (mapLockedInputs[in.prevout] != tx.GetHash()) { LogPrintf("SwiftX::CheckForConflictingLocks - found two complete conflicting locks - removing both. %s %s", tx.GetHash().ToString().c_str(), mapLockedInputs[in.prevout].ToString().c_str()); @@ -443,13 +444,13 @@ void CleanTransactionLocksList() if (mapTxLockReq.count(it->second.txHash)) { CTransaction& tx = mapTxLockReq[it->second.txHash]; - BOOST_FOREACH (const CTxIn& in, tx.vin) + for (const CTxIn& in : tx.vin) mapLockedInputs.erase(in.prevout); mapTxLockReq.erase(it->second.txHash); mapTxLockReqRejected.erase(it->second.txHash); - BOOST_FOREACH (CConsensusVote& v, it->second.vecConsensusVotes) + for (CConsensusVote& v : it->second.vecConsensusVotes) mapTxLockVote.erase(v.GetHash()); } @@ -529,7 +530,7 @@ bool CConsensusVote::Sign() bool CTransactionLock::SignaturesValid() { - BOOST_FOREACH (CConsensusVote vote, vecConsensusVotes) { + for (CConsensusVote vote : vecConsensusVotes) { int n = mnodeman.GetKarmanodeRank(vote.vinKarmanode, vote.nBlockHeight, MIN_SWIFTTX_PROTO_VERSION); if (n == -1) { @@ -566,7 +567,7 @@ int CTransactionLock::CountSignatures() if (nBlockHeight == 0) return -1; int n = 0; - BOOST_FOREACH (CConsensusVote v, vecConsensusVotes) { + for (CConsensusVote v : vecConsensusVotes) { if (v.nBlockHeight == nBlockHeight) { n++; } diff --git a/src/sync.cpp b/src/sync.cpp index 03746ea..f3be870 100755 --- a/src/sync.cpp +++ b/src/sync.cpp @@ -12,7 +12,6 @@ #include -#include #include #ifdef DEBUG_LOCKCONTENTION @@ -82,7 +81,7 @@ static void potential_deadlock_detected(const std::pair& mismatch, { LogPrintf("POTENTIAL DEADLOCK DETECTED\n"); LogPrintf("Previous lock order was:\n"); - for (const PAIRTYPE(void*, CLockLocation) & i : s2) { + for (const std::pair & i : s2) { if (i.first == mismatch.first) { LogPrintf(" (1)"); } @@ -92,7 +91,7 @@ static void potential_deadlock_detected(const std::pair& mismatch, LogPrintf(" %s\n", i.second.ToString()); } LogPrintf("Current lock order is:\n"); - for (const PAIRTYPE(void*, CLockLocation) & i : s1) { + for (const std::pair & i : s1) { if (i.first == mismatch.first) { LogPrintf(" (1)"); } @@ -112,7 +111,7 @@ static void push_lock(void* c, const CLockLocation& locklocation, bool fTry) (*lockstack).push_back(std::make_pair(c, locklocation)); - for (const PAIRTYPE(void*, CLockLocation) & i : (*lockstack)) { + for (const std::pair & i : (*lockstack)) { if (i.first == c) break; @@ -146,14 +145,14 @@ void LeaveCritical() std::string LocksHeld() { std::string result; - for (const PAIRTYPE(void*, CLockLocation) & i : *lockstack) + for (const std::pair & i : *lockstack) result += i.second.ToString() + std::string("\n"); return result; } void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) { - for (const PAIRTYPE(void*, CLockLocation) & i : *lockstack) + for (const std::pair & i : *lockstack) if (i.first == cs) return; fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str()); diff --git a/src/test/DoS_tests.cpp b/src/test/DoS_tests.cpp index 39102bf..9c79c4f 100755 --- a/src/test/DoS_tests.cpp +++ b/src/test/DoS_tests.cpp @@ -20,7 +20,6 @@ #include // for 'map_list_of()' #include -#include #include // Tests this internal-to-main.cpp method: diff --git a/src/test/accounting_tests.cpp b/src/test/accounting_tests.cpp index 6413ca6..1113792 100755 --- a/src/test/accounting_tests.cpp +++ b/src/test/accounting_tests.cpp @@ -2,12 +2,11 @@ // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include "wallet.h" -#include "walletdb.h" +#include "wallet/wallet.h" +#include "wallet/walletdb.h" #include -#include #include extern CWallet* pwalletMain; @@ -22,7 +21,7 @@ GetResults(CWalletDB& walletdb, std::map& results) results.clear(); BOOST_CHECK(walletdb.ReorderTransactions(pwalletMain) == DB_LOAD_OK); walletdb.ListAccountCreditDebit("", aes); - BOOST_FOREACH(CAccountingEntry& ae, aes) + for(CAccountingEntry& ae : aes) { results[ae.nOrderPos] = ae; } diff --git a/src/test/alert_tests.cpp b/src/test/alert_tests.cpp index 4869ba5..ca78dc3 100755 --- a/src/test/alert_tests.cpp +++ b/src/test/alert_tests.cpp @@ -18,7 +18,6 @@ #include #include -#include #include #if 0 @@ -118,7 +117,7 @@ BOOST_AUTO_TEST_CASE(AlertApplies) { SetMockTime(11); - BOOST_FOREACH(const CAlert& alert, alerts) + for(const CAlert& alert : alerts) { BOOST_CHECK(alert.CheckSignature()); } @@ -163,7 +162,7 @@ BOOST_AUTO_TEST_CASE(AlertNotify) mapArgs["-alertnotify"] = std::string("echo %s >> ") + temp.string(); - BOOST_FOREACH(CAlert alert, alerts) + for(CAlert alert : alerts) alert.ProcessAlert(false); std::vector r = read_lines(temp); diff --git a/src/test/base58_tests.cpp b/src/test/base58_tests.cpp index 2bd8018..1f2754e 100755 --- a/src/test/base58_tests.cpp +++ b/src/test/base58_tests.cpp @@ -12,7 +12,6 @@ #include "util.h" #include "utilstrencodings.h" -#include #include #include diff --git a/src/test/bip32_tests.cpp b/src/test/bip32_tests.cpp index 9cf07fc..348be7a 100755 --- a/src/test/bip32_tests.cpp +++ b/src/test/bip32_tests.cpp @@ -82,7 +82,7 @@ void RunTest(const TestVector &test) { CExtPubKey pubkey; key.SetMaster(&seed[0], seed.size()); pubkey = key.Neuter(); - BOOST_FOREACH(const TestDerivation &derive, test.vDerive) { + for(const TestDerivation &derive : test.vDerive) { unsigned char data[74]; key.Encode(data); pubkey.Encode(data); diff --git a/src/test/budget_tests.cpp b/src/test/budget_tests.cpp index aea4491..c3d0f52 100644 --- a/src/test/budget_tests.cpp +++ b/src/test/budget_tests.cpp @@ -2,10 +2,11 @@ // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include -#include -#include #include "karmanode-budget.h" +#include "tinyformat.h" +#include "utilmoneystr.h" + +#include BOOST_AUTO_TEST_SUITE(budget_tests) @@ -19,13 +20,13 @@ void CheckBudgetValue(int nHeight, std::string strNetwork, CAmount nExpectedValu BOOST_AUTO_TEST_CASE(budget_value) { - SelectParams(CBaseChainParams::MAIN); - int nHeightTest = Params().Zerocoin_Block_V2_Start() + 1; - CheckBudgetValue(nHeightTest, "mainnet", 43200*COIN); - SelectParams(CBaseChainParams::TESTNET); nHeightTest = Params().Zerocoin_Block_V2_Start() + 1; CheckBudgetValue(nHeightTest, "testnet", 7300*COIN); + + SelectParams(CBaseChainParams::MAIN); + int nHeightTest = Params().Zerocoin_Block_V2_Start() + 1; + CheckBudgetValue(nHeightTest, "mainnet", 43200*COIN); } -BOOST_AUTO_TEST_SUITE_END() \ No newline at end of file +BOOST_AUTO_TEST_SUITE_END() diff --git a/src/test/dbwrapper_tests.cpp b/src/test/dbwrapper_tests.cpp new file mode 100755 index 0000000..2381ba4 --- /dev/null +++ b/src/test/dbwrapper_tests.cpp @@ -0,0 +1,325 @@ +// 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. + +#include "dbwrapper.h" +#include "uint256.h" +#include "random.h" +#include "test/test_bitcoin.h" + +#include // for 'operator+=()' +#include +#include + +// Test if a string consists entirely of null characters +bool is_null_key(const std::vector& key) { + bool isnull = true; + + for (unsigned int i = 0; i < key.size(); i++) + isnull &= (key[i] == '\x00'); + + return isnull; +} + +BOOST_FIXTURE_TEST_SUITE(dbwrapper_tests, BasicTestingSetup) + +BOOST_AUTO_TEST_CASE(dbwrapper) +{ + // Perform tests both obfuscated and non-obfuscated. + for (int i = 0; i < 2; i++) { + bool obfuscate = (bool)i; + boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path(); + CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate); + char key = 'k'; + uint256 in = GetRandHash(); + uint256 res; + + // Ensure that we're doing real obfuscation when obfuscate=true + BOOST_CHECK(obfuscate != is_null_key(dbwrapper_private::GetObfuscateKey(dbw))); + + BOOST_CHECK(dbw.Write(key, in)); + BOOST_CHECK(dbw.Read(key, res)); + BOOST_CHECK_EQUAL(res.ToString(), in.ToString()); + } +} + +// Test batch operations +BOOST_AUTO_TEST_CASE(dbwrapper_batch) +{ + // Perform tests both obfuscated and non-obfuscated. + for (int i = 0; i < 2; i++) { + bool obfuscate = (bool)i; + boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path(); + CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate); + + char key = 'i'; + uint256 in = GetRandHash(); + char key2 = 'j'; + uint256 in2 = GetRandHash(); + char key3 = 'k'; + uint256 in3 = GetRandHash(); + + uint256 res; + CDBBatch batch(dbw); + + batch.Write(key, in); + batch.Write(key2, in2); + batch.Write(key3, in3); + + // Remove key3 before it's even been written + batch.Erase(key3); + + dbw.WriteBatch(batch); + + BOOST_CHECK(dbw.Read(key, res)); + BOOST_CHECK_EQUAL(res.ToString(), in.ToString()); + BOOST_CHECK(dbw.Read(key2, res)); + BOOST_CHECK_EQUAL(res.ToString(), in2.ToString()); + + // key3 should've never been written + BOOST_CHECK(dbw.Read(key3, res) == false); + } +} + +BOOST_AUTO_TEST_CASE(dbwrapper_iterator) +{ + // Perform tests both obfuscated and non-obfuscated. + for (int i = 0; i < 2; i++) { + bool obfuscate = (bool)i; + boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path(); + CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate); + + // The two keys are intentionally chosen for ordering + char key = 'j'; + uint256 in = GetRandHash(); + BOOST_CHECK(dbw.Write(key, in)); + char key2 = 'k'; + uint256 in2 = GetRandHash(); + BOOST_CHECK(dbw.Write(key2, in2)); + + std::unique_ptr it(const_cast(&dbw)->NewIterator()); + + // Be sure to seek past the obfuscation key (if it exists) + it->Seek(key); + + char key_res; + uint256 val_res; + + it->GetKey(key_res); + it->GetValue(val_res); + BOOST_CHECK_EQUAL(key_res, key); + BOOST_CHECK_EQUAL(val_res.ToString(), in.ToString()); + + it->Next(); + + it->GetKey(key_res); + it->GetValue(val_res); + BOOST_CHECK_EQUAL(key_res, key2); + BOOST_CHECK_EQUAL(val_res.ToString(), in2.ToString()); + + it->Next(); + BOOST_CHECK_EQUAL(it->Valid(), false); + } +} + +// Test that we do not obfuscation if there is existing data. +BOOST_AUTO_TEST_CASE(existing_data_no_obfuscate) +{ + // We're going to share this boost::filesystem::path between two wrappers + boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path(); + create_directories(ph); + + // Set up a non-obfuscated wrapper to write some initial data. + CDBWrapper* dbw = new CDBWrapper(ph, (1 << 10), false, false, false); + char key = 'k'; + uint256 in = GetRandHash(); + uint256 res; + + BOOST_CHECK(dbw->Write(key, in)); + BOOST_CHECK(dbw->Read(key, res)); + BOOST_CHECK_EQUAL(res.ToString(), in.ToString()); + + // Call the destructor to free leveldb LOCK + delete dbw; + dbw = nullptr; + + // Now, set up another wrapper that wants to obfuscate the same directory + CDBWrapper odbw(ph, (1 << 10), false, false, true); + + // Check that the key/val we wrote with unobfuscated wrapper exists and + // is readable. + uint256 res2; + BOOST_CHECK(odbw.Read(key, res2)); + BOOST_CHECK_EQUAL(res2.ToString(), in.ToString()); + + BOOST_CHECK(!odbw.IsEmpty()); // There should be existing data + BOOST_CHECK(is_null_key(dbwrapper_private::GetObfuscateKey(odbw))); // The key should be an empty string + + uint256 in2 = GetRandHash(); + uint256 res3; + + // Check that we can write successfully + BOOST_CHECK(odbw.Write(key, in2)); + BOOST_CHECK(odbw.Read(key, res3)); + BOOST_CHECK_EQUAL(res3.ToString(), in2.ToString()); +} + +// Ensure that we start obfuscating during a reindex. +BOOST_AUTO_TEST_CASE(existing_data_reindex) +{ + // We're going to share this boost::filesystem::path between two wrappers + boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path(); + create_directories(ph); + + // Set up a non-obfuscated wrapper to write some initial data. + CDBWrapper* dbw = new CDBWrapper(ph, (1 << 10), false, false, false); + char key = 'k'; + uint256 in = GetRandHash(); + uint256 res; + + BOOST_CHECK(dbw->Write(key, in)); + BOOST_CHECK(dbw->Read(key, res)); + BOOST_CHECK_EQUAL(res.ToString(), in.ToString()); + + // Call the destructor to free leveldb LOCK + delete dbw; + dbw = nullptr; + + // Simulate a -reindex by wiping the existing data store + CDBWrapper odbw(ph, (1 << 10), false, true, true); + + // Check that the key/val we wrote with unobfuscated wrapper doesn't exist + uint256 res2; + BOOST_CHECK(!odbw.Read(key, res2)); + BOOST_CHECK(!is_null_key(dbwrapper_private::GetObfuscateKey(odbw))); + + uint256 in2 = GetRandHash(); + uint256 res3; + + // Check that we can write successfully + BOOST_CHECK(odbw.Write(key, in2)); + BOOST_CHECK(odbw.Read(key, res3)); + BOOST_CHECK_EQUAL(res3.ToString(), in2.ToString()); +} + +BOOST_AUTO_TEST_CASE(iterator_ordering) +{ + boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path(); + CDBWrapper dbw(ph, (1 << 20), true, false, false); + for (int x=0x00; x<256; ++x) { + uint8_t key = x; + uint32_t value = x*x; + BOOST_CHECK(dbw.Write(key, value)); + } + + std::unique_ptr it(const_cast(&dbw)->NewIterator()); + for (int c=0; c<2; ++c) { + int seek_start; + if (c == 0) + seek_start = 0x00; + else + seek_start = 0x80; + it->Seek((uint8_t)seek_start); + for (int x=seek_start; x<256; ++x) { + uint8_t key; + uint32_t value; + BOOST_CHECK(it->Valid()); + if (!it->Valid()) // Avoid spurious errors about invalid iterator's key and value in case of failure + break; + BOOST_CHECK(it->GetKey(key)); + BOOST_CHECK(it->GetValue(value)); + BOOST_CHECK_EQUAL(key, x); + BOOST_CHECK_EQUAL(value, x*x); + it->Next(); + } + BOOST_CHECK(!it->Valid()); + } +} + +struct StringContentsSerializer { + // Used to make two serialized objects the same while letting them have a different lengths + // This is a terrible idea + std::string str; + StringContentsSerializer() {} + StringContentsSerializer(const std::string& inp) : str(inp) {} + + StringContentsSerializer& operator+=(const std::string& s) { + str += s; + return *this; + } + StringContentsSerializer& operator+=(const StringContentsSerializer& s) { return *this += s.str; } + + ADD_SERIALIZE_METHODS; + + template + inline void SerializationOp(Stream& s, Operation ser_action) { + if (ser_action.ForRead()) { + str.clear(); + char c = 0; + while (true) { + try { + READWRITE(c); + str.push_back(c); + } catch (const std::ios_base::failure& e) { + break; + } + } + } else { + for (size_t i = 0; i < str.size(); i++) + READWRITE(str[i]); + } + } +}; + +BOOST_AUTO_TEST_CASE(iterator_string_ordering) +{ + char buf[10]; + + boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path(); + CDBWrapper dbw(ph, (1 << 20), true, false, false); + for (int x=0x00; x<10; ++x) { + for (int y = 0; y < 10; y++) { + snprintf(buf, sizeof(buf), "%d", x); + StringContentsSerializer key(buf); + for (int z = 0; z < y; z++) + key += key; + uint32_t value = x*x; + BOOST_CHECK(dbw.Write(key, value)); + } + } + + std::unique_ptr it(const_cast(&dbw)->NewIterator()); + for (int c=0; c<2; ++c) { + int seek_start; + if (c == 0) + seek_start = 0; + else + seek_start = 5; + snprintf(buf, sizeof(buf), "%d", seek_start); + StringContentsSerializer seek_key(buf); + it->Seek(seek_key); + for (int x=seek_start; x<10; ++x) { + for (int y = 0; y < 10; y++) { + snprintf(buf, sizeof(buf), "%d", x); + std::string exp_key(buf); + for (int z = 0; z < y; z++) + exp_key += exp_key; + StringContentsSerializer key; + uint32_t value; + BOOST_CHECK(it->Valid()); + if (!it->Valid()) // Avoid spurious errors about invalid iterator's key and value in case of failure + break; + BOOST_CHECK(it->GetKey(key)); + BOOST_CHECK(it->GetValue(value)); + BOOST_CHECK_EQUAL(key.str, exp_key); + BOOST_CHECK_EQUAL(value, x*x); + it->Next(); + } + } + BOOST_CHECK(!it->Valid()); + } +} + + + +BOOST_AUTO_TEST_SUITE_END() diff --git a/src/test/getarg_tests.cpp b/src/test/getarg_tests.cpp index b73623b..752fc17 100755 --- a/src/test/getarg_tests.cpp +++ b/src/test/getarg_tests.cpp @@ -8,7 +8,6 @@ #include #include -#include #include BOOST_AUTO_TEST_SUITE(getarg_tests) @@ -24,7 +23,7 @@ static void ResetArgs(const std::string& strArg) // Convert to char*: std::vector vecChar; - BOOST_FOREACH(std::string& s, vecArg) + for(std::string& s : vecArg) vecChar.push_back(s.c_str()); ParseParameters(vecChar.size(), &vecChar[0]); diff --git a/src/test/miner_tests.cpp b/src/test/miner_tests.cpp index 8baa790..72238eb 100755 --- a/src/test/miner_tests.cpp +++ b/src/test/miner_tests.cpp @@ -259,7 +259,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) SetMockTime(0); mempool.clear(); - BOOST_FOREACH(CTransaction *tx, txFirst) + for(CTransaction *tx : txFirst) delete tx; Checkpoints::fEnabled = true; diff --git a/src/test/multisig_tests.cpp b/src/test/multisig_tests.cpp index 7281b85..2cba040 100755 --- a/src/test/multisig_tests.cpp +++ b/src/test/multisig_tests.cpp @@ -12,11 +12,10 @@ #include "uint256.h" #ifdef ENABLE_WALLET -#include "wallet_ismine.h" +#include "wallet/wallet_ismine.h" #endif #include -#include #include using namespace std; @@ -33,7 +32,7 @@ sign_multisig(CScript scriptPubKey, vector keys, CTransaction transaction, CScript result; result << OP_0; // CHECKMULTISIG bug workaround - BOOST_FOREACH(const CKey &key, keys) + for(const CKey &key : keys) { vector vchSig; BOOST_CHECK(key.Sign(hash, vchSig)); diff --git a/src/test/rpc_tests.cpp b/src/test/rpc_tests.cpp index 696a739..ee1e82c 100755 --- a/src/test/rpc_tests.cpp +++ b/src/test/rpc_tests.cpp @@ -2,8 +2,8 @@ // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include "rpcserver.h" -#include "rpcclient.h" +#include "rpc/server.h" +#include "rpc/client.h" #include "base58.h" #include "netbase.h" diff --git a/src/test/rpc_wallet_tests.cpp b/src/test/rpc_wallet_tests.cpp new file mode 100755 index 0000000..a6eed22 --- /dev/null +++ b/src/test/rpc_wallet_tests.cpp @@ -0,0 +1,185 @@ +// Copyright (c) 2013-2014 The Bitcoin Core developers +// Copyright (c) 2017 The PIVX developers +// Copyright (c) 2020 The Ohmcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "rpc/server.h" +#include "rpc/client.h" + +#include "base58.h" +#include "wallet/wallet.h" + +#include +#include + +#include + +using namespace std; + +extern UniValue createArgs(int nRequired, const char* address1 = NULL, const char* address2 = NULL); +extern UniValue CallRPC(string args); + +extern CWallet* pwalletMain; + +BOOST_AUTO_TEST_SUITE(rpc_wallet_tests) + +BOOST_AUTO_TEST_CASE(rpc_addmultisig) +{ + LOCK(pwalletMain->cs_wallet); + + rpcfn_type addmultisig = tableRPC["addmultisigaddress"]->actor; + + // old, 65-byte-long: + const char address1Hex[] = "041431A18C7039660CD9E3612A2A47DC53B69CB38EA4AD743B7DF8245FD0438F8E7270415F1085B9DC4D7DA367C69F1245E27EE5552A481D6854184C80F0BB8456"; + // new, compressed: + const char address2Hex[] = "029BBEFF390CE736BD396AF43B52A1C14ED52C086B1E5585C15931F68725772BAC"; + + UniValue v; + CBitcoinAddress address; + BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex), false)); + address.SetString(v.get_str()); + BOOST_CHECK(address.IsValid() && address.IsScript()); + + BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex, address2Hex), false)); + address.SetString(v.get_str()); + BOOST_CHECK(address.IsValid() && address.IsScript()); + + BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(2, address1Hex, address2Hex), false)); + address.SetString(v.get_str()); + BOOST_CHECK(address.IsValid() && address.IsScript()); + + BOOST_CHECK_THROW(addmultisig(createArgs(0), false), runtime_error); + BOOST_CHECK_THROW(addmultisig(createArgs(1), false), runtime_error); + BOOST_CHECK_THROW(addmultisig(createArgs(2, address1Hex), false), runtime_error); + + BOOST_CHECK_THROW(addmultisig(createArgs(1, ""), false), runtime_error); + BOOST_CHECK_THROW(addmultisig(createArgs(1, "NotAValidPubkey"), false), runtime_error); + + string short1(address1Hex, address1Hex + sizeof(address1Hex) - 2); // last byte missing + BOOST_CHECK_THROW(addmultisig(createArgs(2, short1.c_str()), false), runtime_error); + + string short2(address1Hex + 1, address1Hex + sizeof(address1Hex)); // first byte missing + BOOST_CHECK_THROW(addmultisig(createArgs(2, short2.c_str()), false), runtime_error); +} + +BOOST_AUTO_TEST_CASE(rpc_wallet) +{ + // Test RPC calls for various wallet statistics + UniValue r; + + LOCK2(cs_main, pwalletMain->cs_wallet); + + CPubKey demoPubkey = pwalletMain->GenerateNewKey(); + CBitcoinAddress demoAddress = CBitcoinAddress(CTxDestination(demoPubkey.GetID())); + UniValue retValue; + string strAccount = "walletDemoAccount"; + string strPurpose = "receive"; + BOOST_CHECK_NO_THROW({ /*Initialize Wallet with an account */ + CWalletDB walletdb(pwalletMain->strWalletFile); + CAccount account; + account.vchPubKey = demoPubkey; + pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, strPurpose); + walletdb.WriteAccount(strAccount, account); + }); + + CPubKey setaccountDemoPubkey = pwalletMain->GenerateNewKey(); + CBitcoinAddress setaccountDemoAddress = CBitcoinAddress(CTxDestination(setaccountDemoPubkey.GetID())); + + /********************************* + * setaccount + *********************************/ + BOOST_CHECK_NO_THROW(CallRPC("setaccount " + setaccountDemoAddress.ToString() + " nullaccount")); + /* D8w12Vu3WVhn543dgrUUf9uYu6HLwnPm5R is not owned by the test wallet. */ + BOOST_CHECK_THROW(CallRPC("setaccount D8w12Vu3WVhn543dgrUUf9uYu6HLwnPm5R nullaccount"), runtime_error); + BOOST_CHECK_THROW(CallRPC("setaccount"), runtime_error); + /* D8w12Vu3WVhn543dgrUUf9uYu6HLwnPm5 (33 chars) is an illegal address (should be 34 chars) */ + BOOST_CHECK_THROW(CallRPC("setaccount D8w12Vu3WVhn543dgrUUf9uYu6HLwnPm5 nullaccount"), runtime_error); + + /********************************* + * listunspent + *********************************/ + BOOST_CHECK_NO_THROW(CallRPC("listunspent")); + BOOST_CHECK_THROW(CallRPC("listunspent string"), runtime_error); + BOOST_CHECK_THROW(CallRPC("listunspent 0 string"), runtime_error); + BOOST_CHECK_THROW(CallRPC("listunspent 0 1 not_array"), runtime_error); + BOOST_CHECK_THROW(CallRPC("listunspent 0 1 [] extra"), runtime_error); + BOOST_CHECK_NO_THROW(r = CallRPC("listunspent 0 1 []")); + BOOST_CHECK(r.get_array().empty()); + + /********************************* + * listreceivedbyaddress + *********************************/ + BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress")); + BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0")); + BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress not_int"), runtime_error); + BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 not_bool"), runtime_error); + BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0 true")); + BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 true extra"), runtime_error); + + /********************************* + * listreceivedbyaccount + *********************************/ + BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount")); + BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0")); + BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount not_int"), runtime_error); + BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 not_bool"), runtime_error); + BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0 true")); + BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 true extra"), runtime_error); + + /********************************* + * getrawchangeaddress + *********************************/ + BOOST_CHECK_NO_THROW(CallRPC("getrawchangeaddress")); + + /********************************* + * getnewaddress + *********************************/ + BOOST_CHECK_NO_THROW(CallRPC("getnewaddress")); + BOOST_CHECK_NO_THROW(CallRPC("getnewaddress getnewaddress_demoaccount")); + + /********************************* + * getaccountaddress + *********************************/ + BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress \"\"")); + BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress accountThatDoesntExists")); // Should generate a new account + BOOST_CHECK_NO_THROW(retValue = CallRPC("getaccountaddress " + strAccount)); + BOOST_CHECK(CBitcoinAddress(retValue.get_str()).Get() == demoAddress.Get()); + + /********************************* + * getaccount + *********************************/ + BOOST_CHECK_THROW(CallRPC("getaccount"), runtime_error); + BOOST_CHECK_NO_THROW(CallRPC("getaccount " + demoAddress.ToString())); + + /********************************* + * signmessage + verifymessage + *********************************/ + BOOST_CHECK_NO_THROW(retValue = CallRPC("signmessage " + demoAddress.ToString() + " mymessage")); + BOOST_CHECK_THROW(CallRPC("signmessage"), runtime_error); + /* Should throw error because this address is not loaded in the wallet */ + BOOST_CHECK_THROW(CallRPC("signmessage D8w12Vu3WVhn543dgrUUf9uYu6HLwnPm5R mymessage"), runtime_error); + + /* missing arguments */ + BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString()), runtime_error); + BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str()), runtime_error); + /* Illegal address */ + BOOST_CHECK_THROW(CallRPC("verifymessage D8w12Vu3WVhn543dgrUUf9uYu6HLwnPm5 " + retValue.get_str() + " mymessage"), runtime_error); + /* wrong address */ + BOOST_CHECK(CallRPC("verifymessage D8w12Vu3WVhn543dgrUUf9uYu6HLwnPm5R " + retValue.get_str() + " mymessage").get_bool() == false); + /* Correct address and signature but wrong message */ + BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " wrongmessage").get_bool() == false); + /* Correct address, message and signature*/ + BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " mymessage").get_bool() == true); + + /********************************* + * getaddressesbyaccount + *********************************/ + BOOST_CHECK_THROW(CallRPC("getaddressesbyaccount"), runtime_error); + BOOST_CHECK_NO_THROW(retValue = CallRPC("getaddressesbyaccount " + strAccount)); + UniValue arr = retValue.get_array(); + BOOST_CHECK(arr.size() > 0); + BOOST_CHECK(CBitcoinAddress(arr[0].get_str()).Get() == demoAddress.Get()); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp index b6fa23b..9d45085 100755 --- a/src/test/script_tests.cpp +++ b/src/test/script_tests.cpp @@ -31,7 +31,6 @@ #include #include #include -#include #include #include @@ -809,7 +808,7 @@ BOOST_AUTO_TEST_CASE(script_build) std::string strGood; std::string strBad; - BOOST_FOREACH(TestBuilder& test, good) { + for(TestBuilder& test : good) { test.Test(true); std::string str = JSONPrettyPrint(test.GetJSON()); #ifndef UPDATE_JSON_TESTS @@ -819,7 +818,7 @@ BOOST_AUTO_TEST_CASE(script_build) #endif strGood += str + ",\n"; } - BOOST_FOREACH(TestBuilder& test, bad) { + for(TestBuilder& test : bad) { test.Test(false); std::string str = JSONPrettyPrint(test.GetJSON()); #ifndef UPDATE_JSON_TESTS @@ -961,7 +960,7 @@ sign_multisig(CScript scriptPubKey, std::vector keys, CTransaction transac // and vice-versa) // result << OP_0; - BOOST_FOREACH(const CKey &key, keys) + for(const CKey &key : keys) { vector vchSig; BOOST_CHECK(key.Sign(hash, vchSig)); @@ -1075,7 +1074,7 @@ BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23) CScript badsig6 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig6, scriptPubKey23, NULL, flags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err)); -} +} BOOST_AUTO_TEST_CASE(script_combineSigs) { diff --git a/src/test/sigopcount_tests.cpp b/src/test/sigopcount_tests.cpp index 87f987c..8829ae6 100755 --- a/src/test/sigopcount_tests.cpp +++ b/src/test/sigopcount_tests.cpp @@ -11,7 +11,6 @@ #include -#include #include using namespace std; diff --git a/src/test/transaction_tests.cpp b/src/test/transaction_tests.cpp index 761a811..7c7f85f 100755 --- a/src/test/transaction_tests.cpp +++ b/src/test/transaction_tests.cpp @@ -27,7 +27,6 @@ #include #include #include -#include #include @@ -66,7 +65,7 @@ unsigned int ParseScriptFlags(string strFlags) vector words; split(words, strFlags, is_any_of(",")); - BOOST_FOREACH(string word, words) + for(string word : words) { if (!mapFlagNames.count(word)) BOOST_ERROR("Bad test: unknown verification flag '" << word << "'"); @@ -401,7 +400,7 @@ void CheckWithFlag(const CTransaction& output, const CMutableTransaction& input, static CScript PushAll(const vector& values) { CScript result; - BOOST_FOREACH(const valtype& v, values) { + for(const valtype& v : values) { if (v.size() == 0) { result << OP_0; } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) { diff --git a/src/test/zerocoin_denomination_tests.cpp b/src/test/zerocoin_denomination_tests.cpp index af03c70..91e3d5f 100644 --- a/src/test/zerocoin_denomination_tests.cpp +++ b/src/test/zerocoin_denomination_tests.cpp @@ -8,8 +8,8 @@ #include "denomination_functions.h" #include "main.h" #include "txdb.h" -#include "wallet.h" -#include "walletdb.h" +#include "wallet/wallet.h" +#include "wallet/walletdb.h" #include #include @@ -132,7 +132,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test241) listMints, mapDenom, nNeededSpends); - + if (fDebug) { if (vSpends.size() > 0) { std::cout << "SUCCESS : Coins = " << nValueTarget / COIN << " # spends used = " << vSpends.size() @@ -237,7 +237,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_245) // const int DenomAmounts[] = {0, 1, 4, 0, 0, 0, 0, 0}; // For 51 //const int nSpendValue = 51; - + // CoinsHeld = 245 const int DenomAmounts[] = {0, 1, 4, 2, 1, 0, 0, 0}; // We can spend up to this amount for above set for less 6 spends @@ -287,7 +287,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_245) // bool fDebug = 0; int nCoinsReturned; int nNeededSpends = 0; // Number of spends which would be needed if selection failed - + // Go through all possible spend between 1 and 241 and see if it's possible or not for (int i = 0; i < CoinsHeld; i++) { std::vector vSpends = SelectMintsFromList(nValueTarget, nSelectedValue, @@ -297,7 +297,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_245) listMints, mapOfDenomsHeld, nNeededSpends); - + // if (fDebug) { // if (vSpends.size() > 0) { // std::cout << "SUCCESS : Coins = " << nValueTarget / COIN << " # spends = " << vSpends.size() @@ -311,7 +311,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_245) bool spends_not_ok = ((vSpends.size() > nMaxNumberOfSpends) || (vSpends.size() == 0)); if (i < nMaxSpendAmount) BOOST_CHECK_MESSAGE(!spends_not_ok, "Too many spends"); else BOOST_CHECK_MESSAGE(spends_not_ok, "Expected to fail but didn't"); - + std::vector vSpendsAlt = SelectMintsFromList(nValueTarget, nSelectedValue, nMaxNumberOfSpends, true, @@ -319,8 +319,8 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_245) listMints, mapOfDenomsHeld, nNeededSpends); - - + + // if (fDebug) { // if (vSpendsAlt.size() > 0) { // std::cout << "# spends = " << vSpendsAlt.size() @@ -330,11 +330,11 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_245) // std::cout << "UNABLE TO SPEND : Coins = " << nValueTarget / COIN << " Held = " << CoinsHeld << "\n"; // } // } - + spends_not_ok = ((vSpendsAlt.size() > nMaxNumberOfSpends) || (vSpendsAlt.size() == 0)); if (i < nMaxSpendAmount) BOOST_CHECK_MESSAGE(!spends_not_ok, "Too many spends"); else BOOST_CHECK_MESSAGE(spends_not_ok, "Expected to fail but didn't"); - + nValueTarget += OneCoinAmount; } } @@ -392,7 +392,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_145) //bool fDebug = 0; int nCoinsReturned; int nNeededSpends = 0; // Number of spends which would be needed if selection failed - + // Go through all possible spend between 1 and 241 and see if it's possible or not for (int i = 0; i < CoinsHeld; i++) { std::vector vSpends = SelectMintsFromList(nValueTarget, nSelectedValue, @@ -402,7 +402,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_145) listMints, mapOfDenomsHeld, nNeededSpends); - + // if (fDebug) { // if (vSpends.size() > 0) { // std::cout << "SUCCESS : Coins = " << nValueTarget / COIN << " # spends = " << vSpends.size() @@ -412,11 +412,11 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_145) // std::cout << "UNABLE TO SPEND : Coins = " << nValueTarget / COIN << " Held = " << CoinsHeld << "\n"; // } // } - + bool spends_not_ok = ((vSpends.size() > nMaxNumberOfSpends) || (vSpends.size() == 0)); if (i < nMaxSpendAmount) BOOST_CHECK_MESSAGE(!spends_not_ok, "Too many spends"); else BOOST_CHECK_MESSAGE(spends_not_ok, "Expected to fail but didn't"); - + std::vector vSpendsAlt = SelectMintsFromList(nValueTarget, nSelectedValue, nMaxNumberOfSpends, true, @@ -424,8 +424,8 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_145) listMints, mapOfDenomsHeld, nNeededSpends); - - + + // if (fDebug) { // if (vSpendsAlt.size() > 0) { // std::cout << "# spends = " << vSpendsAlt.size() @@ -435,12 +435,12 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_145) // std::cout << "UNABLE TO SPEND : Coins = " << nValueTarget / COIN << " Held = " << CoinsHeld << "\n"; // } // } - + spends_not_ok = ((vSpendsAlt.size() > nMaxNumberOfSpends) || (vSpendsAlt.size() == 0)); if (i < nMaxSpendAmount) BOOST_CHECK_MESSAGE(!spends_not_ok, "Too many spends"); else BOOST_CHECK_MESSAGE(spends_not_ok, "Expected to fail but didn't"); - + nValueTarget += OneCoinAmount; } } diff --git a/src/test/zerocoin_implementation_tests.cpp b/src/test/zerocoin_implementation_tests.cpp index a36ff96..b1c619f 100644 --- a/src/test/zerocoin_implementation_tests.cpp +++ b/src/test/zerocoin_implementation_tests.cpp @@ -132,7 +132,7 @@ bool CheckZerocoinSpendNoDB(const CTransaction tx, string& strError) set serials; list vSpends; CAmount nTotalRedeemed = 0; - BOOST_FOREACH(const CTxIn& txin, tx.vin) { + for (const CTxIn& txin : tx.vin) { //only check txin that is a zcspend if (!txin.scriptSig.IsZerocoinSpend()) diff --git a/src/test/zerocoin_transactions_tests.cpp b/src/test/zerocoin_transactions_tests.cpp index 743ad3f..da68b48 100644 --- a/src/test/zerocoin_transactions_tests.cpp +++ b/src/test/zerocoin_transactions_tests.cpp @@ -7,8 +7,8 @@ #include "chainparams.h" #include "coincontrol.h" #include "main.h" -#include "wallet.h" -#include "walletdb.h" +#include "wallet/wallet.h" +#include "wallet/walletdb.h" #include "txdb.h" #include #include diff --git a/src/timedata.cpp b/src/timedata.cpp index c79bbfa..34faeb2 100755 --- a/src/timedata.cpp +++ b/src/timedata.cpp @@ -10,8 +10,6 @@ #include "util.h" #include "utilstrencodings.h" -#include - using namespace std; static CCriticalSection cs_nTimeOffset; @@ -83,7 +81,7 @@ void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample) if (!fDone) { // If nobody has a time different than ours but within 5 minutes of ours, give a warning bool fMatch = false; - BOOST_FOREACH (int64_t nOffset, vSorted) + for (int64_t nOffset : vSorted) if (nOffset != 0 && abs64(nOffset) < 5 * 60) fMatch = true; @@ -97,7 +95,7 @@ void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample) } } if (fDebug) { - BOOST_FOREACH (int64_t n, vSorted) + for (int64_t n : vSorted) LogPrintf("%+d ", n); LogPrintf("| "); } diff --git a/src/torcontrol.cpp b/src/torcontrol.cpp index 36e5c57..67bb9dd 100644 --- a/src/torcontrol.cpp +++ b/src/torcontrol.cpp @@ -18,7 +18,6 @@ #include #include #include -#include #include #include #include @@ -488,7 +487,7 @@ void TorController::add_onion_cb(TorControlConnection& _conn, const TorControlRe { if (reply.code == 250) { LogPrint("tor", "tor: ADD_ONION successful\n"); - BOOST_FOREACH(const std::string &s, reply.lines) { + for(const std::string &s : reply.lines) { std::map m = ParseTorReplyMapping(s); std::map::iterator i; if ((i = m.find("ServiceID")) != m.end()) @@ -619,7 +618,7 @@ void TorController::protocolinfo_cb(TorControlConnection& _conn, const TorContro * 250-AUTH METHODS=NULL * 250-AUTH METHODS=HASHEDPASSWORD */ - BOOST_FOREACH(const std::string &s, reply.lines) { + for(const std::string &s : reply.lines) { std::pair l = SplitTorReplyLine(s); if (l.first == "AUTH") { std::map m = ParseTorReplyMapping(l.second); @@ -636,7 +635,7 @@ void TorController::protocolinfo_cb(TorControlConnection& _conn, const TorContro } } } - BOOST_FOREACH(const std::string &s, methods) { + for(const std::string &s : methods) { LogPrint("tor", "tor: Supported authentication method: %s\n", s); } // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD @@ -780,4 +779,4 @@ void StopTorControl() event_base_free(gBase); gBase = 0; } -} \ No newline at end of file +} diff --git a/src/txmempool.cpp b/src/txmempool.cpp index 26b6d67..decec42 100755 --- a/src/txmempool.cpp +++ b/src/txmempool.cpp @@ -87,14 +87,14 @@ class CBlockAverage size_t FeeSamples() const { return feeSamples.size(); } size_t GetFeeSamples(std::vector& insertInto) const { - BOOST_FOREACH (const CFeeRate& f, feeSamples) + for (const CFeeRate& f : feeSamples) insertInto.push_back(f); return feeSamples.size(); } size_t PrioritySamples() const { return prioritySamples.size(); } size_t GetPrioritySamples(std::vector& insertInto) const { - BOOST_FOREACH (double d, prioritySamples) + for (double d : prioritySamples) insertInto.push_back(d); return prioritySamples.size(); } @@ -113,7 +113,7 @@ class CBlockAverage } static bool AreSane(const std::vector& vecFee, const CFeeRate& minRelayFee) { - BOOST_FOREACH (CFeeRate fee, vecFee) { + for (CFeeRate fee : vecFee) { if (!AreSane(fee, minRelayFee)) return false; } @@ -125,7 +125,7 @@ class CBlockAverage } static bool AreSane(const std::vector vecPriority) { - BOOST_FOREACH (double priority, vecPriority) { + for (double priority : vecPriority) { if (!AreSane(priority)) return false; } @@ -224,7 +224,7 @@ class CMinerPolicyEstimator // to confirm. std::vector > entriesByConfirmations; entriesByConfirmations.resize(history.size()); - BOOST_FOREACH (const CTxMemPoolEntry& entry, entries) { + for (const CTxMemPoolEntry& entry : entries) { // How many blocks did it take for miners to include this transaction? int delta = nBlockHeight - entry.GetHeight(); if (delta <= 0) { @@ -244,7 +244,7 @@ class CMinerPolicyEstimator std::random_shuffle(e.begin(), e.end()); e.resize(10); } - BOOST_FOREACH (const CTxMemPoolEntry* entry, e) { + for (const CTxMemPoolEntry* entry : e) { // Fees are stored and reported as BTC-per-kb: CFeeRate feeRate(entry->GetFee(), entry->GetTxSize()); double dPriority = entry->GetPriority(entry->GetHeight()); // Want priority when it went IN @@ -336,7 +336,7 @@ class CMinerPolicyEstimator { fileout << nBestSeenHeight; fileout << history.size(); - BOOST_FOREACH (const CBlockAverage& entry, history) { + for (const CBlockAverage& entry : history) { entry.Write(fileout); } } @@ -467,7 +467,7 @@ void CTxMemPool::remove(const CTransaction& origTx, std::list& rem txToRemove.push_back(it->second->GetHash()); } } - BOOST_FOREACH (const CTxIn& txin, tx.vin) + for (const CTxIn& txin : tx.vin) mapNextTx.erase(txin.prevout); removed.push_back(tx); @@ -485,7 +485,7 @@ void CTxMemPool::removeCoinbaseSpends(const CCoinsViewCache* pcoins, unsigned in list transactionsToRemove; for (std::map::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) { const CTransaction& tx = it->second.GetTx(); - BOOST_FOREACH (const CTxIn& txin, tx.vin) { + for (const CTxIn& txin : tx.vin) { std::map::const_iterator it2 = mapTx.find(txin.prevout.hash); if (it2 != mapTx.end()) continue; @@ -497,7 +497,7 @@ void CTxMemPool::removeCoinbaseSpends(const CCoinsViewCache* pcoins, unsigned in } } } - BOOST_FOREACH (const CTransaction& tx, transactionsToRemove) { + for (const CTransaction& tx : transactionsToRemove) { list removed; remove(tx, removed, true); } @@ -508,7 +508,7 @@ void CTxMemPool::removeConflicts(const CTransaction& tx, std::list // Remove transactions which depend on inputs of tx, recursively list result; LOCK(cs); - BOOST_FOREACH (const CTxIn& txin, tx.vin) { + for (const CTxIn& txin : tx.vin) { auto it = mapNextTx.find(txin.prevout); if (it != mapNextTx.end()) { const CTransaction& txConflict = *it->second; @@ -526,13 +526,13 @@ void CTxMemPool::removeForBlock(const std::vector& vtx, unsigned i { LOCK(cs); std::vector entries; - BOOST_FOREACH (const CTransaction& tx, vtx) { + for (const CTransaction& tx : vtx) { uint256 hash = tx.GetHash(); if (mapTx.count(hash)) entries.push_back(mapTx[hash]); } minerPolicyEstimator->seenBlock(entries, nBlockHeight, minRelayFee); - BOOST_FOREACH (const CTransaction& tx, vtx) { + for (const CTransaction& tx : vtx) { std::list dummy; remove(tx, dummy, false); removeConflicts(tx, conflicts); @@ -568,7 +568,7 @@ void CTxMemPool::check(const CCoinsViewCache* pcoins) const checkTotal += it->second.GetTxSize(); const CTransaction& tx = it->second.GetTx(); bool fDependsWait = false; - BOOST_FOREACH (const CTxIn& txin, tx.vin) { + for (const CTxIn& txin : tx.vin) { if (tx.IsZerocoinSpend()) continue; // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's. diff --git a/src/util.cpp b/src/util.cpp index 71e7dfb..b44f596 100755 --- a/src/util.cpp +++ b/src/util.cpp @@ -82,7 +82,6 @@ #include // for startswith() and endswith() #include #include -#include #include #include #include @@ -135,7 +134,6 @@ bool fDebug = false; bool fPrintToConsole = false; bool fPrintToDebugLog = true; bool fDaemon = false; -bool fServer = false; string strMiscWarning; bool fLogTimestamps = false; bool fLogIPs = false; diff --git a/src/util.h b/src/util.h index 9dd9918..74d5c75 100755 --- a/src/util.h +++ b/src/util.h @@ -53,7 +53,6 @@ extern std::map > mapMultiArgs; extern bool fDebug; extern bool fPrintToConsole; extern bool fPrintToDebugLog; -extern bool fServer; extern std::string strMiscWarning; extern bool fLogTimestamps; extern bool fLogIPs; diff --git a/src/utilstrencodings.h b/src/utilstrencodings.h index 4e8c794..d6b4211 100755 --- a/src/utilstrencodings.h +++ b/src/utilstrencodings.h @@ -20,9 +20,6 @@ #define UEND(a) ((unsigned char*)&((&(a))[1])) #define ARRAYLEN(array) (sizeof(array) / sizeof((array)[0])) -/** This is needed because the foreach macro can't get over the comma in pair */ -#define PAIRTYPE(t1, t2) std::pair - std::string SanitizeString(const std::string& str); std::vector ParseHex(const char* psz); std::vector ParseHex(const std::string& str); diff --git a/src/db.cpp b/src/wallet/db.cpp similarity index 100% rename from src/db.cpp rename to src/wallet/db.cpp diff --git a/src/db.h b/src/wallet/db.h similarity index 100% rename from src/db.h rename to src/wallet/db.h diff --git a/src/rpcdump.cpp b/src/wallet/rpcdump.cpp similarity index 99% rename from src/rpcdump.cpp rename to src/wallet/rpcdump.cpp index cc5f9a6..8a3a977 100755 --- a/src/rpcdump.cpp +++ b/src/wallet/rpcdump.cpp @@ -7,7 +7,7 @@ #include "bip38.h" #include "init.h" #include "main.h" -#include "rpcserver.h" +#include "rpc/server.h" #include "script/script.h" #include "script/standard.h" #include "sync.h" @@ -53,7 +53,7 @@ int64_t static DecodeDumpTime(const std::string& str) std::string static EncodeDumpString(const std::string& str) { std::stringstream ret; - BOOST_FOREACH (unsigned char c, str) { + for (unsigned char c : str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { @@ -135,7 +135,7 @@ UniValue importprivkey(const UniValue& params, bool fHelp) if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); - + pwalletMain->LearnAllRelatedScripts(pubkey); // whenever a key is imported, we need to scan the whole chain diff --git a/src/rpcwallet.cpp b/src/wallet/rpcwallet.cpp similarity index 99% rename from src/rpcwallet.cpp rename to src/wallet/rpcwallet.cpp index 30e2c29..51d118f 100755 --- a/src/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -13,7 +13,7 @@ #include "init.h" #include "net.h" #include "netbase.h" -#include "rpcserver.h" +#include "rpc/server.h" #include "timedata.h" #include "util.h" #include "utilmoneystr.h" @@ -64,12 +64,12 @@ void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry) uint256 hash = wtx.GetHash(); entry.push_back(Pair("txid", hash.GetHex())); UniValue conflicts(UniValue::VARR); - BOOST_FOREACH (const uint256& conflict, wtx.GetConflicts()) + for (const uint256& conflict : wtx.GetConflicts()) conflicts.push_back(conflict.GetHex()); entry.push_back(Pair("walletconflicts", conflicts)); entry.push_back(Pair("time", wtx.GetTxTime())); entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived)); - BOOST_FOREACH (const PAIRTYPE(string, string) & item, wtx.mapValue) + for (const std::pair & item : wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } @@ -145,7 +145,7 @@ CTxDestination GetAccountDestination(string strAccount, bool bForceNew = false) it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); ++it) { const CWalletTx& wtx = (*it).second; - BOOST_FOREACH (const CTxOut& txout, wtx.vout) + for (const CTxOut& txout : wtx.vout) if (txout.scriptPubKey == scriptPubKey) bKeyUsed = true; } @@ -318,7 +318,7 @@ UniValue getaddressesbyaccount(const UniValue& params, bool fHelp) // Find all addresses that have the given account UniValue ret(UniValue::VARR); - BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, pwalletMain->mapAddressBook) { + for (const std::pair & item : pwalletMain->mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second.name; if (strName == strAccount) @@ -474,9 +474,9 @@ UniValue listaddressgroupings(const UniValue& params, bool fHelp) UniValue jsonGroupings(UniValue::VARR); map balances = pwalletMain->GetAddressBalances(); - BOOST_FOREACH (set grouping, pwalletMain->GetAddressGroupings()) { + for (set grouping : pwalletMain->GetAddressGroupings()) { UniValue jsonGrouping(UniValue::VARR); - BOOST_FOREACH (CTxDestination address, grouping) { + for (CTxDestination address : grouping) { UniValue addressInfo(UniValue::VARR); addressInfo.push_back(EncodeDestination(address)); addressInfo.push_back(ValueFromAmount(balances[address])); @@ -582,7 +582,7 @@ UniValue getreceivedbyaddress(const UniValue& params, bool fHelp) if (wtx.IsCoinBase() || !IsFinalTx(wtx)) continue; - BOOST_FOREACH (const CTxOut& txout, wtx.vout) + for (const CTxOut& txout : wtx.vout) if (txout.scriptPubKey == scriptPubKey) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; @@ -628,7 +628,7 @@ UniValue getreceivedbyaccount(const UniValue& params, bool fHelp) if (wtx.IsCoinBase() || !IsFinalTx(wtx)) continue; - BOOST_FOREACH (const CTxOut& txout, wtx.vout) { + for (const CTxOut& txout : wtx.vout) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) if (wtx.GetDepthInMainChain() >= nMinDepth) @@ -723,10 +723,10 @@ UniValue getbalance(const UniValue& params, bool fHelp) list listSent; wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount, filter); if (wtx.GetDepthInMainChain() >= nMinDepth) { - BOOST_FOREACH (const COutputEntry& r, listReceived) + for (const COutputEntry& r : listReceived) nBalance += r.amount; } - BOOST_FOREACH (const COutputEntry& s, listSent) + for (const COutputEntry& s : listSent) nBalance -= s.amount; nBalance -= allFee; } @@ -918,7 +918,7 @@ UniValue sendmany(const UniValue& params, bool fHelp) CAmount totalAmount = 0; vector keys = sendTo.getKeys(); - BOOST_FOREACH(const string& name_, keys) { + for(const string& name_ : keys) { if (!IsValidDestinationString(name_)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Ohmcoin address: ")+name_); @@ -955,7 +955,7 @@ UniValue sendmany(const UniValue& params, bool fHelp) return wtx.GetHash().GetHex(); } -// Defined in rpcmisc.cpp +// Defined in rpc/misc.cpp extern CScript _createmultisig_redeemScript(const UniValue& params); UniValue addmultisigaddress(const UniValue& params, bool fHelp) @@ -1162,7 +1162,7 @@ UniValue ListReceived(const UniValue& params, bool fByAccounts) if (nDepth < nMinDepth) continue; - BOOST_FOREACH (const CTxOut& txout, wtx.vout) { + for (const CTxOut& txout : wtx.vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) continue; @@ -1184,7 +1184,7 @@ UniValue ListReceived(const UniValue& params, bool fByAccounts) // Reply UniValue ret(UniValue::VARR); map mapAccountTally; - BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, pwalletMain->mapAddressBook) { + for (const std::pair & item : pwalletMain->mapAddressBook) { const CTxDestination& address = item.first; const string& strAccount = item.second.name; map::iterator it = mapTally.find(address); @@ -1219,7 +1219,7 @@ UniValue ListReceived(const UniValue& params, bool fByAccounts) obj.push_back(Pair("bcconfirmations", (nBCConf == std::numeric_limits::max() ? 0 : nBCConf))); UniValue transactions(UniValue::VARR); if (it != mapTally.end()) { - BOOST_FOREACH (const uint256& item, (*it).second.txids) { + for (const uint256& item : (*it).second.txids) { transactions.push_back(item.GetHex()); } } @@ -1330,7 +1330,7 @@ void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDe // Sent if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) { - BOOST_FOREACH (const COutputEntry& s, listSent) { + for (const COutputEntry& s : listSent) { UniValue entry(UniValue::VOBJ); if (involvesWatchonly || (::IsMine(*pwalletMain, s.destination) & ISMINE_WATCH_ONLY)) entry.push_back(Pair("involvesWatchonly", true)); @@ -1349,7 +1349,7 @@ void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDe // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { - BOOST_FOREACH (const COutputEntry& r, listReceived) { + for (const COutputEntry& r : listReceived) { string account; if (pwalletMain->mapAddressBook.count(r.destination)) account = pwalletMain->mapAddressBook[r.destination].name; @@ -1544,7 +1544,7 @@ UniValue listaccounts(const UniValue& params, bool fHelp) includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY; map mapAccountBalances; - BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & entry, pwalletMain->mapAddressBook) { + for (const std::pair & entry : pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first) & includeWatchonly) // This address belongs to me mapAccountBalances[entry.second.name] = 0; } @@ -1560,10 +1560,10 @@ UniValue listaccounts(const UniValue& params, bool fHelp) continue; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, includeWatchonly); mapAccountBalances[strSentAccount] -= nFee; - BOOST_FOREACH (const COutputEntry& s, listSent) + for (const COutputEntry& s : listSent) mapAccountBalances[strSentAccount] -= s.amount; if (nDepth >= nMinDepth) { - BOOST_FOREACH (const COutputEntry& r, listReceived) + for (const COutputEntry& r : listReceived) if (pwalletMain->mapAddressBook.count(r.destination)) mapAccountBalances[pwalletMain->mapAddressBook[r.destination].name] += r.amount; else @@ -1572,11 +1572,11 @@ UniValue listaccounts(const UniValue& params, bool fHelp) } const list & acentries = pwalletMain->laccentries; - BOOST_FOREACH (const CAccountingEntry& entry, acentries) + for (const CAccountingEntry& entry : acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; UniValue ret(UniValue::VOBJ); - BOOST_FOREACH (const PAIRTYPE(string, CAmount) & accountBalance, mapAccountBalances) { + for (const std::pair & accountBalance : mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; @@ -2087,7 +2087,7 @@ UniValue listlockunspent(const UniValue& params, bool fHelp) UniValue ret(UniValue::VARR); - BOOST_FOREACH (COutPoint& outpt, vOutpts) { + for (COutPoint& outpt : vOutpts) { UniValue o(UniValue::VOBJ); o.push_back(Pair("txid", outpt.hash.GetHex())); @@ -2319,7 +2319,7 @@ UniValue printAddresses() std::vector vCoins; pwalletMain->AvailableCoins(vCoins); std::map mapAddresses; - BOOST_FOREACH (const COutput& out, vCoins) { + for (const COutput& out : vCoins) { CTxDestination utxoAddress; ExtractDestination(out.tx->vout[out.i].scriptPubKey, utxoAddress); std::string strAdd = EncodeDestination(utxoAddress); @@ -3520,4 +3520,4 @@ UniValue searchdzohmc(const UniValue& params, bool fHelp) //todo: better response return "done"; -} \ No newline at end of file +} diff --git a/src/test/wallet_tests.cpp b/src/wallet/test/wallet_tests.cpp similarity index 99% rename from src/test/wallet_tests.cpp rename to src/wallet/test/wallet_tests.cpp index 90fc470..65a43b1 100755 --- a/src/test/wallet_tests.cpp +++ b/src/wallet/test/wallet_tests.cpp @@ -2,14 +2,13 @@ // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include "wallet.h" +#include "wallet/wallet.h" #include #include #include #include -#include #include // how many times to run all the tests to have a chance to catch errors that only show up with particular random shuffles @@ -52,7 +51,7 @@ static void add_coin(const CAmount& nValue, int nAge = 6*24, bool fIsFromMe = fa static void empty_wallet(void) { - BOOST_FOREACH(COutput output, vCoins) + for(COutput output : vCoins) delete output.tx; vCoins.clear(); } diff --git a/src/wallet.cpp b/src/wallet/wallet.cpp similarity index 97% rename from src/wallet.cpp rename to src/wallet/wallet.cpp index f8dfce1..e383288 100755 --- a/src/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -6,7 +6,7 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include "wallet.h" +#include "wallet/wallet.h" #include "accumulators.h" #include "base58.h" @@ -285,7 +285,7 @@ bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool anonymizeOnly { LOCK(cs_wallet); - BOOST_FOREACH (const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { + for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys) { if (!crypter.SetKeyFromPassphrase(strWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) @@ -310,7 +310,7 @@ bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, CCrypter crypter; CKeyingMaterial vMasterKey; - BOOST_FOREACH (MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { + for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys) { if (!crypter.SetKeyFromPassphrase(strOldWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) @@ -401,7 +401,7 @@ set CWallet::GetConflicts(const uint256& txid) const std::pair range; - BOOST_FOREACH (const CTxIn& txin, wtx.vin) { + for (const CTxIn& txin : wtx.vin) { if (mapTxSpends.count(txin.prevout) <= 1 || wtx.IsZerocoinSpend()) continue; // No conflict if zero or one spends range = mapTxSpends.equal_range(txin.prevout); @@ -478,7 +478,7 @@ void CWallet::AddToSpends(const uint256& wtxid) if (thisTx.IsCoinBase()) // Coinbases don't spend anything! return; - BOOST_FOREACH (const CTxIn& txin, thisTx.vin) + for (const CTxIn& txin : thisTx.vin) AddToSpends(txin.prevout, wtxid); } @@ -509,7 +509,7 @@ bool CWallet::GetKarmanodeVinAndKeys(CTxIn& txinRet, CPubKey& pubKeyRet, CKey& k return false; } - BOOST_FOREACH (COutput& out, vPossibleCoins) + for (COutput& out : vPossibleCoins) if (out.tx->GetHash() == txHash && out.i == nOutputIndex) // found it! return GetVinAndKeysFromOutput(out, txinRet, pubKeyRet, keyRet); @@ -648,7 +648,7 @@ void CWallet::MarkDirty() { { LOCK(cs_wallet); - BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) + for (std::pair & item : mapWallet) item.second.MarkDirty(); } } @@ -674,6 +674,7 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet) if (!wtx.nTimeReceived) wtx.nTimeReceived = GetAdjustedTime(); wtx.nOrderPos = IncOrderPosNext(); + wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0))); wtx.nTimeSmart = ComputeTimeSmart(wtx); AddToSpends(hash); @@ -756,7 +757,7 @@ void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock) // If a transaction changes 'conflicted' state, that changes the balance // available of the outputs it spends. So force those to be // recomputed, also: - BOOST_FOREACH (const CTxIn& txin, tx.vin) { + for (const CTxIn& txin : tx.vin) { if (!tx.IsZerocoinSpend() && mapWallet.count(txin.prevout.hash)) mapWallet[txin.prevout.hash].MarkDirty(); } @@ -855,7 +856,7 @@ int CWallet::GetRealInputObfuscationRounds(CTxIn in, int rounds) const } bool fAllDenoms = true; - BOOST_FOREACH (CTxOut out, wtx->vout) { + for (CTxOut out : wtx->vout) { fAllDenoms = fAllDenoms && IsDenominatedAmount(out.nValue); } // this one is denominated but there is another non-denominated output found in the same tx @@ -868,7 +869,7 @@ int CWallet::GetRealInputObfuscationRounds(CTxIn in, int rounds) const int nShortest = -10; // an initial value, should be no way to get this by calculations bool fDenomFound = false; // only denoms here so let's look up - BOOST_FOREACH (CTxIn in2, wtx->vin) { + for (CTxIn in2 : wtx->vin) { if (IsMine(in2)) { int n = GetRealInputObfuscationRounds(in2, rounds + 1); // denom found, find the shortest chain or initially assign nShortest with the first found value @@ -915,7 +916,7 @@ bool CWallet::IsDenominated(const CTransaction& tx) const Return false if ANY inputs are non-denom */ bool ret = true; - BOOST_FOREACH (const CTxIn& txin, tx.vin) { + for (const CTxIn& txin : tx.vin) { if (!IsDenominated(txin)) { ret = false; } @@ -926,7 +927,7 @@ bool CWallet::IsDenominated(const CTransaction& tx) const bool CWallet::IsDenominatedAmount(CAmount nInputAmount) const { - BOOST_FOREACH (CAmount d, obfuScationDenominations) + for (CAmount d : obfuScationDenominations) if (nInputAmount == d) return true; return false; @@ -1220,7 +1221,7 @@ CAmount CWalletTx::GetLockedCredit() const } // Add karmanode collaterals which are handled likc locked coins - if (fMasterNode && vout[i].nValue == 10000 * COIN) { + else if (fMasterNode && vout[i].nValue == 10000 * COIN) { nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE); } @@ -1339,7 +1340,7 @@ CAmount CWalletTx::GetLockedWatchOnlyCredit() const } // Add karmanode collaterals which are handled likc locked coins - if (fMasterNode && vout[i].nValue == 10000 * COIN) { + else if (fMasterNode && vout[i].nValue == 10000 * COIN) { nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY); } @@ -1417,13 +1418,13 @@ void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived, GetAmounts(listReceived, listSent, allFee, strSentAccount, filter); if (strAccount == strSentAccount) { - BOOST_FOREACH (const COutputEntry& s, listSent) + for (const COutputEntry& s : listSent) nSent += s.amount; nFee = allFee; } { LOCK(pwallet->cs_wallet); - BOOST_FOREACH (const COutputEntry& r, listReceived) { + for (const COutputEntry& r : listReceived) { if (pwallet->mapAddressBook.count(r.destination)) { map::const_iterator mi = pwallet->mapAddressBook.find(r.destination); if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount) @@ -1446,7 +1447,7 @@ bool CWalletTx::WriteToDisk() * from or to us. If fUpdate is true, found transactions that already * exist in the wallet will be updated. */ -int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) +int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate, bool fromStartup) { int ret = 0; int64_t nNow = GetTime(); @@ -1472,9 +1473,14 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0) ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100)))); + if (fromStartup && ShutdownRequested()) { + return -1; + } + + CBlock block; ReadBlockFromDisk(block, pindex); - BOOST_FOREACH (CTransaction& tx, block.vtx) { + for (CTransaction& tx : block.vtx) { if (AddToWalletIfInvolvingMe(tx, &block, fUpdate)) ret++; } @@ -1539,7 +1545,7 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) void CWallet::ReacceptWalletTransactions() { LOCK2(cs_main, cs_wallet); - BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) { + for (std::pair & item : mapWallet) { const uint256& wtxid = item.first; CWalletTx& wtx = item.second; assert(wtx.GetHash() == wtxid); @@ -1615,14 +1621,14 @@ void CWallet::ResendWalletTransactions() LOCK(cs_wallet); // Sort them in chronological order multimap mapSorted; - BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) { + for (std::pair & item : mapWallet) { CWalletTx& wtx = item.second; // Don't rebroadcast until it's had plenty of time that // it should have gotten in already by now. if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60) mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); } - BOOST_FOREACH (PAIRTYPE(const unsigned int, CWalletTx*) & item, mapSorted) { + for (std::pair & item : mapSorted) { CWalletTx& wtx = *item.second; wtx.RelayWalletTransaction(); } @@ -2021,7 +2027,7 @@ map > CWallet::AvailableCoinsByAddress(bool fCon AvailableCoins(vCoins, fConfirmed); map > mapCoins; - BOOST_FOREACH (COutput out, vCoins) { + for (COutput out : vCoins) { if (maxCoinValue > 0 && out.tx->vout[out.i].nValue > maxCoinValue) continue; @@ -2084,7 +2090,7 @@ bool less_then_denom(const COutput& out1, const COutput& out2) bool found1 = false; bool found2 = false; - BOOST_FOREACH (CAmount d, obfuScationDenominations) // loop through predefined denoms + for (CAmount d : obfuScationDenominations) // loop through predefined denoms { if (pcoin1->vout[out1.i].nValue == d) found1 = true; if (pcoin2->vout[out2.i].nValue == d) found2 = true; @@ -2196,7 +2202,7 @@ bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int if (fDebug) LogPrint("selectcoins", "tryDenom: %d\n", tryDenom); vValue.clear(); nTotalLower = 0; - BOOST_FOREACH (const COutput& output, vCoins) { + for (const COutput& output : vCoins) { if (!output.fSpendable) continue; @@ -2296,7 +2302,7 @@ bool CWallet::SelectCoins(const CAmount& nTargetValue, set return all selected outputs (we want all selected to go into the transaction for sure) if (coinControl && coinControl->HasSelected()) { - BOOST_FOREACH (const COutput& out, vCoins) { + for (const COutput& out : vCoins) { if (!out.fSpendable) continue; @@ -2316,8 +2322,8 @@ bool CWallet::SelectCoins(const CAmount& nTargetValue, setvout[out.i].nValue == v //make sure it's the denom we're looking for && nValueRet + out.tx->vout[out.i].nValue < nTargetValue + (0.1 * COIN) + 100 //round the amount up to .1 OHMC over ) { @@ -2373,7 +2379,7 @@ bool CWallet::SelectCoinsByDenominations(int nDenom, CAmount nValueMin, CAmount if (!(nDenom & (1 << 4))) fFound1 = true; if (!(nDenom & (1 << 5))) fFoundDot1 = true; - BOOST_FOREACH (const COutput& out, vCoins) { + for (const COutput& out : vCoins) { // karmanode-like input should not be selected by AvailableCoins now anyway //if(out.tx->vout[out.i].nValue == 10000*COIN) continue; if (nValueRet + out.tx->vout[out.i].nValue <= nValueMax) { @@ -2466,7 +2472,7 @@ bool CWallet::SelectCoinsDark(CAmount nValueMin, CAmount nValueMax, std::vector< //order the array so largest nondenom are first, then denominations, then very small inputs. sort(vCoins.rbegin(), vCoins.rend(), CompareByPriority()); - BOOST_FOREACH (const COutput& out, vCoins) { + for (const COutput& out : vCoins) { //do not allow inputs less than 1 CENT if (out.tx->vout[out.i].nValue < CENT) continue; //do not allow collaterals to be selected @@ -2503,7 +2509,7 @@ bool CWallet::SelectCoinsCollateral(std::vector& setCoinsRet, CAmount& //LogPrintf("found coins %d\n", (int)vCoins.size()); - BOOST_FOREACH (const COutput& out, vCoins) { + for (const COutput& out : vCoins) { // collateral inputs will always be a multiple of DARSEND_COLLATERAL, up to five if (IsCollateralAmount(out.tx->vout[out.i].nValue)) { CTxIn vin = CTxIn(out.tx->GetHash(), out.i); @@ -2556,7 +2562,7 @@ bool CWallet::HasCollateralInputs(bool fOnlyConfirmed) const AvailableCoins(vCoins, fOnlyConfirmed); int nFound = 0; - BOOST_FOREACH (const COutput& out, vCoins) + for (const COutput& out : vCoins) if (IsCollateralAmount(out.tx->vout[out.i].nValue)) nFound++; return nFound > 0; @@ -2602,7 +2608,7 @@ bool CWallet::CreateCollateralTransaction(CMutableTransaction& txCollateral, std int vinNumber = 0; bool success = true; - BOOST_FOREACH (CTxPair v, vCoinsCollateral) { + for (CTxPair v : vCoinsCollateral) { txCollateral.vin.push_back(v.vin); if (!SignSignature(*this, v.vin.prevPubKey, txCollateral, vinNumber, v.prevout.nValue, int(SIGHASH_ALL | SIGHASH_ANYONECANPAY))) { success = false; @@ -2613,7 +2619,7 @@ bool CWallet::CreateCollateralTransaction(CMutableTransaction& txCollateral, std // if signing was not successful, unlock the inputs if (!success) { - BOOST_FOREACH (CTxPair v, vCoinsCollateral) + for (CTxPair v : vCoinsCollateral) UnlockCoin(v.vin.prevout); strReason = "CObfuscationPool::Sign - Unable to sign collateral transaction! \n"; @@ -2650,7 +2656,7 @@ bool CWallet::GetBudgetSystemCollateralTX(CWalletTx& tx, uint256 hash, bool useI bool CWallet::ConvertList(std::vector vCoins, std::vector& vecAmounts) { - BOOST_FOREACH (CTxIn i, vCoins) { + for (CTxIn i : vCoins) { if (mapWallet.count(i.prevout.hash)) { CWalletTx& wtx = mapWallet[i.prevout.hash]; if (i.prevout.n < wtx.vout.size()) { @@ -2742,7 +2748,7 @@ bool CWallet::CreateTransactionHelper(const std::vector & s : vecSend) { if (nValue < 0) { strFailReason = _("Transaction amounts must be positive"); return false; @@ -2776,7 +2782,7 @@ bool CWallet::CreateTransactionHelper(const std::vectorfSplitBlock) { - BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) { + for (const std::pair & s : vecSend) { CTxOut txout(s.second, s.first); if (txout.IsDust(::minRelayTxFee)) { strFailReason = _("Transaction amount too small"); @@ -2793,7 +2799,7 @@ bool CWallet::CreateTransactionHelper(const std::vector & s : vecSend) { for (int i = 0; i < nSplitBlock; i++) { if (i == nSplitBlock - 1) { uint64_t nRemainder = s.second % nSplitBlock; @@ -2828,7 +2834,7 @@ bool CWallet::CreateTransactionHelper(const std::vector pcoin : setCoins) { CAmount nCredit = pcoin.first->vout[pcoin.second].nValue; //The coin age after the next block (depth+1) is used instead of the current, //reflecting an assumption the user would accept a bit more delay for @@ -2910,13 +2916,13 @@ bool CWallet::CreateTransactionHelper(const std::vector & coin : setCoins) txNew.vin.push_back(CTxIn(coin.first->GetHash(), coin.second)); // Sign int nIn = 0; CTransaction txNewConst(txNew); - BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) + for(const std::pair & coin : setCoins) { const CScript& scriptPubKey = coin.first->vout[coin.second].scriptPubKey; SignatureData sigdata; @@ -3035,7 +3041,7 @@ bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int if (GetAdjustedTime() <= chainActive.Tip()->nTime) MilliSleep(10000); - BOOST_FOREACH (PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setStakeCoins) { + for (std::pair pcoin : setStakeCoins) { //make sure that enough time has elapsed between CBlockIndex* pindex = NULL; BlockMap::iterator it = mapBlockIndex.find(pcoin.first->hashBlock); @@ -3157,7 +3163,7 @@ bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int // Sign int nIn = 0; - BOOST_FOREACH (const CWalletTx* pcoin, vwtxPrev) { + for (const CWalletTx* pcoin : vwtxPrev) { if (!SignSignature(*this, *pcoin, txNew, nIn++, SIGHASH_ALL)) return error("CreateCoinStake : failed to sign coinstake"); } @@ -3194,7 +3200,7 @@ bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, std: // Notify that old coins are spent if (!wtxNew.IsZerocoinSpend()) { set updated_hahes; - BOOST_FOREACH (const CTxIn& txin, wtxNew.vin) { + for (const CTxIn& txin : wtxNew.vin) { // notify only once if (updated_hahes.find(txin.prevout.hash) != updated_hahes.end()) continue; @@ -3262,7 +3268,7 @@ CAmount CWallet::GetTotalValue(std::vector vCoins) { CAmount nTotalValue = 0; CWalletTx wtx; - BOOST_FOREACH (CTxIn i, vCoins) { + for (CTxIn i : vCoins) { if (mapWallet.count(i.prevout.hash)) { CWalletTx& wtx = mapWallet[i.prevout.hash]; if (i.prevout.n < wtx.vout.size()) { @@ -3305,7 +3311,7 @@ string CWallet::PrepareObfuscationDenominate(int minRounds, int maxRounds) { LOCK(cs_wallet); - BOOST_FOREACH (CTxIn v, vCoins) + for (CTxIn v : vCoins) LockCoin(v.prevout); } @@ -3323,7 +3329,7 @@ string CWallet::PrepareObfuscationDenominate(int minRounds, int maxRounds) int nStep = 0; int nStepsMax = 5 + GetRandInt(5); while (nStep < nStepsMax) { - BOOST_FOREACH (CAmount v, obfuScationDenominations) { + for (CAmount v : obfuScationDenominations) { // only use the ones that are approved bool fAccepted = false; if ((obfuScationPool.sessionDenom & (1 << 0)) && v == ((10000 * COIN) + 10000000)) { @@ -3385,14 +3391,14 @@ string CWallet::PrepareObfuscationDenominate(int minRounds, int maxRounds) { // unlock unused coins LOCK(cs_wallet); - BOOST_FOREACH (CTxIn v, vCoins) + for (CTxIn v : vCoins) UnlockCoin(v.prevout); } if (obfuScationPool.GetDenominations(vOut) != obfuScationPool.sessionDenom) { // unlock used coins on failure LOCK(cs_wallet); - BOOST_FOREACH (CTxIn v, vCoinsResult) + for (CTxIn v : vCoinsResult) UnlockCoin(v.prevout); return "Error: can't make current denominated outputs"; } @@ -3481,7 +3487,7 @@ bool CWallet::DelAddressBook(const CTxDestination& address) if (fFileBacked) { // Delete destdata tuples associated with address std::string strAddress = EncodeDestination(address); - BOOST_FOREACH (const PAIRTYPE(string, string) & item, mapAddressBook[address].destdata) { + for (const std::pair & item : mapAddressBook[address].destdata) { CWalletDB(strWalletFile).EraseDestData(strAddress, item.first); } } @@ -3515,7 +3521,7 @@ bool CWallet::NewKeyPool() { LOCK(cs_wallet); CWalletDB walletdb(strWalletFile); - BOOST_FOREACH (int64_t nIndex, setKeyPool) + for (int64_t nIndex : setKeyPool) walletdb.ErasePool(nIndex); setKeyPool.clear(); @@ -3648,7 +3654,7 @@ std::map CWallet::GetAddressBalances() { LOCK(cs_wallet); - BOOST_FOREACH (PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { + for (std::pair walletEntry : mapWallet) { CWalletTx* pcoin = &walletEntry.second; if (!IsFinalTx(*pcoin) || !pcoin->IsTrusted()) @@ -3686,13 +3692,13 @@ set > CWallet::GetAddressGroupings() set > groupings; set grouping; - BOOST_FOREACH (PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { + for (std::pair walletEntry : mapWallet) { CWalletTx* pcoin = &walletEntry.second; if (pcoin->vin.size() > 0) { bool any_mine = false; // group all input addresses with each other - BOOST_FOREACH (CTxIn txin, pcoin->vin) { + for (CTxIn txin : pcoin->vin) { CTxDestination address; if (!IsMine(txin)) /* If this input isn't mine, ignore it */ continue; @@ -3704,7 +3710,7 @@ set > CWallet::GetAddressGroupings() // group change with input addresses if (any_mine) { - BOOST_FOREACH (CTxOut txout, pcoin->vout) + for (CTxOut txout : pcoin->vout) if (IsChange(txout)) { CTxDestination txoutAddr; if (!ExtractDestination(txout.scriptPubKey, txoutAddr)) @@ -3732,17 +3738,17 @@ set > CWallet::GetAddressGroupings() set*> uniqueGroupings; // a set of pointers to groups of addresses map*> setmap; // map addresses to the unique group containing it - BOOST_FOREACH (set grouping, groupings) { + for (set grouping : groupings) { // make a set of all the groups hit by this new group set*> hits; map*>::iterator it; - BOOST_FOREACH (CTxDestination address, grouping) + for (CTxDestination address : grouping) if ((it = setmap.find(address)) != setmap.end()) hits.insert((*it).second); // merge all hit groups into a new single group and delete old groups set* merged = new set(grouping); - BOOST_FOREACH (set* hit, hits) { + for (set* hit : hits) { merged->insert(hit->begin(), hit->end()); uniqueGroupings.erase(hit); delete hit; @@ -3750,12 +3756,12 @@ set > CWallet::GetAddressGroupings() uniqueGroupings.insert(merged); // update setmap - BOOST_FOREACH (CTxDestination element, *merged) + for (CTxDestination element : *merged) setmap[element] = merged; } set > ret; - BOOST_FOREACH (set* uniqueGrouping, uniqueGroupings) { + for (set* uniqueGrouping : uniqueGroupings) { ret.insert(*uniqueGrouping); delete uniqueGrouping; } @@ -3767,7 +3773,7 @@ set CWallet::GetAccountAddresses(string strAccount) const { LOCK(cs_wallet); set result; - BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, mapAddressBook) { + for (const std::pair & item : mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second.name; if (strName == strAccount) @@ -3815,7 +3821,7 @@ void CWallet::GetAllReserveKeys(set& setAddress) const CWalletDB walletdb(strWalletFile); LOCK2(cs_main, cs_wallet); - BOOST_FOREACH (const int64_t& id, setKeyPool) { + for (const int64_t& id : setKeyPool) { CKeyPool keypool; if (!walletdb.ReadPool(id, keypool)) throw runtime_error("GetAllReserveKeyHashes() : read failed"); @@ -3894,7 +3900,7 @@ class CAffectedKeysVisitor : public boost::static_visitor std::vector vDest; int nRequired; if (ExtractDestinations(script, type, vDest, nRequired)) { - BOOST_FOREACH (const CTxDestination& dest, vDest) + for (const CTxDestination& dest : vDest) boost::apply_visitor(*this, dest); } } @@ -3949,7 +3955,7 @@ void CWallet::GetKeyBirthTimes(std::map& mapKeyBirth) const std::map mapKeyFirstBlock; std::set setKeys; GetKeys(setKeys); - BOOST_FOREACH (const CKeyID& keyid, setKeys) { + for (const CKeyID& keyid : setKeys) { if (mapKeyBirth.count(keyid) == 0) mapKeyFirstBlock[keyid] = pindexMax; } @@ -3968,10 +3974,10 @@ void CWallet::GetKeyBirthTimes(std::map& mapKeyBirth) const if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) { // ... which are already in a block int nHeight = blit->second->nHeight; - BOOST_FOREACH (const CTxOut& txout, wtx.vout) { + for (const CTxOut& txout : wtx.vout) { // iterate over all their outputs CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey); - BOOST_FOREACH (const CKeyID& keyid, vAffected) { + for (const CKeyID& keyid : vAffected) { // ... and all their affected keys std::map::iterator rit = mapKeyFirstBlock.find(keyid); if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight) @@ -4195,7 +4201,7 @@ void CWallet::AutoCombineDust() //find karmanode rewards that need to be combined CCoinControl* coinControl = new CCoinControl(); CAmount nTotalRewardsValue = 0; - BOOST_FOREACH (const COutput& out, vCoins) { + for (const COutput& out : vCoins) { if (!out.fSpendable) continue; //no coins should get this far if they dont have proper maturity, this is double checking @@ -5246,11 +5252,10 @@ void CWallet::ReconsiderZerocoins(std::list& listMintsRestored, s string CWallet::GetUniqueWalletBackupName(bool fzohmcAuto) const { - posix_time::ptime timeLocal = posix_time::second_clock::local_time(); stringstream ssDateTime; + std::string strWalletBackupName = strprintf("%s", DateTimeStrFormat(".%Y-%m-%d-%H-%M", GetTime())); + ssDateTime << strWalletBackupName; - - ssDateTime << gregorian::to_iso_extended_string(timeLocal.date()) << "-" << timeLocal.time_of_day(); return strprintf("wallet%s.dat%s", fzohmcAuto ? "-autozohmcbackup" : "", DateTimeStrFormat(".%Y-%m-%d-%H-%M", GetTime())); } diff --git a/src/wallet.h b/src/wallet/wallet.h similarity index 99% rename from src/wallet.h rename to src/wallet/wallet.h index 272a2ab..936f79a 100755 --- a/src/wallet.h +++ b/src/wallet/wallet.h @@ -21,8 +21,8 @@ #include "ui_interface.h" #include "util.h" #include "validationinterface.h" -#include "wallet_ismine.h" -#include "walletdb.h" +#include "wallet/wallet_ismine.h" +#include "wallet/walletdb.h" #include "zohmctracker.h" #include "zohmcwallet.h" @@ -331,7 +331,7 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface fBackupMints = false; // Stake Settings - nHashDrift = 45; + nHashDrift = 30; nStakeSplitThreshold = 500; nHashInterval = 22; nStakeSetUpdateTime = 300; // 5 minutes @@ -518,7 +518,7 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface void SyncTransaction(const CTransaction& tx, const CBlock* pblock); bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate); void EraseFromWallet(const uint256& hash); - int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false); + int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false, bool fromStartup = false); void ReacceptWalletTransactions(); void ResendWalletTransactions(); CAmount GetBalance() const; @@ -613,7 +613,7 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface } bool IsMine(const CTransaction& tx) const { - BOOST_FOREACH (const CTxOut& txout, tx.vout) + for (const CTxOut& txout : tx.vout) if (IsMine(txout)) return true; return false; @@ -626,7 +626,7 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const { CAmount nDebit = 0; - BOOST_FOREACH (const CTxIn& txin, tx.vin) { + for (const CTxIn& txin : tx.vin) { nDebit += GetDebit(txin, filter); if (!MoneyRange(nDebit)) throw std::runtime_error("CWallet::GetDebit() : value out of range"); @@ -636,7 +636,7 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const { CAmount nCredit = 0; - BOOST_FOREACH (const CTxOut& txout, tx.vout) { + for (const CTxOut& txout : tx.vout) { nCredit += GetCredit(txout, filter); if (!MoneyRange(nCredit)) throw std::runtime_error("CWallet::GetCredit() : value out of range"); @@ -646,7 +646,7 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface CAmount GetChange(const CTransaction& tx) const { CAmount nChange = 0; - BOOST_FOREACH (const CTxOut& txout, tx.vout) { + for (const CTxOut& txout : tx.vout) { nChange += GetChange(txout); if (!MoneyRange(nChange)) throw std::runtime_error("CWallet::GetChange() : value out of range"); @@ -1072,7 +1072,7 @@ class CWalletTx : public CMerkleTx return false; // Trusted if all inputs are from us and are in the mempool: - BOOST_FOREACH (const CTxIn& txin, vin) { + for (const CTxIn& txin : vin) { // Transactions not sent by us: not trusted const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash); if (parent == NULL) @@ -1114,7 +1114,7 @@ class COutput //Used with Obfuscation. Will return largest nondenom, then denominations, then very small inputs int Priority() const { - BOOST_FOREACH (CAmount d, obfuScationDenominations) + for (CAmount d : obfuScationDenominations) if (tx->vout[i].nValue == d) return 10000; if (tx->vout[i].nValue < 1 * COIN) return 20000; @@ -1279,4 +1279,4 @@ class CAccountingEntry std::vector _ssExtra; }; -#endif // BITCOIN_WALLET_H \ No newline at end of file +#endif // BITCOIN_WALLET_H diff --git a/src/wallet_ismine.cpp b/src/wallet/wallet_ismine.cpp similarity index 99% rename from src/wallet_ismine.cpp rename to src/wallet/wallet_ismine.cpp index 19e23c3..eff796b 100755 --- a/src/wallet_ismine.cpp +++ b/src/wallet/wallet_ismine.cpp @@ -11,8 +11,6 @@ #include "script/standard.h" #include "script/sign.h" -#include - typedef std::vector valtype; unsigned int HaveKeys(const std::vector& pubkeys, const CKeyStore& keystore) @@ -155,4 +153,4 @@ isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey, bool& return ProduceSignature(DummySignatureCreator(&keystore), scriptPubKey, sigs) ? ISMINE_WATCH_SOLVABLE : ISMINE_WATCH_UNSOLVABLE; } return ISMINE_NO; -} \ No newline at end of file +} diff --git a/src/wallet_ismine.h b/src/wallet/wallet_ismine.h similarity index 100% rename from src/wallet_ismine.h rename to src/wallet/wallet_ismine.h diff --git a/src/walletdb.cpp b/src/wallet/walletdb.cpp similarity index 99% rename from src/walletdb.cpp rename to src/wallet/walletdb.cpp index 11e9408..414b420 100755 --- a/src/walletdb.cpp +++ b/src/wallet/walletdb.cpp @@ -5,7 +5,7 @@ // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include "walletdb.h" +#include "wallet/walletdb.h" #include "base58.h" #include "consensus/validation.h" @@ -20,7 +20,6 @@ #include "primitives/deterministicmint.h" #include -#include #include #include #include @@ -290,7 +289,7 @@ CAmount CWalletDB::GetAccountCreditDebit(const string& strAccount) ListAccountCreditDebit(strAccount, entries); CAmount nCreditDebit = 0; - BOOST_FOREACH (const CAccountingEntry& entry, entries) + for (const CAccountingEntry& entry : entries) nCreditDebit += entry.nCreditDebit; return nCreditDebit; @@ -354,7 +353,7 @@ DBErrors CWalletDB::ReorderTransactions(CWallet* pwallet) } list acentries; ListAccountCreditDebit("", acentries); - BOOST_FOREACH (CAccountingEntry& entry, acentries) { + for (CAccountingEntry& entry : acentries) { txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry))); } @@ -377,7 +376,7 @@ DBErrors CWalletDB::ReorderTransactions(CWallet* pwallet) return DB_LOAD_FAIL; } else { int64_t nOrderPosOff = 0; - BOOST_FOREACH (const int64_t& nOffsetStart, nOrderPosOffsets) { + for (const int64_t& nOffsetStart : nOrderPosOffsets) { if (nOrderPos >= nOffsetStart) ++nOrderPosOff; } @@ -751,7 +750,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet) if ((wss.nKeys + wss.nCKeys) != wss.nKeyMeta) pwallet->nTimeFirstKey = 1; // 0 would be considered 'no value' - BOOST_FOREACH (uint256 hash, wss.vWalletUpgrade) + for (uint256 hash : wss.vWalletUpgrade) WriteTx(hash, pwallet->mapWallet[hash]); // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc: @@ -766,7 +765,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet) pwallet->laccentries.clear(); ListAccountCreditDebit("*", pwallet->laccentries); - BOOST_FOREACH(CAccountingEntry& entry, pwallet->laccentries) { + for(CAccountingEntry& entry : pwallet->laccentries) { pwallet->wtxOrdered.insert(make_pair(entry.nOrderPos, CWallet::TxPair((CWalletTx*)0, &entry))); } @@ -842,7 +841,7 @@ DBErrors CWalletDB::ZapWalletTx(CWallet* pwallet, vector& vWtx) return err; // erase each wallet TX - BOOST_FOREACH (uint256& hash, vTxHash) { + for (uint256& hash : vTxHash) { if (!EraseTx(hash)) return DB_CORRUPT; } @@ -1091,7 +1090,7 @@ bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys) CWalletScanState wss; DbTxn* ptxn = dbenv.TxnBegin(); - BOOST_FOREACH (CDBEnv::KeyValPair& row, salvagedData) { + for (CDBEnv::KeyValPair& row : salvagedData) { if (fOnlyKeys) { CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION); CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION); diff --git a/src/walletdb.h b/src/wallet/walletdb.h similarity index 99% rename from src/walletdb.h rename to src/wallet/walletdb.h index 2d838bb..5dd0907 100755 --- a/src/walletdb.h +++ b/src/wallet/walletdb.h @@ -10,7 +10,7 @@ #include "amount.h" #include "primitives/transaction.h" -#include "db.h" +#include "wallet/db.h" #include "key.h" #include "keystore.h" #include "primitives/zerocoin.h" diff --git a/src/zohmctracker.cpp b/src/zohmctracker.cpp index d182e6a..b315279 100644 --- a/src/zohmctracker.cpp +++ b/src/zohmctracker.cpp @@ -8,7 +8,7 @@ #include "sync.h" #include "main.h" #include "txdb.h" -#include "walletdb.h" +#include "wallet/walletdb.h" #include "accumulators.h" using namespace std; diff --git a/src/zohmcwallet.cpp b/src/zohmcwallet.cpp index 139eb45..9510a53 100644 --- a/src/zohmcwallet.cpp +++ b/src/zohmcwallet.cpp @@ -5,9 +5,9 @@ #include "zohmcwallet.h" #include "main.h" #include "txdb.h" -#include "walletdb.h" +#include "wallet/walletdb.h" #include "init.h" -#include "wallet.h" +#include "wallet/wallet.h" #include "primitives/deterministicmint.h" using namespace libzerocoin; @@ -327,7 +327,7 @@ bool CzOHMCWallet::SetMintSeen(const CBigNum& bnValue, const int& nHeight, const // Add to zohmcTracker which also adds to database pwalletMain->zohmcTracker->Add(dMint, true); - + //Update the count if it is less than the mint's count if (nCountLastUsed < pMint.second) { CWalletDB walletdb(strWalletFile);