Files
dragonx/src/asyncrpcoperation.h
DanS 81f803948c hygiene: Phase 6 (partial) — fix 7 verified bugs + quick-wins + dedup
From the Phase-6 structural scoping: land the verified behavioral bugs and
the safe quick-wins/dedups now; the large refactors (monolith splits, ~180
header globals) and consensus-adjacent items stay deferred. Built clean;
self-mined; verifychain=true.

BUGS (verified by reading the code):
- net.cpp CNode::Ban: a braceless `if (subNet.Match(...))` left
  `pnode->fDisconnect = true;` OUTSIDE the guard, so banning any one subnet
  marked EVERY connected peer for disconnect (dropped the whole peer set).
  Wrapped the two statements in braces. (LIVE, high severity.)
- rpcdump.cpp importwallet: the `!fGood -> throw "Error adding some keys"`
  check was trapped inside the `if (fRescan)` block, so importwallet with
  rescan=false silently reported success when key import failed. Hoisted the
  check before the rescan branch and cleaned the garbled braces/indentation.
- wallet.cpp CommitTransaction: ignored AddToWallet()'s return, so a failed
  disk-persist of a just-signed spend was swallowed while the tx broadcast.
  Now logs a hard error on failure.
- hush_nSPV_fullnode.h: the UTXOS branch declared `uint8_t filter` while the
  twin TXIDS branch uses `uint32_t filter`; dragon_rwnum switches on
  sizeof(filter), so the utxos path parsed only 1 of 4 wire filter bytes.
  Widened to uint32_t.
- asyncrpcoperation_sweep.cpp: LogPrintf("%s ... %s", one-arg) read a missing
  vararg; added the __func__ argument.
- rpcdump.cpp importprivkey: inner `auto secret_key` shadowed the outer
  uint8_t and changed the type into DecodeCustomSecret; dropped the shadow.
- rpcdump.cpp getrescaninfo: char[8] + sprintf("%.4f") overflows when the
  ratio >= 10.0 (transient reorg); widened to char[16] + snprintf.

QUICK WINS: removed the duplicate DRAGON_MAXSCRIPTSIZE #define; pinned the
dead HUSH3-branch NOTARISATION_SCAN_LIMIT_BLOCKS to 1440; fixed init typos
(fRequestShutdown, RPC warmup).

DEDUP: extracted the 19-line try/catch error-mapping block — copy-pasted
identically into all six async operations — into
AsyncRPCOperation::set_error_from_current_exception(), so the mapping is
edited in one place. Behavior-identical (verified all six blocks were byte-
identical first).

Deferred (endorsed by the scoping, better as their own PRs): addrman Select_
dedup, the pow.cpp powLimit helper (consensus file), the miner CreateNewBlock
lock-asymmetry, the wallet monolith splits, and the ~180-global / consensus-
retarget / Komodo-heritage work.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-27 15:55:00 -05:00

174 lines
5.5 KiB
C++

// Copyright (c) 2016 The Zcash developers
// Copyright (c) 2016-2024 The Hush developers
// Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
/******************************************************************************
* Copyright © 2014-2019 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* SuperNET software, including this file may be copied, modified, propagated *
* or distributed except according to the terms contained in the LICENSE file *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
#ifndef ASYNCRPCOPERATION_H
#define ASYNCRPCOPERATION_H
#include <string>
#include <atomic>
#include <map>
#include <chrono>
#include <memory>
#include <thread>
#include <utility>
#include <future>
#include <univalue.h>
using namespace std;
/**
* AsyncRPCOperation objects are submitted to the AsyncRPCQueue for processing.
*
* To subclass AsyncRPCOperation, implement the main() method.
* Update the operation status as work is underway and completes.
* If main() can be interrupted, implement the cancel() method.
*/
typedef std::string AsyncRPCOperationId;
typedef enum class operationStateEnum {
READY = 0,
EXECUTING,
CANCELLED,
FAILED,
SUCCESS
} OperationStatus;
class AsyncRPCOperation {
public:
AsyncRPCOperation();
virtual ~AsyncRPCOperation();
// You must implement this method in your subclass.
virtual void main();
// Override this method if you can interrupt execution of main() in your subclass.
void cancel();
// Getters and setters
OperationStatus getState() const {
return state_.load();
}
AsyncRPCOperationId getId() const {
return id_;
}
int64_t getCreationTime() const {
return creation_time_;
}
// Override this method to add data to the default status object.
virtual UniValue getStatus() const;
UniValue getError() const;
UniValue getResult() const;
std::string getStateAsString() const;
int getErrorCode() const {
std::lock_guard<std::mutex> guard(lock_);
return error_code_;
}
std::string getErrorMessage() const {
std::lock_guard<std::mutex> guard(lock_);
return error_message_;
}
bool isCancelled() const {
return OperationStatus::CANCELLED == getState();
}
bool isExecuting() const {
return OperationStatus::EXECUTING == getState();
}
bool isReady() const {
return OperationStatus::READY == getState();
}
bool isFailed() const {
return OperationStatus::FAILED == getState();
}
bool isSuccess() const {
return OperationStatus::SUCCESS == getState();
}
protected:
// The state_ is atomic because only it can be mutated externally.
// For example, the user initiates a shut down of the application, which closes
// the AsyncRPCQueue, which in turn invokes cancel() on all operations.
// The member variables below are protected rather than private in order to
// allow subclasses of AsyncRPCOperation the ability to access and update
// internal state. Currently, all operations are executed in a single-thread
// by a single worker.
mutable std::mutex lock_; // lock on this when read/writing non-atomics
UniValue result_;
int error_code_;
std::string error_message_;
std::atomic<OperationStatus> state_;
std::chrono::time_point<std::chrono::system_clock> start_time_, end_time_;
void start_execution_clock();
void stop_execution_clock();
void set_state(OperationStatus state) {
this->state_.store(state);
}
void set_error_code(int errorCode) {
std::lock_guard<std::mutex> guard(lock_);
this->error_code_ = errorCode;
}
void set_error_message(std::string errorMessage) {
std::lock_guard<std::mutex> guard(lock_);
this->error_message_ = errorMessage;
}
// Map the in-flight (rethrown) exception to error_code_/error_message_. Called from
// every async op's main() catch(...) so the UniValue/runtime/logic/exception mapping
// lives in one place instead of being copy-pasted into all six operations.
void set_error_from_current_exception();
void set_result(UniValue v) {
std::lock_guard<std::mutex> guard(lock_);
this->result_ = v;
}
private:
// Derived classes should write their own copy constructor and assignment operators
AsyncRPCOperation(const AsyncRPCOperation& orig);
AsyncRPCOperation& operator=( const AsyncRPCOperation& other );
// Initialized in the operation constructor, never to be modified again.
AsyncRPCOperationId id_;
int64_t creation_time_;
};
#endif /* ASYNCRPCOPERATION_H */