Files
salvium-rs/test/debug-specific-output.js
T
Matt Hess 7f01cafc62 Crypto layer consolidation: eliminate JS scalar ops, add cn_scan + RCT batch verify
Crypto Backend Refactoring
   ──────────────────────────
   - Delete src/ed25519.js — all scalar/point operations now route through
     the crypto provider (WASM/FFI/JSI backends only)
   - Remove duplicate JS BigInt implementations of scReduce32, scReduce64,
     scalarAdd, scalarMul from scanning.js, carrot.js, and carrot-scanning.js;
     delegate to Rust backend via crypto/index.js
   - Remove debug/test exports from index.js (randomPoint, testDouble,
     getBasePoint, isOnCurve, etc.) that were only used during development
   - Rebuild WASM binary (476KB → 487KB) with updated Rust crate

   Consolidated CryptoNote Scanner (cn_scan)
   ─────────────────────────────────────────
   - New Rust module crates/salvium-crypto/src/cn_scan.rs replaces 5-12
     individual FFI round-trips per output with a single native call:
     view tag check → derive subaddress pubkey → subaddress map lookup →
     amount decryption → commitment mask → key image generation
   - FFI wrapper salvium_cn_scan_output in ffi.rs + C header declaration
   - FFI backend scanCnOutput() with full subaddress map marshaling
     (32-byte key + u32 major/minor LE per entry) and JSON result parsing
   - JSI backend delegation via this.native.cnScanOutput()
   - wallet-sync.js _scanCNOutput() tries native path first when available
     (FFI/JSI), falls through to existing JS pipeline for WASM/JS backends
   - Change pub(crate) visibility on subaddress.rs cn_subaddress_secret_key
   - 8 Rust unit tests covering view tag, amount, commitment mask,
     subaddress matching, and key image generation
   - Verified identical results: WASM (JS fallback) and FFI (native cn_scan)
     produce same 964 outputs at same chain height; FFI is 3x faster sync
     (0.8s vs 2.5s) with 12x less heap (12MB vs 150MB)

   RCT Batch Signature Verification
   ─────────────────────────────────
   - New Rust module crates/salvium-crypto/src/rct_verify.rs — single-call
     verification of all ring signatures in a transaction (CLSAG + TCLSAG),
     avoiding N individual JS↔Rust boundary crossings
   - Computes pre-MLSAG message hash matching C++ get_pre_mlsag_hash
   - FFI export salvium_verify_rct_signatures with flat byte array interface
   - FFI backend verifyRctSignatures() method
   - JS backend stub returns null (validation.js handles JS fallback)
   - validation.js: 200+ lines of RCT verification logic including
     flattenKeyImages, packTclsagSigsFlat, packClsagSigsFlat helpers

   Transaction Expansion
   ─────────────────────
   - transaction.js: add expandTransaction() matching C++ expand_transaction_2
     (copies key images from prefix inputs into TCLSAG/CLSAG signature structs)
   - New test/expand-transaction.test.js (634 lines)
   - New test/rct-verify-testnet.test.js (430 lines)

   Mining Resilience
   ─────────────────
   - salvium-miner main.rs: retry get_info and get_block_template up to 5
     times with 2s delay for transient daemon errors
   - full-testnet.js mineTo(): retry miner up to 3 times with 3s delay,
     check for partial progress between attempts

   Testnet Tooling
   ───────────────
   - sync-only.js: CRYPTO_BACKEND env var for A/B testing (wasm vs ffi)
   - full-testnet.js: daemon URL update (node12.whiskymine.io)
   - Debug scripts for cn_scan development (debug-cn-scan/marshal/match/wasm)
   - Android .gitignore and build-bundle.sh for mobile builds
2026-02-14 17:02:35 +00:00

109 lines
4.3 KiB
JavaScript

