diff --git a/.gitignore b/.gitignore index 03f81cc82..a3f474a14 100644 --- a/.gitignore +++ b/.gitignore @@ -118,6 +118,14 @@ src/komodo-cli.exe src/komodod.exe src/komodo-tx.exe +src/hush-cli +src/hushd +src/hush-tx +src/hush-test +src/hush-cli.exe +src/hushd.exe +src/hush-tx.exe + #output during builds, symbol tables? *.dSYM diff --git a/Makefile.am b/Makefile.am index 7b4d44e2d..90085c5e2 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1,3 +1,7 @@ +# Copyright 2016-2021 The Hush developers +# Distributed under the GPLv3 software license, see the accompanying +# file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html + ACLOCAL_AMFLAGS = -I build-aux/m4 SUBDIRS = src if ENABLE_MAN diff --git a/asmap.dat b/asmap.dat new file mode 100644 index 000000000..aaf3fdada Binary files /dev/null and b/asmap.dat differ diff --git a/autogen.sh b/autogen.sh index 3e26a1830..6932fae53 100755 --- a/autogen.sh +++ b/autogen.sh @@ -1,4 +1,7 @@ #!/bin/sh +# Copyright (c) 2016-2021 The Hush developers +# Distributed under the GPLv3 software license, see the accompanying +# file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html set -e srcdir="$(dirname $0)" cd "$srcdir" diff --git a/configure.ac b/configure.ac index 526ad358d..4f369aebd 100644 --- a/configure.ac +++ b/configure.ac @@ -1,7 +1,7 @@ dnl require autoconf 2.60 (AS_ECHO/AS_ECHO_N) AC_PREREQ([2.60]) define(_CLIENT_VERSION_MAJOR, 3) -define(_CLIENT_VERSION_MINOR, 7) +define(_CLIENT_VERSION_MINOR, 8) define(_CLIENT_VERSION_REVISION, 1) define(_CLIENT_VERSION_BUILD, 50) define(_ZC_BUILD_VAL, m4_if(m4_eval(_CLIENT_VERSION_BUILD < 25), 1, m4_incr(_CLIENT_VERSION_BUILD), m4_eval(_CLIENT_VERSION_BUILD < 50), 1, m4_eval(_CLIENT_VERSION_BUILD - 24), m4_eval(_CLIENT_VERSION_BUILD == 50), 1, , m4_eval(_CLIENT_VERSION_BUILD - 50))) @@ -14,9 +14,9 @@ AC_CONFIG_HEADERS([src/config/bitcoin-config.h]) AC_CONFIG_AUX_DIR([build-aux]) AC_CONFIG_MACRO_DIR([build-aux/m4]) -BITCOIN_DAEMON_NAME=komodod -BITCOIN_CLI_NAME=komodo-cli -BITCOIN_TX_NAME=komodo-tx +BITCOIN_DAEMON_NAME=hushd +BITCOIN_CLI_NAME=hush-cli +BITCOIN_TX_NAME=hush-tx dnl Unless the user specified ARFLAGS, force it to be cr AC_ARG_VAR(ARFLAGS, [Flags for the archiver, defaults to if not set]) @@ -231,7 +231,7 @@ CPPFLAGS="$CPPFLAGS -DHAVE_BUILD_INFO -D__STDC_FORMAT_MACROS" AC_ARG_WITH([utils], [AS_HELP_STRING([--with-utils], - [build komodo-cli komodo-tx wallet-utility (default=yes)])], + [build hush-cli hush-tx wallet-utility (default=yes)])], [build_bitcoin_utils=$withval], [build_bitcoin_utils=yes]) @@ -766,11 +766,11 @@ AX_CHECK_COMPILE_FLAG([-Wno-builtin-declaration-mismatch],[CXXFLAGS="$CXXFLAGS - LIBZCASH_LIBS="-lgmp -lgmpxx $BOOST_SYSTEM_LIB -lwolfssl -lsodium $RUST_LIBS" -AC_MSG_CHECKING([whether to build komodod]) +AC_MSG_CHECKING([whether to build hushd]) AM_CONDITIONAL([BUILD_BITCOIND], [test x$build_bitcoind = xyes]) AC_MSG_RESULT($build_bitcoind) -AC_MSG_CHECKING([whether to build utils (komodo-cli komodo-tx wallet-utility)]) +AC_MSG_CHECKING([whether to build utils (hush-cli hush-tx wallet-utility)]) AM_CONDITIONAL([BUILD_BITCOIN_UTILS], [test x$build_bitcoin_utils = xyes]) AC_MSG_RESULT($build_bitcoin_utils) diff --git a/doc/developer-notes.md b/doc/developer-notes.md index c22ae3fe8..26be1e262 100644 --- a/doc/developer-notes.md +++ b/doc/developer-notes.md @@ -1,5 +1,86 @@ -Coding -==================== +# Fresh sync + +Many times, you will want to do a "fresh sync" test, to verify code works when syncing from the genesis block, which is a different code path than a "partial sync" which means you already have part of blockchain history and are "catching up" to get in sync. + +A "fresh sync" goes thru the Initial Blockchain Download (IBD) optimized codepath and is often faster than than rescanning all of history. Fresh sync and partial sync testing any important change should be done for all important changes. + +A fresh sync preserves peers.dat, so it will always be faster than a "fresh clone", which has to learn enough p2p peers to being syncing, which can often add many minutes to completing a sync. When code related to peers.dat changes (such in the `p2p` branch) then doing a fresh clone is needed to fully test it. + +One way to do a fresh sync is: + +``` +cd ~/.komodo/HUSH3 +rm blocks chainstate database notarizations hushstate +``` + +If you are using `zindex=1` then you need to also delete zindex.dat + +``` +cd ~/.komodo/HUSH3 +rm zindex.dat blocks chainstate database notarizations hushstate +``` + +It's possible to confused hush if you ran old code, stop, restart, and then write out zindex.dat that is incorrect, with later hushds will load from disk and believe. + + +# Testing a Branch + +To test a branch called `zindexdb` with a fresh clone: + +``` +# TODO: this should probably become a script in ./contrib +git clone https://git.hush.is/hush/hush3 hush3-testing +cd hush3-testing +git checkout zindexdb +# you need 2GB RAM free per -jN +./build.sh -j2; make; make; make # this deals with build-system race condition bugs + +# we want to test a fresh sync, so backup current data +TIME=`perl -e "print time"` +mv ~/.komodo/{HUSH3,HUSH3-backup-$TIME} +mkdir ~/.komodo/HUSH3 + +# Use your previous config as a base +cp ~/.komodo/{HUSH3-backup-$TIME,HUSH3}/HUSH3.conf +# Add zindex to your node +echo "zindex=1" >> ~/.komodo/HUSH3/HUSH3.conf + + +# This is optional but will likely speed up sync time greatly +cp ~/.komodo/{HUSH3-backup,HUSH3}/peers.dat + +# This log file is helpful for debugging more and will contain a history of the +# size of the anonset at every block height +./src/hushd &> hushd.log & +# to look at the log +tail -f hushd.log +``` + +To get a CSV file of the value of the anonset size for every block height: +``` +grep anonset hushd.log | cut -d= -f2 > anonset.csv +``` + +This only needs to be calculated once, if we can verify it's correct. These are historical values that do not change. The goal is a web page with a historical view of the HUSH anonset size. + + +These values should match on all nodes: + +``` +46913,2547,2253,294 +46914,2549,2254,295 +46915,2549,2254,295 +46916,2553,2257,296 +46917,2553,2257,296 +``` + +We should also check a recent block height to verify it's working correctly. The big "test" for this `zindexdb` branch is: + + * If you stop a node, and restart, are the stats from `getchaintxtstats` correct, i.e. the anonset stats? For instance, `shielded_pool_size` should be close to 500000, if it's close to or exactly 0, something is wrong. + * Is there a new file called `zindex.dat` in `~/.komodo/HUSH3/` ? + * Is `zindex.dat` 149 bytes ? + +# Coding Various coding styles have been used during the history of the codebase, and the result is not very consistent. However, we're now trying to converge to @@ -36,59 +117,6 @@ class Class } ``` -Doxygen comments ------------------ - -To facilitate the generation of documentation, use doxygen-compatible comment blocks for functions, methods and fields. - -For example, to describe a function use: -```c++ -/** - * ... text ... - * @param[in] arg1 A description - * @param[in] arg2 Another argument description - * @pre Precondition for function... - */ -bool function(int arg1, const char *arg2) -``` -A complete list of `@xxx` commands can be found at http://www.stack.nl/~dimitri/doxygen/manual/commands.html. -As Doxygen recognizes the comments by the delimiters (`/**` and `*/` in this case), you don't -*need* to provide any commands for a comment to be valid; just a description text is fine. - -To describe a class use the same construct above the class definition: -```c++ -/** - * Alerts are for notifying old versions if they become too obsolete and - * need to upgrade. The message is displayed in the status bar. - * @see GetWarnings() - */ -class CAlert -{ -``` - -To describe a member or variable use: -```c++ -int var; //!< Detailed description after the member -``` - -Also OK: -```c++ -/// -/// ... text ... -/// -bool function2(int arg1, const char *arg2) -``` - -Not OK (used plenty in the current source, but not picked up): -```c++ -// -// ... text ... -// -``` - -A full list of comment syntaxes picked up by doxygen can be found at http://www.stack.nl/~dimitri/doxygen/manual/docblocks.html, -but if possible use one of the above styles. - Development tips and tricks --------------------------- diff --git a/doc/man/hush-cli.1 b/doc/man/hush-cli.1 index 63d05ac06..668b3c4a7 100644 --- a/doc/man/hush-cli.1 +++ b/doc/man/hush-cli.1 @@ -1,9 +1,9 @@ .\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.13. -.TH HUSH-CLI "1" "April 2021" "hush-cli v3.7.1" "User Commands" +.TH HUSH-CLI "1" "July 2021" "hush-cli v3.8.0" "User Commands" .SH NAME -hush-cli \- manual page for hush-cli v3.7.1 +hush-cli \- manual page for hush-cli v3.8.0 .SH DESCRIPTION -Hush RPC client version v3.7.1\-2da07fe58\-dirty +Hush RPC client version v3.8.0\-10a6706e7\-dirty .PP In order to ensure you are adequately protecting your privacy when using Hush, please see . diff --git a/doc/man/hush-tx.1 b/doc/man/hush-tx.1 index 37c17b9b4..5c07d059a 100644 --- a/doc/man/hush-tx.1 +++ b/doc/man/hush-tx.1 @@ -1,9 +1,9 @@ .\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.13. -.TH HUSH-TX "1" "April 2021" "hush-tx v3.7.1" "User Commands" +.TH HUSH-TX "1" "July 2021" "hush-tx v3.8.0" "User Commands" .SH NAME -hush-tx \- manual page for hush-tx v3.7.1 +hush-tx \- manual page for hush-tx v3.8.0 .SH DESCRIPTION -hush\-tx utility version v3.7.1\-2da07fe58\-dirty +hush\-tx utility version v3.8.0\-10a6706e7\-dirty .SS "Usage:" .TP hush\-tx [options] [commands] diff --git a/doc/man/hushd.1 b/doc/man/hushd.1 index 23959cf1b..e73677110 100644 --- a/doc/man/hushd.1 +++ b/doc/man/hushd.1 @@ -1,9 +1,9 @@ .\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.13. -.TH HUSHD "1" "April 2021" "hushd v3.7.1" "User Commands" +.TH HUSHD "1" "July 2021" "hushd v3.8.0" "User Commands" .SH NAME -hushd \- manual page for hushd v3.7.1 +hushd \- manual page for hushd v3.8.0 .SH DESCRIPTION -Hush Daemon version v3.7.1\-2da07fe58\-dirty +Hush Daemon version v3.8.0\-10a6706e7\-dirty .PP In order to ensure you are adequately protecting your privacy when using Hush, please see . @@ -341,10 +341,19 @@ Minimum fee (in HUSH/kB) to allow for OP_RETURN transactions (default: .IP Fee (in HUSH/kB) to add to transactions you send (default: 0.00) .HP +\fB\-keepnotewitnesscache\fR +.IP +Keep partial Sapling Note Witness cache. Must be used with \fB\-rescanheight\fR +to find missing cache items. +.HP \fB\-rescan\fR .IP Rescan the block chain for missing wallet transactions on startup .HP +\fB\-rescanheight\fR +.IP +Rescan from specified height when rescan=1 on startup +.HP \fB\-salvagewallet\fR .IP Attempt to recover private keys from a corrupt wallet.dat on startup diff --git a/doc/privacy-basics.md b/doc/privacy-basics.md new file mode 100644 index 000000000..b231520c4 --- /dev/null +++ b/doc/privacy-basics.md @@ -0,0 +1,12 @@ +# Privacy Basics + +## Browser Tips + +Firefox is likely the best browser for privacy. Use this to improve + customize: + +https://ebin.city/~werwolf/posts/firefox-hardening-guide/ + +which is a guide around using and customizing the [Arkenfox](https://github.com/arkenfox/user.js/wiki/1.3-Implementation) user.js project + +Those are helpful when NOT using a Tor browser. If you are using Tor Browser (which is a fork of Firefox), then you do not need the above guide and should probably use the default that Tor Browser devs provide. + diff --git a/doc/relnotes/README.md b/doc/relnotes/README.md index 002b23513..529063a8e 100644 --- a/doc/relnotes/README.md +++ b/doc/relnotes/README.md @@ -10,6 +10,32 @@ and no longer on Github, since they banned Duke Leto and also because they censor many people around the world and work with evil organizations. +# Hush 3.8.0 "XXX YYY" + +This is an OPTIONAL release, but since it contains many privacy improvements, it's HIGHLY RECOMMENDED for all users to upgrade. + + * New Sietch feature: Randomized change output location + * Zcash and Pirate always put the change as the last shielded output, which leaks metadata. Hush no longer has this metadata leakage. + * This feature improves the `z_sendmany`, `z_mergetoaddress` and `z_shieldtocoinbase` since it's done in the Hush TransactionBuilder. + * New Sietch feature: Sitech-ified `z_shieldcoinbase` + * This RPC now leaks less metadata by making it hard for blockchain analysts to know which of the three outputs has value. + * This also increases Hush's "anonset velocity", which is how fast we increase our anonymity set, or "anonset". + * Previously you could only run `stop` while Hush was in RPC warmup, but now additional RPCs are allowed: + * `stop` - Oops, you started hushd on accident a few seconds ago? Now you can stop it without waiting. + * `help` - Get help during long rescans, finally! + * `z_listaddresses` - See a list of all zaddrs in this wallet, even during a long rescan! + * `z_exportkey` - Export a key from this node, even during rescan! + * `listaddresses` - See a list of taddrs as soon as we load the wallet. + * `dumpprivkey` - Dump the private key of a taddr, even when node isn't fully synced! + * `getpeerinfo` - See current peers even before we get enough peers to start syncing or a long rescan! + * `-keepnotewitnesscache` prevents the Sapling Note Witness cache from being deleted from wallet.dat on shutdown. + * `-rescanheight` can be used with `-keepnotewitnesscache` and `-rescan` to do a partial rescan of history and avoid completely rebuilding the Witness Cache. + * `-zindex` data is now stored on disk in the new `zindex.dat` file + * All nodes that use `-zindex` will now have reliable anonset statistics even after a restart + * Improvements to the RPC help documentation + * `hushd.bat` for Windows now uses the ASN map via `-asmap` and has the latest seed nodes + * `hushd-tx.bat` for Windows now exists for making raw transactions on Windows + # Hush 3.7.1 "Neologistic Nautilus" ``` diff --git a/src/Makefile.am b/src/Makefile.am index 0711b52cc..3232cabdb 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -98,11 +98,11 @@ noinst_PROGRAMS = TESTS = #if BUILD_BITCOIND - bin_PROGRAMS += komodod + bin_PROGRAMS += hushd #endif if BUILD_BITCOIN_UTILS - bin_PROGRAMS += komodo-cli komodo-tx + bin_PROGRAMS += hush-cli hush-tx endif if ENABLE_WALLET bin_PROGRAMS += wallet-utility @@ -203,6 +203,7 @@ BITCOIN_CORE_H = \ script/standard.h \ serialize.h \ streams.h \ + stratum.h \ support/allocators/secure.h \ support/allocators/zeroafterfree.h \ support/cleanse.h \ @@ -315,6 +316,7 @@ libbitcoin_server_a_SOURCES = \ rpc/server.cpp \ script/serverchecker.cpp \ script/sigcache.cpp \ + stratum.cpp \ timedata.cpp \ torcontrol.cpp \ txdb.cpp \ @@ -333,7 +335,7 @@ libbitcoin_zmq_a_SOURCES = \ zmq/zmqpublishnotifier.cpp endif -# wallet: komodod, but only linked when wallet enabled +# wallet: hushd, but only linked when wallet enabled libbitcoin_wallet_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) libbitcoin_wallet_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) libbitcoin_wallet_a_SOURCES = \ @@ -481,17 +483,17 @@ libbitcoin_cli_a_SOURCES = \ nodist_libbitcoin_util_a_SOURCES = $(srcdir)/obj/build.h # -# komodod binary # -komodod_SOURCES = bitcoind.cpp -komodod_CPPFLAGS = -fPIC $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) -komodod_CXXFLAGS = -fPIC $(AM_CXXFLAGS) $(PIE_FLAGS) -komodod_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) +# hushd binary # +hushd_SOURCES = bitcoind.cpp +hushd_CPPFLAGS = -fPIC $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) +hushd_CXXFLAGS = -fPIC $(AM_CXXFLAGS) $(PIE_FLAGS) +hushd_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) if TARGET_WINDOWS -komodod_SOURCES += bitcoind-res.rc +hushd_SOURCES += bitcoind-res.rc endif -komodod_LDADD = \ +hushd_LDADD = \ $(LIBBITCOIN_SERVER) \ $(LIBBITCOIN_COMMON) \ $(LIBUNIVALUE) \ @@ -506,10 +508,10 @@ komodod_LDADD = \ $(LIBCRYPTOCONDITIONS) if ENABLE_WALLET -komodod_LDADD += $(LIBBITCOIN_WALLET) +hushd_LDADD += $(LIBBITCOIN_WALLET) endif -komodod_LDADD += \ +hushd_LDADD += \ $(BOOST_LIBS) \ $(BDB_LIBS) \ $(SSL_LIBS) \ @@ -521,27 +523,27 @@ komodod_LDADD += \ $(LIBZCASH_LIBS) if TARGET_DARWIN -komodod_LDADD += libcc.dylib $(LIBSECP256K1) +hushd_LDADD += libcc.dylib $(LIBSECP256K1) endif if TARGET_WINDOWS -komodod_LDADD += libcc.dll $(LIBSECP256K1) +hushd_LDADD += libcc.dll $(LIBSECP256K1) endif if TARGET_LINUX -komodod_LDADD += libcc.so $(LIBSECP256K1) +hushd_LDADD += libcc.so $(LIBSECP256K1) endif # [+] Decker: use static linking for libstdc++.6.dylib, libgomp.1.dylib, libgcc_s.1.dylib if TARGET_DARWIN -komodod_LDFLAGS += -static-libgcc +hushd_LDFLAGS += -static-libgcc endif -# komodo-cli binary # -komodo_cli_SOURCES = bitcoin-cli.cpp -komodo_cli_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(EVENT_CFLAGS) -komodo_cli_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) -komodo_cli_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) +# hush-cli binary # +hush_cli_SOURCES = bitcoin-cli.cpp +hush_cli_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(EVENT_CFLAGS) +hush_cli_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) +hush_cli_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) if TARGET_DARWIN -komodo_cli_LDFLAGS += -static-libgcc +hush_cli_LDFLAGS += -static-libgcc endif # wallet-utility binary # @@ -553,10 +555,10 @@ wallet_utility_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) endif if TARGET_WINDOWS -komodo_cli_SOURCES += bitcoin-cli-res.rc +hush_cli_SOURCES += bitcoin-cli-res.rc endif -komodo_cli_LDADD = \ +hush_cli_LDADD = \ $(LIBBITCOIN_CLI) \ $(LIBUNIVALUE) \ $(LIBBITCOIN_UTIL) \ @@ -584,17 +586,17 @@ wallet_utility_LDADD = \ $(LIBCRYPTOCONDITIONS) endif -# komodo-tx binary # -komodo_tx_SOURCES = komodo-tx.cpp -komodo_tx_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) -komodo_tx_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) -komodo_tx_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) +# hush-tx binary # +hush_tx_SOURCES = hush-tx.cpp +hush_tx_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) +hush_tx_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) +hush_tx_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) if TARGET_WINDOWS -komodo_tx_SOURCES += bitcoin-tx-res.rc +hush_tx_SOURCES += bitcoin-tx-res.rc endif -komodo_tx_LDADD = \ +hush_tx_LDADD = \ $(LIBUNIVALUE) \ $(LIBBITCOIN_COMMON) \ $(LIBBITCOIN_UTIL) \ @@ -605,7 +607,7 @@ komodo_tx_LDADD = \ $(LIBZCASH_LIBS) \ $(LIBCRYPTOCONDITIONS) -komodo_tx_LDADD += $(BOOST_LIBS) $(CRYPTO_LIBS) +hush_tx_LDADD += $(BOOST_LIBS) $(CRYPTO_LIBS) # Zcash Protocol Primitives libzcash_a_SOURCES = \ diff --git a/src/Makefile.gtest.include b/src/Makefile.gtest.include index e3468a6f8..457ef6bdf 100644 --- a/src/Makefile.gtest.include +++ b/src/Makefile.gtest.include @@ -1,10 +1,10 @@ # Copyright (c) 2016-2021 The Hush developers # Released under the GPLv3 -TESTS += komodo-gtest -bin_PROGRAMS += komodo-gtest +TESTS += hush-gtest +bin_PROGRAMS += hush-gtest # tool for generating our public parameters -komodo_gtest_SOURCES = \ +hush_gtest_SOURCES = \ gtest/main.cpp \ gtest/utils.cpp \ gtest/test_checktransaction.cpp \ @@ -22,7 +22,6 @@ zcash_gtest_SOURCES += \ gtest/test_deprecation.cpp \ gtest/test_equihash.cpp \ gtest/test_httprpc.cpp \ - gtest/test_joinsplit.cpp \ gtest/test_keys.cpp \ gtest/test_keystore.cpp \ gtest/test_noteencryption.cpp \ @@ -51,23 +50,23 @@ zcash_gtest_SOURCES += \ wallet/gtest/test_wallet.cpp endif -komodo_gtest_CPPFLAGS = $(AM_CPPFLAGS) -DMULTICORE -fopenmp -DBINARY_OUTPUT -DCURVE_ALT_BN128 -DSTATIC $(BITCOIN_INCLUDES) -komodo_gtest_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) +hush_gtest_CPPFLAGS = $(AM_CPPFLAGS) -DMULTICORE -fopenmp -DBINARY_OUTPUT -DCURVE_ALT_BN128 -DSTATIC $(BITCOIN_INCLUDES) +hush_gtest_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) -komodo_gtest_LDADD = -lgtest -lgmock $(LIBBITCOIN_SERVER) $(LIBBITCOIN_CLI) $(LIBBITCOIN_COMMON) $(LIBBITCOIN_UTIL) $(LIBBITCOIN_CRYPTO) $(LIBBITCOIN_UNIVALUE) $(LIBLEVELDB) $(LIBMEMENV) \ +hush_gtest_LDADD = -lgtest -lgmock $(LIBBITCOIN_SERVER) $(LIBBITCOIN_CLI) $(LIBBITCOIN_COMMON) $(LIBBITCOIN_UTIL) $(LIBBITCOIN_CRYPTO) $(LIBBITCOIN_UNIVALUE) $(LIBLEVELDB) $(LIBMEMENV) \ $(BOOST_LIBS) $(BOOST_UNIT_TEST_FRAMEWORK_LIB) $(LIBSECP256K1) if ENABLE_ZMQ zcash_gtest_LDADD += $(LIBBITCOIN_ZMQ) $(ZMQ_LIBS) endif if ENABLE_WALLET -komodo_gtest_LDADD += $(LIBBITCOIN_WALLET) +hush_gtest_LDADD += $(LIBBITCOIN_WALLET) endif -komodo_gtest_LDADD += $(LIBZCASH_CONSENSUS) $(BDB_LIBS) $(SSL_LIBS) $(CRYPTO_LIBS) $(EVENT_PTHREADS_LIBS) $(EVENT_LIBS) $(LIBZCASH) $(LIBZCASH_LIBS) +hush_gtest_LDADD += $(LIBZCASH_CONSENSUS) $(BDB_LIBS) $(SSL_LIBS) $(CRYPTO_LIBS) $(EVENT_PTHREADS_LIBS) $(EVENT_LIBS) $(LIBZCASH) $(LIBZCASH_LIBS) -komodo_gtest_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) -static +hush_gtest_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) -static -komodo_gtest_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) -static +hush_gtest_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) -static -komodo-gtest-expected-failures: komodo-gtest FORCE - ./komodo-gtest --gtest_filter=*DISABLED_* --gtest_also_run_disabled_tests +hush-gtest-expected-failures: hush-gtest FORCE + ./hush-gtest --gtest_filter=*DISABLED_* --gtest_also_run_disabled_tests diff --git a/src/assetchains_stop b/src/assetchains_stop index dfdfed0c9..a44e3c403 100755 --- a/src/assetchains_stop +++ b/src/assetchains_stop @@ -1,8 +1,9 @@ #!/bin/bash +# Copyright (c) 2016-2021 The Hush developers set -eo pipefail -komodo_cli='./komodo-cli' +hush_cli='./hush-cli' ./listassetchains | while read chain; do - $komodo_cli --ac_name=$chain stop + $hush_cli --ac_name=$chain stop done diff --git a/src/bitcoin-cli.cpp b/src/bitcoin-cli.cpp index dbf2e82e9..e9623f9bd 100644 --- a/src/bitcoin-cli.cpp +++ b/src/bitcoin-cli.cpp @@ -28,9 +28,13 @@ #include #include #include "support/events.h" -uint16_t BITCOIND_RPCPORT = 7771; + +uint16_t ASSETCHAINS_RPCPORT = 18031; +uint16_t BITCOIND_RPCPORT = 18031; char SMART_CHAIN_SYMBOL[65]; +extern uint16_t ASSETCHAINS_RPCPORT; + #include using namespace std; @@ -43,13 +47,13 @@ std::string HelpMessageCli() std::string strUsage; strUsage += HelpMessageGroup(_("Options:")); strUsage += HelpMessageOpt("-?", _("This help message")); - strUsage += HelpMessageOpt("-conf=", strprintf(_("Specify configuration file (default: %s)"), "komodo.conf")); + strUsage += HelpMessageOpt("-conf=", strprintf(_("Specify configuration file (default: %s)"), "HUSH3.conf")); strUsage += HelpMessageOpt("-datadir=", _("Specify data directory")); strUsage += HelpMessageOpt("-testnet", _("Use the test network")); strUsage += HelpMessageOpt("-regtest", _("Enter regression test mode, which uses a special chain in which blocks can be " "solved instantly. This is intended for regression testing tools and app development.")); strUsage += HelpMessageOpt("-rpcconnect=", strprintf(_("Send commands to node running on (default: %s)"), "127.0.0.1")); - strUsage += HelpMessageOpt("-rpcport=", strprintf(_("Connect to JSON-RPC on (default: %u or testnet: %u)"), 8232, 18232)); + strUsage += HelpMessageOpt("-rpcport=", strprintf(_("Connect to JSON-RPC on (default: %u )"), 18030)); strUsage += HelpMessageOpt("-rpcwait", _("Wait for RPC server to start")); strUsage += HelpMessageOpt("-rpcuser=", _("Username for JSON-RPC connections")); strUsage += HelpMessageOpt("-rpcpassword=", _("Password for JSON-RPC connections")); @@ -82,7 +86,10 @@ static int AppInitRPC(int argc, char* argv[]) // Parameters ParseParameters(argc, argv); std:string name; - name = GetArg("-ac_name",""); + + // default HSC is HUSH3 itself, which to the internals, is also an HSC + name = GetArg("-ac_name","HUSH3"); + if ( !name.empty() ) strncpy(SMART_CHAIN_SYMBOL,name.c_str(),sizeof(SMART_CHAIN_SYMBOL)-1); @@ -249,14 +256,16 @@ UniValue CallRPC(const std::string& strMethod, const UniValue& params) event_base_dispatch(base.get()); - if (response.status == 0) - throw CConnectionFailed(strprintf("couldn't connect to server: %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)", http_errorstring(response.error), response.error)); - else if (response.status == HTTP_UNAUTHORIZED) + if (response.status == 0) { + throw CConnectionFailed(strprintf("couldn't connect to server at port %d : %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)", + ASSETCHAINS_RPCPORT, http_errorstring(response.error), response.error)); + } else if (response.status == HTTP_UNAUTHORIZED) { throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); - else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR) + } else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR) { throw std::runtime_error(strprintf("server returned HTTP error %d", response.status)); - else if (response.body.empty()) - throw std::runtime_error("no response from server"); + } else if (response.body.empty()) { + throw std::runtime_error(strprintf("no response from server at port %d", ASSETCHAINS_RPCPORT )); + } // Parse reply UniValue valReply(UniValue::VSTR); diff --git a/src/bitcoind.cpp b/src/bitcoind.cpp index 91e4cef56..9ba1b93ae 100644 --- a/src/bitcoind.cpp +++ b/src/bitcoind.cpp @@ -109,14 +109,11 @@ void WaitForShutdown(boost::thread_group* threadGroup) } } -////////////////////////////////////////////////////////////////////////////// -// // Start -// extern int32_t IS_HUSH_NOTARY,USE_EXTERNAL_PUBKEY; extern uint32_t ASSETCHAIN_INIT; extern std::string NOTARY_PUBKEY; -int32_t komodo_is_issuer(); +int32_t hush_is_issuer(); void hush_passport_iteration(); bool AppInit(int argc, char* argv[]) @@ -172,7 +169,7 @@ bool AppInit(int argc, char* argv[]) { fprintf(stderr, "%s reading config file\n", __FUNCTION__); ReadConfigFile(mapArgs, mapMultiArgs); - } catch (const missing_zcash_conf& e) { + } catch (const missing_hush_conf& e) { fprintf(stderr, (_("Before starting hushd, you need to create a configuration file:\n" "%s\n" diff --git a/src/cc/CC_made_easy.md b/src/cc/CC_made_easy.md index 30a45e173..48ccde25a 100644 --- a/src/cc/CC_made_easy.md +++ b/src/cc/CC_made_easy.md @@ -1,3 +1,4 @@ +// Copyright (c) 2016-2021 The Hush developers /****************************************************************************** * Copyright © 2014-2019 The SuperNET Developers. * * * @@ -13,18 +14,18 @@ * * ******************************************************************************/ -How to write utxo based CryptoConditions contracts for KMD chains +How to write utxo based CryptoConditions contracts for HUSH chains by jl777 -This is not the only smart contracts methodology that is possible to build on top of OP_CHECKCRYPTOCONDITION, just the first one. All the credit for getting OP_CHECKCRYPTOCONDITION working in the Komodo codebase goes to @libscott. I am just hooking into the code that he made and tried to make it just a little easier to make new contracts. +This is not the only smart contracts methodology that is possible to build on top of OP_CHECKCRYPTOCONDITION, just the first one. All the credit for getting OP_CHECKCRYPTOCONDITION working in the Hush codebase goes to @libscott. I am just hooking into the code that he made and tried to make it just a little easier to make new contracts. -There is probably some fancy marketing name to use, but for now, I will just call it "CC contract" for short, knowing that it is not 100% technically accurate as the CryptoConditions aspect is not really the main attribute. However, the KMD contracts were built to make the CryptoConditions codebase that was integrated into it to be more accessible. +There is probably some fancy marketing name to use, but for now, I will just call it "CC contract" for short, knowing that it is not 100% technically accurate as the CryptoConditions aspect is not really the main attribute. However, the HUSH contracts were built to make the CryptoConditions codebase that was integrated into it to be more accessible. Since CC contracts run native C/C++ code, it is turing complete and that means that any contract that is possible to do on any other platform will be possible to create via CC contract. utxo based contracts are a bit harder to start writing than for balance based contracts. However, they are much more secure as they leverage the existing bitcoin utxo system. That makes it much harder to have bugs that issue a zillion new coins from a bug, since all the CC contract operations needs to also obey the existing bitcoin utxo protocol. -This document will be heavily example based so it will utilize many of the existing reference CC contracts. After understanding this document, you should be in a good position to start creating either a new CC contract to be integrated into komodod or to make rpc based dapps directly. +This document will be heavily example based so it will utilize many of the existing reference CC contracts. After understanding this document, you should be in a good position to start creating either a new CC contract to be integrated into hushd or to make rpc based dapps directly. Chapter 0 - Bitcoin Protocol Basics There are many aspects of the bitcoin protocol that isnt needed to understand the CC contracts dependence on it. Such details will not be discussed. The primary aspect is the utxo, unspent transaction output. Just a fancy name for txid/vout, so when you sendtoaddress some coins, it creates a txid and the first output is vout.0, combine it and txid/0 is a specific utxo. @@ -151,7 +152,7 @@ Ultimately the CC contract is all about how it constrains its inputs, but before Chapter 4 - CC rpc extensions Currently, CC contracts need to be integrated at the source level. This limits who is able to create and add new CC contracts, which at first is good, but eventually will be a too strict limitation. The runtime bindings chapter will touch on how to break out of the source based limitation, but there is another key interface level, the RPC. -By convention, each CC contract adds an associated set of rpc calls to the komodo-cli. This not only simplifies the creation of the CC contract transactions, it further will allow dapps to be created just via rpc calls. That will require there being enough foundational CC contracts already in place. As we find new usecases that cannot be implemented via rpc, then a new CC contract is made that can handle that (and more) and the power of the rpc level increases. This is a long term process. +By convention, each CC contract adds an associated set of rpc calls to the hush-cli. This not only simplifies the creation of the CC contract transactions, it further will allow dapps to be created just via rpc calls. That will require there being enough foundational CC contracts already in place. As we find new usecases that cannot be implemented via rpc, then a new CC contract is made that can handle that (and more) and the power of the rpc level increases. This is a long term process. The typical rpc calls that are added address, , return the various special CC addresses, the list of CC contract instances and info about each CC contract instance. Along with an rpc that creates a CC instance and of course the calls to invoke a CC instance. @@ -227,9 +228,9 @@ faucetfund calls FaucetFund faucetget calls FaucetGet faucetinfo calls FaucetInfo -Now you might not be a programmer, but I hope you are able to understand the above sequence. user types in a cli call, komodo-cli processes it by calling the rpc function, which in turn calls the function inside faucet.cpp +Now you might not be a programmer, but I hope you are able to understand the above sequence. user types in a cli call, hush-cli processes it by calling the rpc function, which in turn calls the function inside faucet.cpp -No magic, just simple conversion of a user command line call that runs code inside the komodod. Both the faucetfund and faucetget create properly signed rawtransaction that is ready to be broadcast to the network using the standard sendrawtransaction rpc. It doesnt automatically do this to allow the GUI to have a confirmation step with all the details before doing an irrevocable CC contract transaction. +No magic, just simple conversion of a user command line call that runs code inside the hushd. Both the faucetfund and faucetget create properly signed rawtransaction that is ready to be broadcast to the network using the standard sendrawtransaction rpc. It doesnt automatically do this to allow the GUI to have a confirmation step with all the details before doing an irrevocable CC contract transaction. faucetfund allows anybody to add funds to the faucet faucetget allows anybody to get 0.1 coins from the faucet as long as they dont violate the rules. @@ -238,7 +239,7 @@ And we come to what it is all about. The rules of the faucet. Initially it was m To make it much harder to leech, it was made so each faucetget returned only 0.1 coins (down from 1.0) so it was worth 90% less. It was also made so that it had to be to a fresh address with less than 3 transactions. Finally each txid was constrained to start and end with 00! This is a cool trick to force usage of precious CPU time (20 to 60 seconds depending on system) to generate a valid txid. Like PoW mining for the txid and I expect other CC contracts to use a similar mechanism if they want to rate limit usage. -Combined, it became such a pain to get 0.1 coins, the faucet leeching problem was solved. It might not seem like too much trouble to change an address to get another 0.1 coins, but the way things are setup you need to launch the komodod -pubkey= to change the pubkey that is active for a node. That means to change the pubkey being used, the komodod needs to be restarted and this creates a lot of issues for any automation trying to do this. Combined with the PoW required, only when 0.1 coins becomes worth a significant effort will faucet leeching return. In that case, the PoW requirement can be increased and coin amount decreased, likely with a faucet2 CC contract as I dont expect many such variations to be needed. +Combined, it became such a pain to get 0.1 coins, the faucet leeching problem was solved. It might not seem like too much trouble to change an address to get another 0.1 coins, but the way things are setup you need to launch the hushd -pubkey= to change the pubkey that is active for a node. That means to change the pubkey being used, the hushd needs to be restarted and this creates a lot of issues for any automation trying to do this. Combined with the PoW required, only when 0.1 coins becomes worth a significant effort will faucet leeching return. In that case, the PoW requirement can be increased and coin amount decreased, likely with a faucet2 CC contract as I dont expect many such variations to be needed. Chapter 7 - rewards example The next CC contract in complexity is the rewards CC contract. This is designed to capture what most people like about masternodes, without anything else, ie. the rewards! @@ -652,9 +653,9 @@ Our testing cycle went a lot faster than expected as the bugs found were few and Yes, blockchains are complicated. Chapter 13 - different languages -The current codebase is integrated into the komodod codebase, which is C/C++. However, it is possible to use different languages and integrate into the C/C++ as zcash has shown by using the rust language for some parts of the zcashd. +The current codebase is integrated into the hushd codebase, which is C/C++. However, it is possible to use different languages and integrate into the C/C++ as zcash has shown by using the rust language for some parts of the zcashd. -I think any language that is compiled and can create a linkable library while being able to call and be called by C/C++ functions can be used. If you are able to make such a language binding for a simple CC contract like faucet, this will be good for a 777 KMD bounty. Of course, you need to be the first to submit a properly working pull request. +I think any language that is compiled and can create a linkable library while being able to call and be called by C/C++ functions can be used. If you are able to make such a language binding for a simple CC contract like faucet, this will be good for a 777 HUSH bounty. Of course, you need to be the first to submit a properly working pull request. Chapter 14 - runtime bindings @@ -676,7 +677,7 @@ This codebase and tools in between the GUI and the rpc level will be a very good ########## Conclusion -I hope this document has helped you understand what a Komodo utxo based CC contract is and how it is different from the other smart contracts. If you are now able to dive into the cc directory and start making your own CC contract, then I am very happy! +I hope this document has helped you understand what a Hush utxo based CC contract is and how it is different from the other smart contracts. If you are now able to dive into the cc directory and start making your own CC contract, then I am very happy! gateways CC @@ -712,8 +713,3 @@ gatewayswithdraw bindtxid coin withdrawpub amount And with a bit more magic in the oraclefeed, this is achieved. To be continued... - - - - - diff --git a/src/cc/CCutils.cpp b/src/cc/CCutils.cpp index 9e9ccc765..e40698ac6 100644 --- a/src/cc/CCutils.cpp +++ b/src/cc/CCutils.cpp @@ -675,7 +675,7 @@ int32_t hush_get_current_height() else return chainActive.LastTip()->GetHeight(); } -bool komodo_txnotarizedconfirmed(uint256 txid) +bool hush_txnotarizedconfirmed(uint256 txid) { char str[65]; int32_t confirms,notarized=0,txheight=0,currentheight=0;; @@ -688,17 +688,17 @@ bool komodo_txnotarizedconfirmed(uint256 txid) { if ( NSPV_myGetTransaction(txid,tx,hashBlock,txheight,currentheight) == 0 ) { - fprintf(stderr,"komodo_txnotarizedconfirmed cant find txid %s\n",txid.ToString().c_str()); + fprintf(stderr,"hush_txnotarizedconfirmed cant find txid %s\n",txid.ToString().c_str()); return(0); } else if (txheight<=0) { - fprintf(stderr,"komodo_txnotarizedconfirmed no txheight.%d for txid %s\n",txheight,txid.ToString().c_str()); + fprintf(stderr,"hush_txnotarizedconfirmed no txheight.%d for txid %s\n",txheight,txid.ToString().c_str()); return(0); } else if (txheight>currentheight) { - fprintf(stderr,"komodo_txnotarizedconfirmed backwards heights for txid %s hts.(%d %d)\n",txid.ToString().c_str(),txheight,currentheight); + fprintf(stderr,"hush_txnotarizedconfirmed backwards heights for txid %s hts.(%d %d)\n",txid.ToString().c_str(),txheight,currentheight); return(0); } confirms=1 + currentheight - txheight; @@ -707,22 +707,22 @@ bool komodo_txnotarizedconfirmed(uint256 txid) { if ( myGetTransaction(txid,tx,hashBlock) == 0 ) { - fprintf(stderr,"komodo_txnotarizedconfirmed cant find txid %s\n",txid.ToString().c_str()); + fprintf(stderr,"hush_txnotarizedconfirmed cant find txid %s\n",txid.ToString().c_str()); return(0); } else if ( hashBlock == zeroid ) { - fprintf(stderr,"komodo_txnotarizedconfirmed no hashBlock for txid %s\n",txid.ToString().c_str()); + fprintf(stderr,"hush_txnotarizedconfirmed no hashBlock for txid %s\n",txid.ToString().c_str()); return(0); } else if ( (pindex= hush_blockindex(hashBlock)) == 0 || (txheight= pindex->GetHeight()) <= 0 ) { - fprintf(stderr,"komodo_txnotarizedconfirmed no txheight.%d %p for txid %s\n",txheight,pindex,txid.ToString().c_str()); + fprintf(stderr,"hush_txnotarizedconfirmed no txheight.%d %p for txid %s\n",txheight,pindex,txid.ToString().c_str()); return(0); } else if ( (pindex= chainActive.LastTip()) == 0 || pindex->GetHeight() < txheight ) { - fprintf(stderr,"komodo_txnotarizedconfirmed backwards heights for txid %s hts.(%d %d)\n",txid.ToString().c_str(),txheight,(int32_t)pindex->GetHeight()); + fprintf(stderr,"hush_txnotarizedconfirmed backwards heights for txid %s hts.(%d %d)\n",txid.ToString().c_str(),txheight,(int32_t)pindex->GetHeight()); return(0); } confirms=1 + pindex->GetHeight() - txheight; diff --git a/src/cc/betprotocol.cpp b/src/cc/betprotocol.cpp index d5959b707..d8e904287 100644 --- a/src/cc/betprotocol.cpp +++ b/src/cc/betprotocol.cpp @@ -167,7 +167,7 @@ bool GetOpReturnHash(CScript script, uint256 &hash) * notarised on another chain. * * IN: params - condition params - * IN: importTx - Payout transaction on value chain (KMD) + * IN: importTx - Payout transaction on value chain (HUSH) * IN: nIn - index of input of stake * * importTx: Spends stakeTx with payouts from asset chain diff --git a/src/cc/betprotocol.h b/src/cc/betprotocol.h index 02c0000f2..6694cb331 100644 --- a/src/cc/betprotocol.h +++ b/src/cc/betprotocol.h @@ -62,7 +62,7 @@ public: CMutableTransaction MakePostEvidenceTx(uint256 signedSessionTxHash, int playerIndex, std::vector state); - // on KMD + // on HUSH CC* MakePayoutCond(uint256 signedSessionTxHash); CMutableTransaction MakeStakeTx(CAmount totalPayout, uint256 signedSessionTx); CMutableTransaction MakeAgreePayoutTx(std::vector payouts, uint256 signedStakeTxHash); diff --git a/src/cc/channels.cpp b/src/cc/channels.cpp index 97728d1e7..135d0dc9d 100644 --- a/src/cc/channels.cpp +++ b/src/cc/channels.cpp @@ -249,7 +249,7 @@ bool ChannelsValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction & return eval->Invalid("vout.1 is CC marker to srcpub or invalid amount for channelopen!"); else if ( ConstrainVout(channelOpenTx.vout[2],1,destmarker,CC_MARKER_VALUE)==0 ) return eval->Invalid("vout.2 is CC marker to destpub or invalid amount for channelopen!"); - else if (komodo_txnotarizedconfirmed(opentxid) == 0) + else if (hush_txnotarizedconfirmed(opentxid) == 0) return eval->Invalid("channelopen is not yet confirmed(notarised)!"); else if ( IsCCInput(tx.vin[0].scriptSig) != 0 ) return eval->Invalid("vin.0 is normal for channelpayment!"); @@ -310,7 +310,7 @@ bool ChannelsValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction & return eval->Invalid("vout.1 is CC marker to srcpub or invalid amount for channelopen!"); else if ( ConstrainVout(channelOpenTx.vout[2],1,destmarker,CC_MARKER_VALUE)==0 ) return eval->Invalid("vout.2 is CC marker to destpub or invalid amount for channelopen!"); - else if (komodo_txnotarizedconfirmed(opentxid) == 0) + else if (hush_txnotarizedconfirmed(opentxid) == 0) return eval->Invalid("channelopen is not yet confirmed(notarised)!"); else if ( IsCCInput(tx.vin[0].scriptSig) != 0 ) return eval->Invalid("vin.0 is normal for channelclose!"); @@ -351,9 +351,9 @@ bool ChannelsValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction & return eval->Invalid("vout.1 is CC marker to srcpub or invalid amount for channelopen!"); else if ( ConstrainVout(channelOpenTx.vout[2],1,destmarker,CC_MARKER_VALUE)==0 ) return eval->Invalid("vout.2 is CC marker to destpub or invalid amount for channelopen!"); - else if (komodo_txnotarizedconfirmed(opentxid) == 0) + else if (hush_txnotarizedconfirmed(opentxid) == 0) return eval->Invalid("channelopen is not yet confirmed(notarised)!"); - else if (komodo_txnotarizedconfirmed(param3) == 0) + else if (hush_txnotarizedconfirmed(param3) == 0) return eval->Invalid("channelClose is not yet confirmed(notarised)!"); else if ( IsCCInput(tx.vin[0].scriptSig) != 0 ) return eval->Invalid("vin.0 is normal for channelrefund!"); @@ -537,7 +537,7 @@ UniValue ChannelPayment(const CPubKey& pk, uint64_t txfee,uint256 opentxid,int64 } else CCERR_RESULT("channelscc",CCLOG_INFO, stream << "invalid channel open tx"); - if (komodo_txnotarizedconfirmed(opentxid)==false) CCERR_RESULT("channelscc",CCLOG_INFO, stream << "channelsopen tx not yet confirmed/notarized"); + if (hush_txnotarizedconfirmed(opentxid)==false) CCERR_RESULT("channelscc",CCLOG_INFO, stream << "channelsopen tx not yet confirmed/notarized"); if (AddNormalinputs(mtx,mypk,txfee+CC_MARKER_VALUE,3,pk.IsValid()) > 0) { if ((funds=AddChannelsInputs(cp,mtx,channelOpenTx,prevtxid,mypk)) !=0 && (change=funds-amount)>=0) @@ -612,7 +612,7 @@ UniValue ChannelClose(const CPubKey& pk, uint64_t txfee,uint256 opentxid) CCERR_RESULT("channelscc",CCLOG_INFO, stream << "invalid channel open txid"); if ((numvouts=channelOpenTx.vout.size()) < 1 || DecodeChannelsOpRet(channelOpenTx.vout[numvouts-1].scriptPubKey,tokenid,tmp_txid,srcpub,destpub,numpayments,payment,hashchain)!='O') CCERR_RESULT("channelscc",CCLOG_INFO, stream << "invalid channel open tx"); - if (komodo_txnotarizedconfirmed(opentxid)==false) + if (hush_txnotarizedconfirmed(opentxid)==false) CCERR_RESULT("channelscc",CCLOG_INFO, stream <<"channelsopen tx not yet confirmed/notarized"); if (mypk != srcpub) CCERR_RESULT("channelscc",CCLOG_INFO, stream << "cannot close, you are not channel owner"); @@ -650,13 +650,13 @@ UniValue ChannelRefund(const CPubKey& pk, uint64_t txfee,uint256 opentxid,uint25 CCERR_RESULT("channelscc",CCLOG_INFO, stream << "invalid channel close txid"); if ((numvouts=channelCloseTx.vout.size()) < 1 || DecodeChannelsOpRet(channelCloseTx.vout[numvouts-1].scriptPubKey,tokenid,txid,srcpub,destpub,param1,param2,param3)!='C') CCERR_RESULT("channelscc",CCLOG_INFO, stream << "invalid channel close tx"); - if (komodo_txnotarizedconfirmed(closetxid)==false) + if (hush_txnotarizedconfirmed(closetxid)==false) CCERR_RESULT("channelscc",CCLOG_INFO, stream << "channelsclose tx not yet confirmed/notarized"); if (txid!=opentxid) CCERR_RESULT("channelscc",CCLOG_INFO, stream << "open and close txid are not from same channel"); if (myGetTransaction(opentxid,channelOpenTx,hashblock) == 0) CCERR_RESULT("channelscc",CCLOG_INFO, stream << "invalid channel open txid"); - if (komodo_txnotarizedconfirmed(opentxid)==false) + if (hush_txnotarizedconfirmed(opentxid)==false) CCERR_RESULT("channelscc",CCLOG_INFO, stream << "channelsopen tx not yet confirmed/notarized"); if ((numvouts=channelOpenTx.vout.size()) < 1 || DecodeChannelsOpRet(channelOpenTx.vout[numvouts-1].scriptPubKey,tokenid,txid,srcpub,destpub,numpayments,payment,hashchain)!='O') CCERR_RESULT("channelscc",CCLOG_INFO, stream << "invalid channel open tx"); diff --git a/src/cc/customcc.cpp b/src/cc/customcc.cpp index 343195dfe..c1b1c9028 100644 --- a/src/cc/customcc.cpp +++ b/src/cc/customcc.cpp @@ -10,7 +10,7 @@ ./makecustom ../hush-smart-chain -ac_name=CUSTOM -ac_cclib=custom -ac_cc=2 ... - The above will rebuild komodod and get it running again + The above will rebuild hushd and get it running again */ CScript custom_opret(uint8_t funcid,CPubKey pk) diff --git a/src/cc/customcc.h b/src/cc/customcc.h index c3614d2af..c88f6333d 100644 --- a/src/cc/customcc.h +++ b/src/cc/customcc.h @@ -10,7 +10,7 @@ 3. write the actual custom_func0, custom_func1 and custom_validate in customcc.cpp - 4. ./makecustom, which builds cclib.cpp with -DBUILD_CUSTOMCC and puts the libcc.so in ~/komodo/src and rebuilds komodod + 4. ./makecustom, which builds cclib.cpp with -DBUILD_CUSTOMCC and puts the libcc.so in ~/hush3/src and rebuilds hushd 5. launch your chain with -ac_cclib=customcc -ac_cc=2 diff --git a/src/cc/dapps/dappinc.h b/src/cc/dapps/dappinc.h index 29c15f111..f81db7dd2 100644 --- a/src/cc/dapps/dappinc.h +++ b/src/cc/dapps/dappinc.h @@ -384,7 +384,7 @@ cJSON *hushdex_cli(char *clistr,char **retstrp,char *method,char *arg0,char *arg return(retjson); } -bits256 komodobroadcast(char *refcoin,char *acname,cJSON *hexjson) +bits256 hushbroadcast(char *refcoin,char *acname,cJSON *hexjson) { char *hexstr,*retstr,str[65]; cJSON *retjson; bits256 txid; memset(txid.bytes,0,sizeof(txid)); @@ -439,7 +439,7 @@ bits256 tokentransfer(char *refcoin,char *acname,char *tokenid,char *destpub,int sprintf(numstr,"%llu",(long long)units); if ( (retjson= get_hushcli(refcoin,&retstr,acname,"tokentransfer",tokenid,destpub,numstr,"","","","")) != 0 ) { - txid = komodobroadcast(refcoin,acname,retjson); + txid = hushbroadcast(refcoin,acname,retjson); fprintf(stderr,"tokentransfer returned (%s)\n",jprint(retjson,0)); free_json(retjson); } @@ -639,7 +639,7 @@ cJSON *get_rawmempool(char *refcoin,char *acname) cJSON *get_addressutxos(char *refcoin,char *acname,char *coinaddr) { cJSON *retjson; char *retstr,jsonbuf[256]; - if ( refcoin[0] != 0 && strcmp(refcoin,"KMD") != 0 ) + if ( refcoin[0] != 0 && strcmp(refcoin,"HUSH3") != 0 ) printf("warning: assumes %s has addressindex enabled\n",refcoin); sprintf(jsonbuf,"{\\\"addresses\\\":[\\\"%s\\\"]}",coinaddr); if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getaddressutxos",jsonbuf,"","","","","","")) != 0 ) diff --git a/src/cc/dapps/dappstd.c b/src/cc/dapps/dappstd.c index 98475c4f5..1d897196b 100644 --- a/src/cc/dapps/dappstd.c +++ b/src/cc/dapps/dappstd.c @@ -669,7 +669,7 @@ uint16_t hush_userpass(char *userpass,char *symbol) #define is_cJSON_True(json) ((json) != 0 && ((json)->type & 0xff) == cJSON_True) -char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port) +char *hush_issuemethod(char *userpass,char *method,char *params,uint16_t port) { //static void *cHandle; char url[512],*retstr=0,*retstr2=0,postdata[8192]; @@ -691,7 +691,7 @@ int32_t games_sendrawtransaction(char *rawtx) char *params,*retstr,*hexstr; cJSON *retjson,*resobj; int32_t retval = -1; params = (char *)malloc(strlen(rawtx) + 16); sprintf(params,"[\"%s\"]",rawtx); - if ( (retstr= komodo_issuemethod(USERPASS,(char *)"sendrawtransaction",params,GAMES_PORT)) != 0 ) + if ( (retstr= hush_issuemethod(USERPASS,(char *)"sendrawtransaction",params,GAMES_PORT)) != 0 ) { if ( 0 ) // causes 4th level crash { @@ -768,7 +768,7 @@ int32_t games_progress(struct games_state *rs,int32_t waitflag,uint64_t seed,gam if ( fp == 0 ) fp = fopen("keystrokes.log","a"); sprintf(params,"[\"keystrokes\",\"17\",\"[%%22%s%%22,%%22%s%%22]\"]",Gametxidstr,hexstr); - if ( (retstr= komodo_issuemethod(USERPASS,(char *)"cclib",params,GAMES_PORT)) != 0 ) + if ( (retstr= hush_issuemethod(USERPASS,(char *)"cclib",params,GAMES_PORT)) != 0 ) { if ( fp != 0 ) { @@ -970,7 +970,7 @@ int32_t games_setplayerdata(struct games_state *rs,char *gametxidstr) if ( 0 ) { sprintf(fname,"%s.gameinfo",gametxidstr); - sprintf(cmd,"./komodo-cli -ac_name=%s cclib gameinfo 17 \\\"[%%22%s%%22]\\\" > %s",ASSETCHAINS_SYMBOL,gametxidstr,fname); + sprintf(cmd,"./hush-cli -ac_name=%s cclib gameinfo 17 \\\"[%%22%s%%22]\\\" > %s",ASSETCHAINS_SYMBOL,gametxidstr,fname); if ( system(cmd) != 0 ) fprintf(stderr,"error issuing (%s)\n",cmd); else filestr = (char *)OS_fileptr(&allocsize,fname); @@ -978,7 +978,7 @@ int32_t games_setplayerdata(struct games_state *rs,char *gametxidstr) else { sprintf(params,"[\"gameinfo\",\"17\",\"[%%22%s%%22]\"]",gametxidstr); - filestr = komodo_issuemethod(USERPASS,(char *)"cclib",params,GAMES_PORT); + filestr = hush_issuemethod(USERPASS,(char *)"cclib",params,GAMES_PORT); } if ( filestr != 0 ) { diff --git a/src/cc/dapps/diceloop b/src/cc/dapps/diceloop deleted file mode 100755 index 44550b46a..000000000 --- a/src/cc/dapps/diceloop +++ /dev/null @@ -1,6 +0,0 @@ -while true -do -./c dicestatus KMDICE 5be49570c56d036abb08b6d084da93a8a86f58fc48db4a1086be95540d752d6f - -sleep 10 -done diff --git a/src/cc/dapps/sendmany b/src/cc/dapps/sendmany deleted file mode 100755 index 45560b505..000000000 --- a/src/cc/dapps/sendmany +++ /dev/null @@ -1,3 +0,0 @@ -export addr="RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo" -./komodo-cli -ac_name=KMDICE sendmany "" "{\"$addr\":0.023,\"$addr\":0.023,\"$addr\":0.023,\"$addr\":0.023,\"$addr\":0.023,\"$addr\":0.023,\"$addr\":0.023,\"$addr\":0.023,\"$addr\":0.023,\"$addr\":0.023}" - diff --git a/src/cc/dapps/sendmany100 b/src/cc/dapps/sendmany100 deleted file mode 100755 index 9638766ab..000000000 --- a/src/cc/dapps/sendmany100 +++ /dev/null @@ -1,2 +0,0 @@ -./komodo-cli -ac_name=KMDICE sendmany "" "{\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002,\"RXgCPfi6wccRr3Eai3X9duTTkAirhcQLNo\":0.0002}" - diff --git a/src/cc/dapps/zmigrate.c b/src/cc/dapps/zmigrate.c index 057c2b374..e8b547c6b 100644 --- a/src/cc/dapps/zmigrate.c +++ b/src/cc/dapps/zmigrate.c @@ -23,6 +23,8 @@ #include "cJSON.c" /* +NOTE: HUSH nor any Hush Smart Chain has any sprout outputs. This code is kept for historical and educational purposes. + z_migrate: the purpose of z_migrate is to make converting of all sprout outputs into sapling. the usage would be for the user to specify a sapling address and call z_migrate zsaddr, until it returns that there is nothing left to be done. its main functionality is quite similar to a z_mergetoaddress ANY_ZADDR -> onetime_taddr followed by a z_sendmany onetime_taddr -> zsaddr @@ -314,20 +316,18 @@ cJSON *get_urljson(char *url,char *fname) char *REFCOIN_CLI; -cJSON *get_komodocli(char *refcoin,char **retstrp,char *acname,char *method,char *arg0,char *arg1,char *arg2,char *arg3) +cJSON *get_hushcli(char *refcoin,char **retstrp,char *acname,char *method,char *arg0,char *arg1,char *arg2,char *arg3) { long fsize; cJSON *retjson = 0; char cmdstr[32768],*jsonstr,fname[256]; sprintf(fname,"/tmp/zmigrate.%s",method); - //if ( (acname == 0 || acname[0] == 0) && strcmp(refcoin,"KMD") != 0 ) - // acname = refcoin; if ( acname[0] != 0 ) { - if ( refcoin[0] != 0 && strcmp(refcoin,"KMD") != 0 ) + if ( refcoin[0] != 0 && strcmp(refcoin,"HUSH3") != 0 ) printf("unexpected: refcoin.(%s) acname.(%s)\n",refcoin,acname); - sprintf(cmdstr,"./komodo-cli -ac_name=%s %s %s %s %s %s > %s\n",acname,method,arg0,arg1,arg2,arg3,fname); + sprintf(cmdstr,"./hush-cli -ac_name=%s %s %s %s %s %s > %s\n",acname,method,arg0,arg1,arg2,arg3,fname); } - else if ( strcmp(refcoin,"KMD") == 0 ) - sprintf(cmdstr,"./komodo-cli %s %s %s %s %s > %s\n",method,arg0,arg1,arg2,arg3,fname); + else if ( strcmp(refcoin,"HUSH3") == 0 ) + sprintf(cmdstr,"./hush-cli %s %s %s %s %s > %s\n",method,arg0,arg1,arg2,arg3,fname); else if ( REFCOIN_CLI != 0 && REFCOIN_CLI[0] != 0 ) { sprintf(cmdstr,"%s %s %s %s %s %s > %s\n",REFCOIN_CLI,method,arg0,arg1,arg2,arg3,fname); @@ -346,37 +346,12 @@ cJSON *get_komodocli(char *refcoin,char **retstrp,char *acname,char *method,char return(retjson); } -bits256 komodobroadcast(char *refcoin,char *acname,cJSON *hexjson) -{ - char *hexstr,*retstr,str[65]; cJSON *retjson; bits256 txid; - memset(txid.bytes,0,sizeof(txid)); - if ( (hexstr= jstr(hexjson,"hex")) != 0 ) - { - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"sendrawtransaction",hexstr,"","","")) != 0 ) - { - //fprintf(stderr,"broadcast.(%s)\n",jprint(retjson,0)); - free_json(retjson); - } - else if ( retstr != 0 ) - { - if ( strlen(retstr) >= 64 ) - { - retstr[64] = 0; - decode_hex(txid.bytes,32,retstr); - } - fprintf(stderr,"broadcast %s txid.(%s)\n",strlen(acname)>0?acname:refcoin,bits256_str(str,txid)); - free(retstr); - } - } - return(txid); -} - bits256 sendtoaddress(char *refcoin,char *acname,char *destaddr,int64_t satoshis) { char numstr[32],*retstr,str[65]; cJSON *retjson; bits256 txid; memset(txid.bytes,0,sizeof(txid)); sprintf(numstr,"%.8f",(double)satoshis/SATOSHIDEN); - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"sendtoaddress",destaddr,numstr,"","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"sendtoaddress",destaddr,numstr,"","")) != 0 ) { fprintf(stderr,"unexpected sendrawtransaction json.(%s)\n",jprint(retjson,0)); free_json(retjson); @@ -397,7 +372,7 @@ bits256 sendtoaddress(char *refcoin,char *acname,char *destaddr,int64_t satoshis int32_t get_coinheight(char *refcoin,char *acname) { cJSON *retjson; char *retstr; int32_t height=0; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"getblockchaininfo","","","","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getblockchaininfo","","","","")) != 0 ) { height = jint(retjson,"blocks"); free_json(retjson); @@ -415,7 +390,7 @@ bits256 get_coinblockhash(char *refcoin,char *acname,int32_t height) cJSON *retjson; char *retstr,heightstr[32]; bits256 hash; memset(hash.bytes,0,sizeof(hash)); sprintf(heightstr,"%d",height); - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"getblockhash",heightstr,"","","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getblockhash",heightstr,"","","")) != 0 ) { fprintf(stderr,"unexpected blockhash json.(%s)\n",jprint(retjson,0)); free_json(retjson); @@ -436,7 +411,7 @@ bits256 get_coinmerkleroot(char *refcoin,char *acname,bits256 blockhash) { cJSON *retjson; char *retstr,str[65]; bits256 merkleroot; memset(merkleroot.bytes,0,sizeof(merkleroot)); - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"getblockheader",bits256_str(str,blockhash),"","","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getblockheader",bits256_str(str,blockhash),"","","")) != 0 ) { merkleroot = jbits256(retjson,"merkleroot"); //fprintf(stderr,"got merkleroot.(%s)\n",bits256_str(str,merkleroot)); @@ -474,7 +449,7 @@ int32_t get_coinheader(char *refcoin,char *acname,bits256 *blockhashp,bits256 *m cJSON *get_rawmempool(char *refcoin,char *acname) { cJSON *retjson; char *retstr; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"getrawmempool","","","","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getrawmempool","","","","")) != 0 ) { //printf("mempool.(%s)\n",jprint(retjson,0)); return(retjson); @@ -490,10 +465,10 @@ cJSON *get_rawmempool(char *refcoin,char *acname) cJSON *get_addressutxos(char *refcoin,char *acname,char *coinaddr) { cJSON *retjson; char *retstr,jsonbuf[256]; - if ( refcoin[0] != 0 && strcmp(refcoin,"KMD") != 0 ) + if ( refcoin[0] != 0 && strcmp(refcoin,"HUSH3") != 0 ) printf("warning: assumes %s has addressindex enabled\n",refcoin); sprintf(jsonbuf,"{\\\"addresses\\\":[\\\"%s\\\"]}",coinaddr); - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"getaddressutxos",jsonbuf,"","","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getaddressutxos",jsonbuf,"","","")) != 0 ) { //printf("addressutxos.(%s)\n",jprint(retjson,0)); return(retjson); @@ -509,7 +484,7 @@ cJSON *get_addressutxos(char *refcoin,char *acname,char *coinaddr) cJSON *get_rawtransaction(char *refcoin,char *acname,bits256 txid) { cJSON *retjson; char *retstr,str[65]; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"getrawtransaction",bits256_str(str,txid),"1","","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getrawtransaction",bits256_str(str,txid),"1","","")) != 0 ) { return(retjson); } @@ -524,7 +499,7 @@ cJSON *get_rawtransaction(char *refcoin,char *acname,bits256 txid) cJSON *get_listunspent(char *refcoin,char *acname) { cJSON *retjson; char *retstr,str[65]; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"listunspent","","","","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"listunspent","","","","")) != 0 ) { return(retjson); } @@ -539,7 +514,7 @@ cJSON *get_listunspent(char *refcoin,char *acname) cJSON *z_listunspent(char *refcoin,char *acname) { cJSON *retjson; char *retstr,str[65]; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"z_listunspent","","","","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_listunspent","","","","")) != 0 ) { return(retjson); } @@ -554,7 +529,7 @@ cJSON *z_listunspent(char *refcoin,char *acname) cJSON *z_listoperationids(char *refcoin,char *acname) { cJSON *retjson; char *retstr,str[65]; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"z_listoperationids","","","","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_listoperationids","","","","")) != 0 ) { return(retjson); } @@ -570,7 +545,7 @@ cJSON *z_getoperationstatus(char *refcoin,char *acname,char *opid) { cJSON *retjson; char *retstr,str[65],params[512]; sprintf(params,"'[\"%s\"]'",opid); - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"z_getoperationstatus",params,"","","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_getoperationstatus",params,"","","")) != 0 ) { //printf("got status (%s)\n",jprint(retjson,0)); return(retjson); @@ -587,7 +562,7 @@ cJSON *z_getoperationresult(char *refcoin,char *acname,char *opid) { cJSON *retjson; char *retstr,str[65],params[512]; sprintf(params,"'[\"%s\"]'",opid); - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"z_getoperationresult",params,"","","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_getoperationresult",params,"","","")) != 0 ) { return(retjson); } @@ -602,7 +577,7 @@ cJSON *z_getoperationresult(char *refcoin,char *acname,char *opid) int32_t validateaddress(char *refcoin,char *acname,char *depositaddr, char* compare) { cJSON *retjson; char *retstr; int32_t res=0; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"validateaddress",depositaddr,"","","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"validateaddress",depositaddr,"","","")) != 0 ) { if (is_cJSON_True(jobj(retjson,compare)) != 0 ) res=1; free_json(retjson); @@ -618,7 +593,7 @@ int32_t validateaddress(char *refcoin,char *acname,char *depositaddr, char* comp int32_t z_validateaddress(char *refcoin,char *acname,char *depositaddr, char *compare) { cJSON *retjson; char *retstr; int32_t res=0; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"z_validateaddress",depositaddr,"","","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_validateaddress",depositaddr,"","","")) != 0 ) { if (is_cJSON_True(jobj(retjson,compare)) != 0 ) res=1; @@ -635,7 +610,7 @@ int32_t z_validateaddress(char *refcoin,char *acname,char *depositaddr, char *co int64_t z_getbalance(char *refcoin,char *acname,char *coinaddr) { cJSON *retjson; char *retstr,cmpstr[64]; int64_t amount=0; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"z_getbalance",coinaddr,"","","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_getbalance",coinaddr,"","","")) != 0 ) { fprintf(stderr,"z_getbalance.(%s) %s returned json!\n",refcoin,acname); free_json(retjson); @@ -656,7 +631,7 @@ int32_t z_exportkey(char *privkey,char *refcoin,char *acname,char *zaddr) { cJSON *retjson; char *retstr,cmpstr[64]; int64_t amount=0; privkey[0] = 0; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"z_exportkey",zaddr,"","","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_exportkey",zaddr,"","","")) != 0 ) { fprintf(stderr,"z_exportkey.(%s) %s returned json!\n",refcoin,acname); free_json(retjson); @@ -675,7 +650,7 @@ int32_t z_exportkey(char *privkey,char *refcoin,char *acname,char *zaddr) int32_t getnewaddress(char *coinaddr,char *refcoin,char *acname) { cJSON *retjson; char *retstr; int64_t amount=0; int32_t retval = -1; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"getnewaddress","","","","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getnewaddress","","","","")) != 0 ) { fprintf(stderr,"getnewaddress.(%s) %s returned json!\n",refcoin,acname); free_json(retjson); @@ -692,7 +667,7 @@ int32_t getnewaddress(char *coinaddr,char *refcoin,char *acname) int32_t z_getnewaddress(char *coinaddr,char *refcoin,char *acname,char *typestr) { cJSON *retjson; char *retstr; int64_t amount=0; int32_t retval = -1; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"z_getnewaddress",typestr,"","","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_getnewaddress",typestr,"","","")) != 0 ) { fprintf(stderr,"z_getnewaddress.(%s) %s returned json!\n",refcoin,acname); free_json(retjson); @@ -764,7 +739,7 @@ int64_t find_sprout_amount(char *coinstr,char *zcaddr) void importaddress(char *refcoin,char *acname,char *depositaddr) { cJSON *retjson; char *retstr; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"importaddress",depositaddr,"","true","")) != 0 ) + if ( (retjson= get_hushcli(refcoin,&retstr,acname,"importaddress",depositaddr,"","true","")) != 0 ) { printf("importaddress.(%s)\n",jprint(retjson,0)); free_json(retjson); @@ -782,7 +757,7 @@ int32_t z_sendmany(char *opidstr,char *coinstr,char *acname,char *srcaddr,char * sprintf(params,"'[{\"address\":\"%s\",\"amount\":%.8f}]'",destaddr,dstr(amount)); sprintf(addr,"\"%s\"",srcaddr); printf("z_sendmany from.(%s) -> %s\n",srcaddr,params); - if ( (retjson= get_komodocli(coinstr,&retstr,acname,"z_sendmany",addr,params,"","")) != 0 ) + if ( (retjson= get_hushcli(coinstr,&retstr,acname,"z_sendmany",addr,params,"","")) != 0 ) { printf("unexpected json z_sendmany.(%s)\n",jprint(retjson,0)); free_json(retjson); @@ -801,7 +776,7 @@ int32_t z_mergetoaddress(char *opidstr,char *coinstr,char *acname,char *destaddr { cJSON *retjson; char *retstr,addr[128],*opstr; int32_t retval = -1; sprintf(addr,"[\\\"ANY_SPROUT\\\"]"); - if ( (retjson= get_komodocli(coinstr,&retstr,acname,"z_mergetoaddress",addr,destaddr,"","")) != 0 ) + if ( (retjson= get_hushcli(coinstr,&retstr,acname,"z_mergetoaddress",addr,destaddr,"","")) != 0 ) { if ( (opstr= jstr(retjson,"opid")) != 0 ) strcpy(opidstr,opstr); @@ -1044,8 +1019,8 @@ int32_t itemvalid(char *refcoin,int64_t *refundedp,int64_t *waitingp,struct clai *refundedp = *waitingp = 0; if ( item->refundvalue < 0 ) return(-1); - // change "kmd" -> %s, tolowerstr(refcoin) - sprintf(url,"https://kmd.explorer.dexstats.info/insight-api-komodo/addr/%s",item->destaddr); + + sprintf(url,"https://explorer.hush.is/api/addr/%s",item->destaddr); if ( (retstr= send_curl(url,"/tmp/itemvalid")) != 0 ) { if ( (curljson= cJSON_Parse(retstr)) != 0 ) @@ -1294,7 +1269,7 @@ void reconcile_claims(char *refcoin,char *fname) else fields[n][i++] = *str++; } printf("%s\n",fields[1]); - total += update_claimstats(fields[1],fields[3],fields[5 + (strcmp("KMD",refcoin)==0)],atof(fields[4])*SATOSHIDEN + 0.0000000049); + total += update_claimstats(fields[1],fields[3],fields[5 + (strcmp("HUSH3",refcoin)==0)],atof(fields[4])*SATOSHIDEN + 0.0000000049); numlines++; } fclose(fp); @@ -1310,26 +1285,20 @@ int32_t main(int32_t argc,char **argv) printf("argc needs to be 2: coin\n"); return(-1); } - if ( strcmp(argv[1],"KMD") == 0 ) + if ( strcmp(argv[1],"HUSH3") == 0 ) { - REFCOIN_CLI = "./komodo-cli"; - coinstr = clonestr("KMD"); - acstr = ""; - } - else if ( strcmp(argv[1],"CHIPS") == 0 ) - { - REFCOIN_CLI = "./chips-cli"; - coinstr = clonestr("CHIPS"); + REFCOIN_CLI = "./hush-cli"; + coinstr = clonestr("HUSH3"); acstr = ""; } else { - sprintf(buf,"./komodo-cli -ac_name=%s",argv[1]); + sprintf(buf,"./hush-cli -ac_name=%s",argv[1]); REFCOIN_CLI = clonestr(buf); coinstr = clonestr(argv[1]); acstr = coinstr; } - if ( 1 )//strcmp(coinstr,"KMD") == 0 ) + if ( 1 ) { sprintf(buf,"%s-Claims.csv",coinstr); reconcile_claims(coinstr,buf); @@ -1364,12 +1333,12 @@ int32_t main(int32_t argc,char **argv) } continue; } - if ( strcmp(coinstr,"KMD") == 0 && verify_vin(coinstr,jbits256(item,"txid"),0,"R9JCEd6xnCxNUSpLrHEWvzPSh7CNXm7z75") < 0 ) + if ( strcmp(coinstr,"HUSH3") == 0 && verify_vin(coinstr,jbits256(item,"txid"),0,"R9JCEd6xnCxNUSpLrHEWvzPSh7CNXm7z75") < 0 ) { printf("WARNING: imposter dust detected! %s\n",bits256_str(str,jbits256(item,"txid"))); continue; } - else if ( strcmp(coinstr,"KMD") != 0 && verify_vin(coinstr,jbits256(item,"txid"),0,"R9MUnxXijovvSeT9sFuUX23TiFtVvZEGjT") < 0 ) + else if ( strcmp(coinstr,"HUSH3") != 0 && verify_vin(coinstr,jbits256(item,"txid"),0,"R9MUnxXijovvSeT9sFuUX23TiFtVvZEGjT") < 0 ) { printf("WARNING: imposter dust detected! %s\n",bits256_str(str,jbits256(item,"txid"))); continue; @@ -1452,14 +1421,14 @@ int32_t zmigratemain(int32_t argc,char **argv) printf("argc needs to be 3\n"); return(-1); } - if ( strcmp(argv[1],"KMD") == 0 ) + if ( strcmp(argv[1],"HUSH3") == 0 ) { - REFCOIN_CLI = "./komodo-cli"; - coinstr = clonestr("KMD"); + REFCOIN_CLI = "./hush-cli"; + coinstr = clonestr("HUSH3"); } else { - sprintf(buf,"./komodo-cli -ac_name=%s",argv[1]); + sprintf(buf,"./hush-cli -ac_name=%s",argv[1]); REFCOIN_CLI = clonestr(buf); coinstr = clonestr(argv[1]); } diff --git a/src/cc/dice.cpp b/src/cc/dice.cpp index 4dd519b8d..67e5ff1bf 100644 --- a/src/cc/dice.cpp +++ b/src/cc/dice.cpp @@ -1732,7 +1732,7 @@ void *dealer0_loop(void *_arg) if ( num < DICE_MINUTXOS ) // this deadlocks, need to put it in a different thread { char *cmd = (char *)malloc(100 * 128); - sprintf(cmd,"./komodo-cli -ac_name=%s sendmany \"\" \"{\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002}\"",SMART_CHAIN_SYMBOL,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr); + sprintf(cmd,"./hush-cli -ac_name=%s sendmany \"\" \"{\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002,\\\"%s\\\":0.0002}\"",SMART_CHAIN_SYMBOL,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr,coinaddr); n = sqrt((DICE_MINUTXOS - num) / 100)*2 + 1; fprintf(stderr,"num normal 0.0002 utxos.%d < %d -> n.%d\n",num,DICE_MINUTXOS,n); for (i=0; i= 72) { if (strcmp("BTC", &s[68]) == 0) return 1; - if (strcmp("KMD", &s[68]) == 0) return 1; + if (strcmp("HUSH3", &s[68]) == 0) return 1; } return 0; } diff --git a/src/cc/games/prices.c b/src/cc/games/prices.c index f23a4ccea..dc046d667 100644 --- a/src/cc/games/prices.c +++ b/src/cc/games/prices.c @@ -206,7 +206,7 @@ int32_t issue_games_events(struct games_state *rs,char *gametxidstr,uint32_t eve sprintf(params,"[\"events\",\"17\",\"[%%22%08x%%22,%%22%s%%22,%u]\"]",(uint32_t)c&0xffffffff,gametxidstr,eventid); else if ( sizeof(c) == 8 ) sprintf(params,"[\"events\",\"17\",\"[%%22%016llx%%22,%%22%s%%22,%u]\"]",(long long)c,gametxidstr,eventid); - if ( (retstr= komodo_issuemethod(USERPASS,(char *)"cclib",params,GAMES_PORT)) != 0 ) + if ( (retstr= hush_issuemethod(USERPASS,(char *)"cclib",params,GAMES_PORT)) != 0 ) { if ( (retjson= cJSON_Parse(retstr)) != 0 ) { @@ -237,7 +237,7 @@ int32_t issue_bet(struct games_state *rs,int64_t x,int64_t betsize) x >>= 8; } sprintf(params,"[\"bet\",\"17\",\"[%.8f,%%22%s%%22]\"]",dstr(betsize),hexstr); - if ( (retstr= komodo_issuemethod(USERPASS,(char *)"cclib",params,GAMES_PORT)) != 0 ) + if ( (retstr= hush_issuemethod(USERPASS,(char *)"cclib",params,GAMES_PORT)) != 0 ) { if ( (retjson= cJSON_Parse(retstr)) != 0 ) { diff --git a/src/cc/games/tetris.c b/src/cc/games/tetris.c index c0a3633f2..848e9aacc 100644 --- a/src/cc/games/tetris.c +++ b/src/cc/games/tetris.c @@ -822,7 +822,7 @@ int32_t issue_games_events(struct games_state *rs,char *gametxidstr,uint32_t eve sprintf(params,"[\"events\",\"17\",\"[%%22%08x%%22,%%22%s%%22,%u]\"]",(uint32_t)c&0xffffffff,gametxidstr,eventid); else if ( sizeof(c) == 8 ) sprintf(params,"[\"events\",\"17\",\"[%%22%016llx%%22,%%22%s%%22,%u]\"]",(long long)c,gametxidstr,eventid); - if ( (retstr= komodo_issuemethod(USERPASS,(char *)"cclib",params,GAMES_PORT)) != 0 ) + if ( (retstr= hush_issuemethod(USERPASS,(char *)"cclib",params,GAMES_PORT)) != 0 ) { if ( (retjson= cJSON_Parse(retstr)) != 0 ) { diff --git a/src/cc/gamescc.cpp b/src/cc/gamescc.cpp index 810907c89..e2d563d00 100644 --- a/src/cc/gamescc.cpp +++ b/src/cc/gamescc.cpp @@ -874,7 +874,7 @@ uint64_t games_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 obj.push_back(Pair("seed",(int64_t)seed)); if ( games_iamregistered(maxplayers,gametxid,tx,mygamesaddr) > 0 ) sprintf(cmd,"cc/%s %llu %s",GAMENAME,(long long)seed,gametxid.ToString().c_str()); - else sprintf(cmd,"./komodo-cli -ac_name=%s cclib register %d \"[%%22%s%%22]\"",SMART_CHAIN_SYMBOL,EVAL_GAMES,gametxid.ToString().c_str()); + else sprintf(cmd,"./hush-cli -ac_name=%s cclib register %d \"[%%22%s%%22]\"",SMART_CHAIN_SYMBOL,EVAL_GAMES,gametxid.ToString().c_str()); obj.push_back(Pair("run",cmd)); } } diff --git a/src/cc/gateways.cpp b/src/cc/gateways.cpp index fe70b4625..c8036e5f2 100644 --- a/src/cc/gateways.cpp +++ b/src/cc/gateways.cpp @@ -33,8 +33,8 @@ the potential pubkeys to be used would be based on active oracle data providers with recent activity. - bind asset <-> KMD gateway deposit address - KMD deposit -> globally spendable marker utxo + bind asset <-> HUSH gateway deposit address + HUSH deposit -> globally spendable marker utxo spend marker utxo and spend linked/locked asset to user's CC address redeem -> asset to global CC address with withdraw address -> gateway spendable marker utxo @@ -57,19 +57,19 @@ In order to create a new gateway it is necessary to follow some strict steps. 1. create a token with the max possible supply that will be issued 2. transfer 100% of them to the gateways CC's global pubkey's asset CC address. (yes it is a bit confusing) - 3. create an oracle with the identical name, ie. KMD and format must start with Ihh (height, blockhash, merkleroot) + 3. create an oracle with the identical name, ie. HUSH and format must start with Ihh (height, blockhash, merkleroot) 4. register a publisher and fund it with a subscribe. there will be a special client app that will automatically publish the merkleroots. 5. Now a gatewaysbind can bind an external coin to an asset, along with the oracle for the merkleroots. the txid from the bind is used in most of the other gateways CC calls usage: - ./c tokencreate KMD 1000000 KMD_equivalent_token_for_gatewaysCC + ./c tokencreate HUSH 1000000 HUSH_equivalent_token_for_gatewaysCC a7398a8748354dd0a3f8d07d70e65294928ecc3674674bb2d9483011ccaa9a7a transfer to gateways pubkey: 03ea9c062b9652d8eff34879b504eda0717895d27597aaeb60347d65eed96ccb40 RDMqGyREkP1Gwub1Nr5Ye8a325LGZsWBCb ./c tokentransfer a7398a8748354dd0a3f8d07d70e65294928ecc3674674bb2d9483011ccaa9a7a 03ea9c062b9652d8eff34879b504eda0717895d27597aaeb60347d65eed96ccb40 100000000000000 2206fc39c0f384ca79819eb491ddbf889642cbfe4d0796bb6a8010ed53064a56 - ./c oraclescreate KMD blockheaders Ihh + ./c oraclescreate HUSH blockheaders Ihh 1f1aefcca2bdea8196cfd77337fb21de22d200ddea977c2f9e8742c55829d808 ./c oraclesregister 1f1aefcca2bdea8196cfd77337fb21de22d200ddea977c2f9e8742c55829d808 1000000 @@ -79,7 +79,7 @@ f9499d8bb04ffb511fcec4838d72e642ec832558824a2ce5aed87f1f686f8102 gatewaysbind tokenid oracletxid coin tokensupply M N pubkey(s) - ./c gatewaysbind a7398a8748354dd0a3f8d07d70e65294928ecc3674674bb2d9483011ccaa9a7a 1f1aefcca2bdea8196cfd77337fb21de22d200ddea977c2f9e8742c55829d808 KMD 100000000000000 1 1 02ebc786cb83de8dc3922ab83c21f3f8a2f3216940c3bf9da43ce39e2a3a882c92 + ./c gatewaysbind a7398a8748354dd0a3f8d07d70e65294928ecc3674674bb2d9483011ccaa9a7a 1f1aefcca2bdea8196cfd77337fb21de22d200ddea977c2f9e8742c55829d808 HUSH 100000000000000 1 1 02ebc786cb83de8dc3922ab83c21f3f8a2f3216940c3bf9da43ce39e2a3a882c92 e6c99f79d4afb216aa8063658b4222edb773dd24bb0f8e91bd4ef341f3e47e5e ./c gatewaysinfo e6c99f79d4afb216aa8063658b4222edb773dd24bb0f8e91bd4ef341f3e47e5e @@ -87,7 +87,7 @@ "result": "success", "name": "Gateways", "pubkey": "02ebc786cb83de8dc3922ab83c21f3f8a2f3216940c3bf9da43ce39e2a3a882c92", - "coin": "KMD", + "coin": "HUSH", "oracletxid": "1f1aefcca2bdea8196cfd77337fb21de22d200ddea977c2f9e8742c55829d808", "taddr": 0, "prefix": 60, @@ -99,40 +99,40 @@ "issued": "0.00000000" } - To make a gateway deposit, send the funds to the "deposit" address, along with any amount to the same pubkey address you want to get the assetized KMD to appear in. + To make a gateway deposit, send the funds to the "deposit" address, along with any amount to the same pubkey address you want to get the assetized HUSH to appear in. 0223d114dededb04f253816d6ad0ce78dd08c617c94ce3c53bf50dc74a5157bef8 pubkey for RFpxgqff7FDHFuHa3jSX5NzqqWCcELz8ha - ./komodo-cli z_sendmany "" '[{"address":"RFpxgqff7FDHFuHa3jSX5NzqqWCcELz8ha","amount":0.0001},{"address":"RHV2As4rox97BuE3LK96vMeNY8VsGRTmBj","amount":7.6999}]' + ./hush-cli z_sendmany "" '[{"address":"RFpxgqff7FDHFuHa3jSX5NzqqWCcELz8ha","amount":0.0001},{"address":"RHV2As4rox97BuE3LK96vMeNY8VsGRTmBj","amount":7.6999}]' bc41a00e429db741c3199f17546a48012fd3b7eea45dfc6bc2f5228278133009 height.1003776 merkle.90aedc2f19200afc9aca2e351438d011ebae8264a58469bf225883045f61917f - ./komodo-cli gettxoutproof '["bc41a00e429db741c3199f17546a48012fd3b7eea45dfc6bc2f5228278133009"]' + ./hush-cli gettxoutproof '["bc41a00e429db741c3199f17546a48012fd3b7eea45dfc6bc2f5228278133009"]' 04000000232524ea04b54489eb222f8b3f566ed35504e3050488a63f0ab7b1c2030000007f91615f04835822bf6984a56482aeeb11d03814352eca9afc0a20192fdcae900000000000000000000000000000000000000000000000000000000000000000268e965ba608071d0800038e16762900000000000000000000000000000000000000000042008dd6fd4005016b4292b05df6dfd316c458c53e28fb2befb96e4870a40c6c04e733d75d8a7a18cce34fe326005efdc403bfa4644e30eeafdaeff34419edc591299e6cc5933cb2eeecbab5c4dfe97cd413b75215999a3dd02b540373581e81d8512bff1640590a6b4da4aaa9b8adc0102c38ca0022daed997b53ed192ba326e212fba5e505ce29e3ad149cef7f48d0e00948a1acd81731d84008760759211eb4abbc7b037939a7964182edb59cf9065357e864188ee5fc7316e8796963036bb99eeb9f06c95d64f78749ecec7181c12eb5d83a3b9b1c1e8a0aae9a20ce04a250b28216620bfc99bb81a6de4db80b93a5aea916de97c1a272e26644abdd683f19c5e3174a2e4513ed767d8f11a4c3074295f697839c5d9139676a813451cc7da38f68cbae5d990a79075f98903233ca04fe1b4b099e433585e5adcc45d41d54a9c648179297359c75950a5e574f13f70b728bbbf552770256315cd0a00139d6ab6934cb5ed70a4fc01a92611b096dd0028f17f4cc687b75f37dca530aa47a18321c50528dbd9272eabb3e13a87021a05918a6d2627e2caba6d7cf1a9f0b831ea3337b9a6af92746d83140078d60c72b6beacf91c9e68a34cee209e08670be1d17ff8d80b7a2285b1325461a2e33f2ee675593f1900e066a5d212615cd8da18749b0e684eee73edcc9031709be715b889c6d015cf4bd4ad5ab7e21bd3492c208930a54d353ef36a437f507ead38855633c1b88d060d9e4221ca8ce2f698e8a6ae0d41e9ace3cbd401f1e0f07650e9c126d4ef20278c8be6e85c7637513643f8d02d7ad64c09da11c16429d60e5160c345844b8158ece62794e8ad280d4e4664150e74978609ece431e51a9f9e1ce8aa49c16f36c7fd12b71acc42d893e18476b8b1e144a8175519612efc93e0aecc61f3b21212c958b0e2331d76aaa62faf11a58fe2bd91ab9ab01b906406c9bbc02df2a106e67182aae0a20b538bf19f09c57f9de5e198ba254580fb1b11e22ad526550093420cb7c68628d4c3ad329c8acc6e219093d277810ed016b6099b7e3781de412a22dacedaa2acf29e8062debcd85c7b9529a20b2782a2470763ac27cf89611a527d43ac89b8063ffb93b6ed993425194f8ee821a8493a563072c896f9584f95db28e3f2fc5fb4a6f3c39d615cd563641717cd50afb73ed3989cbf504b2043882993ce9575f56402534173b1396fbc13df80920b46788ae340ad5a91f25177cc74aa69024d76f56166199d2e4d50a053555256c4e3137ea1cee1130e916a88b6ee5cf2c85652fb8824d5dacfa485e3ef6190591ac0c2fcacc4fc7deb65aca4b0b89b76e35a46b0627e2e967cc63a5d606a984c8e63eabb98fde3e69114340ae524c974cb936e57690e98a7a74533f6f7d1d0496976496b54d14a8163efb32b70dfbb79d80a3022c4f53571c08bf044270565716b435084376714b224ab23e9817c05af8223723afc0577af5c8fc28f71036ca82528aaa4ca9bcd18a50e25d2a528f183d3a2074d968d170876d8dce434c5937261b55173ab87e03d5632ca0834fdc5387c15ab3a17d75c0f274004f289ff1bf7d14e97fdf4172eb49adfb418cc2f4794806ae7c0111c97df4d65d38679ec93fea3ef738ed565e8906a8fe1861cafe3938c772fedcfab40159938e06ef414fd299f2355c6d3369bc1bd3c4db64ce205f0a1b70a40030f505b736e28230de82e97776b5ee7b10708bb3020d28cec7a8e124549ec80c547ac4e7b52bf397c72bcfce30820554ab8fb4d1f73b209bc32a0e7e878843cdbf5f01222728ccea7e6ab7cb5e3fee3234f5b85d1985f91492f6ceaa6454a658dab5074f163ce26ed753137fa61c940679de13bd7b212cd3cf2b334f5201cecbc7473342bd7a239e09169bccd56d03000000037a9068df0625e548e71263c8361b4e904c998378f6b9e32729c3f19b10ad752e093013788222f5c26bfc5da4eeb7d32f01486a54179f19c341b79d420ea041bc8878d22fad4692b2d609c3cf190903874d3682a714c7483518c9392e07c25035010b - ./komodo-cli getrawtransaction bc41a00e429db741c3199f17546a48012fd3b7eea45dfc6bc2f5228278133009 + ./hush-cli getrawtransaction bc41a00e429db741c3199f17546a48012fd3b7eea45dfc6bc2f5228278133009 010000000149964cdcd17fe9b1cae4d0f3b5f5db301d9b4f54099fdf4d34498df281757094010000006a4730440220594f3a630dd73c123f44621aa8bb9968ab86734833453dd479af6d79ae6f584202207bb5e35f13b337ccc8a88d9a006c8c5ddb016c0a6f4f2dc44357a8128623d85d01210223154bf53cd3a75e64d86697070d6437c8f0010a09c1df35b659e31ce3d79b5dffffffff0310270000000000001976a91447d2e323a14b0c3be08698aa46a9b91489b189d688ac701de52d000000001976a91459fdba29ea85c65ad90f6d38f7a6646476b26b1688acb0a86a00000000001976a914f9a9daf5519dae38b8b61d945f075da895df441d88ace18d965b gatewaysdeposit bindtxid height coin cointxid claimvout deposithex proof destpub amount - ./komodo-cli -ac_name=AT5 gatewaysdeposit e6c99f79d4afb216aa8063658b4222edb773dd24bb0f8e91bd4ef341f3e47e5e 1003776 KMD bc41a00e429db741c3199f17546a48012fd3b7eea45dfc6bc2f5228278133009 0 010000000149964cdcd17fe9b1cae4d0f3b5f5db301d9b4f54099fdf4d34498df281757094010000006a4730440220594f3a630dd73c123f44621aa8bb9968ab86734833453dd479af6d79ae6f584202207bb5e35f13b337ccc8a88d9a006c8c5ddb016c0a6f4f2dc44357a8128623d85d01210223154bf53cd3a75e64d86697070d6437c8f0010a09c1df35b659e31ce3d79b5dffffffff0310270000000000001976a91447d2e323a14b0c3be08698aa46a9b91489b189d688ac701de52d000000001976a91459fdba29ea85c65ad90f6d38f7a6646476b26b1688acb0a86a00000000001976a914f9a9daf5519dae38b8b61d945f075da895df441d88ace18d965b 04000000232524ea04b54489eb222f8b3f566ed35504e3050488a63f0ab7b1c2030000007f91615f04835822bf6984a56482aeeb11d03814352eca9afc0a20192fdcae900000000000000000000000000000000000000000000000000000000000000000268e965ba608071d0800038e16762900000000000000000000000000000000000000000042008dd6fd4005016b4292b05df6dfd316c458c53e28fb2befb96e4870a40c6c04e733d75d8a7a18cce34fe326005efdc403bfa4644e30eeafdaeff34419edc591299e6cc5933cb2eeecbab5c4dfe97cd413b75215999a3dd02b540373581e81d8512bff1640590a6b4da4aaa9b8adc0102c38ca0022daed997b53ed192ba326e212fba5e505ce29e3ad149cef7f48d0e00948a1acd81731d84008760759211eb4abbc7b037939a7964182edb59cf9065357e864188ee5fc7316e8796963036bb99eeb9f06c95d64f78749ecec7181c12eb5d83a3b9b1c1e8a0aae9a20ce04a250b28216620bfc99bb81a6de4db80b93a5aea916de97c1a272e26644abdd683f19c5e3174a2e4513ed767d8f11a4c3074295f697839c5d9139676a813451cc7da38f68cbae5d990a79075f98903233ca04fe1b4b099e433585e5adcc45d41d54a9c648179297359c75950a5e574f13f70b728bbbf552770256315cd0a00139d6ab6934cb5ed70a4fc01a92611b096dd0028f17f4cc687b75f37dca530aa47a18321c50528dbd9272eabb3e13a87021a05918a6d2627e2caba6d7cf1a9f0b831ea3337b9a6af92746d83140078d60c72b6beacf91c9e68a34cee209e08670be1d17ff8d80b7a2285b1325461a2e33f2ee675593f1900e066a5d212615cd8da18749b0e684eee73edcc9031709be715b889c6d015cf4bd4ad5ab7e21bd3492c208930a54d353ef36a437f507ead38855633c1b88d060d9e4221ca8ce2f698e8a6ae0d41e9ace3cbd401f1e0f07650e9c126d4ef20278c8be6e85c7637513643f8d02d7ad64c09da11c16429d60e5160c345844b8158ece62794e8ad280d4e4664150e74978609ece431e51a9f9e1ce8aa49c16f36c7fd12b71acc42d893e18476b8b1e144a8175519612efc93e0aecc61f3b21212c958b0e2331d76aaa62faf11a58fe2bd91ab9ab01b906406c9bbc02df2a106e67182aae0a20b538bf19f09c57f9de5e198ba254580fb1b11e22ad526550093420cb7c68628d4c3ad329c8acc6e219093d277810ed016b6099b7e3781de412a22dacedaa2acf29e8062debcd85c7b9529a20b2782a2470763ac27cf89611a527d43ac89b8063ffb93b6ed993425194f8ee821a8493a563072c896f9584f95db28e3f2fc5fb4a6f3c39d615cd563641717cd50afb73ed3989cbf504b2043882993ce9575f56402534173b1396fbc13df80920b46788ae340ad5a91f25177cc74aa69024d76f56166199d2e4d50a053555256c4e3137ea1cee1130e916a88b6ee5cf2c85652fb8824d5dacfa485e3ef6190591ac0c2fcacc4fc7deb65aca4b0b89b76e35a46b0627e2e967cc63a5d606a984c8e63eabb98fde3e69114340ae524c974cb936e57690e98a7a74533f6f7d1d0496976496b54d14a8163efb32b70dfbb79d80a3022c4f53571c08bf044270565716b435084376714b224ab23e9817c05af8223723afc0577af5c8fc28f71036ca82528aaa4ca9bcd18a50e25d2a528f183d3a2074d968d170876d8dce434c5937261b55173ab87e03d5632ca0834fdc5387c15ab3a17d75c0f274004f289ff1bf7d14e97fdf4172eb49adfb418cc2f4794806ae7c0111c97df4d65d38679ec93fea3ef738ed565e8906a8fe1861cafe3938c772fedcfab40159938e06ef414fd299f2355c6d3369bc1bd3c4db64ce205f0a1b70a40030f505b736e28230de82e97776b5ee7b10708bb3020d28cec7a8e124549ec80c547ac4e7b52bf397c72bcfce30820554ab8fb4d1f73b209bc32a0e7e878843cdbf5f01222728ccea7e6ab7cb5e3fee3234f5b85d1985f91492f6ceaa6454a658dab5074f163ce26ed753137fa61c940679de13bd7b212cd3cf2b334f5201cecbc7473342bd7a239e09169bccd56d03000000037a9068df0625e548e71263c8361b4e904c998378f6b9e32729c3f19b10ad752e093013788222f5c26bfc5da4eeb7d32f01486a54179f19c341b79d420ea041bc8878d22fad4692b2d609c3cf190903874d3682a714c7483518c9392e07c25035010b 0223d114dededb04f253816d6ad0ce78dd08c617c94ce3c53bf50dc74a5157bef8 7.6999 + ./hush-cli -ac_name=AT5 gatewaysdeposit e6c99f79d4afb216aa8063658b4222edb773dd24bb0f8e91bd4ef341f3e47e5e 1003776 HUSH bc41a00e429db741c3199f17546a48012fd3b7eea45dfc6bc2f5228278133009 0 010000000149964cdcd17fe9b1cae4d0f3b5f5db301d9b4f54099fdf4d34498df281757094010000006a4730440220594f3a630dd73c123f44621aa8bb9968ab86734833453dd479af6d79ae6f584202207bb5e35f13b337ccc8a88d9a006c8c5ddb016c0a6f4f2dc44357a8128623d85d01210223154bf53cd3a75e64d86697070d6437c8f0010a09c1df35b659e31ce3d79b5dffffffff0310270000000000001976a91447d2e323a14b0c3be08698aa46a9b91489b189d688ac701de52d000000001976a91459fdba29ea85c65ad90f6d38f7a6646476b26b1688acb0a86a00000000001976a914f9a9daf5519dae38b8b61d945f075da895df441d88ace18d965b 04000000232524ea04b54489eb222f8b3f566ed35504e3050488a63f0ab7b1c2030000007f91615f04835822bf6984a56482aeeb11d03814352eca9afc0a20192fdcae900000000000000000000000000000000000000000000000000000000000000000268e965ba608071d0800038e16762900000000000000000000000000000000000000000042008dd6fd4005016b4292b05df6dfd316c458c53e28fb2befb96e4870a40c6c04e733d75d8a7a18cce34fe326005efdc403bfa4644e30eeafdaeff34419edc591299e6cc5933cb2eeecbab5c4dfe97cd413b75215999a3dd02b540373581e81d8512bff1640590a6b4da4aaa9b8adc0102c38ca0022daed997b53ed192ba326e212fba5e505ce29e3ad149cef7f48d0e00948a1acd81731d84008760759211eb4abbc7b037939a7964182edb59cf9065357e864188ee5fc7316e8796963036bb99eeb9f06c95d64f78749ecec7181c12eb5d83a3b9b1c1e8a0aae9a20ce04a250b28216620bfc99bb81a6de4db80b93a5aea916de97c1a272e26644abdd683f19c5e3174a2e4513ed767d8f11a4c3074295f697839c5d9139676a813451cc7da38f68cbae5d990a79075f98903233ca04fe1b4b099e433585e5adcc45d41d54a9c648179297359c75950a5e574f13f70b728bbbf552770256315cd0a00139d6ab6934cb5ed70a4fc01a92611b096dd0028f17f4cc687b75f37dca530aa47a18321c50528dbd9272eabb3e13a87021a05918a6d2627e2caba6d7cf1a9f0b831ea3337b9a6af92746d83140078d60c72b6beacf91c9e68a34cee209e08670be1d17ff8d80b7a2285b1325461a2e33f2ee675593f1900e066a5d212615cd8da18749b0e684eee73edcc9031709be715b889c6d015cf4bd4ad5ab7e21bd3492c208930a54d353ef36a437f507ead38855633c1b88d060d9e4221ca8ce2f698e8a6ae0d41e9ace3cbd401f1e0f07650e9c126d4ef20278c8be6e85c7637513643f8d02d7ad64c09da11c16429d60e5160c345844b8158ece62794e8ad280d4e4664150e74978609ece431e51a9f9e1ce8aa49c16f36c7fd12b71acc42d893e18476b8b1e144a8175519612efc93e0aecc61f3b21212c958b0e2331d76aaa62faf11a58fe2bd91ab9ab01b906406c9bbc02df2a106e67182aae0a20b538bf19f09c57f9de5e198ba254580fb1b11e22ad526550093420cb7c68628d4c3ad329c8acc6e219093d277810ed016b6099b7e3781de412a22dacedaa2acf29e8062debcd85c7b9529a20b2782a2470763ac27cf89611a527d43ac89b8063ffb93b6ed993425194f8ee821a8493a563072c896f9584f95db28e3f2fc5fb4a6f3c39d615cd563641717cd50afb73ed3989cbf504b2043882993ce9575f56402534173b1396fbc13df80920b46788ae340ad5a91f25177cc74aa69024d76f56166199d2e4d50a053555256c4e3137ea1cee1130e916a88b6ee5cf2c85652fb8824d5dacfa485e3ef6190591ac0c2fcacc4fc7deb65aca4b0b89b76e35a46b0627e2e967cc63a5d606a984c8e63eabb98fde3e69114340ae524c974cb936e57690e98a7a74533f6f7d1d0496976496b54d14a8163efb32b70dfbb79d80a3022c4f53571c08bf044270565716b435084376714b224ab23e9817c05af8223723afc0577af5c8fc28f71036ca82528aaa4ca9bcd18a50e25d2a528f183d3a2074d968d170876d8dce434c5937261b55173ab87e03d5632ca0834fdc5387c15ab3a17d75c0f274004f289ff1bf7d14e97fdf4172eb49adfb418cc2f4794806ae7c0111c97df4d65d38679ec93fea3ef738ed565e8906a8fe1861cafe3938c772fedcfab40159938e06ef414fd299f2355c6d3369bc1bd3c4db64ce205f0a1b70a40030f505b736e28230de82e97776b5ee7b10708bb3020d28cec7a8e124549ec80c547ac4e7b52bf397c72bcfce30820554ab8fb4d1f73b209bc32a0e7e878843cdbf5f01222728ccea7e6ab7cb5e3fee3234f5b85d1985f91492f6ceaa6454a658dab5074f163ce26ed753137fa61c940679de13bd7b212cd3cf2b334f5201cecbc7473342bd7a239e09169bccd56d03000000037a9068df0625e548e71263c8361b4e904c998378f6b9e32729c3f19b10ad752e093013788222f5c26bfc5da4eeb7d32f01486a54179f19c341b79d420ea041bc8878d22fad4692b2d609c3cf190903874d3682a714c7483518c9392e07c25035010b 0223d114dededb04f253816d6ad0ce78dd08c617c94ce3c53bf50dc74a5157bef8 7.6999 -> 9d80ea79a65aaa0d464f8b762356fa01047e16e9793505a22ca04559f81a6eb6 to get the merkleroots onchain, from the multisig signers nodes run the oraclefeed program with acname oracletxid pubkey Ihh ./oraclefeed AT5 1f1aefcca2bdea8196cfd77337fb21de22d200ddea977c2f9e8742c55829d808 02ebc786cb83de8dc3922ab83c21f3f8a2f3216940c3bf9da43ce39e2a3a882c92 Ihh gatewaysclaim bindtxid coin deposittxid destpub amount - ./c gatewaysclaim e6c99f79d4afb216aa8063658b4222edb773dd24bb0f8e91bd4ef341f3e47e5e KMD 9d80ea79a65aaa0d464f8b762356fa01047e16e9793505a22ca04559f81a6eb6 0223d114dededb04f253816d6ad0ce78dd08c617c94ce3c53bf50dc74a5157bef8 7.6999 + ./c gatewaysclaim e6c99f79d4afb216aa8063658b4222edb773dd24bb0f8e91bd4ef341f3e47e5e HUSH 9d80ea79a65aaa0d464f8b762356fa01047e16e9793505a22ca04559f81a6eb6 0223d114dededb04f253816d6ad0ce78dd08c617c94ce3c53bf50dc74a5157bef8 7.6999 now the asset is in the pubkey's asset address! it can be used, traded freely and any node who has the asset can do a gatewayswithdraw gatewayswithdraw bindtxid coin withdrawpub amount - ./c gatewayswithdraw e6c99f79d4afb216aa8063658b4222edb773dd24bb0f8e91bd4ef341f3e47e5e KMD 03b7621b44118017a16043f19b30cc8a4cfe068ac4e42417bae16ba460c80f3828 1 + ./c gatewayswithdraw e6c99f79d4afb216aa8063658b4222edb773dd24bb0f8e91bd4ef341f3e47e5e HUSH 03b7621b44118017a16043f19b30cc8a4cfe068ac4e42417bae16ba460c80f3828 1 ef3cc452da006eb2edda6b6ed3d3347664be51260f3e91f59ec44ec9701367f0 - Now there is a withdraw pending, so it needs to be processed by the signing nodes on the KMD side + Now there is a withdraw pending, so it needs to be processed by the signing nodes on the HUSH side gatewayspending bindtxid coin gatewayspending will display all pending withdraws and if it is done on one of the msigpubkeys, then it will queue it for processing - ./c gatewayspending e6c99f79d4afb216aa8063658b4222edb773dd24bb0f8e91bd4ef341f3e47e5e KMD + ./c gatewayspending e6c99f79d4afb216aa8063658b4222edb773dd24bb0f8e91bd4ef341f3e47e5e HUSH Implementation Issues: @@ -151,10 +151,10 @@ */ // start of consensus code -#define KMD_PUBTYPE 60 -#define KMD_P2SHTYPE 85 -#define KMD_WIFTYPE 188 -#define KMD_TADDR 0 +#define HUSH_PUBTYPE 60 +#define HUSH_P2SHTYPE 85 +#define HUSH_WIFTYPE 188 +#define HUSH_TADDR 0 #define CC_MARKER_VALUE 10000 CScript EncodeGatewaysBindOpRet(uint8_t funcid,uint256 tokenid,std::string coin,int64_t totalsupply,uint256 oracletxid,uint8_t M,uint8_t N,std::vector gatewaypubkeys,uint8_t taddr,uint8_t prefix,uint8_t prefix2,uint8_t wiftype) @@ -184,7 +184,7 @@ uint8_t DecodeGatewaysBindOpRet(char *depositaddr,const CScript &scriptPubKey,ui depositaddr[0] = 0; if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> coin; ss >> totalsupply; ss >> oracletxid; ss >> M; ss >> N; ss >> gatewaypubkeys; ss >> taddr; ss >> prefix; ss >> prefix2; ss >> wiftype) != 0 ) { - if ( prefix == KMD_PUBTYPE && prefix2 == KMD_P2SHTYPE ) + if ( prefix == HUSH_PUBTYPE && prefix2 == HUSH_P2SHTYPE ) { if ( N > 1 ) { @@ -612,7 +612,7 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & sprintf(validationError,"illegal format %s != Ihh\n",format.c_str()); return eval->Invalid(validationError); } - else if (komodo_txnotarizedconfirmed(bindtxid) == false) + else if (hush_txnotarizedconfirmed(bindtxid) == false) return eval->Invalid("gatewaysbind tx is not yet confirmed(notarised)!"); else if (myGetTransaction(deposittxid,tmptx,hashblock) == 0) return eval->Invalid("invalid gatewaysdeposittxid!"); @@ -630,7 +630,7 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & return eval->Invalid("bindtxid does not match to bindtxid from gatewaysdeposit"); else if (tmpamount>totalsupply) return eval->Invalid("deposit amount greater then bind total supply"); - else if (komodo_txnotarizedconfirmed(deposittxid) == false) + else if (hush_txnotarizedconfirmed(deposittxid) == false) return eval->Invalid("gatewaysdeposit tx is not yet confirmed(notarised)!"); else if (tx.vin.size()>0) { @@ -704,7 +704,7 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & return eval->Invalid("invalid marker vout for gatewaysWithdraw!"); else if ( ConstrainVout(tmptx.vout[1],1,gatewaystokensaddr,amount)==0) return eval->Invalid("invalid tokens to gateways vout for gatewaysWithdraw!"); - else if (komodo_txnotarizedconfirmed(withdrawtxid) == false) + else if (hush_txnotarizedconfirmed(withdrawtxid) == false) return eval->Invalid("gatewayswithdraw tx is not yet confirmed(notarised)!"); else if (myGetTransaction(bindtxid,tmptx,hashblock) == 0) return eval->Invalid("invalid gatewaysbind txid!"); @@ -714,7 +714,7 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & return eval->Invalid("refcoin different than in bind tx"); else if (tmptokenid!=tokenid) return eval->Invalid("tokenid does not match tokenid from gatewaysbind"); - else if (komodo_txnotarizedconfirmed(bindtxid) == false) + else if (hush_txnotarizedconfirmed(bindtxid) == false) return eval->Invalid("gatewaysbind tx is not yet confirmed(notarised)!"); else if (IsCCInput(tx.vin[0].scriptSig) != 0) return eval->Invalid("vin.0 is normal for gatewayspartialsign!"); @@ -746,7 +746,7 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & return eval->Invalid("invalid tokens to gateways vout for gatewaysWithdraw!"); else if (tmptx.vout[1].nValue!=amount) return eval->Invalid("amount in opret not matching tx tokens amount!"); - else if (komodo_txnotarizedconfirmed(withdrawtxid) == false) + else if (hush_txnotarizedconfirmed(withdrawtxid) == false) return eval->Invalid("gatewayswithdraw tx is not yet confirmed(notarised)!"); else if (myGetTransaction(bindtxid,tmptx,hashblock) == 0) return eval->Invalid("invalid gatewaysbind txid!"); @@ -756,7 +756,7 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & return eval->Invalid("refcoin different than in bind tx"); else if (tmptokenid!=tokenid) return eval->Invalid("tokenid does not match tokenid from gatewaysbind"); - else if (komodo_txnotarizedconfirmed(bindtxid) == false) + else if (hush_txnotarizedconfirmed(bindtxid) == false) return eval->Invalid("gatewaysbind tx is not yet confirmed(notarised)!"); else if (IsCCInput(tx.vin[0].scriptSig) != 0) return eval->Invalid("vin.0 is normal for gatewayscompletesigning!"); @@ -777,7 +777,7 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & return eval->Invalid("invalid gatewayscompletesigning txid!"); else if ((numvouts=tmptx.vout.size()) > 0 && DecodeGatewaysCompleteSigningOpRet(tmptx.vout[numvouts-1].scriptPubKey,withdrawtxid,tmprefcoin,K,hex)!='S') return eval->Invalid("invalid gatewayscompletesigning OP_RETURN data!"); - else if (komodo_txnotarizedconfirmed(completetxid) == false) + else if (hush_txnotarizedconfirmed(completetxid) == false) return eval->Invalid("gatewayscompletesigning tx is not yet confirmed(notarised)!"); else if (myGetTransaction(withdrawtxid,tmptx,hashblock) == 0) return eval->Invalid("invalid withdraw txid!"); @@ -785,7 +785,7 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & return eval->Invalid("invalid gatewayswithdraw OP_RETURN data!"); else if (tmprefcoin!=refcoin) return eval->Invalid("refcoin different than in bind tx"); - else if (komodo_txnotarizedconfirmed(withdrawtxid) == false) + else if (hush_txnotarizedconfirmed(withdrawtxid) == false) return eval->Invalid("gatewayswithdraw tx is not yet confirmed(notarised)!"); else if (myGetTransaction(bindtxid,tmptx,hashblock) == 0) return eval->Invalid("invalid gatewaysbind txid!"); @@ -795,7 +795,7 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & return eval->Invalid("refcoin different than in bind tx"); else if (tmptokenid!=tokenid) return eval->Invalid("tokenid does not match tokenid from gatewaysbind"); - else if (komodo_txnotarizedconfirmed(bindtxid) == false) + else if (hush_txnotarizedconfirmed(bindtxid) == false) return eval->Invalid("gatewaysbind tx is not yet confirmed(notarised)!"); else if ( IsCCInput(tx.vin[0].scriptSig) != 0 ) return eval->Invalid("vin.0 is normal for gatewaysmarkdone!"); @@ -874,12 +874,12 @@ UniValue GatewaysBind(const CPubKey& pk, uint64_t txfee,std::string coin,uint256 cp = CCinit(&C,EVAL_GATEWAYS); cpTokens = CCinit(&CTokens,EVAL_TOKENS); - if (coin=="KMD") + if (coin=="HUSH") { - prefix = KMD_PUBTYPE; - prefix2 = KMD_P2SHTYPE; - wiftype = KMD_WIFTYPE; - taddr = KMD_TADDR; + prefix = HUSH_PUBTYPE; + prefix2 = HUSH_P2SHTYPE; + wiftype = HUSH_WIFTYPE; + taddr = HUSH_TADDR; } else { @@ -946,7 +946,7 @@ UniValue GatewaysDeposit(const CPubKey& pk, uint64_t txfee,uint256 bindtxid,int3 CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "cant find bindtxid " << bindtxid.GetHex()); if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) != 'B' || refcoin != coin ) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "invalid coin - bindtxid " << bindtxid.GetHex() << " coin." << coin); - if (komodo_txnotarizedconfirmed(bindtxid)==false) + if (hush_txnotarizedconfirmed(bindtxid)==false) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "gatewaysbind tx not yet confirmed/notarized"); n = (int32_t)pubkeys.size(); merkleroot = zeroid; @@ -997,13 +997,13 @@ UniValue GatewaysClaim(const CPubKey& pk, uint64_t txfee,uint256 bindtxid,std::s CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "cant find bindtxid " << bindtxid.GetHex()); if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) != 'B' || refcoin != coin ) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "invalid coin - bindtxid " << bindtxid.GetHex() << " coin." << coin); - if (komodo_txnotarizedconfirmed(bindtxid)==false) + if (hush_txnotarizedconfirmed(bindtxid)==false) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "gatewaysbind tx not yet confirmed/notarized"); if ( myGetTransaction(deposittxid,tx,hashBlock) == 0 || (numvouts= tx.vout.size()) <= 0 ) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "cant find deposittxid " << bindtxid.GetHex()); if (DecodeGatewaysDepositOpRet(tx.vout[numvouts-1].scriptPubKey,tmptxid,coin,publishers,txids,height,cointxid,claimvout,deposithex,proof,tmpdestpub,tmpamount) != 'D' || coin != refcoin) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "invalid coin - deposittxid " << bindtxid.GetHex() << " coin." << coin); - if (komodo_txnotarizedconfirmed(deposittxid)==false) + if (hush_txnotarizedconfirmed(deposittxid)==false) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "gatewaysdeposit tx not yet confirmed/notarized"); if (tmpdestpub!=destpub) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "different destination pubkey from desdeposit tx"); @@ -1038,7 +1038,7 @@ UniValue GatewaysWithdraw(const CPubKey& pk, uint64_t txfee,uint256 bindtxid,std CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "cant find bindtxid " << bindtxid.GetHex()); if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) != 'B' || refcoin != coin ) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "invalid coin - bindtxid " << bindtxid.GetHex() << " coin." << coin); - if (komodo_txnotarizedconfirmed(bindtxid)==false) + if (hush_txnotarizedconfirmed(bindtxid)==false) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "gatewaysbind tx not yet confirmed/notarized"); _GetCCaddress(coinaddr,EVAL_GATEWAYS,gatewayspk); SetCCunspents(unspentOutputs,coinaddr,true); @@ -1097,7 +1097,7 @@ UniValue GatewaysPartialSign(const CPubKey& pk, uint64_t txfee,uint256 lasttxid, withdrawtxid=lasttxid; if (DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount)!='W' || refcoin!=coin) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "invalid withdraw tx " << lasttxid.GetHex()); - else if (komodo_txnotarizedconfirmed(withdrawtxid)==false) + else if (hush_txnotarizedconfirmed(withdrawtxid)==false) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "gatewayswithdraw tx not yet confirmed/notarized"); else if (myGetTransaction(bindtxid,tmptx,hashBlock)==0 || (numvouts=tmptx.vout.size())<=0) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "can't find bind tx " << bindtxid.GetHex()); @@ -1114,7 +1114,7 @@ UniValue GatewaysPartialSign(const CPubKey& pk, uint64_t txfee,uint256 lasttxid, else if (DecodeGatewaysWithdrawOpRet(tmptx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount)!='W' || refcoin!=coin) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "invalid withdraw tx " << withdrawtxid.GetHex()); - else if (komodo_txnotarizedconfirmed(withdrawtxid)==false) + else if (hush_txnotarizedconfirmed(withdrawtxid)==false) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "gatewayswithdraw tx not yet confirmed/notarized"); else if (myGetTransaction(bindtxid,tmptx,hashBlock)==0 || (numvouts=tmptx.vout.size())<=0) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "can't find bind tx " << bindtxid.GetHex()); @@ -1151,7 +1151,7 @@ UniValue GatewaysCompleteSigning(const CPubKey& pk, uint64_t txfee,uint256 lastt withdrawtxid=lasttxid; if (DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount)!='W' || refcoin!=coin) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "invalid withdraw tx " << lasttxid.GetHex()); - else if (komodo_txnotarizedconfirmed(withdrawtxid)==false) + else if (hush_txnotarizedconfirmed(withdrawtxid)==false) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "gatewayswithdraw tx not yet confirmed/notarized"); else if (myGetTransaction(bindtxid,tmptx,hashBlock)==0 || (numvouts=tmptx.vout.size())<=0) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "can't find bind tx " << bindtxid.GetHex()); @@ -1168,7 +1168,7 @@ UniValue GatewaysCompleteSigning(const CPubKey& pk, uint64_t txfee,uint256 lastt else if (DecodeGatewaysWithdrawOpRet(tmptx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount)!='W' || refcoin!=coin) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "invalid withdraw tx " << withdrawtxid.GetHex()); - else if (komodo_txnotarizedconfirmed(withdrawtxid)==false) + else if (hush_txnotarizedconfirmed(withdrawtxid)==false) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "gatewayswithdraw tx not yet confirmed/notarized"); else if (myGetTransaction(bindtxid,tmptx,hashBlock)==0 || (numvouts=tmptx.vout.size())<=0) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "can't find bind tx " << bindtxid.GetHex()); @@ -1200,7 +1200,7 @@ UniValue GatewaysMarkDone(const CPubKey& pk, uint64_t txfee,uint256 completetxid CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "invalid completesigning txid " << completetxid.GetHex()); else if (DecodeGatewaysCompleteSigningOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,coin,K,hex)!='S' || refcoin!=coin) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "cannot decode completesigning tx opret " << completetxid.GetHex()); - if (komodo_txnotarizedconfirmed(completetxid)==false) + if (hush_txnotarizedconfirmed(completetxid)==false) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "gatewayscompletesigning tx not yet confirmed/notarized"); else if (myGetTransaction(withdrawtxid,tx,hashBlock)==0 || (numvouts= tx.vout.size())==0) CCERR_RESULT("gatewayscc",CCLOG_INFO, stream << "invalid withdraw txid " << withdrawtxid.GetHex()); @@ -1266,7 +1266,7 @@ UniValue GatewaysPendingDeposits(const CPubKey& pk, uint256 bindtxid,std::string pub=HexStr(destpub); obj.push_back(Pair("claim_pubkey",pub)); obj.push_back(Pair("amount",(double)amount/COIN)); - obj.push_back(Pair("confirmed_or_notarized",komodo_txnotarizedconfirmed(txid))); + obj.push_back(Pair("confirmed_or_notarized",hush_txnotarizedconfirmed(txid))); pending.push_back(obj); } } @@ -1340,7 +1340,7 @@ UniValue GatewaysPendingWithdraws(const CPubKey& pk, uint256 bindtxid,std::strin obj.push_back(Pair("withdrawaddr",withaddr)); sprintf(numstr,"%.8f",(double)tx.vout[1].nValue/COIN); obj.push_back(Pair("amount",numstr)); - obj.push_back(Pair("confirmed_or_notarized",komodo_txnotarizedconfirmed(tx.GetHash()))); + obj.push_back(Pair("confirmed_or_notarized",hush_txnotarizedconfirmed(tx.GetHash()))); if ( queueflag != 0 ) { obj.push_back(Pair("depositaddr",depositaddr)); @@ -1415,7 +1415,7 @@ UniValue GatewaysProcessedWithdraws(const CPubKey& pk, uint256 bindtxid,std::str obj.push_back(Pair("withdrawtxidaddr",txidaddr)); GetCustomscriptaddress(withaddr,CScript() << ParseHex(HexStr(withdrawpub)) << OP_CHECKSIG,taddr,prefix,prefix2); obj.push_back(Pair("withdrawaddr",withaddr)); - obj.push_back(Pair("confirmed_or_notarized",komodo_txnotarizedconfirmed(txid))); + obj.push_back(Pair("confirmed_or_notarized",hush_txnotarizedconfirmed(txid))); sprintf(numstr,"%.8f",(double)tx.vout[1].nValue/COIN); obj.push_back(Pair("amount",numstr)); obj.push_back(Pair("hex",hex)); diff --git a/src/cc/import.cpp b/src/cc/import.cpp index 06fc75dff..61e901e84 100644 --- a/src/cc/import.cpp +++ b/src/cc/import.cpp @@ -395,7 +395,7 @@ int32_t CheckGATEWAYimport(CTransaction importTx,CTransaction burnTx,std::string LOGSTREAM("importgateway", CCLOG_INFO, stream << "CheckGATEWAYimport not enough pubkeys for given N " << std::endl); return(-1); } - else if (komodo_txnotarizedconfirmed(bindtxid) == false) + else if (hush_txnotarizedconfirmed(bindtxid) == false) { LOGSTREAM("importgateway", CCLOG_INFO, stream << "CheckGATEWAYimport bindtx not yet confirmed/notarized" << std::endl); return(-1); diff --git a/src/cc/importgateway.cpp b/src/cc/importgateway.cpp index b2cd169f7..1afaeec94 100644 --- a/src/cc/importgateway.cpp +++ b/src/cc/importgateway.cpp @@ -19,13 +19,11 @@ #include "CCImportGateway.h" #include "key_io.h" #include "../importcoin.h" - // start of consensus code - -#define KMD_PUBTYPE 60 -#define KMD_P2SHTYPE 85 -#define KMD_WIFTYPE 188 -#define KMD_TADDR 0 +#define HUSH_PUBTYPE 60 +#define HUSH_P2SHTYPE 85 +#define HUSH_WIFTYPE 188 +#define HUSH_TADDR 0 #define CC_MARKER_VALUE 10000 extern uint256 HUSH_EARLYTXID; @@ -46,7 +44,7 @@ uint8_t DecodeImportGatewayBindOpRet(char *burnaddr,const CScript &scriptPubKey, burnaddr[0] = 0; if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> coin; ss >> oracletxid; ss >> M; ss >> N; ss >> importgatewaypubkeys; ss >> taddr; ss >> prefix; ss >> prefix2; ss >> wiftype) != 0 ) { - if ( prefix == KMD_PUBTYPE && prefix2 == KMD_P2SHTYPE ) + if ( prefix == HUSH_PUBTYPE && prefix2 == HUSH_P2SHTYPE ) { if ( N > 1 ) { @@ -362,7 +360,7 @@ bool ImportGatewayValidate(struct CCcontract_info *cp,Eval *eval,const CTransact return eval->Invalid("invalid tokens to gateways vout for gatewaysWithdraw!"); else if (tmptx.vout[1].nValue!=amount) return eval->Invalid("amount in opret not matching tx tokens amount!"); - else if (komodo_txnotarizedconfirmed(withdrawtxid) == false) + else if (hush_txnotarizedconfirmed(withdrawtxid) == false) return eval->Invalid("gatewayswithdraw tx is not yet confirmed(notarised)!"); else if (myGetTransaction(bindtxid,tmptx,hashblock) == 0) return eval->Invalid("invalid gatewaysbind txid!"); @@ -370,7 +368,7 @@ bool ImportGatewayValidate(struct CCcontract_info *cp,Eval *eval,const CTransact return eval->Invalid("invalid gatewaysbind OP_RETURN data!"); else if (tmprefcoin!=refcoin) return eval->Invalid("refcoin different than in bind tx"); - else if (komodo_txnotarizedconfirmed(bindtxid) == false) + else if (hush_txnotarizedconfirmed(bindtxid) == false) return eval->Invalid("gatewaysbind tx is not yet confirmed(notarised)!"); else if (IsCCInput(tx.vin[0].scriptSig) != 0) return eval->Invalid("vin.0 is normal for gatewayspartialsign!"); @@ -404,7 +402,7 @@ bool ImportGatewayValidate(struct CCcontract_info *cp,Eval *eval,const CTransact return eval->Invalid("invalid tokens to gateways vout for gatewaysWithdraw!"); else if (tmptx.vout[1].nValue!=amount) return eval->Invalid("amount in opret not matching tx tokens amount!"); - else if (komodo_txnotarizedconfirmed(withdrawtxid) == false) + else if (hush_txnotarizedconfirmed(withdrawtxid) == false) return eval->Invalid("gatewayswithdraw tx is not yet confirmed(notarised)!"); else if (myGetTransaction(bindtxid,tmptx,hashblock) == 0) return eval->Invalid("invalid gatewaysbind txid!"); @@ -412,7 +410,7 @@ bool ImportGatewayValidate(struct CCcontract_info *cp,Eval *eval,const CTransact return eval->Invalid("invalid gatewaysbind OP_RETURN data!"); else if (tmprefcoin!=refcoin) return eval->Invalid("refcoin different than in bind tx"); - else if (komodo_txnotarizedconfirmed(bindtxid) == false) + else if (hush_txnotarizedconfirmed(bindtxid) == false) return eval->Invalid("gatewaysbind tx is not yet confirmed(notarised)!"); else if (IsCCInput(tx.vin[0].scriptSig) != 0) return eval->Invalid("vin.0 is normal for gatewayscompletesigning!"); @@ -433,7 +431,7 @@ bool ImportGatewayValidate(struct CCcontract_info *cp,Eval *eval,const CTransact return eval->Invalid("invalid gatewayscompletesigning txid!"); else if ((numvouts=tmptx.vout.size()) > 0 && DecodeImportGatewayCompleteSigningOpRet(tmptx.vout[numvouts-1].scriptPubKey,withdrawtxid,tmprefcoin,K,hex)!='S') return eval->Invalid("invalid gatewayscompletesigning OP_RETURN data!"); - else if (komodo_txnotarizedconfirmed(completetxid) == false) + else if (hush_txnotarizedconfirmed(completetxid) == false) return eval->Invalid("gatewayscompletesigning tx is not yet confirmed(notarised)!"); else if (myGetTransaction(withdrawtxid,tmptx,hashblock) == 0) return eval->Invalid("invalid withdraw txid!"); @@ -441,7 +439,7 @@ bool ImportGatewayValidate(struct CCcontract_info *cp,Eval *eval,const CTransact return eval->Invalid("invalid gatewayswithdraw OP_RETURN data!"); else if (tmprefcoin!=refcoin) return eval->Invalid("refcoin different than in bind tx"); - else if (komodo_txnotarizedconfirmed(withdrawtxid) == false) + else if (hush_txnotarizedconfirmed(withdrawtxid) == false) return eval->Invalid("gatewayswithdraw tx is not yet confirmed(notarised)!"); else if (myGetTransaction(bindtxid,tmptx,hashblock) == 0) return eval->Invalid("invalid gatewaysbind txid!"); @@ -449,7 +447,7 @@ bool ImportGatewayValidate(struct CCcontract_info *cp,Eval *eval,const CTransact return eval->Invalid("invalid gatewaysbind OP_RETURN data!"); else if (tmprefcoin!=refcoin) return eval->Invalid("refcoin different than in bind tx"); - else if (komodo_txnotarizedconfirmed(bindtxid) == false) + else if (hush_txnotarizedconfirmed(bindtxid) == false) return eval->Invalid("gatewaysbind tx is not yet confirmed(notarised)!"); else if ( IsCCInput(tx.vin[0].scriptSig) != 0 ) return eval->Invalid("vin.0 is normal for gatewaysmarkdone!"); @@ -481,12 +479,12 @@ std::string ImportGatewayBind(uint64_t txfee,std::string coin,uint256 oracletxid cp = CCinit(&C,EVAL_IMPORTGATEWAY); cpTokens = CCinit(&CTokens,EVAL_TOKENS); - if (coin=="KMD") + if (coin=="HUSH") { - prefix = KMD_PUBTYPE; - prefix2 = KMD_P2SHTYPE; - wiftype = KMD_WIFTYPE; - taddr = KMD_TADDR; + prefix = HUSH_PUBTYPE; + prefix2 = HUSH_P2SHTYPE; + wiftype = HUSH_WIFTYPE; + taddr = HUSH_TADDR; } else { @@ -597,7 +595,7 @@ std::string ImportGatewayDeposit(uint64_t txfee,uint256 bindtxid,int32_t height, LOGSTREAM("importgateway",CCLOG_INFO, stream << CCerror << std::endl); return(""); } - if (komodo_txnotarizedconfirmed(bindtxid)==false) + if (hush_txnotarizedconfirmed(bindtxid)==false) { CCerror = strprintf("gatewaysbind tx not yet confirmed/notarized"); LOGSTREAM("importgateway",CCLOG_INFO, stream << CCerror << std::endl); @@ -673,7 +671,7 @@ std::string ImportGatewayWithdraw(uint64_t txfee,uint256 bindtxid,std::string re LOGSTREAM("importgateway",CCLOG_INFO, stream << CCerror << std::endl); return(""); } - if (komodo_txnotarizedconfirmed(bindtxid)==false) + if (hush_txnotarizedconfirmed(bindtxid)==false) { CCerror = strprintf("gatewaysbind tx not yet confirmed/notarized"); LOGSTREAM("importgateway",CCLOG_INFO, stream << CCerror << std::endl); @@ -754,7 +752,7 @@ std::string ImportGatewayPartialSign(uint64_t txfee,uint256 lasttxid,std::string LOGSTREAM("importgateway",CCLOG_INFO, stream << CCerror << std::endl); return(""); } - else if (komodo_txnotarizedconfirmed(withdrawtxid)==false) + else if (hush_txnotarizedconfirmed(withdrawtxid)==false) { CCerror = strprintf("gatewayswithdraw tx not yet confirmed/notarized"); LOGSTREAM("importgateway",CCLOG_INFO, stream << CCerror << std::endl); @@ -801,7 +799,7 @@ std::string ImportGatewayPartialSign(uint64_t txfee,uint256 lasttxid,std::string LOGSTREAM("importgateway",CCLOG_INFO, stream << CCerror << std::endl); return(""); } - else if (komodo_txnotarizedconfirmed(withdrawtxid)==false) + else if (hush_txnotarizedconfirmed(withdrawtxid)==false) { CCerror = strprintf("gatewayswithdraw tx not yet confirmed/notarized"); LOGSTREAM("importgateway",CCLOG_INFO, stream << CCerror << std::endl); @@ -872,7 +870,7 @@ std::string ImportGatewayCompleteSigning(uint64_t txfee,uint256 lasttxid,std::st LOGSTREAM("importgateway",CCLOG_INFO, stream << CCerror << std::endl); return(""); } - else if (komodo_txnotarizedconfirmed(withdrawtxid)==false) + else if (hush_txnotarizedconfirmed(withdrawtxid)==false) { CCerror = strprintf("gatewayswithdraw tx not yet confirmed/notarized"); LOGSTREAM("importgateway",CCLOG_INFO, stream << CCerror << std::endl); @@ -918,7 +916,7 @@ std::string ImportGatewayCompleteSigning(uint64_t txfee,uint256 lasttxid,std::st LOGSTREAM("importgateway",CCLOG_INFO, stream << CCerror << std::endl); return(""); } - else if (komodo_txnotarizedconfirmed(withdrawtxid)==false) + else if (hush_txnotarizedconfirmed(withdrawtxid)==false) { CCerror = strprintf("gatewayswithdraw tx not yet confirmed/notarized"); LOGSTREAM("importgateway",CCLOG_INFO, stream << CCerror << std::endl); @@ -972,7 +970,7 @@ std::string ImportGatewayMarkDone(uint64_t txfee,uint256 completetxid,std::strin LOGSTREAM("importgateway",CCLOG_INFO, stream << CCerror << std::endl); return(""); } - if (komodo_txnotarizedconfirmed(completetxid)==false) + if (hush_txnotarizedconfirmed(completetxid)==false) { CCerror = strprintf("gatewayscompletesigning tx not yet confirmed/notarized"); LOGSTREAM("importgateway",CCLOG_INFO, stream << CCerror << std::endl); @@ -1084,7 +1082,7 @@ UniValue ImportGatewayPendingWithdraws(uint256 bindtxid,std::string refcoin) obj.push_back(Pair("withdrawaddr",withaddr)); sprintf(numstr,"%.8f",(double)tx.vout[1].nValue/COIN); obj.push_back(Pair("amount",numstr)); - obj.push_back(Pair("confirmed_or_notarized",komodo_txnotarizedconfirmed(tx.GetHash()))); + obj.push_back(Pair("confirmed_or_notarized",hush_txnotarizedconfirmed(tx.GetHash()))); if ( queueflag != 0 ) { obj.push_back(Pair("depositaddr",burnaddr)); @@ -1159,7 +1157,7 @@ UniValue ImportGatewayProcessedWithdraws(uint256 bindtxid,std::string refcoin) obj.push_back(Pair("withdrawtxidaddr",txidaddr)); GetCustomscriptaddress(withaddr,CScript() << ParseHex(HexStr(withdrawpub)) << OP_CHECKSIG,taddr,prefix,prefix2); obj.push_back(Pair("withdrawaddr",withaddr)); - obj.push_back(Pair("confirmed_or_notarized",komodo_txnotarizedconfirmed(txid))); + obj.push_back(Pair("confirmed_or_notarized",hush_txnotarizedconfirmed(txid))); sprintf(numstr,"%.8f",(double)tx.vout[1].nValue/COIN); obj.push_back(Pair("amount",numstr)); obj.push_back(Pair("hex",hex)); diff --git a/src/cc/importpayout.cpp b/src/cc/importpayout.cpp index 2740d8ef2..a3fd90394 100644 --- a/src/cc/importpayout.cpp +++ b/src/cc/importpayout.cpp @@ -31,7 +31,7 @@ * notarised on another chain. * * IN: params - condition params - * IN: importTx - Payout transaction on value chain (KMD) + * IN: importTx - Payout transaction on value chain (HUSH) * IN: nIn - index of input of stake * * importTx: Spends stakeTx with payouts from asset chain diff --git a/src/cc/makerogue b/src/cc/makerogue index ff16cbb16..408b35c77 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,12 +1,14 @@ #!/bin/sh +# Copyright 2016-2021 The Hush developers cd rogue; make clean; if [ "$HOST" = "x86_64-w64-mingw32" ]; then - echo building rogue.exe... + echo "Not supported" + exit 1 ./configure --host=x86_64-w64-mingw32 echo $PWD - wget https://github.com/KomodoPlatform/rogue/releases/download/0.3.3b-01/x86_64-w64-mingw32.tar.gz + # wget ... tar xvfz x86_64-w64-mingw32.tar.gz && rm x86_64-w64-mingw32.tar.gz echo lib archive cleaned echo $PWD diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 4019f2962..363cca280 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -18,7 +18,7 @@ /* first make a combined pk: -./komodo-cli -ac_name=MUSIG cclib combine 18 '["02fb6aa0b96cad24d46b5da93eba3864c45ce07a73bba12da530ae841e140fcf28","0255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4"]' +./hush-cli -ac_name=MUSIG cclib combine 18 '["02fb6aa0b96cad24d46b5da93eba3864c45ce07a73bba12da530ae841e140fcf28","0255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4"]' { "pkhash": "5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b", "combined_pk": "03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b", @@ -28,7 +28,7 @@ the combined_pk and pkhash will be needed for various other rpc calls second, send 1 coin to the combined_pk - ./komodo-cli -ac_name=MUSIG cclib send 18 '["03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b",1]' + ./hush-cli -ac_name=MUSIG cclib send 18 '["03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b",1]' { "hex": "0400008085202f8901a980664dffc810725a79ffb89ac48be4c7b6bade9b789732fcf871acf8e81a2e010000006a47304402207e52763661ecd2c34a65d6623950be11794825db71576dc11894c606ddc317800220028fef46dc20630d0fdf22647b5d4ff0f1c47cf75f48702d0a91d5589eff99d001210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ffffffff031008f60500000000302ea22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401cce09aa4350000000023210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac0000000000000000266a2412782103f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b00000000920500000000000000000000000000", "txid": "5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c", @@ -36,7 +36,7 @@ } sendrawtransaction of the above hex. - ./komodo-cli -ac_name=MUSIG getrawtransaction 5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c 1 + ./hush-cli -ac_name=MUSIG getrawtransaction 5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c 1 "vout": [ { "value": 1.00010000, @@ -72,7 +72,7 @@ get the msg we need to sign: - ./komodo-cli -ac_name=MUSIG cclib calcmsg 18 '["5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c","210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac"]' + ./hush-cli -ac_name=MUSIG cclib calcmsg 18 '["5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c","210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac"]' { "msg": "f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75", @@ -85,7 +85,7 @@ the "msg" is what needs to be signed to create a valid spend 5 args: ind, numsigners, combined_pk, pkhash, message to be signed on node with pubkey: 02fb6aa0b96cad24d46b5da93eba3864c45ce07a73bba12da530ae841e140fcf28 - ./komodo-cli -ac_name=MUSIG cclib session 18 '[0,2,"03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b","5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75"]' + ./hush-cli -ac_name=MUSIG cclib session 18 '[0,2,"03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b","5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75"]' { "myind": 0, "numsigners": 2, @@ -94,7 +94,7 @@ the "msg" is what needs to be signed to create a valid spend } on node with pubkey: 0255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4 - ./komodo-cli -ac_name=MUSIG cclib session 18 '[1,2,"03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b","5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75"]' + ./hush-cli -ac_name=MUSIG cclib session 18 '[1,2,"03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b","5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75"]' { "myind": 1, "numsigners": 2, @@ -103,7 +103,7 @@ the "msg" is what needs to be signed to create a valid spend } now we need to get the commitment from each node to the other one. the session already put the commitment for each node into the global struct. Keep in mind there is a single global struct with session unique to each cclib session call. that means no restarting any deamon in the middle of the process on any of the nodes and only call cclib session a single time. this is an artificial restriction just to simplify the initial implementation of musig - ./komodo-cli -ac_name=MUSIG cclib commit 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","1","c2291acb747a75b1a40014d8eb0cc90a1360f74d413f65f78e20a7de45eda851"]' + ./hush-cli -ac_name=MUSIG cclib commit 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","1","c2291acb747a75b1a40014d8eb0cc90a1360f74d413f65f78e20a7de45eda851"]' { "added_index": 1, "myind": 0, @@ -111,7 +111,7 @@ the "msg" is what needs to be signed to create a valid spend "result": "success" } - ./komodo-cli -ac_name=MUSIG cclib commit 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b",0,"d242cff13fa8c9b83248e4219fda459ada146b885f2171481f1b0f66c66d94ad"]' + ./hush-cli -ac_name=MUSIG cclib commit 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b",0,"d242cff13fa8c9b83248e4219fda459ada146b885f2171481f1b0f66c66d94ad"]' { "added_index": 0, "myind": 1, @@ -120,7 +120,7 @@ the "msg" is what needs to be signed to create a valid spend } Now exchange the revealed nonces to each node: - ./komodo-cli -ac_name=MUSIG cclib nonce 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","1","039365deaaaea089d509ba4c9f846de2baf4aa04cf6b26fa2c1cd818553e47f80c"]' + ./hush-cli -ac_name=MUSIG cclib nonce 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","1","039365deaaaea089d509ba4c9f846de2baf4aa04cf6b26fa2c1cd818553e47f80c"]' { "added_index": 1, "myind": 0, @@ -128,7 +128,7 @@ the "msg" is what needs to be signed to create a valid spend "result": "success" } -./komodo-cli -ac_name=MUSIG cclib nonce 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b",0,"02fec7a9310c959a0a97b86bc3f8c30d392d1fb51793915898c568f73f1f70476b"]' +./hush-cli -ac_name=MUSIG cclib nonce 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b",0,"02fec7a9310c959a0a97b86bc3f8c30d392d1fb51793915898c568f73f1f70476b"]' { "added_index": 0, "myind": 1, @@ -137,14 +137,14 @@ the "msg" is what needs to be signed to create a valid spend } Almost there! final step is to exchange the partial sigs between signers - ./komodo-cli -ac_name=MUSIG cclib partialsig 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","1","4a3795e6801b355102c617390cf5a462061e082e35dc2ed8f8b1fab54cc0769e"]' + ./hush-cli -ac_name=MUSIG cclib partialsig 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","1","4a3795e6801b355102c617390cf5a462061e082e35dc2ed8f8b1fab54cc0769e"]' { "added_index": 1, "result": "success", "combinedsig": "a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f9" } - ./komodo-cli -ac_name=MUSIG cclib partialsig 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b",0,"1d65c09cd9bffe4f0604227e66cd7cd221480bbb08262fe885563a9df7cf8f5b"]' + ./hush-cli -ac_name=MUSIG cclib partialsig 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b",0,"1d65c09cd9bffe4f0604227e66cd7cd221480bbb08262fe885563a9df7cf8f5b"]' { "added_index": 0, "result": "success", @@ -155,7 +155,7 @@ the "msg" is what needs to be signed to create a valid spend Now for a sanity test, we can use the verify call to make sure this sig will work with the msg needed for the spend: - ./komodo-cli -ac_name=MUSIG cclib verify 18 '["f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75","03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b","a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f9"]' + ./hush-cli -ac_name=MUSIG cclib verify 18 '["f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75","03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b","a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f9"]' { "msg": "f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75", "combined_pk": "03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b", @@ -165,7 +165,7 @@ the "msg" is what needs to be signed to create a valid spend and finally the spend: sendtxid, scriptPubKey, musig - ./komodo-cli -ac_name=MUSIG cclib spend 18 '["5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c","210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac","a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f9"]' + ./hush-cli -ac_name=MUSIG cclib spend 18 '["5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c","210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac","a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f9"]' { "scriptpubkey": "210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac", "msg": "f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75", diff --git a/src/cc/payments.cpp b/src/cc/payments.cpp index 5f541a95e..4fd071fd6 100644 --- a/src/cc/payments.cpp +++ b/src/cc/payments.cpp @@ -31,7 +31,7 @@ First step is to create txids with the info needed in their opreturns. this info is the weight, scriptPubKey and opret if needed. To do that txidopret is used: - ./c is a script that invokes komodo-cli with the correct -ac_name + ./c is a script that invokes hush-cli with the correct -ac_name ./c paymentstxidopret \"[9,%222102d6f13a8f745921cdb811e32237bb98950af1a5952be7b3d429abd9152f8e388dac%22]\" -> rawhex with txid 95d9fc8d8a3ef63693c7427e59ff5e177ef63b7345d5f6d6497ac262699a8def diff --git a/src/cc/pegs.cpp b/src/cc/pegs.cpp index 7ee5c815b..47570fe05 100644 --- a/src/cc/pegs.cpp +++ b/src/cc/pegs.cpp @@ -31,45 +31,45 @@ pegs CC is able to create a coin backed (by any supported coin with gateways CC - OK, now we are ready to describe the pegs CC. Let us imagine an -ac_import sidechain with KMD gateways CC. Now we have each native coin fungible with the real KMD via the gateways deposit/withdraw mechanism. Let us start with that and make a pegged and backed USD chain. + OK, now we are ready to describe the pegs CC. Let us imagine an -ac_import sidechain with HUSH gateways CC. Now we have each native coin fungible with the real HUSH via the gateways deposit/withdraw mechanism. Let us start with that and make a pegged and backed USD chain. - Here the native coin is KMD, but we want USD, so there needs to be a way to convert the KMD amounts into USD amounts. Something like "KMDBTC, BTCUSD, *, 1" which is the prices CC syntax to calculate KMD/USD, which is exactly what we need. So now we can assume that we have a block by block usable KMD/USD price. implementationwise, there can be an -ac option like -ac_peg="KMDBTC, BTCUSD, *, 1" and in conjunction with -ac_import=KMD gateways CC sidechain, we now have a chain where deposit of KMD issues the correct USD coins and redeem of USD coins releases the correct number of KMD coins. + Here the native coin is HUSH, but we want USD, so there needs to be a way to convert the HUSH amounts into USD amounts. Something like "HUSHBTC, BTCUSD, *, 1" which is the prices CC syntax to calculate HUSH/USD, which is exactly what we need. So now we can assume that we have a block by block usable HUSH/USD price. implementationwise, there can be an -ac option like -ac_peg="HUSHBTC, BTCUSD, *, 1" and in conjunction with -ac_import=HUSH gateways CC sidechain, we now have a chain where deposit of HUSH issues the correct USD coins and redeem of USD coins releases the correct number of HUSH coins. Are we done yet? - Not quite, as the prices of KMD will be quite volatile relative to USD, which is good during bull markets, not so happy during bear markets. There are 2 halves to this problem, how to deal with massive price increase (easy to solve), how to solve 90% price drop (a lot harder). + Not quite, as the prices of HUSH will be quite volatile relative to USD, which is good during bull markets, not so happy during bear markets. There are 2 halves to this problem, how to deal with massive price increase (easy to solve), how to solve 90% price drop (a lot harder). In order to solve both, what is needed is an "account" based tracking which updates based on both price change, coins issued, payments made. So let us create an account that is based on a specific pubkey, where all relevant deposits, issuances, withdraws are tracked via appropriate vin/vout markers. - Let us modify the USD chain above so that only 80% of the possible USD is issued and 20% held in reserve. This 80% should be at least some easily changeable #define, or even an -ac parameter. We want the issued coins to be released without any encumberances, but the residual 20% value is still controlled (owned) but the depositor. This account has the amount of KMD deposited and USD issued. At the moment of deposit, there will still be 20% equity left. Let us start with 1000 KMD deposit, $1.5 per KMD -> 800 KMD converted to 1200 USD into depositor pubkey and the account of (1000 KMD, -1200 USD) = 200 KMD or $300 equity. + Let us modify the USD chain above so that only 80% of the possible USD is issued and 20% held in reserve. This 80% should be at least some easily changeable #define, or even an -ac parameter. We want the issued coins to be released without any encumberances, but the residual 20% value is still controlled (owned) but the depositor. This account has the amount of HUSH deposited and USD issued. At the moment of deposit, there will still be 20% equity left. Let us start with 1000 HUSH deposit, $1.5 per HUSH -> 800 HUSH converted to 1200 USD into depositor pubkey and the account of (1000 HUSH, -1200 USD) = 200 HUSH or $300 equity. - Now it becomes easy for the bull market case, which is to allow (for a fee like 1%) issuance of more USD as the equity increases, so let us imagine KMD at $10: + Now it becomes easy for the bull market case, which is to allow (for a fee like 1%) issuance of more USD as the equity increases, so let us imagine HUSH at $10: - (1000 KMD, -1200 USD, 200KMD reserve) -> $2000 equity, issue 80% -> $1600 using 160 KMD - (1000 KMD, -1200 USD, 200KMD reserve, -160KMD, issue $1600 USD, 40 KMD reserve) + (1000 HUSH, -1200 USD, 200HUSH reserve) -> $2000 equity, issue 80% -> $1600 using 160 HUSH + (1000 HUSH, -1200 USD, 200HUSH reserve, -160HUSH, issue $1600 USD, 40 HUSH reserve) - we have $2800 USD in circulation, 40 KMD reserve left against $10000 marketcap of the original deposit. It it easy to see that there are never any problems with lack of KMD to redeem the issued USD in a world where prices only go up. Total USD issuance can be limited by using a decentralized account tracking based on each deposit. + we have $2800 USD in circulation, 40 HUSH reserve left against $10000 marketcap of the original deposit. It it easy to see that there are never any problems with lack of HUSH to redeem the issued USD in a world where prices only go up. Total USD issuance can be limited by using a decentralized account tracking based on each deposit. What is evident though is that with the constantly changing price and the various times that all the various deposits issue USD, the global reserves are something that will be hard to predict and in fact needs to be specifically tracked. Let us combine all accounts exposure in to a global reserves factor. This factor will control various max/min/ allowed and fee percentages. Now we are prepared to handle the price goes down scenario. We can rely on the global equity/reserve ratio to be changing relatively slowly as the reference price is the smooted trustless oracles price. This means there will be enough blocks to adjust the global reserves percentage. What we need to do is liquidate specific positions that have the least reserves. - What does liquidation mean? It means a specific account will be purchased at below its current value and the KMD withdrawn. Let us assume the price drops to $5: + What does liquidation mean? It means a specific account will be purchased at below its current value and the HUSH withdrawn. Let us assume the price drops to $5: - (1000 KMD, -1200 USD, 200KMD reserve, -160KMD, issue $1600 USD, 40 KMD reserve) 1000 KMD with 2800 USD issued so $2200 reserves. Let us assume it can be liquidated at a 10% discount, so for $2000 in addition to the $2800, the 5000 KMD is able to be withdrawn. This removes 4800 USD coins for 1000 KMD, which is a very low reserve amount of 4%. If a low reserve amount is removed from the system, then the global reserve amount must be improved. + (1000 HUSH, -1200 USD, 200HUSH reserve, -160HUSH, issue $1600 USD, 40 HUSH reserve) 1000 HUSH with 2800 USD issued so $2200 reserves. Let us assume it can be liquidated at a 10% discount, so for $2000 in addition to the $2800, the 5000 HUSH is able to be withdrawn. This removes 4800 USD coins for 1000 HUSH, which is a very low reserve amount of 4%. If a low reserve amount is removed from the system, then the global reserve amount must be improved. In addition to the global reserves calculation, there needs to be a trigger percentage that enables positions to be liquidated. We also want to liquidate the worst positions, so in addition to the trigger percentage, there should be a liquidation threshold, and the liquidator would need to find 3 or more better positions that are beyond the liquidation threshold, to be able to liquidate. This will get us to at most 3 accounts that could be liquidated but are not able to, so some method to allow those to also be liquidated. The liquidating nodes are making instant profits, so they should be expected to do whatever blockchain scanning and proving to make things easy for the rest of the nodes. One last issue is the normal redemption case where we are not liquidating. In this case, it should be done at the current marketprice, should improve the global reserves metrics and not cause anybody whose position was modified to have cause for complaint. Ideally, there would be an account that has the identical to the global reserve percentage and also at the same price as current marketprice, but this is not realistic, so we need to identify classes of accounts and consider which ones can be fully or partially liquidated to satisfy the constraints. looking at our example account: - (1000 KMD, -1200 USD, 200KMD reserve, -160KMD, issue $1600 USD, 40 KMD reserve) + (1000 HUSH, -1200 USD, 200HUSH reserve, -160HUSH, issue $1600 USD, 40 HUSH reserve) - what sort of non-liquidation withdraw would be acceptable? if the base amount 1000 KMD is reduced along with USD owed, then the reserve status will go up for the account. but that would seem to allow extra USD to be able to be issued. there should be no disadvantage from funding a withdraw, but also not any large advantage. it needs to be a neutral event.... + what sort of non-liquidation withdraw would be acceptable? if the base amount 1000 HUSH is reduced along with USD owed, then the reserve status will go up for the account. but that would seem to allow extra USD to be able to be issued. there should be no disadvantage from funding a withdraw, but also not any large advantage. it needs to be a neutral event.... - One solution is to allow for the chance for any account to be liquidated, but the equity compensated for with a premium based on the account reserves. So in the above case, a premium of 5% on the 40KMD reserve is paid to liquidate its account. Instead of 5% premium, a lower 1% can be done if based on the MAX(correlated[daywindow],smoothed) so we get something that is close to the current marketprice. To prevent people taking advantage of the slowness of the smoothed price to adjust, there would need to be a one day delay in the withdraw. + One solution is to allow for the chance for any account to be liquidated, but the equity compensated for with a premium based on the account reserves. So in the above case, a premium of 5% on the 40HUSH reserve is paid to liquidate its account. Instead of 5% premium, a lower 1% can be done if based on the MAX(correlated[daywindow],smoothed) so we get something that is close to the current marketprice. To prevent people taking advantage of the slowness of the smoothed price to adjust, there would need to be a one day delay in the withdraw. From a practical sense, it seems a day is a long time, so maybe having a way to pay a premium like 10%, or wait a day to get the MAX(correlated[daywindow],smoothed) price. This price "jumping" might also be taken advantage of in the deposit side, so similar to prices CC it seems good to have the MAX(correlated[daywindow],smoothed) method. diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 3052b72ee..5ded26d56 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -620,7 +620,7 @@ char *curl_post(CURL **cHandlep,char *url,char *userpass,char *postfields,char * return(chunk.memory); } -uint16_t _komodo_userpass(char *username, char *password, FILE *fp) +uint16_t _hush_userpass(char *username, char *password, FILE *fp) { char *rpcuser,*rpcpassword,*str,*ipaddress,line[8192]; uint16_t port = 0; rpcuser = rpcpassword = 0; @@ -658,60 +658,17 @@ uint16_t _komodo_userpass(char *username, char *password, FILE *fp) return(port); } -/*void hush_statefname(char *fname,char *symbol,char *str) -{ - int32_t n,len; - sprintf(fname,"%s",getDataDir()); - if ( (n= (int32_t)strlen(ASSETCHAINS_SYMBOL)) != 0 ) - { - len = (int32_t)strlen(fname); - if ( strcmp(ASSETCHAINS_SYMBOL,&fname[len - n]) == 0 ) - fname[len - n] = 0; - else - { - printf("unexpected fname.(%s) vs %s [%s] n.%d len.%d (%s)\n",fname,symbol,ASSETCHAINS_SYMBOL,n,len,&fname[len - n]); - return; - } - } - else - { -#ifdef _WIN32 - strcat(fname,"\\"); -#else - strcat(fname,"/"); -#endif - } - if ( symbol != 0 && symbol[0] != 0 && strcmp("KMD",symbol) != 0 ) - { - strcat(fname,symbol); - //printf("statefname.(%s) -> (%s)\n",symbol,fname); -#ifdef _WIN32 - strcat(fname,"\\"); -#else - strcat(fname,"/"); -#endif - } - strcat(fname,str); - //printf("test.(%s) -> [%s] statename.(%s) %s\n",test,ASSETCHAINS_SYMBOL,symbol,fname); -}*/ - -uint16_t komodo_userpass(char *userpass,char *symbol) +uint16_t hush_userpass(char *userpass,char *symbol) { FILE *fp; uint16_t port = 0; char fname[512],username[512],password[512],confname[HUSH_SMART_CHAIN_MAXLEN]; userpass[0] = 0; - if ( strcmp("KMD",symbol) == 0 ) - { -#ifdef __APPLE__ - sprintf(confname,"Komodo.conf"); -#else - sprintf(confname,"komodo.conf"); -#endif - } - else sprintf(confname,"%s.conf",symbol); + + sprintf(confname,"%s.conf",symbol); + //hush_statefname(fname,symbol,confname); if ( (fp= fopen(confname,"rb")) != 0 ) { - port = _komodo_userpass(username,password,fp); + port = _hush_userpass(username,password,fp); sprintf(userpass,"%s:%s",username,password); if ( strcmp(symbol,ASSETCHAINS_SYMBOL) == 0 ) strcpy(USERPASS,userpass); @@ -722,7 +679,7 @@ uint16_t komodo_userpass(char *userpass,char *symbol) #define is_cJSON_True(json) ((json) != 0 && ((json)->type & 0xff) == cJSON_True) -char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port) +char *hush_issuemethod(char *userpass,char *method,char *params,uint16_t port) { //static void *cHandle; char url[512],*retstr=0,*retstr2=0,postdata[8192]; @@ -746,7 +703,7 @@ int32_t rogue_sendrawtransaction(char *rawtx) char *params,*retstr,*hexstr; cJSON *retjson,*resobj; int32_t retval = -1; params = (char *)malloc(strlen(rawtx) + 16); sprintf(params,"[\"%s\"]",rawtx); - if ( (retstr= komodo_issuemethod(USERPASS,"sendrawtransaction",params,ROGUE_PORT)) != 0 ) + if ( (retstr= hush_issuemethod(USERPASS,"sendrawtransaction",params,ROGUE_PORT)) != 0 ) { if ( 0 ) // causes 4th level crash { @@ -811,7 +768,7 @@ int32_t rogue_progress(struct rogue_state *rs,int32_t waitflag,uint64_t seed,cha if ( 0 && (pastkeys= rogue_keystrokesload(&numpastkeys,seed,1)) != 0 ) { sprintf(params,"[\"extract\",\"17\",\"[%%22%s%%22]\"]",Gametxidstr); - if ( (retstr= komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) + if ( (retstr= hush_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) { if ( (retjson= cJSON_Parse(retstr)) != 0 ) { @@ -843,7 +800,7 @@ int32_t rogue_progress(struct rogue_state *rs,int32_t waitflag,uint64_t seed,cha hexstr[i<<1] = 0; if ( 0 ) { - sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib keystrokes 17 \\\"[%%22%s%%22,%%22%s%%22]\\\" >> keystrokes.log",Gametxidstr,hexstr); + sprintf(cmd,"./hush-cli -ac_name=ROGUE cclib keystrokes 17 \\\"[%%22%s%%22,%%22%s%%22]\\\" >> keystrokes.log",Gametxidstr,hexstr); if ( system(cmd) != 0 ) fprintf(stderr,"error issuing (%s)\n",cmd); } @@ -853,7 +810,7 @@ int32_t rogue_progress(struct rogue_state *rs,int32_t waitflag,uint64_t seed,cha if ( fp == 0 ) fp = fopen("keystrokes.log","a"); sprintf(params,"[\"keystrokes\",\"17\",\"[%%22%s%%22,%%22%s%%22]\"]",Gametxidstr,hexstr); - if ( (retstr= komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) + if ( (retstr= hush_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) { if ( fp != 0 ) { @@ -903,7 +860,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) if ( 0 ) { sprintf(fname,"%s.gameinfo",gametxidstr); - sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib gameinfo 17 \\\"[%%22%s%%22]\\\" > %s",gametxidstr,fname); + sprintf(cmd,"./hush-cli -ac_name=ROGUE cclib gameinfo 17 \\\"[%%22%s%%22]\\\" > %s",gametxidstr,fname); if ( system(cmd) != 0 ) fprintf(stderr,"error issuing (%s)\n",cmd); else filestr = (char *)OS_fileptr(&allocsize,fname); @@ -911,7 +868,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) else { sprintf(params,"[\"gameinfo\",\"17\",\"[%%22%s%%22]\"]",gametxidstr); - filestr = komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT); + filestr = hush_issuemethod(USERPASS,"cclib",params,ROGUE_PORT); } if ( filestr != 0 ) { @@ -1007,7 +964,7 @@ int main(int argc, char **argv, char **envp) #endif #endif - ROGUE_PORT = komodo_userpass(userpass,ASSETCHAINS_SYMBOL); + ROGUE_PORT = hush_userpass(userpass,ASSETCHAINS_SYMBOL); if ( IPADDRESS[0] == 0 ) strcpy(IPADDRESS,"127.0.0.1"); printf("ASSETCHAINS_SYMBOL.(%s) port.%u (%s) IPADDRESS.%s \n",ASSETCHAINS_SYMBOL,ROGUE_PORT,USERPASS,IPADDRESS); sleep(1); @@ -1035,7 +992,7 @@ int main(int argc, char **argv, char **envp) fclose(fp); if ( ROGUE_PORT == 0 ) { - printf("you must copy ROGUE.conf from ~/.komodo/ROGUE/ROGUE.conf (or equivalent location) to current dir\n"); + printf("you must copy ROGUE.conf from ~/.hush/ROGUE/ROGUE.conf (or equivalent location) to current dir\n"); return(-1); } return(rogue(argc,argv,envp)); diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index d1d42f449..9f135f894 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -191,7 +191,7 @@ void rogue_bailout(struct rogue_state *rs) //sleep(5); return; /*fprintf(stderr,"bailing out\n"); - sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib bailout 17 \\\"[%%22%s%%22]\\\" >> bailout.log",Gametxidstr); + sprintf(cmd,"./hush-cli -ac_name=ROGUE cclib bailout 17 \\\"[%%22%s%%22]\\\" >> bailout.log",Gametxidstr); if ( system(cmd) != 0 ) fprintf(stderr,"error issuing (%s)\n",cmd);*/ } diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 1caedbe45..b1fd8635d 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -52,29 +52,29 @@ std::string Rogue_pname = ""; Here is how to play: - ./komodo-cli -ac_name=ROGUE cclib newgame 17 \"[3,10]\" -> this will create a hex transaction that when broadcast with sendrawtransaction will get a gametxid onto the blockchain. This specific command was for 3 players and a buyin of 10 ROGUE. Lets assume the gametxid is 4fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a, most all the other commands will need the gametxid. + ./hush-cli -ac_name=ROGUE cclib newgame 17 \"[3,10]\" -> this will create a hex transaction that when broadcast with sendrawtransaction will get a gametxid onto the blockchain. This specific command was for 3 players and a buyin of 10 ROGUE. Lets assume the gametxid is 4fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a, most all the other commands will need the gametxid. you can always find all the existing games with: - ./komodo-cli -ac_name=ROGUE cclib pending 17 + ./hush-cli -ac_name=ROGUE cclib pending 17 and info about a specific game with: - ./komodo-cli -ac_name=ROGUE cclib gameinfo 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22]\" + ./hush-cli -ac_name=ROGUE cclib gameinfo 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22]\" due to quirks of various parsing at the shell, rpc and internal level, the above convention is used where %22 is added where " should be. also all fields are separated by , without any space. When you do a gameinfo command it will show a "run" field and that will tell you if you are registered for the game or not. If not, the "run" field shows the register syntax you need to do, if you are registered, it will show the command line to start the rogue game that is playing the registered game. -./komodo-cli -ac_name=ROGUE cclib register 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22,%22playerdata_txid%22]\" +./hush-cli -ac_name=ROGUE cclib register 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22,%22playerdata_txid%22]\" If you want to cash in your ingame gold and preserve your character for another battle, do the bailout: -./komodo-cli -ac_name=ROGUE cclib bailout 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22]\" +./hush-cli -ac_name=ROGUE cclib bailout 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22]\" If you won your game before anybody else did or if you are the last one left who didnt bailout, you can claim the prize: - ./komodo-cli -ac_name=ROGUE cclib highlander 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22]\" + ./hush-cli -ac_name=ROGUE cclib highlander 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22]\" The txid you get from the bailout or highlander transactions is the "playerdata_txid" that you can use in future games. @@ -129,7 +129,7 @@ std::string Rogue_pname = ""; // keystrokes retry //////////////////////// start of CClib interface -//./komodod -ac_name=ROGUE -ac_supply=1000000 -pubkey=03951a6f7967ad784453116bc55cd30c54f91ea8a5b1e9b04d6b29cfd6b395ba6c -addnode=5.9.102.210 -ac_cclib=rogue -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60001 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc > /dev/null & +//./hushd -ac_name=ROGUE -ac_supply=1000000 -pubkey=03951a6f7967ad784453116bc55cd30c54f91ea8a5b1e9b04d6b29cfd6b395ba6c -addnode=5.9.102.210 -ac_cclib=rogue -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60001 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc > /dev/null & // cclib newgame 17 \"[3,10]\" // cclib pending 17 @@ -138,7 +138,7 @@ std::string Rogue_pname = ""; // ./rogue gui -> creates keystroke files // ./c cclib register 17 \"[%226d3243c6e5ab383898b28a87e01f6c00b5bdd9687020f17f5caacc8a61febd19%22,%222475182f9d5169d8a3249d17640e4eccd90f4ee43ab04791129b0fa3f177b14a%22]\" // ./c cclib bailout 17 \"[%226d3243c6e5ab383898b28a87e01f6c00b5bdd9687020f17f5caacc8a61febd19%22]\" -// ./komodo-cli -ac_name=ROGUE cclib register 17 \"[%22a898f4ceef7647ba113b9f3c24ef045f5d134935a3b09bdd1a997b9d474f4c1b%22,%22f11d0cb4e2e4c21f029a1146f8e5926f11456885b7ab7d665096f5efedec8ea0%22]\" +// ./hush-cli -ac_name=ROGUE cclib register 17 \"[%22a898f4ceef7647ba113b9f3c24ef045f5d134935a3b09bdd1a997b9d474f4c1b%22,%22f11d0cb4e2e4c21f029a1146f8e5926f11456885b7ab7d665096f5efedec8ea0%22]\" CScript rogue_newgameopret(int64_t buyin,int32_t maxplayers) @@ -704,7 +704,7 @@ uint64_t rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 obj.push_back(Pair("seed",(int64_t)seed)); if ( rogue_iamregistered(maxplayers,gametxid,tx,myrogueaddr) > 0 ) sprintf(cmd,"cc/rogue/rogue %llu %s",(long long)seed,gametxid.ToString().c_str()); - else sprintf(cmd,"./komodo-cli -ac_name=%s cclib register %d \"[%%22%s%%22]\"",SMART_CHAIN_SYMBOL,EVAL_ROGUE,gametxid.ToString().c_str()); + else sprintf(cmd,"./hush-cli -ac_name=%s cclib register %d \"[%%22%s%%22]\"",SMART_CHAIN_SYMBOL,EVAL_ROGUE,gametxid.ToString().c_str()); obj.push_back(Pair("run",cmd)); } } diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 6edd868b2..4feda6701 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2480,7 +2480,7 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) } //////////////////////// start of CClib interface -// ./komodod -ac_name=SUDOKU -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -gen -genproclimit=1 -ac_cclib=sudoku -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60000 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc & +// ./hushd -ac_name=SUDOKU -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -gen -genproclimit=1 -ac_cclib=sudoku -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60000 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc & /* cclib "gen" 17 \"10\" 5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432 */ diff --git a/src/chain.cpp b/src/chain.cpp index e90466a62..d2b7382d9 100644 --- a/src/chain.cpp +++ b/src/chain.cpp @@ -1,10 +1,8 @@ // Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers // Copyright (c) 2016-2021 The Hush developers - // Distributed under the GPLv3 software license, see the accompanying // file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html - /****************************************************************************** * Copyright © 2014-2019 The SuperNET Developers. * * * @@ -80,15 +78,13 @@ const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const { CChainPower::CChainPower(CBlockIndex *pblockIndex) { - nHeight = pblockIndex->GetHeight(); - chainStake = arith_uint256(0); + nHeight = pblockIndex->GetHeight(); chainWork = arith_uint256(0); } -CChainPower::CChainPower(CBlockIndex *pblockIndex, const arith_uint256 &stake, const arith_uint256 &work) +CChainPower::CChainPower(CBlockIndex *pblockIndex, const arith_uint256 &work) { - nHeight = pblockIndex->GetHeight(); - chainStake = stake; + nHeight = pblockIndex->GetHeight(); chainWork = work; } @@ -96,38 +92,29 @@ bool operator==(const CChainPower &p1, const CChainPower &p2) { arith_uint256 bigZero = arith_uint256(0); arith_uint256 workDivisor = p1.chainWork > p2.chainWork ? p1.chainWork : (p2.chainWork != bigZero ? p2.chainWork : 1); - arith_uint256 stakeDivisor = p1.chainStake > p2.chainStake ? p1.chainStake : (p2.chainStake != bigZero ? p2.chainStake : 1); // use up 16 bits for precision - return ((p1.chainWork << 16) / workDivisor + (p1.chainStake << 16) / stakeDivisor) == - ((p2.chainWork << 16) / workDivisor + (p2.chainStake << 16) / stakeDivisor); + return ((p1.chainWork << 16) / workDivisor == ((p2.chainWork << 16) / workDivisor)); } bool operator<(const CChainPower &p1, const CChainPower &p2) { arith_uint256 bigZero = arith_uint256(0); arith_uint256 workDivisor = p1.chainWork > p2.chainWork ? p1.chainWork : (p2.chainWork != bigZero ? p2.chainWork : 1); - arith_uint256 stakeDivisor = p1.chainStake > p2.chainStake ? p1.chainStake : (p2.chainStake != bigZero ? p2.chainStake : 1); // use up 16 bits for precision - return ((p1.chainWork << 16) / workDivisor + (p1.chainStake << 16) / stakeDivisor) < - ((p2.chainWork << 16) / workDivisor + (p2.chainStake << 16) / stakeDivisor); + return ((p1.chainWork << 16) / workDivisor < ((p2.chainWork << 16) / workDivisor)); } bool operator<=(const CChainPower &p1, const CChainPower &p2) { arith_uint256 bigZero = arith_uint256(0); arith_uint256 workDivisor = p1.chainWork > p2.chainWork ? p1.chainWork : (p2.chainWork != bigZero ? p2.chainWork : 1); - arith_uint256 stakeDivisor = p1.chainStake > p2.chainStake ? p1.chainStake : (p2.chainStake != bigZero ? p2.chainStake : 1); // use up 16 bits for precision - return ((p1.chainWork << 16) / workDivisor + (p1.chainStake << 16) / stakeDivisor) <= - ((p2.chainWork << 16) / workDivisor + (p2.chainStake << 16) / stakeDivisor); + return ((p1.chainWork << 16) / workDivisor <= ((p2.chainWork << 16) / workDivisor)); } - - - /** Turn the lowest '1' bit in the binary representation of a number into a '0'. */ int static inline InvertLowestOne(int n) { return n & (n - 1); } diff --git a/src/chain.h b/src/chain.h index 1d8f2a462..3162f6634 100644 --- a/src/chain.h +++ b/src/chain.h @@ -127,31 +127,23 @@ static const BlockStatus BLOCK_VALID_CONSENSUS = BLOCK_VALID_SCRIPTS; class CBlockIndex; -// This class provides an accumulator for both the chainwork and the chainPOS value -// CChainPower's can be compared, and the comparison ensures that work and proof of stake power -// are both used equally to determine which chain has the most work. This makes an attack -// that involves mining in secret completely ineffective, even before dPOW, unless a large part -// of the staking supply is also controlled. It also enables a faster deterministic convergence, -// aided by both POS and POW. -// TODO: delete this junk +// This class provides an accumulator for chainwork class CChainPower { public: arith_uint256 chainWork; - arith_uint256 chainStake; int32_t nHeight; - CChainPower() : nHeight(0), chainStake(0), chainWork(0) {} + CChainPower() : nHeight(0), chainWork(0) {} CChainPower(CBlockIndex *pblockIndex); - CChainPower(CBlockIndex *pblockIndex, const arith_uint256 &stake, const arith_uint256 &work); - CChainPower(int32_t height) : nHeight(height), chainStake(0), chainWork(0) {} - CChainPower(int32_t height, const arith_uint256 &stake, const arith_uint256 &work) : - nHeight(height), chainStake(stake), chainWork(work) {} + CChainPower(CBlockIndex *pblockIndex, const arith_uint256 &work); + CChainPower(int32_t height) : nHeight(height), chainWork(0) {} + CChainPower(int32_t height, const arith_uint256 &work) : + nHeight(height), chainWork(work) {} CChainPower &operator=(const CChainPower &chainPower) { chainWork = chainPower.chainWork; - chainStake = chainPower.chainStake; nHeight = chainPower.nHeight; return *this; } @@ -159,7 +151,6 @@ class CChainPower CChainPower &operator+=(const CChainPower &chainPower) { this->chainWork += chainPower.chainWork; - this->chainStake += chainPower.chainStake; return *this; } @@ -167,7 +158,6 @@ class CChainPower { CChainPower result = CChainPower(chainPowerA); result.chainWork += chainPowerB.chainWork; - result.chainStake += chainPowerB.chainStake; return result; } @@ -175,7 +165,6 @@ class CChainPower { CChainPower result = CChainPower(chainPowerA); result.chainWork -= chainPowerB.chainWork; - result.chainStake -= chainPowerB.chainStake; return result; } @@ -183,16 +172,9 @@ class CChainPower { CChainPower result = CChainPower(chainPower); result.chainWork *= x; - result.chainStake *= x; return result; } - CChainPower &addStake(const arith_uint256 &nChainStake) - { - chainStake += nChainStake; - return *this; - } - CChainPower &addWork(const arith_uint256 &nChainWork) { chainWork += nChainWork; @@ -266,7 +248,7 @@ public: int64_t nPayments; //! (memory only) Number of shielded transactions (of any kind) in the block up to and including this block. - //! A shielded transaction is defined as a transaction that contains at least 1 JoinSplit, which includes + //! A shielded transaction is defined as a transaction that contains at least 1 ShieldedInput or ShieldedOutput //! shielding/de-shielding and other complex transaction possibilties including multiple taddrs/zaddrs as //! inputs and outputs. int64_t nShieldedTx; @@ -278,7 +260,7 @@ public: int64_t nShieldedSpends; //! (memory only) Number of fully shielded transactions. A fully shielded transaction is defined - //! as a transaction containing JoinSplits and only shielded inputs and outputs, i.e. no transparent + //! as a transaction containing only shielded inputs and outputs, i.e. no transparent // inputs or outputs: z->z or z->(z,z) or z->(z,z,z,) etc... int64_t nFullyShieldedTx; @@ -295,7 +277,7 @@ public: int64_t nFullyShieldedPayments; //! (memory only) Number of deshielding transactions. A deshielding transaction is defined - //! as a transaction containing JoinSplits and at least one transparent output. + //! as a transaction containing ShieldedInputs and at least one transparent output. int64_t nDeshieldingTx; //! (memory only) Number of deshielding payments. A deshielding payment is defined @@ -303,7 +285,7 @@ public: int64_t nDeshieldingPayments; //! (memory only) Number of shielding transactions. A shielding transaction is defined - //! as a transaction containing JoinSplits and at least one transparent input + //! as a transaction containing ShieldedOutputs and at least one transparent input // i.e. t->z or t->(z,t) or z->(z,z,t) int64_t nShieldingTx; @@ -322,7 +304,7 @@ public: int64_t nChainPayments; //! (memory only) Number of shielded transactions (of any kind) in the chain up to and including this block. - //! A shielded transaction is defined as a transaction that contains at least 1 JoinSplit, which includes + //! A shielded transaction is defined as a transaction that contains at least 1 ShieldedInput or ShieldedOutput //! shielding/de-shielding and other complex transaction possibilties including multiple taddrs/zaddrs as //! inputs and outputs. int64_t nChainShieldedTx; @@ -334,7 +316,7 @@ public: int64_t nChainShieldedSpends; //! (memory only) Number of fully shielded transactions. A fully shielded transaction is defined - //! as a transaction containing JoinSplits and only shielded inputs and outputs, i.e. no transparent + //! as a transaction containing and only shielded inputs and outputs, i.e. no transparent // inputs or outputs: z->z or z->(z,z) or z->(z,z,z,) etc... int64_t nChainFullyShieldedTx; @@ -351,7 +333,7 @@ public: int64_t nChainFullyShieldedPayments; //! (memory only) Number of deshielding transactions. A deshielding transaction is defined - //! as a transaction containing JoinSplits and at least one transparent output. + //! as a transaction containing ShieldedInputs and at least one transparent output. int64_t nChainDeshieldingTx; //! (memory only) Number of deshielding payments. A deshielding payment is defined @@ -359,7 +341,7 @@ public: int64_t nChainDeshieldingPayments; //! (memory only) Number of shielding transactions. A shielding transaction is defined - //! as a transaction containing JoinSplits and at least one transparent input + //! as a transaction containing ShieldedOutputs and at least one transparent input // i.e. t->z or t->(z,t) or z->(z,z,t) int64_t nChainShieldingTx; diff --git a/src/chainparams.cpp b/src/chainparams.cpp index 9cd9bb7f9..26f4e8488 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -521,11 +521,15 @@ void hush_setactivation(int32_t height) void *chainparams_commandline() { CChainParams::CCheckpointData checkpointData; - if(fDebug) { + //if(fDebug) { fprintf(stderr,"chainparams_commandline called with port=%u\n", ASSETCHAINS_P2PPORT); - } + //} if ( SMART_CHAIN_SYMBOL[0] != 0 ) { + if (strcmp(SMART_CHAIN_SYMBOL,"HUSH3") == 0) { + ASSETCHAINS_P2PPORT = 18030; + } + if ( ASSETCHAINS_BLOCKTIME != 60 ) { pCurrentParams->consensus.nMaxFutureBlockTime = 7 * ASSETCHAINS_BLOCKTIME; // 7 blocks @@ -538,8 +542,11 @@ void *chainparams_commandline() { pCurrentParams->SetNValue(ASSETCHAINS_NK[0]); pCurrentParams->SetKValue(ASSETCHAINS_NK[1]); } - if ( HUSH_TESTNODE != 0 ) + if ( HUSH_TESTNODE != 0 ) { + fprintf(stderr,"%s: This is a test node, mining will not require peers!\n", __func__); pCurrentParams->SetMiningRequiresPeers(false); + } + if ( ASSETCHAINS_RPCPORT == 0 ) ASSETCHAINS_RPCPORT = ASSETCHAINS_P2PPORT + 1; pCurrentParams->pchMessageStart[0] = ASSETCHAINS_MAGIC & 0xff; @@ -783,12 +790,102 @@ void *chainparams_commandline() { (492000, uint256S("0x00000013bbbff98ddab19a3178a0088a20628791e94963e5d1ea635015dfa9c6")) (493000, uint256S("0x00000001ed829c061ba14f6953e79d99577079adf5526f1e43e6dc9d9f9571bf")) (494000, uint256S("0x00000018dfeced2d1584a1003fefa4349810239bade096e53b4fa6bbc38a1685")) - (495000, uint256S("0x0000001816af55724cd49c0bfe02c9eac29b4a73db2b7d868b958218a03e6c94")) - (496000, uint256S("0x000000007e2019c5246db5a75122c6826822fa154d68a51eee2ff23f54ec668e")), - (int64_t) 1618760194, // time of last checkpointed block - (int64_t) 842496, // total txs - (double) 1812 // txs in the last day before block 496013 - + (495000, uint256S("0x0000001816af55724cd49c0bfe02c9eac29b4a73db2b7d868b958218a03e6c94")) + (496000, uint256S("0x000000007e2019c5246db5a75122c6826822fa154d68a51eee2ff23f54ec668e")) + (497000, uint256S("0x0000000aa5803c0825cfa1a34227d0ecb80be191674365a372f71611eacdc742")) + (498000, uint256S("0x000000166385022d4b4ade0921a5f6c7d4aec56257cd679f7c441aeb0552b28c")) + (499000, uint256S("0x0000002ce5e48efb664e936c9551b2781c742416e519d3a023d087036519507b")) + (500000, uint256S("0x0000000cdfe9389bde0e9f1d649dd2f19ee69d765b00907aa681c3cdaad0bdb6")) + (501000, uint256S("0x00000028736fd4ce6995a46d217c0022d2882165b5f716e94f255877c73f474a")) + (502000, uint256S("0x000000459520215ade21db91a83ad47a806320ba3e290d686149bcf5672e132a")) + (503000, uint256S("0x000000086aee5827d0254e1176a4dfd5c8a7958ee1f61458bdb1eb4d6ffbc131")) + (504000, uint256S("0x000000474906b6ad537fe14eca1316c7be23f181bc554a2244c97634a6d361a7")) + (505000, uint256S("0x00000035db569efc139988b7d506529bb482284bf2dfc40060159b321883974d")) + (506000, uint256S("0x0000000c55ddd54e1f0aa6a59abe774f0e14501743c2594184772031f5bf51fd")) + (507000, uint256S("0x000000061ca0ea34d5d3ddd5d8ceb0dcf9a0720483efd98155c0aa3774387e60")) + (508000, uint256S("0x00000004bd6cdfbbee3945b897c4d6b6f49199d788151fe5536417d31d2f36ab")) + (509000, uint256S("0x0000000b73f9dd08528827a8224decf6635462d2adabac9301e5c17b7a24a5f4")) + (510000, uint256S("0x00000004c41a5b61302564abc741195c915fdf9edd12669f93ac5d4443613664")) + (511000, uint256S("0x000000094319bb7199e5697e458520e95639dcec5180d4442e1470f48feaf125")) + (512000, uint256S("0x00000014516f2d52467edd913c52e1742ca8a767debd9294bbbf8f39bdbae506")) + (513000, uint256S("0x000000177739b5379d196b74faeaabf35dbb9d3f6f9e172f659f68b3288a71c3")) + (514000, uint256S("0x0000000940533509d21f249ab0b0144923e65050a24dbf53863c9c07fd21fd6b")) + (515000, uint256S("0x000000007d256fc4cbfff1c05f83550b8dfdf093b060a98fafac6a090e349bc1")) + (516000, uint256S("0x000000029ee7abc14842e22b4f3e7e3c640c55fa2a898773c83ff34ceb2a5482")) + (517000, uint256S("0x00000019ca7705b4a8b35ae1aa4071401ed1de7449306ef8a34716637f43c2f1")) + (518000, uint256S("0x00000013f4aa06fca6c2a57e80c3950d0e7613f3bcba0b52887d4c7579e5b20a")) + (519000, uint256S("0x0000000b7d1e4efbbb38c91e838a50876be93a6549fdaeb534ec1d8657117e69")) + (520000, uint256S("0x00000000c2fb98b56bf9c549406710b57308081663230a477c7b5983720a456a")) + (521000, uint256S("0x0000000d48660709c9fd60f01b71260e0e6ba3875cdb109b7b037ec6b80f3098")) + (522000, uint256S("0x00000019d0ad6bdebc9d39a5b9a6ae4d844b45bbfcdd97885841a1d8033c956f")) + (523000, uint256S("0x000000121da004ec14c89b67151439765a19aadbdf4d4feca701cce7c3820efb")) + (524000, uint256S("0x00000003d3445c4cb6e980751cd8119679d572f57bbaa3b9c9114e397841827e")) + (525000, uint256S("0x0000000b2a079f083c86f9ab8b0f73dc511c20f6aa44d7735f29409df966f026")) + (526000, uint256S("0x00000004d3ae427a98336ee4bc5e60f00ebd4c88f9ffdd18003f17535465888a")) + (527000, uint256S("0x000000057e5cb13f42332f59b6c2d6f333369b8e4d9bdf6fa9bb441e2ddb5c51")) + (528000, uint256S("0x000000045f51825c19aab9d1d620d7073c2114ccf3e40f63d66c729c71c2bc05")) + (529000, uint256S("0x000000116ac2795cdbde2d3af6d804d9dbf445d2ed12d7cf13c155540f10c119")) + (530000, uint256S("0x0000000be4932b469923d826991810109f2c2ca50d5fa0133c765b5ab96bf315")) + (531000, uint256S("0x0000000a7fdd8ce073da5d95fcbefba5d0366c9b834cac914889108094d0cd18")) + (532000, uint256S("0x0000000600d2ea28f32220c054e2ae66ec8471a2f755ef219a0c81e4a4296135")) + (533000, uint256S("0x0000000a5f4a460970f6dcd3a271315f936648c854c1a7bb251dbc7996f90e92")) + (534000, uint256S("0x00000009b5d0615eb98f06820cc6d66af542b8bbde0cabe5b54b6e7625e77803")) + (535000, uint256S("0x0000000ac06f5d79b927f2dfb54eecd72f9ada28fa59092f5c3c83627b281605")) + (536000, uint256S("0x000000037a51adb2cccf29b9c164386c8418959db16606b70a1389fb8755829f")) + (537000, uint256S("0x0000000a129157792e233e233f85693625abb14be90362ff727ab97e8d5ec340")) + (538000, uint256S("0x00000015e13085045c090a51e9c1114749fa7b465009f2ad70ff278d9ae05b5c")) + (539000, uint256S("0x00000001953384069e477f7e1839dc0498cbeb951adb32bcbf3b96ef487fce4a")) + (540000, uint256S("0x0000000281246b5d2e845aa711b6af76c8cc0d1f39ba25fe414f83bbe47544bb")) + (541000, uint256S("0x0000000f27b777a942d6317438836258c4e34bd3761736a2b32cc2b7c8305d71")) + (542000, uint256S("0x00000005d4667fb45a862d91ba843acbaee033915bf75536c67aeca1a2a3a5ff")) + (543000, uint256S("0x0000000509b08619049b1aec8e715d971b8dbc2175acf7874a37b9ce13dfb137")) + (544000, uint256S("0x0000000582563d79bf72a925ae3bc5c6f0eacbdb317c92fa89eb56d570427fd7")) + (545000, uint256S("0x0000000ff9df3d3a00d682f069819acbc5697b42da69a78f6e07486ac68f0e49")) + (546000, uint256S("0x00000004653460c603fa7a70292a85e286272b587f0b9cea7e73b765e8b0ef7b")) + (547000, uint256S("0x000000074c5f411190c5bf788a37a00506935015df4872cc5471416abadb757d")) + (548000, uint256S("0x00000005444a4ecd1eea940ad5395f2f7839967ee5b01be4a9b68755de4395ac")) + (549000, uint256S("0x0000000216eafee0e40374b8e8db63118cb4e3adc3159068bdafff1f0e0d9deb")) + (550000, uint256S("0x0000000056b84bc88604b9df668b60c020a6926b2dfdcd09955e5d8d3e7a5ca7")) + (551000, uint256S("0x0000000adaaeb79c5c6c49038d7206f88d5b4ecaaf21aaca09b5a7d548f76b25")) + (552000, uint256S("0x00000004185669b566e62cbebc9c50930c8ae0d5c42f23280262a7f55b726553")) + (553000, uint256S("0x00000010112434cdb0203a053e0c22ef16b9d39b8feed2328d7ff97013b216be")) + (554000, uint256S("0x00000006dacee96c0f48fc7250c71cc1e746befa84af8cd2ed0499d8d24cc6cb")) + (555000, uint256S("0x00000001b3b2c149029d5a2e7cedb0683c97692a52cbc91bb532cb78bbcadcc0")) + (556000, uint256S("0x0000000397bdd61939cc3d2c39360c5e3713ef9dd82b8cedac17075b8e177304")) + (557000, uint256S("0x0000000414bb81b82a2e71608086ac585dba19ca249067c9e967d6f44a1d3163")) + (558000, uint256S("0x00000003516d27423b1b5b60eab97d425e7be3f08f14bafd935666b1e955608e")) + (559000, uint256S("0x00000005c44ef4543da5924e65f0fd2d2c8fe926b2f3995b83ccfd1463b443d7")) + (560000, uint256S("0x00000002eb33454ba48e61a50351686115c47cb59b8fb0496432ad58e0484acf")) + (561000, uint256S("0x00000004172d5940c07ec6d493e410fbab8a05dc73e350505e1540d7336eb353")) + (562000, uint256S("0x00000000d9caaf66ad7782046886d3bfdf966c0a015dbae64042cd0c35e516e4")) + (563000, uint256S("0x000000000d953e53c65145bfb41ba544a9ce9e5432c9ed8eabd39873dfcb8ab0")) + (564000, uint256S("0x0000000d49258678c42bc2ea6f9e5d1206c578da8dc564d1a6114ce68bf77817")) + (565000, uint256S("0x0000000124077b644281fe8b904a84773cc69ff75cc1a337a7d8b7a8b60f4948")) + (566000, uint256S("0x0000000569218dbcbf107acfa0ee400185a67699cb9ab33ba6342a518548a4bd")) + (567000, uint256S("0x00000003d6b00efbf21aa135d0c05c4e5389d37ca1f0bc27f93ca0ad40df5d7e")) + (568000, uint256S("0x000000075d6bfd54e9f5df8e3e3416f31f7080823d943452a801d6dfe2e009c4")) + (569000, uint256S("0x000000157ae620dfd5a4eda2fae481b38c1c8487d0a08419faaf85dad04e710a")) + (570000, uint256S("0x00000003cb99686983e1298491d554b3b368a65c8f20ff66e5f973cf72c95060")) + (571000, uint256S("0x00000008b76fe3a819ea810206f2c368f04e06e299cf8a00cbc0b419b6f184db")) + (572000, uint256S("0x0000000c20bbb828e25309964ea14c238ff617f2e97de2a0ca1c15b0f18f3496")) + (573000, uint256S("0x00000004b9b9bb2b972d7faf6abb529b4ed5e69efe516ea72c4e202426fbc142")) + (574000, uint256S("0x000000035646917f7350d27d1031a105b373e0009943925c86347c0ac944c8cc")) + (575000, uint256S("0x0000000a6699cfd656d9e1530f497a3258c4ed4bea80f5bcbe3d666d0edf482d")) + (576000, uint256S("0x00000005e0ed2dea3cb2d8666227c0e7375f4da8bd7045e915a087b5662f179b")) + (577000, uint256S("0x00000009009599f27a22da268316f2d20669a8886a1fa3f2e4e7806c03b441a5")) + (578000, uint256S("0x0000000aece28967d3a83a3008e7dec96d525c7cb5eb0d9942e11d81a263e487")) + (579000, uint256S("0x00000000cdae1d8f9ff55f9a0848ee7ed2c9634ef876be74c0136598ab3f11a3")) + (580000, uint256S("0x00000004b8e4f7d23de574ffe97b22334b33fb15a58e91b5689c02a7c024cdc7")) + (581000, uint256S("0x00000003d8e78ee3716bb52274a1ea80228b4014ddff201bc69a4cd200f6fa17")) + (582000, uint256S("0x000000060c8ecbc2535c7a6c88795ee8b4ca35047a2a2c620ff5d1e9c77487d7")) + (583000, uint256S("0x00000004bf3dd01180d59a167e23fdab0ab50e8a9f8ce16542e0a01387c400b6")) + (584000, uint256S("0x0000000720f29b0d72469739e9d94607e67b48eb9957b45c2fd5a34b86df039a")) + (585000, uint256S("0x00000001409c395b2e37e2b88110b320996996241bfb489103db9e17aaf2ddc7")) + (586000, uint256S("0x00000006ff6509d260f66af2fc4fc1769d56394333f3ad5a19bbd10c8c26742b")) + (587000, uint256S("0x00000003866d330ac5448e07eb5e95d2e1860203f2e0ca568161d04ea5c5deb8")), + (int64_t) 1625849524, // time of last checkpointed block + (int64_t) 0, // total txs + (double) 2304 // txs in the last day before block 587157 }; } else { checkpointData = //(Checkpoints::CCheckpointData) diff --git a/src/chainparamsbase.cpp b/src/chainparamsbase.cpp index 2c15f8ffc..1f0eb7740 100644 --- a/src/chainparamsbase.cpp +++ b/src/chainparamsbase.cpp @@ -1,8 +1,8 @@ // Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers +// Copyright (c) 2016-2021 The Hush developers // Distributed under the GPLv3 software license, see the accompanying // file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html - /****************************************************************************** * Copyright © 2014-2019 The SuperNET Developers. * * * @@ -19,9 +19,7 @@ ******************************************************************************/ #include "chainparamsbase.h" - #include "util.h" - #include /** @@ -32,7 +30,7 @@ class CBaseMainParams : public CBaseChainParams public: CBaseMainParams() { - nRPCPort = 7771; + nRPCPort = 18031; } }; static CBaseMainParams mainParams; @@ -45,7 +43,7 @@ class CBaseTestNetParams : public CBaseChainParams public: CBaseTestNetParams() { - nRPCPort = 17771; + nRPCPort = 28031; strDataDir = "testnet3"; } }; diff --git a/src/chainparamsbase.h b/src/chainparamsbase.h index 9379e95b4..1fbdec8bd 100644 --- a/src/chainparamsbase.h +++ b/src/chainparamsbase.h @@ -40,6 +40,7 @@ public: const std::string& DataDir() const { return strDataDir; } int RPCPort() const { return nRPCPort; } + int StratumPort() const { return (RPCPort() + 1000); } protected: CBaseChainParams() {} diff --git a/src/clearassets b/src/clearassets deleted file mode 100755 index 6c37fb95d..000000000 --- a/src/clearassets +++ /dev/null @@ -1,32 +0,0 @@ -rm -rf ~/.komodo/USD -rm -rf ~/.komodo/EUR -rm -rf ~/.komodo/JPY -rm -rf ~/.komodo/GBP -rm -rf ~/.komodo/AUD -rm -rf ~/.komodo/CAD -rm -rf ~/.komodo/CHF -rm -rf ~/.komodo/NZD -rm -rf ~/.komodo/CNY -rm -rf ~/.komodo/RUB -rm -rf ~/.komodo/MXN -rm -rf ~/.komodo/BRL -rm -rf ~/.komodo/INR -rm -rf ~/.komodo/HKD -rm -rf ~/.komodo/TRY -rm -rf ~/.komodo/ZAR -rm -rf ~/.komodo/PLN -rm -rf ~/.komodo/NOK -rm -rf ~/.komodo/SEK -rm -rf ~/.komodo/DKK -rm -rf ~/.komodo/CZK -rm -rf ~/.komodo/HUF -rm -rf ~/.komodo/ILS -rm -rf ~/.komodo/KRW -rm -rf ~/.komodo/MYR -rm -rf ~/.komodo/PHP -rm -rf ~/.komodo/RON -rm -rf ~/.komodo/SGD -rm -rf ~/.komodo/THB -rm -rf ~/.komodo/BGN -rm -rf ~/.komodo/IDR -rm -rf ~/.komodo/HRK diff --git a/src/clientversion.h b/src/clientversion.h index a7e850e7c..375f82690 100644 --- a/src/clientversion.h +++ b/src/clientversion.h @@ -29,8 +29,8 @@ //! These need to be macros, as clientversion.cpp's and bitcoin*-res.rc's voodoo requires it // Must be kept in sync with configure.ac , ugh! #define CLIENT_VERSION_MAJOR 3 -#define CLIENT_VERSION_MINOR 7 -#define CLIENT_VERSION_REVISION 1 +#define CLIENT_VERSION_MINOR 8 +#define CLIENT_VERSION_REVISION 0 #define CLIENT_VERSION_BUILD 50 //! Set to true for release, false for prerelease or test build diff --git a/src/crypto/equihash.h b/src/crypto/equihash.h index 3b977dffc..968fbdd79 100644 --- a/src/crypto/equihash.h +++ b/src/crypto/equihash.h @@ -204,7 +204,7 @@ public: #include "equihash.tcc" /* -* Equihash 200,9 (KMD/Zcash) +* Equihash 200,9 (HUSH/ZEC and other ASIC coins) * Equihash 150,5 (beam) * Equihash 144,5 (SnowGem) * Equihash 96,5 (Minex) diff --git a/src/httprpc.cpp b/src/httprpc.cpp index 799d2fbe6..fd6849e61 100644 --- a/src/httprpc.cpp +++ b/src/httprpc.cpp @@ -1,3 +1,6 @@ +// Copyright (c) 2016-2021 The Hush developers +// Distributed under the GPLv3 software license, see the accompanying +// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html /****************************************************************************** * Copyright © 2014-2019 The SuperNET Developers. * * * @@ -12,9 +15,7 @@ * Removal or modification of this copyright notice is prohibited. * * * ******************************************************************************/ - #include "httprpc.h" - #include "chainparams.h" #include "httpserver.h" #include "key_io.h" @@ -25,7 +26,6 @@ #include "util.h" #include "utilstrencodings.h" #include "ui_interface.h" - #include // boost::trim // WWW-Authenticate to present with 401 Unauthorized response diff --git a/src/httpserver.cpp b/src/httpserver.cpp index 0e4e42c2b..58cc9ca45 100644 --- a/src/httpserver.cpp +++ b/src/httpserver.cpp @@ -157,6 +157,16 @@ public: boost::unique_lock lock(cs); return queue.size(); } + size_t MaxDepth() + { + boost::unique_lock lock(cs); + return maxDepth; + } + int NumThreads() + { + boost::unique_lock lock(cs); + return numThreads; + } }; struct HTTPPathHandler @@ -186,6 +196,22 @@ std::vector pathHandlers; //! Bound listening sockets std::vector boundSockets; + +int getWorkQueueDepth() +{ + return workQueue->Depth(); +} + +int getWorkQueueMaxDepth() +{ + return workQueue->MaxDepth(); +} + +int getWorkQueueNumThreads() +{ + return workQueue->NumThreads(); +} + /** Check if a network address is allowed to access the HTTP server */ static bool ClientAllowed(const CNetAddr& netaddr) { diff --git a/src/httpserver.h b/src/httpserver.h index b903f91cd..348ccda2b 100644 --- a/src/httpserver.h +++ b/src/httpserver.h @@ -24,6 +24,10 @@ struct event_base; class CService; class HTTPRequest; +int getWorkQueueDepth(); +int getWorkQueueMaxDepth(); +int getWorkQueueNumThreads(); + /** Initialize HTTP server. * Call this before RegisterHTTPHandler or EventBase(). */ diff --git a/src/hush-cli b/src/hush-cli deleted file mode 100755 index ecd45bd74..000000000 --- a/src/hush-cli +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/bash -# Copyright (c) 2016-2021 The Hush developers -# Released under the GPLv3 - -# set working directory to the location of this script -# readlink -f does not always exist -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -cd $DIR -DIR="$( cd "$( dirname "$( readlink "${BASH_SOURCE[0]}" )" )" && pwd )" -cd $DIR - -NAME=HUSH3 - -CLI=${KOMODOCLI:-./komodo-cli} -if [ -f $CLI ]; then - $CLI -ac_name=$NAME "$@" -else - # We prefix our binary when installed - # system wide on Debain systems, to prevent clashes, - # because we are classy like that. Fuck jl777, The KYC Traitor. - CLI=hush-komodo-cli - $CLI -ac_name=$NAME "$@" -fi diff --git a/src/hush-cli-testnet b/src/hush-cli-testnet deleted file mode 100755 index eb98bc2ea..000000000 --- a/src/hush-cli-testnet +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash -# Copyright (c) 2016-2021 The Hush developers - -# set working directory to the location of this script -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -cd $DIR - -NAME=HUSH3T - -CLI=${KOMODOCLI:-./komodo-cli} -$CLI -ac_name=$NAME "$@" diff --git a/src/hush-cli.bat b/src/hush-cli.bat deleted file mode 100644 index 802315b44..000000000 --- a/src/hush-cli.bat +++ /dev/null @@ -1,14 +0,0 @@ -@call :GET_CURRENT_DIR -@cd %THIS_DIR% -komodo-cli.exe -ac_name=HUSH3 %1 %2 %3 %4 %5 %6 %7 %8 %9 -@goto :EOF - -:GET_CURRENT_DIR -@pushd %~dp0 -@set THIS_DIR=%CD% -@popd -@goto :EOF - - - - diff --git a/src/hush-smart-chain b/src/hush-smart-chain index 537fdc9a3..c5543b221 100755 --- a/src/hush-smart-chain +++ b/src/hush-smart-chain @@ -7,18 +7,8 @@ cd $DIR DIR="$( cd "$( dirname "$( readlink "${BASH_SOURCE[0]}" )" )" && pwd )" cd $DIR -NAME=HUSH3 -CLIENTNAME="GoldenSandtrout" -DEFAULTS="-ac_sapling=1 -clientname=$CLIENTNAME" +DEFAULTS="" -# This is a Hush-flavored KMD that allows us to pass in arbitary CLI -# flags, since hushd is specific to Hush mainnet -KMD=${KOMODOD:-./komodod} -if [ -f $KMD ]; then - $KMD $DEFAULTS "$@" -else - # We prefix our binary when installed - # system wide on Debain system, to prevent clashes - KMD=hush-komodod - $KMD $DEFAULTS "$@" -fi +# People should just use hushd going forward +HUSH="./hushd" +$HUSH $DEFAULTS "$@" diff --git a/src/hush-tx b/src/hush-tx deleted file mode 100755 index cbad82fc7..000000000 --- a/src/hush-tx +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash -# Copyright (c) 2016-2021 The Hush developers -# Released under the GPLv3 - -# set working directory to the location of this script -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -cd $DIR - -NAME=HUSHT - -./komodo-tx -ac_name=$NAME "$@" diff --git a/src/komodo-tx.cpp b/src/hush-tx.cpp similarity index 100% rename from src/komodo-tx.cpp rename to src/hush-tx.cpp diff --git a/src/hush.h b/src/hush.h index 14e8fd2f7..b25dcfcb4 100644 --- a/src/hush.h +++ b/src/hush.h @@ -82,9 +82,7 @@ int32_t hush_parsestatefile(struct hush_state *sp,FILE *fp,char *symbol,char *de int32_t func,ht,notarized_height,num,matched=0,MoMdepth; uint256 MoM,notarized_hash,notarized_desttxid; uint8_t pubkeys[64][33]; if ( (func= fgetc(fp)) != EOF ) { - if ( SMART_CHAIN_SYMBOL[0] == 0 && strcmp(symbol,"KMD") == 0 ) - matched = 1; - else matched = (strcmp(symbol,SMART_CHAIN_SYMBOL) == 0); + matched = (strcmp(symbol,SMART_CHAIN_SYMBOL) == 0); if ( fread(&ht,1,sizeof(ht),fp) != sizeof(ht) ) errs++; if ( 0 && SMART_CHAIN_SYMBOL[0] != 0 && func != 'T' ) @@ -98,7 +96,7 @@ int32_t hush_parsestatefile(struct hush_state *sp,FILE *fp,char *symbol,char *de else { //printf("updated %d pubkeys at %s ht.%d\n",num,symbol,ht); - if ( (HUSH_EXTERNAL_NOTARIES != 0 && matched != 0) || (strcmp(symbol,"KMD") == 0 && HUSH_EXTERNAL_NOTARIES == 0) ) + if ( (HUSH_EXTERNAL_NOTARIES != 0 && matched != 0) ) hush_eventadd_pubkeys(sp,symbol,ht,num,pubkeys); } } else printf("illegal num.%d\n",num); @@ -228,10 +226,9 @@ int32_t hush_parsestatefiledata(struct hush_state *sp,uint8_t *filedata,long *fp int32_t func= -1,ht,notarized_height,MoMdepth,num,matched=0; uint256 MoM,notarized_hash,notarized_desttxid; uint8_t pubkeys[64][33]; long fpos = *fposp; if ( fpos < datalen ) { - func = filedata[fpos++]; - if ( SMART_CHAIN_SYMBOL[0] == 0 && strcmp(symbol,"KMD") == 0 ) - matched = 1; - else matched = (strcmp(symbol,SMART_CHAIN_SYMBOL) == 0); + func = filedata[fpos++]; + matched = (strcmp(symbol,SMART_CHAIN_SYMBOL) == 0); + if ( memread(&ht,sizeof(ht),filedata,&fpos,datalen) != sizeof(ht) ) errs++; if ( func == 'P' ) @@ -243,7 +240,7 @@ int32_t hush_parsestatefiledata(struct hush_state *sp,uint8_t *filedata,long *fp else { //printf("updated %d pubkeys at %s ht.%d\n",num,symbol,ht); - if ( (HUSH_EXTERNAL_NOTARIES != 0 && matched != 0) || (strcmp(symbol,"KMD") == 0 && HUSH_EXTERNAL_NOTARIES == 0) ) + if ( (HUSH_EXTERNAL_NOTARIES != 0 && matched != 0) ) hush_eventadd_pubkeys(sp,symbol,ht,num,pubkeys); } } else printf("illegal num.%d\n",num); @@ -353,7 +350,7 @@ int32_t hush_parsestatefiledata(struct hush_state *sp,uint8_t *filedata,long *fp return(-1); } -void hush_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotaries,uint8_t notaryid,uint256 txhash,uint64_t voutmask,uint8_t numvouts,uint32_t *pvals,uint8_t numpvals,int32_t KMDheight,uint32_t KMDtimestamp,uint64_t opretvalue,uint8_t *opretbuf,uint16_t opretlen,uint16_t vout,uint256 MoM,int32_t MoMdepth) +void hush_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotaries,uint8_t notaryid,uint256 txhash,uint64_t voutmask,uint8_t numvouts,uint32_t *pvals,uint8_t numpvals,int32_t HUSHheight,uint32_t HUSHtimestamp,uint64_t opretvalue,uint8_t *opretbuf,uint16_t opretlen,uint16_t vout,uint256 MoM,int32_t MoMdepth) { static FILE *fp; static int32_t errs,didinit; static uint256 zero; struct hush_state *sp; char fname[512],symbol[HUSH_SMART_CHAIN_MAXLEN],dest[HUSH_SMART_CHAIN_MAXLEN]; int32_t retval,ht,func; uint8_t num,pubkeys[64][33]; @@ -394,30 +391,26 @@ void hush_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotarie if ( fp != 0 ) // write out funcid, height, other fields, call side effect function { //printf("fpos.%ld ",ftell(fp)); - if ( KMDheight != 0 ) + if ( HUSHheight != 0 ) { - if ( KMDtimestamp != 0 ) + if ( HUSHtimestamp != 0 ) { fputc('T',fp); if ( fwrite(&height,1,sizeof(height),fp) != sizeof(height) ) errs++; - if ( fwrite(&KMDheight,1,sizeof(KMDheight),fp) != sizeof(KMDheight) ) + if ( fwrite(&HUSHheight,1,sizeof(HUSHheight),fp) != sizeof(HUSHheight) ) errs++; - if ( fwrite(&KMDtimestamp,1,sizeof(KMDtimestamp),fp) != sizeof(KMDtimestamp) ) + if ( fwrite(&HUSHtimestamp,1,sizeof(HUSHtimestamp),fp) != sizeof(HUSHtimestamp) ) errs++; - } - else - { + } else { fputc('K',fp); if ( fwrite(&height,1,sizeof(height),fp) != sizeof(height) ) errs++; - if ( fwrite(&KMDheight,1,sizeof(KMDheight),fp) != sizeof(KMDheight) ) + if ( fwrite(&HUSHheight,1,sizeof(HUSHheight),fp) != sizeof(HUSHheight) ) errs++; } - hush_eventadd_kmdheight(sp,symbol,height,KMDheight,KMDtimestamp); - } - else if ( opretbuf != 0 && opretlen > 0 ) - { + hush_eventadd_kmdheight(sp,symbol,height,HUSHheight,HUSHtimestamp); + } else if ( opretbuf != 0 && opretlen > 0 ) { uint16_t olen = opretlen; fputc('R',fp); if ( fwrite(&height,1,sizeof(height),fp) != sizeof(height) ) @@ -432,8 +425,7 @@ void hush_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotarie errs++; if ( fwrite(opretbuf,1,olen,fp) != olen ) errs++; -//printf("create ht.%d R opret[%d] sp.%p\n",height,olen,sp); - //komodo_opreturn(height,opretvalue,opretbuf,olen,txhash,vout); + //printf("create ht.%d R opret[%d] sp.%p\n",height,olen,sp); hush_eventadd_opreturn(sp,symbol,height,txhash,opretvalue,vout,opretbuf,olen); } else if ( notarypubs != 0 && numnotaries > 0 ) @@ -510,7 +502,7 @@ void hush_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotarie } } -int32_t komodo_validate_chain(uint256 srchash,int32_t notarized_height) +int32_t hush_validate_chain(uint256 srchash,int32_t notarized_height) { static int32_t last_rewind; int32_t rewindtarget; CBlockIndex *pindex; struct hush_state *sp; char symbol[HUSH_SMART_CHAIN_MAXLEN],dest[HUSH_SMART_CHAIN_MAXLEN]; if ( (sp= hush_stateptr(symbol,dest)) == 0 ) @@ -535,7 +527,7 @@ int32_t komodo_validate_chain(uint256 srchash,int32_t notarized_height) } else return(1); } -int32_t komodo_voutupdate(bool fJustCheck,int32_t *isratificationp,int32_t notaryid,uint8_t *scriptbuf,int32_t scriptlen,int32_t height,uint256 txhash,int32_t i,int32_t j,uint64_t *voutmaskp,int32_t *specialtxp,int32_t *notarizedheightp,uint64_t value,int32_t notarized,uint64_t signedmask,uint32_t timestamp) +int32_t hush_voutupdate(bool fJustCheck,int32_t *isratificationp,int32_t notaryid,uint8_t *scriptbuf,int32_t scriptlen,int32_t height,uint256 txhash,int32_t i,int32_t j,uint64_t *voutmaskp,int32_t *specialtxp,int32_t *notarizedheightp,uint64_t value,int32_t notarized,uint64_t signedmask,uint32_t timestamp) { static uint256 zero; static FILE *signedfp; int32_t opretlen,nid,offset,k,MoMdepth,matched,len = 0; uint256 MoM,srchash,desttxid; uint8_t crypto555[33]; struct hush_state *sp; char symbol[HUSH_SMART_CHAIN_MAXLEN],dest[HUSH_SMART_CHAIN_MAXLEN]; @@ -598,11 +590,7 @@ int32_t komodo_voutupdate(bool fJustCheck,int32_t *isratificationp,int32_t notar matched = 0; if ( SMART_CHAIN_SYMBOL[0] == 0 ) { - if ( strcmp("KMD",(char *)&scriptbuf[len+32 * 2 + 4]) == 0 ) - matched = 1; - } - else - { + } else { if ( scriptbuf[len] == 'K' ) { //fprintf(stderr,"i.%d j.%d KV OPRET len.%d %.8f\n",i,j,opretlen,dstr(value)); @@ -622,7 +610,7 @@ int32_t komodo_voutupdate(bool fJustCheck,int32_t *isratificationp,int32_t notar memset(&MoMoMdata,0,sizeof(MoMoMdata)); if ( matched == 0 && signedmask != 0 && bitweight(signedmask) >= HUSH_MINRATIFY ) notarized = 1; - if ( strcmp("PIZZA",ccdata.symbol) == 0 || strncmp("TXSCL",ccdata.symbol,5) == 0 || strcmp("BEER",ccdata.symbol) == 0) + if ( strcmp("DPOW",ccdata.symbol) == 0 || strncmp("ZPOW",ccdata.symbol,5) == 0 || strcmp("TUSH",ccdata.symbol) == 0) notarized = 1; if ( 0 && opretlen != 149 ) printf("[%s].%d (%s) matched.%d i.%d j.%d notarized.%d %llx opretlen.%d len.%d offset.%d opoffset.%d\n",SMART_CHAIN_SYMBOL,height,ccdata.symbol,matched,i,j,notarized,(long long)signedmask,opretlen,len,offset,opoffset); @@ -631,7 +619,7 @@ int32_t komodo_voutupdate(bool fJustCheck,int32_t *isratificationp,int32_t notar if ( matched != 0 ) len += dragon_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&desttxid); if ( matched != 0 ) - validated = komodo_validate_chain(srchash,*notarizedheightp); + validated = hush_validate_chain(srchash,*notarizedheightp); else validated = 1; // Any notarization that is matched and has a decodable op_return is enough to pay notaries. Otherwise bugs! if ( fJustCheck && matched != 0 ) @@ -691,7 +679,7 @@ int32_t komodo_voutupdate(bool fJustCheck,int32_t *isratificationp,int32_t notar } else { - komodo_rwccdata(SMART_CHAIN_SYMBOL,1,&ccdata,&MoMoMdata); + hush_rwccdata(SMART_CHAIN_SYMBOL,1,&ccdata,&MoMoMdata); if ( matched != 0 ) printf("[%s] matched.%d VALID (%s) MoM.%s [%d] CCid.%u\n",SMART_CHAIN_SYMBOL,matched,ccdata.symbol,MoM.ToString().c_str(),MoMdepth&0xffff,(MoMdepth>>16)&0xffff); } @@ -700,8 +688,6 @@ int32_t komodo_voutupdate(bool fJustCheck,int32_t *isratificationp,int32_t notar memset(&ccdata,0,sizeof(ccdata)); memset(&MoMoMdata,0,sizeof(MoMoMdata)); } - else if ( SMART_CHAIN_SYMBOL[0] == 0 && matched != 0 && notarized != 0 && validated != 0 ) - komodo_rwccdata((char *)"KMD",1,&ccdata,0); if ( matched != 0 && *notarizedheightp > sp->NOTARIZED_HEIGHT && *notarizedheightp < height ) { @@ -715,36 +701,12 @@ int32_t komodo_voutupdate(bool fJustCheck,int32_t *isratificationp,int32_t notar } hush_stateupdate(height,0,0,0,zero,0,0,0,0,0,0,0,0,0,0,sp->MoM,sp->MoMdepth); //if ( SMART_CHAIN_SYMBOL[0] != 0 ) - printf("[%s] ht.%d NOTARIZED.%d %s.%s %sTXID.%s lens.(%d %d) MoM.%s %d\n",SMART_CHAIN_SYMBOL,height,sp->NOTARIZED_HEIGHT,SMART_CHAIN_SYMBOL[0]==0?"KMD":SMART_CHAIN_SYMBOL,srchash.ToString().c_str(),SMART_CHAIN_SYMBOL[0]==0?"BTC":"KMD",desttxid.ToString().c_str(),opretlen,len,sp->MoM.ToString().c_str(),sp->MoMdepth); + printf("[%s] ht.%d NOTARIZED.%d %s.%s %sTXID.%s lens.(%d %d) MoM.%s %d\n",SMART_CHAIN_SYMBOL,height,sp->NOTARIZED_HEIGHT,SMART_CHAIN_SYMBOL,srchash.ToString().c_str(),"HUSH",desttxid.ToString().c_str(),opretlen,len,sp->MoM.ToString().c_str(),sp->MoMdepth); - if ( SMART_CHAIN_SYMBOL[0] == 0 ) - { - if ( signedfp == 0 ) - { - char fname[512]; - hush_statefname(fname,SMART_CHAIN_SYMBOL,(char *)"hushsignedmasks"); - if ( (signedfp= fopen(fname,"rb+")) == 0 ) - signedfp = fopen(fname,"wb"); - else fseek(signedfp,0,SEEK_END); - } - if ( signedfp != 0 ) - { - fwrite(&height,1,sizeof(height),signedfp); - fwrite(&signedmask,1,sizeof(signedmask),signedfp); - fflush(signedfp); - } - if ( opretlen > len && scriptbuf[len] == 'A' ) - { - //for (i=0; i 600000 && matched != 0 ) - printf("%s validated.%d notarized.%d %llx reject ht.%d NOTARIZED.%d prev.%d %s.%s DESTTXID.%s len.%d opretlen.%d\n",ccdata.symbol,validated,notarized,(long long)signedmask,height,*notarizedheightp,sp->NOTARIZED_HEIGHT,SMART_CHAIN_SYMBOL[0]==0?"KMD":SMART_CHAIN_SYMBOL,srchash.ToString().c_str(),desttxid.ToString().c_str(),len,opretlen); + printf("%s validated.%d notarized.%d %llx reject ht.%d NOTARIZED.%d prev.%d %s.%s DESTTXID.%s len.%d opretlen.%d\n",ccdata.symbol,validated,notarized,(long long)signedmask,height,*notarizedheightp,sp->NOTARIZED_HEIGHT,SMART_CHAIN_SYMBOL,srchash.ToString().c_str(),desttxid.ToString().c_str(),len,opretlen); } else if ( matched != 0 && i == 0 && j == 1 && opretlen == 149 ) { @@ -756,7 +718,7 @@ int32_t komodo_voutupdate(bool fJustCheck,int32_t *isratificationp,int32_t notar //int32_t k; for (k=0; k= 32*2+4 && strcmp(SMART_CHAIN_SYMBOL[0]==0?"KMD":SMART_CHAIN_SYMBOL,(char *)&scriptbuf[len+32*2+4]) == 0 ) + if ( opretlen >= 32*2+4 && strcmp(SMART_CHAIN_SYMBOL,(char *)&scriptbuf[len+32*2+4]) == 0 ) { for (k=0; k<32; k++) if ( scriptbuf[len+k] != 0 ) @@ -764,7 +726,7 @@ int32_t komodo_voutupdate(bool fJustCheck,int32_t *isratificationp,int32_t notar if ( k == 32 ) { *isratificationp = 1; - printf("ISRATIFICATION (%s)\n",(char *)&scriptbuf[len+32*2+4]); + printf("%s: ISRATIFICATION (%s)\n",__func__,(char *)&scriptbuf[len+32*2+4]); } } @@ -775,12 +737,6 @@ int32_t komodo_voutupdate(bool fJustCheck,int32_t *isratificationp,int32_t notar return(notaryid); } -/*int32_t komodo_isratify(int32_t isspecial,int32_t numvalid) -{ - if ( isspecial != 0 && numvalid >= HUSH_MINRATIFY ) - return(1); - else return(0); -}*/ // Special tx have vout[0] -> CRYPTO555 address // with more than HUSH_MINRATIFY pay2pubkey outputs -> ratify @@ -790,7 +746,7 @@ int32_t komodo_voutupdate(bool fJustCheck,int32_t *isratificationp,int32_t notar int32_t gettxout_scriptPubKey(uint8_t *scriptPubKey,int32_t maxsize,uint256 txid,int32_t n); -int32_t komodo_notarycmp(uint8_t *scriptPubKey,int32_t scriptlen,uint8_t pubkeys[64][33],int32_t numnotaries,uint8_t rmd160[20]) +int32_t hush_notarycmp(uint8_t *scriptPubKey,int32_t scriptlen,uint8_t pubkeys[64][33],int32_t numnotaries,uint8_t rmd160[20]) { int32_t i; if ( scriptlen == 25 && memcmp(&scriptPubKey[3],rmd160,20) == 0 ) @@ -818,7 +774,7 @@ int32_t hush_connectblock(bool fJustCheck, CBlockIndex *pindex,CBlock& block) return(0); } memset(&zero,0,sizeof(zero)); - komodo_init(pindex->GetHeight()); + hush_init(pindex->GetHeight()); HUSH_INITDONE = (uint32_t)time(NULL); if ( (sp= hush_stateptr(symbol,dest)) == 0 ) { @@ -853,7 +809,7 @@ int32_t hush_connectblock(bool fJustCheck, CBlockIndex *pindex,CBlock& block) txn_count = block.vtx.size(); for (i=0; i 1 && ASSETCHAINS_NOTARY_PAY[0] != 0 ) break; txhash = block.vtx[i].GetHash(); @@ -868,7 +824,7 @@ int32_t hush_connectblock(bool fJustCheck, CBlockIndex *pindex,CBlock& block) continue; if ( (scriptlen= gettxout_scriptPubKey(scriptPubKey,sizeof(scriptPubKey),block.vtx[i].vin[j].prevout.hash,block.vtx[i].vin[j].prevout.n)) > 0 ) { - if ( (k= komodo_notarycmp(scriptPubKey,scriptlen,pubkeys,numnotaries,rmd160)) >= 0 ) + if ( (k= hush_notarycmp(scriptPubKey,scriptlen,pubkeys,numnotaries,rmd160)) >= 0 ) signedmask |= (1LL << k); else if ( 0 && numvins >= 17 ) { @@ -938,7 +894,7 @@ int32_t hush_connectblock(bool fJustCheck, CBlockIndex *pindex,CBlock& block) if ( len >= sizeof(uint32_t) && len <= sizeof(scriptbuf) ) { memcpy(scriptbuf,(uint8_t *)&block.vtx[i].vout[j].scriptPubKey[0],len); - notaryid = komodo_voutupdate(fJustCheck,&isratification,notaryid,scriptbuf,len,height,txhash,i,j,&voutmask,&specialtx,¬arizedheight,(uint64_t)block.vtx[i].vout[j].nValue,notarized,signedmask,(uint32_t)chainActive.LastTip()->GetBlockTime()); + notaryid = hush_voutupdate(fJustCheck,&isratification,notaryid,scriptbuf,len,height,txhash,i,j,&voutmask,&specialtx,¬arizedheight,(uint64_t)block.vtx[i].vout[j].nValue,notarized,signedmask,(uint32_t)chainActive.LastTip()->GetBlockTime()); if ( fJustCheck && notaryid == -2 ) { // We see a valid notarisation here, save its location. @@ -988,14 +944,14 @@ int32_t hush_connectblock(bool fJustCheck, CBlockIndex *pindex,CBlock& block) { memset(&txhash,0,sizeof(txhash)); hush_stateupdate(height,pubkeys,numvalid,0,txhash,0,0,0,0,0,0,0,0,0,0,zero,0); - printf("RATIFIED! >>>>>>>>>> new notaries.%d newheight.%d from height.%d\n",numvalid,(((height+KOMODO_ELECTION_GAP/2)/KOMODO_ELECTION_GAP)+1)*KOMODO_ELECTION_GAP,height); + printf("RATIFIED! >>>>>>>>>> new notaries.%d newheight.%d from height.%d\n",numvalid,(((height+HUSH_DPOW_GAP/2)/HUSH_DPOW_GAP)+1)*HUSH_DPOW_GAP,height); } else printf("signedmask.%llx numvalid.%d wt.%d numnotaries.%d\n",(long long)signedmask,numvalid,bitweight(signedmask),numnotaries); } } } } if ( !fJustCheck && IS_HUSH_NOTARY != 0 && SMART_CHAIN_SYMBOL[0] == 0 ) - printf("%s ht.%d\n",SMART_CHAIN_SYMBOL[0] == 0 ? "KMD" : SMART_CHAIN_SYMBOL,height); + printf("%s ht.%d\n",SMART_CHAIN_SYMBOL,height); if ( !fJustCheck && pindex->GetHeight() == hwmheight ) hush_stateupdate(height,0,0,0,zero,0,0,0,0,height,(uint32_t)pindex->nTime,0,0,0,0,zero,0); } diff --git a/src/hush_bitcoind.h b/src/hush_bitcoind.h index 4b6af7e53..bf53316db 100644 --- a/src/hush_bitcoind.h +++ b/src/hush_bitcoind.h @@ -15,7 +15,7 @@ * Removal or modification of this copyright notice is prohibited. * * * ******************************************************************************/ -// Hush functions that interact with bitcoind C++ +// Hush functions that interact with hushd C++ #include #include #include "consensus/params.h" @@ -25,8 +25,8 @@ #include "sietch.h" int32_t hush_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp); -int32_t komodo_electednotary(int32_t *numnotariesp,uint8_t *pubkey33,int32_t height,uint32_t timestamp); -int32_t komodo_voutupdate(bool fJustCheck,int32_t *isratificationp,int32_t notaryid,uint8_t *scriptbuf,int32_t scriptlen,int32_t height,uint256 txhash,int32_t i,int32_t j,uint64_t *voutmaskp,int32_t *specialtxp,int32_t *notarizedheightp,uint64_t value,int32_t notarized,uint64_t signedmask,uint32_t timestamp); +int32_t hush_electednotary(int32_t *numnotariesp,uint8_t *pubkey33,int32_t height,uint32_t timestamp); +int32_t hush_voutupdate(bool fJustCheck,int32_t *isratificationp,int32_t notaryid,uint8_t *scriptbuf,int32_t scriptlen,int32_t height,uint256 txhash,int32_t i,int32_t j,uint64_t *voutmaskp,int32_t *specialtxp,int32_t *notarizedheightp,uint64_t value,int32_t notarized,uint64_t signedmask,uint32_t timestamp); bool EnsureWalletIsAvailable(bool avoidException); extern bool fRequestShutdown; extern CScript HUSH_EARLYTXID_SCRIPTPUB; @@ -367,9 +367,8 @@ char *curl_post(CURL **cHandlep,char *url,char *userpass,char *postfields,char * return(chunk.memory); } -char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port) +char *hush_issuemethod(char *userpass,char *method,char *params,uint16_t port) { - //static void *cHandle; char url[512],*retstr=0,*retstr2=0,postdata[8192]; if ( params == 0 || params[0] == 0 ) params = (char *)"[]"; @@ -384,11 +383,11 @@ char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port) return(retstr2); } -int32_t notarizedtxid_height(char *dest,char *txidstr,int32_t *kmdnotarized_heightp) +int32_t notarizedtxid_height(char *dest,char *txidstr,int32_t *hushnotarized_heightp) { char *jsonstr,params[256],*userpass; uint16_t port; cJSON *json,*item; int32_t height = 0,txid_height = 0,txid_confirmations = 0; params[0] = 0; - *kmdnotarized_heightp = 0; + *hushnotarized_heightp = 0; if ( strcmp(dest,"HUSH3") == 0 ) { port = HUSH3_PORT; userpass = HUSHUSERPASS; @@ -401,7 +400,7 @@ int32_t notarizedtxid_height(char *dest,char *txidstr,int32_t *kmdnotarized_heig } if ( userpass[0] != 0 ) { - if ( (jsonstr= komodo_issuemethod(userpass,(char *)"getinfo",params,port)) != 0 ) + if ( (jsonstr= hush_issuemethod(userpass,(char *)"getinfo",params,port)) != 0 ) { //printf("(%s)\n",jsonstr); if ( (json= cJSON_Parse(jsonstr)) != 0 ) @@ -409,14 +408,14 @@ int32_t notarizedtxid_height(char *dest,char *txidstr,int32_t *kmdnotarized_heig if ( (item= jobj(json,(char *)"result")) != 0 ) { height = jint(item,(char *)"blocks"); - *kmdnotarized_heightp = strcmp(dest,"KMD") == 0 ? jint(item,(char *)"notarized") : height; + *hushnotarized_heightp = strcmp(dest,"HUSH3") == 0 ? jint(item,(char *)"notarized") : height; } free_json(json); } free(jsonstr); } sprintf(params,"[\"%s\", 1]",txidstr); - if ( (jsonstr= komodo_issuemethod(userpass,(char *)"getrawtransaction",params,port)) != 0 ) + if ( (jsonstr= hush_issuemethod(userpass,(char *)"getrawtransaction",params,port)) != 0 ) { //printf("(%s)\n",jsonstr); if ( (json= cJSON_Parse(jsonstr)) != 0 ) @@ -437,7 +436,7 @@ int32_t notarizedtxid_height(char *dest,char *txidstr,int32_t *kmdnotarized_heig return(txid_height); } -int32_t komodo_verifynotarizedscript(int32_t height,uint8_t *script,int32_t len,uint256 NOTARIZED_HASH) +int32_t hush_verifynotarizedscript(int32_t height,uint8_t *script,int32_t len,uint256 NOTARIZED_HASH) { int32_t i; uint256 hash; char params[256]; for (i=0; i<32; i++) @@ -453,19 +452,19 @@ int32_t komodo_verifynotarizedscript(int32_t height,uint8_t *script,int32_t len, return(-1); } -void komodo_reconsiderblock(uint256 blockhash) +void hush_reconsiderblock(uint256 blockhash) { char params[256],*jsonstr,*hexstr; sprintf(params,"[\"%s\"]",blockhash.ToString().c_str()); - if ( (jsonstr= komodo_issuemethod(ASSETCHAINS_USERPASS,(char *)"reconsiderblock",params,ASSETCHAINS_RPCPORT)) != 0 ) + if ( (jsonstr= hush_issuemethod(ASSETCHAINS_USERPASS,(char *)"reconsiderblock",params,ASSETCHAINS_RPCPORT)) != 0 ) { - //fprintf(stderr,"komodo_reconsiderblock.(%s) (%s %u) -> (%s)\n",params,ASSETCHAINS_USERPASS,ASSETCHAINS_RPCPORT,jsonstr); + //fprintf(stderr,"hush_reconsiderblock.(%s) (%s %u) -> (%s)\n",params,ASSETCHAINS_USERPASS,ASSETCHAINS_RPCPORT,jsonstr); free(jsonstr); } - //fprintf(stderr,"komodo_reconsiderblock.(%s) (%s %u) -> NULL\n",params,ASSETCHAINS_USERPASS,ASSETCHAINS_RPCPORT); + //fprintf(stderr,"hush_reconsiderblock.(%s) (%s %u) -> NULL\n",params,ASSETCHAINS_USERPASS,ASSETCHAINS_RPCPORT); } -int32_t komodo_verifynotarization(char *symbol,char *dest,int32_t height,int32_t NOTARIZED_HEIGHT,uint256 NOTARIZED_HASH,uint256 NOTARIZED_DESTTXID) +int32_t hush_verifynotarization(char *symbol,char *dest,int32_t height,int32_t NOTARIZED_HEIGHT,uint256 NOTARIZED_HASH,uint256 NOTARIZED_DESTTXID) { char params[256],*jsonstr,*hexstr; uint8_t *script,_script[8192]; int32_t n,len,retval = -1; cJSON *json,*txjson,*vouts,*vout,*skey; script = _script; @@ -475,34 +474,30 @@ int32_t komodo_verifynotarization(char *symbol,char *dest,int32_t height,int32_t sprintf(¶ms[i*2 + 2],"%02x",((uint8_t *)&NOTARIZED_DESTTXID)[31-i]); strcat(params,"\", 1]");*/ sprintf(params,"[\"%s\", 1]",NOTARIZED_DESTTXID.ToString().c_str()); - if ( strcmp(symbol,SMART_CHAIN_SYMBOL[0]==0?(char *)"KMD":SMART_CHAIN_SYMBOL) != 0 ) + if ( strcmp(symbol,SMART_CHAIN_SYMBOL[0]==0?(char *)"HUSH3":SMART_CHAIN_SYMBOL) != 0 ) return(0); if ( 0 && SMART_CHAIN_SYMBOL[0] != 0 ) printf("[%s] src.%s dest.%s params.[%s] ht.%d notarized.%d\n",SMART_CHAIN_SYMBOL,symbol,dest,params,height,NOTARIZED_HEIGHT); - if ( strcmp(dest,"KMD") == 0 ) + if ( strcmp(dest,"HUSH3") == 0 ) { if ( HUSHUSERPASS[0] != 0 ) { if ( SMART_CHAIN_SYMBOL[0] != 0 ) { - jsonstr = komodo_issuemethod(HUSHUSERPASS,(char *)"getrawtransaction",params,HUSH3_PORT); + jsonstr = hush_issuemethod(HUSHUSERPASS,(char *)"getrawtransaction",params,HUSH3_PORT); //printf("userpass.(%s) got (%s)\n",HUSHUSERPASS,jsonstr); } }//else jsonstr = _dex_getrawtransaction(); else return(0); // need universal way to issue DEX* API, since notaries mine most blocks, this ok - } - else if ( strcmp(dest,"BTC") == 0 ) - { + } else if ( strcmp(dest,"BTC") == 0 ) { if ( BTCUSERPASS[0] != 0 ) { //printf("BTCUSERPASS.(%s)\n",BTCUSERPASS); - jsonstr = komodo_issuemethod(BTCUSERPASS,(char *)"getrawtransaction",params,8332); + jsonstr = hush_issuemethod(BTCUSERPASS,(char *)"getrawtransaction",params,8332); } //else jsonstr = _dex_getrawtransaction(); else return(0); - } - else - { + } else { printf("[%s] verifynotarization error unexpected dest.(%s)\n",SMART_CHAIN_SYMBOL,dest); return(-1); } @@ -532,7 +527,7 @@ int32_t komodo_verifynotarization(char *symbol,char *dest,int32_t height,int32_t script += 2; len -= 2; } - retval = komodo_verifynotarizedscript(height,script,len,NOTARIZED_HASH); + retval = hush_verifynotarizedscript(height,script,len,NOTARIZED_HASH); } } } @@ -543,7 +538,7 @@ int32_t komodo_verifynotarization(char *symbol,char *dest,int32_t height,int32_t return(retval); } -CScript komodo_makeopret(CBlock *pblock, bool fNew) +CScript hush_makeopret(CBlock *pblock, bool fNew) { std::vector vLeaves; vLeaves.push_back(pblock->hashPrevBlock); @@ -560,7 +555,7 @@ CScript komodo_makeopret(CBlock *pblock, bool fNew) uint256 hash; char params[128],*hexstr,*jsonstr; cJSON *result; int32_t i; uint8_t revbuf[32]; memset(&hash,0,sizeof(hash)); sprintf(params,"[%d]",height); - if ( (jsonstr= komodo_issuemethod(HUSHUSERPASS,(char *)"getblockhash",params,BITCOIND_RPCPORT)) != 0 ) + if ( (jsonstr= hush_issuemethod(HUSHUSERPASS,(char *)"getblockhash",params,BITCOIND_RPCPORT)) != 0 ) { if ( (result= cJSON_Parse(jsonstr)) != 0 ) { @@ -575,7 +570,7 @@ CScript komodo_makeopret(CBlock *pblock, bool fNew) } free_json(result); } - printf("KMD hash.%d (%s) %x\n",height,jsonstr,*(uint32_t *)&hash); + printf("HUSH3 hash.%d (%s) %x\n",height,jsonstr,*(uint32_t *)&hash); free(jsonstr); } return(hash); @@ -583,7 +578,7 @@ CScript komodo_makeopret(CBlock *pblock, bool fNew) uint256 _hush_getblockhash(int32_t height);*/ -uint64_t komodo_seed(int32_t height) +uint64_t hush_seed(int32_t height) { uint64_t seed = 0; /*if ( 0 ) // problem during init time, seeds are needed for loading blockindex, so null seeds... @@ -613,7 +608,7 @@ uint64_t komodo_seed(int32_t height) return(seed); } -uint32_t komodo_txtime(CScript &opret,uint64_t *valuep,uint256 hash, int32_t n, char *destaddr) +uint32_t hush_txtime(CScript &opret,uint64_t *valuep,uint256 hash, int32_t n, char *destaddr) { CTxDestination address; CTransaction tx; uint256 hashBlock; int32_t numvouts; *valuep = 0; @@ -644,36 +639,10 @@ CBlockIndex *hush_getblockindex(uint256 hash) return((it != mapBlockIndex.end()) ? it->second : NULL); } -uint32_t komodo_txtime2(uint64_t *valuep,uint256 hash,int32_t n,char *destaddr) -{ - CTxDestination address; CBlockIndex *pindex; CTransaction tx; uint256 hashBlock; uint32_t txtime = 0; - *valuep = 0; - if (!GetTransaction(hash, tx, -#ifndef HUSH_ZCASH - Params().GetConsensus(), -#endif - hashBlock, true)) - { - //fprintf(stderr,"ERROR: %s/v%d locktime.%u\n",hash.ToString().c_str(),n,(uint32_t)tx.nLockTime); - return(0); - } - if ( (pindex= hush_getblockindex(hashBlock)) != 0 ) - txtime = pindex->nTime; - else txtime = tx.nLockTime; - //fprintf(stderr,"%s/v%d locktime.%u\n",hash.ToString().c_str(),n,(uint32_t)tx.nLockTime); - if ( n < tx.vout.size() ) - { - *valuep = tx.vout[n].nValue; - if (ExtractDestination(tx.vout[n].scriptPubKey, address)) - strcpy(destaddr,CBitcoinAddress(address).ToString().c_str()); - } - return(txtime); -} - bool hush_checkopret(CBlock *pblock, CScript &merkleroot) { merkleroot = pblock->vtx.back().vout.back().scriptPubKey; - return(merkleroot.IsOpReturn() && merkleroot == komodo_makeopret(pblock, false)); + return(merkleroot.IsOpReturn() && merkleroot == hush_makeopret(pblock, false)); } @@ -690,23 +659,11 @@ bool hush_hardfork_active(uint32_t time) return isactive; } -int32_t komodo_isPoS(CBlock *pblock,int32_t height,bool fJustCheck) +int32_t hush_isPoS(CBlock *pblock,int32_t height,bool fJustCheck) { return(0); } -void komodo_disconnect(CBlockIndex *pindex,CBlock& block) -{ - char symbol[HUSH_SMART_CHAIN_MAXLEN],dest[HUSH_SMART_CHAIN_MAXLEN]; struct hush_state *sp; - //fprintf(stderr,"disconnect ht.%d\n",pindex->GetHeight()); - komodo_init(pindex->GetHeight()); - if ( (sp= hush_stateptr(symbol,dest)) != 0 ) - { - //sp->rewinding = pindex->GetHeight(); - //fprintf(stderr,"-%d ",pindex->GetHeight()); - } else printf("hush_disconnect: ht.%d cant get hush_state.(%s)\n",pindex->GetHeight(),SMART_CHAIN_SYMBOL); -} - int32_t hush_is_notarytx(const CTransaction& tx) { uint8_t *ptr; static uint8_t crypto555[33]; @@ -719,7 +676,7 @@ int32_t hush_is_notarytx(const CTransaction& tx) decode_hex(crypto555,33,(char *)CRYPTO555_PUBSECPSTR); if ( memcmp(ptr+1,crypto555,33) == 0 ) { - //printf("found notarytx\n"); + fprintf(stderr,"%s: found notarytx\n", __func__); return(1); } } @@ -754,7 +711,7 @@ int32_t hush_block2height(CBlock *block) } //printf(" <- coinbase.%d ht.%d\n",(int32_t)block->vtx[0].vin[0].scriptSig.size(),height); } - //komodo_init(height); + //hush_init(height); } if ( height != height2 ) { @@ -836,48 +793,7 @@ uint32_t hush_heightstamp(int32_t height) return(0); } -/*void komodo_pindex_init(CBlockIndex *pindex,int32_t height) gets data corrupted -{ - int32_t i,num; uint8_t pubkeys[64][33]; CBlock block; - if ( pindex->didinit != 0 ) - return; - //printf("pindex.%d komodo_pindex_init notary.%d from height.%d\n",pindex->GetHeight(),pindex->notaryid,height); - if ( pindex->didinit == 0 ) - { - pindex->notaryid = -1; - if ( HUSH_LOADINGBLOCKS == 0 ) - memset(pindex->pubkey33,0xff,33); - else memset(pindex->pubkey33,0,33); - if ( hush_blockload(block,pindex) == 0 ) - { - hush_block2pubkey33(pindex->pubkey33,&block); - //for (i=0; i<33; i++) - // fprintf(stderr,"%02x",pindex->pubkey33[i]); - //fprintf(stderr," set pubkey at height %d/%d\n",pindex->GetHeight(),height); - //if ( pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 ) - // pindex->didinit = (HUSH_LOADINGBLOCKS == 0); - } // else fprintf(stderr,"error loading block at %d/%d",pindex->GetHeight(),height); - } - if ( pindex->didinit != 0 && pindex->GetHeight() >= 0 && (num= hush_notaries(pubkeys,(int32_t)pindex->GetHeight(),(uint32_t)pindex->nTime)) > 0 ) - { - for (i=0; ipubkey33,33) == 0 ) - { - pindex->notaryid = i; - break; - } - } - if ( 0 && i == num ) - { - for (i=0; i<33; i++) - fprintf(stderr,"%02x",pindex->pubkey33[i]); - fprintf(stderr," unmatched pubkey at height %d/%d\n",pindex->GetHeight(),height); - } - } -}*/ - -void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) +void hush_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) { int32_t num,i; CBlock block; memset(pubkey33,0,33); @@ -888,35 +804,7 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) } } -/*int8_t komodo_minerid(int32_t height,uint8_t *destpubkey33) -{ - int32_t num,i,numnotaries; CBlockIndex *pindex; uint32_t timestamp=0; uint8_t pubkey33[33],pubkeys[64][33]; - if ( (pindex= chainActive[height]) != 0 ) - { - if ( pindex->didinit != 0 ) - { - if ( destpubkey33 != 0 ) - memcpy(destpubkey33,pindex->pubkey33,33); - return(pindex->notaryid); - } - komodo_index2pubkey33(pubkey33,pindex,height); - if ( destpubkey33 != 0 ) - memcpy(destpubkey33,pindex->pubkey33,33); - if ( pindex->didinit != 0 ) - return(pindex->notaryid); - timestamp = pindex->GetBlockTime(); - if ( (num= hush_notaries(pubkeys,height,timestamp)) > 0 ) - { - for (i=0; i= 0 && i > 0 && mids[i] == mids[0] ) duplicate++; } @@ -949,7 +839,7 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t blo else return(0); } -int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) +int32_t hush_minerids(uint8_t *minerids,int32_t height,int32_t width) { int32_t i,j,nonz,numnotaries; CBlock block; CBlockIndex *pindex; uint8_t notarypubs33[64][33],pubkey33[33]; numnotaries = hush_notaries(notarypubs33,height,0); @@ -1029,7 +919,7 @@ int32_t hush_checkpoint(int32_t *notarized_heightp,int32_t nHeight,uint256 hash) int32_t notarized_height,MoMdepth; uint256 MoM,notarized_hash,notarized_desttxid; CBlockIndex *notary,*pindex; if ( (pindex= chainActive.LastTip()) == 0 ) return(-1); - notarized_height = komodo_notarizeddata(pindex->GetHeight(),¬arized_hash,¬arized_desttxid); + notarized_height = hush_notarizeddata(pindex->GetHeight(),¬arized_hash,¬arized_desttxid); *notarized_heightp = notarized_height; BlockMap::const_iterator it; if ( notarized_height >= 0 && notarized_height <= pindex->GetHeight() && (it = mapBlockIndex.find(notarized_hash)) != mapBlockIndex.end() && (notary = it->second) != NULL ) @@ -1060,10 +950,10 @@ int32_t hush_nextheight() else return(hush_longestchain() + 1); } -int32_t komodo_isrealtime(int32_t *kmdheightp) +int32_t hush_isrealtime(int32_t *kmdheightp) { struct hush_state *sp; CBlockIndex *pindex; - if ( (sp= hush_stateptrget((char *)"KMD")) != 0 ) + if ( (sp= hush_stateptrget((char *)"HUSH3")) != 0 ) *kmdheightp = sp->CURRENT_HEIGHT; else *kmdheightp = 0; if ( (pindex= chainActive.LastTip()) != 0 && pindex->GetHeight() >= (int32_t)hush_longestchain() ) @@ -1282,7 +1172,7 @@ int8_t hush_segid(int32_t nocache,int32_t height) { txid = block.vtx[txn_count-1].vin[0].prevout.hash; vout = block.vtx[txn_count-1].vin[0].prevout.n; - txtime = komodo_txtime(opret,&value,txid,vout,destaddr); + txtime = hush_txtime(opret,&value,txid,vout,destaddr); if ( ExtractDestination(block.vtx[txn_count-1].vout[0].scriptPubKey,voutaddress) ) { strcpy(voutaddr,CBitcoinAddress(voutaddress).ToString().c_str()); @@ -1455,7 +1345,7 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he // lulz int32_t komodo_is_PeiceOfShit() { return(1); } -uint64_t komodo_notarypayamount(int32_t nHeight, int64_t notarycount) +uint64_t hush_notarypayamount(int32_t nHeight, int64_t notarycount) { int8_t curEra = 0; int64_t ret = 0; // if we have an end block in the first era, find our current era @@ -1472,7 +1362,7 @@ uint64_t komodo_notarypayamount(int32_t nHeight, int64_t notarycount) if ( notarycount == 0 ) { - fprintf(stderr, "komodo_notarypayamount failed num notaries is 0!\n"); + fprintf(stderr, "hush_notarypayamount failed num notaries is 0!\n"); return(0); } // Because of reorgs we cannot use the notarized height value. @@ -1493,7 +1383,7 @@ int32_t hush_getnotarizedheight(uint32_t timestamp,int32_t height, uint8_t *scri if ( len >= sizeof(uint32_t) && len <= sizeof(scriptbuf) ) { memcpy(scriptbuf,script,len); - if ( komodo_voutupdate(true,&isratification,0,scriptbuf,len,height,uint256(),1,1,&voutmask,&specialtx,¬arizedheight,0,1,0,timestamp) != -2 ) + if ( hush_voutupdate(true,&isratification,0,scriptbuf,len,height,uint256(),1,1,&voutmask,&specialtx,¬arizedheight,0,1,0,timestamp) != -2 ) { fprintf(stderr, "<<<<< &NotarizationNotaries, uint32_t timestamp, int32_t height, uint8_t *script, int32_t len) +uint64_t hush_notarypay(CMutableTransaction &txNew, std::vector &NotarizationNotaries, uint32_t timestamp, int32_t height, uint8_t *script, int32_t len) { // fetch notary pubkey array. uint64_t total = 0, AmountToPay = 0; @@ -1522,7 +1412,7 @@ uint64_t komodo_notarypay(CMutableTransaction &txNew, std::vector &Notar txNew.vout.resize(NotarizationNotaries.size()+1); // Calcualte the amount to pay according to the current era. - AmountToPay = komodo_notarypayamount(height,NotarizationNotaries.size()); + AmountToPay = hush_notarypayamount(height,NotarizationNotaries.size()); if ( AmountToPay == 0 ) return(0); @@ -1597,7 +1487,7 @@ uint64_t hush_checknotarypay(CBlock *pblock,int32_t height) { // Create the coinbase tx again, using the extracted data, this is the same function the miner uses, with the same data. // This allows us to know exactly that the coinbase is correct. - totalsats = komodo_notarypay(txNew, NotarizationNotaries, pblock->nTime, height, script, scriptlen); + totalsats = hush_notarypay(txNew, NotarizationNotaries, pblock->nTime, height, script, scriptlen); } else { diff --git a/src/hush_ccdata.h b/src/hush_ccdata.h index c45cd3c62..e5e431219 100644 --- a/src/hush_ccdata.h +++ b/src/hush_ccdata.h @@ -24,7 +24,7 @@ int32_t CC_firstheight; uint256 BuildMerkleTree(bool* fMutated, const std::vector leaves, std::vector &vMerkleTree); -uint256 komodo_calcMoM(int32_t height,int32_t MoMdepth) +uint256 hush_calcMoM(int32_t height,int32_t MoMdepth) { static uint256 zero; CBlockIndex *pindex; int32_t i; std::vector tree, leaves; bool fMutated; @@ -203,7 +203,7 @@ void komodo_purge_ccdata(int32_t height) } // this is just a demo of ccdata processing to create example data for the MoMoM and allMoMs calls -int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct hush_ccdata *ccdata,struct hush_ccdataMoMoM *MoMoMdata) +int32_t hush_rwccdata(char *thischain,int32_t rwflag,struct hush_ccdata *ccdata,struct hush_ccdataMoMoM *MoMoMdata) { uint256 hash,zero; bits256 tmp; int32_t i,nonz; struct hush_ccdata *ptr; struct notarized_checkpoint *np; return(0); // disable this path as libscott method is much better diff --git a/src/hush_curve25519.h b/src/hush_curve25519.h index 5094719e7..688d9cc9b 100644 --- a/src/hush_curve25519.h +++ b/src/hush_curve25519.h @@ -955,14 +955,14 @@ uint64_t conv_NXTpassword(unsigned char *mysecret,unsigned char *mypublic,uint8_ return(addr); } -uint256 komodo_kvprivkey(uint256 *pubkeyp,char *passphrase) +uint256 hush_kvprivkey(uint256 *pubkeyp,char *passphrase) { uint256 privkey; conv_NXTpassword((uint8_t *)&privkey,(uint8_t *)pubkeyp,(uint8_t *)passphrase,(int32_t)strlen(passphrase)); return(privkey); } -uint256 komodo_kvsig(uint8_t *buf,int32_t len,uint256 _privkey) +uint256 hush_kvsig(uint8_t *buf,int32_t len,uint256 _privkey) { bits256 sig,hash,otherpub,checksig,pubkey,privkey; uint256 usig; memcpy(&privkey,&_privkey,sizeof(privkey)); @@ -984,7 +984,7 @@ uint256 komodo_kvsig(uint8_t *buf,int32_t len,uint256 _privkey) return(usig); } -int32_t komodo_kvsigverify(uint8_t *buf,int32_t len,uint256 _pubkey,uint256 sig) +int32_t hush_kvsigverify(uint8_t *buf,int32_t len,uint256 _pubkey,uint256 sig) { bits256 hash,checksig,pubkey; static uint256 zeroes; memcpy(&pubkey,&_pubkey,sizeof(pubkey)); diff --git a/src/hush_defs.h b/src/hush_defs.h index f1ea61524..8fa2024ee 100644 --- a/src/hush_defs.h +++ b/src/hush_defs.h @@ -23,7 +23,7 @@ #define HUSH_EARLYTXID_HEIGHT 100 #define ASSETCHAINS_MINHEIGHT 128 #define ASSETCHAINS_MAX_ERAS 7 -#define KOMODO_ELECTION_GAP 2000 +#define HUSH_DPOW_GAP 2000 #define ROUNDROBIN_DELAY 61 #define HUSH_SMART_CHAIN_MAXLEN 65 #define HUSH_LIMITED_NETWORKSIZE 4 @@ -538,8 +538,8 @@ uint64_t komodo_paxprice(uint64_t *seedp,int32_t height,char *base,char *rel,uin int32_t komodo_paxprices(int32_t *heights,uint64_t *prices,int32_t max,char *base,char *rel); int32_t hush_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp); char *bitcoin_address(char *coinaddr,uint8_t addrtype,uint8_t *pubkey_or_rmd160,int32_t len); -int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width); -int32_t komodo_kvsearch(uint256 *refpubkeyp,int32_t current_height,uint32_t *flagsp,int32_t *heightp,uint8_t value[DRAGON_MAXSCRIPTSIZE],uint8_t *key,int32_t keylen); +int32_t hush_minerids(uint8_t *minerids,int32_t height,int32_t width); +int32_t hush_kvsearch(uint256 *refpubkeyp,int32_t current_height,uint32_t *flagsp,int32_t *heightp,uint8_t value[DRAGON_MAXSCRIPTSIZE],uint8_t *key,int32_t keylen); uint32_t hush_blocktime(uint256 hash); int32_t hush_longestchain(); @@ -556,7 +556,7 @@ uint32_t hush_heightstamp(int32_t height); int64_t komodo_pricemult(int32_t ind); int32_t komodo_priceget(int64_t *buf64,int32_t ind,int32_t height,int32_t numblocks); int32_t hush_currentheight(); -int32_t komodo_notarized_bracket(struct notarized_checkpoint *nps[2],int32_t height); +int32_t hush_notarized_bracket(struct notarized_checkpoint *nps[2],int32_t height); arith_uint256 komodo_adaptivepow_target(int32_t height,arith_uint256 bnTarget,uint32_t nTime); bool hush_hardfork_active(uint32_t time); @@ -567,7 +567,7 @@ int32_t hush_nextheight(); CBlockIndex *hush_blockindex(uint256 hash); CBlockIndex *hush_chainactive(int32_t height); int32_t hush_blockheight(uint256 hash); -bool komodo_txnotarizedconfirmed(uint256 txid); +bool hush_txnotarizedconfirmed(uint256 txid); int32_t hush_blockload(CBlock& block, CBlockIndex *pindex); uint32_t hush_chainactive_timestamp(); uint32_t GetLatestTimestamp(int32_t height); diff --git a/src/hush_events.h b/src/hush_events.h index d3a0ffb21..6d733483d 100644 --- a/src/hush_events.h +++ b/src/hush_events.h @@ -25,7 +25,7 @@ struct hush_event *hush_eventadd(struct hush_state *sp,int32_t height,char *symb struct hush_event *ep=0; uint16_t len = (uint16_t)(sizeof(*ep) + datalen); if ( sp != 0 && SMART_CHAIN_SYMBOL[0] != 0 ) { - portable_mutex_lock(&komodo_mutex); + portable_mutex_lock(&hush_mutex); ep = (struct hush_event *)calloc(1,len); ep->len = len; ep->height = height; @@ -35,7 +35,7 @@ struct hush_event *hush_eventadd(struct hush_state *sp,int32_t height,char *symb memcpy(ep->space,data,datalen); sp->Hush_events = (struct hush_event **)realloc(sp->Hush_events,(1 + sp->Hush_numeventss) * sizeof(*sp->Hush_events)); sp->Hush_events[sp->Hush_numeventss++] = ep; - portable_mutex_unlock(&komodo_mutex); + portable_mutex_unlock(&hush_mutex); } return(ep); } @@ -43,8 +43,8 @@ struct hush_event *hush_eventadd(struct hush_state *sp,int32_t height,char *symb void hush_eventadd_notarized(struct hush_state *sp,char *symbol,int32_t height,char *dest,uint256 notarized_hash,uint256 notarized_desttxid,int32_t notarizedheight,uint256 MoM,int32_t MoMdepth) { static uint32_t counter; int32_t verified=0; char *coin; struct hush_event_notarized N; - coin = (SMART_CHAIN_SYMBOL[0] == 0) ? (char *)"KMD" : SMART_CHAIN_SYMBOL; - if ( IS_HUSH_NOTARY != 0 && (verified= komodo_verifynotarization(symbol,dest,height,notarizedheight,notarized_hash,notarized_desttxid)) < 0 ) + coin = (SMART_CHAIN_SYMBOL[0] == 0) ? (char *)"HUSH3" : SMART_CHAIN_SYMBOL; + if ( IS_HUSH_NOTARY != 0 && (verified= hush_verifynotarization(symbol,dest,height,notarizedheight,notarized_hash,notarized_desttxid)) < 0 ) { if ( counter++ < 100 ) printf("[%s] error validating notarization ht.%d notarized_height.%d, if on a pruned %s node this can be ignored\n",SMART_CHAIN_SYMBOL,height,notarizedheight,dest); @@ -62,20 +62,20 @@ void hush_eventadd_notarized(struct hush_state *sp,char *symbol,int32_t height,c strncpy(N.dest,dest,sizeof(N.dest)-1); hush_eventadd(sp,height,symbol,HUSH_EVENT_NOTARIZED,(uint8_t *)&N,sizeof(N)); if ( sp != 0 ) - komodo_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid,MoM,MoMdepth); + hush_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid,MoM,MoMdepth); } } void hush_eventadd_pubkeys(struct hush_state *sp,char *symbol,int32_t height,uint8_t num,uint8_t pubkeys[64][33]) { struct hush_event_pubkeys P; - //printf("eventadd pubkeys ht.%d\n",height); + fprintf(stderr, "%s: eventadd pubkeys height=%d\n",__func__,height); memset(&P,0,sizeof(P)); P.num = num; memcpy(P.pubkeys,pubkeys,33 * num); hush_eventadd(sp,height,symbol,HUSH_EVENT_RATIFY,(uint8_t *)&P,(int32_t)(sizeof(P.num) + 33 * num)); if ( sp != 0 ) - komodo_notarysinit(height,pubkeys,num); + hush_notarysinit(height,pubkeys,num); } void hush_eventadd_pricefeed(struct hush_state *sp,char *symbol,int32_t height,uint32_t *prices,uint8_t num) @@ -117,7 +117,7 @@ void hush_event_undo(struct hush_state *sp,struct hush_event *ep) { case HUSH_EVENT_RATIFY: printf("rewind of ratify, needs to be coded.%d\n",ep->height); break; case HUSH_EVENT_NOTARIZED: break; - case HUSH_EVENT_KMDHEIGHT: + case HUSH_EVENT_HUSHHEIGHT: if ( ep->height <= sp->SAVEDHEIGHT ) sp->SAVEDHEIGHT = ep->height; break; @@ -175,7 +175,7 @@ void hush_eventadd_kmdheight(struct hush_state *sp,char *symbol,int32_t height,i if ( kmdheight > 0 ) { buf[0] = (uint32_t)kmdheight; buf[1] = timestamp; - hush_eventadd(sp,height,symbol,HUSH_EVENT_KMDHEIGHT,(uint8_t *)buf,sizeof(buf)); + hush_eventadd(sp,height,symbol,HUSH_EVENT_HUSHHEIGHT,(uint8_t *)buf,sizeof(buf)); if ( sp != 0 ) komodo_setkmdheight(sp,kmdheight,timestamp); } else { diff --git a/src/hush_gateway.h b/src/hush_gateway.h index 9beabb6fb..ddaf366a2 100644 --- a/src/hush_gateway.h +++ b/src/hush_gateway.h @@ -32,7 +32,7 @@ int32_t pax_fiatstatus(uint64_t *available,uint64_t *deposited,uint64_t *issued, { int32_t baseid; struct hush_state *sp; int64_t netliability,maxallowed,maxval; *available = *deposited = *issued = *withdrawn = *approved = *redeemed = 0; - if ( (baseid= komodo_baseid(base)) >= 0 ) + if ( (baseid= hush_baseid(base)) >= 0 ) { if ( (sp= hush_stateptrget(base)) != 0 ) { @@ -65,10 +65,10 @@ void pax_keyset(uint8_t *buf,uint256 txid,uint16_t vout,uint8_t type) struct pax_transaction *komodo_paxfind(uint256 txid,uint16_t vout,uint8_t type) { struct pax_transaction *pax; uint8_t buf[35]; - pthread_mutex_lock(&komodo_mutex); + pthread_mutex_lock(&hush_mutex); pax_keyset(buf,txid,vout,type); HASH_FIND(hh,PAX,buf,sizeof(buf),pax); - pthread_mutex_unlock(&komodo_mutex); + pthread_mutex_unlock(&hush_mutex); return(pax); } @@ -84,7 +84,7 @@ struct pax_transaction *komodo_paxfinds(uint256 txid,uint16_t vout) struct pax_transaction *komodo_paxmark(int32_t height,uint256 txid,uint16_t vout,uint8_t type,int32_t mark) { struct pax_transaction *pax; uint8_t buf[35]; - pthread_mutex_lock(&komodo_mutex); + pthread_mutex_lock(&hush_mutex); pax_keyset(buf,txid,vout,type); HASH_FIND(hh,PAX,buf,sizeof(buf),pax); if ( pax == 0 ) @@ -104,16 +104,16 @@ struct pax_transaction *komodo_paxmark(int32_t height,uint256 txid,uint16_t vout // printf("mark ht.%d %.8f %.8f\n",pax->height,dstr(pax->komodoshis),dstr(pax->fiatoshis)); } - pthread_mutex_unlock(&komodo_mutex); + pthread_mutex_unlock(&hush_mutex); return(pax); } void komodo_paxdelete(struct pax_transaction *pax) { return; // breaks when out of order - pthread_mutex_lock(&komodo_mutex); + pthread_mutex_lock(&hush_mutex); HASH_DELETE(hh,PAX,pax); - pthread_mutex_unlock(&komodo_mutex); + pthread_mutex_unlock(&hush_mutex); } void komodo_gateway_deposit(char *coinaddr,uint64_t value,char *symbol,uint64_t fiatoshis,uint8_t *rmd160,uint256 txid,uint16_t vout,uint8_t type,int32_t height,int32_t otherheight,char *source,int32_t approved) // assetchain context @@ -124,7 +124,7 @@ void komodo_gateway_deposit(char *coinaddr,uint64_t value,char *symbol,uint64_t //if ( strcmp(symbol,SMART_CHAIN_SYMBOL) != 0 ) // return; sp = hush_stateptr(str,dest); - pthread_mutex_lock(&komodo_mutex); + pthread_mutex_lock(&hush_mutex); pax_keyset(buf,txid,vout,type); HASH_FIND(hh,PAX,buf,sizeof(buf),pax); if ( pax == 0 ) @@ -143,7 +143,7 @@ void komodo_gateway_deposit(char *coinaddr,uint64_t value,char *symbol,uint64_t printf(" v.%d [%s] kht.%d ht.%d create pax.%p symbol.%s source.%s\n",vout,SMART_CHAIN_SYMBOL,height,otherheight,pax,symbol,source); } } - pthread_mutex_unlock(&komodo_mutex); + pthread_mutex_unlock(&hush_mutex); if ( coinaddr != 0 ) { strcpy(pax->coinaddr,coinaddr); @@ -236,12 +236,12 @@ int32_t komodo_issued_opreturn(char *base,uint256 *txids,uint16_t *vouts,int64_t { txids[n] = p.txid; vouts[n] = p.vout; - values[n] = (strcmp("KMD",base) == 0) ? p.komodoshis : p.fiatoshis; - srcvalues[n] = (strcmp("KMD",base) == 0) ? p.fiatoshis : p.komodoshis; + values[n] = (strcmp("HUSH3",base) == 0) ? p.komodoshis : p.fiatoshis; + srcvalues[n] = (strcmp("HUSH3",base) == 0) ? p.fiatoshis : p.komodoshis; kmdheights[n] = p.height; otherheights[n] = p.otherheight; memcpy(&rmd160s[n * 20],p.rmd160,20); - baseids[n] = komodo_baseid(p.source); + baseids[n] = hush_baseid(p.source); if ( 0 ) { char coinaddr[64]; @@ -261,11 +261,11 @@ int32_t komodo_issued_opreturn(char *base,uint256 *txids,uint16_t *vouts,int64_t } vouts[n] = opretbuf[len++]; vouts[n] = (opretbuf[len++] << 8) | vouts[n]; - baseids[n] = komodo_baseid(base); + baseids[n] = hush_baseid(base); if ( (pax= komodo_paxfinds(txids[n],vouts[n])) != 0 ) { - values[n] = (strcmp("KMD",base) == 0) ? pax->komodoshis : pax->fiatoshis; - srcvalues[n] = (strcmp("KMD",base) == 0) ? pax->fiatoshis : pax->komodoshis; + values[n] = (strcmp("HUSH3",base) == 0) ? pax->komodoshis : pax->fiatoshis; + srcvalues[n] = (strcmp("HUSH3",base) == 0) ? pax->fiatoshis : pax->komodoshis; kmdheights[n] = pax->height; otherheights[n] = pax->otherheight; memcpy(&rmd160s[n * 20],pax->rmd160,20); @@ -306,7 +306,7 @@ uint64_t komodo_paxtotal() struct pax_transaction *pax,*pax2,*tmp,*tmp2; char symbol[HUSH_SMART_CHAIN_MAXLEN],dest[HUSH_SMART_CHAIN_MAXLEN],*str; int32_t i,ht; int64_t checktoshis; uint64_t seed,total = 0; struct hush_state *basesp; if ( HUSH_PASSPORT_INITDONE == 0 ) //HUSH_PAX == 0 || return(0); - if ( komodo_isrealtime(&ht) == 0 ) + if ( hush_isrealtime(&ht) == 0 ) return(0); else { @@ -337,7 +337,7 @@ uint64_t komodo_paxtotal() else if ( pax->type == 'W' ) { //bitcoin_address(coinaddr,addrtype,rmd160,20); - if ( (checktoshis= komodo_paxprice(&seed,pax->height,pax->source,(char *)"KMD",(uint64_t)pax->fiatoshis)) != 0 ) + if ( (checktoshis= komodo_paxprice(&seed,pax->height,pax->source,(char *)"HUSH3",(uint64_t)pax->fiatoshis)) != 0 ) { if ( komodo_paxcmp(pax->source,pax->height,pax->komodoshis,checktoshis,seed) != 0 ) { @@ -369,7 +369,7 @@ uint64_t komodo_paxtotal() { if ( pax->marked == 0 ) { - if ( komodo_is_issuer() != 0 ) + if ( hush_is_issuer() != 0 ) { if ( pax->validated != 0 && pax->type == 'D' ) { @@ -387,8 +387,8 @@ uint64_t komodo_paxtotal() else { seed = 0; - checktoshis = komodo_paxprice(&seed,pax->height,pax->source,(char *)"KMD",(uint64_t)pax->fiatoshis); - //printf("paxtotal PAX_fiatdest ht.%d price %s %.8f -> KMD %.8f vs %.8f\n",pax->height,pax->symbol,(double)pax->fiatoshis/COIN,(double)pax->komodoshis/COIN,(double)checktoshis/COIN); + checktoshis = komodo_paxprice(&seed,pax->height,pax->source,(char *)"HUSH3",(uint64_t)pax->fiatoshis); + //printf("paxtotal PAX_fiatdest ht.%d price %s %.8f -> HUSH %.8f vs %.8f\n",pax->height,pax->symbol,(double)pax->fiatoshis/COIN,(double)pax->komodoshis/COIN,(double)checktoshis/COIN); //printf(" v%d %.8f k.%d ht.%d\n",pax->vout,dstr(pax->komodoshis),pax->height,pax->otherheight); if ( seed != 0 && checktoshis != 0 ) { @@ -431,7 +431,7 @@ int32_t komodo_pending_withdraws(char *opretstr) // todo: enforce deterministic struct pax_transaction *pax,*pax2,*tmp,*paxes[64]; uint8_t opretbuf[16384*4]; int32_t i,n,ht,len=0; uint64_t total = 0; if ( HUSH_PAX == 0 || HUSH_PASSPORT_INITDONE == 0 ) return(0); - if ( komodo_isrealtime(&ht) == 0 || SMART_CHAIN_SYMBOL[0] != 0 ) + if ( hush_isrealtime(&ht) == 0 || SMART_CHAIN_SYMBOL[0] != 0 ) return(0); n = 0; HASH_ITER(hh,PAX,pax,tmp) @@ -446,7 +446,7 @@ int32_t komodo_pending_withdraws(char *opretstr) // todo: enforce deterministic else if ( (pax2= komodo_paxfind(pax->txid,pax->vout,'X')) != 0 ) pax->approved = pax->height; //printf("pending_withdraw: pax %s marked.%u approved.%u validated.%llu\n",pax->symbol,pax->marked,pax->approved,(long long)pax->validated); - if ( pax->marked == 0 && pax->approved == 0 && pax->validated != 0 ) //strcmp((char *)"KMD",pax->symbol) == 0 && + if ( pax->marked == 0 && pax->approved == 0 && pax->validated != 0 ) { if ( n < sizeof(paxes)/sizeof(*paxes) ) { @@ -480,15 +480,15 @@ int32_t komodo_gateway_deposits(CMutableTransaction *txNew,char *base,int32_t to struct pax_transaction *pax,*tmp; char symbol[HUSH_SMART_CHAIN_MAXLEN],dest[HUSH_SMART_CHAIN_MAXLEN]; uint8_t *script,opcode,opret[16384*4],data[16384*4]; int32_t i,baseid,ht,len=0,opretlen=0,numvouts=1; struct hush_state *sp; uint64_t available,deposited,issued,withdrawn,approved,redeemed,mask,sum = 0; if ( HUSH_PASSPORT_INITDONE == 0 )//HUSH_PAX == 0 || return(0); - struct hush_state *kmdsp = hush_stateptrget((char *)"KMD"); + struct hush_state *kmdsp = hush_stateptrget((char *)"HUSH3"); sp = hush_stateptr(symbol,dest); strcpy(symbol,base); - if ( SMART_CHAIN_SYMBOL[0] != 0 && komodo_baseid(SMART_CHAIN_SYMBOL) < 0 ) + if ( SMART_CHAIN_SYMBOL[0] != 0 && hush_baseid(SMART_CHAIN_SYMBOL) < 0 ) return(0); PENDING_HUSH_TX = 0; for (i=0; i<3; i++) { - if ( komodo_isrealtime(&ht) != 0 ) + if ( hush_isrealtime(&ht) != 0 ) break; sleep(1); } @@ -556,7 +556,7 @@ int32_t komodo_gateway_deposits(CMutableTransaction *txNew,char *base,int32_t to { if ( kmdsp != 0 ) { - if ( (baseid= komodo_baseid(pax->symbol)) < 0 || ((1LL << baseid) & sp->RTmask) == 0 ) + if ( (baseid= hush_baseid(pax->symbol)) < 0 || ((1LL << baseid) & sp->RTmask) == 0 ) { printf("not RT for (%s) %llx baseid.%d %llx\n",pax->symbol,(long long)sp->RTmask,baseid,(long long)(1LL< 1 ) { if ( tokomodo != 0 ) - strcpy(symbol,(char *)"KMD"); + strcpy(symbol,(char *)"HUSH3"); for (i=0; symbol[i]!=0; i++) data[len++] = symbol[i]; data[len++] = 0; for (i=0; ivout.resize(numvouts+1); txNew->vout[numvouts].nValue = 0; txNew->vout[numvouts].scriptPubKey.resize(opretlen); @@ -791,12 +791,12 @@ int32_t hush_check_deposit(int32_t height,const CBlock& block,uint32_t prevtime) else if ( height > 814000 ) { script = (uint8_t *)&block.vtx[0].vout[0].scriptPubKey[0]; - //int32_t notary = komodo_electednotary(&num,script+1,height,0); - //if ( (-1 * (komodo_electednotary(&num,script+1,height,0) >= 0) * (height > 1000000)) < 0 ) + //int32_t notary = hush_electednotary(&num,script+1,height,0); + //if ( (-1 * (hush_electednotary(&num,script+1,height,0) >= 0) * (height > 1000000)) < 0 ) // fprintf(stderr, ">>>>>>> FAILED BLOCK.%d notary.%d insync.%d\n",height,notary,HUSH_INSYNC); //else // fprintf(stderr, "<<<<<<< VALID BLOCK.%d notary.%d insync.%d\n",height,notary,HUSH_INSYNC); - return(-1 * (komodo_electednotary(&num,script+1,height,0) >= 0) * (height > 1000000)); + return(-1 * (hush_electednotary(&num,script+1,height,0) >= 0) * (height > 1000000)); } } else @@ -832,7 +832,7 @@ const char *komodo_opreturn(int32_t height,uint64_t value,uint8_t *opretbuf,int3 { uint8_t rmd160[20],rmd160s[64*20],addrtype,shortflag,pubkey33[33]; int32_t didstats,i,j,n,kvheight,len,tokomodo,kmdheight,otherheights[64],kmdheights[64]; int8_t baseids[64]; char base[4],coinaddr[64],destaddr[64]; uint256 txids[64]; uint16_t vouts[64]; uint64_t convtoshis,seed; int64_t fee,fiatoshis,komodoshis,checktoshis,values[64],srcvalues[64]; struct pax_transaction *pax,*pax2; struct hush_state *basesp; double diff; const char *typestr = "unknown"; - if ( SMART_CHAIN_SYMBOL[0] != 0 && komodo_baseid(SMART_CHAIN_SYMBOL) < 0 && opretbuf[0] != 'K' ) + if ( SMART_CHAIN_SYMBOL[0] != 0 && hush_baseid(SMART_CHAIN_SYMBOL) < 0 && opretbuf[0] != 'K' ) { //printf("komodo_opreturn skip %s\n",SMART_CHAIN_SYMBOL); return("assetchain"); @@ -843,10 +843,10 @@ const char *komodo_opreturn(int32_t height,uint64_t value,uint8_t *opretbuf,int3 memset(rmd160s,0,sizeof(rmd160s)); memset(kmdheights,0,sizeof(kmdheights)); memset(otherheights,0,sizeof(otherheights)); - tokomodo = (komodo_is_issuer() == 0); + tokomodo = (hush_is_issuer() == 0); if ( opretbuf[0] == 'K' && opretlen != 40 ) { - komodo_kvupdate(opretbuf,opretlen,value); + hush_kvupdate(opretbuf,opretlen,value); return("kv"); } else if ( SMART_CHAIN_SYMBOL[0] == 0 && HUSH_PAX == 0 ) @@ -854,7 +854,7 @@ const char *komodo_opreturn(int32_t height,uint64_t value,uint8_t *opretbuf,int3 if ( opretbuf[0] == 'D' ) { tokomodo = 0; - if ( opretlen == 38 ) // any KMD tx + if ( opretlen == 38 ) // any HUSH3 tx { dragon_rwnum(0,&opretbuf[34],sizeof(kmdheight),&kmdheight); memset(base,0,sizeof(base)); @@ -867,7 +867,7 @@ const char *komodo_opreturn(int32_t height,uint64_t value,uint8_t *opretbuf,int3 if ( 0 && strcmp("NOK",base) == 0 ) { printf("[%s] %s paxdeposit height.%d vs kmdheight.%d\n",SMART_CHAIN_SYMBOL,base,height,kmdheight); - printf("(%s) (%s) kmdheight.%d vs height.%d check %.8f vs %.8f tokomodo.%d %d seed.%llx\n",SMART_CHAIN_SYMBOL,base,kmdheight,height,dstr(checktoshis),dstr(value),komodo_is_issuer(),strncmp(SMART_CHAIN_SYMBOL,base,strlen(base)) == 0,(long long)seed); + printf("(%s) (%s) kmdheight.%d vs height.%d check %.8f vs %.8f tokomodo.%d %d seed.%llx\n",SMART_CHAIN_SYMBOL,base,kmdheight,height,dstr(checktoshis),dstr(value),hush_is_issuer(),strncmp(SMART_CHAIN_SYMBOL,base,strlen(base)) == 0,(long long)seed); for (i=0; i<32; i++) printf("%02x",((uint8_t *)&txid)[i]); printf(" <- txid.v%u ",vout); @@ -889,7 +889,7 @@ const char *komodo_opreturn(int32_t height,uint64_t value,uint8_t *opretbuf,int3 if ( 0 && strcmp(base,SMART_CHAIN_SYMBOL) == 0 ) printf("########### %p deposited %s += %.8f kmdheight.%d %.8f\n",basesp,base,dstr(fiatoshis),kmdheight,dstr(value)); } else printf("cant get stateptr.(%s)\n",base); - komodo_gateway_deposit(coinaddr,value,base,fiatoshis,rmd160,txid,vout,'D',kmdheight,height,(char *)"KMD",0); + komodo_gateway_deposit(coinaddr,value,base,fiatoshis,rmd160,txid,vout,'D',kmdheight,height,(char *)"HUSH3",0); } if ( (pax= komodo_paxfind(txid,vout,'D')) != 0 ) { @@ -933,7 +933,7 @@ const char *komodo_opreturn(int32_t height,uint64_t value,uint8_t *opretbuf,int3 if ( (pax= komodo_paxfind(txid,vout,'D')) != 0 ) pax->marked = checktoshis; if ( kmdheight > 238000 && (kmdheight > 214700 || strcmp(base,SMART_CHAIN_SYMBOL) == 0) ) //seed != 0 && - printf("pax %s deposit %.8f rejected kmdheight.%d %.8f KMD check %.8f seed.%llu\n",base,dstr(fiatoshis),kmdheight,dstr(value),dstr(checktoshis),(long long)seed); + printf("pax %s deposit %.8f rejected kmdheight.%d %.8f HUSH3 check %.8f seed.%llu\n",base,dstr(fiatoshis),kmdheight,dstr(value),dstr(checktoshis),(long long)seed); } } //else printf("[%s] %s paxdeposit height.%d vs kmdheight.%d\n",SMART_CHAIN_SYMBOL,base,height,kmdheight); } //else printf("unsupported size.%d for opreturn D\n",opretlen); @@ -941,7 +941,7 @@ const char *komodo_opreturn(int32_t height,uint64_t value,uint8_t *opretbuf,int3 else if ( opretbuf[0] == 'I' ) { tokomodo = 0; - if ( strncmp((char *)"KMD",(char *)&opretbuf[opretlen-4],3) != 0 && strncmp(SMART_CHAIN_SYMBOL,(char *)&opretbuf[opretlen-4],3) == 0 ) + if ( strncmp((char *)"HUSH3",(char *)&opretbuf[opretlen-4],3) != 0 && strncmp(SMART_CHAIN_SYMBOL,(char *)&opretbuf[opretlen-4],3) == 0 ) { if ( (n= komodo_issued_opreturn(base,txids,vouts,values,srcvalues,kmdheights,otherheights,baseids,rmd160s,opretbuf,opretlen,0)) > 0 ) { @@ -991,7 +991,7 @@ const char *komodo_opreturn(int32_t height,uint64_t value,uint8_t *opretbuf,int3 } else if ( height < 236000 && opretbuf[0] == 'W' && strncmp(SMART_CHAIN_SYMBOL,(char *)&opretbuf[opretlen-4],3) == 0 )//&& opretlen >= 38 ) { - if ( komodo_baseid((char *)&opretbuf[opretlen-4]) >= 0 && strcmp(SMART_CHAIN_SYMBOL,(char *)&opretbuf[opretlen-4]) == 0 ) + if ( hush_baseid((char *)&opretbuf[opretlen-4]) >= 0 && strcmp(SMART_CHAIN_SYMBOL,(char *)&opretbuf[opretlen-4]) == 0 ) { for (i=0; i (%s) len.%d\n",SMART_CHAIN_SYMBOL,base,kmdheight,height,dstr(checktoshis),dstr(komodoshis),dstr(value),komodo_is_issuer(),strncmp(SMART_CHAIN_SYMBOL,base,strlen(base)) == 0,(long long)seed,coinaddr,opretlen); + //printf(" [%s] WITHDRAW %s.height.%d vs height.%d check %.8f/%.8f vs %.8f tokomodo.%d %d seed.%llx -> (%s) len.%d\n",SMART_CHAIN_SYMBOL,base,kmdheight,height,dstr(checktoshis),dstr(komodoshis),dstr(value),hush_is_issuer(),strncmp(SMART_CHAIN_SYMBOL,base,strlen(base)) == 0,(long long)seed,coinaddr,opretlen); didstats = 0; //if ( komodo_paxcmp(base,kmdheight,komodoshis,checktoshis,seed) == 0 ) { @@ -1021,12 +1021,12 @@ const char *komodo_opreturn(int32_t height,uint64_t value,uint8_t *opretbuf,int3 if ( 0 && strcmp(base,"RUB") == 0 && (pax == 0 || pax->approved == 0) ) printf("notarize %s %.8f -> %.8f kmd.%d other.%d\n",SMART_CHAIN_SYMBOL,dstr(value),dstr(komodoshis),kmdheight,height); } - komodo_gateway_deposit(coinaddr,0,(char *)"KMD",value,rmd160,txid,vout,'W',kmdheight,height,source,0); + komodo_gateway_deposit(coinaddr,0,(char *)"HUSH3",value,rmd160,txid,vout,'W',kmdheight,height,source,0); if ( (pax= komodo_paxfind(txid,vout,'W')) != 0 ) { pax->type = opretbuf[0]; strcpy(pax->source,base); - strcpy(pax->symbol,"KMD"); + strcpy(pax->symbol,"HUSH3"); pax->height = kmdheight; pax->otherheight = height; pax->komodoshis = komodoshis; @@ -1058,7 +1058,7 @@ const char *komodo_opreturn(int32_t height,uint64_t value,uint8_t *opretbuf,int3 //printf("baseids[%d] %d\n",i,baseids[i]); if ( (pax= komodo_paxfind(txids[i],vouts[i],'W')) != 0 || (pax= komodo_paxfind(txids[i],vouts[i],'X')) != 0 ) { - baseids[i] = komodo_baseid(pax->symbol); + baseids[i] = hush_baseid(pax->symbol); printf("override neg1 with (%s)\n",pax->symbol); } if ( baseids[i] < 0 ) @@ -1066,8 +1066,8 @@ const char *komodo_opreturn(int32_t height,uint64_t value,uint8_t *opretbuf,int3 } didstats = 0; seed = 0; - checktoshis = komodo_paxprice(&seed,kmdheights[i],CURRENCIES[baseids[i]],(char *)"KMD",(uint64_t)values[i]); - //printf("PAX_fiatdest ht.%d price %s %.8f -> KMD %.8f vs %.8f\n",kmdheights[i],CURRENCIES[baseids[i]],(double)values[i]/COIN,(double)srcvalues[i]/COIN,(double)checktoshis/COIN); + checktoshis = komodo_paxprice(&seed,kmdheights[i],CURRENCIES[baseids[i]],(char *)"HUSH3",(uint64_t)values[i]); + //printf("PAX_fiatdest ht.%d price %s %.8f -> HUSH3 %.8f vs %.8f\n",kmdheights[i],CURRENCIES[baseids[i]],(double)values[i]/COIN,(double)srcvalues[i]/COIN,(double)checktoshis/COIN); if ( srcvalues[i] == checktoshis ) { if ( (pax= komodo_paxfind(txids[i],vouts[i],'A')) == 0 ) @@ -1123,7 +1123,7 @@ const char *komodo_opreturn(int32_t height,uint64_t value,uint8_t *opretbuf,int3 if ( baseids[i] < 0 ) continue; bitcoin_address(coinaddr,60,&rmd160s[i*20],20); - komodo_gateway_deposit(coinaddr,0,0,0,0,txids[i],vouts[i],'X',height,0,(char *)"KMD",0); + komodo_gateway_deposit(coinaddr,0,0,0,0,txids[i],vouts[i],'X',height,0,(char *)"HUSH3",0); komodo_paxmark(height,txids[i],vouts[i],'W',height); komodo_paxmark(height,txids[i],vouts[i],'A',height); komodo_paxmark(height,txids[i],vouts[i],'X',height); @@ -1241,8 +1241,8 @@ void hush_stateind_set(struct hush_state *sp,uint32_t *inds,int32_t n,uint8_t *f } } printf("numR.%d numV.%d numN.%d count.%d\n",numR,numV,numN,count); - /*else if ( func == 'K' ) // KMD height: stop after 1st - else if ( func == 'T' ) // KMD height+timestamp: stop after 1st + /*else if ( func == 'K' ) // HUSH height: stop after 1st + else if ( func == 'T' ) // HUSH height+timestamp: stop after 1st else if ( func == 'N' ) // notarization, scan backwards 1440+ blocks; else if ( func == 'V' ) // price feed: can stop after 1440+ else if ( func == 'R' ) // opreturn:*/ @@ -1444,7 +1444,7 @@ void hush_passport_iteration() limit = 10000000; } else { limit = 10000000; - refid = komodo_baseid(SMART_CHAIN_SYMBOL)+1; // illegal base -> baseid.-1 -> 0 + refid = hush_baseid(SMART_CHAIN_SYMBOL)+1; // illegal base -> baseid.-1 -> 0 if ( refid == 0 ) { HUSH_PASSPORT_INITDONE = 1; @@ -1465,7 +1465,7 @@ void hush_passport_iteration() //printf("PASSPORT %s baseid+1 %d refid.%d\n",SMART_CHAIN_SYMBOL,baseid+1,refid); if ( baseid+1 != refid ) // only need to import state from a different coin { - if ( baseid == 32 ) // only care about KMD's state + if ( baseid == 32 ) // only care about HUSH3's state { refsp->RTmask &= ~(1LL << baseid); hush_statefname(fname,baseid<32?base:(char *)"",(char *)"hushstate"); @@ -1507,8 +1507,8 @@ void hush_passport_iteration() n++; } lastpos[baseid] = ftell(fp); - if ( 0 && lastpos[baseid] == 0 && strcmp(symbol,"KMD") == 0 ) - printf("from.(%s) lastpos[%s] %ld isrt.%d\n",SMART_CHAIN_SYMBOL,CURRENCIES[baseid],lastpos[baseid],komodo_isrealtime(&ht)); + if ( 0 && lastpos[baseid] == 0 && strcmp(symbol,"HUSH3") == 0 ) + printf("from.(%s) lastpos[%s] %ld isrt.%d\n",SMART_CHAIN_SYMBOL,CURRENCIES[baseid],lastpos[baseid],hush_isrealtime(&ht)); } //else fprintf(stderr,"%s.%ld ",CURRENCIES[baseid],ftell(fp)); fclose(fp); } else fprintf(stderr,"load error.(%s) %p\n",fname,sp); @@ -1555,7 +1555,7 @@ void hush_passport_iteration() if ( sp != 0 && isrealtime == 0 ) refsp->RTbufs[0][2] = 0; } - //komodo_paxtotal(); // calls komodo_isrealtime(), which calls hush_longestchain() + //komodo_paxtotal(); // calls hush_isrealtime(), which calls hush_longestchain() refsp->RTmask |= RTmask; if ( expired == 0 && HUSH_PASSPORT_INITDONE == 0 ) { @@ -1574,7 +1574,7 @@ extern std::vector Mineropret; // opreturn data set by the data gatheri #define issue_curl(cmdstr) bitcoind_RPC(0,(char *)"CBCOINBASE",cmdstr,0,0,0) -const char *Cryptos[] = { "KMD", "ETH" }; // must be on binance (for now) +const char *Cryptos[] = { "HUSH", "ETH" }; // must be on binance (for now) // "LTC", "BCHABC", "XMR", "IOTA", "ZEC", "WAVES", "LSK", "DCR", "RVN", "DASH", "XEM", "BTS", "ICX", "HOT", "STEEM", "ENJ", "STRAT" const char *Forex[] = { "BGN","NZD","ILS","RUB","CAD","PHP","CHF","AUD","JPY","TRY","HKD","MYR","HRK","CZK","IDR","DKK","NOK","HUF","GBP","MXN","THB","ISK","ZAR","BRL","SGD","PLN","INR","KRW","RON","CNY","SEK","EUR" @@ -1753,10 +1753,10 @@ CScript komodo_mineropret(int32_t nHeight) } /* - komodo_opretvalidate() is the entire price validation! + hush_opretvalidate() is the entire price validation! it prints out some useful info for debugging, like the lag from current time and prev block and the prices encoded in the opreturn. - The only way komodo_opretvalidate() doesnt return an error is if maxflag is set or it is within tolerance of both the prior block and the local data. The local data validation only happens if it is a recent block and not a block from the past as the local node is only getting the current price data. + The only way hush_opretvalidate() doesnt return an error is if maxflag is set or it is within tolerance of both the prior block and the local data. The local data validation only happens if it is a recent block and not a block from the past as the local node is only getting the current price data. */ @@ -1772,7 +1772,7 @@ void komodo_queuelocalprice(int32_t dir,int32_t height,uint32_t timestamp,uint25 ExtremePrice.pricebits = pricebits; } -int32_t komodo_opretvalidate(const CBlock *block,CBlockIndex * const previndex,int32_t nHeight,CScript scriptPubKey) +int32_t hush_opretvalidate(const CBlock *block,CBlockIndex * const previndex,int32_t nHeight,CScript scriptPubKey) { int32_t testchain_exemption = 0; std::vector vopret; char maxflags[HUSH_MAXPRICES]; uint256 bhash; double btcusd,btcgbp,btceur; uint32_t localbits[HUSH_MAXPRICES],pricebits[HUSH_MAXPRICES],prevbits[HUSH_MAXPRICES],newprice; int32_t i,j,prevtime,maxflag,lag,lag2,lag3,n,errflag,iter; uint32_t now; @@ -2228,7 +2228,7 @@ void hush_cbopretupdate(int32_t forceflag) if ( Queued_reconsiderblock != zeroid ) { fprintf(stderr,"Queued_reconsiderblock %s\n",Queued_reconsiderblock.GetHex().c_str()); - komodo_reconsiderblock(Queued_reconsiderblock); + hush_reconsiderblock(Queued_reconsiderblock); Queued_reconsiderblock = zeroid; } if ( forceflag != 0 && pending != 0 ) diff --git a/src/hush_globals.h b/src/hush_globals.h index 7bd1222b8..12f4f7f65 100644 --- a/src/hush_globals.h +++ b/src/hush_globals.h @@ -20,21 +20,21 @@ void hush_prefetch(FILE *fp); uint32_t hush_heightstamp(int32_t height); void hush_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotaries,uint8_t notaryid,uint256 txhash,uint64_t voutmask,uint8_t numvouts,uint32_t *pvals,uint8_t numpvals,int32_t kheight,uint32_t ktime,uint64_t opretvalue,uint8_t *opretbuf,uint16_t opretlen,uint16_t vout,uint256 MoM,int32_t MoMdepth); -void komodo_init(int32_t height); +void hush_init(int32_t height); int32_t hush_MoMdata(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip); -int32_t komodo_notarizeddata(int32_t nHeight,uint256 *notarized_hashp,uint256 *notarized_desttxidp); -char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port); -void komodo_init(int32_t height); +int32_t hush_notarizeddata(int32_t nHeight,uint256 *notarized_hashp,uint256 *notarized_desttxidp); +char *hush_issuemethod(char *userpass,char *method,char *params,uint16_t port); +void hush_init(int32_t height); int32_t hush_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp); -int32_t komodo_isrealtime(int32_t *kmdheightp); +int32_t hush_isrealtime(int32_t *kmdheightp); uint64_t komodo_paxtotal(); int32_t hush_longestchain(); uint64_t komodo_maxallowed(int32_t baseid); int32_t komodo_bannedset(int32_t *indallvoutsp,uint256 *array,int32_t max); int32_t hush_checkvout(int32_t vout,int32_t k,int32_t indallvouts); -pthread_mutex_t komodo_mutex,staked_mutex; +pthread_mutex_t hush_mutex; -#define KOMODO_ELECTION_GAP 2000 //((SMART_CHAIN_SYMBOL[0] == 0) ? 2000 : 100) +#define HUSH_DPOW_GAP 2000 //((SMART_CHAIN_SYMBOL[0] == 0) ? 2000 : 100) #define HUSH_SMART_CHAIN_MAXLEN 65 struct pax_transaction *PAX; @@ -103,15 +103,15 @@ int32_t HUSH_TESTNODE, HUSH_SNAPSHOT_INTERVAL; CScript HUSH_EARLYTXID_SCRIPTPUB; int32_t ASSETCHAINS_EARLYTXIDCONTRACT; std::map mapHeightEvalActivate; -struct komodo_kv *HUSH_KV; +struct hush_kv *HUSH_KV; pthread_mutex_t HUSH_KV_mutex,HUSH_CC_mutex; #define MAX_CURRENCIES 32 char CURRENCIES[][8] = { "USD", "EUR", "JPY", "GBP", "AUD", "CAD", "CHF", "NZD", // major currencies "CNY", "RUB", "MXN", "BRL", "INR", "HKD", "TRY", "ZAR", "PLN", "NOK", "SEK", "DKK", "CZK", "HUF", "ILS", "KRW", "MYR", "PHP", "RON", "SGD", "THB", "BGN", "IDR", "HRK", - "KMD" }; + "HUSH" }; -int32_t komodo_baseid(char *origbase) +int32_t hush_baseid(char *origbase) { int32_t i; char base[64]; for (i=0; origbase[i]!=0&&i= 0 && baseid < 32 ) + //if ( (baseid = hush_baseid(SMART_CHAIN_SYMBOL)) >= 0 && baseid < 32 ) // cur_money = ASSETCHAINS_GENESISTXVAL + ASSETCHAINS_SUPPLY + nHeight * ASSETCHAINS_REWARD[0] / SATOSHIDEN; //else { diff --git a/src/hush_kv.h b/src/hush_kv.h index 3fdde30ff..9149c9ec4 100644 --- a/src/hush_kv.h +++ b/src/hush_kv.h @@ -21,7 +21,7 @@ #include "hush_defs.h" -int32_t komodo_kvcmp(uint8_t *refvalue,uint16_t refvaluesize,uint8_t *value,uint16_t valuesize) +int32_t hush_kvcmp(uint8_t *refvalue,uint16_t refvaluesize,uint8_t *value,uint16_t valuesize) { if ( refvalue == 0 && value == 0 ) return(0); @@ -32,7 +32,7 @@ int32_t komodo_kvcmp(uint8_t *refvalue,uint16_t refvaluesize,uint8_t *value,uint else return(memcmp(refvalue,value,valuesize)); } -int32_t komodo_kvnumdays(uint32_t flags) +int32_t hush_kvnumdays(uint32_t flags) { int32_t numdays; if ( (numdays= ((flags>>2)&0x3ff)+1) > 365 ) @@ -40,25 +40,25 @@ int32_t komodo_kvnumdays(uint32_t flags) return(numdays); } -int32_t komodo_kvduration(uint32_t flags) +int32_t hush_kvduration(uint32_t flags) { - return(komodo_kvnumdays(flags) * HUSH_KVDURATION); + return(hush_kvnumdays(flags) * HUSH_KVDURATION); } -uint64_t komodo_kvfee(uint32_t flags,int32_t opretlen,int32_t keylen) +uint64_t hush_kvfee(uint32_t flags,int32_t opretlen,int32_t keylen) { int32_t numdays,k; uint64_t fee; if ( (k= keylen) > 32 ) k = 32; - numdays = komodo_kvnumdays(flags); + numdays = hush_kvnumdays(flags); if ( (fee= (numdays*(opretlen * opretlen / k))) < 100000 ) fee = 100000; return(fee); } -int32_t komodo_kvsearch(uint256 *pubkeyp,int32_t current_height,uint32_t *flagsp,int32_t *heightp,uint8_t value[DRAGON_MAXSCRIPTSIZE],uint8_t *key,int32_t keylen) +int32_t hush_kvsearch(uint256 *pubkeyp,int32_t current_height,uint32_t *flagsp,int32_t *heightp,uint8_t value[DRAGON_MAXSCRIPTSIZE],uint8_t *key,int32_t keylen) { - struct komodo_kv *ptr; int32_t duration,retval = -1; + struct hush_kv *ptr; int32_t duration,retval = -1; *heightp = -1; *flagsp = 0; memset(pubkeyp,0,sizeof(*pubkeyp)); @@ -66,7 +66,7 @@ int32_t komodo_kvsearch(uint256 *pubkeyp,int32_t current_height,uint32_t *flagsp HASH_FIND(hh,HUSH_KV,key,keylen,ptr); if ( ptr != 0 ) { - duration = komodo_kvduration(ptr->flags); + duration = hush_kvduration(ptr->flags); //fprintf(stderr,"duration.%d flags.%d current.%d ht.%d keylen.%d valuesize.%d\n",duration,ptr->flags,current_height,ptr->height,ptr->keylen,ptr->valuesize); if ( current_height > (ptr->height + duration) ) { @@ -100,11 +100,11 @@ int32_t komodo_kvsearch(uint256 *pubkeyp,int32_t current_height,uint32_t *flagsp return(retval); } -void komodo_kvupdate(uint8_t *opretbuf,int32_t opretlen,uint64_t value) +void hush_kvupdate(uint8_t *opretbuf,int32_t opretlen,uint64_t value) { static uint256 zeroes; - uint32_t flags; uint256 pubkey,refpubkey,sig; int32_t i,refvaluesize,hassig,coresize,haspubkey,height,kvheight; uint16_t keylen,valuesize,newflag = 0; uint8_t *key,*valueptr,keyvalue[DRAGON_MAXSCRIPTSIZE*8]; struct komodo_kv *ptr; char *transferpubstr,*tstr; uint64_t fee; - if ( SMART_CHAIN_SYMBOL[0] == 0 ) // disable KV for KMD + uint32_t flags; uint256 pubkey,refpubkey,sig; int32_t i,refvaluesize,hassig,coresize,haspubkey,height,kvheight; uint16_t keylen,valuesize,newflag = 0; uint8_t *key,*valueptr,keyvalue[DRAGON_MAXSCRIPTSIZE*8]; struct hush_kv *ptr; char *transferpubstr,*tstr; uint64_t fee; + if ( SMART_CHAIN_SYMBOL[0] == 0 ) // disable KV return; dragon_rwnum(0,&opretbuf[1],sizeof(keylen),&keylen); dragon_rwnum(0,&opretbuf[3],sizeof(valuesize),&valuesize); @@ -115,11 +115,11 @@ void komodo_kvupdate(uint8_t *opretbuf,int32_t opretlen,uint64_t value) { static uint32_t counter; if ( ++counter < 1 ) - fprintf(stderr,"komodo_kvupdate: keylen.%d + 13 > opretlen.%d, this can be ignored\n",keylen,opretlen); + fprintf(stderr,"hush_kvupdate: keylen.%d + 13 > opretlen.%d, this can be ignored\n",keylen,opretlen); return; } valueptr = &key[keylen]; - fee = komodo_kvfee(flags,opretlen,keylen); + fee = hush_kvfee(flags,opretlen,keylen); //fprintf(stderr,"fee %.8f vs %.8f flags.%d keylen.%d valuesize.%d height.%d (%02x %02x %02x) (%02x %02x %02x)\n",(double)fee/COIN,(double)value/COIN,flags,keylen,valuesize,height,key[0],key[1],key[2],valueptr[0],valueptr[1],valueptr[2]); if ( value >= fee ) { @@ -139,13 +139,13 @@ void komodo_kvupdate(uint8_t *opretbuf,int32_t opretlen,uint64_t value) ((uint8_t *)&sig)[i] = opretbuf[coresize+sizeof(uint256)+i]; } memcpy(keyvalue,key,keylen); - if ( (refvaluesize= komodo_kvsearch((uint256 *)&refpubkey,height,&flags,&kvheight,&keyvalue[keylen],key,keylen)) >= 0 ) + if ( (refvaluesize= hush_kvsearch((uint256 *)&refpubkey,height,&flags,&kvheight,&keyvalue[keylen],key,keylen)) >= 0 ) { if ( memcmp(&zeroes,&refpubkey,sizeof(refpubkey)) != 0 ) { - if ( komodo_kvsigverify(keyvalue,keylen+refvaluesize,refpubkey,sig) < 0 ) + if ( hush_kvsigverify(keyvalue,keylen+refvaluesize,refpubkey,sig) < 0 ) { - //fprintf(stderr,"komodo_kvsigverify error [%d]\n",coresize-13); + //fprintf(stderr,"hush_kvsigverify error [%d]\n",coresize-13); return; } } @@ -169,7 +169,7 @@ void komodo_kvupdate(uint8_t *opretbuf,int32_t opretlen,uint64_t value) } else if ( ptr == 0 ) { - ptr = (struct komodo_kv *)calloc(1,sizeof(*ptr)); + ptr = (struct hush_kv *)calloc(1,sizeof(*ptr)); ptr->key = (uint8_t *)calloc(1,keylen); ptr->keylen = keylen; memcpy(ptr->key,key,keylen); diff --git a/src/hush_nSPV.h b/src/hush_nSPV.h index b2576f7ea..f8e1645d1 100644 --- a/src/hush_nSPV.h +++ b/src/hush_nSPV.h @@ -578,7 +578,7 @@ int32_t NSPV_notarizationextract(int32_t verifyntz,int32_t *ntzheightp,uint256 * int32_t numsigs=0; uint8_t elected[64][33]; char *symbol; std::vector opret; uint32_t nTime; if ( tx.vout.size() >= 2 ) { - symbol = (SMART_CHAIN_SYMBOL[0] == 0) ? (char *)"KMD" : SMART_CHAIN_SYMBOL; + symbol = (SMART_CHAIN_SYMBOL[0] == 0) ? (char *)"HUSH3" : SMART_CHAIN_SYMBOL; GetOpReturnData(tx.vout[1].scriptPubKey,opret); if ( opret.size() >= 32*2+4 ) { diff --git a/src/hush_nSPV_fullnode.h b/src/hush_nSPV_fullnode.h index 53770f430..a33013b6a 100644 --- a/src/hush_nSPV_fullnode.h +++ b/src/hush_nSPV_fullnode.h @@ -38,7 +38,7 @@ struct NSPV_ntzargs int32_t NSPV_notarization_find(struct NSPV_ntzargs *args,int32_t height,int32_t dir) { int32_t ntzheight = 0; uint256 hashBlock; CTransaction tx; Notarization nota; char *symbol; std::vector opret; - symbol = (SMART_CHAIN_SYMBOL[0] == 0) ? (char *)"KMD" : SMART_CHAIN_SYMBOL; + symbol = (SMART_CHAIN_SYMBOL[0] == 0) ? (char *)"HUSH3" : SMART_CHAIN_SYMBOL; memset(args,0,sizeof(*args)); if ( dir > 0 ) height += 10; diff --git a/src/hush_notary.h b/src/hush_notary.h index 53a4c0a33..610407df3 100644 --- a/src/hush_notary.h +++ b/src/hush_notary.h @@ -87,7 +87,7 @@ int32_t getacseason(uint32_t timestamp) int32_t hush_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp) { int32_t i,htind,n; uint64_t mask = 0; struct knotary_entry *kp,*tmp; - static uint8_t kmd_pubkeys[NUM_HUSH_SEASONS][64][33],didinit[NUM_HUSH_SEASONS]; + static uint8_t hush_pubkeys[NUM_HUSH_SEASONS][64][33],didinit[NUM_HUSH_SEASONS]; if ( timestamp == 0 && SMART_CHAIN_SYMBOL[0] != 0 ) { timestamp = hush_heightstamp(height); @@ -99,28 +99,33 @@ int32_t hush_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp) int32_t hush_season = 0; bool ishush3 = strncmp(SMART_CHAIN_SYMBOL, "HUSH3",5) == 0 ? true : false; hush_season = ishush3 ? gethushseason(height) : getacseason(timestamp); + + if(IS_HUSH_NOTARY) { + fprintf(stderr,"%s: [%s] season=%d height=%d time=%d\n", __func__, ishush3 ? "HUSH3" : SMART_CHAIN_SYMBOL, hush_season, height, timestamp); + } + if ( hush_season != 0 ) { if ( didinit[hush_season-1] == 0 ) { for (i=0; i= HUSH_MAXBLOCKS / KOMODO_ELECTION_GAP ) - htind = (HUSH_MAXBLOCKS / KOMODO_ELECTION_GAP) - 1; - numnotaries = Pubkeys[htind].numnotaries; - for (i=0; i (numnotaries >> 1) || (wt > 7 && (signedmask & 1) != 0) ) - return(1); - else return(0); -} - -void komodo_notarysinit(int32_t origheight,uint8_t pubkeys[64][33],int32_t num) +void hush_notarysinit(int32_t origheight,uint8_t pubkeys[64][33],int32_t num) { static int32_t hwmheight; int32_t k,i,htind,height; struct knotary_entry *kp; struct knotaries_entry N; if ( Pubkeys == 0 ) - Pubkeys = (struct knotaries_entry *)calloc(1 + (HUSH_MAXBLOCKS / KOMODO_ELECTION_GAP),sizeof(*Pubkeys)); + Pubkeys = (struct knotaries_entry *)calloc(1 + (HUSH_MAXBLOCKS / HUSH_DPOW_GAP),sizeof(*Pubkeys)); memset(&N,0,sizeof(N)); if ( origheight > 0 ) { - height = (origheight + KOMODO_ELECTION_GAP/2); - height /= KOMODO_ELECTION_GAP; - height = ((height + 1) * KOMODO_ELECTION_GAP); - htind = (height / KOMODO_ELECTION_GAP); - if ( htind >= HUSH_MAXBLOCKS / KOMODO_ELECTION_GAP ) - htind = (HUSH_MAXBLOCKS / KOMODO_ELECTION_GAP) - 1; - //printf("htind.%d activation %d from %d vs %d | hwmheight.%d %s\n",htind,height,origheight,(((origheight+KOMODO_ELECTION_GAP/2)/KOMODO_ELECTION_GAP)+1)*KOMODO_ELECTION_GAP,hwmheight,SMART_CHAIN_SYMBOL); + height = (origheight + HUSH_DPOW_GAP/2); + height /= HUSH_DPOW_GAP; + height = ((height + 1) * HUSH_DPOW_GAP); + htind = (height / HUSH_DPOW_GAP); + if ( htind >= HUSH_MAXBLOCKS / HUSH_DPOW_GAP ) + htind = (HUSH_MAXBLOCKS / HUSH_DPOW_GAP) - 1; + //printf("htind.%d activation %d from %d vs %d | hwmheight.%d %s\n",htind,height,origheight,(((origheight+HUSH_DPOW_GAP/2)/HUSH_DPOW_GAP)+1)*HUSH_DPOW_GAP,hwmheight,SMART_CHAIN_SYMBOL); } else htind = 0; - pthread_mutex_lock(&komodo_mutex); + pthread_mutex_lock(&hush_mutex); for (k=0; k hwmheight ) hwmheight = origheight; } @@ -207,7 +197,7 @@ int32_t hush_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,ui } if ( height >= HUSH_NOTARIES_HARDCODED || SMART_CHAIN_SYMBOL[0] != 0 ) { - if ( (*notaryidp= komodo_electednotary(&numnotaries,pubkey33,height,timestamp)) >= 0 && numnotaries != 0 ) + if ( (*notaryidp= hush_electednotary(&numnotaries,pubkey33,height,timestamp)) >= 0 && numnotaries != 0 ) { modval = ((height % numnotaries) == *notaryidp); return(modval); @@ -216,13 +206,13 @@ int32_t hush_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,ui if ( height >= 250000 ) return(-1); if ( Pubkeys == 0 ) - komodo_init(0); - htind = height / KOMODO_ELECTION_GAP; - if ( htind >= HUSH_MAXBLOCKS / KOMODO_ELECTION_GAP ) - htind = (HUSH_MAXBLOCKS / KOMODO_ELECTION_GAP) - 1; - pthread_mutex_lock(&komodo_mutex); + hush_init(0); + htind = height / HUSH_DPOW_GAP; + if ( htind >= HUSH_MAXBLOCKS / HUSH_DPOW_GAP ) + htind = (HUSH_MAXBLOCKS / HUSH_DPOW_GAP) - 1; + pthread_mutex_lock(&hush_mutex); HASH_FIND(hh,Pubkeys[htind].Notaries,pubkey33,33,kp); - pthread_mutex_unlock(&komodo_mutex); + pthread_mutex_unlock(&hush_mutex); if ( kp != 0 ) { if ( (numnotaries= Pubkeys[htind].numnotaries) > 0 ) @@ -355,7 +345,7 @@ int32_t hush_MoMdata(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int3 return(0); } -int32_t komodo_notarizeddata(int32_t nHeight,uint256 *notarized_hashp,uint256 *notarized_desttxidp) +int32_t hush_notarizeddata(int32_t nHeight,uint256 *notarized_hashp,uint256 *notarized_desttxidp) { struct notarized_checkpoint *np = 0; int32_t i=0,flag = 0; char symbol[HUSH_SMART_CHAIN_MAXLEN],dest[HUSH_SMART_CHAIN_MAXLEN]; struct hush_state *sp; if ( (sp= hush_stateptr(symbol,dest)) != 0 ) @@ -411,17 +401,17 @@ int32_t komodo_notarizeddata(int32_t nHeight,uint256 *notarized_hashp,uint256 *n return(0); } -void komodo_notarized_update(struct hush_state *sp,int32_t nHeight,int32_t notarized_height,uint256 notarized_hash,uint256 notarized_desttxid,uint256 MoM,int32_t MoMdepth) +void hush_notarized_update(struct hush_state *sp,int32_t nHeight,int32_t notarized_height,uint256 notarized_hash,uint256 notarized_desttxid,uint256 MoM,int32_t MoMdepth) { struct notarized_checkpoint *np; if ( notarized_height >= nHeight ) { - fprintf(stderr,"komodo_notarized_update REJECT notarized_height %d > %d nHeight\n",notarized_height,nHeight); + fprintf(stderr,"hush_notarized_update REJECT notarized_height %d > %d nHeight\n",notarized_height,nHeight); return; } if ( 0 && SMART_CHAIN_SYMBOL[0] != 0 ) - fprintf(stderr,"[%s] komodo_notarized_update nHeight.%d notarized_height.%d\n",SMART_CHAIN_SYMBOL,nHeight,notarized_height); - portable_mutex_lock(&komodo_mutex); + fprintf(stderr,"[%s] hush_notarized_update nHeight.%d notarized_height.%d\n",SMART_CHAIN_SYMBOL,nHeight,notarized_height); + portable_mutex_lock(&hush_mutex); sp->NPOINTS = (struct notarized_checkpoint *)realloc(sp->NPOINTS,(sp->NUM_NPOINTS+1) * sizeof(*sp->NPOINTS)); np = &sp->NPOINTS[sp->NUM_NPOINTS++]; memset(np,0,sizeof(*np)); @@ -431,18 +421,18 @@ void komodo_notarized_update(struct hush_state *sp,int32_t nHeight,int32_t notar sp->NOTARIZED_DESTTXID = np->notarized_desttxid = notarized_desttxid; sp->MoM = np->MoM = MoM; sp->MoMdepth = np->MoMdepth = MoMdepth; - portable_mutex_unlock(&komodo_mutex); + portable_mutex_unlock(&hush_mutex); } -void komodo_init(int32_t height) +void hush_init(int32_t height) { static int didinit; uint256 zero; int32_t k,n; uint8_t pubkeys[64][33]; if ( 0 && height != 0 ) - printf("komodo_init ht.%d didinit.%d\n",height,didinit); + printf("hush_init ht.%d didinit.%d\n",height,didinit); memset(&zero,0,sizeof(zero)); if ( didinit == 0 ) { - pthread_mutex_init(&komodo_mutex,NULL); + pthread_mutex_init(&hush_mutex,NULL); decode_hex(NOTARY_PUBKEY33,33,(char *)NOTARY_PUBKEY.c_str()); if ( height >= 0 ) { @@ -453,7 +443,7 @@ void komodo_init(int32_t height) break; decode_hex(pubkeys[k],33,(char *)Notaries_genesis[k][1]); } - komodo_notarysinit(0,pubkeys,k); + hush_notarysinit(0,pubkeys,k); } //for (i=0; i sizeof(crc32) ) - { - if ( (retval= (int32_t)fread(data,1,fsize,fp)) == fsize ) - { - len = dragon_rwnum(0,data,sizeof(crc32),(void *)&crc32); - check = calc_crc32(0,data+sizeof(crc32),(int32_t)(fsize-sizeof(crc32))); - if ( check == crc32 ) - { - double KMDBTC,BTCUSD,CNYUSD; uint32_t pvals[128]; - if ( dpow_readprices(height,&data[len],×tamp,&KMDBTC,&BTCUSD,&CNYUSD,pvals) > 0 ) - { - if ( 0 && lastcrc != crc32 ) - { - for (i=0; i<32; i++) - printf("%u ",pvals[i]); - printf("t%u n.%d KMD %f BTC %f CNY %f (%f)\n",timestamp,n,KMDBTC,BTCUSD,CNYUSD,CNYUSD!=0?1./CNYUSD:0); - } - if ( timestamp > time(NULL)-600 ) - { - n = komodo_opreturnscript(opret,'P',data+sizeof(crc32),(int32_t)(fsize-sizeof(crc32))); - if ( 0 && lastcrc != crc32 ) - { - for (i=0; i maxsize.%d or data[%d]\n",fsize,maxsize,(int32_t)sizeof(data)); - fclose(fp); - } //else printf("couldnt open %s\n",fname); - return(n); -} - -/*uint32_t PAX_val32(double val) - { - uint32_t val32 = 0; struct price_resolution price; - if ( (price.Pval= val*1000000000) != 0 ) - { - if ( price.Pval > 0xffffffff ) - printf("Pval overflow error %lld\n",(long long)price.Pval); - else val32 = (uint32_t)price.Pval; - } - return(val32); - }*/ - int32_t PAX_pubkey(int32_t rwflag,uint8_t *pubkey33,uint8_t *addrtypep,uint8_t rmd160[20],char fiat[4],uint8_t *shortflagp,int64_t *fiatoshisp) { if ( rwflag != 0 ) @@ -332,33 +230,6 @@ double PAX_val(uint32_t pval,int32_t baseid) void komodo_pvals(int32_t height,uint32_t *pvals,uint8_t numpvals) { - int32_t i,nonz; uint32_t kmdbtc,btcusd,cnyusd; double KMDBTC,BTCUSD,CNYUSD; - if ( numpvals >= 35 ) - { - for (nonz=i=0; i<32; i++) - { - if ( pvals[i] != 0 ) - nonz++; - //printf("%u ",pvals[i]); - } - if ( nonz == 32 ) - { - kmdbtc = pvals[i++]; - btcusd = pvals[i++]; - cnyusd = pvals[i++]; - KMDBTC = ((double)kmdbtc / (1000000000. * 1000.)); - BTCUSD = PAX_BTCUSD(height,btcusd); - CNYUSD = ((double)cnyusd / 1000000000.); - portable_mutex_lock(&komodo_mutex); - PVALS = (uint32_t *)realloc(PVALS,(NUM_PRICES+1) * sizeof(*PVALS) * 36); - PVALS[36 * NUM_PRICES] = height; - memcpy(&PVALS[36 * NUM_PRICES + 1],pvals,sizeof(*pvals) * 35); - NUM_PRICES++; - portable_mutex_unlock(&komodo_mutex); - if ( 0 ) - printf("OP_RETURN.%d KMD %.8f BTC %.6f CNY %.6f NUM_PRICES.%d (%llu %llu %llu)\n",height,KMDBTC,BTCUSD,CNYUSD,NUM_PRICES,(long long)kmdbtc,(long long)btcusd,(long long)cnyusd); - } - } } uint64_t komodo_paxcorrelation(uint64_t *votes,int32_t numvotes,uint64_t seed) @@ -423,326 +294,26 @@ uint64_t komodo_paxcorrelation(uint64_t *votes,int32_t numvotes,uint64_t seed) return(sum); } -uint64_t komodo_paxcalc(int32_t height,uint32_t *pvals,int32_t baseid,int32_t relid,uint64_t basevolume,uint64_t refkmdbtc,uint64_t refbtcusd) -{ - uint32_t pvalb,pvalr; double BTCUSD; uint64_t price,kmdbtc,btcusd,usdvol,baseusd,usdkmd,baserel,ranked[32]; - if ( basevolume > HUSH_PAXMAX ) - { - printf("paxcalc overflow %.8f\n",dstr(basevolume)); - return(0); - } - if ( (pvalb= pvals[baseid]) != 0 ) - { - if ( relid == MAX_CURRENCIES ) - { - if ( height < 236000 ) - { - if ( kmdbtc == 0 ) - kmdbtc = pvals[MAX_CURRENCIES]; - if ( btcusd == 0 ) - btcusd = pvals[MAX_CURRENCIES + 1]; - } - else - { - if ( (kmdbtc= pvals[MAX_CURRENCIES]) == 0 ) - kmdbtc = refkmdbtc; - if ( (btcusd= pvals[MAX_CURRENCIES + 1]) == 0 ) - btcusd = refbtcusd; - } - if ( kmdbtc < 25000000 ) - kmdbtc = 25000000; - if ( pvals[USD] != 0 && kmdbtc != 0 && btcusd != 0 ) - { - baseusd = (((uint64_t)pvalb * 1000000000) / pvals[USD]); - usdvol = komodo_paxvol(basevolume,baseusd); - usdkmd = ((uint64_t)kmdbtc * 1000000000) / btcusd; - if ( height >= 236000-10 ) - { - BTCUSD = PAX_BTCUSD(height,btcusd); - if ( height < BTCFACTOR_HEIGHT || (height < 500000 && BTCUSD > 20000) ) - usdkmd = ((uint64_t)kmdbtc * btcusd) / 1000000000; - else usdkmd = ((uint64_t)kmdbtc * btcusd) / 10000000; - ///if ( height >= BTCFACTOR_HEIGHT && BTCUSD >= 43 ) - // usdkmd = ((uint64_t)kmdbtc * btcusd) / 10000000; - //else usdkmd = ((uint64_t)kmdbtc * btcusd) / 1000000000; - price = ((uint64_t)10000000000 * MINDENOMS[USD] / MINDENOMS[baseid]) / komodo_paxvol(usdvol,usdkmd); - //fprintf(stderr,"ht.%d %.3f kmdbtc.%llu btcusd.%llu base -> USD %llu, usdkmd %llu usdvol %llu -> %llu\n",height,BTCUSD,(long long)kmdbtc,(long long)btcusd,(long long)baseusd,(long long)usdkmd,(long long)usdvol,(long long)(MINDENOMS[USD] * komodo_paxvol(usdvol,usdkmd) / (MINDENOMS[baseid]/100))); - //fprintf(stderr,"usdkmd.%llu basevolume.%llu baseusd.%llu paxvol.%llu usdvol.%llu -> %llu %llu\n",(long long)usdkmd,(long long)basevolume,(long long)baseusd,(long long)komodo_paxvol(basevolume,baseusd),(long long)usdvol,(long long)(MINDENOMS[USD] * komodo_paxvol(usdvol,usdkmd) / (MINDENOMS[baseid]/100)),(long long)price); - //fprintf(stderr,"usdkmd.%llu basevolume.%llu baseusd.%llu paxvol.%llu usdvol.%llu -> %llu\n",(long long)usdkmd,(long long)basevolume,(long long)baseusd,(long long)komodo_paxvol(basevolume,baseusd),(long long)usdvol,(long long)(MINDENOMS[USD] * komodo_paxvol(usdvol,usdkmd) / (MINDENOMS[baseid]/100))); - } else price = (MINDENOMS[USD] * komodo_paxvol(usdvol,usdkmd) / (MINDENOMS[baseid]/100)); - return(price); - } //else printf("zero val in KMD conv %llu %llu %llu\n",(long long)pvals[USD],(long long)kmdbtc,(long long)btcusd); - } - else if ( baseid == relid ) - { - if ( baseid != MAX_CURRENCIES ) - { - pax_rank(ranked,pvals); - //printf("%s M1 percentage %.8f\n",CURRENCIES[baseid],dstr(10 * ranked[baseid])); - return(10 * ranked[baseid]); // scaled percentage of M1 total - } else return(basevolume); - } - else if ( (pvalr= pvals[relid]) != 0 ) - { - baserel = ((uint64_t)pvalb * 1000000000) / pvalr; - //printf("baserel.%lld %lld %lld %.8f %.8f\n",(long long)baserel,(long long)MINDENOMS[baseid],(long long)MINDENOMS[relid],dstr(MINDENOMS[baseid]/MINDENOMS[relid]),dstr(MINDENOMS[relid]/MINDENOMS[baseid])); - if ( MINDENOMS[baseid] > MINDENOMS[relid] ) - basevolume /= (MINDENOMS[baseid] / MINDENOMS[relid]); - else if ( MINDENOMS[baseid] < MINDENOMS[relid] ) - basevolume *= (MINDENOMS[relid] / MINDENOMS[baseid]); - return(komodo_paxvol(basevolume,baserel)); - } - else printf("null pval for %s\n",CURRENCIES[relid]); - } else printf("null pval for %s\n",CURRENCIES[baseid]); - return(0); -} - -uint64_t _komodo_paxprice(uint64_t *kmdbtcp,uint64_t *btcusdp,int32_t height,char *base,char *rel,uint64_t basevolume,uint64_t kmdbtc,uint64_t btcusd) -{ - int32_t baseid=-1,relid=-1,i; uint32_t *ptr,*pvals; - if ( height > 10 ) - height -= 10; - if ( (baseid= komodo_baseid(base)) >= 0 && (relid= komodo_baseid(rel)) >= 0 ) - { - //portable_mutex_lock(&komodo_mutex); - for (i=NUM_PRICES-1; i>=0; i--) - { - ptr = &PVALS[36 * i]; - if ( *ptr < height ) - { - pvals = &ptr[1]; - if ( kmdbtcp != 0 && btcusdp != 0 ) - { - *kmdbtcp = pvals[MAX_CURRENCIES] / 539; - *btcusdp = pvals[MAX_CURRENCIES + 1] / 539; - } - //portable_mutex_unlock(&komodo_mutex); - if ( kmdbtc != 0 && btcusd != 0 ) - return(komodo_paxcalc(height,pvals,baseid,relid,basevolume,kmdbtc,btcusd)); - else return(0); - } - } - //portable_mutex_unlock(&komodo_mutex); - } //else printf("paxprice invalid base.%s %d, rel.%s %d\n",base,baseid,rel,relid); - return(0); -} - -int32_t komodo_kmdbtcusd(int32_t rwflag,uint64_t *kmdbtcp,uint64_t *btcusdp,int32_t height) -{ - static uint64_t *KMDBTCS,*BTCUSDS; static int32_t maxheight = 0; int32_t incr = 10000; - if ( height >= maxheight ) - { - //printf("height.%d maxheight.%d incr.%d\n",height,maxheight,incr); - if ( height >= maxheight+incr ) - incr = (height - (maxheight+incr) + 1000); - KMDBTCS = (uint64_t *)realloc(KMDBTCS,((incr + maxheight) * sizeof(*KMDBTCS))); - memset(&KMDBTCS[maxheight],0,(incr * sizeof(*KMDBTCS))); - BTCUSDS = (uint64_t *)realloc(BTCUSDS,((incr + maxheight) * sizeof(*BTCUSDS))); - memset(&BTCUSDS[maxheight],0,(incr * sizeof(*BTCUSDS))); - maxheight += incr; - } - if ( rwflag == 0 ) - { - *kmdbtcp = KMDBTCS[height]; - *btcusdp = BTCUSDS[height]; - } - else - { - KMDBTCS[height] = *kmdbtcp; - BTCUSDS[height] = *btcusdp; - } - if ( *kmdbtcp != 0 && *btcusdp != 0 ) - return(0); - else return(-1); -} - -uint64_t _komodo_paxpriceB(uint64_t seed,int32_t height,char *base,char *rel,uint64_t basevolume) -{ - int32_t i,j,k,ind,zeroes,numvotes,wt,nonz; int64_t delta; uint64_t lastprice,tolerance,den,densum,sum=0,votes[sizeof(Peggy_inds)/sizeof(*Peggy_inds)],btcusds[sizeof(Peggy_inds)/sizeof(*Peggy_inds)],kmdbtcs[sizeof(Peggy_inds)/sizeof(*Peggy_inds)],kmdbtc,btcusd; - if ( basevolume > HUSH_PAXMAX ) - { - printf("komodo_paxprice overflow %.8f\n",dstr(basevolume)); - return(0); - } - if ( strcmp(base,"KMD") == 0 || strcmp(base,"kmd") == 0 ) - { - printf("kmd cannot be base currency\n"); - return(0); - } - numvotes = (int32_t)(sizeof(Peggy_inds)/sizeof(*Peggy_inds)); - memset(votes,0,sizeof(votes)); - //if ( komodo_kmdbtcusd(0,&kmdbtc,&btcusd,height) < 0 ) crashes when via passthru GUI use - { - memset(btcusds,0,sizeof(btcusds)); - memset(kmdbtcs,0,sizeof(kmdbtcs)); - for (i=0; i> 1) ) - { - return(0); - } - return(komodo_paxcorrelation(votes,numvotes,seed) * basevolume / 100000); -} - uint64_t komodo_paxpriceB(uint64_t seed,int32_t height,char *base,char *rel,uint64_t basevolume) { - uint64_t baseusd,basekmd,usdkmd; int32_t baseid = komodo_baseid(base); - if ( height >= 236000 && strcmp(rel,"kmd") == 0 ) - { - usdkmd = _komodo_paxpriceB(seed,height,(char *)"USD",(char *)"KMD",SATOSHIDEN); - if ( strcmp("usd",base) == 0 ) - return(komodo_paxvol(basevolume,usdkmd) * 10); - baseusd = _komodo_paxpriceB(seed,height,base,(char *)"USD",SATOSHIDEN); - basekmd = (komodo_paxvol(basevolume,baseusd) * usdkmd) / 10000000; - //if ( strcmp("KMD",base) == 0 ) - // printf("baseusd.%llu usdkmd.%llu %llu\n",(long long)baseusd,(long long)usdkmd,(long long)basekmd); - return(basekmd); - } else return(_komodo_paxpriceB(seed,height,base,rel,basevolume)); + return 0; } -/*uint64_t komodo_paxpriceB(uint64_t seed,int32_t height,char *base,char *rel,uint64_t basevolume) -{ - uint64_t baseusd,basekmd,usdkmd; int32_t baseid = komodo_baseid(base); - //if ( strcmp(rel,"KMD") != 0 || baseid < 0 || MINDENOMS[baseid] == MINDENOMS[USD] ) - // return(_komodo_paxpriceB(seed,height,base,rel,basevolume)); - //else - { - baseusd = _komodo_paxpriceB(seed,height,base,(char *)"USD",SATOSHIDEN); - usdkmd = _komodo_paxpriceB(seed,height,(char *)"USD",(char *)"KMD",SATOSHIDEN); - basekmd = (komodo_paxvol(basevolume,baseusd) * usdkmd) / 10000000; - if ( strcmp("KMD",base) == 0 ) - printf("baseusd.%llu usdkmd.%llu %llu\n",(long long)baseusd,(long long)usdkmd,(long long)basekmd); - return(basekmd); - } -}*/ - uint64_t komodo_paxprice(uint64_t *seedp,int32_t height,char *base,char *rel,uint64_t basevolume) { - int32_t i,nonz=0; int64_t diff; uint64_t price,seed,sum = 0; - if ( SMART_CHAIN_SYMBOL[0] == 0 && chainActive.LastTip() != 0 && height > chainActive.LastTip()->GetHeight() ) - { - if ( height < 100000000 ) - { - static uint32_t counter; - if ( counter++ < 3 ) - printf("komodo_paxprice height.%d vs tip.%d\n",height,chainActive.LastTip()->GetHeight()); - } - return(0); - } - *seedp = komodo_seed(height); - portable_mutex_lock(&komodo_mutex); - for (i=0; i<17; i++) - { - if ( (price= komodo_paxpriceB(*seedp,height-i,base,rel,basevolume)) != 0 ) - { - sum += price; - nonz++; - if ( 0 && i == 1 && nonz == 2 ) - { - diff = (((int64_t)price - (sum >> 1)) * 10000); - if ( diff < 0 ) - diff = -diff; - diff /= price; - printf("(%llu %llu %lld).%lld ",(long long)price,(long long)(sum>>1),(long long)(((int64_t)price - (sum >> 1)) * 10000),(long long)diff); - if ( diff < 33 ) - break; - } - else if ( 0 && i == 3 && nonz == 4 ) - { - diff = (((int64_t)price - (sum >> 2)) * 10000); - if ( diff < 0 ) - diff = -diff; - diff /= price; - printf("(%llu %llu %lld).%lld ",(long long)price,(long long)(sum>>2),(long long) (((int64_t)price - (sum >> 2)) * 10000),(long long)diff); - if ( diff < 20 ) - break; - } - } - if ( height < 165000 || height > 236000 ) - break; - } - portable_mutex_unlock(&komodo_mutex); - if ( nonz != 0 ) - sum /= nonz; - //printf("-> %lld %s/%s i.%d ht.%d\n",(long long)sum,base,rel,i,height); - return(sum); + return 0; } int32_t komodo_paxprices(int32_t *heights,uint64_t *prices,int32_t max,char *base,char *rel) { - int32_t baseid=-1,relid=-1,i,num = 0; uint32_t *ptr; - if ( (baseid= komodo_baseid(base)) >= 0 && (relid= komodo_baseid(rel)) >= 0 ) - { - for (i=NUM_PRICES-1; i>=0; i--) - { - ptr = &PVALS[36 * i]; - heights[num] = *ptr; - prices[num] = komodo_paxcalc(*ptr,&ptr[1],baseid,relid,COIN,0,0); - num++; - if ( num >= max ) - return(num); - } - } - return(num); + return 0; } void komodo_paxpricefeed(int32_t height,uint8_t *pricefeed,int32_t opretlen) { - double KMDBTC,BTCUSD,CNYUSD; uint32_t numpvals,timestamp,pvals[128]; uint256 zero; - numpvals = dpow_readprices(height,pricefeed,×tamp,&KMDBTC,&BTCUSD,&CNYUSD,pvals); - memset(&zero,0,sizeof(zero)); - hush_stateupdate(height,0,0,0,zero,0,0,pvals,numpvals,0,0,0,0,0,0,zero,0); - if ( 0 ) - { - int32_t i; - for (i=0; i KMD %.8f seed.%llx\n",height,base,(double)fiatoshis/COIN,(double)komodoshis/COIN,(long long)*seedp); - if ( bitcoin_addr2rmd160(&addrtype,rmd160,coinaddr) == 20 ) - { - PAX_pubkey(1,pubkey33,&addrtype,rmd160,base,&shortflag,tokomodo != 0 ? &komodoshis : &fiatoshis); - bitcoin_address(destaddr,HUSH_PUBTYPE,pubkey33,33); - } - return(komodoshis); + return 0; } diff --git a/src/hush_structs.h b/src/hush_structs.h index 1dda55a08..3ba56fefc 100644 --- a/src/hush_structs.h +++ b/src/hush_structs.h @@ -33,7 +33,7 @@ #define HUSH_MAXBLOCKS 250000 // DONT CHANGE #define HUSH_EVENT_RATIFY 'P' #define HUSH_EVENT_NOTARIZED 'N' -#define HUSH_EVENT_KMDHEIGHT 'K' +#define HUSH_EVENT_HUSHHEIGHT 'K' #define HUSH_EVENT_REWIND 'B' #define HUSH_EVENT_PRICEFEED 'V' #define HUSH_EVENT_OPRETURN 'R' @@ -56,7 +56,7 @@ union _bits320 { uint8_t bytes[40]; uint16_t ushorts[20]; uint32_t uints[10]; uint64_t ulongs[5]; uint64_t txid; }; typedef union _bits320 bits320; -struct komodo_kv { UT_hash_handle hh; bits256 pubkey; uint8_t *key,*value; int32_t height; uint32_t flags; uint16_t keylen,valuesize; }; +struct hush_kv { UT_hash_handle hh; bits256 pubkey; uint8_t *key,*value; int32_t height; uint32_t flags; uint16_t keylen,valuesize; }; struct hush_event_notarized { uint256 blockhash,desttxid,MoM; int32_t notarizedheight,MoMdepth; char dest[16]; }; struct hush_event_pubkeys { uint8_t num; uint8_t pubkeys[64][33]; }; diff --git a/src/hush_utils.h b/src/hush_utils.h index 439d85eab..6c19523e4 100644 --- a/src/hush_utils.h +++ b/src/hush_utils.h @@ -809,9 +809,9 @@ char *bitcoin_address(char *coinaddr,uint8_t addrtype,uint8_t *pubkey_or_rmd160, return(coinaddr); } -int32_t komodo_is_issuer() +int32_t hush_is_issuer() { - if ( SMART_CHAIN_SYMBOL[0] != 0 && komodo_baseid(SMART_CHAIN_SYMBOL) >= 0 ) + if ( SMART_CHAIN_SYMBOL[0] != 0 && hush_baseid(SMART_CHAIN_SYMBOL) >= 0 ) return(1); else return(0); } @@ -999,7 +999,7 @@ int32_t komodo_scriptitemlen(int32_t *opretlenp,uint8_t *script) return(len); } -int32_t komodo_opreturnscript(uint8_t *script,uint8_t type,uint8_t *opret,int32_t opretlen) +int32_t hush_opreturnscript(uint8_t *script,uint8_t type,uint8_t *opret,int32_t opretlen) { int32_t offset = 0; script[offset++] = 0x6a; @@ -1295,7 +1295,7 @@ void dragon_initQ(queue_t *Q,char *name) free(item); } -uint16_t _komodo_userpass(char *username,char *password,FILE *fp) +uint16_t _hush_userpass(char *username,char *password,FILE *fp) { char *rpcuser,*rpcpassword,*str,line[8192]; uint16_t port = 0; rpcuser = rpcpassword = 0; @@ -1343,16 +1343,14 @@ void hush_statefname(char *fname,char *symbol,char *str) printf("unexpected fname.(%s) vs %s [%s] n.%d len.%d (%s)\n",fname,symbol,SMART_CHAIN_SYMBOL,n,len,&fname[len - n]); return; } - } - else - { + } else { #ifdef _WIN32 strcat(fname,"\\"); #else strcat(fname,"/"); #endif } - if ( symbol != 0 && symbol[0] != 0 && strcmp("KMD",symbol) != 0 ) + if ( symbol != 0 && symbol[0] != 0) { strcat(fname,symbol); //printf("statefname.(%s) -> (%s)\n",symbol,fname); @@ -1366,10 +1364,10 @@ void hush_statefname(char *fname,char *symbol,char *str) //printf("test.(%s) -> [%s] statename.(%s) %s\n",test,SMART_CHAIN_SYMBOL,symbol,fname); } -void komodo_configfile(char *symbol,uint16_t rpcport) +void hush_configfile(char *symbol,uint16_t rpcport) { static char myusername[512],mypassword[8192]; - FILE *fp; uint16_t kmdport; uint8_t buf2[33]; char fname[512],buf[128],username[512],password[8192]; uint32_t crc,r,r2,i; + FILE *fp; uint16_t hushport; uint8_t buf2[33]; char fname[512],buf[128],username[512],password[8192]; uint32_t crc,r,r2,i; if ( symbol != 0 && rpcport != 0 ) { r = (uint32_t)time(NULL); @@ -1398,13 +1396,13 @@ void komodo_configfile(char *symbol,uint16_t rpcport) #ifndef FROM_CLI if ( (fp= fopen(fname,"wb")) != 0 ) { - fprintf(fp,"rpcuser=user%u\nrpcpassword=pass%s\nrpcport=%u\nserver=1\ntxindex=1\nrpcworkqueue=256\nrpcallowip=127.0.0.1\nrpcbind=127.0.0.1\n",crc,password,rpcport); + fprintf(fp,"rpcuser=user%u\nrpcpassword=pass%s\nrpcport=%u\nserver=1\ntxindex=1\nrpcworkqueue=4096\nrpcallowip=127.0.0.1\nrpcbind=127.0.0.1\n",crc,password,rpcport); fclose(fp); printf("Created (%s)\n",fname); } else printf("Couldnt create (%s)\n",fname); #endif } else { - _komodo_userpass(myusername,mypassword,fp); + _hush_userpass(myusername,mypassword,fp); mapArgs["-rpcpassword"] = mypassword; mapArgs["-rpcusername"] = myusername; //fprintf(stderr,"myusername.(%s)\n",myusername); @@ -1415,43 +1413,39 @@ void komodo_configfile(char *symbol,uint16_t rpcport) #ifdef _WIN32 while ( fname[strlen(fname)-1] != '\\' ) fname[strlen(fname)-1] = 0; - strcat(fname,"komodo.conf"); + strcat(fname,"HUSH3.conf"); #else while ( fname[strlen(fname)-1] != '/' ) fname[strlen(fname)-1] = 0; #ifdef __APPLE__ - strcat(fname,"Komodo.conf"); + strcat(fname,"HUSH3.conf"); #else - strcat(fname,"komodo.conf"); + strcat(fname,"HUSH3.conf"); #endif #endif if ( (fp= fopen(fname,"rb")) != 0 ) { - if ( (kmdport= _komodo_userpass(username,password,fp)) != 0 ) - HUSH3_PORT = kmdport; + if ( (hushport= _hush_userpass(username,password,fp)) != 0 ) + HUSH3_PORT = hushport; sprintf(HUSHUSERPASS,"%s:%s",username,password); fclose(fp); //printf("HUSH.(%s) -> userpass.(%s)\n",fname,HUSHUSERPASS); - } //else printf("couldnt open.(%s)\n",fname); + } else { + printf("could not open.(%s)\n",fname); + } } -uint16_t komodo_userpass(char *userpass,char *symbol) +uint16_t hush_userpass(char *userpass,char *symbol) { FILE *fp; uint16_t port = 0; char fname[512],username[512],password[512],confname[HUSH_SMART_CHAIN_MAXLEN]; userpass[0] = 0; - if ( strcmp("SPECIAL",symbol) == 0 ) - { -#ifdef __APPLE__ - sprintf(confname,"Something.conf"); -#else - sprintf(confname,"Something.conf"); -#endif - } - else sprintf(confname,"%s.conf",symbol); + + sprintf(confname,"%s.conf",symbol); + hush_statefname(fname,symbol,confname); if ( (fp= fopen(fname,"rb")) != 0 ) { - port = _komodo_userpass(username,password,fp); + port = _hush_userpass(username,password,fp); sprintf(userpass,"%s:%s",username,password); if ( strcmp(symbol,SMART_CHAIN_SYMBOL) == 0 ) strcpy(ASSETCHAINS_USERPASS,userpass); @@ -1477,7 +1471,14 @@ uint32_t hush_smartmagic(char *symbol,uint64_t supply,uint8_t *extraptr,int32_t fprintf(stderr,"%02x",extraptr[i]); fprintf(stderr," extralen=%d crc0=%x\n",extralen,crc0); } - return(calc_crc32(crc0,buf,len)); + + //TODO: why is this needed? + bool ishush3 = strncmp(symbol, "HUSH3",5) == 0 ? true : false; + if(ishush3) { + return HUSH_MAGIC; + } else { + return(calc_crc32(crc0,buf,len)); + } } uint16_t hush_smartport(uint32_t magic,int32_t extralen) @@ -1494,13 +1495,9 @@ uint16_t hush_port(char *symbol,uint64_t supply,uint32_t *magicp,uint8_t *extrap { if(fDebug) fprintf(stderr,"%s: extralen=%d\n",__func__,extralen); - if ( strcmp("SPECIAL",symbol) == 0 ) - { - *magicp = 0xdeadbeef; - return(6969); - } + *magicp = hush_smartmagic(symbol,supply,extraptr,extralen); - if(fDebug) + //if(fDebug) fprintf(stderr,"%s: extralen=%d, supply=%lu\n",__func__,extralen, supply); return(hush_smartport(*magicp,extralen)); @@ -1516,7 +1513,6 @@ int32_t hush_whoami(char *pubkeystr,int32_t height,uint32_t timestamp) return(notaryid); } -// TODO: clean up this smoking bath-salts shite from KMD char *argv0suffix[] = { (char *)"fuckjl777d", (char *)"fuckjl777-cli", (char *)"fuckjl777d.exe", (char *)"fuckjl777-cli.exe", (char *)"btchd", (char *)"btch-cli", (char *)"btchd.exe", (char *)"btch-cli.exe" }; @@ -1739,7 +1735,7 @@ int8_t equihash_params_possible(uint64_t n, uint64_t k) * EhBasicSolve * EhOptimisedSolve * EhIsValidSolution - * Alternatively change ASSETCHAINS_N and ASSETCHAINS_K in komodo_nk.h for fast testing. + * Alternatively change ASSETCHAINS_N and ASSETCHAINS_K in hush_nk.h for fast testing. */ if ( k == 9 && (n == 200 || n == 210) ) return(0); @@ -1750,8 +1746,6 @@ int8_t equihash_params_possible(uint64_t n, uint64_t k) return(-1); } -char *dragonfmtstr = (char *)"curl --url \"http://127.0.0.1:7776\" --data \"{\\\"conf\\\":\\\"%s.conf\\\",\\\"path\\\":\\\"${HOME#\"/\"}/.komodo/%s\\\",\\\"unitval\\\":\\\"20\\\",\\\"zcash\\\":1,\\\"RELAY\\\":-1,\\\"VALIDATE\\\":0,\\\"prefetchlag\\\":-1,\\\"poll\\\":100,\\\"active\\\":1,\\\"agent\\\":\\\"dragon\\\",\\\"method\\\":\\\"addcoin\\\",\\\"startpend\\\":4,\\\"endpend\\\":4,\\\"services\\\":129,\\\"maxpeers\\\":8,\\\"newcoin\\\":\\\"%s\\\",\\\"name\\\":\\\"%s\\\",\\\"hasheaders\\\":1,\\\"useaddmultisig\\\":0,\\\"netmagic\\\":\\\"%s\\\",\\\"p2p\\\":%u,\\\"rpc\\\":%u,\\\"pubval\\\":60,\\\"p2shval\\\":85,\\\"wifval\\\":188,\\\"txfee_satoshis\\\":\\\"10000\\\",\\\"isPoS\\\":0,\\\"minoutput\\\":10000,\\\"minconfirms\\\":2,\\\"genesishash\\\":\\\"027e3758c3a65b12aa1046462b486d0a63bfa1beae327897f56c5cfb7daaae71\\\",\\\"protover\\\":170002,\\\"genesisblock\\\":\\\"0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000000000000000000000000000000000000000000000000000000000000029ab5f490f0f0f200b00000000000000000000000000000000000000000000000000000000000000fd4005000d5ba7cda5d473947263bf194285317179d2b0d307119c2e7cc4bd8ac456f0774bd52b0cd9249be9d40718b6397a4c7bbd8f2b3272fed2823cd2af4bd1632200ba4bf796727d6347b225f670f292343274cc35099466f5fb5f0cd1c105121b28213d15db2ed7bdba490b4cedc69742a57b7c25af24485e523aadbb77a0144fc76f79ef73bd8530d42b9f3b9bed1c135ad1fe152923fafe98f95f76f1615e64c4abb1137f4c31b218ba2782bc15534788dda2cc08a0ee2987c8b27ff41bd4e31cd5fb5643dfe862c9a02ca9f90c8c51a6671d681d04ad47e4b53b1518d4befafefe8cadfb912f3d03051b1efbf1dfe37b56e93a741d8dfd80d576ca250bee55fab1311fc7b3255977558cdda6f7d6f875306e43a14413facdaed2f46093e0ef1e8f8a963e1632dcbeebd8e49fd16b57d49b08f9762de89157c65233f60c8e38a1f503a48c555f8ec45dedecd574a37601323c27be597b956343107f8bd80f3a925afaf30811df83c402116bb9c1e5231c70fff899a7c82f73c902ba54da53cc459b7bf1113db65cc8f6914d3618560ea69abd13658fa7b6af92d374d6eca9529f8bd565166e4fcbf2a8dfb3c9b69539d4d2ee2e9321b85b331925df195915f2757637c2805e1d4131e1ad9ef9bc1bb1c732d8dba4738716d351ab30c996c8657bab39567ee3b29c6d054b711495c0d52e1cd5d8e55b4f0f0325b97369280755b46a02afd54be4ddd9f77c22272b8bbb17ff5118fedbae2564524e797bd28b5f74f7079d532ccc059807989f94d267f47e724b3f1ecfe00ec9e6541c961080d8891251b84b4480bc292f6a180bea089fef5bbda56e1e41390d7c0e85ba0ef530f7177413481a226465a36ef6afe1e2bca69d2078712b3912bba1a99b1fbff0d355d6ffe726d2bb6fbc103c4ac5756e5bee6e47e17424ebcbf1b63d8cb90ce2e40198b4f4198689daea254307e52a25562f4c1455340f0ffeb10f9d8e914775e37d0edca019fb1b9c6ef81255ed86bc51c5391e0591480f66e2d88c5f4fd7277697968656a9b113ab97f874fdd5f2465e5559533e01ba13ef4a8f7a21d02c30c8ded68e8c54603ab9c8084ef6d9eb4e92c75b078539e2ae786ebab6dab73a09e0aa9ac575bcefb29e930ae656e58bcb513f7e3c17e079dce4f05b5dbc18c2a872b22509740ebe6a3903e00ad1abc55076441862643f93606e3dc35e8d9f2caef3ee6be14d513b2e062b21d0061de3bd56881713a1a5c17f5ace05e1ec09da53f99442df175a49bd154aa96e4949decd52fed79ccf7ccbce32941419c314e374e4a396ac553e17b5340336a1a25c22f9e42a243ba5404450b650acfc826a6e432971ace776e15719515e1634ceb9a4a35061b668c74998d3dfb5827f6238ec015377e6f9c94f38108768cf6e5c8b132e0303fb5a200368f845ad9d46343035a6ff94031df8d8309415bb3f6cd5ede9c135fdabcc030599858d803c0f85be7661c88984d88faa3d26fb0e9aac0056a53f1b5d0baed713c853c4a2726869a0a124a8a5bbc0fc0ef80c8ae4cb53636aa02503b86a1eb9836fcc259823e2692d921d88e1ffc1e6cb2bde43939ceb3f32a611686f539f8f7c9f0bf00381f743607d40960f06d347d1cd8ac8a51969c25e37150efdf7aa4c2037a2fd0516fb444525ab157a0ed0a7412b2fa69b217fe397263153782c0f64351fbdf2678fa0dc8569912dcd8e3ccad38f34f23bbbce14c6a26ac24911b308b82c7e43062d180baeac4ba7153858365c72c63dcf5f6a5b08070b730adb017aeae925b7d0439979e2679f45ed2f25a7edcfd2fb77a8794630285ccb0a071f5cce410b46dbf9750b0354aae8b65574501cc69efb5b6a43444074fee116641bb29da56c2b4a7f456991fc92b2\\\",\\\"debug\\\":0,\\\"seedipaddr\\\":\\\"%s\\\",\\\"sapling\\\":1,\\\"notarypay\\\":%i}\""; - void hush_args(char *argv0) { std::string name,addn,hexstr,symbol; char *dirname,fname[512],arg0str[64],magicstr[9]; uint8_t magic[4],extrabuf[32756],disablebits[32],*extraptr=0; @@ -1767,15 +1761,9 @@ void hush_args(char *argv0) { HUSH_MININGTHREADS = GetArg("-genproclimit",-1); } - if ( (GetBoolArg("-exchange", false)) != 0 ) { - printf("The KMD-only feature -exchange is not supported by HUSH!\n"); - printf("jl777 uses this \"feature\" to steal from his own users!\n"); - printf("Learn more at https://duke.hush.is :)\n"); - StartShutdown(); - } DONATION_PUBKEY = GetArg("-donation", ""); NOTARY_PUBKEY = GetArg("-pubkey", ""); - HUSH_DEALERNODE = GetArg("-dealer",0); + HUSH_DEALERNODE = GetArg("-dealer",0); HUSH_TESTNODE = GetArg("-testnode",0); if ( strlen(NOTARY_PUBKEY.c_str()) == 66 ) @@ -1801,7 +1789,10 @@ void hush_args(char *argv0) } } - name = GetArg("-ac_name",""); + + name = GetArg("-ac_name","HUSH3"); + fprintf(stderr,".oO Starting %s Full Node (Extreme Privacy!) with genproc=%d notary=%d\n",name.c_str(),HUSH_MININGTHREADS, IS_HUSH_NOTARY); + if ( argv0 != 0 ) { len = (int32_t)strlen(argv0); @@ -1816,18 +1807,30 @@ void hush_args(char *argv0) } } } + + vector HUSH_nodes= {"node1.hush.is","node2.hush.is","node3.hush.is", + "node4.hush.is","node5.hush.is","node6.hush.is", + "node7.hush.is","node8.hush.is"}; + vector more_nodes = mapMultiArgs["-addnode"]; + if (more_nodes.size() > 0) { + fprintf(stderr,"%s: Adding %lu more nodes via custom -addnode arguments\n", __func__, more_nodes.size() ); + } + // Add default HUSH nodes after custom addnodes + more_nodes.insert( more_nodes.end(), HUSH_nodes.begin(), HUSH_nodes.end() ); + + mapMultiArgs["-addnode"] = more_nodes; HUSH_STOPAT = GetArg("-stopat",0); MAX_REORG_LENGTH = GetArg("-maxreorg",MAX_REORG_LENGTH); WITNESS_CACHE_SIZE = MAX_REORG_LENGTH+10; ASSETCHAINS_CC = GetArg("-ac_cc",0); HUSH_CCACTIVATE = GetArg("-ac_ccactivate",0); ASSETCHAINS_BLOCKTIME = GetArg("-ac_blocktime",60); + // We do not support ac_public=1 chains, Hush is a platform for privacy ASSETCHAINS_PUBLIC = 0; ASSETCHAINS_PRIVATE = GetArg("-ac_private",0); HUSH_SNAPSHOT_INTERVAL = GetArg("-ac_snapshot",0); Split(GetArg("-ac_nk",""), sizeof(ASSETCHAINS_NK)/sizeof(*ASSETCHAINS_NK), ASSETCHAINS_NK, 0); - fprintf(stderr,".oO Starting HUSH Full Node (Extreme Privacy!) with genproc=%d notary=%d\n",HUSH_MININGTHREADS, IS_HUSH_NOTARY); // -ac_ccactivateht=evalcode,height,evalcode,height,evalcode,height.... Split(GetArg("-ac_ccactivateht",""), sizeof(ccEnablesHeight)/sizeof(*ccEnablesHeight), ccEnablesHeight, 0); @@ -1886,7 +1889,14 @@ void hush_args(char *argv0) printf("ASSETCHAINS_ALGO, %s not supported. using equihash\n", selectedAlgo.c_str()); } + // Set our symobl from -ac_name value + strncpy(SMART_CHAIN_SYMBOL,name.c_str(),sizeof(SMART_CHAIN_SYMBOL)-1); + bool ishush3 = strncmp(SMART_CHAIN_SYMBOL, "HUSH3",5) == 0 ? true : false; + ASSETCHAINS_LASTERA = GetArg("-ac_eras", 1); + if(ishush3) { + ASSETCHAINS_LASTERA = 3; + } if ( ASSETCHAINS_LASTERA < 1 || ASSETCHAINS_LASTERA > ASSETCHAINS_MAX_ERAS ) { ASSETCHAINS_LASTERA = 1; @@ -1910,10 +1920,29 @@ void hush_args(char *argv0) Split(GetArg("-ac_halving",""), sizeof(ASSETCHAINS_HALVING)/sizeof(*ASSETCHAINS_HALVING), ASSETCHAINS_HALVING, 0); Split(GetArg("-ac_reward",""), sizeof(ASSETCHAINS_REWARD)/sizeof(*ASSETCHAINS_REWARD), ASSETCHAINS_REWARD, 0); - bool ishush3 = strncmp(SMART_CHAIN_SYMBOL, "HUSH3",5) == 0 ? true : false; + MAX_BLOCK_SIGOPS = 60000; + ASSETCHAINS_TXPOW = GetArg("-ac_txpow",0) & 3; + ASSETCHAINS_FOUNDERS = GetArg("-ac_founders",0);// & 1; + ASSETCHAINS_FOUNDERS_REWARD = GetArg("-ac_founders_reward",0); + ASSETCHAINS_SUPPLY = GetArg("-ac_supply",10); + ASSETCHAINS_COMMISSION = GetArg("-ac_perc",0); + ASSETCHAINS_OVERRIDE_PUBKEY = GetArg("-ac_pubkey",""); + ASSETCHAINS_SCRIPTPUB = GetArg("-ac_script",""); + + fprintf(stderr,"%s: Setting custom %s reward HUSH3=%d reward,halving,subsidy chain values...\n",__func__, SMART_CHAIN_SYMBOL, ishush3); if(ishush3) { - fprintf(stderr,"%s: Setting custom HUSH3 reward,halving,subsidy chain values...\n",__func__); + // Migrated from hushd script + ASSETCHAINS_CC = 2; + ASSETCHAINS_BLOCKTIME = 150; // this will change to 75 at the correct block + ASSETCHAINS_COMMISSION = 11111111; + // 6250000 - (Sprout pool at block 500,000) + ASSETCHAINS_SUPPLY = 6178674; + ASSETCHAINS_FOUNDERS = 1; + ASSETCHAINS_SAPLING = 1; + // this corresponds to FR address RHushEyeDm7XwtaTWtyCbjGQumYyV8vMjn + ASSETCHAINS_SCRIPTPUB = "76a9145eb10cf64f2bab1b457f1f25e658526155928fac88ac"; + // Over-ride HUSH3 values from CLI params. Changing our blocktime to 75s changes things ASSETCHAINS_REWARD[0] = 0; ASSETCHAINS_REWARD[1] = 1125000000; @@ -1944,11 +1973,6 @@ void hush_args(char *argv0) } } - MAX_BLOCK_SIGOPS = 60000; - ASSETCHAINS_TXPOW = GetArg("-ac_txpow",0) & 3; - ASSETCHAINS_FOUNDERS = GetArg("-ac_founders",0);// & 1; - ASSETCHAINS_FOUNDERS_REWARD = GetArg("-ac_founders_reward",0); - ASSETCHAINS_SUPPLY = GetArg("-ac_supply",10); if ( ASSETCHAINS_SUPPLY > (uint64_t)90*1000*1000000 ) { fprintf(stderr,"-ac_supply must be less than 90 billion, derpz\n"); @@ -1957,9 +1981,6 @@ void hush_args(char *argv0) if(fDebug) fprintf(stderr,"ASSETCHAINS_SUPPLY %llu\n",(long long)ASSETCHAINS_SUPPLY); - ASSETCHAINS_COMMISSION = GetArg("-ac_perc",0); - ASSETCHAINS_OVERRIDE_PUBKEY = GetArg("-ac_pubkey",""); - ASSETCHAINS_SCRIPTPUB = GetArg("-ac_script",""); ASSETCHAINS_BEAMPORT = GetArg("-ac_beam",0); ASSETCHAINS_CODAPORT = GetArg("-ac_coda",0); ASSETCHAINS_CBOPRET = GetArg("-ac_cbopret",0); @@ -1998,8 +2019,10 @@ void hush_args(char *argv0) if ( ASSETCHAINS_CC != 0 ) { uint8_t prevCCi = 0; - ASSETCHAINS_CCLIB = GetArg("-ac_cclib",""); - Split(GetArg("-ac_ccenable",""), sizeof(ccenables)/sizeof(*ccenables), ccenables, 0); + ASSETCHAINS_CCLIB = GetArg("-ac_cclib","hush3"); + + // these are the enabled CCs on HUSH3 mainnet + Split(GetArg("-ac_ccenable","228,234,235,236,241"), sizeof(ccenables)/sizeof(*ccenables), ccenables, 0); for (i=nonz=0; i<0x100; i++) { if ( ccenables[i] != prevCCi && ccenables[i] != 0 ) @@ -2080,7 +2103,7 @@ void hush_args(char *argv0) } // HUSH will always be The First Pure Sapling Coin, no Sprout JoinSplits in our history! ;) - ASSETCHAINS_SAPLING = GetArg("-ac_sapling", -1); + ASSETCHAINS_SAPLING = GetArg("-ac_sapling", 1); if (ASSETCHAINS_SAPLING == -1) { ASSETCHAINS_OVERWINTER = GetArg("-ac_overwinter", -1); @@ -2298,11 +2321,9 @@ void hush_args(char *argv0) if ( strlen(addn.c_str()) > 0 ) ASSETCHAINS_SEED = 1; - strncpy(SMART_CHAIN_SYMBOL,name.c_str(),sizeof(SMART_CHAIN_SYMBOL)-1); - MAX_MONEY = hush_max_money(); - if ( (baseid = komodo_baseid(SMART_CHAIN_SYMBOL)) >= 0 && baseid < 32 ) + if ( (baseid = hush_baseid(SMART_CHAIN_SYMBOL)) >= 0 && baseid < 32 ) { //komodo_maxallowed(baseid); if(fDebug) @@ -2320,6 +2341,10 @@ void hush_args(char *argv0) if ( GetArg("-port",0) != 0 ) { ASSETCHAINS_P2PPORT = GetArg("-port",0); + if(ishush3) { + fprintf(stderr,"set HUSH3 p2pport.%u\n",ASSETCHAINS_P2PPORT); + ASSETCHAINS_P2PPORT = 18030; + } if(fDebug) fprintf(stderr,"set p2pport.%u\n",ASSETCHAINS_P2PPORT); } else ASSETCHAINS_P2PPORT = tmpport; @@ -2336,15 +2361,11 @@ void hush_args(char *argv0) //fprintf(stderr,"Got datadir.(%s)\n",dirname); if ( SMART_CHAIN_SYMBOL[0] != 0 ) { - int32_t komodo_baseid(char *origbase); + int32_t hush_baseid(char *origbase); extern int COINBASE_MATURITY; - if ( strcmp(SMART_CHAIN_SYMBOL,"KMD") == 0 ) - { - fprintf(stderr,"Oh hellz yezzz\n"); - } - if ( (port= komodo_userpass(ASSETCHAINS_USERPASS,SMART_CHAIN_SYMBOL)) != 0 ) + if ( (port= hush_userpass(ASSETCHAINS_USERPASS,SMART_CHAIN_SYMBOL)) != 0 ) ASSETCHAINS_RPCPORT = port; - else komodo_configfile(SMART_CHAIN_SYMBOL,ASSETCHAINS_P2PPORT + 1); + else hush_configfile(SMART_CHAIN_SYMBOL,ASSETCHAINS_P2PPORT + 1); if (ASSETCHAINS_CBMATURITY != 0) COINBASE_MATURITY = ASSETCHAINS_CBMATURITY; @@ -2365,21 +2386,7 @@ void hush_args(char *argv0) for (i=0; i<4; i++) sprintf(&magicstr[i<<1],"%02x",magic[i]); magicstr[8] = 0; -#ifndef FROM_CLI - /* - sprintf(fname,"%s_7776",SMART_CHAIN_SYMBOL); - // TODO: why are we doing this again? Most users do not need this - if ( (fp= fopen(fname,"wb")) != 0 ) - { - int8_t notarypay = 0; - if ( ASSETCHAINS_NOTARY_PAY[0] != 0 ) - notarypay = 1; - fprintf(fp,dragonfmtstr,name.c_str(),name.c_str(),name.c_str(),name.c_str(),magicstr,ASSETCHAINS_P2PPORT,ASSETCHAINS_RPCPORT,"78.47.196.146",notarypay); - fclose(fp); - //printf("created (%s)\n",fname); - } else printf("error creating (%s)\n",fname); - */ -#endif + if ( ASSETCHAINS_CC < 2 ) { if ( HUSH_CCACTIVATE != 0 ) @@ -2402,24 +2409,24 @@ void hush_args(char *argv0) while ( fname[strlen(fname)-1] != '\\' ) fname[strlen(fname)-1] = 0; if ( iter == 0 ) - strcat(fname,"Komodo\\komodo.conf"); + strcat(fname,"Hush\\HUSH3\\HUSH3.conf"); else strcat(fname,"Bitcoin\\bitcoin.conf"); #else while ( fname[strlen(fname)-1] != '/' ) fname[strlen(fname)-1] = 0; #ifdef __APPLE__ if ( iter == 0 ) - strcat(fname,"Komodo/Komodo.conf"); + strcat(fname,"Hush/HUSH3/HUSH3.conf"); else strcat(fname,"Bitcoin/Bitcoin.conf"); #else if ( iter == 0 ) - strcat(fname,".komodo/komodo.conf"); + strcat(fname,".hush/HUSH3/HUSH3.conf"); else strcat(fname,".bitcoin/bitcoin.conf"); #endif #endif if ( (fp= fopen(fname,"rb")) != 0 ) { - _komodo_userpass(username,password,fp); + _hush_userpass(username,password,fp); sprintf(iter == 0 ? HUSHUSERPASS : BTCUSERPASS,"%s:%s",username,password); fclose(fp); //printf("HUSH.(%s) -> userpass.(%s)\n",fname,HUSHUSERPASS); @@ -2463,7 +2470,7 @@ struct hush_state *hush_stateptrget(char *base) int32_t baseid; if ( base == 0 || base[0] == 0 || strcmp(base,(char *)"KYCSELLOUTS") == 0 ) return(&HUSH_STATES[33]); - else if ( (baseid= komodo_baseid(base)) >= 0 ) + else if ( (baseid= hush_baseid(base)) >= 0 ) return(&HUSH_STATES[baseid+1]); else return(&HUSH_STATES[0]); } diff --git a/src/hushd b/src/hushd deleted file mode 100755 index 7aa99aeb0..000000000 --- a/src/hushd +++ /dev/null @@ -1,99 +0,0 @@ -#!/bin/bash -# Copyright (c) 2016-2021 The Hush developers -# Distributed under the GPLv3 software license, see the accompanying -# file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html - -# set working directory to the location of this script -# readlink -f does not always exist -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -cd $DIR -DIR="$( cd "$( dirname "$( readlink "${BASH_SOURCE[0]}" )" )" && pwd )" -cd $DIR - -# Chain parameters -NAME=HUSH3 - -# this corresponds to FR address RHushEyeDm7XwtaTWtyCbjGQumYyV8vMjn -SCRIPT=76a9145eb10cf64f2bab1b457f1f25e658526155928fac88ac - -# Hush was and will always be: -# The First Pure Sapling Zcash Protocol chain! -SAPLING=1 - -# We use 3 "eras" of different supply curves -ERAS=3 - -# These values are historical and over-ridden by internals! -# Do not change these values, change internals. -BLOCKTIME=150 # Hush goes to 75s blocktime at Block 340K -REWARD=0,1125000000,562500000 -HALVING=129,340000,840000 -PERC=11111111 -END=128,340000,5422111 - -# 6250000 - (Sprout pool at block 500,000) -SUPPLY=6178674 -FOUNDERS=1 -CLIENTNAME=GoldenSandtrout -NODE1=node1.hush.is -NODE2=node2.hush.is -NODE3=node3.hush.is -NODE4=node4.hush.is -NODE5=node5.hush.is -NODE6=node6.hush.is -NODE7=node7.hush.is -NODE8=node8.hush.is -CCLIB=hush3 - -# CryptoConditions/Custom Consensus params -# CCs will effectively be turned off at Block 340K -# since transparent outputs will not be allowed, except -# for mining and dpow. CCs can be used on Hush Smart -# Chains that do not define ac_private=1 -FAUCET=228 -HEIR=234 -CHANNEL=235 -ORACLE=236 -GATEWAY=241 -CCENABLE=$FAUCET,$HEIR,$CHANNEL,$ORACLE,$GATEWAY - -KMD=${KOMODOD:-./komodod} -if [ -f $KMD ]; then - HUSH="TheFuture" - # echo "Found binary: $KMD" -else - KMD=hush-komodod - if [ -f $KMD ]; then - echo "Found binary: $KMD" - else - echo "ERROR: Could not find Komodo binary!!!" - exit 1 - fi -fi - -# jl777 dishonored his village and so Duke The Elder journeys on -# with the True Extreme Privacy Cypherpunks -$KMD -ac_name=$NAME \ - -ac_sapling=$SAPLING \ - -ac_reward=$REWARD \ - -ac_halving=$HALVING \ - -ac_end=$END \ - -ac_eras=$ERAS \ - -ac_blocktime=$BLOCKTIME \ - -ac_cc=2 \ - -ac_ccenable=$CCENABLE \ - -ac_founders=$FOUNDERS \ - -ac_supply=$SUPPLY \ - -ac_perc=$PERC \ - -clientname=$CLIENTNAME \ - -asmap \ - -addnode=$NODE1 \ - -addnode=$NODE2 \ - -addnode=$NODE3 \ - -addnode=$NODE4 \ - -addnode=$NODE5 \ - -addnode=$NODE6 \ - -addnode=$NODE7 \ - -addnode=$NODE8 \ - -ac_cclib=$CCLIB \ - -ac_script=$SCRIPT "$@" diff --git a/src/hushd-testnet b/src/hushd-testnet deleted file mode 100755 index 3e36b81f7..000000000 --- a/src/hushd-testnet +++ /dev/null @@ -1,60 +0,0 @@ -#!/bin/bash -# Copyright (c) 2016-2021 The Hush developers -# Distributed under the GPLv3 software license, see the accompanying -# file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html - -# set working directory to the location of this script -DIR="$( cd "$( dirname "$( readlink -f "${BASH_SOURCE[0]}" )" )" && pwd )" -cd $DIR -DIR="$( cd "$( dirname "$( readlink "${BASH_SOURCE[0]}" )" )" && pwd )" -cd $DIR - -# TESTING VALUES, DO NOT USE EXCEPT FOR DEVELOPMENT -NAME=HUSH3T -# this corresponds to FR address RHushEyeDm7XwtaTWtyCbjGQumYyV8vMjn -SCRIPT=76a9145eb10cf64f2bab1b457f1f25e658526155928fac88ac - -# Hush was and will always be: -# The First Pure Sapling Zcash Protocol chain! -SAPLING=1 - -# Chain parameters -ERAS=3 -BLOCKTIME=150 -# 6250000 - (sprout pool at block 500,000) -SUPPLY=6178674 -FOUNDERS=1 -REWARD=0,1125000000,562500000 -PERC=11111111 -HALVING=129,340000,840000 -END=128,340000,5422111 -CLIENTNAME=GoldenSandtrout -SEEDNODE=1.2.3.4 -CCLIB=hush3 - -# CryptoConditions/Custom Consensus params -FAUCET=228 -HEIR=234 -CHANNEL=235 -ORACLE=236 -GATEWAY=241 -CCENABLE=$FAUCET,$HEIR,$CHANNEL,$ORACLE,$GATEWAY - -# jl777 dishonored his village and so Duke The Elder journeys on -# with the True Extreme Privacy Cypherpunks -KMD=${KOMODOD:-./komodod} -$KMD -ac_name=$NAME \ - -ac_sapling=$SAPLING \ - -ac_reward=$REWARD \ - -ac_halving=$HALVING \ - -ac_end=$END \ - -ac_eras=$ERAS \ - -ac_blocktime=$BLOCKTIME \ - -ac_cc=2 \ - -ac_ccenable=$CCENABLE \ - -ac_founders=$FOUNDERS \ - -ac_supply=$SUPPLY \ - -ac_perc=$PERC \ - -clientname=$CLIENTNAME \ - -ac_cclib=$CCLIB \ - -ac_script=$SCRIPT "$@" diff --git a/src/hushd.bat b/src/hushd.bat deleted file mode 100644 index b2580ffaf..000000000 --- a/src/hushd.bat +++ /dev/null @@ -1,10 +0,0 @@ -@call :GET_CURRENT_DIR -@cd %THIS_DIR% -komodod.exe -ac_name=HUSH3 -ac_sapling=1 -ac_reward=0,1125000000,562500000 -ac_halving=129,340000,840000 -ac_end=128,340000,5422111 -ac_eras=3 -ac_blocktime=150 -ac_cc=2 -ac_ccenable=228,234,235,236,241 -ac_founders=1 -ac_supply=6178674 -ac_perc=11111111 -clientname=GoldenSandtrout -addnode=64.120.113.130 -addnode=209.58.144.205 -addnode=94.130.35.94 -addnode=188.165.212.101 -ac_cclib=hush3 -ac_script=76a9145eb10cf64f2bab1b457f1f25e658526155928fac88ac -daemon %1 %2 %3 %4 %5 %6 %7 %8 %9 -@goto :EOF - -:GET_CURRENT_DIR -@pushd %~dp0 -@set THIS_DIR=%CD% -@popd -@goto :EOF diff --git a/src/init.cpp b/src/init.cpp index 2624945bf..2aaa490a0 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -36,6 +36,7 @@ #include "httprpc.h" #include "key.h" #include "notarizationdb.h" +#include "stratum.h" #ifdef ENABLE_MINING #include "key_io.h" @@ -89,12 +90,13 @@ using namespace std; #include "hush_defs.h" +static const bool DEFAULT_STRATUM_ENABLE = false; extern void ThreadSendAlert(); extern bool hush_dailysnapshot(int32_t height); extern int32_t HUSH_LOADINGBLOCKS; extern char SMART_CHAIN_SYMBOL[]; extern int32_t HUSH_SNAPSHOT_INTERVAL; -extern void komodo_init(int32_t height); +extern void hush_init(int32_t height); #ifdef ENABLE_WALLET CWallet* pwalletMain = NULL; @@ -187,6 +189,7 @@ static boost::scoped_ptr globalVerifyHandle; void Interrupt(boost::thread_group& threadGroup) { + InterruptStratumServer(); InterruptHTTPServer(); InterruptHTTPRPC(); InterruptRPC(); @@ -218,6 +221,7 @@ void Shutdown() StopHTTPRPC(); StopREST(); StopRPC(); + StopStratumServer(); StopHTTPServer(); #ifdef ENABLE_WALLET if (pwalletMain) @@ -390,7 +394,7 @@ std::string HelpMessage(HelpMessageMode mode) strUsage += HelpMessageOpt("-dbcache=", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache)); strUsage += HelpMessageOpt("-loadblock=", _("Imports blocks from external blk000??.dat file") + " " + _("on startup")); strUsage += HelpMessageOpt("-maxorphantx=", strprintf(_("Keep at most unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS)); - strUsage += HelpMessageOpt("-mempooltxinputlimit=", _("[DEPRECATED FROM OVERWINTER] Set the maximum number of transparent inputs in a transaction that the mempool will accept (default: 0 = no limit applied)")); + strUsage += HelpMessageOpt("-mempooltxinputlimit=", _("[DEPRECATED/IGNORED] Set the maximum number of transparent inputs in a transaction that the mempool will accept (default: 0 = no limit applied)")); strUsage += HelpMessageOpt("-par=", strprintf(_("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)"), -(int)boost::thread::hardware_concurrency(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS)); #ifndef _WIN32 @@ -412,7 +416,7 @@ std::string HelpMessage(HelpMessageMode mode) strUsage += HelpMessageOpt("-zindex", strprintf(_("Maintain extra statistics about shielded transactions and payments (default: %u)"), 0)); strUsage += HelpMessageGroup(_("Connection options:")); strUsage += HelpMessageOpt("-addnode=", _("Add a node to connect to and attempt to keep the connection open")); - strUsage += HelpMessageOpt("-asmap=", strprintf("Specify asn mapping used for bucketing of the peers (default: %s). Relative paths will be prefixed by the net-specific datadir location.", DEFAULT_ASMAP_FILENAME)); + strUsage += HelpMessageOpt("-asmap=", strprintf("Specify ASN mapping used for bucketing of the peers (default: %s). Relative paths will be prefixed by the net-specific datadir location.", DEFAULT_ASMAP_FILENAME)); strUsage += HelpMessageOpt("-banscore=", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), 100)); strUsage += HelpMessageOpt("-bantime=", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), 86400)); strUsage += HelpMessageOpt("-bind=", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6")); @@ -466,7 +470,11 @@ std::string HelpMessage(HelpMessageMode mode) CURRENCY_UNIT, FormatMoney(CWallet::minTxFee.GetFeePerK()))); strUsage += HelpMessageOpt("-opretmintxfee=", strprintf(_("Minimum fee (in %s/kB) to allow for OP_RETURN transactions (default: %s)"), CURRENCY_UNIT, 400000 )); strUsage += HelpMessageOpt("-paytxfee=", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"), CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK()))); + // If this is used incorrectly (-rescanheight too large), then the local wallet may attempt to spend funds which it does not have witness data about + // which will cause a "missing inputs" error when added to the mempool. Rescanning from correct height will fix this. + strUsage += HelpMessageOpt("-keepnotewitnesscache", _("Keep partial Sapling Note Witness cache. Must be used with -rescanheight to find missing cache items.")); strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions") + " " + _("on startup")); + strUsage += HelpMessageOpt("-rescanheight", _("Rescan from specified height when rescan=1 on startup")); strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup")); strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0)); strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), 1)); @@ -504,7 +512,7 @@ std::string HelpMessage(HelpMessageMode mode) strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", 0)); strUsage += HelpMessageOpt("-nuparams=hexBranchId:activationHeight", "Use given activation height for specified network upgrade (regtest-only)"); } - string debugCategories = "addrman, alert, bench, coindb, db, deletetx, estimatefee, http, libevent, lock, mempool, net, tls, partitioncheck, pow, proxy, prune, rand, reindex, rpc, selectcoins, tor, zmq, zrpc, zrpcunsafe (implies zrpc)"; // Don't translate these + string debugCategories = "addrman, alert, bench, coindb, db, deletetx, estimatefee, http, libevent, lock, mempool, net, tls, partitioncheck, pow, proxy, prune, rand, reindex, rpc, selectcoins, stratum, tor, zmq, zrpc, zrpcunsafe (implies zrpc)"; // Don't translate these strUsage += HelpMessageOpt("-debug=", strprintf(_("Output debugging information (default: %u, supplying is optional)"), 0) + ". " + _("If is not supplied or if = 1, output all debugging information.") + " " + _(" can be:") + " " + debugCategories + "."); strUsage += HelpMessageOpt("-experimentalfeatures", _("Enable use of experimental features")); @@ -564,7 +572,7 @@ std::string HelpMessage(HelpMessageMode mode) strUsage += HelpMessageOpt("-rpcbind=", _("Bind to given address to listen for JSON-RPC connections. Use [host]:port notation for IPv6. This option can be specified multiple times (default: bind to all interfaces)")); strUsage += HelpMessageOpt("-rpcuser=", _("Username for JSON-RPC connections")); strUsage += HelpMessageOpt("-rpcpassword=", _("Password for JSON-RPC connections")); - strUsage += HelpMessageOpt("-rpcport=", strprintf(_("Listen for JSON-RPC connections on (default: %u or testnet: %u)"), 7771, 17771)); + strUsage += HelpMessageOpt("-rpcport=", strprintf(_("Listen for JSON-RPC connections on (default: %u or testnet: %u)"), ASSETCHAINS_RPCPORT, 10000 + ASSETCHAINS_RPCPORT)); strUsage += HelpMessageOpt("-rpcallowip=", _("Allow JSON-RPC connections from specified source. Valid for are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times")); strUsage += HelpMessageOpt("-rpcthreads=", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS)); if (showDebug) { @@ -578,8 +586,17 @@ std::string HelpMessage(HelpMessageMode mode) strUsage += HelpMessageOpt("-metricsui", _("Set to 1 for a persistent metrics screen, 0 for sequential metrics output (default: 1 if running in a console, 0 otherwise)")); strUsage += HelpMessageOpt("-metricsrefreshtime", strprintf(_("Number of seconds between metrics refreshes (default: %u if running in a console, %u otherwise)"), 1, 600)); } + + strUsage += HelpMessageGroup(_("Stratum server options:")); + strUsage += HelpMessageOpt("-stratum", _("Enable stratum server (default: off)")); + strUsage += HelpMessageOpt("-stratumaddress=
", _("Mining address to use when special address of 'x' is sent by miner (default: none)")); + strUsage += HelpMessageOpt("-stratumbind=", _("Bind to given address to listen for Stratum work requests. Use [host]:port notation for IPv6. This option can be specified multiple times (default: bind to all interfaces)")); + strUsage += HelpMessageOpt("-stratumport=", strprintf(_("Listen for Stratum work requests on (default: %u or testnet: %u)"), BaseParams().StratumPort(), BaseParams().StratumPort())); + strUsage += HelpMessageOpt("-stratumallowip=", _("Allow Stratum work requests from specified source. Valid for are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times")); + + // "ac" stands for "affects consensus" strUsage += HelpMessageGroup(_("Hush Smart Chain options:")); - strUsage += HelpMessageOpt("-ac_algo", _("Choose PoW mining algorithm, default is Equihash")); + strUsage += HelpMessageOpt("-ac_algo", _("Choose PoW mining algorithm, default is Equihash (200,9)")); strUsage += HelpMessageOpt("-ac_blocktime", _("Block time in seconds, default is 60")); strUsage += HelpMessageOpt("-ac_cc", _("Cryptoconditions, default 0")); strUsage += HelpMessageOpt("-ac_beam", _("BEAM integration")); @@ -937,10 +954,13 @@ static void ZC_LoadParams( bool AppInitServers(boost::thread_group& threadGroup) { + fprintf(stderr,"%s: start\n",__func__); RPCServer::OnStopped(&OnRPCStopped); RPCServer::OnPreCommand(&OnRPCPreCommand); if (!InitHTTPServer()) return false; + if (GetBoolArg("-stratum", DEFAULT_STRATUM_ENABLE) && !InitStratumServer()) + return false; if (!StartRPC()) return false; if (!StartHTTPRPC()) @@ -1088,8 +1108,8 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__); } - // Read asmap file if configured - if (mapArgs.count("-asmap")) { + // Read asmap file by default for HUSH3 and all Hush Smart Chains + if (GetArg("-asmap",1)) { fs::path asmap_path = fs::path(GetArg("-asmap", "")); char cwd[1024]; @@ -1573,7 +1593,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) return InitError(strprintf("User Agent comment (%s) contains unsafe characters.", cmt)); uacomments.push_back(SanitizeString(cmt, SAFE_CHARS_UA_COMMENT)); } - strSubVersion = FormatSubVersion(GetArg("-clientname","jl777sRemorse"), CLIENT_VERSION, uacomments); + strSubVersion = FormatSubVersion(GetArg("-clientname","GoldenSandrout"), CLIENT_VERSION, uacomments); if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) { return InitError(strprintf("Total length of network version string %i exceeds maximum of %i characters. Reduce the number and/or size of uacomments.", strSubVersion.size(), MAX_SUBVERSION_LENGTH)); @@ -1836,7 +1856,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) // (we're likely using a testnet datadir, or the other way around). if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0) return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?")); - komodo_init(1); + hush_init(1); // Initialize the block index (no-op if non-empty database was already loaded) if (!InitBlockIndex()) { strLoadError = _("Error initializing block database"); @@ -2072,8 +2092,22 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) CBlockIndex *pindexRescan = chainActive.Tip(); if (clearWitnessCaches || GetBoolArg("-rescan", false)) { - pwalletMain->ClearNoteWitnessCache(); + int rescanHeight = GetArg("-rescanheight", 0); + // Must be used with -rescanheight + if( GetBoolArg("-keepnotewitnesscache", false) && rescanHeight > 0 ) { + LogPrintf("%s: keeping NoteWitnessCache with rescan height=%d\n", __func__, rescanHeight); + } else { + pwalletMain->ClearNoteWitnessCache(); + } + pindexRescan = chainActive.Genesis(); + if (rescanHeight > 0) { + if (rescanHeight > chainActive.Tip()->GetHeight()) { + pindexRescan = chainActive.Tip(); + } else { + pindexRescan = chainActive[rescanHeight]; + } + } } else { CWalletDB walletdb(strWalletFile); CBlockLocator locator; diff --git a/src/main.cpp b/src/main.cpp index 8887292d4..0771ffdb5 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -76,6 +76,7 @@ using namespace std; CCriticalSection cs_main; extern uint8_t NOTARY_PUBKEY33[33]; extern int32_t HUSH_LOADINGBLOCKS,HUSH_LONGESTCHAIN,HUSH_INSYNC,HUSH_CONNECTING,HUSH_EXTRASATOSHI; +extern CZindexStats zstats; int32_t HUSH_NEWBLOCKS; int32_t hush_block2pubkey33(uint8_t *pubkey33,CBlock *block); bool Getscriptaddress(char *destaddr,const CScript &scriptPubKey); @@ -572,6 +573,102 @@ namespace { } // anon namespace +// CZindexDB +CZindexDB::CZindexDB() +{ + pathAddr = GetDataDir() / "zindex.dat"; +} + +bool CZindexDB::Read(CZindexStats& zstats) +{ + // open input file, and associate with CAutoFile + FILE *file = fopen(pathAddr.string().c_str(), "rb"); + CAutoFile filein(file, SER_DISK, CLIENT_VERSION); + if (filein.IsNull()) + return error("%s: Failed to open file %s", __func__, pathAddr.string()); + + // use file size to size memory buffer + int fileSize = boost::filesystem::file_size(pathAddr); + int dataSize = fileSize - sizeof(uint256); + // Don't try to resize to a negative number if file is small + if (dataSize < 0) + dataSize = 0; + vector vchData; + vchData.resize(dataSize); + uint256 hashIn; + + // read data and checksum from file + try { + filein.read((char *)&vchData[0], dataSize); + filein >> hashIn; + } + catch (const std::exception& e) { + return error("%s: Deserialize or I/O error - %s", __func__, e.what()); + } + filein.fclose(); + + CDataStream ssZstats(vchData, SER_DISK, CLIENT_VERSION); + + // verify stored checksum matches input data + uint256 hashTmp = Hash(ssZstats.begin(), ssZstats.end()); + if (hashIn != hashTmp) + return error("%s: zstats Checksum mismatch, data corrupted", __func__); + + unsigned char pchMsgTmp[4]; + try { + // de-serialize file header (network specific magic number) and .. + ssZstats >> FLATDATA(pchMsgTmp); + + // ... verify the network matches ours + if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) + return error("%s: Invalid network magic number", __func__); + + // de-serialize data into one CZindexStats object + ssZstats >> zstats; + } catch (const std::exception& e) { + return error("%s: Deserialize or I/O error - %s", __func__, e.what()); + } + + return true; +} + +bool CZindexDB::Write(const CZindexStats& zstats) +{ + // Generate random temporary filename + unsigned short randv = 0; + GetRandBytes((unsigned char*)&randv, sizeof(randv)); + std::string tmpfn = strprintf("zindex.dat.%04x", randv); + + // serialize zstats, checksum data up to that point, then append checksum + CDataStream ssZstats(SER_DISK, CLIENT_VERSION); + ssZstats << FLATDATA(Params().MessageStart()); + ssZstats << zstats; + uint256 hash = Hash(ssZstats.begin(), ssZstats.end()); + ssZstats << hash; + + // open temp output file, and associate with CAutoFile + boost::filesystem::path pathTmp = GetDataDir() / tmpfn; + FILE *file = fopen(pathTmp.string().c_str(), "wb"); + CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); + if (fileout.IsNull()) + return error("%s: Failed to open file %s", __func__, pathTmp.string()); + + // Write and commit header, data + try { + fileout << ssZstats; + } catch (const std::exception& e) { + return error("%s: Serialize or I/O error - %s", __func__, e.what()); + } + FileCommit(fileout.Get()); + fileout.fclose(); + + // replace existing zindex.dat, if any, with new zindex.dat.XXXX + if (!RenameOver(pathTmp, pathAddr)) + return error("%s: Rename-into-place failed", __func__); + + return true; +} + bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) { LOCK(cs_main); CNodeState *state = State(nodeid); @@ -630,7 +727,7 @@ CBlockTreeDB *pblocktree = NULL; #define HUSH_ZCASH #include "hush.h" -UniValue komodo_snapshot(int top) +UniValue hush_snapshot(int top) { LOCK(cs_main); int64_t total = -1; @@ -648,7 +745,7 @@ UniValue komodo_snapshot(int top) return(result); } -bool komodo_snapshot2(std::map &addressAmounts) +bool hush_snapshot2(std::map &addressAmounts) { if ( fAddressIndex && pblocktree != 0 ) { @@ -690,7 +787,7 @@ bool hush_dailysnapshot(int32_t height) if ( undo_height == lastSnapShotHeight ) return true; std::map addressAmounts; - if ( !komodo_snapshot2(addressAmounts) ) + if ( !hush_snapshot2(addressAmounts) ) return false; // undo blocks in reverse order @@ -1104,7 +1201,7 @@ bool ContextualCheckCoinbaseTransaction(int32_t slowflag,const CBlock *block,CBl { if ( slowflag != 0 && ASSETCHAINS_CBOPRET != 0 && validateprices != 0 && nHeight > 0 && tx.vout.size() > 0 ) { - if ( komodo_opretvalidate(block,previndex,nHeight,tx.vout[tx.vout.size()-1].scriptPubKey) < 0 ) + if ( hush_opretvalidate(block,previndex,nHeight,tx.vout[tx.vout.size()-1].scriptPubKey) < 0 ) return(false); } return(true); @@ -1355,8 +1452,12 @@ bool CheckTransaction(uint32_t tiptime,const CTransaction& tx, CValidationState return true; } +// This is used only in RPC currently but hush_notaries()/gethushseason/getacseason is consensus int32_t hush_isnotaryvout(char *coinaddr,uint32_t tiptime) { - int32_t season = getacseason(tiptime); + bool ishush3 = strncmp(SMART_CHAIN_SYMBOL, "HUSH3",5) == 0 ? true : false; + int32_t height = chainActive.LastTip()->GetHeight(); + int32_t season = ishush3 ? gethushseason(height) : getacseason(tiptime); + fprintf(stderr,"%s: season=%d, tiptime=%d\n", __func__, season,tiptime); if ( NOTARY_ADDRESSES[season-1][0][0] == 0 ) { uint8_t pubkeys[64][33]; hush_notaries(pubkeys,0,tiptime); @@ -1456,12 +1557,12 @@ bool CheckTransactionWithoutProofVerification(uint32_t tiptime,const CTransactio //fprintf(stderr,"private chain nValue %.8f iscoinbase.%d\n",(double)txout.nValue/COIN,iscoinbase); if (iscoinbase == 0 && txout.nValue > 0) { - // TODO: if we are upgraded to Sapling, we can allow Sprout sourced funds to sit in a transparent address char destaddr[65]; Getscriptaddress(destaddr,txout.scriptPubKey); if ( hush_isnotaryvout(destaddr,tiptime) == 0 ) { invalid_private_taddr = 1; + fprintf(stderr,"%s: invalid taddr %s on private chain!\n", __func__, destaddr); //return state.DoS(100, error("CheckTransaction(): this is a private chain, no public allowed"),REJECT_INVALID, "bad-txns-acprivacy-chain"); } } @@ -1661,6 +1762,8 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa // Node operator can choose to reject tx by number of transparent inputs static_assert(std::numeric_limits::max() >= std::numeric_limits::max(), "size_t too small"); size_t limit = (size_t) GetArg("-mempooltxinputlimit", 0); + + // Limit is ignored if Overwinter is active, which is the case on HUSH3 and all HSC's if (NetworkUpgradeActive(nextBlockHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER)) { limit = 0; } @@ -2853,7 +2956,7 @@ bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex *pfClean = false; bool fClean = true; - //komodo_disconnect(pindex,block); does nothing? + CBlockUndo blockUndo; CDiskBlockPos pos = pindex->GetUndoPos(); if (pos.IsNull()) @@ -3746,7 +3849,7 @@ bool static DisconnectTip(CValidationState &state, bool fBare = false) { CValidationState stateDummy; // don't keep staking or invalid transactions - if (tx.IsCoinBase() || ((i == (block.vtx.size() - 1)) && (ASSETCHAINS_STAKED && komodo_isPoS((CBlock *)&block,pindexDelete->GetHeight(),true) != 0)) || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL)) + if (tx.IsCoinBase() || ((i == (block.vtx.size() - 1)) && (ASSETCHAINS_STAKED && hush_isPoS((CBlock *)&block,pindexDelete->GetHeight(),true) != 0)) || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL)) { mempool.remove(tx, removed, true); } @@ -3928,7 +4031,7 @@ bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock * int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1; LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001); LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001); - if ( HUSH_LONGESTCHAIN != 0 && (pindexNew->GetHeight() == HUSH_LONGESTCHAIN || pindexNew->GetHeight() == HUSH_LONGESTCHAIN+1) ) + if ( HUSH_LONGESTCHAIN != 0 && (pindexNew->GetHeight() >= HUSH_LONGESTCHAIN )) HUSH_INSYNC = (int32_t)pindexNew->GetHeight(); else HUSH_INSYNC = 0; //fprintf(stderr,"connect.%d insync.%d ASSETCHAINS_SAPLING.%d\n",(int32_t)pindexNew->GetHeight(),HUSH_INSYNC,ASSETCHAINS_SAPLING); @@ -4110,19 +4213,17 @@ static bool ActivateBestChainStep(bool fSkipdpow, CValidationState &state, CBloc if ( reorgLength > MAX_REORG_LENGTH) { auto msg = strprintf(_( - "A block chain reorganization has been detected that would roll back %d blocks! " + "A block chain reorganization has been detected that would roll back %d blocks!!! " "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety." ), reorgLength, MAX_REORG_LENGTH) + "\n\n" + _("Reorganization details") + ":\n" + - "- " + strprintf(_("Current tip: %s, height %d, work %s\nstake %s"), - pindexOldTip->phashBlock->GetHex(), pindexOldTip->GetHeight(), pindexOldTip->chainPower.chainWork.GetHex(), - pindexOldTip->chainPower.chainStake.GetHex()) + "\n" + - "- " + strprintf(_("New tip: %s, height %d, work %s\nstake %s"), - pindexMostWork->phashBlock->GetHex(), pindexMostWork->GetHeight(), pindexMostWork->chainPower.chainWork.GetHex(), - pindexMostWork->chainPower.chainStake.GetHex()) + "\n" + + "- " + strprintf(_("Current tip: %s, height %d, work %s\n"), + pindexOldTip->phashBlock->GetHex(), pindexOldTip->GetHeight(), pindexOldTip->chainPower.chainWork.GetHex()) + "\n" + + "- " + strprintf(_("New tip: %s, height %d, work %s\n"), + pindexMostWork->phashBlock->GetHex(), pindexMostWork->GetHeight(), pindexMostWork->chainPower.chainWork.GetHex()) + "\n" + "- " + strprintf(_("Fork point: %s %s, height %d"), SMART_CHAIN_SYMBOL,pindexFork->phashBlock->GetHex(), pindexFork->GetHeight()) + "\n\n" + - _("Please help, human!"); + _("Please help me, wise human!"); LogPrintf("*** %s\nif you launch with -maxreorg=%d it might be able to resolve this automatically", msg,reorgLength+10); fprintf(stderr,"*** %s\nif you launch with -maxreorg=%d it might be able to resolve this automatically", msg.c_str(),reorgLength+10); uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR); @@ -4150,7 +4251,7 @@ static bool ActivateBestChainStep(bool fSkipdpow, CValidationState &state, CBloc if ( !DisconnectTip(state) ) break; } - fprintf(stderr,"reached rewind.%d, best to do: ./komodo-cli -ac_name=%s stop\n",HUSH_REWIND,SMART_CHAIN_SYMBOL); + fprintf(stderr,"reached rewind.%d, best to do: ./hush-cli -ac_name=%s stop\n",HUSH_REWIND,SMART_CHAIN_SYMBOL); sleep(20); fprintf(stderr,"resuming normal operations\n"); HUSH_REWIND = 0; @@ -4429,13 +4530,6 @@ bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBl // pool. So we invert the sign here. saplingValue += -tx.valueBalance; - /* - for (auto js : tx.vjoinsplit) { - sproutValue += js.vpub_old; - sproutValue -= js.vpub_new; - } - */ - // Ignore following stats unless -zindex enabled if (!fZindex) continue; @@ -4560,6 +4654,39 @@ bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBl if (fZdebug) { //fprintf(stderr,"%s: setting blockchain zstats with zspends=%d, zouts=%d\n", __FUNCTION__, nShieldedSpendsInBlock, nShieldedOutputsInBlock ); } + if (pindex->pprev) { + // If chain stats are zero (such as after restart), load data from zindex.dat + if (pindex->pprev->nChainNotarizations == 0) + pindex->pprev->nChainNotarizations = zstats.nChainNotarizations; + if (pindex->pprev->nChainShieldedTx == 0) + pindex->pprev->nChainShieldedTx = zstats.nChainShieldedTx; + if (pindex->pprev->nChainShieldedOutputs == 0) + pindex->pprev->nChainShieldedOutputs = zstats.nChainShieldedOutputs; + if (pindex->pprev->nChainShieldedSpends == 0) { + pindex->pprev->nChainShieldedSpends = zstats.nChainShieldedSpends; + // TODO: if zstats.nHeight != chainActive.Height() the stats will be off + fprintf(stderr, "%s: loaded anonymity set of %li at stats height=%li vs local height=%d from disk\n", __func__, zstats.nChainShieldedOutputs - zstats.nChainShieldedSpends, zstats.nHeight, chainActive.Height() ); + } + if (pindex->pprev->nChainFullyShieldedTx == 0) + pindex->pprev->nChainFullyShieldedTx = zstats.nChainFullyShieldedTx; + if (pindex->pprev->nChainShieldingTx == 0) + pindex->pprev->nChainShieldingTx = zstats.nChainShieldingTx; + if (pindex->pprev->nChainDeshieldingTx == 0) + pindex->pprev->nChainDeshieldingTx = zstats.nChainDeshieldingTx; + if (pindex->pprev->nChainPayments == 0) { + fprintf(stderr, "%s: setting nChainPayments=%li at height %d\n", __func__, zstats.nChainPayments, chainActive.Height() ); + pindex->pprev->nChainPayments = zstats.nChainPayments; + } + if (pindex->pprev->nChainShieldedPayments == 0) + pindex->pprev->nChainShieldedPayments = zstats.nChainShieldedPayments; + if (pindex->pprev->nChainFullyShieldedPayments == 0) + pindex->pprev->nChainFullyShieldedPayments = zstats.nChainFullyShieldedPayments; + if (pindex->pprev->nChainShieldingPayments == 0) + pindex->pprev->nChainShieldingPayments = zstats.nChainShieldingPayments; + if (pindex->pprev->nChainDeshieldingPayments == 0) + pindex->pprev->nChainDeshieldingPayments = zstats.nChainDeshieldingPayments; + } + pindex->nChainNotarizations = (pindex->pprev ? pindex->pprev->nChainNotarizations : 0) + pindex->nNotarizations; pindex->nChainShieldedTx = (pindex->pprev ? pindex->pprev->nChainShieldedTx : 0) + pindex->nShieldedTx; pindex->nChainShieldedOutputs = (pindex->pprev ? pindex->pprev->nChainShieldedOutputs : 0) + pindex->nShieldedOutputs; @@ -4572,6 +4699,23 @@ bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBl pindex->nChainFullyShieldedPayments = (pindex->pprev ? pindex->pprev->nChainFullyShieldedPayments : 0) + pindex->nFullyShieldedPayments; pindex->nChainShieldingPayments = (pindex->pprev ? pindex->pprev->nChainShieldingPayments : 0) + pindex->nShieldingPayments; pindex->nChainDeshieldingPayments = (pindex->pprev ? pindex->pprev->nChainDeshieldingPayments : 0) + pindex->nDeshieldingPayments; + + // Update in-memory structure that gets serialized to zindex.dat + zstats.nHeight = pindex->GetHeight(); + zstats.nChainNotarizations = pindex->nChainNotarizations ; + zstats.nChainShieldedTx = pindex->nChainShieldedTx ; + zstats.nChainShieldedOutputs = pindex->nChainShieldedOutputs ; + zstats.nChainShieldedSpends = pindex->nChainShieldedSpends ; + zstats.nChainFullyShieldedTx = pindex->nChainFullyShieldedTx ; + zstats.nChainShieldingTx = pindex->nChainShieldingTx ; + zstats.nChainDeshieldingTx = pindex->nChainDeshieldingTx ; + zstats.nChainPayments = pindex->nChainPayments ; + zstats.nChainShieldedPayments = pindex->nChainShieldedPayments ; + zstats.nChainFullyShieldedPayments = pindex->nChainFullyShieldedPayments ; + zstats.nChainShieldingPayments = pindex->nChainShieldingPayments ; + zstats.nChainDeshieldingPayments = pindex->nChainDeshieldingPayments ; + fprintf(stderr,"%s: setting zstats with height,zouts,zspends,anonset=%li,%li,%li,%li\n", __FUNCTION__, zstats.nHeight, zstats.nChainShieldedOutputs, zstats.nChainShieldedSpends, zstats.nChainShieldedOutputs - zstats.nChainShieldedSpends); + } if (pindex->pprev) { @@ -4610,6 +4754,7 @@ bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBl } } + if (fZindex) fprintf(stderr, "ht.%d, ShieldedPayments=%d, ShieldedTx=%d, ShieldedOutputs=%d, FullyShieldedTx=%d, ntz=%d\n", pindexNew->GetHeight(), nShieldedPayments, nShieldedTx, nShieldedOutputs, nFullyShieldedTx, nNotarizations ); @@ -4855,7 +5000,7 @@ bool CheckBlockHeader(int32_t *futureblockp,int32_t height,CBlockIndex *pindex, return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); } // Check proof of work matches claimed amount - /*komodo_index2pubkey33(pubkey33,pindex,height); + /*hush_index2pubkey33(pubkey33,pindex,height); if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), blockhdr.nBits, Params().GetConsensus(),blockhdr.nTime) ) return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),REJECT_INVALID, "high-hash");*/ return true; diff --git a/src/main.h b/src/main.h index 078e48cef..676a069cd 100644 --- a/src/main.h +++ b/src/main.h @@ -950,4 +950,114 @@ std::pair>, uint64_t> DrainRecent void SetChainNotifiedSequence(uint64_t recentlyConflictedSequence); bool ChainIsFullyNotified(); +class CZindexStats +{ +//private: +public: + int64_t nHeight; + int64_t nChainTx; + int64_t nChainNotarizations; + int64_t nChainPayments; + int64_t nChainShieldedTx; + int64_t nChainShieldedOutputs; + int64_t nChainShieldedSpends; + int64_t nChainFullyShieldedTx; + int64_t nChainShieldingPayments; + int64_t nChainShieldedPayments; + int64_t nChainFullyShieldedPayments; + int64_t nChainDeshieldingTx; + int64_t nChainDeshieldingPayments; + int64_t nChainShieldingTx; + + size_t Height() const + { + return nHeight; + } + + void Clear() + { + LOCK(cs_main); + nChainTx=0; + nChainNotarizations=0; + nChainPayments=0; + nChainShieldedTx=0; + nChainShieldedOutputs=0; + nChainShieldedSpends=0; + nChainFullyShieldedTx=0; + nChainShieldingPayments=0; + nChainShieldedPayments=0; + nChainFullyShieldedPayments=0; + nChainDeshieldingTx=0; + nChainDeshieldingPayments=0; + nChainShieldingTx=0; + } + + CZindexStats() + { + Clear(); + } + + ~CZindexStats() + { + } + + template void Serialize(Stream &s) const + { + LOCK(cs_main); + + // So we can detect a new version and force a rescan + unsigned char nVersion = 1; + s << nVersion; + s << nHeight; + s << nChainTx; + s << nChainNotarizations; + s << nChainPayments; + s << nChainShieldedTx; + s << nChainShieldedOutputs; + s << nChainShieldedSpends; + s << nChainFullyShieldedTx; + s << nChainShieldingPayments; + s << nChainShieldedPayments; + s << nChainFullyShieldedPayments; + s << nChainDeshieldingTx; + s << nChainDeshieldingPayments; + s << nChainShieldingTx; + } + + template void Unserialize(Stream& s) + { + LOCK(cs_main); + + Clear(); + unsigned char nVersion; + s >> nVersion; + s >> nHeight; + s >> nChainTx; + s >> nChainNotarizations; + s >> nChainPayments; + s >> nChainShieldedTx; + s >> nChainShieldedOutputs; + s >> nChainShieldedSpends; + s >> nChainFullyShieldedTx; + s >> nChainShieldingPayments; + s >> nChainShieldedPayments; + s >> nChainFullyShieldedPayments; + s >> nChainDeshieldingTx; + s >> nChainDeshieldingPayments; + s >> nChainShieldingTx; + } +}; + +// Wrapper for zindex.dat stats +class CZindexDB +{ +private: + boost::filesystem::path pathAddr; +public: + CZindexDB(); + bool Write(const CZindexStats& zstats); + bool Read(CZindexStats& zstats); +}; + + #endif // HUSH_MAIN_H diff --git a/src/miner.cpp b/src/miner.cpp index 159682f32..2f4b7495e 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -137,15 +137,14 @@ void vcalc_sha256(char deprecated[(256 >> 3) * 2 + 1],uint8_t hash[256 >> 3],uin uint32_t Mining_start,Mining_height; int32_t My_notaryid = -1; int32_t hush_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp); -int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize); -int32_t komodo_baseid(char *origbase); +int32_t hush_baseid(char *origbase); int32_t hush_longestchain(); int64_t hush_block_unlocktime(uint32_t nHeight); uint64_t the_commission(const CBlock *block,int32_t height); int32_t hush_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33, void *ptr); int32_t decode_hex(uint8_t *bytes,int32_t n,char *hex); int32_t hush_is_notarytx(const CTransaction& tx); -uint64_t komodo_notarypay(CMutableTransaction &txNew, std::vector &NotarizationNotaries, uint32_t timestamp, int32_t height, uint8_t *script, int32_t len); +uint64_t hush_notarypay(CMutableTransaction &txNew, std::vector &NotarizationNotaries, uint32_t timestamp, int32_t height, uint8_t *script, int32_t len); int32_t hush_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp); int32_t hush_getnotarizedheight(uint32_t timestamp,int32_t height, uint8_t *script, int32_t len); CScript komodo_mineropret(int32_t nHeight); @@ -210,10 +209,6 @@ CBlockTemplate* CreateNewBlock(CPubKey _pk,const CScript& _scriptPubKeyIn, int32 // Collect memory pool transactions into the block CAmount nFees = 0; - // we will attempt to spend any cheats we see - CTransaction cheatTx; - boost::optional cheatSpend; - uint256 cbHash; boost::this_thread::interruption_point(); // exit thread before entering locks. @@ -587,7 +582,7 @@ CBlockTemplate* CreateNewBlock(CPubKey _pk,const CScript& _scriptPubKeyIn, int32 //pblock->nTime = blocktime + 1; pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); - LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x stake.%i\n", nBlockSize,blocktime,pblock->nBits,isStake); + LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits); // Create coinbase tx CMutableTransaction txNew = CreateNewContextualCMutableTransaction(consensusParams, nHeight); @@ -653,7 +648,7 @@ CBlockTemplate* CreateNewBlock(CPubKey _pk,const CScript& _scriptPubKeyIn, int32 int32_t scriptlen = (int32_t)pblock->vtx[1].vout[1].scriptPubKey.size(); if ( script[0] == OP_RETURN ) { - uint64_t totalsats = komodo_notarypay(txNew, NotarizationNotaries, pblock->nTime, nHeight, script, scriptlen); + uint64_t totalsats = hush_notarypay(txNew, NotarizationNotaries, pblock->nTime, nHeight, script, scriptlen); if ( totalsats == 0 ) { fprintf(stderr, "Could not create notary payment, trying again.\n"); @@ -861,19 +856,26 @@ CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, int32_t nHeight, scriptPubKey = CScript() << ParseHex(HexStr(pubkey)) << OP_CHECKSIG; } else { { - if (!reservekey.GetReservedKey(pubkey)) - { - return NULL; - } - scriptPubKey.resize(35); - ptr = (uint8_t *)pubkey.begin(); - scriptPubKey[0] = 33; - for (i=0; i<33; i++) { - scriptPubKey[i+1] = ptr[i]; - } - scriptPubKey[34] = OP_CHECKSIG; - } - } + // Support mining with -disablewallet and minetolocalwallet=0 + if (!GetBoolArg("-disablewallet", false)) { + // wallet enabled + if (!reservekey.GetReservedKey(pubkey)) + return NULL; + scriptPubKey.clear(); + scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG; + } else { + // wallet disabled + CTxDestination dest = DecodeDestination(GetArg("-mineraddress", "")); + if (IsValidDestination(dest)) { + // CKeyID keyID = boost::get(dest); + // scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; + scriptPubKey = GetScriptForDestination(dest); + } else { + return NULL; + } + } + } + } return CreateNewBlock(pubkey, scriptPubKey, gpucount, isStake); } @@ -895,29 +897,6 @@ void komodo_sendmessage(int32_t minpeers,int32_t maxpeers,const char *message,st } } -void komodo_broadcast(CBlock *pblock,int32_t limit) -{ - if (IsInitialBlockDownload()) - return; - int32_t n = 1; - //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL)); - { - LOCK(cs_vNodes); - BOOST_FOREACH(CNode* pnode, vNodes) - { - if ( pnode->hSocket == INVALID_SOCKET ) - continue; - if ( (rand() % n) == 0 ) - { - pnode->PushMessage("block", *pblock); - if ( n++ > limit ) - break; - } - } - } - //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL)); -} - static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) #else static bool ProcessBlockFound(CBlock* pblock) @@ -972,12 +951,11 @@ static bool ProcessBlockFound(CBlock* pblock) return error("HushMiner: ProcessNewBlock, block not accepted"); TrackMinedBlock(pblock->GetHash()); - //komodo_broadcast(pblock,16); return true; } -int32_t komodo_baseid(char *origbase); -int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height); +int32_t hush_baseid(char *origbase); +int32_t hush_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height); arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc); int32_t FOUND_BLOCK,HUSH_MAYBEMINED; extern int32_t HUSH_LASTMINED,HUSH_INSYNC; @@ -1076,7 +1054,7 @@ void static BitcoinMiner() while ( (ASSETCHAIN_INIT == 0 || HUSH_INITDONE == 0) ) { sleep(1); - if ( komodo_baseid(SMART_CHAIN_SYMBOL) < 0 ) + if ( hush_baseid(SMART_CHAIN_SYMBOL) < 0 ) break; } if ( SMART_CHAIN_SYMBOL[0] == 0 ) @@ -1205,12 +1183,12 @@ void static BitcoinMiner() if ( SMART_CHAIN_SYMBOL[0] == 0 && notaryid >= 0 ) { j = 65; - if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 || Mining_height > 1000000 ) + if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % HUSH_DPOW_GAP) > 64 || (Mining_height % HUSH_DPOW_GAP) == 0 || Mining_height > 1000000 ) { int32_t dispflag = 0; if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) || notaryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 ) dispflag = 1; - komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->GetHeight()); + hush_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->GetHeight()); if ( nonzpkeys > 0 ) { for (i=0; i<33; i++) diff --git a/src/musigtest.py b/src/musigtest.py index a452b7e97..9e99da51d 100755 --- a/src/musigtest.py +++ b/src/musigtest.py @@ -16,15 +16,14 @@ def def_credentials(chain): rpcport = ''; operating_system = platform.system() if operating_system == 'Darwin': - ac_dir = os.environ['HOME'] + '/Library/Application Support/Komodo' + ac_dir = os.environ['HOME'] + '/Library/Application Support/Hush' elif operating_system == 'Linux': - ac_dir = os.environ['HOME'] + '/.komodo' + ac_dir = os.environ['HOME'] + '/.hush' elif operating_system == 'Windows': - ac_dir = '%s/komodo/' % os.environ['APPDATA'] - if chain == 'KMD': - coin_config_file = str(ac_dir + '/komodo.conf') - else: - coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf') + ac_dir = '%s/hush/' % os.environ['APPDATA'] + + coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf') + with open(coin_config_file, 'r') as f: for line in f: l = line.rstrip() @@ -35,8 +34,8 @@ def def_credentials(chain): elif re.search('rpcport', l): rpcport = l.replace('rpcport=', '') if len(rpcport) == 0: - if chain == 'KMD': - rpcport = 7771 + if chain == 'HUSH3': + rpcport = 18031 else: print("rpcport not in conf file, exiting") print("check " + coin_config_file) diff --git a/src/net.cpp b/src/net.cpp index 808df788c..ae61ea51b 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -48,6 +48,11 @@ using namespace hush; // Satoshi originally used 10 seconds(!), did they know something Peter Wuille didn't? #define DUMP_ADDRESSES_INTERVAL 300 +// This is every 2 blocks, on avg, on HUSH3 +#define DUMP_ZINDEX_INTERVAL 150 + +#define CHECK_PLZ_STOP_INTERVAL 120 + #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL) #define MSG_NOSIGNAL 0 #endif @@ -89,10 +94,10 @@ namespace { }; } + // Global state variables extern uint16_t ASSETCHAINS_P2PPORT; extern char SMART_CHAIN_SYMBOL[65]; - bool fDiscover = true; bool fListen = true; uint64_t nLocalServices = NODE_NETWORK | NODE_NSPV; @@ -103,11 +108,14 @@ static CNode* pnodeLocalHost = NULL; uint64_t nLocalHostNonce = 0; static std::vector vhListenSocket; CAddrMan addrman; +CZindexStats zstats; int nMaxConnections = DEFAULT_MAX_PEER_CONNECTIONS; bool fAddressesInitialized = false; std::string strSubVersion; TLSManager tlsmanager = TLSManager(); +extern void StartShutdown(); + vector vNodes; CCriticalSection cs_vNodes; map mapRelay; @@ -1400,6 +1408,28 @@ void DumpAddresses() LogPrint("net", "Flushed %d addresses to peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart); } +void DumpZindexStats() +{ + int64_t nStart = GetTimeMillis(); + + CZindexDB zdb; + zdb.Write(zstats); + + LogPrintf("Flushed stats at height %li to zindex.dat %dms\n", zstats.Height(), GetTimeMillis() - nStart); +} + +void CheckIfWeShouldStop() +{ + // If the RPC interface is "stuck", such as filling up with deadlocks + // and cannot process any more requests, the only option was to kill the full node. + // This is a disk-based method where a node can realize it should stop, and which + // can help avoid extremely long rescans + if(boost::filesystem::exists(GetDataDir() / "plz_stop")) { + LogPrintf("%s: Found plz_stop file, shutting down...\n", __func__); + StartShutdown(); + } +} + void static ProcessOneShot() { string strDest; @@ -1909,8 +1939,40 @@ void static Discover(boost::thread_group& threadGroup) #endif } +//extern CWallet pwalletMain; void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler) { + + CheckIfWeShouldStop(); + + if (fZindex) { + uiInterface.InitMessage(_("Loading zindex stats...")); + int64_t nStart = GetTimeMillis(); + { + CZindexDB zdb; + if (!zdb.Read(zstats)) { + // The first time nodes use zindex.dat code, no file will be found + // TODO: rescan if invalid only + LogPrintf("Invalid or missing zindex.dat! Generating new...\n"); + + //bool update = true; + //pwalletMain->ScanForWalletTransactions(chainActive.Genesis(),update); + + // We assume this is the first startup with zindex.dat code, and serialize current data to disk. + DumpZindexStats(); + + // Now read-in the stats we just wrote to disk to memory + if(!zdb.Read(zstats)) { + LogPrintf("Invalid or missing zindex.dat! Stats may be corrupt\n"); + } else { + LogPrintf("Loaded stats at height %li from zindex.dat %dms\n", zstats.Height(), GetTimeMillis() - nStart); + } + } else { + LogPrintf("Loaded stats at height %li from zindex.dat %dms\n", zstats.Height(), GetTimeMillis() - nStart); + } + } + } + uiInterface.InitMessage(_("Loading addresses...")); // Load addresses for peers.dat int64_t nStart = GetTimeMillis(); @@ -1919,8 +1981,7 @@ void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler) if (!adb.Read(addrman)) LogPrintf("Invalid or missing peers.dat! This can happen when upgrading. Whatevz, recreating\n"); } - LogPrintf("Loaded %i addresses from peers.dat %dms\n", - addrman.size(), GetTimeMillis() - nStart); + LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart); fAddressesInitialized = true; if (semOutbound == NULL) { @@ -1968,6 +2029,13 @@ void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler) // Dump network addresses scheduler.scheduleEvery(&DumpAddresses, DUMP_ADDRESSES_INTERVAL); + + // Dump zindex stats if -zindex is enabled + if (fZindex) { + scheduler.scheduleEvery(&DumpZindexStats, DUMP_ZINDEX_INTERVAL); + } + + scheduler.scheduleEvery(&CheckIfWeShouldStop, CHECK_PLZ_STOP_INTERVAL); } bool StopNode() @@ -1977,6 +2045,9 @@ bool StopNode() for (int i=0; i<(MAX_OUTBOUND_CONNECTIONS + MAX_FEELER_CONNECTIONS); i++) semOutbound->post(); + // persist current zindex stats to disk before we exit + DumpZindexStats(); + if (HUSH_NSPV_FULLNODE && fAddressesInitialized) { DumpAddresses(); @@ -2049,7 +2120,7 @@ void RelayTransaction(const CTransaction& tx, const CDataStream& ss) random_shuffle( vRelayNodes.begin(), vRelayNodes.end(), GetRandInt ); vRelayNodes.resize(newSize); - fprintf(stderr, "%s: Relaying to %lu peers\n", __func__, newSize); + fprintf(stderr, "%s: Relaying to %lu of %lu peers\n", __func__, newSize, vNodes.size() ); // Only relay to randomly chosen 50% of peers BOOST_FOREACH(CNode* pnode, vRelayNodes) @@ -2212,7 +2283,7 @@ bool CAddrDB::Read(CAddrMan& addr) // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) - return error("%s: Invalid network magic number", __func__); + return error("%s: Invalid network magic number in %s", __func__, pathAddr.string()); // de-serialize address data into one CAddrMan object ssPeers >> addr; diff --git a/src/net.h b/src/net.h index bdc56de1b..d55d500e1 100644 --- a/src/net.h +++ b/src/net.h @@ -223,6 +223,7 @@ public: int nStartingHeight; uint64_t nSendBytes; uint64_t nRecvBytes; + bool fRelayTxes; bool fAllowlisted; // If true this node bypasses DoS ban limits bool fFeeler; // If true this node is being used as a short lived feeler. double dPingTime; diff --git a/src/pow.cpp b/src/pow.cpp index 703deb765..143ee71c0 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -672,14 +672,14 @@ bool CheckEquihashSolution(const CBlockHeader *pblock, const CChainParams& param int32_t hush_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp); int32_t hush_currentheight(); -void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height); +void hush_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height); bool hush_checkopret(CBlock *pblock, CScript &merkleroot); -CScript komodo_makeopret(CBlock *pblock, bool fNew); +CScript hush_makeopret(CBlock *pblock, bool fNew); extern int32_t HUSH_CHOSEN_ONE; extern char SMART_CHAIN_SYMBOL[HUSH_SMART_CHAIN_MAXLEN]; -#define KOMODO_ELECTION_GAP 2000 +#define HUSH_DPOW_GAP 2000 -int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t blocktimes[66],int32_t *nonzpkeysp,int32_t height); +int32_t hush_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t blocktimes[66],int32_t *nonzpkeysp,int32_t height); int32_t HUSH_LOADINGBLOCKS = 1; extern std::string NOTARY_PUBKEY; @@ -749,7 +749,7 @@ bool CheckProofOfWork(const CBlockHeader &blkHeader, uint8_t *pubkey33, int32_t CChainPower GetBlockProof(const CBlockIndex& block) { - arith_uint256 bnWorkTarget, bnStakeTarget = arith_uint256(0); + arith_uint256 bnWorkTarget; bool fNegative; bool fOverflow; @@ -758,7 +758,7 @@ CChainPower GetBlockProof(const CBlockIndex& block) if (fNegative || fOverflow || bnWorkTarget == 0) return CChainPower(0); - return CChainPower(0, bnStakeTarget, (~bnWorkTarget / (bnWorkTarget + 1)) + 1); + return CChainPower(0, (~bnWorkTarget / (bnWorkTarget + 1)) + 1); } int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params) diff --git a/src/purge b/src/purge index 1480c40a8..df6624596 100755 --- a/src/purge +++ b/src/purge @@ -4,7 +4,7 @@ echo "Purging $1" -rm -rf ~/.komodo/$1/chainstate -rm -rf ~/.komodo/$1/database -rm -rf ~/.komodo/$1/blocks -rm -rf ~/.komodo/$1/komodostate +rm -rf ~/.hush/$1/chainstate +rm -rf ~/.hush/$1/database +rm -rf ~/.hush/$1/blocks +rm -rf ~/.hush/$1/hushstate diff --git a/src/revs b/src/revs deleted file mode 100755 index 5c8782ae5..000000000 --- a/src/revs +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/bash -./komodo-cli -ac_name=REVS $1 $2 $3 $4 diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index 7c38ef1eb..bf38cc5e2 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -893,7 +893,7 @@ UniValue kvsearch(const UniValue& params, bool fHelp, const CPubKey& mypk) if ( keylen < sizeof(key) ) { memcpy(key,params[0].get_str().c_str(),keylen); - if ( (valuesize= komodo_kvsearch(&refpubkey,chainActive.LastTip()->GetHeight(),&flags,&height,value,key,keylen)) >= 0 ) + if ( (valuesize= hush_kvsearch(&refpubkey,chainActive.LastTip()->GetHeight(),&flags,&height,value,key,keylen)) >= 0 ) { std::string val; char *valuestr; val.resize(valuesize); @@ -928,7 +928,7 @@ UniValue minerids(const UniValue& params, bool fHelp, const CPubKey& mypk) if ( pblockindex != 0 ) timestamp = pblockindex->GetBlockTime(); } - if ( (n= komodo_minerids(minerids,height,(int32_t)(sizeof(minerids)/sizeof(*minerids)))) > 0 ) + if ( (n= hush_minerids(minerids,height,(int32_t)(sizeof(minerids)/sizeof(*minerids)))) > 0 ) { memset(tally,0,sizeof(tally)); numnotaries = hush_notaries(pubkeys,height,timestamp); @@ -1567,7 +1567,6 @@ inline CBlockIndex* LookupBlockIndex(const uint256& hash) UniValue getchaintxstats(const UniValue& params, bool fHelp, const CPubKey& mypk) { - THROW_IF_SYNCING(HUSH_INSYNC); if (fHelp || params.size() > 2) throw runtime_error( @@ -1631,6 +1630,8 @@ UniValue getchaintxstats(const UniValue& params, bool fHelp, const CPubKey& mypk + HelpExampleRpc("getchaintxstats", "2016") ); + THROW_IF_SYNCING(HUSH_INSYNC); + const CBlockIndex* pindex; int blockcount = 30 * 24 * 60 * 60 / Params().GetConsensus().nPowTargetSpacing; // By default: 1 month @@ -1660,10 +1661,12 @@ UniValue getchaintxstats(const UniValue& params, bool fHelp, const CPubKey& mypk throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid block count: should be between 0 and the block's height - 1"); } } + LogPrintf("%s: blockcount = %d\n", __func__, blockcount); const CBlockIndex* pindexPast = pindex->GetAncestor(pindex->GetHeight() - blockcount); int nTimeDiff = pindex->GetMedianTimePast() - pindexPast->GetMedianTimePast(); int nTxDiff = pindex->nChainTx - pindexPast->nChainTx; + LogPrintf("%s: pindexPast.height = %d, pindex.height = %d\n", __func__, pindexPast->GetHeight(), pindex->GetHeight() ); UniValue ret(UniValue::VOBJ); ret.pushKV("time", (int64_t)pindex->nTime); @@ -1695,6 +1698,7 @@ UniValue getchaintxstats(const UniValue& params, bool fHelp, const CPubKey& mypk ret.pushKV("window_tx_count", nTxDiff); ret.pushKV("window_interval", nTimeDiff); int64_t nPaymentsDiff = pindex->nChainPayments - pindexPast->nChainPayments; + LogPrintf("%s: pindexPast.nChainPayments = %d, pindex.nChainPayments = %d\n", __func__, pindexPast->nChainPayments, pindex->nChainPayments ); int64_t nShieldedTxDiff = pindex->nChainShieldedTx - pindexPast->nChainShieldedTx; int64_t nShieldingTxDiff = pindex->nChainShieldingTx - pindexPast->nChainShieldingTx; int64_t nDeshieldingTxDiff = pindex->nChainDeshieldingTx - pindexPast->nChainDeshieldingTx; diff --git a/src/rpc/crosschain.cpp b/src/rpc/crosschain.cpp index 0ac6fd46b..45140138b 100644 --- a/src/rpc/crosschain.cpp +++ b/src/rpc/crosschain.cpp @@ -59,7 +59,7 @@ bool EnsureWalletIsAvailable(bool avoidException); int32_t hush_MoM(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip); int32_t hush_MoMoMdata(char *hexstr,int32_t hexsize,struct hush_ccdataMoMoM *mdata,char *symbol,int32_t kmdheight,int32_t notarized_height); struct hush_ccdata_entry *komodo_allMoMs(int32_t *nump,uint256 *MoMoMp,int32_t kmdstarti,int32_t kmdendi); -uint256 komodo_calcMoM(int32_t height,int32_t MoMdepth); +uint256 hush_calcMoM(int32_t height,int32_t MoMdepth); int32_t hush_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp); extern std::string ASSETCHAINS_SELFIMPORT; @@ -169,7 +169,7 @@ UniValue calc_MoM(const UniValue& params, bool fHelp, const CPubKey& mypk) if ( height <= 0 || MoMdepth <= 0 || MoMdepth >= height ) throw runtime_error("calc_MoM illegal height or MoMdepth\n"); //fprintf(stderr,"height_MoM height.%d\n",height); - MoM = komodo_calcMoM(height,MoMdepth); + MoM = hush_calcMoM(height,MoMdepth); ret.push_back(Pair("coin",(char *)(SMART_CHAIN_SYMBOL[0] == 0 ? "HUSH" : SMART_CHAIN_SYMBOL))); ret.push_back(Pair("height",height)); ret.push_back(Pair("MoMdepth",MoMdepth)); @@ -670,7 +670,7 @@ UniValue migrate_createnotaryapprovaltransaction(const UniValue& params, bool fH if (fHelp || params.size() != 2) throw runtime_error("migrate_createnotaryapprovaltransaction burntxid txoutproof\n\n" "Creates a tx for destination chain with burn tx proof\n" - "txoutproof should be retrieved by komodo-cli migrate_checkburntransactionsource call on the source chain\n" ); + "txoutproof should be retrieved by hush-cli migrate_checkburntransactionsource call on the source chain\n" ); if (SMART_CHAIN_SYMBOL[0] == 0) throw runtime_error("Must be called on asset chain"); diff --git a/src/rpc/misc.cpp b/src/rpc/misc.cpp index d4f797b0e..2933d7393 100644 --- a/src/rpc/misc.cpp +++ b/src/rpc/misc.cpp @@ -59,7 +59,7 @@ using namespace std; int32_t hush_longestchain(); int32_t hush_notarized_height(int32_t *prevMoMheightp,uint256 *hashp,uint256 *txidp); -bool komodo_txnotarizedconfirmed(uint256 txid); +bool hush_txnotarizedconfirmed(uint256 txid); uint32_t hush_chainactive_timestamp(); int32_t hush_whoami(char *pubkeystr,int32_t height,uint32_t timestamp); extern int32_t HUSH_LASTMINED,HUSH_LONGESTCHAIN,IS_HUSH_NOTARY,HUSH_INSYNC; @@ -67,7 +67,7 @@ extern char SMART_CHAIN_SYMBOL[HUSH_SMART_CHAIN_MAXLEN]; uint32_t hush_segid32(char *coinaddr); int64_t hush_coinsupply(int64_t *zfundsp,int64_t *sproutfundsp,int32_t height); int32_t notarizedtxid_height(char *dest,char *txidstr,int32_t *hushnotarized_heightp); -uint64_t komodo_notarypayamount(int32_t nHeight, int64_t notarycount); +uint64_t hush_notarypayamount(int32_t nHeight, int64_t notarycount); int32_t hush_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp); extern uint16_t ASSETCHAINS_P2PPORT,ASSETCHAINS_RPCPORT; @@ -178,6 +178,28 @@ UniValue geterablockheights(const UniValue& params, bool fHelp, const CPubKey& m return(ret); } +extern int getWorkQueueDepth(); +extern int getWorkQueueMaxDepth(); +extern int getWorkQueueNumThreads(); + +UniValue rpcinfo(const UniValue& params, bool fHelp, const CPubKey& mypk) +{ + UniValue result(UniValue::VOBJ); + if (fHelp || params.size() != 0) { + throw runtime_error( + "rpcinfo\n" + "Returns an object containing various RPC state info.\n" + ); + } + LOCK(cs_main); + int depth = getWorkQueueDepth(); + + result.push_back(Pair("work_queue_depth", depth)); + result.push_back(Pair("work_queue_max_depth", getWorkQueueMaxDepth() )); + result.push_back(Pair("work_queue_num_threads", getWorkQueueNumThreads() )); + return result; +} + UniValue getinfo(const UniValue& params, bool fHelp, const CPubKey& mypk) { uint256 notarized_hash,notarized_desttxid; int32_t prevMoMheight,notarized_height,longestchain,hushnotarized_height,txid_height; @@ -230,7 +252,7 @@ UniValue getinfo(const UniValue& params, bool fHelp, const CPubKey& mypk) obj.push_back(Pair("notarizedtxid", notarized_desttxid.ToString())); if ( HUSH_NSPV_FULLNODE ) { - txid_height = notarizedtxid_height(SMART_CHAIN_SYMBOL[0] != 0 ? (char *)"HUSH" : (char *)"BTC",(char *)notarized_desttxid.ToString().c_str(),&hushnotarized_height); + txid_height = notarizedtxid_height( (char *)"HUSH3" ,(char *)notarized_desttxid.ToString().c_str(),&hushnotarized_height); if ( txid_height > 0 ) obj.push_back(Pair("notarizedtxid_height", txid_height)); else obj.push_back(Pair("notarizedtxid_height", "mempool")); @@ -1189,7 +1211,7 @@ UniValue getnotarypayinfo(const UniValue& params, bool fHelp, const CPubKey& myp balance = checkburnaddress(received, TotalNotaryPay, height, "REDVp3ox1pbcWYCzySadfHhk8UU3HM4k5x"); notarycount = hush_notaries(notarypubkeys, height, chainActive[height]->GetBlockTime()); - NotaryPay = komodo_notarypayamount(height, notarycount)*notarycount; + NotaryPay = hush_notarypayamount(height, notarycount)*notarycount; bool spent = (received != balance); if ( !spent ) { @@ -1265,7 +1287,7 @@ UniValue getaddressbalance(const UniValue& params, bool fHelp, const CPubKey& my } -UniValue komodo_snapshot(int top); +UniValue hush_snapshot(int top); UniValue getsnapshot(const UniValue& params, bool fHelp, const CPubKey& mypk) { @@ -1315,7 +1337,7 @@ UniValue getsnapshot(const UniValue& params, bool fHelp, const CPubKey& mypk) + HelpExampleRpc("getsnapshot", "1000") ); } - result = komodo_snapshot(top); + result = hush_snapshot(top); if ( result.size() > 0 ) { result.push_back(Pair("end_time", (int) time(NULL))); } else { @@ -1463,7 +1485,7 @@ UniValue txnotarizedconfirmed(const UniValue& params, bool fHelp, const CPubKey& if (fHelp || params.size() < 1 || params.size() > 1) { string msg = "txnotarizedconfirmed txid\n" - "\nReturns true if transaction is notarized on chain that has dPoW or if confirmation number is greater than 60 on chain taht does not have dPoW.\n" + "\nReturns true if transaction is notarized on chain that has dPoW or if confirmation number is greater than 60 on chain that does not have dPoW.\n" "\nArguments:\n" "1. txid (string, required) Transaction id.\n" @@ -1476,7 +1498,7 @@ UniValue txnotarizedconfirmed(const UniValue& params, bool fHelp, const CPubKey& throw runtime_error(msg); } txid = uint256S((char *)params[0].get_str().c_str()); - notarizedconfirmed=komodo_txnotarizedconfirmed(txid); + notarizedconfirmed=hush_txnotarizedconfirmed(txid); UniValue result(UniValue::VOBJ); result.push_back(Pair("result", notarizedconfirmed)); return result; @@ -1556,6 +1578,7 @@ static const CRPCCommand commands[] = { "util", "z_validateaddress", &z_validateaddress, true }, /* uses wallet if enabled */ { "util", "createmultisig", &createmultisig, true }, { "util", "verifymessage", &verifymessage, true }, + { "util", "rpcinfo", &rpcinfo, true }, /* Not shown in help */ { "hidden", "setmocktime", &setmocktime, true }, diff --git a/src/rpc/net.cpp b/src/rpc/net.cpp index 46c3cf24d..4533b0196 100644 --- a/src/rpc/net.cpp +++ b/src/rpc/net.cpp @@ -95,6 +95,7 @@ UniValue getpeerinfo(const UniValue& params, bool fHelp, const CPubKey& mypk) " \"lastrecv\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last receive\n" " \"bytessent\": n, (numeric) The total bytes sent\n" " \"bytesrecv\": n, (numeric) The total bytes received\n" + " \"relaytxes\":true|false, (boolean) Whether peer has asked us to relay transactions to it\n" " \"conntime\": ttt, (numeric) The connection time in seconds since epoch (Jan 1 1970 GMT)\n" " \"timeoffset\": ttt, (numeric) The time offset in seconds (deprecated, always 0)\n" " \"pingtime\": n, (numeric) ping time\n" @@ -146,6 +147,8 @@ UniValue getpeerinfo(const UniValue& params, bool fHelp, const CPubKey& mypk) obj.push_back(Pair("lastrecv", stats.nLastRecv)); obj.push_back(Pair("bytessent", stats.nSendBytes)); obj.push_back(Pair("bytesrecv", stats.nRecvBytes)); + obj.push_back(Pair("relaytxes", stats.fRelayTxes)); + obj.push_back(Pair("conntime", stats.nTimeConnected)); obj.push_back(Pair("timeoffset", 0)); obj.push_back(Pair("pingtime", stats.dPingTime)); @@ -177,15 +180,15 @@ UniValue getpeerinfo(const UniValue& params, bool fHelp, const CPubKey& mypk) } int32_t HUSH_LONGESTCHAIN; +static int32_t hush_longest_depth = 0; int32_t hush_longestchain() { - static int32_t depth; int32_t ht,n=0,num=0,maxheight=0,height = 0; - if ( depth < 0 ) - depth = 0; - if ( depth == 0 ) + if ( hush_longest_depth < 0 ) + hush_longest_depth = 0; + if ( hush_longest_depth == 0 ) { - depth++; + hush_longest_depth++; vector vstats; { //LOCK(cs_main); @@ -212,7 +215,7 @@ int32_t hush_longestchain() if ( ht > height ) height = ht; } - depth--; + hush_longest_depth--; if ( num > (n >> 1) ) { if ( 0 && height != HUSH_LONGESTCHAIN ) diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 1914aa8df..69e614f3b 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -646,12 +646,12 @@ UniValue createrawtransaction(const UniValue& params, bool fHelp, const CPubKey& " ]\n" "2. \"outputs\" (object, required) a json object with outputs\n" " {\n" - " \"address\": x.xxx, (numeric or string, required) The key is the komodo address or script (in hex), the numeric value (can be string) is the " + CURRENCY_UNIT + " amount\n" + " \"address\": x.xxx, (numeric or string, required) The key is the HUSH address or script (in hex), the numeric value (can be string) is the " + CURRENCY_UNIT + " amount\n" " \"data\": \"hex\" (string, required) The key is \"data\", the value is hex encoded data\n" " ,...\n" " }\n" "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n" - "4. expiryheight (numeric, optional, default=" + strprintf("%d", DEFAULT_TX_EXPIRY_DELTA) + ") Expiry height of transaction (if Overwinter is active)\n" + "4. expiryheight (numeric, optional, default=" + strprintf("%d", DEFAULT_TX_EXPIRY_DELTA) + ") Expiry height of transaction\n" "\nResult:\n" "\"transaction\" (string) hex string of the transaction\n" @@ -821,7 +821,7 @@ UniValue decoderawtransaction(const UniValue& params, bool fHelp, const CPubKey& " \"reqSigs\" : n, (numeric) The required sigs\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " \"addresses\" : [ (json array of string)\n" - " \"RTZMZHDFSTFQst8XmX2dR4DaH87cEUs3gC\" (string) komodo address\n" + " \"RTZMZHDFSTFQst8XmX2dR4DaH87cEUs3gC\" (string) HUSH address\n" " ,...\n" " ]\n" " }\n" diff --git a/src/rpc/register.h b/src/rpc/register.h index 2493e447b..7c545da48 100644 --- a/src/rpc/register.h +++ b/src/rpc/register.h @@ -1,7 +1,7 @@ +// Copyright (c) 2016-2021 The Hush developers // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the GPLv3 software license, see the accompanying // file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html - /****************************************************************************** * Copyright © 2014-2019 The SuperNET Developers. * * * @@ -38,6 +38,9 @@ void RegisterRawTransactionRPCCommands(CRPCTable &tableRPC); /** Register test transaction RPC commands */ void RegisterTesttransactionsRPCCommands(CRPCTable &tableRPC); +/** Register stratum RPC commands */ +void RegisterStratumRPCCommands(CRPCTable &tableRPC); + static inline void RegisterAllCoreRPCCommands(CRPCTable &tableRPC) { @@ -49,6 +52,7 @@ static inline void RegisterAllCoreRPCCommands(CRPCTable &tableRPC) #ifdef TESTMODE RegisterTesttransactionsRPCCommands(tableRPC); #endif + RegisterStratumRPCCommands(tableRPC); } #endif diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp index 5ae2c88e1..8139c93ce 100644 --- a/src/rpc/server.cpp +++ b/src/rpc/server.cpp @@ -825,9 +825,15 @@ UniValue CRPCTable::execute(const std::string &strMethod, const UniValue ¶ms { LOCK(cs_rpcWarmup); if (fRPCInWarmup) { - // hush-cli stop is the only valid RPC command during warmup - // We don't know if we have valid blocks or wallet yet, nothing else is safe - if (pcmd->name != "stop") { + // Most RPCs are unsafe to run during warmup, but stop+help are fine + // Others may not have data loaded yet, such as wallet details, but + // those RPCs are written defensively to deal with that. Allowing these + // few RPCs means we can see our addresses and make private key backups + // while a very long wallet rescan is happening + if (pcmd->name != "stop" && pcmd->name != "help" && pcmd->name != "z_listaddresses" && pcmd->name != "z_exportkey" && + pcmd->name != "getaddressesbyaccount" && pcmd->name != "listaddresses" && pcmd->name != "z_exportwallet" && + pcmd->name != "notaries" && pcmd->name != "signmessage" && pcmd->name != "decoderawtransaction" && + pcmd->name != "dumpprivkey" && pcmd->name != "getpeerinfo" && pcmd->name != "getnetworkinfo" ) { throw JSONRPCError(RPC_IN_WARMUP, rpcWarmupStatus); } } @@ -852,12 +858,10 @@ UniValue CRPCTable::execute(const std::string &strMethod, const UniValue ¶ms std::string HelpExampleCli(const std::string& methodname, const std::string& args) { - if ( SMART_CHAIN_SYMBOL[0] == 0 ) { - return "> komodo-cli " + methodname + " " + args + "\n"; - } else if ((strncmp(SMART_CHAIN_SYMBOL, "HUSH3", 5) == 0) ) { + if ((strncmp(SMART_CHAIN_SYMBOL, "HUSH3", 5) == 0) ) { return "> hush-cli " + methodname + " " + args + "\n"; } else { - return "> komodo-cli -ac_name=" + strprintf("%s", SMART_CHAIN_SYMBOL) + " " + methodname + " " + args + "\n"; + return "> hush-cli -ac_name=" + strprintf("%s", SMART_CHAIN_SYMBOL) + " " + methodname + " " + args + "\n"; } } @@ -870,7 +874,7 @@ std::string HelpExampleRpc(const std::string& methodname, const std::string& arg string experimentalDisabledHelpMsg(const string& rpc, const string& enableArg) { string daemon = "hushd"; - string ticker = SMART_CHAIN_SYMBOL[0] == 0 ? "komodo" : SMART_CHAIN_SYMBOL; + string ticker = SMART_CHAIN_SYMBOL; return "\nWARNING: " + rpc + " is disabled.\n" "To enable it, restart " + daemon + " with the -experimentalfeatures and\n" diff --git a/src/rpc/server.h b/src/rpc/server.h index d809597f1..4e301ea8c 100644 --- a/src/rpc/server.h +++ b/src/rpc/server.h @@ -351,6 +351,7 @@ extern UniValue getrawchangeaddress(const UniValue& params, bool fHelp, const CP extern UniValue setaccount(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue getaccount(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue getaddressesbyaccount(const UniValue& params, bool fHelp, const CPubKey& mypk); +extern UniValue listaddresses(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue sendtoaddress(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue signmessage(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue verifymessage(const UniValue& params, bool fHelp, const CPubKey& mypk); diff --git a/src/script/standard.h b/src/script/standard.h index 601b9e5cd..697150372 100644 --- a/src/script/standard.h +++ b/src/script/standard.h @@ -117,45 +117,6 @@ class COptCCParams std::vector AsVector(); }; -class CStakeParams -{ - public: - static const uint32_t STAKE_MINPARAMS = 4; - static const uint32_t STAKE_MAXPARAMS = 5; - - uint32_t srcHeight; - uint32_t blkHeight; - uint256 prevHash; - CPubKey pk; - - CStakeParams() : srcHeight(0), blkHeight(0), prevHash(), pk() {} - - CStakeParams(const std::vector> &vData); - - CStakeParams(uint32_t _srcHeight, uint32_t _blkHeight, const uint256 &_prevHash, const CPubKey &_pk) : - srcHeight(_srcHeight), blkHeight(_blkHeight), prevHash(_prevHash), pk(_pk) {} - - std::vector AsVector() - { - std::vector ret; - CScript scr = CScript(); - scr << OPRETTYPE_STAKEPARAMS; - scr << srcHeight; - scr << blkHeight; - scr << std::vector(prevHash.begin(), prevHash.end()); - - if (pk.IsValid()) - { - scr << std::vector(pk.begin(), pk.end()); - } - - ret = std::vector(scr.begin(), scr.end()); - return ret; - } - - bool IsValid() { return srcHeight != 0; } -}; - /** Check whether a CTxDestination is a CNoDestination. */ bool IsValidDestination(const CTxDestination& dest); diff --git a/src/stratum.cpp b/src/stratum.cpp new file mode 100644 index 000000000..4dd30f524 --- /dev/null +++ b/src/stratum.cpp @@ -0,0 +1,2152 @@ +// Copyright (c) 2021-2021 The Hush developers +// Copyright (c) 2020-2021 The Freicoin Developers +// Copyright (c) 2021-2021 Decker +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// Stratum protocol: +// - https://en.bitcoin.it/wiki/Stratum_mining_protocol - Stratum mining protocol +// - https://github.com/slushpool/poclbm-zcash/wiki/Stratum-protocol-changes-for-ZCash - Stratum protocol changes for ZCash + +#include "stratum.h" +#include "base58.h" +#include "chainparams.h" +#include "consensus/validation.h" +#include "crypto/sha256.h" +#include "httpserver.h" +#include "miner.h" +#include "netbase.h" +#include "net.h" +#include "rpc/server.h" +#include "serialize.h" +#include "streams.h" +#include "sync.h" +#include "txmempool.h" +#include "uint256.h" +#include "util.h" +#include "utilstrencodings.h" +#include +#include // for std::reverse +#include +#include + +#include // for boost::trim +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#ifdef WIN32 +#include +#else +#include +#include +#include +#endif + +#include "main.h" // cs_main +#include +#include "ui_interface.h" +#include // make_unique + +#include +#include + +#include +#include + +// https://en.cppreference.com/w/cpp/types/integer - cinttypes for format constants, like PRId64, etc. +#include + + +extern uint16_t ASSETCHAINS_RPCPORT; // don't want to include hush_globals.h +UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false); // rpc/blockchain.cpp +bool DecodeHexTx(CTransaction& tx, const std::string& strHexTx); // src/core_read.cpp + +static const long jobRebroadcastTimeout = 30; +static const long txMemPoolCheckTimeout = 10; + +/** + * Begin of helper routines, + * included: missed in httpserver.cpp in our codebase, missed + * constructors for CSubNet(...), etc. +*/ + +namespace { // better to use anonymous namespace for helper routines + + class CStratumParams { + private: + const arith_uint256 defaultHashTarget; + arith_uint256 currentHashTarget; + public: + CStratumParams() : defaultHashTarget(UintToArith256(uint256S("00ffff0000000000000000000000000000000000000000000000000000000000"))), + currentHashTarget(defaultHashTarget), fAllowLowDiffShares(false), fCheckEquihashSolution(true), + fstdErrDebugOutput(false) { } + ~CStratumParams() {} + + void setTarget(const arith_uint256& target) { currentHashTarget = target; } + arith_uint256 getTarget() { return currentHashTarget; } + + bool fAllowLowDiffShares; + bool fCheckEquihashSolution; + bool fstdErrDebugOutput; + + } instance_of_cstratumparams; + + /** Check if a network address is allowed to access the Stratum server */ + static bool ClientAllowed(const std::vector& allowed_subnets, const CNetAddr& netaddr) + { + if (!netaddr.IsValid()) + return false; + for(const CSubNet& subnet : allowed_subnets) + if (subnet.Match(netaddr)) + return true; + return false; + } + + /** Initialize ACL list for Stratum server */ + static bool InitStratumAllowList(std::vector& allowed_subnets) + { + allowed_subnets.clear(); + allowed_subnets.push_back(CSubNet("127.0.0.0/8")); // always allow IPv4 local subnet + allowed_subnets.push_back(CSubNet("::1")); // always allow IPv6 localhost + if (mapMultiArgs.count("-stratumallowip")) { + const std::vector& vAllow = mapMultiArgs["-stratumallowip"]; + for(const std::string& strAllow : vAllow) { + CSubNet subnet(strAllow); + if (!subnet.IsValid()) { + uiInterface.ThreadSafeMessageBox( + strprintf("Invalid -stratumallowip subnet specification: %s. Valid are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24).", strAllow), + "", CClientUIInterface::MSG_ERROR); + return false; + } + allowed_subnets.push_back(subnet); + } + } + return true; + } + + double GetDifficultyFromBits(uint32_t bits) { + + uint32_t powLimit = UintToArith256(Params().GetConsensus().powLimit).GetCompact(); + int nShift = (bits >> 24) & 0xff; + int nShiftAmount = (powLimit >> 24) & 0xff; + + double dDiff = + (double)(powLimit & 0x00ffffff) / + (double)(bits & 0x00ffffff); + + while (nShift < nShiftAmount) + { + dDiff *= 256.0; + nShift++; + } + while (nShift > nShiftAmount) + { + dDiff /= 256.0; + nShift--; + } + + return dDiff; + } + + std::string DateTimeStrPrecise() // or we can use standart one, like DateTimeStrFormat("[%Y-%m-%d %H:%M:%S.%f]", GetTime()) + { + // https://stackoverflow.com/questions/28136660/format-a-posix-time-with-just-3-digits-in-fractional-seconds + // https://www.boost.org/doc/libs/1_35_0/doc/html/date_time/date_time_io.html#date_time.format_flags + + // std::locale takes ownership of the pointer + boost::posix_time::ptime const date_time = boost::posix_time::microsec_clock::local_time(); + std::locale loc(std::locale::classic(), new boost::posix_time::time_facet("[%Y-%m-%d %H:%M:%S.%f] ")); + std::stringstream ss; + ss.imbue(loc); + // ss << boost::posix_time::from_time_t(nTime); + ss << date_time; + return ss.str(); + } + + std::string get_stripped_username(const std::string& username) { + std::string res(username); + size_t dotpos = username.find('.'); + if (dotpos != std::string::npos) + res.resize(dotpos); + return res; + } + + // C++11 map initialization + const std::map mapColors = { + { "cl_N", "\x1B[0m" }, + { "cl_RED", "\x1B[31m" }, + { "cl_GRN", "\x1B[32m" }, + { "cl_YLW", "\x1B[33m" }, + { "cl_BLU", "\x1B[34m" }, + { "cl_MAG", "\x1B[35m" }, + { "cl_CYN", "\x1B[36m" }, + { "cl_BLK", "\x1B[22;30m" }, /* black */ + { "cl_RD2", "\x1B[22;31m" }, /* red */ + { "cl_GR2", "\x1B[22;32m" }, /* green */ + { "cl_YL2", "\x1B[22;33m" }, /* dark yellow */ + { "cl_BL2", "\x1B[22;34m" }, /* blue */ + { "cl_MA2", "\x1B[22;35m" }, /* magenta */ + { "cl_CY2", "\x1B[22;36m" }, /* cyan */ + { "cl_SIL", "\x1B[22;37m" }, /* gray */ + { "cl_LRD", "\x1B[01;31m" }, /* light red */ + { "cl_LGR", "\x1B[01;32m" }, /* light green */ + { "cl_LYL", "\x1B[01;33m" }, /* tooltips */ + { "cl_LBL", "\x1B[01;34m" }, /* light blue */ + { "cl_LMA", "\x1B[01;35m" }, /* light magenta */ + { "cl_LCY", "\x1B[01;36m" }, /* light cyan */ + { "cl_WHT", "\x1B[01;37m" }, /* white */ + }; + + enum ColorType + { + cl_N, cl_RED, cl_GRN, cl_YLW, cl_BLU, cl_MAG, cl_CYN, cl_BLK, cl_RD2, cl_GR2, cl_YL2, cl_BL2, cl_MA2, cl_CY2, cl_SIL, cl_LRD, cl_LGR, cl_LYL, cl_LBL, cl_LMA, cl_LCY, cl_WHT + }; + + char const* ColorTypeNames[]= + { + "\x1B[0m" , "\x1B[31m" , "\x1B[32m" , "\x1B[33m" , "\x1B[34m" , + "\x1B[35m" , "\x1B[36m" , "\x1B[22;30m", "\x1B[22;31m", "\x1B[22;32m", + "\x1B[22;33m", "\x1B[22;34m", "\x1B[22;35m", "\x1B[22;36m", "\x1B[22;37m", + "\x1B[01;31m", "\x1B[01;32m", "\x1B[01;33m", "\x1B[01;34m", "\x1B[01;35m", + "\x1B[01;36m", "\x1B[01;37m" + }; +} + +namespace ccminer { + + bool hex2bin(void *output, const char *hexstr, size_t len) + { + unsigned char *p = (unsigned char *) output; + char hex_byte[4]; + char *ep; + + hex_byte[2] = '\0'; + + while (*hexstr && len) { + if (!hexstr[1]) { + LogPrint("stratum", "hex2bin str truncated"); + return false; + } + hex_byte[0] = hexstr[0]; + hex_byte[1] = hexstr[1]; + *p = (unsigned char) strtol(hex_byte, &ep, 16); + if (*ep) { + LogPrint("stratum", "hex2bin failed on '%s'", hex_byte); + return false; + } + p++; + hexstr += 2; + len--; + } + + return (len == 0 && *hexstr == 0) ? true : false; + } + + // equi/equi-stratum.cpp + double target_to_diff_equi(uint32_t* target) + { + unsigned char* tgt = (unsigned char*) target; + uint64_t m = + (uint64_t)tgt[30] << 24 | + (uint64_t)tgt[29] << 16 | + (uint64_t)tgt[28] << 8 | + (uint64_t)tgt[27] << 0; + + if (!m) + return 0.; + else + return (double)0xffff0000UL/m; + } + + void diff_to_target_equi(uint32_t *target, double diff) + { + uint64_t m; + int k; + + for (k = 6; k > 0 && diff > 1.0; k--) + diff /= 4294967296.0; + m = (uint64_t)(4294901760.0 / diff); + if (m == 0 && k == 6) + memset(target, 0xff, 32); + else { + memset(target, 0, 32); + target[k + 1] = (uint32_t)(m >> 8); + target[k + 2] = (uint32_t)(m >> 40); + //memset(target, 0xff, 6*sizeof(uint32_t)); + for (k = 0; k < 28 && ((uint8_t*)target)[k] == 0; k++) + ((uint8_t*)target)[k] = 0xff; + } + } + + void hush_diff_to_target_equi(uint32_t *target, double diff) + { + uint64_t m; + int k; + + for (k = 6; k > 0 && diff > 1.0; k--) + diff /= (double)((uint64_t)0x100000000); + m = (uint64_t)((uint64_t)0x0f0f0f0f / diff); + if (m == 0 && k == 6) + memset(target, 0xff, 32); + else { + memset(target, 0, 32); + target[k + 1] = (uint32_t)(m >> 8); + target[k + 2] = (uint32_t)(m >> 40); + //memset(target, 0xff, 6*sizeof(uint32_t)); + + for (k = 0; k < 28 && ((uint8_t*)target)[k] == 0; k++) + ((uint8_t*)target)[k] = 0xff; + for (k = 0; k < 32; k++) ((uint8_t*)target)[31-k] = ((uint8_t*)target)[31-k-1]; + ((uint8_t*)target)[0] = 0xff; + } + } + + /* compute nbits to get the network diff */ + double equi_network_diff(uint32_t nbits) + { + //HUSH bits: "1e 015971", + //HUSH target: "00 00 015971000000000000000000000000000000000000000000000000000000", + //HUSH bits: "1d 686aaf", + //HUSH target: "00 0000 686aaf0000000000000000000000000000000000000000000000000000", + // uint32_t nbits = work->data[26]; + + uint32_t bits = (nbits & 0xffffff); + int16_t shift = (/*swab32*/bswap_32(nbits) & 0xff); + shift = (31 - shift) * 8; // 8 bits shift for 0x1e, 16 for 0x1d + uint64_t tgt64 = /*swab32*/bswap_32(bits); + tgt64 = tgt64 << shift; + // applog_hex(&tgt64, 8); + uint8_t net_target[32] = { 0 }; + for (int b=0; b<8; b++) + net_target[31-b] = ((uint8_t*)&tgt64)[b]; + // applog_hex(net_target, 32); + double d = target_to_diff_equi((uint32_t*)net_target); + return d; + } + + double equi_stratum_target_to_diff(const std::string& target) + { + uint8_t target_bin[32], target_be[32]; + + const char *target_hex = target.c_str(); + if (!target_hex || strlen(target_hex) == 0) + return false; + + hex2bin(target_bin, target_hex, 32); + memset(target_be, 0xff, 32); + int filled = 0; + for (int i=0; i<32; i++) { + if (filled == 3) break; + target_be[31-i] = target_bin[i]; + if (target_bin[i]) filled++; + } + + double d = target_to_diff_equi((uint32_t*) &target_be); + return d; + } + + /* Subtract the `struct timeval' values X and Y, + storing the result in RESULT. + Return 1 if the difference is negative, otherwise 0. */ + int timeval_subtract(struct timeval *result, struct timeval *x, + struct timeval *y) + { + /* Perform the carry for the later subtraction by updating Y. */ + if (x->tv_usec < y->tv_usec) { + int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; + y->tv_usec -= 1000000 * nsec; + y->tv_sec += nsec; + } + if (x->tv_usec - y->tv_usec > 1000000) { + int nsec = (x->tv_usec - y->tv_usec) / 1000000; + y->tv_usec += 1000000 * nsec; + y->tv_sec -= nsec; + } + + /* Compute the time remaining to wait. + * `tv_usec' is certainly positive. */ + result->tv_sec = x->tv_sec - y->tv_sec; + result->tv_usec = x->tv_usec - y->tv_usec; + + /* Return 1 if result is negative. */ + return x->tv_sec < y->tv_sec; + } + +} + +/** + * End of helper routines +*/ + +struct StratumClient +{ + evconnlistener* m_listener; + evutil_socket_t m_socket; + bufferevent* m_bev; + CService m_from; + int m_nextid; + uint256 m_secret; + + CService GetPeer() const + { return m_from; } + + std::string m_client; + + bool m_authorized; + CBitcoinAddress m_addr; + double m_mindiff; + + uint32_t m_version_rolling_mask; + + CBlockIndex* m_last_tip; + bool m_second_stage; + bool m_send_work; + + bool m_supports_aux; + std::set m_aux_addr; + + bool m_supports_extranonce; + + StratumClient() : m_listener(0), m_socket(0), m_bev(0), m_nextid(0), m_authorized(false), m_mindiff(0.0), m_version_rolling_mask(0x00000000), m_last_tip(0), m_second_stage(false), m_send_work(false), m_supports_aux(false), m_supports_extranonce(false) { GenSecret(); } + StratumClient(evconnlistener* listener, evutil_socket_t socket, bufferevent* bev, CService from) : m_listener(listener), m_socket(socket), m_bev(bev), m_nextid(0), m_from(from), m_authorized(false), m_mindiff(0.0), m_version_rolling_mask(0x00000000), m_last_tip(0), m_second_stage(false), m_send_work(false), m_supports_aux(false), m_supports_extranonce(false) { GenSecret(); } + + void GenSecret(); + std::vector ExtraNonce1(uint256 job_id) const; +}; + +void StratumClient::GenSecret() +{ + GetRandBytes(m_secret.begin(), 32); +} + +std::vector StratumClient::ExtraNonce1(uint256 job_id) const +{ + CSHA256 nonce_hasher; + nonce_hasher.Write(m_secret.begin(), 32); + + if (m_supports_extranonce) { + nonce_hasher.Write(job_id.begin(), 32); + } + + uint256 job_nonce; + nonce_hasher.Finalize(job_nonce.begin()); + return {job_nonce.begin(), job_nonce.begin()+8}; +} + +struct StratumWork { + CBlockTemplate m_block_template; + // First we generate the segwit commitment for the miner's coinbase with + // ComputeFastMerkleBranch. + std::vector m_cb_wit_branch; + // Then we compute the initial right-branch for the block-tx Merkle tree + // using ComputeStableMerkleBranch... + std::vector m_bf_branch; + // ...which is appended to the end of m_cb_branch so we can compute the + // block's hashMerkleRoot with ComputeMerkleBranch. + std::vector m_cb_branch; + bool m_is_witness_enabled; + + int32_t nHeight; + std::string local_diff; + + // The cached 2nd-stage auxiliary hash value, if an auxiliary proof-of-work + // solution has been found. + boost::optional m_aux_hash2; + + StratumWork() : m_is_witness_enabled(false),nHeight(0) { }; + StratumWork(const CBlockTemplate& block_template, bool is_witness_enabled); + + CBlock& GetBlock() + { return m_block_template.block; } + const CBlock& GetBlock() const + { return m_block_template.block; } +}; + +StratumWork::StratumWork(const CBlockTemplate& block_template, bool is_witness_enabled) + : m_block_template(block_template) + , m_is_witness_enabled(is_witness_enabled), nHeight(0) +{ + // Generate the block-witholding secret for the work unit. + + std::vector leaves; + for (const auto& tx : m_block_template.block.vtx) { + leaves.push_back(tx.GetHash()); + } + + std::vector vMerkleTree; uint256 merkleRoot; bool fMutated; + + merkleRoot = BuildMerkleTree(&fMutated, leaves, vMerkleTree); + m_cb_branch = GetMerkleBranch(0, leaves.size(), vMerkleTree); + // m_cb_branch = ComputeMerkleBranch(leaves, 0); +}; + +//! Critical seciton guarding access to any of the stratum global state +static CCriticalSection cs_stratum; + +//! List of subnets to allow stratum connections from +static std::vector stratum_allow_subnets; + +//! Bound stratum listening sockets +static std::map bound_listeners; + +//! Active miners connected to us +static std::map subscriptions; + +//! Mapping of stratum method names -> handlers +static std::map > stratum_method_dispatch; + +//! A mapping of job_id -> work templates +static std::map work_templates; + +//! The job_id of the first work unit to have its auxiliary proof-of-work solved +//! for the current block, or boost::none if no solution has been returned yet. +static boost::optional half_solved_work; + +//! A thread to watch for new blocks and send mining notifications +static boost::thread block_watcher_thread; + +std::string HexInt4(uint32_t val) +{ + std::vector vch; + vch.push_back((val >> 24) & 0xff); + vch.push_back((val >> 16) & 0xff); + vch.push_back((val >> 8) & 0xff); + vch.push_back( val & 0xff); + return HexStr(vch); +} + +uint32_t ParseHexInt4(const UniValue& hex, const std::string& name) +{ + std::vector vch = ParseHexV(hex, name); + if (vch.size() != 4) { + throw JSONRPCError(RPC_INVALID_PARAMETER, name+" must be exactly 4 bytes / 8 hex"); + } + uint32_t ret = 0; + ret |= vch[0] << 24; + ret |= vch[1] << 16; + ret |= vch[2] << 8; + ret |= vch[3]; + return ret; +} + +uint256 ParseUInt256(const UniValue& hex, const std::string& name) +{ + if (!hex.isStr()) { + throw std::runtime_error(name+" must be a hexidecimal string"); + } + std::vector vch = ParseHex(hex.get_str()); + if (vch.size() != 32) { + throw std::runtime_error(name+" must be exactly 32 bytes / 64 hex"); + } + uint256 ret; + std::copy(vch.begin(), vch.end(), ret.begin()); + return ret; +} + +static double ClampDifficulty(const StratumClient& client, double diff) +{ + if (client.m_mindiff > 0) { + diff = client.m_mindiff; + } + diff = std::max(diff, 0.001); + return diff; +} + +static std::string GetExtraNonceRequest(StratumClient& client, const uint256& job_id) +{ + // https://en.bitcoin.it/wiki/Stratum_mining_protocol#mining.set_extranonce + // mining.set_extranonce("extranonce1", extranonce2_size) + + std::string ret; + if (client.m_supports_extranonce) + { + std::vector extranonce1 = client.ExtraNonce1(job_id); + + const std::string k_extranonce_req = std::string() + + "{" + + "\"id\":"; + const std::string k_extranonce_req2 = std::string() + + "," + + "\"method\":\"mining.set_extranonce\"," + + "\"params\":[" + + "\""; + const std::string k_extranonce_req3 = std::string() + + "\"," // extranonce1 + + strprintf("%d", 32 - extranonce1.size()) // extranonce2.size() = 32 - extranonce1.size() + + "]" + + "}" + + "\n"; + + ret = k_extranonce_req + + strprintf("%d", client.m_nextid++) + + k_extranonce_req2 + + HexStr(extranonce1) + + k_extranonce_req3; + } + return ret; +} + +/** + * @brief + * + * @param client + * @param current_work + * @param addr + * @param extranonce1 + * @param extranonce2 + * @param cb + * @param bf + * @param cb_branch + */ +void CustomizeWork(const StratumClient& client, const StratumWork& current_work, const CBitcoinAddress& addr, const std::vector& extranonce1, const std::vector& extranonce2, CMutableTransaction& cb, CMutableTransaction& bf, std::vector& cb_branch) +{ + if (current_work.GetBlock().vtx.empty()) { + const std::string msg = strprintf("%s: no transactions in block template; unable to submit work", __func__); + LogPrint("stratum", "%s\n", msg); + throw std::runtime_error(msg); + } + + cb = CMutableTransaction(current_work.GetBlock().vtx[0]); + + if (cb.vin.size() != 1) { + const std::string msg = strprintf("%s: unexpected number of inputs; is this even a coinbase transaction?", __func__); + LogPrint("stratum", "%s\n", msg); + throw std::runtime_error(msg); + } + + std::vector nonce(extranonce1); + + if ((nonce.size() + extranonce2.size()) != 32) { + const std::string msg = strprintf("%s: unexpected combined nonce length: extranonce1(%d) + extranonce2(%d) != 32; unable to submit work", __func__, nonce.size(), extranonce2.size()); + LogPrint("stratum", "%s\n", msg); + throw std::runtime_error(msg); + } + nonce.insert(nonce.end(), extranonce2.begin(), extranonce2.end()); + + // nonce = extranonce1 + extranonce2 + // if (instance_of_cstratumparams.fstdErrDebugOutput) { + // std::cerr << __func__ << ": " << __FILE__ << "," << __LINE__ << " nonce = " << HexStr(nonce) << std::endl; + // } + + if (cb.vin.empty()) { + const std::string msg = strprintf("%s: first transaction is missing coinbase input; unable to customize work to miner", __func__); + LogPrint("stratum", "%s\n", msg); + throw std::runtime_error(msg); + } + // cb.vin[0].scriptSig = + // CScript() + // << cb.lock_height + // << nonce; + + /* actually we will change only cb destination on the miner address */ + { + if (cb.vout.empty()) { + const std::string msg = strprintf("%s: coinbase transaction is missing outputs; unable to customize work to miner", __func__); + LogPrint("stratum", "%s\n", msg); + throw std::runtime_error(msg); + } + if (cb.vout[0].scriptPubKey == (CScript() << OP_FALSE)) { + cb.vout[0].scriptPubKey = GetScriptForDestination(addr.Get()); + } + } + + // cb_branch = current_work.m_cb_branch; +} + +std::string GetWorkUnit(StratumClient& client) +{ + // LOCK(cs_main); + + /* if (!g_connman) { + throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); + } */ + + /* if (!Params().MineBlocksOnDemand() && g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0) { + throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Hush is not connected!"); + } */ + + bool fvNodesEmpty; + { + LOCK(cs_vNodes); + fvNodesEmpty = vNodes.empty(); + } + + if (Params().MiningRequiresPeers() && fvNodesEmpty) + { + const std::string msg = strprintf("%s: Unable to get work unit, Hush is not connected!", __func__); + LogPrint("stratum", "%s\n", msg); + throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Hush is not connected!"); + } + + if (IsInitialBlockDownload()) { + const std::string msg = strprintf("%s: Unable to get work unit, Hush is still downloading blocks!", __func__); + LogPrint("stratum", "%s\n", msg); + throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Hush is downloading blocks..."); + } + + if (!client.m_authorized && client.m_aux_addr.empty()) { + const std::string msg = strprintf("%s: Unable to get work unit, client not authorized! Use address 'x' to mine to the default address", __func__); + LogPrint("stratum", "%s\n", msg); + throw JSONRPCError(RPC_INVALID_REQUEST, "Stratum client not authorized. Use mining.authorize first, with a Hush R.. address as the username or 'x' to mine to the default address."); + } + + static CBlockIndex* tip = NULL; // pindexPrev + static uint256 job_id; + static unsigned int transactions_updated_last = 0; + static int64_t last_update_time = 0; + + // rpc/mining.cpp -> getblocktemplate -> Update block + if ( tip != chainActive.Tip() || + (mempool.GetTransactionsUpdated() != transactions_updated_last && (GetTime() - last_update_time) > 5) || + !work_templates.count(job_id)) + { + CBlockIndex *tip_new = chainActive.Tip(); + + /** + * We will check script later inside CustomizeWork, if it will be == CScript() << OP_FALSE it will mean + * that work need to be customized, and in that case cb.vout[0].scriptPubKey will be set to GetScriptForDestination(addr.Get()) . + * In other words to the address with which stratum client is authorized. + */ + const CScript scriptDummy = CScript() << OP_FALSE; + std::unique_ptr new_work(CreateNewBlock(CPubKey(), scriptDummy, HUSH_MAXGPUCOUNT, false)); // std::unique_ptr new_work = BlockAssembler(Params()).CreateNewBlock(script); + + /* test values for debug */ + // new_work->block.nBits = 0x200f0f0f; + // new_work->block.nTime = 1623567886; + // new_work->block.hashPrevBlock = uint256S("027e3758c3a65b12aa1046462b486d0a63bfa1beae327897f56c5cfb7daaae71"); + // new_work->block.hashMerkleRoot = uint256S("29f0e769c762b691d81d31bbb603719a94ef04d53d332f7de5e5533ddfd08e19"); + // new_work->block.hashFinalSaplingRoot = uint256S("3e49b5f954aa9d3545bc6c37744661eea48d7c34e3000d82b7f0010c30f4c2fb"); + // DecodeHexTx(new_work->block.vtx[0], "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff03510101ffffffff01aa2ce73b0000000023210325b4ca6736f90679f712be1454c5302050aae6edb51b0d2a051156bc868fec16ac4aabc560"); + + if (!new_work) { + const std::string msg = strprintf("%s: Out of memory!", __func__); + LogPrint("stratum", "%s\n", msg); + throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); + } + + // if (instance_of_cstratumparams.fstdErrDebugOutput) std::cerr << __func__ << ": " << __FILE__ << "," << __LINE__ << "hashMerkleRoot = " << new_work->block.hashMerkleRoot.ToString() << std::endl; + + // So that block.GetHash() is correct + //new_work->block.hashMerkleRoot = BlockMerkleRoot(new_work->block); + new_work->block.hashMerkleRoot = new_work->block.BuildMerkleTree(); + + // NB! here we have merkle with scriptDummy script in coinbase, after CustomizeWork we should recalculate it (!) + // if (instance_of_cstratumparams.fstdErrDebugOutput) std::cerr << __func__ << ": " << __FILE__ << "," << __LINE__ << "hashMerkleRoot = " << new_work->block.hashMerkleRoot.ToString() << std::endl; + + job_id = new_work->block.GetHash(); + //work_templates[job_id] = StratumWork(*new_work, new_work->block.vtx[0]->HasWitness()); + work_templates[job_id] = StratumWork(*new_work, false); + + tip = tip_new; + + transactions_updated_last = mempool.GetTransactionsUpdated(); + last_update_time = GetTime(); + + LogPrint("stratum", "New stratum block template (%d total): %s\n", work_templates.size(), HexStr(job_id.begin(), job_id.end())); + + // Remove any old templates + std::vector old_job_ids; + boost::optional oldest_job_id = boost::none; + uint32_t oldest_job_nTime = last_update_time; + for (const auto& work_template : work_templates) { + // If, for whatever reason the new work was generated with + // an old nTime, don't erase it! + if (work_template.first == job_id) { + continue; + } + // Build a list of outdated work units to free. + if (work_template.second.GetBlock().nTime < (last_update_time - 900)) { + old_job_ids.push_back(work_template.first); + } + // Track the oldest work unit, in case we have too much + // recent work. + if (work_template.second.GetBlock().nTime <= oldest_job_nTime) { + oldest_job_id = work_template.first; + oldest_job_nTime = work_template.second.GetBlock().nTime; + } + } + // Remove all outdated work. + for (const auto& old_job_id : old_job_ids) { + work_templates.erase(old_job_id); + LogPrint("stratum", "Removed outdated stratum block template (%d total): %s\n", work_templates.size(), HexStr(old_job_id.begin(), old_job_id.end())); + } + // Remove the oldest work unit if we're still over the maximum + // number of stored work templates. + if (work_templates.size() > 30 && oldest_job_id) { + work_templates.erase(oldest_job_id.get()); + LogPrint("stratum", "Removed oldest stratum block template (%d total): %s\n", work_templates.size(), HexStr(oldest_job_id.get().begin(), oldest_job_id.get().end())); + } + } + + StratumWork& current_work = work_templates[job_id]; + + + CBlockIndex tmp_index; + + // Native proof-of-work difficulty + tmp_index.nBits = current_work.GetBlock().nBits; + double diff = ClampDifficulty(client, GetDifficulty(&tmp_index)); + + UniValue set_target(UniValue::VOBJ); + set_target.push_back(Pair("id", client.m_nextid++)); + set_target.push_back(Pair("method", "mining.set_target")); + UniValue set_target_params(UniValue::VARR); + + std::string strTarget; // set_target + { + arith_uint256 hashTarget; bool fNegative,fOverflow; + /* + + // Targets Table Example: hush diff and ccminer diff are different (!), + // Hush diff = NiceHash diff, ccminer_diff = Yiimp diff. + + hashTarget.SetCompact(HUSH_MINDIFF_NBITS,&fNegative,&fOverflow); // blkhdr.nBits + hashTarget = UintToArith256(uint256S("0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f")); + hashTarget.SetHex("0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f"); + + hashTarget.SetHex("00ffff0000000000000000000000000000000000000000000000000000000000"); // hush_diff = 15.0591, ccminer_diff = 1 + hashTarget.SetHex("003fffc000000000000000000000000000000000000000000000000000000000"); // hush_diff = 60.2362, ccminer_diff = 4 + hashTarget.SetHex("0007fff800000000000000000000000000000000000000000000000000000000"); // hush_diff = 481.89, ccminer_diff = 31.9999 + hashTarget.SetHex("c7ff3800ffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); // hush_diff = 0.0752956, ccminer_diff = 1.00303 + hashTarget.SetHex("0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f"); // hush_diff = 1, ccminer_diff = 16.9956 + */ + + arith_uint256 aHashTarget = instance_of_cstratumparams.getTarget(); + + // arith_uint256 aHashTarget = UintToArith256(uint256S("00ffff0000000000000000000000000000000000000000000000000000000000")); // 1.0 + // aHashTarget = aHashTarget / 8704; // hush_diff = 131074 (NiceHash), ccminer_diff = 8704 (Yiimp) + + /* here we can adjust diff by some algo, note that 00ffff0000000000000000000000000000000000000000000000000000000000 / 8704 = + 0000078780000000000000000000000000000000000000000000000000000000, which is equivalent to hush_diff = 131074 (NiceHash), + ccminer_diff = 8704 (Yiimp) + */ + + hashTarget = aHashTarget; + strTarget = hashTarget.GetHex(); + current_work.local_diff = strTarget; + + if (instance_of_cstratumparams.fstdErrDebugOutput) { + std::cerr << DateTimeStrPrecise() << __func__ << ": " << __FILE__ << "," << __LINE__ << + strprintf(" target = %s, hush_diff = %g, ccminer_diff = %g", + strTarget, GetDifficultyFromBits(hashTarget.GetCompact(false)), ccminer::equi_stratum_target_to_diff(strTarget)) << std::endl; + } + } + + set_target_params.push_back(UniValue(strTarget)); // TODO: send real local diff (!) + set_target.push_back(Pair("params", set_target_params)); + + CMutableTransaction cb, bf; + std::vector cb_branch; + + // if (instance_of_cstratumparams.fstdErrDebugOutput) + // { + // std::cerr << __func__ << ": " << __FILE__ << "," << __LINE__ << " [1] cb = " << CTransaction(cb).ToString() << std::endl; + // std::cerr << __func__ << ": " << __FILE__ << "," << __LINE__ << " [1] current_work.GetBlock().vtx[0] = " << current_work.GetBlock().vtx[0].ToString() << std::endl; + // } + + { + std::vector extranonce1 = client.ExtraNonce1(job_id); + + static const std::vector dummy(32-extranonce1.size(), 0x00); // extranonce2 + CustomizeWork(client, current_work, client.m_addr, extranonce1, dummy, cb, bf, cb_branch); + + // without 2 lines below equihash solutinon on SubmitWork will be incorrect, bcz we should + // change vtx[0] in current work and re-calc hashMerkleRoot + // TODO: refactor all of these ... may be change this in current_work directly is bad idea, + // and we should do all checks and hashMerkleRoot at SubmitBlock(...) + + current_work.GetBlock().vtx[0] = cb; + current_work.GetBlock().hashMerkleRoot = current_work.GetBlock().BuildMerkleTree(); + + } + + // if (instance_of_cstratumparams.fstdErrDebugOutput) + // { + // std::cerr << __func__ << ": " << __FILE__ << "," << __LINE__ << " [2] cb = " << CTransaction(cb).ToString() << std::endl; + // std::cerr << __func__ << ": " << __FILE__ << "," << __LINE__ << " [2] current_work.GetBlock().vtx[0] = " << current_work.GetBlock().vtx[0].ToString() << std::endl; + // } + + CBlockHeader blkhdr; + // Setup native proof-of-work + + blkhdr = current_work.GetBlock().GetBlockHeader(); // copy entire blockheader created with CreateNewBlock to blkhdr + // CDataStream ds(SER_GETHASH, SERIALIZE_TRANSACTION_NO_WITNESS); + CDataStream ds(SER_GETHASH, PROTOCOL_VERSION); + ds << cb; + + /* + HexInt4(blkhdr.nVersion) = 00000004, so we can't use it here, will use swab conversion via 1 of 3 methods: + + (1) params.push_back(HexStr((unsigned char *)&blkhdr.nVersion, (unsigned char *)&blkhdr.nVersion + sizeof(blkhdr.nVersion))); // VERSION + (2) std::vector vnVersion(4, 0); + WriteLE64(&vnVersion[0], blkhdr.nVersion); + params.push_back(HexStr(vnVersion)); + (3) params.push_back(HexInt4(bswap_32(blkhdr.nVersion))); + + Bytes order, cheatsheet: + + [ need ] fbc2f4300c01f0b7820d00e3347c8da4ee614674376cbc45359daa54f9b5493e - HexStr(ToByteVector(blkhdr.hashFinalSaplingRoot)) + [ need ] fbc2f4300c01f0b7820d00e3347c8da4ee614674376cbc45359daa54f9b5493e - HexStr(blkhdr.hashFinalSaplingRoot) + [ ---- ] 3e49b5f954aa9d3545bc6c37744661eea48d7c34e3000d82b7f0010c30f4c2fb - blkhdr.hashFinalSaplingRoot.GetHex() + [ ---- ] 3e49b5f954aa9d3545bc6c37744661eea48d7c34e3000d82b7f0010c30f4c2fb - blkhdr.hashFinalSaplingRoot.ToString() + */ + + /* mining.notify params */ + UniValue params(UniValue::VARR); // mining.notify params + params.push_back(HexStr(job_id.begin(), job_id.end())); // JOB_ID + params.push_back(HexInt4(bswap_32(blkhdr.nVersion))); // VERSION (0x4 -> "04000000") + params.push_back(HexStr(blkhdr.hashPrevBlock)); // PREVHASH + params.push_back(HexStr(blkhdr.hashMerkleRoot)); // MERKLEROOT + params.push_back(HexStr(blkhdr.hashFinalSaplingRoot)); // RESERVED -> hashFinalSaplingRoot + + UpdateTime(&blkhdr, Params().GetConsensus(), tip /* or pindexPrev [tip-1] is needed? */); + // blkhdr.nTime = GetTime(); + + params.push_back(HexInt4(bswap_32(blkhdr.nTime))); // TIME + params.push_back(HexInt4(bswap_32(blkhdr.nBits))); // BITS + + // Clean Jobs. If true, miners should abort their current work and immediately use the new job. + // If false, they can still use the current job, but should move to the new one after exhausting the current nonce range. + + UniValue clean_jobs(UniValue::VBOOL); + clean_jobs = client.m_last_tip != tip; + params.push_back(clean_jobs); // CLEAN_JOBS + + if (instance_of_cstratumparams.fstdErrDebugOutput) std::cerr << DateTimeStrPrecise() << "New job: " << HexStr(job_id) << " " << strprintf("%08x", blkhdr.nTime) << std::endl; + + client.m_last_tip = tip; + + UniValue mining_notify(UniValue::VOBJ); + mining_notify.push_back(Pair("id", client.m_nextid++)); + mining_notify.push_back(Pair("method", "mining.notify")); + mining_notify.push_back(Pair("params", params)); + + return GetExtraNonceRequest(client, job_id) + + set_target.write() + "\n" + + mining_notify.write() + "\n"; +} +bool SubmitBlock(StratumClient& client, const uint256& job_id, const StratumWork& current_work, + const std::vector& extranonce1, const std::vector& extranonce2, + boost::optional nVersion, uint32_t nTime, const std::vector& sol) +{ + // called from stratum_mining_submit and uses following data, came from client: + // ["WORKER_NAME", "JOB_ID", "TIME", "NONCE_2", "EQUIHASH_SOLUTION"] + // all other params we have saved in other places + + if (extranonce1.size() + extranonce2.size() != 32) { + std::string msg = strprintf("extranonce1 [%d] length + extranonce2 [%d] length != %d", extranonce1.size(), extranonce2.size(), 32); + LogPrint("stratum", "%s\n", msg); + throw JSONRPCError(RPC_INVALID_PARAMETER, msg); + } + + // TODO: change hardcoded constants on actual determine of solution size, depends on equihash algo type: 200.9, etc. + if (sol.size() != 1347) { + std::string msg = strprintf("%s: solution is wrong length (received %d bytes; expected %d bytes", __func__, extranonce2.size(), 1347); + LogPrint("stratum", "%s\n", msg); + throw JSONRPCError(RPC_INVALID_PARAMETER, msg); + } + + CMutableTransaction cb, bf; + std::vector cb_branch; + CustomizeWork(client, current_work, client.m_addr, extranonce1, extranonce2, cb, bf, cb_branch); + + bool res = false; + { + // Check native proof-of-work + uint32_t version = current_work.GetBlock().nVersion; + + if (nVersion) version = *nVersion; + CBlockHeader blkhdr(current_work.GetBlock()); + + blkhdr.nVersion = version; + blkhdr.hashPrevBlock = current_work.GetBlock().hashPrevBlock; + // blkhdr.hashMerkleRoot = ComputeMerkleRootFromBranch(cb.GetHash(), cb_branch, 0); + // blkhdr.hashMerkleRoot = blkhdr.BuildMerkleTree(); + blkhdr.nTime = nTime; + blkhdr.nBits = current_work.GetBlock().nBits; + + // just an example of how-to reverse the things, don't needed in real life + // std::vector noncerev(extranonce1); + // std::reverse(noncerev.begin(), noncerev.end()); + // noncerev.insert(noncerev.begin(), extranonce2.rbegin(), extranonce2.rend()); + + std::vector nonce(extranonce1); + nonce.insert(nonce.end(), extranonce2.begin(), extranonce2.end()); + + blkhdr.nSolution = std::vector(sol.begin() + 3, sol.end()); + + blkhdr.hashFinalSaplingRoot = current_work.GetBlock().hashFinalSaplingRoot; + blkhdr.hashMerkleRoot = current_work.GetBlock().hashMerkleRoot; + blkhdr.nNonce = (uint256) nonce; + + // example how to display constructed block + // if (instance_of_cstratumparams.fstdErrDebugOutput) { + // CBlockIndex index {blkhdr}; + // index.SetHeight(current_work.nHeight); + // std::cerr << __func__ << ": " << __FILE__ << "," << __LINE__ << " blkhdr.hashPrevBlock = " << blkhdr.hashPrevBlock.GetHex() << std::endl; + // std::cerr << __func__ << ": " << __FILE__ << "," << __LINE__ << " blkhdr = " << blockToJSON(blkhdr, &index).write() << std::endl; + // } + + // block is constructed, now it's time to VerifyEH + + if (instance_of_cstratumparams.fCheckEquihashSolution && !CheckEquihashSolution(&blkhdr, Params())) + throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid equihash solution"); + + arith_uint256 bnTarget; bool fNegative, fOverflow; + bnTarget.SetCompact(blkhdr.nBits, &fNegative, &fOverflow); + + // check range + // if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) + // return false; + + if (UintToArith256(blkhdr.GetHash()) > bnTarget) { + res = false; + } else { + uint8_t pubkey33[33]; int32_t height = current_work.nHeight; + res = CheckProofOfWork(blkhdr, pubkey33, height, Params().GetConsensus()); + } + // if (instance_of_cstratumparams.fstdErrDebugOutput) std::cerr << DateTimeStrPrecise() << "res[1] = " << res << std::endl; + + uint256 hash = blkhdr.GetHash(); + + // bits = GetNextWorkRequired(blockindex, nullptr, Params().GetConsensus()); + + static uint64_t counter_TotalBlocks, counter_TotalShares, counter_prev; + if (res) + counter_TotalBlocks++; + counter_TotalShares++; + + // https://en.cppreference.com/w/cpp/types/integer - PRId64, PRIu64 (people always forget about various OS and format specifications) + + // native proof-of-work difficulty + CBlockIndex tmp_index; + + tmp_index.nBits = blkhdr.nBits; + double hush_target_diff = GetDifficulty(&tmp_index); // diff from nbits (target) + tmp_index.nBits = UintToArith256(hash).GetCompact(); + double hush_real_diff = GetDifficulty(&tmp_index); // real diff (from hash) + tmp_index.nBits = arith_uint256(current_work.local_diff).GetCompact(); + double hush_local_diff = GetDifficulty(&tmp_index); // local diff (from local port diff) + + double ccminer_real_diff = ccminer::equi_stratum_target_to_diff(hash.ToString()); + double ccminer_target_diff = ccminer::equi_stratum_target_to_diff(arith_uint256().SetCompact(blkhdr.nBits).ToString()); + double ccminer_local_diff = ccminer::equi_stratum_target_to_diff(current_work.local_diff); + + static std::chrono::high_resolution_clock::time_point start; + std::chrono::high_resolution_clock::time_point finish = std::chrono::high_resolution_clock::now(); + std::chrono::duration elapsed; + uint64_t shares_accepted_since_last; + + // TODO: we need to check hash > local port diff, and if it's true -> throw an exception -> diff too low (!) + if (!instance_of_cstratumparams.fAllowLowDiffShares) + if (UintToArith256(blkhdr.GetHash()) > arith_uint256(current_work.local_diff)) + throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Low diff share (diff %g, local %g)", hush_real_diff, hush_local_diff)); + + if (finish > start) + { + elapsed = finish - start; + shares_accepted_since_last = counter_TotalShares - counter_prev; + start = finish; + counter_prev = counter_TotalShares; + // std::cerr << strprintf("%f ms - %" PRIu64 "", elapsed.count(), shares_accepted_since_last) << std::endl; + } + + bool fDisplayDiffHUSH = true; // otherwise it will display ccminer diff + + std::cerr << DateTimeStrPrecise() << + strprintf("%saccepted: %" PRIu64 "/%" PRIu64 "%s ", ColorTypeNames[cl_WHT], counter_TotalBlocks, counter_TotalShares, ColorTypeNames[cl_N] ); + if (fDisplayDiffHUSH) { + /* hushd diff display */ + std::cerr << strprintf("%slocal %g%s ", "\x1B[90m", hush_local_diff, ColorTypeNames[cl_N]) << + strprintf("%s(diff %g, target %g) %s ", ColorTypeNames[cl_WHT], hush_real_diff, hush_target_diff, ColorTypeNames[cl_N]); + } else { /* ccminer diff display */ + std::cerr << strprintf("%slocal %.3f%s ", "\x1B[90m", ccminer_local_diff, ColorTypeNames[cl_N]) << + strprintf("%s(diff %.3f, target %.3f) %s", ColorTypeNames[cl_WHT], ccminer_real_diff, ccminer_target_diff, ColorTypeNames[cl_N]); // ccminer diff + } + + std::cerr << "" << + strprintf("%f ms ", elapsed.count()) << // 1 share took elapsed ms + strprintf("%s%s%s ", ColorTypeNames[cl_LGR], (res ? "yay!!!": "yes!"), ColorTypeNames[cl_N]) << + std::endl; + + // (diff %g, target %g), % + if (res) { + + LogPrintf("GOT BLOCK!!! by %s: %s\n", client.m_addr.ToString(), hash.ToString()); + + CBlock block(current_work.GetBlock()); + // block.vtx[0] = MakeTransactionRef(std::move(cb)); + block.vtx[0] = cb; + + // if (!current_work.m_aux_hash2 && current_work.m_is_witness_enabled) { + // block.vtx.back() = MakeTransactionRef(std::move(bf)); + // } + block.nVersion = version; + // block.hashMerkleRoot = BlockMerkleRoot(block); + block.hashMerkleRoot = block.BuildMerkleTree(); + //if (instance_of_cstratumparams.fstdErrDebugOutput) std::cerr << "hashMerkleRoot = " << block.hashMerkleRoot.GetHex() << std::endl; + + block.nTime = nTime; + // block.nNonce = nNonce; + // nNonce <<= 32; nNonce >>= 16; // clear the top and bottom 16 bits (for local use as thread flags and counters) + + block.nNonce = (uint256) nonce; + block.nSolution = std::vector(sol.begin() + 3, sol.end()); + + // example how to pre-check the equihash solution + // if(instance_of_cstratumparams.fstdErrDebugOutput) { + // CBlockIndex index {blkhdr}; + // index.SetHeight(-1); + // std::cerr << "block = " << blockToJSON(block, &index, true).write(1) << std::endl; + // std::cerr << "CheckEquihashSolution = " << CheckEquihashSolution(&block, Params()) << std::endl; + // } + + // std::shared_ptr pblock = std::make_shared(block); + // res = ProcessNewBlock(Params(), pblock, true, NULL); + + CValidationState state; + res = ProcessNewBlock(0,0,state, NULL, &block, true /* forceProcessing */ , NULL); + + //if (instance_of_cstratumparams.fstdErrDebugOutput) std::cerr << DateTimeStrPrecise() << "res[2] = " << res << std::endl; + + // we haven't PreciousBlock, so we can't prioritize the block this way for now + /* + if (res) { + // LOCK(cs_main); + if (!mapBlockIndex.count(hash)) { + LogPrintf("Unable to find new block index entry; cannot prioritise block 0x%s\n", hash.ToString()); + } else + { + CBlockIndex* block_index = mapBlockIndex.at(hash); + CValidationState state; + + // PreciousBlock(state, Params(), block_index); + // if (!state.IsValid()) { + // LogPrintf("Database error while prioritising new block 0x%s: %d (%s) %s\n", hash.ToString(), state.GetRejectCode(), state.GetRejectReason(), state.GetDebugMessage()); + // } + } + } + */ + } else { + LogPrintf("NEW SHARE!!! by %s: %s\n", client.m_addr.ToString(), hash.ToString()); + } + } + + if (res) { + client.m_send_work = true; + } + + return res; +} + +void BoundParams(const std::string& method, const UniValue& params, size_t min, size_t max) +{ + if (params.size() < min) { + throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s expects at least %d parameters; received %d", method, min, params.size())); + } + + if (params.size() > max) { + throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s receives no more than %d parameters; got %d", method, max, params.size())); + } +} + +UniValue stratum_mining_subscribe(StratumClient& client, const UniValue& params) +{ + const std::string method("mining.subscribe"); + BoundParams(method, params, 0, 4); + + if (params.size() >= 1) { + client.m_client = params[0].get_str(); + LogPrint("stratum", "Received subscription from client %s\n", client.m_client); + } + + // According to 'Stratum protocol changes for ZCash' - https://github.com/slushpool/poclbm-zcash/wiki/Stratum-protocol-changes-for-ZCash + // mining.subscribe params looks like following: + + // {"id": 1, "method": "mining.subscribe", "params": ["CONNECT_HOST", CONNECT_PORT, "MINER_USER_AGENT", "SESSION_ID"]} + // So, params[params.size()-1] should be SESSION_ID, but currently we don't support it. + + // Also we should answer with these: + // {"id": 1, "result": ["SESSION_ID", "NONCE_1"], "error": null} + // {"id":1,"result":[null,"81000001"],"error":null} + + // NONCE_1 is first part of the block header nonce (in hex). + + // By protocol, Zcash's nonce is 32 bytes long. The miner will pick NONCE_2 such that len(NONCE_2) = 32 - len(NONCE_1). + // Please note that Stratum use hex encoding, so you have to convert NONCE_1 from hex to binary before. + + // ["CONNECT_HOST", CONNECT_PORT, "MINER_USER_AGENT", "SESSION_ID"] + // ["NiceHash/1.0.0", null, "stratum.hush.is", 28030] // ua, session_id, host, port? + // ["ccminer/2.3.1"] + + UniValue ret(UniValue::VARR); + + // ExtraNonce1 -> client.m_supports_extranonce is false, so the job_id isn't used + std::vector vExtraNonce1 = client.ExtraNonce1(uint256()); + + // std::string sExtraNonce1 = HexStr(vExtraNonce1.begin(), vExtraNonce1.begin() + (vExtraNonce1.size() > 3 ? 4 : vExtraNonce1.size())); + std::string sExtraNonce1 = HexStr(vExtraNonce1); + + /** + * Potentially we can use something like strprintf("%08x", GetRand(std::numeric_limits::max()) + * here to generate sExtraNonce1, but don't forget that client.ExtraNonce1 method return 8 bytes + * job_nonce:8 = sha256(client.m_secret:32 + client.job_id:32) , so, somewhere in future we can re-calculate + * sExtraNonce1 for a given client based on m_secret. + */ + + // if (instance_of_cstratumparams.fstdErrDebugOutput && vExtraNonce1.size() > 3) { + // std::cerr << __func__ << ": " << __FILE__ << "," << __LINE__ << " " << strprintf("client.m_supports_extranonce = %d, [%d, %d, %d, %d], %s", client.m_supports_extranonce, vExtraNonce1[0], vExtraNonce1[1], vExtraNonce1[2], vExtraNonce1[3], sExtraNonce1) << std::endl; + // // recalc from client.m_secret example + // uint256 sha256; + // CSHA256().Write(client.m_secret.begin(), 32).Finalize(sha256.begin()); + // std::cerr << __func__ << ": " << __FILE__ << "," << __LINE__ << " " << HexStr(std::vector(sha256.begin(), sha256.begin() + 4)) << std::endl; + // } + + ret.push_back(NullUniValue); + ret.push_back(sExtraNonce1); + + // On mining.subscribe we don't need to send anything else, we will send + // mining.set_target and mining.notify bit later, inside GetWorkUnit. + // Scheme is the following: + // 1. stratum_read_cb(bufferevent * bev, void * ctx) + // 2. if (client.m_send_work) -> GetWorkUnit + // 3. CustomizeWork (throw if error and exit from GetWorkUnit) + // 4. set_target + // 5. ... + // Last. GetWorkUnit returns string data (!) to send to client ( ... + mining.set_target + mining.notify + ... ) + + return ret; +} + +UniValue stratum_mining_authorize(StratumClient& client, const UniValue& params) +{ + const std::string method("mining.authorize"); + BoundParams(method, params, 1, 2); + + std::string username = params[0].get_str(); + boost::trim(username); + + // params[1] is the client-provided password. We do not perform + // user authorization, so we ignore this value. + + double mindiff = 0.0; + size_t pos = username.find('+'); + if (pos != std::string::npos) { + // Extract the suffix and trim it + std::string suffix(username, pos+1); + boost::trim_left(suffix); + // Extract the minimum difficulty request + mindiff = boost::lexical_cast(suffix); + // Remove the '+' and everything after + username.resize(pos); + boost::trim_right(username); + } + + CBitcoinAddress addr(get_stripped_username(username)); + + // If given the special address "x", mine to the default address given by -stratumaddress + // This means a miner can run a private pool without TLS and not + // worry about MITM attacks that change addresses, and leaks less metadata. + // It also means many miners can be used and updating their mining address does not + // require any changes on each miner, just restart hushd with a new -stratumaddress + if(addr.ToString() == "x") { + addr = CBitcoinAddress(GetArg("-stratumaddress", "")); + const std::string msg = strprintf("%s: Authorized client with default stratum address=%s", __func__, addr.ToString()); + LogPrint("stratum", "%s\n", msg); + } + + if (!addr.IsValid()) { + const std::string msg = strprintf("%s: Invalid Hush address=%s", __func__, addr.ToString()); + LogPrint("stratum", "%s\n", msg); + throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid Hush address: %s", username)); + } + + client.m_addr = addr; + client.m_mindiff = mindiff; + client.m_authorized = true; + client.m_send_work = true; + + LogPrintf("Authorized stratum miner %s from %s, mindiff=%f\n", addr.ToString(), client.GetPeer().ToString(), mindiff); + + return true; +} + +UniValue stratum_mining_configure(StratumClient& client, const UniValue& params) +{ + const std::string method("mining.configure"); + BoundParams(method, params, 2, 2); + + UniValue res(UniValue::VOBJ); + + UniValue extensions = params[0].get_array(); + UniValue config = params[1].get_obj(); + for (int i = 0; i < extensions.size(); ++i) { + std::string name = extensions[i].get_str(); + + if ("version-rolling" == name) { + uint32_t mask = ParseHexInt4(find_value(config, "version-rolling.mask"), "version-rolling.mask"); + size_t min_bit_count = find_value(config, "version-rolling.min-bit-count").get_int(); + client.m_version_rolling_mask = mask & 0x1fffe000; + res.push_back(Pair("version-rolling", true)); + res.push_back(Pair("version-rolling.mask", HexInt4(client.m_version_rolling_mask))); + LogPrint("stratum", "Received version rolling request from %s\n", client.GetPeer().ToString()); + } + + else { + LogPrint("stratum", "Unrecognized stratum extension '%s' sent by %s\n", name, client.GetPeer().ToString()); + } + } + + return res; +} + +UniValue stratum_mining_submit(StratumClient& client, const UniValue& params) +{ + // {"id": 4, "method": "mining.submit", "params": ["WORKER_NAME", "JOB_ID", "TIME", "NONCE_2", "EQUIHASH_SOLUTION"]}\n + + // NONCE_1 is first part of the block header nonce (in hex). + // By protocol, Zcash's nonce is 32 bytes long. The miner will pick NONCE_2 such that len(NONCE_2) = 32 - len(NONCE_1). Please note that Stratum use hex encoding, so you have to convert NONCE_1 from hex to binary before. + // NONCE_2 is the second part of the block header nonce. + /** + * + * {"method":"mining.submit","params":[ + [0] WORKER_NAME "RDeckerSubnU8QVgrhj27apzUvbVK3pnTk", + [1] JOB_ID "1", + [2] TIME "0eaec560", + [3] NONCE_2 "0000000000000000d890000001000000000000000000000000000000", + [4] EQUIHASH_SOLUTION(1347) "fd400501762fe7c0d228a4b249727f52d85c3d5d989b3f9d07148506820a50e6db2ba3456b4ccfb168d7eb65651c7d7b893d87fb77077b56224a6fc9b9ca283b7a44a25be67d956ee55f9aaeca80eae765076495fd2eb50cf3e279a68dfd15ae6b30e911db6331d6717f352510b5834d3045db3833cdf74d1fe8379ab7b4fe46fe0d855c964085d5779701a25dbcd601ea87fb5d4bbe16c39e9c5fa22c874b4922605ed21411353cef39ce02b954a09961742d8011060a3c45f6b5b316d4a1d75530bd45722945d7a8d4698e75f49b86a485b7f1851b47d10d66d74eebb492c4269d34ca3691a459a80427f79f6d01e469bb250715fc49420d6e87383b598804bdf8b50b8510e44fd0740aa5650ed5ba19543c8657f67b5164d610bbb0ab75da1c48e81e9a8a9861bc119a31c695c5c3530ae271cf9ab4a2fa08d2b4fc851e273c324dc926d6901ca20ba5fed13118f12925760871909e8351d9e944c2959a61bf74238a587dd32826de63ab4819473bb3fad67c9a54baeddd137cb6350a25969531fa055dee51464b36cbdfb6afc4be0cee0f0fe11188c8d70d0238b3ba0c6459cd34d8b7bd8b1cdaa2b7728d51269707a70c54faac778eb4bcb6492e5fcc32406ed87fdfaecc52c9f461af3f4c3c51b529e2ab9a0e15a15b3cdcb35fe3bfe4854952ae975e3171cd2600a54509d386d45ecf668b5a17249b157a13212d0e465bc1796048d63c7b4027cb0850b9607261800e4fe6217e1fba2a28601aec9b524dac787a6c14df668a7c4fabf51f8885be7ed84ca72d0ff9a7491fddae1f5309441d243cb6d5c5c4f45a08b1b858bd15ef4d1ca1565c39000f9298b52e4221723457a0ec2e904aa6cd96e854cd8c1bbd07f1c9237c831d694817227aafe7873c43826e691d3971e82e87b538c42a48603696075b19c72b85c7d20863635621da1939d9024a434f6d840cac7a30058a51650485eabf9c0735163fd9b468249ea5889c62b4f739f58665d7f8c5010a661c1355ea7e9d85b6a18424b0027e86df5aa42b1bc2bb7a38b69c8db620251c4138b69956235640c502e26185d923a045777919984e71558edb77fb54981c6ac3dc979cd0b4f704874f02536daae894da78f31913554f91a30d6badc935fe58cc9d29d152138dde520ddb9906966e077ee3380641ce88fa74a658245202a8183e1807100c3f7d22df6577f309e4d85429e94a6f6f5dbaec3653ca6414bf6ed8794db84b7860be1984cb525b235cdb263cd527c74aa6d336615e1d361f4965ddad1fd191bc4a72fa92acc13a7c92b6e0ee077d70911004f422813e408a49ba38b950ead458b72cacb1ede9e35e2fd002eaaad0ecc2cf62801e4fe010a2cfd7190c51337513f1819acf170dda5f3b23452f36d28c20509a39fedd658f45c5e58a02feb64b0e027e05804350afc3220e53fe1761e93d018f3be9eb3554ecc98fe9fdc584ac06c0dcd63812180e94876f42f2955e242358d590a8b521b641b9729e6c7dcf6164571758ac2b2ee7656f0b0e986abf7f6b569daca304c944ded083ff202a80e8636fe9aeae39707401b321a6094c4a59cc7bcec9852189c746697963f7062304d57335795ec60dd49081a4329d3b1a8c9d55f67d11f36fb54133e67fe8a362a1f8db601aa054d97d3002f898374fd201f10af65393c9c3634e0139551e362da976b7aa0f4f8156aef59620bd24a216663784d205ef5976aa3cf6a9eed571de7cb350a355c35b67c621184608f72357d32d49842e5534f232567ed7ef9a0edc109b3b487e86d1cdd9231969a76e5d7c54bc3e28942e99301a89c13895c2bc5acac2111f53182951183f50c839601dc5fabfd39d95258c79b93a140ab727288179ce1262b13e8cc5a829edf26e7d241fbf6b" + ], + "id":10} + */ + + const std::string method("mining.submit"); + BoundParams(method, params, 5,5); + // First parameter is the client username, which is ignored. + + /* EWBF 31 bytes job_id fix */ + bool fEWBFJobIDFixNeeded = false; + uint256 ret; + if (params[1].isStr()) { + //std::cerr << "\"" << params[1].get_str() << "\"" << std::endl; + const std::string job_id_str = params[1].get_str(); + const std::string hexDigits = "0123456789abcdef"; + // std::cerr << strprintf("\"%s\" (%d)", job_id_str, job_id_str.length()) << std::endl; + if (job_id_str.length() == 63) { + fEWBFJobIDFixNeeded = true; + for(const auto& hexDigit : hexDigits) { + ret = uint256(ParseHex(job_id_str + hexDigit)); + if (work_templates.count(ret)) break; + } + } + } + + uint256 job_id; + if (!fEWBFJobIDFixNeeded) + job_id = ParseUInt256(params[1], "job_id"); + else + job_id = ret; + + // uint256 job_id = ParseUInt256(params[1], "job_id"); + if (!work_templates.count(job_id)) { + LogPrint("stratum", "Received completed share for unknown job_id : %s\n", HexStr(job_id.begin(), job_id.end())); + return false; + } + + StratumWork ¤t_work = work_templates[job_id]; + + uint32_t nTime = bswap_32(ParseHexInt4(params[2], "nTime")); + + std::vector sol = ParseHexV(params[4], "solution"); + if (sol.size() != 1347) { + throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("solution is wrong length (received %d bytes; expected %d bytes", sol.size(), 1347)); + } + + std::vector extranonce1 = client.ExtraNonce1(job_id); + std::vector extranonce2 = ParseHexV(params[3], "extranonce2"); + boost::optional nVersion = 4; // block version always 4 + + SubmitBlock(client, job_id, current_work, extranonce1, extranonce2, nVersion, nTime, sol); + + return true; +} + +UniValue stratum_mining_extranonce_subscribe(StratumClient& client, const UniValue& params) +{ + const std::string method("mining.extranonce.subscribe"); + BoundParams(method, params, 0, 0); + + /*client.m_supports_extranonce = true; + + return true;*/ + client.m_supports_extranonce = false; + + return true; +} + +UniValue stratum_mining_multi_version(StratumClient& client, const UniValue& params) +{ + const std::string method("mining.multi_version"); + BoundParams(method, params, 0, 1); + + /* + Received stratum request from Miner: {"id": 135828, "method": "mining.multi_version", "params": [1]} + Sending stratum response to Miner : {"result":null,"error":{"code":-32601,"message":"Method 'mining.multi_version' not found"},"id":135828} + */ + + return false; +} + + + +/** Callback to write from a stratum connection. */ +static void stratum_write_cb(bufferevent *bev, void *ctx) +{ + /* template */ +} + +/** Callback to read from a stratum connection. */ +static void stratum_read_cb(bufferevent *bev, void *ctx) +{ + evconnlistener *listener = (evconnlistener*)ctx; + LOCK(cs_stratum); + // Lookup the client record for this connection + if (!subscriptions.count(bev)) { + LogPrint("stratum", "Received read notification for unknown stratum connection 0x%x\n", (size_t)bev); + return; + } + StratumClient& client = subscriptions[bev]; + // Get links to the input and output buffers + evbuffer *input = bufferevent_get_input(bev); + assert(input); + evbuffer *output = bufferevent_get_output(bev); + assert(output); + + // Process each line of input that we have received + char *cstr = 0; + size_t len = 0; + while ((cstr = evbuffer_readln(input, &len, EVBUFFER_EOL_CRLF))) { + std::string line(cstr, len); + free(cstr); + LogPrint("stratum", "Received stratum request from %s : %s\n", client.GetPeer().ToString(), line); + + JSONRequest jreq; + + std::string reply; + try { + // Parse request + UniValue valRequest; + if (!valRequest.read(line)) { + // Not JSON; is this even a stratum miner? + throw JSONRPCError(RPC_PARSE_ERROR, strprintf("Invalid JSON, Parse error on: %s",line) ); + } + if (!valRequest.isObject()) { + // Not a JSON object; don't know what to do. + throw JSONRPCError(RPC_PARSE_ERROR, "Not a JSON object"); + } + if (valRequest.exists("result")) { + // JSON-RPC reply. Ignore. + LogPrint("stratum", "Ignoring JSON-RPC response\n"); + continue; + } + jreq.parse(valRequest); + + // Dispatch to method handler + UniValue result = NullUniValue; + if (stratum_method_dispatch.count(jreq.strMethod)) { + result = stratum_method_dispatch[jreq.strMethod](client, jreq.params); + } else { + throw JSONRPCError(RPC_METHOD_NOT_FOUND, strprintf("Method '%s' not found", jreq.strMethod)); + } + + // Compose reply + reply = JSONRPCReply(result, NullUniValue, jreq.id); + } catch (const UniValue& objError) { + reply = JSONRPCReply(NullUniValue, objError, jreq.id); + } catch (const std::exception& e) { + reply = JSONRPCReply(NullUniValue, JSONRPCError(RPC_INTERNAL_ERROR, e.what()), jreq.id); + } + + LogPrint("stratum", "Sending stratum response to %s : %s", client.GetPeer().ToString(), reply); + assert(output); + if (evbuffer_add(output, reply.data(), reply.size())) { + LogPrint("stratum", "Sending stratum response failed. (Reason: %d, '%s')\n", errno, evutil_socket_error_to_string(errno)); + } + } + + // If required, send new work to the client. + if (client.m_send_work) { + std::string data; + try { + data = GetWorkUnit(client); + } catch (const UniValue& objError) { + data = JSONRPCReply(NullUniValue, objError, NullUniValue); + } catch (const std::exception& e) { + data = JSONRPCReply(NullUniValue, JSONRPCError(RPC_INTERNAL_ERROR, e.what()), NullUniValue); + } + + LogPrint("stratum", "Sending requested stratum work unit to %s : %s", client.GetPeer().ToString(), data); + assert(output); + if (evbuffer_add(output, data.data(), data.size())) { + LogPrint("stratum", "Sending stratum work unit failed. (Reason: %d, '%s')\n", errno, evutil_socket_error_to_string(errno)); + } + + client.m_send_work = false; + } +} + +/** Callback to handle unrecoverable errors in a stratum link. */ +static void stratum_event_cb(bufferevent *bev, short what, void *ctx) +{ + evconnlistener *listener = (evconnlistener*)ctx; + LOCK(cs_stratum); + // Fetch the return address for this connection, for the debug log. + std::string from("UNKNOWN"); + if (!subscriptions.count(bev)) { + LogPrint("stratum", "Received event notification for unknown stratum connection 0x%x\n", (size_t)bev); + return; + } else { + from = subscriptions[bev].GetPeer().ToString(); + } + // Report the reason why we are closing the connection. + if (what & BEV_EVENT_ERROR) { + LogPrint("stratum", "Error detected on stratum connection from %s\n", from); + } + if (what & BEV_EVENT_EOF) { + LogPrint("stratum", "Remote disconnect received on stratum connection from %s\n", from); + } + // Remove the connection from our records, and tell libevent to + // disconnect and free its resources. + if (what & (BEV_EVENT_EOF | BEV_EVENT_ERROR)) { + LogPrint("stratum", "Closing stratum connection from %s\n", from); + subscriptions.erase(bev); + if (bev) { + bufferevent_free(bev); + bev = NULL; + } + } +} + +/** Callback to accept a stratum connection. */ +static void stratum_accept_conn_cb(evconnlistener *listener, evutil_socket_t fd, sockaddr *address, int socklen, void *ctx) +{ + // Parse the return address + CService from; + from.SetSockAddr(address); + // Early address-based allow check + + if (!ClientAllowed(stratum_allow_subnets, from)) + { + // evconnlistener_free(listener); + + /* + Here we shouldn't free listener, bcz if somebody will connect on stratum port from + disallowed network -> future connections will be anavailable. + */ + LogPrint("stratum", "Rejected connection from disallowed subnet: %s\n", from.ToString()); + return; + } + + { + LOCK(cs_stratum); + // Should be the same as EventBase(), but let's get it the official way. + event_base *base = evconnlistener_get_base(listener); + // Create a buffer for sending/receiving from this connection. + bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE); + // Disable Nagle's algorithm, so that TCP packets are sent + // immediately, even if it results in a small packet. + int one = 1; + setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*)&one, sizeof(one)); + // Setup the read and event callbacks to handle receiving requests + // from the miner and error handling. A write callback isn't + // needed because we're not sending enough data to fill buffers. + bufferevent_setcb(bev, stratum_read_cb, NULL, stratum_event_cb, (void*)listener); + // Enable bidirectional communication on the connection. + bufferevent_enable(bev, EV_READ|EV_WRITE); + // Record the connection state + subscriptions[bev] = StratumClient(listener, fd, bev, from); + // Log the connection. + LogPrint("stratum", "Accepted stratum connection from %s\n", from.ToString()); + } +} + +/** Setup the stratum connection listening services */ +static bool StratumBindAddresses(event_base* base) +{ + int stratumPort = BaseParams().StratumPort(); + int defaultPort = GetArg("-stratumport", stratumPort); + std::vector > endpoints; + + // Determine what addresses to bind to + if (!mapArgs.count("-stratumallowip")) { // Default to loopback if not allowing external IPs + endpoints.push_back(std::make_pair("::1", defaultPort)); + endpoints.push_back(std::make_pair("127.0.0.1", defaultPort)); + if (mapArgs.count("-stratumbind")) { + LogPrintf("WARNING: option -stratumbind was ignored because -stratumallowip was not specified, refusing to allow everyone to connect\n"); + } + } else if (mapArgs.count("-stratumbind")) { // Specific bind address + const std::vector& vbind = mapMultiArgs["-stratumbind"]; + for (std::vector::const_iterator i = vbind.begin(); i != vbind.end(); ++i) { + int port = defaultPort; + std::string host; + SplitHostPort(*i, port, host); + endpoints.push_back(std::make_pair(host, port)); + } + } else { // No specific bind address specified, bind to any + endpoints.push_back(std::make_pair("::", defaultPort)); + endpoints.push_back(std::make_pair("0.0.0.0", defaultPort)); + } + + // Bind each addresses + for (const auto& endpoint : endpoints) { + LogPrint("stratum", "Binding stratum on address %s port %i\n", endpoint.first, endpoint.second); + // Use CService to translate string -> sockaddr + CNetAddr netaddr; + std::vector vIP; + + LookupHost(endpoint.first.c_str(), vIP, 1, true); + assert(vIP.size() >= 1); + + netaddr = vIP[0]; + + CService socket(netaddr, endpoint.second); + union { + sockaddr ipv4; + sockaddr_in6 ipv6; + } addr; + socklen_t len = sizeof(addr); + socket.GetSockAddr((sockaddr*)&addr, &len); + // Setup an event listener for the endpoint + evconnlistener *listener = evconnlistener_new_bind(base, stratum_accept_conn_cb, NULL, LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1, (sockaddr*)&addr, len); + // Only record successful binds + if (listener) { + bound_listeners[listener] = socket; + } else { + LogPrintf("Binding stratum on address %s port %i failed. (Reason: %d, '%s')\n", endpoint.first, endpoint.second, errno, evutil_socket_error_to_string(errno)); + } + } + + return !bound_listeners.empty(); +} + +/** Watches for new blocks and send updated work to miners. */ +static bool g_shutdown = false; + +void BlockWatcher() +{ + RenameThread("hush-stratum-blkwatcher"); + boost::unique_lock lock(csBestBlock); + boost::system_time checktxtime; + boost::system_time starttime = boost::get_system_time(); + + unsigned int txns_updated_last = 0; + boost::posix_time::time_duration time_passed = boost::posix_time::seconds(0); + bool fRebroadcastAnyway = false; + + if (instance_of_cstratumparams.fstdErrDebugOutput) std::cerr << DateTimeStrPrecise() << __func__ << ": " << __FILE__ << "," << __LINE__ << " time = " << boost::get_system_time() << " checktxtime = " << checktxtime << std::endl; + while (true) { // (A) + /* This will execute before waiting of cvBlockChange */ + + if (instance_of_cstratumparams.fstdErrDebugOutput) std::cerr << DateTimeStrPrecise() << __func__ << ": " << __FILE__ << "," << __LINE__ << " time = " << boost::get_system_time() << " checktxtime = " << checktxtime << std::endl; + checktxtime = boost::get_system_time() + boost::posix_time::seconds(txMemPoolCheckTimeout); + // - time_passed + if (instance_of_cstratumparams.fstdErrDebugOutput) std::cerr << DateTimeStrPrecise() << __func__ << ": " << __FILE__ << "," << __LINE__ << " time = " << boost::get_system_time() << " checktxtime = " << checktxtime << std::endl; + + if (!cvBlockChange.timed_wait(lock, checktxtime)) { + // Timeout: Check to see if mempool was updated. + + /* This will execute after txMemPoolCheckTimeout seconds */ + unsigned int txns_updated_next = mempool.GetTransactionsUpdated(); + + if (instance_of_cstratumparams.fstdErrDebugOutput) std::cerr << DateTimeStrPrecise() << __func__ << ": " << __FILE__ << "," << __LINE__ << ColorTypeNames[cl_WHT] << " seconds_passed = " << (boost::get_system_time() - starttime) << ColorTypeNames[cl_N] << " txns_updated_last = " << txns_updated_last << " txns_updated_next = " << txns_updated_next << std::endl; + time_passed = boost::posix_time::time_duration(boost::get_system_time() - starttime); + + if ((boost::get_system_time() - starttime) < boost::posix_time::seconds(jobRebroadcastTimeout)) { + if (instance_of_cstratumparams.fstdErrDebugOutput) std::cerr << DateTimeStrPrecise() << "seconds_passed < jobRebroadcastTimeout" << std::endl; + fRebroadcastAnyway = false; + if (txns_updated_last == txns_updated_next) continue; // (A) + } else { + if (instance_of_cstratumparams.fstdErrDebugOutput) std::cerr << DateTimeStrPrecise() << ColorTypeNames[cl_GRN] << "Force update work!"<< ColorTypeNames[cl_N] << " seconds_passed >= jobRebroadcastTimeout" << std::endl; + // in case of rebroadcast we should "emulate" that everything is changed and clients must go for new work + mempool.AddTransactionsUpdated(1); + for (auto& subscription : subscriptions) { + subscription.second.m_last_tip = (subscription.second.m_last_tip ? nullptr : chainActive.Tip()); + } + fRebroadcastAnyway = true; + starttime += boost::posix_time::seconds(jobRebroadcastTimeout); + } + + if (instance_of_cstratumparams.fstdErrDebugOutput) std::cerr << DateTimeStrPrecise() << __func__ << ": " << __FILE__ << "," << __LINE__ << std::endl; + txns_updated_last = txns_updated_next; + } + + /* This will excute after wait cvBlockChange will completed, or if 'timeout branch' will allow + execution goes here (mean, if it will not use condition with `continue`) */ + + if (instance_of_cstratumparams.fstdErrDebugOutput) std::cerr << DateTimeStrPrecise() << __func__ << ": " << __FILE__ << "," << __LINE__ << " time = " << boost::get_system_time() << " checktxtime = " << checktxtime << std::endl; + + if (g_shutdown) { + break; + } + + // Either new block, or updated transactions. Either way, + // send updated work to miners. + { + LOCK(cs_stratum); + for (auto& subscription : subscriptions) { + + bufferevent* bev = subscription.first; + + if (!bev) + continue; + evbuffer *output = bufferevent_get_output(bev); + if (!output) + continue; + + StratumClient& client = subscription.second; + // Ignore clients that aren't authorized yet. + if (!client.m_authorized && client.m_aux_addr.empty()) { + continue; + } + // Ignore clients that are already working on the new block. + // Typically this is just the miner that found the block, who was + // immediately sent a work update. This check avoids sending that + // work notification again, moments later. Due to race conditions + // there could be more than one miner that have already received an + // update, however. + if (!fRebroadcastAnyway && client.m_last_tip == chainActive.Tip()) { + continue; + } + + if (instance_of_cstratumparams.fstdErrDebugOutput) std::cerr << DateTimeStrPrecise() << __func__ << ": " << __FILE__ << "," << __LINE__ << " time = " << boost::get_system_time() << " checktxtime = " << checktxtime << std::endl; + + // Get new work + std::string data; + try { + data = GetWorkUnit(client); + } catch (const UniValue& objError) { + data = JSONRPCReply(NullUniValue, objError, NullUniValue); + } catch (const std::exception& e) { + // Some sort of error. Ignore. + std::string msg = strprintf("Error generating updated work for stratum client: %s", e.what()); + LogPrint("stratum", "%s\n", msg); + data = JSONRPCReply(NullUniValue, JSONRPCError(RPC_INTERNAL_ERROR, msg), NullUniValue); + } + // Send the new work to the client + + assert(output); + if (evbuffer_add(output, data.data(), data.size())) { + LogPrint("stratum", "Sending stratum work unit failed. (Reason: %d, '%s')\n", errno, evutil_socket_error_to_string(errno)); + } + } + } + + if (instance_of_cstratumparams.fstdErrDebugOutput) std::cerr << DateTimeStrPrecise() << __func__ << ": " << __FILE__ << "," << __LINE__ << " time = " << boost::get_system_time() << " checktxtime = " << checktxtime << std::endl; + } +} + +void SendKeepAlivePackets() +{ + RenameThread("hush-stratum-keepalive"); + while (true) { + // Run the notifier on an integer second in the steady clock. + auto now = std::chrono::steady_clock::now().time_since_epoch(); + auto nextFire = std::chrono::duration_cast( + now + std::chrono::seconds(10)); + std::this_thread::sleep_until( + std::chrono::time_point(nextFire)); + + boost::this_thread::interruption_point(); + + // Either new block, or updated transactions. Either way, + // send updated work to miners. + for (auto& subscription : subscriptions) { + bufferevent* bev = subscription.first; + + if (!bev) + continue; + evbuffer *output = bufferevent_get_output(bev); + if (!output) + continue; + evbuffer *input = bufferevent_get_input(bev); + if (!input) + continue; + + StratumClient& client = subscription.second; + + if (instance_of_cstratumparams.fstdErrDebugOutput) { + std::cerr << __func__ << ": " << __FILE__ << "," << __LINE__ << std::endl << + "client.m_authorized = " << client.m_authorized << std::endl << + "client.m_aux_addr.size() = " << client.m_aux_addr.size() << std::endl << + "client.m_last_tip = " << strprintf("%p", client.m_last_tip) << std::endl << + (client.m_last_tip ? strprintf("client.m_last_tip->GetHeight() = %d", client.m_last_tip->GetHeight()) : "") << std::endl << + "chainActive.Tip()->GetHeight() = " << chainActive.Tip()->GetHeight() << std::endl << + "client.m_supports_extranonce = " << client.m_supports_extranonce << std::endl << + "client.m_send_work = " << client.m_send_work << std::endl << + std::endl; + } + + // Ignore clients that aren't authorized yet. + if (!client.m_authorized && client.m_aux_addr.empty()) { + continue; + } + + std::string data = "\r\n"; + // to see the socket / connection is alive, we will see bunch of + // JSON decode failed(1): '[' or '{' expected near end of file + // on client if will send "\r\n" every second + + assert(output); + if (evbuffer_add(output, data.data(), data.size())) { + LogPrint("stratum", "Sending stratum keepalive unit failed. (Reason: %d, '%s')\n", errno, evutil_socket_error_to_string(errno)); + } + + if ( (client.m_last_tip && client.m_last_tip->GetHeight() == chainActive.Tip()->GetHeight()) || (!client.m_last_tip) ) + { + LOCK(cs_stratum); + std::cerr << DateTimeStrPrecise() << "\033[31m" << client.m_from.ToString() << "\033[0m seems stucked (ccminer issue), need to emulate new block incoming to unstuck!" << std::endl; + mempool.AddTransactionsUpdated(1); + client.m_last_tip = (client.m_last_tip ? nullptr : chainActive.Tip()); + client.m_nextid++; + cvBlockChange.notify_all(); // change the state of all threads waiting on *this to ready + // cvBlockChange.notify_one(); // if there is a thread waiting on *this, change that thread state to ready + } + } + + } + +} + +/** Configure the Hush stratum server */ +bool InitStratumServer() +{ + LOCK(cs_stratum); + + int stratumPort = BaseParams().StratumPort(); + int defaultPort = GetArg("-stratumport", stratumPort); + fprintf(stderr,"%s: Starting built-in stratum server on port %d\n",__func__, defaultPort ); + + + if (!InitStratumAllowList(stratum_allow_subnets)) { + LogPrint("stratum", "Unable to bind stratum server to an endpoint.\n"); + return false; + } + + std::string strAllowed; + for(const CSubNet& subnet : stratum_allow_subnets) + strAllowed += subnet.ToString() + " "; + LogPrint("stratum", "Allowing Stratum connections from: %s\n", strAllowed); + + event_base* base = EventBase(); + if (!base) { + LogPrint("stratum", "No event_base object, cannot setup stratum server.\n"); + return false; + } + + if (!StratumBindAddresses(base)) { + LogPrintf("Unable to bind any endpoint for stratum server\n"); + } else { + LogPrint("stratum", "Initialized stratum server\n"); + } + + stratum_method_dispatch["mining.subscribe"] = stratum_mining_subscribe; + stratum_method_dispatch["mining.authorize"] = stratum_mining_authorize; + stratum_method_dispatch["mining.configure"] = stratum_mining_configure; + stratum_method_dispatch["mining.submit"] = stratum_mining_submit; + stratum_method_dispatch["mining.extranonce.subscribe"] = stratum_mining_extranonce_subscribe; + stratum_method_dispatch["mining.multi_version"] = stratum_mining_multi_version; + + + // Start thread to wait for block notifications and send updated + // work to miners. + block_watcher_thread = boost::thread(BlockWatcher); + // block_watcher_thread = boost::thread(SendKeepAlivePackets); + + return true; +} + +/** Interrupt the stratum server connections */ +void InterruptStratumServer() +{ + LOCK(cs_stratum); + // Stop listening for connections on stratum sockets + for (const auto& binding : bound_listeners) { + LogPrint("stratum", "Interrupting stratum service on %s\n", binding.second.ToString()); + evconnlistener_disable(binding.first); + } + // Tell the block watching thread to stop + g_shutdown = true; +} + +/** Cleanup stratum server network connections and free resources. */ +void StopStratumServer() +{ + LOCK(cs_stratum); + /* Tear-down active connections. */ + for (const auto& subscription : subscriptions) { + LogPrint("stratum", "Closing stratum server connection to %s due to process termination\n", subscription.second.GetPeer().ToString()); + bufferevent_free(subscription.first); + } + subscriptions.clear(); + /* Un-bind our listeners from their network interfaces. */ + for (const auto& binding : bound_listeners) { + LogPrint("stratum", "Removing stratum server binding on %s\n", binding.second.ToString()); + evconnlistener_free(binding.first); + } + bound_listeners.clear(); + /* Free any allocated block templates. */ + work_templates.clear(); +} + +/* RPC */ +UniValue rpc_stratum_updatework(const UniValue& params, bool fHelp, const CPubKey& mypk) +{ + if (fHelp || params.size() != 0) + throw std::runtime_error( + "stratum_updatework\n" + "Tries to immediatelly update work on all connected miners.\n" + "\nExamples:\n" + + HelpExampleCli("stratum_updatework", "") + + HelpExampleRpc("stratum_updatework", "") + ); + + UniValue obj(UniValue::VOBJ); + UniValue json_clients(UniValue::VARR); + uint64_t skipped = 0; + + // send updated work to miners + // if (cs_stratum.try_lock()) + { + LOCK(cs_stratum); + for (auto& subscription : subscriptions) { + + bufferevent* bev = subscription.first; + + if (!bev) + continue; + evbuffer *output = bufferevent_get_output(bev); + if (!output) + continue; + evbuffer *input = bufferevent_get_input(bev); + if (!input) + continue; + + StratumClient& client = subscription.second; + + if (instance_of_cstratumparams.fstdErrDebugOutput) { + std::cerr << __func__ << ": " << __FILE__ << "," << __LINE__ << std::endl << + "client.m_authorized = " << client.m_authorized << std::endl << + "client.m_aux_addr.size() = " << client.m_aux_addr.size() << std::endl << + "client.m_last_tip = " << strprintf("%p", client.m_last_tip) << std::endl << + (client.m_last_tip ? strprintf("client.m_last_tip->GetHeight() = %d", client.m_last_tip->GetHeight()) : "") << std::endl << + "chainActive.Tip()->GetHeight() = " << chainActive.Tip()->GetHeight() << std::endl << + "client.m_supports_extranonce = " << client.m_supports_extranonce << std::endl << + "client.m_send_work = " << client.m_send_work << std::endl << + std::endl; + } + + // Ignore clients that aren't authorized yet. + if (!client.m_authorized && client.m_aux_addr.empty()) { + fprintf(stderr,"%s: Ignoring unauthorized client\n", __func__); + continue; + } + + if ( (client.m_last_tip && client.m_last_tip->GetHeight() == chainActive.Tip()->GetHeight()) || (!client.m_last_tip) ) + { + mempool.AddTransactionsUpdated(1); + client.m_last_tip = (client.m_last_tip ? nullptr : chainActive.Tip()); + cvBlockChange.notify_all(); + } + + std::string data = ""; + + try { + data = GetWorkUnit(client); + + UniValue json_client(UniValue::VOBJ); + json_client.push_back(Pair("addr", client.m_addr.ToString())); + json_client.push_back(Pair("service", client.m_from.ToString())); + + json_clients.push_back(json_client); + + } catch (const UniValue& objError) { + data = JSONRPCReply(NullUniValue, objError, NullUniValue); + skipped++; + } catch (const std::exception& e) { + // Some sort of error. Ignore. + std::string msg = strprintf("Error generating updated work for stratum client: %s", e.what()); + LogPrint("stratum", "%s\n", msg); + data = JSONRPCReply(NullUniValue, JSONRPCError(RPC_INTERNAL_ERROR, msg), NullUniValue); + skipped++; + } + + assert(output); + if (evbuffer_add(output, data.data(), data.size())) { + LogPrint("stratum", "Sending stratum work unit failed. (Reason: %d, '%s')\n", errno, evutil_socket_error_to_string(errno)); + } + } + } + // else { + // throw JSONRPCError(RPC_INTERNAL_ERROR, "Something went wrong, plz try again!"); + // } + + obj.push_back(Pair("clients", json_clients)); + obj.push_back(Pair("updated", json_clients.size())); + obj.push_back(Pair("skipped", skipped)); + obj.push_back(Pair("total", subscriptions.size())); + + return obj; +} + +UniValue rpc_stratum_getdifficulty (const UniValue& params, bool fHelp, const CPubKey& mypk) { + + if (fHelp || params.size() != 0) + throw std::runtime_error( + "stratum_getdifficulty\n" + "Show the current local diff of a stratum port.\n" + "\nExamples:\n" + + HelpExampleCli("stratum_getdifficulty", "") + + HelpExampleRpc("stratum_getdifficulty", "") + ); + + UniValue obj(UniValue::VOBJ); + + arith_uint256 aHashTarget = instance_of_cstratumparams.getTarget(); + std::string strTarget = aHashTarget.GetHex(); + + CBlockIndex tmp_index; + tmp_index.nBits = arith_uint256(strTarget).GetCompact(); + double hush_diff = GetDifficulty(&tmp_index); + double ccminer_diff = ccminer::equi_stratum_target_to_diff(strTarget); + + obj.push_back(Pair("target", strTarget)); + obj.push_back(Pair("target_compact", strprintf("%08x",tmp_index.nBits))); + obj.push_back(Pair("hush_diff_str", strprintf("%g",hush_diff))); + obj.push_back(Pair("ccminer_diff_str", strprintf("%g", ccminer_diff))); + obj.push_back(Pair("hush_diff", hush_diff)); + obj.push_back(Pair("ccminer_diff", ccminer_diff)); + + return obj; +}; + +UniValue rpc_stratum_setdifficulty (const UniValue& params, bool fHelp, const CPubKey& mypk) { + + /* + https://bitcoin.stackexchange.com/questions/30467/what-are-the-equations-to-convert-between-bits-and-difficulty + + There are 3 representations of the same thing (with varying degrees of precision) in Bitcoin: + + - bits - unsigned int 32-bit + - target - unsigned int 256-bit + - difficulty - double-precision float (64-bit) + + and 6 methods are necessary to convert between any two of these: + + - bits -> target (SetCompact() in bitcoin/src/arith_uint256.cpp) + - bits -> difficulty (GetDifficulty() in bitcoin/src/rpc/blockchain.cpp) + - target -> bits (GetCompact() in bitcoin/src/arith_uint256.cpp) + - target -> difficulty (same as target -> bits -> difficulty) + - difficulty -> bits (not done in bitcoin/src) -> we will use hush_diff_to_target_equi for that + - difficulty -> target (same as difficulty -> bits -> target) + */ + if (fHelp || params.size() != 1) + throw std::runtime_error( + "stratum_setdifficulty\n" + "Set the diff on a stratum port.\n" + "\nExamples:\n" + + HelpExampleCli("stratum_setdifficulty", "") + + HelpExampleRpc("stratum_setdifficulty", "") + ); + + // diff can be accepted in two ways: as a hex target or as a hush_diff, both variants assume + // passing a string with 32 bytes hex target or string (!) with a double value, or double + // value as a double + + double hush_diff; // calculated value: diff_str -> hush_diff + std::string diff_str = instance_of_cstratumparams.getTarget().ToString(); + + if (params[0].getType() == UniValue::VSTR) { + std::string param_str = params[0].get_str(); + if (IsHex(param_str) && param_str.size() == 64) { + // hex target passed + diff_str = param_str; + + } else { + if (ParseDouble(param_str, &hush_diff)) { + // kmd diff as a str passed + + // difficulty = difficulty_1_target / current_target + arith_uint256 target; + ccminer::hush_diff_to_target_equi((uint32_t *)&target, hush_diff); + diff_str = target.ToString(); + + } else + throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid difficulty (not hex target, not hush_diff)"); + } + } else if (params[0].getType() == UniValue::VNUM) { + // kmd diff as a num passed + hush_diff = params[0].get_real(); + + // difficulty = difficulty_1_target / current_target + arith_uint256 target; + ccminer::hush_diff_to_target_equi((uint32_t *)&target, hush_diff); + diff_str = target.ToString(); + + } else + throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid difficulty"); + + instance_of_cstratumparams.setTarget(arith_uint256(diff_str)); + + UniValue obj(UniValue::VOBJ); + obj.push_back(Pair("target", diff_str)); + + CBlockIndex tmp_index; + tmp_index.nBits = arith_uint256(diff_str).GetCompact(); + + double new_hush_diff = GetDifficulty(&tmp_index); + obj.push_back(Pair("hush_diff_str", strprintf("%g",new_hush_diff))); + obj.push_back(Pair("hush_diff", new_hush_diff)); + + return obj; +}; + +UniValue rpc_stratum_getclientscount (const UniValue& params, bool fHelp, const CPubKey& mypk) { + + if (fHelp || params.size() != 0) + throw std::runtime_error( + "stratum_getclientscount\n" + "Show the the number of stratum clients.\n" + "\nExamples:\n" + + HelpExampleCli("stratum_getclientscount", "") + + HelpExampleRpc("stratum_getclientscount", "") + ); + + UniValue obj(UniValue::VOBJ); + obj.push_back(Pair("total", subscriptions.size())); + + return obj; +}; + +static const CRPCCommand commands[] = +{ // category name actor (function) okSafeMode + // --------------------- ------------------------ ----------------------- ---------- + { "stratum", "stratum_updatework", &rpc_stratum_updatework, true }, + { "stratum", "stratum_getdifficulty", &rpc_stratum_getdifficulty, true }, + { "stratum", "stratum_setdifficulty", &rpc_stratum_setdifficulty, true }, + { "stratum", "stratum_getclientscount", &rpc_stratum_getclientscount, true }, +}; + +void RegisterStratumRPCCommands(CRPCTable &tableRPC) +{ + for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) + tableRPC.appendCommand(commands[vcidx].name, &commands[vcidx]); +} + +// End of File diff --git a/src/stratum.h b/src/stratum.h new file mode 100644 index 000000000..56dc52056 --- /dev/null +++ b/src/stratum.h @@ -0,0 +1,21 @@ +// Copyright (c) 2021-2021 The Hush developers +// Copyright (c) 2020-2021 The Freicoin Developers +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#ifndef HUSH_STRATUM_H +#define HUSH_STRATUM_H + +/** Configure the stratum server. */ +bool InitStratumServer(); + +/** Interrupt the stratum server connections. */ +void InterruptStratumServer(); + +/** Cleanup stratum server network connections and free resources. */ +void StopStratumServer(); + +#endif // HUSH_STRATUM_H + +// End of File diff --git a/src/test-hush/test_addrman.cpp b/src/test-hush/test_addrman.cpp index afded7393..29d5fc319 100644 --- a/src/test-hush/test_addrman.cpp +++ b/src/test-hush/test_addrman.cpp @@ -2,16 +2,13 @@ // Distributed under the GPLv3 software license, see the accompanying // file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html #include - #include "addrman.h" #include #include #include - #include "hash.h" #include "random.h" #include "util/asmap.h" - #include "netbase.h" #include "chainparams.h" #include "tinyformat.h" @@ -51,7 +48,7 @@ class TestCout : public std::stringstream using namespace std; -/* xxd -i est-komodo/data/asmap.raw | sed 's/unsigned char/static unsigned const char/g' */ +/* xxd -i test-hush/data/asmap.raw | sed 's/unsigned char/static unsigned const char/g' */ static unsigned const char asmap_raw[] = { 0xfb, 0x03, 0xec, 0x0f, 0xb0, 0x3f, 0xc0, 0xfe, 0x00, 0xfb, 0x03, 0xec, 0x0f, 0xb0, 0x3f, 0xc0, 0xfe, 0x00, 0xfb, 0x03, 0xec, 0x0f, 0xb0, 0xff, diff --git a/src/test-hush/test_eval_notarization.cpp b/src/test-hush/test_eval_notarization.cpp index c0c1c6751..d42327718 100644 --- a/src/test-hush/test_eval_notarization.cpp +++ b/src/test-hush/test_eval_notarization.cpp @@ -3,7 +3,6 @@ // file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html #include #include - #include "cc/betprotocol.h" #include "cc/eval.h" #include "base58.h" @@ -14,16 +13,12 @@ #include "primitives/transaction.h" #include "script/interpreter.h" #include "script/serverchecker.h" - #include "testutils.h" - extern int32_t hush_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp); - namespace TestEvalNotarization { - class EvalMock : public Eval { public: @@ -86,7 +81,6 @@ namespace TestEvalNotarization { } - // https://kmd.explorer.supernet.org/tx/5b8055d37cff745a404d1ae45e21ffdba62da7b28ed6533c67468d7379b20bae // inputs have been dropped static auto rawNotaryTx = "01000000000290460100000000002321020e46e79a2a8d12b9b5d12c7a91adb4e454edfae43c0a0cb805427d2ac7613fd9ac0000000000000000506a4c4dae8e0f3e6e5de498a072f5967f3c418c4faba5d56ac8ce17f472d029ef3000008f2e0100424f545300050ba773f0bc31da5839fc7cb9bd7b87f3b765ca608e5cf66785a466659b28880500000000000000"; CTransaction notaryTx; @@ -201,6 +195,4 @@ TEST(TestEvalNotarization, testInvalidNotarizationInputNotCheckSig) ASSERT_FALSE(eval.GetNotarizationData(notary.GetHash(), data)); } - - } /* namespace TestEvalNotarization */ diff --git a/src/test-hush/test_parse_notarization.cpp b/src/test-hush/test_parse_notarization.cpp index 5f7549071..655c6d5b6 100644 --- a/src/test-hush/test_parse_notarization.cpp +++ b/src/test-hush/test_parse_notarization.cpp @@ -2,14 +2,11 @@ // Distributed under the GPLv3 software license, see the accompanying // file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html #include - #include "cc/eval.h" #include "core_io.h" #include "key.h" - #include "testutils.h" - namespace TestParseNotarization { class TestParseNotarization : public ::testing::Test, public Eval {}; @@ -52,6 +49,6 @@ TEST(TestParseNotarization, test__b) -// for l in `g 'parse notarisation' ~/.komodo/debug.log | pyline 'l.split()[8]'`; do hoek decodeTx '{"hex":"'`src/komodo-cli getrawtransaction "$l"`'"}' | jq '.outputs[1].script.op_return' | pyline 'import base64; print base64.b64decode(l).encode("hex")'; done +// for l in `g 'parse notarisation' ~/.hush/HUSH3/debug.log | pyline 'l.split()[8]'`; do hoek decodeTx '{"hex":"'`src/hush-cli getrawtransaction "$l"`'"}' | jq '.outputs[1].script.op_return' | pyline 'import base64; print base64.b64decode(l).encode("hex")'; done } diff --git a/src/transaction_builder.cpp b/src/transaction_builder.cpp index c17051ff9..3ff6269b2 100644 --- a/src/transaction_builder.cpp +++ b/src/transaction_builder.cpp @@ -59,6 +59,13 @@ void TransactionBuilder::AddSaplingOutput( mtx.valueBalance -= value; } +// randomize the order of outputs +void TransactionBuilder::ShuffleOutputs() +{ + LogPrintf("%s: Shuffling %d zouts\n", __func__, outputs.size() ); + random_shuffle( outputs.begin(), outputs.end(), GetRandInt ); +} + void TransactionBuilder::AddTransparentInput(COutPoint utxo, CScript scriptPubKey, CAmount value, uint32_t _nSequence) { if (keystore == nullptr) { @@ -212,6 +219,9 @@ boost::optional TransactionBuilder::Build() mtx.vShieldedSpend.push_back(sdesc); } + // Prevent leaking metadata about the position of change output + ShuffleOutputs(); + // Create Sapling OutputDescriptions for (auto output : outputs) { auto cm = output.note.cm(); diff --git a/src/transaction_builder.h b/src/transaction_builder.h index dba7e7b43..89a8d6580 100644 --- a/src/transaction_builder.h +++ b/src/transaction_builder.h @@ -92,6 +92,8 @@ public: CAmount value, std::array memo = {{0}}); + void ShuffleOutputs(); + // Assumes that the value correctly corresponds to the provided UTXO. void AddTransparentInput(COutPoint utxo, CScript scriptPubKey, CAmount value, uint32_t nSequence = 0xffffffff); diff --git a/src/txdb.cpp b/src/txdb.cpp index e6b82332a..15f2b99cc 100644 --- a/src/txdb.cpp +++ b/src/txdb.cpp @@ -429,23 +429,8 @@ bool getAddressFromIndex(const int &type, const uint160 &hash, std::string &addr uint32_t hush_segid32(char *coinaddr); #define DECLARE_IGNORELIST std::map ignoredMap = { \ - {"RReUxSs5hGE39ELU23DfydX8riUuzdrHAE", 1}, \ - {"RMUF3UDmzWFLSKV82iFbMaqzJpUnrWjcT4", 1}, \ - {"RA5imhVyJa7yHhggmBytWuDr923j2P1bxx", 1}, \ - {"RBM5LofZFodMeewUzoMWcxedm3L3hYRaWg", 1}, \ - {"RAdcko2d94TQUcJhtFHZZjMyWBKEVfgn4J", 1}, \ - {"RLzUaZ934k2EFCsAiVjrJqM8uU1vmMRFzk", 1}, \ - {"RMSZMWZXv4FhUgWhEo4R3AQXmRDJ6rsGyt", 1}, \ - {"RUDrX1v5toCsJMUgtvBmScKjwCB5NaR8py", 1}, \ - {"RMSZMWZXv4FhUgWhEo4R3AQXmRDJ6rsGyt", 1}, \ - {"RRvwmbkxR5YRzPGL5kMFHMe1AH33MeD8rN", 1}, \ - {"RQLQvSgpPAJNPgnpc8MrYsbBhep95nCS8L", 1}, \ - {"RK8JtBV78HdvEPvtV5ckeMPSTojZPzHUTe", 1}, \ - {"RHVs2KaCTGUMNv3cyWiG1jkEvZjigbCnD2", 1}, \ - {"RE3SVaDgdjkRPYA6TRobbthsfCmxQedVgF", 1}, \ - {"RW6S5Lw5ZCCvDyq4QV9vVy7jDHfnynr5mn", 1}, \ - {"RTkJwAYtdXXhVsS3JXBAJPnKaBfMDEswF8", 1}, \ - {"RD6GgnrMpPaTSMn8vai6yiGA7mN4QGPVMY", 1} \ + {"RUeUxSs5hGE39ELU23DfydX8riUuzdrHAE", 1}, \ + {"R2d2gnrMpPaTSMn8vai6yiGA7mN4QGPVMY", 1} \ }; bool CBlockTreeDB::Snapshot2(std::map &addressAmounts, UniValue *ret) @@ -662,7 +647,7 @@ bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) { return true; } -void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height); +void hush_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height); bool CBlockTreeDB::blockOnchainActive(const uint256 &hash) { BlockMap::const_iterator it = mapBlockIndex.find(hash); @@ -738,7 +723,7 @@ bool CBlockTreeDB::LoadBlockIndexGuts() if ( 0 ) // POW will be checked before any block is connected { uint8_t pubkey33[33]; - komodo_index2pubkey33(pubkey33,pindexNew,pindexNew->GetHeight()); + hush_index2pubkey33(pubkey33,pindexNew,pindexNew->GetHeight()); if (!CheckProofOfWork(header,pubkey33,pindexNew->GetHeight(),Params().GetConsensus())) return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString()); } diff --git a/src/txmempool.cpp b/src/txmempool.cpp index b780d15d6..4c30fdfcb 100644 --- a/src/txmempool.cpp +++ b/src/txmempool.cpp @@ -487,21 +487,7 @@ std::vector CTxMemPool::removeExpired(unsigned int nBlockHeight) // Remove expired txs from the mempool LOCK(cs); list transactionsToRemove; - for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) - { - const CTransaction& tx = it->GetTx(); - tipindex = chainActive.LastTip(); - /* - bool fInterestNotValidated = SMART_CHAIN_SYMBOL[0] == 0 && tipindex != 0 && komodo_validate_interest(tx,tipindex->GetHeight()+1,tipindex->GetMedianTimePast() + 777,0) < 0; - if (IsExpiredTx(tx, nBlockHeight) || fInterestNotValidated) - { - if (fInterestNotValidated && tipindex != 0) - LogPrintf("Removing interest violate txid.%s nHeight.%d nTime.%u vs locktime.%u\n",tx.GetHash().ToString(),tipindex->GetHeight()+1,tipindex->GetMedianTimePast() + 777,tx.nLockTime); - transactionsToRemove.push_back(tx); - } - */ - } std::vector ids; for (const CTransaction& tx : transactionsToRemove) { list removed; diff --git a/src/util.cpp b/src/util.cpp index 71152f2bd..a2940a0a3 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -497,17 +497,42 @@ boost::filesystem::path GetDefaultDataDir() if ( SMART_CHAIN_SYMBOL[0] != 0 ) strcpy(symbol,SMART_CHAIN_SYMBOL); else symbol[0] = 0; + // OLD NAMES: // Windows < Vista: C:\Documents and Settings\Username\Application Data\Komodo // Windows >= Vista: C:\Users\Username\AppData\Roaming\Komodo // Mac: ~/Library/Application Support/Komodo // Unix: ~/.komodo + + // NEW NAMES: + // Windows < Vista: C:\Documents and Settings\Username\Application Data\Hush + // Windows >= Vista: C:\Users\Username\AppData\Roaming\Hush + // Mac: ~/Library/Application Support/Hush + // Unix: ~/.hush + + // ~/.hush was actually used by the original 1.x version of Hush, but we will + // only make subdirectories inside of it, so we won't be able to overwrite + // an old wallet.dat from the Ice Ages :) + + fs::path pathRet; #ifdef _WIN32 // Windows - if ( symbol[0] == 0 ) - return GetSpecialFolderPath(CSIDL_APPDATA) / "Komodo"; - else return GetSpecialFolderPath(CSIDL_APPDATA) / "Komodo" / symbol; + pathRet = GetSpecialFolderPath(CSIDL_APPDATA) / "Hush" / symbol; + // Always use .hush/HUSH3, if it exists (even if .komodo/HUSH3 exists) + if(fs::is_directory(pathRet)) { + return pathRet; + } else { + pathRet = GetSpecialFolderPath(CSIDL_APPDATA) / "Komodo" / symbol; + if(fs::is_directory(pathRet)) { + // existing legacy directory, use that for backward compat + return pathRet; + } else { + // For new clones, use Hush/HUSH3 + pathRet = GetSpecialFolderPath(CSIDL_APPDATA) / "Hush" / symbol; + return pathRet; + } + } + return pathRet; #else - fs::path pathRet; char* pszHome = getenv("HOME"); if (pszHome == NULL || strlen(pszHome) == 0) pathRet = fs::path("/"); @@ -517,19 +542,49 @@ boost::filesystem::path GetDefaultDataDir() // Mac pathRet /= "Library/Application Support"; TryCreateDirectory(pathRet); - if ( symbol[0] == 0 ) - return pathRet / "Komodo"; - else - { - pathRet /= "Komodo"; - TryCreateDirectory(pathRet); - return pathRet / symbol; + fs::path tmppath; + tmppath = pathRet; + tmppath /= "Hush"; + + // create Library/Application Support/Hush if it doesn't exist + TryCreateDirectory(tmppath); + + // Always use Hush/HUSH3 if it exists + if(fs::is_directory(tmppath / symbol)) { + return tmppath / symbol; + } else { + // Check for legacy dir + tmppath = pathRet; + tmppath /= "Komodo"; + //TryCreateDirectory(tmppath); + if(fs::is_directory( tmppath / symbol) { + // Found legacy dir, use that + return tmppath / symbol; + } else { + // For new clones, use Hush/HUSH3 + tmppath = pathRet / "Hush" / HUSH3; + } + return tmppath; } #else // Unix - if ( symbol[0] == 0 ) - return pathRet / ".komodo"; - else return pathRet / ".komodo" / symbol; + // New directory :) + fs::path tmppath = pathRet / ".hush" / symbol; + // Always use .hush/HUSH3, if it exists (even if .komodo/HUSH3 exists) + if(fs::is_directory(tmppath)) { + return tmppath; + } else { + // This is the legacy location + tmppath = pathRet / ".komodo" / symbol; + if(fs::is_directory(tmppath)) { + // existing legacy directory, use that for backward compat + return tmppath; + } else { + // For new clones, use .hush/HUSH3 + tmppath = pathRet / ".hush" / symbol; + } + return tmppath; + } #endif #endif } @@ -638,8 +693,6 @@ const boost::filesystem::path &GetDataDir(bool fNetSpecific) path /= BaseParams().DataDir(); fs::create_directories(path); - //std::string assetpath = path + "/assets"; - //boost::filesystem::create_directory(assetpath); return path; } @@ -652,15 +705,10 @@ void ClearDatadirCache() boost::filesystem::path GetConfigFile() { char confname[512]; - if ( SMART_CHAIN_SYMBOL[0] != 0 ) + if ( SMART_CHAIN_SYMBOL[0] != 0 ) { sprintf(confname,"%s.conf",SMART_CHAIN_SYMBOL); - else - { -#ifdef __APPLE__ - strcpy(confname,"Komodo.conf"); -#else - strcpy(confname,"komodo.conf"); -#endif + } else { + strcpy(confname,"HUSH3.conf"); } boost::filesystem::path pathConfigFile(GetArg("-conf",confname)); if (!pathConfigFile.is_complete()) @@ -674,14 +722,14 @@ void ReadConfigFile(map& mapSettingsRet, { boost::filesystem::ifstream streamConfig(GetConfigFile()); if (!streamConfig.good()) - throw missing_zcash_conf(); + throw missing_hush_conf(); set setOptions; setOptions.insert("*"); for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it) { - // Don't overwrite existing settings so command line settings override komodo.conf + // Don't overwrite existing settings so command line settings override HUSH3.conf string strKey = string("-") + it->string_key; if (mapSettingsRet.count(strKey) == 0) { diff --git a/src/util.h b/src/util.h index ba2feb38e..7dd63b5bb 100644 --- a/src/util.h +++ b/src/util.h @@ -145,9 +145,9 @@ boost::filesystem::path GetConfigFile(); boost::filesystem::path GetPidFile(); void CreatePidFile(const boost::filesystem::path &path, pid_t pid); #endif -class missing_zcash_conf : public std::runtime_error { +class missing_hush_conf : public std::runtime_error { public: - missing_zcash_conf() : std::runtime_error("Missing komodo.conf") { } + missing_hush_conf() : std::runtime_error(strprintf("Missing %s",GetConfigFile().string() )) { } }; void ReadConfigFile(std::map& mapSettingsRet, std::map >& mapMultiSettingsRet); #ifdef _WIN32 diff --git a/src/version.h b/src/version.h index fde7afc4b..3c8f28347 100644 --- a/src/version.h +++ b/src/version.h @@ -21,7 +21,7 @@ #define HUSH_VERSION_H // network protocol versioning -static const int PROTOCOL_VERSION = 1987422; +static const int PROTOCOL_VERSION = 1987423; //! initial proto version, to be increased after version/verack negotiation static const int INIT_PROTO_VERSION = 209; //! In this version, 'getheaders' was introduced. diff --git a/src/wallet-utility.cpp b/src/wallet-utility.cpp index 32dad9c42..a82dfa3b7 100644 --- a/src/wallet-utility.cpp +++ b/src/wallet-utility.cpp @@ -13,7 +13,7 @@ char SMART_CHAIN_SYMBOL[HUSH_SMART_CHAIN_MAXLEN]; int64_t MAX_MONEY = 200000000 * 100000000LL; uint64_t ASSETCHAINS_SUPPLY; -uint16_t BITCOIND_RPCPORT = 7771; +uint16_t BITCOIND_RPCPORT = 18031; uint16_t ASSETCHAINS_P2PPORT,ASSETCHAINS_RPCPORT; uint32_t ASSETCHAIN_INIT,ASSETCHAINS_CC; uint32_t ASSETCHAINS_MAGIC = 2387029918; diff --git a/src/wallet/asyncrpcoperation_sendmany.cpp b/src/wallet/asyncrpcoperation_sendmany.cpp index 04d700c44..762d50021 100644 --- a/src/wallet/asyncrpcoperation_sendmany.cpp +++ b/src/wallet/asyncrpcoperation_sendmany.cpp @@ -194,9 +194,11 @@ bool AsyncRPCOperation_sendmany::main_impl() { assert(isfromtaddr_ != isfromzaddr_); + /* TODO: this needs to allow DPoW addresses. Consensus-time checks do it correctly. if(t_outputs_.size() > 0) { throw JSONRPCError(RPC_WALLET_ERROR, "Extreme Privacy! You cannot send to a transparent address."); } + */ bool isSingleZaddrOutput = (t_outputs_.size()==0 && z_outputs_.size()==1); bool isMultipleZaddrOutput = (t_outputs_.size()==0 && z_outputs_.size()>=1); diff --git a/src/wallet/asyncrpcoperation_shieldcoinbase.cpp b/src/wallet/asyncrpcoperation_shieldcoinbase.cpp index e432ffdb0..a4d4857e0 100644 --- a/src/wallet/asyncrpcoperation_shieldcoinbase.cpp +++ b/src/wallet/asyncrpcoperation_shieldcoinbase.cpp @@ -46,6 +46,7 @@ using namespace libzcash; extern uint64_t ASSETCHAINS_TIMELOCKGTE; +extern string randomSietchZaddr(); AsyncRPCOperation_shieldcoinbase::AsyncRPCOperation_shieldcoinbase( TransactionBuilder builder, @@ -229,6 +230,17 @@ bool ShieldToAddress::operator()(const libzcash::SaplingPaymentAddress &zaddr) c // Send all value to the target z-addr m_op->builder_.SendChangeTo(zaddr, ovk); + // Sietchified Shielding of Coinbase Funds + // Add Sietch zouts so it's unclear which zout contains value :) + // This reduces metadata leakage of coinbase t=>z tx's + CAmount amount = 0; + auto zdust1 = DecodePaymentAddress(randomSietchZaddr()); + auto zdust2 = DecodePaymentAddress(randomSietchZaddr()); + auto sietchZout1 = boost::get(zdust1); + auto sietchZout2 = boost::get(zdust2); + m_op->builder_.AddSaplingOutput(ovk, sietchZout1, amount); + m_op->builder_.AddSaplingOutput(ovk, sietchZout2, amount); + // Build the transaction auto maybe_tx = m_op->builder_.Build(); if (!maybe_tx) { diff --git a/src/wallet/db.cpp b/src/wallet/db.cpp index d9d1312a9..ec312a6d0 100644 --- a/src/wallet/db.cpp +++ b/src/wallet/db.cpp @@ -1,8 +1,8 @@ // Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers +// Copyright (c) 2016-2021 The Hush developers // Distributed under the GPLv3 software license, see the accompanying // file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html - /****************************************************************************** * Copyright © 2014-2019 The SuperNET Developers. * * * @@ -19,13 +19,11 @@ ******************************************************************************/ #include "db.h" - #include "addrman.h" #include "hash.h" #include "protocol.h" #include "util.h" #include "utilstrencodings.h" - #include #ifndef _WIN32 @@ -38,13 +36,9 @@ using namespace std; - unsigned int nWalletDBUpdated; - -// // CDB -// CDBEnv bitdb; diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp index 8a5398945..e5a7d2034 100644 --- a/src/wallet/rpcdump.cpp +++ b/src/wallet/rpcdump.cpp @@ -201,7 +201,7 @@ UniValue importprivkey(const UniValue& params, bool fHelp, const CPubKey& mypk) "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "4. height (integer, optional, default=0) start at block height?\n" "5. secret_key (integer, optional, default=188) decimal value used to import WIFs of other coins\n" - "\nNote: This call can take minutes to complete if rescan is true.\n" + "\nNote: This call can take a long time to complete if rescan is true.\n" "\nExamples:\n" "\nDump a private key\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + @@ -295,7 +295,7 @@ UniValue importaddress(const UniValue& params, bool fHelp, const CPubKey& mypk) "1. \"address\" (string, required) The address\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" - "\nNote: This call can take minutes to complete if rescan is true.\n" + "\nNote: This call can take a long time to complete if rescan is true.\n" "\nExamples:\n" "\nImport an address with rescan\n" + HelpExampleCli("importaddress", "\"myaddress\"") + @@ -749,7 +749,7 @@ UniValue z_importkey(const UniValue& params, bool fHelp, const CPubKey& mypk) "1. \"zkey\" (string, required) The zkey (see z_exportkey)\n" "2. rescan (string, optional, default=\"whenkeyisnew\") Rescan the wallet for transactions - can be \"yes\", \"no\" or \"whenkeyisnew\"\n" "3. startHeight (numeric, optional, default=0) Block height to start rescan from\n" - "\nNote: This call can take minutes to complete if rescan is true.\n" + "\nNote: This call can take a long time to complete if rescan is true.\n" "\nExamples:\n" "\nExport a zkey\n" + HelpExampleCli("z_exportkey", "\"myaddress\"") + @@ -841,7 +841,7 @@ UniValue z_importviewingkey(const UniValue& params, bool fHelp, const CPubKey& m "2. rescan (string, optional, default=\"whenkeyisnew\") Rescan the wallet for transactions - can be \"yes\", \"no\" or \"whenkeyisnew\"\n" "3. startHeight (numeric, optional, default=0) Block height to start rescan from\n" "4. zaddr (string, optional, default=\"\") zaddr in case of importing viewing key for Sapling\n" - "\nNote: This call can take minutes to complete if rescan is true.\n" + "\nNote: This call can take a long time to complete if rescan is true.\n" "\nExamples:\n" "\nImport a viewing key\n" + HelpExampleCli("z_importviewingkey", "\"vkey\"") + diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 1b90c56a5..f7cc48433 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -423,6 +423,37 @@ UniValue getaccount(const UniValue& params, bool fHelp, const CPubKey& mypk) return strAccount; } +UniValue listaddresses(const UniValue& params, bool fHelp, const CPubKey& mypk) +{ + if (!EnsureWalletIsAvailable(fHelp)) + return NullUniValue; + + if (fHelp || params.size() != 0) + throw runtime_error( + "listaddresses\n" + "\nResult:\n" + "[ (json array of string)\n" + " \"" + strprintf("%s",hush_chainname()) + "_address\" (string) a " + strprintf("%s",hush_chainname()) + " address\n" + " ,...\n" + "]\n" + "\nExamples:\n" + + HelpExampleCli("listaddresses", "") + + HelpExampleRpc("listaddresses", "") + ); + + LOCK2(cs_main, pwalletMain->cs_wallet); + + string strAccount = AccountFromValue(params[0]); + + // Find all taddrs + UniValue ret(UniValue::VARR); + for (const std::pair& item : pwalletMain->mapAddressBook) { + const CTxDestination& dest = item.first; + const std::string& strName = item.second.name; + ret.push_back(EncodeDestination(dest)); + } + return ret; +} UniValue getaddressesbyaccount(const UniValue& params, bool fHelp, const CPubKey& mypk) { @@ -441,8 +472,8 @@ UniValue getaddressesbyaccount(const UniValue& params, bool fHelp, const CPubKey " ,...\n" "]\n" "\nExamples:\n" - + HelpExampleCli("getaddressesbyaccount", "\"tabby\"") - + HelpExampleRpc("getaddressesbyaccount", "\"tabby\"") + + HelpExampleCli("getaddressesbyaccount", "\"\"") + + HelpExampleRpc("getaddressesbyaccount", "\"\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); @@ -579,25 +610,25 @@ UniValue sendtoaddress(const UniValue& params, bool fHelp, const CPubKey& mypk) #define HUSH_KVDURATION 1440 #define DRAGON_MAXSCRIPTSIZE 10001 uint64_t PAX_fiatdest(uint64_t *seedp,int32_t tokomodo,char *destaddr,uint8_t pubkey37[37],char *coinaddr,int32_t height,char *base,int64_t fiatoshis); -int32_t komodo_opreturnscript(uint8_t *script,uint8_t type,uint8_t *opret,int32_t opretlen); +int32_t hush_opreturnscript(uint8_t *script,uint8_t type,uint8_t *opret,int32_t opretlen); extern int32_t HUSH_PAX; -int32_t komodo_is_issuer(); +int32_t hush_is_issuer(); int32_t dragon_rwnum(int32_t rwflag,uint8_t *serialized,int32_t len,void *endianedp); -int32_t komodo_isrealtime(int32_t *kmdheightp); +int32_t hush_isrealtime(int32_t *kmdheightp); int32_t pax_fiatstatus(uint64_t *available,uint64_t *deposited,uint64_t *issued,uint64_t *withdrawn,uint64_t *approved,uint64_t *redeemed,char *base); -int32_t komodo_kvsearch(uint256 *refpubkeyp,int32_t current_height,uint32_t *flagsp,int32_t *heightp,uint8_t value[DRAGON_MAXSCRIPTSIZE],uint8_t *key,int32_t keylen); -int32_t komodo_kvcmp(uint8_t *refvalue,uint16_t refvaluesize,uint8_t *value,uint16_t valuesize); -uint64_t komodo_kvfee(uint32_t flags,int32_t opretlen,int32_t keylen); -uint256 komodo_kvsig(uint8_t *buf,int32_t len,uint256 privkey); -int32_t komodo_kvduration(uint32_t flags); -uint256 komodo_kvprivkey(uint256 *pubkeyp,char *passphrase); -int32_t komodo_kvsigverify(uint8_t *buf,int32_t len,uint256 _pubkey,uint256 sig); +int32_t hush_kvsearch(uint256 *refpubkeyp,int32_t current_height,uint32_t *flagsp,int32_t *heightp,uint8_t value[DRAGON_MAXSCRIPTSIZE],uint8_t *key,int32_t keylen); +int32_t hush_kvcmp(uint8_t *refvalue,uint16_t refvaluesize,uint8_t *value,uint16_t valuesize); +uint64_t hush_kvfee(uint32_t flags,int32_t opretlen,int32_t keylen); +uint256 hush_kvsig(uint8_t *buf,int32_t len,uint256 privkey); +int32_t hush_kvduration(uint32_t flags); +uint256 hush_kvprivkey(uint256 *pubkeyp,char *passphrase); +int32_t hush_kvsigverify(uint8_t *buf,int32_t len,uint256 _pubkey,uint256 sig); UniValue kvupdate(const UniValue& params, bool fHelp, const CPubKey& mypk) { static uint256 zeroes; CWalletTx wtx; UniValue ret(UniValue::VOBJ); - uint8_t keyvalue[DRAGON_MAXSCRIPTSIZE*8],opretbuf[DRAGON_MAXSCRIPTSIZE*8]; int32_t i,coresize,haveprivkey,duration,opretlen,height; uint16_t keylen=0,valuesize=0,refvaluesize=0; uint8_t *key,*value=0; uint32_t flags,tmpflags,n; struct komodo_kv *ptr; uint64_t fee; uint256 privkey,pubkey,refpubkey,sig; + uint8_t keyvalue[DRAGON_MAXSCRIPTSIZE*8],opretbuf[DRAGON_MAXSCRIPTSIZE*8]; int32_t i,coresize,haveprivkey,duration,opretlen,height; uint16_t keylen=0,valuesize=0,refvaluesize=0; uint8_t *key,*value=0; uint32_t flags,tmpflags,n; struct hush_kv *ptr; uint64_t fee; uint256 privkey,pubkey,refpubkey,sig; if (fHelp || params.size() < 3 ) throw runtime_error( "kvupdate key \"value\" days passphrase\n" @@ -639,7 +670,7 @@ UniValue kvupdate(const UniValue& params, bool fHelp, const CPubKey& mypk) //printf("flags.%d (%s) n.%d\n",flags,params[2].get_str().c_str(),n); } else flags = 0; if ( n >= 4 ) - privkey = komodo_kvprivkey(&pubkey,(char *)(n >= 4 ? params[3].get_str().c_str() : "password")); + privkey = hush_kvprivkey(&pubkey,(char *)(n >= 4 ? params[3].get_str().c_str() : "password")); haveprivkey = 1; flags |= 1; /*for (i=0; i<32; i++) @@ -659,7 +690,7 @@ UniValue kvupdate(const UniValue& params, bool fHelp, const CPubKey& mypk) valuesize = (int32_t)strlen(params[1].get_str().c_str()); } memcpy(keyvalue,key,keylen); - if ( (refvaluesize= komodo_kvsearch(&refpubkey,chainActive.LastTip()->GetHeight(),&tmpflags,&height,&keyvalue[keylen],key,keylen)) >= 0 ) + if ( (refvaluesize= hush_kvsearch(&refpubkey,chainActive.LastTip()->GetHeight(),&tmpflags,&height,&keyvalue[keylen],key,keylen)) >= 0 ) { if ( (tmpflags & HUSH_KVPROTECTED) != 0 ) { @@ -671,8 +702,8 @@ UniValue kvupdate(const UniValue& params, bool fHelp, const CPubKey& mypk) } if ( keylen+refvaluesize <= sizeof(keyvalue) ) { - sig = komodo_kvsig(keyvalue,keylen+refvaluesize,privkey); - if ( komodo_kvsigverify(keyvalue,keylen+refvaluesize,refpubkey,sig) < 0 ) + sig = hush_kvsig(keyvalue,keylen+refvaluesize,privkey); + if ( hush_kvsigverify(keyvalue,keylen+refvaluesize,refpubkey,sig) < 0 ) { ret.push_back(Pair("error",(char *)"error verifying sig, passphrase is probably wrong")); printf("VERIFY ERROR\n"); @@ -683,12 +714,12 @@ UniValue kvupdate(const UniValue& params, bool fHelp, const CPubKey& mypk) //for (i=0; i<32; i++) // printf("%02x",((uint8_t *)&sig)[i]); //printf(" sig for keylen.%d + valuesize.%d\n",keylen,refvaluesize); - ret.push_back(Pair("coin",(char *)(SMART_CHAIN_SYMBOL[0] == 0 ? "KMD" : SMART_CHAIN_SYMBOL))); + ret.push_back(Pair("coin",(char *)(SMART_CHAIN_SYMBOL[0] == 0 ? "HUSH3" : SMART_CHAIN_SYMBOL))); height = chainActive.LastTip()->GetHeight(); if ( memcmp(&zeroes,&refpubkey,sizeof(refpubkey)) != 0 ) ret.push_back(Pair("owner",refpubkey.GetHex())); ret.push_back(Pair("height", (int64_t)height)); - duration = komodo_kvduration(flags); //((flags >> 2) + 1) * HUSH_KVDURATION; + duration = hush_kvduration(flags); //((flags >> 2) + 1) * HUSH_KVDURATION; ret.push_back(Pair("expiration", (int64_t)(height+duration))); ret.push_back(Pair("flags",(int64_t)flags)); ret.push_back(Pair("key",params[0].get_str())); @@ -718,13 +749,13 @@ UniValue kvupdate(const UniValue& params, bool fHelp, const CPubKey& mypk) coresize += 32; } } - if ( (opretlen= komodo_opreturnscript(opretbuf,'K',keyvalue,coresize)) == 40 ) + if ( (opretlen= hush_opreturnscript(opretbuf,'K',keyvalue,coresize)) == 40 ) opretlen++; //for (i=0; ics_wallet); CBitcoinAddress address(params[0].get_str()); @@ -811,7 +842,7 @@ UniValue paxwithdraw(const UniValue& params, bool fHelp, const CPubKey& mypk) if ( fee < 10000 ) fee = 10000; dragon_rwnum(1,&pubkey37[33],sizeof(kmdheight),&kmdheight); - opretlen = komodo_opreturnscript(opretbuf,'W',pubkey37,37); + opretlen = hush_opreturnscript(opretbuf,'W',pubkey37,37); SendMoney(destaddress.Get(),fee,fSubtractFeeFromAmount,wtx,opretbuf,opretlen,fiatoshis); return wtx.GetHash().GetHex(); } @@ -1103,7 +1134,7 @@ UniValue cleanwallettransactions(const UniValue& params, bool fHelp, const CPubK if (fHelp || params.size() > 1 ) throw runtime_error( "cleanwallettransactions \"txid\"\n" - "\nRemove all txs that are spent. You can clear all txs bar one, by specifiying a txid.\n" + "\nRemove all transparent UTXOs that are spent. You can clear all transactions bar one, by specifiying a txid.\n" "\nPlease backup your wallet.dat before running this command.\n" "\nArguments:\n" "1. \"txid\" (string, optional) The transaction id to keep.\n" @@ -1133,9 +1164,7 @@ UniValue cleanwallettransactions(const UniValue& params, bool fHelp, const CPubK if ( !pwalletMain->IsMine(tmp_tx) ) { throw runtime_error("\nThe transaction is not yours!\n"); - } - else - { + } else { for (map::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; @@ -1145,14 +1174,10 @@ UniValue cleanwallettransactions(const UniValue& params, bool fHelp, const CPubK } } } - } - else - { + } else { throw runtime_error("\nThe transaction could not be found!\n"); } - } - else - { + } else { // get all locked utxos to relock them later. vector vLockedUTXO; pwalletMain->ListLockedCoins(vLockedUTXO); @@ -5002,8 +5027,8 @@ UniValue z_shieldcoinbase(const UniValue& params, bool fHelp, const CPubKey& myp "\nShield transparent coinbase funds by sending to a shielded zaddr. This is an asynchronous operation and utxos" "\nselected for shielding will be locked. If there is an error, they are unlocked. The RPC call `listlockunspent`" "\ncan be used to return a list of locked utxos. The number of coinbase utxos selected for shielding can be limited" - "\nby the caller. If the limit parameter is set to zero, and Overwinter is not yet active, the -mempooltxinputlimit" - "\noption will determine the number of uxtos. Any limit is constrained by the consensus rule defining a maximum" + "\nby the caller. If the limit parameter is set to zero, as many as will fit will be used." + "\nAny limit is constrained by the consensus rule defining a maximum" "\ntransaction size of " + strprintf("%d bytes.", MAX_TX_SIZE_AFTER_SAPLING) + HelpRequiringPassphrase() + "\n" "\nArguments:\n" @@ -5012,7 +5037,7 @@ UniValue z_shieldcoinbase(const UniValue& params, bool fHelp, const CPubKey& myp "3. fee (numeric, optional, default=" + strprintf("%s", FormatMoney(SHIELD_COINBASE_DEFAULT_MINERS_FEE)) + ") The fee amount to attach to this transaction.\n" "4. limit (numeric, optional, default=" - + strprintf("%d", SHIELD_COINBASE_DEFAULT_LIMIT) + ") Limit on the maximum number of utxos to shield. Set to 0 to use node option -mempooltxinputlimit (before Overwinter), or as many as will fit in the transaction (after Overwinter).\n" + + strprintf("%d", SHIELD_COINBASE_DEFAULT_LIMIT) + ") Limit on the maximum number of utxos to shield. Set to 0 to use as many as will fit in the transaction.\n" "\nResult:\n" "{\n" " \"remainingUTXOs\": xxx (numeric) Number of coinbase utxos still available for shielding.\n" @@ -8283,6 +8308,7 @@ static const CRPCCommand commands[] = { "wallet", "getaccount", &getaccount, true }, { "wallet", "getalldata", &getalldata, true }, { "wallet", "getaddressesbyaccount", &getaddressesbyaccount, true }, + { "wallet", "listaddresses", &listaddresses , true }, { "wallet", "getbalance", &getbalance, false }, { "wallet", "getnewaddress", &getnewaddress, true }, { "wallet", "getrawchangeaddress", &getrawchangeaddress, true }, diff --git a/src/wallet/test/wallet_tests.cpp b/src/wallet/test/wallet_tests.cpp index 529449ba1..3831aaed4 100644 --- a/src/wallet/test/wallet_tests.cpp +++ b/src/wallet/test/wallet_tests.cpp @@ -211,7 +211,7 @@ BOOST_AUTO_TEST_CASE(coin_selection_tests) BOOST_CHECK( wallet.SelectCoinsMinConf(1 * CENT, 1, 1, vCoins, setCoinsRet, nValueRet,0)); BOOST_CHECK_EQUAL(nValueRet, 1 * CENT); // we should get the exact amount - // run the 'mtgox' test (see http://blockexplorer.com/tx/29a3efd3ef04f9153d47a990bd7b048a4b2d213daaa5fb8ed670fb85f13bdbcf) + // run the 'mtgox' test // they tried to consolidate 10 50k coins into one 500k coin, and ended up with 50k in change empty_wallet(); for (int i = 0; i < 20; i++) diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 0a848ff33..4217e3825 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -480,13 +480,19 @@ void CWallet::ChainTip(const CBlockIndex *pindex, pblock->GetBlockTime() > GetTime() - 144*ASSETCHAINS_BLOCKTIME) { BuildWitnessCache(pindex, false); - RunSaplingConsolidation(pindex->GetHeight()); - DeleteWalletTransactions(pindex); + if (fSaplingConsolidationEnabled) { + RunSaplingConsolidation(pindex->GetHeight()); + } + if (fTxDeleteEnabled) { + DeleteWalletTransactions(pindex); + } } else { //Build initial witnesses on every block BuildWitnessCache(pindex, true); - if (initialDownloadCheck && pindex->GetHeight() % fDeleteInterval == 0) { - DeleteWalletTransactions(pindex); + if (fTxDeleteEnabled) { + if (initialDownloadCheck && pindex->GetHeight() % fDeleteInterval == 0) { + DeleteWalletTransactions(pindex); + } } } } else { @@ -902,12 +908,15 @@ int64_t CWallet::NullifierCount() void CWallet::ClearNoteWitnessCache() { LOCK(cs_wallet); + int notes = 0; for (std::pair& wtxItem : mapWallet) { for (mapSaplingNoteData_t::value_type& item : wtxItem.second.mapSaplingNoteData) { item.second.witnesses.clear(); item.second.witnessHeight = -1; + notes++; } } + LogPrintf("%s: Cleared witness data from %d wallet items and %d SaplingNotes\n", __func__, mapWallet.size(), notes); } void CWallet::DecrementNoteWitnesses(const CBlockIndex* pindex) @@ -1122,6 +1131,7 @@ void CWallet::BuildWitnessCache(const CBlockIndex* pindex, bool witnessOnly) nd->witnessHeight = pblockindex->GetHeight(); } } + } } @@ -2378,12 +2388,6 @@ bool CWalletTx::WriteToDisk(CWalletDB *pwalletdb) return pwalletdb->WriteTx(GetHash(), *this); } -void CWallet::WitnessNoteCommitment(std::vector commitments, - std::vector>& witnesses, - uint256 &final_anchor) -{ -} - /** * Reorder the transactions based on block hieght and block index. * Transactions can get out of order when they are deleted and subsequently @@ -2713,10 +2717,12 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100)))); CBlock block; + bool involvesMe = false; ReadBlockFromDisk(block, pindex,1); BOOST_FOREACH(CTransaction& tx, block.vtx) { if (AddToWalletIfInvolvingMe(tx, &block, fUpdate)) { + involvesMe = true; ret++; } } @@ -2730,12 +2736,17 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) } } - // Build initial witness caches - BuildWitnessCache(pindex, true); + // Build initial witness caches for blocks involving one of our addresses + if (involvesMe) { + LogPrintf("%s: block has one of our transactions, building witness cache\n", __func__); + BuildWitnessCache(pindex, true); + } //Delete Transactions - if (pindex->GetHeight() % fDeleteInterval == 0) - DeleteWalletTransactions(pindex); + if (fTxDeleteEnabled) { + if (pindex->GetHeight() % fDeleteInterval == 0) + DeleteWalletTransactions(pindex); + } if (GetTime() >= nNow + 60) { nNow = GetTime(); @@ -3050,7 +3061,7 @@ std::vector CWallet::ResendWalletTransactionsBefore(int64_t nTime) if ( (wtx.nLockTime >= LOCKTIME_THRESHOLD && wtx.nLockTime < now-HUSH_MAXMEMPOOLTIME) ) { - //LogPrintf("skip Relaying wtx %s nLockTime %u vs now.%u\n", wtx.GetHash().ToString(),(uint32_t)wtx.nLockTime,now); + LogPrintf("%s: skip Relaying wtx %s nLockTime %u vs now.%u\n", __func__, wtx.GetHash().ToString(),(uint32_t)wtx.nLockTime,now); //vwtxh.push_back(wtx.GetHash()); continue; } diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index d78834727..965ab5b22 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -1122,10 +1122,6 @@ public: void SyncTransaction(const CTransaction& tx, const CBlock* pblock); void RescanWallet(); bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate); - void WitnessNoteCommitment( - std::vector commitments, - std::vector>& witnesses, - uint256 &final_anchor); void ReorderWalletTransactions(std::map, CWalletTx*> &mapSorted, int64_t &maxOrderPos); void UpdateWalletTransactionOrder(std::map, CWalletTx*> &mapSorted, bool resetOrder); void DeleteTransactions(std::vector &removeTxs); diff --git a/src/wallet/walletdb.cpp b/src/wallet/walletdb.cpp index 937d3b15c..7b286c2c7 100644 --- a/src/wallet/walletdb.cpp +++ b/src/wallet/walletdb.cpp @@ -441,7 +441,7 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, ssValue >> wtx; CValidationState state; auto verifier = libzcash::ProofVerifier::Strict(); - // ac_public chains set at height like KMD and ZEX, will force a rescan if we dont ignore this error: bad-txns-acpublic-chain + // ac_public chains which enable at a certain height instead of from genesis, this will force a rescan if we dont ignore this error: bad-txns-acpublic-chain // there cannot be any ztx in the wallet on ac_public chains that started from block 1, so this wont affect those. // ac_private chains fail this check for notary nodes, need exception. Triggers full rescan without it. if ( !(CheckTransaction(0,wtx, state, verifier, 0, 0) && (wtx.GetHash() == hash) && state.IsValid()) && (state.GetRejectReason() != "bad-txns-acpublic-chain" && state.GetRejectReason() != "bad-txns-acprivacy-chain" && state.GetRejectReason() != "bad-txns-stakingtx") ) diff --git a/src/zush b/src/zush index e6da90523..5aefa7a9e 100755 --- a/src/zush +++ b/src/zush @@ -10,12 +10,7 @@ cd $DIR NAME=ZUSH -CLI=${KOMODOCLI:-./komodo-cli} +CLI=${HUSHCLI:-./hush-cli} if [ -f $CLI ]; then $CLI -ac_name=$NAME "$@" -else - # We prefix our binary when installed - # system wide on Debain system, to prevent clashes - CLI=hush-komodo-cli - $CLI -ac_name=$NAME "$@" fi diff --git a/zcutil/build-debian-package.sh b/zcutil/build-debian-package.sh index af013cd9f..4a3b63cae 100755 --- a/zcutil/build-debian-package.sh +++ b/zcutil/build-debian-package.sh @@ -57,6 +57,7 @@ strip $DEB_BIN/hush-komodo-tx cp $SRC_PATH/src/hushd $DEB_BIN cp $SRC_PATH/src/hush-cli $DEB_BIN cp $SRC_PATH/src/hush-tx $DEB_BIN +cp $SRC_PATH/src/hush-smart-chain $DEB_BIN #cp $SRC_DEB/changelog $DEB_DOC/changelog.Debian cp $SRC_DEB/copyright $DEB_DOC cp -r $SRC_DEB/examples $DEB_DOC