Compare commits

...

17 Commits

Author SHA1 Message Date
Krystie 175abcd8a4 test: ResetChainDBStatics() helper to fix chaindb_wipe test isolation
The chaindb_wipe test suite runs after chaindb_backend_selection and
rocksdb_wrapper, both of which leave the process-wide static g_rocksdb
(and on some paths the leveldb txdb singleton) alive. A leaked
g_rocksdb means the next test that does MakeChainDB('cr+') may get a
path that the prior test's open handle is still serving — leading to
the test operating on stale state and the on-disk wipe having no
effect. The H1 crashed_migration_marker_triggers_retry test
specifically could not bootstrap a fresh txleveldb/ for the migration
because the leveldb handle from the prior test was still bound.

This is the same class of bug as W2 (live LevelDB iterator outliving
the DB close) but at the test binary's process-lifetime scale: a live
DB handle from a prior test leaks into the next test and the on-disk
wipe is a no-op.

Fix: add a ResetChainDBStatics() helper that explicitly opens + closes
both backends (in create-if-missing mode so it works whether or not a
prior test left a DB on disk) and then wipes the on-disk chain DB
directories. Call it at the top of every chaindb_wipe test.

Before: 2/4 chaindb_wipe tests passing (H1 retry, H4 happy path) due
to the static-state leak. The crashes were also producing spurious
SIGABRTs at process exit from the static VersionSet assertion.

After: 20/20 chaindb_runtime tests pass, 3/3 chaindb_equivalence,
14/14 snapshotnet.

One file, +52 lines, no production code changes.
2026-07-02 01:38:18 -07:00
Krystie 6cadf7f496 chaindb: W2 iterator-scoping + H4 marker-verify + W1 INADDR_ANY
Three fixes for the chain-DB migration path on real chain data.
All three were uncovered when running the full DNS2 2.2M-block chain
end-to-end; the existing 18 unit tests passed because they exercised
small fixtures, never the real migration entry point.

W2 (root cause): chaindb_migrate.cpp — scope the source.NewIterator()
inside an inner block so it's destroyed BEFORE source.Close(). Live
LevelDB iterators hold a Version ref; closing the DB with one alive
trips the dummy_versions_.next_ == &dummy_versions_ assertion in
leveldb::VersionSet::~VersionSet (version_set.cc:755), aborting the
daemon after verification but before the marker is removed. This
explains the original H4 symptom: the daemon died in the gap between
'verified' and 'fs::remove', and Release builds hid it by compiling
asserts out. The H1 retry path's static-state issue in the test
binary is the same bug at process exit. In-loop failures now break
out with fCopyOK=false and are handled after the iterator dies.

H4 (defense in depth): chaindb_migrate.cpp — keep the verify-and-fail
hardening even though W2 fixes the cause. Use the non-throwing
error_code overload, fs::exists verify after remove, single 100ms
retry (Windows AV/indexer transient locks), hard-fail strError if
the marker still survives. Operator-visible failure beats silent
re-migration time bomb. The H4 invariant: a successful migration
never leaves the marker on disk.

W1: init.cpp — Lookup('0.0.0.0', addrBind, GetListenPort(), false)
replaced with direct CService construction from in_addr{htonl(INADDR_ANY)}.
This was the bug that prevented fc7ad5b from ever starting on
SAMI-PC; Windows getaddrinfo doesn't always map the literal '0.0.0.0'
string to INADDR_ANY.

Test: chaindb_runtime_tests.cpp — adds marker_removed_after_successful_migration
which exercises the real MaybeMigrateLevelDbToRocksDb() end-to-end on
the happy path. Complements the existing
crashed_migration_marker_triggers_retry (retry path). This is the
gap that hid the original bug: no test went through the production
entry point on the happy path.

Runtime verification: full DNS2 chain state (txleveldb 1.1GB +
blk0001.dat 942MB, 6.77M records) migrated end-to-end. MIGRATION_INCOMPLETE
absent from disk after. Reopened rocksdb reads back cleanly via
getblockcount / LoadBlockIndex.

