Files
triangles_v5/src/qt/walletmodel.cpp
T
sami7777 7d62e34868 Harden network security, fix moneysupply tracking, version system overhaul (v5.8.0)
- Fix moneysupply calculation in FastImportBlockFile and ConnectBlock assumevalid path
- Route bootstrap downloads through Tor SOCKS proxy (no more clearnet leaks)
- Remove hardcoded clearnet fallback IP from bootstrap
- Fix snprintf missing argument in walletmodel.cpp narration key (UB/crash)
- Fix potential null deref from db_strerror() in rpcwallet.cpp
- Filter non-.onion addresses from HTTPS seed list parser
- Add periodic re-seeding when node has 0 outbound peers
- Make clientversion.h single source of truth for version display string
- Remove redundant DISPLAY_VERSION macros from version.h
- Update README: max supply 2,222,222, CMake build instructions, Tor-only config

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 19:26:12 -07:00

676 lines
21 KiB
C++

#include "walletmodel.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include "transactiontablemodel.h"
#include "ui_interface.h"
#include "wallet.h"
#include "walletdb.h" // for BackupWallet
#include "base58.h"
#include "main.h"
#include "tor/onion_v3.h"
#include <QSet>
#include <QTimer>
#include <QMutexLocker>
static const int MODEL_UPDATE_BATCH_THRESHOLD = 128;
static const int MODEL_UPDATE_BATCH_DELAY_MS = 250;
static const int MODEL_FULL_REFRESH_MIN_INTERVAL_MS = 1500;
WalletModel::WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent) :
QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0),
transactionTableModel(0),
cachedBalance(0), cachedStake(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0),
cachedNumTransactions(0),
cachedEncryptionStatus(Unencrypted),
cachedNumBlocks(0),
transactionNotificationFlushQueued(false),
fullTransactionRefreshQueued(false),
transactionSyncing(false),
transactionNotificationTimer(0),
lastFullTransactionRefreshTime(0)
{
addressTableModel = new AddressTableModel(wallet, this);
transactionTableModel = new TransactionTableModel(wallet, this);
// This timer will be fired repeatedly to update the balance
pollTimer = new QTimer(this);
connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged()));
pollTimer->start(MODEL_UPDATE_DELAY);
transactionNotificationTimer = new QTimer(this);
transactionNotificationTimer->setSingleShot(true);
connect(transactionNotificationTimer, SIGNAL(timeout()), this, SLOT(flushTransactionNotifications()));
subscribeToCoreSignals();
}
WalletModel::~WalletModel()
{
unsubscribeFromCoreSignals();
}
qint64 WalletModel::getBalance() const
{
return wallet->GetBalance();
}
qint64 WalletModel::getUnconfirmedBalance() const
{
return wallet->GetUnconfirmedBalance();
}
qint64 WalletModel::getStake() const
{
return wallet->GetStake();
}
qint64 WalletModel::getImmatureBalance() const
{
return wallet->GetImmatureBalance();
}
int WalletModel::getNumTransactions() const
{
int numTransactions = 0;
{
LOCK(wallet->cs_wallet);
numTransactions = wallet->mapWallet.size();
}
return numTransactions;
}
bool WalletModel::isTransactionSyncing() const
{
return transactionSyncing;
}
void WalletModel::updateStatus()
{
EncryptionStatus newEncryptionStatus = getEncryptionStatus();
if(cachedEncryptionStatus != newEncryptionStatus)
emit encryptionStatusChanged(newEncryptionStatus);
}
void WalletModel::pollBalanceChanged()
{
if(nBestHeight != cachedNumBlocks)
{
// Balance and number of transactions might have changed.
// Only update cachedNumBlocks AFTER a successful balance check,
// otherwise a TRY_LOCK failure loses the update permanently.
if(checkBalanceChanged())
cachedNumBlocks = nBestHeight;
}
}
bool WalletModel::checkBalanceChanged()
{
// Get all balances in a single lock acquisition + single pass.
// Uses TRY_LOCK internally - if cs_wallet is busy (block processing),
// skip this cycle. The timer will retry in 2.5 seconds.
int64_t newBalance = 0, newStake = 0, newUnconfirmedBalance = 0, newImmatureBalance = 0;
if (!wallet->GetAllBalances(newBalance, newStake, newUnconfirmedBalance, newImmatureBalance))
return false;
if(cachedBalance != newBalance || cachedStake != newStake || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance)
{
cachedBalance = newBalance;
cachedStake = newStake;
cachedUnconfirmedBalance = newUnconfirmedBalance;
cachedImmatureBalance = newImmatureBalance;
emit balanceChanged(newBalance, newStake, newUnconfirmedBalance, newImmatureBalance);
}
return true;
}
void WalletModel::updateTransaction(const QString &hash, int status)
{
queueTransactionUpdate(hash, status);
}
void WalletModel::queueTransactionUpdate(const QString &hash, int status)
{
bool shouldScheduleFlush = false;
{
QMutexLocker locker(&transactionNotificationMutex);
int mergedStatus = status;
QMap<QString, int>::iterator it = queuedTransactionNotifications.find(hash);
if (it != queuedTransactionNotifications.end())
{
// Preserve insert/delete semantics when multiple updates arrive
// for the same transaction before the UI thread drains the queue.
if (it.value() == CT_DELETED || status == CT_DELETED)
mergedStatus = CT_DELETED;
else if (it.value() == CT_NEW || status == CT_NEW)
mergedStatus = CT_NEW;
else
mergedStatus = CT_UPDATED;
it.value() = mergedStatus;
}
else
{
queuedTransactionNotifications.insert(hash, mergedStatus);
}
if (IsInitialBlockDownload() || queuedTransactionNotifications.size() >= MODEL_UPDATE_BATCH_THRESHOLD)
fullTransactionRefreshQueued = true;
if (!transactionNotificationFlushQueued)
{
transactionNotificationFlushQueued = true;
shouldScheduleFlush = true;
}
}
if (shouldScheduleFlush)
QMetaObject::invokeMethod(this, "startTransactionNotificationTimer", Qt::QueuedConnection);
}
void WalletModel::startTransactionNotificationTimer()
{
if (transactionNotificationTimer)
transactionNotificationTimer->start(MODEL_UPDATE_BATCH_DELAY_MS);
}
void WalletModel::flushTransactionNotifications()
{
QMap<QString, int> pendingNotifications;
bool refreshAll = false;
bool shouldRescheduleRefresh = false;
{
QMutexLocker locker(&transactionNotificationMutex);
pendingNotifications.swap(queuedTransactionNotifications);
refreshAll = fullTransactionRefreshQueued;
fullTransactionRefreshQueued = false;
transactionNotificationFlushQueued = false;
}
const bool shouldSync = refreshAll ||
IsInitialBlockDownload() ||
pendingNotifications.size() >= MODEL_UPDATE_BATCH_THRESHOLD;
if (transactionSyncing != shouldSync)
{
transactionSyncing = shouldSync;
emit transactionSyncStateChanged(transactionSyncing);
}
if(transactionTableModel)
{
if (refreshAll)
{
const qint64 now = GetTimeMillis();
if (transactionSyncing &&
lastFullTransactionRefreshTime != 0 &&
now - lastFullTransactionRefreshTime < MODEL_FULL_REFRESH_MIN_INTERVAL_MS)
{
QMutexLocker locker(&transactionNotificationMutex);
fullTransactionRefreshQueued = true;
if (!transactionNotificationFlushQueued)
{
transactionNotificationFlushQueued = true;
shouldRescheduleRefresh = true;
}
}
else
{
transactionTableModel->refreshWallet();
lastFullTransactionRefreshTime = now;
}
}
else
{
for (QMap<QString, int>::const_iterator it = pendingNotifications.begin(); it != pendingNotifications.end(); ++it)
transactionTableModel->updateTransaction(it.key(), it.value());
}
}
if (shouldRescheduleRefresh && transactionNotificationTimer)
transactionNotificationTimer->start(MODEL_FULL_REFRESH_MIN_INTERVAL_MS);
bool stillPending = false;
int queuedNotificationCount = 0;
{
QMutexLocker locker(&transactionNotificationMutex);
stillPending = transactionNotificationFlushQueued || !queuedTransactionNotifications.isEmpty();
queuedNotificationCount = queuedTransactionNotifications.size();
}
if (!transactionSyncing && pendingNotifications.size() >= MODEL_UPDATE_BATCH_THRESHOLD)
{
transactionSyncing = true;
emit transactionSyncStateChanged(true);
}
if (transactionSyncing && !IsInitialBlockDownload() && !stillPending)
{
transactionSyncing = false;
emit transactionSyncStateChanged(false);
}
const int pendingNotificationCount = transactionSyncing
? pendingNotifications.size() + queuedNotificationCount
: queuedNotificationCount;
emit transactionSyncProgressChanged(transactionSyncing, pendingNotificationCount);
// Don't call checkBalanceChanged() here - it does LOCK(cs_wallet) + iterates
// all wallet transactions, blocking the UI thread. The pollBalanceChanged()
// timer already handles balance updates every 2.5 seconds with TRY_LOCK.
// Same for getNumTransactions() - use cached count from the transaction model
// to avoid another LOCK(cs_wallet) on the UI thread.
if(transactionTableModel)
{
int newNumTransactions = transactionTableModel->rowCount(QModelIndex());
if(cachedNumTransactions != newNumTransactions)
{
cachedNumTransactions = newNumTransactions;
emit numTransactionsChanged(newNumTransactions);
}
}
}
void WalletModel::updateAddressBook(const QString &address, const QString &label, bool isMine, int status)
{
if(addressTableModel)
addressTableModel->updateEntry(address, label, isMine, status);
}
bool WalletModel::validateAddress(const QString &address)
{
std::string sAddr = address.toStdString();
// Accept V3 .onion addresses (56-char base32 + ".onion" = 62 chars)
if (sAddr.size() == 62 && sAddr.substr(sAddr.size() - 6) == ".onion")
return CTorV3Service::ValidateOnionAddress(sAddr);
CTrianglesAddress addressParsed(sAddr);
return addressParsed.IsValid();
}
WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, const CCoinControl *coinControl)
{
qint64 total = 0;
QSet<QString> setAddress;
QString hex;
if(recipients.empty())
{
return OK;
}
// Pre-check input data for validity
foreach(const SendCoinsRecipient &rcp, recipients)
{
if(!validateAddress(rcp.address))
{
return InvalidAddress;
}
setAddress.insert(rcp.address);
if(rcp.amount <= 0)
{
return InvalidAmount;
}
total += rcp.amount;
}
if(recipients.size() > setAddress.size())
{
return DuplicateAddress;
}
int64_t nBalance = 0;
std::vector<COutput> vCoins;
wallet->AvailableCoins(vCoins, true, coinControl);
for (const COutput& out : vCoins)
nBalance += out.tx->vout[out.i].nValue;
if(total > nBalance)
{
return AmountExceedsBalance;
}
if((total + nTransactionFee) > nBalance)
{
return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
}
std::map<int, std::string> mapStealthNarr;
{
LOCK2(cs_main, wallet->cs_wallet);
CWalletTx wtx;
// Sendmany
std::vector<std::pair<CScript, int64_t> > vecSend;
foreach(const SendCoinsRecipient &rcp, recipients)
{
std::string sAddr = rcp.address.toStdString();
CScript scriptPubKey;
scriptPubKey.SetDestination(CTrianglesAddress(sAddr).Get());
vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
if (rcp.narration.length() > 0)
{
std::string sNarr = rcp.narration.toStdString();
if (sNarr.length() > 24)
{
printf("Narration is too long.\n");
return NarrationTooLong;
};
std::vector<uint8_t> vNarr(sNarr.c_str(), sNarr.c_str() + sNarr.length());
std::vector<uint8_t> vNDesc;
vNDesc.resize(2);
vNDesc[0] = 'n';
vNDesc[1] = 'p';
CScript scriptN = CScript() << OP_RETURN << vNDesc << OP_RETURN << vNarr;
vecSend.push_back(make_pair(scriptN, 0));
}
}
CReserveKey keyChange(wallet);
int64_t nFeeRequired = 0;
bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, coinControl);
std::map<int, std::string>::iterator it;
for (it = mapStealthNarr.begin(); it != mapStealthNarr.end(); ++it)
{
char key[64];
if (snprintf(key, sizeof(key), "n_%u", it->first) < 1)
{
printf("CreateStealthTransaction(): Error creating narration key.");
continue;
};
wtx.mapValue[key] = it->second;
};
if(!fCreated)
{
// NOTE: Potential edge case in fee calculation. The term "collisions" is unclear
// from original comment - may refer to transaction conflicts or UTXO selection issues.
// Consider reviewing Bitcoin Core's current implementation of this balance check.
if((total + nFeeRequired) > nBalance)
{
return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
}
return TransactionCreationFailed;
}
if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
{
return Aborted;
}
if(!wallet->CommitTransaction(wtx, keyChange))
{
return TransactionCommitFailed;
}
hex = QString::fromStdString(wtx.GetHash().GetHex());
}
// Add addresses / update labels that we've sent to to the address book
foreach(const SendCoinsRecipient &rcp, recipients)
{
std::string strAddress = rcp.address.toStdString();
CTxDestination dest = CTrianglesAddress(strAddress).Get();
std::string strLabel = rcp.label.toStdString();
{
LOCK(wallet->cs_wallet);
std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest);
// Check if we have a new address or an updated label
if (mi == wallet->mapAddressBook.end() || mi->second != strLabel)
{
wallet->SetAddressBookName(dest, strLabel);
};
//};
}
}
return SendCoinsReturn(OK, 0, hex);
}
OptionsModel *WalletModel::getOptionsModel()
{
return optionsModel;
}
AddressTableModel *WalletModel::getAddressTableModel()
{
return addressTableModel;
}
TransactionTableModel *WalletModel::getTransactionTableModel()
{
return transactionTableModel;
}
WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const
{
if(!wallet->IsCrypted())
{
return Unencrypted;
}
else if(wallet->IsLocked())
{
return Locked;
}
else
{
return Unlocked;
}
}
bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase)
{
if(encrypted)
{
// Encrypt
return wallet->EncryptWallet(passphrase);
}
else
{
// Decrypt -- TODO; not supported yet
return false;
}
}
bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase)
{
if(locked)
{
// Lock
return wallet->Lock();
}
else
{
// Unlock
return wallet->Unlock(passPhrase);
}
}
bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass)
{
bool retval;
{
LOCK(wallet->cs_wallet);
wallet->Lock(); // Make sure wallet is locked before attempting pass change
retval = wallet->ChangeWalletPassphrase(oldPass, newPass);
}
return retval;
}
bool WalletModel::backupWallet(const QString &filename)
{
return BackupWallet(*wallet, filename.toLocal8Bit().data());
}
// Handlers for core signals
static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet)
{
OutputDebugStringF("NotifyKeyStoreStatusChanged\n");
QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection);
}
static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)
{
OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CTrianglesAddress(address).ToString().c_str(), label.c_str(), isMine, status);
QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(CTrianglesAddress(address).ToString())),
Q_ARG(QString, QString::fromStdString(label)),
Q_ARG(bool, isMine),
Q_ARG(int, status));
}
static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status)
{
OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status);
walletmodel->queueTransactionUpdate(QString::fromStdString(hash.GetHex()), status);
}
void WalletModel::subscribeToCoreSignals()
{
// Connect signals to wallet
wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
}
void WalletModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from wallet
wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
}
// WalletModel::UnlockContext implementation
WalletModel::UnlockContext WalletModel::requestUnlock()
{
bool was_locked = getEncryptionStatus() == Locked;
if ((!was_locked) && fWalletUnlockStakingOnly)
{
setWalletLocked(true);
was_locked = getEncryptionStatus() == Locked;
}
if(was_locked)
{
// Request UI to unlock wallet
emit requireUnlock();
}
// If wallet is still locked, unlock was failed or cancelled, mark context as invalid
bool valid = getEncryptionStatus() != Locked;
return UnlockContext(this, valid, was_locked && !fWalletUnlockStakingOnly);
}
WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock):
wallet(wallet),
valid(valid),
relock(relock)
{
}
WalletModel::UnlockContext::~UnlockContext()
{
if(valid && relock)
{
wallet->setWalletLocked(true);
}
}
void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
{
// Transfer context; old object no longer relocks wallet
*this = rhs;
rhs.relock = false;
}
bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
{
return wallet->GetPubKey(address, vchPubKeyOut);
}
// returns a list of COutputs from COutPoints
void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs)
{
for (const COutPoint& outpoint : vOutpoints)
{
if (!wallet->mapWallet.count(outpoint.hash)) continue;
int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain();
if (nDepth < 0) continue;
COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth);
vOutputs.push_back(out);
}
}
// AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address)
void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const
{
std::vector<COutput> vCoins;
wallet->AvailableCoins(vCoins);
std::vector<COutPoint> vLockedCoins;
// add locked coins
for (const COutPoint& outpoint : vLockedCoins)
{
if (!wallet->mapWallet.count(outpoint.hash)) continue;
int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain();
if (nDepth < 0) continue;
COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth);
vCoins.push_back(out);
}
for (const COutput& out : vCoins)
{
COutput cout = out;
while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0]))
{
if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break;
cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0);
}
CTxDestination address;
if(!ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address)) continue;
mapCoins[CTrianglesAddress(address).ToString().c_str()].push_back(out);
}
}
bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const
{
return false;
}
void WalletModel::lockCoin(COutPoint& output)
{
return;
}
void WalletModel::unlockCoin(COutPoint& output)
{
return;
}
void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts)
{
return;
}