From 52be259d32f4262d610734580fbf8e02fecaa823 Mon Sep 17 00:00:00 2001 From: Bhavi Dhingra Date: Fri, 31 Jul 2026 15:08:42 +0530 Subject: [PATCH] test(examples): add SIMD-525 devnet verification scripts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Hot wallet presign rebuild test (120s hold, blockhash B1≠B2) - Custodial wallets durable nonce check (AdvanceNonceAccount ix) - Recovery warning test for PR #9372 (logger.warn on missing durableNonce) References: CSHLD-000 --- ...5-custodial-wallets-durable-nonce-check.ts | 231 ++++++++++++++++++ examples/ts/sol/simd525-hot-wallet-presign.ts | 171 +++++++++++++ examples/ts/sol/simd525-recovery-warning.ts | 152 ++++++++++++ 3 files changed, 554 insertions(+) create mode 100644 examples/ts/sol/simd525-custodial-wallets-durable-nonce-check.ts create mode 100644 examples/ts/sol/simd525-hot-wallet-presign.ts create mode 100644 examples/ts/sol/simd525-recovery-warning.ts diff --git a/examples/ts/sol/simd525-custodial-wallets-durable-nonce-check.ts b/examples/ts/sol/simd525-custodial-wallets-durable-nonce-check.ts new file mode 100644 index 0000000000..d09937bf83 --- /dev/null +++ b/examples/ts/sol/simd525-custodial-wallets-durable-nonce-check.ts @@ -0,0 +1,231 @@ +/** + * SIMD-525 Verification: Cold + Custodial Durable Nonce Check + * + * Cold wallets require offline-console-vault for signing — we can't do a + * full end-to-end send. But we DON'T need to. The protection claim is: + * cold and custodial wallets use durable nonce in prebuild, which bypasses + * blockhash expiry entirely. We just verify the prebuild. + * + * Flow: + * 1. Prebuild transfer → deserialize txHex → inspect instructions + * 2. Find AdvanceNonceAccount instruction (System program, ix index 4) + * 3. Extract nonceAccount + nonceAuthority from instruction accounts + * 4. Verify the "recentBlockhash" field is actually a nonce value + * + * Copyright 2025, BitGo, Inc. All Rights Reserved. + */ +import { BitGoAPI } from '@bitgo/sdk-api'; +import { Tsol } from '@bitgo/sdk-coin-sol'; +import { coins } from '@bitgo/statics'; +import { VersionedTransaction } from '@solana/web3.js'; +import * as bs58 from 'bs58'; + +const path = require('path'); +const envPath = path.resolve(__dirname, '../../../.env'); +require('dotenv').config({ path: envPath }); + +// ==================== CONFIG ==================== +const ACCESS_TOKEN = process.env.TESTNET_ACCESS_TOKEN || ''; +const ENV = 'staging'; + +const COLD_WALLET_ID = ''; // skipped — no cold wallet available +const CUSTODIAL_WALLET_ID = '69de2c72b12f278ab5d009701b89dc52'; + +const RECIPIENT_ADDRESS = '2dLaAjaMWTftQrAcAjhPd6k7nJhYgPkWDctWpwYJ8sbv'; // self-transfer to avoid policy denial +const TRANSFER_AMOUNT = '1000'; // lamports +// ================================================= + +// System program instruction indices +// https://github.com/solana-labs/solana/blob/master/sdk/program/src/system_instruction.rs +const SYSTEM_PROGRAM_ID = '11111111111111111111111111111111'; +const SYSVAR_RECENT_BLOCKHASHES = 'SysvarRecentB1ockHashes11111111111111111111'; +const ADVANCE_NONCE_ACCOUNT_IX = 4; // NOT 2 (that's Transfer) + +interface NonceAnalysis { + hasDurableNonce: boolean; + nonceAccount?: string; + nonceAuthority?: string; + nonceValue?: string; // the "recentBlockhash" field is actually the stored nonce + instructions: { type: string; program: string; accounts: string[] }[]; +} + +function analyzeTxHex(txHex: string): NonceAnalysis { + if (!txHex || txHex.length < 20) { + return { hasDurableNonce: false, instructions: [] }; + } + try { + const buf = Buffer.from(txHex, 'hex'); + const tx = VersionedTransaction.deserialize(buf); + const msg = tx.message as any; + const keys = msg.staticAccountKeys; + + // recentBlockhash is raw bytes, not a PublicKey — encode to base58 + const blockhashBytes = msg.recentBlockhash; + let nonceValue: string; + if (typeof blockhashBytes === 'string') { + nonceValue = blockhashBytes; + } else if (blockhashBytes && typeof blockhashBytes.toBase58 === 'function') { + nonceValue = blockhashBytes.toBase58(); + } else { + nonceValue = bs58.encode(Buffer.from(blockhashBytes)); + } + + const systemIxNames: Record = { + 0: 'CreateAccount', + 1: 'Assign', + 2: 'Transfer', + 3: 'CreateAccountWithSeed', + 4: 'AdvanceNonceAccount', + 5: 'WithdrawNonceAccount', + 6: 'InitializeNonceAccount', + }; + + const instructions = msg.compiledInstructions.map((ix: any) => { + const program = keys[ix.programIdIndex]?.toBase58(); + // NOTE: field is accountKeyIndexes (not accountKeyIndices) + const accounts = (ix.accountKeyIndexes || ix.accountKeyIndices || []).map( + (idx: number) => keys[idx]?.toBase58() + ); + const ixType = ix.data[0]; + const typeName = program === SYSTEM_PROGRAM_ID ? (systemIxNames[ixType] || `Unknown(${ixType})`) : `Custom`; + return { type: typeName, program, accounts, ixType }; + }); + + // Find AdvanceNonceAccount instruction + // Account layout for AdvanceNonceAccount: + // [0] = nonce account (writable, not signer) + // [1] = SysvarRecentB1ockHashes (read-only, not signer) + // [2] = nonce authority (read-only, signer) + const nonceIx = msg.compiledInstructions.find((ix: any) => { + const program = keys[ix.programIdIndex]?.toBase58(); + return program === SYSTEM_PROGRAM_ID && ix.data[0] === ADVANCE_NONCE_ACCOUNT_IX; + }); + + if (nonceIx) { + const accountIdxes = nonceIx.accountKeyIndexes || nonceIx.accountKeyIndices; + const nonceAccount = keys[accountIdxes[0]]?.toBase58(); + const sysvarSlot = keys[accountIdxes[1]]?.toBase58(); + const nonceAuthority = keys[accountIdxes[2]]?.toBase58(); + + // Verify the sysvar account is the recent blockhashes sysvar + const isSysvarCorrect = sysvarSlot === SYSVAR_RECENT_BLOCKHASHES; + + return { + hasDurableNonce: true, + nonceAccount, + nonceAuthority, + nonceValue, + instructions: instructions.map((ix: any) => ({ type: ix.type, program: ix.program, accounts: ix.accounts })), + }; + } + + return { + hasDurableNonce: false, + nonceValue, + instructions: instructions.map((ix: any) => ({ type: ix.type, program: ix.program, accounts: ix.accounts })), + }; + } catch (e: any) { + console.log(' [analyzeTxHex] failed:', e.message); + return { hasDurableNonce: false, instructions: [] }; + } +} + +async function checkDurableNonce( + bitgo: BitGoAPI, + walletId: string, + label: string +): Promise<{ hasDurableNonce: boolean; details?: NonceAnalysis }> { + console.log(`\n--- ${label} (wallet: ${walletId}) ---`); + + const sol = bitgo.coin('tsol'); + const wallet = await sol.wallets().get({ id: walletId }); + console.log(' Type:', wallet.type()); + + try { await bitgo.lock(); } catch {} + await bitgo.unlock({ otp: '000000' }); + + const prebuild = await wallet.prebuildTransaction({ + type: 'transfer', + recipients: [{ address: RECIPIENT_ADDRESS, amount: TRANSFER_AMOUNT }], + } as any); + + const txHex = (prebuild as any).txHex || ''; + const txRequestId = (prebuild as any).txRequestId; + console.log(' txRequestId:', txRequestId); + console.log(' txHex length:', txHex.length); + + const analysis = analyzeTxHex(txHex); + + console.log('\n Instructions:'); + analysis.instructions.forEach((ix, i) => { + console.log(` [${i}] ${ix.type} (program: ${ix.program.slice(0, 12)}...)`); + ix.accounts.forEach((addr, j) => { + console.log(` account[${j}]: ${addr}`); + }); + }); + + console.log(''); + console.log(' Nonce value (recentBlockhash field):', analysis.nonceValue || '(not extracted)'); + console.log(' nonceAccount:', analysis.nonceAccount || '(not found)'); + console.log(' nonceAuthority:', analysis.nonceAuthority || '(not found)'); + + if (analysis.hasDurableNonce) { + console.log('\n ✅ USES DURABLE NONCE — protected from SIMD-525 blockhash expiry'); + console.log(' AdvanceNonceAccount instruction found in prebuild'); + console.log(' Tx uses nonce value instead of blockhash → bypasses expiry window'); + } else { + console.log('\n ⚠️ No AdvanceNonceAccount instruction found'); + console.log(' This wallet type may NOT use durable nonce'); + } + + return { hasDurableNonce: analysis.hasDurableNonce, details: analysis }; +} + +async function main() { + console.log('=== SIMD-525: Durable Nonce Verification (Cold + Custodial) ===\n'); + + if (!ACCESS_TOKEN) { + console.error('No access token found. Set TESTNET_ACCESS_TOKEN in .env'); + process.exit(1); + } + + const bitgo = new BitGoAPI({ + accessToken: ACCESS_TOKEN, + env: ENV, + }); + const coin = coins.get('tsol'); + bitgo.register(coin.name, Tsol.createInstance); + + let coldResult: { hasDurableNonce: boolean } | null = null; + let custodialResult: { hasDurableNonce: boolean } | null = null; + + // --- Check 1: Cold wallet --- + if (COLD_WALLET_ID) { + coldResult = await checkDurableNonce(bitgo, COLD_WALLET_ID, 'Cold Wallet'); + } else { + console.log('\n--- Cold Wallet: SKIPPED (no cold wallet available) ---'); + } + + // --- Check 2: Custodial hot wallet --- + if (CUSTODIAL_WALLET_ID) { + custodialResult = await checkDurableNonce(bitgo, CUSTODIAL_WALLET_ID, 'Custodial Hot Wallet'); + } else { + console.log('\n--- Custodial Hot Wallet: SKIPPED (set CUSTODIAL_WALLET_ID in CONFIG) ---'); + } + + // --- Summary --- + console.log('\n=== Summary ==='); + if (coldResult) { + console.log(` Cold wallet: ${coldResult.hasDurableNonce ? '✅ durable nonce → PROTECTED' : '⚠️ no durable nonce'}`); + } + if (custodialResult) { + console.log(` Custodial hot: ${custodialResult.hasDurableNonce ? '✅ durable nonce → PROTECTED' : '⚠️ no durable nonce'}`); + } + if (!coldResult && !custodialResult) { + console.log(' No wallets checked — fill in wallet IDs'); + } + + console.log('\n=== Test Complete ==='); +} + +main().catch((e) => console.log(e)); diff --git a/examples/ts/sol/simd525-hot-wallet-presign.ts b/examples/ts/sol/simd525-hot-wallet-presign.ts new file mode 100644 index 0000000000..f9b5ab4944 --- /dev/null +++ b/examples/ts/sol/simd525-hot-wallet-presign.ts @@ -0,0 +1,171 @@ +/** + * SIMD-525 Verification: Hot Wallet Presign Rebuild + * + * Tests: presignTransaction triggers backend rebuild → fresh blockhash. + * Verifies hot wallet send flow is NOT affected by SIMD-525. + * + * Flow: + * 1. Prebuild tx → capture blockhash B1 from txHex + * 2. Wait (5s for smoke test, 120s for real test) + * 3. Sign → presignTransaction fires → rebuild → fresh blockhash B2 + * 4. Verify B1 ≠ B2 (rebuild happened, not using durable nonce) + * 5. Broadcast → success proves B2 is fresh + * + * Copyright 2025, BitGo, Inc. All Rights Reserved. + */ +import { BitGoAPI } from '@bitgo/sdk-api'; +import { Tsol } from '@bitgo/sdk-coin-sol'; +import { coins } from '@bitgo/statics'; +import { VersionedTransaction } from '@solana/web3.js'; +import * as bs58 from 'bs58'; + +const path = require('path'); +const envPath = path.resolve(__dirname, '../../../.env'); +require('dotenv').config({ path: envPath }); + +// ==================== CONFIG ==================== +const ACCESS_TOKEN = process.env.TESTNET_ACCESS_TOKEN || ''; +const WALLET_ID = '6a10383dcccf729bb7740d59defd5c49'; +const WALLET_PASSPHRASE = 'Ghghjkg!455544llll'; +const RECIPIENT_ADDRESS = 'DTn5zvSLiHJ4fApHobgkzcHzSdgM4Hc9Enkfy2UCC8oo'; +const TRANSFER_AMOUNT = '1000'; // lamports +const HOLD_SECONDS = 120; // 120s — B1 will be stale, proving presign rebuild gives fresh blockhash +const ENV = 'staging'; +// ================================================= + +function extractBlockhashFromTxHex(txHex: string): string | null { + if (!txHex || txHex.length < 20) return null; + try { + const buf = Buffer.from(txHex, 'hex'); + const tx = VersionedTransaction.deserialize(buf); + const blockhash = (tx.message as any).recentBlockhash; + // recentBlockhash is a PublicKey — convert to base58 + if (blockhash && typeof blockhash.toBase58 === 'function') { + return blockhash.toBase58(); + } + // Fallback: raw bytes to base58 + if (Buffer.isBuffer(blockhash)) { + return bs58.encode(blockhash); + } + return String(blockhash); + } catch (e: any) { + console.log(' [extractBlockhash] failed:', e.message); + return null; + } +} + +async function main() { + console.log('=== SIMD-525: Hot Wallet Presign Rebuild ===\n'); + + if (!ACCESS_TOKEN) { + console.error('No access token found. Set TESTNET_ACCESS_TOKEN in .env'); + process.exit(1); + } + + const bitgo = new BitGoAPI({ + accessToken: ACCESS_TOKEN, + env: ENV, + }); + const coin = coins.get('tsol'); + bitgo.register(coin.name, Tsol.createInstance); + + const sol = bitgo.coin('tsol'); + const wallet = await sol.wallets().get({ id: WALLET_ID }); + + console.log('Wallet ID:', wallet.id()); + console.log('Wallet type:', wallet.type()); + + if (wallet.type() !== 'hot') { + console.error('This test requires a HOT wallet. Got:', wallet.type()); + process.exit(1); + } + + // --- Step 1: Prebuild tx → capture blockhash B1 --- + console.log('\n[Step 1] Prebuilding tx...'); + try { + await bitgo.lock(); + } catch {} + await bitgo.unlock({ otp: '000000' }); + + const prebuild = await wallet.prebuildTransaction({ + type: 'transfer', + recipients: [{ address: RECIPIENT_ADDRESS, amount: TRANSFER_AMOUNT }], + } as any); + + const txRequestId = (prebuild as any).txRequestId; + const txHexB1 = (prebuild as any).txHex || ''; + console.log(' txRequestId:', txRequestId); + console.log(' txHex length:', txHexB1.length); + const blockhashB1 = extractBlockhashFromTxHex(txHexB1); + console.log(' Prebuild blockhash (B1):', blockhashB1 || '(not found)'); + + // --- Step 2: Wait --- + console.log(`\n[Step 2] Waiting ${HOLD_SECONDS}s...`); + await new Promise((resolve) => setTimeout(resolve, HOLD_SECONDS * 1000)); + console.log(' Done waiting.'); + + // --- Step 3: Sign → presignTransaction fires → rebuild --- + console.log('\n[Step 3] Signing (presignTransaction will trigger rebuild)...'); + const keychains = await sol.keychains().getKeysForSigning({ wallet }); + + const signedTx = await wallet.signTransaction({ + txPrebuild: prebuild, + keychain: keychains[0], + walletPassphrase: WALLET_PASSPHRASE, + pubs: keychains.map((k) => k.pub), + } as any); + + const signedTxId = (signedTx as any).txRequestId; + console.log(' Signed txRequestId:', signedTxId); + console.log(' signedTx keys:', Object.keys(signedTx)); + + // Try to extract B2 from signedTx — after presign rebuild, the unsignedTxs + // array contains the REBUILT tx with the fresh blockhash + const rebuiltUnsignedTx = (signedTx as any).unsignedTxs?.[0]; + const signedTxHex = rebuiltUnsignedTx?.serializedTxHex + || (signedTx as any).signedTxHex + || (signedTx as any).txHex + || ''; + console.log(' unsignedTxs[0] keys:', rebuiltUnsignedTx ? Object.keys(rebuiltUnsignedTx) : 'none'); + console.log(' signedTxHex length:', signedTxHex.length); + const blockhashB2 = extractBlockhashFromTxHex(signedTxHex); + console.log(' Rebuilt blockhash (B2):', blockhashB2 || '(not found)'); + + // --- Step 4: Verify B1 ≠ B2 --- + console.log('\n[Step 4] Verifying presign rebuild...'); + + if (blockhashB1 && blockhashB2) { + if (blockhashB1 !== blockhashB2) { + console.log(' ✅ B1 ≠ B2 — presignTransaction rebuilt with FRESH blockhash'); + console.log(' B1:', blockhashB1); + console.log(' B2:', blockhashB2); + } else { + console.log(' ⚠️ B1 == B2 — blockhash unchanged (rebuild may not have triggered)'); + } + } else { + console.log(' ℹ️ Could not compare blockhashes'); + if (!blockhashB1) console.log(' B1 missing — txHex deserialization failed'); + if (!blockhashB2) console.log(' B2 missing — need to find signed tx hex'); + } + + // --- Step 5: Broadcast --- + console.log('\n[Step 5] Submitting tx...'); + try { + const submitted = await bitgo + .post(sol.url(`/wallet/${WALLET_ID}/tx/send`)) + .send({ txRequestId: signedTxId }) + .result(); + + console.log(' ✅ SUBMITTED:', submitted.txid || submitted.txHash || JSON.stringify(submitted).slice(0, 200)); + console.log('\n ✓ Hot wallet send succeeds'); + console.log(' ✓ presignTransaction rebuild gives fresh blockhash'); + console.log(' ✓ Hot wallet flow NOT affected by SIMD-525'); + } catch (err: any) { + const errMsg = (err.message || String(err)).slice(0, 300); + console.log(' ❌ SUBMIT FAILED:', errMsg); + } + + console.log('\n=== Test Complete ==='); +} + +main().catch((e) => console.log(e)); diff --git a/examples/ts/sol/simd525-recovery-warning.ts b/examples/ts/sol/simd525-recovery-warning.ts new file mode 100644 index 0000000000..596593396b --- /dev/null +++ b/examples/ts/sol/simd525-recovery-warning.ts @@ -0,0 +1,152 @@ +/** + * SIMD-525 Verification: Recovery Warning (PR #9372) + * + * Tests: recover() logs warning when durableNonce is not provided. + * + * This test calls recover() with and without durableNonce, capturing log + * output to verify the warning fires correctly. + * + * IMPORTANT: This test requires the BitGoJS from the fix branch + * (feat/sol-200ms-slot-recovery-nonce-warning). The warning code is at + * sol.ts:~1283 in the recover() method. + * + * The recover() call will fail early (no real key material), but the + * warning fires before network calls — so we just check if it fired. + * + * Copyright 2025, BitGo, Inc. All Rights Reserved. + */ +import { BitGoAPI } from '@bitgo/sdk-api'; +import { Tsol } from '@bitgo/sdk-coin-sol'; +import { coins } from '@bitgo/statics'; + +const path = require('path'); +const envPath = path.resolve(__dirname, '../../../.env'); +require('dotenv').config({ path: envPath }); + +// ==================== CONFIG ==================== +const ACCESS_TOKEN = process.env.TESTNET_ACCESS_TOKEN || ''; +const ENV = 'staging'; + +// Key material for recovery (from a wallet you control) +// These don't need to be real — recover() will fail, but the warning +// fires before any validation that would reject fake keys +const BITGO_KEY = 'fakeBitGoKeyForTestingPurposesOnly'; +const USER_KEY = { prv: 'fakeUserPrvForTestingPurposesOnly' }; +const BACKUP_KEY = { prv: 'fakeBackupPrvForTestingPurposesOnly' }; +const WALLET_PASSPHRASE = 'fakePassphrase'; +const RECOVERY_DESTINATION = 'DTn5zvSLiHJ4fApHobgkzcHzSdgM4Hc9Enkfy2UCC8oo'; + +// Durable nonce params (for the "with nonce" test) +const DURABLE_NONCE_ACCOUNT = '45zDnMboeZBrgvbnbJ8yjtgdJN9UAgUecezbTcaVzxEK'; +// ================================================= + +// Capture console.warn output +const warnings: string[] = []; +const originalWarn = console.warn; + +function hookWarn() { + warnings.length = 0; + console.warn = (...args: any[]) => { + const msg = args.join(' '); + warnings.push(msg); + originalWarn.apply(console, args as any); + }; +} + +function unhookWarn() { + console.warn = originalWarn; +} + +async function main() { + console.log('=== SIMD-525: Recovery Warning Verification ===\n'); + + if (!ACCESS_TOKEN) { + console.error('No access token found. Set TESTNET_ACCESS_TOKEN in .env'); + process.exit(1); + } + + const bitgo = new BitGoAPI({ + accessToken: ACCESS_TOKEN, + env: ENV, + }); + const coin = coins.get('tsol'); + bitgo.register(coin.name, Tsol.createInstance); + + const sol = bitgo.coin('tsol'); + + const baseRecoveryParams: any = { + bitgoKey: BITGO_KEY, + recoveryDestination: RECOVERY_DESTINATION, + userKey: USER_KEY, + backupKey: BACKUP_KEY, + walletPassphrase: WALLET_PASSPHRASE, + }; + + // --- Test A: recover WITHOUT durable nonce → expect warning --- + console.log('--- TEST A: recover() WITHOUT durableNonce ---'); + hookWarn(); + + try { + await sol.recover({ ...baseRecoveryParams }); + } catch (err: any) { + // Expected — we just want to see if the warning fired + } + + unhookWarn(); + + const warningA = warnings.find((w) => + w.includes('durable nonce') || w.includes('durableNonce') || w.includes('SOL recovery') + ); + + if (warningA) { + console.log(' ✅ WARNING FIRED:', warningA.slice(0, 120)); + console.log(' ✓ PR #9372 works — warning fires when durableNonce is not provided\n'); + } else { + console.log(' ❌ WARNING DID NOT FIRE'); + console.log(' All captured warnings:', warnings.length > 0 ? warnings : '(none)'); + console.log(' PR #9372 may not be in this build, or recover() failed before reaching the warning\n'); + } + + // --- Test B: recover WITH durable nonce → expect NO warning --- + console.log('--- TEST B: recover() WITH durableNonce ---'); + hookWarn(); + + try { + await sol.recover({ + ...baseRecoveryParams, + durableNonce: { + nonceAccount: DURABLE_NONCE_ACCOUNT, + }, + }); + } catch (err: any) { + // Expected + } + + unhookWarn(); + + const warningB = warnings.find((w) => + w.includes('durable nonce') || w.includes('durableNonce') || w.includes('SOL recovery') + ); + + if (!warningB) { + console.log(' ✅ NO WARNING — correct behavior when durableNonce is provided'); + console.log(' ✓ Recovery with durableNonce does not trigger the warning\n'); + } else { + console.log(' ❌ WARNING FIRED even with durableNonce — bug in the guard'); + console.log(' Warning:', warningB.slice(0, 120)); + } + + // --- Summary --- + console.log('=== Summary ==='); + if (warningA && !warningB) { + console.log(' ✅ PR #9372 verified: warning fires WITHOUT durableNonce, silent WITH durableNonce'); + } else if (!warningA) { + console.log(' ⚠️ Warning not firing — ensure you are running the fix branch build'); + console.log(' Branch: feat/sol-200ms-slot-recovery-nonce-warning'); + console.log(' Run: yarn install && tsc -b ./tsconfig.packages.json'); + } + + console.log('\n=== Test Complete ==='); +} + +main().catch((e) => console.log(e));