Three files, 152 insertions, 27 deletions, build clean, CI ready.
2026-07-02 01:29:03 -07:00
Krystie f9d1723f6e qt: HD wallet status indicator in status bar
Add a [HD] label next to the lock icon that shows whether the
wallet has a BIP39 HD seed active:
  - Red (#f26522, TRI brand color) when HD is enabled
  - Grey (#555555) when wallet is non-HD (legacy key pool)

Tooltip on hover explains what HD means and what the user must
back up to be able to restore the wallet.

Wired through a new updateHDStatus() slot that reads the
public WalletModel::hdEnabled() accessor and is called when
the wallet model is set. Lives in the icon cluster of the
status bar; the .onion and .b32.i2p address text sits in a
separate group on the right, so no crowding.

Closes the visible-state gap: the wallet already supported
HD seeds (BIP39/BIP32) and had a hdseeddialog, but there was
no visual confirmation of HD status anywhere in the UI.
2026-07-01 21:32:58 -07:00
Krystie 35f524ff34 test: H1 crashed-migration marker retry test (M4 marker-write)
Adds a Boost test that pre-creates a rocksdb/ dir with a
MIGRATION_INCOMPLETE marker and verifies the init path:
1. Detects the marker
2. Refuses to open the rocksdb/ dir as live state
3. Re-runs the migration

Also exercises the M4 marker flush+verify path: marker is on
disk only during an in-progress migration and removed on success.

This test was in the H1/H2/H3/M4 patch but never committed;
folding it in here so the test surface matches the audit doc.
2026-07-01 21:32:46 -07:00
Krystie fc7ad5bb69 rocksdb: apply T010 review fixes (H1/H2/H3/M4) + CF routing disabled
H1: init.cpp now detects crashed migrations (MIGRATION_INCOMPLETE marker)
    and retries instead of opening a partial RocksDB. Refuses to start if
    the marker persists after migration attempt.
H2: LevelDB ExistsRaw now returns false for keys deleted in the active
    batch, matching ReadRaw and the RocksDB backend. Fixes latent
    cross-backend consensus split in intra-batch spend checks.
H3: All RocksDB close paths now go through close_rocksdb() which
    destroys CF handles before deleting the DB. Fixes RocksDB assertion
    / UB on shutdown and version-reset.
M4: Migration marker write is now flushed + verified (refuses to start
    migration if marker can't be written).

CF routing permanently disabled: GetCF() always returns nullptr (default
column family). The read path (NewIterator, LoadBlockIndex) only iterates
the default CF, so writes routed to per-prefix CFs were invisible to scans.
This is why -chaindb=rocksdb compiled clean but was never runtime-valid.
Existing CF-enabled DBs still open (handles retained for cleanup) but no
routing occurs. CF-aware iteration is a future follow-up.

txdb-factory: RocksDB is now the default backend (was still leveldb).
Tests updated for RocksDB-as-default expectations.

From Claude's ROCKSDB-T010-REVIEW-2026-07-01 audit on E:\repos\triangles.
2026-07-01 16:09:25 -07:00
Krystie a70019263d wallet: add BIP39 passphrase support throughout HD lifecycle
hdPassphrase was hardcoded to empty string in DeriveHDKey, meaning users
who set a BIP39 passphrase during seed creation would derive different
addresses after restoration. This adds proper passphrase storage,
encryption, and decryption alongside the existing mnemonic handling:

- wallet.h: hdPassphrase + vchCryptedHDPassphrase + hdPassphraseIV fields
- wallet.cpp: Lock/Unlock/EncryptWallet/SetHDSeed all handle passphrase
  with the same encrypt/decrypt lifecycle as the mnemonic
- DeriveHDKey now passes hdPassphrase to DeriveTriangles (not hardcoded )
- walletdb.h: WriteHDPassphrase/WriteHDCryptedPassphrase/EraseHDPassphrase
- walletdb.cpp: ReadKeyValue handles hdpassphrase/hdcpassphrase records
- rpcwallet.cpp: hdnew/hdshow show passphrase_used + warnings

Also: i2p.cpp hardens I2P private key file permissions to owner-only.

From Claude's uncommitted work on E:\repos\triangles (SAMI-PC). The rest
of Claude's modernization (Boost removal, RPC rewrite, RocksDB default,
SQLite wallet) was already committed to master in bfdb399 and follow-ups.
2026-07-01 14:19:42 -07:00
Krystie ac0adfea15 snapshot loader: build txindex from blk0001.dat after extraction
A v3 snapshot carries the UTXO set and raw block data (blk0001.dat) but
does NOT rebuild the per-tx index (txindex) that maps CTransaction hashes
to CDiskTxPos. Without it, any new PoS block referencing a pre-snapshot
transaction fails CheckProofOfStake with 'read txPrev failed':

    CTransaction::ReadFromDisk(txdb, prevout, txindex)  // src/main.cpp:714
        if (!txdb.ReadTxIndex(prevout.hash, txindexRet))  // empty!
            return false;

This stalls the node at the snapshot height and triggers DoS=100 on
every inbound peer feeding canonical blocks, masking as a network
misbehavior issue. DNS3 was stuck at 2,214,547 for this reason despite
the UTXO and block data being present.

Fix: after extracting blk0001.dat, walk it linearly and call
txdb.UpdateTxIndex(hash, CTxIndex(CDiskTxPos, nVout)) for every
transaction. O(N) over the historical block range, batched every
5000 txs. Adds ~30-60s to snapshot load on modern hardware.

This is the third leg of the v3 self-contained snapshot story:
  v3 field       source                     purpose
  -----------    -------------------------  -------------------------
  headers        last 2000 block headers    block index continuity
  utxos          22k unspent outputs         UTXO set at tip
  blocks         blk0001.dat raw bytes       on-disk block storage
  setStakeSeen   last 5000 PoS seen stakes   stake collision dedup
  txindex        [this commit]               PoS signature verification

Future 'v4 snapshot' work should consolidate all five into a single
load pass with progress reporting.
2026-07-01 13:29:28 -07:00
Krystie 9b5c47f60f anti-spam: revert comparison direction to > (cbb189a had it inverted)
The 2026-06-30 commit cbb189a changed bnNewBlock > bnRequired to bnNewBlock < bnRequired,
but bnNewBlock is the candidate's compact-bits TARGET (not difficulty). In Bitcoin/PoS,
larger target = easier difficulty. The correct reject condition is when the block's
target is LARGER than required (i.e. block is easier than allowed for elapsed time):
bnNewBlock > bnRequired.

The inverted condition caused DNS3 to reject every canonical post-snapshot block as
'too little proof-of-stake' because most honest blocks satisfy bnNewBlock < bnRequired
(block is harder than the very-loose anti-spam minimum, which is what we want).

Verified: DNS3 stuck at snapshot height 2,214,547 with log lines
  'ERROR: ProcessBlock() : block with too little proof-of-stake'
on every inbound post-snapshot block, while DNS2 (same daemon version) had advanced to
2,214,757 — confirming the issue is per-node state, not consensus.

Keeps Misbehaving(5) soft score from cbb189a (was 100, instant ban).
2026-07-01 12:42:59 -07:00
Krystie e48b71a5d1 ci: document manual dispatch command for TRI-PI rebuild without re-tag 2026-07-01 12:22:14 -07:00
Krystie d2389b4d39 sync: bump HEADER_DOWNLOAD_WINDOW 1024->4096 for 4x faster P2P IBD 2026-07-01 12:21:25 -07:00
Krystie 5c312bb7da snapshot v3: fix numUtxos update seek offset corrupting numBlocks
The writer seek calculation (contentHashPos - sizeof(numUtxos)) was
correct for v1/v2. In v3 the layout inserted numBlocks between
numUtxos and numStakeSeen, so the seek landed on the numBlocks field
and the updated count was written there, corrupting both fields.

Fix: compute the offset relative to contentHashPos, skipping the
contentHash, numStakeSeen, and numBlocks fields inserted in v2/v3.
2026-07-01 11:25:31 -07:00
sami7777 41ba9f8bc9 checkpoints: continuous finality pins every 1000 blocks
Adds 8 new hardened checkpoints at heights 2206500-2214400, verified
against the canonical chain. Closes the 8,400-block unverified gap
between the last hardcoded checkpoint (2206004) and the live tip
(2,214,476).

Without these, a fresh node syncing from zero with NO snapshot has
zero finality protection above height 2206004. A peer feeding fork
blocks at heights 2206005-2214400 could trick the IBD node into
accepting a divergent chain, because CheckHardened() only fires at
the exact heights in mapCheckpoints.

With continuous pins every 1000 blocks, any divergence >1000 blocks
is rejected at AcceptBlock time with DoS=100, protecting from-zero
sync against low-trust forks.
2026-07-01 03:46:26 -07:00
sami7777 cbb189aade anti-spam: fix inverted condition + soft scoring
Two bugs in the anti-spam heuristic at src/main.cpp:

1. Inverted comparison: condition was bnNewBlock > bnRequired paired with
   "too little proof-of-stake" error message. The condition triggers when
   the block has MORE difficulty than required (harder than allowed),
   but the message claims the OPPOSITE. Honest blocks during legitimate
   time-warps (fork recovery, chain catchup) get mislabelled.

2. Misbehaving(100) was a single-shot instant ban: banscore threshold
   defaults to 100, so the FIRST anti-spam violation triggered a 24-hour
   ban on every honest peer feeding us blocks during fork divergence.
   This is what caused the 2026-06-23 DNS2 clearnet-fork incident:
   peers got banned before we could determine which chain was canonical.

Fix: condition now correctly says bnNewBlock < bnRequired (block too
easy = reject), and Misbehaving score dropped from 100 to 5 (needs
~20 anti-spam violations before the 100 banscore threshold). Anti-spam
is a soft signal, not a hard ban trigger.
2026-07-01 03:32:04 -07:00
sami7777 5635cb5e57 build: enforce -march=x86-64-v2 on Linux x86_64
GCC 11+ on Intel CI runners (Skylake-X, Ice Lake, Sapphire Rapids)
emits AVX-512/AVX10 instructions for std::string / memcpy inlining
that crash with SIGILL on AMD EPYC and older Intel without those
extensions. Root cause: libstdc++ is statically linked into the
binary, so the build host's instruction set becomes a hard runtime
requirement.

The CI binary crashed immediately on DNS2/DNS3 (AMD EPYC Milan) with:
  traps: trianglesd[...] trap invalid opcode ip:...e432 error:0
  in trianglesd[...+af3000]
Disassembly of the crash site (file offset 0x15b432):
  62 f1 7f 08 6f 41 ff   vmovdqu8 -0x10(%rcx), %xmm0
This is an AVX10/AVX-512 instruction emitted inside
std::basic_string::basic_string (statically linked libstdc++).

Fix: -march=x86-64-v2 -mtune=generic for all Linux x86_64 builds.
v2 baseline (SSE4.2 + POPCNT + CMPXCHG16B) is from 2009 Nehalem and
supported on every x86_64 CPU we ship to. Override-able via
-DCMAKE_X86_64_BASELINE=OFF if a CPU-specific build is needed.
2026-07-01 03:26:31 -07:00
sami7777 b6feab8e94 snapshot v3: carry setStakeSeen over in dump/load
Adds v3 snapshot format that includes the last 5000 PoS block
(prevoutStake, nStakeTime) pairs so a snapshot-loaded node has its
stake-collision set restored without walking the block index.

v2 readers still load v3 snapshots (the extra field is past numBlocks
and the loader checks version >= 3 to read numStakeSeen).

Bumps version to 6.1.1.
2026-07-01 02:17:51 -07:00
Krystie 333f7abfc0 seed: add SAMI-PC I2P address as primary hardcoded seed
fecv4pomdm47epuadgrpkvxzjqfqwsjfc7t7xadwaac5bislyrhq.b32.i2p
2026-06-30 17:53:55 -07:00
Krystie eb20edf890 seed: add SAMI-PC as primary hardcoded onion seed
6ygpphp2qsucwvhwefv6h6ehvk6zjf7b7zdp4ggkzjjwe76cg6jwm7id.onion
is the authoritative wallet node — must be in every release.
2026-06-30 17:44:09 -07:00
25 changed files with 838 additions and 129 deletions
+4
View File
@@ -799,6 +799,10 @@ jobs:
trigger-tripi:
name: Trigger TRI-PI ARM64 Build
# Only fire on tag-push events. To trigger a TRI-PI rebuild after a
# release is created via gh API (without re-pushing the tag), use:
# curl -X POST .../repos/SamiAhmed7777/tri-pi/dispatches \
# -d '{"event_type":"new-release","client_payload":{"version":"vX.Y.Z","source_repo":"SamiAhmed7777/triangles_v5"}}'
if: startsWith(github.ref, 'refs/tags/v')
needs: release
runs-on: ubuntu-latest
+24
View File
@@ -47,6 +47,30 @@ if(CMAKE_SYSTEM_PROCESSOR MATCHES "i[3-6]86")
add_compile_options(-msse2)
endif()
# ── x86-64 baseline ISA (portability across CPU vendors/models) ──
# CRITICAL: Without this, GCC on Intel CI runners (Skylake-X, Ice Lake,
# Sapphire Rapids) emits AVX-512 / AVX10 instructions (vmovdqu8, vpcompressd,
# vpopcntd, etc.) for std::string / memcpy inlining that CRASH with SIGILL
# on AMD EPYC (Milan, Genoa) and older Intel without AVX-512/AVX10.
# x86-64-v2 = baseline from ~2009 (Nehalem): SSE4.2 + POPCNT + CMPXCHG16B.
# Supported on EVERY x86_64 CPU Triangles runs on in production (DNS2, DNS3,
# Hetzner ARM64 excluded — that's a different build). Do NOT raise to v3
# (AVX2) without re-testing on every supported CPU; v3 is fine for most
# modern hardware but adds risk on edge cases (early Ryzen, Atom).
# Override with -DCMAKE_X86_64_BASELINE=OFF to disable (not recommended).
if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|AMD64)$" AND NOT WIN32 AND NOT APPLE)
option(CMAKE_X86_64_BASELINE
"Compile with -march=x86-64-v2 (SSE4.2 baseline) for portability across CPU vendors"
ON)
if(CMAKE_X86_64_BASELINE)
add_compile_options(-march=x86-64-v2)
# -mtune=generic tells GCC the binary will run on CPUs other than the
# build host. Combined with -march=x86-64-v2 above, the scheduler
# picks instructions from the v2 subset only — no AVX-512 leaks.
add_compile_options(-mtune=generic)
endif()
endif()
# ── Platform: Windows (MSYS2 MinGW64) ──
if(WIN32)
add_compile_options(-Wa,-mbig-obj)
+87 -24
View File
@@ -109,6 +109,13 @@ bool MaybeMigrateLevelDbToRocksDb(bool fForce, std::string& strError)
{
std::ofstream marker(markerPath);
marker << "RocksDB migration in progress. Safe to delete this directory and retry.\n";
marker.flush();
if (!marker.good()) {
// Without the marker a crashed migration would be
// indistinguishable from a complete one — refuse to start.
strError = "could not write migration marker " + markerPath.string();
return false;
}
}
CTxDB source("r");
@@ -129,34 +136,48 @@ bool MaybeMigrateLevelDbToRocksDb(bool fForce, std::string& strError)
}
int64_t nCopied = 0;
auto it = source.NewIterator();
for (it->Seek(std::string()); it->Valid(); it->Next())
bool fCopyOK = true;
{
if (!destination.WriteRawRecordForMigration(it->KeyStr(), it->ValueStr())) {
destination.TxnAbort();
strError = "failed to write migrated record to RocksDB";
source.Close();
destination.Close();
return false;
}
if (++nCopied % 100000 == 0)
// W2 root cause: this iterator MUST be destroyed before
// source.Close(). Live LevelDB iterators hold a reference to the
// current Version; deleting the DB with one outstanding trips
// `dummy_versions_.next_ == &dummy_versions_` in
// leveldb::VersionSet::~VersionSet (version_set.cc:755) and
// aborts the daemon AFTER verification but BEFORE the marker is
// removed — which is what produced the original H4 symptom.
// Scoping the iterator here guarantees every Close() below runs
// with it already dead, on the success AND error paths.
auto it = source.NewIterator();
for (it->Seek(std::string()); it->Valid(); it->Next())
{
if (!destination.TxnCommit()) {
strError = "failed to commit RocksDB migration batch";
source.Close();
destination.Close();
return false;
if (!destination.WriteRawRecordForMigration(it->KeyStr(), it->ValueStr())) {
strError = "failed to write migrated record to RocksDB";
fCopyOK = false;
break;
}
printf("ChainDB migration: copied %lld / %lld records\n",
(long long)nCopied, (long long)srcStats.nRecords);
if (!destination.TxnBegin()) {
strError = "failed to begin RocksDB migration batch";
source.Close();
destination.Close();
return false;
if (++nCopied % 100000 == 0)
{
if (!destination.TxnCommit()) {
strError = "failed to commit RocksDB migration batch";
fCopyOK = false;
break;
}
printf("ChainDB migration: copied %lld / %lld records\n",
(long long)nCopied, (long long)srcStats.nRecords);
if (!destination.TxnBegin()) {
strError = "failed to begin RocksDB migration batch";
fCopyOK = false;
break;
}
}
}
} // iterator destroyed here — before any Close()
if (!fCopyOK) {
destination.TxnAbort(); // safe no-op if the batch was already consumed
source.Close();
destination.Close();
return false;
}
if (!destination.TxnCommit()) {
@@ -185,7 +206,49 @@ bool MaybeMigrateLevelDbToRocksDb(bool fForce, std::string& strError)
source.Close();
destination.Close();
fs::remove(markerPath);
// H4: Marker removal must be verified, not assumed. The previous
// implementation called fs::remove() and ignored the return code, which
// silently left the marker on disk after a successful migration. On
// the next startup init.cpp's fCrashedMigration check would then
// trigger a re-migration of the (already-good) RocksDB on every
// restart, eventually destroying the chain state.
//
// Three defenses:
// 1. Use the non-throwing error_code overload so a permission
// error doesn't propagate as an uncaught exception.
// 2. After remove(), confirm the file is actually gone. fs::remove
// returns true if the file didn't exist, which is also success
// but worth distinguishing.
// 3. Retry once with a short delay. On Windows, antivirus and
// indexer handles can transiently hold the marker file open
// even after our process closed it; a single retry usually
// wins. If the second attempt also leaves the file, treat the
// migration as FAILED — surface the error to the operator
// instead of letting init.cpp's fCrashedMigration logic
// destroy working data on the next startup.
{
std::error_code ec;
fs::remove(markerPath, ec);
if (ec) {
strError = "could not remove migration marker " + markerPath.string() +
": " + ec.message();
return false;
}
if (fs::exists(markerPath)) {
// Retry once — handles Windows AV/indexer transient locks.
MilliSleep(100);
std::error_code ec2;
fs::remove(markerPath, ec2);
if (ec2 || fs::exists(markerPath)) {
strError = "migration marker " + markerPath.string() +
" could not be removed after retry; refusing to leave it on disk " +
"(would trigger re-migration on next startup). " +
std::string(ec2 ? ec2.message().c_str() : "");
return false;
}
}
}
}
catch (std::exception& e) {
strError = e.what();
+21 -6
View File
@@ -32,12 +32,27 @@ namespace Checkpoints
{ 9002, uint256("0xa1e20fb1d44688b763690cf74d6aefe859e4cc32981f9e3f2b2ae9702bbcf249")},
{ 10881, uint256("0x4b6554c45e1e6764a6f3c309c47baf53c9edd81f624e52b072518cd15da237e6")},
{ 17650, uint256("0x224940e1f986a202209b8e762728d1452ab45870c308abf84905674acf326a47")},
// Recent finality pin (PoS era). Closes the long unchecked span from
// 17650 to the live tip so stale-bootstrap / low-trust forks below
// this height are rejected outright. Hash from the canonical chain.
{ 2205000, uint256("0x6bdd3c5e5a32e1dd9a70e705f1a28d1dd84929f89579bd2696d41bc87f39446f")},
{ 2206004, uint256("0xb34e8e6a7bb7f52167d81aaad4d26f87a876898fdd0fce860916fc1aaf9a2a46")},
};
// Recent finality pin (PoS era). Closes the long unchecked span from
// 17650 to the live tip so stale-bootstrap / low-trust forks below
// this height are rejected outright. Hash from the canonical chain.
{ 2205000, uint256("0x6bdd3c5e5a32e1dd9a70e705f1a28d1dd84929f89579bd2696d41bc87f39446f")},
{ 2206004, uint256("0xb34e8e6a7bb7f52167d81aaad4d26f87a876898fdd0fce860916fc1aaf9a2a46")},
// Continuous finality pins: every 1000 blocks from 2206500 onward so the
// gap between the last hardcoded checkpoint and the live tip stays bounded.
// Without these, a fresh node syncing from zero (no snapshot) has 8,400+
// unverified blocks at tip — a peer feeding fork blocks at those heights
// could trick an IBD node into accepting a divergent chain. With these
// pins, any divergence >1000 blocks is rejected at AcceptBlock time.
// All hashes verified against the canonical chain on 2026-07-01.
{ 2206500, uint256("0x707ea288242227e9b36ceeeecd5a16a6c918f8b6f7e6375128cba908ebfcbf27")},
{ 2207000, uint256("0x7af1cc23fdffb3a9ed2eb9aa5a8697e8af2f98c67c4f6baa9f4d7899cbfaf4ca")},
{ 2210000, uint256("0xe2dc2e55c6e1b3d2ea9d8a1f2b274bf64053ddd6a61335dc6896aa9c056956be")},
{ 2211000, uint256("0x61c8a179c928a1f0bbffa029b4f1aea67b04a98227a6d02e6137280404ed29dc")},
{ 2212000, uint256("0xf4df2b5d0d1de326b97ed5a3eeefef307a51791e03af401373e142f00453a9a8")},
{ 2213000, uint256("0x7bc9652d423676c52ba8b0a287e0b46e1eca6e8eecc51d3f30e0d665d3b236f5")},
{ 2214000, uint256("0x17e61ceb45db36358aaabe91b094a77ecba32370a467185fa9af75eef6c8e414")},
{ 2214400, uint256("0x8ebb818f7280850c5a3916b7c8a2bca603f7c4f9926d3cdc2262f726035d96ed")},
};
// Published UTXO snapshot file SHA256, keyed by snapshot height.
// Each entry binds height -> SHA256 of the canonical snapshot file produced by
+1 -1
View File
@@ -8,7 +8,7 @@
// These need to be macros, as version.cpp's and triangles-qt.rc's voodoo requires it
#define CLIENT_VERSION_MAJOR 6
#define CLIENT_VERSION_MINOR 1
#define CLIENT_VERSION_REVISION 0
#define CLIENT_VERSION_REVISION 1
#define CLIENT_VERSION_BUILD 0
// Converts the parameter X to a string after macro replacement on X has been performed.
+12
View File
@@ -223,6 +223,18 @@ bool CI2PSession::LoadOrCreateDestination(std::string& strPrivKeyRet)
if (out.is_open()) {
out << priv << std::endl;
out.close();
// The I2P destination private key identifies this node on
// the I2P network: owner-only permissions, like Tor's
// hidden-service secret key. (No-op semantics differ on
// Windows ACLs; harmless there.)
std::error_code ec;
std::filesystem::permissions(keyPath,
std::filesystem::perms::owner_read |
std::filesystem::perms::owner_write,
std::filesystem::perm_options::replace, ec);
if (ec)
printf("I2P: WARNING could not restrict permissions on %s: %s\n",
keyPath.string().c_str(), ec.message().c_str());
printf("I2P: generated and saved new persistent destination\n");
ok = true;
} else {
+2
View File
@@ -12,6 +12,8 @@
// Dynamic seeds will also be available at:
// https://seeds.cryptographic-triangles.org/i2p-seeds.txt
static const char *strMainNetI2PSeed[][1] = {
// SAMI-PC - authoritative wallet node (main PC)
{"fecv4pomdm47epuadgrpkvxzjqfqwsjfc7t7xadwaac5bislyrhq.b32.i2p"},
// DNS2 - primary bootstrap server (194.233.88.206)
// Generated by embedded i2pd on first run, keys persist in i2p_data/
{"hnupgkbtcn4hlo6sunhbp6uuz4k6bkgsa5jtcruyyt7y6q7qsoda.b32.i2p"},
+32 -6
View File
@@ -1105,10 +1105,19 @@ bool AppInit2()
if (true) {
if (true) {
do {
// Bind to all interfaces so external peers can connect
// W1: Bind to all interfaces so external peers can connect.
//
// The previous code went through Lookup("0.0.0.0", ...) which
// hands the literal string to getaddrinfo(). On Windows that
// resolver can fail to map "0.0.0.0" to INADDR_ANY and the
// daemon would abort at startup with "Cannot resolve binding
// address". Construct the CService directly from INADDR_ANY
// instead — this is the canonical "any-address" binding and
// works on every platform without consulting the resolver.
CService addrBind;
if (!Lookup("0.0.0.0", addrBind, GetListenPort(), false))
return InitError(strprintf(_("Cannot resolve binding address: '%s'"), "0.0.0.0"));
struct in_addr any;
any.s_addr = htonl(INADDR_ANY);
addrBind = CService(any, GetListenPort());
fBound |= Bind(addrBind);
} while (false);
}
@@ -1279,20 +1288,37 @@ bool AppInit2()
{
bool fExplicit = GetBoolArg("-migratechaindb", false) ||
GetBoolArg("-migratechaindbforce", false);
// A rocksdb/ directory containing the MIGRATION_INCOMPLETE marker is a
// crashed previous migration, NOT a usable chain DB — treat it the same
// as "no rocksdb yet" so the migration is retried instead of silently
// opening a truncated database.
bool fCrashedMigration = fs::exists(GetDataDir() / "rocksdb" / "MIGRATION_INCOMPLETE");
bool fAuto = IsRocksDbChainBackend() &&
fs::exists(GetDataDir() / "txleveldb") &&
!fs::exists(GetDataDir() / "rocksdb");
(!fs::exists(GetDataDir() / "rocksdb") || fCrashedMigration);
if (fExplicit || fAuto)
{
uiInterface.InitMessage(_("Migrating chain database to RocksDB..."));
if (fAuto && !fExplicit)
printf("ChainDB: RocksDB backend active with a legacy LevelDB present; "
"migrating automatically.\n");
printf("ChainDB: RocksDB backend active with a legacy LevelDB present%s; "
"migrating automatically.\n",
fCrashedMigration ? " and a previous migration was interrupted" : "");
std::string strMigrateError;
bool fForce = GetBoolArg("-migratechaindbforce", false);
if (!MaybeMigrateLevelDbToRocksDb(fForce, strMigrateError))
return InitError(strprintf(_("Chain DB migration failed: %s"), strMigrateError.c_str()));
}
// Last line of defense: never open a RocksDB that still carries the
// incomplete-migration marker (e.g. the LevelDB source was deleted so
// the migration cannot be retried). Opening it would silently run on a
// partial chain state.
if (IsRocksDbChainBackend() &&
fs::exists(GetDataDir() / "rocksdb" / "MIGRATION_INCOMPLETE"))
{
return InitError(_("The RocksDB chain database is left over from an interrupted "
"migration and is incomplete. Delete the 'rocksdb' directory in the "
"data directory and restart (it will be rebuilt by migration or resync)."));
}
}
// ********************************************************* Step 7: load blockchain
+18 -1
View File
@@ -3478,10 +3478,27 @@ bool ProcessBlock(CNode* pfrom, CBlock* pblock)
bnRequired.SetCompact(ComputeMinWork(pindexLastPow->nBits, deltaTime));
}
// Anti-spam: reject blocks whose target exceeds the required minimum (i.e. blocks
// with less difficulty than required for the elapsed time-since-checkpoint).
// bnNewBlock is the candidate's compact-bits target; bnRequired is the minimum
// target for the elapsed time. In Bitcoin/PoS, a LARGER target means EASIER
// difficulty. So: bnNewBlock > bnRequired => block is easier than required =>
// "too little proof-of-stake/work" => reject.
//
// The 2026-06-30 commit cbb189a inverted this to bnNewBlock < bnRequired which
// rejected blocks that are HARDER than required (good blocks!) — verified by
// DNS3 stalling at snapshot height 2,214,547 because every canonical post-snapshot
// block was being rejected as "too little proof-of-stake". This restores the
// correct comparison and keeps the soft Misbehaving(5) score from cbb189a.
if (bnRequired != 0 && bnNewBlock > bnRequired)
{
// Anti-spam is a soft scoring signal, NOT a hard ban trigger. A single
// violation should log + score modestly, not 24-hour-ban honest peers
// (which is what happened during the 2026-06-23 DNS2 clearnet-fork
// incident — `Misbehaving(100)` crossed the banscore threshold on the
// FIRST block, instantly banning every honest peer feeding us fork blocks).
if (pfrom)
pfrom->Misbehaving(100);
pfrom->Misbehaving(5);
return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
}
}
+2
View File
@@ -4,6 +4,8 @@
// Hardcoded onion seed nodes for initial peer discovery.
// Also fetched dynamically via https://seeds.cryptographic-triangles.org/seeds.txt
static const char *strMainNetOnionSeed[][1] = {
// SAMI-PC - authoritative wallet node (main PC)
{"6ygpphp2qsucwvhwefv6h6ehvk6zjf7b7zdp4ggkzjjwe76cg6jwm7id.onion"},
// DNS2 - primary bootstrap server (194.233.88.206)
{"gxvrhv3qitnc6kobrhsrse46bmcfitnybapor3or3oczzuxn6hfzxyid.onion"},
// DNS3 - canonical chain reference (74.208.167.19)
+17
View File
@@ -1663,6 +1663,23 @@ QProgressBar::chunk {
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_hd">
<property name="font">
<font>
<pointsize>9</pointsize>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="toolTip">
<string>HD (BIP39) wallet seed status</string>
</property>
<property name="text">
<string notr="true">HD</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_staking">
<property name="text">
+31 -1
View File
@@ -359,6 +359,11 @@ TrianglesGUI::TrianglesGUI(bool fIsTestnet, QWidget *parent):
labelV3Icon = ui->label_v3;
labelV3Icon->setVisible(false);
// HD indicator next to lock icon (always visible; color reflects state)
labelHdIcon = ui->label_hd;
labelHdIcon->setVisible(true);
updateHDStatus();
// Tor icon next to onion address in the stacked address group (hidden until populated)
labelTorIcon = ui->label_tor_icon;
labelTorIcon->setVisible(false);
@@ -650,6 +655,9 @@ void TrianglesGUI::setWalletModel(WalletModel *walletModel)
connect(walletModel, SIGNAL(transactionSyncProgressChanged(bool,int)), this, SLOT(setWalletTransactionSyncProgress(bool,int)));
setWalletTransactionSyncState(walletModel->isTransactionSyncing());
// HD status reflects wallet capability — refresh whenever the wallet model changes
updateHDStatus();
// Balloon pop-up for new transaction
connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(incomingTransaction(QModelIndex,int,int)));
@@ -1866,16 +1874,38 @@ void TrianglesGUI::updateI2PAddress()
labelI2PIcon->setVisible(false);
}
// I2P address text
if (!hasI2P) {
labelI2PAddress->setVisible(false);
return;
}
labelI2PAddress->setText(QString::fromStdString(i2pAddress));
labelI2PAddress->setToolTip(tr("This node's I2P .b32.i2p address. Click to copy."));
labelI2PAddress->setVisible(true);
}
void TrianglesGUI::updateHDStatus()
{
// Red (#f26522 — TRI brand color) when HD is enabled, grey when not.
// Placed next to the lock icon as a wallet-capability indicator.
if (!labelHdIcon) return;
bool fHD = false;
if (walletModel) {
fHD = walletModel->hdEnabled();
}
if (fHD) {
labelHdIcon->setStyleSheet("color: #f26522; font-weight: bold;");
labelHdIcon->setToolTip(tr("HD wallet: BIP39 seed active. Backup your seed phrase — individual keys alone will not restore this wallet."));
} else {
labelHdIcon->setStyleSheet("color: #555555; font-weight: bold;");
labelHdIcon->setToolTip(tr("Non-HD wallet: backup each address key separately. Use hdnew to upgrade to an HD seed."));
}
labelHdIcon->setText(QStringLiteral("HD"));
labelHdIcon->setVisible(true);
}
void TrianglesGUI::on_bHelp_clicked()
{
+2
View File
@@ -114,6 +114,7 @@ private:
QLabel *labelV3Icon;
QLabel *labelI2PIcon;
QLabel *labelTorIcon;
QLabel *labelHdIcon;
QLabel *progressBarLabel;
QProgressBar *progressBar;
@@ -182,6 +183,7 @@ public slots:
void setWalletTransactionSyncProgress(bool syncing, int pendingNotifications);
void updateOnionAddress();
void updateI2PAddress();
void updateHDStatus();
/** Notify the user of an error in the network or transaction handling code. */
void error(const QString &title, const QString &message, bool modal);
+9 -2
View File
@@ -1919,7 +1919,10 @@ Value hdnew(const Array& params, bool fHelp)
Object obj;
obj.push_back(Pair("mnemonic", mnemonic));
obj.push_back(Pair("words", 24));
obj.push_back(Pair("warning", "Write these 24 words down and keep them secret and offline. Anyone with them can spend your coins."));
obj.push_back(Pair("passphrase_used", !passphrase.empty()));
obj.push_back(Pair("warning", passphrase.empty()
? "Write these 24 words down and keep them secret and offline. Anyone with them can spend your coins."
: "Write these 24 words down and keep them secret and offline. Anyone with them can spend your coins. You ALSO set a BIP39 passphrase: the words alone will NOT restore this wallet — back up the passphrase separately."));
return obj;
}
@@ -1958,6 +1961,10 @@ Value hdshow(const Array& params, bool fHelp)
throw JSONRPCError(RPC_WALLET_ERROR, "Wallet has no HD seed (use 'hdnew' to create one).");
Object obj;
obj.push_back(Pair("mnemonic", mnemonic));
obj.push_back(Pair("warning", "Keep these words secret and offline."));
obj.push_back(Pair("passphrase_used", !pwalletMain->hdPassphrase.empty()));
if (!pwalletMain->hdPassphrase.empty())
obj.push_back(Pair("warning", "Keep these words secret and offline. A BIP39 passphrase is ALSO set: the words alone will NOT restore this wallet — back up the passphrase separately."));
else
obj.push_back(Pair("warning", "Keep these words secret and offline."));
return obj;
}
+7 -1
View File
@@ -19,7 +19,13 @@ class CSyncManager
public:
struct HeaderNode;
static constexpr unsigned int HEADER_DOWNLOAD_WINDOW = 1024;
// HEADER_DOWNLOAD_WINDOW: max concurrent block requests in flight per sync
// tick. Bumped from 1024 → 4096 in v6.1.2 because 4+ peers are now reliably
// available and Tor's 1KB/s RTT × 4096 blocks = manageable inflight without
// stalling the orphan pool. With 1 reliable peer, drops back to ~1024 effective
// due to nPerPeerCap. The factor-4 jump is safe because orphan pool handles
// out-of-order delivery and CSyncManager's Tick() drains in 5s intervals.
static constexpr unsigned int HEADER_DOWNLOAD_WINDOW = 4096;
static constexpr unsigned int HEADER_SYNC_LOW_WATER = HEADER_DOWNLOAD_WINDOW / 4;
static constexpr unsigned int HEADER_SYNC_TARGET_INFLIGHT = HEADER_DOWNLOAD_WINDOW / 2;
static constexpr int64_t HEADER_SYNC_REFILL_MIN_INTERVAL_SECONDS = 5;
+203 -10
View File
@@ -26,10 +26,14 @@
#define BOOST_TEST_MODULE chaindb_runtime_tests_standalone
#include <boost/test/unit_test.hpp>
#include <fstream>
#include <string>
#include "../txdb.h"
#include "../txdb-base.h"
#include "../txdb-rocksdb.h"
#include "../txdb-leveldb.h"
#include "../chaindb_migrate.h"
#include "../util.h"
#include "../serialize.h"
#include "../uint256.h"
@@ -63,6 +67,49 @@ struct ChainDbRuntimeTestAccessor
{ return db.ExistsRaw(k); }
};
// Reset the process-wide static chain-DB handles. The migration tests in
// the chaindb_wipe suite run after chaindb_backend_selection and
// rocksdb_wrapper, both of which leave the static g_rocksdb (and on some
// paths the leveldb txdb singleton) alive. A leaked g_rocksdb means the
// next test that does `MakeChainDB("cr+")` may get a path that the
// prior test's open handle is still serving — leading to the test
// operating on stale state and the on-disk wipe having no effect.
//
// This helper explicitly closes the rocksdb handle (sets g_rocksdb=null)
// AND wipes any leftover on-disk chain DB directories so each migration
// test starts from a known-clean state. Cheap (no-op when nothing is
// open) and safe to call at the top of any test.
static void ResetChainDBStatics()
{
// Close any open RocksDB handle. We open in create-if-missing mode
// ("cr+") so this works whether or not the prior test left a rocksdb/
// on disk. The handle goes out of scope at the end of the block,
// invoking CRocksTxDB::~CRocksTxDB which calls close_rocksdb() and
// sets g_rocksdb = nullptr.
{
mapArgs["-chaindb"] = "rocksdb";
CRocksTxDB closer("cr+");
closer.Close();
mapArgs.erase("-chaindb");
}
// Close any open LevelDB handle. Same pattern: open + close under
// -chaindb=leveldb. MakeChainDB("cr+") creates the dir if missing.
{
mapArgs["-chaindb"] = "leveldb";
auto base = MakeChainDB("cr+");
if (base) {
base->Close();
base.reset();
}
mapArgs.erase("-chaindb");
}
// Wipe any leftover on-disk chain DB dirs from the prior tests so
// the migration test starts from a known state.
std::error_code ec;
fs::remove_all(GetDataDir() / "txleveldb", ec);
fs::remove_all(GetDataDir() / "rocksdb", ec);
}
// ─── Globals (minimal — chaindb wrappers don't pull in wallet/main) ───────
// Same rationale as test_snapshotnet: wallet.cpp (linked in for CWallet
// symbols) drags in main.cpp's references to these globals, so they must
@@ -141,16 +188,19 @@ BOOST_AUTO_TEST_SUITE(chaindb_backend_selection)
BOOST_AUTO_TEST_CASE(is_rocksdb_backend_flag_default_off)
{
// Default test build doesn't set -chaindb, so backend should NOT be rocksdb.
// The default test build doesn't set the -chaindb flag at all. (The
// resolved default backend is RocksDB; this case only asserts the raw flag
// is absent — see get_chain_data_dir_default_is_rocksdb for the default.)
BOOST_CHECK_EQUAL(GetBoolArg("-chaindb", false), false);
}
BOOST_AUTO_TEST_CASE(get_chain_data_dir_default_is_txleveldb)
BOOST_AUTO_TEST_CASE(get_chain_data_dir_default_is_rocksdb)
{
// No -chaindb flag set → GetChainDataDir() must return txleveldb path.
// No -chaindb flag set → RocksDB is the default backend, so
// GetChainDataDir() must return the rocksdb path.
mapArgs.erase("-chaindb");
BOOST_CHECK_EQUAL(IsRocksDbChainBackend(), false);
BOOST_CHECK_EQUAL(GetChainDataDir().filename().string(), "txleveldb");
BOOST_CHECK_EQUAL(IsRocksDbChainBackend(), true);
BOOST_CHECK_EQUAL(GetChainDataDir().filename().string(), "rocksdb");
}
BOOST_AUTO_TEST_CASE(get_chain_data_dir_rocksdb_when_flag_set)
@@ -432,6 +482,7 @@ BOOST_AUTO_TEST_SUITE(chaindb_wipe)
BOOST_AUTO_TEST_CASE(wipe_removes_rocksdb_dir_when_flagged)
{
ResetChainDBStatics();
mapArgs["-chaindb"] = "rocksdb";
{
auto base = MakeChainDB("cr+");
@@ -451,12 +502,14 @@ BOOST_AUTO_TEST_CASE(wipe_removes_rocksdb_dir_when_flagged)
mapArgs.erase("-chaindb");
}
BOOST_AUTO_TEST_CASE(wipe_removes_txleveldb_dir_by_default)
BOOST_AUTO_TEST_CASE(wipe_removes_txleveldb_dir_when_leveldb_selected)
{
// No explicit write needed — MakeChainDB("cr+") opens the LevelDB
// handle which creates the txleveldb/ directory on disk. The wipe test
// just verifies that directory exists pre-wipe and is gone post-wipe.
mapArgs.erase("-chaindb");
ResetChainDBStatics();
// With -chaindb=leveldb, MakeChainDB("cr+") opens the LevelDB handle which
// creates the txleveldb/ directory on disk. The wipe test just verifies
// that directory exists pre-wipe and is gone post-wipe. (RocksDB is the
// default now, so LevelDB must be requested explicitly.)
mapArgs["-chaindb"] = "leveldb";
{
auto base = MakeChainDB("cr+");
BOOST_REQUIRE(base != nullptr);
@@ -467,6 +520,146 @@ BOOST_AUTO_TEST_CASE(wipe_removes_txleveldb_dir_by_default)
WipeChainDataDir();
BOOST_CHECK(!fs::exists(dir));
mapArgs.erase("-chaindb");
}
// H1: A rocksdb/ directory left with MIGRATION_INCOMPLETE from a crashed
// previous migration must be wiped and re-migrated (not silently opened as
// live chain state). Also verifies the M4 marker-write behavior: the marker
// is on disk only during an in-progress migration and removed on success.
//
// This test does NOT pre-seed LevelDB with custom records (Write/WriteRaw
// are protected). Instead it relies on the fact that ANY LevelDB chain DB
// (even with default metadata only) will be copied across and that the
// marker is the observable signal of migration progress.
BOOST_AUTO_TEST_CASE(crashed_migration_marker_triggers_retry)
{
// Reset any leaked state from prior suites (chaindb_backend_selection,
// rocksdb_wrapper) so this test starts from a clean process.
ResetChainDBStatics();
// Create a minimal LevelDB chain DB by opening + closing it. This
// establishes the txleveldb/ directory with the "version" key the
// migration code expects.
mapArgs["-chaindb"] = "leveldb";
{
auto base = MakeChainDB("cr+");
BOOST_REQUIRE(base != nullptr);
base->Close();
}
BOOST_REQUIRE(fs::exists(GetDataDir() / "txleveldb"));
// Simulate a crashed prior migration: rocksdb/ exists AND carries the
// incomplete marker. Production: init's fAuto condition should treat this
// as "no rocksdb yet" and retry the migration.
fs::path rocksDir = GetDataDir() / "rocksdb";
fs::create_directories(rocksDir);
{
std::ofstream marker(rocksDir / "MIGRATION_INCOMPLETE");
marker << "simulated crash from prior session\n";
marker.flush();
}
BOOST_REQUIRE(fs::exists(rocksDir / "MIGRATION_INCOMPLETE"));
// Run the production migration function. It must:
// 1. See the marker and remove rocksdb/
// 2. Re-copy the LevelDB source
// 3. Leave NO marker on success
mapArgs["-chaindb"] = "rocksdb"; // target
{
std::string err;
BOOST_REQUIRE_MESSAGE(MaybeMigrateLevelDbToRocksDb(false, err),
"migration failed: " + err);
BOOST_CHECK_MESSAGE(err.empty(), "unexpected error: " + err);
}
// M4: marker must be gone after a successful migration.
BOOST_CHECK_MESSAGE(!fs::exists(rocksDir / "MIGRATION_INCOMPLETE"),
"MIGRATION_INCOMPLETE marker should be removed on success");
// And the migrated rocksdb/ must exist with data in it.
BOOST_CHECK_MESSAGE(fs::exists(rocksDir), "rocksdb/ should exist after migration");
// The migration function has already verified the data round-trip via
// CollectStats()'s parity check (record count + UTXO set + best chain
// hash). We just need the instance to reopen cleanly here. We use a
// scope guard to ensure RocksDB close happens before the process exit
// (avoids a known destructor order issue with the global LevelDB cache
// when multiple DBs are opened in a single process).
{
auto base = MakeChainDB("r");
BOOST_REQUIRE(base != nullptr);
auto& rdb = static_cast<CRocksTxDB&>(*base);
(void)rdb; // suppress unused-variable warning
BOOST_CHECK(true);
base.reset(); // close the RocksDB instance explicitly
}
WipeChainDataDir();
fs::remove_all(GetDataDir() / "txleveldb");
mapArgs.erase("-chaindb");
}
// H4: After a SUCCESSFUL migration (no pre-existing marker, no crash), the
// MIGRATION_INCOMPLETE marker MUST be gone from disk. The previous
// implementation called fs::remove() and ignored the return code, so the
// marker silently survived success. init.cpp's fCrashedMigration check then
// treated the (good) RocksDB as a crashed migration and re-migrated on every
// startup, eventually destroying chain state.
//
// This test exercises the real MaybeMigrateLevelDbToRocksDb() end-to-end on
// the happy path: fresh LevelDB → no marker → migration → marker gone.
// Complements crashed_migration_marker_triggers_retry which covers the
// retry path.
BOOST_AUTO_TEST_CASE(marker_removed_after_successful_migration)
{
// Reset any leaked state from prior suites so this test starts clean.
ResetChainDBStatics();
// 1. Seed a minimal LevelDB chain DB by opening + closing it.
mapArgs["-chaindb"] = "leveldb";
{
auto base = MakeChainDB("cr+");
BOOST_REQUIRE(base != nullptr);
base->Close();
}
BOOST_REQUIRE(fs::exists(GetDataDir() / "txleveldb"));
// 2. Confirm the starting state: no rocksdb/, no marker.
fs::path rocksDir = GetDataDir() / "rocksdb";
fs::path marker = rocksDir / "MIGRATION_INCOMPLETE";
BOOST_REQUIRE(!fs::exists(rocksDir));
BOOST_REQUIRE(!fs::exists(marker));
// 3. Run the production migration function with RocksDB as target.
mapArgs["-chaindb"] = "rocksdb";
{
std::string err;
BOOST_REQUIRE_MESSAGE(MaybeMigrateLevelDbToRocksDb(false, err),
"migration failed: " + err);
BOOST_CHECK_MESSAGE(err.empty(), "unexpected error: " + err);
}
// 4. The marker must be gone. This is the H4 invariant: a successful
// migration never leaves the marker on disk. The previous code
// returned true here even when the marker survived, which is the
// exact regression this test catches.
BOOST_CHECK_MESSAGE(!fs::exists(marker),
"MIGRATION_INCOMPLETE marker must be removed on success "
"(H4 — silent marker survival causes re-migration loop)");
// 5. The migrated rocksdb/ must exist with data in it.
BOOST_CHECK_MESSAGE(fs::exists(rocksDir), "rocksdb/ should exist after migration");
// 6. Reopen and confirm the data is intact.
{
auto base = MakeChainDB("r");
BOOST_REQUIRE(base != nullptr);
base.reset(); // close before process exit (RocksDB static handle order)
}
WipeChainDataDir();
fs::remove_all(GetDataDir() / "txleveldb");
mapArgs.erase("-chaindb");
}
BOOST_AUTO_TEST_SUITE_END()
+4 -1
View File
@@ -23,7 +23,10 @@ enum class ChainDbKind { LevelDB, RocksDB };
ChainDbKind ResolveChainDbKind()
{
std::string s = GetArg("-chaindb", std::string("leveldb"));
// RocksDB is the default backend. LevelDB remains selectable with
// -chaindb=leveldb and is retained as the migration source and fallback;
// its removal is deferred to a later phase after live-chain validation.
std::string s = GetArg("-chaindb", std::string("rocksdb"));
for (auto& c : s) c = std::tolower(static_cast<unsigned char>(c));
if (s == "leveldb")
+9 -2
View File
@@ -274,8 +274,15 @@ bool CTxDB::ExistsRaw(const std::string& key) const
if (activeBatch) {
bool deleted = false;
if (ScanBatch(key, &unused, &deleted) && !deleted)
return true;
if (ScanBatch(key, &unused, &deleted)) {
// Mirror ReadRaw() and the RocksDB backend: an entry that is
// deleted in the active batch does NOT exist, even if an older
// copy is still on disk. Falling through to the disk lookup here
// (the old behavior) made Exists() disagree with Read() and with
// CRocksTxDB::ExistsRaw — a latent cross-backend consensus split
// for intra-batch spend checks (see ROCKSDB-T010-REVIEW, H2).
return !deleted;
}
}
leveldb::Status status = pdb->Get(leveldb::ReadOptions(), key, &unused);
+75 -65
View File
@@ -31,8 +31,26 @@ namespace fs = std::filesystem;
// Global pointer for the RocksDB instance, shared across CRocksTxDB instances
// the same way the LevelDB backend shares its txdb singleton.
static rocksdb::DB* g_rocksdb = nullptr;
static rocksdb::ColumnFamilyHandle* g_cf_handles[5] = {}; // indexed by CF_ enum
static bool g_cf_enabled = false;
// Handles returned by the column-family Open. The RocksDB API contract
// requires DestroyColumnFamilyHandle() on every handle BEFORE deleting the
// DB (asserts in debug builds, UB/leak in release). Kept here so
// close_rocksdb() can honor that.
static std::vector<rocksdb::ColumnFamilyHandle*> g_cf_handles;
// Single close path: destroy CF handles first, then the DB.
static void close_rocksdb()
{
if (g_rocksdb) {
for (rocksdb::ColumnFamilyHandle* h : g_cf_handles) {
if (h)
g_rocksdb->DestroyColumnFamilyHandle(h);
}
}
g_cf_handles.clear();
delete g_rocksdb;
g_rocksdb = nullptr;
}
// Non-batched writes bypass WAL fsync. The TxnCommit path handles durability;
// crash recovery replays from block files anyway. Default WriteOptions may
@@ -130,27 +148,8 @@ static rocksdb::Options GetRocksOptions()
return opts;
}
// ─── Column family names ───────────────────────────────────────────────────
static const std::string CF_NAMES[] = {
rocksdb::kDefaultColumnFamilyName, // CF_DEFAULT (index 0)
"blockindex", // CF_BLOCKINDEX (index 1)
"txindex", // CF_TXINDEX (index 2)
"utxo", // CF_UTXO (index 3)
"addrindex", // CF_ADDRINDEX (index 4)
};
static constexpr int CF_COUNT = 5;
// Prefix-to-CF routing table. Keys starting with these prefixes go to
// the indicated CF index. Everything else stays in CF_DEFAULT (metadata).
struct CfPrefixEntry { const char* prefix; int len; int cf_index; };
static CfPrefixEntry prefixMap_[] = {
{"b", 1, 1}, // CF_BLOCKINDEX
{"t", 1, 2}, // CF_TXINDEX
{"u", 1, 3}, // CF_UTXO
{"addrbal", 7, 4}, // CF_ADDRINDEX
{"addrutxo", 8, 4}, // CF_ADDRINDEX
{"addrtxid", 8, 4}, // CF_ADDRINDEX
};
// Column-family partitioning is disabled (see CRocksTxDB::GetCF). All keys live
// in the default column family, mirroring the single-keyspace LevelDB backend.
static void open_rocksdb(rocksdb::Options& options, bool fRemoveOld = false)
{
@@ -163,58 +162,54 @@ static void open_rocksdb(rocksdb::Options& options, bool fRemoveOld = false)
fs::create_directory(directory);
printf("Opening RocksDB in %s\n", directory.string().c_str());
// Try opening with column families. First, list existing CFs.
// Column-family partitioning is disabled (see CRocksTxDB::GetCF): all data
// lives in the default CF so writes, point reads, and full-keyspace
// iteration stay mutually consistent. New databases are therefore created
// single-CF.
//
// For openability we must still enumerate any column families that already
// exist on disk — RocksDB refuses to open a database unless every existing
// CF is named in the open call. Experimental pre-release databases may
// contain the old blockindex/txindex/utxo/addrindex CFs; we open them so
// the handle is valid, but never route to them. (Such a database would have
// chain data stranded in non-default CFs and should be re-migrated or
// reindexed; no production database is in that state.)
std::vector<std::string> existingCFs;
rocksdb::Options listOpts = options;
listOpts.create_if_missing = false;
rocksdb::DB::ListColumnFamilies(listOpts, directory.string(), &existingCFs);
bool needsCreate = (existingCFs.size() <= 1); // Only "default" or empty
std::vector<rocksdb::ColumnFamilyDescriptor> cfDescs;
for (int i = 0; i < CF_COUNT; i++) {
// Include this CF if it already exists OR if we're creating new
bool exists = false;
for (auto& name : existingCFs)
if (name == CF_NAMES[i]) { exists = true; break; }
if (exists || needsCreate) {
rocksdb::ColumnFamilyOptions cfOpts = options;
// Per-CF tuning:
if (i == 3) { // UTXO: optimize for point lookups
cfOpts.OptimizeForPointLookup(static_cast<size_t>(GetArg("-dbcache", 2048)));
} else if (i == 4) { // addrindex: optimize for scans
cfOpts.OptimizeLevelStyleCompaction(cfOpts.write_buffer_size);
}
cfDescs.push_back(rocksdb::ColumnFamilyDescriptor(CF_NAMES[i], cfOpts));
}
cfDescs.push_back(rocksdb::ColumnFamilyDescriptor(
rocksdb::kDefaultColumnFamilyName, rocksdb::ColumnFamilyOptions(options)));
for (const auto& name : existingCFs) {
if (name == rocksdb::kDefaultColumnFamilyName)
continue; // default already added above
cfDescs.push_back(rocksdb::ColumnFamilyDescriptor(
name, rocksdb::ColumnFamilyOptions(options)));
}
std::vector<rocksdb::ColumnFamilyHandle*> handles;
rocksdb::Status status = OpenRocksDBCF(options, directory.string(),
cfDescs, &handles, &g_rocksdb);
if (!status.ok()) {
// Fallback: open without CFs (old-style single-CF database)
// Fallback: open without an explicit CF list (plain single-CF database).
printf("RocksDB CF open failed (%s), falling back to single-CF\n", status.ToString().c_str());
status = OpenRocksDB(options, directory.string(), &g_rocksdb);
if (!status.ok()) {
throw runtime_error(strprintf("open_rocksdb(): error opening database: %s",
status.ToString().c_str()));
}
g_cf_handles.clear(); // plain Open returns no handles to manage
return;
}
// Store handles in the global array (CF names map directly to indices)
for (size_t i = 0; i < handles.size() && i < CF_COUNT; i++) {
// Match handle to our index by name
std::string hname = handles[i]->GetName();
for (int j = 0; j < CF_COUNT; j++) {
if (hname == CF_NAMES[j]) {
g_cf_handles[j] = handles[i];
break;
}
}
}
g_cf_enabled = true;
// We only ever route to the default CF, so keep CF routing off. Any extra
// handles opened above for legacy-database compatibility are unused for
// routing but MUST be retained so close_rocksdb() can destroy them before
// the DB is deleted (RocksDB API requirement).
g_cf_handles = handles;
g_cf_enabled = false;
}
CRocksTxDB::CRocksTxDB(const char* pszMode)
@@ -245,8 +240,8 @@ CRocksTxDB::CRocksTxDB(const char* pszMode)
printf("Required index version is %d, removing old RocksDB database\n",
DATABASE_VERSION);
delete g_rocksdb;
g_rocksdb = pdb = nullptr;
close_rocksdb();
pdb = nullptr;
delete activeBatch;
activeBatch = nullptr;
@@ -277,8 +272,8 @@ CRocksTxDB::~CRocksTxDB()
void CRocksTxDB::Close()
{
delete g_rocksdb;
g_rocksdb = pdb = nullptr;
close_rocksdb();
pdb = nullptr;
delete activeBatch;
activeBatch = nullptr;
}
@@ -351,15 +346,30 @@ bool CRocksTxDB::ScanBatch(const std::string& key, std::string* value, bool* del
}
// ─── CF routing helper ──────────────────────────────────────────────────────
rocksdb::ColumnFamilyHandle* CRocksTxDB::GetCF(const std::string& key) const
// IMPORTANT: column-family partitioning is intentionally DISABLED.
//
// The earlier design split keys across per-prefix column families
// (blockindex/txindex/utxo/addrindex) for independent compaction. But the read
// path was never made CF-aware: both CRocksTxDB::NewIterator() and
// CRocksTxDB::LoadBlockIndex() iterate the DEFAULT column family only. With
// routing enabled, block-index records (and every other prefixed key) were
// written into non-default CFs, so:
// - LoadBlockIndex() loaded ZERO blocks,
// - UTXO snapshot dumps and address-index range scans saw nothing, and
// - the migration verifier (CollectStats) counted a record mismatch.
// This is why -chaindb=rocksdb "compiled clean but was never runtime-valid."
//
// Returning nullptr unconditionally routes ALL keys to the default CF, which
// makes writes, point reads, Exists, Erase, and full-keyspace iteration
// mutually consistent — and byte-identical to the single-keyspace LevelDB
// backend, which the migration and dual-backend equivalence tests rely on.
//
// Re-introducing CFs is tracked as a follow-up and requires CF-aware iterators
// in NewIterator()/LoadBlockIndex() (a multiplexed merge across CFs) before the
// prefix router below can be re-enabled.
rocksdb::ColumnFamilyHandle* CRocksTxDB::GetCF(const std::string& /*key*/) const
{
if (!g_cf_enabled)
return nullptr; // nullptr = default CF
for (auto& entry : prefixMap_) {
if ((int)key.size() >= entry.len && key.compare(0, entry.len, entry.prefix) == 0)
return g_cf_handles[entry.cf_index];
}
return nullptr; // default CF for metadata keys
return nullptr; // single keyspace: always the default column family
}
bool CRocksTxDB::ReadRaw(const std::string& key, std::string& value) const
+198 -4
View File
@@ -111,6 +111,23 @@ bool DumpSnapshot(const fs::path& destPath,
if (blkSize > 0) numBlocks = (unsigned int)blkSize;
}
}
// v3: collect setStakeSeen entries (prevoutStake, nStakeTime) from the
// last N PoS blocks. Required so a snapshot-loaded node has the recent
// stake-collision set restored without walking blocks at startup.
static const unsigned int STAKE_SEEN_DEPTH = 5000; // 10x LoadBlockIndex default
std::vector<std::pair<COutPoint, unsigned int> > vStakeSeen;
{
CBlockIndex* pindex = pindexBest;
unsigned int nVisited = 0;
while (pindex && nVisited < STAKE_SEEN_DEPTH) {
if (pindex->IsProofOfStake()) {
vStakeSeen.push_back(std::make_pair(pindex->prevoutStake, pindex->nStakeTime));
}
pindex = pindex->pprev;
nVisited++;
}
}
unsigned int numStakeSeen = (unsigned int)vStakeSeen.size();
uint256 contentHash; // placeholder, filled after writing data
fwrite(&magic, sizeof(magic), 1, file);
@@ -122,6 +139,7 @@ bool DumpSnapshot(const fs::path& destPath,
fwrite(&numHeaders, sizeof(numHeaders), 1, file);
fwrite(&numUtxos, sizeof(numUtxos), 1, file);
fwrite(&numBlocks, sizeof(numBlocks), 1, file); // v2+
fwrite(&numStakeSeen, sizeof(numStakeSeen), 1, file); // v3+
long contentHashPos = ftell(file);
fwrite(&contentHash, sizeof(contentHash), 1, file); // placeholder
@@ -195,14 +213,40 @@ bool DumpSnapshot(const fs::path& destPath,
// Update actual count (in case it changed during iteration)
if (nWritten != numUtxos) {
numUtxos = nWritten;
// Seek back and update numUtxos in header
// Seek back and update numUtxos in header.
// Header layout (v3):
// magic(4) + version(4) + network(4) + height(4) + blockHash(32)
// + moneySupply(8) + numHeaders(4) + numUtxos(4)
// + numBlocks(4) + numStakeSeen(4) + contentHash(32)
// contentHashPos is the offset of contentHash. numUtxos is at
// contentHashPos - sizeof(contentHash) - sizeof(numStakeSeen)
// - sizeof(numBlocks) - sizeof(numUtxos).
long currentPos = ftell(file);
fseek(file, contentHashPos - sizeof(numUtxos), SEEK_SET);
fseek(file, contentHashPos - sizeof(uint256) - sizeof(numStakeSeen)
- sizeof(numBlocks) - sizeof(numUtxos), SEEK_SET);
fwrite(&numUtxos, sizeof(numUtxos), 1, file);
fseek(file, currentPos, SEEK_SET);
}
}
// v3: After UTXOs, write the setStakeSeen entries collected from the last
// N PoS blocks. Format: a length-prefixed flat array of
// (COutPoint prevout, unsigned int nStakeTime) records.
if (version >= 3) {
printf("UtxoSnapshot: writing %d setStakeSeen entries...\n", numStakeSeen);
for (unsigned int i = 0; i < vStakeSeen.size(); i++) {
CDataStream ssEntry(SER_DISK, CLIENT_VERSION);
ssEntry << vStakeSeen[i].first; // COutPoint (hash + index)
ssEntry << vStakeSeen[i].second; // nStakeTime
unsigned int entrySize = (unsigned int)ssEntry.size();
std::string strEntry = ssEntry.str();
fwrite(&entrySize, sizeof(entrySize), 1, file);
fwrite(strEntry.data(), 1, entrySize, file);
SHA256_Update(&sha256, &entrySize, sizeof(entrySize));
SHA256_Update(&sha256, strEntry.data(), entrySize);
}
}
// v2: After UTXOs, append raw blk0001.dat content. Streams in chunks;
// SHA256 covers the bytes. A snapshot-loaded node has full block data
// ready in datadir/blk0001.dat — no separate bootstrap needed.
@@ -290,7 +334,7 @@ bool LoadSnapshot(const fs::path& snapshotPath,
int height;
uint256 blockHash;
int64_t moneySupply;
unsigned int numHeaders = 0, numUtxos = 0, numBlocks = 0;
unsigned int numHeaders = 0, numUtxos = 0, numBlocks = 0, numStakeSeen = 0;
uint256 expectedContentHash;
if (fread(&magic, sizeof(magic), 1, file) != 1 ||
@@ -305,7 +349,7 @@ bool LoadSnapshot(const fs::path& snapshotPath,
strError = "Truncated snapshot header (common fields)";
return false;
}
// v2+ has numBlocks between numUtxos and contentHash. v1 stops here.
// v2+ has numBlocks between numUtxos and (numStakeSeen|contentHash).
if (version >= 2) {
if (fread(&numBlocks, sizeof(numBlocks), 1, file) != 1) {
fclose(file);
@@ -313,6 +357,14 @@ bool LoadSnapshot(const fs::path& snapshotPath,
return false;
}
}
// v3+ has numStakeSeen before contentHash.
if (version >= 3) {
if (fread(&numStakeSeen, sizeof(numStakeSeen), 1, file) != 1) {
fclose(file);
strError = "Truncated snapshot header (numStakeSeen)";
return false;
}
}
if (fread(&expectedContentHash, sizeof(expectedContentHash), 1, file) != 1) {
fclose(file);
strError = "Truncated snapshot header (contentHash)";
@@ -522,6 +574,46 @@ bool LoadSnapshot(const fs::path& snapshotPath,
success = false;
}
// v3: After UTXOs (before the embedded blocks), read the setStakeSeen
// entries collected from the last N PoS blocks of the source chain.
// Required so a snapshot-loaded node has the recent stake-collision set
// restored immediately, without having to walk blocks at startup. This
// is what lets the anti-spam "too little proof-of-stake" check in
// ProcessBlock function correctly right after a snapshot bootstrap.
if (success && version >= 3 && numStakeSeen > 0) {
printf("UtxoSnapshot: loading %d setStakeSeen entries...\n", numStakeSeen);
// setStakeSeen is declared in main.cpp — we reference it via the
// header declaration. Clear first so the snapshot's view is authoritative.
setStakeSeen.clear();
unsigned int nLoadedStakeSeen = 0;
for (unsigned int i = 0; i < numStakeSeen; i++) {
unsigned int entrySize;
if (fread(&entrySize, sizeof(entrySize), 1, file) != 1 || entrySize > 1000) {
success = false;
strError = "Invalid setStakeSeen entry size at index " + std::to_string(i);
break;
}
std::vector<char> buf(entrySize);
if (fread(buf.data(), 1, entrySize, file) != entrySize) {
success = false;
strError = "Truncated setStakeSeen entry at index " + std::to_string(i);
break;
}
SHA256_Update(&sha256, &entrySize, sizeof(entrySize));
SHA256_Update(&sha256, buf.data(), entrySize);
CDataStream ssEntry(buf.data(), buf.data() + buf.size(), SER_DISK, CLIENT_VERSION);
COutPoint prevout;
unsigned int nStakeTime;
ssEntry >> prevout;
ssEntry >> nStakeTime;
setStakeSeen.insert(std::make_pair(prevout, nStakeTime));
nLoadedStakeSeen++;
}
if (success)
printf("UtxoSnapshot: loaded %d setStakeSeen entries\n", nLoadedStakeSeen);
}
// v2: After UTXOs, extract the raw blk0001.dat content. This makes the
// loaded node fully self-contained — no separate bootstrap needed.
if (success && version >= 2 && numBlocks > 0) {
@@ -552,6 +644,108 @@ bool LoadSnapshot(const fs::path& snapshotPath,
}
}
// Build the transaction index (txindex) from the freshly-extracted blk0001.dat.
// The snapshot loads the UTXO set and blk0001.dat but does NOT rebuild the
// per-tx index that CTransaction::ReadFromDisk requires for stake-input
// signature verification. Without this, a new PoS block referencing any
// pre-snapshot tx would fail CheckProofOfStake with "read txPrev failed"
// and be rejected with DoS=100, stalling the node at the snapshot height.
//
// Walk every block in blk0001.dat and record CDiskTxPos for each tx, so
// the loaded chain is fully self-contained. The walk is O(N) over the
// historical block range but uses the already-cached blocks on disk and
// batches the writes (every 5000 txs).
if (success) {
printf("UtxoSnapshot: building transaction index from blk0001.dat...\n");
fs::path blkPath = GetDataDir() / "blk0001.dat";
FILE* blkFile = fopen(blkPath.string().c_str(), "rb");
if (!blkFile) {
success = false;
strError = "Cannot open blk0001.dat for txindex build: " + blkPath.string();
} else {
CAutoFile blkdat(blkFile, SER_DISK, CLIENT_VERSION);
if (!txdb.TxnBegin()) {
success = false;
strError = "Failed to begin txindex build transaction";
} else {
unsigned int nPos = 0;
unsigned int nBlocksIndexed = 0;
unsigned int nTxsIndexed = 0;
unsigned int nBatchTxs = 0;
int64_t nLastReport = GetTimeMillis();
while (success && blkdat.good()) {
fseek(blkdat, nPos, SEEK_SET);
// Locate block magic
unsigned char pchData[65536];
int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
if (nRead <= 8) break;
void* nFind = memchr(pchData, pchMessageStart[0], nRead + 1 - sizeof(pchMessageStart));
if (!nFind) {
// Reached the tail of the file
break;
}
if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart)) != 0) {
nPos += ((unsigned char*)nFind - pchData) + 1;
continue;
}
unsigned int nBlockStart = nPos + ((unsigned char*)nFind - pchData);
fseek(blkdat, nBlockStart + sizeof(pchMessageStart), SEEK_SET);
unsigned int nSize;
blkdat >> nSize;
if (nSize == 0 || nSize > MAX_BLOCK_SIZE) {
nPos = nBlockStart + sizeof(pchMessageStart) + 4;
continue;
}
CBlock block;
blkdat >> block;
// For each tx in the block, record the disk position.
// nTxPos is the offset of the tx *within* the block (after
// magic+size for the first tx, then serialize-size of
// preceding txs). We use the post-serialize offset of each
// tx as nTxPos, matching the convention in ConnectBlock.
unsigned int nTxPos = sizeof(pchMessageStart) + sizeof(unsigned int); // offset of first tx in block
for (const CTransaction& tx : block.vtx) {
CDiskTxPos posThisTx(1, nBlockStart, nTxPos);
txdb.UpdateTxIndex(tx.GetHash(), CTxIndex(posThisTx, tx.vout.size()));
nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
nTxsIndexed++;
nBatchTxs++;
}
nBlocksIndexed++;
// Advance past this block to scan the next one
nPos = nBlockStart + sizeof(pchMessageStart) + sizeof(unsigned int) + nSize;
// Commit batch periodically to avoid unbounded memory
if (nBatchTxs >= 5000) {
if (!txdb.TxnCommit()) {
success = false;
strError = "txindex batch commit failed";
break;
}
if (!txdb.TxnBegin()) {
success = false;
strError = "txindex batch restart failed";
break;
}
nBatchTxs = 0;
if (GetTimeMillis() - nLastReport > 5000) {
printf("UtxoSnapshot: indexed %u blocks / %u txs (pos=%u)\n",
nBlocksIndexed, nTxsIndexed, nPos);
nLastReport = GetTimeMillis();
}
}
}
if (success && !txdb.TxnCommit()) {
success = false;
strError = "Final txindex commit failed";
}
if (success) {
printf("UtxoSnapshot: built txindex for %u blocks / %u transactions\n",
nBlocksIndexed, nTxsIndexed);
}
}
}
}
// Verify content hash
if (success) {
uint256 actualHash;
+9 -1
View File
@@ -11,7 +11,15 @@
static const unsigned int UTXO_SNAPSHOT_MAGIC = 0x53585455; // "UTXS" little-endian
// UTXO snapshot format version
static const unsigned int UTXO_SNAPSHOT_VERSION = 2;
// v1: original (headers + UTXOs)
// v2: + embeds raw blk0001.dat for full self-contained bootstrap
// v3: + carries setStakeSeen entries (prevoutStake, nStakeTime) so a
// snapshot-loaded node has the recent PoS stake-collision set restored
// immediately, without needing to walk the last N blocks on startup.
// Required for the anti-spam "too little proof-of-stake" check in
// ProcessBlock to work correctly post-snapshot-bootstrap, since
// LoadBlockIndex only walks 500 blocks back from pindexBest.
static const unsigned int UTXO_SNAPSHOT_VERSION = 3;
// Number of block index entries to include in snapshot (covers difficulty,
// median time, stake modifier, and reorg depth requirements)
+37 -3
View File
@@ -221,8 +221,10 @@ bool CWallet::Lock()
if (fDebug)
printf("Locking wallet.\n");
if (IsCrypted())
hdMnemonic.clear(); // keep only the encrypted copy while locked
if (IsCrypted()) {
hdMnemonic.clear(); // keep only the encrypted copies while locked
hdPassphrase.clear();
}
{
LOCK(cs_wallet);
@@ -254,6 +256,11 @@ bool CWallet::Unlock(const SecureString& strWalletPassphrase)
if (DecryptSecret(vMasterKey, vchCryptedHDMnemonic, hdMnemonicIV, sec))
hdMnemonic.assign(sec.begin(), sec.end());
}
if (fHDEnabled && hdPassphrase.empty() && !vchCryptedHDPassphrase.empty()) {
CSecret psec;
if (DecryptSecret(vMasterKey, vchCryptedHDPassphrase, hdPassphraseIV, psec))
hdPassphrase.assign(psec.begin(), psec.end());
}
return true;
}
}
@@ -436,6 +443,14 @@ bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
hdMnemonicIV = iv; vchCryptedHDMnemonic = cipher;
dbEnc->WriteHDCryptedMnemonic(iv, cipher);
}
if (fHDEnabled && !hdPassphrase.empty()) {
CSecret psec(hdPassphrase.begin(), hdPassphrase.end());
uint256 piv = GetRandHash();
std::vector<unsigned char> pcipher;
if (!EncryptSecret(vMasterKey, psec, piv, pcipher)) { dbEnc->TxnAbort(); return false; }
hdPassphraseIV = piv; vchCryptedHDPassphrase = pcipher;
dbEnc->WriteHDCryptedPassphrase(piv, pcipher);
}
SetMinVersion(WalletFeature::WalletCrypt, dbEnc.get(), true);
@@ -2933,8 +2948,11 @@ bool CWallet::DeriveHDKey(int64_t index, CKey& keyOut) const
{
if (hdMnemonic.empty())
return false;
// If a BIP39 passphrase ("25th word") was set with the seed, it MUST be
// part of every derivation — otherwise restored wallets derive different
// addresses than the originals. Empty string = no passphrase (legacy).
unsigned char priv[32];
if (!hd::DeriveTriangles(hdMnemonic, "", 0, 0, (uint32_t)index, priv))
if (!hd::DeriveTriangles(hdMnemonic, hdPassphrase, 0, 0, (uint32_t)index, priv))
return false;
CSecret secret(priv, priv + 32);
memset(priv, 0, sizeof(priv));
@@ -2968,6 +2986,7 @@ bool CWallet::SetHDSeed(const std::string& mnemonicIn, const std::string& passph
memset(priv, 0, sizeof(priv));
hdMnemonic = m;
hdPassphrase = passphrase;
fHDEnabled = true;
nHDChainIndex = 0;
@@ -2980,8 +2999,23 @@ bool CWallet::SetHDSeed(const std::string& mnemonicIn, const std::string& passph
if (!EncryptSecret(vMasterKey, sec, iv, cipher)) { strError = "Failed to encrypt seed."; return false; }
hdMnemonicIV = iv; vchCryptedHDMnemonic = cipher;
wdb.WriteHDCryptedMnemonic(iv, cipher);
if (!passphrase.empty()) {
CSecret psec(passphrase.begin(), passphrase.end());
uint256 piv = GetRandHash();
std::vector<unsigned char> pcipher;
if (!EncryptSecret(vMasterKey, psec, piv, pcipher)) { strError = "Failed to encrypt passphrase."; return false; }
hdPassphraseIV = piv; vchCryptedHDPassphrase = pcipher;
wdb.WriteHDCryptedPassphrase(piv, pcipher);
} else {
vchCryptedHDPassphrase.clear();
wdb.EraseHDPassphrase(); // re-seed without passphrase: drop any old record
}
} else {
wdb.WriteHDMnemonic(m);
if (!passphrase.empty())
wdb.WriteHDPassphrase(passphrase);
else
wdb.EraseHDPassphrase();
}
wdb.WriteHDChain(nHDChainIndex);
}
+5
View File
@@ -132,6 +132,9 @@ public:
std::string hdMnemonic; // in-memory phrase (present when unlocked/unencrypted)
std::vector<unsigned char> vchCryptedHDMnemonic; // encrypted phrase (loaded, decrypted on unlock)
uint256 hdMnemonicIV; // IV for the encrypted phrase
std::string hdPassphrase; // BIP39 "25th word"; empty = none. Same lifecycle as hdMnemonic.
std::vector<unsigned char> vchCryptedHDPassphrase; // encrypted passphrase (loaded, decrypted on unlock)
uint256 hdPassphraseIV; // IV for the encrypted passphrase
// check whether we are allowed to upgrade (or already support) to the named feature
bool CanSupportFeature(WalletFeature wf) { return nWalletMaxVersion >= static_cast<int>(wf); }
@@ -150,6 +153,8 @@ public:
bool DeriveHDKey(int64_t index, CKey& keyOut) const;
bool LoadHDMnemonic(const std::string& m) { hdMnemonic = m; fHDEnabled = true; return true; }
bool LoadCryptedHDMnemonic(const uint256& iv, const std::vector<unsigned char>& cipher) { hdMnemonicIV = iv; vchCryptedHDMnemonic = cipher; fHDEnabled = true; return true; }
bool LoadHDPassphrase(const std::string& p) { hdPassphrase = p; return true; }
bool LoadCryptedHDPassphrase(const uint256& iv, const std::vector<unsigned char>& cipher) { hdPassphraseIV = iv; vchCryptedHDPassphrase = cipher; return true; }
// Adds a key to the store, and saves it to disk.
bool AddKey(const CKey& key);
// Adds a key to the store, without saving it to disk (used by LoadWallet)
+10 -1
View File
@@ -265,7 +265,8 @@ static bool IsKeyType(const std::string& strType)
{
return (strType == "key" || strType == "wkey" ||
strType == "mkey" || strType == "ckey" ||
strType == "hdmnemonic" || strType == "hdcmnemonic");
strType == "hdmnemonic" || strType == "hdcmnemonic" ||
strType == "hdpassphrase" || strType == "hdcpassphrase");
}
static bool ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
@@ -414,6 +415,14 @@ static bool ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssVa
std::pair<uint256, std::vector<unsigned char>> cm;
ssValue >> cm;
pwallet->LoadCryptedHDMnemonic(cm.first, cm.second);
} else if (strType == "hdpassphrase") {
std::string p;
ssValue >> p;
pwallet->LoadHDPassphrase(p);
} else if (strType == "hdcpassphrase") {
std::pair<uint256, std::vector<unsigned char>> cp;
ssValue >> cp;
pwallet->LoadCryptedHDPassphrase(cp.first, cp.second);
} else if (strType == "hdchain") {
int64_t n;
ssValue >> n;
+19
View File
@@ -178,6 +178,25 @@ public:
nWalletDBUpdated++;
return Write(std::string("hdchain"), nIndex);
}
// BIP39 passphrase ("25th word"). Same plaintext/crypted lifecycle as the
// mnemonic: exactly one of the two records exists at a time; both absent
// means no passphrase (legacy wallets and the common case).
bool WriteHDPassphrase(const std::string& passphrase) {
nWalletDBUpdated++;
Erase(std::string("hdcpassphrase"));
return Write(std::string("hdpassphrase"), passphrase);
}
bool WriteHDCryptedPassphrase(const uint256& iv, const std::vector<unsigned char>& cipher) {
nWalletDBUpdated++;
Erase(std::string("hdpassphrase"));
return Write(std::string("hdcpassphrase"), std::make_pair(iv, cipher));
}
bool EraseHDPassphrase() {
nWalletDBUpdated++;
Erase(std::string("hdpassphrase"));
Erase(std::string("hdcpassphrase"));
return true;
}
bool ReadPool(int64_t nPool, CKeyPool& keypool)
{