Commit Graph

183 Commits

Author SHA1 Message Date
Matt Hess 4696eddf31 Add browser support for WASM crypto loader
Replace static fs/path imports with dynamic environment detection.
  Node/Bun uses fs.readFile, browsers use fetch() with import.meta.url
  resolution for bundler compatibility
2026-02-01 03:42:29 +00:00
Matt Hess 9c6b2943b9 Add composite crypto functions to provider and rewire remaining imports
Add 17 new provider-level functions (derivationToScalar, deriveViewTag,
  ecdhDecodeFull, computeCarrotSpendPubkey, randomScalar, etc.) that
  compose backend primitives. Rewire all consumer files to import through
  the crypto provider. Only internal JS point serialization (pointFromBytes/
  pointToBytes) and source implementation files retain direct imports.
2026-02-01 03:39:36 +00:00
Matt Hess 64d9d40470 Export WasmCryptoBackend from crypto module public API 2026-02-01 03:31:23 +00:00
Matt Hess 0bbb7bd6f0 Wire crypto provider into transaction, wallet, and scanning code
Switch 16 consumer files from direct crypto imports to the switchable
  crypto provider. setCryptoBackend('wasm') now accelerates all real
  transaction building, output scanning, and key derivation end-to-end.
  Source implementation files (keccak.js, ed25519.js, scanning.js, etc.)
  keep direct imports to avoid circular dependencies.
2026-02-01 03:29:45 +00:00
Matt Hess 0bf0c9e4b3 Add Pedersen commitment functions to WASM crypto backend (Phase 4)
Implement pedersen_commit, zero_commit, and gen_commitment_mask in Rust
  with hardcoded H generator point. All 56 equivalence tests pass including
  homomorphic property verification: commit(a,m) - zeroCommit(a) = m*G.
2026-02-01 01:24:43 +00:00
Matt Hess 638171efe1 Add Ed25519 scalar and point operations to WASM crypto backend (Phase 2)
Adds 16 operations via curve25519-dalek: scAdd, scSub, scMul, scMulAdd,
  scMulSub, scReduce32, scReduce64, scInvert, scCheck, scIsZero,
  scalarMultBase, scalarMultPoint, pointAddCompressed, pointSubCompressed,
  pointNegate, doubleScalarMultBase. Uses variable-time Straus algorithm
  for point multiplication. All 44 equivalence tests pass byte-for-byte.
  Benchmarks: scMulAdd 3.5x, scalarMultBase 2.3x, pointAdd 16.7x faster.
2026-01-31 22:36:10 +00:00
Matt Hess 2486d1f00f ● Add Rust WASM crypto backend with provider pattern for runtime switching
Phase 1: keccak256 and blake2b compiled from Rust via wasm-pack (23KB).
  Provider pattern enables switching between JS and WASM backends at runtime
  while keeping all existing JS crypto code intact. Equivalence tests confirm
  byte-for-byte matching across all inputs. Benchmarks: keccak256 ~4.6x faster,
  blake2b ~15x faster with WASM backend.
2026-01-31 20:50:04 +00:00
Matt Hess 4bbcb8afe1 Add transaction sending to testnet with full CLSAG ring signature pipeline
Exercises the complete transfer flow on the self-contained testnet:
UTXO selection, gamma-distribution decoy selection, ring member
fetching, buildTransaction with CLSAG signing, mempool submission,
block mining, and recipient wallet scanning.

Key changes:
- TestnetNode: global output index, spent key image tracking,
  getOuts/getOutputDistribution/sendRawTransaction/isKeyImageSpent RPCs
- TestnetMiner: includes mempool user transactions in mined blocks
- Testnet.transfer(): end-to-end send from wallet to wallet
- WalletSync: fallback to JSON-based tx processing when as_hex unavailable
- 5 new tests covering transfer, change outputs, double-spend rejection
2026-01-31 17:24:44 +00:00
Matt Hess c7643663af Add self-contained testnet with CARROT hard fork support
Build a fully functional in-memory blockchain for integration testing:
- TestnetNode: daemon RPC-compatible interface backed by in-memory chain
- TestnetMiner: block assembly with real RandomX PoW (difficulty 1)
- Miner TX construction ported from C++ construct_miner_tx()
- Testnet orchestrator with wallet creation, sync, and balance tracking

