Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b9c5498bd2 | ||
|
|
a2348515a2 | ||
|
|
433892e40b | ||
|
|
93f8b3768b | ||
|
|
3537531901 | ||
|
|
179429ef7e | ||
|
|
dbe154c2dc | ||
|
|
2ff5c5d541 | ||
|
|
b0e0d211d2 | ||
|
|
227cc7730b | ||
|
|
695050afe1 | ||
|
|
b61611d5c2 | ||
|
|
ca07b8299f | ||
|
|
eec0d86dbf | ||
|
|
70dd6c6f8b | ||
|
|
2e78769817 | ||
|
|
c59b445ac1 |
@@ -25,7 +25,6 @@ RUN cd /hush && \
|
||||
RUN ln -sf /hush/src/hushd /usr/bin/hushd && \
|
||||
ln -sf /hush/src/hush-tx /usr/bin/hush-tx && \
|
||||
ln -sf /hush/src/wallet-utility /usr/bin/hush-wallet-utility && \
|
||||
ln -sf /hush/src/hush-arrakis-chain /usr/bin/hush-arrakis-chain && \
|
||||
ln -sf /hush/util/docker-entrypoint.sh /usr/bin/entrypoint && \
|
||||
ln -sf /hush/util/docker-hush-cli.sh /usr/bin/hush-cli
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ this can take a while, so most users start from the [bootstrap snapshot](#fastes
|
||||
| Block reward | 3 DRAGONX, halving every 3,500,000 blocks |
|
||||
| Max block size | 4 MB |
|
||||
| RPC port | 21769 |
|
||||
| P2P port | 18030 |
|
||||
| P2P port | 21768 |
|
||||
| Data directory | `~/.hush/DRAGONX` (Linux) |
|
||||
| Config file | `DRAGONX.conf` |
|
||||
| Binaries | `dragonxd`, `dragonx-cli`, `dragonx-tx` |
|
||||
|
||||
@@ -27,7 +27,7 @@ if ($block <= $blockcount) {
|
||||
} else {
|
||||
my $diff = $block - $blockcount;
|
||||
# TODO: support custom blocktimes
|
||||
# assumes HACs use default blocktime of 60s
|
||||
# assumes smart chains use default blocktime of 60s
|
||||
my $minpb = $coin ? 1 : 0.6; # 36s in minutes for DragonX
|
||||
my $minutes = $diff*$minpb;
|
||||
my $seconds = $minutes*60;
|
||||
|
||||
@@ -169,7 +169,7 @@ hush (3.10.5) stable; urgency=medium
|
||||
* It cannot be determined from public blockchain data if a donation is being made, as it takes the place of a Sietch output
|
||||
* It cannot be determined from public blockchain data the amount of the donation
|
||||
* Donations do not create new transactions, do not use additional blockspace and cannot be detected by anyone but the sender or reciever
|
||||
* New HAC option `ac_clearnet` can be used to disable clearnet networking for an entire blockchain instead of just a single node
|
||||
* New smart chain option `ac_clearnet` can be used to disable clearnet networking for an entire blockchain instead of just a single node
|
||||
* Updated test framework and tests which allowed the fixing of the `z_sendmany` bug above
|
||||
* Faster compiling of RandomX internals
|
||||
* GMP dependency removed, as it is no longer needed
|
||||
@@ -184,7 +184,7 @@ hush (3.10.4) stable; urgency=medium
|
||||
* New CLI option -clearnet=0 which disables clearnet networking
|
||||
* Using -mineraddress with -clearnet=0 disallowed since would reduce privacy
|
||||
* Add CLI options -disableipv4 and -disableipv6 to disable IPv4 or IPv6
|
||||
* New HAC CLI consensus option -ac_minopreturnfee
|
||||
* New smart chain CLI consensus option -ac_minopreturnfee
|
||||
* Updated ASmap, which maps IP addresses to Autonomous System (AS) numbers
|
||||
* Added ASmap health check, which logs stats about the ASmap once per 24 hours
|
||||
* Improved cjdns/i2p/tor docs
|
||||
@@ -199,11 +199,11 @@ hush (3.10.3) stable; urgency=high
|
||||
* Set minimum fee to 0.1 HUSH per 1 KB of data if `OP_RETURN` is used.
|
||||
* Absurd fee allows sending amount < fee; used only in a full node.
|
||||
* Fixed various bugs relating to lock ordering and missing locks
|
||||
* Fixed RPC docs for addnode and disconnectnode having incorrect port for HACs
|
||||
* Fixed RPC docs for addnode and disconnectnode having incorrect port for smart chains
|
||||
* Value of DEBUG_LOCKORDER is now logged to debug.log on node startup
|
||||
* New script ./debug-build.sh to make it easier to make debug builds
|
||||
* DragonX nodes now have their own list of seed nodes
|
||||
* Hush nodes now have own protocol version independent from HACs
|
||||
* Hush nodes now have own protocol version independent from smart chains
|
||||
* Fixed off-by-one bug in `newSietchRecipient`
|
||||
* Performance improvement to `ActivateBestChainStep` ed86f2dd1d
|
||||
* Improved navigation in README for new users.
|
||||
|
||||
@@ -11,7 +11,7 @@ use warnings;
|
||||
use strict;
|
||||
|
||||
# call this script like this to generate checkpoints for another chain:
|
||||
# CLI=./src/hac-cli ./contrib/sdl_checkpoints.pl ...
|
||||
# CLI="./src/dragonx-cli -ac_name=OTHERCHAIN" ./contrib/sdl_checkpoints.pl ...
|
||||
|
||||
my $cli = $ENV{CLI} || "./src/dragonx-cli";
|
||||
my $gethash = "$cli getblockhash";
|
||||
|
||||
+7
-7
@@ -97,27 +97,27 @@ If you are adding a new CLI option that changes consensus rules such as
|
||||
convention is that if a CLI option affects consensus, it MUST begin with `-ac_`
|
||||
and if it does not affect consensus (such as -datadir) then it MUST NOT begin
|
||||
with `-ac_`. Originally the `ac` meant "asset chain" but now it means "affects
|
||||
consensus" or "arrakis chain", take your pick.
|
||||
consensus".
|
||||
|
||||
The reason for this is the `extraptr` variable is used to deterministically
|
||||
generate the "chain magic" `ASSETCHAINS_MAGIC` as well as the default p2p and
|
||||
rpc ports for a HAC. This means that if two HACs have *exactly* the same
|
||||
rpc ports for a chain. This means that if two chains have *exactly* the same
|
||||
consensus options except for `-ac_foo` (even if they have the same `-ac_name`)
|
||||
then they will still get different chain magic values and p2p and rpc ports.
|
||||
This is a way of preventing HACs with different consensus rules from trying to
|
||||
talk with each other when they should not. For instance, if you make a HAC with
|
||||
This is a way of preventing chains with different consensus rules from trying to
|
||||
talk with each other when they should not. For instance, if you make a chain with
|
||||
`-ac_name=MYCOIN` on one machine with one set of consensus rules and then
|
||||
another HAC with the same name on a different machine but with different
|
||||
another chain with the same name on a different machine but with different
|
||||
consensus rules, the chain magic being different (as well as the default p2p
|
||||
port) are ways to prevent them from communicating. This is good because these
|
||||
two HACs will eventually chain fork due to their different consensus rules and
|
||||
two chains will eventually fork due to their different consensus rules and
|
||||
ban each other, wasting time, bandwidth and sanity.
|
||||
|
||||
An example of this pattern in the Git history is the commit which added the
|
||||
`-ac_burn` consensus changing option; search the log for `ac_burn` to find it.
|
||||
|
||||
The chain magic value is the CRC32 checksum of every non-default consensus
|
||||
option the HAC uses.
|
||||
option the chain uses.
|
||||
|
||||
Also make sure to actually validate the new consensus option! That is probably
|
||||
going to happen in `src/main.cpp` . If you don't, a malicious node can just
|
||||
|
||||
@@ -311,7 +311,7 @@ Threads
|
||||
|
||||
- ThreadMapPort : Universal plug-and-play startup/shutdown
|
||||
|
||||
- ThreadSocketHandler : Sends/Receives data from peers on the P2P port (18030 on DragonX mainnet).
|
||||
- ThreadSocketHandler : Sends/Receives data from peers on the P2P port (21768 on DragonX mainnet).
|
||||
|
||||
- ThreadOpenAddedConnections : Opens network connections to added nodes.
|
||||
|
||||
|
||||
+2
-2
@@ -39,8 +39,8 @@ are baked into DragonX consensus.
|
||||
## RandomX key-block tuning options
|
||||
|
||||
RandomX periodically rotates the "key block" it derives its dataset from. Two
|
||||
advanced options control this. They are inherited from the upstream Hush /
|
||||
Arrakis-chain tooling and default to values suited to DragonX's 36s block time;
|
||||
advanced options control this. They are inherited from the upstream Hush
|
||||
tooling and default to values suited to DragonX's 36s block time;
|
||||
you should not normally change them:
|
||||
|
||||
* `-ac_randomx_interval` controls how often the RandomX key block changes
|
||||
|
||||
@@ -33,7 +33,7 @@ This is an OPTIONAL but RECOMMENDED upgrade.
|
||||
* It cannot be determined from public blockchain data if a donation is being made, as it takes the place of a Sietch output
|
||||
* It cannot be determined from public blockchain data the amount of the donation
|
||||
* Donations do not create new transactions, do not use additional blockspace and cannot be detected by anyone but the sender or reciever
|
||||
* New HAC option `ac_clearnet` can be used to disable clearnet networking for an entire blockchain instead of just a single node
|
||||
* New smart chain option `ac_clearnet` can be used to disable clearnet networking for an entire blockchain instead of just a single node
|
||||
* Updated test framework and tests which allowed the fixing of the `z_sendmany` bug above
|
||||
* Faster compiling of RandomX internals
|
||||
* GMP dependency removed, as it is no longer needed
|
||||
@@ -67,7 +67,7 @@ problems finding nodes, you want to upgrade.
|
||||
```
|
||||
* Using -mineraddress with -clearnet=0 is disallowed since it would reduce privacy
|
||||
* Add CLI options `-disableipv4` and `-disableipv6` which can be used to disable IPv4 or IPv6
|
||||
* New HAC CLI consensus option `-ac_minopreturnfee`
|
||||
* New smart chain CLI consensus option `-ac_minopreturnfee`
|
||||
* `OP_RETURN` minimum fee per tx, regardless of tx size, default is 1 coin, specified in puposhis
|
||||
* Updated ASmap, which maps IP addresses to Autonomous System (AS) numbers
|
||||
* Added ASmap health check, which logs stats about the ASmap once per 24 hours
|
||||
@@ -81,11 +81,11 @@ problems finding nodes, you want to upgrade.
|
||||
* Set minimum fee to 0.1 HUSH per 1 KB of data if `OP_RETURN` is used.
|
||||
* A feature in absurd fee that allows sending amount < fee, can be used only in a full node by advanced users.
|
||||
* Fixed various bugs relating to lock ordering and missing locks
|
||||
* Fixed RPC docs for addnode and disconnectnode having the incorrect port for HACs
|
||||
* Fixed RPC docs for addnode and disconnectnode having the incorrect port for smart chains
|
||||
* Value of DEBUG_LOCKORDER is now logged to debug.log on node startup
|
||||
* New script ./debug-build.sh to make it easier to make debug builds
|
||||
* DragonX nodes now have their own list of seed nodes
|
||||
* Hush nodes now have their own protocol version which is independent from HACs
|
||||
* Hush nodes now have their own protocol version which is independent from smart chains
|
||||
* Fixed off-by-one bug in `newSietchRecipient`
|
||||
* Performance improvement to `ActivateBestChainStep` https://git.hush.is/hush/hush3/commit/ed86f2dd1da370fe2dbf7db475afc41b218cbc5f
|
||||
* Improved navigation in README for new users.
|
||||
@@ -102,7 +102,7 @@ problems finding nodes, you want to upgrade.
|
||||
* Mining now starts faster because instead of only using 2 threads to prepare
|
||||
data needed to mine, now it uses all physical cores https://git.hush.is/hush/hush3/commit/1b5422eb2ddcedd9aabdf4f039144f9eef5c6f95
|
||||
* RandomX mining takes slightly less memory
|
||||
* `ac_sapling` is no longer an option for Arrakis Chains
|
||||
* `ac_sapling` is no longer an option for smart chains
|
||||
* All chains enable Sapling at height 1 like Hush + DragonX
|
||||
* This means there is no need to call `NetworkUpgradeActive` on every block height
|
||||
which means syncing is faster
|
||||
@@ -113,7 +113,7 @@ problems finding nodes, you want to upgrade.
|
||||
* Upgraded WolfSSL to 5.2.0 on Linux+Mac : https://git.hush.is/hush/hush3/issues/380
|
||||
* Upgraded to 4.8.1 on Windows because newer versions do not compile on Windows: https://git.hush.is/hush/hush3/commit/5e5a15018d0e55f094c89282a1983104f4d4387a
|
||||
* Only Hush + DragonX will automatically connect to various seed nodes https://git.hush.is/hush/hush3/issues/379
|
||||
* Other Arrakis Chains must opt-in via -connect or -addnode
|
||||
* Other smart chains must opt-in via -connect or -addnode
|
||||
* Updated i2p seed node: https://git.hush.is/hush/hush3/commit/8c8b6e88f0c076c86c713e7e22e2d826202cc64d
|
||||
* Better error message: https://git.hush.is/hush/hush3/commit/f64c10baa9ae6940f434f6ff6750b299c1da548e, https://git.hush.is/hush/hush3/commit/f71f8124c3ffb8df6d83f6fd00201cb11aa0f239
|
||||
* Improve `hush_scanner` and seed node contrib file: https://git.hush.is/hush/hush3/commit/16dd3aef74ac312bc8953af34a3d9a297b03d9f4
|
||||
|
||||
+4
-4
@@ -160,11 +160,11 @@ You can also manually configure your node to be reachable from the Tor network.
|
||||
Add these lines to your `/etc/tor/torrc` (or equivalent config file):
|
||||
|
||||
HiddenServiceDir /var/lib/tor/dragonx-service/
|
||||
HiddenServicePort 18030 127.0.0.1:18032
|
||||
HiddenServicePort 21768 127.0.0.1:21768
|
||||
|
||||
The directory can be different of course, but virtual port numbers should be equal to
|
||||
your dragonxd's P2P listen port (18030 by default), and target addresses and ports
|
||||
should be equal to binding address and port for inbound Tor connections (127.0.0.1:18032 by default).
|
||||
your dragonxd's P2P listen port (21768 by default), and target addresses and ports
|
||||
should be equal to binding address and port for inbound Tor connections (127.0.0.1:21768 by default).
|
||||
|
||||
-externalip=X You can tell dragonx about its publicly reachable addresses using
|
||||
this option, and this can be an onion address. Given the above
|
||||
@@ -204,7 +204,7 @@ as well, use `discover` instead:
|
||||
|
||||
./dragonxd ... -discover
|
||||
|
||||
and open port 18030 on your firewall (or use port mapping, i.e., `-upnp` or `-natpmp`).
|
||||
and open port 21768 on your firewall (or use port mapping, i.e., `-upnp` or `-natpmp`).
|
||||
|
||||
If you only want to use Tor to reach .onion addresses, but not use it as a proxy
|
||||
for normal IPv4/IPv6 communication, use:
|
||||
|
||||
@@ -97,5 +97,18 @@ class HTTPBasicsTest (BitcoinTestFramework):
|
||||
assert_equal('"error":null' in out1, True)
|
||||
assert_equal(conn.sock!=None, True) # connection must be closed because hushd should use keep-alive by default
|
||||
|
||||
# Check excessive request size: request line + headers are capped at 8 KiB
|
||||
conn = httplib.HTTPConnection(urlNode2.hostname, urlNode2.port)
|
||||
conn.connect()
|
||||
conn.request('GET', '/' + ('x'*1000), '', headers)
|
||||
out1 = conn.getresponse()
|
||||
assert_equal(out1.status, httplib.NOT_FOUND)
|
||||
|
||||
conn = httplib.HTTPConnection(urlNode2.hostname, urlNode2.port)
|
||||
conn.connect()
|
||||
conn.request('GET', '/' + ('x'*10000), '', headers)
|
||||
out1 = conn.getresponse()
|
||||
assert_equal(out1.status, httplib.BAD_REQUEST)
|
||||
|
||||
if __name__ == '__main__':
|
||||
HTTPBasicsTest().main()
|
||||
|
||||
@@ -167,10 +167,10 @@ class ComparisonTestFramework(BitcoinTestFramework):
|
||||
|
||||
def add_options(self, parser):
|
||||
parser.add_option("--testbinary", dest="testbinary",
|
||||
default=os.getenv("BITCOIND", "hush-arrakis-chain"),
|
||||
default=os.getenv("BITCOIND", "src/dragonxd"),
|
||||
help="bitcoind binary to test")
|
||||
parser.add_option("--refbinary", dest="refbinary",
|
||||
default=os.getenv("BITCOIND", "hush-arrakis-chain"),
|
||||
default=os.getenv("BITCOIND", "src/dragonxd"),
|
||||
help="bitcoind binary to use for reference nodes (if any)")
|
||||
|
||||
def setup_chain(self):
|
||||
|
||||
+6
-1
@@ -504,7 +504,12 @@ dragonxd_LDADD = $(LINK_GROUP_START) \
|
||||
$(LIBRANDOMX)
|
||||
|
||||
if ENABLE_WALLET
|
||||
dragonxd_LDADD += $(LIBBITCOIN_WALLET)
|
||||
# libbitcoin_server again after the wallet: the two archives use each other (the wallet's async
|
||||
# operations derive from libbitcoin_server's AsyncRPCOperation), and GNU ld scans each archive once,
|
||||
# in order. Spelled ./ on purpose: libtool drops a repeated archive, keeping only the last copy, which
|
||||
# would put the server after the wallet and break the other direction. (LINK_GROUP_START/END cannot
|
||||
# do it either: libtool moves both flags ahead of the archives.)
|
||||
dragonxd_LDADD += $(LIBBITCOIN_WALLET) ./$(LIBBITCOIN_SERVER)
|
||||
endif
|
||||
|
||||
dragonxd_LDADD += \
|
||||
|
||||
@@ -16,15 +16,19 @@ hush_gtest_SOURCES = \
|
||||
gtest/test_hdtransparent.cpp \
|
||||
gtest/test_mnemonic_compat.cpp \
|
||||
gtest/test_stratum_jobid.cpp \
|
||||
gtest/test_sweep_note_selection.cpp \
|
||||
gtest/test_asyncrpc_cancel.cpp \
|
||||
gtest/test_wallet_notedata.cpp \
|
||||
gtest/test_net_closesocket.cpp \
|
||||
gtest/test_net_addrrelay.cpp \
|
||||
gtest/test_fd_defense.cpp \
|
||||
gtest/test_wallet_dbenv.cpp \
|
||||
gtest/test_wallet_notecache.cpp \
|
||||
gtest/test_wallet_history.cpp \
|
||||
gtest/test_wallet_consolidation.cpp \
|
||||
gtest/test_wallet_shutdownsave.cpp \
|
||||
gtest/test_wallet_witnessroots.cpp
|
||||
gtest/test_wallet_witnessroots.cpp \
|
||||
gtest/test_sapling_addr_validity.cpp
|
||||
|
||||
hush_gtest_CPPFLAGS = $(AM_CPPFLAGS) -DMULTICORE -fopenmp -DBINARY_OUTPUT -DCURVE_ALT_BN128 -DSTATIC $(BITCOIN_INCLUDES)
|
||||
hush_gtest_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
|
||||
@@ -45,7 +49,8 @@ hush_gtest_LDADD = -lgtest -lgmock \
|
||||
$(LIBSECP256K1) \
|
||||
$(LIBRANDOMX)
|
||||
if ENABLE_WALLET
|
||||
hush_gtest_LDADD += $(LIBBITCOIN_WALLET)
|
||||
# libbitcoin_server again after the wallet, spelled ./ so libtool keeps both copies (see dragonxd_LDADD).
|
||||
hush_gtest_LDADD += $(LIBBITCOIN_WALLET) ./$(LIBBITCOIN_SERVER)
|
||||
endif
|
||||
|
||||
hush_gtest_LDADD += \
|
||||
|
||||
@@ -32,7 +32,9 @@ using namespace std;
|
||||
|
||||
static boost::uuids::random_generator uuidgen;
|
||||
|
||||
static std::map<OperationStatus, std::string> OperationStatusMap = {
|
||||
// const and read with at(): getStatus() runs on several RPC threads at once, and operator[] of a
|
||||
// std::map is not one of the calls the standard guarantees safe for concurrent use.
|
||||
static const std::map<OperationStatus, std::string> OperationStatusMap = {
|
||||
{OperationStatus::READY, "queued"},
|
||||
{OperationStatus::EXECUTING, "executing"},
|
||||
{OperationStatus::CANCELLED, "cancelled"},
|
||||
@@ -194,7 +196,7 @@ UniValue AsyncRPCOperation::getStatus() const {
|
||||
OperationStatus status = this->getState();
|
||||
UniValue obj(UniValue::VOBJ);
|
||||
obj.push_back(Pair("id", this->id_));
|
||||
obj.push_back(Pair("status", OperationStatusMap[status]));
|
||||
obj.push_back(Pair("status", OperationStatusMap.at(status)));
|
||||
obj.push_back(Pair("creation_time", this->creation_time_));
|
||||
// TODO: Issue #1354: There may be other useful metadata to return to the user.
|
||||
UniValue err = this->getError();
|
||||
@@ -218,5 +220,5 @@ UniValue AsyncRPCOperation::getStatus() const {
|
||||
*/
|
||||
std::string AsyncRPCOperation::getStateAsString() const {
|
||||
OperationStatus status = this->getState();
|
||||
return OperationStatusMap[status];
|
||||
return OperationStatusMap.at(status);
|
||||
}
|
||||
|
||||
@@ -60,8 +60,10 @@ public:
|
||||
// You must implement this method in your subclass.
|
||||
virtual void main();
|
||||
|
||||
// Override this method if you can interrupt execution of main() in your subclass.
|
||||
void cancel();
|
||||
// Override this method if you can interrupt execution of main() in your subclass. It must be virtual:
|
||||
// callers hold a std::shared_ptr<AsyncRPCOperation> (the queue's map, the wallet schedulers). It used
|
||||
// not to be, which left every subclass override dead and a running operation uncancellable.
|
||||
virtual void cancel();
|
||||
|
||||
// Getters and setters
|
||||
|
||||
|
||||
+1
-1
@@ -87,7 +87,7 @@ static int AppInitRPC(int argc, char* argv[])
|
||||
ParseParameters(argc, argv);
|
||||
std:string name;
|
||||
|
||||
// default HAC is DRAGONX itself, which to the internals, is also a HAC
|
||||
// default chain is DRAGONX itself, which to the internals is also a smart chain
|
||||
name = GetArg("-ac_name","DRAGONX");
|
||||
|
||||
if ( !name.empty() )
|
||||
|
||||
+3
-3
@@ -117,7 +117,7 @@ public:
|
||||
consensus.nPowMaxAdjustDown = 32; // 32% adjustment down
|
||||
consensus.nPowMaxAdjustUp = 16; // 16% adjustment up
|
||||
// we are emulating old node behavior at startup, they used 150s
|
||||
consensus.nPowTargetSpacing = 150; // 75; // HUSH is 75 seconds, Hush Arrakis Chains are 60 seconds by default
|
||||
consensus.nPowTargetSpacing = 150; // 75; // HUSH is 75 seconds, smart chains are 60 seconds by default
|
||||
consensus.nPowAllowMinDifficultyBlocksAfterHeight = boost::none;
|
||||
// HUSH never had Sprout in our blockchain history, but some internals require *knowing* about Sprout
|
||||
// or it breaks backward compatibility. We do what we can.
|
||||
@@ -366,7 +366,7 @@ public:
|
||||
assert(maxUint/UintToArith256(consensus.powLimit) >= consensus.nPowAveragingWindow);
|
||||
consensus.nPowMaxAdjustDown = 0; // Turn off adjustment down
|
||||
consensus.nPowMaxAdjustUp = 0; // Turn off adjustment up
|
||||
consensus.nPowTargetSpacing = 60; // HAC's default to 60 seconds so a theoretical testnet should as well
|
||||
consensus.nPowTargetSpacing = 60; // smart chains default to 60 seconds so a theoretical testnet should as well
|
||||
consensus.nPowAllowMinDifficultyBlocksAfterHeight = 0;
|
||||
ups[Consensus::BASE_SPROUT].nProtocolVersion = 170002;
|
||||
ups[Consensus::BASE_SPROUT].nActivationHeight = NUNU::ALWAYS_ACTIVE;
|
||||
@@ -6074,7 +6074,7 @@ void *chainparams_commandline() {
|
||||
|
||||
};
|
||||
} else {
|
||||
// all other HAC's with no checkpoints
|
||||
// all other smart chains with no checkpoints
|
||||
checkpointData = //(Checkpoints::CCheckpointData)
|
||||
{
|
||||
boost::assign::map_list_of
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
// Copyright (c) 2016-2024 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
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
#include "asyncrpcoperation.h"
|
||||
#include "wallet/asyncrpcoperation_autoshieldcoinbase.h"
|
||||
#include "wallet/asyncrpcoperation_saplingconsolidation.h"
|
||||
#include "wallet/asyncrpcoperation_sweep.h"
|
||||
|
||||
namespace {
|
||||
|
||||
// Lets a test put an operation into any state, without running it.
|
||||
template <class Op>
|
||||
class Probe : public Op {
|
||||
public:
|
||||
template <class... Args>
|
||||
explicit Probe(Args&&... args) : Op(std::forward<Args>(args)...) {}
|
||||
void Set(OperationStatus status) { this->set_state(status); }
|
||||
};
|
||||
|
||||
// An operation that does not override cancel(): the base behaviour.
|
||||
class PlainOp : public AsyncRPCOperation {
|
||||
public:
|
||||
void main() override {}
|
||||
void Set(OperationStatus status) { set_state(status); }
|
||||
};
|
||||
|
||||
int S(OperationStatus status) { return static_cast<int>(status); }
|
||||
|
||||
// The queue's map and the wallet schedulers hold every operation as a shared_ptr<AsyncRPCOperation>, so
|
||||
// that is how cancel() is called here. Before cancel() was virtual, each of these overrides was dead.
|
||||
template <class P>
|
||||
void CheckOverride(std::shared_ptr<P> probe)
|
||||
{
|
||||
std::shared_ptr<AsyncRPCOperation> op = probe;
|
||||
|
||||
probe->Set(OperationStatus::EXECUTING);
|
||||
op->cancel();
|
||||
EXPECT_TRUE(op->isCancelled()) << "a running round can be stopped";
|
||||
|
||||
for (OperationStatus done : {OperationStatus::SUCCESS, OperationStatus::FAILED}) {
|
||||
probe->Set(done);
|
||||
op->cancel();
|
||||
EXPECT_EQ(S(done), S(op->getState())) << "a finished round is not relabelled as cancelled";
|
||||
}
|
||||
|
||||
probe->Set(OperationStatus::READY);
|
||||
op->cancel();
|
||||
EXPECT_TRUE(op->isCancelled()) << "a round that has not started is cancelled, as before";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
TEST(AsyncRPCCancel, TheSweepOverrideIsReachedThroughTheBasePointer) {
|
||||
CheckOverride(std::make_shared<Probe<AsyncRPCOperation_sweep>>(100));
|
||||
}
|
||||
|
||||
TEST(AsyncRPCCancel, TheConsolidationOverrideIsReachedThroughTheBasePointer) {
|
||||
CheckOverride(std::make_shared<Probe<AsyncRPCOperation_saplingconsolidation>>(100, SaplingConsolidationRequest()));
|
||||
}
|
||||
|
||||
TEST(AsyncRPCCancel, TheAutoshieldOverrideIsReachedThroughTheBasePointer) {
|
||||
CheckOverride(std::make_shared<Probe<AsyncRPCOperation_autoshieldcoinbase>>(100));
|
||||
}
|
||||
|
||||
TEST(AsyncRPCCancel, AnOperationWithoutAnOverrideOnlyCancelsBeforeItStarts) {
|
||||
auto plain = std::make_shared<PlainOp>();
|
||||
std::shared_ptr<AsyncRPCOperation> op = plain;
|
||||
|
||||
plain->Set(OperationStatus::EXECUTING);
|
||||
op->cancel();
|
||||
EXPECT_TRUE(op->isExecuting()) << "z_sendmany and friends are not interrupted mid-run";
|
||||
|
||||
plain->Set(OperationStatus::READY);
|
||||
op->cancel();
|
||||
EXPECT_TRUE(op->isCancelled());
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// Copyright (c) 2016-2024 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
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "net.h"
|
||||
#include "netbase.h"
|
||||
|
||||
// CNode::PushAddress must filter on the address being queued, not on the peer's own address (the
|
||||
// CNode::addr member). The peer's own address routinely lands in its addrKnown (it advertises itself,
|
||||
// or comes back in a getaddr reply); after that, filtering on the member dropped every address queued
|
||||
// for that peer until the daily addrKnown.reset().
|
||||
TEST(NetAddrRelay, PushAddressFiltersOnQueuedAddress) {
|
||||
const CAddress peer(LookupNumeric("20.0.0.1", 21768));
|
||||
const CAddress other(LookupNumeric("20.1.0.1", 21768));
|
||||
const CAddress known(LookupNumeric("20.2.0.1", 21768));
|
||||
ASSERT_TRUE(peer.IsValid() && other.IsValid() && known.IsValid());
|
||||
|
||||
CNode* node = new CNode(INVALID_SOCKET, peer, "", true); // inbound: sends no version message
|
||||
|
||||
ASSERT_TRUE(node->AddAddressIfNotAlreadyKnown(peer)); // the peer's own address is now known to it
|
||||
node->PushAddress(other);
|
||||
ASSERT_EQ(1u, node->vAddrToSend.size()) << "an unknown address was dropped because the peer's own address is known";
|
||||
EXPECT_TRUE(node->vAddrToSend[0] == other);
|
||||
|
||||
// An address the peer already knows is still filtered out.
|
||||
ASSERT_TRUE(node->AddAddressIfNotAlreadyKnown(known));
|
||||
node->PushAddress(known);
|
||||
EXPECT_EQ(1u, node->vAddrToSend.size()) << "an address the peer already knows was queued";
|
||||
|
||||
delete node;
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
// Copyright (c) 2016-2024 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
|
||||
//
|
||||
// DecodePaymentAddress must reject Sapling addresses that pass the bech32 checksum but
|
||||
// cannot receive funds (diversifier with no valid g_d, or pk_d not a prime-order Jubjub
|
||||
// point). Before this check, z_validateaddress said isvalid:true for them and z_sendmany
|
||||
// accepted them, then the async op failed with "Failed to build transaction." and took
|
||||
// every other recipient in the batch down with it (a mining pool's payouts stalled for
|
||||
// 10.5h on one such miner address).
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "arith_uint256.h"
|
||||
#include "bech32.h"
|
||||
#include "chainparams.h"
|
||||
#include "key_io.h"
|
||||
#include "uint256.h"
|
||||
#include "zcash/Address.hpp"
|
||||
#include "zcash/Note.hpp"
|
||||
#include "zcash/zip32.h"
|
||||
|
||||
#include <boost/variant.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
// Bech32 checksum and length are fine, so these test the curve check, not the decoder.
|
||||
void ExpectWellFormed(const std::string& s)
|
||||
{
|
||||
auto bech = bech32::Decode(s);
|
||||
ASSERT_EQ(bech.first, Params().Bech32HRP(CChainParams::SAPLING_PAYMENT_ADDRESS)) << s;
|
||||
ASSERT_EQ(bech.second.size(), (size_t)(((32 + 11) * 8 + 4) / 5)) << s;
|
||||
}
|
||||
|
||||
void ExpectRejected(const std::string& s)
|
||||
{
|
||||
auto decoded = DecodePaymentAddress(s);
|
||||
EXPECT_TRUE(boost::get<libzcash::InvalidEncoding>(&decoded) != nullptr) << s;
|
||||
EXPECT_FALSE(IsValidPaymentAddress(decoded)) << s;
|
||||
EXPECT_FALSE(IsValidPaymentAddressString(s, SAPLING_BRANCH_ID)) << s;
|
||||
}
|
||||
|
||||
void ExpectAccepted(const std::string& s)
|
||||
{
|
||||
auto decoded = DecodePaymentAddress(s);
|
||||
ASSERT_TRUE(boost::get<libzcash::SaplingPaymentAddress>(&decoded) != nullptr) << s;
|
||||
EXPECT_TRUE(IsValidPaymentAddress(decoded)) << s;
|
||||
EXPECT_EQ(EncodePaymentAddress(decoded), s);
|
||||
}
|
||||
|
||||
libzcash::SaplingExtendedSpendingKey TestKey(uint32_t i)
|
||||
{
|
||||
std::vector<unsigned char, secure_allocator<unsigned char>> rawSeed(32, 0x5a);
|
||||
HDSeed seed(rawSeed);
|
||||
return libzcash::SaplingExtendedSpendingKey::Master(seed).Derive(i | ZIP32_HARDENED_KEY_LIMIT);
|
||||
}
|
||||
|
||||
// is_valid() must agree with what the transaction builder sees: SaplingNote::cm() is the
|
||||
// call that fails in TransactionBuilder::Build for a bad recipient.
|
||||
bool BuilderCanCommit(const libzcash::SaplingPaymentAddress& addr)
|
||||
{
|
||||
return libzcash::SaplingNote(addr, 1).cm() != boost::none;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(SaplingAddressValidity, RejectsRealWorldUnpayableAddresses)
|
||||
{
|
||||
SelectParams(CBaseChainParams::MAIN);
|
||||
const std::vector<std::string> unpayable = {
|
||||
// pk_d is on the curve but not in the prime-order subgroup (the 2026-11-14 payout stall)
|
||||
"zs1w3jhmncfz0qkwkm857pt8g4dplvrnq42xg9xuas9uer0m05lugqjgvf8eum6gmc9ltd72e60t9u",
|
||||
// diversifier has no valid g_d
|
||||
"zs1d6w54jpkh28acqcknjc5alvnw649far8qv36smygszh27cg74f3g5cka3ahfsgqg03gr5e54d42",
|
||||
"zs1q9fnfa74uqpejjuwvs6h8zh7hh878s4n28u8vqzjzyyx06lawqn65lxl5enfn6k5q9d02pvlqak",
|
||||
};
|
||||
for (const auto& s : unpayable) {
|
||||
ExpectWellFormed(s);
|
||||
ExpectRejected(s);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(SaplingAddressValidity, AcceptsDerivedAndHardcodedAddresses)
|
||||
{
|
||||
SelectParams(CBaseChainParams::MAIN);
|
||||
|
||||
for (uint32_t i = 0; i < 20; i++) {
|
||||
auto sk = TestKey(i);
|
||||
ExpectAccepted(EncodePaymentAddress(sk.DefaultAddress()));
|
||||
|
||||
// Non-default diversifiers too: every valid d must give a payable address.
|
||||
auto ivk = sk.ToXFVK().fvk.in_viewing_key();
|
||||
int found = 0;
|
||||
for (uint32_t j = 0; j < 64 && found < 5; j++) {
|
||||
libzcash::diversifier_t d = {};
|
||||
d[0] = (unsigned char)j;
|
||||
d[1] = (unsigned char)i;
|
||||
auto addr = ivk.address(d);
|
||||
if (!addr) continue;
|
||||
found++;
|
||||
EXPECT_TRUE(addr->is_valid());
|
||||
ExpectAccepted(EncodePaymentAddress(*addr));
|
||||
}
|
||||
EXPECT_GT(found, 0);
|
||||
}
|
||||
|
||||
// Addresses hardcoded in the daemon (shieldcoinbase donation address and RPC help
|
||||
// examples) must keep decoding.
|
||||
ExpectAccepted("zs1uhmry4jjaymhh2x7x53fkahp57u60qr54ydtcd6c2nzu73lgm78a4kml2x7ylm547hu2qqtsnw5");
|
||||
ExpectAccepted("zs14d8tc0hl9q0vg5l28uec5vk6sk34fkj2n8s7jalvw5fxpy6v39yn4s2ga082lymrkjk0x2nqg37");
|
||||
ExpectAccepted("zs1z7rejlpsa98s2rrrfkwmaxu53e4ue0ulcrw0h4x5g8jl04tak0d3mm47vdtahatqrlkngh9slya");
|
||||
}
|
||||
|
||||
TEST(SaplingAddressValidity, RejectsConstructedBadPoints)
|
||||
{
|
||||
SelectParams(CBaseChainParams::MAIN);
|
||||
auto good = TestKey(0).DefaultAddress();
|
||||
ASSERT_TRUE(good.is_valid());
|
||||
|
||||
auto withPkd = [&](const std::string& hex) {
|
||||
uint256 pk_d;
|
||||
pk_d.SetHex(hex);
|
||||
return libzcash::SaplingPaymentAddress(good.d, pk_d);
|
||||
};
|
||||
|
||||
// (0, -1) has order 2: on the curve, not in the prime-order subgroup.
|
||||
auto order2 = withPkd("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000");
|
||||
// y = q + 1 would be the identity, but y >= q is not a canonical field element and is rejected.
|
||||
auto noncanon = withPkd("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000002");
|
||||
// y = 2: (y^2 - 1) / (d*y^2 + 1) is not a square, so there is no point with this y.
|
||||
auto offcurve = withPkd("02");
|
||||
|
||||
for (const auto& addr : {order2, noncanon, offcurve}) {
|
||||
EXPECT_FALSE(addr.is_valid()) << addr.pk_d.GetHex();
|
||||
EXPECT_FALSE(BuilderCanCommit(addr)) << addr.pk_d.GetHex();
|
||||
std::string s = EncodePaymentAddress(addr);
|
||||
ExpectWellFormed(s);
|
||||
ExpectRejected(s);
|
||||
}
|
||||
|
||||
// A diversifier with no valid g_d, paired with a good pk_d.
|
||||
bool sawBadD = false;
|
||||
for (uint32_t j = 0; j < 256 && !sawBadD; j++) {
|
||||
libzcash::diversifier_t d = {};
|
||||
d[0] = (unsigned char)j;
|
||||
d[10] = 0xa5;
|
||||
libzcash::SaplingPaymentAddress addr(d, good.pk_d);
|
||||
if (addr.is_valid()) continue;
|
||||
sawBadD = true;
|
||||
EXPECT_FALSE(BuilderCanCommit(addr));
|
||||
std::string s = EncodePaymentAddress(addr);
|
||||
ExpectWellFormed(s);
|
||||
ExpectRejected(s);
|
||||
}
|
||||
EXPECT_TRUE(sawBadD);
|
||||
|
||||
// The identity point is in the prime-order subgroup, and the builder accepts it, so
|
||||
// decoding does too. Funds sent there are unspendable, but that is no different from
|
||||
// sending to any address whose key nobody holds.
|
||||
auto identity = withPkd("01");
|
||||
EXPECT_TRUE(identity.is_valid());
|
||||
EXPECT_TRUE(BuilderCanCommit(identity));
|
||||
}
|
||||
|
||||
TEST(SaplingAddressValidity, IsValidMatchesBuilder)
|
||||
{
|
||||
SelectParams(CBaseChainParams::MAIN);
|
||||
auto good = TestKey(1).DefaultAddress();
|
||||
// Small y values hit every case: off-curve, small-order and prime-order points.
|
||||
int valid = 0, invalid = 0;
|
||||
for (int y = 0; y < 200; y++) {
|
||||
uint256 pk_d = ArithToUint256(arith_uint256(y));
|
||||
libzcash::SaplingPaymentAddress addr(good.d, pk_d);
|
||||
bool v = addr.is_valid();
|
||||
EXPECT_EQ(v, BuilderCanCommit(addr)) << "y=" << y;
|
||||
(v ? valid : invalid)++;
|
||||
}
|
||||
EXPECT_GT(valid, 0);
|
||||
EXPECT_GT(invalid, 0);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
// Copyright (c) 2016-2024 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
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <boost/optional.hpp>
|
||||
|
||||
#include "primitives/transaction.h"
|
||||
#include "uint256.h"
|
||||
#include "wallet/asyncrpcoperation_sweep.h"
|
||||
#include "zcash/IncrementalMerkleTree.hpp"
|
||||
|
||||
namespace {
|
||||
|
||||
// A witness in a one-leaf tree: each leaf gives a different root().
|
||||
SaplingWitness WitnessAt(const std::string& leaf)
|
||||
{
|
||||
SaplingMerkleTree tree;
|
||||
tree.append(uint256S(leaf));
|
||||
return tree.witness();
|
||||
}
|
||||
|
||||
const SaplingWitness GOOD = WitnessAt("0a"); // at an anchor the chain knows
|
||||
const SaplingWitness OTHER = WitnessAt("0c"); // at another known anchor
|
||||
SaplingWitness Bad(int i) { return WitnessAt("b0" + std::to_string(i)); } // desynced: roots the chain never had
|
||||
|
||||
SaplingOutPoint Op(int i) { return SaplingOutPoint(uint256S("f0"), i); }
|
||||
|
||||
// Stands in for the wallet: each note's latest cached witness (none = no witness) and the chainstate's
|
||||
// anchors. Counts how many notes the selection asked about.
|
||||
struct FakeWallet {
|
||||
std::map<SaplingOutPoint, boost::optional<SaplingWitness>> latest;
|
||||
std::set<uint256> knownAnchors{GOOD.root(), OTHER.root()};
|
||||
int calls = 0;
|
||||
size_t asked = 0;
|
||||
|
||||
SweepNoteSelection Select(size_t n, size_t maxInputs)
|
||||
{
|
||||
std::vector<SaplingOutPoint> ops;
|
||||
for (size_t i = 0; i < n; i++)
|
||||
ops.push_back(Op(i));
|
||||
return SelectSweepableNotes(ops, maxInputs,
|
||||
[this](const std::vector<SaplingOutPoint>& o) {
|
||||
calls++;
|
||||
asked += o.size();
|
||||
std::vector<boost::optional<SaplingWitness>> out;
|
||||
for (const SaplingOutPoint& op : o)
|
||||
out.push_back(latest[op]);
|
||||
return out;
|
||||
},
|
||||
[this](const uint256& root) { return knownAnchors.count(root) > 0; });
|
||||
}
|
||||
};
|
||||
|
||||
std::vector<size_t> V(std::initializer_list<size_t> l) { return std::vector<size_t>(l); }
|
||||
std::vector<size_t> Range(size_t from, size_t to) { std::vector<size_t> v; for (size_t i = from; i < to; i++) v.push_back(i); return v; }
|
||||
|
||||
}
|
||||
|
||||
TEST(SweepNoteSelection, TakesAtMostMaxInputsAndDoesNotSkipTheRest) {
|
||||
FakeWallet w;
|
||||
for (int i = 0; i < 7; i++) w.latest[Op(i)] = GOOD;
|
||||
SweepNoteSelection sel = w.Select(7, 5);
|
||||
EXPECT_EQ(Range(0, 5), sel.chosen);
|
||||
EXPECT_EQ(5u, sel.witnesses.size());
|
||||
EXPECT_EQ(GOOD.root(), sel.anchor);
|
||||
EXPECT_TRUE(sel.skipped.empty()) << "notes past the cap are left for the next round, not skipped";
|
||||
}
|
||||
|
||||
// A healthy address costs about what the old first-maxInputs selection did: one window of 2*maxInputs.
|
||||
TEST(SweepNoteSelection, AHealthyAddressReadsOneWindow) {
|
||||
FakeWallet w;
|
||||
for (int i = 0; i < 200; i++) w.latest[Op(i)] = GOOD;
|
||||
SweepNoteSelection sel = w.Select(200, 5);
|
||||
EXPECT_EQ(Range(0, 5), sel.chosen);
|
||||
EXPECT_EQ(1, w.calls);
|
||||
EXPECT_EQ(10u, w.asked);
|
||||
EXPECT_TRUE(sel.skipped.empty());
|
||||
}
|
||||
|
||||
TEST(SweepNoteSelection, SkipsNotesWithoutAWitness) {
|
||||
FakeWallet w;
|
||||
for (int i = 0; i < 5; i++) w.latest[Op(i)] = GOOD;
|
||||
w.latest[Op(0)] = boost::none;
|
||||
w.latest[Op(2)] = boost::none;
|
||||
SweepNoteSelection sel = w.Select(5, 5);
|
||||
EXPECT_EQ(V({1, 3, 4}), sel.chosen);
|
||||
EXPECT_EQ(V({0, 2}), sel.skipped);
|
||||
}
|
||||
|
||||
// The case seen on a real wallet: desynced notes outnumber the good ones at their address.
|
||||
TEST(SweepNoteSelection, PassesOverADesyncedMajority) {
|
||||
FakeWallet w;
|
||||
for (int i = 0; i < 3; i++) w.latest[Op(i)] = Bad(0);
|
||||
for (int i = 3; i < 5; i++) w.latest[Op(i)] = GOOD;
|
||||
SweepNoteSelection sel = w.Select(5, 5);
|
||||
EXPECT_EQ(V({3, 4}), sel.chosen);
|
||||
EXPECT_EQ(GOOD.root(), sel.anchor);
|
||||
EXPECT_EQ(V({0, 1, 2}), sel.skipped);
|
||||
}
|
||||
|
||||
// A run of bad notes at the front must not hide good notes behind it.
|
||||
TEST(SweepNoteSelection, ADesyncedRunAtTheFrontDoesNotHideTheRest) {
|
||||
FakeWallet w;
|
||||
for (int i = 0; i < 12; i++) w.latest[Op(i)] = Bad(0);
|
||||
for (int i = 12; i < 14; i++) w.latest[Op(i)] = GOOD;
|
||||
SweepNoteSelection sel = w.Select(14, 5);
|
||||
EXPECT_EQ(V({12, 13}), sel.chosen);
|
||||
EXPECT_EQ(Range(0, 12), sel.skipped);
|
||||
}
|
||||
|
||||
// However the desynced notes split, a good group is found: no limit on the number of bad roots.
|
||||
TEST(SweepNoteSelection, ALoneGoodNoteBehindManyDesyncedGroups) {
|
||||
FakeWallet w;
|
||||
for (int g = 0; g < 5; g++)
|
||||
for (int j = 0; j < 2; j++)
|
||||
w.latest[Op(g * 2 + j)] = Bad(g);
|
||||
w.latest[Op(10)] = GOOD;
|
||||
SweepNoteSelection sel = w.Select(11, 5);
|
||||
EXPECT_EQ(V({10}), sel.chosen);
|
||||
EXPECT_EQ(Range(0, 10), sel.skipped);
|
||||
}
|
||||
|
||||
TEST(SweepNoteSelection, NothingWhenNoWitnessIsAtAKnownAnchor) {
|
||||
FakeWallet w;
|
||||
for (int i = 0; i < 4; i++) w.latest[Op(i)] = Bad(i % 2);
|
||||
w.latest[Op(4)] = boost::none;
|
||||
SweepNoteSelection sel = w.Select(5, 5);
|
||||
EXPECT_TRUE(sel.chosen.empty());
|
||||
EXPECT_TRUE(sel.witnesses.empty());
|
||||
EXPECT_EQ(Range(0, 5), sel.skipped);
|
||||
}
|
||||
|
||||
// Two real anchors: one transaction can only use one, so the larger group is spent and the other waits
|
||||
// for a later round.
|
||||
TEST(SweepNoteSelection, OneAnchorPerTransaction) {
|
||||
FakeWallet w;
|
||||
for (int i = 0; i < 3; i++) w.latest[Op(i)] = GOOD;
|
||||
for (int i = 3; i < 5; i++) w.latest[Op(i)] = OTHER;
|
||||
SweepNoteSelection sel = w.Select(5, 5);
|
||||
EXPECT_EQ(V({0, 1, 2}), sel.chosen);
|
||||
EXPECT_EQ(GOOD.root(), sel.anchor);
|
||||
EXPECT_EQ(V({3, 4}), sel.skipped);
|
||||
}
|
||||
|
||||
TEST(SweepNoteSelection, NoCandidates) {
|
||||
FakeWallet w;
|
||||
SweepNoteSelection sel = w.Select(0, 5);
|
||||
EXPECT_TRUE(sel.chosen.empty());
|
||||
EXPECT_TRUE(sel.skipped.empty());
|
||||
EXPECT_EQ(0, w.calls);
|
||||
}
|
||||
@@ -381,3 +381,46 @@ TEST_F(WalletShutdownSaveDb, AddingANoteNeedsASave) {
|
||||
ASSERT_TRUE(wallet.AddToWallet(wtx, false, &walletdb));
|
||||
EXPECT_EQ("nothing changed since the last save", Reason(wallet, true)) << "the same tx again";
|
||||
}
|
||||
|
||||
// While the startup rescan is running or was cut short, init has not seeded the wallet tip yet, and the
|
||||
// only stamp that can arrive is FlushStateToDisk's chain tip (its hourly write, or the one in Shutdown).
|
||||
// Writing that over the scan's own locator would mark the unscanned range as scanned -- after
|
||||
// -zapwallettxes, its transactions would be gone from the wallet. It must write nothing.
|
||||
TEST_F(WalletShutdownSave, DoesNotStampTheChainTipOverAnIncompleteStartupRescan) {
|
||||
CBlockLocator chainTip(std::vector<uint256>{uint256S("0def")});
|
||||
|
||||
SaveWallet wallet;
|
||||
wallet.NoteRescanStarted(0);
|
||||
{
|
||||
FakeWalletDB db;
|
||||
EXPECT_FALSE(wallet.SetBestChainWith(db, chainTip)) << "while the scan runs";
|
||||
EXPECT_TRUE(db.written.vHave.empty());
|
||||
}
|
||||
wallet.NoteRescanInterrupted(500);
|
||||
{
|
||||
FakeWalletDB db;
|
||||
EXPECT_FALSE(wallet.SetBestChainWith(db, chainTip)) << "after the scan was cut short";
|
||||
EXPECT_TRUE(db.written.vHave.empty());
|
||||
}
|
||||
|
||||
// Once init seeds the wallet tip (at the scan's checkpoint, when it was cut short), that is stamped.
|
||||
uint256 hash = uint256S("0abc");
|
||||
CBlockIndex tip;
|
||||
tip.phashBlock = &hash;
|
||||
wallet.SetWalletTip(&tip);
|
||||
{
|
||||
FakeWalletDB db;
|
||||
EXPECT_TRUE(wallet.SetBestChainWith(db, chainTip));
|
||||
ASSERT_FALSE(db.written.vHave.empty());
|
||||
EXPECT_EQ(hash, db.written.vHave.front());
|
||||
}
|
||||
|
||||
// A startup scan that completed leaves nothing to protect: init's own stamp goes through.
|
||||
SaveWallet completed;
|
||||
int before = completed.NoteRescanStarted(0);
|
||||
completed.NoteRescanCompleted(0, before);
|
||||
FakeWalletDB db;
|
||||
EXPECT_TRUE(completed.SetBestChainWith(db, chainTip));
|
||||
ASSERT_FALSE(db.written.vHave.empty());
|
||||
EXPECT_EQ(uint256S("0def"), db.written.vHave.front());
|
||||
}
|
||||
|
||||
@@ -420,6 +420,10 @@ static void libevent_log_cb(int severity, const char *msg)
|
||||
LogPrint("libevent", "libevent: %s\n", msg);
|
||||
}
|
||||
|
||||
/** Maximum size of an HTTP request line + headers. libevent's default is unbounded and it
|
||||
* buffers all of it before the -rpcallowip ACL and auth checks run. Same value as upstream. */
|
||||
static const size_t MAX_HEADERS_SIZE = 8192;
|
||||
|
||||
bool InitHTTPServer()
|
||||
{
|
||||
struct evhttp* http = 0;
|
||||
@@ -466,6 +470,7 @@ bool InitHTTPServer()
|
||||
}
|
||||
|
||||
evhttp_set_timeout(http, GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
|
||||
evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
|
||||
evhttp_set_max_body_size(http, MAX_SIZE);
|
||||
evhttp_set_gencb(http, http_request_cb, NULL);
|
||||
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Copyright (c) 2016-2024 The Hush developers
|
||||
# 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
|
||||
|
||||
DEFAULTS=""
|
||||
|
||||
# People can just use hushd going forward, but this script makes it
|
||||
# more clear what is going on
|
||||
HUSH="./hushd"
|
||||
$HUSH $DEFAULTS "$@"
|
||||
@@ -1,10 +0,0 @@
|
||||
:: Copyright (c) 2016-2024 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
|
||||
@call :GET_CURRENT_DIR
|
||||
@cd %THIS_DIR%
|
||||
hushd %*
|
||||
@goto :EOF
|
||||
|
||||
:GET_CURRENT_DIR
|
||||
@pushd %~dp0
|
||||
+1
-1
@@ -961,7 +961,7 @@ CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
|
||||
// This function defines the Hush Founders Reward (AKA Dev Tax)
|
||||
// 10% of all block rewards go towards Hush core team
|
||||
// If you do not like this, you are encouraged to fork the chain
|
||||
// or start your own Hush Arrakis Chain: https://git.hush.is/hush/hush-arrakis-chains
|
||||
// or start your own chain.
|
||||
// HUSH supply curve cannot be exactly represented via CLI args, so we do it ourselves.
|
||||
// You specify the BR, and the FR % gets added so 10% of 12.5 is 1.25
|
||||
// but to tell the AC params, I need to say "11% of 11.25" is 1.25
|
||||
|
||||
+1
-1
@@ -72,7 +72,7 @@ const uint32_t nHushHardforkHeight4 = 1605555;
|
||||
const uint32_t nHushHardforkTimestamp = 1580303652; // Jan 29nd 1pm GMT
|
||||
const uint32_t nHushHardforkTimestamp2 = 1594425600; // Jul 11th 12a GMT
|
||||
|
||||
// Used by HACs
|
||||
// Used by smart chains
|
||||
static const uint32_t HUSH_SEASON_TIMESTAMPS[NUM_HUSH_SEASONS] = {1525132800, 1563148800, nHushHardforkTimestamp, nHushHardforkTimestamp2, nHushHardforkTimestamp2*5, nHushHardforkTimestamp2*6, nHushHardforkTimestamp2*7};
|
||||
|
||||
// Used by HUSH3+TUSH
|
||||
|
||||
+2
-2
@@ -101,7 +101,7 @@ 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 hush_pubkeys[NUM_HUSH_SEASONS][64][33],didinit[NUM_HUSH_SEASONS];
|
||||
|
||||
//HUSH3+TUSH use block heights, HACs use timestamps
|
||||
//HUSH3+TUSH use block heights, other smart chains use timestamps
|
||||
if ( timestamp == 0 && SMART_CHAIN_SYMBOL[0] != 0 ) {
|
||||
timestamp = hush_heightstamp(height);
|
||||
} else if ( SMART_CHAIN_SYMBOL[0] == 0 ) {
|
||||
@@ -112,7 +112,7 @@ 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;
|
||||
bool istush = strncmp(SMART_CHAIN_SYMBOL, "TUSH",4) == 0 ? true : false;
|
||||
// TUSH uses height activation like HUSH3, other HACs use timestamps
|
||||
// TUSH uses height activation like HUSH3, other smart chains use timestamps
|
||||
hush_season = (ishush3 || istush) ? gethushseason(height) : getacseason(timestamp);
|
||||
|
||||
if(IS_HUSH_NOTARY) {
|
||||
|
||||
+1
-1
@@ -1913,7 +1913,7 @@ void hush_args(char *argv0)
|
||||
} else if (strncmp(SMART_CHAIN_SYMBOL, "TUMIN", 5) == 0) {
|
||||
ASSETCHAINS_RANDOMX_VALIDATION = 1200; // TBD: set to coordinated upgrade height
|
||||
} else {
|
||||
ASSETCHAINS_RANDOMX_VALIDATION = 1; // all other RandomX HACs: enforce from height 1
|
||||
ASSETCHAINS_RANDOMX_VALIDATION = 1; // all other RandomX smart chains: enforce from height 1
|
||||
}
|
||||
LogPrintf("ASSETCHAINS_RANDOMX_VALIDATION set to %d for %s\n", ASSETCHAINS_RANDOMX_VALIDATION, SMART_CHAIN_SYMBOL);
|
||||
}
|
||||
|
||||
+57
-2
@@ -656,7 +656,7 @@ std::string HelpMessage(HelpMessageMode mode)
|
||||
strUsage += HelpMessageOpt("-zsweepaddress=<zaddr>", _("Specify the shielded address where swept funds will be sent)"));
|
||||
strUsage += HelpMessageOpt("-zsweepfee", strprintf(_("Fee amount in puposhis used send sweep transactions. (default %i)"), DEFAULT_SWEEP_FEE));
|
||||
strUsage += HelpMessageOpt("-zsweepinterval", strprintf(_("Sweep shielded funds every X blocks (default %i)"), 10));
|
||||
strUsage += HelpMessageOpt("-zsweepmaxinputs", strprintf(_("Maximum number of shielded inputs to sweep per transaction (default %i)"), 8));
|
||||
strUsage += HelpMessageOpt("-zsweepmaxinputs", strprintf(_("Maximum number of shielded inputs to sweep per transaction, %i to %i (default %i)"), MIN_SWEEP_MAX_INPUTS, MAX_SWEEP_MAX_INPUTS, DEFAULT_SWEEP_MAX_INPUTS));
|
||||
// By default we only allow sweeping to the current wallet which must have the spending key of the sweep zaddr
|
||||
// This hopefully will make it harder for people to accidentally sweep funds to a wrong zaddr and lose funds
|
||||
strUsage += HelpMessageOpt("-zsweepexternal", _("Enable sweeping to an external wallet (default false)"));
|
||||
@@ -824,7 +824,7 @@ std::string HelpMessage(HelpMessageMode mode)
|
||||
strUsage += HelpMessageOpt("-ac_randomx_interval", _("Controls how often the RandomX key block will change, default is 1024"));
|
||||
strUsage += HelpMessageOpt("-ac_randomx_lag", _("Sets the number of RandomX blocks to wait before updating the key block, default is 64"));
|
||||
strUsage += HelpMessageOpt("-ac_reward", _("Block reward in satoshis, default is 0"));
|
||||
// All HAC's activate sapling at block height 1, other heights are not supported
|
||||
// All smart chains activate sapling at block height 1, other heights are not supported
|
||||
//strUsage += HelpMessageOpt("-ac_sapling", _("Sapling activation block height"));
|
||||
strUsage += HelpMessageOpt("-ac_script", _("P2SH/multisig address to receive founders rewards"));
|
||||
strUsage += HelpMessageOpt("-ac_supply", _("Starting supply, default is 10"));
|
||||
@@ -1306,6 +1306,44 @@ static void AdjustCoinCacheForMemoryPressure()
|
||||
nCoinCacheUsage = (size_t)(newTargetMB << 20);
|
||||
}
|
||||
|
||||
#ifdef ENABLE_WALLET
|
||||
// Where a forced wallet rescan (-rescan, -zapwallettxes, a witness-cache reset) starts: genesis, or
|
||||
// -rescanheight capped at the tip.
|
||||
static CBlockIndex* ForcedRescanStart()
|
||||
{
|
||||
int rescanHeight = GetArg("-rescanheight", 0);
|
||||
if (rescanHeight > 0)
|
||||
return rescanHeight > chainActive.Tip()->GetHeight() ? chainActive.Tip() : chainActive[rescanHeight];
|
||||
return chainActive.Genesis();
|
||||
}
|
||||
|
||||
// A forced rescan starts below the locator on disk, which ScanForWalletTransactions only ever moves
|
||||
// forward. Left there, a scan cut short -- a shutdown, abortrescan, or a kill -- would leave it at the
|
||||
// old tip, and the next normal start would skip everything the scan had not reached. After
|
||||
// -zapwallettxes that range's transactions are simply gone from the wallet until someone rescans
|
||||
// again. So move the locator back to where the scan starts: an interrupted scan then checkpoints
|
||||
// forward from there, and a killed one restarts from there. Never moves the locator forward.
|
||||
static void RewindWalletLocatorForRescan(const std::string& strWalletFile, const CBlockIndex* pindexRescan)
|
||||
{
|
||||
if (pindexRescan == NULL)
|
||||
return;
|
||||
CWalletDB walletdb(strWalletFile);
|
||||
CBlockLocator locPersisted;
|
||||
if (!walletdb.ReadBestBlock(locPersisted))
|
||||
return;
|
||||
CBlockIndex* pindexPersisted = FindForkInGlobalIndex(chainActive, locPersisted);
|
||||
if (pindexPersisted == NULL || pindexPersisted->GetHeight() <= pindexRescan->GetHeight())
|
||||
return;
|
||||
if (walletdb.WriteBestBlock(chainActive.GetLocator(pindexRescan)))
|
||||
LogPrintf("%s: moved the wallet's best-block locator back from height %d to %d, where the rescan "
|
||||
"starts, so an interrupted rescan resumes instead of skipping the rest\n",
|
||||
__func__, pindexPersisted->GetHeight(), pindexRescan->GetHeight());
|
||||
else
|
||||
LogPrintf("%s: WARNING: could not move the wallet's best-block locator back to height %d; "
|
||||
"if the rescan is interrupted, restart with -rescan\n", __func__, pindexRescan->GetHeight());
|
||||
}
|
||||
#endif
|
||||
|
||||
bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
|
||||
{
|
||||
// ********************************************************* Step 1: setup
|
||||
@@ -2411,6 +2449,12 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
|
||||
|
||||
delete pwalletMain;
|
||||
pwalletMain = NULL;
|
||||
|
||||
// The zap is on disk now. Rewind the locator straight away rather than at the rescan below:
|
||||
// if startup fails in between (a config error, say), the next start must still rescan the
|
||||
// erased range rather than trust the old tip.
|
||||
if (chainActive.Tip() != NULL)
|
||||
RewindWalletLocatorForRescan(strWalletFile, ForcedRescanStart());
|
||||
}
|
||||
|
||||
uiInterface.InitMessage(_("Loading wallet..."));
|
||||
@@ -2630,6 +2674,13 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
|
||||
LogPrintf("%s: set nextSweep=%d with sweepInterval=%d\n", __func__, pwalletMain->nextSweep, pwalletMain->sweepInterval );
|
||||
fSweepTxFee = GetArg("-zsweepfee", DEFAULT_SWEEP_FEE);
|
||||
fSweepMapUsed = !mapMultiArgs["-zsweepaddress"].empty();
|
||||
int sweepMaxInputs = GetArg("-zsweepmaxinputs", DEFAULT_SWEEP_MAX_INPUTS);
|
||||
if (sweepMaxInputs < MIN_SWEEP_MAX_INPUTS || sweepMaxInputs > MAX_SWEEP_MAX_INPUTS) {
|
||||
LogPrintf("%s: Invalid -zsweepmaxinputs=%d (must be %d to %d), using the default of %d\n", __func__,
|
||||
sweepMaxInputs, MIN_SWEEP_MAX_INPUTS, MAX_SWEEP_MAX_INPUTS, DEFAULT_SWEEP_MAX_INPUTS);
|
||||
sweepMaxInputs = DEFAULT_SWEEP_MAX_INPUTS;
|
||||
}
|
||||
pwalletMain->sweepMaxInputs = sweepMaxInputs;
|
||||
|
||||
//Validate Sapling Addresses
|
||||
vector<string>& vSweep = mapMultiArgs["-zsweepaddress"];
|
||||
@@ -2869,6 +2920,10 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
|
||||
pindexRescan = chainActive[rescanHeight];
|
||||
}
|
||||
}
|
||||
|
||||
// See RewindWalletLocatorForRescan. (After -zapwallettxes this already happened, right after
|
||||
// the zap; doing it again is a no-op.)
|
||||
RewindWalletLocatorForRescan(strWalletFile, pindexRescan);
|
||||
} else {
|
||||
CWalletDB walletdb(strWalletFile);
|
||||
CBlockLocator locator;
|
||||
|
||||
+8
-1
@@ -304,7 +304,14 @@ libzcash::PaymentAddress DecodePaymentAddress(const std::string& str)
|
||||
CDataStream ss(data, SER_NETWORK, PROTOCOL_VERSION);
|
||||
libzcash::SaplingPaymentAddress ret;
|
||||
ss >> ret;
|
||||
return ret;
|
||||
// A good checksum is not enough: reject addresses whose diversifier or pk_d is
|
||||
// not a valid curve point. Nothing can ever be sent to them, and before this
|
||||
// check z_validateaddress called them valid and z_sendmany accepted them, only
|
||||
// for the async operation to fail with "Failed to build transaction." and take
|
||||
// every other recipient in the batch down with it.
|
||||
if (ret.is_valid()) {
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
}
|
||||
return libzcash::InvalidEncoding();
|
||||
|
||||
+21
-18
@@ -5372,7 +5372,7 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta
|
||||
}
|
||||
}
|
||||
|
||||
// Check Proof-of-Work difficulty for smart chains (HACs)
|
||||
// Check Proof-of-Work difficulty for smart chains
|
||||
// Without this check, an attacker can submit blocks with arbitrary nBits
|
||||
// (e.g., powLimit / diff=1) and they will be accepted, allowing the chain
|
||||
// to be flooded with minimum-difficulty blocks.
|
||||
@@ -5381,7 +5381,7 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta
|
||||
if (!ishush3 && SMART_CHAIN_SYMBOL[0] != 0 && nHeight > daaForkHeight) {
|
||||
unsigned int nNextWork = GetNextWorkRequired(pindexPrev, &block, consensusParams);
|
||||
if (fDebug) {
|
||||
LogPrintf("%s: HAC nbits height=%d expected=%lu actual=%lu\n",
|
||||
LogPrintf("%s: nbits height=%d expected=%lu actual=%lu\n",
|
||||
__func__, nHeight, (unsigned long)nNextWork, (unsigned long)block.nBits);
|
||||
}
|
||||
if (block.nBits != nNextWork) {
|
||||
@@ -8412,6 +8412,20 @@ bool SendMessages(CNode* pto, bool fSendTrickle)
|
||||
// Message: addr
|
||||
if (fSendTrickle)
|
||||
{
|
||||
// Collect the addresses the peer doesn't know yet into vAddr and send that, once
|
||||
// (in MAX_ADDR_TO_SEND batches). This used to push the whole of vAddrToSend for every
|
||||
// accepted address, so one getaddr reply went out as N messages of N addresses.
|
||||
const char* msg_type;
|
||||
int make_flags;
|
||||
if (pto->m_wants_addrv2) {
|
||||
msg_type = NetMsgType::ADDRV2;
|
||||
make_flags = ADDRV2_FORMAT;
|
||||
} else {
|
||||
msg_type = NetMsgType::ADDR;
|
||||
make_flags = 0;
|
||||
}
|
||||
const CNetMsgMaker msgMaker(std::min(pto->nVersion, PROTOCOL_VERSION));
|
||||
|
||||
vector<CAddress> vAddr;
|
||||
vAddr.reserve(pto->vAddrToSend.size());
|
||||
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
|
||||
@@ -8419,29 +8433,18 @@ bool SendMessages(CNode* pto, bool fSendTrickle)
|
||||
if (pto->AddAddressIfNotAlreadyKnown(addr))
|
||||
{
|
||||
vAddr.push_back(addr);
|
||||
|
||||
// receiver penalizes a message of more than MAX_ADDR_TO_SEND addresses
|
||||
if (vAddr.size() >= MAX_ADDR_TO_SEND)
|
||||
{
|
||||
// Should be impossible since we always check size before adding to
|
||||
// vAddrToSend. Recover by trimming the vector.
|
||||
vAddr.resize(MAX_ADDR_TO_SEND);
|
||||
pto->PushAddrMessage(msgMaker.Make(make_flags, msg_type, vAddr));
|
||||
vAddr.clear();
|
||||
}
|
||||
const char* msg_type;
|
||||
int make_flags;
|
||||
if (pto->m_wants_addrv2) {
|
||||
msg_type = NetMsgType::ADDRV2;
|
||||
make_flags = ADDRV2_FORMAT;
|
||||
} else {
|
||||
msg_type = NetMsgType::ADDR;
|
||||
make_flags = 0;
|
||||
}
|
||||
pto->PushAddrMessage(CNetMsgMaker(std::min(pto->nVersion, PROTOCOL_VERSION)).Make(make_flags, msg_type, pto->vAddrToSend));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
pto->vAddrToSend.clear();
|
||||
vAddr.clear();
|
||||
if (!vAddr.empty())
|
||||
pto->PushAddrMessage(msgMaker.Make(make_flags, msg_type, vAddr));
|
||||
}
|
||||
|
||||
CNodeState &state = *State(pto->GetId());
|
||||
|
||||
+3
-3
@@ -1216,15 +1216,15 @@ void static RandomXMiner()
|
||||
char randomxHash[RANDOMX_HASH_SIZE];
|
||||
rxdebug("%s: created randomxHash of size %d\n", RANDOMX_HASH_SIZE);
|
||||
char randomxKey[82]; // randomx spec says keysize of >60 bytes is implementation-specific
|
||||
// initial randomx key is unique to every Hush Arrakis Chain, and has at least 9 bytes (2^9=128 bits) of entropy
|
||||
// initial randomx key is unique to every smart chain, and has at least 9 bytes (2^9=128 bits) of entropy
|
||||
// since magic is 4 bytes, rpc port is 4 bytes and smart chain symbol must be at least 1 character long
|
||||
snprintf(randomxKey, 81, "%08x%s%08x", ASSETCHAINS_MAGIC, SMART_CHAIN_SYMBOL, ASSETCHAINS_RPCPORT);
|
||||
|
||||
// With the defaults of 1024 and 64
|
||||
// the key block will change every ~21.3 hours with a 75s block time
|
||||
// and every ~17 hours with the default 60s block time for HACs
|
||||
// and every ~17 hours with the default 60s block time for smart chains
|
||||
static int randomxInterval = GetRandomXInterval();
|
||||
// This lag is 80 mins for 75s blocktime and 64 mins for 60s (default) blocktime for HACs
|
||||
// This lag is 80 mins for 75s blocktime and 64 mins for 60s (default) blocktime for smart chains
|
||||
static int randomxBlockLag = GetRandomXBlockLag();
|
||||
randomx_vm *myVM = nullptr;
|
||||
|
||||
|
||||
+11
@@ -2974,6 +2974,17 @@ size_t GetNodeCount(NumConnections flags)
|
||||
return nNum;
|
||||
}
|
||||
|
||||
void GetNodeCounts(int& nAll, int& nTls)
|
||||
{
|
||||
LOCK(cs_vNodes);
|
||||
nAll = (int)vNodes.size();
|
||||
nTls = 0;
|
||||
for (const CNode* pnode : vNodes) {
|
||||
if (pnode->ssl != NULL)
|
||||
nTls++;
|
||||
}
|
||||
}
|
||||
|
||||
void SetNetworkActive(bool active)
|
||||
{
|
||||
LogPrint("net", "SetNetworkActive: %s\n", active);
|
||||
|
||||
@@ -173,6 +173,8 @@ enum NumConnections {
|
||||
};
|
||||
|
||||
size_t GetNodeCount(NumConnections num);
|
||||
// All peers and TLS peers, counted under one hold of cs_vNodes so that nTls <= nAll.
|
||||
void GetNodeCounts(int& nAll, int& nTls);
|
||||
|
||||
bool GetNetworkActive();
|
||||
void SetNetworkActive(bool active);
|
||||
@@ -615,7 +617,9 @@ public:
|
||||
// Known checking here is only to save space from duplicates.
|
||||
// SendMessages will filter it again for knowns that were added
|
||||
// after addresses were pushed.
|
||||
if (_addr.IsValid() && !IsAddressKnown(addr) && addr_format_supported) {
|
||||
// Test _addr, the address being queued: the member `addr` is this peer's own address, and
|
||||
// once that was in addrKnown every address queued for the peer was dropped.
|
||||
if (_addr.IsValid() && !IsAddressKnown(_addr) && addr_format_supported) {
|
||||
|
||||
if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
|
||||
vAddrToSend[insecure_rand() % vAddrToSend.size()] = _addr;
|
||||
|
||||
+22
-7
@@ -534,6 +534,9 @@ UniValue getblockdeltas(const UniValue& params, bool fHelp, const CPubKey& mypk)
|
||||
if (fHelp || params.size() != 1)
|
||||
throw runtime_error("");
|
||||
|
||||
// mapBlockIndex and chainActive (read here and in blockToDeltasJSON) are guarded by cs_main.
|
||||
LOCK(cs_main);
|
||||
|
||||
std::string strHash = params[0].get_str();
|
||||
uint256 hash(uint256S(strHash));
|
||||
|
||||
@@ -602,11 +605,20 @@ UniValue getblockhashes(const UniValue& params, bool fHelp, const CPubKey& mypk)
|
||||
|
||||
std::vector<std::pair<uint256, unsigned int> > blockHashes;
|
||||
|
||||
if (fActiveOnly)
|
||||
LOCK(cs_main);
|
||||
|
||||
if (!GetTimestampIndex(high, low, fActiveOnly, blockHashes)) {
|
||||
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for block hashes");
|
||||
{
|
||||
// With noOrphans, GetTimestampIndex checks every row against mapBlockIndex/chainActive, so
|
||||
// cs_main must span the call (the old unbraced "if (fActiveOnly) LOCK(cs_main);" released it
|
||||
// on the same line). Without noOrphans it only walks the LevelDB index, so no lock is taken:
|
||||
// holding cs_main over a wide range would stall block validation for the whole scan.
|
||||
bool fFound;
|
||||
if (fActiveOnly) {
|
||||
LOCK(cs_main);
|
||||
fFound = GetTimestampIndex(high, low, fActiveOnly, blockHashes);
|
||||
} else {
|
||||
fFound = GetTimestampIndex(high, low, fActiveOnly, blockHashes);
|
||||
}
|
||||
if (!fFound)
|
||||
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for block hashes");
|
||||
}
|
||||
|
||||
UniValue result(UniValue::VARR);
|
||||
@@ -868,7 +880,7 @@ UniValue getblockmerkletree(const UniValue& params, bool fHelp, const CPubKey& m
|
||||
if (fHelp || params.size() != 1 )
|
||||
throw runtime_error(
|
||||
"getblockmerkletree height\n"
|
||||
"\nGet full merkletree for a given Hush or HAC block height.\n"
|
||||
"\nGet full merkletree for a given block height.\n"
|
||||
"\nArguments:\n"
|
||||
"1. height (int, required) block height\n"
|
||||
"\nResult:\n"
|
||||
@@ -877,13 +889,16 @@ UniValue getblockmerkletree(const UniValue& params, bool fHelp, const CPubKey& m
|
||||
+ HelpExampleRpc("getblockmerkletree", "290000")
|
||||
);
|
||||
|
||||
// chainActive and pcoinsTip (whose anchor cache inserts on a miss) are guarded by cs_main.
|
||||
LOCK(cs_main);
|
||||
|
||||
CBlockIndex* phushblockindex;
|
||||
uint256 blockRoot;
|
||||
SaplingMerkleTree tree;
|
||||
|
||||
int nHeight = params[0].get_int();
|
||||
if ( (nHeight < 1) || (nHeight > chainActive.LastTip()->GetHeight()) ) {
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid Hush or HAC block height parameter");
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid block height parameter");
|
||||
}
|
||||
|
||||
phushblockindex = chainActive[nHeight];
|
||||
|
||||
+26
-7
@@ -71,6 +71,22 @@ uint64_t the_commission(const CBlock *pblock,int32_t height);
|
||||
int32_t hush_blockload(CBlock& block,CBlockIndex *pindex);
|
||||
arith_uint256 hush_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);
|
||||
|
||||
/**
|
||||
* Releases cs_main for its scope and re-acquires it on exit, including when unwinding.
|
||||
* For code already holding cs_main through a scoped LOCK(cs_main): if an exception escaped
|
||||
* while cs_main was released by hand, that LOCK's destructor would unlock a mutex this thread
|
||||
* no longer owns (BOOST_VERIFY -> abort).
|
||||
*/
|
||||
class CMainUnlockScope
|
||||
{
|
||||
public:
|
||||
CMainUnlockScope() { LEAVE_CRITICAL_SECTION(cs_main); }
|
||||
~CMainUnlockScope() { ENTER_CRITICAL_SECTION(cs_main); }
|
||||
private:
|
||||
CMainUnlockScope(const CMainUnlockScope&);
|
||||
CMainUnlockScope& operator=(const CMainUnlockScope&);
|
||||
};
|
||||
|
||||
/**
|
||||
* Return average network hashes per second based on the last 'lookup' blocks,
|
||||
* or over the difficulty averaging window if 'lookup' is nonpositive.
|
||||
@@ -712,8 +728,8 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp, const CPubKey& myp
|
||||
}
|
||||
|
||||
// Release the wallet and main lock while waiting
|
||||
LEAVE_CRITICAL_SECTION(cs_main);
|
||||
{
|
||||
CMainUnlockScope unlockMain;
|
||||
checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);
|
||||
|
||||
boost::unique_lock<boost::mutex> lock(csBestBlock);
|
||||
@@ -728,7 +744,6 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp, const CPubKey& myp
|
||||
}
|
||||
}
|
||||
}
|
||||
ENTER_CRITICAL_SECTION(cs_main);
|
||||
|
||||
if (!IsRPCRunning())
|
||||
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
|
||||
@@ -758,12 +773,16 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp, const CPubKey& myp
|
||||
}
|
||||
#ifdef ENABLE_WALLET
|
||||
CReserveKey reservekey(pwalletMain);
|
||||
LEAVE_CRITICAL_SECTION(cs_main);
|
||||
pblocktemplate = CreateNewBlockWithKey(reservekey,pindexPrevNew->GetHeight()+1,HUSH_MAXGPUCOUNT,false);
|
||||
#else
|
||||
pblocktemplate = CreateNewBlockWithKey();
|
||||
#endif
|
||||
ENTER_CRITICAL_SECTION(cs_main);
|
||||
{
|
||||
// CreateNewBlockWithKey can throw (keypool/wallet DB errors); cs_main must be held again by then.
|
||||
CMainUnlockScope unlockMain;
|
||||
#ifdef ENABLE_WALLET
|
||||
pblocktemplate = CreateNewBlockWithKey(reservekey,pindexPrevNew->GetHeight()+1,HUSH_MAXGPUCOUNT,false);
|
||||
#else
|
||||
pblocktemplate = CreateNewBlockWithKey();
|
||||
#endif
|
||||
}
|
||||
if (!pblocktemplate)
|
||||
throw std::runtime_error("CreateNewBlock(): create block failed");
|
||||
//throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory or no available utxo for staking");
|
||||
|
||||
+11
-4
@@ -132,6 +132,11 @@ UniValue getinfo(const UniValue& params, bool fHelp, const CPubKey& mypk)
|
||||
+ HelpExampleRpc("getinfo", "")
|
||||
);
|
||||
|
||||
// vNodes is guarded by cs_vNodes, not cs_main: the socket thread adds and erases peers while we
|
||||
// read it. Take the counts before cs_main so the two locks are never held together.
|
||||
int nConnections = 0, nTlsConnections = 0;
|
||||
GetNodeCounts(nConnections, nTlsConnections);
|
||||
|
||||
#ifdef ENABLE_WALLET
|
||||
LOCK2(cs_main, pwalletMain ? &pwalletMain->cs_wallet : NULL);
|
||||
#else
|
||||
@@ -175,8 +180,8 @@ UniValue getinfo(const UniValue& params, bool fHelp, const CPubKey& mypk)
|
||||
}
|
||||
//obj.push_back(Pair("build_date", BUILD_DATE));
|
||||
obj.push_back(Pair("timeoffset", 0));
|
||||
obj.push_back(Pair("connections", (int)vNodes.size()));
|
||||
obj.push_back(Pair("tls_connections", (int)std::count_if(vNodes.begin(), vNodes.end(), [](CNode* n) {return n->ssl != NULL;})));
|
||||
obj.push_back(Pair("connections", nConnections));
|
||||
obj.push_back(Pair("tls_connections", nTlsConnections));
|
||||
obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.proxy.ToStringIPPort() : string())));
|
||||
obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC()));
|
||||
obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
|
||||
@@ -362,13 +367,13 @@ UniValue validateaddress(const UniValue& params, bool fHelp, const CPubKey& mypk
|
||||
if (fHelp || params.size() != 1)
|
||||
throw runtime_error(
|
||||
"validateaddress \"addr\"\n"
|
||||
"\nReturn information about the given Hush or Hush Arrakis Chain (HAC) address.\n"
|
||||
"\nReturn information about the given DragonX address.\n"
|
||||
"\nArguments:\n"
|
||||
"1. \"addr\" (string, required) The address to validate\n"
|
||||
"\nResult:\n"
|
||||
"{\n"
|
||||
" \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
|
||||
" \"address\" : \"addr\", (string) The Hush or HAC address validated\n"
|
||||
" \"address\" : \"addr\", (string) The DragonX address validated\n"
|
||||
" \"scriptPubKey\" : \"hex\", (string) The hex encoded scriptPubKey generated by the address\n"
|
||||
" \"ismine\" : true|false, (boolean) If the address is yours or not\n"
|
||||
" \"isscript\" : true|false, (boolean) If the key is a script\n"
|
||||
@@ -425,6 +430,8 @@ UniValue z_validateaddress(const UniValue& params, bool fHelp, const CPubKey& my
|
||||
"\nResult:\n"
|
||||
"{\n"
|
||||
" \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
|
||||
" An address with a good checksum is still invalid if it cannot receive funds\n"
|
||||
" (its diversifier or pk_d is not a valid Sapling curve point).\n"
|
||||
" \"address\" : \"zaddr\", (string) The z address validated\n"
|
||||
" \"type\" : \"xxxx\", (string) \"sapling\"\n"
|
||||
" \"ismine\" : true|false, (boolean) If the address is yours or not\n"
|
||||
|
||||
+6
-2
@@ -533,6 +533,10 @@ UniValue getnetworkinfo(const UniValue& params, bool fHelp, const CPubKey& mypk)
|
||||
+ HelpExampleRpc("getnetworkinfo", "")
|
||||
);
|
||||
|
||||
// vNodes is guarded by cs_vNodes, not cs_main (see getinfo).
|
||||
int nConnections = 0, nTlsConnections = 0;
|
||||
GetNodeCounts(nConnections, nTlsConnections);
|
||||
|
||||
LOCK(cs_main);
|
||||
|
||||
UniValue obj(UniValue::VOBJ);
|
||||
@@ -541,8 +545,8 @@ UniValue getnetworkinfo(const UniValue& params, bool fHelp, const CPubKey& mypk)
|
||||
obj.push_back(Pair("protocolversion",PROTOCOL_VERSION));
|
||||
obj.push_back(Pair("localservices", strprintf("%016x", nLocalServices)));
|
||||
obj.push_back(Pair("timeoffset", 0));
|
||||
obj.push_back(Pair("connections", (int)vNodes.size()));
|
||||
obj.push_back(Pair("tls_connections", (int)std::count_if(vNodes.begin(), vNodes.end(), [](CNode* n) {return n->ssl != NULL;})));
|
||||
obj.push_back(Pair("connections", nConnections));
|
||||
obj.push_back(Pair("tls_connections", nTlsConnections));
|
||||
obj.push_back(Pair("networks", GetNetworksInfo()));
|
||||
obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
|
||||
UniValue localAddresses(UniValue::VARR);
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Copyright (c) 2018-2024 The Hush developers
|
||||
./hush-arrakis-chain -ac_name=KOOLAID $@
|
||||
@@ -1,3 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Copyright (c) 2018-2024 The Hush developers
|
||||
./hush-arrakis-chain -ac_name=KUSH $@
|
||||
@@ -1,3 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Copyright (c) 2018-2024 The Hush developers
|
||||
./hush-arrakis-chain -ac_name=ZEX $@
|
||||
@@ -1,21 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Copyright (c) 2018-2024 The Hush developers
|
||||
set -eo pipefail
|
||||
|
||||
# You can now add delay line to pubkey.txt file
|
||||
source pubkey.txt
|
||||
overide_args="$@"
|
||||
seed_ip=$(SEEDNODE)
|
||||
hsc='./hush-arrakis-chain'
|
||||
|
||||
if [ -z "$delay" ]; then delay=20; fi
|
||||
|
||||
./listassetchainparams | while read args; do
|
||||
gen=""
|
||||
if [ $[RANDOM % 10] == 1 ]; then
|
||||
gen=" -gen -genproclimit=1"
|
||||
fi
|
||||
|
||||
$hsc $gen $args $overide_args -pubkey=$pubkey -addnode=$seed_ip &
|
||||
sleep $delay
|
||||
done
|
||||
@@ -236,7 +236,9 @@ boost::optional<CTransaction> TransactionBuilder::Build()
|
||||
for (auto output : outputs) {
|
||||
auto cm = output.note.cm();
|
||||
if (!cm) {
|
||||
LogPrintf("%s: Invalid sapling note commitment!\n", __FUNCTION__);
|
||||
// Only an invalid recipient (bad diversifier, or pk_d not a prime-order point)
|
||||
// gets here; DecodePaymentAddress rejects those, so this is a caller bug.
|
||||
LogPrintf("%s: Invalid sapling note commitment! An output's recipient address is not a valid Sapling address\n", __FUNCTION__);
|
||||
librustzcash_sapling_proving_ctx_free(ctx);
|
||||
return boost::none;
|
||||
}
|
||||
|
||||
+1
-1
@@ -37,7 +37,7 @@ static const int GETHEADERS_VERSION = 31800;
|
||||
//! disconnect from peers older than this proto version (HUSH mainnet)
|
||||
static const int MIN_HUSH_PEER_PROTO_VERSION = 1987426;
|
||||
|
||||
//! disconnect from peers older than this proto version (DragonX/HACs)
|
||||
//! disconnect from peers older than this proto version (DragonX/smart chains)
|
||||
//! Set to 2000000 to reject nodes without RandomX validation fix
|
||||
static const int MIN_PEER_PROTO_VERSION = 2000000;
|
||||
|
||||
|
||||
@@ -82,7 +82,9 @@ void AsyncRPCOperation_autoshieldcoinbase::main() {
|
||||
}
|
||||
}
|
||||
|
||||
set_state(success ? OperationStatus::SUCCESS : OperationStatus::FAILED);
|
||||
// A round cancelled part-way (the queue at shutdown) stays CANCELLED rather than being relabelled.
|
||||
if (!isCancelled())
|
||||
set_state(success ? OperationStatus::SUCCESS : OperationStatus::FAILED);
|
||||
setResult();
|
||||
|
||||
LogPrintf("%s: autoshield operation finished (status=%s, txs=%d, shielded=%s)\n",
|
||||
@@ -475,11 +477,12 @@ void AsyncRPCOperation_autoshieldcoinbase::setResult() {
|
||||
}
|
||||
|
||||
void AsyncRPCOperation_autoshieldcoinbase::cancel() {
|
||||
// Cancelling is how the scheduler stops an in-flight round, so unlike the base
|
||||
// class this must be able to move an EXECUTING operation to CANCELLED. What it
|
||||
// must not do is overwrite a state that is already terminal: the scheduler
|
||||
// cancels the previous operation when it enqueues the next one, and that one may
|
||||
// have already SUCCEEDED, whose result would otherwise be relabelled as cancelled.
|
||||
// Lets the queue stop an executing round when it closes at shutdown, so unlike the
|
||||
// base class this must be able to move an EXECUTING operation to CANCELLED. The
|
||||
// scheduler never cancels a running round (it returns early while one is in flight);
|
||||
// it cancels the previous operation only when enqueueing the next, by which time
|
||||
// that one is terminal -- and a terminal state must not be overwritten, or a
|
||||
// SUCCEEDED result would be relabelled as cancelled.
|
||||
if (isSuccess() || isFailed() || isCancelled())
|
||||
return;
|
||||
set_state(OperationStatus::CANCELLED);
|
||||
|
||||
@@ -52,7 +52,7 @@ public:
|
||||
AsyncRPCOperation_autoshieldcoinbase& operator=(AsyncRPCOperation_autoshieldcoinbase&&) = delete;
|
||||
|
||||
virtual void main();
|
||||
virtual void cancel();
|
||||
virtual void cancel() override;
|
||||
virtual UniValue getStatus() const;
|
||||
|
||||
private:
|
||||
|
||||
@@ -245,14 +245,15 @@ void AsyncRPCOperation_saplingconsolidation::main() {
|
||||
|
||||
stop_execution_clock();
|
||||
|
||||
if (success) {
|
||||
set_state(OperationStatus::SUCCESS);
|
||||
} else {
|
||||
set_state(OperationStatus::FAILED);
|
||||
}
|
||||
// A round cancelled part-way (only the queue closing at shutdown cancels a running op) stays
|
||||
// CANCELLED rather than being relabelled by how much of it got done.
|
||||
if (!isCancelled())
|
||||
set_state(success ? OperationStatus::SUCCESS : OperationStatus::FAILED);
|
||||
|
||||
std::string s = strprintf("%s: Sapling Consolidation operation complete. (status=%s", getId(), getStateAsString());
|
||||
if (success) {
|
||||
if (isCancelled()) {
|
||||
s += ")\n";
|
||||
} else if (success) {
|
||||
s += strprintf(", success)\n");
|
||||
} else {
|
||||
s += strprintf(", error=%s)\n", getErrorMessage());
|
||||
@@ -447,8 +448,8 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() {
|
||||
};
|
||||
|
||||
for (const PlannedTx& planned : txs) {
|
||||
// The queue's cancel at shutdown never reaches an executing op (AsyncRPCOperation::cancel() is
|
||||
// not virtual), so look for the shutdown here, or a stop would wait for the whole round.
|
||||
// ShutdownRequested() too: the shutdown flag is set well before the queue is closed and this op
|
||||
// is cancelled, so checking it stops the round as soon as a stop is asked for.
|
||||
if (isCancelled() || ShutdownRequested()) {
|
||||
LogPrintf("%s: %s. Stopping.\n", opid, isCancelled() ? "Canceled" : "Shutting down");
|
||||
tally.error = isCancelled() ? "cancelled" : "shutting down";
|
||||
@@ -581,11 +582,12 @@ void AsyncRPCOperation_saplingconsolidation::setConsolidationResult(const Consol
|
||||
}
|
||||
|
||||
void AsyncRPCOperation_saplingconsolidation::cancel() {
|
||||
// Cancelling is how the scheduler stops an in-flight round, so unlike the base
|
||||
// class this must be able to move an EXECUTING operation to CANCELLED. What it
|
||||
// must not do is overwrite a state that is already terminal: the scheduler
|
||||
// cancels the previous operation when it enqueues the next one, and that one may
|
||||
// have already SUCCEEDED, whose result would otherwise be relabelled as cancelled.
|
||||
// Lets the queue stop an executing round when it closes at shutdown, so unlike the
|
||||
// base class this must be able to move an EXECUTING operation to CANCELLED. The
|
||||
// scheduler never cancels a running round (it returns early while one is in flight);
|
||||
// it cancels the previous operation only when enqueueing the next, by which time
|
||||
// that one is terminal -- and a terminal state must not be overwritten, or a
|
||||
// SUCCEEDED result would be relabelled as cancelled.
|
||||
if (isSuccess() || isFailed() || isCancelled())
|
||||
return;
|
||||
set_state(OperationStatus::CANCELLED);
|
||||
|
||||
@@ -121,7 +121,7 @@ public:
|
||||
|
||||
virtual void main();
|
||||
|
||||
virtual void cancel();
|
||||
virtual void cancel() override;
|
||||
|
||||
virtual UniValue getStatus() const;
|
||||
|
||||
|
||||
@@ -15,6 +15,9 @@
|
||||
#include "utilmoneystr.h"
|
||||
#include "wallet.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <map>
|
||||
|
||||
extern string randomSietchZaddr();
|
||||
|
||||
CAmount fSweepTxFee = DEFAULT_SWEEP_FEE;
|
||||
@@ -51,11 +54,10 @@ void AsyncRPCOperation_sweep::main() {
|
||||
|
||||
stop_execution_clock();
|
||||
|
||||
if (success) {
|
||||
set_state(OperationStatus::SUCCESS);
|
||||
} else {
|
||||
set_state(OperationStatus::FAILED);
|
||||
}
|
||||
// A round cancelled part-way (only the queue closing at shutdown cancels a running op) stays
|
||||
// CANCELLED rather than being relabelled by how much of it got done.
|
||||
if (!isCancelled())
|
||||
set_state(success ? OperationStatus::SUCCESS : OperationStatus::FAILED);
|
||||
|
||||
// Scheduler bookkeeping, done here so it runs on success AND failure AND
|
||||
// exception (main_impl's terminal code is skipped when it throws). Only the
|
||||
@@ -75,7 +77,9 @@ void AsyncRPCOperation_sweep::main() {
|
||||
}
|
||||
|
||||
std::string s = strprintf("%s: Sweep operation finished. (status=%s", getId(), getStateAsString());
|
||||
if (success) {
|
||||
if (isCancelled()) {
|
||||
s += ")\n";
|
||||
} else if (success) {
|
||||
s += strprintf(", success)\n");
|
||||
} else {
|
||||
s += strprintf(", error=%s)\n", getErrorMessage());
|
||||
@@ -105,6 +109,73 @@ bool IsExcludedAddress(libzcash::SaplingPaymentAddress zaddr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
SweepNoteSelection SelectSweepableNotes(
|
||||
const std::vector<SaplingOutPoint>& candidates, size_t maxInputs,
|
||||
const std::function<std::vector<boost::optional<SaplingWitness>>(const std::vector<SaplingOutPoint>&)>& getLatestWitnesses,
|
||||
const std::function<bool(const uint256&)>& isKnownAnchor)
|
||||
{
|
||||
struct Group {
|
||||
std::vector<size_t> notes;
|
||||
std::vector<SaplingWitness> witnesses;
|
||||
};
|
||||
std::map<uint256, Group> groups; // by witness root
|
||||
std::map<uint256, bool> knownAnchor; // isKnownAnchor, asked once per root
|
||||
const uint256* best = nullptr;
|
||||
size_t bestSize = 0;
|
||||
size_t examined = 0;
|
||||
const size_t window = std::max<size_t>(2 * maxInputs, 1);
|
||||
|
||||
while (examined < candidates.size()) {
|
||||
const size_t end = std::min(candidates.size(), examined + window);
|
||||
std::vector<SaplingOutPoint> ops(candidates.begin() + examined, candidates.begin() + end);
|
||||
std::vector<boost::optional<SaplingWitness>> latest = getLatestWitnesses(ops);
|
||||
for (size_t k = 0; k < ops.size() && k < latest.size(); k++) {
|
||||
if (!latest[k])
|
||||
continue;
|
||||
Group& group = groups[latest[k]->root()];
|
||||
group.notes.push_back(examined + k);
|
||||
group.witnesses.push_back(*latest[k]);
|
||||
}
|
||||
examined = end;
|
||||
|
||||
// The largest group at a known anchor (ties: the lowest root, by map order).
|
||||
best = nullptr;
|
||||
bestSize = 0;
|
||||
for (const auto& entry : groups) {
|
||||
if (entry.second.notes.size() <= bestSize)
|
||||
continue;
|
||||
auto known = knownAnchor.find(entry.first);
|
||||
if (known == knownAnchor.end())
|
||||
known = knownAnchor.emplace(entry.first, isKnownAnchor(entry.first)).first;
|
||||
if (known->second) {
|
||||
best = &entry.first;
|
||||
bestSize = entry.second.notes.size();
|
||||
}
|
||||
}
|
||||
if (bestSize >= maxInputs)
|
||||
break;
|
||||
}
|
||||
|
||||
SweepNoteSelection sel;
|
||||
std::vector<bool> inBest(candidates.size(), false);
|
||||
if (best != nullptr) {
|
||||
const Group& group = groups[*best];
|
||||
sel.anchor = *best;
|
||||
for (size_t i = 0; i < group.notes.size(); i++) {
|
||||
inBest[group.notes[i]] = true;
|
||||
if (sel.chosen.size() < maxInputs) {
|
||||
sel.chosen.push_back(group.notes[i]);
|
||||
sel.witnesses.push_back(group.witnesses[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Notes past the last window read were not looked at this round; they are not skipped.
|
||||
for (size_t i = 0; i < examined; i++)
|
||||
if (!inBest[i])
|
||||
sel.skipped.push_back(i);
|
||||
return sel;
|
||||
}
|
||||
|
||||
bool AsyncRPCOperation_sweep::main_impl() {
|
||||
bool status=true;
|
||||
auto opid=getId();
|
||||
@@ -128,6 +199,15 @@ bool AsyncRPCOperation_sweep::main_impl() {
|
||||
return true;
|
||||
}
|
||||
|
||||
// A locked wallet yields no spending keys, so every address below would be skipped and the round
|
||||
// would report success having swept nothing. RunSaplingSweep already declines to enqueue while
|
||||
// locked; this catches a wallet locked between enqueue and execution, and makes the reason
|
||||
// visible in z_getoperationstatus.
|
||||
if (pwalletMain->IsLocked()) {
|
||||
LogPrintf("%s: wallet is locked; nothing can be swept. Unlock it with walletpassphrase\n", getId());
|
||||
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is locked; unlock it with walletpassphrase for zsweep to sign");
|
||||
}
|
||||
|
||||
std::vector<SaplingNoteEntry> saplingEntries;
|
||||
libzcash::SaplingPaymentAddress sweepAddress;
|
||||
std::map<libzcash::SaplingPaymentAddress, std::vector<SaplingNoteEntry>> mapAddresses;
|
||||
@@ -192,6 +272,11 @@ bool AsyncRPCOperation_sweep::main_impl() {
|
||||
bool sweepComplete = true;
|
||||
|
||||
for (std::map<libzcash::SaplingPaymentAddress, std::vector<SaplingNoteEntry>>::iterator it = mapAddresses.begin(); it != mapAddresses.end(); it++) {
|
||||
// Stop before starting another address: building takes seconds, and a stop would only discard it.
|
||||
if (isCancelled() || ShutdownRequested()) {
|
||||
LogPrintf("%s: %s. Stopping.\n", getId(), isCancelled() ? "Canceled" : "Shutting down");
|
||||
break;
|
||||
}
|
||||
auto addr = (*it).first;
|
||||
auto saplingEntries = (*it).second;
|
||||
|
||||
@@ -200,52 +285,52 @@ bool AsyncRPCOperation_sweep::main_impl() {
|
||||
|
||||
std::vector<SaplingNoteEntry> fromNotes;
|
||||
CAmount amountToSend = 0;
|
||||
int maxInputs = GetArg("-zsweepmaxinputs", 8);
|
||||
if( maxInputs > 100 || maxInputs < 5) {
|
||||
fprintf(stderr,"%s: Invalid zsweep maxinputs=%d is >100 and <5, setting to default of 8\n", __func__, maxInputs);
|
||||
maxInputs = 8;
|
||||
}
|
||||
// -zsweepmaxinputs, parsed and range-checked once at startup.
|
||||
const size_t maxInputs = pwalletMain->sweepMaxInputs;
|
||||
|
||||
//Count Notes availiable for this address
|
||||
int targetCount = 0;
|
||||
int noteCount = 0;
|
||||
// Every note of this address the wallet can spend.
|
||||
std::vector<SaplingNoteEntry> candidates;
|
||||
for (const SaplingNoteEntry& saplingEntry : saplingEntries) {
|
||||
|
||||
libzcash::SaplingIncomingViewingKey ivk;
|
||||
pwalletMain->GetSaplingIncomingViewingKey(boost::get<libzcash::SaplingPaymentAddress>(saplingEntry.address), ivk);
|
||||
|
||||
if (ivk == extsk.expsk.full_viewing_key().in_viewing_key() && saplingEntry.address == addr) {
|
||||
noteCount++;
|
||||
}
|
||||
}
|
||||
|
||||
//Don't sweep if under the threshold
|
||||
if (noteCount <= targetCount){
|
||||
continue;
|
||||
}
|
||||
|
||||
//if we make it here then we need to sweep and the routine is considered incomplete
|
||||
sweepComplete = false;
|
||||
|
||||
for (const SaplingNoteEntry& saplingEntry : saplingEntries) {
|
||||
|
||||
libzcash::SaplingIncomingViewingKey ivk;
|
||||
pwalletMain->GetSaplingIncomingViewingKey(boost::get<libzcash::SaplingPaymentAddress>(saplingEntry.address), ivk);
|
||||
|
||||
//Select Notes from that same address we will be sending to.
|
||||
if (ivk == extsk.expsk.full_viewing_key().in_viewing_key() && saplingEntry.address == addr) {
|
||||
amountToSend += CAmount(saplingEntry.note.value());
|
||||
fromNotes.push_back(saplingEntry);
|
||||
}
|
||||
|
||||
if (fromNotes.size() >= maxInputs)
|
||||
break;
|
||||
|
||||
if (ivk == extsk.expsk.full_viewing_key().in_viewing_key() && saplingEntry.address == addr)
|
||||
candidates.push_back(saplingEntry);
|
||||
}
|
||||
if (candidates.empty())
|
||||
continue;
|
||||
|
||||
int minQuantity = 1;
|
||||
if (fromNotes.size() < minQuantity)
|
||||
continue;
|
||||
// Up to maxInputs of them that share a witness anchor the chain knows. Notes without one (a
|
||||
// missing or desynced witness) are left for a later round instead of failing this address,
|
||||
// and with it the round and every address after it.
|
||||
std::vector<SaplingOutPoint> candidateOps;
|
||||
for (const SaplingNoteEntry& candidate : candidates)
|
||||
candidateOps.push_back(candidate.op);
|
||||
SweepNoteSelection selection = SelectSweepableNotes(candidateOps, maxInputs,
|
||||
[](const std::vector<SaplingOutPoint>& ops) {
|
||||
// Copies only; the roots are computed by the caller with no lock held.
|
||||
std::vector<boost::optional<SaplingWitness>> latest;
|
||||
LOCK(pwalletMain->cs_wallet);
|
||||
for (const SaplingOutPoint& op : ops)
|
||||
latest.push_back(pwalletMain->GetSaplingNoteLatestWitness(op));
|
||||
return latest;
|
||||
},
|
||||
[](const uint256& anchor) {
|
||||
LOCK(cs_main);
|
||||
SaplingMerkleTree tree;
|
||||
return pcoinsTip->GetSaplingAnchorAt(anchor, tree);
|
||||
});
|
||||
if (!selection.skipped.empty()) {
|
||||
const SaplingOutPoint& first = candidates[selection.skipped.front()].op;
|
||||
LogPrintf("%s: %u of the %u notes at one address cannot be spent with the others this round "
|
||||
"(no witness, or one at an unknown or different anchor; first: %s:%u)\n", getId(),
|
||||
selection.skipped.size(), candidates.size(), first.hash.ToString(), first.n);
|
||||
}
|
||||
if (selection.chosen.empty())
|
||||
continue;
|
||||
for (size_t i : selection.chosen) {
|
||||
fromNotes.push_back(candidates[i]);
|
||||
amountToSend += CAmount(candidates[i].note.value());
|
||||
}
|
||||
|
||||
CAmount fee = fSweepTxFee;
|
||||
if (amountToSend <= fSweepTxFee) {
|
||||
@@ -253,34 +338,26 @@ bool AsyncRPCOperation_sweep::main_impl() {
|
||||
fee = 0;
|
||||
}
|
||||
|
||||
auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain);
|
||||
builder.SetExpiryHeight(tipHeight + AUTO_OP_EXPIRY_DELTA);
|
||||
// Build and expire against the tip as it is now, not as it was when the round began: a round
|
||||
// over many addresses can outlive the block it started at, and a transaction built against
|
||||
// a stale height can be expiring, or already expired, by the time it is committed.
|
||||
int buildHeight;
|
||||
{
|
||||
LOCK(cs_main);
|
||||
buildHeight = (chainActive.Tip() != NULL) ? chainActive.Tip()->GetHeight() : tipHeight;
|
||||
}
|
||||
auto nextActivation = NextActivationHeight(buildHeight, consensusParams);
|
||||
if (nextActivation && buildHeight + AUTO_OP_EXPIRY_DELTA >= nextActivation.get()) {
|
||||
LogPrintf("%s: Sweep txs would now be created before a NU activation but may expire after. Stopping this round.\n", getId());
|
||||
break;
|
||||
}
|
||||
auto builder = TransactionBuilder(consensusParams, buildHeight, pwalletMain);
|
||||
builder.SetExpiryHeight(buildHeight + AUTO_OP_EXPIRY_DELTA);
|
||||
LogPrintf("%s: Beginning creating transaction with Sapling output amount=%s\n", getId(), FormatMoney(amountToSend - fee));
|
||||
|
||||
// Select Sapling notes
|
||||
std::vector<SaplingOutPoint> ops;
|
||||
std::vector<libzcash::SaplingNote> notes;
|
||||
for (auto fromNote : fromNotes) {
|
||||
ops.push_back(fromNote.op);
|
||||
notes.push_back(fromNote.note);
|
||||
}
|
||||
|
||||
// Fetch Sapling anchor and witnesses
|
||||
uint256 anchor;
|
||||
std::vector<boost::optional<SaplingWitness>> witnesses;
|
||||
{
|
||||
LOCK2(cs_main, pwalletMain->cs_wallet);
|
||||
pwalletMain->GetSaplingNoteWitnesses(ops, witnesses, anchor);
|
||||
}
|
||||
|
||||
// Add Sapling spends
|
||||
for (size_t i = 0; i < notes.size(); i++) {
|
||||
if (!witnesses[i]) {
|
||||
LogPrintf("%s: Missing Witnesses! Stopping.\n", getId());
|
||||
break;
|
||||
}
|
||||
builder.AddSaplingSpend(extsk.expsk, notes[i], anchor, witnesses[i].get());
|
||||
}
|
||||
// Add Sapling spends, each with the witness it was selected with
|
||||
for (size_t i = 0; i < fromNotes.size(); i++)
|
||||
builder.AddSaplingSpend(extsk.expsk, fromNotes[i].note, selection.anchor, selection.witnesses[i].get());
|
||||
|
||||
builder.SetFee(fee);
|
||||
builder.AddSaplingOutput(extsk.expsk.ovk, sweepAddress, amountToSend - fee);
|
||||
@@ -307,20 +384,29 @@ bool AsyncRPCOperation_sweep::main_impl() {
|
||||
|
||||
auto maybe_tx = builder.Build();
|
||||
if (!maybe_tx) {
|
||||
LogPrintf("%s: Failed to build transaction %s.\n",__func__, getId());
|
||||
// Nothing was recorded, so the other addresses can still be swept. The round still fails.
|
||||
LogPrintf("%s: Failed to build transaction %s; trying the remaining addresses\n",__func__, getId());
|
||||
status=false;
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
CTransaction tx = maybe_tx.get();
|
||||
|
||||
if (isCancelled()) {
|
||||
LogPrintf("%s: Canceled. Stopping.\n", getId());
|
||||
if (isCancelled() || ShutdownRequested()) {
|
||||
LogPrintf("%s: %s. Stopping.\n", getId(), isCancelled() ? "Canceled" : "Shutting down");
|
||||
break;
|
||||
}
|
||||
|
||||
if (pwalletMain->CommitAutomatedTx(tx)) {
|
||||
LogPrintf("%s: Committed sweep transaction with txid=%s\n", getId(), tx.GetHash().ToString());
|
||||
// The address may hold more; the next block's round looks again. An address whose notes
|
||||
// all lack a usable witness commits nothing, so it no longer has the scheduler re-dispatch
|
||||
// on every block -- it is retried an interval later.
|
||||
sweepComplete = false;
|
||||
amountSwept += amountToSend - fee;
|
||||
{
|
||||
LOCK(pwalletMain->cs_wallet);
|
||||
pwalletMain->amountSwept += amountToSend - fee;
|
||||
}
|
||||
sweepTxIds.push_back(tx.GetHash().ToString());
|
||||
numTxCreated++;
|
||||
} else {
|
||||
@@ -329,6 +415,17 @@ bool AsyncRPCOperation_sweep::main_impl() {
|
||||
status = false;
|
||||
break;
|
||||
}
|
||||
} else if (pwalletMain->IsLocked()) {
|
||||
// Locked part-way through the round (a walletpassphrase timeout): nothing further can be
|
||||
// signed. Fail the round rather than report the unswept addresses as done.
|
||||
LogPrintf("%s: wallet was locked during the sweep; stopping. Unlock it with walletpassphrase\n", getId());
|
||||
set_error_code(RPC_WALLET_UNLOCK_NEEDED);
|
||||
set_error_message("Wallet was locked during the sweep; unlock it with walletpassphrase for zsweep to sign");
|
||||
status = false;
|
||||
break;
|
||||
} else {
|
||||
// A viewing-key-only address: its notes are visible but cannot be spent from this wallet.
|
||||
LogPrint("zrpcunsafe", "%s: no spending key for %s; not sweeping it\n", getId(), EncodePaymentAddress(addr));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,11 +453,12 @@ void AsyncRPCOperation_sweep::setSweepResult(int numTxCreated, const CAmount& am
|
||||
}
|
||||
|
||||
void AsyncRPCOperation_sweep::cancel() {
|
||||
// Cancelling is how the scheduler stops an in-flight round, so unlike the base
|
||||
// class this must be able to move an EXECUTING operation to CANCELLED. What it
|
||||
// must not do is overwrite a state that is already terminal: the scheduler
|
||||
// cancels the previous operation when it enqueues the next one, and that one may
|
||||
// have already SUCCEEDED, whose result would otherwise be relabelled as cancelled.
|
||||
// Lets the queue stop an executing round when it closes at shutdown, so unlike the
|
||||
// base class this must be able to move an EXECUTING operation to CANCELLED. The
|
||||
// scheduler never cancels a running round (it returns early while one is in flight);
|
||||
// it cancels the previous operation only when enqueueing the next, by which time
|
||||
// that one is terminal -- and a terminal state must not be overwritten, or a
|
||||
// SUCCEEDED result would be relabelled as cancelled.
|
||||
if (isSuccess() || isFailed() || isCancelled())
|
||||
return;
|
||||
set_state(OperationStatus::CANCELLED);
|
||||
|
||||
@@ -1,18 +1,55 @@
|
||||
// Copyright (c) 2016-2024 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
|
||||
#ifndef HUSH_WALLET_ASYNCRPCOPERATION_SWEEP_H
|
||||
#define HUSH_WALLET_ASYNCRPCOPERATION_SWEEP_H
|
||||
|
||||
#include "amount.h"
|
||||
#include "asyncrpcoperation.h"
|
||||
#include "primitives/transaction.h"
|
||||
#include "uint256.h"
|
||||
#include "univalue.h"
|
||||
#include "zcash/Address.hpp"
|
||||
#include "zcash/IncrementalMerkleTree.hpp"
|
||||
#include "zcash/zip32.h"
|
||||
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
|
||||
#include <boost/optional.hpp>
|
||||
|
||||
//Default fee used for sweep transactions
|
||||
static const CAmount DEFAULT_SWEEP_FEE = 10000;
|
||||
extern CAmount fSweepTxFee;
|
||||
extern bool fSweepMapUsed;
|
||||
extern boost::optional<libzcash::SaplingPaymentAddress> rpcSweepAddress;
|
||||
|
||||
// The notes of one address that a sweep transaction spends.
|
||||
struct SweepNoteSelection {
|
||||
std::vector<size_t> chosen; // indexes into the candidates, at most maxInputs
|
||||
std::vector<boost::optional<SaplingWitness>> witnesses; // one per chosen note
|
||||
uint256 anchor; // the root all of their witnesses share
|
||||
std::vector<size_t> skipped; // candidates looked at but not spendable alongside the
|
||||
// chosen notes: no witness, or one at an unknown or
|
||||
// different anchor
|
||||
};
|
||||
|
||||
// Pick up to maxInputs of an address's notes that can be spent together: witnessed at one root that
|
||||
// is an anchor the chain knows. getLatestWitnesses returns a copy of each note's latest cached witness
|
||||
// (CWallet::GetSaplingNoteLatestWitness, which does no hashing), so each root is computed once, here,
|
||||
// with no lock held. Notes are grouped by root and the largest group at a known anchor wins: a
|
||||
// desynced group can outnumber the good notes at an address (it did on a real wallet), and its root is
|
||||
// one the chain never had. The candidates are read in windows of 2 * maxInputs, stopping as soon as a
|
||||
// known group can fill a transaction, so a healthy address costs about what the old first-maxInputs
|
||||
// selection did, while a run of bad notes at the front cannot hide the good ones behind it. Notes left
|
||||
// out are reported in skipped instead of failing the address -- or, as it used to, the whole round,
|
||||
// which left every address after it unswept, every interval. Notes at another real anchor are swept
|
||||
// by a later round, once the larger group is gone.
|
||||
SweepNoteSelection SelectSweepableNotes(
|
||||
const std::vector<SaplingOutPoint>& candidates, size_t maxInputs,
|
||||
const std::function<std::vector<boost::optional<SaplingWitness>>(const std::vector<SaplingOutPoint>&)>& getLatestWitnesses,
|
||||
const std::function<bool(const uint256&)>& isKnownAnchor);
|
||||
|
||||
class AsyncRPCOperation_sweep : public AsyncRPCOperation
|
||||
{
|
||||
public:
|
||||
@@ -27,7 +64,7 @@ public:
|
||||
|
||||
virtual void main();
|
||||
|
||||
virtual void cancel();
|
||||
virtual void cancel() override;
|
||||
|
||||
virtual UniValue getStatus() const;
|
||||
|
||||
@@ -44,3 +81,5 @@ private:
|
||||
void setSweepResult(int numTxCreated, const CAmount& amountSwept, const std::vector<std::string>& sweepTxIds);
|
||||
|
||||
};
|
||||
|
||||
#endif // HUSH_WALLET_ASYNCRPCOPERATION_SWEEP_H
|
||||
|
||||
@@ -299,7 +299,9 @@ UniValue importprivkey(const UniValue& params, bool fHelp, const CPubKey& mypk)
|
||||
bool fRescan = true;
|
||||
if (params.size() > 2)
|
||||
fRescan = params[2].get_bool();
|
||||
if ( fRescan && params.size() == 4 )
|
||||
// '> 3', not '== 4': with the optional 5th (secret_key) argument the height was silently
|
||||
// dropped and the rescan started from genesis.
|
||||
if ( fRescan && params.size() > 3 )
|
||||
height = params[3].get_int();
|
||||
|
||||
|
||||
|
||||
@@ -550,7 +550,7 @@ void zsWalletTxJSON(const CWalletTx& wtx, UniValue& ret, const std::string strAd
|
||||
tx.push_back(Pair("expiryheight", (int64_t)wtx.nExpiryHeight));
|
||||
tx.push_back(Pair("confirmations", confirms));
|
||||
tx.push_back(Pair("time", wtx.GetTxTime()));
|
||||
tx.push_back(Pair("size", static_cast<uint64_t>(GetSerializeSize(static_cast<CTransaction>(wtx), SER_NETWORK, PROTOCOL_VERSION))));
|
||||
tx.push_back(Pair("size", static_cast<uint64_t>(GetSerializeSize(static_cast<const CTransaction&>(wtx), SER_NETWORK, PROTOCOL_VERSION))));
|
||||
|
||||
//Wallet Conflicts
|
||||
UniValue conflicts(UniValue::VARR);
|
||||
|
||||
+49
-11
@@ -43,6 +43,7 @@
|
||||
#include "wallet/asyncrpcoperation_sendmany.h"
|
||||
#include "wallet/asyncrpcoperation_shieldcoinbase.h"
|
||||
#include "wallet/asyncrpcoperation_saplingconsolidation.h"
|
||||
#include "wallet/asyncrpcoperation_sweep.h"
|
||||
#include "consensus/upgrades.h"
|
||||
#include "sodium.h"
|
||||
#include <stdint.h>
|
||||
@@ -1804,7 +1805,7 @@ void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDe
|
||||
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
|
||||
if (fLong)
|
||||
WalletTxToJSON(wtx, entry);
|
||||
entry.push_back(Pair("size", static_cast<uint64_t>(GetSerializeSize(static_cast<CTransaction>(wtx), SER_NETWORK, PROTOCOL_VERSION))));
|
||||
entry.push_back(Pair("size", static_cast<uint64_t>(GetSerializeSize(static_cast<const CTransaction&>(wtx), SER_NETWORK, PROTOCOL_VERSION))));
|
||||
ret.push_back(entry);
|
||||
}
|
||||
}
|
||||
@@ -1849,7 +1850,7 @@ void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDe
|
||||
entry.push_back(Pair("vout", r.vout));
|
||||
if (fLong)
|
||||
WalletTxToJSON(wtx, entry);
|
||||
entry.push_back(Pair("size", static_cast<uint64_t>(GetSerializeSize(static_cast<CTransaction>(wtx), SER_NETWORK, PROTOCOL_VERSION))));
|
||||
entry.push_back(Pair("size", static_cast<uint64_t>(GetSerializeSize(static_cast<const CTransaction&>(wtx), SER_NETWORK, PROTOCOL_VERSION))));
|
||||
ret.push_back(entry);
|
||||
}
|
||||
}
|
||||
@@ -1951,6 +1952,10 @@ UniValue listtransactions(const UniValue& params, bool fHelp, const CPubKey& myp
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
|
||||
if (nFrom < 0)
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
|
||||
// nCount + nFrom wraps negative otherwise (-fwrapv), and the window below then indexes far out of
|
||||
// bounds. No wallet has INT_MAX entries, so clamping changes no valid reply.
|
||||
if (nCount > std::numeric_limits<int>::max() - nFrom)
|
||||
nCount = std::numeric_limits<int>::max() - nFrom;
|
||||
|
||||
UniValue ret(UniValue::VARR);
|
||||
|
||||
@@ -2239,7 +2244,7 @@ UniValue gettransaction(const UniValue& params, bool fHelp, const CPubKey& mypk)
|
||||
ListTransactions(wtx, "*", 0, false, details, filter);
|
||||
entry.push_back(Pair("details", details));
|
||||
|
||||
string strHex = EncodeHexTx(static_cast<CTransaction>(wtx));
|
||||
string strHex = EncodeHexTx(static_cast<const CTransaction&>(wtx));
|
||||
entry.push_back(Pair("hex", strHex));
|
||||
|
||||
return entry;
|
||||
@@ -3541,7 +3546,21 @@ UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk)
|
||||
if (fHelp || params.size() > 0)
|
||||
throw runtime_error(
|
||||
"z_sweepstatus\n"
|
||||
"\nGive details about zsweep operations since the node was started."
|
||||
"\nGive details about zsweep operations since the node was started.\n"
|
||||
"\nResult:\n"
|
||||
"{\n"
|
||||
" \"zsweep\" : true|false, (boolean) whether -zsweep is enabled\n"
|
||||
" \"running\" : true|false, (boolean) whether a sweep round is in flight\n"
|
||||
" \"wallet_locked\" : true|false, (boolean) the wallet is encrypted and locked, so nothing can be swept\n"
|
||||
" until it is unlocked with walletpassphrase\n"
|
||||
" \"amount_swept\" : x.xxx, (numeric) DRGX sent to the sweep address since startup\n"
|
||||
" \"next_zsweep\" : n, (numeric) height of the next round\n"
|
||||
" \"zsweepinterval\" : n, (numeric) blocks between rounds\n"
|
||||
" \"zsweepaddress\" : \"zaddr\", (string) where swept funds are sent\n"
|
||||
" \"zsweepexclude\" : [\"zaddr\",...], (array) addresses that are never swept\n"
|
||||
" \"zsweepmaxinputs\" : n, (numeric) shielded inputs per sweep transaction\n"
|
||||
" \"zsweepfee\" : n, (numeric) fee per sweep transaction in puposhis\n"
|
||||
" \"zsweepexternal\" : true|false (boolean) whether sweeping to an external wallet is allowed\n"
|
||||
"}\n"
|
||||
"\nExamples:\n"
|
||||
+ HelpExampleCli("z_sweepstatus", "")
|
||||
@@ -3553,7 +3572,8 @@ UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk)
|
||||
UniValue ret(UniValue::VOBJ);
|
||||
ret.push_back(Pair("zsweep", pwalletMain->fSweepEnabled));
|
||||
ret.push_back(Pair("running", pwalletMain->fSweepRunning));
|
||||
ret.push_back(Pair("amount_swept", pwalletMain->amountSwept));
|
||||
ret.push_back(Pair("wallet_locked", pwalletMain->IsLocked()));
|
||||
ret.push_back(Pair("amount_swept", ValueFromAmount(pwalletMain->amountSwept)));
|
||||
ret.push_back(Pair("next_zsweep", pwalletMain->nextSweep));
|
||||
ret.push_back(Pair("zsweepinterval", pwalletMain->sweepInterval));
|
||||
ret.push_back(Pair("zsweepaddress", pwalletMain->sweepAddress));
|
||||
@@ -3563,7 +3583,7 @@ UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk)
|
||||
}
|
||||
ret.push_back(Pair("zsweepexclude", excludes));
|
||||
ret.push_back(Pair("zsweepmaxinputs", pwalletMain->sweepMaxInputs));
|
||||
ret.push_back(Pair("zsweepfee", pwalletMain->sweepFee));
|
||||
ret.push_back(Pair("zsweepfee", fSweepTxFee));
|
||||
ret.push_back(Pair("zsweepexternal", pwalletMain->fSweepExternalEnabled));
|
||||
|
||||
return ret;
|
||||
@@ -5169,8 +5189,17 @@ UniValue z_viewtransaction(const UniValue& params, bool fHelp, const CPubKey& my
|
||||
continue;
|
||||
}
|
||||
auto op = res->second;
|
||||
auto wtxPrev = pwalletMain->mapWallet.at(op.hash);
|
||||
auto decrypted = wtxPrev.DecryptSaplingNote(op).get();
|
||||
// By reference: a CWalletTx copy deep-copies every note's witness list. The nullifier map can
|
||||
// outlive the tx it points to (DeleteTransactions doesn't prune it); skip such a spend like an
|
||||
// unknown one instead of failing the whole call with "map::at".
|
||||
std::map<uint256, CWalletTx>::const_iterator itPrev = pwalletMain->mapWallet.find(op.hash);
|
||||
if (itPrev == pwalletMain->mapWallet.end())
|
||||
continue;
|
||||
const CWalletTx& wtxPrev = itPrev->second;
|
||||
auto maybeDecrypted = wtxPrev.DecryptSaplingNote(op);
|
||||
if (!maybeDecrypted)
|
||||
continue;
|
||||
auto decrypted = maybeDecrypted.get();
|
||||
auto notePt = decrypted.first;
|
||||
auto pa = decrypted.second;
|
||||
|
||||
@@ -5272,7 +5301,11 @@ UniValue z_getoperationresult(const UniValue& params, bool fHelp, const CPubKey&
|
||||
+ HelpExampleRpc("z_getoperationresult", "'[\"operationid\", ... ]'")
|
||||
);
|
||||
|
||||
// This call will remove finished operations
|
||||
// This call will remove finished operations. It keeps cs_main + cs_wallet, which
|
||||
// z_getoperationstatus no longer takes: the wallet schedulers (RunSaplingSweep and friends,
|
||||
// z_consolidate) cancel and pop their previous operation under cs_wallet, and this keeps the
|
||||
// removal serialised with them and with other z_getoperationresult callers, as before.
|
||||
LOCK2(cs_main, pwalletMain->cs_wallet);
|
||||
return z_getoperationstatus_IMPL(params, true);
|
||||
}
|
||||
|
||||
@@ -5301,7 +5334,11 @@ UniValue z_getoperationstatus(const UniValue& params, bool fHelp, const CPubKey&
|
||||
|
||||
UniValue z_getoperationstatus_IMPL(const UniValue& params, bool fRemoveFinishedOperations=false)
|
||||
{
|
||||
LOCK2(cs_main, pwalletMain->cs_wallet);
|
||||
// No cs_main/cs_wallet here (the removing caller, z_getoperationresult, takes them itself).
|
||||
// Nothing below reads chain or wallet state: AsyncRPCQueue guards its map with its own mutex,
|
||||
// and getStatus() (base and every override) reads only the atomic state_, members fixed at
|
||||
// construction, and result/error under the operation's own lock_. Holding the wallet locks
|
||||
// only made a GUI's status poll wait behind block connection and wallet scans.
|
||||
|
||||
std::set<AsyncRPCOperationId> filter;
|
||||
if (params.size()==1) {
|
||||
@@ -6438,7 +6475,8 @@ UniValue z_listoperationids(const UniValue& params, bool fHelp, const CPubKey& m
|
||||
+ HelpExampleRpc("z_listoperationids", "")
|
||||
);
|
||||
|
||||
LOCK2(cs_main, pwalletMain->cs_wallet);
|
||||
// No cs_main/cs_wallet: like z_getoperationstatus, this only reads the self-locking async
|
||||
// queue and each operation's atomic state.
|
||||
|
||||
std::string filter;
|
||||
bool useFilter = false;
|
||||
|
||||
+31
-7
@@ -625,13 +625,14 @@ void CWallet::RunSaplingSweep(int blockHeight) {
|
||||
// consolidation waits on sweep, and autoshield shares the same gate, so a
|
||||
// wedged sweep silently disables coinbase shielding forever.
|
||||
// Only honour the baton while a sweep operation genuinely is in flight.
|
||||
bool fSweepInFlight = false;
|
||||
if (fSweepRunning) {
|
||||
std::shared_ptr<AsyncRPCQueue> sweepQueue = getAsyncRPCQueue();
|
||||
std::shared_ptr<AsyncRPCOperation> inFlightSweep =
|
||||
(sweepQueue != nullptr) ? sweepQueue->getOperationForId(saplingSweepOperationId) : nullptr;
|
||||
bool inFlight = (inFlightSweep != nullptr) &&
|
||||
(inFlightSweep->isReady() || inFlightSweep->isExecuting());
|
||||
if (!inFlight) {
|
||||
fSweepInFlight = (inFlightSweep != nullptr) &&
|
||||
(inFlightSweep->isReady() || inFlightSweep->isExecuting());
|
||||
if (!fSweepInFlight) {
|
||||
LogPrintf("%s: clearing stale fSweepRunning at blockHeight=%d (no sweep operation in flight)\n",
|
||||
__func__, blockHeight);
|
||||
fSweepRunning = false;
|
||||
@@ -642,12 +643,32 @@ void CWallet::RunSaplingSweep(int blockHeight) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Self-guard: let an in-flight round finish. Re-dispatching on every block, as this used to, cancels
|
||||
// the running op (now that AsyncRPCOperation::cancel() is virtual, the sweep's override can stop an
|
||||
// executing round), discarding the transaction it is building -- on a wallet where one build
|
||||
// outlasts a block, nothing would ever be swept. Before cancel() was virtual it merely queued a
|
||||
// redundant round behind the running one.
|
||||
if (fSweepInFlight) {
|
||||
LogPrintf("%s: sweep operation %s (enqueued at height %d) is still running at blockHeight=%d; "
|
||||
"not re-dispatching\n", __func__, saplingSweepOperationId, sweepDispatchHeight, blockHeight);
|
||||
return;
|
||||
}
|
||||
|
||||
if (nextSweep > blockHeight) {
|
||||
LogPrintf("%s: Not time to sweep yet at blockHeight=%d nextSweep=%d\n", __func__, blockHeight, nextSweep);
|
||||
return;
|
||||
}
|
||||
LogPrintf("%s: Sweep enabled at blockHeight=%d nextSweep=%d\n", __func__, blockHeight, nextSweep);
|
||||
|
||||
// Nothing can be signed while the wallet is locked: every address would be skipped and the round
|
||||
// would report success with nothing swept. Say so, and look again an interval later.
|
||||
if (IsLocked()) {
|
||||
LogPrintf("%s: wallet locked; not sweeping at height=%d. Unlock it with walletpassphrase "
|
||||
"for zsweep to resume\n", __func__, blockHeight);
|
||||
nextSweep = sweepInterval + blockHeight;
|
||||
return;
|
||||
}
|
||||
|
||||
//Don't Run if consolidation will run soon.
|
||||
if (fSaplingConsolidationEnabled && nextConsolidation - 5 <= blockHeight) {
|
||||
LogPrintf("%s: not sweeping since next consolidation is within 5 blocks, nextConsolidation=%d , blockHeight=%d\n", __func__, nextConsolidation, blockHeight);
|
||||
@@ -680,6 +701,7 @@ void CWallet::RunSaplingSweep(int blockHeight) {
|
||||
pendingSaplingSweepTxs.clear();
|
||||
std::shared_ptr<AsyncRPCOperation> operation(new AsyncRPCOperation_sweep(blockHeight + AUTO_OP_TARGET_HEIGHT_OFFSET));
|
||||
saplingSweepOperationId = operation->getId();
|
||||
sweepDispatchHeight = blockHeight;
|
||||
if (!q->addOperation(operation)) {
|
||||
// Queue is closing (shutdown). Release the flag we just set, or it stays
|
||||
// set with no operation in flight and blocks every later round.
|
||||
@@ -809,7 +831,7 @@ void CWallet::RefreshConsolidationSuggestion() {
|
||||
// silent no-op wherever it cannot act (locked wallet, no owned coinbase,
|
||||
// external -mineraddress), so it is safe to run on every node.
|
||||
void CWallet::RunAutoShieldCoinbase(int blockHeight) {
|
||||
// Sapling is always active from height 1 on DragonX+HACs.
|
||||
// Sapling is always active from height 1 on DragonX and other smart chains.
|
||||
if (blockHeight == 0)
|
||||
return;
|
||||
|
||||
@@ -3329,12 +3351,14 @@ boost::optional<std::pair<
|
||||
SaplingPaymentAddress>> CWalletTx::DecryptSaplingNote(SaplingOutPoint op) const
|
||||
{
|
||||
// Check whether we can decrypt this SaplingOutPoint
|
||||
if (this->mapSaplingNoteData.count(op) == 0) {
|
||||
mapSaplingNoteData_t::const_iterator ndIt = this->mapSaplingNoteData.find(op);
|
||||
if (ndIt == this->mapSaplingNoteData.end()) {
|
||||
return boost::none;
|
||||
}
|
||||
|
||||
auto output = this->vShieldedOutput[op.n];
|
||||
auto nd = this->mapSaplingNoteData.at(op);
|
||||
// References: a SaplingNoteData copy deep-copies the note's witness list.
|
||||
const OutputDescription& output = this->vShieldedOutput[op.n];
|
||||
const SaplingNoteData& nd = ndIt->second;
|
||||
|
||||
auto maybe_pt = SaplingNotePlaintext::decrypt(
|
||||
output.encCiphertext,
|
||||
|
||||
+19
-3
@@ -112,6 +112,10 @@ static const int MIN_AUTOSHIELD_INTERVAL = 5;
|
||||
static const int DEFAULT_AUTOSHIELD_MIN_UTXOS = 1;
|
||||
static const CAmount AUTOSHIELD_MIN_FEE = 1000; // comfortably above minRelayTxFee for a small tx
|
||||
static const CAmount AUTOSHIELD_MAX_FEE = 10000000; // 0.1 DRGX; no sane autoshield fee exceeds this
|
||||
// zsweep (-zsweepmaxinputs): Sapling spends per sweep transaction. Out-of-range values fall back to the default.
|
||||
static const int DEFAULT_SWEEP_MAX_INPUTS = 8;
|
||||
static const int MIN_SWEEP_MAX_INPUTS = 5;
|
||||
static const int MAX_SWEEP_MAX_INPUTS = 100;
|
||||
// Sapling consolidation (-consolidation / z_consolidate). An address is only consolidated once it holds
|
||||
// MORE than the threshold of spendable notes; a round then sends up to maxtxs transactions per address,
|
||||
// each spending up to batchsize of its smallest notes back to that same address.
|
||||
@@ -930,7 +934,10 @@ public:
|
||||
// Id of the in-flight sweep op; read by the op to confirm it is still the
|
||||
// current one before mutating scheduler state.
|
||||
AsyncRPCOperationId saplingSweepOperationId;
|
||||
int amountSwept = 0;
|
||||
// Block height at which that op was enqueued (for the log while RunSaplingSweep waits on it).
|
||||
int sweepDispatchHeight = 0;
|
||||
// Total sent to the sweep address by committed sweep transactions since startup. Guarded by cs_wallet.
|
||||
CAmount amountSwept = 0;
|
||||
// What consolidation rounds have done since startup. Guarded by cs_wallet.
|
||||
SaplingConsolidationStats consolidationStats;
|
||||
// With -consolidation off: how many addresses are over the threshold (-1 until counted), at which
|
||||
@@ -945,8 +952,8 @@ public:
|
||||
int consolidationMaxTxs = DEFAULT_CONSOLIDATION_MAXTXS;
|
||||
// -consolidatesaplingaddress (or the zsweep address); empty: every address the wallet can spend.
|
||||
std::vector<libzcash::SaplingPaymentAddress> consolidationAddresses;
|
||||
int sweepFee = 10000;
|
||||
int sweepMaxInputs = 200;
|
||||
// Set from -zsweepmaxinputs at startup and read by every sweep op. (The fee lives in fSweepTxFee.)
|
||||
int sweepMaxInputs = DEFAULT_SWEEP_MAX_INPUTS;
|
||||
std::string sweepAddress = "";
|
||||
std::vector<std::string> sweepExcludeAddresses;
|
||||
std::string consolidationAddress = "";
|
||||
@@ -1069,6 +1076,15 @@ protected:
|
||||
if (pindexWalletTip != nullptr) {
|
||||
locator = chainActive.GetLocator(pindexWalletTip);
|
||||
pindexStamped = pindexWalletTip;
|
||||
} else if (nInterruptedRescanHeight >= 0) {
|
||||
// No wallet tip yet, but a scan of this session is running or was cut short: this is
|
||||
// the startup rescan, and the caller is FlushStateToDisk stamping the chain tip (its
|
||||
// hourly write, or the one in Shutdown). Writing that would mark the unscanned range
|
||||
// as scanned, and the next start would skip it for good -- after -zapwallettxes, the
|
||||
// transactions in it would simply be gone. Keep the scan's own locator instead.
|
||||
LogPrintf("SetBestChain(): not stamping the chain tip over an incomplete rescan; the next "
|
||||
"start resumes it from height %d\n", nInterruptedRescanHeight);
|
||||
return false;
|
||||
} else if (!loc.vHave.empty()) {
|
||||
BlockMap::const_iterator mi = mapBlockIndex.find(loc.vHave.front());
|
||||
if (mi != mapBlockIndex.end())
|
||||
|
||||
@@ -24,6 +24,16 @@ uint256 SaplingPaymentAddress::GetHash() const {
|
||||
return Hash(ss.begin(), ss.end());
|
||||
}
|
||||
|
||||
bool SaplingPaymentAddress::is_valid() const {
|
||||
// librustzcash_sapling_compute_cm is the exact check the transaction builder runs
|
||||
// (via SaplingNote::cm()) on every output: it fails if the diversifier gives no valid
|
||||
// g_d or if pk_d does not decode to a prime-order Jubjub point. The value and rcm play
|
||||
// no part in that; zero is a canonical scalar, so rcm = 0 is accepted.
|
||||
uint256 rcm;
|
||||
uint256 cm;
|
||||
return librustzcash_sapling_compute_cm(d.data(), pk_d.begin(), 0, rcm.begin(), cm.begin());
|
||||
}
|
||||
|
||||
SaplingFullViewingKey SaplingExpandedSpendingKey::full_viewing_key() const {
|
||||
uint256 ak;
|
||||
uint256 nk;
|
||||
|
||||
@@ -89,6 +89,13 @@ public:
|
||||
//! Get the 256-bit SHA256d hash of this payment address.
|
||||
uint256 GetHash() const;
|
||||
|
||||
//! True if funds can actually be sent to this address: the diversifier hashes to a
|
||||
//! valid g_d and pk_d is a point in Jubjub's prime-order subgroup. Any 43 bytes with a
|
||||
//! good bech32 checksum decode to a SaplingPaymentAddress, but an address failing this
|
||||
//! check can never receive a note, and the transaction builder fails ("Invalid sapling
|
||||
//! note commitment") on any transaction with an output to it.
|
||||
bool is_valid() const;
|
||||
|
||||
friend inline bool operator==(const SaplingPaymentAddress& a, const SaplingPaymentAddress& b) {
|
||||
return a.d == b.d && a.pk_d == b.pk_d;
|
||||
}
|
||||
|
||||
+1
-1
@@ -31,7 +31,7 @@ my $acname = shift;
|
||||
if ($acname) {
|
||||
# TODO: is acname valid?
|
||||
$cli .= " -ac_name=$acname";
|
||||
# HSC's by default have a blocktime of 60s
|
||||
# smart chains by default have a blocktime of 60s
|
||||
$perday = 1440;
|
||||
} else {
|
||||
$acname = 'DRAGONX';
|
||||
|
||||
Reference in New Issue
Block a user