dash/src/spork.cpp

469 lines
14 KiB
C++
Raw Normal View History

// Copyright (c) 2014-2023 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
2015-02-09 21:54:51 +01:00
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 <spork.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 <chainparams.h>
#include <consensus/params.h>
refactor: decouple db hooks from CFlatDB-based C*Manager objects, migrate to *Store structs (#5555) ## Motivation As highlighted in https://github.com/dashpay/dash-issues/issues/52, decoupling of `CFlatDB`-interacting components from managers of objects like `CGovernanceManager` and `CSporkManager` is a key task for achieving deglobalization of Dash-specific components. The design of `CFlatDB` as a flat database agent relies on hooking into the object's state its meant to load and store, using its (de)serialization routines and other miscellaneous functions (notably, without defining an interface) to achieve those ends. This approach was taken predominantly for components that want a single-file cache. Because of the method it uses to hook into the object (templates and the use of temporary objects), it explicitly prevented passing arguments into the object constructor, an explicit requirement for storing references to other components during construction. This, in turn, created an explicit dependency on those same components being available in the global context, which would block the backport of bitcoin#21866, a requirement for future backports meant to achieve parity in `assumeutxo` support. The design of these objects made no separation between persistent (i.e. cached) and ephemeral (i.e. generated/fetched during initialization or state transitions) data and the design of `CFlatDB` attempts to "clean" the database by breaching this separation and attempting to access this ephemeral data. This might be acceptable if it is contained within the manager itself, like `CSporkManager`'s `CheckAndRemove()` but is utterly unacceptable when it relies on other managers (that, as a reminder, are only accessible through the global state because of restrictions caused by existing design), like `CGovernanceManager`'s `UpdateCachesAndClean()`. This pull request aims to separate the `CFlatDB`-interacting portions of these managers into a struct, with `CFlatDB` interacting only with this struct, while the manager inherits the struct and manages load/store/update of the database through the `CFlatDB` instance initialized within its scope, though the instance only has knowledge of what is exposed through the limited parent struct. ## Additional information * As regards to existing behaviour, `CFlatDB` is written entirely as a header as it relies on templates to specialize itself for the object it hooks into. Attempting to split the logic and function definitions into separate files will require you to explicitly define template specializations, which is tedious. * `m_db` is defined as a pointer as you cannot instantiate a forward-declared template (see [this Stack Overflow answer](https://stackoverflow.com/a/12797282) for more information), which is done when defined as a member in the object scope. * The conditional cache flush predicating on RPC _not_ being in the warm-up state has been replaced with unconditional flushing of the database on object destruction (@UdjinM6, is this acceptable?) ## TODOs This is a list of things that aren't within the scope of this pull request but should be addressed in subsequent pull requests * [ ] Definition of an interface that `CFlatDB` stores are expected to implement * [ ] Lock annotations for all potential uses of members protected by the `cs` mutex in each manager object and store * [ ] Additional comments documenting what each function and member does * [ ] Deglobalization of affected managers --------- Co-authored-by: Kittywhiskers Van Gogh <63189531+kittywhiskers@users.noreply.github.com>
2023-09-24 16:50:21 +02:00
#include <flat-database.h>
#include <key_io.h>
#include <logging.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 <messagesigner.h>
#include <net.h>
#include <net_processing.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 <netmessagemaker.h>
#include <primitives/block.h>
#include <protocol.h>
#include <script/standard.h>
#include <timedata.h>
#include <util/message.h> // for MESSAGE_MAGIC
#include <util/ranges.h>
#include <util/string.h>
#include <validation.h>
2015-02-09 21:54:51 +01:00
#include <string>
2015-02-09 21:54:51 +01:00
refactor: decouple db hooks from CFlatDB-based C*Manager objects, migrate to *Store structs (#5555) ## Motivation As highlighted in https://github.com/dashpay/dash-issues/issues/52, decoupling of `CFlatDB`-interacting components from managers of objects like `CGovernanceManager` and `CSporkManager` is a key task for achieving deglobalization of Dash-specific components. The design of `CFlatDB` as a flat database agent relies on hooking into the object's state its meant to load and store, using its (de)serialization routines and other miscellaneous functions (notably, without defining an interface) to achieve those ends. This approach was taken predominantly for components that want a single-file cache. Because of the method it uses to hook into the object (templates and the use of temporary objects), it explicitly prevented passing arguments into the object constructor, an explicit requirement for storing references to other components during construction. This, in turn, created an explicit dependency on those same components being available in the global context, which would block the backport of bitcoin#21866, a requirement for future backports meant to achieve parity in `assumeutxo` support. The design of these objects made no separation between persistent (i.e. cached) and ephemeral (i.e. generated/fetched during initialization or state transitions) data and the design of `CFlatDB` attempts to "clean" the database by breaching this separation and attempting to access this ephemeral data. This might be acceptable if it is contained within the manager itself, like `CSporkManager`'s `CheckAndRemove()` but is utterly unacceptable when it relies on other managers (that, as a reminder, are only accessible through the global state because of restrictions caused by existing design), like `CGovernanceManager`'s `UpdateCachesAndClean()`. This pull request aims to separate the `CFlatDB`-interacting portions of these managers into a struct, with `CFlatDB` interacting only with this struct, while the manager inherits the struct and manages load/store/update of the database through the `CFlatDB` instance initialized within its scope, though the instance only has knowledge of what is exposed through the limited parent struct. ## Additional information * As regards to existing behaviour, `CFlatDB` is written entirely as a header as it relies on templates to specialize itself for the object it hooks into. Attempting to split the logic and function definitions into separate files will require you to explicitly define template specializations, which is tedious. * `m_db` is defined as a pointer as you cannot instantiate a forward-declared template (see [this Stack Overflow answer](https://stackoverflow.com/a/12797282) for more information), which is done when defined as a member in the object scope. * The conditional cache flush predicating on RPC _not_ being in the warm-up state has been replaced with unconditional flushing of the database on object destruction (@UdjinM6, is this acceptable?) ## TODOs This is a list of things that aren't within the scope of this pull request but should be addressed in subsequent pull requests * [ ] Definition of an interface that `CFlatDB` stores are expected to implement * [ ] Lock annotations for all potential uses of members protected by the `cs` mutex in each manager object and store * [ ] Additional comments documenting what each function and member does * [ ] Deglobalization of affected managers --------- Co-authored-by: Kittywhiskers Van Gogh <63189531+kittywhiskers@users.noreply.github.com>
2023-09-24 16:50:21 +02:00
const std::string SporkStore::SERIALIZATION_VERSION_STRING = "CSporkManager-Version-2";
std::optional<SporkValue> CSporkManager::SporkValueIfActive(SporkId nSporkID) const
{
AssertLockHeld(cs);
if (!mapSporksActive.count(nSporkID)) return std::nullopt;
{
LOCK(cs_mapSporksCachedValues);
if (auto it = mapSporksCachedValues.find(nSporkID); it != mapSporksCachedValues.end()) {
return {it->second};
}
}
// calc how many values we have and how many signers vote for every value
std::unordered_map<SporkValue, int> mapValueCounts;
for (const auto& [_, spork] : mapSporksActive.at(nSporkID)) {
mapValueCounts[spork.nValue]++;
if (mapValueCounts.at(spork.nValue) >= nMinSporkKeys) {
// nMinSporkKeys is always more than the half of the max spork keys number,
// so there is only one such value and we can stop here
{
LOCK(cs_mapSporksCachedValues);
mapSporksCachedValues[nSporkID] = spork.nValue;
}
return {spork.nValue};
}
}
return std::nullopt;
}
refactor: decouple db hooks from CFlatDB-based C*Manager objects, migrate to *Store structs (#5555) ## Motivation As highlighted in https://github.com/dashpay/dash-issues/issues/52, decoupling of `CFlatDB`-interacting components from managers of objects like `CGovernanceManager` and `CSporkManager` is a key task for achieving deglobalization of Dash-specific components. The design of `CFlatDB` as a flat database agent relies on hooking into the object's state its meant to load and store, using its (de)serialization routines and other miscellaneous functions (notably, without defining an interface) to achieve those ends. This approach was taken predominantly for components that want a single-file cache. Because of the method it uses to hook into the object (templates and the use of temporary objects), it explicitly prevented passing arguments into the object constructor, an explicit requirement for storing references to other components during construction. This, in turn, created an explicit dependency on those same components being available in the global context, which would block the backport of bitcoin#21866, a requirement for future backports meant to achieve parity in `assumeutxo` support. The design of these objects made no separation between persistent (i.e. cached) and ephemeral (i.e. generated/fetched during initialization or state transitions) data and the design of `CFlatDB` attempts to "clean" the database by breaching this separation and attempting to access this ephemeral data. This might be acceptable if it is contained within the manager itself, like `CSporkManager`'s `CheckAndRemove()` but is utterly unacceptable when it relies on other managers (that, as a reminder, are only accessible through the global state because of restrictions caused by existing design), like `CGovernanceManager`'s `UpdateCachesAndClean()`. This pull request aims to separate the `CFlatDB`-interacting portions of these managers into a struct, with `CFlatDB` interacting only with this struct, while the manager inherits the struct and manages load/store/update of the database through the `CFlatDB` instance initialized within its scope, though the instance only has knowledge of what is exposed through the limited parent struct. ## Additional information * As regards to existing behaviour, `CFlatDB` is written entirely as a header as it relies on templates to specialize itself for the object it hooks into. Attempting to split the logic and function definitions into separate files will require you to explicitly define template specializations, which is tedious. * `m_db` is defined as a pointer as you cannot instantiate a forward-declared template (see [this Stack Overflow answer](https://stackoverflow.com/a/12797282) for more information), which is done when defined as a member in the object scope. * The conditional cache flush predicating on RPC _not_ being in the warm-up state has been replaced with unconditional flushing of the database on object destruction (@UdjinM6, is this acceptable?) ## TODOs This is a list of things that aren't within the scope of this pull request but should be addressed in subsequent pull requests * [ ] Definition of an interface that `CFlatDB` stores are expected to implement * [ ] Lock annotations for all potential uses of members protected by the `cs` mutex in each manager object and store * [ ] Additional comments documenting what each function and member does * [ ] Deglobalization of affected managers --------- Co-authored-by: Kittywhiskers Van Gogh <63189531+kittywhiskers@users.noreply.github.com>
2023-09-24 16:50:21 +02:00
void SporkStore::Clear()
{
LOCK(cs);
mapSporksActive.clear();
mapSporksByHash.clear();
// sporkPubKeyID and sporkPrivKey should be set in init.cpp,
// we should not alter them here.
}
refactor: decouple db hooks from CFlatDB-based C*Manager objects, migrate to *Store structs (#5555) ## Motivation As highlighted in https://github.com/dashpay/dash-issues/issues/52, decoupling of `CFlatDB`-interacting components from managers of objects like `CGovernanceManager` and `CSporkManager` is a key task for achieving deglobalization of Dash-specific components. The design of `CFlatDB` as a flat database agent relies on hooking into the object's state its meant to load and store, using its (de)serialization routines and other miscellaneous functions (notably, without defining an interface) to achieve those ends. This approach was taken predominantly for components that want a single-file cache. Because of the method it uses to hook into the object (templates and the use of temporary objects), it explicitly prevented passing arguments into the object constructor, an explicit requirement for storing references to other components during construction. This, in turn, created an explicit dependency on those same components being available in the global context, which would block the backport of bitcoin#21866, a requirement for future backports meant to achieve parity in `assumeutxo` support. The design of these objects made no separation between persistent (i.e. cached) and ephemeral (i.e. generated/fetched during initialization or state transitions) data and the design of `CFlatDB` attempts to "clean" the database by breaching this separation and attempting to access this ephemeral data. This might be acceptable if it is contained within the manager itself, like `CSporkManager`'s `CheckAndRemove()` but is utterly unacceptable when it relies on other managers (that, as a reminder, are only accessible through the global state because of restrictions caused by existing design), like `CGovernanceManager`'s `UpdateCachesAndClean()`. This pull request aims to separate the `CFlatDB`-interacting portions of these managers into a struct, with `CFlatDB` interacting only with this struct, while the manager inherits the struct and manages load/store/update of the database through the `CFlatDB` instance initialized within its scope, though the instance only has knowledge of what is exposed through the limited parent struct. ## Additional information * As regards to existing behaviour, `CFlatDB` is written entirely as a header as it relies on templates to specialize itself for the object it hooks into. Attempting to split the logic and function definitions into separate files will require you to explicitly define template specializations, which is tedious. * `m_db` is defined as a pointer as you cannot instantiate a forward-declared template (see [this Stack Overflow answer](https://stackoverflow.com/a/12797282) for more information), which is done when defined as a member in the object scope. * The conditional cache flush predicating on RPC _not_ being in the warm-up state has been replaced with unconditional flushing of the database on object destruction (@UdjinM6, is this acceptable?) ## TODOs This is a list of things that aren't within the scope of this pull request but should be addressed in subsequent pull requests * [ ] Definition of an interface that `CFlatDB` stores are expected to implement * [ ] Lock annotations for all potential uses of members protected by the `cs` mutex in each manager object and store * [ ] Additional comments documenting what each function and member does * [ ] Deglobalization of affected managers --------- Co-authored-by: Kittywhiskers Van Gogh <63189531+kittywhiskers@users.noreply.github.com>
2023-09-24 16:50:21 +02:00
CSporkManager::CSporkManager() :
m_db{std::make_unique<db_type>("sporks.dat", "magicSporkCache")}
{
}
CSporkManager::~CSporkManager()
{
if (!is_valid) return;
m_db->Store(*this);
}
bool CSporkManager::LoadCache()
{
assert(m_db != nullptr);
is_valid = m_db->Load(*this);
if (is_valid) {
CheckAndRemove();
}
return is_valid;
}
2018-09-26 16:15:02 +02:00
void CSporkManager::CheckAndRemove()
{
LOCK(cs);
refactor: decouple db hooks from CFlatDB-based C*Manager objects, migrate to *Store structs (#5555) ## Motivation As highlighted in https://github.com/dashpay/dash-issues/issues/52, decoupling of `CFlatDB`-interacting components from managers of objects like `CGovernanceManager` and `CSporkManager` is a key task for achieving deglobalization of Dash-specific components. The design of `CFlatDB` as a flat database agent relies on hooking into the object's state its meant to load and store, using its (de)serialization routines and other miscellaneous functions (notably, without defining an interface) to achieve those ends. This approach was taken predominantly for components that want a single-file cache. Because of the method it uses to hook into the object (templates and the use of temporary objects), it explicitly prevented passing arguments into the object constructor, an explicit requirement for storing references to other components during construction. This, in turn, created an explicit dependency on those same components being available in the global context, which would block the backport of bitcoin#21866, a requirement for future backports meant to achieve parity in `assumeutxo` support. The design of these objects made no separation between persistent (i.e. cached) and ephemeral (i.e. generated/fetched during initialization or state transitions) data and the design of `CFlatDB` attempts to "clean" the database by breaching this separation and attempting to access this ephemeral data. This might be acceptable if it is contained within the manager itself, like `CSporkManager`'s `CheckAndRemove()` but is utterly unacceptable when it relies on other managers (that, as a reminder, are only accessible through the global state because of restrictions caused by existing design), like `CGovernanceManager`'s `UpdateCachesAndClean()`. This pull request aims to separate the `CFlatDB`-interacting portions of these managers into a struct, with `CFlatDB` interacting only with this struct, while the manager inherits the struct and manages load/store/update of the database through the `CFlatDB` instance initialized within its scope, though the instance only has knowledge of what is exposed through the limited parent struct. ## Additional information * As regards to existing behaviour, `CFlatDB` is written entirely as a header as it relies on templates to specialize itself for the object it hooks into. Attempting to split the logic and function definitions into separate files will require you to explicitly define template specializations, which is tedious. * `m_db` is defined as a pointer as you cannot instantiate a forward-declared template (see [this Stack Overflow answer](https://stackoverflow.com/a/12797282) for more information), which is done when defined as a member in the object scope. * The conditional cache flush predicating on RPC _not_ being in the warm-up state has been replaced with unconditional flushing of the database on object destruction (@UdjinM6, is this acceptable?) ## TODOs This is a list of things that aren't within the scope of this pull request but should be addressed in subsequent pull requests * [ ] Definition of an interface that `CFlatDB` stores are expected to implement * [ ] Lock annotations for all potential uses of members protected by the `cs` mutex in each manager object and store * [ ] Additional comments documenting what each function and member does * [ ] Deglobalization of affected managers --------- Co-authored-by: Kittywhiskers Van Gogh <63189531+kittywhiskers@users.noreply.github.com>
2023-09-24 16:50:21 +02:00
if (setSporkPubKeyIDs.empty()) return;
2018-09-26 16:15:02 +02:00
for (auto itActive = mapSporksActive.begin(); itActive != mapSporksActive.end();) {
auto itSignerPair = itActive->second.begin();
while (itSignerPair != itActive->second.end()) {
bool fHasValidSig = setSporkPubKeyIDs.find(itSignerPair->first) != setSporkPubKeyIDs.end() &&
itSignerPair->second.CheckSignature(itSignerPair->first);
if (!fHasValidSig) {
mapSporksByHash.erase(itSignerPair->second.GetHash());
itActive->second.erase(itSignerPair++);
continue;
}
++itSignerPair;
}
if (itActive->second.empty()) {
mapSporksActive.erase(itActive++);
continue;
2018-09-26 16:15:02 +02:00
}
++itActive;
}
for (auto itByHash = mapSporksByHash.begin(); itByHash != mapSporksByHash.end();) {
bool found = false;
for (const auto& signer : setSporkPubKeyIDs) {
if (itByHash->second.CheckSignature(signer)) {
found = true;
break;
2018-09-26 16:15:02 +02:00
}
}
if (!found) {
mapSporksByHash.erase(itByHash++);
continue;
}
2018-09-26 16:15:02 +02:00
++itByHash;
}
}
PeerMsgRet CSporkManager::ProcessMessage(CNode& peer, CConnman& connman, PeerManager& peerman, std::string_view msg_type, CDataStream& vRecv)
2015-02-09 21:54:51 +01:00
{
if (msg_type == NetMsgType::SPORK) {
return ProcessSpork(peer, peerman, vRecv);
} else if (msg_type == NetMsgType::GETSPORKS) {
ProcessGetSporks(peer, connman);
}
return {};
}
2015-02-09 21:54:51 +01:00
PeerMsgRet CSporkManager::ProcessSpork(const CNode& peer, PeerManager& peerman, CDataStream& vRecv)
{
CSporkMessage spork;
vRecv >> spork;
2015-02-09 21:54:51 +01:00
uint256 hash = spork.GetHash();
std::string strLogMsg;
{
LOCK(cs_main);
EraseObjectRequest(peer.GetId(), CInv(MSG_SPORK, hash));
strLogMsg = strprintf("SPORK -- hash: %s id: %d value: %10d peer=%d", hash.ToString(), spork.nSporkID, spork.nValue, peer.GetId());
}
if (spork.nTimeSigned > GetAdjustedTime() + 2 * 60 * 60) {
LogPrint(BCLog::SPORK, "CSporkManager::ProcessSpork -- ERROR: too far into the future\n");
return tl::unexpected{100};
}
auto opt_keyIDSigner = spork.GetSignerKeyID();
if (opt_keyIDSigner == std::nullopt || WITH_LOCK(cs, return !setSporkPubKeyIDs.count(*opt_keyIDSigner))) {
LogPrint(BCLog::SPORK, "CSporkManager::ProcessSpork -- ERROR: invalid signature\n");
return tl::unexpected{100};
}
auto keyIDSigner = *opt_keyIDSigner;
{
LOCK(cs); // make sure to not lock this together with cs_main
if (mapSporksActive.count(spork.nSporkID)) {
if (mapSporksActive[spork.nSporkID].count(keyIDSigner)) {
if (mapSporksActive[spork.nSporkID][keyIDSigner].nTimeSigned >= spork.nTimeSigned) {
LogPrint(BCLog::SPORK, "%s seen\n", strLogMsg);
return {};
} else {
LogPrintf("%s updated\n", strLogMsg);
}
2015-02-09 21:54:51 +01:00
} else {
LogPrintf("%s new signer\n", strLogMsg);
2015-02-09 21:54:51 +01:00
}
} else {
LogPrintf("%s new\n", strLogMsg);
2015-02-09 21:54:51 +01:00
}
}
2015-02-09 21:54:51 +01:00
{
LOCK(cs); // make sure to not lock this together with cs_main
mapSporksByHash[hash] = spork;
mapSporksActive[spork.nSporkID][keyIDSigner] = spork;
// Clear cached values on new spork being processed
WITH_LOCK(cs_mapSporksCachedActive, mapSporksCachedActive.erase(spork.nSporkID));
WITH_LOCK(cs_mapSporksCachedValues, mapSporksCachedValues.erase(spork.nSporkID));
2015-02-09 21:54:51 +01:00
}
spork.Relay(peerman);
return {};
}
void CSporkManager::ProcessGetSporks(CNode& peer, CConnman& connman)
{
LOCK(cs); // make sure to not lock this together with cs_main
for (const auto& pair : mapSporksActive) {
for (const auto& signerSporkPair : pair.second) {
Merge #17785: p2p: Unify Send and Receive protocol versions ddefb5c0b759950942ac03f28c43b548af7b4033 p2p: Use the greatest common version in peer logic (Hennadii Stepanov) e084d45562b94827b3a7873895882fcaae9f4d48 p2p: Remove SetCommonVersion() from VERACK handler (Hennadii Stepanov) 8d2026796a6f7add0c2cda9806e759817d1eae6f refactor: Rename local variable nSendVersion (Hennadii Stepanov) e9a6d8b13b0558b17cdafbd32fd2663b4138ff11 p2p: Unify Send and Receive protocol versions (Hennadii Stepanov) Pull request description: On master (6fef85bfa3cd7f76e83b8b57f9e4acd63eb664ec) `CNode` has two members to keep protocol version: - `nRecvVersion` for received messages - `nSendVersion` for messages to send After exchanging with `VERSION` and `VERACK` messages via protocol version `INIT_PROTO_VERSION`, both nodes set `nRecvVersion` _and_ `nSendVersion` to _the same_ value which is the greatest common protocol version. This PR: - replaces two `CNode` members, `nRecvVersion` `nSendVersion`, with `m_greatest_common_version` - removes duplicated getter and setter There is no change in behavior on the P2P network. ACKs for top commit: jnewbery: ACK ddefb5c0b759950942ac03f28c43b548af7b4033 naumenkogs: ACK ddefb5c0b759950942ac03f28c43b548af7b4033 fjahr: Code review ACK ddefb5c0b759950942ac03f28c43b548af7b4033 amitiuttarwar: code review but untested ACK ddefb5c0b7 benthecarman: utACK `ddefb5c` Tree-SHA512: 5305538dbaa5426b923b0afd20bdef4f248d310855d1d78427210c00716c67b7cb691515c421716b6157913e453076e293b10ff5fd2cd26a8e5375d42da7809d
2020-06-05 09:22:53 +02:00
connman.PushMessage(&peer, CNetMsgMaker(peer.GetCommonVersion()).Make(NetMsgType::SPORK, signerSporkPair.second));
}
}
2015-02-09 21:54:51 +01:00
}
bool CSporkManager::UpdateSpork(PeerManager& peerman, SporkId nSporkID, SporkValue nValue)
{
CSporkMessage spork(nSporkID, nValue, GetAdjustedTime());
{
LOCK(cs);
if (!spork.Sign(sporkPrivKey)) {
LogPrintf("CSporkManager::%s -- ERROR: signing failed for spork %d\n", __func__, nSporkID);
return false;
}
auto opt_keyIDSigner = spork.GetSignerKeyID();
if (opt_keyIDSigner == std::nullopt || !setSporkPubKeyIDs.count(*opt_keyIDSigner)) {
LogPrintf("CSporkManager::UpdateSpork: failed to find keyid for private key\n");
return false;
}
LogPrintf("CSporkManager::%s -- signed %d %s\n", __func__, nSporkID, spork.GetHash().ToString());
mapSporksByHash[spork.GetHash()] = spork;
mapSporksActive[nSporkID][*opt_keyIDSigner] = spork;
// Clear cached values on new spork being processed
WITH_LOCK(cs_mapSporksCachedActive, mapSporksCachedActive.erase(spork.nSporkID));
WITH_LOCK(cs_mapSporksCachedValues, mapSporksCachedValues.erase(spork.nSporkID));
}
spork.Relay(peerman);
return true;
}
bool CSporkManager::IsSporkActive(SporkId nSporkID) const
2015-02-09 21:54:51 +01:00
{
// If nSporkID is cached, and the cached value is true, then return early true
{
LOCK(cs_mapSporksCachedActive);
if (auto it = mapSporksCachedActive.find(nSporkID); it != mapSporksCachedActive.end() && it->second) {
return true;
}
}
SporkValue nSporkValue = GetSporkValue(nSporkID);
// Get time is somewhat costly it looks like
bool ret = nSporkValue < GetAdjustedTime();
// Only cache true values
if (ret) {
LOCK(cs_mapSporksCachedActive);
mapSporksCachedActive[nSporkID] = ret;
}
return ret;
2015-02-09 21:54:51 +01:00
}
SporkValue CSporkManager::GetSporkValue(SporkId nSporkID) const
2015-02-11 15:47:21 +01:00
{
// Harden all sporks on Mainnet
if (!Params().IsTestChain()) {
switch (nSporkID) {
case SPORK_21_QUORUM_ALL_CONNECTED:
return 1;
default:
return 0;
}
}
LOCK(cs);
if (auto opt_sporkValue = SporkValueIfActive(nSporkID)) {
return *opt_sporkValue;
}
2015-02-11 15:47:21 +01:00
if (auto optSpork = ranges::find_if_opt(sporkDefs,
[&nSporkID](const auto& sporkDef){return sporkDef.sporkId == nSporkID;})) {
return optSpork->defaultValue;
} else {
LogPrint(BCLog::SPORK, "CSporkManager::GetSporkValue -- Unknown Spork ID %d\n", nSporkID);
return -1;
}
2015-02-11 15:47:21 +01:00
}
SporkId CSporkManager::GetSporkIDByName(std::string_view strName)
2015-02-12 05:05:09 +01:00
{
if (auto optSpork = ranges::find_if_opt(sporkDefs,
[&strName](const auto& sporkDef){return sporkDef.name == strName;})) {
return optSpork->sporkId;
}
2015-08-02 23:59:28 +02:00
LogPrint(BCLog::SPORK, "CSporkManager::GetSporkIDByName -- Unknown Spork name '%s'\n", strName);
return SPORK_INVALID;
2015-02-12 05:05:09 +01:00
}
std::optional<CSporkMessage> CSporkManager::GetSporkByHash(const uint256& hash) const
{
LOCK(cs);
if (const auto it = mapSporksByHash.find(hash); it != mapSporksByHash.end())
return {it->second};
return std::nullopt;
}
bool CSporkManager::SetSporkAddress(const std::string& strAddress)
{
LOCK(cs);
Merge #11117: Prepare for non-Base58 addresses (#3294) * Merge #11117: Prepare for non-Base58 addresses 864cd2787 Move CBitcoinAddress to base58.cpp (Pieter Wuille) 5c8ff0d44 Introduce wrappers around CBitcoinAddress (Pieter Wuille) Pull request description: This patch removes the need for the intermediary Base58 type `CBitcoinAddress`, by providing {`Encode`,`Decode`,`IsValid`}`Destination` functions that directly operate on the conversion between `std::string`s and `CTxDestination`. As a side, it also fixes a number of indentation issues, and removes probably several unnecessary implicit `CTxDestination`<->`CBitcoinAddress` conversions. This change is far from complete. In follow-ups I'd like to: * Split off the specific address and key encoding logic from base58.h, and move it to a address.h or so. * Replace `CTxDestination` with a non-`boost::variant` version (which can be more efficient as `boost::variant` allocates everything on the heap, and remove the need for `boost::get<...>` and `IsValidDestination` calls everywhere). * Do the same for `CBitcoinSecret`, `CBitcoinExtKey`, and `CBitcoinExtPubKey`. However, I've tried to keep this patch to be minimally invasive, but still enough to support non-Base58 addresses. Perhaps a smaller patch is possible to hack Bech32 support into `CBitcoinAddress`, but I would consider that a move in the wrong direction. Tree-SHA512: c2c77ffb57caeadf2429b1c2562ce60e8c7be8aa9f8e51b591f354b6b441162625b2efe14c023a1ae485cf2ed417263afa35c892891dfaa7844e7fbabccab85e * CBitcoinAddress -> EncodeDestination in providertx.h Signed-off-by: Pasta <pasta@dashboost.org> * more CBitcoinAddress -> EncodeDestination in providertx.h Signed-off-by: Pasta <pasta@dashboost.org> * more CBitcoinAddress -> EncodeDestination in providertx.h Signed-off-by: Pasta <pasta@dashboost.org> * more CBitcoinAddress -> EncodeDestination in providertx.h Signed-off-by: Pasta <pasta@dashboost.org> * fix CBitcoinAddress GetKeyID check Signed-off-by: Pasta <pasta@dashboost.org> * fix providertx.cpp Signed-off-by: Pasta <pasta@dashboost.org> * hopefully fix governance-classes.cpp Signed-off-by: Pasta <pasta@dashboost.org> * partially fix governance-validators.cpp, unable to resolve "address.IsScript()" Signed-off-by: Pasta <pasta@dashboost.org> * partially fix governance-classes.cpp, unable to resolve "address.IsScript()" Signed-off-by: Pasta <pasta@dashboost.org> * fix governance-classes.h Signed-off-by: Pasta <pasta@dashboost.org> * DecodeTransaction -> DecodeDestination, fix governance-validators.cpp Signed-off-by: Pasta <pasta@dashboost.org> * More fixes for 3294 * Move GetIndexKey into rpc/misc.cpp near getAddressesFromParams No need to have it in base58.cpp anymore as this is only used in getAddressesFromParams Co-authored-by: Wladimir J. van der Laan <laanwj@gmail.com> Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com> Co-authored-by: Alexander Block <ablock84@gmail.com>
2020-01-22 11:35:04 +01:00
CTxDestination dest = DecodeDestination(strAddress);
const PKHash* pkhash = std::get_if<PKHash>(&dest);
if (!pkhash) {
LogPrintf("CSporkManager::SetSporkAddress -- Failed to parse spork address\n");
return false;
}
setSporkPubKeyIDs.insert(ToKeyID(*pkhash));
return true;
}
bool CSporkManager::SetMinSporkKeys(int minSporkKeys)
{
LOCK(cs);
if (int maxKeysNumber = setSporkPubKeyIDs.size(); (minSporkKeys <= maxKeysNumber / 2) || (minSporkKeys > maxKeysNumber)) {
LogPrintf("CSporkManager::SetMinSporkKeys -- Invalid min spork signers number: %d\n", minSporkKeys);
return false;
}
nMinSporkKeys = minSporkKeys;
return true;
}
bool CSporkManager::SetPrivKey(const std::string& strPrivKey)
2015-02-09 21:54:51 +01:00
{
CKey key;
CPubKey pubKey;
if (!CMessageSigner::GetKeysFromSecret(strPrivKey, key, pubKey)) {
LogPrintf("CSporkManager::SetPrivKey -- Failed to parse private key\n");
return false;
}
2015-02-09 21:54:51 +01:00
LOCK(cs);
if (setSporkPubKeyIDs.find(pubKey.GetID()) == setSporkPubKeyIDs.end()) {
LogPrintf("CSporkManager::SetPrivKey -- New private key does not belong to spork addresses\n");
return false;
}
if (!CSporkMessage().Sign(key)) {
LogPrintf("CSporkManager::SetPrivKey -- Test signing failed\n");
2015-02-09 21:54:51 +01:00
return false;
}
// Test signing successful, proceed
LogPrintf("CSporkManager::SetPrivKey -- Successfully initialized as spork signer\n");
sporkPrivKey = key;
return true;
2015-02-09 21:54:51 +01:00
}
refactor: decouple db hooks from CFlatDB-based C*Manager objects, migrate to *Store structs (#5555) ## Motivation As highlighted in https://github.com/dashpay/dash-issues/issues/52, decoupling of `CFlatDB`-interacting components from managers of objects like `CGovernanceManager` and `CSporkManager` is a key task for achieving deglobalization of Dash-specific components. The design of `CFlatDB` as a flat database agent relies on hooking into the object's state its meant to load and store, using its (de)serialization routines and other miscellaneous functions (notably, without defining an interface) to achieve those ends. This approach was taken predominantly for components that want a single-file cache. Because of the method it uses to hook into the object (templates and the use of temporary objects), it explicitly prevented passing arguments into the object constructor, an explicit requirement for storing references to other components during construction. This, in turn, created an explicit dependency on those same components being available in the global context, which would block the backport of bitcoin#21866, a requirement for future backports meant to achieve parity in `assumeutxo` support. The design of these objects made no separation between persistent (i.e. cached) and ephemeral (i.e. generated/fetched during initialization or state transitions) data and the design of `CFlatDB` attempts to "clean" the database by breaching this separation and attempting to access this ephemeral data. This might be acceptable if it is contained within the manager itself, like `CSporkManager`'s `CheckAndRemove()` but is utterly unacceptable when it relies on other managers (that, as a reminder, are only accessible through the global state because of restrictions caused by existing design), like `CGovernanceManager`'s `UpdateCachesAndClean()`. This pull request aims to separate the `CFlatDB`-interacting portions of these managers into a struct, with `CFlatDB` interacting only with this struct, while the manager inherits the struct and manages load/store/update of the database through the `CFlatDB` instance initialized within its scope, though the instance only has knowledge of what is exposed through the limited parent struct. ## Additional information * As regards to existing behaviour, `CFlatDB` is written entirely as a header as it relies on templates to specialize itself for the object it hooks into. Attempting to split the logic and function definitions into separate files will require you to explicitly define template specializations, which is tedious. * `m_db` is defined as a pointer as you cannot instantiate a forward-declared template (see [this Stack Overflow answer](https://stackoverflow.com/a/12797282) for more information), which is done when defined as a member in the object scope. * The conditional cache flush predicating on RPC _not_ being in the warm-up state has been replaced with unconditional flushing of the database on object destruction (@UdjinM6, is this acceptable?) ## TODOs This is a list of things that aren't within the scope of this pull request but should be addressed in subsequent pull requests * [ ] Definition of an interface that `CFlatDB` stores are expected to implement * [ ] Lock annotations for all potential uses of members protected by the `cs` mutex in each manager object and store * [ ] Additional comments documenting what each function and member does * [ ] Deglobalization of affected managers --------- Co-authored-by: Kittywhiskers Van Gogh <63189531+kittywhiskers@users.noreply.github.com>
2023-09-24 16:50:21 +02:00
std::string SporkStore::ToString() const
{
LOCK(cs);
return strprintf("Sporks: %llu", mapSporksActive.size());
}
uint256 CSporkMessage::GetHash() const
{
return SerializeHash(*this);
}
uint256 CSporkMessage::GetSignatureHash() const
{
CHashWriter s(SER_GETHASH, 0);
s << nSporkID;
s << nValue;
s << nTimeSigned;
return s.GetHash();
}
bool CSporkMessage::Sign(const CKey& key)
2015-02-09 21:54:51 +01:00
{
if (!key.IsValid()) {
LogPrintf("CSporkMessage::Sign -- signing key is not valid\n");
return false;
}
CKeyID pubKeyId = key.GetPubKey().GetID();
2015-02-09 21:54:51 +01:00
// Harden Spork6 so that it is active on testnet and no other networks
if (std::string strError; Params().NetworkIDString() == CBaseChainParams::TESTNET) {
uint256 hash = GetSignatureHash();
2015-02-09 21:54:51 +01:00
if (!CHashSigner::SignHash(hash, key, vchSig)) {
LogPrintf("CSporkMessage::Sign -- SignHash() failed\n");
return false;
}
if (!CHashSigner::VerifyHash(hash, pubKeyId, vchSig, strError)) {
LogPrintf("CSporkMessage::Sign -- VerifyHash() failed, error: %s\n", strError);
return false;
}
} else {
std::string strMessage = ToString(nSporkID) + ToString(nValue) + ToString(nTimeSigned);
if (!CMessageSigner::SignMessage(strMessage, vchSig, key)) {
LogPrintf("CSporkMessage::Sign -- SignMessage() failed\n");
return false;
}
if (!CMessageSigner::VerifyMessage(pubKeyId, vchSig, strMessage, strError)) {
LogPrintf("CSporkMessage::Sign -- VerifyMessage() failed, error: %s\n", strError);
return false;
}
2015-02-09 21:54:51 +01:00
}
return true;
}
bool CSporkMessage::CheckSignature(const CKeyID& pubKeyId) const
2015-02-09 21:54:51 +01:00
{
// Harden Spork6 so that it is active on testnet and no other networks
if (std::string strError; Params().NetworkIDString() == CBaseChainParams::TESTNET) {
uint256 hash = GetSignatureHash();
if (!CHashSigner::VerifyHash(hash, pubKeyId, vchSig, strError)) {
2020-01-28 11:04:47 +01:00
LogPrint(BCLog::SPORK, "CSporkMessage::CheckSignature -- VerifyHash() failed, error: %s\n", strError);
return false;
}
} else {
std::string strMessage = ToString(nSporkID) + ToString(nValue) + ToString(nTimeSigned);
if (!CMessageSigner::VerifyMessage(pubKeyId, vchSig, strMessage, strError)) {
LogPrint(BCLog::SPORK, "CSporkMessage::CheckSignature -- VerifyMessage() failed, error: %s\n", strError);
return false;
}
2015-02-09 21:54:51 +01:00
}
return true;
2015-02-09 21:54:51 +01:00
}
std::optional<CKeyID> CSporkMessage::GetSignerKeyID() const
{
CPubKey pubkeyFromSig;
// Harden Spork6 so that it is active on testnet and no other networks
if (Params().NetworkIDString() == CBaseChainParams::TESTNET) {
if (!pubkeyFromSig.RecoverCompact(GetSignatureHash(), vchSig)) {
return std::nullopt;
}
} else {
std::string strMessage = ToString(nSporkID) + ToString(nValue) + ToString(nTimeSigned);
CHashWriter ss(SER_GETHASH, 0);
ss << MESSAGE_MAGIC;
ss << strMessage;
if (!pubkeyFromSig.RecoverCompact(ss.GetHash(), vchSig)) {
return std::nullopt;
}
}
return {pubkeyFromSig.GetID()};
}
void CSporkMessage::Relay(PeerManager& peerman) const
2015-02-09 21:54:51 +01:00
{
CInv inv(MSG_SPORK, GetHash());
peerman.RelayInv(inv);
2015-04-03 00:51:08 +02:00
}