Fix CARROT output creation to match C++ reference implementation:
- Use keyed Blake2b with SpFixedTranscript format (was unkeyed)
- Use X25519 curve for ECDH and ephemeral pubkeys (was Ed25519)
- Use blinding factor k_a=1 for coinbase outputs (was hash-derived)
- Handle coinbase clear-text amounts and zeroCommit in scanner
- Add isCarrot flag to WalletOutput model and serialization

20 tests, 105 assertions covering legacy and CARROT coinbase outputs
across the hard fork boundary at testnet height 1100.
2026-01-30 20:28:43 +00:00
Matt Hess dfc4651657 ● Fix fee estimation to match Salvium C++ source
Six bugs fixed in tx size/weight estimation: bp_base clawback formula,
  input key offset size, BP range proof size with +3 bytes, padded log
  starting at 2, estimateTransactionFee switched to per-byte weight,
  priority 0 default mapped to Normal. Added getDynamicBaseFee() and
  getDynamicBaseFee2021Scaling() 4-tier fee model. Added chain reorg
  handling: AlternativeChainManager, wallet reorg detection/rollback,
  storage rollback methods. 30 new tests.
2026-01-30 02:56:15 +00:00
Matt Hess 5aa7baad1e Update to README for TCLSAG additions 2026-01-28 16:54:22 +00:00
Matt Hess 206ff22614 ● Add TCLSAG signing and verification for SalviumOne (RCT type 9)
- Implement tclsagSign() with dual generators G and T
  - Implement tclsagVerify() with matching equations
  - Add 29 comprehensive tests for sign/verify round-trips
  - Update AUDIT.md to reflect full RingCT completeness
2026-01-28 16:37:30 +00:00
Matt Hess dd6fb7c817 transaction.js reduced from 5,426 to 2,206 lines (59% reduction).
Duplicated code replaced with re-exports from transaction/ submodules
  (constants, serialization, utxo, parsing, analysis, carrot-output).
  Unique code retained: output creation, CLSAG signing, decoy selection,
  fee estimation, and all transaction builders.
2026-01-28 13:41:51 +00:00
Matt Hess 164324a73b removed inaccurate copy/ paste of readme section 2026-01-28 13:08:17 +00:00
Matt Hess 85f30e107f ● Refactor transaction and wallet modules into focused submodules
Split large monolithic files into category-specific modules:

  Transaction module (src/transaction/):
  - constants.js: TX_TYPE, RCT_TYPE, fees, CARROT domains
  - serialization.js: Scalar ops, commitments, varint, tx serialization
  - utxo.js: UTXO selection strategies
  - parsing.js: Transaction/block/RingCT parsing
  - analysis.js: Hash calculation, amount decryption, summarization
  - carrot-output.js: CARROT key derivation and encryption
  - index.js: Re-exports for granular imports

  Block module (src/block/):
  - serialization.js: Block header, pricing record, merkle tree
  - index.js: Re-exports

  Wallet module (src/wallet/):
  - constants.js: WALLET_TYPE, subaddress limits
  - listener.js: WalletListener, ConsoleListener, CallbackListener
  - account.js: Account class
  - index.js: Re-exports
2026-01-27 00:01:33 +00:00
Matt Hess 27babe33f6 ● Add height-based hard fork detection for CARROT activation
- wallet.js: isCarrotEnabled() now uses sync height and network to
    automatically determine CARROT status based on HF activation heights
  - wallet.js: getHfVersion() derives version from sync height instead
    of relying on manually set value
  - wallet.js: Added _getNetworkId() to map network strings to NETWORK_ID
  - Mainnet CARROT activates at height 334750, testnet/stagenet at 1100
  - Falls back to stored _hfVersion when sync height is 0 (pre-sync)
2026-01-26 14:14:10 +00:00
Matt Hess 6eeadbe8ed ● Add transaction validation module and complete sweepDust
- Create src/validation.js with complete Salvium validation rules:
    - TX type/version validation (validateTxTypeAndVersion)
    - Asset type validation (SAL, SAL1, BURN rules)
    - Output validation (types, sorting, overflow checks)
    - RCT type validation by hard fork version
    - Input validation (ring size 16, key image sorting)
    - Fee validation with dynamic fee calculation
    - Miner/protocol TX validation
    - Yield payout calculation (calculateYieldPayout)
    - Comprehensive validateTransactionFull() combining all checks
  - Implement sweepDust in wallet.js with selective UTXO spending
  - Add 58 tests in test/validation.test.js
  - Export validation module from index.js
