2 Commits
Author SHA1 Message Date
DanS 25b29d293e Merge branch 'dev' 2026-11-08 11:22:26 -06:00
DanS 09fa5c7b5f Merge branch 'dev' for the v1.3.1 release 2026-10-27 15:27:37 -05:00
63 changed files with 341 additions and 1349 deletions
+1
View File
@@ -25,6 +25,7 @@ RUN cd /hush && \
RUN ln -sf /hush/src/hushd /usr/bin/hushd && \ RUN ln -sf /hush/src/hushd /usr/bin/hushd && \
ln -sf /hush/src/hush-tx /usr/bin/hush-tx && \ 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/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-entrypoint.sh /usr/bin/entrypoint && \
ln -sf /hush/util/docker-hush-cli.sh /usr/bin/hush-cli ln -sf /hush/util/docker-hush-cli.sh /usr/bin/hush-cli
+1 -1
View File
@@ -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 | | Block reward | 3 DRAGONX, halving every 3,500,000 blocks |
| Max block size | 4 MB | | Max block size | 4 MB |
| RPC port | 21769 | | RPC port | 21769 |
| P2P port | 21768 | | P2P port | 18030 |
| Data directory | `~/.hush/DRAGONX` (Linux) | | Data directory | `~/.hush/DRAGONX` (Linux) |
| Config file | `DRAGONX.conf` | | Config file | `DRAGONX.conf` |
| Binaries | `dragonxd`, `dragonx-cli`, `dragonx-tx` | | Binaries | `dragonxd`, `dragonx-cli`, `dragonx-tx` |
+1 -1
View File
@@ -27,7 +27,7 @@ if ($block <= $blockcount) {
} else { } else {
my $diff = $block - $blockcount; my $diff = $block - $blockcount;
# TODO: support custom blocktimes # TODO: support custom blocktimes
# assumes smart chains use default blocktime of 60s # assumes HACs use default blocktime of 60s
my $minpb = $coin ? 1 : 0.6; # 36s in minutes for DragonX my $minpb = $coin ? 1 : 0.6; # 36s in minutes for DragonX
my $minutes = $diff*$minpb; my $minutes = $diff*$minpb;
my $seconds = $minutes*60; my $seconds = $minutes*60;
+4 -4
View File
@@ -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 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 * 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 * Donations do not create new transactions, do not use additional blockspace and cannot be detected by anyone but the sender or reciever
* New smart chain option `ac_clearnet` can be used to disable clearnet networking for an entire blockchain instead of just a single node * New HAC 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 * Updated test framework and tests which allowed the fixing of the `z_sendmany` bug above
* Faster compiling of RandomX internals * Faster compiling of RandomX internals
* GMP dependency removed, as it is no longer needed * 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 * New CLI option -clearnet=0 which disables clearnet networking
* Using -mineraddress with -clearnet=0 disallowed since would reduce privacy * Using -mineraddress with -clearnet=0 disallowed since would reduce privacy
* Add CLI options -disableipv4 and -disableipv6 to disable IPv4 or IPv6 * Add CLI options -disableipv4 and -disableipv6 to disable IPv4 or IPv6
* New smart chain CLI consensus option -ac_minopreturnfee * New HAC CLI consensus option -ac_minopreturnfee
* Updated ASmap, which maps IP addresses to Autonomous System (AS) numbers * 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 * Added ASmap health check, which logs stats about the ASmap once per 24 hours
* Improved cjdns/i2p/tor docs * 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. * 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. * Absurd fee allows sending amount < fee; used only in a full node.
* Fixed various bugs relating to lock ordering and missing locks * Fixed various bugs relating to lock ordering and missing locks
* Fixed RPC docs for addnode and disconnectnode having incorrect port for smart chains * Fixed RPC docs for addnode and disconnectnode having incorrect port for HACs
* Value of DEBUG_LOCKORDER is now logged to debug.log on node startup * 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 * New script ./debug-build.sh to make it easier to make debug builds
* DragonX nodes now have their own list of seed nodes * DragonX nodes now have their own list of seed nodes
* Hush nodes now have own protocol version independent from smart chains * Hush nodes now have own protocol version independent from HACs
* Fixed off-by-one bug in `newSietchRecipient` * Fixed off-by-one bug in `newSietchRecipient`
* Performance improvement to `ActivateBestChainStep` ed86f2dd1d * Performance improvement to `ActivateBestChainStep` ed86f2dd1d
* Improved navigation in README for new users. * Improved navigation in README for new users.
+1 -1
View File
@@ -11,7 +11,7 @@ use warnings;
use strict; use strict;
# call this script like this to generate checkpoints for another chain: # call this script like this to generate checkpoints for another chain:
# CLI="./src/dragonx-cli -ac_name=OTHERCHAIN" ./contrib/sdl_checkpoints.pl ... # CLI=./src/hac-cli ./contrib/sdl_checkpoints.pl ...
my $cli = $ENV{CLI} || "./src/dragonx-cli"; my $cli = $ENV{CLI} || "./src/dragonx-cli";
my $gethash = "$cli getblockhash"; my $gethash = "$cli getblockhash";
+7 -7
View File
@@ -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_` 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 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 with `-ac_`. Originally the `ac` meant "asset chain" but now it means "affects
consensus". consensus" or "arrakis chain", take your pick.
The reason for this is the `extraptr` variable is used to deterministically 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 generate the "chain magic" `ASSETCHAINS_MAGIC` as well as the default p2p and
rpc ports for a chain. This means that if two chains have *exactly* the same rpc ports for a HAC. This means that if two HACs have *exactly* the same
consensus options except for `-ac_foo` (even if they have the same `-ac_name`) 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. then they will still get different chain magic values and p2p and rpc ports.
This is a way of preventing chains with different consensus rules from trying to 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 chain with talk with each other when they should not. For instance, if you make a HAC with
`-ac_name=MYCOIN` on one machine with one set of consensus rules and then `-ac_name=MYCOIN` on one machine with one set of consensus rules and then
another chain with the same name on a different machine but with different another HAC with the same name on a different machine but with different
consensus rules, the chain magic being different (as well as the default p2p 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 port) are ways to prevent them from communicating. This is good because these
two chains will eventually fork due to their different consensus rules and two HACs will eventually chain fork due to their different consensus rules and
ban each other, wasting time, bandwidth and sanity. ban each other, wasting time, bandwidth and sanity.
An example of this pattern in the Git history is the commit which added the 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. `-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 The chain magic value is the CRC32 checksum of every non-default consensus
option the chain uses. option the HAC uses.
Also make sure to actually validate the new consensus option! That is probably 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 going to happen in `src/main.cpp` . If you don't, a malicious node can just
+1 -1
View File
@@ -311,7 +311,7 @@ Threads
- ThreadMapPort : Universal plug-and-play startup/shutdown - ThreadMapPort : Universal plug-and-play startup/shutdown
- ThreadSocketHandler : Sends/Receives data from peers on the P2P port (21768 on DragonX mainnet). - ThreadSocketHandler : Sends/Receives data from peers on the P2P port (18030 on DragonX mainnet).
- ThreadOpenAddedConnections : Opens network connections to added nodes. - ThreadOpenAddedConnections : Opens network connections to added nodes.
+2 -2
View File
@@ -39,8 +39,8 @@ are baked into DragonX consensus.
## RandomX key-block tuning options ## RandomX key-block tuning options
RandomX periodically rotates the "key block" it derives its dataset from. Two RandomX periodically rotates the "key block" it derives its dataset from. Two
advanced options control this. They are inherited from the upstream Hush advanced options control this. They are inherited from the upstream Hush /
tooling and default to values suited to DragonX's 36s block time; Arrakis-chain tooling and default to values suited to DragonX's 36s block time;
you should not normally change them: you should not normally change them:
* `-ac_randomx_interval` controls how often the RandomX key block changes * `-ac_randomx_interval` controls how often the RandomX key block changes
+6 -6
View File
@@ -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 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 * 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 * Donations do not create new transactions, do not use additional blockspace and cannot be detected by anyone but the sender or reciever
* New smart chain option `ac_clearnet` can be used to disable clearnet networking for an entire blockchain instead of just a single node * New HAC 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 * Updated test framework and tests which allowed the fixing of the `z_sendmany` bug above
* Faster compiling of RandomX internals * Faster compiling of RandomX internals
* GMP dependency removed, as it is no longer needed * 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 * 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 * Add CLI options `-disableipv4` and `-disableipv6` which can be used to disable IPv4 or IPv6
* New smart chain CLI consensus option `-ac_minopreturnfee` * New HAC CLI consensus option `-ac_minopreturnfee`
* `OP_RETURN` minimum fee per tx, regardless of tx size, default is 1 coin, specified in puposhis * `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 * 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 * 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. * 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. * 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 various bugs relating to lock ordering and missing locks
* Fixed RPC docs for addnode and disconnectnode having the incorrect port for smart chains * Fixed RPC docs for addnode and disconnectnode having the incorrect port for HACs
* Value of DEBUG_LOCKORDER is now logged to debug.log on node startup * 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 * New script ./debug-build.sh to make it easier to make debug builds
* DragonX nodes now have their own list of seed nodes * DragonX nodes now have their own list of seed nodes
* Hush nodes now have their own protocol version which is independent from smart chains * Hush nodes now have their own protocol version which is independent from HACs
* Fixed off-by-one bug in `newSietchRecipient` * Fixed off-by-one bug in `newSietchRecipient`
* Performance improvement to `ActivateBestChainStep` https://git.hush.is/hush/hush3/commit/ed86f2dd1da370fe2dbf7db475afc41b218cbc5f * Performance improvement to `ActivateBestChainStep` https://git.hush.is/hush/hush3/commit/ed86f2dd1da370fe2dbf7db475afc41b218cbc5f
* Improved navigation in README for new users. * 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 * 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 data needed to mine, now it uses all physical cores https://git.hush.is/hush/hush3/commit/1b5422eb2ddcedd9aabdf4f039144f9eef5c6f95
* RandomX mining takes slightly less memory * RandomX mining takes slightly less memory
* `ac_sapling` is no longer an option for smart chains * `ac_sapling` is no longer an option for Arrakis Chains
* All chains enable Sapling at height 1 like Hush + DragonX * All chains enable Sapling at height 1 like Hush + DragonX
* This means there is no need to call `NetworkUpgradeActive` on every block height * This means there is no need to call `NetworkUpgradeActive` on every block height
which means syncing is faster 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 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 * 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 * Only Hush + DragonX will automatically connect to various seed nodes https://git.hush.is/hush/hush3/issues/379
* Other smart chains must opt-in via -connect or -addnode * Other Arrakis Chains must opt-in via -connect or -addnode
* Updated i2p seed node: https://git.hush.is/hush/hush3/commit/8c8b6e88f0c076c86c713e7e22e2d826202cc64d * 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 * 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 * Improve `hush_scanner` and seed node contrib file: https://git.hush.is/hush/hush3/commit/16dd3aef74ac312bc8953af34a3d9a297b03d9f4
+4 -4
View File
@@ -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): Add these lines to your `/etc/tor/torrc` (or equivalent config file):
HiddenServiceDir /var/lib/tor/dragonx-service/ HiddenServiceDir /var/lib/tor/dragonx-service/
HiddenServicePort 21768 127.0.0.1:21768 HiddenServicePort 18030 127.0.0.1:18032
The directory can be different of course, but virtual port numbers should be equal to The directory can be different of course, but virtual port numbers should be equal to
your dragonxd's P2P listen port (21768 by default), and target addresses and ports 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:21768 by default). should be equal to binding address and port for inbound Tor connections (127.0.0.1:18032 by default).
-externalip=X You can tell dragonx about its publicly reachable addresses using -externalip=X You can tell dragonx about its publicly reachable addresses using
this option, and this can be an onion address. Given the above this option, and this can be an onion address. Given the above
@@ -204,7 +204,7 @@ as well, use `discover` instead:
./dragonxd ... -discover ./dragonxd ... -discover
and open port 21768 on your firewall (or use port mapping, i.e., `-upnp` or `-natpmp`). and open port 18030 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 If you only want to use Tor to reach .onion addresses, but not use it as a proxy
for normal IPv4/IPv6 communication, use: for normal IPv4/IPv6 communication, use:
+3 -6
View File
@@ -58,8 +58,7 @@ witness rebuilds. Consolidation keeps that in check.
so every address keeps at least one spendable note while the round confirms. so every address keeps at least one spendable note while the round confirms.
* Each transaction has exactly 8 shielded outputs: the real one plus 7 zero-value dummy ("Sietch") outputs to random * Each transaction has exactly 8 shielded outputs: the real one plus 7 zero-value dummy ("Sietch") outputs to random
addresses, so it does not shrink the anonymity set. It pays `consolidationtxfee`, or no fee when its notes are worth addresses, so it does not shrink the anonymity set. It pays `consolidationtxfee`, or no fee when its notes are worth
no more than the fee, and expires `-txexpirydelta` blocks (default 200) after it is made, like any other wallet no more than the fee, and expires 15 blocks after it is made.
transaction, so the wallet's periodic rebroadcast can still retry it.
* Only the notes a round actually spends are locked while it proves, so sends made meanwhile still see the rest of * Only the notes a round actually spends are locked while it proves, so sends made meanwhile still see the rest of
the wallet. the wallet.
* All spends of one transaction must use one anchor (Sapling tree root). An address's spends use the tip's root, * All spends of one transaction must use one anchor (Sapling tree root). An address's spends use the tip's root,
@@ -129,10 +128,8 @@ wallet: `N addresses have more than 25 spendable notes; consider -consolidation=
1. With zsweep on, consolidation only works on the sweep address: a `consolidatesaplingaddress` other than the 1. With zsweep on, consolidation only works on the sweep address: a `consolidatesaplingaddress` other than the
sweep address is refused at startup (with `consolidation=0` it is replaced by the sweep address, with a warning), sweep address is refused at startup (with `consolidation=0` it is replaced by the sweep address, with a warning),
and `z_consolidate` refuses any other address too. Sweep and consolidation never run at the same time, and they take and `z_consolidate` refuses any other address too. Sweep and consolidation never run at the same time, and a
strict turns: a round that comes due while the other op is running goes next, and the other op starts no new sweep is not started when a consolidation round is due within 5 blocks.
round until it has run, so neither can starve the other. `z_sweepstatus` shows `"waiting_for_consolidation": true`
and `z_consolidationstatus` shows `"waiting_for_sweep": true` while a round is waiting for its turn.
### Copyright ### Copyright
-13
View File
@@ -97,18 +97,5 @@ class HTTPBasicsTest (BitcoinTestFramework):
assert_equal('"error":null' in out1, True) 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 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__': if __name__ == '__main__':
HTTPBasicsTest().main() HTTPBasicsTest().main()
@@ -167,10 +167,10 @@ class ComparisonTestFramework(BitcoinTestFramework):
def add_options(self, parser): def add_options(self, parser):
parser.add_option("--testbinary", dest="testbinary", parser.add_option("--testbinary", dest="testbinary",
default=os.getenv("BITCOIND", "src/dragonxd"), default=os.getenv("BITCOIND", "hush-arrakis-chain"),
help="bitcoind binary to test") help="bitcoind binary to test")
parser.add_option("--refbinary", dest="refbinary", parser.add_option("--refbinary", dest="refbinary",
default=os.getenv("BITCOIND", "src/dragonxd"), default=os.getenv("BITCOIND", "hush-arrakis-chain"),
help="bitcoind binary to use for reference nodes (if any)") help="bitcoind binary to use for reference nodes (if any)")
def setup_chain(self): def setup_chain(self):
+1 -6
View File
@@ -504,12 +504,7 @@ dragonxd_LDADD = $(LINK_GROUP_START) \
$(LIBRANDOMX) $(LIBRANDOMX)
if ENABLE_WALLET if ENABLE_WALLET
# libbitcoin_server again after the wallet: the two archives use each other (the wallet's async dragonxd_LDADD += $(LIBBITCOIN_WALLET)
# 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 endif
dragonxd_LDADD += \ dragonxd_LDADD += \
+2 -8
View File
@@ -16,20 +16,15 @@ hush_gtest_SOURCES = \
gtest/test_hdtransparent.cpp \ gtest/test_hdtransparent.cpp \
gtest/test_mnemonic_compat.cpp \ gtest/test_mnemonic_compat.cpp \
gtest/test_stratum_jobid.cpp \ gtest/test_stratum_jobid.cpp \
gtest/test_sweep_note_selection.cpp \
gtest/test_asyncrpc_cancel.cpp \
gtest/test_wallet_notedata.cpp \ gtest/test_wallet_notedata.cpp \
gtest/test_wallet_witnesstrim.cpp \
gtest/test_net_closesocket.cpp \ gtest/test_net_closesocket.cpp \
gtest/test_net_addrrelay.cpp \
gtest/test_fd_defense.cpp \ gtest/test_fd_defense.cpp \
gtest/test_wallet_dbenv.cpp \ gtest/test_wallet_dbenv.cpp \
gtest/test_wallet_notecache.cpp \ gtest/test_wallet_notecache.cpp \
gtest/test_wallet_history.cpp \ gtest/test_wallet_history.cpp \
gtest/test_wallet_consolidation.cpp \ gtest/test_wallet_consolidation.cpp \
gtest/test_wallet_shutdownsave.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_CPPFLAGS = $(AM_CPPFLAGS) -DMULTICORE -fopenmp -DBINARY_OUTPUT -DCURVE_ALT_BN128 -DSTATIC $(BITCOIN_INCLUDES)
hush_gtest_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) hush_gtest_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
@@ -50,8 +45,7 @@ hush_gtest_LDADD = -lgtest -lgmock \
$(LIBSECP256K1) \ $(LIBSECP256K1) \
$(LIBRANDOMX) $(LIBRANDOMX)
if ENABLE_WALLET if ENABLE_WALLET
# libbitcoin_server again after the wallet, spelled ./ so libtool keeps both copies (see dragonxd_LDADD). hush_gtest_LDADD += $(LIBBITCOIN_WALLET)
hush_gtest_LDADD += $(LIBBITCOIN_WALLET) ./$(LIBBITCOIN_SERVER)
endif endif
hush_gtest_LDADD += \ hush_gtest_LDADD += \
+3 -5
View File
@@ -32,9 +32,7 @@ using namespace std;
static boost::uuids::random_generator uuidgen; static boost::uuids::random_generator uuidgen;
// const and read with at(): getStatus() runs on several RPC threads at once, and operator[] of a static std::map<OperationStatus, std::string> OperationStatusMap = {
// 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::READY, "queued"},
{OperationStatus::EXECUTING, "executing"}, {OperationStatus::EXECUTING, "executing"},
{OperationStatus::CANCELLED, "cancelled"}, {OperationStatus::CANCELLED, "cancelled"},
@@ -196,7 +194,7 @@ UniValue AsyncRPCOperation::getStatus() const {
OperationStatus status = this->getState(); OperationStatus status = this->getState();
UniValue obj(UniValue::VOBJ); UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("id", this->id_)); obj.push_back(Pair("id", this->id_));
obj.push_back(Pair("status", OperationStatusMap.at(status))); obj.push_back(Pair("status", OperationStatusMap[status]));
obj.push_back(Pair("creation_time", this->creation_time_)); obj.push_back(Pair("creation_time", this->creation_time_));
// TODO: Issue #1354: There may be other useful metadata to return to the user. // TODO: Issue #1354: There may be other useful metadata to return to the user.
UniValue err = this->getError(); UniValue err = this->getError();
@@ -220,5 +218,5 @@ UniValue AsyncRPCOperation::getStatus() const {
*/ */
std::string AsyncRPCOperation::getStateAsString() const { std::string AsyncRPCOperation::getStateAsString() const {
OperationStatus status = this->getState(); OperationStatus status = this->getState();
return OperationStatusMap.at(status); return OperationStatusMap[status];
} }
+2 -4
View File
@@ -60,10 +60,8 @@ public:
// You must implement this method in your subclass. // You must implement this method in your subclass.
virtual void main(); virtual void main();
// Override this method if you can interrupt execution of main() in your subclass. It must be virtual: // Override this method if you can interrupt execution of main() in your subclass.
// callers hold a std::shared_ptr<AsyncRPCOperation> (the queue's map, the wallet schedulers). It used void cancel();
// not to be, which left every subclass override dead and a running operation uncancellable.
virtual void cancel();
// Getters and setters // Getters and setters
+1 -1
View File
@@ -87,7 +87,7 @@ static int AppInitRPC(int argc, char* argv[])
ParseParameters(argc, argv); ParseParameters(argc, argv);
std:string name; std:string name;
// default chain is DRAGONX itself, which to the internals is also a smart chain // default HAC is DRAGONX itself, which to the internals, is also a HAC
name = GetArg("-ac_name","DRAGONX"); name = GetArg("-ac_name","DRAGONX");
if ( !name.empty() ) if ( !name.empty() )
+3 -3
View File
@@ -117,7 +117,7 @@ public:
consensus.nPowMaxAdjustDown = 32; // 32% adjustment down consensus.nPowMaxAdjustDown = 32; // 32% adjustment down
consensus.nPowMaxAdjustUp = 16; // 16% adjustment up consensus.nPowMaxAdjustUp = 16; // 16% adjustment up
// we are emulating old node behavior at startup, they used 150s // we are emulating old node behavior at startup, they used 150s
consensus.nPowTargetSpacing = 150; // 75; // HUSH is 75 seconds, smart chains are 60 seconds by default consensus.nPowTargetSpacing = 150; // 75; // HUSH is 75 seconds, Hush Arrakis Chains are 60 seconds by default
consensus.nPowAllowMinDifficultyBlocksAfterHeight = boost::none; consensus.nPowAllowMinDifficultyBlocksAfterHeight = boost::none;
// HUSH never had Sprout in our blockchain history, but some internals require *knowing* about Sprout // 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. // or it breaks backward compatibility. We do what we can.
@@ -366,7 +366,7 @@ public:
assert(maxUint/UintToArith256(consensus.powLimit) >= consensus.nPowAveragingWindow); assert(maxUint/UintToArith256(consensus.powLimit) >= consensus.nPowAveragingWindow);
consensus.nPowMaxAdjustDown = 0; // Turn off adjustment down consensus.nPowMaxAdjustDown = 0; // Turn off adjustment down
consensus.nPowMaxAdjustUp = 0; // Turn off adjustment up consensus.nPowMaxAdjustUp = 0; // Turn off adjustment up
consensus.nPowTargetSpacing = 60; // smart chains default to 60 seconds so a theoretical testnet should as well consensus.nPowTargetSpacing = 60; // HAC's default to 60 seconds so a theoretical testnet should as well
consensus.nPowAllowMinDifficultyBlocksAfterHeight = 0; consensus.nPowAllowMinDifficultyBlocksAfterHeight = 0;
ups[Consensus::BASE_SPROUT].nProtocolVersion = 170002; ups[Consensus::BASE_SPROUT].nProtocolVersion = 170002;
ups[Consensus::BASE_SPROUT].nActivationHeight = NUNU::ALWAYS_ACTIVE; ups[Consensus::BASE_SPROUT].nActivationHeight = NUNU::ALWAYS_ACTIVE;
@@ -6074,7 +6074,7 @@ void *chainparams_commandline() {
}; };
} else { } else {
// all other smart chains with no checkpoints // all other HAC's with no checkpoints
checkpointData = //(Checkpoints::CCheckpointData) checkpointData = //(Checkpoints::CCheckpointData)
{ {
boost::assign::map_list_of boost::assign::map_list_of
-82
View File
@@ -1,82 +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
#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());
}
-33
View File
@@ -1,33 +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
#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;
}
-183
View File
@@ -1,183 +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
//
// 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);
}
-158
View File
@@ -1,158 +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
#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);
}
-43
View File
@@ -381,46 +381,3 @@ TEST_F(WalletShutdownSaveDb, AddingANoteNeedsASave) {
ASSERT_TRUE(wallet.AddToWallet(wtx, false, &walletdb)); ASSERT_TRUE(wallet.AddToWallet(wtx, false, &walletdb));
EXPECT_EQ("nothing changed since the last save", Reason(wallet, true)) << "the same tx again"; 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());
}
-93
View File
@@ -1,93 +0,0 @@
// Copyright (c) 2024-2026 The DragonX 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 "random.h"
#include "uint256.h"
#include "wallet/wallet.h"
#include "zcash/IncrementalMerkleTree.hpp"
namespace {
libzcash::SaplingIncomingViewingKey TestIvk()
{
return libzcash::SaplingIncomingViewingKey(uint256S("0202020202020202020202020202020202020202020202020202020202020202"));
}
// A note with a witness for every one of nSnapshots blocks, newest at the front, the way
// BuildWitnessCache leaves it: each snapshot is the previous one plus one more commitment.
SaplingNoteData NoteWithHistory(int nSnapshots, int tipHeight, bool fNullifier = true)
{
SaplingNoteData nd = fNullifier ? SaplingNoteData(TestIvk(), GetRandHash()) : SaplingNoteData(TestIvk());
SaplingMerkleTree tree;
tree.append(GetRandHash()); // the note's own commitment
nd.witnesses.push_front(tree.witness());
for (int i = 1; i < nSnapshots; i++) {
nd.witnesses.push_front(nd.witnesses.front());
nd.witnesses.front().append(GetRandHash());
}
nd.witnessHeight = tipHeight;
return nd;
}
const unsigned int CACHE = 109; // WITNESS_CACHE_SIZE on DragonX: MAX_REORG_LENGTH (99) + 10
} // namespace
// Spent deeper than the cache: only the newest witness survives, unchanged, and the note keeps the
// position and height its nullifier and startup validation depend on.
TEST(WalletWitnessTrim, DeeplySpentNoteKeepsOnlyNewestWitness)
{
SaplingNoteData nd = NoteWithHistory(CACHE, 5000);
const uint256 rootBefore = nd.witnesses.front().root();
const uint64_t posBefore = nd.witnesses.front().position();
const boost::optional<uint256> nfBefore = nd.nullifier;
EXPECT_TRUE(TrimDeeplySpentNoteWitnesses(nd, CACHE + 1, CACHE));
ASSERT_EQ(nd.witnesses.size(), 1u);
EXPECT_EQ(nd.witnesses.front().root(), rootBefore);
EXPECT_EQ(nd.witnesses.front().position(), posBefore);
EXPECT_EQ(nd.witnessHeight, 5000);
EXPECT_TRUE(nd.nullifier == nfBefore);
// Already trimmed: nothing more to do.
EXPECT_FALSE(TrimDeeplySpentNoteWitnesses(nd, CACHE + 50, CACHE));
EXPECT_EQ(nd.witnesses.size(), 1u);
}
// Unspent (depth 0) and spent within reorg reach: a reorg may still need the older snapshots.
TEST(WalletWitnessTrim, UnspentAndShallowSpentNotesAreUntouched)
{
SaplingNoteData unspent = NoteWithHistory(CACHE, 5000);
EXPECT_FALSE(TrimDeeplySpentNoteWitnesses(unspent, 0, CACHE));
EXPECT_EQ(unspent.witnesses.size(), CACHE);
SaplingNoteData shallow = NoteWithHistory(CACHE, 5000);
EXPECT_FALSE(TrimDeeplySpentNoteWitnesses(shallow, CACHE, CACHE)); // depth == cache size: still in reach
EXPECT_EQ(shallow.witnesses.size(), CACHE);
}
// A note without a nullifier is never trimmed (it is not known to be spent), and an empty list stays
// empty: trimming must never be what leaves a note with no witnesses.
TEST(WalletWitnessTrim, NoNullifierOrNoWitnessesIsLeftAlone)
{
SaplingNoteData noNf = NoteWithHistory(CACHE, 5000, false);
EXPECT_FALSE(TrimDeeplySpentNoteWitnesses(noNf, CACHE + 1, CACHE));
EXPECT_EQ(noNf.witnesses.size(), CACHE);
SaplingNoteData empty(TestIvk(), GetRandHash());
EXPECT_FALSE(TrimDeeplySpentNoteWitnesses(empty, CACHE + 1, CACHE));
EXPECT_TRUE(empty.witnesses.empty());
}
// The serialized note shrinks with the list: what SetBestChain rewrites for every spent note.
TEST(WalletWitnessTrim, SerializedSizeShrinks)
{
SaplingNoteData nd = NoteWithHistory(CACHE, 5000);
const size_t before = ::GetSerializeSize(nd, SER_DISK, CLIENT_VERSION);
ASSERT_TRUE(TrimDeeplySpentNoteWitnesses(nd, CACHE + 1, CACHE));
const size_t after = ::GetSerializeSize(nd, SER_DISK, CLIENT_VERSION);
EXPECT_LT(after * 20, before);
}
-5
View File
@@ -420,10 +420,6 @@ static void libevent_log_cb(int severity, const char *msg)
LogPrint("libevent", "libevent: %s\n", 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() bool InitHTTPServer()
{ {
struct evhttp* http = 0; struct evhttp* http = 0;
@@ -470,7 +466,6 @@ bool InitHTTPServer()
} }
evhttp_set_timeout(http, GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT)); 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_max_body_size(http, MAX_SIZE);
evhttp_set_gencb(http, http_request_cb, NULL); evhttp_set_gencb(http, http_request_cb, NULL);
+15
View File
@@ -0,0 +1,15 @@
#!/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 "$@"
+10
View File
@@ -0,0 +1,10 @@
:: 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
View File
@@ -961,7 +961,7 @@ CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
// This function defines the Hush Founders Reward (AKA Dev Tax) // This function defines the Hush Founders Reward (AKA Dev Tax)
// 10% of all block rewards go towards Hush core team // 10% of all block rewards go towards Hush core team
// If you do not like this, you are encouraged to fork the chain // If you do not like this, you are encouraged to fork the chain
// or start your own chain. // or start your own Hush Arrakis Chain: https://git.hush.is/hush/hush-arrakis-chains
// HUSH supply curve cannot be exactly represented via CLI args, so we do it ourselves. // 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 // 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 // but to tell the AC params, I need to say "11% of 11.25" is 1.25
+1 -1
View File
@@ -72,7 +72,7 @@ const uint32_t nHushHardforkHeight4 = 1605555;
const uint32_t nHushHardforkTimestamp = 1580303652; // Jan 29nd 1pm GMT const uint32_t nHushHardforkTimestamp = 1580303652; // Jan 29nd 1pm GMT
const uint32_t nHushHardforkTimestamp2 = 1594425600; // Jul 11th 12a GMT const uint32_t nHushHardforkTimestamp2 = 1594425600; // Jul 11th 12a GMT
// Used by smart chains // Used by HACs
static const uint32_t HUSH_SEASON_TIMESTAMPS[NUM_HUSH_SEASONS] = {1525132800, 1563148800, nHushHardforkTimestamp, nHushHardforkTimestamp2, nHushHardforkTimestamp2*5, nHushHardforkTimestamp2*6, nHushHardforkTimestamp2*7}; static const uint32_t HUSH_SEASON_TIMESTAMPS[NUM_HUSH_SEASONS] = {1525132800, 1563148800, nHushHardforkTimestamp, nHushHardforkTimestamp2, nHushHardforkTimestamp2*5, nHushHardforkTimestamp2*6, nHushHardforkTimestamp2*7};
// Used by HUSH3+TUSH // Used by HUSH3+TUSH
+2 -2
View File
@@ -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; 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]; static uint8_t hush_pubkeys[NUM_HUSH_SEASONS][64][33],didinit[NUM_HUSH_SEASONS];
//HUSH3+TUSH use block heights, other smart chains use timestamps //HUSH3+TUSH use block heights, HACs use timestamps
if ( timestamp == 0 && SMART_CHAIN_SYMBOL[0] != 0 ) { if ( timestamp == 0 && SMART_CHAIN_SYMBOL[0] != 0 ) {
timestamp = hush_heightstamp(height); timestamp = hush_heightstamp(height);
} else if ( SMART_CHAIN_SYMBOL[0] == 0 ) { } 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; int32_t hush_season = 0;
bool ishush3 = strncmp(SMART_CHAIN_SYMBOL, "HUSH3",5) == 0 ? true : false; bool ishush3 = strncmp(SMART_CHAIN_SYMBOL, "HUSH3",5) == 0 ? true : false;
bool istush = strncmp(SMART_CHAIN_SYMBOL, "TUSH",4) == 0 ? true : false; bool istush = strncmp(SMART_CHAIN_SYMBOL, "TUSH",4) == 0 ? true : false;
// TUSH uses height activation like HUSH3, other smart chains use timestamps // TUSH uses height activation like HUSH3, other HACs use timestamps
hush_season = (ishush3 || istush) ? gethushseason(height) : getacseason(timestamp); hush_season = (ishush3 || istush) ? gethushseason(height) : getacseason(timestamp);
if(IS_HUSH_NOTARY) { if(IS_HUSH_NOTARY) {
+1 -1
View File
@@ -1913,7 +1913,7 @@ void hush_args(char *argv0)
} else if (strncmp(SMART_CHAIN_SYMBOL, "TUMIN", 5) == 0) { } else if (strncmp(SMART_CHAIN_SYMBOL, "TUMIN", 5) == 0) {
ASSETCHAINS_RANDOMX_VALIDATION = 1200; // TBD: set to coordinated upgrade height ASSETCHAINS_RANDOMX_VALIDATION = 1200; // TBD: set to coordinated upgrade height
} else { } else {
ASSETCHAINS_RANDOMX_VALIDATION = 1; // all other RandomX smart chains: enforce from height 1 ASSETCHAINS_RANDOMX_VALIDATION = 1; // all other RandomX HACs: enforce from height 1
} }
LogPrintf("ASSETCHAINS_RANDOMX_VALIDATION set to %d for %s\n", ASSETCHAINS_RANDOMX_VALIDATION, SMART_CHAIN_SYMBOL); LogPrintf("ASSETCHAINS_RANDOMX_VALIDATION set to %d for %s\n", ASSETCHAINS_RANDOMX_VALIDATION, SMART_CHAIN_SYMBOL);
} }
+2 -57
View File
@@ -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("-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("-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("-zsweepinterval", strprintf(_("Sweep shielded funds every X blocks (default %i)"), 10));
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)); strUsage += HelpMessageOpt("-zsweepmaxinputs", strprintf(_("Maximum number of shielded inputs to sweep per transaction (default %i)"), 8));
// By default we only allow sweeping to the current wallet which must have the spending key of the sweep zaddr // 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 // 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)")); 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_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_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")); strUsage += HelpMessageOpt("-ac_reward", _("Block reward in satoshis, default is 0"));
// All smart chains activate sapling at block height 1, other heights are not supported // All HAC's activate sapling at block height 1, other heights are not supported
//strUsage += HelpMessageOpt("-ac_sapling", _("Sapling activation block height")); //strUsage += HelpMessageOpt("-ac_sapling", _("Sapling activation block height"));
strUsage += HelpMessageOpt("-ac_script", _("P2SH/multisig address to receive founders rewards")); strUsage += HelpMessageOpt("-ac_script", _("P2SH/multisig address to receive founders rewards"));
strUsage += HelpMessageOpt("-ac_supply", _("Starting supply, default is 10")); strUsage += HelpMessageOpt("-ac_supply", _("Starting supply, default is 10"));
@@ -1306,44 +1306,6 @@ static void AdjustCoinCacheForMemoryPressure()
nCoinCacheUsage = (size_t)(newTargetMB << 20); 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) bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
{ {
// ********************************************************* Step 1: setup // ********************************************************* Step 1: setup
@@ -2449,12 +2411,6 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
delete pwalletMain; delete pwalletMain;
pwalletMain = NULL; 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...")); uiInterface.InitMessage(_("Loading wallet..."));
@@ -2674,13 +2630,6 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
LogPrintf("%s: set nextSweep=%d with sweepInterval=%d\n", __func__, pwalletMain->nextSweep, pwalletMain->sweepInterval ); LogPrintf("%s: set nextSweep=%d with sweepInterval=%d\n", __func__, pwalletMain->nextSweep, pwalletMain->sweepInterval );
fSweepTxFee = GetArg("-zsweepfee", DEFAULT_SWEEP_FEE); fSweepTxFee = GetArg("-zsweepfee", DEFAULT_SWEEP_FEE);
fSweepMapUsed = !mapMultiArgs["-zsweepaddress"].empty(); 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 //Validate Sapling Addresses
vector<string>& vSweep = mapMultiArgs["-zsweepaddress"]; vector<string>& vSweep = mapMultiArgs["-zsweepaddress"];
@@ -2920,10 +2869,6 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
pindexRescan = chainActive[rescanHeight]; 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 { } else {
CWalletDB walletdb(strWalletFile); CWalletDB walletdb(strWalletFile);
CBlockLocator locator; CBlockLocator locator;
-7
View File
@@ -304,16 +304,9 @@ libzcash::PaymentAddress DecodePaymentAddress(const std::string& str)
CDataStream ss(data, SER_NETWORK, PROTOCOL_VERSION); CDataStream ss(data, SER_NETWORK, PROTOCOL_VERSION);
libzcash::SaplingPaymentAddress ret; libzcash::SaplingPaymentAddress ret;
ss >> ret; ss >> 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 ret;
} }
} }
}
return libzcash::InvalidEncoding(); return libzcash::InvalidEncoding();
} }
+20 -26
View File
@@ -5372,7 +5372,7 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta
} }
} }
// Check Proof-of-Work difficulty for smart chains // Check Proof-of-Work difficulty for smart chains (HACs)
// Without this check, an attacker can submit blocks with arbitrary nBits // Without this check, an attacker can submit blocks with arbitrary nBits
// (e.g., powLimit / diff=1) and they will be accepted, allowing the chain // (e.g., powLimit / diff=1) and they will be accepted, allowing the chain
// to be flooded with minimum-difficulty blocks. // 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) { if (!ishush3 && SMART_CHAIN_SYMBOL[0] != 0 && nHeight > daaForkHeight) {
unsigned int nNextWork = GetNextWorkRequired(pindexPrev, &block, consensusParams); unsigned int nNextWork = GetNextWorkRequired(pindexPrev, &block, consensusParams);
if (fDebug) { if (fDebug) {
LogPrintf("%s: nbits height=%d expected=%lu actual=%lu\n", LogPrintf("%s: HAC nbits height=%d expected=%lu actual=%lu\n",
__func__, nHeight, (unsigned long)nNextWork, (unsigned long)block.nBits); __func__, nHeight, (unsigned long)nNextWork, (unsigned long)block.nBits);
} }
if (block.nBits != nNextWork) { if (block.nBits != nNextWork) {
@@ -8398,12 +8398,9 @@ bool SendMessages(CNode* pto, bool fSendTrickle)
LOCK(cs_vNodes); LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
{ {
// Periodically clear addrKnown to allow refresh broadcasts. Under cs_addrKnown, as in // Periodically clear addrKnown to allow refresh broadcasts
// CloseSocketDisconnect: the message handler reads and inserts into it concurrently. if (nLastRebroadcast)
if (nLastRebroadcast) {
LOCK(pnode->cs_addrKnown);
pnode->addrKnown.reset(); pnode->addrKnown.reset();
}
// Rebroadcast our address // Rebroadcast our address
AdvertizeLocal(pnode); AdvertizeLocal(pnode);
@@ -8415,9 +8412,20 @@ bool SendMessages(CNode* pto, bool fSendTrickle)
// Message: addr // Message: addr
if (fSendTrickle) if (fSendTrickle)
{ {
// Collect the addresses the peer doesn't know yet into vAddr and send that, once vector<CAddress> vAddr;
// (in MAX_ADDR_TO_SEND batches). This used to push the whole of vAddrToSend for every vAddr.reserve(pto->vAddrToSend.size());
// accepted address, so one getaddr reply went out as N messages of N addresses. BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
{
if (pto->AddAddressIfNotAlreadyKnown(addr))
{
vAddr.push_back(addr);
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);
}
const char* msg_type; const char* msg_type;
int make_flags; int make_flags;
if (pto->m_wants_addrv2) { if (pto->m_wants_addrv2) {
@@ -8427,27 +8435,13 @@ bool SendMessages(CNode* pto, bool fSendTrickle)
msg_type = NetMsgType::ADDR; msg_type = NetMsgType::ADDR;
make_flags = 0; make_flags = 0;
} }
const CNetMsgMaker msgMaker(std::min(pto->nVersion, PROTOCOL_VERSION)); pto->PushAddrMessage(CNetMsgMaker(std::min(pto->nVersion, PROTOCOL_VERSION)).Make(make_flags, msg_type, pto->vAddrToSend));
vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
{
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)
{
pto->PushAddrMessage(msgMaker.Make(make_flags, msg_type, vAddr));
vAddr.clear();
}
} }
} }
pto->vAddrToSend.clear(); pto->vAddrToSend.clear();
if (!vAddr.empty()) vAddr.clear();
pto->PushAddrMessage(msgMaker.Make(make_flags, msg_type, vAddr));
} }
CNodeState &state = *State(pto->GetId()); CNodeState &state = *State(pto->GetId());
+22 -9
View File
@@ -224,12 +224,10 @@ CBlockTemplate* CreateNewBlock(CPubKey _pk,const CScript& _scriptPubKeyIn, int32
CBlockIndex* pindexPrev = 0; CBlockIndex* pindexPrev = 0;
{ {
// Scoped, so every return below and any exception releases both, in reverse order. They // this should stop create block ever exiting until it has returned something.
// were taken and released by hand, which leaked them whenever something in here threw, and boost::this_thread::disable_interruption();
// released cs_main before mempool.cs. (The boost::this_thread::disable_interruption() that ENTER_CRITICAL_SECTION(cs_main);
// stood here built a temporary, so it never disabled anything; with scoped locks an ENTER_CRITICAL_SECTION(mempool.cs);
// interruption now unwinds cleanly.)
LOCK2(cs_main, mempool.cs);
pindexPrev = chainActive.LastTip(); pindexPrev = chainActive.LastTip();
const int nHeight = pindexPrev->GetHeight() + 1; const int nHeight = pindexPrev->GetHeight() + 1;
const Consensus::Params &consensusParams = chainparams.GetConsensus(); const Consensus::Params &consensusParams = chainparams.GetConsensus();
@@ -666,6 +664,8 @@ CBlockTemplate* CreateNewBlock(CPubKey _pk,const CScript& _scriptPubKeyIn, int32
} }
} else if ( (uint64_t)(txNew.vout[0].nValue) >= ASSETCHAINS_TIMELOCKGTE) { } else if ( (uint64_t)(txNew.vout[0].nValue) >= ASSETCHAINS_TIMELOCKGTE) {
LogPrintf("timelocked chains not supported in this code!\n"); LogPrintf("timelocked chains not supported in this code!\n");
LEAVE_CRITICAL_SECTION(cs_main);
LEAVE_CRITICAL_SECTION(mempool.cs);
return(0); return(0);
} else if ( fNotarizationBlock && ASSETCHAINS_NOTARY_PAY[0] != 0 && pblock->vtx[1].vout.size() == 2 && pblock->vtx[1].vout[1].nValue == 0 ) { } else if ( fNotarizationBlock && ASSETCHAINS_NOTARY_PAY[0] != 0 && pblock->vtx[1].vout.size() == 2 && pblock->vtx[1].vout[1].nValue == 0 ) {
// Get the OP_RETURN for the notarization // Get the OP_RETURN for the notarization
@@ -677,6 +677,11 @@ CBlockTemplate* CreateNewBlock(CPubKey _pk,const CScript& _scriptPubKeyIn, int32
if ( totalsats == 0 ) if ( totalsats == 0 )
{ {
LogPrintf("Could not create notary payment, trying again.\n"); LogPrintf("Could not create notary payment, trying again.\n");
// Release unconditionally to match the unconditional ENTER above. The old
// `if(!isStake)` guard leaked cs_main/mempool.cs on the isStake path (this
// still return(0)s), while the success and timelock paths always release.
LEAVE_CRITICAL_SECTION(cs_main);
LEAVE_CRITICAL_SECTION(mempool.cs);
return(0); return(0);
} }
} else LogPrintf("vout 2 of notarization is not OP_RETURN scriptlen.%i\n", scriptlen); } else LogPrintf("vout 2 of notarization is not OP_RETURN scriptlen.%i\n", scriptlen);
@@ -721,6 +726,11 @@ CBlockTemplate* CreateNewBlock(CPubKey _pk,const CScript& _scriptPubKeyIn, int32
CValidationState state; CValidationState state;
if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) // invokes CC checks if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) // invokes CC checks
{ {
// Release unconditionally to match the unconditional ENTER above. The old
// `if(!isStake)` guard leaked cs_main/mempool.cs on the isStake path (this
// still return(0)s), while the success and timelock paths always release.
LEAVE_CRITICAL_SECTION(cs_main);
LEAVE_CRITICAL_SECTION(mempool.cs);
LogPrintf("%s: TestBlockValidity failed!\n", __func__); LogPrintf("%s: TestBlockValidity failed!\n", __func__);
//throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed"); // crashes the node, moved to GetBlockTemplate and issue return. //throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed"); // crashes the node, moved to GetBlockTemplate and issue return.
return(0); return(0);
@@ -728,6 +738,9 @@ CBlockTemplate* CreateNewBlock(CPubKey _pk,const CScript& _scriptPubKeyIn, int32
} }
} }
LEAVE_CRITICAL_SECTION(cs_main);
LEAVE_CRITICAL_SECTION(mempool.cs);
return pblocktemplate.release(); return pblocktemplate.release();
} }
@@ -1203,15 +1216,15 @@ void static RandomXMiner()
char randomxHash[RANDOMX_HASH_SIZE]; char randomxHash[RANDOMX_HASH_SIZE];
rxdebug("%s: created randomxHash of size %d\n", 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 char randomxKey[82]; // randomx spec says keysize of >60 bytes is implementation-specific
// initial randomx key is unique to every smart chain, and has at least 9 bytes (2^9=128 bits) of entropy // initial randomx key is unique to every Hush Arrakis 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 // 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); snprintf(randomxKey, 81, "%08x%s%08x", ASSETCHAINS_MAGIC, SMART_CHAIN_SYMBOL, ASSETCHAINS_RPCPORT);
// With the defaults of 1024 and 64 // With the defaults of 1024 and 64
// the key block will change every ~21.3 hours with a 75s block time // 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 smart chains // and every ~17 hours with the default 60s block time for HACs
static int randomxInterval = GetRandomXInterval(); static int randomxInterval = GetRandomXInterval();
// This lag is 80 mins for 75s blocktime and 64 mins for 60s (default) blocktime for smart chains // This lag is 80 mins for 75s blocktime and 64 mins for 60s (default) blocktime for HACs
static int randomxBlockLag = GetRandomXBlockLag(); static int randomxBlockLag = GetRandomXBlockLag();
randomx_vm *myVM = nullptr; randomx_vm *myVM = nullptr;
-11
View File
@@ -2974,17 +2974,6 @@ size_t GetNodeCount(NumConnections flags)
return nNum; 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) void SetNetworkActive(bool active)
{ {
LogPrint("net", "SetNetworkActive: %s\n", active); LogPrint("net", "SetNetworkActive: %s\n", active);
+1 -5
View File
@@ -173,8 +173,6 @@ enum NumConnections {
}; };
size_t GetNodeCount(NumConnections num); 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(); bool GetNetworkActive();
void SetNetworkActive(bool active); void SetNetworkActive(bool active);
@@ -617,9 +615,7 @@ public:
// Known checking here is only to save space from duplicates. // Known checking here is only to save space from duplicates.
// SendMessages will filter it again for knowns that were added // SendMessages will filter it again for knowns that were added
// after addresses were pushed. // after addresses were pushed.
// Test _addr, the address being queued: the member `addr` is this peer's own address, and if (_addr.IsValid() && !IsAddressKnown(addr) && addr_format_supported) {
// 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) { if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
vAddrToSend[insecure_rand() % vAddrToSend.size()] = _addr; vAddrToSend[insecure_rand() % vAddrToSend.size()] = _addr;
+5 -25
View File
@@ -534,9 +534,6 @@ UniValue getblockdeltas(const UniValue& params, bool fHelp, const CPubKey& mypk)
if (fHelp || params.size() != 1) if (fHelp || params.size() != 1)
throw runtime_error(""); 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(); std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash)); uint256 hash(uint256S(strHash));
@@ -605,19 +602,10 @@ UniValue getblockhashes(const UniValue& params, bool fHelp, const CPubKey& mypk)
std::vector<std::pair<uint256, unsigned int> > blockHashes; std::vector<std::pair<uint256, unsigned int> > blockHashes;
{ if (fActiveOnly)
// 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); LOCK(cs_main);
fFound = GetTimestampIndex(high, low, fActiveOnly, blockHashes);
} else { if (!GetTimestampIndex(high, low, fActiveOnly, blockHashes)) {
fFound = GetTimestampIndex(high, low, fActiveOnly, blockHashes);
}
if (!fFound)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for block hashes"); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for block hashes");
} }
@@ -861,11 +849,6 @@ UniValue gettxoutsetinfo(const UniValue& params, bool fHelp, const CPubKey& mypk
UniValue ret(UniValue::VOBJ); UniValue ret(UniValue::VOBJ);
CCoinsStats stats; CCoinsStats stats;
// Hold cs_main across the flush and the scan: GetStats reads the best block and iterates a
// snapshot of the coins database separately, and a flush landing in between would report the
// UTXO totals of a different block than "height"/"bestblock" claim. The transparent UTXO set
// of a fully shielded chain is small, so the scan is short.
LOCK(cs_main);
FlushStateToDisk(); FlushStateToDisk();
if (pcoinsTip->GetStats(stats)) { if (pcoinsTip->GetStats(stats)) {
ret.push_back(Pair("height", (int64_t)stats.nHeight)); ret.push_back(Pair("height", (int64_t)stats.nHeight));
@@ -885,7 +868,7 @@ UniValue getblockmerkletree(const UniValue& params, bool fHelp, const CPubKey& m
if (fHelp || params.size() != 1 ) if (fHelp || params.size() != 1 )
throw runtime_error( throw runtime_error(
"getblockmerkletree height\n" "getblockmerkletree height\n"
"\nGet full merkletree for a given block height.\n" "\nGet full merkletree for a given Hush or HAC block height.\n"
"\nArguments:\n" "\nArguments:\n"
"1. height (int, required) block height\n" "1. height (int, required) block height\n"
"\nResult:\n" "\nResult:\n"
@@ -894,16 +877,13 @@ UniValue getblockmerkletree(const UniValue& params, bool fHelp, const CPubKey& m
+ HelpExampleRpc("getblockmerkletree", "290000") + HelpExampleRpc("getblockmerkletree", "290000")
); );
// chainActive and pcoinsTip (whose anchor cache inserts on a miss) are guarded by cs_main.
LOCK(cs_main);
CBlockIndex* phushblockindex; CBlockIndex* phushblockindex;
uint256 blockRoot; uint256 blockRoot;
SaplingMerkleTree tree; SaplingMerkleTree tree;
int nHeight = params[0].get_int(); int nHeight = params[0].get_int();
if ( (nHeight < 1) || (nHeight > chainActive.LastTip()->GetHeight()) ) { if ( (nHeight < 1) || (nHeight > chainActive.LastTip()->GetHeight()) ) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid block height parameter"); throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid Hush or HAC block height parameter");
} }
phushblockindex = chainActive[nHeight]; phushblockindex = chainActive[nHeight];
+13 -33
View File
@@ -71,22 +71,6 @@ uint64_t the_commission(const CBlock *pblock,int32_t height);
int32_t hush_blockload(CBlock& block,CBlockIndex *pindex); int32_t hush_blockload(CBlock& block,CBlockIndex *pindex);
arith_uint256 hush_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc); 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, * Return average network hashes per second based on the last 'lookup' blocks,
* or over the difficulty averaging window if 'lookup' is nonpositive. * or over the difficulty averaging window if 'lookup' is nonpositive.
@@ -728,8 +712,8 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp, const CPubKey& myp
} }
// Release the wallet and main lock while waiting // 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); checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);
boost::unique_lock<boost::mutex> lock(csBestBlock); boost::unique_lock<boost::mutex> lock(csBestBlock);
@@ -744,6 +728,7 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp, const CPubKey& myp
} }
} }
} }
ENTER_CRITICAL_SECTION(cs_main);
if (!IsRPCRunning()) if (!IsRPCRunning())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down"); throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
@@ -765,29 +750,24 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp, const CPubKey& myp
CBlockIndex* pindexPrevNew = chainActive.LastTip(); CBlockIndex* pindexPrevNew = chainActive.LastTip();
nStart = GetTime(); nStart = GetTime();
// Create new block. cs_main is released while it is built, so another getblocktemplate call can // Create new block
// run this block meanwhile: build into a local and only touch the shared pblocktemplate once cs_main if(pblocktemplate)
// is held again, or that call could delete or overwrite it under us. {
CBlockTemplate* pblocktemplateNew = NULL; delete pblocktemplate;
pblocktemplate = NULL;
}
#ifdef ENABLE_WALLET #ifdef ENABLE_WALLET
CReserveKey reservekey(pwalletMain); CReserveKey reservekey(pwalletMain);
#endif LEAVE_CRITICAL_SECTION(cs_main);
{ pblocktemplate = CreateNewBlockWithKey(reservekey,pindexPrevNew->GetHeight()+1,HUSH_MAXGPUCOUNT,false);
// CreateNewBlockWithKey can throw (keypool/wallet DB errors); cs_main must be held again by then.
CMainUnlockScope unlockMain;
#ifdef ENABLE_WALLET
pblocktemplateNew = CreateNewBlockWithKey(reservekey,pindexPrevNew->GetHeight()+1,HUSH_MAXGPUCOUNT,false);
#else #else
pblocktemplateNew = CreateNewBlockWithKey(); pblocktemplate = CreateNewBlockWithKey();
#endif #endif
} ENTER_CRITICAL_SECTION(cs_main);
if (!pblocktemplateNew) if (!pblocktemplate)
throw std::runtime_error("CreateNewBlock(): create block failed"); throw std::runtime_error("CreateNewBlock(): create block failed");
//throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory or no available utxo for staking"); //throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory or no available utxo for staking");
delete pblocktemplate;
pblocktemplate = pblocktemplateNew;
// Need to update only after we know CreateNewBlockWithKey succeeded // Need to update only after we know CreateNewBlockWithKey succeeded
pindexPrev = pindexPrevNew; pindexPrev = pindexPrevNew;
} }
+4 -11
View File
@@ -132,11 +132,6 @@ UniValue getinfo(const UniValue& params, bool fHelp, const CPubKey& mypk)
+ HelpExampleRpc("getinfo", "") + 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 #ifdef ENABLE_WALLET
LOCK2(cs_main, pwalletMain ? &pwalletMain->cs_wallet : NULL); LOCK2(cs_main, pwalletMain ? &pwalletMain->cs_wallet : NULL);
#else #else
@@ -180,8 +175,8 @@ UniValue getinfo(const UniValue& params, bool fHelp, const CPubKey& mypk)
} }
//obj.push_back(Pair("build_date", BUILD_DATE)); //obj.push_back(Pair("build_date", BUILD_DATE));
obj.push_back(Pair("timeoffset", 0)); obj.push_back(Pair("timeoffset", 0));
obj.push_back(Pair("connections", nConnections)); obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("tls_connections", nTlsConnections)); obj.push_back(Pair("tls_connections", (int)std::count_if(vNodes.begin(), vNodes.end(), [](CNode* n) {return n->ssl != NULL;})));
obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.proxy.ToStringIPPort() : string()))); obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.proxy.ToStringIPPort() : string())));
obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC())); obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC()));
obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK()))); obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
@@ -367,13 +362,13 @@ UniValue validateaddress(const UniValue& params, bool fHelp, const CPubKey& mypk
if (fHelp || params.size() != 1) if (fHelp || params.size() != 1)
throw runtime_error( throw runtime_error(
"validateaddress \"addr\"\n" "validateaddress \"addr\"\n"
"\nReturn information about the given DragonX address.\n" "\nReturn information about the given Hush or Hush Arrakis Chain (HAC) address.\n"
"\nArguments:\n" "\nArguments:\n"
"1. \"addr\" (string, required) The address to validate\n" "1. \"addr\" (string, required) The address to validate\n"
"\nResult:\n" "\nResult:\n"
"{\n" "{\n"
" \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\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 DragonX address validated\n" " \"address\" : \"addr\", (string) The Hush or HAC address validated\n"
" \"scriptPubKey\" : \"hex\", (string) The hex encoded scriptPubKey generated by the address\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" " \"ismine\" : true|false, (boolean) If the address is yours or not\n"
" \"isscript\" : true|false, (boolean) If the key is a script\n" " \"isscript\" : true|false, (boolean) If the key is a script\n"
@@ -430,8 +425,6 @@ UniValue z_validateaddress(const UniValue& params, bool fHelp, const CPubKey& my
"\nResult:\n" "\nResult:\n"
"{\n" "{\n"
" \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\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" " \"address\" : \"zaddr\", (string) The z address validated\n"
" \"type\" : \"xxxx\", (string) \"sapling\"\n" " \"type\" : \"xxxx\", (string) \"sapling\"\n"
" \"ismine\" : true|false, (boolean) If the address is yours or not\n" " \"ismine\" : true|false, (boolean) If the address is yours or not\n"
+2 -6
View File
@@ -533,10 +533,6 @@ UniValue getnetworkinfo(const UniValue& params, bool fHelp, const CPubKey& mypk)
+ HelpExampleRpc("getnetworkinfo", "") + HelpExampleRpc("getnetworkinfo", "")
); );
// vNodes is guarded by cs_vNodes, not cs_main (see getinfo).
int nConnections = 0, nTlsConnections = 0;
GetNodeCounts(nConnections, nTlsConnections);
LOCK(cs_main); LOCK(cs_main);
UniValue obj(UniValue::VOBJ); UniValue obj(UniValue::VOBJ);
@@ -545,8 +541,8 @@ UniValue getnetworkinfo(const UniValue& params, bool fHelp, const CPubKey& mypk)
obj.push_back(Pair("protocolversion",PROTOCOL_VERSION)); obj.push_back(Pair("protocolversion",PROTOCOL_VERSION));
obj.push_back(Pair("localservices", strprintf("%016x", nLocalServices))); obj.push_back(Pair("localservices", strprintf("%016x", nLocalServices)));
obj.push_back(Pair("timeoffset", 0)); obj.push_back(Pair("timeoffset", 0));
obj.push_back(Pair("connections", nConnections)); obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("tls_connections", nTlsConnections)); obj.push_back(Pair("tls_connections", (int)std::count_if(vNodes.begin(), vNodes.end(), [](CNode* n) {return n->ssl != NULL;})));
obj.push_back(Pair("networks", GetNetworksInfo())); obj.push_back(Pair("networks", GetNetworksInfo()));
obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK()))); obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
UniValue localAddresses(UniValue::VARR); UniValue localAddresses(UniValue::VARR);
Executable
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
# Copyright (c) 2018-2024 The Hush developers
./hush-arrakis-chain -ac_name=KOOLAID $@
Executable
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
# Copyright (c) 2018-2024 The Hush developers
./hush-arrakis-chain -ac_name=KUSH $@
Executable
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
# Copyright (c) 2018-2024 The Hush developers
./hush-arrakis-chain -ac_name=ZEX $@
+21
View File
@@ -0,0 +1,21 @@
#!/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
+2 -4
View File
@@ -1274,16 +1274,14 @@ UniValue stratum_mining_authorize(StratumClient& client, const UniValue& params)
boost::trim_right(username); boost::trim_right(username);
} }
const std::string strippedUsername = get_stripped_username(username); CBitcoinAddress addr(get_stripped_username(username));
CBitcoinAddress addr(strippedUsername);
// If given the special address "x", mine to the default address given by -stratumaddress // If given the special address "x", mine to the default address given by -stratumaddress
// This means a miner can run a private pool without TLS and not // This means a miner can run a private pool without TLS and not
// worry about MITM attacks that change addresses, and leaks less metadata. // worry about MITM attacks that change addresses, and leaks less metadata.
// It also means many miners can be used and updating their mining address does not // It also means many miners can be used and updating their mining address does not
// require any changes on each miner, just restart dragonxd with a new -stratumaddress // require any changes on each miner, just restart dragonxd with a new -stratumaddress
// Compare the name as sent: "x" is not a valid address, so addr.ToString() never returns it. if(addr.ToString() == "x") {
if(strippedUsername == "x") {
addr = CBitcoinAddress(GetArg("-stratumaddress", "")); addr = CBitcoinAddress(GetArg("-stratumaddress", ""));
const std::string msg = strprintf("%s: Authorized client with default stratum address=%s", __func__, addr.ToString()); const std::string msg = strprintf("%s: Authorized client with default stratum address=%s", __func__, addr.ToString());
LogPrint("stratum", "%s\n", msg); LogPrint("stratum", "%s\n", msg);
+1 -3
View File
@@ -236,9 +236,7 @@ boost::optional<CTransaction> TransactionBuilder::Build()
for (auto output : outputs) { for (auto output : outputs) {
auto cm = output.note.cm(); auto cm = output.note.cm();
if (!cm) { if (!cm) {
// Only an invalid recipient (bad diversifier, or pk_d not a prime-order point) LogPrintf("%s: Invalid sapling note commitment!\n", __FUNCTION__);
// 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); librustzcash_sapling_proving_ctx_free(ctx);
return boost::none; return boost::none;
} }
+1 -1
View File
@@ -37,7 +37,7 @@ static const int GETHEADERS_VERSION = 31800;
//! disconnect from peers older than this proto version (HUSH mainnet) //! disconnect from peers older than this proto version (HUSH mainnet)
static const int MIN_HUSH_PEER_PROTO_VERSION = 1987426; static const int MIN_HUSH_PEER_PROTO_VERSION = 1987426;
//! disconnect from peers older than this proto version (DragonX/smart chains) //! disconnect from peers older than this proto version (DragonX/HACs)
//! Set to 2000000 to reject nodes without RandomX validation fix //! Set to 2000000 to reject nodes without RandomX validation fix
static const int MIN_PEER_PROTO_VERSION = 2000000; static const int MIN_PEER_PROTO_VERSION = 2000000;
@@ -82,8 +82,6 @@ void AsyncRPCOperation_autoshieldcoinbase::main() {
} }
} }
// A round cancelled part-way (the queue at shutdown) stays CANCELLED rather than being relabelled.
if (!isCancelled())
set_state(success ? OperationStatus::SUCCESS : OperationStatus::FAILED); set_state(success ? OperationStatus::SUCCESS : OperationStatus::FAILED);
setResult(); setResult();
@@ -294,7 +292,7 @@ bool AsyncRPCOperation_autoshieldcoinbase::main_impl() {
// from below), not the stale enqueue-time targetHeight_, so a queue delay // from below), not the stale enqueue-time targetHeight_, so a queue delay
// cannot slip a straddling expiry past this guard. // cannot slip a straddling expiry past this guard.
auto nextActivationHeight = NextActivationHeight(tipHeight, consensusParams); auto nextActivationHeight = NextActivationHeight(tipHeight, consensusParams);
if (nextActivationHeight && tipHeight + AutoOpExpiryDelta() >= nextActivationHeight.get()) { if (nextActivationHeight && tipHeight + AUTO_OP_EXPIRY_DELTA >= nextActivationHeight.get()) {
LogPrintf("%s: autoshield tx could expire across a NU activation. Skipping this round.\n", opid); LogPrintf("%s: autoshield tx could expire across a NU activation. Skipping this round.\n", opid);
return true; return true;
} }
@@ -414,7 +412,7 @@ bool AsyncRPCOperation_autoshieldcoinbase::main_impl() {
// stale enqueue-time height here meant the guard was checking a height the // stale enqueue-time height here meant the guard was checking a height the
// transaction was not actually signed against. // transaction was not actually signed against.
auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain); auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain);
builder.SetExpiryHeight(tipHeight + AutoOpExpiryDelta()); builder.SetExpiryHeight(tipHeight + AUTO_OP_EXPIRY_DELTA);
builder.SetFee(fee); builder.SetFee(fee);
for (const auto& t : inputs) { for (const auto& t : inputs) {
@@ -461,9 +459,6 @@ bool AsyncRPCOperation_autoshieldcoinbase::main_impl() {
} }
LogPrintf("%s: autoshield tx FAILED in CommitTransaction, txid=%s\n", opid, tx.GetHash().ToString()); LogPrintf("%s: autoshield tx FAILED in CommitTransaction, txid=%s\n", opid, tx.GetHash().ToString());
set_error_code(RPC_WALLET_ERROR);
set_error_message(strprintf("Autoshield transaction %s was not accepted into the mempool (see debug.log for the "
"reason). The next round tries again.", tx.GetHash().ToString()));
return false; return false;
} }
@@ -480,12 +475,11 @@ void AsyncRPCOperation_autoshieldcoinbase::setResult() {
} }
void AsyncRPCOperation_autoshieldcoinbase::cancel() { void AsyncRPCOperation_autoshieldcoinbase::cancel() {
// Lets the queue stop an executing round when it closes at shutdown, so unlike the // Cancelling is how the scheduler stops an in-flight round, so unlike the base
// base class this must be able to move an EXECUTING operation to CANCELLED. The // class this must be able to move an EXECUTING operation to CANCELLED. What it
// scheduler never cancels a running round (it returns early while one is in flight); // must not do is overwrite a state that is already terminal: the scheduler
// it cancels the previous operation only when enqueueing the next, by which time // cancels the previous operation when it enqueues the next one, and that one may
// that one is terminal -- and a terminal state must not be overwritten, or a // have already SUCCEEDED, whose result would otherwise be relabelled as cancelled.
// SUCCEEDED result would be relabelled as cancelled.
if (isSuccess() || isFailed() || isCancelled()) if (isSuccess() || isFailed() || isCancelled())
return; return;
set_state(OperationStatus::CANCELLED); set_state(OperationStatus::CANCELLED);
@@ -52,7 +52,7 @@ public:
AsyncRPCOperation_autoshieldcoinbase& operator=(AsyncRPCOperation_autoshieldcoinbase&&) = delete; AsyncRPCOperation_autoshieldcoinbase& operator=(AsyncRPCOperation_autoshieldcoinbase&&) = delete;
virtual void main(); virtual void main();
virtual void cancel() override; virtual void cancel();
virtual UniValue getStatus() const; virtual UniValue getStatus() const;
private: private:
@@ -245,15 +245,14 @@ void AsyncRPCOperation_saplingconsolidation::main() {
stop_execution_clock(); stop_execution_clock();
// A round cancelled part-way (only the queue closing at shutdown cancels a running op) stays if (success) {
// CANCELLED rather than being relabelled by how much of it got done. set_state(OperationStatus::SUCCESS);
if (!isCancelled()) } else {
set_state(success ? OperationStatus::SUCCESS : OperationStatus::FAILED); set_state(OperationStatus::FAILED);
}
std::string s = strprintf("%s: Sapling Consolidation operation complete. (status=%s", getId(), getStateAsString()); std::string s = strprintf("%s: Sapling Consolidation operation complete. (status=%s", getId(), getStateAsString());
if (isCancelled()) { if (success) {
s += ")\n";
} else if (success) {
s += strprintf(", success)\n"); s += strprintf(", success)\n");
} else { } else {
s += strprintf(", error=%s)\n", getErrorMessage()); s += strprintf(", error=%s)\n", getErrorMessage());
@@ -313,7 +312,7 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() {
// the NU-straddle guard agree with the height the tx is signed for. Mirrors // the NU-straddle guard agree with the height the tx is signed for. Mirrors
// the autoshield op (commit 65130c312). // the autoshield op (commit 65130c312).
auto nextActivationHeight = NextActivationHeight(tipHeight, consensusParams); auto nextActivationHeight = NextActivationHeight(tipHeight, consensusParams);
if (nextActivationHeight && tipHeight + AutoOpExpiryDelta() >= nextActivationHeight.get()) { if (nextActivationHeight && tipHeight + AUTO_OP_EXPIRY_DELTA >= nextActivationHeight.get()) {
LogPrintf("%s: Consolidation txs would be created before a NU activation but may expire after. Skipping this round.\n",opid); LogPrintf("%s: Consolidation txs would be created before a NU activation but may expire after. Skipping this round.\n",opid);
setConsolidationResult(ConsolidationTally()); setConsolidationResult(ConsolidationTally());
return status; return status;
@@ -448,8 +447,8 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() {
}; };
for (const PlannedTx& planned : txs) { for (const PlannedTx& planned : txs) {
// ShutdownRequested() too: the shutdown flag is set well before the queue is closed and this op // The queue's cancel at shutdown never reaches an executing op (AsyncRPCOperation::cancel() is
// is cancelled, so checking it stops the round as soon as a stop is asked for. // not virtual), so look for the shutdown here, or a stop would wait for the whole round.
if (isCancelled() || ShutdownRequested()) { if (isCancelled() || ShutdownRequested()) {
LogPrintf("%s: %s. Stopping.\n", opid, isCancelled() ? "Canceled" : "Shutting down"); LogPrintf("%s: %s. Stopping.\n", opid, isCancelled() ? "Canceled" : "Shutting down");
tally.error = isCancelled() ? "cancelled" : "shutting down"; tally.error = isCancelled() ? "cancelled" : "shutting down";
@@ -469,7 +468,7 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() {
const AddressNotes& group = groups[planned.group]; const AddressNotes& group = groups[planned.group];
auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain); auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain);
builder.SetExpiryHeight(tipHeight + AutoOpExpiryDelta()); builder.SetExpiryHeight(tipHeight + AUTO_OP_EXPIRY_DELTA);
CAmount amountToSend = 0; CAmount amountToSend = 0;
for (const SaplingNoteEntry& entry : planned.notes) for (const SaplingNoteEntry& entry : planned.notes)
@@ -582,12 +581,11 @@ void AsyncRPCOperation_saplingconsolidation::setConsolidationResult(const Consol
} }
void AsyncRPCOperation_saplingconsolidation::cancel() { void AsyncRPCOperation_saplingconsolidation::cancel() {
// Lets the queue stop an executing round when it closes at shutdown, so unlike the // Cancelling is how the scheduler stops an in-flight round, so unlike the base
// base class this must be able to move an EXECUTING operation to CANCELLED. The // class this must be able to move an EXECUTING operation to CANCELLED. What it
// scheduler never cancels a running round (it returns early while one is in flight); // must not do is overwrite a state that is already terminal: the scheduler
// it cancels the previous operation only when enqueueing the next, by which time // cancels the previous operation when it enqueues the next one, and that one may
// that one is terminal -- and a terminal state must not be overwritten, or a // have already SUCCEEDED, whose result would otherwise be relabelled as cancelled.
// SUCCEEDED result would be relabelled as cancelled.
if (isSuccess() || isFailed() || isCancelled()) if (isSuccess() || isFailed() || isCancelled())
return; return;
set_state(OperationStatus::CANCELLED); set_state(OperationStatus::CANCELLED);
@@ -121,7 +121,7 @@ public:
virtual void main(); virtual void main();
virtual void cancel() override; virtual void cancel();
virtual UniValue getStatus() const; virtual UniValue getStatus() const;
+80 -184
View File
@@ -15,9 +15,6 @@
#include "utilmoneystr.h" #include "utilmoneystr.h"
#include "wallet.h" #include "wallet.h"
#include <algorithm>
#include <map>
extern string randomSietchZaddr(); extern string randomSietchZaddr();
CAmount fSweepTxFee = DEFAULT_SWEEP_FEE; CAmount fSweepTxFee = DEFAULT_SWEEP_FEE;
@@ -54,10 +51,11 @@ void AsyncRPCOperation_sweep::main() {
stop_execution_clock(); stop_execution_clock();
// A round cancelled part-way (only the queue closing at shutdown cancels a running op) stays if (success) {
// CANCELLED rather than being relabelled by how much of it got done. set_state(OperationStatus::SUCCESS);
if (!isCancelled()) } else {
set_state(success ? OperationStatus::SUCCESS : OperationStatus::FAILED); set_state(OperationStatus::FAILED);
}
// Scheduler bookkeeping, done here so it runs on success AND failure AND // 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 // exception (main_impl's terminal code is skipped when it throws). Only the
@@ -77,9 +75,7 @@ void AsyncRPCOperation_sweep::main() {
} }
std::string s = strprintf("%s: Sweep operation finished. (status=%s", getId(), getStateAsString()); std::string s = strprintf("%s: Sweep operation finished. (status=%s", getId(), getStateAsString());
if (isCancelled()) { if (success) {
s += ")\n";
} else if (success) {
s += strprintf(", success)\n"); s += strprintf(", success)\n");
} else { } else {
s += strprintf(", error=%s)\n", getErrorMessage()); s += strprintf(", error=%s)\n", getErrorMessage());
@@ -109,73 +105,6 @@ bool IsExcludedAddress(libzcash::SaplingPaymentAddress zaddr) {
return false; 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 AsyncRPCOperation_sweep::main_impl() {
bool status=true; bool status=true;
auto opid=getId(); auto opid=getId();
@@ -192,22 +121,13 @@ bool AsyncRPCOperation_sweep::main_impl() {
// targetHeight_, so a queue delay cannot slip a straddling expiry past this // targetHeight_, so a queue delay cannot slip a straddling expiry past this
// guard. Mirrors the autoshield op (commit 65130c312). // guard. Mirrors the autoshield op (commit 65130c312).
auto nextActivationHeight = NextActivationHeight(tipHeight, consensusParams); auto nextActivationHeight = NextActivationHeight(tipHeight, consensusParams);
if (nextActivationHeight && tipHeight + AutoOpExpiryDelta() >= nextActivationHeight.get()) { if (nextActivationHeight && tipHeight + AUTO_OP_EXPIRY_DELTA >= nextActivationHeight.get()) {
LogPrintf("%s: Sweep txs would be created before a NU activation but may expire after. Skipping this round.\n", getId()); LogPrintf("%s: Sweep txs would be created before a NU activation but may expire after. Skipping this round.\n", getId());
setSweepResult(0, 0, std::vector<std::string>()); setSweepResult(0, 0, std::vector<std::string>());
sweepComplete_ = true; // nothing to do this round; back nextSweep off one interval instead of re-dispatching every block sweepComplete_ = true; // nothing to do this round; back nextSweep off one interval instead of re-dispatching every block
return true; 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; std::vector<SaplingNoteEntry> saplingEntries;
libzcash::SaplingPaymentAddress sweepAddress; libzcash::SaplingPaymentAddress sweepAddress;
std::map<libzcash::SaplingPaymentAddress, std::vector<SaplingNoteEntry>> mapAddresses; std::map<libzcash::SaplingPaymentAddress, std::vector<SaplingNoteEntry>> mapAddresses;
@@ -272,11 +192,6 @@ bool AsyncRPCOperation_sweep::main_impl() {
bool sweepComplete = true; bool sweepComplete = true;
for (std::map<libzcash::SaplingPaymentAddress, std::vector<SaplingNoteEntry>>::iterator it = mapAddresses.begin(); it != mapAddresses.end(); it++) { 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 addr = (*it).first;
auto saplingEntries = (*it).second; auto saplingEntries = (*it).second;
@@ -285,79 +200,87 @@ bool AsyncRPCOperation_sweep::main_impl() {
std::vector<SaplingNoteEntry> fromNotes; std::vector<SaplingNoteEntry> fromNotes;
CAmount amountToSend = 0; CAmount amountToSend = 0;
// -zsweepmaxinputs, parsed and range-checked once at startup. int maxInputs = GetArg("-zsweepmaxinputs", 8);
const size_t maxInputs = pwalletMain->sweepMaxInputs; 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;
}
// Every note of this address the wallet can spend. //Count Notes availiable for this address
std::vector<SaplingNoteEntry> candidates; int targetCount = 0;
int noteCount = 0;
for (const SaplingNoteEntry& saplingEntry : saplingEntries) { for (const SaplingNoteEntry& saplingEntry : saplingEntries) {
libzcash::SaplingIncomingViewingKey ivk; libzcash::SaplingIncomingViewingKey ivk;
pwalletMain->GetSaplingIncomingViewingKey(boost::get<libzcash::SaplingPaymentAddress>(saplingEntry.address), ivk); pwalletMain->GetSaplingIncomingViewingKey(boost::get<libzcash::SaplingPaymentAddress>(saplingEntry.address), ivk);
if (ivk == extsk.expsk.full_viewing_key().in_viewing_key() && saplingEntry.address == addr)
candidates.push_back(saplingEntry);
}
if (candidates.empty())
continue;
// Up to maxInputs of them that share a witness anchor the chain knows. Notes without one (a if (ivk == extsk.expsk.full_viewing_key().in_viewing_key() && saplingEntry.address == addr) {
// missing or desynced witness) are left for a later round instead of failing this address, noteCount++;
// 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()) }
//Don't sweep if under the threshold
if (noteCount <= targetCount){
continue; continue;
for (size_t i : selection.chosen) {
fromNotes.push_back(candidates[i]);
amountToSend += CAmount(candidates[i].note.value());
} }
//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;
}
int minQuantity = 1;
if (fromNotes.size() < minQuantity)
continue;
CAmount fee = fSweepTxFee; CAmount fee = fSweepTxFee;
if (amountToSend <= fSweepTxFee) { if (amountToSend <= fSweepTxFee) {
LogPrintf("%s: Amount to send %s is <= fee, using fee=0", getId(), FormatMoney(amountToSend)); LogPrintf("%s: Amount to send %s is <= fee, using fee=0", getId(), FormatMoney(amountToSend));
fee = 0; fee = 0;
} }
// Build and expire against the tip as it is now, not as it was when the round began: a round auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain);
// over many addresses can outlive the block it started at, and a transaction built against builder.SetExpiryHeight(tipHeight + AUTO_OP_EXPIRY_DELTA);
// 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 + AutoOpExpiryDelta() >= 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 + AutoOpExpiryDelta());
LogPrintf("%s: Beginning creating transaction with Sapling output amount=%s\n", getId(), FormatMoney(amountToSend - fee)); LogPrintf("%s: Beginning creating transaction with Sapling output amount=%s\n", getId(), FormatMoney(amountToSend - fee));
// Add Sapling spends, each with the witness it was selected with // Select Sapling notes
for (size_t i = 0; i < fromNotes.size(); i++) std::vector<SaplingOutPoint> ops;
builder.AddSaplingSpend(extsk.expsk, fromNotes[i].note, selection.anchor, selection.witnesses[i].get()); 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());
}
builder.SetFee(fee); builder.SetFee(fee);
builder.AddSaplingOutput(extsk.expsk.ovk, sweepAddress, amountToSend - fee); builder.AddSaplingOutput(extsk.expsk.ovk, sweepAddress, amountToSend - fee);
@@ -384,54 +307,28 @@ bool AsyncRPCOperation_sweep::main_impl() {
auto maybe_tx = builder.Build(); auto maybe_tx = builder.Build();
if (!maybe_tx) { if (!maybe_tx) {
// Nothing was recorded, so the other addresses can still be swept. The round still fails. LogPrintf("%s: Failed to build transaction %s.\n",__func__, getId());
LogPrintf("%s: Failed to build transaction %s; trying the remaining addresses\n",__func__, getId());
status=false; status=false;
continue; break;
} }
CTransaction tx = maybe_tx.get(); CTransaction tx = maybe_tx.get();
if (isCancelled() || ShutdownRequested()) { if (isCancelled()) {
LogPrintf("%s: %s. Stopping.\n", getId(), isCancelled() ? "Canceled" : "Shutting down"); LogPrintf("%s: Canceled. Stopping.\n", getId());
break; break;
} }
if (pwalletMain->CommitAutomatedTx(tx)) { if (pwalletMain->CommitAutomatedTx(tx)) {
LogPrintf("%s: Committed sweep transaction with txid=%s\n", getId(), tx.GetHash().ToString()); 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; amountSwept += amountToSend - fee;
{
LOCK(pwalletMain->cs_wallet);
pwalletMain->amountSwept += amountToSend - fee;
}
sweepTxIds.push_back(tx.GetHash().ToString()); sweepTxIds.push_back(tx.GetHash().ToString());
numTxCreated++; numTxCreated++;
} else { } else {
LogPrintf("%s: Sweep transaction FAILED in CommitTransaction, txid=%s\n",opid , tx.GetHash().ToString()); LogPrintf("%s: Sweep transaction FAILED in CommitTransaction, txid=%s\n",opid , tx.GetHash().ToString());
// Say why the round failed: this used to finish as "failed" with an empty error. The mempool's
// reason is in debug.log just above (most often a note already spent by another transaction).
set_error_code(RPC_WALLET_ERROR);
set_error_message(strprintf("Sweep transaction %s was not accepted into the mempool (see debug.log for "
"the reason; usually one of its notes was spent by another transaction "
"meanwhile). The next round sweeps what is left.", tx.GetHash().ToString()));
setSweepResult(numTxCreated, amountSwept, sweepTxIds); setSweepResult(numTxCreated, amountSwept, sweepTxIds);
status = false; status = false;
break; 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));
} }
} }
@@ -459,12 +356,11 @@ void AsyncRPCOperation_sweep::setSweepResult(int numTxCreated, const CAmount& am
} }
void AsyncRPCOperation_sweep::cancel() { void AsyncRPCOperation_sweep::cancel() {
// Lets the queue stop an executing round when it closes at shutdown, so unlike the // Cancelling is how the scheduler stops an in-flight round, so unlike the base
// base class this must be able to move an EXECUTING operation to CANCELLED. The // class this must be able to move an EXECUTING operation to CANCELLED. What it
// scheduler never cancels a running round (it returns early while one is in flight); // must not do is overwrite a state that is already terminal: the scheduler
// it cancels the previous operation only when enqueueing the next, by which time // cancels the previous operation when it enqueues the next one, and that one may
// that one is terminal -- and a terminal state must not be overwritten, or a // have already SUCCEEDED, whose result would otherwise be relabelled as cancelled.
// SUCCEEDED result would be relabelled as cancelled.
if (isSuccess() || isFailed() || isCancelled()) if (isSuccess() || isFailed() || isCancelled())
return; return;
set_state(OperationStatus::CANCELLED); set_state(OperationStatus::CANCELLED);
+1 -40
View File
@@ -1,55 +1,18 @@
// Copyright (c) 2016-2024 The Hush developers // Copyright (c) 2016-2024 The Hush developers
// Distributed under the GPLv3 software license, see the accompanying // Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html // 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 "amount.h"
#include "asyncrpcoperation.h" #include "asyncrpcoperation.h"
#include "primitives/transaction.h"
#include "uint256.h"
#include "univalue.h" #include "univalue.h"
#include "zcash/Address.hpp" #include "zcash/Address.hpp"
#include "zcash/IncrementalMerkleTree.hpp"
#include "zcash/zip32.h" #include "zcash/zip32.h"
#include <functional>
#include <vector>
#include <boost/optional.hpp>
//Default fee used for sweep transactions //Default fee used for sweep transactions
static const CAmount DEFAULT_SWEEP_FEE = 10000; static const CAmount DEFAULT_SWEEP_FEE = 10000;
extern CAmount fSweepTxFee; extern CAmount fSweepTxFee;
extern bool fSweepMapUsed; extern bool fSweepMapUsed;
extern boost::optional<libzcash::SaplingPaymentAddress> rpcSweepAddress; 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 class AsyncRPCOperation_sweep : public AsyncRPCOperation
{ {
public: public:
@@ -64,7 +27,7 @@ public:
virtual void main(); virtual void main();
virtual void cancel() override; virtual void cancel();
virtual UniValue getStatus() const; virtual UniValue getStatus() const;
@@ -81,5 +44,3 @@ private:
void setSweepResult(int numTxCreated, const CAmount& amountSwept, const std::vector<std::string>& sweepTxIds); void setSweepResult(int numTxCreated, const CAmount& amountSwept, const std::vector<std::string>& sweepTxIds);
}; };
#endif // HUSH_WALLET_ASYNCRPCOPERATION_SWEEP_H
+1 -3
View File
@@ -299,9 +299,7 @@ UniValue importprivkey(const UniValue& params, bool fHelp, const CPubKey& mypk)
bool fRescan = true; bool fRescan = true;
if (params.size() > 2) if (params.size() > 2)
fRescan = params[2].get_bool(); fRescan = params[2].get_bool();
// '> 3', not '== 4': with the optional 5th (secret_key) argument the height was silently if ( fRescan && params.size() == 4 )
// dropped and the rescan started from genesis.
if ( fRescan && params.size() > 3 )
height = params[3].get_int(); height = params[3].get_int();
+1 -1
View File
@@ -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("expiryheight", (int64_t)wtx.nExpiryHeight));
tx.push_back(Pair("confirmations", confirms)); tx.push_back(Pair("confirmations", confirms));
tx.push_back(Pair("time", wtx.GetTxTime())); tx.push_back(Pair("time", wtx.GetTxTime()));
tx.push_back(Pair("size", static_cast<uint64_t>(GetSerializeSize(static_cast<const CTransaction&>(wtx), SER_NETWORK, PROTOCOL_VERSION)))); tx.push_back(Pair("size", static_cast<uint64_t>(GetSerializeSize(static_cast<CTransaction>(wtx), SER_NETWORK, PROTOCOL_VERSION))));
//Wallet Conflicts //Wallet Conflicts
UniValue conflicts(UniValue::VARR); UniValue conflicts(UniValue::VARR);
+28 -55
View File
@@ -43,7 +43,6 @@
#include "wallet/asyncrpcoperation_sendmany.h" #include "wallet/asyncrpcoperation_sendmany.h"
#include "wallet/asyncrpcoperation_shieldcoinbase.h" #include "wallet/asyncrpcoperation_shieldcoinbase.h"
#include "wallet/asyncrpcoperation_saplingconsolidation.h" #include "wallet/asyncrpcoperation_saplingconsolidation.h"
#include "wallet/asyncrpcoperation_sweep.h"
#include "consensus/upgrades.h" #include "consensus/upgrades.h"
#include "sodium.h" #include "sodium.h"
#include <stdint.h> #include <stdint.h>
@@ -113,6 +112,23 @@ void EnsureWalletIsUnlocked()
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
} }
void Lock2NSPV(const CPubKey &pk)
{
if (!pk.IsValid())
{
ENTER_CRITICAL_SECTION(cs_main);
ENTER_CRITICAL_SECTION(pwalletMain->cs_wallet);
}
}
void Unlock2NSPV(const CPubKey &pk)
{
if (!pk.IsValid())
{
LEAVE_CRITICAL_SECTION(cs_main);
LEAVE_CRITICAL_SECTION(pwalletMain->cs_wallet);
}
}
void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry) void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry)
{ {
@@ -1788,7 +1804,7 @@ void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDe
entry.push_back(Pair("fee", ValueFromAmount(-nFee))); entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong) if (fLong)
WalletTxToJSON(wtx, entry); WalletTxToJSON(wtx, entry);
entry.push_back(Pair("size", static_cast<uint64_t>(GetSerializeSize(static_cast<const CTransaction&>(wtx), SER_NETWORK, PROTOCOL_VERSION)))); entry.push_back(Pair("size", static_cast<uint64_t>(GetSerializeSize(static_cast<CTransaction>(wtx), SER_NETWORK, PROTOCOL_VERSION))));
ret.push_back(entry); ret.push_back(entry);
} }
} }
@@ -1833,7 +1849,7 @@ void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDe
entry.push_back(Pair("vout", r.vout)); entry.push_back(Pair("vout", r.vout));
if (fLong) if (fLong)
WalletTxToJSON(wtx, entry); WalletTxToJSON(wtx, entry);
entry.push_back(Pair("size", static_cast<uint64_t>(GetSerializeSize(static_cast<const CTransaction&>(wtx), SER_NETWORK, PROTOCOL_VERSION)))); entry.push_back(Pair("size", static_cast<uint64_t>(GetSerializeSize(static_cast<CTransaction>(wtx), SER_NETWORK, PROTOCOL_VERSION))));
ret.push_back(entry); ret.push_back(entry);
} }
} }
@@ -1935,10 +1951,6 @@ UniValue listtransactions(const UniValue& params, bool fHelp, const CPubKey& myp
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count"); throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0) if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from"); 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); UniValue ret(UniValue::VARR);
@@ -2227,7 +2239,7 @@ UniValue gettransaction(const UniValue& params, bool fHelp, const CPubKey& mypk)
ListTransactions(wtx, "*", 0, false, details, filter); ListTransactions(wtx, "*", 0, false, details, filter);
entry.push_back(Pair("details", details)); entry.push_back(Pair("details", details));
string strHex = EncodeHexTx(static_cast<const CTransaction&>(wtx)); string strHex = EncodeHexTx(static_cast<CTransaction>(wtx));
entry.push_back(Pair("hex", strHex)); entry.push_back(Pair("hex", strHex));
return entry; return entry;
@@ -3300,8 +3312,6 @@ UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey
"{\n" "{\n"
" \"consolidation\" : true|false, (boolean) whether periodic consolidation (-consolidation) is on\n" " \"consolidation\" : true|false, (boolean) whether periodic consolidation (-consolidation) is on\n"
" \"running\" : true|false, (boolean) whether a round is in flight\n" " \"running\" : true|false, (boolean) whether a round is in flight\n"
" \"waiting_for_sweep\" : true|false, (boolean) a due round is waiting for a zsweep round to end;\n"
" no new sweep round starts until it has run\n"
" \"amount_consolidated\" : n, (numeric) value of the notes created since startup, in puposhis\n" " \"amount_consolidated\" : n, (numeric) value of the notes created since startup, in puposhis\n"
" \"next_consolidation\" : n, (numeric) height of the next periodic round\n" " \"next_consolidation\" : n, (numeric) height of the next periodic round\n"
" \"consolidationinterval\" : n, (numeric) blocks between periodic rounds\n" " \"consolidationinterval\" : n, (numeric) blocks between periodic rounds\n"
@@ -3350,7 +3360,6 @@ UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey
UniValue ret(UniValue::VOBJ); UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("consolidation", pwalletMain->fSaplingConsolidationEnabled)); ret.push_back(Pair("consolidation", pwalletMain->fSaplingConsolidationEnabled));
ret.push_back(Pair("running", pwalletMain->fConsolidationRunning)); ret.push_back(Pair("running", pwalletMain->fConsolidationRunning));
ret.push_back(Pair("waiting_for_sweep", pwalletMain->fConsolidationWaiting));
ret.push_back(Pair("amount_consolidated", (int64_t)stats.amountConsolidated)); ret.push_back(Pair("amount_consolidated", (int64_t)stats.amountConsolidated));
ret.push_back(Pair("next_consolidation", pwalletMain->nextConsolidation)); ret.push_back(Pair("next_consolidation", pwalletMain->nextConsolidation));
ret.push_back(Pair("consolidationinterval", pwalletMain->consolidationInterval)); ret.push_back(Pair("consolidationinterval", pwalletMain->consolidationInterval));
@@ -3532,23 +3541,7 @@ UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk)
if (fHelp || params.size() > 0) if (fHelp || params.size() > 0)
throw runtime_error( throw runtime_error(
"z_sweepstatus\n" "z_sweepstatus\n"
"\nGive details about zsweep operations since the node was started.\n" "\nGive details about zsweep operations since the node was started."
"\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"
" \"waiting_for_consolidation\" : true|false, (boolean) a due round is waiting for a consolidation round to end;\n"
" no new consolidation round starts until it has run\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" "}\n"
"\nExamples:\n" "\nExamples:\n"
+ HelpExampleCli("z_sweepstatus", "") + HelpExampleCli("z_sweepstatus", "")
@@ -3560,9 +3553,7 @@ UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk)
UniValue ret(UniValue::VOBJ); UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("zsweep", pwalletMain->fSweepEnabled)); ret.push_back(Pair("zsweep", pwalletMain->fSweepEnabled));
ret.push_back(Pair("running", pwalletMain->fSweepRunning)); ret.push_back(Pair("running", pwalletMain->fSweepRunning));
ret.push_back(Pair("wallet_locked", pwalletMain->IsLocked())); ret.push_back(Pair("amount_swept", pwalletMain->amountSwept));
ret.push_back(Pair("waiting_for_consolidation", pwalletMain->fSweepWaiting));
ret.push_back(Pair("amount_swept", ValueFromAmount(pwalletMain->amountSwept)));
ret.push_back(Pair("next_zsweep", pwalletMain->nextSweep)); ret.push_back(Pair("next_zsweep", pwalletMain->nextSweep));
ret.push_back(Pair("zsweepinterval", pwalletMain->sweepInterval)); ret.push_back(Pair("zsweepinterval", pwalletMain->sweepInterval));
ret.push_back(Pair("zsweepaddress", pwalletMain->sweepAddress)); ret.push_back(Pair("zsweepaddress", pwalletMain->sweepAddress));
@@ -3572,7 +3563,7 @@ UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk)
} }
ret.push_back(Pair("zsweepexclude", excludes)); ret.push_back(Pair("zsweepexclude", excludes));
ret.push_back(Pair("zsweepmaxinputs", pwalletMain->sweepMaxInputs)); ret.push_back(Pair("zsweepmaxinputs", pwalletMain->sweepMaxInputs));
ret.push_back(Pair("zsweepfee", fSweepTxFee)); ret.push_back(Pair("zsweepfee", pwalletMain->sweepFee));
ret.push_back(Pair("zsweepexternal", pwalletMain->fSweepExternalEnabled)); ret.push_back(Pair("zsweepexternal", pwalletMain->fSweepExternalEnabled));
return ret; return ret;
@@ -5178,17 +5169,8 @@ UniValue z_viewtransaction(const UniValue& params, bool fHelp, const CPubKey& my
continue; continue;
} }
auto op = res->second; auto op = res->second;
// By reference: a CWalletTx copy deep-copies every note's witness list. The nullifier map can auto wtxPrev = pwalletMain->mapWallet.at(op.hash);
// outlive the tx it points to (DeleteTransactions doesn't prune it); skip such a spend like an auto decrypted = wtxPrev.DecryptSaplingNote(op).get();
// 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 notePt = decrypted.first;
auto pa = decrypted.second; auto pa = decrypted.second;
@@ -5290,11 +5272,7 @@ UniValue z_getoperationresult(const UniValue& params, bool fHelp, const CPubKey&
+ HelpExampleRpc("z_getoperationresult", "'[\"operationid\", ... ]'") + HelpExampleRpc("z_getoperationresult", "'[\"operationid\", ... ]'")
); );
// This call will remove finished operations. It keeps cs_main + cs_wallet, which // This call will remove finished operations
// 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); return z_getoperationstatus_IMPL(params, true);
} }
@@ -5323,11 +5301,7 @@ UniValue z_getoperationstatus(const UniValue& params, bool fHelp, const CPubKey&
UniValue z_getoperationstatus_IMPL(const UniValue& params, bool fRemoveFinishedOperations=false) UniValue z_getoperationstatus_IMPL(const UniValue& params, bool fRemoveFinishedOperations=false)
{ {
// No cs_main/cs_wallet here (the removing caller, z_getoperationresult, takes them itself). LOCK2(cs_main, pwalletMain->cs_wallet);
// 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; std::set<AsyncRPCOperationId> filter;
if (params.size()==1) { if (params.size()==1) {
@@ -6464,8 +6438,7 @@ UniValue z_listoperationids(const UniValue& params, bool fHelp, const CPubKey& m
+ HelpExampleRpc("z_listoperationids", "") + HelpExampleRpc("z_listoperationids", "")
); );
// No cs_main/cs_wallet: like z_getoperationstatus, this only reads the self-locking async LOCK2(cs_main, pwalletMain->cs_wallet);
// queue and each operation's atomic state.
std::string filter; std::string filter;
bool useFilter = false; bool useFilter = false;
+16 -93
View File
@@ -625,14 +625,13 @@ void CWallet::RunSaplingSweep(int blockHeight) {
// consolidation waits on sweep, and autoshield shares the same gate, so a // consolidation waits on sweep, and autoshield shares the same gate, so a
// wedged sweep silently disables coinbase shielding forever. // wedged sweep silently disables coinbase shielding forever.
// Only honour the baton while a sweep operation genuinely is in flight. // Only honour the baton while a sweep operation genuinely is in flight.
bool fSweepInFlight = false;
if (fSweepRunning) { if (fSweepRunning) {
std::shared_ptr<AsyncRPCQueue> sweepQueue = getAsyncRPCQueue(); std::shared_ptr<AsyncRPCQueue> sweepQueue = getAsyncRPCQueue();
std::shared_ptr<AsyncRPCOperation> inFlightSweep = std::shared_ptr<AsyncRPCOperation> inFlightSweep =
(sweepQueue != nullptr) ? sweepQueue->getOperationForId(saplingSweepOperationId) : nullptr; (sweepQueue != nullptr) ? sweepQueue->getOperationForId(saplingSweepOperationId) : nullptr;
fSweepInFlight = (inFlightSweep != nullptr) && bool inFlight = (inFlightSweep != nullptr) &&
(inFlightSweep->isReady() || inFlightSweep->isExecuting()); (inFlightSweep->isReady() || inFlightSweep->isExecuting());
if (!fSweepInFlight) { if (!inFlight) {
LogPrintf("%s: clearing stale fSweepRunning at blockHeight=%d (no sweep operation in flight)\n", LogPrintf("%s: clearing stale fSweepRunning at blockHeight=%d (no sweep operation in flight)\n",
__func__, blockHeight); __func__, blockHeight);
fSweepRunning = false; fSweepRunning = false;
@@ -640,18 +639,6 @@ void CWallet::RunSaplingSweep(int blockHeight) {
} }
if (!fSweepEnabled) { if (!fSweepEnabled) {
fSweepWaiting = false;
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; return;
} }
@@ -661,29 +648,15 @@ void CWallet::RunSaplingSweep(int blockHeight) {
} }
LogPrintf("%s: Sweep enabled at blockHeight=%d nextSweep=%d\n", __func__, blockHeight, nextSweep); 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 //Don't Run if consolidation will run soon.
// would report success with nothing swept. Say so, and look again an interval later. if (fSaplingConsolidationEnabled && nextConsolidation - 5 <= blockHeight) {
if (IsLocked()) { LogPrintf("%s: not sweeping since next consolidation is within 5 blocks, nextConsolidation=%d , blockHeight=%d\n", __func__, nextConsolidation, blockHeight);
LogPrintf("%s: wallet locked; not sweeping at height=%d. Unlock it with walletpassphrase "
"for zsweep to resume\n", __func__, blockHeight);
nextSweep = sweepInterval + blockHeight;
fSweepWaiting = false;
return; return;
} }
// Strict turns with consolidation (see fSweepWaiting / fConsolidationWaiting). This replaces a //Don't Run While consolidation is running.
// "consolidation is due within 5 blocks" blackout, which with consolidationinterval=5 was always true.
//Don't Run While consolidation is running: wait, and take the next turn.
if (fConsolidationRunning) { if (fConsolidationRunning) {
LogPrintf("%s: not sweeping since consolidation is currently running at height=%d; the sweep goes next\n", __func__, blockHeight); LogPrintf("%s: not sweeping since consolidation is currently running at height=%d\n", __func__, blockHeight);
fSweepWaiting = true;
return;
}
//A consolidation round that came due while a sweep was running goes first.
if (fConsolidationWaiting && fSaplingConsolidationEnabled) {
LogPrintf("%s: not sweeping since a consolidation round is waiting for its turn at height=%d\n", __func__, blockHeight);
fSweepWaiting = false; // never both waiting: that would leave neither op able to start
return; return;
} }
@@ -694,7 +667,6 @@ void CWallet::RunSaplingSweep(int blockHeight) {
} }
fSweepRunning = true; fSweepRunning = true;
fSweepWaiting = false;
std::shared_ptr<AsyncRPCQueue> q = getAsyncRPCQueue(); std::shared_ptr<AsyncRPCQueue> q = getAsyncRPCQueue();
std::shared_ptr<AsyncRPCOperation> lastOperation = q->getOperationForId(saplingSweepOperationId); std::shared_ptr<AsyncRPCOperation> lastOperation = q->getOperationForId(saplingSweepOperationId);
@@ -708,7 +680,6 @@ void CWallet::RunSaplingSweep(int blockHeight) {
pendingSaplingSweepTxs.clear(); pendingSaplingSweepTxs.clear();
std::shared_ptr<AsyncRPCOperation> operation(new AsyncRPCOperation_sweep(blockHeight + AUTO_OP_TARGET_HEIGHT_OFFSET)); std::shared_ptr<AsyncRPCOperation> operation(new AsyncRPCOperation_sweep(blockHeight + AUTO_OP_TARGET_HEIGHT_OFFSET));
saplingSweepOperationId = operation->getId(); saplingSweepOperationId = operation->getId();
sweepDispatchHeight = blockHeight;
if (!q->addOperation(operation)) { if (!q->addOperation(operation)) {
// Queue is closing (shutdown). Release the flag we just set, or it stays // Queue is closing (shutdown). Release the flag we just set, or it stays
// set with no operation in flight and blocks every later round. // set with no operation in flight and blocks every later round.
@@ -727,7 +698,6 @@ void CWallet::RunSaplingConsolidation(int blockHeight) {
LOCK(cs_wallet); LOCK(cs_wallet);
if (!fSaplingConsolidationEnabled) { if (!fSaplingConsolidationEnabled) {
fConsolidationWaiting = false;
return; return;
} }
@@ -747,23 +717,13 @@ void CWallet::RunSaplingConsolidation(int blockHeight) {
if (IsLocked()) { if (IsLocked()) {
LogPrintf("%s: wallet locked; not consolidating at height=%d\n", __func__, blockHeight); LogPrintf("%s: wallet locked; not consolidating at height=%d\n", __func__, blockHeight);
nextConsolidation = consolidationInterval + blockHeight; nextConsolidation = consolidationInterval + blockHeight;
fConsolidationWaiting = false;
return; return;
} }
LogPrintf("%s: consolidation enabled at blockHeight=%d fSweepRunning=%d\n", __func__, blockHeight, fSweepRunning ); LogPrintf("%s: consolidation enabled at blockHeight=%d fSweepRunning=%d\n", __func__, blockHeight, fSweepRunning );
//Don't Run While a sweep is running: wait, and take the next turn (nextConsolidation stays put).
if (fSweepRunning) { if (fSweepRunning) {
LogPrintf("%s: not consolidating since sweep is currently running at height=%d; consolidation goes next\n", __func__, blockHeight); LogPrintf("%s: not consolidating since sweep is currently running at height=%d\n", __func__, blockHeight);
fConsolidationWaiting = true;
return;
}
//A sweep that came due while this op was running goes first.
if (fSweepWaiting && fSweepEnabled) {
LogPrintf("%s: not consolidating since a due sweep is waiting for its turn at height=%d\n", __func__, blockHeight);
fConsolidationWaiting = false; // never both waiting
return; return;
} }
@@ -774,7 +734,6 @@ void CWallet::RunSaplingConsolidation(int blockHeight) {
LogPrintf("%s: creating consolidation operation at blockHeight=%d\n", __func__, blockHeight); LogPrintf("%s: creating consolidation operation at blockHeight=%d\n", __func__, blockHeight);
fConsolidationRunning = true; fConsolidationRunning = true;
fConsolidationWaiting = false;
std::shared_ptr<AsyncRPCQueue> q = getAsyncRPCQueue(); std::shared_ptr<AsyncRPCQueue> q = getAsyncRPCQueue();
std::shared_ptr<AsyncRPCOperation> lastOperation = q->getOperationForId(saplingConsolidationOperationId); std::shared_ptr<AsyncRPCOperation> lastOperation = q->getOperationForId(saplingConsolidationOperationId);
if (lastOperation != nullptr) { if (lastOperation != nullptr) {
@@ -850,7 +809,7 @@ void CWallet::RefreshConsolidationSuggestion() {
// silent no-op wherever it cannot act (locked wallet, no owned coinbase, // silent no-op wherever it cannot act (locked wallet, no owned coinbase,
// external -mineraddress), so it is safe to run on every node. // external -mineraddress), so it is safe to run on every node.
void CWallet::RunAutoShieldCoinbase(int blockHeight) { void CWallet::RunAutoShieldCoinbase(int blockHeight) {
// Sapling is always active from height 1 on DragonX and other smart chains. // Sapling is always active from height 1 on DragonX+HACs.
if (blockHeight == 0) if (blockHeight == 0)
return; return;
@@ -1454,17 +1413,6 @@ void ClearSingleNoteWitnessCache(NoteData* nd)
nd->witnessRootValidated = false; nd->witnessRootValidated = false;
} }
bool TrimDeeplySpentNoteWitnesses(SaplingNoteData& nd, unsigned int nSpendDepth, unsigned int nCacheSize)
{
// Never empty the list: UpdateSaplingNullifierNoteMapWithTx drops the nullifier of a note with no
// witnesses, and a spent note without a nullifier is counted as unspent by GetFilteredNotes.
if (!nd.nullifier || nSpendDepth <= nCacheSize || nd.witnesses.size() <= 1)
return false;
while (nd.witnesses.size() > 1)
nd.witnesses.pop_back(); // oldest snapshots are at the back; front() stays the one at witnessHeight
return true;
}
// A note without a nullifier is never extended by BuildWitnessCache (its pending-note gate requires one), // A note without a nullifier is never extended by BuildWitnessCache (its pending-note gate requires one),
// so it doesn't pull the rebuild's start height down. // so it doesn't pull the rebuild's start height down.
int CWallet::SaplingWitnessMinimumHeight(const boost::optional<uint256>& nullifier, int nWitnessHeight, int nMinimumHeight) int CWallet::SaplingWitnessMinimumHeight(const boost::optional<uint256>& nullifier, int nWitnessHeight, int nMinimumHeight)
@@ -1765,7 +1713,6 @@ void CWallet::BuildWitnessCache(const CBlockIndex* pindex, bool witnessOnly)
// cost changes from O(blocks * walletSize) to O(blocks + activeNotes). // cost changes from O(blocks * walletSize) to O(blocks + activeNotes).
struct PendingNote { int startWitnessHeight; SaplingNoteData* nd; }; struct PendingNote { int startWitnessHeight; SaplingNoteData* nd; };
std::vector<PendingNote> pending; std::vector<PendingNote> pending;
int nNotesTrimmed = 0;
for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) { for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
if (wtxItem.second.mapSaplingNoteData.empty()) if (wtxItem.second.mapSaplingNoteData.empty())
continue; continue;
@@ -1777,24 +1724,14 @@ void CWallet::BuildWitnessCache(const CBlockIndex* pindex, bool witnessOnly)
continue; continue;
if (nd->witnesses.empty()) // cannot extend (front() would be UB); the original gate also never matched these in practice if (nd->witnesses.empty()) // cannot extend (front() would be UB); the original gate also never matched these in practice
continue; continue;
const unsigned int nSpendDepth = GetSaplingSpendDepth(*nd->nullifier); if (GetSaplingSpendDepth(*nd->nullifier) > WITNESS_CACHE_SIZE)
if (nSpendDepth > WITNESS_CACHE_SIZE) {
// Spent beyond reorg reach: no longer extended, so its older snapshots are dead weight.
if (TrimDeeplySpentNoteWitnesses(*nd, nSpendDepth, WITNESS_CACHE_SIZE))
nNotesTrimmed++;
continue; continue;
}
// Only notes that still lag the build target need extension. The lowest such witnessHeight // Only notes that still lag the build target need extension. The lowest such witnessHeight
// is exactly startHeight-1 (startHeight = nMinimumHeight+1 from SaplingWitnessMinimumHeight). // is exactly startHeight-1 (startHeight = nMinimumHeight+1 from SaplingWitnessMinimumHeight).
if (nd->witnessHeight >= startHeight - 1 && nd->witnessHeight <= pindex->GetHeight() - 1) if (nd->witnessHeight >= startHeight - 1 && nd->witnessHeight <= pindex->GetHeight() - 1)
pending.push_back({ nd->witnessHeight, nd }); pending.push_back({ nd->witnessHeight, nd });
} }
} }
if (nNotesTrimmed > 0) {
nWitnessGeneration++; // the next SetBestChain (or the shutdown save) writes the shorter lists
LogPrintf("%s: dropped the older witnesses of %d note(s) spent more than %u blocks ago\n",
__func__, nNotesTrimmed, WITNESS_CACHE_SIZE);
}
std::sort(pending.begin(), pending.end(), std::sort(pending.begin(), pending.end(),
[](const PendingNote& a, const PendingNote& b) { return a.startWitnessHeight < b.startWitnessHeight; }); [](const PendingNote& a, const PendingNote& b) { return a.startWitnessHeight < b.startWitnessHeight; });
@@ -3392,14 +3329,12 @@ boost::optional<std::pair<
SaplingPaymentAddress>> CWalletTx::DecryptSaplingNote(SaplingOutPoint op) const SaplingPaymentAddress>> CWalletTx::DecryptSaplingNote(SaplingOutPoint op) const
{ {
// Check whether we can decrypt this SaplingOutPoint // Check whether we can decrypt this SaplingOutPoint
mapSaplingNoteData_t::const_iterator ndIt = this->mapSaplingNoteData.find(op); if (this->mapSaplingNoteData.count(op) == 0) {
if (ndIt == this->mapSaplingNoteData.end()) {
return boost::none; return boost::none;
} }
// References: a SaplingNoteData copy deep-copies the note's witness list. auto output = this->vShieldedOutput[op.n];
const OutputDescription& output = this->vShieldedOutput[op.n]; auto nd = this->mapSaplingNoteData.at(op);
const SaplingNoteData& nd = ndIt->second;
auto maybe_pt = SaplingNotePlaintext::decrypt( auto maybe_pt = SaplingNotePlaintext::decrypt(
output.encCiphertext, output.encCiphertext,
@@ -4351,9 +4286,7 @@ std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
{ {
std::vector<uint256> result; std::vector<uint256> result;
// Both callers (the periodic Broadcast signal from SendMessages, and resendwallettransactions) hold LOCK(cs_wallet);
// cs_main already; GetDepthInMainChain below needs it.
LOCK2(cs_main, cs_wallet);
// Sort them in chronological order // Sort them in chronological order
multimap<unsigned int, CWalletTx*> mapSorted; multimap<unsigned int, CWalletTx*> mapSorted;
uint32_t now = (uint32_t)time(NULL); uint32_t now = (uint32_t)time(NULL);
@@ -4361,7 +4294,7 @@ std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
// vector of wallet transactions to delete // vector of wallet transactions to delete
std::vector<uint256> vwtxh; std::vector<uint256> vwtxh;
uint32_t erased = 0, skipped = 0, expired = 0; uint32_t erased = 0, skipped = 0;
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{ {
@@ -4370,18 +4303,10 @@ std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
if (wtx.nTimeReceived > nTime) if (wtx.nTimeReceived > nTime)
continue; continue;
// A mined transaction has nothing to rebroadcast. It used to reach the expiry test below, and every
// confirmed tx is past its expiry height a few hundred blocks after it was mined, so each pass logged
// one "ignoring expired tx" line per wallet tx ever made: 1.1M lines (354 MB of debug.log) in a day on
// an exchange-style wallet of ~15k txs.
if (wtx.GetDepthInMainChain() > 0)
continue;
// Do not relay expired transactions, to avoid other nodes banning us // Do not relay expired transactions, to avoid other nodes banning us
// Current code will not ban nodes relaying expired txs but older nodes will // Current code will not ban nodes relaying expired txs but older nodes will
if (wtx.nExpiryHeight > 0 && wtx.nExpiryHeight < chainActive.LastTip()->GetHeight()) { if (wtx.nExpiryHeight > 0 && wtx.nExpiryHeight < chainActive.LastTip()->GetHeight()) {
LogPrint("wallet", "%s: ignoring expired tx %s with expiry %d at height %d\n", __func__, wtx.GetHash().ToString().c_str(), wtx.nExpiryHeight, chainActive.LastTip()->GetHeight() ); LogPrintf("%s: ignoring expired tx %s with expiry %d at height %d\n", __func__, wtx.GetHash().ToString().c_str(), wtx.nExpiryHeight, chainActive.LastTip()->GetHeight() );
expired++;
// TODO: expired detection doesn't seem to work right // TODO: expired detection doesn't seem to work right
// append to list of txs to delete // append to list of txs to delete
// vwtxh.push_back(wtx.GetHash()); // vwtxh.push_back(wtx.GetHash());
@@ -4427,8 +4352,6 @@ std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
if(erased > 0 || skipped > 0) { if(erased > 0 || skipped > 0) {
LogPrintf("%s: Prevented relaying %d and erased %d transactions which are too old\n", __func__, skipped, erased); LogPrintf("%s: Prevented relaying %d and erased %d transactions which are too old\n", __func__, skipped, erased);
} }
if (expired > 0)
LogPrintf("%s: not relaying %u expired unconfirmed transaction(s) (-debug=wallet lists them)\n", __func__, expired);
return result; return result;
} }
+4 -41
View File
@@ -112,10 +112,6 @@ static const int MIN_AUTOSHIELD_INTERVAL = 5;
static const int DEFAULT_AUTOSHIELD_MIN_UTXOS = 1; 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_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 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 // 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, // 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. // each spending up to batchsize of its smallest notes back to that same address.
@@ -132,12 +128,7 @@ static const CAmount CONSOLIDATION_MIN_FEE = AUTOSHIELD_MIN_FEE;
static const CAmount CONSOLIDATION_MAX_FEE = AUTOSHIELD_MAX_FEE; static const CAmount CONSOLIDATION_MAX_FEE = AUTOSHIELD_MAX_FEE;
static const int CONSOLIDATION_MIN_DEPTH = 11; // leaves room for an anchor at height N-10 static const int CONSOLIDATION_MIN_DEPTH = 11; // leaves room for an anchor at height N-10
static const int AUTO_OP_TARGET_HEIGHT_OFFSET = 5; // blocks of lookahead when scheduling an async op static const int AUTO_OP_TARGET_HEIGHT_OFFSET = 5; // blocks of lookahead when scheduling an async op
// Expiry window for the transactions zsweep, consolidation and autoshield build, and for their NU-straddle static const int AUTO_OP_EXPIRY_DELTA = 15; // NU-straddle expiry window, shared by all three ops
// guards: the same -txexpirydelta (default 200) as any other wallet transaction. These used a fixed 15 blocks,
// which ran out before the wallet's rebroadcast (every 0-30 min, and only for txs a few minutes older than the
// last block) ever retried a tx the half-of-peers relay had not carried to a miner: on a node with a handful of
// peers about one sweep tx in five expired unmined, while the sweep had already counted it as swept.
inline int AutoOpExpiryDelta() { return (int)expiryDelta; }
extern const char * DEFAULT_WALLET_DAT; extern const char * DEFAULT_WALLET_DAT;
@@ -399,13 +390,6 @@ public:
typedef std::map<JSOutPoint, SproutNoteData> mapSproutNoteData_t; typedef std::map<JSOutPoint, SproutNoteData> mapSproutNoteData_t;
typedef std::map<SaplingOutPoint, SaplingNoteData> mapSaplingNoteData_t; typedef std::map<SaplingOutPoint, SaplingNoteData> mapSaplingNoteData_t;
//! For a note spent nSpendDepth blocks ago: once that is deeper than nCacheSize (WITNESS_CACHE_SIZE) no reorg
//! can un-spend it and BuildWitnessCache stops extending it, so only the newest witness is kept. That one holds
//! the note's position (its nullifier) and the root VerifyAndSetInitialWitness validates; the older snapshots,
//! up to nCacheSize per note, were otherwise kept in memory and rewritten to wallet.dat for every spent note
//! the wallet ever had. Returns true if anything was dropped; never empties the list.
bool TrimDeeplySpentNoteWitnesses(SaplingNoteData& nd, unsigned int nSpendDepth, unsigned int nCacheSize);
/** Sapling note, its location in a transaction, and number of confirmations. */ /** Sapling note, its location in a transaction, and number of confirmations. */
struct SaplingNoteEntry struct SaplingNoteEntry
{ {
@@ -915,15 +899,6 @@ public:
bool fSweepEnabled = false; bool fSweepEnabled = false;
bool fSweepExternalEnabled = false; bool fSweepExternalEnabled = false;
bool fSweepRunning = false; bool fSweepRunning = false;
// Strict turns between zsweep and consolidation: an op that came due while the other was running
// goes next. fSweepWaiting is set when a due sweep finds a consolidation round running, and keeps a
// new consolidation round from starting; fConsolidationWaiting is the same the other way round, and
// keeps a new sweep round from starting. Each is cleared when its own op is dispatched (or turned
// off, or skipped for a locked wallet). Without them the two starved each other: the sweep lost every
// block to a 5-block "consolidation is due soon" blackout, and once that was relaxed, back-to-back
// sweep rounds left consolidation no block at all.
bool fSweepWaiting = false;
bool fConsolidationWaiting = false;
// Automatic coinbase shielding (t->z). The real default is computed in // Automatic coinbase shielding (t->z). The real default is computed in
// init.cpp: ON only for known-recoverable seed provenance (CREATED/RESTORED), // init.cpp: ON only for known-recoverable seed provenance (CREATED/RESTORED),
@@ -955,10 +930,7 @@ public:
// Id of the in-flight sweep op; read by the op to confirm it is still the // Id of the in-flight sweep op; read by the op to confirm it is still the
// current one before mutating scheduler state. // current one before mutating scheduler state.
AsyncRPCOperationId saplingSweepOperationId; AsyncRPCOperationId saplingSweepOperationId;
// Block height at which that op was enqueued (for the log while RunSaplingSweep waits on it). int amountSwept = 0;
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. // What consolidation rounds have done since startup. Guarded by cs_wallet.
SaplingConsolidationStats consolidationStats; SaplingConsolidationStats consolidationStats;
// With -consolidation off: how many addresses are over the threshold (-1 until counted), at which // With -consolidation off: how many addresses are over the threshold (-1 until counted), at which
@@ -973,8 +945,8 @@ public:
int consolidationMaxTxs = DEFAULT_CONSOLIDATION_MAXTXS; int consolidationMaxTxs = DEFAULT_CONSOLIDATION_MAXTXS;
// -consolidatesaplingaddress (or the zsweep address); empty: every address the wallet can spend. // -consolidatesaplingaddress (or the zsweep address); empty: every address the wallet can spend.
std::vector<libzcash::SaplingPaymentAddress> consolidationAddresses; std::vector<libzcash::SaplingPaymentAddress> consolidationAddresses;
// Set from -zsweepmaxinputs at startup and read by every sweep op. (The fee lives in fSweepTxFee.) int sweepFee = 10000;
int sweepMaxInputs = DEFAULT_SWEEP_MAX_INPUTS; int sweepMaxInputs = 200;
std::string sweepAddress = ""; std::string sweepAddress = "";
std::vector<std::string> sweepExcludeAddresses; std::vector<std::string> sweepExcludeAddresses;
std::string consolidationAddress = ""; std::string consolidationAddress = "";
@@ -1097,15 +1069,6 @@ protected:
if (pindexWalletTip != nullptr) { if (pindexWalletTip != nullptr) {
locator = chainActive.GetLocator(pindexWalletTip); locator = chainActive.GetLocator(pindexWalletTip);
pindexStamped = 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()) { } else if (!loc.vHave.empty()) {
BlockMap::const_iterator mi = mapBlockIndex.find(loc.vHave.front()); BlockMap::const_iterator mi = mapBlockIndex.find(loc.vHave.front());
if (mi != mapBlockIndex.end()) if (mi != mapBlockIndex.end())
-10
View File
@@ -24,16 +24,6 @@ uint256 SaplingPaymentAddress::GetHash() const {
return Hash(ss.begin(), ss.end()); 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 { SaplingFullViewingKey SaplingExpandedSpendingKey::full_viewing_key() const {
uint256 ak; uint256 ak;
uint256 nk; uint256 nk;
-7
View File
@@ -89,13 +89,6 @@ public:
//! Get the 256-bit SHA256d hash of this payment address. //! Get the 256-bit SHA256d hash of this payment address.
uint256 GetHash() const; 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) { friend inline bool operator==(const SaplingPaymentAddress& a, const SaplingPaymentAddress& b) {
return a.d == b.d && a.pk_d == b.pk_d; return a.d == b.d && a.pk_d == b.pk_d;
} }
+1 -1
View File
@@ -31,7 +31,7 @@ my $acname = shift;
if ($acname) { if ($acname) {
# TODO: is acname valid? # TODO: is acname valid?
$cli .= " -ac_name=$acname"; $cli .= " -ac_name=$acname";
# smart chains by default have a blocktime of 60s # HSC's by default have a blocktime of 60s
$perday = 1440; $perday = 1440;
} else { } else {
$acname = 'DRAGONX'; $acname = 'DRAGONX';