Files
salvium-rs/test/debug-raw-tx.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

98 lines
4.3 KiB
JavaScript

#!/usr/bin/env bun
/**
* Raw TX hex analysis - manually find outPk position and verify parsing.
* Also try using the daemon's view of the commitment directly.
*/
import { setCryptoBackend, commit } from '../src/crypto/index.js';
import { DaemonRPC } from '../src/rpc/daemon.js';
await setCryptoBackend('wasm');
function hexToBytes(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' });
const txHash = 'd2ad187cc0dde491ae6134c8ad2df9188646859ecf2974271375f5257a51ada2';
const txResp = await daemon.getTransactions([txHash], { decode_as_json: true, prune: false });
const txData = txResp.result?.txs?.[0] || txResp.txs?.[0];
const rawHex = txData.as_hex;
// Find the outPk in the raw hex
const outPk0 = 'fdd6e627997742579544cc64529aeb73a7b3770555bbc73056786adccfea15e4';
const outPk1 = '2e9c3b33757e6ad2461b139e220d9968c8d5780f58bd51c719f2f6124b88f584';
const ecdhAmount0 = '1b48655a3f838e68';
const posOutPk0 = rawHex.indexOf(outPk0);
const posOutPk1 = rawHex.indexOf(outPk1);
const posEcdh0 = rawHex.indexOf(ecdhAmount0);
console.log(`Raw TX hex length: ${rawHex.length} chars (${rawHex.length/2} bytes)`);
console.log(`outPk[0] position in hex: ${posOutPk0} (byte ${posOutPk0/2})`);
console.log(`outPk[1] position in hex: ${posOutPk1} (byte ${posOutPk1/2})`);
console.log(`ecdhInfo[0].amount position: ${posEcdh0} (byte ${posEcdh0/2})`);
console.log(`Distance outPk0-outPk1: ${posOutPk1 - posOutPk0} chars (${(posOutPk1 - posOutPk0)/2} bytes)`);
// Show context around outPk
if (posOutPk0 >= 0) {
const before = rawHex.slice(Math.max(0, posOutPk0 - 20), posOutPk0);
const after = rawHex.slice(posOutPk0 + 64, posOutPk0 + 84);
console.log(`\nBefore outPk0: ...${before}`);
console.log(`outPk0: ${outPk0}`);
console.log(`After outPk0: ${after}...`);
}
// Now let's try something completely different: use the daemon's get_outs RPC
// to get the commitment for this output, which is what ring members use.
// But we'd need the global output index...
// Let's check if our amount + commitment works with a different approach.
// What if we need to REVERSE the comparison: find what mask produces outPk?
// C_a = mask*G + amount*H
// C_a - amount*H = mask*G
// So mask*G = outPk - amount*H
// And amount*H = commit(amount, 0)
const zeroMask = new Uint8Array(32);
const amountH = commit(2366447376n, zeroMask); // amount*H
console.log(`\namount*H = ${bytesToHex(amountH)}`);
// Now outPk - amount*H should = mask*G
// Use point subtraction: outPk + (-(amount*H))
import { pointAddCompressed, scalarMultBase } from '../src/crypto/index.js';
const negAmountH = new Uint8Array(amountH);
negAmountH[31] ^= 0x80; // Negate point
const maskG = pointAddCompressed(hexToBytes(outPk0), negAmountH);
console.log(`maskG = outPk - amount*H: ${bytesToHex(maskG)}`);
// If our derived mask is correct, then scalarMultBase(mask) should equal maskG
const mask = hexToBytes('803b135e5613cdf4905268b48e408213b336ac491d81b67ce1adaf8d6673d004');
const expectedMaskG = scalarMultBase(mask);
console.log(`scalarMultBase(our mask): ${bytesToHex(expectedMaskG)}`);
console.log(`maskG == scalarMultBase(mask): ${bytesToHex(maskG) === bytesToHex(expectedMaskG)}`);
// What is the actual mask that would produce outPk?
// We can't easily derive the scalar, but we can check if maskG is a known point
console.log(`\n=== Are we using the right H point? ===`);
const H = commit(1n, zeroMask); // 0*G + 1*H = H
console.log(`H point: ${bytesToHex(H)}`);
// Check if maybe outPk uses zeroCommit formula instead of commit
import { getCryptoBackend } from '../src/crypto/provider.js';
const backend = getCryptoBackend();
const zc = backend.zeroCommit(2366447376n);
console.log(`\nzeroCommit(amount): ${bytesToHex(zc)}`);
console.log(`zeroCommit == outPk: ${bytesToHex(zc) === outPk0}`);
// What if the amount needs to be in piconero (atomic units)?
// 2366447376 might already be atomic units, or might need conversion
console.log(`\nAmount: ${2366447376}`);
console.log(`Amount / 1e12 = ${2366447376 / 1e12} SAL`);
console.log(`Amount / 1e8 = ${2366447376 / 1e8} SAL`);