2026-01-26 12:24:44 +00:00
Matt Hess 43e1ebbef8 ● Add oracle/pricing system implementation
- Create src/oracle.js with complete pricing record support
  - Data structures: PricingRecord, AssetData, SupplyData (matching C++ pricing_record.h)
  - DSA/ECDSA signature verification with mainnet/testnet public keys
  - Conversion rate calculation with rounding (getConversionRate, getConvertedAmount)
  - Slippage calculation (1/32 = 3.125%) with refund logic
  - Pricing record validation (HF gates, timestamps, signatures)
  - JSON serialization/parsing for oracle responses
  - HTTP client for fetching pricing records from oracle server
  - Add 66 unit tests in test/oracle.test.js
  - Export oracle module from index.js
2026-01-26 11:45:08 +00:00
Matt Hess 4ba87a02d8 Add AUDIT transaction support for compliance audits
- Add buildAuditTransaction() in transaction.js
  - Add createAuditTransaction() in wallet.js
  - Change-is-zero requirement: all coins locked
  - Coins return via protocol_tx after maturity
  - 14 unit tests
  - Only valid during AUDIT hard fork periods (HF v6, v8)
2026-01-25 20:50:41 +00:00
Matt Hess 6e6743269e Add CONVERT transaction support for SAL<->VSD conversion
- Add buildConvertTransaction() in transaction.js
  - Add createConvertTransaction() in wallet.js
  - Oracle-priced conversion with 3.125% slippage
  - SAL <-> VSD only (other pairs rejected)
  - 15 unit tests + integration test
  - Note: Gated at HF v255, not yet enabled on mainnet
2026-01-25 13:11:31 +00:00
Matt Hess bc9412b5da ● Add BURN transaction support and security hardening
- Add buildBurnTransaction() and createBurnTransaction()
  - destination_asset_type = "BURN" for burned coins
  - 9 unit tests + integration test for BURN transactions
  - Remove hardcoded test mnemonics (use env vars)
  - Add pre-commit hook to detect potential secrets
  - Add testnet testing plan (test/TESTNET_PLAN.md)
  - Update .gitignore for secret files
2026-01-25 00:13:39 +00:00
Matt Hess ea09516981 ● Add proper error handling - eliminate silent failures
- Add ParseError class with context (offset, field, expected/actual)
  - transaction.js: parseRctSigPrunable throws instead of returning null
  - address.js: createAddress, toIntegratedAddress, toStandardAddress throw on invalid input
  - base58.js: decode functions throw descriptive errors
  - scanning.js: validate inputs and throw on failures
  - carrot-scanning.js: validate required fields
  - signature.js: remove debug console.log and testEd25519
  - Update tests to expect throws for error cases
2026-01-24 20:56:24 +00:00
Matt Hess 56ab4ec3fe Convert debug-full-carrot-scan.js and verify-real-carrot.js to use
environment variables instead of hardcoded SPEND_SECRET values.

  Required env vars: SPEND_SECRET, TX_HASH
  Optional: DAEMON_URL (defaults to seed01.salvium.io:19081)
2026-01-22 03:24:00 +00:00
Matt Hess aa716113f5 Add STAKE transaction creation and fix CLSAG verification
STAKE transactions:
  - Add buildStakeTransaction() for creating stake transactions
  - Add createStakeTransaction() wallet API for staking SAL/SAL1
  - Extend serializeTxPrefix() with Salvium-specific fields (txType,
    amount_burnt, asset types, return address, protocol_tx_data)
  - Support STAKE_LOCK_PERIOD from network config (21600 mainnet, 20 testnet)

  CLSAG fixes:
  - Fix challenge hash to include full ring data matching C++ implementation
  - Update both signing and verification to use consistent hash format