#!/usr/bin/env bun
/**
* Debug specific CARROT output commitment mismatch
*/
import { DaemonRPC } from '../src/rpc/daemon.js';
import { MemoryStorage } from '../src/wallet-store.js';
import { readFileSync } from 'fs';
import { commit } from '../src/crypto/index.js';
import { parseTransaction } from '../src/transaction/parsing.js';
function hexToBytes(hex) {
if (typeof hex !== 'string') return hex;
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < bytes.length; i++) {
bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
}
return bytes;
}
function bytesToHex(bytes) {
return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
}
const daemon = new DaemonRPC({ url: 'http://node12.whiskymine.io:29081' });
// Load cached sync state
const CACHE_FILE = '/home/mxhess/testnet-wallet/wallet-a-sync.json';
const storage = new MemoryStorage();
const cached = JSON.parse(readFileSync(CACHE_FILE, 'utf-8'));
storage.load(cached);
const allOutputs = await storage.getOutputs({ isSpent: false });
// Find CARROT outputs with commitments that DON'T match mask*G + amount*H
const mismatchOutputs = [];
for (const o of allOutputs) {
if (!o.mask || !o.commitment) continue;
const maskBytes = hexToBytes(o.mask);
const computed = commit(BigInt(o.amount), maskBytes);
if (bytesToHex(computed) !== o.commitment) {
mismatchOutputs.push(o);
}
}
console.log(`Total outputs: ${allOutputs.length}`);
console.log(`Outputs with commitment mismatch: ${mismatchOutputs.length}`);
console.log(` CARROT: ${mismatchOutputs.filter(o => o.isCarrot).length}`);
console.log(` Non-CARROT: ${mismatchOutputs.filter(o => !o.isCarrot).length}`);
// Analyze first few mismatches
for (const output of mismatchOutputs.slice(0, 3)) {
console.log(`\n=== Output ${output.txHash.slice(0, 16)}..., idx ${output.outputIndex} ===`);
console.log(` isCarrot: ${output.isCarrot}`);
console.log(` assetType: ${output.assetType}`);
console.log(` blockHeight: ${output.blockHeight}`);
console.log(` amount: ${output.amount}`);
console.log(` mask: ${output.mask.slice(0, 32)}...`);
console.log(` stored commitment: ${output.commitment.slice(0, 32)}...`);
const maskBytes = hexToBytes(output.mask);
const computed = commit(BigInt(output.amount), maskBytes);
console.log(` computed commitment: ${bytesToHex(computed).slice(0, 32)}...`);
// Try to fetch the TX from daemon
try {
const txResp = await daemon.getTransactions([output.txHash], true, false);
const txData = txResp.result?.txs?.[0] || txResp.txs?.[0];
if (txData?.as_hex) {
// Parse from binary
const txBytes = hexToBytes(txData.as_hex);
const parsed = parseTransaction(txBytes);
console.log(` Parsed rctType: ${parsed.rct?.type}`);
console.log(` Parsed outPk count: ${parsed.rct?.outPk?.length || 0}`);
if (parsed.rct?.outPk?.[output.outputIndex]) {
const parsedCommitment = bytesToHex(parsed.rct.outPk[output.outputIndex]);
console.log(` Parsed outPk[${output.outputIndex}]: ${parsedCommitment.slice(0, 32)}...`);
console.log(` outPk matches stored: ${parsedCommitment === output.commitment}`);
// Verify: does outPk from blockchain match computed?
console.log(` outPk matches computed: ${parsedCommitment === bytesToHex(computed)}`);
}
} else if (txData?.as_json) {
const txJson = JSON.parse(txData.as_json);
console.log(` JSON rctType: ${txJson.rct_signatures?.type}`);
const outPk = txJson.rct_signatures?.outPk;
if (outPk?.[output.outputIndex]) {
console.log(` JSON outPk[${output.outputIndex}]: ${outPk[output.outputIndex].slice(0, 32)}...`);
}
} else {
console.log(` TX has no as_hex or as_json`);
}
} catch (e) {
console.log(` Error: ${e.message}`);
}
}
// Also count: how many outputs have CORRECT commitments?
const matchOutputs = allOutputs.filter(o => {
if (!o.mask || !o.commitment) return false;
const maskBytes = hexToBytes(o.mask);
const computed = commit(BigInt(o.amount), maskBytes);
return bytesToHex(computed) === o.commitment;
});
console.log(`\nOutputs with CORRECT commitment: ${matchOutputs.length}`);
console.log(` CARROT: ${matchOutputs.filter(o => o.isCarrot).length}`);
console.log(` Non-CARROT: ${matchOutputs.filter(o => !o.isCarrot).length}`);