dash/src/coinjoin/client.cpp

1854 lines
77 KiB
C++
Raw Normal View History

// Copyright (c) 2014-2021 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
2018-11-05 10:29:33 +01:00
#include <coinjoin/client.h>
#include <coinjoin/options.h>
#include <chainparams.h>
Backport 11651 (#3358) * scripted-diff: Replace #include "" with #include <> (ryanofsky) -BEGIN VERIFY SCRIPT- for f in \ src/*.cpp \ src/*.h \ src/bench/*.cpp \ src/bench/*.h \ src/compat/*.cpp \ src/compat/*.h \ src/consensus/*.cpp \ src/consensus/*.h \ src/crypto/*.cpp \ src/crypto/*.h \ src/crypto/ctaes/*.h \ src/policy/*.cpp \ src/policy/*.h \ src/primitives/*.cpp \ src/primitives/*.h \ src/qt/*.cpp \ src/qt/*.h \ src/qt/test/*.cpp \ src/qt/test/*.h \ src/rpc/*.cpp \ src/rpc/*.h \ src/script/*.cpp \ src/script/*.h \ src/support/*.cpp \ src/support/*.h \ src/support/allocators/*.h \ src/test/*.cpp \ src/test/*.h \ src/wallet/*.cpp \ src/wallet/*.h \ src/wallet/test/*.cpp \ src/wallet/test/*.h \ src/zmq/*.cpp \ src/zmq/*.h do base=${f%/*}/ relbase=${base#src/} sed -i "s:#include \"\(.*\)\"\(.*\):if test -e \$base'\\1'; then echo \"#include <\"\$relbase\"\\1>\\2\"; else echo \"#include <\\1>\\2\"; fi:e" $f done -END VERIFY SCRIPT- Signed-off-by: Pasta <pasta@dashboost.org> * scripted-diff: Replace #include "" with #include <> (Dash Specific) -BEGIN VERIFY SCRIPT- for f in \ src/bls/*.cpp \ src/bls/*.h \ src/evo/*.cpp \ src/evo/*.h \ src/governance/*.cpp \ src/governance/*.h \ src/llmq/*.cpp \ src/llmq/*.h \ src/masternode/*.cpp \ src/masternode/*.h \ src/privatesend/*.cpp \ src/privatesend/*.h do base=${f%/*}/ relbase=${base#src/} sed -i "s:#include \"\(.*\)\"\(.*\):if test -e \$base'\\1'; then echo \"#include <\"\$relbase\"\\1>\\2\"; else echo \"#include <\\1>\\2\"; fi:e" $f done -END VERIFY SCRIPT- Signed-off-by: Pasta <pasta@dashboost.org> * build: Remove -I for everything but project root Remove -I from build system for everything but the project root, and built-in dependencies. Signed-off-by: Pasta <pasta@dashboost.org> # Conflicts: # src/Makefile.test.include * qt: refactor: Use absolute include paths in .ui files * qt: refactor: Changes to make include paths absolute This makes all include paths in the GUI absolute. Many changes are involved as every single source file in src/qt/ assumes to be able to use relative includes. Signed-off-by: Pasta <pasta@dashboost.org> # Conflicts: # src/qt/dash.cpp # src/qt/optionsmodel.cpp # src/qt/test/rpcnestedtests.cpp * test: refactor: Use absolute include paths for test data files * Recommend #include<> syntax in developer notes * refactor: Include obj/build.h instead of build.h * END BACKPORT #11651 Remove trailing whitespace causing travis failure * fix backport 11651 Signed-off-by: Pasta <pasta@dashboost.org> * More of 11651 * fix blockchain.cpp Signed-off-by: pasta <pasta@dashboost.org> * Add missing "qt/" in includes * Add missing "test/" in includes * Fix trailing whitespaces Co-authored-by: Wladimir J. van der Laan <laanwj@gmail.com> Co-authored-by: Russell Yanofsky <russ@yanofsky.org> Co-authored-by: MeshCollider <dobsonsa68@gmail.com> Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com>
2020-03-19 23:46:56 +01:00
#include <consensus/validation.h>
#include <core_io.h>
#include <evo/deterministicmns.h>
#include <masternode/meta.h>
#include <masternode/sync.h>
#include <net_processing.h>
#include <netmessagemaker.h>
Backport 11651 (#3358) * scripted-diff: Replace #include "" with #include <> (ryanofsky) -BEGIN VERIFY SCRIPT- for f in \ src/*.cpp \ src/*.h \ src/bench/*.cpp \ src/bench/*.h \ src/compat/*.cpp \ src/compat/*.h \ src/consensus/*.cpp \ src/consensus/*.h \ src/crypto/*.cpp \ src/crypto/*.h \ src/crypto/ctaes/*.h \ src/policy/*.cpp \ src/policy/*.h \ src/primitives/*.cpp \ src/primitives/*.h \ src/qt/*.cpp \ src/qt/*.h \ src/qt/test/*.cpp \ src/qt/test/*.h \ src/rpc/*.cpp \ src/rpc/*.h \ src/script/*.cpp \ src/script/*.h \ src/support/*.cpp \ src/support/*.h \ src/support/allocators/*.h \ src/test/*.cpp \ src/test/*.h \ src/wallet/*.cpp \ src/wallet/*.h \ src/wallet/test/*.cpp \ src/wallet/test/*.h \ src/zmq/*.cpp \ src/zmq/*.h do base=${f%/*}/ relbase=${base#src/} sed -i "s:#include \"\(.*\)\"\(.*\):if test -e \$base'\\1'; then echo \"#include <\"\$relbase\"\\1>\\2\"; else echo \"#include <\\1>\\2\"; fi:e" $f done -END VERIFY SCRIPT- Signed-off-by: Pasta <pasta@dashboost.org> * scripted-diff: Replace #include "" with #include <> (Dash Specific) -BEGIN VERIFY SCRIPT- for f in \ src/bls/*.cpp \ src/bls/*.h \ src/evo/*.cpp \ src/evo/*.h \ src/governance/*.cpp \ src/governance/*.h \ src/llmq/*.cpp \ src/llmq/*.h \ src/masternode/*.cpp \ src/masternode/*.h \ src/privatesend/*.cpp \ src/privatesend/*.h do base=${f%/*}/ relbase=${base#src/} sed -i "s:#include \"\(.*\)\"\(.*\):if test -e \$base'\\1'; then echo \"#include <\"\$relbase\"\\1>\\2\"; else echo \"#include <\\1>\\2\"; fi:e" $f done -END VERIFY SCRIPT- Signed-off-by: Pasta <pasta@dashboost.org> * build: Remove -I for everything but project root Remove -I from build system for everything but the project root, and built-in dependencies. Signed-off-by: Pasta <pasta@dashboost.org> # Conflicts: # src/Makefile.test.include * qt: refactor: Use absolute include paths in .ui files * qt: refactor: Changes to make include paths absolute This makes all include paths in the GUI absolute. Many changes are involved as every single source file in src/qt/ assumes to be able to use relative includes. Signed-off-by: Pasta <pasta@dashboost.org> # Conflicts: # src/qt/dash.cpp # src/qt/optionsmodel.cpp # src/qt/test/rpcnestedtests.cpp * test: refactor: Use absolute include paths for test data files * Recommend #include<> syntax in developer notes * refactor: Include obj/build.h instead of build.h * END BACKPORT #11651 Remove trailing whitespace causing travis failure * fix backport 11651 Signed-off-by: Pasta <pasta@dashboost.org> * More of 11651 * fix blockchain.cpp Signed-off-by: pasta <pasta@dashboost.org> * Add missing "qt/" in includes * Add missing "test/" in includes * Fix trailing whitespaces Co-authored-by: Wladimir J. van der Laan <laanwj@gmail.com> Co-authored-by: Russell Yanofsky <russ@yanofsky.org> Co-authored-by: MeshCollider <dobsonsa68@gmail.com> Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com>
2020-03-19 23:46:56 +01:00
#include <script/sign.h>
#include <shutdown.h>
merge bitcoin#14555: Move util files to directory (script modified to account for Dash backports, doesn't account for rebasing) ------------- BEGIN SCRIPT --------------- mkdir -p src/util git mv src/util.h src/util/system.h git mv src/util.cpp src/util/system.cpp git mv src/utilmemory.h src/util/memory.h git mv src/utilmoneystr.h src/util/moneystr.h git mv src/utilmoneystr.cpp src/util/moneystr.cpp git mv src/utilstrencodings.h src/util/strencodings.h git mv src/utilstrencodings.cpp src/util/strencodings.cpp git mv src/utiltime.h src/util/time.h git mv src/utiltime.cpp src/util/time.cpp git mv src/utilasmap.h src/util/asmap.h git mv src/utilasmap.cpp src/util/asmap.cpp git mv src/utilstring.h src/util/string.h git mv src/utilstring.cpp src/util/string.cpp gsed -i 's/<util\.h>/<util\/system\.h>/g' $(git ls-files 'src/*.h' 'src/*.cpp') gsed -i 's/<utilmemory\.h>/<util\/memory\.h>/g' $(git ls-files 'src/*.h' 'src/*.cpp') gsed -i 's/<utilmoneystr\.h>/<util\/moneystr\.h>/g' $(git ls-files 'src/*.h' 'src/*.cpp') gsed -i 's/<utilstrencodings\.h>/<util\/strencodings\.h>/g' $(git ls-files 'src/*.h' 'src/*.cpp') gsed -i 's/<utiltime\.h>/<util\/time\.h>/g' $(git ls-files 'src/*.h' 'src/*.cpp') gsed -i 's/<utilasmap\.h>/<util\/asmap\.h>/g' $(git ls-files 'src/*.h' 'src/*.cpp') gsed -i 's/<utilstring\.h>/<util\/string\.h>/g' $(git ls-files 'src/*.h' 'src/*.cpp') gsed -i 's/BITCOIN_UTIL_H/BITCOIN_UTIL_SYSTEM_H/g' src/util/system.h gsed -i 's/BITCOIN_UTILMEMORY_H/BITCOIN_UTIL_MEMORY_H/g' src/util/memory.h gsed -i 's/BITCOIN_UTILMONEYSTR_H/BITCOIN_UTIL_MONEYSTR_H/g' src/util/moneystr.h gsed -i 's/BITCOIN_UTILSTRENCODINGS_H/BITCOIN_UTIL_STRENCODINGS_H/g' src/util/strencodings.h gsed -i 's/BITCOIN_UTILTIME_H/BITCOIN_UTIL_TIME_H/g' src/util/time.h gsed -i 's/BITCOIN_UTILASMAP_H/BITCOIN_UTIL_ASMAP_H/g' src/util/asmap.h gsed -i 's/BITCOIN_UTILSTRING_H/BITCOIN_UTIL_STRING_H/g' src/util/string.h gsed -i 's/ util\.\(h\|cpp\)/ util\/system\.\1/g' src/Makefile.am gsed -i 's/utilmemory\.\(h\|cpp\)/util\/memory\.\1/g' src/Makefile.am gsed -i 's/utilmoneystr\.\(h\|cpp\)/util\/moneystr\.\1/g' src/Makefile.am gsed -i 's/utilstrencodings\.\(h\|cpp\)/util\/strencodings\.\1/g' src/Makefile.am gsed -i 's/utiltime\.\(h\|cpp\)/util\/time\.\1/g' src/Makefile.am gsed -i 's/utilasmap\.\(h\|cpp\)/util\/asmap\.\1/g' src/Makefile.am gsed -i 's/utilstring\.\(h\|cpp\)/util\/string\.\1/g' src/Makefile.am gsed -i 's/-> util ->/-> util\/system ->/' test/lint/lint-circular-dependencies.sh gsed -i 's/src\/util\.cpp/src\/util\/system\.cpp/g' test/lint/lint-format-strings.py test/lint/lint-locale-dependence.sh gsed -i 's/src\/utilmoneystr\.cpp/src\/util\/moneystr\.cpp/g' test/lint/lint-locale-dependence.sh gsed -i 's/src\/utilstrencodings\.\(h\|cpp\)/src\/util\/strencodings\.\1/g' test/lint/lint-locale-dependence.sh ------------- END SCRIPT ---------------
2021-06-27 08:33:13 +02:00
#include <util/moneystr.h>
#include <util/ranges.h>
#include <util/system.h>
#include <util/translation.h>
Backport 11651 (#3358) * scripted-diff: Replace #include "" with #include <> (ryanofsky) -BEGIN VERIFY SCRIPT- for f in \ src/*.cpp \ src/*.h \ src/bench/*.cpp \ src/bench/*.h \ src/compat/*.cpp \ src/compat/*.h \ src/consensus/*.cpp \ src/consensus/*.h \ src/crypto/*.cpp \ src/crypto/*.h \ src/crypto/ctaes/*.h \ src/policy/*.cpp \ src/policy/*.h \ src/primitives/*.cpp \ src/primitives/*.h \ src/qt/*.cpp \ src/qt/*.h \ src/qt/test/*.cpp \ src/qt/test/*.h \ src/rpc/*.cpp \ src/rpc/*.h \ src/script/*.cpp \ src/script/*.h \ src/support/*.cpp \ src/support/*.h \ src/support/allocators/*.h \ src/test/*.cpp \ src/test/*.h \ src/wallet/*.cpp \ src/wallet/*.h \ src/wallet/test/*.cpp \ src/wallet/test/*.h \ src/zmq/*.cpp \ src/zmq/*.h do base=${f%/*}/ relbase=${base#src/} sed -i "s:#include \"\(.*\)\"\(.*\):if test -e \$base'\\1'; then echo \"#include <\"\$relbase\"\\1>\\2\"; else echo \"#include <\\1>\\2\"; fi:e" $f done -END VERIFY SCRIPT- Signed-off-by: Pasta <pasta@dashboost.org> * scripted-diff: Replace #include "" with #include <> (Dash Specific) -BEGIN VERIFY SCRIPT- for f in \ src/bls/*.cpp \ src/bls/*.h \ src/evo/*.cpp \ src/evo/*.h \ src/governance/*.cpp \ src/governance/*.h \ src/llmq/*.cpp \ src/llmq/*.h \ src/masternode/*.cpp \ src/masternode/*.h \ src/privatesend/*.cpp \ src/privatesend/*.h do base=${f%/*}/ relbase=${base#src/} sed -i "s:#include \"\(.*\)\"\(.*\):if test -e \$base'\\1'; then echo \"#include <\"\$relbase\"\\1>\\2\"; else echo \"#include <\\1>\\2\"; fi:e" $f done -END VERIFY SCRIPT- Signed-off-by: Pasta <pasta@dashboost.org> * build: Remove -I for everything but project root Remove -I from build system for everything but the project root, and built-in dependencies. Signed-off-by: Pasta <pasta@dashboost.org> # Conflicts: # src/Makefile.test.include * qt: refactor: Use absolute include paths in .ui files * qt: refactor: Changes to make include paths absolute This makes all include paths in the GUI absolute. Many changes are involved as every single source file in src/qt/ assumes to be able to use relative includes. Signed-off-by: Pasta <pasta@dashboost.org> # Conflicts: # src/qt/dash.cpp # src/qt/optionsmodel.cpp # src/qt/test/rpcnestedtests.cpp * test: refactor: Use absolute include paths for test data files * Recommend #include<> syntax in developer notes * refactor: Include obj/build.h instead of build.h * END BACKPORT #11651 Remove trailing whitespace causing travis failure * fix backport 11651 Signed-off-by: Pasta <pasta@dashboost.org> * More of 11651 * fix blockchain.cpp Signed-off-by: pasta <pasta@dashboost.org> * Add missing "qt/" in includes * Add missing "test/" in includes * Fix trailing whitespaces Co-authored-by: Wladimir J. van der Laan <laanwj@gmail.com> Co-authored-by: Russell Yanofsky <russ@yanofsky.org> Co-authored-by: MeshCollider <dobsonsa68@gmail.com> Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com>
2020-03-19 23:46:56 +01:00
#include <validation.h>
#include <version.h>
Backport 11651 (#3358) * scripted-diff: Replace #include "" with #include <> (ryanofsky) -BEGIN VERIFY SCRIPT- for f in \ src/*.cpp \ src/*.h \ src/bench/*.cpp \ src/bench/*.h \ src/compat/*.cpp \ src/compat/*.h \ src/consensus/*.cpp \ src/consensus/*.h \ src/crypto/*.cpp \ src/crypto/*.h \ src/crypto/ctaes/*.h \ src/policy/*.cpp \ src/policy/*.h \ src/primitives/*.cpp \ src/primitives/*.h \ src/qt/*.cpp \ src/qt/*.h \ src/qt/test/*.cpp \ src/qt/test/*.h \ src/rpc/*.cpp \ src/rpc/*.h \ src/script/*.cpp \ src/script/*.h \ src/support/*.cpp \ src/support/*.h \ src/support/allocators/*.h \ src/test/*.cpp \ src/test/*.h \ src/wallet/*.cpp \ src/wallet/*.h \ src/wallet/test/*.cpp \ src/wallet/test/*.h \ src/zmq/*.cpp \ src/zmq/*.h do base=${f%/*}/ relbase=${base#src/} sed -i "s:#include \"\(.*\)\"\(.*\):if test -e \$base'\\1'; then echo \"#include <\"\$relbase\"\\1>\\2\"; else echo \"#include <\\1>\\2\"; fi:e" $f done -END VERIFY SCRIPT- Signed-off-by: Pasta <pasta@dashboost.org> * scripted-diff: Replace #include "" with #include <> (Dash Specific) -BEGIN VERIFY SCRIPT- for f in \ src/bls/*.cpp \ src/bls/*.h \ src/evo/*.cpp \ src/evo/*.h \ src/governance/*.cpp \ src/governance/*.h \ src/llmq/*.cpp \ src/llmq/*.h \ src/masternode/*.cpp \ src/masternode/*.h \ src/privatesend/*.cpp \ src/privatesend/*.h do base=${f%/*}/ relbase=${base#src/} sed -i "s:#include \"\(.*\)\"\(.*\):if test -e \$base'\\1'; then echo \"#include <\"\$relbase\"\\1>\\2\"; else echo \"#include <\\1>\\2\"; fi:e" $f done -END VERIFY SCRIPT- Signed-off-by: Pasta <pasta@dashboost.org> * build: Remove -I for everything but project root Remove -I from build system for everything but the project root, and built-in dependencies. Signed-off-by: Pasta <pasta@dashboost.org> # Conflicts: # src/Makefile.test.include * qt: refactor: Use absolute include paths in .ui files * qt: refactor: Changes to make include paths absolute This makes all include paths in the GUI absolute. Many changes are involved as every single source file in src/qt/ assumes to be able to use relative includes. Signed-off-by: Pasta <pasta@dashboost.org> # Conflicts: # src/qt/dash.cpp # src/qt/optionsmodel.cpp # src/qt/test/rpcnestedtests.cpp * test: refactor: Use absolute include paths for test data files * Recommend #include<> syntax in developer notes * refactor: Include obj/build.h instead of build.h * END BACKPORT #11651 Remove trailing whitespace causing travis failure * fix backport 11651 Signed-off-by: Pasta <pasta@dashboost.org> * More of 11651 * fix blockchain.cpp Signed-off-by: pasta <pasta@dashboost.org> * Add missing "qt/" in includes * Add missing "test/" in includes * Fix trailing whitespaces Co-authored-by: Wladimir J. van der Laan <laanwj@gmail.com> Co-authored-by: Russell Yanofsky <russ@yanofsky.org> Co-authored-by: MeshCollider <dobsonsa68@gmail.com> Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com>
2020-03-19 23:46:56 +01:00
#include <wallet/coincontrol.h>
#include <wallet/fees.h>
2017-07-03 15:14:07 +02:00
#include <memory>
#include <univalue.h>
std::map<const std::string, std::shared_ptr<CCoinJoinClientManager>> coinJoinClientManagers;
CCoinJoinClientQueueManager coinJoinClientQueueManager;
scripted-diff: Merge #18533 Replace strCommand with msg_type (#4761) -BEGIN VERIFY SCRIPT- sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/client.cpp sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/client.h sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/server.cpp sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/server.h sed -i 's/\<strCommand\>/msg_type/g' src/evo/mnauth.cpp sed -i 's/\<strCommand\>/msg_type/g' src/evo/mnauth.h sed -i 's/\<strCommand\>/msg_type/g' src/governance/governance.cpp sed -i 's/\<strCommand\>/msg_type/g' src/governance/governance.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/blockprocessor.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/blockprocessor.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/chainlocks.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/chainlocks.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionhandler.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionhandler.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionmgr.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionmgr.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/instantsend.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/instantsend.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/quorums.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/quorums.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing_shares.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing_shares.h sed -i 's/\<strCommand\>/msg_type/g' src/masternode/sync.cpp sed -i 's/\<strCommand\>/msg_type/g' src/masternode/sync.h sed -i 's/\<strCommand\>/msg_type/g' src/net_processing.cpp sed -i 's/\<strCommand\>/msg_type/g' src/spork.cpp sed -i 's/\<strCommand\>/msg_type/g' src/spork.h -END VERIFY SCRIPT-
2022-04-18 18:47:26 +02:00
void CCoinJoinClientQueueManager::ProcessMessage(CNode* pfrom, const std::string& msg_type, CDataStream& vRecv, CConnman& connman, bool enable_bip61)
{
2018-11-05 10:29:07 +01:00
if (fMasternodeMode) return;
if (!CCoinJoinClientOptions::IsEnabled()) return;
2018-11-05 10:29:07 +01:00
if (!masternodeSync.IsBlockchainSynced()) return;
if (!CheckDiskSpace(GetDataDir())) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientQueueManager::ProcessMessage -- Not enough disk space, disabling CoinJoin.\n");
return;
}
scripted-diff: Merge #18533 Replace strCommand with msg_type (#4761) -BEGIN VERIFY SCRIPT- sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/client.cpp sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/client.h sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/server.cpp sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/server.h sed -i 's/\<strCommand\>/msg_type/g' src/evo/mnauth.cpp sed -i 's/\<strCommand\>/msg_type/g' src/evo/mnauth.h sed -i 's/\<strCommand\>/msg_type/g' src/governance/governance.cpp sed -i 's/\<strCommand\>/msg_type/g' src/governance/governance.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/blockprocessor.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/blockprocessor.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/chainlocks.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/chainlocks.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionhandler.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionhandler.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionmgr.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionmgr.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/instantsend.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/instantsend.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/quorums.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/quorums.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing_shares.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing_shares.h sed -i 's/\<strCommand\>/msg_type/g' src/masternode/sync.cpp sed -i 's/\<strCommand\>/msg_type/g' src/masternode/sync.h sed -i 's/\<strCommand\>/msg_type/g' src/net_processing.cpp sed -i 's/\<strCommand\>/msg_type/g' src/spork.cpp sed -i 's/\<strCommand\>/msg_type/g' src/spork.h -END VERIFY SCRIPT-
2022-04-18 18:47:26 +02:00
if (msg_type == NetMsgType::DSQUEUE) {
CCoinJoinQueue dsq;
vRecv >> dsq;
{
TRY_LOCK(cs_vecqueue, lockRecv);
2018-11-05 10:29:07 +01:00
if (!lockRecv) return;
// process every dsq only once
for (const auto& q : vecCoinJoinQueue) {
2018-11-05 10:29:07 +01:00
if (q == dsq) {
return;
}
if (q.fReady == dsq.fReady && q.masternodeOutpoint == dsq.masternodeOutpoint) {
// no way the same mn can send another dsq with the same readiness this soon
LogPrint(BCLog::COINJOIN, "DSQUEUE -- Peer %s is sending WAY too many dsq messages for a masternode with collateral %s\n", pfrom->GetLogString(), dsq.masternodeOutpoint.ToStringShort());
return;
}
}
} // cs_vecqueue
LogPrint(BCLog::COINJOIN, "DSQUEUE -- %s new\n", dsq.ToString());
if (dsq.IsTimeOutOfBounds()) return;
auto mnList = deterministicMNManager->GetListAtChainTip();
auto dmn = mnList.GetValidMNByCollateral(dsq.masternodeOutpoint);
if (!dmn) return;
if (!dsq.CheckSignature(dmn->pdmnState->pubKeyOperator.Get())) {
LOCK(cs_main);
Misbehaving(pfrom->GetId(), 10);
return;
}
// if the queue is ready, submit if we can
if (dsq.fReady && ranges::any_of(coinJoinClientManagers,
[&dmn, &connman](const auto& pair){ return pair.second->TrySubmitDenominate(dmn->pdmnState->addr, connman); })) {
LogPrint(BCLog::COINJOIN, "DSQUEUE -- CoinJoin queue (%s) is ready on masternode %s\n", dsq.ToString(), dmn->pdmnState->addr.ToString());
return;
} else {
int64_t nLastDsq = mmetaman.GetMetaInfo(dmn->proTxHash)->GetLastDsq();
int64_t nDsqThreshold = mmetaman.GetDsqThreshold(dmn->proTxHash, mnList.GetValidMNsCount());
LogPrint(BCLog::COINJOIN, "DSQUEUE -- nLastDsq: %d nDsqThreshold: %d nDsqCount: %d\n", nLastDsq, nDsqThreshold, mmetaman.GetDsqCount());
// don't allow a few nodes to dominate the queuing process
if (nLastDsq != 0 && nDsqThreshold > mmetaman.GetDsqCount()) {
LogPrint(BCLog::COINJOIN, "DSQUEUE -- Masternode %s is sending too many dsq messages\n", dmn->proTxHash.ToString());
return;
}
mmetaman.AllowMixing(dmn->proTxHash);
LogPrint(BCLog::COINJOIN, "DSQUEUE -- new CoinJoin queue (%s) from masternode %s\n", dsq.ToString(), dmn->pdmnState->addr.ToString());
ranges::any_of(coinJoinClientManagers,
[&dsq](const auto& pair){ return pair.second->MarkAlreadyJoinedQueueAsTried(dsq); });
{
TRY_LOCK(cs_vecqueue, lockRecv);
if (!lockRecv) return;
vecCoinJoinQueue.push_back(dsq);
}
Eliminate remaining uses of g_connman in Dash-specific code. (#1635) This monstrous change eliminates all remaining uses of g_connman global variable in Dash-specific code. Unlike previous changes eliminating g_connman use that were isolated to particular modules, this one covers multiple modules simultaneously because they are so interdependent that change in one module was quickly spreading to others. This is mostly invariant change that was done by * changing all functions using g_connman to use connman argument, * changing all functions calling these functions to use connman argument, * repeating previous step until there's nothing to change. After multiple iterations, this process converged to final result, producing code that is mostly equivalent to original one, but passing CConnman instance through arguments instead of global variable. The only exception to equivalence of resulting code is that I had to create overload of CMasternodeMan::CheckAndRemove() method without arguments that does nothing just for use in CFlatDB<CMasternodeMan>::Dump() and CFlatDB<CMasternodeMan>::Load() methods. Normal CMasternodeMan::CheckAndRemove() overload now has argument of CConnman& type and is used everywhere else. The normal overload has this code in the beginning: if(!masternodeSync.IsMasternodeListSynced()) return; Masternode list is not synced yet when we load "mncache.dat" file, and we save "mncache.dat" file on shutdown, so I presume that it's OK to use overload that does nothing in both cases. Signed-off-by: Oleg Girko <ol@infoserver.lv>
2017-09-19 16:51:38 +02:00
dsq.Relay(connman);
}
}
}
scripted-diff: Merge #18533 Replace strCommand with msg_type (#4761) -BEGIN VERIFY SCRIPT- sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/client.cpp sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/client.h sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/server.cpp sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/server.h sed -i 's/\<strCommand\>/msg_type/g' src/evo/mnauth.cpp sed -i 's/\<strCommand\>/msg_type/g' src/evo/mnauth.h sed -i 's/\<strCommand\>/msg_type/g' src/governance/governance.cpp sed -i 's/\<strCommand\>/msg_type/g' src/governance/governance.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/blockprocessor.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/blockprocessor.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/chainlocks.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/chainlocks.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionhandler.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionhandler.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionmgr.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionmgr.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/instantsend.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/instantsend.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/quorums.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/quorums.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing_shares.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing_shares.h sed -i 's/\<strCommand\>/msg_type/g' src/masternode/sync.cpp sed -i 's/\<strCommand\>/msg_type/g' src/masternode/sync.h sed -i 's/\<strCommand\>/msg_type/g' src/net_processing.cpp sed -i 's/\<strCommand\>/msg_type/g' src/spork.cpp sed -i 's/\<strCommand\>/msg_type/g' src/spork.h -END VERIFY SCRIPT-
2022-04-18 18:47:26 +02:00
void CCoinJoinClientManager::ProcessMessage(CNode* pfrom, const std::string& msg_type, CDataStream& vRecv, CConnman& connman, bool enable_bip61)
{
if (fMasternodeMode) return;
if (!CCoinJoinClientOptions::IsEnabled()) return;
if (!masternodeSync.IsBlockchainSynced()) return;
if (!CheckDiskSpace(GetDataDir())) {
ResetPool();
StopMixing();
LogPrint(BCLog::COINJOIN, "CCoinJoinClientManager::ProcessMessage -- Not enough disk space, disabling CoinJoin.\n");
return;
}
scripted-diff: Merge #18533 Replace strCommand with msg_type (#4761) -BEGIN VERIFY SCRIPT- sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/client.cpp sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/client.h sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/server.cpp sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/server.h sed -i 's/\<strCommand\>/msg_type/g' src/evo/mnauth.cpp sed -i 's/\<strCommand\>/msg_type/g' src/evo/mnauth.h sed -i 's/\<strCommand\>/msg_type/g' src/governance/governance.cpp sed -i 's/\<strCommand\>/msg_type/g' src/governance/governance.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/blockprocessor.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/blockprocessor.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/chainlocks.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/chainlocks.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionhandler.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionhandler.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionmgr.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionmgr.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/instantsend.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/instantsend.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/quorums.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/quorums.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing_shares.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing_shares.h sed -i 's/\<strCommand\>/msg_type/g' src/masternode/sync.cpp sed -i 's/\<strCommand\>/msg_type/g' src/masternode/sync.h sed -i 's/\<strCommand\>/msg_type/g' src/net_processing.cpp sed -i 's/\<strCommand\>/msg_type/g' src/spork.cpp sed -i 's/\<strCommand\>/msg_type/g' src/spork.h -END VERIFY SCRIPT-
2022-04-18 18:47:26 +02:00
if (msg_type == NetMsgType::DSSTATUSUPDATE ||
msg_type == NetMsgType::DSFINALTX ||
msg_type == NetMsgType::DSCOMPLETE) {
AssertLockNotHeld(cs_deqsessions);
LOCK(cs_deqsessions);
for (auto& session : deqSessions) {
scripted-diff: Merge #18533 Replace strCommand with msg_type (#4761) -BEGIN VERIFY SCRIPT- sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/client.cpp sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/client.h sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/server.cpp sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/server.h sed -i 's/\<strCommand\>/msg_type/g' src/evo/mnauth.cpp sed -i 's/\<strCommand\>/msg_type/g' src/evo/mnauth.h sed -i 's/\<strCommand\>/msg_type/g' src/governance/governance.cpp sed -i 's/\<strCommand\>/msg_type/g' src/governance/governance.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/blockprocessor.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/blockprocessor.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/chainlocks.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/chainlocks.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionhandler.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionhandler.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionmgr.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionmgr.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/instantsend.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/instantsend.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/quorums.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/quorums.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing_shares.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing_shares.h sed -i 's/\<strCommand\>/msg_type/g' src/masternode/sync.cpp sed -i 's/\<strCommand\>/msg_type/g' src/masternode/sync.h sed -i 's/\<strCommand\>/msg_type/g' src/net_processing.cpp sed -i 's/\<strCommand\>/msg_type/g' src/spork.cpp sed -i 's/\<strCommand\>/msg_type/g' src/spork.h -END VERIFY SCRIPT-
2022-04-18 18:47:26 +02:00
session.ProcessMessage(pfrom, msg_type, vRecv, connman, enable_bip61);
}
}
}
scripted-diff: Merge #18533 Replace strCommand with msg_type (#4761) -BEGIN VERIFY SCRIPT- sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/client.cpp sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/client.h sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/server.cpp sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/server.h sed -i 's/\<strCommand\>/msg_type/g' src/evo/mnauth.cpp sed -i 's/\<strCommand\>/msg_type/g' src/evo/mnauth.h sed -i 's/\<strCommand\>/msg_type/g' src/governance/governance.cpp sed -i 's/\<strCommand\>/msg_type/g' src/governance/governance.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/blockprocessor.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/blockprocessor.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/chainlocks.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/chainlocks.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionhandler.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionhandler.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionmgr.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionmgr.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/instantsend.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/instantsend.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/quorums.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/quorums.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing_shares.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing_shares.h sed -i 's/\<strCommand\>/msg_type/g' src/masternode/sync.cpp sed -i 's/\<strCommand\>/msg_type/g' src/masternode/sync.h sed -i 's/\<strCommand\>/msg_type/g' src/net_processing.cpp sed -i 's/\<strCommand\>/msg_type/g' src/spork.cpp sed -i 's/\<strCommand\>/msg_type/g' src/spork.h -END VERIFY SCRIPT-
2022-04-18 18:47:26 +02:00
void CCoinJoinClientSession::ProcessMessage(CNode* pfrom, const std::string& msg_type, CDataStream& vRecv, CConnman& connman, bool enable_bip61)
{
2018-11-05 10:29:07 +01:00
if (fMasternodeMode) return;
if (!CCoinJoinClientOptions::IsEnabled()) return;
2018-11-05 10:29:07 +01:00
if (!masternodeSync.IsBlockchainSynced()) return;
scripted-diff: Merge #18533 Replace strCommand with msg_type (#4761) -BEGIN VERIFY SCRIPT- sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/client.cpp sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/client.h sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/server.cpp sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/server.h sed -i 's/\<strCommand\>/msg_type/g' src/evo/mnauth.cpp sed -i 's/\<strCommand\>/msg_type/g' src/evo/mnauth.h sed -i 's/\<strCommand\>/msg_type/g' src/governance/governance.cpp sed -i 's/\<strCommand\>/msg_type/g' src/governance/governance.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/blockprocessor.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/blockprocessor.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/chainlocks.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/chainlocks.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionhandler.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionhandler.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionmgr.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionmgr.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/instantsend.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/instantsend.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/quorums.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/quorums.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing_shares.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing_shares.h sed -i 's/\<strCommand\>/msg_type/g' src/masternode/sync.cpp sed -i 's/\<strCommand\>/msg_type/g' src/masternode/sync.h sed -i 's/\<strCommand\>/msg_type/g' src/net_processing.cpp sed -i 's/\<strCommand\>/msg_type/g' src/spork.cpp sed -i 's/\<strCommand\>/msg_type/g' src/spork.h -END VERIFY SCRIPT-
2022-04-18 18:47:26 +02:00
if (msg_type == NetMsgType::DSSTATUSUPDATE) {
if (!mixingMasternode) return;
if (mixingMasternode->pdmnState->addr != pfrom->addr) {
return;
}
CCoinJoinStatusUpdate psssup;
vRecv >> psssup;
ProcessPoolStateUpdate(psssup);
scripted-diff: Merge #18533 Replace strCommand with msg_type (#4761) -BEGIN VERIFY SCRIPT- sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/client.cpp sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/client.h sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/server.cpp sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/server.h sed -i 's/\<strCommand\>/msg_type/g' src/evo/mnauth.cpp sed -i 's/\<strCommand\>/msg_type/g' src/evo/mnauth.h sed -i 's/\<strCommand\>/msg_type/g' src/governance/governance.cpp sed -i 's/\<strCommand\>/msg_type/g' src/governance/governance.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/blockprocessor.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/blockprocessor.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/chainlocks.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/chainlocks.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionhandler.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionhandler.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionmgr.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionmgr.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/instantsend.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/instantsend.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/quorums.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/quorums.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing_shares.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing_shares.h sed -i 's/\<strCommand\>/msg_type/g' src/masternode/sync.cpp sed -i 's/\<strCommand\>/msg_type/g' src/masternode/sync.h sed -i 's/\<strCommand\>/msg_type/g' src/net_processing.cpp sed -i 's/\<strCommand\>/msg_type/g' src/spork.cpp sed -i 's/\<strCommand\>/msg_type/g' src/spork.h -END VERIFY SCRIPT-
2022-04-18 18:47:26 +02:00
} else if (msg_type == NetMsgType::DSFINALTX) {
if (!mixingMasternode) return;
if (mixingMasternode->pdmnState->addr != pfrom->addr) {
return;
}
int nMsgSessionID;
vRecv >> nMsgSessionID;
CTransaction txNew(deserialize, vRecv);
2018-11-05 10:29:07 +01:00
if (nSessionID != nMsgSessionID) {
LogPrint(BCLog::COINJOIN, "DSFINALTX -- message doesn't match current CoinJoin session: nSessionID: %d nMsgSessionID: %d\n", nSessionID, nMsgSessionID);
return;
}
LogPrint(BCLog::COINJOIN, "DSFINALTX -- txNew %s", txNew.ToString()); /* Continued */
// check to see if input is spent already? (and probably not confirmed)
Eliminate remaining uses of g_connman in Dash-specific code. (#1635) This monstrous change eliminates all remaining uses of g_connman global variable in Dash-specific code. Unlike previous changes eliminating g_connman use that were isolated to particular modules, this one covers multiple modules simultaneously because they are so interdependent that change in one module was quickly spreading to others. This is mostly invariant change that was done by * changing all functions using g_connman to use connman argument, * changing all functions calling these functions to use connman argument, * repeating previous step until there's nothing to change. After multiple iterations, this process converged to final result, producing code that is mostly equivalent to original one, but passing CConnman instance through arguments instead of global variable. The only exception to equivalence of resulting code is that I had to create overload of CMasternodeMan::CheckAndRemove() method without arguments that does nothing just for use in CFlatDB<CMasternodeMan>::Dump() and CFlatDB<CMasternodeMan>::Load() methods. Normal CMasternodeMan::CheckAndRemove() overload now has argument of CConnman& type and is used everywhere else. The normal overload has this code in the beginning: if(!masternodeSync.IsMasternodeListSynced()) return; Masternode list is not synced yet when we load "mncache.dat" file, and we save "mncache.dat" file on shutdown, so I presume that it's OK to use overload that does nothing in both cases. Signed-off-by: Oleg Girko <ol@infoserver.lv>
2017-09-19 16:51:38 +02:00
SignFinalTransaction(txNew, pfrom, connman);
scripted-diff: Merge #18533 Replace strCommand with msg_type (#4761) -BEGIN VERIFY SCRIPT- sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/client.cpp sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/client.h sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/server.cpp sed -i 's/\<strCommand\>/msg_type/g' src/coinjoin/server.h sed -i 's/\<strCommand\>/msg_type/g' src/evo/mnauth.cpp sed -i 's/\<strCommand\>/msg_type/g' src/evo/mnauth.h sed -i 's/\<strCommand\>/msg_type/g' src/governance/governance.cpp sed -i 's/\<strCommand\>/msg_type/g' src/governance/governance.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/blockprocessor.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/blockprocessor.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/chainlocks.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/chainlocks.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionhandler.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionhandler.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionmgr.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/dkgsessionmgr.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/instantsend.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/instantsend.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/quorums.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/quorums.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing.h sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing_shares.cpp sed -i 's/\<strCommand\>/msg_type/g' src/llmq/signing_shares.h sed -i 's/\<strCommand\>/msg_type/g' src/masternode/sync.cpp sed -i 's/\<strCommand\>/msg_type/g' src/masternode/sync.h sed -i 's/\<strCommand\>/msg_type/g' src/net_processing.cpp sed -i 's/\<strCommand\>/msg_type/g' src/spork.cpp sed -i 's/\<strCommand\>/msg_type/g' src/spork.h -END VERIFY SCRIPT-
2022-04-18 18:47:26 +02:00
} else if (msg_type == NetMsgType::DSCOMPLETE) {
if (!mixingMasternode) return;
if (mixingMasternode->pdmnState->addr != pfrom->addr) {
LogPrint(BCLog::COINJOIN, "DSCOMPLETE -- message doesn't match current Masternode: infoMixingMasternode=%s addr=%s\n", mixingMasternode->pdmnState->addr.ToString(), pfrom->addr.ToString());
return;
}
int nMsgSessionID;
PoolMessage nMsgMessageID;
vRecv >> nMsgSessionID >> nMsgMessageID;
2018-11-05 10:29:07 +01:00
if (nMsgMessageID < MSG_POOL_MIN || nMsgMessageID > MSG_POOL_MAX) {
LogPrint(BCLog::COINJOIN, "DSCOMPLETE -- nMsgMessageID is out of bounds: %d\n", nMsgMessageID);
return;
}
2018-11-05 10:29:07 +01:00
if (nSessionID != nMsgSessionID) {
LogPrint(BCLog::COINJOIN, "DSCOMPLETE -- message doesn't match current CoinJoin session: nSessionID: %d nMsgSessionID: %d\n", nSessionID, nMsgSessionID);
return;
}
2022-04-06 22:37:20 +02:00
LogPrint(BCLog::COINJOIN, "DSCOMPLETE -- nMsgSessionID %d nMsgMessageID %d (%s)\n", nMsgSessionID, nMsgMessageID, CCoinJoin::GetMessageByID(nMsgMessageID).translated);
CompletedTransaction(nMsgMessageID);
}
}
bool CCoinJoinClientManager::StartMixing() {
bool expected{false};
return fMixing.compare_exchange_strong(expected, true);
}
void CCoinJoinClientManager::StopMixing() {
fMixing = false;
}
bool CCoinJoinClientManager::IsMixing() const
{
return fMixing;
}
void CCoinJoinClientSession::ResetPool()
{
txMyCollateral = CMutableTransaction();
UnlockCoins();
keyHolderStorage.ReturnAll();
WITH_LOCK(cs_coinjoin, SetNull());
}
void CCoinJoinClientManager::ResetPool()
{
nCachedLastSuccessBlock = 0;
vecMasternodesUsed.clear();
AssertLockNotHeld(cs_deqsessions);
LOCK(cs_deqsessions);
for (auto& session : deqSessions) {
session.ResetPool();
}
deqSessions.clear();
}
void CCoinJoinClientSession::SetNull()
{
AssertLockHeld(cs_coinjoin);
// Client side
mixingMasternode = nullptr;
pendingDsaRequest = CPendingDsaRequest();
CCoinJoinBaseSession::SetNull();
}
//
// Unlock coins after mixing fails or succeeds
//
void CCoinJoinClientSession::UnlockCoins()
{
if (!CCoinJoinClientOptions::IsEnabled()) return;
2018-11-05 10:29:07 +01:00
while (true) {
TRY_LOCK(mixingWallet.cs_wallet, lockWallet);
2018-11-05 10:29:07 +01:00
if (!lockWallet) {
UninterruptibleSleep(std::chrono::milliseconds{50});
2018-11-05 10:29:07 +01:00
continue;
}
for (const auto& outpoint : vecOutPointLocked)
mixingWallet.UnlockCoin(outpoint);
break;
}
vecOutPointLocked.clear();
}
2022-04-06 22:37:20 +02:00
bilingual_str CCoinJoinClientSession::GetStatus(bool fWaitForBlock) const
{
static int nStatusMessageProgress = 0;
nStatusMessageProgress += 10;
std::string strSuffix;
if (fWaitForBlock || !masternodeSync.IsBlockchainSynced()) {
return strAutoDenomResult;
}
2018-11-05 10:29:07 +01:00
switch (nState) {
case POOL_STATE_IDLE:
2022-04-06 22:37:20 +02:00
return strprintf(_("%s is idle."), gCoinJoinName);
2018-11-05 10:29:07 +01:00
case POOL_STATE_QUEUE:
if (nStatusMessageProgress % 70 <= 30)
strSuffix = ".";
else if (nStatusMessageProgress % 70 <= 50)
strSuffix = "..";
else
2018-11-05 10:29:07 +01:00
strSuffix = "...";
2022-04-06 22:37:20 +02:00
return strprintf(_("Submitted to masternode, waiting in queue %s"), strSuffix);
2018-11-05 10:29:07 +01:00
case POOL_STATE_ACCEPTING_ENTRIES:
return strAutoDenomResult;
2018-11-05 10:29:07 +01:00
case POOL_STATE_SIGNING:
if (nStatusMessageProgress % 70 <= 40)
2022-04-06 22:37:20 +02:00
return _("Found enough users, signing ...");
2018-11-05 10:29:07 +01:00
else if (nStatusMessageProgress % 70 <= 50)
strSuffix = ".";
else if (nStatusMessageProgress % 70 <= 60)
strSuffix = "..";
else
2018-11-05 10:29:07 +01:00
strSuffix = "...";
2022-04-06 22:37:20 +02:00
return strprintf(_("Found enough users, signing ( waiting %s )"), strSuffix);
2018-11-05 10:29:07 +01:00
case POOL_STATE_ERROR:
2022-04-06 22:37:20 +02:00
return strprintf(_("%s request incomplete:"), gCoinJoinName) + strLastMessage + Untranslated(" ") + _("Will retry...");
2018-11-05 10:29:07 +01:00
default:
2022-04-06 22:37:20 +02:00
return strprintf(_("Unknown state: id = %u"), nState);
}
}
2022-04-06 22:37:20 +02:00
bilingual_str CCoinJoinClientManager::GetStatuses()
{
2022-04-06 22:37:20 +02:00
bilingual_str strStatus;
bool fWaitForBlock = WaitForAnotherBlock();
AssertLockNotHeld(cs_deqsessions);
LOCK(cs_deqsessions);
for (const auto& session : deqSessions) {
2022-04-06 22:37:20 +02:00
strStatus = strStatus + session.GetStatus(fWaitForBlock) + Untranslated("; ");
}
return strStatus;
}
std::string CCoinJoinClientManager::GetSessionDenoms()
{
std::string strSessionDenoms;
AssertLockNotHeld(cs_deqsessions);
LOCK(cs_deqsessions);
for (const auto& session : deqSessions) {
strSessionDenoms += CCoinJoin::DenominationToString(session.nSessionDenom);
strSessionDenoms += "; ";
}
return strSessionDenoms.empty() ? "N/A" : strSessionDenoms;
}
bool CCoinJoinClientSession::GetMixingMasternodeInfo(CDeterministicMNCPtr& ret) const
{
ret = mixingMasternode;
return ret != nullptr;
}
bool CCoinJoinClientManager::GetMixingMasternodesInfo(std::vector<CDeterministicMNCPtr>& vecDmnsRet) const
{
AssertLockNotHeld(cs_deqsessions);
LOCK(cs_deqsessions);
for (const auto& session : deqSessions) {
CDeterministicMNCPtr dmn;
if (session.GetMixingMasternodeInfo(dmn)) {
vecDmnsRet.push_back(dmn);
}
}
return !vecDmnsRet.empty();
}
//
// Check session timeouts
//
bool CCoinJoinClientSession::CheckTimeout()
{
2018-11-05 10:29:07 +01:00
if (fMasternodeMode) return false;
if (nState == POOL_STATE_IDLE) return false;
if (nState == POOL_STATE_ERROR) {
if (GetTime() - nTimeLastSuccessfulStep >= 10) {
// reset after being in POOL_STATE_ERROR for 10 or more seconds
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- resetting session %d\n", __func__, nSessionID);
WITH_LOCK(cs_coinjoin, SetNull());
}
return false;
}
int nLagTime = 10; // give the server a few extra seconds before resetting.
int nTimeout = (nState == POOL_STATE_SIGNING) ? COINJOIN_SIGNING_TIMEOUT : COINJOIN_QUEUE_TIMEOUT;
bool fTimeout = GetTime() - nTimeLastSuccessfulStep >= nTimeout + nLagTime;
if (!fTimeout) return false;
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- %s %d timed out (%ds)\n", __func__,
(nState == POOL_STATE_SIGNING) ? "Signing at session" : "Session", nSessionID, nTimeout);
SetState(POOL_STATE_ERROR);
UnlockCoins();
keyHolderStorage.ReturnAll();
nTimeLastSuccessfulStep = GetTime();
strLastMessage = CCoinJoin::GetMessageByID(ERR_SESSION);
return true;
}
//
// Check all queues and sessions for timeouts
//
void CCoinJoinClientManager::CheckTimeout()
{
AssertLockNotHeld(cs_deqsessions);
2018-11-05 10:29:07 +01:00
if (fMasternodeMode) return;
if (!CCoinJoinClientOptions::IsEnabled() || !IsMixing()) return;
LOCK(cs_deqsessions);
for (auto& session : deqSessions) {
if (session.CheckTimeout()) {
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Session timed out.");
}
}
}
//
// Execute a mixing denomination via a Masternode.
// This is only ran from clients
//
bool CCoinJoinClientSession::SendDenominate(const std::vector<std::pair<CTxDSIn, CTxOut> >& vecPSInOutPairsIn, CConnman& connman)
{
2018-11-05 10:29:07 +01:00
if (fMasternodeMode) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::SendDenominate -- CoinJoin from a Masternode is not supported currently.\n");
return false;
}
if (CTransaction(txMyCollateral).IsNull()) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClient:SendDenominate -- CoinJoin collateral not set\n");
return false;
}
// we should already be connected to a Masternode
2018-11-05 10:29:07 +01:00
if (!nSessionID) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::SendDenominate -- No Masternode has been selected yet.\n");
UnlockCoins();
keyHolderStorage.ReturnAll();
WITH_LOCK(cs_coinjoin, SetNull());
return false;
}
if (!CheckDiskSpace(GetDataDir())) {
UnlockCoins();
keyHolderStorage.ReturnAll();
WITH_LOCK(cs_coinjoin, SetNull());
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::SendDenominate -- Not enough disk space.\n");
return false;
}
SetState(POOL_STATE_ACCEPTING_ENTRIES);
2022-04-06 22:37:20 +02:00
strLastMessage = Untranslated("");
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::SendDenominate -- Added transaction to pool.\n");
CMutableTransaction tx; // for debug purposes only
std::vector<CTxDSIn> vecTxDSInTmp;
std::vector<CTxOut> vecTxOutTmp;
for (const auto& pair : vecPSInOutPairsIn) {
vecTxDSInTmp.emplace_back(pair.first);
vecTxOutTmp.emplace_back(pair.second);
tx.vin.emplace_back(pair.first);
tx.vout.emplace_back(pair.second);
}
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::SendDenominate -- Submitting partial tx %s", tx.ToString()); /* Continued */
// store our entry for later use
LOCK(cs_coinjoin);
vecEntries.emplace_back(vecTxDSInTmp, vecTxOutTmp, CTransaction(txMyCollateral));
RelayIn(vecEntries.back(), connman);
nTimeLastSuccessfulStep = GetTime();
return true;
}
// Process incoming messages from Masternode updating the progress of mixing
void CCoinJoinClientSession::ProcessPoolStateUpdate(CCoinJoinStatusUpdate psssup)
{
if (fMasternodeMode) return;
// do not update state when mixing client state is one of these
if (nState == POOL_STATE_IDLE || nState == POOL_STATE_ERROR) return;
if (psssup.nState < POOL_STATE_MIN || psssup.nState > POOL_STATE_MAX) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- psssup.nState is out of bounds: %d\n", __func__, psssup.nState);
return;
}
if (psssup.nMessageID < MSG_POOL_MIN || psssup.nMessageID > MSG_POOL_MAX) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- psssup.nMessageID is out of bounds: %d\n", __func__, psssup.nMessageID);
return;
}
2022-04-06 22:37:20 +02:00
bilingual_str strMessageTmp = CCoinJoin::GetMessageByID(psssup.nMessageID);
strAutoDenomResult = _("Masternode:") + Untranslated(" ") + strMessageTmp;
switch (psssup.nStatusUpdate) {
case STATUS_REJECTED: {
2022-04-06 22:37:20 +02:00
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- rejected by Masternode: %s\n", __func__, strMessageTmp.translated);
SetState(POOL_STATE_ERROR);
UnlockCoins();
keyHolderStorage.ReturnAll();
nTimeLastSuccessfulStep = GetTime();
strLastMessage = strMessageTmp;
break;
}
case STATUS_ACCEPTED: {
if (nState == psssup.nState && psssup.nState == POOL_STATE_QUEUE && nSessionID == 0 && psssup.nSessionID != 0) {
// new session id should be set only in POOL_STATE_QUEUE state
nSessionID = psssup.nSessionID;
nTimeLastSuccessfulStep = GetTime();
2022-04-06 22:37:20 +02:00
strMessageTmp = strMessageTmp + strprintf(Untranslated(" Set nSessionID to %d."), nSessionID);
}
2022-04-06 22:37:20 +02:00
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- accepted by Masternode: %s\n", __func__, strMessageTmp.translated);
break;
}
default: {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- psssup.nStatusUpdate is out of bounds: %d\n", __func__, psssup.nStatusUpdate);
break;
}
}
}
//
// After we receive the finalized transaction from the Masternode, we must
// check it to make sure it's what we want, then sign it if we agree.
// If we refuse to sign, it's possible we'll be charged collateral
//
bool CCoinJoinClientSession::SignFinalTransaction(const CTransaction& finalTransactionNew, CNode* pnode, CConnman& connman)
{
if (!CCoinJoinClientOptions::IsEnabled()) return false;
2018-11-05 10:29:07 +01:00
if (fMasternodeMode || pnode == nullptr) return false;
if (!mixingMasternode) return false;
LOCK(cs_main);
LOCK(mixingWallet.cs_wallet);
LOCK(cs_coinjoin);
finalMutableTransaction = CMutableTransaction{finalTransactionNew};
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- finalMutableTransaction=%s", __func__, finalMutableTransaction.ToString()); /* Continued */
// STEP 1: check final transaction general rules
// Make sure it's BIP69 compliant
sort(finalMutableTransaction.vin.begin(), finalMutableTransaction.vin.end(), CompareInputBIP69());
sort(finalMutableTransaction.vout.begin(), finalMutableTransaction.vout.end(), CompareOutputBIP69());
2018-11-05 10:29:07 +01:00
if (finalMutableTransaction.GetHash() != finalTransactionNew.GetHash()) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- ERROR! Masternode %s is not BIP69 compliant!\n", __func__, mixingMasternode->proTxHash.ToString());
UnlockCoins();
keyHolderStorage.ReturnAll();
SetNull();
return false;
}
// Make sure all inputs/outputs are valid
PoolMessage nMessageID{MSG_NOERR};
if (!IsValidInOuts(finalMutableTransaction.vin, finalMutableTransaction.vout, nMessageID, nullptr)) {
2022-04-06 22:37:20 +02:00
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- ERROR! IsValidInOuts() failed: %s\n", __func__, CCoinJoin::GetMessageByID(nMessageID).translated);
UnlockCoins();
keyHolderStorage.ReturnAll();
SetNull();
return false;
}
// STEP 2: make sure our own inputs/outputs are present, otherwise refuse to sign
std::vector<CTxIn> sigs;
for (const auto &entry: vecEntries) {
// Check that the final transaction has all our outputs
for (const auto &txout: entry.vecTxOut) {
bool fFound = ranges::any_of(finalMutableTransaction.vout, [&txout](const auto& txoutFinal){
return txoutFinal == txout;
});
if (!fFound) {
// Something went wrong and we'll refuse to sign. It's possible we'll be charged collateral. But that's
// better than signing if the transaction doesn't look like what we wanted.
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- an output is missing, refusing to sign! txout=%s\n", __func__, txout.ToString());
UnlockCoins();
keyHolderStorage.ReturnAll();
SetNull();
return false;
}
}
for (const auto& txdsin : entry.vecTxDSIn) {
/* Sign my transaction and all outputs */
int nMyInputIndex = -1;
CScript prevPubKey = CScript();
2018-11-05 10:29:07 +01:00
for (unsigned int i = 0; i < finalMutableTransaction.vin.size(); i++) {
if (finalMutableTransaction.vin[i] == txdsin) {
nMyInputIndex = i;
prevPubKey = txdsin.prevPubKey;
break;
}
}
if (nMyInputIndex == -1) {
// Can't find one of my own inputs, refuse to sign. It's possible we'll be charged collateral. But that's
// better than signing if the transaction doesn't look like what we wanted.
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- missing input! txdsin=%s\n", __func__, txdsin.ToString());
UnlockCoins();
keyHolderStorage.ReturnAll();
SetNull();
return false;
}
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- Signing my input %i\n", __func__, nMyInputIndex);
// TODO we're using amount=0 here but we should use the correct amount. This works because Dash ignores the amount while signing/verifying (only used in Bitcoin/Segwit)
if (!SignSignature(mixingWallet, prevPubKey, finalMutableTransaction, nMyInputIndex, 0, int(SIGHASH_ALL | SIGHASH_ANYONECANPAY))) { // changes scriptSig
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- Unable to sign my own transaction!\n", __func__);
// not sure what to do here, it will time out...?
}
sigs.push_back(finalMutableTransaction.vin[nMyInputIndex]);
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- nMyInputIndex: %d, sigs.size(): %d, scriptSig=%s\n",
__func__, nMyInputIndex, (int) sigs.size(),ScriptToAsmStr(finalMutableTransaction.vin[nMyInputIndex].scriptSig));
}
}
2018-11-05 10:29:07 +01:00
if (sigs.empty()) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- can't sign anything!\n", __func__);
UnlockCoins();
keyHolderStorage.ReturnAll();
SetNull();
return false;
}
// push all of our signatures to the Masternode
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- pushing sigs to the masternode, finalMutableTransaction=%s", __func__, finalMutableTransaction.ToString()); /* Continued */
CNetMsgMaker msgMaker(pnode->GetSendVersion());
connman.PushMessage(pnode, msgMaker.Make(NetMsgType::DSSIGNFINALTX, sigs));
SetState(POOL_STATE_SIGNING);
nTimeLastSuccessfulStep = GetTime();
return true;
}
// mixing transaction was completed (failed or successful)
void CCoinJoinClientSession::CompletedTransaction(PoolMessage nMessageID)
{
2018-11-05 10:29:07 +01:00
if (fMasternodeMode) return;
2018-11-05 10:29:07 +01:00
if (nMessageID == MSG_SUCCESS) {
LogPrint(BCLog::COINJOIN, "CompletedTransaction -- success\n");
coinJoinClientManagers.at(mixingWallet.GetName())->UpdatedSuccessBlock();
keyHolderStorage.KeepAll();
} else {
LogPrint(BCLog::COINJOIN, "CompletedTransaction -- error\n");
keyHolderStorage.ReturnAll();
}
UnlockCoins();
WITH_LOCK(cs_coinjoin, SetNull());
strLastMessage = CCoinJoin::GetMessageByID(nMessageID);
}
void CCoinJoinClientManager::UpdatedSuccessBlock()
{
2018-11-05 10:29:07 +01:00
if (fMasternodeMode) return;
nCachedLastSuccessBlock = nCachedBlockHeight;
}
bool CCoinJoinClientManager::WaitForAnotherBlock() const
{
if (!masternodeSync.IsBlockchainSynced()) return true;
if (CCoinJoinClientOptions::IsMultiSessionEnabled()) return false;
return nCachedBlockHeight - nCachedLastSuccessBlock < nMinBlocksToWait;
}
bool CCoinJoinClientManager::CheckAutomaticBackup()
{
if (!CCoinJoinClientOptions::IsEnabled() || !IsMixing()) return false;
2018-11-05 10:29:07 +01:00
switch (nWalletBackups) {
case 0:
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Automatic backups disabled") + Untranslated(", ") + _("no mixing available.");
LogPrint(BCLog::COINJOIN, "CCoinJoinClientManager::CheckAutomaticBackup -- %s\n", strAutoDenomResult.original);
StopMixing();
mixingWallet.nKeysLeftSinceAutoBackup = 0; // no backup, no "keys since last backup"
2018-11-05 10:29:07 +01:00
return false;
case -1:
// Automatic backup failed, nothing else we can do until user fixes the issue manually.
// There is no way to bring user attention in daemon mode, so we just update status and
2018-11-05 10:29:07 +01:00
// keep spamming if debug is on.
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("ERROR! Failed to create automatic backup") + Untranslated(", ") + _("see debug.log for details.");
LogPrint(BCLog::COINJOIN, "CCoinJoinClientManager::CheckAutomaticBackup -- %s\n", strAutoDenomResult.original);
2018-11-05 10:29:07 +01:00
return false;
case -2:
// We were able to create automatic backup but keypool was not replenished because wallet is locked.
// There is no way to bring user attention in daemon mode, so we just update status and
2018-11-05 10:29:07 +01:00
// keep spamming if debug is on.
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("WARNING! Failed to replenish keypool, please unlock your wallet to do so.") + Untranslated(", ") + _("see debug.log for details.");
LogPrint(BCLog::COINJOIN, "CCoinJoinClientManager::CheckAutomaticBackup -- %s\n", strAutoDenomResult.original);
2018-11-05 10:29:07 +01:00
return false;
}
if (mixingWallet.nKeysLeftSinceAutoBackup < COINJOIN_KEYS_THRESHOLD_STOP) {
// We should never get here via mixing itself but probably something else is still actively using keypool
2022-04-06 22:37:20 +02:00
strAutoDenomResult = strprintf(_("Very low number of keys left: %d") + Untranslated(", ") + _("no mixing available."), mixingWallet.nKeysLeftSinceAutoBackup);
LogPrint(BCLog::COINJOIN, "CCoinJoinClientManager::CheckAutomaticBackup -- %s\n", strAutoDenomResult.original);
// It's getting really dangerous, stop mixing
StopMixing();
return false;
} else if (mixingWallet.nKeysLeftSinceAutoBackup < COINJOIN_KEYS_THRESHOLD_WARNING) {
// Low number of keys left, but it's still more or less safe to continue
2022-04-06 22:37:20 +02:00
strAutoDenomResult = strprintf(_("Very low number of keys left: %d"), mixingWallet.nKeysLeftSinceAutoBackup);
LogPrint(BCLog::COINJOIN, "CCoinJoinClientManager::CheckAutomaticBackup -- %s\n", strAutoDenomResult.original);
2018-11-05 10:29:07 +01:00
if (fCreateAutoBackups) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientManager::CheckAutomaticBackup -- Trying to create new backup.\n");
bilingual_str errorString;
std::vector<bilingual_str> warnings;
if (!mixingWallet.AutoBackupWallet("", errorString, warnings)) {
if (!warnings.empty()) {
// There were some issues saving backup but yet more or less safe to continue
Merge #18922: gui: Do not translate InitWarning messages in debug.log 78be8d97d3d750fcfbbe509a72639b7b30b7bd18 util: Drop OpOriginal() and OpTranslated() (Hennadii Stepanov) da16f95c3fecf4ee1e9a1dc4333b0b92cd981afd gui: Do not translate InitWarning messages in debug.log (Hennadii Stepanov) 4c9b9a4882e68835f16a52f1f0657efe47e589b5 util: Enhance Join() (Hennadii Stepanov) fe05dd0611cfc2929a7fdec04ca5948bccf0233b util: Enhance bilingual_str (Hennadii Stepanov) Pull request description: This PR forces the `bitcoin-qt` to write `InitWarning()` messages to the `debug.log` file in untranslated form, i.e., in English. On master (376294cde6b1588cb17055d8fde567eaf5848c3c): ``` $ ./src/qt/bitcoin-qt -lang=nl -debug=vladidation -printtoconsole | grep 'vladi' Warning: Niet-ondersteunde logcategorie -debug=vladidation. 2020-05-09T12:39:59Z Warning: Niet-ondersteunde logcategorie -debug=vladidation. 2020-05-09T12:40:02Z Command-line arg: debug="vladidation" ``` With this PR: ``` $ ./src/qt/bitcoin-qt -lang=nl -debug=vladidation -printtoconsole | grep 'vladi' Warning: Unsupported logging category -debug=vladidation. 2020-05-09T12:42:04Z Warning: Unsupported logging category -debug=vladidation. 2020-05-09T12:42:35Z Command-line arg: debug="vladidation" ``` ![Screenshot from 2020-05-09 15-42-31](https://user-images.githubusercontent.com/32963518/81474073-c7a50e00-920b-11ea-8775-c41122dacafe.png) Related to #16218. ACKs for top commit: laanwj: ACK 78be8d97d3d750fcfbbe509a72639b7b30b7bd18 jonasschnelli: utACK 78be8d97d3d750fcfbbe509a72639b7b30b7bd18 MarcoFalke: ACK 78be8d97d3d750fcfbbe509a72639b7b30b7bd18 📢 Tree-SHA512: 48e9ecd23c4dd8ec262e3eb94f8e30944bcc9c6c163245fb837b2e0c484d4d0b4f47f7abc638c14edc27d635d340ba3ee4ba4506b062399e9cf59a1564c98755 # Conflicts: # src/wallet/load.cpp
2020-05-13 20:30:31 +02:00
LogPrint(BCLog::COINJOIN, "CCoinJoinClientManager::CheckAutomaticBackup -- WARNING! Something went wrong on automatic backup: %s\n", Join(warnings, Untranslated("\n")).translated);
}
if (!errorString.original.empty()) {
// Things are really broken
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("ERROR! Failed to create automatic backup") + Untranslated(": ") + errorString;
LogPrint(BCLog::COINJOIN, "CCoinJoinClientManager::CheckAutomaticBackup -- %s\n", strAutoDenomResult.original);
return false;
}
}
} else {
// Wait for something else (e.g. GUI action) to create automatic backup for us
return false;
}
}
LogPrint(BCLog::COINJOIN, "CCoinJoinClientManager::CheckAutomaticBackup -- Keys left since latest backup: %d\n", mixingWallet.nKeysLeftSinceAutoBackup);
return true;
}
//
// Passively run mixing in the background to mix funds based on the given configuration.
//
bool CCoinJoinClientSession::DoAutomaticDenominating(CConnman& connman, bool fDryRun)
{
2018-11-05 10:29:07 +01:00
if (fMasternodeMode) return false; // no client-side mixing on masternodes
if (nState != POOL_STATE_IDLE) return false;
Remove all legacy/compatibility MN code (#2600) * Remove CActiveLegacyMasternodeManager * Remove sentinelping RPC * Remove unused P2P messages and inv types There are still places where these are used in the code. The next commits will clean these up. * Remove MNB/MNP/MNVERIFY related code from masternode(man).h/cpp * Remove all legacy code regarding block MN payee voting * Remove MASTERNODE_SYNC_LIST and MASTERNODE_SYNC_MNW states Also replace all uses of IsMasternodeListSynced and IsWinnersListSynced with IsBlockchainSynced. * Remove unsupported masternode RPCs * Remove UpdateLastPaid methods * Remove duplicate deterministicmns.h include * Remove masternode.conf support * Remove legacy MN lists support from masternode list GUI * Remove unnecessary AskForMN call * Remove compatibility code in CPrivateSendQueue::GetSignatureHash * Don't add locally calculated MN payee in case GetBlockTxOuts failed This is not valid in DIP3 mode * Remove check for IsDeterministicMNsSporkActive in "masternode status" * Move CMasternode::IsValidNetAddr to CActiveDeterministicMasternodeManager * Remove use of CMasternode::CheckCollateral in governance code * Remove uses of MASTERNODE_SENTINEL_PING_MAX_SECONDS/MASTERNODE_SENTINEL_PING_MAX_SECONDS * Remove support for "-masternodeprivkey" * Remove pre-DIP3 vote cleanup * Remove compatibility code for quorumModifierHash/masternodeProTxHash * Remove check for invalid nBlockHeight in CMasternodePayments::GetBlockTxOuts ...and let it crash instead. We expect this method to be called with the correct height now (after DIP3 was fully deployed). * Remove ECDSA based Sign/CheckSignature from CGovernanceObject Only masternodes sign governance objects, so there is no need for ECDSA support here anymore. * Always add superblock and MN reward payments into new block * Always check block payees (except if fLiteMode==true) * Always allow superblock and MN payees in same block * Remove/Fix a few references to masternode.conf and related stuff Also delete guide-startmany.md and masternode_conf.md * Implement NotifyMasternodeListChanged signal and call governance maintenance * Remove non-DIP3 code path from CMasternodeMan::Find * Remove remaining unused code from CMasternode/CMasternodeMan * Always load governance.dat on startup * Mine an empty block instead of incrementing nHeight from chain tip in miner tests This test is crashing otherwise in GetBlockTxOuts as it tries to access a previous block that is not existing. * Skip MN payments verification on historical blocks (pre-DIP3 blocks) Even though DIP3 was active on BIP9 level, the spork was not active yet at that point meaning that payments were not enforced at that time. * Remove unused state and CollateralStatus enums * Unconditionally return false from IsBlockPayeeValid when IsTransactionValid returns false IsTransactionValid already handles the case where IsDIP3Active() returns false, making it return true. * Add override keyword to CDSNotificationInterface::NotifyMasternodeListChanged * Fix help for masternodelist status (POSE_BANNED and no OUTPOINT_SPENT)
2019-01-03 10:17:43 +01:00
if (!masternodeSync.IsBlockchainSynced()) {
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Can't mix while sync in progress.");
return false;
}
if (!CCoinJoinClientOptions::IsEnabled()) return false;
CAmount nBalanceNeedsAnonymized;
{
LOCK2(cs_main, mixingWallet.cs_wallet);
if (!fDryRun && mixingWallet.IsLocked(true)) {
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Wallet is locked.");
2018-11-05 10:29:07 +01:00
return false;
}
2018-11-05 10:29:07 +01:00
if (GetEntriesCount() > 0) {
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Mixing in progress...");
2018-11-05 10:29:07 +01:00
return false;
}
TRY_LOCK(cs_coinjoin, lockDS);
2018-11-05 10:29:07 +01:00
if (!lockDS) {
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Lock is already in place.");
2018-11-05 10:29:07 +01:00
return false;
}
if (deterministicMNManager->GetListAtChainTip().GetValidMNsCount() == 0 &&
Params().NetworkIDString() != CBaseChainParams::REGTEST) {
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("No Masternodes detected.");
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::DoAutomaticDenominating -- %s\n", strAutoDenomResult.original);
2018-11-05 10:29:07 +01:00
return false;
}
const auto bal = mixingWallet.GetBalance();
// check if there is anything left to do
CAmount nBalanceAnonymized = bal.m_anonymized;
nBalanceNeedsAnonymized = CCoinJoinClientOptions::GetAmount() * COIN - nBalanceAnonymized;
if (nBalanceNeedsAnonymized < 0) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::DoAutomaticDenominating -- Nothing to do\n");
// nothing to do, just keep it in idle mode
return false;
}
CAmount nValueMin = CCoinJoin::GetSmallestDenomination();
2018-11-05 10:29:07 +01:00
// if there are no confirmed DS collateral inputs yet
if (!mixingWallet.HasCollateralInputs()) {
2018-11-05 10:29:07 +01:00
// should have some additional amount for them
nValueMin += CCoinJoin::GetMaxCollateralAmount();
2018-11-05 10:29:07 +01:00
}
2018-11-05 10:29:07 +01:00
// including denoms but applying some restrictions
CAmount nBalanceAnonymizable = mixingWallet.GetAnonymizableBalance();
// mixable balance is way too small
if (nBalanceAnonymizable < nValueMin) {
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Not enough funds to mix.");
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::DoAutomaticDenominating -- %s\n", strAutoDenomResult.original);
2018-11-05 10:29:07 +01:00
return false;
}
2018-11-05 10:29:07 +01:00
// excluding denoms
CAmount nBalanceAnonimizableNonDenom = mixingWallet.GetAnonymizableBalance(true);
2018-11-05 10:29:07 +01:00
// denoms
CAmount nBalanceDenominatedConf = bal.m_denominated_trusted;
CAmount nBalanceDenominatedUnconf = bal.m_denominated_untrusted_pending;
2018-11-05 10:29:07 +01:00
CAmount nBalanceDenominated = nBalanceDenominatedConf + nBalanceDenominatedUnconf;
CAmount nBalanceToDenominate = CCoinJoinClientOptions::GetAmount() * COIN - nBalanceDenominated;
// adjust nBalanceNeedsAnonymized to consume final denom
if (nBalanceDenominated - nBalanceAnonymized > nBalanceNeedsAnonymized) {
auto denoms = CCoinJoin::GetStandardDenominations();
CAmount nAdditionalDenom{0};
for (const auto& denom : denoms) {
if (nBalanceNeedsAnonymized < denom) {
nAdditionalDenom = denom;
} else {
break;
}
}
nBalanceNeedsAnonymized += nAdditionalDenom;
}
2018-11-05 10:29:07 +01:00
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::DoAutomaticDenominating -- current stats:\n"
" nValueMin: %s\n"
" nBalanceAnonymizable: %s\n"
" nBalanceAnonymized: %s\n"
" nBalanceNeedsAnonymized: %s\n"
" nBalanceAnonimizableNonDenom: %s\n"
" nBalanceDenominatedConf: %s\n"
" nBalanceDenominatedUnconf: %s\n"
2019-05-02 01:20:36 +02:00
" nBalanceDenominated: %s\n"
" nBalanceToDenominate: %s\n",
FormatMoney(nValueMin),
FormatMoney(nBalanceAnonymizable),
FormatMoney(nBalanceAnonymized),
FormatMoney(nBalanceNeedsAnonymized),
FormatMoney(nBalanceAnonimizableNonDenom),
FormatMoney(nBalanceDenominatedConf),
FormatMoney(nBalanceDenominatedUnconf),
FormatMoney(nBalanceDenominated),
FormatMoney(nBalanceToDenominate)
);
2018-11-05 10:29:07 +01:00
if (fDryRun) return true;
// Check if we have should create more denominated inputs i.e.
// there are funds to denominate and denominated balance does not exceed
// max amount to mix yet.
if (nBalanceAnonimizableNonDenom >= nValueMin + CCoinJoin::GetCollateralAmount() && nBalanceToDenominate > 0) {
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
CreateDenominated(nBalanceToDenominate);
}
2018-11-05 10:29:07 +01:00
//check if we have the collateral sized inputs
if (!mixingWallet.HasCollateralInputs()) {
return !mixingWallet.HasCollateralInputs(false) && MakeCollateralAmounts();
}
2018-11-05 10:29:07 +01:00
if (nSessionID) {
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Mixing in progress...");
2018-11-05 10:29:07 +01:00
return false;
}
2018-11-05 10:29:07 +01:00
// Initial phase, find a Masternode
// Clean if there is anything left from previous session
UnlockCoins();
keyHolderStorage.ReturnAll();
SetNull();
2018-11-05 10:29:07 +01:00
// should be no unconfirmed denoms in non-multi-session mode
if (!CCoinJoinClientOptions::IsMultiSessionEnabled() && nBalanceDenominatedUnconf > 0) {
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Found unconfirmed denominated outputs, will wait till they confirm to continue.");
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::DoAutomaticDenominating -- %s\n", strAutoDenomResult.original);
return false;
}
2018-11-05 10:29:07 +01:00
//check our collateral and create new if needed
std::string strReason;
if (CTransaction(txMyCollateral).IsNull()) {
if (!CreateCollateralTransaction(txMyCollateral, strReason)) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::DoAutomaticDenominating -- create collateral error:%s\n", strReason);
return false;
}
2018-11-05 10:29:07 +01:00
} else {
if (!CCoinJoin::IsCollateralValid(CTransaction(txMyCollateral))) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::DoAutomaticDenominating -- invalid collateral, recreating...\n");
if (!CreateCollateralTransaction(txMyCollateral, strReason)) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::DoAutomaticDenominating -- create collateral error: %s\n", strReason);
2018-11-05 10:29:07 +01:00
return false;
}
}
}
// lock the funds we're going to use for our collateral
for (const auto& txin : txMyCollateral.vin) {
mixingWallet.LockCoin(txin.prevout);
vecOutPointLocked.push_back(txin.prevout);
}
} // LOCK2(cs_main, mixingWallet.cs_wallet);
// Always attempt to join an existing queue
if (JoinExistingQueue(nBalanceNeedsAnonymized, connman)) {
return true;
}
// If we were unable to find/join an existing queue then start a new one.
if (StartNewQueue(nBalanceNeedsAnonymized, connman)) return true;
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("No compatible Masternode found.");
return false;
}
bool CCoinJoinClientManager::DoAutomaticDenominating(CConnman& connman, bool fDryRun)
{
if (fMasternodeMode) return false; // no client-side mixing on masternodes
if (!CCoinJoinClientOptions::IsEnabled() || !IsMixing()) return false;
Remove all legacy/compatibility MN code (#2600) * Remove CActiveLegacyMasternodeManager * Remove sentinelping RPC * Remove unused P2P messages and inv types There are still places where these are used in the code. The next commits will clean these up. * Remove MNB/MNP/MNVERIFY related code from masternode(man).h/cpp * Remove all legacy code regarding block MN payee voting * Remove MASTERNODE_SYNC_LIST and MASTERNODE_SYNC_MNW states Also replace all uses of IsMasternodeListSynced and IsWinnersListSynced with IsBlockchainSynced. * Remove unsupported masternode RPCs * Remove UpdateLastPaid methods * Remove duplicate deterministicmns.h include * Remove masternode.conf support * Remove legacy MN lists support from masternode list GUI * Remove unnecessary AskForMN call * Remove compatibility code in CPrivateSendQueue::GetSignatureHash * Don't add locally calculated MN payee in case GetBlockTxOuts failed This is not valid in DIP3 mode * Remove check for IsDeterministicMNsSporkActive in "masternode status" * Move CMasternode::IsValidNetAddr to CActiveDeterministicMasternodeManager * Remove use of CMasternode::CheckCollateral in governance code * Remove uses of MASTERNODE_SENTINEL_PING_MAX_SECONDS/MASTERNODE_SENTINEL_PING_MAX_SECONDS * Remove support for "-masternodeprivkey" * Remove pre-DIP3 vote cleanup * Remove compatibility code for quorumModifierHash/masternodeProTxHash * Remove check for invalid nBlockHeight in CMasternodePayments::GetBlockTxOuts ...and let it crash instead. We expect this method to be called with the correct height now (after DIP3 was fully deployed). * Remove ECDSA based Sign/CheckSignature from CGovernanceObject Only masternodes sign governance objects, so there is no need for ECDSA support here anymore. * Always add superblock and MN reward payments into new block * Always check block payees (except if fLiteMode==true) * Always allow superblock and MN payees in same block * Remove/Fix a few references to masternode.conf and related stuff Also delete guide-startmany.md and masternode_conf.md * Implement NotifyMasternodeListChanged signal and call governance maintenance * Remove non-DIP3 code path from CMasternodeMan::Find * Remove remaining unused code from CMasternode/CMasternodeMan * Always load governance.dat on startup * Mine an empty block instead of incrementing nHeight from chain tip in miner tests This test is crashing otherwise in GetBlockTxOuts as it tries to access a previous block that is not existing. * Skip MN payments verification on historical blocks (pre-DIP3 blocks) Even though DIP3 was active on BIP9 level, the spork was not active yet at that point meaning that payments were not enforced at that time. * Remove unused state and CollateralStatus enums * Unconditionally return false from IsBlockPayeeValid when IsTransactionValid returns false IsTransactionValid already handles the case where IsDIP3Active() returns false, making it return true. * Add override keyword to CDSNotificationInterface::NotifyMasternodeListChanged * Fix help for masternodelist status (POSE_BANNED and no OUTPOINT_SPENT)
2019-01-03 10:17:43 +01:00
if (!masternodeSync.IsBlockchainSynced()) {
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Can't mix while sync in progress.");
return false;
}
if (!fDryRun && mixingWallet.IsLocked(true)) {
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Wallet is locked.");
return false;
}
int nMnCountEnabled = deterministicMNManager->GetListAtChainTip().GetValidMNsCount();
// If we've used 90% of the Masternode list then drop the oldest first ~30%
int nThreshold_high = nMnCountEnabled * 0.9;
int nThreshold_low = nThreshold_high * 0.7;
LogPrint(BCLog::COINJOIN, "Checking vecMasternodesUsed: size: %d, threshold: %d\n", (int)vecMasternodesUsed.size(), nThreshold_high);
2018-11-05 10:29:07 +01:00
if ((int)vecMasternodesUsed.size() > nThreshold_high) {
vecMasternodesUsed.erase(vecMasternodesUsed.begin(), vecMasternodesUsed.begin() + vecMasternodesUsed.size() - nThreshold_low);
LogPrint(BCLog::COINJOIN, " vecMasternodesUsed: new size: %d, threshold: %d\n", (int)vecMasternodesUsed.size(), nThreshold_high);
}
bool fResult = true;
AssertLockNotHeld(cs_deqsessions);
LOCK(cs_deqsessions);
if ((int)deqSessions.size() < CCoinJoinClientOptions::GetSessions()) {
deqSessions.emplace_back(mixingWallet);
}
for (auto& session : deqSessions) {
if (!CheckAutomaticBackup()) return false;
if (WaitForAnotherBlock()) {
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Last successful action was too recent.");
LogPrint(BCLog::COINJOIN, "CCoinJoinClientManager::DoAutomaticDenominating -- %s\n", strAutoDenomResult.original);
return false;
}
fResult &= session.DoAutomaticDenominating(connman, fDryRun);
}
return fResult;
}
void CCoinJoinClientManager::AddUsedMasternode(const COutPoint& outpointMn)
{
vecMasternodesUsed.push_back(outpointMn);
}
CDeterministicMNCPtr CCoinJoinClientManager::GetRandomNotUsedMasternode()
{
auto mnList = deterministicMNManager->GetListAtChainTip();
size_t nCountEnabled = mnList.GetValidMNsCount();
size_t nCountNotExcluded = nCountEnabled - vecMasternodesUsed.size();
LogPrint(BCLog::COINJOIN, "CCoinJoinClientManager::%s -- %d enabled masternodes, %d masternodes to choose from\n", __func__, nCountEnabled, nCountNotExcluded);
if (nCountNotExcluded < 1) {
return nullptr;
}
// fill a vector
std::vector<CDeterministicMNCPtr> vpMasternodesShuffled;
vpMasternodesShuffled.reserve(nCountEnabled);
refactor: numerous changes to avoid passing around a const ref to shared_ptr of CDeterministicMNC when not needed. (#4653) * refactor: numerous changes to avoid passing around a const ref to shared_ptr of CDeterministicMNC when not needed. Introduces ForEachMNShared, a version of ForEachMN that uses a shared_ptr, and may extend the lifetime of the underlying shared_ptr. This is not preferred, should prefer ForEachMN. See docs. Adjusts ForEachMN to pass a reference. This is preferred for use over ForEachMNShared. See docs. A reference should be used since in usage we assume it's non-null anyway. Additionally, it allows us to know that the lifespan of the dmn is not being being extended (if lifespan needs to be extended, should use ForEachMNShared. IsMNValid, IsMNPoSeBanned, UpdateMN, UpdateMN, AddUniqueProperty, DeleteUniqueProperty, UpdateUniqueProperty now take a const reference to CDeterministicMN instead of a const reference to shared_ptr<CDeterministicMN>. All of these functions previously assumed (or would've crashed) a non-null ptr, and non extended lifetime, as such converting to ref is appropriate. CompareByLastPaid ptr overload now takes raw ptr instead of a const ref to shared. Since we simply dereference them, a raw ptr makes the most sense. This also avoids a potential expensive and implicit raw ptr -> shared ptr conversion if the function was called with raw ptrs. rpcevo BuildDMNListEntry now takes a const ref for reasons as stated above Signed-off-by: Pasta <pasta@dashboost.org> * make stuff const Signed-off-by: Pasta <pasta@dashboost.org> * refactor/llmq: use ranges count_if Signed-off-by: Pasta <pasta@dashboost.org>
2022-01-04 17:13:38 +01:00
mnList.ForEachMNShared(true, [&vpMasternodesShuffled](const CDeterministicMNCPtr& dmn) {
vpMasternodesShuffled.emplace_back(dmn);
});
// shuffle pointers
Shuffle(vpMasternodesShuffled.begin(), vpMasternodesShuffled.end(), FastRandomContext());
std::set<COutPoint> excludeSet(vecMasternodesUsed.begin(), vecMasternodesUsed.end());
// loop through
for (const auto& dmn : vpMasternodesShuffled) {
if (excludeSet.count(dmn->collateralOutpoint)) {
continue;
}
LogPrint(BCLog::COINJOIN, "CCoinJoinClientManager::%s -- found, masternode=%s\n", __func__, dmn->collateralOutpoint.ToStringShort());
return dmn;
}
LogPrint(BCLog::COINJOIN, "CCoinJoinClientManager::%s -- failed\n", __func__);
return nullptr;
}
bool CCoinJoinClientSession::JoinExistingQueue(CAmount nBalanceNeedsAnonymized, CConnman& connman)
{
if (!CCoinJoinClientOptions::IsEnabled()) return false;
auto mnList = deterministicMNManager->GetListAtChainTip();
int winners_to_skip{8};
if (Params().NetworkIDString() == CBaseChainParams::DEVNET || Params().NetworkIDString() == CBaseChainParams::REGTEST) {
winners_to_skip = 0;
}
// Look through the queues and see if anything matches
CCoinJoinQueue dsq;
while (coinJoinClientQueueManager.GetQueueItemAndTry(dsq)) {
auto dmn = mnList.GetValidMNByCollateral(dsq.masternodeOutpoint);
if (!dmn) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::JoinExistingQueue -- dsq masternode is not in masternode list, masternode=%s\n", dsq.masternodeOutpoint.ToStringShort());
continue;
}
// skip next mn payments winners
if (dmn->pdmnState->nLastPaidHeight + int(mnList.GetValidMNsCount()) < mnList.GetHeight() + winners_to_skip) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::JoinExistingQueue -- skipping winner, masternode=%s\n", dmn->proTxHash.ToString());
continue;
}
// mixing rate limit i.e. nLastDsq check should already pass in DSQUEUE ProcessMessage
// in order for dsq to get into vecCoinJoinQueue, so we should be safe to mix already,
// no need for additional verification here
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::JoinExistingQueue -- trying queue: %s\n", dsq.ToString());
std::vector<CTxDSIn> vecTxDSInTmp;
// Try to match their denominations if possible, select exact number of denominations
if (!mixingWallet.SelectTxDSInsByDenomination(dsq.nDenom, nBalanceNeedsAnonymized, vecTxDSInTmp)) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::JoinExistingQueue -- Couldn't match denomination %d (%s)\n", dsq.nDenom, CCoinJoin::DenominationToString(dsq.nDenom));
continue;
}
coinJoinClientManagers.at(mixingWallet.GetName())->AddUsedMasternode(dsq.masternodeOutpoint);
if (connman.IsMasternodeOrDisconnectRequested(dmn->pdmnState->addr)) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::JoinExistingQueue -- skipping masternode connection, addr=%s\n", dmn->pdmnState->addr.ToString());
Backport Bitcoin PR#8085: p2p: Begin encapsulation (#1537) * net: move CBanDB and CAddrDB out of net.h/cpp This will eventually solve a circular dependency * net: Create CConnman to encapsulate p2p connections * net: Move socket binding into CConnman * net: move OpenNetworkConnection into CConnman * net: move ban and addrman functions into CConnman * net: Add oneshot functions to CConnman * net: move added node functions to CConnman * net: Add most functions needed for vNodes to CConnman * net: handle nodesignals in CConnman * net: Pass CConnection to wallet rather than using the global * net: Add rpc error for missing/disabled p2p functionality * net: Pass CConnman around as needed * gui: add NodeID to the peer table * net: create generic functor accessors and move vNodes to CConnman * net: move whitelist functions into CConnman * net: move nLastNodeId to CConnman * net: move nLocalHostNonce to CConnman This behavior seems to have been quite racy and broken. Move nLocalHostNonce into CNode, and check received nonces against all non-fully-connected nodes. If there's a match, assume we've connected to ourself. * net: move messageHandlerCondition to CConnman * net: move send/recv statistics to CConnman * net: move SendBufferSize/ReceiveFloodSize to CConnman * net: move nLocalServices/nRelevantServices to CConnman These are in-turn passed to CNode at connection time. This allows us to offer different services to different peers (or test the effects of doing so). * net: move semOutbound and semMasternodeOutbound to CConnman * net: SocketSendData returns written size * net: move max/max-outbound to CConnman * net: Pass best block known height into CConnman CConnman then passes the current best height into CNode at creation time. This way CConnman/CNode have no dependency on main for height, and the signals only move in one direction. This also helps to prevent identity leakage a tiny bit. Before this change, an attacker could theoretically make 2 connections on different interfaces. They would connect fully on one, and only establish the initial connection on the other. Once they receive a new block, they would relay it to your first connection, and immediately commence the version handshake on the second. Since the new block height is reflected immediately, they could attempt to learn whether the two connections were correlated. This is, of course, incredibly unlikely to work due to the small timings involved and receipt from other senders. But it doesn't hurt to lock-in nBestHeight at the time of connection, rather than letting the remote choose the time. * net: pass CClientUIInterface into CConnman * net: Drop StartNode/StopNode and use CConnman directly * net: Introduce CConnection::Options to avoid passing so many params * net: add nSendBufferMaxSize/nReceiveFloodSize to CConnection::Options * net: move vNodesDisconnected into CConnman * Made the ForEachNode* functions in src/net.cpp more pragmatic and self documenting * Convert ForEachNode* functions to take a templated function argument rather than a std::function to eliminate std::function overhead * net: move MAX_FEELER_CONNECTIONS into connman
2017-07-21 11:35:19 +02:00
continue;
}
nSessionDenom = dsq.nDenom;
mixingMasternode = dmn;
pendingDsaRequest = CPendingDsaRequest(dmn->pdmnState->addr, CCoinJoinAccept(nSessionDenom, txMyCollateral));
connman.AddPendingMasternode(dmn->proTxHash);
SetState(POOL_STATE_QUEUE);
nTimeLastSuccessfulStep = GetTime();
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::JoinExistingQueue -- pending connection (from queue): nSessionDenom: %d (%s), addr=%s\n",
nSessionDenom, CCoinJoin::DenominationToString(nSessionDenom), dmn->pdmnState->addr.ToString());
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Trying to connect...");
return true;
}
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Failed to find mixing queue to join");
return false;
}
bool CCoinJoinClientSession::StartNewQueue(CAmount nBalanceNeedsAnonymized, CConnman& connman)
{
if (!CCoinJoinClientOptions::IsEnabled()) return false;
if (nBalanceNeedsAnonymized <= 0) return false;
int nTries = 0;
auto mnList = deterministicMNManager->GetListAtChainTip();
int nMnCount = mnList.GetValidMNsCount();
// find available denominated amounts
std::set<CAmount> setAmounts;
if (!mixingWallet.SelectDenominatedAmounts(nBalanceNeedsAnonymized, setAmounts)) {
// this should never happen
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Can't mix: no compatible inputs found!");
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::StartNewQueue -- %s\n", strAutoDenomResult.original);
return false;
}
// otherwise, try one randomly
2018-11-05 10:29:07 +01:00
while (nTries < 10) {
auto dmn = coinJoinClientManagers.at(mixingWallet.GetName())->GetRandomNotUsedMasternode();
if (!dmn) {
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Can't find random Masternode.");
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::StartNewQueue -- %s\n", strAutoDenomResult.original);
return false;
}
coinJoinClientManagers.at(mixingWallet.GetName())->AddUsedMasternode(dmn->collateralOutpoint);
// skip next mn payments winners
if (dmn->pdmnState->nLastPaidHeight + nMnCount < mnList.GetHeight() + 8) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::StartNewQueue -- skipping winner, masternode=%s\n", dmn->proTxHash.ToString());
nTries++;
continue;
}
int64_t nLastDsq = mmetaman.GetMetaInfo(dmn->proTxHash)->GetLastDsq();
int64_t nDsqThreshold = mmetaman.GetDsqThreshold(dmn->proTxHash, nMnCount);
if (nLastDsq != 0 && nDsqThreshold > mmetaman.GetDsqCount()) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::StartNewQueue -- Too early to mix on this masternode!" /* Continued */
" masternode=%s addr=%s nLastDsq=%d nDsqThreshold=%d nDsqCount=%d\n",
dmn->proTxHash.ToString(), dmn->pdmnState->addr.ToString(), nLastDsq,
nDsqThreshold, mmetaman.GetDsqCount());
nTries++;
continue;
}
if (connman.IsMasternodeOrDisconnectRequested(dmn->pdmnState->addr)) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::StartNewQueue -- skipping masternode connection, addr=%s\n", dmn->pdmnState->addr.ToString());
Backport Bitcoin PR#8085: p2p: Begin encapsulation (#1537) * net: move CBanDB and CAddrDB out of net.h/cpp This will eventually solve a circular dependency * net: Create CConnman to encapsulate p2p connections * net: Move socket binding into CConnman * net: move OpenNetworkConnection into CConnman * net: move ban and addrman functions into CConnman * net: Add oneshot functions to CConnman * net: move added node functions to CConnman * net: Add most functions needed for vNodes to CConnman * net: handle nodesignals in CConnman * net: Pass CConnection to wallet rather than using the global * net: Add rpc error for missing/disabled p2p functionality * net: Pass CConnman around as needed * gui: add NodeID to the peer table * net: create generic functor accessors and move vNodes to CConnman * net: move whitelist functions into CConnman * net: move nLastNodeId to CConnman * net: move nLocalHostNonce to CConnman This behavior seems to have been quite racy and broken. Move nLocalHostNonce into CNode, and check received nonces against all non-fully-connected nodes. If there's a match, assume we've connected to ourself. * net: move messageHandlerCondition to CConnman * net: move send/recv statistics to CConnman * net: move SendBufferSize/ReceiveFloodSize to CConnman * net: move nLocalServices/nRelevantServices to CConnman These are in-turn passed to CNode at connection time. This allows us to offer different services to different peers (or test the effects of doing so). * net: move semOutbound and semMasternodeOutbound to CConnman * net: SocketSendData returns written size * net: move max/max-outbound to CConnman * net: Pass best block known height into CConnman CConnman then passes the current best height into CNode at creation time. This way CConnman/CNode have no dependency on main for height, and the signals only move in one direction. This also helps to prevent identity leakage a tiny bit. Before this change, an attacker could theoretically make 2 connections on different interfaces. They would connect fully on one, and only establish the initial connection on the other. Once they receive a new block, they would relay it to your first connection, and immediately commence the version handshake on the second. Since the new block height is reflected immediately, they could attempt to learn whether the two connections were correlated. This is, of course, incredibly unlikely to work due to the small timings involved and receipt from other senders. But it doesn't hurt to lock-in nBestHeight at the time of connection, rather than letting the remote choose the time. * net: pass CClientUIInterface into CConnman * net: Drop StartNode/StopNode and use CConnman directly * net: Introduce CConnection::Options to avoid passing so many params * net: add nSendBufferMaxSize/nReceiveFloodSize to CConnection::Options * net: move vNodesDisconnected into CConnman * Made the ForEachNode* functions in src/net.cpp more pragmatic and self documenting * Convert ForEachNode* functions to take a templated function argument rather than a std::function to eliminate std::function overhead * net: move MAX_FEELER_CONNECTIONS into connman
2017-07-21 11:35:19 +02:00
nTries++;
continue;
}
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::StartNewQueue -- attempt %d connection to Masternode %s\n", nTries, dmn->pdmnState->addr.ToString());
// try to get a single random denom out of setAmounts
2018-11-05 10:29:07 +01:00
while (nSessionDenom == 0) {
for (auto it = setAmounts.rbegin(); it != setAmounts.rend(); ++it) {
if (setAmounts.size() > 1 && GetRandInt(2)) continue;
nSessionDenom = CCoinJoin::AmountToDenomination(*it);
break;
}
}
mixingMasternode = dmn;
connman.AddPendingMasternode(dmn->proTxHash);
pendingDsaRequest = CPendingDsaRequest(dmn->pdmnState->addr, CCoinJoinAccept(nSessionDenom, txMyCollateral));
SetState(POOL_STATE_QUEUE);
nTimeLastSuccessfulStep = GetTime();
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::StartNewQueue -- pending connection, nSessionDenom: %d (%s), addr=%s\n",
nSessionDenom, CCoinJoin::DenominationToString(nSessionDenom), dmn->pdmnState->addr.ToString());
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Trying to connect...");
return true;
}
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Failed to start a new mixing queue");
return false;
}
bool CCoinJoinClientSession::ProcessPendingDsaRequest(CConnman& connman)
{
if (!pendingDsaRequest) return false;
bool fDone = connman.ForNode(pendingDsaRequest.GetAddr(), [this, &connman](CNode* pnode) {
LogPrint(BCLog::COINJOIN, "-- processing dsa queue for addr=%s\n", pnode->addr.ToString());
nTimeLastSuccessfulStep = GetTime();
CNetMsgMaker msgMaker(pnode->GetSendVersion());
connman.PushMessage(pnode, msgMaker.Make(NetMsgType::DSACCEPT, pendingDsaRequest.GetDSA()));
return true;
});
if (fDone) {
pendingDsaRequest = CPendingDsaRequest();
} else if (pendingDsaRequest.IsExpired()) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- failed to connect to %s\n", __func__, pendingDsaRequest.GetAddr().ToString());
WITH_LOCK(cs_coinjoin, SetNull());
}
return fDone;
}
void CCoinJoinClientManager::ProcessPendingDsaRequest(CConnman& connman)
{
AssertLockNotHeld(cs_deqsessions);
LOCK(cs_deqsessions);
for (auto& session : deqSessions) {
if (session.ProcessPendingDsaRequest(connman)) {
2022-04-06 22:37:20 +02:00
strAutoDenomResult = _("Mixing in progress...");
}
}
}
bool CCoinJoinClientManager::TrySubmitDenominate(const CService& mnAddr, CConnman& connman)
{
AssertLockNotHeld(cs_deqsessions);
LOCK(cs_deqsessions);
for (auto& session : deqSessions) {
CDeterministicMNCPtr mnMixing;
if (session.GetMixingMasternodeInfo(mnMixing) && mnMixing->pdmnState->addr == mnAddr && session.GetState() == POOL_STATE_QUEUE) {
session.SubmitDenominate(connman);
return true;
}
}
return false;
}
bool CCoinJoinClientManager::MarkAlreadyJoinedQueueAsTried(CCoinJoinQueue& dsq) const
{
AssertLockNotHeld(cs_deqsessions);
LOCK(cs_deqsessions);
for (const auto& session : deqSessions) {
CDeterministicMNCPtr mnMixing;
if (session.GetMixingMasternodeInfo(mnMixing) && mnMixing->collateralOutpoint == dsq.masternodeOutpoint) {
dsq.fTried = true;
return true;
}
}
return false;
}
bool CCoinJoinClientSession::SubmitDenominate(CConnman& connman)
{
LOCK2(cs_main, mixingWallet.cs_wallet);
std::string strError;
std::vector<CTxDSIn> vecTxDSIn;
std::vector<std::pair<CTxDSIn, CTxOut> > vecPSInOutPairsTmp;
if (!SelectDenominate(strError, vecTxDSIn)) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::SubmitDenominate -- SelectDenominate failed, error: %s\n", strError);
return false;
}
2018-11-05 10:29:07 +01:00
std::vector<std::pair<int, size_t> > vecInputsByRounds;
for (int i = 0; i < CCoinJoinClientOptions::GetRounds() + CCoinJoinClientOptions::GetRandomRounds(); i++) {
if (PrepareDenominate(i, i, strError, vecTxDSIn, vecPSInOutPairsTmp, true)) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::SubmitDenominate -- Running CoinJoin denominate for %d rounds, success\n", i);
vecInputsByRounds.emplace_back(i, vecPSInOutPairsTmp.size());
} else {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::SubmitDenominate -- Running CoinJoin denominate for %d rounds, error: %s\n", i, strError);
}
}
// more inputs first, for equal input count prefer the one with fewer rounds
std::sort(vecInputsByRounds.begin(), vecInputsByRounds.end(), [](const auto& a, const auto& b) {
return a.second > b.second || (a.second == b.second && a.first < b.first);
});
LogPrint(BCLog::COINJOIN, "vecInputsByRounds for denom %d\n", nSessionDenom);
for (const auto& pair : vecInputsByRounds) {
LogPrint(BCLog::COINJOIN, "vecInputsByRounds: rounds: %d, inputs: %d\n", pair.first, pair.second);
}
int nRounds = vecInputsByRounds.begin()->first;
if (PrepareDenominate(nRounds, nRounds, strError, vecTxDSIn, vecPSInOutPairsTmp)) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::SubmitDenominate -- Running CoinJoin denominate for %d rounds, success\n", nRounds);
return SendDenominate(vecPSInOutPairsTmp, connman);
}
// We failed? That's strange but let's just make final attempt and try to mix everything
if (PrepareDenominate(0, CCoinJoinClientOptions::GetRounds() - 1, strError, vecTxDSIn, vecPSInOutPairsTmp)) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::SubmitDenominate -- Running CoinJoin denominate for all rounds, success\n");
return SendDenominate(vecPSInOutPairsTmp, connman);
}
// Should never actually get here but just in case
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::SubmitDenominate -- Running CoinJoin denominate for all rounds, error: %s\n", strError);
2022-04-06 22:37:20 +02:00
strAutoDenomResult = Untranslated(strError);
return false;
}
bool CCoinJoinClientSession::SelectDenominate(std::string& strErrorRet, std::vector<CTxDSIn>& vecTxDSInRet)
{
if (!CCoinJoinClientOptions::IsEnabled()) return false;
if (mixingWallet.IsLocked(true)) {
strErrorRet = "Wallet locked, unable to create transaction!";
return false;
}
if (GetEntriesCount() > 0) {
strErrorRet = "Already have pending entries in the CoinJoin pool";
return false;
}
vecTxDSInRet.clear();
bool fSelected = mixingWallet.SelectTxDSInsByDenomination(nSessionDenom, CCoinJoin::GetMaxPoolAmount(), vecTxDSInRet);
if (!fSelected) {
strErrorRet = "Can't select current denominated inputs";
return false;
}
return true;
}
bool CCoinJoinClientSession::PrepareDenominate(int nMinRounds, int nMaxRounds, std::string& strErrorRet, const std::vector<CTxDSIn>& vecTxDSIn, std::vector<std::pair<CTxDSIn, CTxOut> >& vecPSInOutPairsRet, bool fDryRun)
{
AssertLockHeld(cs_main);
AssertLockHeld(mixingWallet.cs_wallet);
if (!CCoinJoin::IsValidDenomination(nSessionDenom)) {
strErrorRet = "Incorrect session denom";
return false;
}
CAmount nDenomAmount = CCoinJoin::DenominationToAmount(nSessionDenom);
// NOTE: No need to randomize order of inputs because they were
// initially shuffled in CWallet::SelectTxDSInsByDenomination already.
size_t nSteps{0};
vecPSInOutPairsRet.clear();
// Try to add up to COINJOIN_ENTRY_MAX_SIZE of every needed denomination
for (const auto& entry : vecTxDSIn) {
if (nSteps >= COINJOIN_ENTRY_MAX_SIZE) break;
if (entry.nRounds < nMinRounds || entry.nRounds > nMaxRounds) continue;
CScript scriptDenom;
if (fDryRun) {
scriptDenom = CScript();
} else {
// randomly skip some inputs when we have at least one of the same denom already
// TODO: make it adjustable via options/cmd-line params
if (nSteps >= 1 && GetRandInt(5) == 0) {
// still count it as a step to randomize number of inputs
// if we have more than (or exactly) COINJOIN_ENTRY_MAX_SIZE of them
++nSteps;
continue;
}
const auto pwallet = GetWallet(mixingWallet.GetName());
if (!pwallet) {
strErrorRet ="Couldn't get wallet pointer";
return false;
}
scriptDenom = keyHolderStorage.AddKey(pwallet.get());
}
vecPSInOutPairsRet.emplace_back(entry, CTxOut(nDenomAmount, scriptDenom));
// step is complete
++nSteps;
}
if (vecPSInOutPairsRet.empty()) {
keyHolderStorage.ReturnAll();
strErrorRet = "Can't prepare current denominated outputs";
return false;
}
if (fDryRun) {
return true;
}
for (const auto& pair : vecPSInOutPairsRet) {
mixingWallet.LockCoin(pair.first.prevout);
vecOutPointLocked.push_back(pair.first.prevout);
}
return true;
}
// Create collaterals by looping through inputs grouped by addresses
bool CCoinJoinClientSession::MakeCollateralAmounts()
{
if (!CCoinJoinClientOptions::IsEnabled()) return false;
LOCK2(cs_main, mixingWallet.cs_wallet);
// NOTE: We do not allow txes larger than 100 kB, so we have to limit number of inputs here.
// We still want to consume a lot of inputs to avoid creating only smaller denoms though.
// Knowing that each CTxIn is at least 148 B big, 400 inputs should take 400 x ~148 B = ~60 kB.
// This still leaves more than enough room for another data of typical MakeCollateralAmounts tx.
std::vector<CompactTallyItem> vecTally = mixingWallet.SelectCoinsGroupedByAddresses(false, false, true, 400);
if (vecTally.empty()) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::MakeCollateralAmounts -- SelectCoinsGroupedByAddresses can't find any inputs!\n");
return false;
}
// Start from the smallest balances first to consume tiny amounts and cleanup UTXO a bit
std::sort(vecTally.begin(), vecTally.end(), [](const CompactTallyItem& a, const CompactTallyItem& b) {
return a.nAmount < b.nAmount;
});
// First try to use only non-denominated funds
for (const auto& item : vecTally) {
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
if (!MakeCollateralAmounts(item, false)) continue;
return true;
}
// There should be at least some denominated funds we should be able to break in pieces to continue mixing
for (const auto& item : vecTally) {
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
if (!MakeCollateralAmounts(item, true)) continue;
return true;
}
// If we got here then something is terribly broken actually
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::MakeCollateralAmounts -- ERROR: Can't make collaterals!\n");
return false;
}
// Split up large inputs or create fee sized inputs
bool CCoinJoinClientSession::MakeCollateralAmounts(const CompactTallyItem& tallyItem, bool fTryDenominated)
{
AssertLockHeld(cs_main);
AssertLockHeld(mixingWallet.cs_wallet);
if (!CCoinJoinClientOptions::IsEnabled()) return false;
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
// Denominated input is always a single one, so we can check its amount directly and return early
if (!fTryDenominated && tallyItem.vecInputCoins.size() == 1 && CCoinJoin::IsDenominatedAmount(tallyItem.nAmount)) {
return false;
}
// Skip single inputs that can be used as collaterals already
if (tallyItem.vecInputCoins.size() == 1 && CCoinJoin::IsCollateralAmount(tallyItem.nAmount)) {
return false;
}
const auto pwallet = GetWallet(mixingWallet.GetName());
if (!pwallet) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- Couldn't get wallet pointer\n", __func__);
return false;
}
CTransactionBuilder txBuilder(pwallet, tallyItem);
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- Start %s\n", __func__, txBuilder.ToString());
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
// Skip way too tiny amounts. Smallest we want is minimum collateral amount in a one output tx
if (!txBuilder.CouldAddOutput(CCoinJoin::GetCollateralAmount())) {
return false;
}
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
int nCase{0}; // Just for debug logs
if (txBuilder.CouldAddOutputs({CCoinJoin::GetMaxCollateralAmount(), CCoinJoin::GetCollateralAmount()})) {
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
nCase = 1;
// <case1>, see TransactionRecord::decomposeTransaction
// Out1 == CCoinJoin::GetMaxCollateralAmount()
// Out2 >= CCoinJoin::GetCollateralAmount()
txBuilder.AddOutput(CCoinJoin::GetMaxCollateralAmount());
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
// Note, here we first add a zero amount output to get the remainder after all fees and then assign it
CTransactionBuilderOutput* out = txBuilder.AddOutput();
CAmount nAmountLeft = txBuilder.GetAmountLeft();
// If remainder is denominated add one duff to the fee
out->UpdateAmount(CCoinJoin::IsDenominatedAmount(nAmountLeft) ? nAmountLeft - 1 : nAmountLeft);
} else if (txBuilder.CouldAddOutputs({CCoinJoin::GetCollateralAmount(), CCoinJoin::GetCollateralAmount()})) {
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
nCase = 2;
// <case2>, see TransactionRecord::decomposeTransaction
// Out1 CCoinJoin::IsCollateralAmount()
// Out2 CCoinJoin::IsCollateralAmount()
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
// First add two outputs to get the available value after all fees
CTransactionBuilderOutput* out1 = txBuilder.AddOutput();
CTransactionBuilderOutput* out2 = txBuilder.AddOutput();
// Create two equal outputs from the available value. This adds one duff to the fee if txBuilder.GetAmountLeft() is odd.
CAmount nAmountOutputs = txBuilder.GetAmountLeft() / 2;
assert(CCoinJoin::IsCollateralAmount(nAmountOutputs));
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
out1->UpdateAmount(nAmountOutputs);
out2->UpdateAmount(nAmountOutputs);
} else { // still at least possible to add one CCoinJoin::GetCollateralAmount() output
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
nCase = 3;
// <case3>, see TransactionRecord::decomposeTransaction
// Out1 CCoinJoin::IsCollateralAmount()
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
// Out2 Skipped
CTransactionBuilderOutput* out = txBuilder.AddOutput();
out->UpdateAmount(txBuilder.GetAmountLeft());
assert(CCoinJoin::IsCollateralAmount(out->GetAmount()));
}
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- Done with case %d: %s\n", __func__, nCase, txBuilder.ToString());
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
assert(txBuilder.IsDust(txBuilder.GetAmountLeft()));
bilingual_str strResult;
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
if (!txBuilder.Commit(strResult)) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- Commit failed: %s\n", __func__, strResult.original);
return false;
}
coinJoinClientManagers.at(mixingWallet.GetName())->UpdatedSuccessBlock();
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- txid: %s\n", __func__, strResult.original);
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
return true;
}
bool CCoinJoinClientSession::CreateCollateralTransaction(CMutableTransaction& txCollateral, std::string& strReason)
{
auto locked_chain = mixingWallet.chain().lock();
LOCK(mixingWallet.cs_wallet);
std::vector<COutput> vCoins;
CCoinControl coin_control;
coin_control.nCoinType = CoinType::ONLY_COINJOIN_COLLATERAL;
mixingWallet.AvailableCoins(*locked_chain, vCoins, true, &coin_control);
if (vCoins.empty()) {
strReason = strprintf("%s requires a collateral transaction and could not locate an acceptable input!", gCoinJoinName);
return false;
}
const auto& output = vCoins.at(GetRandInt(vCoins.size()));
const CTxOut txout = output.tx->tx->vout[output.i];
txCollateral.vin.clear();
txCollateral.vin.emplace_back(output.tx->GetHash(), output.i);
txCollateral.vout.clear();
// pay collateral charge in fees
// NOTE: no need for protobump patch here,
// CCoinJoin::IsCollateralAmount in GetCollateralTxDSIn should already take care of this
if (txout.nValue >= CCoinJoin::GetCollateralAmount() * 2) {
// make our change address
CScript scriptChange;
CPubKey vchPubKey;
CReserveKey reservekey(&mixingWallet);
bool success = reservekey.GetReservedKey(vchPubKey, true);
assert(success); // should never fail, as we just unlocked
scriptChange = GetScriptForDestination(vchPubKey.GetID());
reservekey.KeepKey();
// return change
txCollateral.vout.emplace_back(txout.nValue - CCoinJoin::GetCollateralAmount(), scriptChange);
} else { // txout.nValue < CCoinJoin::GetCollateralAmount() * 2
// create dummy data output only and pay everything as a fee
txCollateral.vout.emplace_back(0, CScript() << OP_RETURN);
}
if (!SignSignature(mixingWallet, txout.scriptPubKey, txCollateral, 0, txout.nValue, SIGHASH_ALL)) {
strReason = "Unable to sign collateral transaction!";
return false;
}
return true;
}
// Create denominations by looping through inputs grouped by addresses
bool CCoinJoinClientSession::CreateDenominated(CAmount nBalanceToDenominate)
{
if (!CCoinJoinClientOptions::IsEnabled()) return false;
LOCK2(cs_main, mixingWallet.cs_wallet);
// NOTE: We do not allow txes larger than 100 kB, so we have to limit number of inputs here.
// We still want to consume a lot of inputs to avoid creating only smaller denoms though.
// Knowing that each CTxIn is at least 148 B big, 400 inputs should take 400 x ~148 B = ~60 kB.
// This still leaves more than enough room for another data of typical CreateDenominated tx.
std::vector<CompactTallyItem> vecTally = mixingWallet.SelectCoinsGroupedByAddresses(true, true, true, 400);
if (vecTally.empty()) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::CreateDenominated -- SelectCoinsGroupedByAddresses can't find any inputs!\n");
return false;
}
// Start from the largest balances first to speed things up by creating txes with larger/largest denoms included
std::sort(vecTally.begin(), vecTally.end(), [](const CompactTallyItem& a, const CompactTallyItem& b) {
return a.nAmount > b.nAmount;
});
bool fCreateMixingCollaterals = !mixingWallet.HasCollateralInputs();
for (const auto& item : vecTally) {
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
if (!CreateDenominated(nBalanceToDenominate, item, fCreateMixingCollaterals)) continue;
return true;
}
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::CreateDenominated -- failed!\n");
return false;
}
// Create denominations
bool CCoinJoinClientSession::CreateDenominated(CAmount nBalanceToDenominate, const CompactTallyItem& tallyItem, bool fCreateMixingCollaterals)
{
AssertLockHeld(cs_main);
AssertLockHeld(mixingWallet.cs_wallet);
if (!CCoinJoinClientOptions::IsEnabled()) return false;
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
// denominated input is always a single one, so we can check its amount directly and return early
if (tallyItem.vecInputCoins.size() == 1 && CCoinJoin::IsDenominatedAmount(tallyItem.nAmount)) {
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
return false;
}
const auto pwallet = GetWallet(mixingWallet.GetName());
if (!pwallet) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- Couldn't get wallet pointer\n", __func__);
return false;
}
CTransactionBuilder txBuilder(pwallet, tallyItem);
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- Start %s\n", __func__, txBuilder.ToString());
// ****** Add an output for mixing collaterals ************ /
if (fCreateMixingCollaterals && !txBuilder.AddOutput(CCoinJoin::GetMaxCollateralAmount())) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- Failed to add collateral output\n", __func__);
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
return false;
}
// ****** Add outputs for denoms ************ /
bool fAddFinal = true;
auto denoms = CCoinJoin::GetStandardDenominations();
std::map<CAmount, int> mapDenomCount;
for (auto nDenomValue : denoms) {
mapDenomCount.insert(std::pair<CAmount, int>(nDenomValue, mixingWallet.CountInputsWithAmount(nDenomValue)));
}
// Will generate outputs for the createdenoms up to coinjoinmaxdenoms per denom
// This works in the way creating PS denoms has traditionally worked, assuming enough funds,
// it will start with the smallest denom then create 11 of those, then go up to the next biggest denom create 11
// and repeat. Previously, once the largest denom was reached, as many would be created were created as possible and
// then any remaining was put into a change address and denominations were created in the same manner a block later.
// Now, in this system, so long as we don't reach COINJOIN_DENOM_OUTPUTS_THRESHOLD outputs the process repeats in
// the same transaction, creating up to nCoinJoinDenomsHardCap per denomination in a single transaction.
while (txBuilder.CouldAddOutput(CCoinJoin::GetSmallestDenomination()) && txBuilder.CountOutputs() < COINJOIN_DENOM_OUTPUTS_THRESHOLD) {
for (auto it = denoms.rbegin(); it != denoms.rend(); ++it) {
CAmount nDenomValue = *it;
auto currentDenomIt = mapDenomCount.find(nDenomValue);
int nOutputs = 0;
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
const auto& strFunc = __func__;
auto needMoreOutputs = [&]() {
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
if (txBuilder.CouldAddOutput(nDenomValue)) {
if (fAddFinal && nBalanceToDenominate > 0 && nBalanceToDenominate < nDenomValue) {
fAddFinal = false; // add final denom only once, only the smalest possible one
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- 1 - FINAL - nDenomValue: %f, nBalanceToDenominate: %f, nOutputs: %d, %s\n",
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
strFunc, (float) nDenomValue / COIN, (float) nBalanceToDenominate / COIN, nOutputs, txBuilder.ToString());
return true;
} else if (nBalanceToDenominate >= nDenomValue) {
return true;
}
}
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
return false;
};
// add each output up to 11 times or until it can't be added again or until we reach nCoinJoinDenomsGoal
while (needMoreOutputs() && nOutputs <= 10 && currentDenomIt->second < CCoinJoinClientOptions::GetDenomsGoal()) {
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
// Add output and subtract denomination amount
if (txBuilder.AddOutput(nDenomValue)) {
++nOutputs;
++currentDenomIt->second;
nBalanceToDenominate -= nDenomValue;
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- 1 - nDenomValue: %f, nBalanceToDenominate: %f, nOutputs: %d, %s\n",
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
__func__, (float) nDenomValue / COIN, (float) nBalanceToDenominate / COIN, nOutputs, txBuilder.ToString());
} else {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- 1 - Error: AddOutput failed for nDenomValue: %f, nBalanceToDenominate: %f, nOutputs: %d, %s\n",
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
__func__, (float) nDenomValue / COIN, (float) nBalanceToDenominate / COIN, nOutputs, txBuilder.ToString());
return false;
}
}
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
if (txBuilder.GetAmountLeft() == 0 || nBalanceToDenominate <= 0) break;
}
bool finished = true;
for (const auto it : mapDenomCount) {
// Check if this specific denom could use another loop, check that there aren't nCoinJoinDenomsGoal of this
// denom and that our nValueLeft/nBalanceToDenominate is enough to create one of these denoms, if so, loop again.
if (it.second < CCoinJoinClientOptions::GetDenomsGoal() && txBuilder.CouldAddOutput(it.first) && nBalanceToDenominate > 0) {
finished = false;
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- 1 - NOT finished - nDenomValue: %f, count: %d, nBalanceToDenominate: %f, %s\n",
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
__func__, (float) it.first / COIN, it.second, (float) nBalanceToDenominate / COIN, txBuilder.ToString());
break;
}
2021-07-19 12:39:22 +02:00
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- 1 - FINISHED - nDenomValue: %f, count: %d, nBalanceToDenominate: %f, %s\n",
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
__func__, (float) it.first / COIN, it.second, (float) nBalanceToDenominate / COIN, txBuilder.ToString());
}
if (finished) break;
}
// Now that nCoinJoinDenomsGoal worth of each denom have been created or the max number of denoms given the value of the input, do something with the remainder.
if (txBuilder.CouldAddOutput(CCoinJoin::GetSmallestDenomination()) && nBalanceToDenominate >= CCoinJoin::GetSmallestDenomination() && txBuilder.CountOutputs() < COINJOIN_DENOM_OUTPUTS_THRESHOLD) {
CAmount nLargestDenomValue = denoms.front();
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- 2 - Process remainder: %s\n", __func__, txBuilder.ToString());
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
auto countPossibleOutputs = [&](CAmount nAmount) -> int {
std::vector<CAmount> vecOutputs;
while (true) {
// Create a potential output
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
vecOutputs.push_back(nAmount);
if (!txBuilder.CouldAddOutputs(vecOutputs) || txBuilder.CountOutputs() + vecOutputs.size() > COINJOIN_DENOM_OUTPUTS_THRESHOLD) {
// If it's not possible to add it due to insufficient amount left or total number of outputs exceeds
// COINJOIN_DENOM_OUTPUTS_THRESHOLD drop the output again and stop trying.
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
vecOutputs.pop_back();
break;
}
}
return static_cast<int>(vecOutputs.size());
};
// Go big to small
for (auto nDenomValue : denoms) {
int nOutputs = 0;
// Number of denoms we can create given our denom and the amount of funds we have left
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
int denomsToCreateValue = countPossibleOutputs(nDenomValue);
// Prefer overshooting the target balance by larger denoms (hence `+1`) instead of a more
// accurate approximation by many smaller denoms. This is ok because when we get here we
// should have nCoinJoinDenomsGoal of each smaller denom already. Also, without `+1`
// we can end up in a situation when there is already nCoinJoinDenomsHardCap of smaller
// denoms, yet we can't mix the remaining nBalanceToDenominate because it's smaller than
// nDenomValue (and thus denomsToCreateBal == 0), so the target would never get reached
// even when there is enough funds for that.
int denomsToCreateBal = (nBalanceToDenominate / nDenomValue) + 1;
// Use the smaller value
int denomsToCreate = denomsToCreateValue > denomsToCreateBal ? denomsToCreateBal : denomsToCreateValue;
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- 2 - nBalanceToDenominate: %f, nDenomValue: %f, denomsToCreateValue: %d, denomsToCreateBal: %d\n",
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
__func__, (float) nBalanceToDenominate / COIN, (float) nDenomValue / COIN, denomsToCreateValue, denomsToCreateBal);
auto it = mapDenomCount.find(nDenomValue);
for (int i = 0; i < denomsToCreate; i++) {
// Never go above the cap unless it's the largest denom
if (nDenomValue != nLargestDenomValue && it->second >= CCoinJoinClientOptions::GetDenomsHardCap()) break;
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
// Increment helpers, add output and subtract denomination amount
if (txBuilder.AddOutput(nDenomValue)) {
nOutputs++;
it->second++;
nBalanceToDenominate -= nDenomValue;
} else {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- 2 - Error: AddOutput failed at %d/%d, %s\n", __func__, i + 1, denomsToCreate, txBuilder.ToString());
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
break;
}
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- 2 - nDenomValue: %f, nBalanceToDenominate: %f, nOutputs: %d, %s\n",
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
__func__, (float) nDenomValue / COIN, (float) nBalanceToDenominate / COIN, nOutputs, txBuilder.ToString());
if (txBuilder.CountOutputs() >= COINJOIN_DENOM_OUTPUTS_THRESHOLD) break;
}
if (txBuilder.CountOutputs() >= COINJOIN_DENOM_OUTPUTS_THRESHOLD) break;
}
}
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- 3 - nBalanceToDenominate: %f, %s\n", __func__, (float) nBalanceToDenominate / COIN, txBuilder.ToString());
for (const auto it : mapDenomCount) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- 3 - DONE - nDenomValue: %f, count: %d\n", __func__, (float) it.first / COIN, it.second);
}
// No reasons to create mixing collaterals if we can't create denoms to mix
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
if ((fCreateMixingCollaterals && txBuilder.CountOutputs() == 1) || txBuilder.CountOutputs() == 0) {
return false;
}
bilingual_str strResult;
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
if (!txBuilder.Commit(strResult)) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- Commit failed: %s\n", __func__, strResult.original);
return false;
}
// use the same nCachedLastSuccessBlock as for DS mixing to prevent race
coinJoinClientManagers.at(mixingWallet.GetName())->UpdatedSuccessBlock();
privatesend|wallet|qt: Improve calculations in CreateDenominated/MakeCollateralAmounts (#3657) * wallet: Add m_dust_feerate to CCoinControl / Use it in CreateTransaction * privatesend: Introduce CTransactionBuilder/CTransactionBuilderOutput Builder classes for transactions from type Inputs: Defined by CompactTallyItem Outputs: Simple outputs with lose reserve keys This takes fully takes care of fee calculations and makes sure calculations are the same like those happening when actually create the transaction with CreateTransaction. * privatesend: Improve amount/fee calculation in CreateDenominated * privatesend: Improve amount/fee calculation in MakeCollateralAmounts * qt: Fix decomposeTransaction's MakeCollateralAmounts detection Align it with the three cases in CPrivateSendClientSession::MakeCollateralAmounts * Refactor GetFee The fee rate is always coinControl.m_feerate, also it's not used outside so should be a private method * Simplify nBytesOutput calculations * Drop unused GetBytesOutput() * Make Clear(), GetBytesTotal() and GetAmountUsed() private * Drop unused GetCoinControl() * Make ToString() const * Refactor `CTransactionBuilder::Commit()` * Reorder cases in decomposeTransaction * Fix "finished" conditions in CreateDenominated * Fix typo * wallet|privatesend: Refactor CCoinControl's m_dust_feerate -> m_discard_feerate * privatesend: Drop unused member CTransactionBuilder::dustFeeRate * privatesend: Improve CTransactionBuilder's readability * privatesend: Make the static CTransactionBuilder::GetAmountLeft private * wallet: Recover previous code style * Update src/privatesend/privatesend-util.cpp Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * Tweak CTransactionBuilder to respect potential compact size diffs * Tweak GetFee param type * Trivial log/comments tweaks * privatesend: Fix countPossibleOutputs - Fix off by one issue - Respect max outputs threshold * privatesend: Use GetSizeOfCompactSizeDiff in CTransactionBuilder * Apply suggestions from code review Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> * privatesend: Rename TryAdd to CouldAdd in CTransactionBuilder * wallet: Reset m_discard_feerate in CCoinControl::SetNull * Respect `-paytxfee` and `settxfee` * privatesend: Check for denominated amount only where really required * qt: Remove obsolete IsCollateralAmount() checks * privatesend: Don't accept negative amounts in CTransactionBuilder * privatesend: Remove unused CConnman parameter * use emplace_back instead of push_back Signed-off-by: pasta <pasta@dashboost.org> * fix typos Signed-off-by: pasta <pasta@dashboost.org> * make GetAmount const Signed-off-by: pasta <pasta@dashboost.org> * privatesend: Explicit capture __func__ in needMoreOutputs lambda * privatesend: Update CTransactionBuilder::UpdateAmount * remove const on parameter in declaration Signed-off-by: pasta <pasta@dashboost.org> * handle unsigned int -> int conversions a bit better Signed-off-by: pasta <pasta@dashboost.org> * explicitly cast to int from unsigned int. estimateSmartFee handles it if negative Signed-off-by: pasta <pasta@dashboost.org> * Make CTransactionBuilderOutput::GetScript const Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> * privatesend: Update comments to follow doxygen * privatesend: Add class descriptions Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Co-authored-by: pasta <pasta@dashboost.org>
2020-09-01 17:27:33 +02:00
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::%s -- txid: %s\n", __func__, strResult.original);
return true;
}
void CCoinJoinClientSession::RelayIn(const CCoinJoinEntry& entry, CConnman& connman) const
{
if (!mixingMasternode) return;
connman.ForNode(mixingMasternode->pdmnState->addr, [&entry, &connman](CNode* pnode) {
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::RelayIn -- found master, relaying message to %s\n", pnode->addr.ToString());
CNetMsgMaker msgMaker(pnode->GetSendVersion());
connman.PushMessage(pnode, msgMaker.Make(NetMsgType::DSVIN, entry));
Backport Bitcoin PR#8085: p2p: Begin encapsulation (#1537) * net: move CBanDB and CAddrDB out of net.h/cpp This will eventually solve a circular dependency * net: Create CConnman to encapsulate p2p connections * net: Move socket binding into CConnman * net: move OpenNetworkConnection into CConnman * net: move ban and addrman functions into CConnman * net: Add oneshot functions to CConnman * net: move added node functions to CConnman * net: Add most functions needed for vNodes to CConnman * net: handle nodesignals in CConnman * net: Pass CConnection to wallet rather than using the global * net: Add rpc error for missing/disabled p2p functionality * net: Pass CConnman around as needed * gui: add NodeID to the peer table * net: create generic functor accessors and move vNodes to CConnman * net: move whitelist functions into CConnman * net: move nLastNodeId to CConnman * net: move nLocalHostNonce to CConnman This behavior seems to have been quite racy and broken. Move nLocalHostNonce into CNode, and check received nonces against all non-fully-connected nodes. If there's a match, assume we've connected to ourself. * net: move messageHandlerCondition to CConnman * net: move send/recv statistics to CConnman * net: move SendBufferSize/ReceiveFloodSize to CConnman * net: move nLocalServices/nRelevantServices to CConnman These are in-turn passed to CNode at connection time. This allows us to offer different services to different peers (or test the effects of doing so). * net: move semOutbound and semMasternodeOutbound to CConnman * net: SocketSendData returns written size * net: move max/max-outbound to CConnman * net: Pass best block known height into CConnman CConnman then passes the current best height into CNode at creation time. This way CConnman/CNode have no dependency on main for height, and the signals only move in one direction. This also helps to prevent identity leakage a tiny bit. Before this change, an attacker could theoretically make 2 connections on different interfaces. They would connect fully on one, and only establish the initial connection on the other. Once they receive a new block, they would relay it to your first connection, and immediately commence the version handshake on the second. Since the new block height is reflected immediately, they could attempt to learn whether the two connections were correlated. This is, of course, incredibly unlikely to work due to the small timings involved and receipt from other senders. But it doesn't hurt to lock-in nBestHeight at the time of connection, rather than letting the remote choose the time. * net: pass CClientUIInterface into CConnman * net: Drop StartNode/StopNode and use CConnman directly * net: Introduce CConnection::Options to avoid passing so many params * net: add nSendBufferMaxSize/nReceiveFloodSize to CConnection::Options * net: move vNodesDisconnected into CConnman * Made the ForEachNode* functions in src/net.cpp more pragmatic and self documenting * Convert ForEachNode* functions to take a templated function argument rather than a std::function to eliminate std::function overhead * net: move MAX_FEELER_CONNECTIONS into connman
2017-07-21 11:35:19 +02:00
return true;
});
}
void CCoinJoinClientSession::SetState(PoolState nStateNew)
{
LogPrint(BCLog::COINJOIN, "CCoinJoinClientSession::SetState -- nState: %d, nStateNew: %d\n", nState, nStateNew);
nState = nStateNew;
}
void CCoinJoinClientManager::UpdatedBlockTip(const CBlockIndex* pindex)
{
nCachedBlockHeight = pindex->nHeight;
LogPrint(BCLog::COINJOIN, "CCoinJoinClientManager::UpdatedBlockTip -- nCachedBlockHeight: %d\n", nCachedBlockHeight);
}
void CCoinJoinClientQueueManager::DoMaintenance()
{
if (!CCoinJoinClientOptions::IsEnabled()) return;
if (fMasternodeMode) return; // no client-side mixing on masternodes
if (!masternodeSync.IsBlockchainSynced() || ShutdownRequested()) return;
CheckQueue();
}
void CCoinJoinClientManager::DoMaintenance(CConnman& connman)
{
if (!CCoinJoinClientOptions::IsEnabled()) return;
2018-11-05 10:29:07 +01:00
if (fMasternodeMode) return; // no client-side mixing on masternodes
if (!masternodeSync.IsBlockchainSynced() || ShutdownRequested()) return;
static int nTick = 0;
static int nDoAutoNextRun = nTick + COINJOIN_AUTO_TIMEOUT_MIN;
nTick++;
CheckTimeout();
ProcessPendingDsaRequest(connman);
2018-11-05 10:29:07 +01:00
if (nDoAutoNextRun == nTick) {
DoAutomaticDenominating(connman);
nDoAutoNextRun = nTick + COINJOIN_AUTO_TIMEOUT_MIN + GetRandInt(COINJOIN_AUTO_TIMEOUT_MAX - COINJOIN_AUTO_TIMEOUT_MIN);
}
}
void CCoinJoinClientSession::GetJsonInfo(UniValue& obj) const
{
assert(obj.isObject());
if (mixingMasternode != nullptr) {
assert(mixingMasternode->pdmnState);
obj.pushKV("protxhash", mixingMasternode->proTxHash.ToString());
obj.pushKV("outpoint", mixingMasternode->collateralOutpoint.ToStringShort());
obj.pushKV("service", mixingMasternode->pdmnState->addr.ToString());
}
obj.pushKV("denomination", ValueFromAmount(CCoinJoin::DenominationToAmount(nSessionDenom)));
obj.pushKV("state", GetStateString());
obj.pushKV("entries_count", GetEntriesCount());
}
void CCoinJoinClientManager::GetJsonInfo(UniValue& obj) const
{
assert(obj.isObject());
obj.pushKV("running", IsMixing());
UniValue arrSessions(UniValue::VARR);
AssertLockNotHeld(cs_deqsessions);
LOCK(cs_deqsessions);
for (const auto& session : deqSessions) {
if (session.GetState() != POOL_STATE_IDLE) {
UniValue objSession(UniValue::VOBJ);
session.GetJsonInfo(objSession);
arrSessions.push_back(objSession);
}
}
obj.pushKV("sessions", arrSessions);
}
void DoCoinJoinMaintenance(CConnman& connman)
{
coinJoinClientQueueManager.DoMaintenance();
for (const auto& pair : coinJoinClientManagers) {
2020-07-16 14:23:58 +02:00
pair.second->DoMaintenance(connman);
}
}