2026-01-22 03:10:40 +00:00
Matt Hess e751b6569a ● Add comprehensive test coverage for wallet modules
- Add tests for wallet-store.js (40 tests: MemoryStorage, WalletOutput, WalletTransaction)
  - Add tests for wallet-sync.js (25 tests: sync engine, events, progress tracking)
  - Add tests for query.js (45 tests: OutputQuery, TxQuery, TransferQuery, presets)
  - Add tests for connection-manager.js (29 tests: ConnectionInfo, failover, events)
  - Add tests for offline.js (29 tests: unsigned/signed tx, key images, output export)
  - Add tests for multisig.js (39 tests: KEX, signers, accounts, tx sets)
  - Add tests for persistent-wallet.js (27 tests: lifecycle, balance, outputs, sync)
  - Update test/all.js to include new test suites
  - Rename SYNC_UNLOCK_BLOCKS to avoid export conflict with wallet.js
2026-01-18 23:43:58 +00:00
Matt Hess 1066ca2110 Add full wallet implementation with storage, sync, and transaction support
New Features:
  - Wallet class with multi-account and subaddress support
  - PersistentWallet with blockchain sync and storage (Memory/IndexedDB)
  - Connection manager for daemon/wallet RPC failover
  - Query system for filtering outputs and transactions
  - Offline transaction signing (cold wallet support)
  - Multisig wallet support (N-of-M threshold signing)

  Daemon RPC:
  - Salvium-specific: getSupplyInfo(), getYieldInfo()
  - Mining control: startMining(), stopMining(), miningStatus()
  - Bandwidth/peer management, admin controls

  Transaction:
  - Full transaction building with UTXO selection
  - Transaction parsing and summarization
  - Fee estimation with priority levels
  - Decoy selection with gamma distribution

  Tests:
  - Wallet class tests (accounts, subaddresses, recovery)
  - Transaction builder and parser tests
  - UTXO selection tests
2026-01-18 21:39:05 +00:00
Matt Hess 7730b6993f ● Add AssemblyScript WASM VM for RandomX full mode
- Create assembly/vm.ts with full RandomX VM implementation
    - 256 instructions, 2048 iterations per hash
    - Native u64/f64 operations in WebAssembly
    - Full mode dataset lookups (2GB pre-computed)

  - Update miner to use WASM VM for full mode
    - mining-worker-asm.js uses pre-compiled WASM
    - ~32 H/s per thread (4x faster than light mode)
    - 8 threads achieves ~260 H/s

  - Clean up redundant code
    - Remove mining-worker-full.js (old JIT approach)
    - Consolidate 'asm' mode into 'full' mode
2026-01-18 01:16:10 +00:00
Matt Hess 714721874e Add RandomX proof-of-work implementation with WASM acceleration
- Full RandomX implementation (light mode + full mode)
   - WASM-accelerated Argon2d cache init (37x faster than pure JS)
   - WASM-accelerated SuperscalarHash with SIMD support
   - Parallel dataset generation using worker threads (8 workers)
   - Light mode: ~4s init, Full mode: ~8min init
   - Mining utilities (difficulty calculation, block construction)
   - Progress callbacks for long-running operations

   Performance targets 2023+ platforms (WASM SIMD: Chrome 91+,
   Firefox 89+, Safari 16.4+, Node 16.4+)
2026-01-15 19:19:27 +00:00
Matt Hess 2c128eb1c0 Add Bulletproofs+ range proof verification (pure JavaScript)
- Implement BP+ verification using @noble/curves for Ed25519 ops
  - MSM 256 points in ~420ms - mobile-friendly, no WASM needed
  - Add verifyBulletproofPlus, verifyBulletproofPlusBatch, verifyRangeProof
  - Add generator initialization with caching (Gi, Hi points)
  - 24 new tests including performance benchmarks
  - Update exports in index.js and package.json
  - Bump version to 0.3.0
2026-01-15 02:09:51 +00:00
Matt Hess 3658a0c33f New Features:
- generateSeed() - Cryptographically secure random seed generation
  - deriveKeys() - CryptoNote key derivation (spend/view secret & public keys)
  - deriveCarrotKeys() - CARROT key derivation (all 6 CARROT keys)
  - Blake2b tests with RFC 7693 test vectors
  - CryptoNote key derivation tests
  - CARROT key derivation tests
  - Updated exports in index.js
2026-01-14 23:59:27 +00:00
Matt Hess 5685d44ac0 bulk updates, sub addresses, integrated address, language support, and mnemonic 2026-01-05 22:31:03 +00:00
Matt Hess 52e12c94d0 README update 2026-01-05 03:14:37 +00:00
Matt Hess df3855c31d initial commit of salvium-js 2026-01-05 03:13:07 +00:00