From 725dfe5397d98c9d65f9f6d9d4a515258dae4b49 Mon Sep 17 00:00:00 2001 From: jagdeep sidhu Date: Wed, 2 Dec 2026 07:57:55 -0700 Subject: [PATCH 01/18] Support P2MR sentry enrollment, collateral rollover and funding votes --- README.md | 30 +++- lib/gov.js | 34 ++-- lib/gov.test.js | 17 ++ lib/proposalPsbt.js | 4 +- lib/sentryAdapter.js | 244 +++++++++++++++++++++++------ lib/sentryManagement.js | 42 +++-- lib/sentryManagement.test.js | 7 +- lib/sentryVotingContext.test.js | 32 +++- package-lock.json | 8 +- package.json | 2 +- routes/gov.js | 2 +- routes/sentry.js | 9 +- scripts/sentry-core-regtest.mjs | 108 ++++++++++--- tests/sentry-codec.integration.mjs | 94 +++++++++-- 14 files changed, 490 insertions(+), 143 deletions(-) diff --git a/README.md b/README.md index 23cdea3..5938cac 100644 --- a/README.md +++ b/README.md @@ -445,11 +445,14 @@ Core network/genesis check. Its fixed `gobject_get` call verifies a valid, non-deleted proposal and returns the on-chain name/URL, not a dapp-provided title. The optional URL is omitted unless it is an HTTP(S) address without credentials; this does not reject an otherwise valid proposal with a non-web URI. -The response is `{ chain, now, proposalHash, proposal: { name, url? }, nodes }`; -each node has `{ proTxHash, collateralOutpoint: { txid, vout }, votingKeyId, -valid: true }`. `valid` means a confirmed registered identity with a voting key, -not a claim about its hosting provider or operational status. Active PQ voting -is not supported by this legacy ECDSA context and is explicitly rejected. +The response includes the proposal, chain era and each confirmed sentry's +collateral outpoint and registered voting identity. Before activation the +identity is the ECDSA key ID. After activation it is the raw P2MR voting root, +with its key version and activation height. PQ responses include +`signingBlock: { height, hash }`, selected six blocks behind the tip. A wallet +can pin that block on a second read by supplying both `signingHeight` and +`signingBlockHash`. Core must still report that block as an active ancestor +for which the current voter registration is eligible. The request has a 10-second total deadline, at most four concurrent node reads, and a 64-KiB limit per Core response. It has a separate 12-request-per-minute IP limit shared across both proxy prefixes, in addition to the normal read limit. @@ -495,15 +498,28 @@ original transaction first, then revalidates and republishes only the stored signed bytes if needed. A per-operation cooldown and atomic claim bound retries; no new signature, new transaction ID, replacement transaction or fee bump occurs. +At PQ activation, registration accepts P2MR owner and voting addresses. A +wallet can fund a new collateral output by supplying `changes.collateralAddress` +instead of `collateralOutpoint`. This form goes directly to fee-input signing +after the wallet confirms the selected collateral script and amount. To migrate +registered P2WPKH collateral, pass `changes.collateralAddress` and +`changes.collateralKeyCommitment` (Core RPC hex order) on an `updateRegistrar`. +The selected wallet must control the old collateral input and fund the fee +separately. The replacement retains the full collateral amount. An enrolled +owner's wallet fills its current opening locally and authorizes the successor +owner root. Preparation exposes only the registered root and requested changes. + Run `npm test -- --runInBand` and `npm run test:sentry-codec`. Codec integration uses real legacy/PQ signatures and fee signatures with synthetic RPC fixtures; it does not submit transactions to a public network. -For the actual legacy consensus smoke test, set `SENTRY_CORE_BIN` to a directory +For the legacy and PQ preparation consensus smoke test, set `SENTRY_CORE_BIN` to a directory containing the metadata-enabled `syscoind` and `syscoin-cli`, then run `npm run test:sentry-core`. It creates a fresh disconnected regtest and synthetic wallet, registers a node, signs NEVM add/update/remove requests with the shared -SDK, and requires Core mempool acceptance plus mined registration readback. +SDK, then activates PQ preparation. It rolls the existing collateral into a +cold P2MR address, checks the original seniority, and confirms a subsequent +owner transfer signed by the enrolled P2MR owner. The test stops its Core process and prints its isolated temporary data directory for inspection. It never uses a configured service RPC or an existing wallet. diff --git a/lib/gov.js b/lib/gov.js index 5aff1b6..eba3af7 100644 --- a/lib/gov.js +++ b/lib/gov.js @@ -11,7 +11,7 @@ // imported voting keys correspond to live masternodes. // * Vote-relay validation + fan-out. The browser signs locally // (VaultGovernanceSigner / voteSigner.js), and we relay each -// compact ECDSA signature to Syscoin Core's `voteraw` RPC. We +// ECDSA signature or PQ funding envelope to Core's `voteraw` RPC. We // intentionally enforce `voteSignal === "funding"` here — non- // funding signals (valid/delete/endorsed) use the BLS operator // key, NOT the voting key, and the vault doesn't hold operator @@ -23,18 +23,10 @@ // (UI copy / i18n keys hang off them). const HEX64 = /^[0-9a-fA-F]{64}$/; -// Permissive base64 charset guard: the real length/shape check happens -// via `Buffer.from(sig, 'base64').length === 65` plus a canonical -// re-encode roundtrip, so the regex is just a cheap filter that -// rejects obviously malformed input (whitespace, non-base64 chars) -// before we allocate a decode buffer. const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/; -// A recoverable ECDSA signature produced by CKey::SignCompact is -// exactly 65 bytes (1-byte header + 32-byte r + 32-byte s). Anything -// else is a programming or tampering error — Core would reject it at -// `voteraw` anyway, but we fail fast here with a stable error code -// so the UI can surface a precise message. const VOTE_SIG_BYTES = 65; +const FUNDING_ENVELOPE_BYTES = 7963; +const FUNDING_LEAF_OFFSET = 2 + 4 + 32 + 32 + 4; const OUTCOMES = Object.freeze({ yes: 1, no: 2, abstain: 3 }); // PR5 intentionally supports only `funding`. The other signals @@ -148,26 +140,22 @@ function validateVoteBody(body, { nowMs = Date.now() } = {}) { ) { return { ok: false, error: `invalid_entry:${i}:collateralIndex` }; } - if (typeof voteSig !== "string" || !BASE64.test(voteSig)) { + if (typeof voteSig !== "string" || (voteSig.length !== 88 && voteSig.length !== Math.ceil(FUNDING_ENVELOPE_BYTES / 3) * 4) || + !BASE64.test(voteSig)) { return { ok: false, error: `invalid_entry:${i}:voteSig` }; } - // Decode and verify the exact raw length. The character-count - // check we used to perform accepted `"A".repeat(88)` (decodes to - // 66 bytes) and `"A".repeat(86) + "=="` (decodes to 64 bytes) - // because both are syntactically valid base64 strings of the - // "right" length. Decoding is the only way to enforce the 65- - // byte invariant. We also require the roundtrip - // (decode → re-encode) to equal the input so non-canonical - // padding (extra "=" chars, non-zero trailing bits) is rejected. - // `Buffer.from(_, 'base64')` never throws on junk input — it - // silently coerces — so both checks are load-bearing here. + // Only legacy compact signatures and Core's delegated funding envelope are relayable. + // Core checks the branch, registered authority, and signature before accepting the vote. const decodedSig = Buffer.from(voteSig, "base64"); + const pqFunding = decodedSig.length === FUNDING_ENVELOPE_BYTES && decodedSig[0] === 1 && decodedSig[1] === 1 && + decodedSig[FUNDING_LEAF_OFFSET] === 0xc2; if ( - decodedSig.length !== VOTE_SIG_BYTES || + (!pqFunding && decodedSig.length !== VOTE_SIG_BYTES) || decodedSig.toString("base64") !== voteSig ) { return { ok: false, error: `invalid_entry:${i}:voteSig` }; } + if (pqFunding && entries.length > 20) return { ok: false, error: "too_many_entries" }; const k = `${collateralHash.toLowerCase()}:${collateralIndex}`; if (dupKey.has(k)) { return { ok: false, error: `duplicate_entry:${i}` }; diff --git a/lib/gov.test.js b/lib/gov.test.js index 7a75bdc..a746c61 100644 --- a/lib/gov.test.js +++ b/lib/gov.test.js @@ -273,6 +273,23 @@ describe('validateVoteBody', () => { expect(res.error).toMatch(/collateralIndex$/); } }); + + test('relays bounded PQ funding envelopes and rejects other formats, roles and leaves', () => { + const envelope = Buffer.alloc(7963); + const check = (size) => validateVoteBody(goodBody({ entries: Array.from({ length: size }, (_, collateralIndex) => + ({ collateralHash: VALID_HASH_2, collateralIndex, voteSig: envelope.toString('base64') })) }), { nowMs: NOW_MS }); + envelope[0] = envelope[1] = 1; + envelope[74] = 0xc2; + expect(check(20).ok).toBe(true); + expect(check(21)).toMatchObject({ ok: false, error: 'too_many_entries' }); + envelope[74] = 0xc4; + expect(check(1)).toMatchObject({ ok: false, error: 'invalid_entry:0:voteSig' }); + envelope[74] = 0xc2; + envelope[1] = 0; + expect(check(1)).toMatchObject({ ok: false, error: 'invalid_entry:0:voteSig' }); + envelope[0] = 2; envelope[1] = 1; + expect(check(1)).toMatchObject({ ok: false, error: 'invalid_entry:0:voteSig' }); + }); }); describe('lookupMatches', () => { diff --git a/lib/proposalPsbt.js b/lib/proposalPsbt.js index 7399e9e..3fa0fef 100644 --- a/lib/proposalPsbt.js +++ b/lib/proposalPsbt.js @@ -387,8 +387,8 @@ function createDefaultSyscoinClient({ blockbookURL, networkKey } = {}) { bitcoinjs: syscoinjs.utils.bitcoinjs, exportPsbtToJson: syscoinjs.utils.exportPsbtToJson, fetchUtxos: (xpub) => syscoinjs.utils.fetchBackendUTXOS(blockbookURL, xpub), - createTransaction: (txOpts, changeAddress, outputs, feeRate, xpub, utxos) => - lib.createTransaction(txOpts, changeAddress, outputs, feeRate, xpub, utxos), + createTransaction: (txOpts, changeAddress, outputs, feeRate, xpub, utxos, forcedInputs) => + lib.createTransaction(txOpts, changeAddress, outputs, feeRate, xpub, utxos, undefined, forcedInputs), }; } diff --git a/lib/sentryAdapter.js b/lib/sentryAdapter.js index ed3257f..f085d7b 100644 --- a/lib/sentryAdapter.js +++ b/lib/sentryAdapter.js @@ -28,15 +28,27 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient if (!['legacy-v3', 'pq-v4'].includes(era)) throw failure('protocol_not_supported', 503); return { chain: { genesisHash, era }, capabilities }; }; - const script = (address) => address ? Buffer.from(bitcoinjs.address.toOutputScript(address, fundingClient.network)).toString('hex') : ''; const networkEncoding = { bech32Hrp: fundingClient.network.bech32, pubKeyHash: fundingClient.network.pubKeyHash, scriptHash: fundingClient.network.scriptHash }; + const script = (address) => { + if (!address) return ''; + if (typeof address === 'string' && address.toLowerCase().startsWith(networkEncoding.bech32Hrp + '1z')) { + try { return '5220' + sdk.sentryP2MRRootFromAddress(address, networkEncoding.bech32Hrp); } + catch { throw failure('invalid_authority_address'); } + } + return Buffer.from(bitcoinjs.address.toOutputScript(address, fundingClient.network)).toString('hex'); + }; + const registeredRoot = (address, root) => { + if (typeof root !== 'string' || !/^[0-9a-f]{64}$/.test(root) || /^0+$/.test(root) || + script(address) !== '5220' + root) throw failure('invalid_authority_address'); + return root; + }; const keyId = (address) => { const value = script(address); if (/^0014[0-9a-f]{40}$/.test(value)) return value.slice(4); if (/^76a914[0-9a-f]{40}88ac$/.test(value)) return value.slice(6, -4); throw failure('invalid_authority_address'); }; - async function votingContext(requested, proposalHash, proTxHashes) { + async function votingContext(requested, proposalHash, proTxHashes, requestedBlock) { const hash = /^[a-f0-9]{64}$/; if (typeof proposalHash !== 'string' || !hash.test(proposalHash) || /^0+$/.test(proposalHash) || !Array.isArray(proTxHashes) || !proTxHashes.length || proTxHashes.length > 20 || proTxHashes.some((value) => typeof value !== 'string' || !hash.test(value) || /^0+$/.test(value)) || new Set(proTxHashes).size !== proTxHashes.length) { @@ -54,7 +66,22 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient }); const observe = async () => { const initial = await assertNetwork(requested, options); - if (initial.chain.era !== 'legacy-v3') throw failure('voting_protocol_not_supported', 503); + // Core votes use the active tip. Provider transactions use the next block's rules. + const { height, activationHeight } = initial.capabilities; + if (initial.chain.era === 'pq-v4' && (!Number.isSafeInteger(activationHeight) || activationHeight < 0)) + throw failure('core_sentry_capabilities_required', 503); + const pq = initial.chain.era === 'pq-v4' && height >= activationHeight; + const chain = { ...initial.chain, era: pq ? 'pq-v4' : 'legacy-v3' }; + let signingBlock; + if (pq) { + const signedHeight = requestedBlock?.height ?? height - 6; + if (!Number.isSafeInteger(signedHeight) || signedHeight < activationHeight || signedHeight > height - 6) + throw failure('signing_block_unavailable', 409); + const signedHash = await read('getblockhash', [signedHeight]); + if (typeof signedHash !== 'string' || !hash.test(signedHash) || /^0+$/.test(signedHash) || + (requestedBlock && requestedBlock.hash !== signedHash)) throw failure('signing_block_unavailable', 409); + signingBlock = { height: signedHeight, hash: signedHash }; + } else if (requestedBlock) throw failure('unexpected_signing_block', 422); let raw; try { raw = await read('gobject_get', [proposalHash]); } catch (error) { @@ -87,24 +114,42 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient const state = node?.state; if (node?.proTxHash !== proTxHash || !state || typeof node.collateralHash !== 'string' || !hash.test(node.collateralHash) || !Number.isSafeInteger(node.collateralIndex) || node.collateralIndex < 0 || node.collateralIndex > 0x7fffffff || - typeof state.confirmedHash !== 'string' || !hash.test(state.confirmedHash) || /^0+$/.test(state.confirmedHash)) throw failure('invalid_voting_node', 422); + typeof state.confirmedHash !== 'string' || !hash.test(state.confirmedHash) || /^0+$/.test(state.confirmedHash) || + ((pq || state.PoSeBanHeight !== undefined) && state.PoSeBanHeight !== -1)) throw failure('invalid_voting_node', 422); const registration = await read('getrawtransaction', [proTxHash, true]); if (!Number.isSafeInteger(registration?.confirmations) || registration.confirmations <= 0) throw failure('node_not_confirmed', 409); - nodes[index] = { proTxHash, collateralOutpoint: { txid: node.collateralHash, vout: node.collateralIndex }, votingKeyId: keyId(state.votingAddress), valid: true }; + const identity = { proTxHash, collateralOutpoint: { txid: node.collateralHash, vout: node.collateralIndex }, valid: true }; + if (pq) { + const votingKeyVersion = state.pqVotingKeyVersion; + const votingKeyActivatedHeight = state.pqVotingKeyActivationHeight; + if (!Number.isSafeInteger(votingKeyVersion) || votingKeyVersion < 1 || votingKeyVersion > 0xffffffff || + !Number.isSafeInteger(votingKeyActivatedHeight) || votingKeyActivatedHeight < 0 || votingKeyActivatedHeight > signingBlock.height) + throw failure('voting_key_not_active_at_signing_block', 409); + nodes[index] = { ...identity, votingKeyId: registeredRoot(state.votingAddress, state.pqVotingCommitment), votingKeyVersion, votingKeyActivatedHeight }; + } else { + nodes[index] = { ...identity, votingKeyId: keyId(state.legacyVotingAddress ?? state.votingAddress) }; + } } })); const final = await assertNetwork(requested, options); if (final.capabilities.height !== initial.capabilities.height || final.capabilities.blockHash !== initial.capabilities.blockHash || final.chain.era !== initial.chain.era) throw failure('chain_context_changed', 409); - return { chain: initial.chain, now: Math.floor(now() / 1000), proposalHash, proposal, nodes }; + return { chain, now: Math.floor(now() / 1000), proposalHash, proposal, ...(signingBlock ? { signingBlock } : {}), nodes }; }; try { return await Promise.race([observe(), deadline]); } finally { clearTimeout(timeout); controller.abort(); } } async function context(requested, proTxHash, collateral) { const { chain, capabilities } = await assertNetwork(requested); - if (collateral) { - if (!/^[a-f0-9]{64}$/.test(collateral.txid || '') || !Number.isSafeInteger(collateral.vout) || collateral.vout < 0) throw failure('invalid_collateral'); + if (collateral && !proTxHash) { if (!/^[1-9][0-9]*$/.test(capabilities.requiredCollateralSatoshis || '')) throw failure('core_sentry_capabilities_required', 503); + if (!Number.isSafeInteger(collateral.vout) || collateral.vout < 0 || collateral.vout > 0xffffffff) throw failure('invalid_collateral'); + if (collateral.address) { + const approvedCollateralScript = script(collateral.address); + if (collateral.txid || chain.era !== 'pq-v4' || !/^5220[0-9a-f]{64}$/.test(approvedCollateralScript)) throw failure('invalid_collateral'); + return { chain, network: networkEncoding, approvedCollateralScript, registration: { + collateralVout: collateral.vout, requiredCollateralSatoshis: capabilities.requiredCollateralSatoshis } }; + } + if (!/^[a-f0-9]{64}$/.test(collateral.txid || '')) throw failure('invalid_collateral'); const [collateralTransactionHex, coin] = await Promise.all([ call('getrawtransaction', [collateral.txid, false]), call('gettxout', [collateral.txid, collateral.vout, true]), ]); @@ -122,6 +167,14 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient // or not-yet-confirmed node as ready merely because a key was imported. const registration = await call('getrawtransaction', [proTxHash, true]); if (!(registration.confirmations > 0)) throw failure('node_not_confirmed', 409); + const isPqOwner = state.ownerKeyType === 'slh-dsa'; + const isPqVoter = state.pqVotingKeyVersion > 0; + const validVersion = (version, height) => Number.isSafeInteger(version) && version > 0 && version <= 0xffffffff && + Number.isSafeInteger(height) && height >= 0 && height <= capabilities.height; + if ((isPqOwner && (!validVersion(state.pqOwnerKeyVersion, state.pqOwnerKeyActivationHeight) || + !/^[a-f0-9]{64}$/.test(state.pqOwnerDerivationNonce || ''))) || + (isPqVoter && (!validVersion(state.pqVotingKeyVersion, state.pqVotingKeyActivationHeight) || + (!state.votingAddress && state.pqVotingCommitment !== '00'.repeat(32))))) throw failure('invalid_authority_record', 503); const node = { proTxHash, operatorPublicKey: state.pubKeyOperator, @@ -132,15 +185,21 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient confirmedHash: state.confirmedHash, poseBanHeight: state.PoSeBanHeight, revocationReason: state.revocationReason, - ownerKeyId: state.ownerKeyType === 'slh-dsa' && state.pqOwnerPublicKey && state.pqOwnerKeyVersion > 0 + ownerKeyId: isPqOwner ? '00'.repeat(20) : keyId(state.ownerAddress), - votingKeyId: keyId(state.votingAddress), + votingKeyId: isPqVoter + ? (state.legacyVotingAddress ? keyId(state.legacyVotingAddress) : '00'.repeat(20)) : (state.votingAddress ? keyId(state.votingAddress) : '00'.repeat(20)), payoutScript: script(state.payoutAddress), - ...(state.pqOwnerPublicKey ? { pqOwnerRecord: { publicKey: state.pqOwnerPublicKey, - keyVersion: state.pqOwnerKeyVersion, activatedHeight: state.pqOwnerKeyActivationHeight } } : {}), - ...(state.pqVotingPublicKey ? { pqVotingPublicKey: state.pqVotingPublicKey } : {}), + ...(isPqOwner ? { pqOwnerRecord: { + commitment: registeredRoot(state.ownerAddress, state.pqOwnerCommitment), + keyVersion: state.pqOwnerKeyVersion, activatedHeight: state.pqOwnerKeyActivationHeight, derivationNonce: state.pqOwnerDerivationNonce } } : {}), + ...(isPqVoter ? { pqVotingCommitment: state.votingAddress + ? registeredRoot(state.votingAddress, state.pqVotingCommitment) : state.pqVotingCommitment } : {}), }; if (chain.era === 'pq-v4' || capabilities.preparationActive === true) { + const coin = await call('gettxout', [raw.collateralHash, raw.collateralIndex, true]); + if (coin?.confirmations > 0 && /^0014[a-f0-9]{40}$/.test(coin.scriptPubKey?.hex || '')) + node.rolloverCollateralInputScript = 'p2wpkh'; let key; try { key = await call('protx_operator_key_info', [proTxHash, true]); } catch (error) { @@ -158,7 +217,16 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient } else if (chain.era === 'pq-v4') node.operatorPublicKey = ''; } else if (chain.era === 'pq-v4') node.operatorPublicKey = ''; } - return { chain, node, network: networkEncoding, + const final = await assertNetwork(requested); + if (final.capabilities.height !== capabilities.height || final.capabilities.blockHash !== capabilities.blockHash) + throw failure('chain_context_changed', 409); + let approvedCollateralScript; + if (collateral) { + if (collateral.txid || !collateral.address || node.rolloverCollateralInputScript !== 'p2wpkh') throw failure('unsupported_collateral_rollover'); + approvedCollateralScript = script(collateral.address); + if (!/^5220[0-9a-f]{64}$/.test(approvedCollateralScript)) throw failure('invalid_collateral'); + } + return { chain, node, network: networkEncoding, ...(approvedCollateralScript ? { approvedCollateralScript } : {}), allowOperatorPreparation: capabilities.preparationActive === true, allowOwnerPreparation: capabilities.preparationActive === true }; } @@ -190,8 +258,9 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient const isService = row.prepared.request.operation === 'updateService'; const current = row.prepared.collateralOutpoint ? await context(row.network, undefined, row.prepared.collateralOutpoint) - : await context(row.network, row.protx_hash); - const anchor = ({ chain, node, registration }) => ({ chain, ...(node ? { node } : {}), ...(registration ? { registration } : {}) }); + : await context(row.network, row.protx_hash, row.prepared.rolloverAddress ? { address: row.prepared.rolloverAddress } : undefined); + const anchor = ({ chain, node, registration, approvedCollateralScript }) => + ({ chain, ...(node ? { node } : {}), ...(registration ? { registration } : {}), ...(approvedCollateralScript ? { approvedCollateralScript } : {}) }); if (JSON.stringify(anchor(current)) !== JSON.stringify(row.prepared.anchor)) throw failure('node_state_changed', 409); const tx = decode(transactionHex); const previousTransactions = await priorTransactions(tx); @@ -210,30 +279,80 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient if (JSON.stringify(feeIndependentShape(expected)) !== JSON.stringify(feeIndependentShape(actual))) throw failure('operation_changed', 409); const valid = isService ? await sdk.verifySentryOperation(request, reviewContext) : await sdk.verifySentryManagementOperation(request, reviewContext); if (!valid) throw failure('invalid_node_authorization'); - return { tx, request, reviewContext }; + return { tx, request, reviewContext, fields: review.fields }; + } + async function checkReservedInputs(tx, row) { + const registrations = await call('protx_list', ['registered', true]); + if (!Array.isArray(registrations)) throw failure('node_list_unavailable', 503); + const inputIds = new Set(tx.ins.map((input) => Buffer.from(input.hash).reverse().toString('hex') + ':' + input.index)); + const old = row.prepared.anchor?.node?.collateralOutpoint; + for (const entry of registrations) { + if (!inputIds.has(entry.collateralHash + ':' + entry.collateralIndex)) continue; + if (!row.prepared.rolloverAddress || entry.proTxHash !== row.protx_hash || entry.collateralHash !== old?.txid || entry.collateralIndex !== old?.vout) + throw failure('registered_collateral_spend'); + } } return { votingContext, async capabilities() { const { chain, capabilities } = await assertNetwork(network); - return { version: 1, network, chain, preparationActive: capabilities.preparationActive === true, ...sdk.getSentryCapabilities(), operations: ['register', 'updateService', 'updateRegistrar', 'revoke', + const management = sdk.getSentryManagementCapabilities(); + return { version: 1, network, chain, preparationActive: capabilities.preparationActive === true, ...sdk.getSentryCapabilities(), + keyRoles: management.roles, schemes: management.schemes, + fundedRegistration: chain.era === 'pq-v4', collateralRollover: chain.era === 'pq-v4' || capabilities.preparationActive === true, + operations: ['register', 'updateService', 'updateRegistrar', 'revoke', ...(capabilities.preparationActive || chain.era === 'pq-v4' ? ['registerOperator'] : []), ...(chain.era === 'pq-v4' ? ['rotateOperator'] : [])], providers: [{ id: 'self-hosted', name: 'Self-hosted', supported: true }, { id: 'nodehub', name: 'NodeHub', supported: false, reason: 'Provider integration is not configured. Keys remain in Pali.' }] }; }, context, async prepare(body) { const operation = body.operation || 'updateService'; - const current = operation === 'register' ? await context(body.network, undefined, body.collateralOutpoint) : await context(body.network, body.proTxHash); + const fundedAddress = operation === 'register' ? body.changes.collateralAddress : undefined; + const rolloverAddress = operation === 'updateRegistrar' ? body.changes.collateralAddress : undefined; + const collateral = fundedAddress ? { address: fundedAddress, vout: 0 } : body.collateralOutpoint; + const current = operation === 'register' ? await context(body.network, undefined, collateral) + : await context(body.network, body.proTxHash, rolloverAddress ? { address: rolloverAddress } : undefined); _internal.assertXpubMatchesNetwork(body.xpub, network); _internal.assertChangeAddress(bitcoinjs, body.changeAddress, fundingClient.network, network); const feeRate = _internal.normalizeFeeRate(body.feeRate); const registrations = await call('protx_list', ['registered', true]); if (!Array.isArray(registrations)) throw failure('node_list_unavailable', 503); const changes = { ...body.changes }; + delete changes.collateralAddress; + delete changes.collateralKeyCommitment; + let rolloverSource; + if (rolloverAddress) { + const keyCommitment = body.changes.collateralKeyCommitment; + const root = sdk.sentryCollateralRootFromCommitment(genesisHash, Buffer.from(keyCommitment, 'hex').reverse().toString('hex')); + if (current.approvedCollateralScript !== '5220' + root) throw failure('collateral_commitment_mismatch'); + const old = current.node.collateralOutpoint; + if (!registrations.some((entry) => entry.proTxHash === body.proTxHash && entry.collateralHash === old.txid && entry.collateralIndex === old.vout)) + throw failure('node_state_changed', 409); + const prior = decode(await call('getrawtransaction', [old.txid, false])); + const output = prior.outs[old.vout]; + if (prior.getId() !== old.txid || !output || !/^0014[0-9a-f]{40}$/.test(Buffer.from(output.script).toString('hex'))) throw failure('unsupported_collateral_rollover'); + rolloverSource = { ...old, scriptHex: Buffer.from(output.script).toString('hex'), valueSatoshis: String(output.value) }; + changes.collateralRollover = { outputIndex: 0, keyCommitment }; + } for (const name of ['ownerAddress', 'votingAddress']) { - if (Object.hasOwn(changes, name)) { changes[name === 'ownerAddress' ? 'ownerKeyId' : 'votingKeyId'] = keyId(changes[name]); delete changes[name]; } + if (!Object.hasOwn(changes, name)) continue; + const role = name === 'ownerAddress' ? 'Owner' : 'Voting'; + if (name === 'votingAddress' && changes[name] === 'revoke' && operation === 'updateRegistrar' && current.chain.era === 'pq-v4') { + changes.pqVotingCommitment = '00'.repeat(32); + } else { + const output = script(changes[name]); + if (current.chain.era === 'pq-v4' || /^5220[0-9a-f]{64}$/.test(output)) { + if (!/^5220[0-9a-f]{64}$/.test(output) || (current.chain.era !== 'pq-v4' && !current.allowOwnerPreparation)) throw failure('invalid_authority_address'); + changes['pq' + role + 'Commitment'] = output.slice(4); + } else { + if (operation !== 'register' && name === 'ownerAddress') throw failure('invalid_authority_address'); + changes[name === 'ownerAddress' ? 'ownerKeyId' : 'votingKeyId'] = keyId(changes[name]); + } + } + delete changes[name]; } if (Object.hasOwn(changes, 'payoutAddress')) { changes.payoutScript = script(changes.payoutAddress); delete changes.payoutAddress; } - if (operation === 'updateRegistrar' && current.allowOwnerPreparation && changes.pqOwnerPublicKey) changes.ownerPreparation = true; + if (operation === 'updateRegistrar' && current.allowOwnerPreparation && + (changes.pqOwnerCommitment || changes.pqVotingCommitment || current.node.pqOwnerRecord || rolloverSource)) changes.ownerPreparation = true; if (operation === 'registerOperator' || operation === 'rotateOperator') { changes.mode = operation === 'registerOperator' ? 'initial' : 'rotate'; changes.candidate = { version: 1, profile: 1, keyVersion: changes.keyVersion, @@ -259,9 +378,12 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient updateRegistrar: sdk.buildSentryRegistrarUpdate, revoke: sdk.buildSentryRevocation, registerOperator: sdk.buildSentryOperatorUpdate, rotateOperator: sdk.buildSentryOperatorUpdate }[operation]; if (!builder) throw failure('operation_not_supported'); - const buildArgs = { ...current, ...changes, ...(body.collateralOutpoint ? { collateralOutpoint: body.collateralOutpoint } : {}) }; + const buildArgs = { ...current, ...changes, ...(collateral ? { collateralOutpoint: fundedAddress + ? { txid: '00'.repeat(32), vout: 0 } : collateral } : {}) }; + const fundedOutput = current.approvedCollateralScript ? { scriptHex: current.approvedCollateralScript, + valueSatoshis: rolloverSource?.valueSatoshis ?? current.registration.requiredCollateralSatoshis } : undefined; const placeholder = builder({ ...buildArgs, - inputs: [{ txid: 'ff'.repeat(32), vout: 0 }], outputs: [], + inputs: [{ txid: 'ff'.repeat(32), vout: 0 }], outputs: fundedOutput ? [fundedOutput] : [], }); const payload = decode(placeholder.transactionHex).outs.at(-1).script; if (!fundingClient.fetchUtxos) throw failure('sentry_funding_unavailable', 503); @@ -272,22 +394,42 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient if (body.collateralOutpoint) reserved.add(`${body.collateralOutpoint.txid}:${body.collateralOutpoint.vout}`); const available = fundingOutputs.filter((entry) => !entry.assetInfo && entry.confirmations > 0 && !reserved.has(`${entry.txid || entry.txId}:${entry.vout}`)); if (!available.length) throw failure('no_unreserved_fee_funds'); + let forcedInputs; + if (rolloverSource) { + const input = fundingOutputs.find((entry) => (entry.txid || entry.txId) === rolloverSource.txid && entry.vout === rolloverSource.vout); + if (!input || input.assetInfo || !(input.confirmations > 0) || String(input.value) !== rolloverSource.valueSatoshis || + script(input.address) !== rolloverSource.scriptHex) throw failure('collateral_not_in_selected_wallet', 409); + forcedInputs = [input]; + } + const outputs = [{ script: Buffer.from(payload), value: new BN(0) }]; + if (fundedOutput) outputs.unshift({ script: Buffer.from(fundedOutput.scriptHex, 'hex'), value: new BN(fundedOutput.valueSatoshis) }); const funded = await fundingClient.createTransaction({ rbf: false }, body.changeAddress, - [{ script: Buffer.from(payload), value: new BN(0) }], feeRate, body.xpub, { utxos: available, assets: [] }); + outputs, feeRate, body.xpub, { utxos: available, assets: [] }, forcedInputs); if (!funded?.psbt) throw failure('funding_failed'); const fundingPsbt = funded.psbt.toBase64(); const unsigned = funded.psbt.__CACHE.__TX; + const spendOutputs = unsigned.outs.filter((output) => output.script[0] !== 0x6a) + .map((output) => ({ valueSatoshis: String(output.value), scriptHex: Buffer.from(output.script).toString('hex') })); + if (fundedOutput) { + const index = spendOutputs.findIndex((output) => output.scriptHex === fundedOutput.scriptHex && output.valueSatoshis === fundedOutput.valueSatoshis); + if (index < 0) throw failure('funded_collateral_missing', 503); + if (rolloverSource) buildArgs.collateralRollover.outputIndex = index; + else buildArgs.collateralOutpoint.vout = collateral.vout = current.registration.collateralVout = index; + } const request = builder({ ...buildArgs, inputs: unsigned.ins.map((input) => ({ txid: Buffer.from(input.hash).reverse().toString('hex'), vout: input.index, sequence: input.sequence })), - outputs: unsigned.outs.filter((output) => output.script[0] !== 0x6a).map((output) => ({ valueSatoshis: String(output.value), scriptHex: Buffer.from(output.script).toString('hex') })), + outputs: spendOutputs, lockTime: unsigned.locktime, }); const previousTransactions = await priorTransactions(decode(request.transactionHex)); - const review = operation === 'updateService' ? sdk.reviewSentryOperation(request, { ...current, previousTransactions, maxFeeSatoshis }) - : sdk.reviewSentryManagementOperation(request, { ...current, previousTransactions, maxFeeSatoshis }); + const reviewContext = { ...current, previousTransactions, maxFeeSatoshis }; + const review = operation === 'updateService' ? sdk.reviewSentryOperation(request, reviewContext) + : sdk.isSentryOwnerDraft(request) ? sdk.reviewSentryOwnerDraft(request, reviewContext) + : sdk.reviewSentryManagementOperation(request, reviewContext); return { request, review, fundingPsbt, - anchor: { chain: current.chain, ...(current.node ? { node: current.node } : {}), ...(current.registration ? { registration: current.registration } : {}) }, - ...(body.collateralOutpoint ? { collateralOutpoint: body.collateralOutpoint } : {}) }; + anchor: { chain: current.chain, ...(current.node ? { node: current.node } : {}), ...(current.registration ? { registration: current.registration } : {}), + ...(current.approvedCollateralScript ? { approvedCollateralScript: current.approvedCollateralScript } : {}) }, + ...(collateral ? { collateralOutpoint: collateral } : {}), ...(rolloverAddress ? { rolloverAddress } : {}) }; }, async authorize(row, authorization) { const validator = row.prepared.request.operation === 'updateService' ? sdk.validateSentryOperationRequest : sdk.validateSentryManagementRequest; @@ -299,22 +441,16 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient if (typeof signedPsbt !== 'string' || signedPsbt.length > 300000) throw failure('invalid_signed_transaction'); const psbt = bitcoinjs.Psbt.fromBase64(signedPsbt, { network: fundingClient.network }); const tx = psbt.extractTransaction(); - await liveReview(row, tx.toHex()); - const currentNodes = await call('protx_list', ['registered', true]); - if (!Array.isArray(currentNodes)) throw failure('node_list_unavailable', 503); - const collateral = new Set(currentNodes.map((entry) => `${entry.collateralHash}:${entry.collateralIndex}`)); - if (tx.ins.some((input) => collateral.has(`${Buffer.from(input.hash).reverse().toString('hex')}:${input.index}`))) throw failure('registered_collateral_spend'); + const { fields } = await liveReview(row, tx.toHex()); + await checkReservedInputs(tx, row); const accepted = await call('testmempoolaccept', [[tx.toHex()]]); if (!Array.isArray(accepted) || accepted.length !== 1 || !accepted[0].allowed) throw failure('transaction_rejected', 422); - return { transactionHex: tx.toHex(), txid: tx.getId() }; + return { transactionHex: tx.toHex(), txid: tx.getId(), fields }; }, async validateStored(row) { await assertNetwork(row.network); if (typeof row.signed_hex !== 'string' || row.signed_hex.length > 400000 || decode(row.signed_hex).getId() !== row.txid) throw failure('stored_transaction_invalid', 409); - const currentNodes = await call('protx_list', ['registered', true]); - if (!Array.isArray(currentNodes)) throw failure('node_list_unavailable', 503); - const collateral = new Set(currentNodes.map((entry) => `${entry.collateralHash}:${entry.collateralIndex}`)); - if (decode(row.signed_hex).ins.some((input) => collateral.has(`${Buffer.from(input.hash).reverse().toString('hex')}:${input.index}`))) throw failure('registered_collateral_spend'); + await checkReservedInputs(decode(row.signed_hex), row); const accepted = await call('testmempoolaccept', [[row.signed_hex]]); if (!Array.isArray(accepted) || accepted.length !== 1 || !accepted[0].allowed) throw failure('transaction_rejected', 422); }, @@ -338,17 +474,35 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient } const operation = row.prepared.request.operation; const observed = await context(row.network, operation === 'register' ? row.txid : row.protx_hash); + const fields = row.prepared.finalFields ?? row.prepared.review.fields; + if (row.prepared.rolloverAddress) { + const { rollover } = sdk.inspectSentryManagementOperation({ ...row.prepared.request, transactionHex: row.signed_hex }); + if (!rollover || observed.node.collateralOutpoint.txid !== row.txid || observed.node.collateralOutpoint.vout !== rollover.outputIndex) + return { confirmed: true, matches: false }; + } + if (fields?.pqOwnerCommitment && !/^0+$/.test(fields.pqOwnerCommitment)) { + const current = observed.node.pqOwnerRecord; + const expectedVersion = (row.prepared.anchor?.node?.pqOwnerRecord?.keyVersion ?? 0) + 1; + if (current?.commitment !== fields.pqOwnerCommitment || current.keyVersion !== expectedVersion || + current.derivationNonce !== (fields.pqOwnerDerivationNonce || '00'.repeat(32))) + return { confirmed: true, matches: false }; + } if (operation === 'revoke') return { confirmed: true, matches: observed.node.poseBanHeight >= 0 && observed.node.revocationReason === Number(row.prepared.review.fields.reason) }; if (operation === 'registerOperator' || operation === 'rotateOperator') return { confirmed: true, - matches: observed.node.pqRecord?.publicKey === row.prepared.review.fields.operatorPublicKey && - observed.node.pqRecord?.keyVersion === Number(row.prepared.review.fields.globalKeyVersion) }; + matches: observed.node.pqRecord?.publicKey === fields.operatorPublicKey && + observed.node.pqRecord?.keyVersion === Number(fields.globalKeyVersion) }; if (operation === 'register' || operation === 'updateRegistrar') { - const fields = row.prepared.review.fields; + if (operation === 'register' && row.prepared.collateralOutpoint) { + const expected = row.prepared.collateralOutpoint; + const observedOutpoint = observed.node.collateralOutpoint; + if (observedOutpoint.txid !== (expected.address ? row.txid : expected.txid) || observedOutpoint.vout !== expected.vout) + return { confirmed: true, matches: false }; + } const expected = Object.entries({ ownerKeyId: fields.ownerKeyId, votingKeyId: fields.votingKeyId, service: fields.service, payoutScript: fields.payoutAddress ? script(fields.payoutAddress) : undefined, - operatorPublicKey: fields.operatorPublicKey, pqVotingPublicKey: fields.pqVotingPublicKey }); - if (fields.pqOwnerPublicKey && observed.node.pqOwnerRecord?.publicKey !== fields.pqOwnerPublicKey) return { confirmed: true, matches: false }; - return { confirmed: true, matches: expected.every(([key, value]) => !value || observed.node[key]?.toLowerCase() === value.toLowerCase()) }; + operatorPublicKey: fields.operatorPublicKey, pqVotingCommitment: fields.pqVotingCommitment }); + return { confirmed: true, matches: expected.every(([key, value]) => !value || + (observed.node[key] ?? (key === 'pqVotingCommitment' ? '00'.repeat(32) : '')).toLowerCase() === value.toLowerCase()) }; } const intended = row.prepared.review.changes; return { confirmed: true, matches: ['service', 'operatorPayoutScript', 'nevmAddress'].every((key) => observed.node[key].toLowerCase() === intended[key].next.toLowerCase()) }; diff --git a/lib/sentryManagement.js b/lib/sentryManagement.js index c319232..c3dbae8 100644 --- a/lib/sentryManagement.js +++ b/lib/sentryManagement.js @@ -62,9 +62,9 @@ function createSentryRepository(db, { now = Date.now } = {}) { }, read, list: (userId) => db.prepare("SELECT id,network,CASE WHEN json_extract(prepared, '$.request.operation')='register' THEN txid ELSE protx_hash END AS proTxHash,status,txid,json_extract(prepared, '$.request.operation') AS operation,created_at AS createdAt,error_code AS errorCode FROM sentry_operations WHERE user_id=? ORDER BY created_at DESC LIMIT 100").all(userId), - claim(id, userId, signedHex, txid) { - const changed = db.prepare("UPDATE sentry_operations SET status='submitting',signed_hex=?,txid=?,protx_hash=CASE WHEN json_extract(prepared, '$.request.operation')='register' THEN ? ELSE protx_hash END,updated_at=? WHERE id=? AND user_id=? AND status='prepared'") - .run(signedHex, txid, txid, now(), id, userId).changes; + claim(id, userId, signedHex, txid, fields) { + const changed = db.prepare("UPDATE sentry_operations SET status='submitting',signed_hex=?,txid=?,protx_hash=CASE WHEN json_extract(prepared, '$.request.operation')='register' THEN ? ELSE protx_hash END,prepared=json_set(prepared, '$.finalFields', json(?)),updated_at=? WHERE id=? AND user_id=? AND status='prepared'") + .run(signedHex, txid, txid, JSON.stringify(fields ?? null), now(), id, userId).changes; return changed === 1; }, claimRetry(id, userId, updatedAt) { @@ -86,11 +86,12 @@ function createSentryManagement({ repository, adapter, now = Date.now }) { return { capabilities: async () => configured().capabilities(), context: async (network, proTxHash, collateral) => { - nodeIdentity(network, proTxHash || collateral?.txid); + nodeIdentity(network, proTxHash || collateral?.txid || (collateral?.address && '0'.repeat(64))); + if (proTxHash && collateral && (!collateral.address || collateral.txid)) throw failure('invalid_collateral'); return configured().context(network, proTxHash, collateral); }, votingContext: async (query) => { - strictObject(query, ['network', 'proposalHash', 'proTxHashes']); + strictObject(query, ['network', 'proposalHash', 'proTxHashes', 'signingHeight', 'signingBlockHash']); if (typeof query.proposalHash !== 'string') throw failure('invalid_node_identity'); nodeIdentity(query.network, query.proposalHash); if (/^0+$/.test(query.proposalHash)) throw failure('invalid_node_identity'); @@ -101,7 +102,13 @@ function createSentryManagement({ repository, adapter, now = Date.now }) { nodeIdentity(query.network, hash); if (/^0+$/.test(hash)) throw failure('invalid_node_identity'); }); - return configured().votingContext(query.network, query.proposalHash, hashes); + if (query.signingHeight === undefined && query.signingBlockHash === undefined) + return configured().votingContext(query.network, query.proposalHash, hashes); + if (typeof query.signingHeight !== 'string' || !/^(0|[1-9][0-9]{0,9})$/.test(query.signingHeight) || + Number(query.signingHeight) > 0x7fffffff || typeof query.signingBlockHash !== 'string' || + !HASH.test(query.signingBlockHash) || /^0+$/.test(query.signingBlockHash)) throw failure('invalid_signing_block'); + return configured().votingContext(query.network, query.proposalHash, hashes, + { height: Number(query.signingHeight), hash: query.signingBlockHash }); }, watches: (userId) => repository.watches(userId), async watch(userId, body) { @@ -121,19 +128,26 @@ function createSentryManagement({ repository, adapter, now = Date.now }) { const operation = body.operation || 'updateService'; const allowed = { updateService: ['nevmAddress', 'service', 'operatorPayoutAddress'], - register: ['service', 'ownerAddress', 'votingAddress', 'operatorPublicKey', 'pqOwnerPublicKey', 'pqVotingPublicKey', 'operatorRewardBasisPoints', 'payoutAddress'], - updateRegistrar: ['operatorPublicKey', 'votingAddress', 'payoutAddress', 'pqOwnerPublicKey', 'pqVotingPublicKey'], + register: ['service', 'ownerAddress', 'votingAddress', 'operatorPublicKey', 'collateralAddress', 'operatorRewardBasisPoints', 'payoutAddress'], + updateRegistrar: ['operatorPublicKey', 'ownerAddress', 'votingAddress', 'payoutAddress', 'collateralAddress', 'collateralKeyCommitment'], revoke: ['reason'], - registerOperator: ['operatorPublicKey', 'childKeyCommitment', 'keyVersion'], - rotateOperator: ['operatorPublicKey', 'childKeyCommitment', 'keyVersion'], + registerOperator: ['operatorPublicKey', 'childKeyCommitment', 'keyVersion', 'ownerAddress'], + rotateOperator: ['operatorPublicKey', 'childKeyCommitment', 'keyVersion', 'ownerAddress'], }; if (!allowed[operation]) throw failure('operation_not_supported'); - const { network, proTxHash } = nodeIdentity(body.network, operation === 'register' ? body.collateralOutpoint?.txid : body.proTxHash); - if (operation === 'register') { + strictObject(body.changes, allowed[operation]); + const funded = operation === 'register' && Object.hasOwn(body.changes, 'collateralAddress'); + if (operation === 'updateRegistrar' && (Object.hasOwn(body.changes, 'collateralAddress') || Object.hasOwn(body.changes, 'collateralKeyCommitment')) && + (typeof body.changes.collateralAddress !== 'string' || !body.changes.collateralAddress || + typeof body.changes.collateralKeyCommitment !== 'string' || !HASH.test(body.changes.collateralKeyCommitment) || /^0+$/.test(body.changes.collateralKeyCommitment))) + throw failure('invalid_collateral'); + if (funded && (typeof body.changes.collateralAddress !== 'string' || !body.changes.collateralAddress || body.collateralOutpoint)) throw failure('invalid_collateral'); + if (operation !== 'register' && body.collateralOutpoint) throw failure('invalid_collateral'); + const { network, proTxHash } = nodeIdentity(body.network, operation === 'register' ? (funded ? '0'.repeat(64) : body.collateralOutpoint?.txid) : body.proTxHash); + if (operation === 'register' && !funded) { strictObject(body.collateralOutpoint, ['txid', 'vout']); if (!Number.isSafeInteger(body.collateralOutpoint.vout) || body.collateralOutpoint.vout < 0 || body.collateralOutpoint.vout > 0xffffffff) throw failure('invalid_collateral'); } - strictObject(body.changes, allowed[operation]); if (!Object.keys(body.changes).length) throw failure('no_changes'); // Omission preserves NEVM. Empty string is an explicit removal only. if (Object.hasOwn(body.changes, 'nevmAddress') && body.changes.nevmAddress !== '' && @@ -165,7 +179,7 @@ function createSentryManagement({ repository, adapter, now = Date.now }) { // Verify exact prepared inputs/outputs, operator signature and current // chain state before occupying the durable one-publication journal. const verified = await configured().validateSigned(row, body.signedPsbt); - if (!repository.claim(id, userId, verified.transactionHex, verified.txid)) { + if (!repository.claim(id, userId, verified.transactionHex, verified.txid, verified.fields)) { const occupied = repository.read(id, userId); return { id, status: occupied.status, txid: occupied.txid }; } diff --git a/lib/sentryManagement.test.js b/lib/sentryManagement.test.js index 74195ab..48286be 100644 --- a/lib/sentryManagement.test.js +++ b/lib/sentryManagement.test.js @@ -83,13 +83,18 @@ describe('Sentry operation boundary and durable journal', () => { const query = { network: 'testnet', proposalHash: TXID, proTxHashes: HASH }; await expect(f.management.votingContext(query)).resolves.toEqual({ proposalHash: TXID, nodes: [] }); expect(f.adapter.votingContext).toHaveBeenCalledWith('testnet', TXID, [HASH]); + await f.management.votingContext({ ...query, signingHeight: '94', signingBlockHash: HASH }); + expect(f.adapter.votingContext).toHaveBeenCalledWith('testnet', TXID, [HASH], { height: 94, hash: HASH }); + for (const pin of [{ signingHeight: '94' }, { signingBlockHash: HASH }, { signingHeight: '094', signingBlockHash: HASH }, + { signingHeight: ['94'], signingBlockHash: HASH }, { signingHeight: '94', signingBlockHash: '0'.repeat(64) }]) + await expect(f.management.votingContext({ ...query, ...pin })).rejects.toMatchObject({ code: 'invalid_signing_block' }); for (const change of [ { rpcUrl: 'https://untrusted.example' }, { proposalHash: [] }, { proposalHash: [TXID] }, { proTxHashes: [] }, { proTxHashes: `${HASH},${HASH}` }, { proTxHashes: Array.from({ length: 21 }, (_, i) => i.toString(16).padStart(64, '0')).join(',') }, { proTxHashes: '' }, { proTxHashes: `${HASH},` }, { network: 'unknown' }, { proTxHashes: '0'.repeat(64) }, { proposalHash: '0'.repeat(64) }, ]) await expect(f.management.votingContext({ ...query, ...change })).rejects.toBeDefined(); - expect(f.adapter.votingContext).toHaveBeenCalledTimes(1); + expect(f.adapter.votingContext).toHaveBeenCalledTimes(2); }); test('rejects secrets, arbitrary RPC fields and malformed NEVM', async () => { await expect(f.management.prepare(1, { ...body(), privateKey: 'secret' })).rejects.toMatchObject({ code: 'invalid_request' }); diff --git a/lib/sentryVotingContext.test.js b/lib/sentryVotingContext.test.js index 293c855..de91631 100644 --- a/lib/sentryVotingContext.test.js +++ b/lib/sentryVotingContext.test.js @@ -16,7 +16,7 @@ function fixture() { const capabilities = { version: 1, genesisHash: GENESIS, network: 'test', height: 100, blockHash: BLOCK, era: 'legacy-v3' }; const implementation = async (method, args) => { if (method === 'getblockchaininfo') return { chain: 'test' }; - if (method === 'getblockhash') return GENESIS; + if (method === 'getblockhash') return args[0] === 0 ? GENESIS : BLOCK; if (method === 'protx_capabilities') return capabilities; if (method === 'gobject_get') return proposal; if (method === 'protx_info') return { ...node, proTxHash: args[0] }; @@ -72,7 +72,35 @@ test('wrong genesis and active PQ era never return legacy voting authority', asy expect(f.rpcCall.mock.calls.some(([method]) => method === 'gobject_get')).toBe(false); f.rpcCall.mockImplementation(f.implementation); f.capabilities.era = 'pq-v4'; - await expect(f.adapter.votingContext('testnet', PROPOSAL, [PROTX])).rejects.toMatchObject({ code: 'voting_protocol_not_supported' }); + await expect(f.adapter.votingContext('testnet', PROPOSAL, [PROTX])).rejects.toMatchObject({ code: 'core_sentry_capabilities_required' }); +}); + +test('a PQ vote uses the same active ancestor after a tip extension and refuses a stale registration or changed block', async () => { + const f = fixture(); + const root = '16'.repeat(32); + Object.assign(f.capabilities, { era: 'pq-v4', activationHeight: 70 }); + Object.assign(f.node.state, { pqVotingCommitment: root, pqVotingKeyVersion: 2, pqVotingKeyActivationHeight: 90, PoSeBanHeight: -1 }); + f.fundingClient.bitcoinjs.address.toOutputScript.mockReturnValue(Buffer.from('5220' + root, 'hex')); + const first = await f.adapter.votingContext('testnet', PROPOSAL, [PROTX]); + expect(first.signingBlock).toEqual({ height: 94, hash: BLOCK }); + expect(first.nodes[0]).toMatchObject({ votingKeyId: root, votingKeyVersion: 2, votingKeyActivatedHeight: 90 }); + f.capabilities.height++; + expect((await f.adapter.votingContext('testnet', PROPOSAL, [PROTX], first.signingBlock)).signingBlock).toEqual(first.signingBlock); + await expect(f.adapter.votingContext('testnet', PROPOSAL, [PROTX], { height: 94, hash: COLLATERAL })).rejects.toMatchObject({ code: 'signing_block_unavailable' }); + await expect(f.adapter.votingContext('testnet', PROPOSAL, [PROTX], { height: 99, hash: BLOCK })).rejects.toMatchObject({ code: 'signing_block_unavailable' }); + f.node.state.pqVotingKeyActivationHeight = 95; + await expect(f.adapter.votingContext('testnet', PROPOSAL, [PROTX], first.signingBlock)).rejects.toMatchObject({ code: 'voting_key_not_active_at_signing_block' }); + f.node.state.PoSeBanHeight = 95; + await expect(f.adapter.votingContext('testnet', PROPOSAL, [PROTX])).rejects.toMatchObject({ code: 'invalid_voting_node' }); +}); + +test('preactivation votes still use the retained ECDSA identifier when the next block activates PQ', async () => { + const f = fixture(); + Object.assign(f.capabilities, { era: 'pq-v4', activationHeight: 101 }); + f.node.state.legacyVotingAddress = 'retained-voting-address'; + const context = await f.adapter.votingContext('testnet', PROPOSAL, [PROTX]); + expect(context.chain.era).toBe('legacy-v3'); + expect(f.fundingClient.bitcoinjs.address.toOutputScript).toHaveBeenCalledWith('retained-voting-address', f.fundingClient.network); }); test.each([ diff --git a/package-lock.json b/package-lock.json index 83639c1..694aa81 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,7 @@ "version": "1.0.0", "license": "MIT", "dependencies": { - "@sidhujag/sysweb3-sentry": "0.1.3", + "@sidhujag/sysweb3-sentry": "0.1.4", "@syscoin/syscoin-js": "git+https://github.com/syscoin/syscoind-rpc.git#637a1de10522d1ce34a4e0f283c59b9d55bde814", "axios": "^1.15.2", "better-sqlite3": "^12.11.1", @@ -1806,9 +1806,9 @@ } }, "node_modules/@sidhujag/sysweb3-sentry": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/@sidhujag/sysweb3-sentry/-/sysweb3-sentry-0.1.3.tgz", - "integrity": "sha512-uFjafUFpNjIX2gdEeiIltkmPKw5vhQNuCrrGN/P+VYvWp8lgow8sfl1qGiVei0gWD0C3qTen758OxFWdtYT+gA==", + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/@sidhujag/sysweb3-sentry/-/sysweb3-sentry-0.1.4.tgz", + "integrity": "sha512-IshrnCoepii6dafUkXgMOdNUkv/kyuET5Ghg0JIbQtZkB0gaoy7EbXwXLpHWo8EjP4JXHB3/q+RFTs7eBwR9hQ==", "license": "MIT", "dependencies": { "@noble/curves": "2.4.0", diff --git a/package.json b/package.json index dd38345..d5ba908 100644 --- a/package.json +++ b/package.json @@ -33,7 +33,7 @@ ] }, "dependencies": { - "@sidhujag/sysweb3-sentry": "0.1.3", + "@sidhujag/sysweb3-sentry": "0.1.4", "@syscoin/syscoin-js": "git+https://github.com/syscoin/syscoind-rpc.git#637a1de10522d1ce34a4e0f283c59b9d55bde814", "axios": "^1.15.2", "better-sqlite3": "^12.11.1", diff --git a/routes/gov.js b/routes/gov.js index 96f5b3d..b201ad0 100644 --- a/routes/gov.js +++ b/routes/gov.js @@ -173,7 +173,7 @@ function createGovRouter({ // entries: [{ // collateralHash: 64-hex, // collateralIndex: uint, - // voteSig: base64(65 bytes) // client-signed + // voteSig: base64 ECDSA signature or PQ funding envelope // }, ...] // } // diff --git a/routes/sentry.js b/routes/sentry.js index a98e3d0..ed8dc7e 100644 --- a/routes/sentry.js +++ b/routes/sentry.js @@ -8,8 +8,13 @@ function createSentryRouter({ management, sessionMw, csrfMw, limiter, readLimite }; if (readLimiter) router.use(readLimiter); router.get('/capabilities', route(() => management.capabilities())); - router.get('/context', route((req) => management.context(req.query.network, req.query.proTxHash, - req.query.collateralTxid ? { txid: req.query.collateralTxid, vout: Number(req.query.collateralVout) } : undefined))); + router.get('/context', route((req) => { + const { network, proTxHash, collateralTxid, collateralAddress, collateralVout } = req.query; + return management.context(network, proTxHash, collateralTxid || collateralAddress + ? { ...(collateralTxid ? { txid: collateralTxid } : {}), ...(collateralAddress ? { address: collateralAddress } : {}), + vout: Number(collateralVout ?? (collateralAddress ? 0 : NaN)) } + : undefined); + })); router.get('/voting-context', votingContextLimiter, route((req) => management.votingContext(req.query))); // The public context is read-only. Every management route requires a // verified session. State-changing calls additionally bind the exact origin. diff --git a/scripts/sentry-core-regtest.mjs b/scripts/sentry-core-regtest.mjs index aab6e7a..5568a94 100644 --- a/scripts/sentry-core-regtest.mjs +++ b/scripts/sentry-core-regtest.mjs @@ -24,8 +24,9 @@ const server = createServer(); await new Promise((done) => server.listen(0, '127.0.0.1', done)); const port = server.address().port; await new Promise((done) => server.close(done)); -const args = ['-regtest', `-datadir=${datadir}`, `-rpcport=${port}`, '-server=1', '-listen=0', '-connect=0', '-dnsseed=0', '-discover=0', '-txindex=1', '-fallbackfee=0.0001', '-dip3params=1:1', '-dip19params=1', '-mncollateral=100']; -const daemon = spawn(resolve(core, 'syscoind'), args, { stdio: 'ignore' }); +const args = ['-regtest', `-datadir=${datadir}`, `-rpcport=${port}`, '-server=1', '-listen=0', '-connect=0', '-dnsseed=0', '-discover=0', '-txindex=1', '-fallbackfee=0.0001', '-dip3params=1:1', '-dip19params=1', '-mncollateral=100', + '-sporkkey=cVpF924EspNh8KjYsfhgY96mmxvT6DgdWiTYMtMjuM74hJaU5psW']; +let daemon = spawn(resolve(core, 'syscoind'), args, { stdio: 'ignore' }); let wallet = false; let indexer; let database; @@ -51,11 +52,17 @@ try { // addresses in this regtest; public-network addresses are not substituted. const address = () => rpc('getnewaddress', ['', 'legacy']); const mining = await address(); + // This disconnected legacy regtest has no governance quorum to service superblocks. + await rpc('spork', ['SPORK_9_SUPERBLOCKS_ENABLED', 4070908800]); await rpc('generatetoaddress', [120, mining]); const capabilities = await rpc('protx_capabilities'); assert.equal(capabilities.era, 'legacy-v3'); assert.equal(capabilities.requiredCollateralSatoshis, '10000000000'); - const owner = await rpc('getnewaddress'); + const bitcoinjs = utils.bitcoinjs; + const network = { ...utils.syscoinNetworks.testnet, bech32: 'bcrt', pubKeyHash: 111 }; + const keyAddress = (key) => bitcoinjs.payments.p2wpkh({ pubkey: Buffer.from(key.publicKey, 'hex'), network }).address; + const initialOwner = await sdk.importSentryAuthorityKey('owner', 'secp256k1', '00'.repeat(31) + '08'); + const owner = keyAddress(initialOwner); const collateralAddress = await rpc('getnewaddress'); const payout = await rpc('getnewaddress'); const feeAddress = await address(); @@ -63,23 +70,12 @@ try { const operator = await sdk.importSentryOperatorKey('bls-basic', '00'.repeat(31) + '02'); await rpc('sendtoaddress', [feeAddress, 200]); await rpc('generatetoaddress', [1, mining]); - const proTxHash = await rpc('protx_register_fund', [collateralAddress, '1.2.3.4:18369', owner, initialOperator.publicKey, owner, 0, payout, feeAddress, true, false]); + const proTxHash = await rpc('protx_register_fund', [collateralAddress, '1.2.3.4:18369', owner, initialOperator.publicKey, owner, 0, payout, feeAddress, true]); // Confirmation is evaluated from the previous block after two node-payment // rounds, so the registering block itself is not one of these confirmations. await rpc('generatetoaddress', [5, mining]); const info = await rpc('protx_info', [proTxHash]); assert(info.state.confirmedHash && !/^0+$/.test(info.state.confirmedHash), 'Registered node must be confirmed before NEVM updates'); - // Operator rotation resets service and bans until the new operator supplies - // a service update. Recover that genuine Core lifecycle through the SDK. - await rpc('protx_update_registrar', [proTxHash, operator.publicKey, '', '', feeAddress, false]); - await rpc('generatetoaddress', [1, mining]); - const resetState = (await rpc('protx_info', [proTxHash])).state; - assert(resetState.PoSeBanHeight >= 0); - console.log(JSON.stringify({ stage: 'operator-reset', service: resetState.service, poseBanHeight: resetState.PoSeBanHeight })); - const bitcoinjs = utils.bitcoinjs; - // Core regtest deliberately uses Bitcoin regtest address prefixes; this - // isolated harness must not label those addresses as Tanenbaum testnet. - const network = { ...utils.syscoinNetworks.testnet, bech32: 'bcrt', pubKeyHash: 111 }; // Minimal local read-only Blockbook-compatible raw-tx endpoint for the // library's legacy-input PSBT population. The data comes from real Core. indexer = createHttpServer(async (request, response) => { @@ -96,9 +92,17 @@ try { const fundingClient = { bitcoinjs, network, async fetchUtxos() { - return (await rpc('listunspent', [1])).map((utxo) => ({ ...utxo, value: Math.round(utxo.amount * 1e8) })); + const outputs = (await rpc('listunspent', [1])).map((utxo) => ({ ...utxo, value: Math.round(utxo.amount * 1e8) })); + // Core's wallet can locally lock registered collateral. Blockbook's + // xpub UTXO response still includes that unspent wallet output. + const coin = await rpc('gettxout', [info.collateralHash, info.collateralIndex, true]); + if (coin && !outputs.some((o) => o.txid === info.collateralHash && o.vout === info.collateralIndex)) + outputs.push({ txid: info.collateralHash, vout: info.collateralIndex, confirmations: coin.confirmations, + value: Math.round(coin.value * 1e8), address: coin.scriptPubKey.address }); + return outputs; }, - createTransaction: (...parameters) => fundingLibrary.createTransaction(...parameters), + createTransaction: (options, change, outputs, rate, xpub, utxos, forced) => + fundingLibrary.createTransaction(options, change, outputs, rate, xpub, utxos, undefined, forced), }; const genesisHash = await rpc('getblockhash', [0]); const adapter = createSentryAdapter({ rpcCall: rpc, network: 'regtest', genesisHash, sdk, fundingClient }); @@ -122,7 +126,6 @@ try { const votingKey = await sdk.importSentryAuthorityKey('voting', 'secp256k1', '00'.repeat(31) + '05'); const registeredOperator = await sdk.importSentryAuthorityKey('operator', 'bls-basic', '00'.repeat(31) + '06'); const rotatedOperator = await sdk.importSentryAuthorityKey('operator', 'bls-basic', '00'.repeat(31) + '07'); - const keyAddress = (key) => bitcoinjs.payments.p2wpkh({ pubkey: Buffer.from(key.publicKey, 'hex'), network }).address; const externalCollateralAddress = keyAddress(collateralKey); const externalCollateralTxid = await rpc('sendtoaddress', [externalCollateralAddress, 100]); await rpc('generatetoaddress', [1, mining]); @@ -160,6 +163,11 @@ try { managementLifecycle.push({ operation: body.operation, txid, proTxHash: confirmed.proTxHash }); return txid; } + // Rotate through the SDK and reset service before exercising operator recovery. + await completeManagement({ operation: 'updateRegistrar', proTxHash, changes: { operatorPublicKey: operator.publicKey } }, initialOwner); + const resetState = (await rpc('protx_info', [proTxHash])).state; + assert(resetState.PoSeBanHeight >= 0); + console.log(JSON.stringify({ stage: 'operator-reset', service: resetState.service, poseBanHeight: resetState.PoSeBanHeight })); const createdProTxHash = await completeManagement({ operation: 'register', collateralOutpoint: externalCollateral, changes: { service: '1.2.3.5:18369', ownerAddress: keyAddress(ownerKey), votingAddress: keyAddress(ownerKey), @@ -198,7 +206,7 @@ try { const authorized = await adapter.authorize(row, authorization); if (!tamperedAddressRejection && update.changes.nevmAddress) { // Change one address byte after operator approval, then legitimately - // re-sign only the fee input. Core must still reject the authorization. + // re-sign only the fee input. The backend must reject the changed approval. const original = bitcoinjs.Psbt.fromBase64(authorized.psbt.psbt, { network }); const tampered = new bitcoinjs.Psbt({ network }); tampered.setVersion(original.version); tampered.setLocktime(original.locktime); @@ -210,11 +218,10 @@ try { }); const feeSigned = await rpc('walletprocesspsbt', [tampered.toBase64()]); assert.equal(feeSigned.complete, true); - const tamperedHex = bitcoinjs.Psbt.fromBase64(feeSigned.psbt, { network }).extractTransaction().toHex(); - const [rejected] = await rpc('testmempoolaccept', [[tamperedHex]]); - assert.equal(rejected.allowed, false, 'Changing NEVM after operator approval must fail Core verification'); - tamperedAddressRejection = rejected['reject-reason']; - assert.match(tamperedAddressRejection, /bad-protx-bls-sig/); + await assert.rejects(adapter.validateSigned(row, feeSigned.psbt), (error) => { + tamperedAddressRejection = error.code; + return error.code === 'operation_changed' || error.code === 'invalid_node_authorization'; + }); } const signed = await rpc('walletprocesspsbt', [authorized.psbt.psbt]); assert.equal(signed.complete, true); @@ -237,7 +244,58 @@ try { if (update.changes.service) { assert.equal(state.service, update.changes.service); assert.equal(state.PoSeBanHeight, -1); } observed.push({ operation: update.operation, txid: verified.txid, nevmAddress: state.nevmAddress || '' }); } - console.log(JSON.stringify({ result: 'passed', scope: 'disconnected synthetic legacy-v3 regtest', proTxHash, createdProTxHash, managementLifecycle, tamperedAddressRejection, manualRetry: 'same bytes and txid after simulated transport outage; known mempool retry skipped', observed, datadir }, null, 2)); + const height = await rpc('getblockcount'); + await rpc('stop'); + await new Promise((done) => daemon.exitCode !== null ? done() : daemon.once('exit', done)); + wallet = false; + daemon = spawn(resolve(core, 'syscoind'), [...args, '-reindex', `-pqpreparationheight=${height}`, + '-pqchainlockepochorigin=1440', '-pqregistrationcutoffblocks=288', '-pqrostersnapshotlag=288', + '-pqfuturehorizonepochs=8', '-pqfinalitypreparation=1'], { stdio: 'ignore' }); + await exec(resolve(core, 'syscoin-cli'), ['-regtest', `-datadir=${datadir}`, `-rpcport=${port}`, '-rpcwait', '-rpcwaittimeout=60', 'getblockchaininfo']); + if (!(await rpc('listwallets')).includes('sentry-qa')) await rpc('loadwallet', ['sentry-qa']); + wallet = true; + while (!(await rpc('mnsync', ['status'])).IsSynced) await rpc('mnsync', ['next']); + assert.equal((await adapter.capabilities()).collateralRollover, true); + const cold = await rpc('protx_generate_collateral_key'); + const pqKey = await sdk.deriveSentryOperatorKey('slh-dsa-shake-128s', '21'.repeat(48)); + const pqOwner = await sdk.importSentryAuthorityKey('owner', pqKey.scheme, pqKey.secretKey); + const pqRoot = sdk.sentryP2MRRoot(genesisHash, 'owner', pqOwner.publicKey); + const pqVotingAddress = sdk.sentryP2MRAddress(sdk.sentryP2MRRoot(genesisHash, 'voting', '43'.repeat(32)), network.bech32); + const rollover = await lifecycleManagement.prepare(1, { ...managementBody, proTxHash, operation: 'updateRegistrar', + changes: { collateralAddress: cold.address, collateralKeyCommitment: cold.key_commitment, ownerAddress: sdk.sentryP2MRAddress(pqRoot, network.bech32), votingAddress: pqVotingAddress } }); + const reviewContext = async (prepared, collateral) => ({ + ...await adapter.context('regtest', proTxHash, collateral), + previousTransactions: await Promise.all([...new Set(sdk.decodeSentryTransaction(prepared.request.transactionHex).inputs.map((i) => i.txid))].map((id) => rpc('getrawtransaction', [id, false]))), + maxFeeSatoshis: '1000000', + }); + const confirm = async (row, approved) => { + const psbt = await lifecycleManagement.authorize(1, row.id, { authorization: approved }); + const signed = await rpc('walletprocesspsbt', [psbt.psbt.psbt]); + assert.equal(signed.complete, true); + const result = await lifecycleManagement.submit(1, row.id, { signedPsbt: signed.psbt }); + assert.equal(result.status, 'submitted'); + await rpc('generatetoaddress', [1, mining]); + assert.equal((await lifecycleManagement.reconcile(1, row.id)).status, 'confirmed'); + return result.txid; + }; + const rolloverContext = await reviewContext(rollover.prepared, { address: cold.address }); + const approved = await sdk.signSentryManagementOperation(rollover.prepared.request, rolloverContext, initialOwner); + const rolloverTxid = await confirm(rollover, approved); + const migrated = await rpc('protx_info', [proTxHash]); + assert.equal(migrated.collateralHash, rolloverTxid); + assert.equal(migrated.state.registeredHeight, info.state.registeredHeight); + assert.equal(migrated.state.pqOwnerCommitment, pqRoot); + assert.equal(migrated.state.legacyVotingAddress, owner); + const nextRoot = sdk.sentryP2MRRoot(genesisHash, 'owner', '67'.repeat(32)); + const update = await lifecycleManagement.prepare(1, { ...managementBody, proTxHash, operation: 'updateRegistrar', + changes: { ownerAddress: sdk.sentryP2MRAddress(nextRoot, network.bech32) } }); + const nextContext = await reviewContext(update.prepared); + const bound = sdk.bindSentryOwnerDraft(update.prepared.request, nextContext, { + pqOwnerOpening: pqOwner.publicKey, pqOwnerCommitment: nextRoot, pqOwnerDerivationNonce: '00'.repeat(32) }); + const transferTxid = await confirm(update, await sdk.signSentryManagementOperation(bound, nextContext, pqOwner)); + assert.equal((await rpc('protx_info', [proTxHash])).state.pqOwnerCommitment, nextRoot); + console.log(JSON.stringify({ result: 'passed', scope: 'disconnected legacy and PQ preparation regtest', proTxHash, createdProTxHash, + rolloverTxid, transferTxid, managementLifecycle, tamperedAddressRejection, observed, datadir }, null, 2)); } finally { database?.close(); if (indexer) await new Promise((done) => indexer.close(done)); diff --git a/tests/sentry-codec.integration.mjs b/tests/sentry-codec.integration.mjs index 031fdce..c4ef2a1 100644 --- a/tests/sentry-codec.integration.mjs +++ b/tests/sentry-codec.integration.mjs @@ -11,7 +11,7 @@ const ECPair = require('ecpair').ECPairFactory(require('@bitcoinerlab/secp256k1' const GENESIS = '12'.repeat(32); const PROTX = '23'.repeat(32); -async function fixture(era = 'legacy-v3', { preparationActive = false, enrolled = true, pqOwner = false, banned = false } = {}) { +async function fixture(era = 'legacy-v3', { preparationActive = false, enrolled = true, pqOwner = false, banned = false, feeFunds = 1000000n } = {}) { const operator = era === 'legacy-v3' ? await sdk.importSentryOperatorKey('bls-basic', '00'.repeat(31) + '01') : await sdk.deriveSentryOperatorKey('slh-dsa-shake-128s', '03'.repeat(48)); @@ -21,18 +21,22 @@ async function fixture(era = 'legacy-v3', { preparationActive = false, enrolled const payment = bitcoinjs.payments.p2wpkh({ pubkey: payer.publicKey, network }); const previous = new bitcoinjs.Transaction(); previous.addInput(Buffer.alloc(32), 0xffffffff, 0xffffffff, Buffer.from('0101', 'hex')); - previous.addOutput(payment.output, 1000000n); + previous.addOutput(payment.output, feeFunds); const collateral = bitcoinjs.Transaction.fromHex(previous.toHex()); collateral.locktime = 1; + const priorCollateral = bitcoinjs.Transaction.fromHex(collateral.toHex()); priorCollateral.locktime = 2; + const pqOwnerKey = pqOwner ? await sdk.importSentryAuthorityKey('owner', 'slh-dsa-shake-128s', + (await sdk.deriveSentryOperatorKey('slh-dsa-shake-128s', '06'.repeat(48))).secretKey) : undefined; + const ownerRoot = pqOwnerKey && sdk.sentryP2MRRoot(GENESIS, 'owner', pqOwnerKey.publicKey); const rpcCalls = []; let nevmAddress = ''; const record = { publicKey: operator.publicKey, keyVersion: 1, recordVersion: 1, profile: 1, hasGlobalKey: true, active: true, revokedHeight: -1, - childKeyCommitment: '01000100eb0010000100000064000000' + '66'.repeat(32) + '77'.repeat(32), activatedHeight: 1, genesisHash: GENESIS, + childKeyCommitment: '01000200eb0010000100000064000000' + '66'.repeat(32) + '77'.repeat(32), activatedHeight: 1, genesisHash: GENESIS, height: 10, blockHash: 'ff'.repeat(32), }; const node = { proTxHash: PROTX, operatorPublicKey: operator.publicKey, service: '1.2.3.4:18369', - nevmAddress, operatorPayoutScript: '', collateralOutpoint: { txid: '78'.repeat(32), vout: 0 }, + nevmAddress, operatorPayoutScript: '', collateralOutpoint: { txid: priorCollateral.getId(), vout: 0 }, ...(era === 'pq-v4' ? { globalKeyVersion: 1, pqRecord: { version: 1, profile: 1, keyVersion: 1, publicKey: operator.publicKey, childKeyCommitmentHex: record.childKeyCommitment, activatedHeight: 1 } } : {}), }; const rpcCall = async (method, args) => { @@ -40,30 +44,40 @@ async function fixture(era = 'legacy-v3', { preparationActive = false, enrolled if (method === 'getblockchaininfo') return { chain: 'test' }; if (method === 'getblockhash') return GENESIS; if (method === 'protx_capabilities') return { version: 1, genesisHash: GENESIS, network: 'test', era, height: 10, blockHash: 'ff'.repeat(32), requiredCollateralSatoshis: '1000000', preparationActive }; - if (method === 'protx_info') return { proTxHash: PROTX, collateralHash: node.collateralOutpoint.txid, collateralIndex: 0, state: { pubKeyOperator: operator.publicKey, ownerAddress: pqOwner ? undefined : ownerPayment.address, ...(pqOwner ? { ownerKeyType: 'slh-dsa', pqOwnerPublicKey: '55'.repeat(32), pqOwnerKeyVersion: 1, pqOwnerKeyActivationHeight: 5 } : {}), votingAddress: payment.address, payoutAddress: payment.address, PoSeBanHeight: banned ? 10 : -1, confirmedHash: '45'.repeat(32), service: node.service, nevmAddress } }; + if (method === 'protx_info') return { proTxHash: PROTX, collateralHash: node.collateralOutpoint.txid, collateralIndex: 0, state: { pubKeyOperator: operator.publicKey, ownerAddress: pqOwner ? sdk.sentryP2MRAddress(ownerRoot, network.bech32) : ownerPayment.address, + ...(pqOwner ? { ownerKeyType: 'slh-dsa', pqOwnerCommitment: ownerRoot, pqOwnerKeyVersion: 1, pqOwnerKeyActivationHeight: 5, pqOwnerDerivationNonce: '00'.repeat(32) } : {}), + votingAddress: payment.address, payoutAddress: payment.address, PoSeBanHeight: banned ? 10 : -1, confirmedHash: '45'.repeat(32), service: node.service, nevmAddress } }; if (method === 'protx_operator_key_info') { assert.deepEqual(args, [PROTX, true]); return enrolled ? record : { hasGlobalKey: false, active: false, revokedHeight: -1, genesisHash: GENESIS, height: 10, blockHash: 'ff'.repeat(32) }; } if (method === 'protx_list') return [{ proTxHash: PROTX, collateralHash: node.collateralOutpoint.txid, collateralIndex: 0 }]; - if (method === 'getrawtransaction') return args[1] === true ? { confirmations: 1 } : args[0] === collateral.getId() ? collateral.toHex() : previous.toHex(); - if (method === 'gettxout') return { confirmations: 10 }; + if (method === 'getrawtransaction') return args[1] === true ? { confirmations: 1 } : args[0] === collateral.getId() ? collateral.toHex() + : args[0] === priorCollateral.getId() ? priorCollateral.toHex() : previous.toHex(); + if (method === 'gettxout') return { confirmations: 10, scriptPubKey: { hex: Buffer.from(payment.output).toString('hex') } }; if (method === 'testmempoolaccept') return [{ allowed: true }]; if (method === 'sendrawtransaction') return bitcoinjs.Transaction.fromHex(args[0]).getId(); throw new Error(`unexpected ${method}`); }; const fundingClient = { bitcoinjs, network, networkKey: 'testnet', - async fetchUtxos() { return [{ txid: previous.getId(), vout: 0, confirmations: 1 }, { txid: node.collateralOutpoint.txid, vout: 0, confirmations: 100 }, { txid: '34'.repeat(32), vout: 0, confirmations: 1, assetInfo: {} }, { txid: '35'.repeat(32), vout: 0, confirmations: 0 }]; }, - async createTransaction(options, address, outputs, rate, xpub, unspent) { + async fetchUtxos() { return [{ txid: previous.getId(), vout: 0, confirmations: 1 }, { txid: node.collateralOutpoint.txid, vout: 0, confirmations: 100, address: payment.address, value: '1000000' }, { txid: '34'.repeat(32), vout: 0, confirmations: 1, assetInfo: {} }, { txid: '35'.repeat(32), vout: 0, confirmations: 0 }]; }, + async createTransaction(options, address, outputs, rate, xpub, unspent, forced) { assert.deepEqual(unspent.utxos, [{ txid: previous.getId(), vout: 0, confirmations: 1 }]); const psbt = new bitcoinjs.Psbt({ network }); - psbt.addInput({ hash: previous.getId(), index: 0, witnessUtxo: { script: payment.output, value: 1000000n } }); - psbt.addOutput({ script: outputs[0].script, value: 0n }); - psbt.addOutput({ address, value: 990000n }); - psbt.addUnknownKeyValToOutput(1, { key: Buffer.from('address'), value: Buffer.from(address) }); + psbt.addInput({ hash: previous.getId(), index: 0, witnessUtxo: { script: payment.output, value: feeFunds } }); + if (forced) { + assert.equal(forced.length, 1); + psbt.addInput({ hash: forced[0].txid, index: forced[0].vout, witnessUtxo: { script: payment.output, value: BigInt(forced[0].value) } }); + } + for (const output of outputs) psbt.addOutput({ script: output.script, value: BigInt(output.value.toString()) }); + const change = feeFunds - 10000n + (forced ? BigInt(forced[0].value) : 0n) - outputs.reduce((sum, o) => sum + BigInt(o.value.toString()), 0n); + if (change > 0n) { + psbt.addOutput({ address, value: change }); + psbt.addUnknownKeyValToOutput(outputs.length, { key: Buffer.from('address'), value: Buffer.from(address) }); + } return { psbt }; }, }; const adapter = createSentryAdapter({ rpcCall, network: 'testnet', genesisHash: GENESIS, sdk, fundingClient }); - return { adapter, operator, owner, ownerPayment, collateral, payer, payment, previous, node, rpcCalls, setNEVM: (value) => { nevmAddress = value; } }; + return { adapter, operator, owner, ownerPayment, ownerRoot, pqOwnerKey, collateral, priorCollateral, payer, payment, previous, node, rpcCalls, setNEVM: (value) => { nevmAddress = value; } }; } for (const era of ['legacy-v3', 'pq-v4']) test(`${era}: prepare -> operator authorization -> fee signing -> exact-byte submission and readback`, async () => { @@ -98,7 +112,55 @@ test('context keeps active PQ owners without requiring a removed legacy owner ad const f = await fixture('pq-v4', { pqOwner: true }); const context = await f.adapter.context('testnet', PROTX); assert.equal(context.node.ownerKeyId, '00'.repeat(20)); - assert.deepEqual(context.node.pqOwnerRecord, { publicKey: '55'.repeat(32), keyVersion: 1, activatedHeight: 5 }); + assert.deepEqual(context.node.pqOwnerRecord, { commitment: f.ownerRoot, keyVersion: 1, activatedHeight: 5, derivationNonce: '00'.repeat(32) }); +}); + +test('funded P2MR registration builds a signable fee PSBT with exactly the selected collateral', async () => { + const f = await fixture('pq-v4', { feeFunds: 2100000n }); + const roleAddress = (role, key) => sdk.sentryP2MRAddress(sdk.sentryP2MRRoot(GENESIS, role, key), network.bech32); + const collateralAddress = roleAddress('collateral', '37'.repeat(32)); + const prepared = await f.adapter.prepare({ network: 'testnet', operation: 'register', changes: { + service: '1.2.3.5:18369', collateralAddress, ownerAddress: roleAddress('owner', '24'.repeat(32)), + votingAddress: roleAddress('voting', '4a'.repeat(32)), payoutAddress: f.payment.address, operatorRewardBasisPoints: 0, + }, xpub: 'vpub12345678901234567890', changeAddress: f.payment.address }); + assert.equal(prepared.review.authorizations.length, 0); + const row = { network: 'testnet', prepared }; + const { psbt } = await f.adapter.authorize(row, prepared.request); + const signed = bitcoinjs.Psbt.fromBase64(psbt.psbt, { network }); + signed.signAllInputs(f.payer); signed.finalizeAllInputs(); + const validated = await f.adapter.validateSigned(row, signed.toBase64()); + assert.equal(validated.fields.collateralAddress, collateralAddress); + assert.equal(validated.fields.collateralSatoshis, '1000000'); +}); + +test('collateral rollover enforces old P2WPKH input, public target, equal principal, and wallet-bound owner opening', async () => { + const f = await fixture('pq-v4', { pqOwner: true }); + const commitment = '1345' + '32'.repeat(30); + const root = sdk.sentryCollateralRootFromCommitment(GENESIS, Buffer.from(commitment, 'hex').reverse().toString('hex')); + const collateralAddress = sdk.sentryP2MRAddress(root, network.bech32); + const current = await f.adapter.context('testnet', PROTX, { address: collateralAddress }); + assert.equal(current.node.rolloverCollateralInputScript, 'p2wpkh'); + const request = { network: 'testnet', proTxHash: PROTX, operation: 'updateRegistrar', xpub: 'vpub12345678901234567890', + changeAddress: f.payment.address, changes: { collateralAddress, collateralKeyCommitment: commitment } }; + await assert.rejects(f.adapter.prepare({ ...request, changes: { ...request.changes, collateralKeyCommitment: '51'.repeat(32) } }), /collateral_commitment_mismatch/); + const prepared = await f.adapter.prepare(request); + const details = sdk.inspectSentryOwnerDraft(prepared.request); + assert.equal(details.rollover.valueSatoshis, '1000000'); + assert.equal(details.rollover.scriptHex, '5220' + root); + assert(!prepared.request.transactionHex.includes(f.pqOwnerKey.publicKey)); + const context = { ...current, previousTransactions: [f.previous.toHex(), f.priorCollateral.toHex()], maxFeeSatoshis: '1000000' }; + const opened = sdk.bindSentryOwnerDraft(prepared.request, context, { pqOwnerOpening: f.pqOwnerKey.publicKey, + pqOwnerCommitment: sdk.sentryP2MRRoot(GENESIS, 'owner', '59'.repeat(32)), pqOwnerDerivationNonce: '07'.repeat(32) }); + const authority = await sdk.signSentryManagementOperation(opened, context, f.pqOwnerKey); + assert.equal(authority.complete, true); + const row = { network: 'testnet', protx_hash: PROTX, prepared }; + const { psbt } = await f.adapter.authorize(row, authority); + const signed = bitcoinjs.Psbt.fromBase64(psbt.psbt, { network }); + signed.signAllInputs(f.payer); signed.finalizeAllInputs(); + const valid = await f.adapter.validateSigned(row, signed.toBase64()); + assert.equal(valid.fields.collateralAddress, collateralAddress); + await f.adapter.validateStored({ ...row, signed_hex: valid.transactionHex, txid: valid.txid }); + await assert.rejects(f.adapter.validateStored({ ...row, protx_hash: '19'.repeat(32), signed_hex: valid.transactionHex, txid: valid.txid }), /registered_collateral_spend/); }); test('banned nodes may restore service but cannot change their NEVM address', async () => { @@ -114,7 +176,7 @@ test('operator preparation requires owner and new operator proof before fee PSBT const f = await fixture('legacy-v3', { preparationActive: true, enrolled: false }); const candidate = await sdk.deriveSentryOperatorKey('slh-dsa-shake-128s', '04'.repeat(48)); const prepared = await f.adapter.prepare({ operation: 'registerOperator', network: 'testnet', proTxHash: PROTX, - changes: { operatorPublicKey: candidate.publicKey, childKeyCommitment: '01000100eb0010000100000064000000' + '66'.repeat(32) + '77'.repeat(32), keyVersion: 1 }, + changes: { operatorPublicKey: candidate.publicKey, childKeyCommitment: '01000200eb0010000100000064000000' + '66'.repeat(32) + '77'.repeat(32), keyVersion: 1 }, xpub: 'vpub12345678901234567890', changeAddress: f.payment.address }); const context = { ...await f.adapter.context('testnet', PROTX), previousTransactions: [f.previous.toHex()], maxFeeSatoshis: '1000000' }; const row = { network: 'testnet', protx_hash: PROTX, prepared }; From c0fb8625bf2c5880c4e834d4171ae51218329397 Mon Sep 17 00:00:00 2001 From: jagdeep sidhu Date: Wed, 2 Dec 2026 08:26:21 -0700 Subject: [PATCH 02/18] Gate new P2MR reward addresses on Core preparation --- lib/sentryAdapter.js | 25 ++++++++++--- tests/sentry-codec.integration.mjs | 58 ++++++++++++++++++++++++++++-- 2 files changed, 76 insertions(+), 7 deletions(-) diff --git a/lib/sentryAdapter.js b/lib/sentryAdapter.js index f085d7b..df2e1e9 100644 --- a/lib/sentryAdapter.js +++ b/lib/sentryAdapter.js @@ -42,6 +42,18 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient script(address) !== '5220' + root) throw failure('invalid_authority_address'); return root; }; + function p2mrPayee(review) { + const operator = review.operation === 'updateService'; + const output = operator ? review.changes.operatorPayoutScript.next + : review.fields?.payoutAddress ? script(review.fields.payoutAddress) : ''; + return /^5220[0-9a-f]{64}$/.test(output) + ? { field: operator ? 'operatorPayoutScript' : 'payoutScript', output } : null; + } + function checkPayeeActivation(review, current) { + if (current.p2mrActive) return; + const payee = p2mrPayee(review); + if (payee && payee.output !== current.node?.[payee.field]) throw failure('p2mr_payout_inactive', 409); + } const keyId = (address) => { const value = script(address); if (/^0014[0-9a-f]{40}$/.test(value)) return value.slice(4); @@ -140,13 +152,14 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient } async function context(requested, proTxHash, collateral) { const { chain, capabilities } = await assertNetwork(requested); + const p2mrActive = capabilities.preparationActive === true; if (collateral && !proTxHash) { if (!/^[1-9][0-9]*$/.test(capabilities.requiredCollateralSatoshis || '')) throw failure('core_sentry_capabilities_required', 503); if (!Number.isSafeInteger(collateral.vout) || collateral.vout < 0 || collateral.vout > 0xffffffff) throw failure('invalid_collateral'); if (collateral.address) { const approvedCollateralScript = script(collateral.address); if (collateral.txid || chain.era !== 'pq-v4' || !/^5220[0-9a-f]{64}$/.test(approvedCollateralScript)) throw failure('invalid_collateral'); - return { chain, network: networkEncoding, approvedCollateralScript, registration: { + return { chain, network: networkEncoding, p2mrActive, approvedCollateralScript, registration: { collateralVout: collateral.vout, requiredCollateralSatoshis: capabilities.requiredCollateralSatoshis } }; } if (!/^[a-f0-9]{64}$/.test(collateral.txid || '')) throw failure('invalid_collateral'); @@ -157,7 +170,7 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient const registrations = await call('protx_list', ['registered', true]); if (!Array.isArray(registrations)) throw failure('node_list_unavailable', 503); if (registrations.some((entry) => entry.collateralHash === collateral.txid && entry.collateralIndex === collateral.vout)) throw failure('collateral_already_registered', 409); - return { chain, network: networkEncoding, registration: { collateralTransactionHex, + return { chain, network: networkEncoding, p2mrActive, registration: { collateralTransactionHex, collateralVout: collateral.vout, requiredCollateralSatoshis: capabilities.requiredCollateralSatoshis } }; } const raw = await call('protx_info', [proTxHash]); @@ -226,7 +239,7 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient approvedCollateralScript = script(collateral.address); if (!/^5220[0-9a-f]{64}$/.test(approvedCollateralScript)) throw failure('invalid_collateral'); } - return { chain, node, network: networkEncoding, ...(approvedCollateralScript ? { approvedCollateralScript } : {}), + return { chain, node, network: networkEncoding, p2mrActive, ...(approvedCollateralScript ? { approvedCollateralScript } : {}), allowOperatorPreparation: capabilities.preparationActive === true, allowOwnerPreparation: capabilities.preparationActive === true }; } @@ -267,6 +280,7 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient const request = { ...row.prepared.request, transactionHex }; const reviewContext = { ...current, previousTransactions, maxFeeSatoshis }; const review = isService ? sdk.reviewSentryOperation(request, reviewContext) : sdk.reviewSentryManagementOperation(request, reviewContext); + checkPayeeActivation(review, current); if (isService && review.authorizationHash !== row.prepared.review.authorizationHash) throw failure('operation_changed', 409); if (!isService && !sdk.matchesSentryManagementIntent(row.prepared.request, request)) throw failure('operation_changed', 409); const expected = sdk.decodeSentryTransaction(row.prepared.request.transactionHex); @@ -426,6 +440,7 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient const review = operation === 'updateService' ? sdk.reviewSentryOperation(request, reviewContext) : sdk.isSentryOwnerDraft(request) ? sdk.reviewSentryOwnerDraft(request, reviewContext) : sdk.reviewSentryManagementOperation(request, reviewContext); + checkPayeeActivation(review, current); return { request, review, fundingPsbt, anchor: { chain: current.chain, ...(current.node ? { node: current.node } : {}), ...(current.registration ? { registration: current.registration } : {}), ...(current.approvedCollateralScript ? { approvedCollateralScript: current.approvedCollateralScript } : {}) }, @@ -448,8 +463,10 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient return { transactionHex: tx.toHex(), txid: tx.getId(), fields }; }, async validateStored(row) { - await assertNetwork(row.network); + const { capabilities } = await assertNetwork(row.network); if (typeof row.signed_hex !== 'string' || row.signed_hex.length > 400000 || decode(row.signed_hex).getId() !== row.txid) throw failure('stored_transaction_invalid', 409); + // A reorg can put a previously signed reward update back before preparation. + if (capabilities.preparationActive !== true && p2mrPayee(row.prepared.review)) await liveReview(row, row.signed_hex); await checkReservedInputs(decode(row.signed_hex), row); const accepted = await call('testmempoolaccept', [[row.signed_hex]]); if (!Array.isArray(accepted) || accepted.length !== 1 || !accepted[0].allowed) throw failure('transaction_rejected', 422); diff --git a/tests/sentry-codec.integration.mjs b/tests/sentry-codec.integration.mjs index c4ef2a1..56d63c5 100644 --- a/tests/sentry-codec.integration.mjs +++ b/tests/sentry-codec.integration.mjs @@ -28,6 +28,7 @@ async function fixture(era = 'legacy-v3', { preparationActive = false, enrolled (await sdk.deriveSentryOperatorKey('slh-dsa-shake-128s', '06'.repeat(48))).secretKey) : undefined; const ownerRoot = pqOwnerKey && sdk.sentryP2MRRoot(GENESIS, 'owner', pqOwnerKey.publicKey); const rpcCalls = []; + const deployment = { preparationActive }; let nevmAddress = ''; const record = { publicKey: operator.publicKey, keyVersion: 1, recordVersion: 1, profile: 1, @@ -36,6 +37,7 @@ async function fixture(era = 'legacy-v3', { preparationActive = false, enrolled height: 10, blockHash: 'ff'.repeat(32), }; const node = { proTxHash: PROTX, operatorPublicKey: operator.publicKey, service: '1.2.3.4:18369', + payoutAddress: payment.address, operatorPayoutAddress: '', nevmAddress, operatorPayoutScript: '', collateralOutpoint: { txid: priorCollateral.getId(), vout: 0 }, ...(era === 'pq-v4' ? { globalKeyVersion: 1, pqRecord: { version: 1, profile: 1, keyVersion: 1, publicKey: operator.publicKey, childKeyCommitmentHex: record.childKeyCommitment, activatedHeight: 1 } } : {}), }; @@ -43,10 +45,11 @@ async function fixture(era = 'legacy-v3', { preparationActive = false, enrolled rpcCalls.push({ method, args }); if (method === 'getblockchaininfo') return { chain: 'test' }; if (method === 'getblockhash') return GENESIS; - if (method === 'protx_capabilities') return { version: 1, genesisHash: GENESIS, network: 'test', era, height: 10, blockHash: 'ff'.repeat(32), requiredCollateralSatoshis: '1000000', preparationActive }; + if (method === 'protx_capabilities') return { version: 1, genesisHash: GENESIS, network: 'test', era, height: 10, blockHash: 'ff'.repeat(32), requiredCollateralSatoshis: '1000000', ...deployment }; if (method === 'protx_info') return { proTxHash: PROTX, collateralHash: node.collateralOutpoint.txid, collateralIndex: 0, state: { pubKeyOperator: operator.publicKey, ownerAddress: pqOwner ? sdk.sentryP2MRAddress(ownerRoot, network.bech32) : ownerPayment.address, ...(pqOwner ? { ownerKeyType: 'slh-dsa', pqOwnerCommitment: ownerRoot, pqOwnerKeyVersion: 1, pqOwnerKeyActivationHeight: 5, pqOwnerDerivationNonce: '00'.repeat(32) } : {}), - votingAddress: payment.address, payoutAddress: payment.address, PoSeBanHeight: banned ? 10 : -1, confirmedHash: '45'.repeat(32), service: node.service, nevmAddress } }; + votingAddress: payment.address, payoutAddress: node.payoutAddress, operatorPayoutAddress: node.operatorPayoutAddress, + PoSeBanHeight: banned ? 10 : -1, confirmedHash: '45'.repeat(32), service: node.service, nevmAddress } }; if (method === 'protx_operator_key_info') { assert.deepEqual(args, [PROTX, true]); return enrolled ? record : { hasGlobalKey: false, active: false, revokedHeight: -1, genesisHash: GENESIS, height: 10, blockHash: 'ff'.repeat(32) }; } if (method === 'protx_list') return [{ proTxHash: PROTX, collateralHash: node.collateralOutpoint.txid, collateralIndex: 0 }]; if (method === 'getrawtransaction') return args[1] === true ? { confirmations: 1 } : args[0] === collateral.getId() ? collateral.toHex() @@ -77,9 +80,58 @@ async function fixture(era = 'legacy-v3', { preparationActive = false, enrolled }, }; const adapter = createSentryAdapter({ rpcCall, network: 'testnet', genesisHash: GENESIS, sdk, fundingClient }); - return { adapter, operator, owner, ownerPayment, ownerRoot, pqOwnerKey, collateral, priorCollateral, payer, payment, previous, node, rpcCalls, setNEVM: (value) => { nevmAddress = value; } }; + return { adapter, operator, owner, ownerPayment, ownerRoot, pqOwnerKey, collateral, priorCollateral, payer, payment, previous, node, deployment, rpcCalls, setNEVM: (value) => { nevmAddress = value; } }; } +test('a new P2MR reward address requires preparation for registration, registrar and service updates', async () => { + const f = await fixture(); + const payoutAddress = sdk.sentryP2MRAddress('ab'.repeat(32), network.bech32); + const base = { network: 'testnet', xpub: 'vpub12345678901234567890', changeAddress: f.payment.address }; + const requests = [ + { ...base, operation: 'register', collateralOutpoint: { txid: f.collateral.getId(), vout: 0 }, + changes: { service: f.node.service, ownerAddress: f.ownerPayment.address, votingAddress: f.ownerPayment.address, + operatorPublicKey: f.operator.publicKey, payoutAddress, operatorRewardBasisPoints: 0 } }, + { ...base, operation: 'updateRegistrar', proTxHash: PROTX, changes: { payoutAddress } }, + { ...base, operation: 'updateService', proTxHash: PROTX, changes: { operatorPayoutAddress: payoutAddress } }, + ]; + for (const request of requests) await assert.rejects(f.adapter.prepare(request), /p2mr_payout_inactive/); + f.node.payoutAddress = f.node.operatorPayoutAddress = payoutAddress; + await f.adapter.prepare(requests[1]); + const preserved = await f.adapter.prepare({ ...requests[2], changes: { service: '1.2.3.5:18369' } }); + assert.equal(preserved.review.changes.operatorPayoutScript.next, '5220' + 'ab'.repeat(32)); + f.node.payoutAddress = f.payment.address; + f.node.operatorPayoutAddress = ''; + f.deployment.preparationActive = true; + for (const request of requests) await f.adapter.prepare(request); + const pq = await fixture('pq-v4'); + await assert.rejects(pq.adapter.prepare(requests[2]), /p2mr_payout_inactive/); + pq.deployment.preparationActive = true; + await pq.adapter.prepare(requests[2]); +}); + +test('a preparation rollback rechecks the embedded payee during authorization, submission and retry', async () => { + const f = await fixture('legacy-v3', { preparationActive: true }); + const payoutAddress = sdk.sentryP2MRAddress('ab'.repeat(32), network.bech32); + const collateralOutpoint = { txid: f.collateral.getId(), vout: 0 }; + const prepared = await f.adapter.prepare({ operation: 'register', network: 'testnet', collateralOutpoint, + changes: { service: f.node.service, ownerAddress: f.ownerPayment.address, votingAddress: f.ownerPayment.address, + operatorPublicKey: f.operator.publicKey, payoutAddress, operatorRewardBasisPoints: 0 }, + xpub: 'vpub12345678901234567890', changeAddress: f.payment.address }); + const context = { ...await f.adapter.context('testnet', undefined, collateralOutpoint), + previousTransactions: [f.previous.toHex()], maxFeeSatoshis: '1000000' }; + const collateralKey = await sdk.importSentryAuthorityKey('collateral', 'secp256k1', '01'.repeat(32)); + const authorization = await sdk.signSentryManagementOperation(prepared.request, context, collateralKey); + const row = { network: 'testnet', protx_hash: collateralOutpoint.txid, prepared }; + const authorized = await f.adapter.authorize(row, authorization); + const psbt = bitcoinjs.Psbt.fromBase64(authorized.psbt.psbt, { network }); + psbt.signAllInputs(f.payer); psbt.finalizeAllInputs(); + const submitted = await f.adapter.validateSigned(row, psbt.toBase64()); + f.deployment.preparationActive = false; + await assert.rejects(f.adapter.authorize(row, authorization), /p2mr_payout_inactive/); + await assert.rejects(f.adapter.validateSigned(row, psbt.toBase64()), /p2mr_payout_inactive/); + await assert.rejects(f.adapter.validateStored({ ...row, signed_hex: submitted.transactionHex, txid: submitted.txid }), /p2mr_payout_inactive/); +}); + for (const era of ['legacy-v3', 'pq-v4']) test(`${era}: prepare -> operator authorization -> fee signing -> exact-byte submission and readback`, async () => { const f = await fixture(era); const prepared = await f.adapter.prepare({ network: 'testnet', proTxHash: PROTX, From 5866a77cff2f052e40d713f42de12afe15f2a5f8 Mon Sep 17 00:00:00 2001 From: jagdeep sidhu Date: Wed, 2 Dec 2026 08:39:35 -0700 Subject: [PATCH 03/18] Gate Sentry updates and funding votes on confirmed owner enrollment --- lib/sentryAdapter.js | 11 ++++++++++- lib/sentryVotingContext.test.js | 15 ++++++++++++--- package-lock.json | 2 +- tests/sentry-codec.integration.mjs | 18 +++++++++++++++++- 4 files changed, 40 insertions(+), 6 deletions(-) diff --git a/lib/sentryAdapter.js b/lib/sentryAdapter.js index df2e1e9..4ed9efe 100644 --- a/lib/sentryAdapter.js +++ b/lib/sentryAdapter.js @@ -132,12 +132,19 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient if (!Number.isSafeInteger(registration?.confirmations) || registration.confirmations <= 0) throw failure('node_not_confirmed', 409); const identity = { proTxHash, collateralOutpoint: { txid: node.collateralHash, vout: node.collateralIndex }, valid: true }; if (pq) { + const ownerEnrolledHeight = state.pqOwnerKeyEnrollmentHeight; + if (state.ownerKeyType !== 'slh-dsa' || !Number.isInteger(state.pqOwnerKeyVersion) || + state.pqOwnerKeyVersion < 1 || state.pqOwnerKeyVersion > 0xffffffff || + !Number.isSafeInteger(ownerEnrolledHeight) || ownerEnrolledHeight < 0 || ownerEnrolledHeight > signingBlock.height || + !Number.isSafeInteger(state.pqOwnerKeyActivationHeight) || state.pqOwnerKeyActivationHeight < ownerEnrolledHeight || + state.pqOwnerKeyActivationHeight > height) throw failure('owner_not_enrolled_at_signing_block', 409); + registeredRoot(state.ownerAddress, state.pqOwnerCommitment); const votingKeyVersion = state.pqVotingKeyVersion; const votingKeyActivatedHeight = state.pqVotingKeyActivationHeight; if (!Number.isSafeInteger(votingKeyVersion) || votingKeyVersion < 1 || votingKeyVersion > 0xffffffff || !Number.isSafeInteger(votingKeyActivatedHeight) || votingKeyActivatedHeight < 0 || votingKeyActivatedHeight > signingBlock.height) throw failure('voting_key_not_active_at_signing_block', 409); - nodes[index] = { ...identity, votingKeyId: registeredRoot(state.votingAddress, state.pqVotingCommitment), votingKeyVersion, votingKeyActivatedHeight }; + nodes[index] = { ...identity, votingKeyId: registeredRoot(state.votingAddress, state.pqVotingCommitment), votingKeyVersion, votingKeyActivatedHeight, ownerEnrolledHeight }; } else { nodes[index] = { ...identity, votingKeyId: keyId(state.legacyVotingAddress ?? state.votingAddress) }; } @@ -325,6 +332,8 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient const collateral = fundedAddress ? { address: fundedAddress, vout: 0 } : body.collateralOutpoint; const current = operation === 'register' ? await context(body.network, undefined, collateral) : await context(body.network, body.proTxHash, rolloverAddress ? { address: rolloverAddress } : undefined); + if (current.chain.era === 'pq-v4' && current.node && !current.node.pqOwnerRecord && + (operation !== 'updateRegistrar' || !body.changes.ownerAddress)) throw failure('owner_enrollment_required', 409); _internal.assertXpubMatchesNetwork(body.xpub, network); _internal.assertChangeAddress(bitcoinjs, body.changeAddress, fundingClient.network, network); const feeRate = _internal.normalizeFeeRate(body.feeRate); diff --git a/lib/sentryVotingContext.test.js b/lib/sentryVotingContext.test.js index de91631..b243921 100644 --- a/lib/sentryVotingContext.test.js +++ b/lib/sentryVotingContext.test.js @@ -79,11 +79,20 @@ test('a PQ vote uses the same active ancestor after a tip extension and refuses const f = fixture(); const root = '16'.repeat(32); Object.assign(f.capabilities, { era: 'pq-v4', activationHeight: 70 }); - Object.assign(f.node.state, { pqVotingCommitment: root, pqVotingKeyVersion: 2, pqVotingKeyActivationHeight: 90, PoSeBanHeight: -1 }); - f.fundingClient.bitcoinjs.address.toOutputScript.mockReturnValue(Buffer.from('5220' + root, 'hex')); + const owner = '27'.repeat(32); + Object.assign(f.node.state, { ownerKeyType: 'slh-dsa', ownerAddress: 'current-owner-address', pqOwnerCommitment: owner, + pqOwnerKeyVersion: 2, pqOwnerKeyEnrollmentHeight: 75, pqOwnerKeyActivationHeight: 99, + pqVotingCommitment: root, pqVotingKeyVersion: 2, pqVotingKeyActivationHeight: 90, PoSeBanHeight: -1 }); + f.fundingClient.bitcoinjs.address.toOutputScript.mockImplementation((address) => + Buffer.from('5220' + (address === 'current-owner-address' ? owner : root), 'hex')); const first = await f.adapter.votingContext('testnet', PROPOSAL, [PROTX]); expect(first.signingBlock).toEqual({ height: 94, hash: BLOCK }); - expect(first.nodes[0]).toMatchObject({ votingKeyId: root, votingKeyVersion: 2, votingKeyActivatedHeight: 90 }); + expect(first.nodes[0]).toMatchObject({ votingKeyId: root, votingKeyVersion: 2, votingKeyActivatedHeight: 90, ownerEnrolledHeight: 75 }); + for (const enrollment of [undefined, 95]) { + f.node.state.pqOwnerKeyEnrollmentHeight = enrollment; + await expect(f.adapter.votingContext('testnet', PROPOSAL, [PROTX])).rejects.toMatchObject({ code: 'owner_not_enrolled_at_signing_block' }); + } + f.node.state.pqOwnerKeyEnrollmentHeight = 75; f.capabilities.height++; expect((await f.adapter.votingContext('testnet', PROPOSAL, [PROTX], first.signingBlock)).signingBlock).toEqual(first.signingBlock); await expect(f.adapter.votingContext('testnet', PROPOSAL, [PROTX], { height: 94, hash: COLLATERAL })).rejects.toMatchObject({ code: 'signing_block_unavailable' }); diff --git a/package-lock.json b/package-lock.json index 694aa81..8211e56 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1808,7 +1808,7 @@ "node_modules/@sidhujag/sysweb3-sentry": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/@sidhujag/sysweb3-sentry/-/sysweb3-sentry-0.1.4.tgz", - "integrity": "sha512-IshrnCoepii6dafUkXgMOdNUkv/kyuET5Ghg0JIbQtZkB0gaoy7EbXwXLpHWo8EjP4JXHB3/q+RFTs7eBwR9hQ==", + "integrity": "sha512-tuwK9ruxc/DV9wjPSUksxsdvD+7OO1rRy0R+L+3Z6jeRY04Ng9DXZs4Nt11MbY1m+v00+rhQ9ppI4TyRWle/tw==", "license": "MIT", "dependencies": { "@noble/curves": "2.4.0", diff --git a/tests/sentry-codec.integration.mjs b/tests/sentry-codec.integration.mjs index 56d63c5..dcb02c8 100644 --- a/tests/sentry-codec.integration.mjs +++ b/tests/sentry-codec.integration.mjs @@ -11,7 +11,7 @@ const ECPair = require('ecpair').ECPairFactory(require('@bitcoinerlab/secp256k1' const GENESIS = '12'.repeat(32); const PROTX = '23'.repeat(32); -async function fixture(era = 'legacy-v3', { preparationActive = false, enrolled = true, pqOwner = false, banned = false, feeFunds = 1000000n } = {}) { +async function fixture(era = 'legacy-v3', { preparationActive = false, enrolled = true, pqOwner = era === 'pq-v4', banned = false, feeFunds = 1000000n } = {}) { const operator = era === 'legacy-v3' ? await sdk.importSentryOperatorKey('bls-basic', '00'.repeat(31) + '01') : await sdk.deriveSentryOperatorKey('slh-dsa-shake-128s', '03'.repeat(48)); @@ -39,6 +39,7 @@ async function fixture(era = 'legacy-v3', { preparationActive = false, enrolled const node = { proTxHash: PROTX, operatorPublicKey: operator.publicKey, service: '1.2.3.4:18369', payoutAddress: payment.address, operatorPayoutAddress: '', nevmAddress, operatorPayoutScript: '', collateralOutpoint: { txid: priorCollateral.getId(), vout: 0 }, + ...(pqOwner ? { pqOwnerRecord: { commitment: ownerRoot, keyVersion: 1, activatedHeight: 5, derivationNonce: '00'.repeat(32) } } : {}), ...(era === 'pq-v4' ? { globalKeyVersion: 1, pqRecord: { version: 1, profile: 1, keyVersion: 1, publicKey: operator.publicKey, childKeyCommitmentHex: record.childKeyCommitment, activatedHeight: 1 } } : {}), }; const rpcCall = async (method, args) => { @@ -167,6 +168,21 @@ test('context keeps active PQ owners without requiring a removed legacy owner ad assert.deepEqual(context.node.pqOwnerRecord, { commitment: f.ownerRoot, keyVersion: 1, activatedHeight: 5, derivationNonce: '00'.repeat(32) }); }); +test('after activation the existing ECDSA owner can enroll the first P2MR owner and must preserve payout', async () => { + const f = await fixture('pq-v4', { pqOwner: false }); + const base = { network: 'testnet', proTxHash: PROTX, xpub: 'vpub12345678901234567890', changeAddress: f.payment.address }; + const ownerAddress = sdk.sentryP2MRAddress('cb'.repeat(32), network.bech32); + for (const operation of ['updateRegistrar', 'updateService', 'registerOperator', 'rotateOperator', 'revoke']) { + await assert.rejects(f.adapter.prepare({ ...base, operation, changes: {} }), /owner_enrollment_required/); + } + await assert.rejects(f.adapter.prepare({ ...base, operation: 'updateRegistrar', + changes: { ownerAddress, payoutAddress: f.ownerPayment.address } }), { code: 'INVALID_OWNER_ENROLLMENT' }); + const prepared = await f.adapter.prepare({ ...base, operation: 'updateRegistrar', changes: { ownerAddress } }); + const context = { ...await f.adapter.context('testnet', PROTX), previousTransactions: [f.previous.toHex()], maxFeeSatoshis: '1000000' }; + const signed = await sdk.signSentryManagementOperation(prepared.request, context, f.owner); + await f.adapter.authorize({ network: 'testnet', protx_hash: PROTX, prepared }, signed); +}); + test('funded P2MR registration builds a signable fee PSBT with exactly the selected collateral', async () => { const f = await fixture('pq-v4', { feeFunds: 2100000n }); const roleAddress = (role, key) => sdk.sentryP2MRAddress(sdk.sentryP2MRRoot(GENESIS, role, key), network.bech32); From f0c767edc81cb04334e4d021f8c3b5b014f5100d Mon Sep 17 00:00:00 2001 From: jagdeep sidhu Date: Wed, 2 Dec 2026 08:56:23 -0700 Subject: [PATCH 04/18] Verify registered collateral before Sentry approvals and recheck activation on retries --- README.md | 6 ++- lib/appFactory.js | 2 +- lib/sentryAdapter.js | 54 ++++++++++++++++----------- lib/sentryManagement.js | 6 +++ middleware/rateLimit.js | 11 +++--- package-lock.json | 2 +- routes/sentry.js | 11 ++++-- scripts/sentry-core-regtest.mjs | 13 ++++--- tests/sentry-codec.integration.mjs | 59 +++++++++++++++++++++++------- tests/sentry.routes.test.js | 17 +++++++++ 10 files changed, 129 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 5938cac..60cbb67 100644 --- a/README.md +++ b/README.md @@ -415,7 +415,11 @@ enabling management: historical registration and transaction readback use treated as transaction absence and do not demote confirmed operation records. `GET /capabilities` and `GET /context` are rate-limited public chain reads for -wallets. All node-watch and operation endpoints require a verified session; +wallets. For a large historical collateral transaction, wallets can request +`GET /collateral-transaction?network=&proTxHash=`. +Core selects the node's registered collateral outpoint. The response contains its +verified witness-stripped transaction in `hex` and shares the governance batch read limit. +All node-watch and operation endpoints require a verified session; writes also require the configured exact Origin and the existing CSRF token. The public API remains `/api/sentry/v1/`, including Pali's default `https://sysnode.info/api/sentry/v1/context`. The proxy example forwards that diff --git a/lib/appFactory.js b/lib/appFactory.js index 773ea65..ed6914a 100644 --- a/lib/appFactory.js +++ b/lib/appFactory.js @@ -253,7 +253,7 @@ function mountAuthAndVault( csrfMw: services.csrfMw, limiter: disableRateLimit ? rateLimiters.disabled() : rateLimiters.sentryManagementLimiter(), readLimiter: disableRateLimit ? rateLimiters.disabled() : rateLimiters.sentryReadLimiter(), - votingContextLimiter: disableRateLimit ? rateLimiters.disabled() : rateLimiters.sentryVotingContextLimiter(), + heavyReadLimiter: disableRateLimit ? rateLimiters.disabled() : rateLimiters.sentryHeavyReadLimiter(), frontendUrl, })); diff --git a/lib/sentryAdapter.js b/lib/sentryAdapter.js index 4ed9efe..39bcd4b 100644 --- a/lib/sentryAdapter.js +++ b/lib/sentryAdapter.js @@ -42,18 +42,6 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient script(address) !== '5220' + root) throw failure('invalid_authority_address'); return root; }; - function p2mrPayee(review) { - const operator = review.operation === 'updateService'; - const output = operator ? review.changes.operatorPayoutScript.next - : review.fields?.payoutAddress ? script(review.fields.payoutAddress) : ''; - return /^5220[0-9a-f]{64}$/.test(output) - ? { field: operator ? 'operatorPayoutScript' : 'payoutScript', output } : null; - } - function checkPayeeActivation(review, current) { - if (current.p2mrActive) return; - const payee = p2mrPayee(review); - if (payee && payee.output !== current.node?.[payee.field]) throw failure('p2mr_payout_inactive', 409); - } const keyId = (address) => { const value = script(address); if (/^0014[0-9a-f]{40}$/.test(value)) return value.slice(4); @@ -166,7 +154,7 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient if (collateral.address) { const approvedCollateralScript = script(collateral.address); if (collateral.txid || chain.era !== 'pq-v4' || !/^5220[0-9a-f]{64}$/.test(approvedCollateralScript)) throw failure('invalid_collateral'); - return { chain, network: networkEncoding, p2mrActive, approvedCollateralScript, registration: { + return { chain, network: networkEncoding, p2mrActive, allowOwnerPreparation: p2mrActive, approvedCollateralScript, registration: { collateralVout: collateral.vout, requiredCollateralSatoshis: capabilities.requiredCollateralSatoshis } }; } if (!/^[a-f0-9]{64}$/.test(collateral.txid || '')) throw failure('invalid_collateral'); @@ -177,7 +165,7 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient const registrations = await call('protx_list', ['registered', true]); if (!Array.isArray(registrations)) throw failure('node_list_unavailable', 503); if (registrations.some((entry) => entry.collateralHash === collateral.txid && entry.collateralIndex === collateral.vout)) throw failure('collateral_already_registered', 409); - return { chain, network: networkEncoding, p2mrActive, registration: { collateralTransactionHex, + return { chain, network: networkEncoding, p2mrActive, allowOwnerPreparation: p2mrActive, registration: { collateralTransactionHex, collateralVout: collateral.vout, requiredCollateralSatoshis: capabilities.requiredCollateralSatoshis } }; } const raw = await call('protx_info', [proTxHash]); @@ -255,6 +243,31 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient if (!ids.length || ids.length > 32) throw failure('funding_input_limit'); return Promise.all(ids.map((id) => call('getrawtransaction', [id, false]))); } + async function collateralTransaction(requested, proTxHash) { + const metadata = { timeout: 10_000, maxContentLength: 64 * 1024 }; + await assertNetwork(requested, metadata); + const node = await call('protx_info', [proTxHash], metadata); + if (node?.proTxHash !== proTxHash || !node.state) throw failure('node_not_found', 404); + if (typeof node.collateralHash !== 'string' || !/^[0-9a-f]{64}$/.test(node.collateralHash) || + !Number.isSafeInteger(node.collateralIndex) || node.collateralIndex < 0 || node.collateralIndex > 0xffffffff) + throw failure('invalid_collateral', 503); + const outpoint = { txid: node.collateralHash, vout: node.collateralIndex }; + // The largest Core transaction fits in 4 MB of bytes plus the JSON-RPC envelope in hex. + const raw = await call('getrawtransaction', [outpoint.txid, false], { timeout: 10_000, maxContentLength: 8_001_024 }); + const hex = sdk.stripSentryCollateralWitness(raw, outpoint); + if (hex.length > 2_000_000) throw failure('collateral_transaction_too_large', 503); + return { hex }; + } + async function signingContext(request, current, previousTransactions) { + const result = { ...current, previousTransactions, maxFeeSatoshis }; + if (request.operation === 'updateService') return result; + const inspection = sdk.isSentryOwnerDraft(request) + ? sdk.inspectSentryOwnerDraft(request) : sdk.inspectSentryManagementOperation(request); + // A rollover already supplies the registered collateral as a verified input. + if (inspection.requiresRegisteredCollateral && !inspection.rollover) + result.registeredCollateralTransactionHex = await call('getrawtransaction', [current.node.collateralOutpoint.txid, false]); + return result; + } const decode = (hex) => bitcoinjs.Transaction.fromHex(hex); function psbtFor(tx, fundingPsbt) { const original = bitcoinjs.Psbt.fromBase64(fundingPsbt, { network: fundingClient.network }); @@ -285,9 +298,8 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient const tx = decode(transactionHex); const previousTransactions = await priorTransactions(tx); const request = { ...row.prepared.request, transactionHex }; - const reviewContext = { ...current, previousTransactions, maxFeeSatoshis }; + const reviewContext = await signingContext(request, current, previousTransactions); const review = isService ? sdk.reviewSentryOperation(request, reviewContext) : sdk.reviewSentryManagementOperation(request, reviewContext); - checkPayeeActivation(review, current); if (isService && review.authorizationHash !== row.prepared.review.authorizationHash) throw failure('operation_changed', 409); if (!isService && !sdk.matchesSentryManagementIntent(row.prepared.request, request)) throw failure('operation_changed', 409); const expected = sdk.decodeSentryTransaction(row.prepared.request.transactionHex); @@ -315,6 +327,7 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient } return { votingContext, + collateralTransaction, async capabilities() { const { chain, capabilities } = await assertNetwork(network); const management = sdk.getSentryManagementCapabilities(); @@ -445,12 +458,11 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient lockTime: unsigned.locktime, }); const previousTransactions = await priorTransactions(decode(request.transactionHex)); - const reviewContext = { ...current, previousTransactions, maxFeeSatoshis }; + const reviewContext = await signingContext(request, current, previousTransactions); const review = operation === 'updateService' ? sdk.reviewSentryOperation(request, reviewContext) : sdk.isSentryOwnerDraft(request) ? sdk.reviewSentryOwnerDraft(request, reviewContext) : sdk.reviewSentryManagementOperation(request, reviewContext); - checkPayeeActivation(review, current); - return { request, review, fundingPsbt, + return { request, review, fundingPsbt, p2mrActive: current.p2mrActive, anchor: { chain: current.chain, ...(current.node ? { node: current.node } : {}), ...(current.registration ? { registration: current.registration } : {}), ...(current.approvedCollateralScript ? { approvedCollateralScript: current.approvedCollateralScript } : {}) }, ...(collateral ? { collateralOutpoint: collateral } : {}), ...(rolloverAddress ? { rolloverAddress } : {}) }; @@ -474,8 +486,8 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient async validateStored(row) { const { capabilities } = await assertNetwork(row.network); if (typeof row.signed_hex !== 'string' || row.signed_hex.length > 400000 || decode(row.signed_hex).getId() !== row.txid) throw failure('stored_transaction_invalid', 409); - // A reorg can put a previously signed reward update back before preparation. - if (capabilities.preparationActive !== true && p2mrPayee(row.prepared.review)) await liveReview(row, row.signed_hex); + // Recheck payout and funding rules when a reorg crosses the preparation boundary. + if (capabilities.preparationActive !== true && row.prepared.p2mrActive) await liveReview(row, row.signed_hex); await checkReservedInputs(decode(row.signed_hex), row); const accepted = await call('testmempoolaccept', [[row.signed_hex]]); if (!Array.isArray(accepted) || accepted.length !== 1 || !accepted[0].allowed) throw failure('transaction_rejected', 422); diff --git a/lib/sentryManagement.js b/lib/sentryManagement.js index c3dbae8..b8e965f 100644 --- a/lib/sentryManagement.js +++ b/lib/sentryManagement.js @@ -90,6 +90,12 @@ function createSentryManagement({ repository, adapter, now = Date.now }) { if (proTxHash && collateral && (!collateral.address || collateral.txid)) throw failure('invalid_collateral'); return configured().context(network, proTxHash, collateral); }, + collateralTransaction: async (query) => { + strictObject(query, ['network', 'proTxHash']); + if (typeof query.proTxHash !== 'string' || /^0+$/.test(query.proTxHash)) throw failure('invalid_node_identity'); + const { network, proTxHash } = nodeIdentity(query.network, query.proTxHash); + return configured().collateralTransaction(network, proTxHash); + }, votingContext: async (query) => { strictObject(query, ['network', 'proposalHash', 'proTxHashes', 'signingHeight', 'signingBlockHash']); if (typeof query.proposalHash !== 'string') throw failure('invalid_node_identity'); diff --git a/middleware/rateLimit.js b/middleware/rateLimit.js index 31142da..36dc485 100644 --- a/middleware/rateLimit.js +++ b/middleware/rateLimit.js @@ -213,12 +213,11 @@ function sentryReadLimiter() { message: { error: 'too_many_sentry_requests' }, handler: trippedHandler('sentry-read') }); } -function sentryVotingContextLimiter() { - // A governance approval can inspect up to 20 registered nodes. Bound the - // heavier read separately without consuming transaction-management quota. +function sentryHeavyReadLimiter() { + // Governance batches and large historical collateral reads share a tighter public quota. return rateLimit({ windowMs: MINUTE, max: 12, standardHeaders: true, legacyHeaders: false, - keyGenerator: (req) => `sentry-voting-context|${ipBucket(req)}`, - message: { error: 'too_many_sentry_requests' }, handler: trippedHandler('sentry-voting-context') }); + keyGenerator: (req) => `sentry-heavy-read|${ipBucket(req)}`, + message: { error: 'too_many_sentry_requests' }, handler: trippedHandler('sentry-heavy-read') }); } function sentryManagementLimiter() { @@ -237,7 +236,7 @@ module.exports = { voteLimiter, reconcileLimiter, sentryReadLimiter, - sentryVotingContextLimiter, + sentryHeavyReadLimiter, sentryManagementLimiter, disabled, // Exported for direct unit testing. diff --git a/package-lock.json b/package-lock.json index 8211e56..c71080f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1808,7 +1808,7 @@ "node_modules/@sidhujag/sysweb3-sentry": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/@sidhujag/sysweb3-sentry/-/sysweb3-sentry-0.1.4.tgz", - "integrity": "sha512-tuwK9ruxc/DV9wjPSUksxsdvD+7OO1rRy0R+L+3Z6jeRY04Ng9DXZs4Nt11MbY1m+v00+rhQ9ppI4TyRWle/tw==", + "integrity": "sha512-Re/RqG7H7zClvSgMWl0kpccTNj9jiZ+lklXqtKTlgPXzw6j2Y12vwqlCUsXmrLHUL+slyMag+ktdA80ljy5bAQ==", "license": "MIT", "dependencies": { "@noble/curves": "2.4.0", diff --git a/routes/sentry.js b/routes/sentry.js index ed8dc7e..5d1f13e 100644 --- a/routes/sentry.js +++ b/routes/sentry.js @@ -1,10 +1,14 @@ 'use strict'; const express = require('express'); -function createSentryRouter({ management, sessionMw, csrfMw, limiter, readLimiter, votingContextLimiter = (_req, _res, next) => next(), frontendUrl }) { +function createSentryRouter({ management, sessionMw, csrfMw, limiter, readLimiter, heavyReadLimiter = (_req, _res, next) => next(), frontendUrl }) { const router = express.Router(); const route = (fn) => async (req, res) => { try { res.json(await fn(req)); } - catch (error) { res.status(error.status || 502).json({ error: error.code || 'sentry_unavailable' }); } + catch (error) { + if (error.code === 'P2MR_PAYOUT_INACTIVE' || error.code === 'P2MR_FUNDING_INACTIVE') + return res.status(409).json({ error: error.code.toLowerCase() }); + res.status(error.status || 502).json({ error: error.code || 'sentry_unavailable' }); + } }; if (readLimiter) router.use(readLimiter); router.get('/capabilities', route(() => management.capabilities())); @@ -15,7 +19,8 @@ function createSentryRouter({ management, sessionMw, csrfMw, limiter, readLimite vout: Number(collateralVout ?? (collateralAddress ? 0 : NaN)) } : undefined); })); - router.get('/voting-context', votingContextLimiter, route((req) => management.votingContext(req.query))); + router.get('/voting-context', heavyReadLimiter, route((req) => management.votingContext(req.query))); + router.get('/collateral-transaction', heavyReadLimiter, route((req) => management.collateralTransaction(req.query))); // The public context is read-only. Every management route requires a // verified session. State-changing calls additionally bind the exact origin. router.use(sessionMw.requireAuth); diff --git a/scripts/sentry-core-regtest.mjs b/scripts/sentry-core-regtest.mjs index 5568a94..ab802b9 100644 --- a/scripts/sentry-core-regtest.mjs +++ b/scripts/sentry-core-regtest.mjs @@ -263,11 +263,14 @@ try { const pqVotingAddress = sdk.sentryP2MRAddress(sdk.sentryP2MRRoot(genesisHash, 'voting', '43'.repeat(32)), network.bech32); const rollover = await lifecycleManagement.prepare(1, { ...managementBody, proTxHash, operation: 'updateRegistrar', changes: { collateralAddress: cold.address, collateralKeyCommitment: cold.key_commitment, ownerAddress: sdk.sentryP2MRAddress(pqRoot, network.bech32), votingAddress: pqVotingAddress } }); - const reviewContext = async (prepared, collateral) => ({ - ...await adapter.context('regtest', proTxHash, collateral), - previousTransactions: await Promise.all([...new Set(sdk.decodeSentryTransaction(prepared.request.transactionHex).inputs.map((i) => i.txid))].map((id) => rpc('getrawtransaction', [id, false]))), - maxFeeSatoshis: '1000000', - }); + const reviewContext = async (prepared, collateral) => { + const current = await adapter.context('regtest', proTxHash, collateral); + return { ...current, + registeredCollateralTransactionHex: await rpc('getrawtransaction', [current.node.collateralOutpoint.txid, false]), + previousTransactions: await Promise.all([...new Set(sdk.decodeSentryTransaction(prepared.request.transactionHex).inputs.map((i) => i.txid))].map((id) => rpc('getrawtransaction', [id, false]))), + maxFeeSatoshis: '1000000', + }; + }; const confirm = async (row, approved) => { const psbt = await lifecycleManagement.authorize(1, row.id, { authorization: approved }); const signed = await rpc('walletprocesspsbt', [psbt.psbt.psbt]); diff --git a/tests/sentry-codec.integration.mjs b/tests/sentry-codec.integration.mjs index dcb02c8..a604f06 100644 --- a/tests/sentry-codec.integration.mjs +++ b/tests/sentry-codec.integration.mjs @@ -11,7 +11,7 @@ const ECPair = require('ecpair').ECPairFactory(require('@bitcoinerlab/secp256k1' const GENESIS = '12'.repeat(32); const PROTX = '23'.repeat(32); -async function fixture(era = 'legacy-v3', { preparationActive = false, enrolled = true, pqOwner = era === 'pq-v4', banned = false, feeFunds = 1000000n } = {}) { +async function fixture(era = 'legacy-v3', { preparationActive = false, enrolled = true, pqOwner = era === 'pq-v4', banned = false, feeFunds = 1000000n, collateralPublicKey } = {}) { const operator = era === 'legacy-v3' ? await sdk.importSentryOperatorKey('bls-basic', '00'.repeat(31) + '01') : await sdk.deriveSentryOperatorKey('slh-dsa-shake-128s', '03'.repeat(48)); @@ -24,6 +24,7 @@ async function fixture(era = 'legacy-v3', { preparationActive = false, enrolled previous.addOutput(payment.output, feeFunds); const collateral = bitcoinjs.Transaction.fromHex(previous.toHex()); collateral.locktime = 1; const priorCollateral = bitcoinjs.Transaction.fromHex(collateral.toHex()); priorCollateral.locktime = 2; + if (collateralPublicKey) priorCollateral.outs[0].script = Buffer.from('5220' + sdk.sentryP2MRRoot(GENESIS, 'collateral', collateralPublicKey), 'hex'); const pqOwnerKey = pqOwner ? await sdk.importSentryAuthorityKey('owner', 'slh-dsa-shake-128s', (await sdk.deriveSentryOperatorKey('slh-dsa-shake-128s', '06'.repeat(48))).secretKey) : undefined; const ownerRoot = pqOwnerKey && sdk.sentryP2MRRoot(GENESIS, 'owner', pqOwnerKey.publicKey); @@ -55,7 +56,7 @@ async function fixture(era = 'legacy-v3', { preparationActive = false, enrolled if (method === 'protx_list') return [{ proTxHash: PROTX, collateralHash: node.collateralOutpoint.txid, collateralIndex: 0 }]; if (method === 'getrawtransaction') return args[1] === true ? { confirmations: 1 } : args[0] === collateral.getId() ? collateral.toHex() : args[0] === priorCollateral.getId() ? priorCollateral.toHex() : previous.toHex(); - if (method === 'gettxout') return { confirmations: 10, scriptPubKey: { hex: Buffer.from(payment.output).toString('hex') } }; + if (method === 'gettxout') return { confirmations: 10, scriptPubKey: { hex: Buffer.from(args[0] === priorCollateral.getId() ? priorCollateral.outs[0].script : payment.output).toString('hex') } }; if (method === 'testmempoolaccept') return [{ allowed: true }]; if (method === 'sendrawtransaction') return bitcoinjs.Transaction.fromHex(args[0]).getId(); throw new Error(`unexpected ${method}`); @@ -95,7 +96,7 @@ test('a new P2MR reward address requires preparation for registration, registrar { ...base, operation: 'updateRegistrar', proTxHash: PROTX, changes: { payoutAddress } }, { ...base, operation: 'updateService', proTxHash: PROTX, changes: { operatorPayoutAddress: payoutAddress } }, ]; - for (const request of requests) await assert.rejects(f.adapter.prepare(request), /p2mr_payout_inactive/); + for (const request of requests) await assert.rejects(f.adapter.prepare(request), { code: 'P2MR_PAYOUT_INACTIVE' }); f.node.payoutAddress = f.node.operatorPayoutAddress = payoutAddress; await f.adapter.prepare(requests[1]); const preserved = await f.adapter.prepare({ ...requests[2], changes: { service: '1.2.3.5:18369' } }); @@ -105,19 +106,22 @@ test('a new P2MR reward address requires preparation for registration, registrar f.deployment.preparationActive = true; for (const request of requests) await f.adapter.prepare(request); const pq = await fixture('pq-v4'); - await assert.rejects(pq.adapter.prepare(requests[2]), /p2mr_payout_inactive/); + await assert.rejects(pq.adapter.prepare(requests[2]), { code: 'P2MR_PAYOUT_INACTIVE' }); pq.deployment.preparationActive = true; await pq.adapter.prepare(requests[2]); }); -test('a preparation rollback rechecks the embedded payee during authorization, submission and retry', async () => { +for (const use of ['payout', 'funding']) test(`a preparation rollback rechecks P2MR ${use} during authorization, submission and retry`, async () => { const f = await fixture('legacy-v3', { preparationActive: true }); - const payoutAddress = sdk.sentryP2MRAddress('ab'.repeat(32), network.bech32); + const p2mrAddress = sdk.sentryP2MRAddress('ab'.repeat(32), network.bech32); + const payoutAddress = use === 'payout' ? p2mrAddress : f.payment.address; + const changeAddress = use === 'funding' ? p2mrAddress : f.payment.address; + const code = use === 'payout' ? 'P2MR_PAYOUT_INACTIVE' : 'P2MR_FUNDING_INACTIVE'; const collateralOutpoint = { txid: f.collateral.getId(), vout: 0 }; const prepared = await f.adapter.prepare({ operation: 'register', network: 'testnet', collateralOutpoint, changes: { service: f.node.service, ownerAddress: f.ownerPayment.address, votingAddress: f.ownerPayment.address, operatorPublicKey: f.operator.publicKey, payoutAddress, operatorRewardBasisPoints: 0 }, - xpub: 'vpub12345678901234567890', changeAddress: f.payment.address }); + xpub: 'vpub12345678901234567890', changeAddress }); const context = { ...await f.adapter.context('testnet', undefined, collateralOutpoint), previousTransactions: [f.previous.toHex()], maxFeeSatoshis: '1000000' }; const collateralKey = await sdk.importSentryAuthorityKey('collateral', 'secp256k1', '01'.repeat(32)); @@ -128,9 +132,9 @@ test('a preparation rollback rechecks the embedded payee during authorization, s psbt.signAllInputs(f.payer); psbt.finalizeAllInputs(); const submitted = await f.adapter.validateSigned(row, psbt.toBase64()); f.deployment.preparationActive = false; - await assert.rejects(f.adapter.authorize(row, authorization), /p2mr_payout_inactive/); - await assert.rejects(f.adapter.validateSigned(row, psbt.toBase64()), /p2mr_payout_inactive/); - await assert.rejects(f.adapter.validateStored({ ...row, signed_hex: submitted.transactionHex, txid: submitted.txid }), /p2mr_payout_inactive/); + await assert.rejects(f.adapter.authorize(row, authorization), { code }); + await assert.rejects(f.adapter.validateSigned(row, psbt.toBase64()), { code }); + await assert.rejects(f.adapter.validateStored({ ...row, signed_hex: submitted.transactionHex, txid: submitted.txid }), { code }); }); for (const era of ['legacy-v3', 'pq-v4']) test(`${era}: prepare -> operator authorization -> fee signing -> exact-byte submission and readback`, async () => { @@ -168,6 +172,19 @@ test('context keeps active PQ owners without requiring a removed legacy owner ad assert.deepEqual(context.node.pqOwnerRecord, { commitment: f.ownerRoot, keyVersion: 1, activatedHeight: 5, derivationNonce: '00'.repeat(32) }); }); +test('the public collateral lookup returns only the registered transaction with witness stripped', async () => { + const f = await fixture(); + for (let i = 0; i < 256; ++i) f.priorCollateral.addOutput(f.payment.output, 1000n); + const stripped = f.priorCollateral.toHex(); + f.node.collateralOutpoint.txid = f.priorCollateral.getId(); + f.priorCollateral.setWitness(0, [Buffer.alloc(1024, 1)]); + assert.equal((await f.adapter.collateralTransaction('testnet', PROTX)).hex, stripped); + assert.deepEqual(f.rpcCalls.filter(({ method }) => method === 'getrawtransaction').map(({ args }) => args), [[f.node.collateralOutpoint.txid, false]]); + await assert.rejects(f.adapter.collateralTransaction('testnet', f.previous.getId()), { code: 'node_not_found' }); + await assert.rejects(f.adapter.collateralTransaction('mainnet', PROTX), { code: 'network_unavailable' }); + assert.equal(f.rpcCalls.filter(({ method }) => method === 'getrawtransaction').length, 1); +}); + test('after activation the existing ECDSA owner can enroll the first P2MR owner and must preserve payout', async () => { const f = await fixture('pq-v4', { pqOwner: false }); const base = { network: 'testnet', proTxHash: PROTX, xpub: 'vpub12345678901234567890', changeAddress: f.payment.address }; @@ -178,13 +195,14 @@ test('after activation the existing ECDSA owner can enroll the first P2MR owner await assert.rejects(f.adapter.prepare({ ...base, operation: 'updateRegistrar', changes: { ownerAddress, payoutAddress: f.ownerPayment.address } }), { code: 'INVALID_OWNER_ENROLLMENT' }); const prepared = await f.adapter.prepare({ ...base, operation: 'updateRegistrar', changes: { ownerAddress } }); - const context = { ...await f.adapter.context('testnet', PROTX), previousTransactions: [f.previous.toHex()], maxFeeSatoshis: '1000000' }; + const context = { ...await f.adapter.context('testnet', PROTX), registeredCollateralTransactionHex: f.priorCollateral.toHex(), + previousTransactions: [f.previous.toHex()], maxFeeSatoshis: '1000000' }; const signed = await sdk.signSentryManagementOperation(prepared.request, context, f.owner); await f.adapter.authorize({ network: 'testnet', protx_hash: PROTX, prepared }, signed); }); test('funded P2MR registration builds a signable fee PSBT with exactly the selected collateral', async () => { - const f = await fixture('pq-v4', { feeFunds: 2100000n }); + const f = await fixture('pq-v4', { preparationActive: true, feeFunds: 2100000n }); const roleAddress = (role, key) => sdk.sentryP2MRAddress(sdk.sentryP2MRRoot(GENESIS, role, key), network.bech32); const collateralAddress = roleAddress('collateral', '37'.repeat(32)); const prepared = await f.adapter.prepare({ network: 'testnet', operation: 'register', changes: { @@ -202,7 +220,7 @@ test('funded P2MR registration builds a signable fee PSBT with exactly the selec }); test('collateral rollover enforces old P2WPKH input, public target, equal principal, and wallet-bound owner opening', async () => { - const f = await fixture('pq-v4', { pqOwner: true }); + const f = await fixture('pq-v4', { preparationActive: true, pqOwner: true }); const commitment = '1345' + '32'.repeat(30); const root = sdk.sentryCollateralRootFromCommitment(GENESIS, Buffer.from(commitment, 'hex').reverse().toString('hex')); const collateralAddress = sdk.sentryP2MRAddress(root, network.bech32); @@ -246,7 +264,8 @@ test('operator preparation requires owner and new operator proof before fee PSBT const prepared = await f.adapter.prepare({ operation: 'registerOperator', network: 'testnet', proTxHash: PROTX, changes: { operatorPublicKey: candidate.publicKey, childKeyCommitment: '01000200eb0010000100000064000000' + '66'.repeat(32) + '77'.repeat(32), keyVersion: 1 }, xpub: 'vpub12345678901234567890', changeAddress: f.payment.address }); - const context = { ...await f.adapter.context('testnet', PROTX), previousTransactions: [f.previous.toHex()], maxFeeSatoshis: '1000000' }; + const context = { ...await f.adapter.context('testnet', PROTX), registeredCollateralTransactionHex: f.priorCollateral.toHex(), + previousTransactions: [f.previous.toHex()], maxFeeSatoshis: '1000000' }; const row = { network: 'testnet', protx_hash: PROTX, prepared }; const ownerSigned = await sdk.signSentryManagementOperation(prepared.request, context, f.owner); assert.equal(ownerSigned.complete, false); @@ -257,6 +276,18 @@ test('operator preparation requires owner and new operator proof before fee PSBT await f.adapter.authorize(row, complete); }); +test('operator preparation checks the confirmed collateral before offering the candidate for approval', async () => { + const candidate = await sdk.deriveSentryOperatorKey('slh-dsa-shake-128s', '04'.repeat(48)); + const f = await fixture('legacy-v3', { preparationActive: true, enrolled: false, collateralPublicKey: candidate.publicKey }); + // The collateral can come from a historical batch larger than a Sentry update. + for (let i = 0; i < 256; ++i) f.priorCollateral.addOutput(f.payment.output, 1000n); + f.node.collateralOutpoint.txid = f.priorCollateral.getId(); + await assert.rejects(f.adapter.prepare({ operation: 'registerOperator', network: 'testnet', proTxHash: PROTX, + changes: { operatorPublicKey: candidate.publicKey, childKeyCommitment: '01000200eb0010000100000064000000' + '66'.repeat(32) + '77'.repeat(32), keyVersion: 1 }, + xpub: 'vpub12345678901234567890', changeAddress: f.payment.address }), { code: 'KEY_REUSE' }); + assert(f.rpcCalls.some(({ method, args }) => method === 'getrawtransaction' && args[0] === f.priorCollateral.getId() && args[1] === false)); +}); + test('legacy registration and owner update use separate required authorities before fee signing', async () => { const f = await fixture(); const collateralKey = await sdk.importSentryAuthorityKey('collateral', 'secp256k1', '01'.repeat(32)); diff --git a/tests/sentry.routes.test.js b/tests/sentry.routes.test.js index 500fcbe..77a7794 100644 --- a/tests/sentry.routes.test.js +++ b/tests/sentry.routes.test.js @@ -20,3 +20,20 @@ test('public context is read-only; writes need authenticated origin and CSRF', a await request(app).post('/api/sentry/v1/operations').set('x-test-user', '1').set('Origin', 'https://sysnode.info').set('Cookie', 'csrf=abc').set('X-CSRF-Token', 'abc').send({}).expect(200); expect(management.prepare).toHaveBeenCalledTimes(1); }); +test.each(['P2MR_PAYOUT_INACTIVE', 'P2MR_FUNDING_INACTIVE'])('a premature signing operation returns an activation conflict for %s', async (code) => { + const { app, management } = fixture(); + management.prepare.mockRejectedValue(Object.assign(new Error('PQ preparation has not started'), { code })); + await request(app).post('/api/sentry/v1/operations').set('x-test-user', '1').set('Origin', 'https://sysnode.info') + .set('Cookie', 'csrf=abc').set('X-CSRF-Token', 'abc').send({}).expect(409, { error: code.toLowerCase() }); +}); +test('public collateral lookup is scoped to a registered Sentry identity', async () => { + const { createSentryManagement } = require('../lib/sentryManagement'); + const adapter = { collateralTransaction: jest.fn(async () => ({ hex: 'aa' })) }; + const app = express(); + app.use(createSentryRouter({ management: createSentryManagement({ adapter }), sessionMw: { requireAuth: (_req, res) => res.sendStatus(401) } })); + const proTxHash = '12'.repeat(32); + await request(app).get('/collateral-transaction').query({ network: 'testnet', proTxHash, txid: proTxHash }).expect(422); + await request(app).get('/collateral-transaction').query({ network: 'testnet', proTxHash: '0'.repeat(64) }).expect(422); + await request(app).get('/collateral-transaction').query({ network: 'testnet', proTxHash }).expect(200, { hex: 'aa' }); + expect(adapter.collateralTransaction.mock.calls).toEqual([['testnet', proTxHash]]); +}); From 884517b986048addd9b34fbcb5df5b7b2f5a128b Mon Sep 17 00:00:00 2001 From: jagdeep sidhu Date: Wed, 2 Dec 2026 09:26:36 -0700 Subject: [PATCH 05/18] Forward registered collateral lookup through the production Sentry adapter --- lib/sentryAdapter.js | 7 +++--- tests/sentry-codec.integration.mjs | 35 +++++++++++++++++++++++++----- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/lib/sentryAdapter.js b/lib/sentryAdapter.js index 39bcd4b..50af213 100644 --- a/lib/sentryAdapter.js +++ b/lib/sentryAdapter.js @@ -331,9 +331,10 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient async capabilities() { const { chain, capabilities } = await assertNetwork(network); const management = sdk.getSentryManagementCapabilities(); - return { version: 1, network, chain, preparationActive: capabilities.preparationActive === true, ...sdk.getSentryCapabilities(), + const preparationActive = capabilities.preparationActive === true; + return { version: 1, network, chain, preparationActive, ...sdk.getSentryCapabilities(), keyRoles: management.roles, schemes: management.schemes, - fundedRegistration: chain.era === 'pq-v4', collateralRollover: chain.era === 'pq-v4' || capabilities.preparationActive === true, + fundedRegistration: chain.era === 'pq-v4' && preparationActive, collateralRollover: preparationActive, operations: ['register', 'updateService', 'updateRegistrar', 'revoke', ...(capabilities.preparationActive || chain.era === 'pq-v4' ? ['registerOperator'] : []), ...(chain.era === 'pq-v4' ? ['rotateOperator'] : [])], providers: [{ id: 'self-hosted', name: 'Self-hosted', supported: true }, { id: 'nodehub', name: 'NodeHub', supported: false, reason: 'Provider integration is not configured. Keys remain in Pali.' }] }; }, @@ -555,7 +556,7 @@ function createConfiguredSentryAdapter({ rpcCall, network, genesisHash, fundingC createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient })); return loaded; }; - return Object.fromEntries(['capabilities', 'context', 'votingContext', 'prepare', 'authorize', 'validateSigned', 'validateStored', 'broadcast', 'readback'] + return Object.fromEntries(['capabilities', 'context', 'votingContext', 'collateralTransaction', 'prepare', 'authorize', 'validateSigned', 'validateStored', 'broadcast', 'readback'] .map((method) => [method, async (...args) => (await load())[method](...args)])); } function createSentryRpc(client) { diff --git a/tests/sentry-codec.integration.mjs b/tests/sentry-codec.integration.mjs index a604f06..2868e1f 100644 --- a/tests/sentry-codec.integration.mjs +++ b/tests/sentry-codec.integration.mjs @@ -1,10 +1,14 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { createRequire } from 'node:module'; +import express from 'express'; +import request from 'supertest'; const sdk = await import(process.env.SENTRY_SDK_TEST_MODULE || '@sidhujag/sysweb3-sentry'); const require = createRequire(import.meta.url); const syscoinjs = require('syscoinjs-lib'); -const { createSentryAdapter } = require('../lib/sentryAdapter'); +const { createSentryAdapter, createConfiguredSentryAdapter } = require('../lib/sentryAdapter'); +const { createSentryManagement } = require('../lib/sentryManagement'); +const { createSentryRouter } = require('../routes/sentry'); const bitcoinjs = syscoinjs.utils.bitcoinjs; const network = syscoinjs.utils.syscoinNetworks.testnet; const ECPair = require('ecpair').ECPairFactory(require('@bitcoinerlab/secp256k1')); @@ -82,9 +86,21 @@ async function fixture(era = 'legacy-v3', { preparationActive = false, enrolled }, }; const adapter = createSentryAdapter({ rpcCall, network: 'testnet', genesisHash: GENESIS, sdk, fundingClient }); - return { adapter, operator, owner, ownerPayment, ownerRoot, pqOwnerKey, collateral, priorCollateral, payer, payment, previous, node, deployment, rpcCalls, setNEVM: (value) => { nevmAddress = value; } }; + return { adapter, rpcCall, fundingClient, operator, owner, ownerPayment, ownerRoot, pqOwnerKey, collateral, priorCollateral, payer, payment, previous, node, deployment, rpcCalls, setNEVM: (value) => { nevmAddress = value; } }; } +test('collateral capabilities follow the preparation flag reported by Core', async () => { + for (const era of ['legacy-v3', 'pq-v4']) { + const f = await fixture(era); + for (const preparationActive of [false, true]) { + f.deployment.preparationActive = preparationActive; + const caps = await f.adapter.capabilities(); + assert.equal(caps.fundedRegistration, preparationActive && era === 'pq-v4'); + assert.equal(caps.collateralRollover, preparationActive); + } + } +}); + test('a new P2MR reward address requires preparation for registration, registrar and service updates', async () => { const f = await fixture(); const payoutAddress = sdk.sentryP2MRAddress('ab'.repeat(32), network.bech32); @@ -172,16 +188,23 @@ test('context keeps active PQ owners without requiring a removed legacy owner ad assert.deepEqual(context.node.pqOwnerRecord, { commitment: f.ownerRoot, keyVersion: 1, activatedHeight: 5, derivationNonce: '00'.repeat(32) }); }); -test('the public collateral lookup returns only the registered transaction with witness stripped', async () => { +test('the configured public collateral route returns only the registered transaction with witness stripped', async () => { const f = await fixture(); for (let i = 0; i < 256; ++i) f.priorCollateral.addOutput(f.payment.output, 1000n); const stripped = f.priorCollateral.toHex(); f.node.collateralOutpoint.txid = f.priorCollateral.getId(); f.priorCollateral.setWitness(0, [Buffer.alloc(1024, 1)]); - assert.equal((await f.adapter.collateralTransaction('testnet', PROTX)).hex, stripped); + const adapter = createConfiguredSentryAdapter({ rpcCall: f.rpcCall, network: 'testnet', genesisHash: GENESIS, fundingClient: f.fundingClient }); + const app = express(); + app.use('/api/sentry/v1', createSentryRouter({ + management: createSentryManagement({ adapter }), + sessionMw: { requireAuth: (_req, res) => res.sendStatus(401) }, + })); + const lookup = (network, proTxHash) => request(app).get('/api/sentry/v1/collateral-transaction').query({ network, proTxHash }); + await lookup('testnet', PROTX).expect(200, { hex: stripped }); assert.deepEqual(f.rpcCalls.filter(({ method }) => method === 'getrawtransaction').map(({ args }) => args), [[f.node.collateralOutpoint.txid, false]]); - await assert.rejects(f.adapter.collateralTransaction('testnet', f.previous.getId()), { code: 'node_not_found' }); - await assert.rejects(f.adapter.collateralTransaction('mainnet', PROTX), { code: 'network_unavailable' }); + await lookup('testnet', f.previous.getId()).expect(404, { error: 'node_not_found' }); + await lookup('mainnet', PROTX).expect(409, { error: 'network_unavailable' }); assert.equal(f.rpcCalls.filter(({ method }) => method === 'getrawtransaction').length, 1); }); From 5f317bccec4fb686e78998aa821b5fb6c3d53ae4 Mon Sep 17 00:00:00 2001 From: jagdeep sidhu Date: Wed, 2 Dec 2026 13:53:11 -0700 Subject: [PATCH 06/18] Retry Sentry transactions orphaned out of the mempool --- lib/sentryAdapter.js | 12 ++++++++++-- lib/sentryAdapter.test.js | 23 +++++++++++++++++++++-- scripts/sentry-core-regtest.mjs | 15 +++++++++++++++ tests/sentry-codec.integration.mjs | 2 +- 4 files changed, 47 insertions(+), 5 deletions(-) diff --git a/lib/sentryAdapter.js b/lib/sentryAdapter.js index 50af213..4fc5676 100644 --- a/lib/sentryAdapter.js +++ b/lib/sentryAdapter.js @@ -507,9 +507,17 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient } throw error; } - if (!(tx.confirmations > 0)) { + if (tx?.txid !== row.txid) throw failure('sentry_rpc_response_mismatch', 503); + // Core checks the mempool before txindex. Only a mempool hit omits both + // block fields. An indexed transaction in a disconnected block has zero confirmations. + const inMempool = tx.blockhash === undefined && tx.confirmations === undefined; + if (!inMempool && (typeof tx.blockhash !== 'string' || !/^[a-f0-9]{64}$/.test(tx.blockhash) || + !Number.isSafeInteger(tx.confirmations) || tx.confirmations < 0)) { + throw failure('sentry_rpc_response_mismatch', 503); + } + if (inMempool || tx.confirmations === 0) { await assertNetwork(row.network); - return { confirmed: false, matches: false, known: true }; + return { confirmed: false, matches: false, known: inMempool }; } const operation = row.prepared.request.operation; const observed = await context(row.network, operation === 'register' ? row.txid : row.protx_hash); diff --git a/lib/sentryAdapter.test.js b/lib/sentryAdapter.test.js index 5ffbb71..9138e1b 100644 --- a/lib/sentryAdapter.test.js +++ b/lib/sentryAdapter.test.js @@ -34,6 +34,24 @@ test('readback recognizes only Core definitive transaction absence', async () => const adapter = readbackFixture(Object.assign(new Error(absentTransaction), { code: -5 })); await expect(adapter.readback({ network: 'testnet', txid: 'b'.repeat(64) })).resolves.toEqual({ confirmed: false, matches: false }); }); +const txid = 'd'.repeat(64); +const blockhash = 'e'.repeat(64); +test.each([ + ['mempool transaction', { txid }, true], + ['indexed transaction in a disconnected block', { txid, blockhash, confirmations: 0 }, false], +])('readback distinguishes a %s', async (_name, observation, known) => { + await expect(readbackFixture(observation).readback({ network: 'testnet', txid })) + .resolves.toEqual({ confirmed: false, matches: false, known }); +}); +test.each([ + { txid: 'b'.repeat(64) }, + { txid, confirmations: 0 }, + { txid, blockhash }, + { txid, blockhash: 'invalid', confirmations: 1 }, +])('readback rejects mismatched or incomplete transaction metadata', async (observation) => { + await expect(readbackFixture(observation).readback({ network: 'testnet', txid })) + .rejects.toMatchObject({ code: 'sentry_rpc_response_mismatch' }); +}); test.each([ ['sentry_rpc_unavailable', 'RPC unavailable'], ['sentry_rpc_response_mismatch', 'Unrelated response ID'], @@ -46,8 +64,9 @@ test.each([ }); test.each([ Object.assign(new Error(absentTransaction), { code: -5 }), - { confirmations: 0 }, + { txid }, + { txid, blockhash, confirmations: 0 }, ])('wrong-genesis absence or pending evidence cannot update the journal', async (observation) => { - await expect(readbackFixture(observation, true).readback({ network: 'testnet', txid: 'd'.repeat(64) })) + await expect(readbackFixture(observation, true).readback({ network: 'testnet', txid })) .rejects.toMatchObject({ code: 'network_mismatch' }); }); diff --git a/scripts/sentry-core-regtest.mjs b/scripts/sentry-core-regtest.mjs index ab802b9..d180881 100644 --- a/scripts/sentry-core-regtest.mjs +++ b/scripts/sentry-core-regtest.mjs @@ -297,6 +297,21 @@ try { pqOwnerOpening: pqOwner.publicKey, pqOwnerCommitment: nextRoot, pqOwnerDerivationNonce: '00'.repeat(32) }); const transferTxid = await confirm(update, await sdk.signSentryManagementOperation(bound, nextContext, pqOwner)); assert.equal((await rpc('protx_info', [proTxHash])).state.pqOwnerCommitment, nextRoot); + // Core reaccepts transactions from at most ten disconnected blocks. Orphan + // the confirmed transfer eleven blocks deep to leave it only in txindex. + const minedBlock = (await rpc('getrawtransaction', [transferTxid, true])).blockhash; + await rpc('generatetoaddress', [10, mining]); + await rpc('invalidateblock', [minedBlock]); + const orphan = await rpc('getrawtransaction', [transferTxid, true]); + assert.equal(orphan.blockhash, minedBlock); + assert.equal(orphan.confirmations, 0); + assert.equal((await rpc('getrawmempool')).includes(transferTxid), false); + now += 30_000; + assert.equal((await lifecycleManagement.retry(1, update.id, {})).status, 'submitted'); + assert((await rpc('getrawmempool')).includes(transferTxid)); + assert.equal(await rpc('getrawtransaction', [transferTxid, false]), repository.read(update.id, 1).signed_hex); + await rpc('generatetoaddress', [1, await rpc('getnewaddress')]); + assert.equal((await lifecycleManagement.reconcile(1, update.id)).status, 'confirmed'); console.log(JSON.stringify({ result: 'passed', scope: 'disconnected legacy and PQ preparation regtest', proTxHash, createdProTxHash, rolloverTxid, transferTxid, managementLifecycle, tamperedAddressRejection, observed, datadir }, null, 2)); } finally { diff --git a/tests/sentry-codec.integration.mjs b/tests/sentry-codec.integration.mjs index 2868e1f..95aa3e8 100644 --- a/tests/sentry-codec.integration.mjs +++ b/tests/sentry-codec.integration.mjs @@ -58,7 +58,7 @@ async function fixture(era = 'legacy-v3', { preparationActive = false, enrolled PoSeBanHeight: banned ? 10 : -1, confirmedHash: '45'.repeat(32), service: node.service, nevmAddress } }; if (method === 'protx_operator_key_info') { assert.deepEqual(args, [PROTX, true]); return enrolled ? record : { hasGlobalKey: false, active: false, revokedHeight: -1, genesisHash: GENESIS, height: 10, blockHash: 'ff'.repeat(32) }; } if (method === 'protx_list') return [{ proTxHash: PROTX, collateralHash: node.collateralOutpoint.txid, collateralIndex: 0 }]; - if (method === 'getrawtransaction') return args[1] === true ? { confirmations: 1 } : args[0] === collateral.getId() ? collateral.toHex() + if (method === 'getrawtransaction') return args[1] === true ? { txid: args[0], blockhash: 'ff'.repeat(32), confirmations: 1 } : args[0] === collateral.getId() ? collateral.toHex() : args[0] === priorCollateral.getId() ? priorCollateral.toHex() : previous.toHex(); if (method === 'gettxout') return { confirmations: 10, scriptPubKey: { hex: Buffer.from(args[0] === priorCollateral.getId() ? priorCollateral.outs[0].script : payment.output).toString('hex') } }; if (method === 'testmempoolaccept') return [{ allowed: true }]; From 11fd171928d8b3de0b2cab95ba9a46dda3d26063 Mon Sep 17 00:00:00 2001 From: jagdeep sidhu Date: Wed, 2 Dec 2026 15:31:46 -0700 Subject: [PATCH 07/18] Use the P2MR-aware transaction builder for backend funding --- package-lock.json | 28 +++++++++++----------- package.json | 2 +- tests/syscoin-dependencies.integration.mjs | 17 +++++++++++++ 3 files changed, 32 insertions(+), 15 deletions(-) diff --git a/package-lock.json b/package-lock.json index c71080f..1fbab7a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -29,7 +29,7 @@ "numeral": "2.0.6", "papaparse": "^5.5.3", "pretty-ms": "6.0.1", - "syscoinjs-lib": "^1.0.275", + "syscoinjs-lib": "git+https://github.com/syscoin/syscoinjs-lib.git#cbdc9d05b353d8bbf5246c2dcdfefa99838630af", "websocket": "1.0.34", "zod": "4.6.7" }, @@ -1808,7 +1808,7 @@ "node_modules/@sidhujag/sysweb3-sentry": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/@sidhujag/sysweb3-sentry/-/sysweb3-sentry-0.1.4.tgz", - "integrity": "sha512-Re/RqG7H7zClvSgMWl0kpccTNj9jiZ+lklXqtKTlgPXzw6j2Y12vwqlCUsXmrLHUL+slyMag+ktdA80ljy5bAQ==", + "integrity": "sha512-OVfgsMOmhxp8cqhZ1ZvAGNjRVf5AsPizuxV+5S3wjNgh+FnJQllY5Uu4erGpEUU2dtA56faXq6GfHkIJSAmA5Q==", "license": "MIT", "dependencies": { "@noble/curves": "2.4.0", @@ -3412,8 +3412,8 @@ }, "node_modules/coinselectsyscoin": { "version": "1.1.12", - "resolved": "https://registry.npmjs.org/coinselectsyscoin/-/coinselectsyscoin-1.1.12.tgz", - "integrity": "sha512-eQ/zZGaHRSvJ5Z8cNt3tEjH77WhRl2yBN0Dl/xMJXWa1Cj4S5x3/SlQB9ZaVfrxFFCmtpptDcQi0eMPT2mq1bQ==", + "resolved": "git+ssh://git@github.com/syscoin/coinselectsyscoin.git#01121ffc5ba45caa00dae96564ace717a94fc06c", + "integrity": "sha512-AHkL0oItW/tCm5H9BY4g/HbizVbiR+01erNJ2O08vhRYBVlrcL1CtNN5YzspS/Hu/xATpOUTUV8p90/ybXCuig==", "license": "MIT", "dependencies": { "bn.js": "^5.2.4" @@ -9345,9 +9345,9 @@ } }, "node_modules/syscoinjs-lib": { - "version": "1.0.275", - "resolved": "https://registry.npmjs.org/syscoinjs-lib/-/syscoinjs-lib-1.0.275.tgz", - "integrity": "sha512-el+6wWDxVObR/f7+Q1aZTgg7goUEEQTfNYoF+CSMvv/VZKd8I2qqImb4LV1opkIPXTwydRBhaFpM7wE+93J8XA==", + "version": "2.0.0", + "resolved": "git+ssh://git@github.com/syscoin/syscoinjs-lib.git#cbdc9d05b353d8bbf5246c2dcdfefa99838630af", + "integrity": "sha512-2TMyJ8icTtegmSmmeFyoUIuW/mz4CXk5Z3uzJLxcVtO4v+zIbRrtnoypjDR6TzM18f/sA+eHUxszoLwjE7wzaw==", "license": "MIT", "dependencies": { "@bitcoinerlab/secp256k1": "^1.2.0", @@ -9359,24 +9359,24 @@ "bn.js": "^5.2.4", "bs58": "^6.0.0", "ecpair": "^3.0.1", - "eth-object": "git+https://github.com/syscoin/eth-object.git", + "eth-object": "https://github.com/syscoin/eth-object.git", "eth-proof": "^2.1.6", "ethers": "^6.17.0", - "syscointx-js": "^1.0.128", + "syscointx-js": "git+https://github.com/syscoin/syscointx-js.git#56d9469cbd48d18cc9d44d496fb76774f1a2cae6", "varuint-bitcoin": "^2.0.0" } }, "node_modules/syscointx-js": { - "version": "1.0.128", - "resolved": "https://registry.npmjs.org/syscointx-js/-/syscointx-js-1.0.128.tgz", - "integrity": "sha512-43dgrnCgRCWcM6PIMU7mvV9t2thjLhtm9yMqmvZvMPWuqRGbWG7yxC6Ix+bsvd/NDIFri26npR5xPdRlXPSO9g==", + "version": "2.0.0", + "resolved": "git+ssh://git@github.com/syscoin/syscointx-js.git#56d9469cbd48d18cc9d44d496fb76774f1a2cae6", + "integrity": "sha512-HJw6LRUzf+4XIjEqj2bmrGNRNe8p4VQMRX49F7f4/4qPSoxGFp/u8Pn1hKo26v6Wlm6q0cXO/9FtjgIu5jbPow==", "license": "MIT", "dependencies": { "@bitcoinerlab/secp256k1": "^1.2.0", "bitcoin-ops": "^1.4.1", - "bitcoinjs-lib": "^7.0.1", + "bitcoinjs-lib": "^7.0.5", "bn.js": "^5.2.4", - "coinselectsyscoin": "^1.1.12", + "coinselectsyscoin": "git+https://github.com/syscoin/coinselectsyscoin.git#01121ffc5ba45caa00dae96564ace717a94fc06c", "ecpair": "^3.0.1", "typeforce": "^1.18.0", "varuint-bitcoin": "^2.0.0" diff --git a/package.json b/package.json index d5ba908..17660c8 100644 --- a/package.json +++ b/package.json @@ -53,7 +53,7 @@ "numeral": "2.0.6", "papaparse": "^5.5.3", "pretty-ms": "6.0.1", - "syscoinjs-lib": "^1.0.275", + "syscoinjs-lib": "git+https://github.com/syscoin/syscoinjs-lib.git#cbdc9d05b353d8bbf5246c2dcdfefa99838630af", "websocket": "1.0.34", "zod": "4.6.7" }, diff --git a/tests/syscoin-dependencies.integration.mjs b/tests/syscoin-dependencies.integration.mjs index 9a9b2bf..8e48350 100644 --- a/tests/syscoin-dependencies.integration.mjs +++ b/tests/syscoin-dependencies.integration.mjs @@ -70,6 +70,23 @@ test('production collateral builder preserves exact OP_RETURN, non-RBF inputs an }); }); +test('production collateral builder quotes the P2MR payment input at 2040 vbytes', async () => { + const address = bitcoinjs.address.toBech32(Buffer.alloc(32, 7), 2, network.bech32); + const fees = []; + for (const fundingAddress of [changeAddress, address]) { + await withBlockbook([rawUtxo(20_000_000_000, '6', { address: fundingAddress })], async client => { + const result = await buildCollateralPsbt({ opReturnHex: 'ab'.repeat(32), xpub, changeAddress, feeRate: 10, syscoinClient: client }); + const psbt = bitcoinjs.Psbt.fromBase64(result.psbt.psbt, { network }); + const input = psbt.data.inputs[0].witnessUtxo; + assert.deepEqual(Buffer.from(input.script), Buffer.from(bitcoinjs.address.toOutputScript(fundingAddress, network))); + const fee = input.value - psbt.txOutputs.reduce((sum, output) => sum + output.value, 0n); + assert.equal(fee, BigInt(result.feeSats)); + fees.push(fee); + }); + } + assert.equal(fees[1] - fees[0], (2040n - 68n) * 10n); +}); + test('native send retains its recipient and reports the exact serialized input/output fee', async () => { await withBlockbook([rawUtxo(100_000_000, '2')], async client => { const result = await client.createTransaction({ rbf: false }, changeAddress, From 4445f1c3e32a7fc54fcd82d62c76b2f21021d1d7 Mon Sep 17 00:00:00 2001 From: jagdeep sidhu Date: Wed, 2 Dec 2026 15:44:49 -0700 Subject: [PATCH 08/18] Build reviewed Sentry SDK in PR checks and refresh patched ws --- .github/workflows/ci.yml | 55 +++++++++++++++++++++++++++ package-lock.json | 8 ++-- package.json | 2 +- scripts/cache-reviewed-sentry-sdk.cjs | 12 ++++++ 4 files changed, 72 insertions(+), 5 deletions(-) create mode 100644 scripts/cache-reviewed-sentry-sdk.cjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c3fcc6a..08ceba1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,6 +38,25 @@ jobs: node-version: ${{ matrix.node }} cache: npm + - name: Checkout reviewed Sentry SDK + if: github.event_name == 'pull_request' && github.head_ref == 'codex/p2mr-sentry-authorities' + uses: actions/checkout@v4 + with: + repository: sidhujag/sysweb3 + ref: 739dd796f6665ec218782dbc5bb8a236c515daea + path: sdk-review + persist-credentials: false + + - name: Cache reviewed Sentry SDK + if: github.event_name == 'pull_request' && github.head_ref == 'codex/p2mr-sentry-authorities' + run: | + npm --prefix sdk-review/packages/sysweb3-sentry ci --ignore-scripts --include=dev + npm --prefix sdk-review/packages/sysweb3-sentry run build + mkdir -p "$RUNNER_TEMP/reviewed-sentry" + (cd sdk-review/packages/sysweb3-sentry && npm pack --ignore-scripts --pack-destination "$RUNNER_TEMP/reviewed-sentry") + node scripts/cache-reviewed-sentry-sdk.cjs "$RUNNER_TEMP/reviewed-sentry" + rm -rf sdk-review + - name: Install # `npm ci` is strict about package-lock.json; if the lock # drifts we want the CI to fail loudly rather than silently @@ -63,6 +82,23 @@ jobs: with: node-version-file: '.nvmrc' cache: npm + - name: Checkout reviewed Sentry SDK + if: github.event_name == 'pull_request' && github.head_ref == 'codex/p2mr-sentry-authorities' + uses: actions/checkout@v4 + with: + repository: sidhujag/sysweb3 + ref: 739dd796f6665ec218782dbc5bb8a236c515daea + path: sdk-review + persist-credentials: false + - name: Cache reviewed Sentry SDK + if: github.event_name == 'pull_request' && github.head_ref == 'codex/p2mr-sentry-authorities' + run: | + npm --prefix sdk-review/packages/sysweb3-sentry ci --ignore-scripts --include=dev + npm --prefix sdk-review/packages/sysweb3-sentry run build + mkdir -p "$RUNNER_TEMP/reviewed-sentry" + (cd sdk-review/packages/sysweb3-sentry && npm pack --ignore-scripts --pack-destination "$RUNNER_TEMP/reviewed-sentry") + node scripts/cache-reviewed-sentry-sdk.cjs "$RUNNER_TEMP/reviewed-sentry" + rm -rf sdk-review - name: Install pinned Anvil uses: foundry-rs/foundry-toolchain@908c540300062bd5a7e473851cdb4282204cee09 # v1 with: @@ -86,6 +122,25 @@ jobs: node-version-file: '.nvmrc' cache: npm + - name: Checkout reviewed Sentry SDK + if: github.event_name == 'pull_request' && github.head_ref == 'codex/p2mr-sentry-authorities' + uses: actions/checkout@v4 + with: + repository: sidhujag/sysweb3 + ref: 739dd796f6665ec218782dbc5bb8a236c515daea + path: sdk-review + persist-credentials: false + + - name: Cache reviewed Sentry SDK + if: github.event_name == 'pull_request' && github.head_ref == 'codex/p2mr-sentry-authorities' + run: | + npm --prefix sdk-review/packages/sysweb3-sentry ci --ignore-scripts --include=dev + npm --prefix sdk-review/packages/sysweb3-sentry run build + mkdir -p "$RUNNER_TEMP/reviewed-sentry" + (cd sdk-review/packages/sysweb3-sentry && npm pack --ignore-scripts --pack-destination "$RUNNER_TEMP/reviewed-sentry") + node scripts/cache-reviewed-sentry-sdk.cjs "$RUNNER_TEMP/reviewed-sentry" + rm -rf sdk-review + - name: Install run: npm ci diff --git a/package-lock.json b/package-lock.json index 1fbab7a..0ae36c5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1808,7 +1808,7 @@ "node_modules/@sidhujag/sysweb3-sentry": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/@sidhujag/sysweb3-sentry/-/sysweb3-sentry-0.1.4.tgz", - "integrity": "sha512-OVfgsMOmhxp8cqhZ1ZvAGNjRVf5AsPizuxV+5S3wjNgh+FnJQllY5Uu4erGpEUU2dtA56faXq6GfHkIJSAmA5Q==", + "integrity": "sha512-SY+EgP6jKEfvpLWBISLbiaNIf5E1YtEMBMJ/q3GdyhQTZtHwEgZCCch3m3Ubtt7b9uGntNvzsNUnqSJOHiC2Pw==", "license": "MIT", "dependencies": { "@noble/curves": "2.4.0", @@ -9883,9 +9883,9 @@ } }, "node_modules/ws": { - "version": "8.21.3", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", - "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "version": "8.23.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz", + "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==", "license": "MIT", "engines": { "node": ">=10.0.0" diff --git a/package.json b/package.json index 17660c8..79c05df 100644 --- a/package.json +++ b/package.json @@ -76,6 +76,6 @@ "node-fetch": "2.7.0", "elliptic": "6.6.1", "ip-address": "10.7.4", - "ws": "8.21.3" + "ws": "8.23.0" } } diff --git a/scripts/cache-reviewed-sentry-sdk.cjs b/scripts/cache-reviewed-sentry-sdk.cjs new file mode 100644 index 0000000..475a130 --- /dev/null +++ b/scripts/cache-reviewed-sentry-sdk.cjs @@ -0,0 +1,12 @@ +const { execFileSync } = require('node:child_process'); +const { createHash } = require('node:crypto'); +const { readFileSync } = require('node:fs'); +const { resolve } = require('node:path'); + +const entry = require('../package-lock.json').packages['node_modules/@sidhujag/sysweb3-sentry']; +const tarball = resolve(process.argv[2], `sidhujag-sysweb3-sentry-${entry.version}.tgz`); +const integrity = `sha512-${createHash('sha512').update(readFileSync(tarball)).digest('base64')}`; +if (integrity !== entry.integrity) { + throw new Error('Reviewed Sentry SDK artifact differs from the committed lockfile'); +} +execFileSync('npm', ['cache', 'add', tarball], { stdio: 'inherit' }); From 3f7a7f24ac255d8611b74696530b021cd50727e7 Mon Sep 17 00:00:00 2001 From: jagdeep sidhu Date: Wed, 2 Dec 2026 15:46:15 -0700 Subject: [PATCH 09/18] Stage reviewed SDK on push and PR checks --- .github/workflows/ci.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 08ceba1..ca2cfb1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,7 +39,7 @@ jobs: cache: npm - name: Checkout reviewed Sentry SDK - if: github.event_name == 'pull_request' && github.head_ref == 'codex/p2mr-sentry-authorities' + if: github.head_ref == 'codex/p2mr-sentry-authorities' || github.ref == 'refs/heads/codex/p2mr-sentry-authorities' uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 @@ -48,7 +48,7 @@ jobs: persist-credentials: false - name: Cache reviewed Sentry SDK - if: github.event_name == 'pull_request' && github.head_ref == 'codex/p2mr-sentry-authorities' + if: github.head_ref == 'codex/p2mr-sentry-authorities' || github.ref == 'refs/heads/codex/p2mr-sentry-authorities' run: | npm --prefix sdk-review/packages/sysweb3-sentry ci --ignore-scripts --include=dev npm --prefix sdk-review/packages/sysweb3-sentry run build @@ -83,7 +83,7 @@ jobs: node-version-file: '.nvmrc' cache: npm - name: Checkout reviewed Sentry SDK - if: github.event_name == 'pull_request' && github.head_ref == 'codex/p2mr-sentry-authorities' + if: github.head_ref == 'codex/p2mr-sentry-authorities' || github.ref == 'refs/heads/codex/p2mr-sentry-authorities' uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 @@ -91,7 +91,7 @@ jobs: path: sdk-review persist-credentials: false - name: Cache reviewed Sentry SDK - if: github.event_name == 'pull_request' && github.head_ref == 'codex/p2mr-sentry-authorities' + if: github.head_ref == 'codex/p2mr-sentry-authorities' || github.ref == 'refs/heads/codex/p2mr-sentry-authorities' run: | npm --prefix sdk-review/packages/sysweb3-sentry ci --ignore-scripts --include=dev npm --prefix sdk-review/packages/sysweb3-sentry run build @@ -123,7 +123,7 @@ jobs: cache: npm - name: Checkout reviewed Sentry SDK - if: github.event_name == 'pull_request' && github.head_ref == 'codex/p2mr-sentry-authorities' + if: github.head_ref == 'codex/p2mr-sentry-authorities' || github.ref == 'refs/heads/codex/p2mr-sentry-authorities' uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 @@ -132,7 +132,7 @@ jobs: persist-credentials: false - name: Cache reviewed Sentry SDK - if: github.event_name == 'pull_request' && github.head_ref == 'codex/p2mr-sentry-authorities' + if: github.head_ref == 'codex/p2mr-sentry-authorities' || github.ref == 'refs/heads/codex/p2mr-sentry-authorities' run: | npm --prefix sdk-review/packages/sysweb3-sentry ci --ignore-scripts --include=dev npm --prefix sdk-review/packages/sysweb3-sentry run build From baf6c3d4a133e663759b15fba9d3fa9ee72c2876 Mon Sep 17 00:00:00 2001 From: jagdeep sidhu Date: Wed, 2 Dec 2026 16:05:16 -0700 Subject: [PATCH 10/18] =?UTF-8?q?Match=20Pali=E2=80=99s=20reviewed=20sentr?= =?UTF-8?q?y=20SDK=20and=20clarify=20governance=20roles?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ci.yml | 6 +++--- lib/gov.js | 6 ++---- package-lock.json | 2 +- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ca2cfb1..27beeec 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: 739dd796f6665ec218782dbc5bb8a236c515daea + ref: c9217c33412071d02ffe4795dd147cc19e985b58 path: sdk-review persist-credentials: false @@ -87,7 +87,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: 739dd796f6665ec218782dbc5bb8a236c515daea + ref: c9217c33412071d02ffe4795dd147cc19e985b58 path: sdk-review persist-credentials: false - name: Cache reviewed Sentry SDK @@ -127,7 +127,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: 739dd796f6665ec218782dbc5bb8a236c515daea + ref: c9217c33412071d02ffe4795dd147cc19e985b58 path: sdk-review persist-credentials: false diff --git a/lib/gov.js b/lib/gov.js index eba3af7..4c8e5a6 100644 --- a/lib/gov.js +++ b/lib/gov.js @@ -12,10 +12,8 @@ // * Vote-relay validation + fan-out. The browser signs locally // (VaultGovernanceSigner / voteSigner.js), and we relay each // ECDSA signature or PQ funding envelope to Core's `voteraw` RPC. We -// intentionally enforce `voteSignal === "funding"` here — non- -// funding signals (valid/delete/endorsed) use the BLS operator -// key, NOT the voting key, and the vault doesn't hold operator -// keys. +// accept only proposal funding here. Core authorizes other signals +// with the operator key for the active era. The vault holds voting keys. // // Error taxonomy for validation: we return `{ ok: false, error: "" }` // rather than throwing, so the HTTP layer maps codes to 4xx without diff --git a/package-lock.json b/package-lock.json index 0ae36c5..837eb47 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1808,7 +1808,7 @@ "node_modules/@sidhujag/sysweb3-sentry": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/@sidhujag/sysweb3-sentry/-/sysweb3-sentry-0.1.4.tgz", - "integrity": "sha512-SY+EgP6jKEfvpLWBISLbiaNIf5E1YtEMBMJ/q3GdyhQTZtHwEgZCCch3m3Ubtt7b9uGntNvzsNUnqSJOHiC2Pw==", + "integrity": "sha512-77rHJQ3unIpptzjMBtdGm26NW0QqDteVuiUkYspC8aRp+H66E+asL7e6XnSIQRNKdcmT620cHNZBjJ60ZG5svQ==", "license": "MIT", "dependencies": { "@noble/curves": "2.4.0", From 476dbb25afadef3d91d3962a68792a76407e5f03 Mon Sep 17 00:00:00 2001 From: jagdeep sidhu Date: Wed, 2 Dec 2026 16:11:39 -0700 Subject: [PATCH 11/18] Apply Sentry transaction size limits after authenticating the operation --- lib/appFactory.js | 3 ++- lib/sentryAdapter.js | 10 ++++++--- lib/sentryBodyLimits.js | 26 ++++++++++++++++++++++ lib/sentryManagement.js | 6 +++++ routes/sentry.js | 14 +++++++----- server.js | 4 ++-- tests/helpers/compressedJsonChild.cjs | 6 ++--- tests/sentry.productionComposition.test.js | 26 ++++++++++++++++++++-- 8 files changed, 79 insertions(+), 16 deletions(-) create mode 100644 lib/sentryBodyLimits.js diff --git a/lib/appFactory.js b/lib/appFactory.js index ed6914a..fa18d23 100644 --- a/lib/appFactory.js +++ b/lib/appFactory.js @@ -1,3 +1,4 @@ +const { parseNonSentryJson } = require('./sentryBodyLimits'); const express = require('express'); const cookieParser = require('cookie-parser'); const helmet = require('helmet'); @@ -401,7 +402,7 @@ function createApp({ // Public pool snapshots never enter the session or credentialed-CORS path. app.use(PRIVACY_PREFIXES, createPrivacyRouter({ index: privacyIndex, relayers: privacyRelayers })); app.use(cors({ origin: effectiveCorsOrigin, credentials: true })); - app.use(express.json({ limit: '256kb' })); + app.use(parseNonSentryJson); app.use(cookieParser()); mountAuthAndVault(app, { diff --git a/lib/sentryAdapter.js b/lib/sentryAdapter.js index 4fc5676..e5c4d6b 100644 --- a/lib/sentryAdapter.js +++ b/lib/sentryAdapter.js @@ -1,4 +1,5 @@ 'use strict'; +const { MAX_STANDARD_WEIGHT, MAX_TX_HEX_LENGTH, signedPsbtLimit } = require('./sentryBodyLimits'); const BN = require('bn.js'); const crypto = require('crypto'); const { failure } = require('./sentryManagement'); @@ -475,9 +476,10 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient return { psbt: { psbt: psbtFor(tx, row.prepared.fundingPsbt).toBase64(), assets: '[]' }, feeSatoshis: row.prepared.review.feeSatoshis }; }, async validateSigned(row, signedPsbt) { - if (typeof signedPsbt !== 'string' || signedPsbt.length > 300000) throw failure('invalid_signed_transaction'); + if (typeof signedPsbt !== 'string' || signedPsbt.length > signedPsbtLimit(row.prepared)) throw failure('invalid_signed_transaction'); const psbt = bitcoinjs.Psbt.fromBase64(signedPsbt, { network: fundingClient.network }); const tx = psbt.extractTransaction(); + if (tx.weight() > MAX_STANDARD_WEIGHT) throw failure('invalid_signed_transaction'); const { fields } = await liveReview(row, tx.toHex()); await checkReservedInputs(tx, row); const accepted = await call('testmempoolaccept', [[tx.toHex()]]); @@ -486,10 +488,12 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient }, async validateStored(row) { const { capabilities } = await assertNetwork(row.network); - if (typeof row.signed_hex !== 'string' || row.signed_hex.length > 400000 || decode(row.signed_hex).getId() !== row.txid) throw failure('stored_transaction_invalid', 409); + if (typeof row.signed_hex !== 'string' || row.signed_hex.length > MAX_TX_HEX_LENGTH) throw failure('stored_transaction_invalid', 409); + const tx = decode(row.signed_hex); + if (tx.weight() > MAX_STANDARD_WEIGHT || tx.getId() !== row.txid) throw failure('stored_transaction_invalid', 409); // Recheck payout and funding rules when a reorg crosses the preparation boundary. if (capabilities.preparationActive !== true && row.prepared.p2mrActive) await liveReview(row, row.signed_hex); - await checkReservedInputs(decode(row.signed_hex), row); + await checkReservedInputs(tx, row); const accepted = await call('testmempoolaccept', [[row.signed_hex]]); if (!Array.isArray(accepted) || accepted.length !== 1 || !accepted[0].allowed) throw failure('transaction_rejected', 422); }, diff --git a/lib/sentryBodyLimits.js b/lib/sentryBodyLimits.js new file mode 100644 index 0000000..6d7832e --- /dev/null +++ b/lib/sentryBodyLimits.js @@ -0,0 +1,26 @@ +'use strict'; + +const express = require('express'); +const { SENTRY_PREFIXES } = require('./credentialedPaths'); + +const MAX_STANDARD_WEIGHT = 400_000; +const MAX_TX_HEX_LENGTH = 2 * MAX_STANDARD_WEIGHT; +const AUTHORIZATION_JSON_BYTES = MAX_TX_HEX_LENGTH + 64 * 1024; +const defaultJson = express.json({ limit: '256kb' }); + +// The Sentry router parses its own bodies after session, origin and quota checks. +function parseNonSentryJson(req, res, next) { + const path = req.path.toLowerCase(); + if (SENTRY_PREFIXES.some((prefix) => path === prefix || path.startsWith(prefix + '/'))) return next(); + return defaultJson(req, res, next); +} + +function signedPsbtLimit(prepared) { + // Previous transactions and input metadata are already present in the + // PSBT the backend issued. Budget the additional signed bytes separately. + const issuedLength = prepared?.fundingPsbt?.length || 0; + return issuedLength + 4 * Math.ceil(MAX_STANDARD_WEIGHT / 3) + 64 * 1024; +} + +module.exports = { defaultJson, parseNonSentryJson, MAX_STANDARD_WEIGHT, MAX_TX_HEX_LENGTH, + AUTHORIZATION_JSON_BYTES, signedPsbtLimit }; diff --git a/lib/sentryManagement.js b/lib/sentryManagement.js index b8e965f..59bdf52 100644 --- a/lib/sentryManagement.js +++ b/lib/sentryManagement.js @@ -1,4 +1,5 @@ 'use strict'; +const { signedPsbtLimit } = require('./sentryBodyLimits'); const crypto = require('crypto'); @@ -176,6 +177,11 @@ function createSentryManagement({ repository, adapter, now = Date.now }) { if (now() - row.created_at > 15 * 60_000) throw failure('operation_expired', 409); return configured().authorize(row, body.authorization); }, + signedBodyLimit(userId, id) { + const row = repository.read(id, userId); + if (!row) throw failure('operation_not_found', 404); + return signedPsbtLimit(row.prepared) + 1024; + }, async submit(userId, id, body) { strictObject(body, ['signedPsbt']); const row = repository.read(id, userId); diff --git a/routes/sentry.js b/routes/sentry.js index 5d1f13e..4e229d3 100644 --- a/routes/sentry.js +++ b/routes/sentry.js @@ -1,4 +1,5 @@ 'use strict'; +const { defaultJson, AUTHORIZATION_JSON_BYTES } = require('../lib/sentryBodyLimits'); const express = require('express'); function createSentryRouter({ management, sessionMw, csrfMw, limiter, readLimiter, heavyReadLimiter = (_req, _res, next) => next(), frontendUrl }) { const router = express.Router(); @@ -31,15 +32,18 @@ function createSentryRouter({ management, sessionMw, csrfMw, limiter, readLimite }); if (limiter) router.use(limiter); router.get('/nodes', route((req) => management.watches(req.user.id))); - router.post('/nodes', route((req) => management.watch(req.user.id, req.body))); + router.post('/nodes', defaultJson, route((req) => management.watch(req.user.id, req.body))); router.delete('/nodes/:network/:proTxHash', route((req) => { management.unwatch(req.user.id, req.params.network, req.params.proTxHash); return { ok: true }; })); router.get('/operations', route((req) => management.operations(req.user.id))); - router.post('/operations', route((req) => management.prepare(req.user.id, req.body))); - router.post('/operations/:id/authorize', route((req) => management.authorize(req.user.id, req.params.id, req.body))); - router.post('/operations/:id/submit', route((req) => management.submit(req.user.id, req.params.id, req.body))); - router.post('/operations/:id/retry', route((req) => management.retry(req.user.id, req.params.id, req.body))); + router.post('/operations', defaultJson, route((req) => management.prepare(req.user.id, req.body))); + router.post('/operations/:id/authorize', express.json({ limit: AUTHORIZATION_JSON_BYTES }), route((req) => management.authorize(req.user.id, req.params.id, req.body))); + router.post('/operations/:id/submit', (req, res, next) => { + try { return express.json({ limit: management.signedBodyLimit(req.user.id, req.params.id) })(req, res, next); } + catch (error) { return res.status(error.status || 502).json({ error: error.code || 'sentry_unavailable' }); } + }, route((req) => management.submit(req.user.id, req.params.id, req.body))); + router.post('/operations/:id/retry', defaultJson, route((req) => management.retry(req.user.id, req.params.id, req.body))); router.get('/operations/:id', route((req) => management.reconcile(req.user.id, req.params.id))); return router; } diff --git a/server.js b/server.js index 4299d0c..b9acd85 100644 --- a/server.js +++ b/server.js @@ -1,6 +1,6 @@ const express = require('express'); const cors = require('cors'); -const bodyParser = require('body-parser'); +const { parseNonSentryJson } = require('./lib/sentryBodyLimits'); const cookieParser = require('cookie-parser'); const helmet = require('helmet'); @@ -98,7 +98,7 @@ app.set( // Security headers apply everywhere. helmet defaults are safe for JSON APIs. app.use(helmet()); app.use(PRIVACY_PREFIXES, createPrivacyRouter({ index: privacyIndex, relayers: privacyRelayers })); -app.use(bodyParser.json({ limit: '256kb' })); +app.use(parseNonSentryJson); app.use(cookieParser()); // ----------------------------------------------------------------------------- diff --git a/tests/helpers/compressedJsonChild.cjs b/tests/helpers/compressedJsonChild.cjs index 626e039..3e3d1a2 100644 --- a/tests/helpers/compressedJsonChild.cjs +++ b/tests/helpers/compressedJsonChild.cjs @@ -7,7 +7,7 @@ const http = require('node:http'); const { once } = require('node:events'); const { gzipSync, deflateSync } = require('node:zlib'); const express = require('express'); -const bodyParser = require('body-parser'); +const { parseNonSentryJson } = require('../../lib/sentryBodyLimits'); const cookieParser = require('cookie-parser'); const { openDatabase } = require('../../lib/db'); const { createMailer } = require('../../lib/mailer'); @@ -22,7 +22,7 @@ let app; if (mode === 'production') { app = express(); // server.js's production parser, followed by its actual auth route wiring. - app.use(bodyParser.json({ limit: '256kb' })); + app.use(parseNonSentryJson); app.use(cookieParser()); mountAuthAndVault(app, { services: buildServices({ db, secureCookies: false }), mailer, disableRateLimit: true }); } else if (mode === 'standalone') { @@ -35,7 +35,7 @@ if (mode === 'production') { // schedules the final write from the real parser's completion callback, as in // the upstream GHSA regression, without intercepting uncaught exceptions. let afterParse = null; -const parserLayer = app._router.stack.find((layer) => layer.name === 'jsonParser'); +const parserLayer = app._router.stack.find((layer) => layer.handle === parseNonSentryJson); assert(parserLayer, 'real JSON parser is mounted'); const parser = parserLayer.handle; parserLayer.handle = (req, res, next) => parser(req, res, (error) => { diff --git a/tests/sentry.productionComposition.test.js b/tests/sentry.productionComposition.test.js index fbb3158..c1b378f 100644 --- a/tests/sentry.productionComposition.test.js +++ b/tests/sentry.productionComposition.test.js @@ -1,3 +1,4 @@ +const { parseNonSentryJson, AUTHORIZATION_JSON_BYTES, signedPsbtLimit } = require('../lib/sentryBodyLimits'); const express = require('express'); const cookieParser = require('cookie-parser'); const cors = require('cors'); @@ -20,7 +21,7 @@ function mount(disableRateLimit = true) { app = express(); // Match server.js before its shared mount. Deliberately do not add a // global session parser like the old standalone test entrypoint did. - app.use(express.json({ limit: '256kb' })); + app.use(parseNonSentryJson); app.use(cookieParser()); const authCors = cors({ origin: ORIGIN, credentials: true }); const legacyCors = cors({ origin: '*', optionsSuccessStatus: 200 }); @@ -35,7 +36,10 @@ function mount(disableRateLimit = true) { votingContext: async (network, proposalHash, hashes) => ({ chain: { genesisHash: HASH, era: 'legacy-v3' }, now: 1800000000, proposalHash, proposal: { name: 'verified-proposal' }, nodes: hashes.map((proTxHash) => ({ proTxHash })) }), capabilities: async () => ({ version: 1 }), - prepare: async () => ({ request: { operation: 'updateService' } }), + prepare: async () => ({ request: { operation: 'updateService' }, fundingPsbt: 'x'.repeat(2048) }), + authorize: async (_row, auth) => ({ received: auth.transactionHex.length }), + validateSigned: async (_row, signedPsbt) => ({ transactionHex: '00', txid: HASH, fields: { received: signedPsbt.length } }), + broadcast: async () => HASH, }, }); app.get('/govlist', (req, res) => res.json({ attachedUser: !!req.user })); @@ -102,6 +106,24 @@ test.each(['/api/sentry/v1', '/sentry/v1'])('production composition retains orig .send({ ...body, label: 'x'.repeat(256 * 1024) }).expect(413); }); +test.each(['/api/sentry/v1', '/sentry/v1'])('large authorized bodies reach the operation through %s', async (prefix) => { + const post = (path) => request(app).post(prefix + path).set('Cookie', cookie) + .set('Origin', ORIGIN).set('X-CSRF-Token', 'test-csrf'); + const prepared = await post('/operations').send({ network: 'testnet', proTxHash: HASH, + changes: { nevmAddress: `0x${'12'.repeat(20)}` } }).expect(200); + const path = `/operations/${prepared.body.id}`; + const authorization = (size) => ({ authorization: { transactionHex: '0'.repeat(size) } }); + const read = await post(path + '/authorize').send(authorization(800_000)).expect(200); + expect(read.body.received).toBe(800_000); + await post(path + '/authorize').send(authorization(AUTHORIZATION_JSON_BYTES)).expect(413); + const limit = signedPsbtLimit({ fundingPsbt: 'x'.repeat(2048) }); + await post(path + '/submit').send({ signedPsbt: 'x'.repeat(limit + 1024) }).expect(413); + await request(app).post(prefix + path + '/submit').send({ signedPsbt: 'x'.repeat(limit + 1024) }).expect(401); + await post('/operations/unknown/submit').send({ signedPsbt: 'x'.repeat(limit + 1024) }).expect(404); + const sent = await post(path + '/submit').send({ signedPsbt: 'x'.repeat(limit) }).expect(200); + expect(sent.body.status).toBe('submitted'); +}); + test.each(['/api/sentry/v1', '/sentry/v1'])('public context stays readable through %s and siblings do not parse sessions', async (prefix) => { await request(app).get(`${prefix}/context?network=testnet&proTxHash=${HASH}`).expect(200); const publicResponse = await request(app).get('/govlist').set('Cookie', cookie).expect(200); From 6d900ca11a45f9fb52a00059524f9eddb36ba943 Mon Sep 17 00:00:00 2001 From: jagdeep sidhu Date: Wed, 2 Dec 2026 16:16:19 -0700 Subject: [PATCH 12/18] Pin reviewed Sentry and virtual-byte funding dependencies --- .github/workflows/ci.yml | 6 +++--- package-lock.json | 20 ++++++++++---------- package.json | 2 +- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 27beeec..db125c0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: c9217c33412071d02ffe4795dd147cc19e985b58 + ref: bce029a5a45e83a6d729f21b410ced4d89fdc524 path: sdk-review persist-credentials: false @@ -87,7 +87,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: c9217c33412071d02ffe4795dd147cc19e985b58 + ref: bce029a5a45e83a6d729f21b410ced4d89fdc524 path: sdk-review persist-credentials: false - name: Cache reviewed Sentry SDK @@ -127,7 +127,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: c9217c33412071d02ffe4795dd147cc19e985b58 + ref: bce029a5a45e83a6d729f21b410ced4d89fdc524 path: sdk-review persist-credentials: false diff --git a/package-lock.json b/package-lock.json index 837eb47..8d03844 100644 --- a/package-lock.json +++ b/package-lock.json @@ -29,7 +29,7 @@ "numeral": "2.0.6", "papaparse": "^5.5.3", "pretty-ms": "6.0.1", - "syscoinjs-lib": "git+https://github.com/syscoin/syscoinjs-lib.git#cbdc9d05b353d8bbf5246c2dcdfefa99838630af", + "syscoinjs-lib": "git+https://github.com/syscoin/syscoinjs-lib.git#ca3ff40fe4d273ced008302b13f9d29ac3337b26", "websocket": "1.0.34", "zod": "4.6.7" }, @@ -1808,7 +1808,7 @@ "node_modules/@sidhujag/sysweb3-sentry": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/@sidhujag/sysweb3-sentry/-/sysweb3-sentry-0.1.4.tgz", - "integrity": "sha512-77rHJQ3unIpptzjMBtdGm26NW0QqDteVuiUkYspC8aRp+H66E+asL7e6XnSIQRNKdcmT620cHNZBjJ60ZG5svQ==", + "integrity": "sha512-xVccQhygrAtEYlCrJE8s0J4lxszfwYHp6e7/hrkgPjn7XeYndLdL/25LmX5OoZUxGMcnFUsvXyqf39gR7GQwwA==", "license": "MIT", "dependencies": { "@noble/curves": "2.4.0", @@ -3412,8 +3412,8 @@ }, "node_modules/coinselectsyscoin": { "version": "1.1.12", - "resolved": "git+ssh://git@github.com/syscoin/coinselectsyscoin.git#01121ffc5ba45caa00dae96564ace717a94fc06c", - "integrity": "sha512-AHkL0oItW/tCm5H9BY4g/HbizVbiR+01erNJ2O08vhRYBVlrcL1CtNN5YzspS/Hu/xATpOUTUV8p90/ybXCuig==", + "resolved": "git+ssh://git@github.com/syscoin/coinselectsyscoin.git#f2e274841ceabe7928b85089eac6420a99442374", + "integrity": "sha512-lmMkbPqMHUy483Opk1WJRaJpL/v6iBqQpIfhhedfv9WGwKJcgF7fQdnJKjNrPKrtHGqpyZubxWmvDyzzhrElRA==", "license": "MIT", "dependencies": { "bn.js": "^5.2.4" @@ -9346,8 +9346,8 @@ }, "node_modules/syscoinjs-lib": { "version": "2.0.0", - "resolved": "git+ssh://git@github.com/syscoin/syscoinjs-lib.git#cbdc9d05b353d8bbf5246c2dcdfefa99838630af", - "integrity": "sha512-2TMyJ8icTtegmSmmeFyoUIuW/mz4CXk5Z3uzJLxcVtO4v+zIbRrtnoypjDR6TzM18f/sA+eHUxszoLwjE7wzaw==", + "resolved": "git+ssh://git@github.com/syscoin/syscoinjs-lib.git#ca3ff40fe4d273ced008302b13f9d29ac3337b26", + "integrity": "sha512-5/Gm9VXcGRAQ5bTQpfvwZK/IGywuybRxDGXz7/NJkNjuUP7gfHWYjtX8mySp7zEKoGtdYpB9BcMIZ1L2kfuOiQ==", "license": "MIT", "dependencies": { "@bitcoinerlab/secp256k1": "^1.2.0", @@ -9362,21 +9362,21 @@ "eth-object": "https://github.com/syscoin/eth-object.git", "eth-proof": "^2.1.6", "ethers": "^6.17.0", - "syscointx-js": "git+https://github.com/syscoin/syscointx-js.git#56d9469cbd48d18cc9d44d496fb76774f1a2cae6", + "syscointx-js": "git+https://github.com/syscoin/syscointx-js.git#b6bdf6b2a007e31d9a620b6d05ebe887217d1501", "varuint-bitcoin": "^2.0.0" } }, "node_modules/syscointx-js": { "version": "2.0.0", - "resolved": "git+ssh://git@github.com/syscoin/syscointx-js.git#56d9469cbd48d18cc9d44d496fb76774f1a2cae6", - "integrity": "sha512-HJw6LRUzf+4XIjEqj2bmrGNRNe8p4VQMRX49F7f4/4qPSoxGFp/u8Pn1hKo26v6Wlm6q0cXO/9FtjgIu5jbPow==", + "resolved": "git+ssh://git@github.com/syscoin/syscointx-js.git#b6bdf6b2a007e31d9a620b6d05ebe887217d1501", + "integrity": "sha512-8yUG8uvwmjhCRIvhyN5T1M1iX29mkgpWUtCoX7IER3OZCcQ8f21zh6CZACKiFfTt8xJvxoPzQYzwd2Hfa9LhaA==", "license": "MIT", "dependencies": { "@bitcoinerlab/secp256k1": "^1.2.0", "bitcoin-ops": "^1.4.1", "bitcoinjs-lib": "^7.0.5", "bn.js": "^5.2.4", - "coinselectsyscoin": "git+https://github.com/syscoin/coinselectsyscoin.git#01121ffc5ba45caa00dae96564ace717a94fc06c", + "coinselectsyscoin": "git+https://github.com/syscoin/coinselectsyscoin.git#f2e274841ceabe7928b85089eac6420a99442374", "ecpair": "^3.0.1", "typeforce": "^1.18.0", "varuint-bitcoin": "^2.0.0" diff --git a/package.json b/package.json index 79c05df..87da18b 100644 --- a/package.json +++ b/package.json @@ -53,7 +53,7 @@ "numeral": "2.0.6", "papaparse": "^5.5.3", "pretty-ms": "6.0.1", - "syscoinjs-lib": "git+https://github.com/syscoin/syscoinjs-lib.git#cbdc9d05b353d8bbf5246c2dcdfefa99838630af", + "syscoinjs-lib": "git+https://github.com/syscoin/syscoinjs-lib.git#ca3ff40fe4d273ced008302b13f9d29ac3337b26", "websocket": "1.0.34", "zod": "4.6.7" }, From b3af65a791f14217368fa83862bef9212fba0e72 Mon Sep 17 00:00:00 2001 From: jagdeep sidhu Date: Wed, 2 Dec 2026 16:27:57 -0700 Subject: [PATCH 13/18] Return the registered owner commitment for PQ funding votes --- .github/workflows/ci.yml | 6 +++--- lib/sentryAdapter.js | 4 ++-- lib/sentryVotingContext.test.js | 2 +- package-lock.json | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index db125c0..92f2841 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: bce029a5a45e83a6d729f21b410ced4d89fdc524 + ref: efe06e19ff8790bebb3c6d2b64f98cc9d79f899e path: sdk-review persist-credentials: false @@ -87,7 +87,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: bce029a5a45e83a6d729f21b410ced4d89fdc524 + ref: efe06e19ff8790bebb3c6d2b64f98cc9d79f899e path: sdk-review persist-credentials: false - name: Cache reviewed Sentry SDK @@ -127,7 +127,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: bce029a5a45e83a6d729f21b410ced4d89fdc524 + ref: efe06e19ff8790bebb3c6d2b64f98cc9d79f899e path: sdk-review persist-credentials: false diff --git a/lib/sentryAdapter.js b/lib/sentryAdapter.js index e5c4d6b..aa363f2 100644 --- a/lib/sentryAdapter.js +++ b/lib/sentryAdapter.js @@ -127,13 +127,13 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient !Number.isSafeInteger(ownerEnrolledHeight) || ownerEnrolledHeight < 0 || ownerEnrolledHeight > signingBlock.height || !Number.isSafeInteger(state.pqOwnerKeyActivationHeight) || state.pqOwnerKeyActivationHeight < ownerEnrolledHeight || state.pqOwnerKeyActivationHeight > height) throw failure('owner_not_enrolled_at_signing_block', 409); - registeredRoot(state.ownerAddress, state.pqOwnerCommitment); + const ownerCommitment = registeredRoot(state.ownerAddress, state.pqOwnerCommitment); const votingKeyVersion = state.pqVotingKeyVersion; const votingKeyActivatedHeight = state.pqVotingKeyActivationHeight; if (!Number.isSafeInteger(votingKeyVersion) || votingKeyVersion < 1 || votingKeyVersion > 0xffffffff || !Number.isSafeInteger(votingKeyActivatedHeight) || votingKeyActivatedHeight < 0 || votingKeyActivatedHeight > signingBlock.height) throw failure('voting_key_not_active_at_signing_block', 409); - nodes[index] = { ...identity, votingKeyId: registeredRoot(state.votingAddress, state.pqVotingCommitment), votingKeyVersion, votingKeyActivatedHeight, ownerEnrolledHeight }; + nodes[index] = { ...identity, votingKeyId: registeredRoot(state.votingAddress, state.pqVotingCommitment), votingKeyVersion, votingKeyActivatedHeight, ownerEnrolledHeight, ownerCommitment }; } else { nodes[index] = { ...identity, votingKeyId: keyId(state.legacyVotingAddress ?? state.votingAddress) }; } diff --git a/lib/sentryVotingContext.test.js b/lib/sentryVotingContext.test.js index b243921..5253fb5 100644 --- a/lib/sentryVotingContext.test.js +++ b/lib/sentryVotingContext.test.js @@ -87,7 +87,7 @@ test('a PQ vote uses the same active ancestor after a tip extension and refuses Buffer.from('5220' + (address === 'current-owner-address' ? owner : root), 'hex')); const first = await f.adapter.votingContext('testnet', PROPOSAL, [PROTX]); expect(first.signingBlock).toEqual({ height: 94, hash: BLOCK }); - expect(first.nodes[0]).toMatchObject({ votingKeyId: root, votingKeyVersion: 2, votingKeyActivatedHeight: 90, ownerEnrolledHeight: 75 }); + expect(first.nodes[0]).toMatchObject({ votingKeyId: root, votingKeyVersion: 2, votingKeyActivatedHeight: 90, ownerEnrolledHeight: 75, ownerCommitment: owner }); for (const enrollment of [undefined, 95]) { f.node.state.pqOwnerKeyEnrollmentHeight = enrollment; await expect(f.adapter.votingContext('testnet', PROPOSAL, [PROTX])).rejects.toMatchObject({ code: 'owner_not_enrolled_at_signing_block' }); diff --git a/package-lock.json b/package-lock.json index 8d03844..9430b4f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1808,7 +1808,7 @@ "node_modules/@sidhujag/sysweb3-sentry": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/@sidhujag/sysweb3-sentry/-/sysweb3-sentry-0.1.4.tgz", - "integrity": "sha512-xVccQhygrAtEYlCrJE8s0J4lxszfwYHp6e7/hrkgPjn7XeYndLdL/25LmX5OoZUxGMcnFUsvXyqf39gR7GQwwA==", + "integrity": "sha512-gwgmGoZ99LD+nDudgkJixOUmy/k+S95yi0XTdNfZjKrUAJEwhy+WO9etm8oIHOtZ2GezzTz2gkYvms1txhfntw==", "license": "MIT", "dependencies": { "@noble/curves": "2.4.0", From 0af137b9a0639f678fa2fadf1974a9fafd9b8dc3 Mon Sep 17 00:00:00 2001 From: jagdeep sidhu Date: Wed, 2 Dec 2026 21:52:47 -0700 Subject: [PATCH 14/18] Prepare and verify both P2MR collateral registration workflows --- .github/workflows/ci.yml | 6 +- README.md | 15 +++- lib/sentryAdapter.js | 104 +++++++++++++++++++++++---- lib/sentryManagement.js | 27 +++++-- lib/sentryVotingContext.test.js | 4 +- package-lock.json | 2 +- routes/sentry.js | 2 +- tests/sentry-codec.integration.mjs | 109 +++++++++++++++++++++++++++++ 8 files changed, 239 insertions(+), 30 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 92f2841..14a42ce 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: efe06e19ff8790bebb3c6d2b64f98cc9d79f899e + ref: 6232fe3c87869bc0f74170be80a7a5cfd93ee727 path: sdk-review persist-credentials: false @@ -87,7 +87,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: efe06e19ff8790bebb3c6d2b64f98cc9d79f899e + ref: 6232fe3c87869bc0f74170be80a7a5cfd93ee727 path: sdk-review persist-credentials: false - name: Cache reviewed Sentry SDK @@ -127,7 +127,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: efe06e19ff8790bebb3c6d2b64f98cc9d79f899e + ref: 6232fe3c87869bc0f74170be80a7a5cfd93ee727 path: sdk-review persist-credentials: false diff --git a/README.md b/README.md index 60cbb67..a1e52b2 100644 --- a/README.md +++ b/README.md @@ -502,8 +502,19 @@ original transaction first, then revalidates and republishes only the stored signed bytes if needed. A per-operation cooldown and atomic claim bound retries; no new signature, new transaction ID, replacement transaction or fee bump occurs. -At PQ activation, registration accepts P2MR owner and voting addresses. A -wallet can fund a new collateral output by supplying `changes.collateralAddress` +At PQ activation, registration accepts P2MR owner and voting addresses. +For owner-bound collateral, send the confirmed `collateralOutpoint` and +`changes.boundCollateral` with the descriptor's `coldKeyCommitment` and +`bootstrapOwnerRoot`. Pali derives the live owner during approval. The +registration keeps the funded outpoint and collateral height. + +To spend a chosen P2MR payment into new collateral, send `fundingOutpoint`, +`changes.collateralAddress` and `changes.collateralKeyCommitment`. Select +the funding P2MR account in Pali. Its address identifies the funding +coins and receives change. Additional coins from that account cover fees. +The new collateral starts aging in the registration block. + +A wallet can fund a new collateral output by supplying `changes.collateralAddress` instead of `collateralOutpoint`. This form goes directly to fee-input signing after the wallet confirms the selected collateral script and amount. To migrate registered P2WPKH collateral, pass `changes.collateralAddress` and diff --git a/lib/sentryAdapter.js b/lib/sentryAdapter.js index aa363f2..9ef9639 100644 --- a/lib/sentryAdapter.js +++ b/lib/sentryAdapter.js @@ -49,6 +49,21 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient if (/^76a914[0-9a-f]{40}88ac$/.test(value)) return value.slice(6, -4); throw failure('invalid_authority_address'); }; + function authenticatedBoundCollateral(state, coin) { + const coldKeyCommitment = state.boundCollateralKeyCommitment; + const bootstrapOwnerRoot = state.boundCollateralOwnerRoot; + if (coldKeyCommitment === undefined && bootstrapOwnerRoot === undefined) return undefined; + if ([coldKeyCommitment, bootstrapOwnerRoot].some(value => typeof value !== 'string' || !/^(?!0+$)[a-f0-9]{64}$/.test(value))) + throw failure('invalid_collateral', 503); + const root = sdk.boundCollateralP2MRRoot(genesisHash, coldKeyCommitment, bootstrapOwnerRoot); + if (!(coin?.confirmations > 0) || coin.scriptPubKey?.hex !== '5220' + root) throw failure('collateral_commitment_mismatch', 409); + return { coldKeyCommitment, bootstrapOwnerRoot }; + } + function checkRegisteredHeight(state, height) { + // protx_info reads the deterministic list at Core's active tip. The enclosing context rechecks that tip. + if (!Number.isSafeInteger(state.registeredHeight) || state.registeredHeight < 0 || state.registeredHeight > height) + throw failure('node_not_confirmed', 409); + } async function votingContext(requested, proposalHash, proTxHashes, requestedBlock) { const hash = /^[a-f0-9]{64}$/; if (typeof proposalHash !== 'string' || !hash.test(proposalHash) || /^0+$/.test(proposalHash) || !Array.isArray(proTxHashes) || !proTxHashes.length || proTxHashes.length > 20 || @@ -117,8 +132,7 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient !Number.isSafeInteger(node.collateralIndex) || node.collateralIndex < 0 || node.collateralIndex > 0x7fffffff || typeof state.confirmedHash !== 'string' || !hash.test(state.confirmedHash) || /^0+$/.test(state.confirmedHash) || ((pq || state.PoSeBanHeight !== undefined) && state.PoSeBanHeight !== -1)) throw failure('invalid_voting_node', 422); - const registration = await read('getrawtransaction', [proTxHash, true]); - if (!Number.isSafeInteger(registration?.confirmations) || registration.confirmations <= 0) throw failure('node_not_confirmed', 409); + checkRegisteredHeight(state, signingBlock?.height ?? height); const identity = { proTxHash, collateralOutpoint: { txid: node.collateralHash, vout: node.collateralIndex }, valid: true }; if (pq) { const ownerEnrolledHeight = state.pqOwnerKeyEnrollmentHeight; @@ -133,6 +147,10 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient if (!Number.isSafeInteger(votingKeyVersion) || votingKeyVersion < 1 || votingKeyVersion > 0xffffffff || !Number.isSafeInteger(votingKeyActivatedHeight) || votingKeyActivatedHeight < 0 || votingKeyActivatedHeight > signingBlock.height) throw failure('voting_key_not_active_at_signing_block', 409); + if (state.boundCollateralKeyCommitment !== undefined || state.boundCollateralOwnerRoot !== undefined) { + const coin = await read('gettxout', [node.collateralHash, node.collateralIndex, true]); + identity.boundCollateral = authenticatedBoundCollateral(state, coin); + } nodes[index] = { ...identity, votingKeyId: registeredRoot(state.votingAddress, state.pqVotingCommitment), votingKeyVersion, votingKeyActivatedHeight, ownerEnrolledHeight, ownerCommitment }; } else { nodes[index] = { ...identity, votingKeyId: keyId(state.legacyVotingAddress ?? state.votingAddress) }; @@ -151,22 +169,25 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient const p2mrActive = capabilities.preparationActive === true; if (collateral && !proTxHash) { if (!/^[1-9][0-9]*$/.test(capabilities.requiredCollateralSatoshis || '')) throw failure('core_sentry_capabilities_required', 503); + const registrationModes = { + boundCollateralRegistration: chain.era === 'pq-v4' && p2mrActive && capabilities.boundCollateralRegistration === true, + selectedFundingRegistration: chain.era === 'pq-v4' && p2mrActive && capabilities.selectedFundingRegistration === true, + }; if (!Number.isSafeInteger(collateral.vout) || collateral.vout < 0 || collateral.vout > 0xffffffff) throw failure('invalid_collateral'); if (collateral.address) { const approvedCollateralScript = script(collateral.address); if (collateral.txid || chain.era !== 'pq-v4' || !/^5220[0-9a-f]{64}$/.test(approvedCollateralScript)) throw failure('invalid_collateral'); - return { chain, network: networkEncoding, p2mrActive, allowOwnerPreparation: p2mrActive, approvedCollateralScript, registration: { + return { chain, network: networkEncoding, p2mrActive, ...registrationModes, allowOwnerPreparation: p2mrActive, approvedCollateralScript, registration: { collateralVout: collateral.vout, requiredCollateralSatoshis: capabilities.requiredCollateralSatoshis } }; } if (!/^[a-f0-9]{64}$/.test(collateral.txid || '')) throw failure('invalid_collateral'); - const [collateralTransactionHex, coin] = await Promise.all([ - call('getrawtransaction', [collateral.txid, false]), call('gettxout', [collateral.txid, collateral.vout, true]), - ]); + const coin = await call('gettxout', [collateral.txid, collateral.vout, true]); if (!coin || !(coin.confirmations > 0)) throw failure('collateral_not_confirmed_or_spent', 409); const registrations = await call('protx_list', ['registered', true]); if (!Array.isArray(registrations)) throw failure('node_list_unavailable', 503); if (registrations.some((entry) => entry.collateralHash === collateral.txid && entry.collateralIndex === collateral.vout)) throw failure('collateral_already_registered', 409); - return { chain, network: networkEncoding, p2mrActive, allowOwnerPreparation: p2mrActive, registration: { collateralTransactionHex, + const collateralTransactionHex = await readCollateralTransaction(collateral); + return { chain, network: networkEncoding, p2mrActive, ...registrationModes, allowOwnerPreparation: p2mrActive, registration: { collateralTransactionHex, collateralVout: collateral.vout, requiredCollateralSatoshis: capabilities.requiredCollateralSatoshis } }; } const raw = await call('protx_info', [proTxHash]); @@ -174,8 +195,7 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient if (!state || raw.proTxHash !== proTxHash) throw failure('node_not_found', 404); // Preserve explicit unavailable states; management never treats a banned // or not-yet-confirmed node as ready merely because a key was imported. - const registration = await call('getrawtransaction', [proTxHash, true]); - if (!(registration.confirmations > 0)) throw failure('node_not_confirmed', 409); + checkRegisteredHeight(state, capabilities.height); const isPqOwner = state.ownerKeyType === 'slh-dsa'; const isPqVoter = state.pqVotingKeyVersion > 0; const validVersion = (version, height) => Number.isSafeInteger(version) && version > 0 && version <= 0xffffffff && @@ -207,6 +227,8 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient }; if (chain.era === 'pq-v4' || capabilities.preparationActive === true) { const coin = await call('gettxout', [raw.collateralHash, raw.collateralIndex, true]); + const boundCollateral = authenticatedBoundCollateral(state, coin); + if (boundCollateral) node.boundCollateral = boundCollateral; if (coin?.confirmations > 0 && /^0014[a-f0-9]{40}$/.test(coin.scriptPubKey?.hex || '')) node.rolloverCollateralInputScript = 'p2wpkh'; let key; @@ -252,12 +274,14 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient if (typeof node.collateralHash !== 'string' || !/^[0-9a-f]{64}$/.test(node.collateralHash) || !Number.isSafeInteger(node.collateralIndex) || node.collateralIndex < 0 || node.collateralIndex > 0xffffffff) throw failure('invalid_collateral', 503); - const outpoint = { txid: node.collateralHash, vout: node.collateralIndex }; + return { hex: await readCollateralTransaction({ txid: node.collateralHash, vout: node.collateralIndex }) }; + } + async function readCollateralTransaction(outpoint) { // The largest Core transaction fits in 4 MB of bytes plus the JSON-RPC envelope in hex. const raw = await call('getrawtransaction', [outpoint.txid, false], { timeout: 10_000, maxContentLength: 8_001_024 }); const hex = sdk.stripSentryCollateralWitness(raw, outpoint); if (hex.length > 2_000_000) throw failure('collateral_transaction_too_large', 503); - return { hex }; + return hex; } async function signingContext(request, current, previousTransactions) { const result = { ...current, previousTransactions, maxFeeSatoshis }; @@ -266,7 +290,7 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient ? sdk.inspectSentryOwnerDraft(request) : sdk.inspectSentryManagementOperation(request); // A rollover already supplies the registered collateral as a verified input. if (inspection.requiresRegisteredCollateral && !inspection.rollover) - result.registeredCollateralTransactionHex = await call('getrawtransaction', [current.node.collateralOutpoint.txid, false]); + result.registeredCollateralTransactionHex = await readCollateralTransaction(current.node.collateralOutpoint); return result; } const decode = (hex) => bitcoinjs.Transaction.fromHex(hex); @@ -336,6 +360,8 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient return { version: 1, network, chain, preparationActive, ...sdk.getSentryCapabilities(), keyRoles: management.roles, schemes: management.schemes, fundedRegistration: chain.era === 'pq-v4' && preparationActive, collateralRollover: preparationActive, + boundCollateralRegistration: chain.era === 'pq-v4' && preparationActive && capabilities.boundCollateralRegistration === true, + selectedFundingRegistration: chain.era === 'pq-v4' && preparationActive && capabilities.selectedFundingRegistration === true, operations: ['register', 'updateService', 'updateRegistrar', 'revoke', ...(capabilities.preparationActive || chain.era === 'pq-v4' ? ['registerOperator'] : []), ...(chain.era === 'pq-v4' ? ['rotateOperator'] : [])], providers: [{ id: 'self-hosted', name: 'Self-hosted', supported: true }, { id: 'nodehub', name: 'NodeHub', supported: false, reason: 'Provider integration is not configured. Keys remain in Pali.' }] }; }, @@ -349,7 +375,16 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient : await context(body.network, body.proTxHash, rolloverAddress ? { address: rolloverAddress } : undefined); if (current.chain.era === 'pq-v4' && current.node && !current.node.pqOwnerRecord && (operation !== 'updateRegistrar' || !body.changes.ownerAddress)) throw failure('owner_enrollment_required', 409); - _internal.assertXpubMatchesNetwork(body.xpub, network); + if (body.changes.boundCollateral && !current.boundCollateralRegistration) throw failure('operation_not_supported'); + if (body.fundingOutpoint && !current.selectedFundingRegistration) throw failure('operation_not_supported'); + const paymentAccount = typeof body.xpub === 'string' && body.xpub.toLowerCase().startsWith(networkEncoding.bech32Hrp + '1z'); + if (paymentAccount) { + if (!current.p2mrActive || body.xpub !== body.changeAddress || !/^5220[0-9a-f]{64}$/.test(script(body.xpub))) + throw failure('selected_p2mr_account_required'); + } else { + if (body.fundingOutpoint) throw failure('selected_p2mr_account_required'); + _internal.assertXpubMatchesNetwork(body.xpub, network); + } _internal.assertChangeAddress(bitcoinjs, body.changeAddress, fundingClient.network, network); const feeRate = _internal.normalizeFeeRate(body.feeRate); const registrations = await call('protx_list', ['registered', true]); @@ -357,6 +392,13 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient const changes = { ...body.changes }; delete changes.collateralAddress; delete changes.collateralKeyCommitment; + if (body.fundingOutpoint) { + const raw = Buffer.from(body.changes.collateralKeyCommitment, 'hex').reverse().toString('hex'); + if (current.approvedCollateralScript !== '5220' + sdk.sentryCollateralRootFromCommitment(genesisHash, raw) || + current.approvedCollateralScript === script(body.xpub)) throw failure('collateral_commitment_mismatch'); + changes.fundingOutpoint = body.fundingOutpoint; + changes.fundingCollateralKeyCommitment = body.changes.collateralKeyCommitment; + } let rolloverSource; if (rolloverAddress) { const keyCommitment = body.changes.collateralKeyCommitment; @@ -421,7 +463,7 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient const fundedOutput = current.approvedCollateralScript ? { scriptHex: current.approvedCollateralScript, valueSatoshis: rolloverSource?.valueSatoshis ?? current.registration.requiredCollateralSatoshis } : undefined; const placeholder = builder({ ...buildArgs, - inputs: [{ txid: 'ff'.repeat(32), vout: 0 }], outputs: fundedOutput ? [fundedOutput] : [], + inputs: [body.fundingOutpoint || { txid: 'ff'.repeat(32), vout: 0 }], outputs: fundedOutput ? [fundedOutput] : [], }); const payload = decode(placeholder.transactionHex).outs.at(-1).script; if (!fundingClient.fetchUtxos) throw failure('sentry_funding_unavailable', 503); @@ -430,9 +472,24 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient if (!Array.isArray(fundingOutputs) || fundingOutputs.length > 10000) throw failure('invalid_funding_response', 503); const reserved = new Set(registrations.map((entry) => `${entry.collateralHash}:${entry.collateralIndex}`)); if (body.collateralOutpoint) reserved.add(`${body.collateralOutpoint.txid}:${body.collateralOutpoint.vout}`); - const available = fundingOutputs.filter((entry) => !entry.assetInfo && entry.confirmations > 0 && !reserved.has(`${entry.txid || entry.txId}:${entry.vout}`)); + // Blockbook omits the address on its address-scoped UTXO response. + const available = fundingOutputs.filter((entry) => !entry.assetInfo && entry.confirmations > 0 && + (!paymentAccount || !entry.address || entry.address === body.xpub) && !reserved.has(`${entry.txid || entry.txId}:${entry.vout}`)) + .map(entry => paymentAccount && !entry.address ? { ...entry, address: body.xpub } : entry); if (!available.length) throw failure('no_unreserved_fee_funds'); let forcedInputs; + if (body.fundingOutpoint) { + const { txid, vout } = body.fundingOutpoint; + const input = available.find((entry) => (entry.txid || entry.txId) === txid && entry.vout === vout); + if (!input) throw failure('collateral_not_in_selected_wallet', 409); + const [raw, coin] = await Promise.all([call('getrawtransaction', [txid, false]), call('gettxout', [txid, vout, true])]); + const prior = decode(raw); + const output = prior.outs[vout]; + if (prior.getId() !== txid || !output || !(coin?.confirmations > 0) || coin.asset_guid !== undefined || + String(input.value) !== String(output.value) || Buffer.from(output.script).toString('hex') !== script(body.xpub) || + coin.scriptPubKey?.hex !== script(body.xpub)) throw failure('collateral_not_in_selected_wallet', 409); + forcedInputs = [input]; + } if (rolloverSource) { const input = fundingOutputs.find((entry) => (entry.txid || entry.txId) === rolloverSource.txid && entry.vout === rolloverSource.vout); if (!input || input.assetInfo || !(input.confirmations > 0) || String(input.value) !== rolloverSource.valueSatoshis || @@ -446,6 +503,8 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient if (!funded?.psbt) throw failure('funding_failed'); const fundingPsbt = funded.psbt.toBase64(); const unsigned = funded.psbt.__CACHE.__TX; + if (body.fundingOutpoint && unsigned.ins.filter((input) => input.index === body.fundingOutpoint.vout && + Buffer.from(input.hash).reverse().toString('hex') === body.fundingOutpoint.txid).length !== 1) throw failure('selected_funding_missing', 503); const spendOutputs = unsigned.outs.filter((output) => output.script[0] !== 0x6a) .map((output) => ({ valueSatoshis: String(output.value), scriptHex: Buffer.from(output.script).toString('hex') })); if (fundedOutput) { @@ -460,6 +519,15 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient lockTime: unsigned.locktime, }); const previousTransactions = await priorTransactions(decode(request.transactionHex)); + if (paymentAccount) { + const parents = new Map(previousTransactions.map(raw => { const tx = decode(raw); return [tx.getId(), tx]; })); + const accountScript = script(body.xpub); + for (const input of unsigned.ins) { + const id = Buffer.from(input.hash).reverse().toString('hex'); + const output = parents.get(id)?.outs[input.index]; + if (!output || Buffer.from(output.script).toString('hex') !== accountScript) throw failure('collateral_not_in_selected_wallet', 409); + } + } const reviewContext = await signingContext(request, current, previousTransactions); const review = operation === 'updateService' ? sdk.reviewSentryOperation(request, reviewContext) : sdk.isSentryOwnerDraft(request) ? sdk.reviewSentryOwnerDraft(request, reviewContext) @@ -473,6 +541,12 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient const validator = row.prepared.request.operation === 'updateService' ? sdk.validateSentryOperationRequest : sdk.validateSentryManagementRequest; validator({ ...row.prepared.request, transactionHex: authorization?.transactionHex }); const { tx } = await liveReview(row, authorization.transactionHex); + await checkReservedInputs(tx, row); + const selected = row.prepared.request.fundingOutpoint; + if (selected) { + const coin = await call('gettxout', [selected.txid, selected.vout, true]); + if (!(coin?.confirmations > 0)) throw failure('collateral_not_confirmed_or_spent', 409); + } return { psbt: { psbt: psbtFor(tx, row.prepared.fundingPsbt).toBase64(), assets: '[]' }, feeSatoshis: row.prepared.review.feeSatoshis }; }, async validateSigned(row, signedPsbt) { diff --git a/lib/sentryManagement.js b/lib/sentryManagement.js index 59bdf52..9d5e861 100644 --- a/lib/sentryManagement.js +++ b/lib/sentryManagement.js @@ -20,6 +20,14 @@ function nodeIdentity(network, proTxHash) { } return { network, proTxHash }; } +function checkOutpoint(outpoint) { + strictObject(outpoint, ['txid', 'vout']); + if (typeof outpoint.txid !== 'string' || !HASH.test(outpoint.txid) || /^0+$/.test(outpoint.txid) || + !Number.isSafeInteger(outpoint.vout) || outpoint.vout < 0 || outpoint.vout > 0xffffffff) throw failure('invalid_collateral'); +} +function nonzeroHash(value) { + return typeof value === 'string' && HASH.test(value) && !/^0+$/.test(value); +} function createSentryRepository(db, { now = Date.now } = {}) { // Only public node identifiers, exact transaction bytes and operation status // are stored here. Operator/owner/voting secrets never enter this service. @@ -131,11 +139,11 @@ function createSentryManagement({ repository, adapter, now = Date.now }) { repository.unwatch(userId, network, proTxHash); }, async prepare(userId, body) { - strictObject(body, ['operation', 'network', 'proTxHash', 'collateralOutpoint', 'changes', 'xpub', 'changeAddress', 'feeRate']); + strictObject(body, ['operation', 'network', 'proTxHash', 'collateralOutpoint', 'fundingOutpoint', 'changes', 'xpub', 'changeAddress', 'feeRate']); const operation = body.operation || 'updateService'; const allowed = { updateService: ['nevmAddress', 'service', 'operatorPayoutAddress'], - register: ['service', 'ownerAddress', 'votingAddress', 'operatorPublicKey', 'collateralAddress', 'operatorRewardBasisPoints', 'payoutAddress'], + register: ['service', 'ownerAddress', 'votingAddress', 'operatorPublicKey', 'collateralAddress', 'boundCollateral', 'collateralKeyCommitment', 'operatorRewardBasisPoints', 'payoutAddress'], updateRegistrar: ['operatorPublicKey', 'ownerAddress', 'votingAddress', 'payoutAddress', 'collateralAddress', 'collateralKeyCommitment'], revoke: ['reason'], registerOperator: ['operatorPublicKey', 'childKeyCommitment', 'keyVersion', 'ownerAddress'], @@ -144,6 +152,16 @@ function createSentryManagement({ repository, adapter, now = Date.now }) { if (!allowed[operation]) throw failure('operation_not_supported'); strictObject(body.changes, allowed[operation]); const funded = operation === 'register' && Object.hasOwn(body.changes, 'collateralAddress'); + if (Object.hasOwn(body, 'fundingOutpoint')) { + checkOutpoint(body.fundingOutpoint); + if (!funded || !nonzeroHash(body.changes.collateralKeyCommitment)) throw failure('invalid_collateral'); + } else if (operation === 'register' && Object.hasOwn(body.changes, 'collateralKeyCommitment')) throw failure('invalid_collateral'); + if (Object.hasOwn(body.changes, 'boundCollateral')) { + const descriptor = body.changes.boundCollateral; + strictObject(descriptor, ['coldKeyCommitment', 'bootstrapOwnerRoot']); + if (funded || Object.hasOwn(body.changes, 'ownerAddress') || + !nonzeroHash(descriptor.coldKeyCommitment) || !nonzeroHash(descriptor.bootstrapOwnerRoot)) throw failure('invalid_collateral'); + } if (operation === 'updateRegistrar' && (Object.hasOwn(body.changes, 'collateralAddress') || Object.hasOwn(body.changes, 'collateralKeyCommitment')) && (typeof body.changes.collateralAddress !== 'string' || !body.changes.collateralAddress || typeof body.changes.collateralKeyCommitment !== 'string' || !HASH.test(body.changes.collateralKeyCommitment) || /^0+$/.test(body.changes.collateralKeyCommitment))) @@ -151,10 +169,7 @@ function createSentryManagement({ repository, adapter, now = Date.now }) { if (funded && (typeof body.changes.collateralAddress !== 'string' || !body.changes.collateralAddress || body.collateralOutpoint)) throw failure('invalid_collateral'); if (operation !== 'register' && body.collateralOutpoint) throw failure('invalid_collateral'); const { network, proTxHash } = nodeIdentity(body.network, operation === 'register' ? (funded ? '0'.repeat(64) : body.collateralOutpoint?.txid) : body.proTxHash); - if (operation === 'register' && !funded) { - strictObject(body.collateralOutpoint, ['txid', 'vout']); - if (!Number.isSafeInteger(body.collateralOutpoint.vout) || body.collateralOutpoint.vout < 0 || body.collateralOutpoint.vout > 0xffffffff) throw failure('invalid_collateral'); - } + if (operation === 'register' && !funded) checkOutpoint(body.collateralOutpoint); if (!Object.keys(body.changes).length) throw failure('no_changes'); // Omission preserves NEVM. Empty string is an explicit removal only. if (Object.hasOwn(body.changes, 'nevmAddress') && body.changes.nevmAddress !== '' && diff --git a/lib/sentryVotingContext.test.js b/lib/sentryVotingContext.test.js index 5253fb5..eb74122 100644 --- a/lib/sentryVotingContext.test.js +++ b/lib/sentryVotingContext.test.js @@ -12,7 +12,7 @@ function fixture() { const proposal = { Hash: PROPOSAL, ObjectType: 1, fLocalValidity: true, fCachedValid: true, fCachedDelete: false, DataString: payload, DataHex: Buffer.from(payload).toString('hex') }; const node = { proTxHash: PROTX, collateralHash: COLLATERAL, collateralIndex: 1, - state: { votingAddress: 'current-voting-address', confirmedHash: BLOCK } }; + state: { registeredHeight: 1, votingAddress: 'current-voting-address', confirmedHash: BLOCK } }; const capabilities = { version: 1, genesisHash: GENESIS, network: 'test', height: 100, blockHash: BLOCK, era: 'legacy-v3' }; const implementation = async (method, args) => { if (method === 'getblockchaininfo') return { chain: 'test' }; @@ -158,7 +158,7 @@ test('rejects a node substitution, non-keyhash voting script, and pending regist f.rpcCall.mockImplementation(f.implementation); f.fundingClient.bitcoinjs.address.toOutputScript.mockReturnValue(Buffer.from('51', 'hex')); await expect(f.adapter.votingContext('testnet', PROPOSAL, [PROTX])).rejects.toMatchObject({ code: 'invalid_authority_address' }); - f.rpcCall.mockImplementation((method, args) => method === 'getrawtransaction' ? Promise.resolve({ confirmations: 0 }) : f.implementation(method, args)); + f.node.state.registeredHeight = f.capabilities.height + 1; await expect(f.adapter.votingContext('testnet', PROPOSAL, [PROTX])).rejects.toMatchObject({ code: 'node_not_confirmed' }); }); diff --git a/package-lock.json b/package-lock.json index 9430b4f..b33f4cf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1808,7 +1808,7 @@ "node_modules/@sidhujag/sysweb3-sentry": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/@sidhujag/sysweb3-sentry/-/sysweb3-sentry-0.1.4.tgz", - "integrity": "sha512-gwgmGoZ99LD+nDudgkJixOUmy/k+S95yi0XTdNfZjKrUAJEwhy+WO9etm8oIHOtZ2GezzTz2gkYvms1txhfntw==", + "integrity": "sha512-fpT2kwhBN3iSfimIrswYXvdSGVqc8QXhiGPmhZvNJotnUMsJ754vln++aS9/8iDhFCVU8px0MEjro+3D+Febow==", "license": "MIT", "dependencies": { "@noble/curves": "2.4.0", diff --git a/routes/sentry.js b/routes/sentry.js index 4e229d3..6ffab9b 100644 --- a/routes/sentry.js +++ b/routes/sentry.js @@ -13,7 +13,7 @@ function createSentryRouter({ management, sessionMw, csrfMw, limiter, readLimite }; if (readLimiter) router.use(readLimiter); router.get('/capabilities', route(() => management.capabilities())); - router.get('/context', route((req) => { + router.get('/context', (req, res, next) => req.query.collateralTxid ? heavyReadLimiter(req, res, next) : next(), route((req) => { const { network, proTxHash, collateralTxid, collateralAddress, collateralVout } = req.query; return management.context(network, proTxHash, collateralTxid || collateralAddress ? { ...(collateralTxid ? { txid: collateralTxid } : {}), ...(collateralAddress ? { address: collateralAddress } : {}), diff --git a/tests/sentry-codec.integration.mjs b/tests/sentry-codec.integration.mjs index 95aa3e8..ab867e8 100644 --- a/tests/sentry-codec.integration.mjs +++ b/tests/sentry-codec.integration.mjs @@ -53,6 +53,7 @@ async function fixture(era = 'legacy-v3', { preparationActive = false, enrolled if (method === 'getblockhash') return GENESIS; if (method === 'protx_capabilities') return { version: 1, genesisHash: GENESIS, network: 'test', era, height: 10, blockHash: 'ff'.repeat(32), requiredCollateralSatoshis: '1000000', ...deployment }; if (method === 'protx_info') return { proTxHash: PROTX, collateralHash: node.collateralOutpoint.txid, collateralIndex: 0, state: { pubKeyOperator: operator.publicKey, ownerAddress: pqOwner ? sdk.sentryP2MRAddress(ownerRoot, network.bech32) : ownerPayment.address, + registeredHeight: 1, ...(pqOwner ? { ownerKeyType: 'slh-dsa', pqOwnerCommitment: ownerRoot, pqOwnerKeyVersion: 1, pqOwnerKeyActivationHeight: 5, pqOwnerDerivationNonce: '00'.repeat(32) } : {}), votingAddress: payment.address, payoutAddress: node.payoutAddress, operatorPayoutAddress: node.operatorPayoutAddress, PoSeBanHeight: banned ? 10 : -1, confirmedHash: '45'.repeat(32), service: node.service, nevmAddress } }; @@ -97,6 +98,12 @@ test('collateral capabilities follow the preparation flag reported by Core', asy const caps = await f.adapter.capabilities(); assert.equal(caps.fundedRegistration, preparationActive && era === 'pq-v4'); assert.equal(caps.collateralRollover, preparationActive); + for (const name of ['boundCollateralRegistration', 'selectedFundingRegistration']) { + assert.equal(caps[name], false); + f.deployment[name] = true; + assert.equal((await f.adapter.capabilities())[name], preparationActive && era === 'pq-v4'); + delete f.deployment[name]; + } } } }); @@ -242,6 +249,108 @@ test('funded P2MR registration builds a signable fee PSBT with exactly the selec assert.equal(validated.fields.collateralSatoshis, '1000000'); }); +test('pre-funded bound registration approves with the bootstrap owner and signs only fee inputs', async () => { + const f = await fixture('pq-v4', { preparationActive: true }); + f.deployment.boundCollateralRegistration = true; + const cold = sdk.sentryColdKeyCommitment(GENESIS, '53'.repeat(32)); + const root = sdk.boundCollateralP2MRRoot(GENESIS, cold, f.ownerRoot); + f.collateral.outs[0].script = Buffer.from('5220' + root, 'hex'); + // A funding transaction can carry many prior input witnesses. Registration uses its txid and output. + f.collateral.setWitness(0, Array.from({length: 9}, () => Buffer.alloc(7856, 1))); + const outpoint = { txid: f.collateral.getId(), vout: 0 }; + const body = { network: 'testnet', operation: 'register', collateralOutpoint: outpoint, + xpub: 'vpub12345678901234567890', changeAddress: f.payment.address, + changes: { service: '1.2.3.5:18369', payoutAddress: f.payment.address, operatorRewardBasisPoints: 0, + votingAddress: sdk.sentryP2MRAddress('a7'.repeat(32), network.bech32), + boundCollateral: { coldKeyCommitment: cold, bootstrapOwnerRoot: f.ownerRoot } } }; + const prepared = await f.adapter.prepare(body); + assert(sdk.isSentryOwnerDraft(prepared.request)); + const context = { ...await f.adapter.context('testnet', undefined, outpoint), + previousTransactions: [f.previous.toHex()], maxFeeSatoshis: '1000000' }; + const stripped = bitcoinjs.Transaction.fromHex(context.registration.collateralTransactionHex); + assert.equal(stripped.getId(), outpoint.txid); + assert.equal(stripped.hasWitnesses(), false); + const derived = sdk.bindSentryOwnerDraft(prepared.request, context, { pqOwnerOpening: f.pqOwnerKey.publicKey, + pqOwnerCommitment: 'a9'.repeat(32), pqOwnerDerivationNonce: '4d'.repeat(32) }); + const signed = await sdk.signSentryManagementOperation(derived, context, f.pqOwnerKey, 'owner'); + const row = { network: 'testnet', prepared }; + const response = await f.adapter.authorize(row, signed); + const psbt = bitcoinjs.Psbt.fromBase64(response.psbt.psbt, { network }); + assert.equal(psbt.inputCount, 1); + assert.equal(Buffer.from(psbt.txInputs[0].hash).reverse().toString('hex'), f.previous.getId()); + psbt.signAllInputs(f.payer); + psbt.finalizeAllInputs(); + assert.equal((await f.adapter.validateSigned(row, psbt.toBase64())).txid, psbt.extractTransaction().getId()); +}); + +test('selecting confirmed PAYMENT principal forces it into the registration and selects a separate fee input', async () => { + const f = await fixture('pq-v4', { preparationActive: true }); + f.deployment.selectedFundingRegistration = true; + const paymentAddress = sdk.sentryP2MRAddress('c1'.repeat(32), network.bech32); + const paymentScript = Buffer.from('5220' + 'c1'.repeat(32), 'hex'); + const principal = bitcoinjs.Transaction.fromHex(f.previous.toHex()); + principal.outs[0] = { script: paymentScript, value: 1000000n }; + const fee = bitcoinjs.Transaction.fromHex(principal.toHex()); + fee.outs[0].value = 100000n; + const coins = new Map([principal, fee].map(tx => [tx.getId(), tx])); + const rpc = async (method, args) => { + const coin = coins.get(args?.[0]); + if (coin && method === 'getrawtransaction') return coin.toHex(); + if (coin && method === 'gettxout') return { confirmations: 2, scriptPubKey: { hex: paymentScript.toString('hex') } }; + return f.rpcCall(method, args); + }; + const lib = new syscoinjs.SyscoinJSLib(null, undefined, network); + const fundingClient = { ...f.fundingClient, + fetchUtxos: async address => { assert.equal(address, paymentAddress); + return [principal, fee].map(tx => ({ txid: tx.getId(), vout: 0, confirmations: 2, value: String(tx.outs[0].value) })); }, + createTransaction: (options, change, outputs, rate, address, utxos, forced) => + lib.createTransaction(options, change, outputs, rate, address, utxos, undefined, forced), + }; + const adapter = createSentryAdapter({ rpcCall: rpc, network: 'testnet', genesisHash: GENESIS, sdk, fundingClient }); + const cold = sdk.sentryColdKeyCommitment(GENESIS, '37'.repeat(32)); + const root = sdk.sentryCollateralRootFromCommitment(GENESIS, Buffer.from(cold, 'hex').reverse().toString('hex')); + const body = { network: 'testnet', operation: 'register', feeRate: 1, xpub: paymentAddress, changeAddress: paymentAddress, + fundingOutpoint: { txid: principal.getId(), vout: 0 }, + changes: { service: '1.2.3.5:18369', collateralAddress: sdk.sentryP2MRAddress(root, network.bech32), + collateralKeyCommitment: cold, votingAddress: sdk.sentryP2MRAddress('71'.repeat(32), network.bech32), + ownerAddress: sdk.sentryP2MRAddress(f.ownerRoot, network.bech32), payoutAddress: f.payment.address, operatorRewardBasisPoints: 0 } }; + const prepared = await adapter.prepare(body); + assert.deepEqual(prepared.request.fundingOutpoint, body.fundingOutpoint); + const tx = sdk.decodeSentryTransaction(prepared.request.transactionHex); + assert.deepEqual(new Set(tx.inputs.map(input => input.txid)), new Set(coins.keys())); + assert(tx.outputs.some(output => output.scriptHex === '5220' + root && output.valueSatoshis === '1000000')); + const ready = await adapter.authorize({ network: 'testnet', prepared }, prepared.request); + assert.equal(bitcoinjs.Psbt.fromBase64(ready.psbt.psbt, {network}).inputCount, 2); +}); + +test('a PQ vote obtains its collateral key commitment from the confirmed bound output', async () => { + const f = await fixture('pq-v4', { preparationActive: true }); + const cold = sdk.sentryColdKeyCommitment(GENESIS, '22'.repeat(32)); + const bootstrap = '34'.repeat(32), voter = '48'.repeat(32), proposal = '97'.repeat(32); + const root = sdk.boundCollateralP2MRRoot(GENESIS, cold, bootstrap); + const story = JSON.stringify({ type: 1, name: 'payout' }); + let collateralScript = '5220' + root; + const rpc = async (method, args) => { + if (method === 'gobject_get') return { Hash: proposal, ObjectType: 1, fLocalValidity: true, fCachedValid: true, + fCachedDelete: false, DataString: story, DataHex: Buffer.from(story).toString('hex') }; + if (method === 'gettxout') return { confirmations: 2, scriptPubKey: { hex: collateralScript } }; + if (method === 'getblockhash' && args[0] !== 0) return 'ff'.repeat(32); + assert.notEqual(method, 'getrawtransaction', 'votes get registration membership from the active list'); + const result = await f.rpcCall(method, args); + if (method === 'protx_capabilities') result.activationHeight = 1; + if (method === 'protx_info') Object.assign(result.state, { pqOwnerKeyEnrollmentHeight: 1, + votingAddress: sdk.sentryP2MRAddress(voter, network.bech32), pqVotingCommitment: voter, + pqVotingKeyVersion: 1, pqVotingKeyActivationHeight: 1, + boundCollateralKeyCommitment: cold, boundCollateralOwnerRoot: bootstrap }); + return result; + }; + const adapter = createSentryAdapter({ rpcCall: rpc, network: 'testnet', genesisHash: GENESIS, sdk, fundingClient: f.fundingClient }); + const context = await adapter.votingContext('testnet', proposal, [PROTX]); + assert.deepEqual(context.nodes[0].boundCollateral, { coldKeyCommitment: cold, bootstrapOwnerRoot: bootstrap }); + collateralScript = '5220' + voter; + await assert.rejects(adapter.votingContext('testnet', proposal, [PROTX]), { code: 'collateral_commitment_mismatch' }); +}); + test('collateral rollover enforces old P2WPKH input, public target, equal principal, and wallet-bound owner opening', async () => { const f = await fixture('pq-v4', { preparationActive: true, pqOwner: true }); const commitment = '1345' + '32'.repeat(30); From d1fc22919c45e56632d5725285c5577cd09bddf9 Mon Sep 17 00:00:00 2001 From: jagdeep sidhu Date: Wed, 2 Dec 2026 22:07:43 -0700 Subject: [PATCH 15/18] Pin the Sentry SDK cold-key signing guard --- .github/workflows/ci.yml | 6 +++--- package-lock.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 14a42ce..657a91e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: 6232fe3c87869bc0f74170be80a7a5cfd93ee727 + ref: 2fcc0ca521074b9da2fb441d6b35462a3fafd90e path: sdk-review persist-credentials: false @@ -87,7 +87,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: 6232fe3c87869bc0f74170be80a7a5cfd93ee727 + ref: 2fcc0ca521074b9da2fb441d6b35462a3fafd90e path: sdk-review persist-credentials: false - name: Cache reviewed Sentry SDK @@ -127,7 +127,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: 6232fe3c87869bc0f74170be80a7a5cfd93ee727 + ref: 2fcc0ca521074b9da2fb441d6b35462a3fafd90e path: sdk-review persist-credentials: false diff --git a/package-lock.json b/package-lock.json index b33f4cf..0f99c65 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1808,7 +1808,7 @@ "node_modules/@sidhujag/sysweb3-sentry": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/@sidhujag/sysweb3-sentry/-/sysweb3-sentry-0.1.4.tgz", - "integrity": "sha512-fpT2kwhBN3iSfimIrswYXvdSGVqc8QXhiGPmhZvNJotnUMsJ754vln++aS9/8iDhFCVU8px0MEjro+3D+Febow==", + "integrity": "sha512-3adgua5SL48YIAFi8ijtqHVFT0AwQxKS/a6CuCUqSJC9e+Q9IGHbbCn4QGQ+bPsdSX1FkOFySetHvnopieK6Wg==", "license": "MIT", "dependencies": { "@noble/curves": "2.4.0", From 672bd47a7ff87abe71358910174ed1180e3e9938 Mon Sep 17 00:00:00 2001 From: jagdeep sidhu Date: Wed, 2 Dec 2026 22:43:16 -0700 Subject: [PATCH 16/18] Pin the same reviewed registration SDK as Pali --- .github/workflows/ci.yml | 6 +++--- package-lock.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 657a91e..3e7d477 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: 2fcc0ca521074b9da2fb441d6b35462a3fafd90e + ref: 0ecddf4adf8a6d21a57f03e72306a45f633738bb path: sdk-review persist-credentials: false @@ -87,7 +87,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: 2fcc0ca521074b9da2fb441d6b35462a3fafd90e + ref: 0ecddf4adf8a6d21a57f03e72306a45f633738bb path: sdk-review persist-credentials: false - name: Cache reviewed Sentry SDK @@ -127,7 +127,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: 2fcc0ca521074b9da2fb441d6b35462a3fafd90e + ref: 0ecddf4adf8a6d21a57f03e72306a45f633738bb path: sdk-review persist-credentials: false diff --git a/package-lock.json b/package-lock.json index 0f99c65..8577af5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1808,7 +1808,7 @@ "node_modules/@sidhujag/sysweb3-sentry": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/@sidhujag/sysweb3-sentry/-/sysweb3-sentry-0.1.4.tgz", - "integrity": "sha512-3adgua5SL48YIAFi8ijtqHVFT0AwQxKS/a6CuCUqSJC9e+Q9IGHbbCn4QGQ+bPsdSX1FkOFySetHvnopieK6Wg==", + "integrity": "sha512-Wo6/XQeh26HDUq7VwOeUvg+1ko6tmrTzIUdeghcMCCW+ttpEXh1RkZXPFdx6LqOrNkTBuh6qCY2N3LrWGiXMAw==", "license": "MIT", "dependencies": { "@noble/curves": "2.4.0", From 8b992e1c4851720ae9ac2234d4b1d0482e13bb28 Mon Sep 17 00:00:00 2001 From: jagdeep sidhu Date: Wed, 2 Dec 2026 23:08:23 -0700 Subject: [PATCH 17/18] Require the cold policy for all funded Sentry registrations --- .github/workflows/ci.yml | 6 ++--- README.md | 7 ++--- lib/sentryAdapter.js | 43 +++++++++++++++++------------- lib/sentryManagement.js | 6 +++-- package-lock.json | 2 +- tests/sentry-codec.integration.mjs | 38 ++++++++++++++++++++++---- 6 files changed, 70 insertions(+), 32 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3e7d477..b101b1c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: 0ecddf4adf8a6d21a57f03e72306a45f633738bb + ref: db299e9ddcbd6931dc409e102737ade305a84bbd path: sdk-review persist-credentials: false @@ -87,7 +87,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: 0ecddf4adf8a6d21a57f03e72306a45f633738bb + ref: db299e9ddcbd6931dc409e102737ade305a84bbd path: sdk-review persist-credentials: false - name: Cache reviewed Sentry SDK @@ -127,7 +127,7 @@ jobs: uses: actions/checkout@v4 with: repository: sidhujag/sysweb3 - ref: 0ecddf4adf8a6d21a57f03e72306a45f633738bb + ref: db299e9ddcbd6931dc409e102737ade305a84bbd path: sdk-review persist-credentials: false diff --git a/README.md b/README.md index a1e52b2..5310960 100644 --- a/README.md +++ b/README.md @@ -514,9 +514,10 @@ the funding P2MR account in Pali. Its address identifies the funding coins and receives change. Additional coins from that account cover fees. The new collateral starts aging in the registration block. -A wallet can fund a new collateral output by supplying `changes.collateralAddress` -instead of `collateralOutpoint`. This form goes directly to fee-input signing -after the wallet confirms the selected collateral script and amount. To migrate +A wallet can also let coin selection fund the new output. Supply +`changes.collateralAddress` and the descriptor’s `changes.collateralKeyCommitment` +in Core RPC hex order. Pali checks that the new output has the cold spending +policy and the required collateral amount before signing the funding inputs. To migrate registered P2WPKH collateral, pass `changes.collateralAddress` and `changes.collateralKeyCommitment` (Core RPC hex order) on an `updateRegistrar`. The selected wallet must control the old collateral input and fund the fee diff --git a/lib/sentryAdapter.js b/lib/sentryAdapter.js index 9ef9639..3d7482b 100644 --- a/lib/sentryAdapter.js +++ b/lib/sentryAdapter.js @@ -164,20 +164,24 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient try { return await Promise.race([observe(), deadline]); } finally { clearTimeout(timeout); controller.abort(); } } + function registrationModes(chain, capabilities) { + const active = chain.era === 'pq-v4' && capabilities.preparationActive === true; + const fundedRegistration = active && capabilities.fundedRegistration === true; + return { fundedRegistration, + boundCollateralRegistration: active && capabilities.boundCollateralRegistration === true, + selectedFundingRegistration: fundedRegistration && capabilities.selectedFundingRegistration === true }; + } async function context(requested, proTxHash, collateral) { const { chain, capabilities } = await assertNetwork(requested); const p2mrActive = capabilities.preparationActive === true; if (collateral && !proTxHash) { if (!/^[1-9][0-9]*$/.test(capabilities.requiredCollateralSatoshis || '')) throw failure('core_sentry_capabilities_required', 503); - const registrationModes = { - boundCollateralRegistration: chain.era === 'pq-v4' && p2mrActive && capabilities.boundCollateralRegistration === true, - selectedFundingRegistration: chain.era === 'pq-v4' && p2mrActive && capabilities.selectedFundingRegistration === true, - }; + const modes = registrationModes(chain, capabilities); if (!Number.isSafeInteger(collateral.vout) || collateral.vout < 0 || collateral.vout > 0xffffffff) throw failure('invalid_collateral'); if (collateral.address) { const approvedCollateralScript = script(collateral.address); if (collateral.txid || chain.era !== 'pq-v4' || !/^5220[0-9a-f]{64}$/.test(approvedCollateralScript)) throw failure('invalid_collateral'); - return { chain, network: networkEncoding, p2mrActive, ...registrationModes, allowOwnerPreparation: p2mrActive, approvedCollateralScript, registration: { + return { chain, network: networkEncoding, p2mrActive, ...modes, allowOwnerPreparation: p2mrActive, approvedCollateralScript, registration: { collateralVout: collateral.vout, requiredCollateralSatoshis: capabilities.requiredCollateralSatoshis } }; } if (!/^[a-f0-9]{64}$/.test(collateral.txid || '')) throw failure('invalid_collateral'); @@ -187,7 +191,7 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient if (!Array.isArray(registrations)) throw failure('node_list_unavailable', 503); if (registrations.some((entry) => entry.collateralHash === collateral.txid && entry.collateralIndex === collateral.vout)) throw failure('collateral_already_registered', 409); const collateralTransactionHex = await readCollateralTransaction(collateral); - return { chain, network: networkEncoding, p2mrActive, ...registrationModes, allowOwnerPreparation: p2mrActive, registration: { collateralTransactionHex, + return { chain, network: networkEncoding, p2mrActive, ...modes, allowOwnerPreparation: p2mrActive, registration: { collateralTransactionHex, collateralVout: collateral.vout, requiredCollateralSatoshis: capabilities.requiredCollateralSatoshis } }; } const raw = await call('protx_info', [proTxHash]); @@ -317,6 +321,8 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient const current = row.prepared.collateralOutpoint ? await context(row.network, undefined, row.prepared.collateralOutpoint) : await context(row.network, row.protx_hash, row.prepared.rolloverAddress ? { address: row.prepared.rolloverAddress } : undefined); + if (row.prepared.collateralOutpoint?.address && !current.fundedRegistration) throw failure('operation_not_supported'); + if (row.prepared.request.fundingOutpoint && !current.selectedFundingRegistration) throw failure('operation_not_supported'); const anchor = ({ chain, node, registration, approvedCollateralScript }) => ({ chain, ...(node ? { node } : {}), ...(registration ? { registration } : {}), ...(approvedCollateralScript ? { approvedCollateralScript } : {}) }); if (JSON.stringify(anchor(current)) !== JSON.stringify(row.prepared.anchor)) throw failure('node_state_changed', 409); @@ -359,9 +365,7 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient const preparationActive = capabilities.preparationActive === true; return { version: 1, network, chain, preparationActive, ...sdk.getSentryCapabilities(), keyRoles: management.roles, schemes: management.schemes, - fundedRegistration: chain.era === 'pq-v4' && preparationActive, collateralRollover: preparationActive, - boundCollateralRegistration: chain.era === 'pq-v4' && preparationActive && capabilities.boundCollateralRegistration === true, - selectedFundingRegistration: chain.era === 'pq-v4' && preparationActive && capabilities.selectedFundingRegistration === true, + ...registrationModes(chain, capabilities), collateralRollover: preparationActive, operations: ['register', 'updateService', 'updateRegistrar', 'revoke', ...(capabilities.preparationActive || chain.era === 'pq-v4' ? ['registerOperator'] : []), ...(chain.era === 'pq-v4' ? ['rotateOperator'] : [])], providers: [{ id: 'self-hosted', name: 'Self-hosted', supported: true }, { id: 'nodehub', name: 'NodeHub', supported: false, reason: 'Provider integration is not configured. Keys remain in Pali.' }] }; }, @@ -376,6 +380,7 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient if (current.chain.era === 'pq-v4' && current.node && !current.node.pqOwnerRecord && (operation !== 'updateRegistrar' || !body.changes.ownerAddress)) throw failure('owner_enrollment_required', 409); if (body.changes.boundCollateral && !current.boundCollateralRegistration) throw failure('operation_not_supported'); + if (fundedAddress && !current.fundedRegistration) throw failure('operation_not_supported'); if (body.fundingOutpoint && !current.selectedFundingRegistration) throw failure('operation_not_supported'); const paymentAccount = typeof body.xpub === 'string' && body.xpub.toLowerCase().startsWith(networkEncoding.bech32Hrp + '1z'); if (paymentAccount) { @@ -392,18 +397,20 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient const changes = { ...body.changes }; delete changes.collateralAddress; delete changes.collateralKeyCommitment; - if (body.fundingOutpoint) { - const raw = Buffer.from(body.changes.collateralKeyCommitment, 'hex').reverse().toString('hex'); - if (current.approvedCollateralScript !== '5220' + sdk.sentryCollateralRootFromCommitment(genesisHash, raw) || - current.approvedCollateralScript === script(body.xpub)) throw failure('collateral_commitment_mismatch'); - changes.fundingOutpoint = body.fundingOutpoint; - changes.fundingCollateralKeyCommitment = body.changes.collateralKeyCommitment; + const keyCommitment = body.changes.collateralKeyCommitment; + if (fundedAddress || rolloverAddress) { + if (typeof keyCommitment !== 'string' || !/^(?!0+$)[0-9a-f]{64}$/.test(keyCommitment)) throw failure('invalid_collateral'); + const raw = Buffer.from(keyCommitment, 'hex').reverse().toString('hex'); + if (current.approvedCollateralScript !== '5220' + sdk.sentryCollateralRootFromCommitment(genesisHash, raw)) + throw failure('collateral_commitment_mismatch'); + } + if (fundedAddress) { + if (paymentAccount && current.approvedCollateralScript === script(body.xpub)) throw failure('collateral_commitment_mismatch'); + changes.fundingCollateralKeyCommitment = keyCommitment; + if (body.fundingOutpoint) changes.fundingOutpoint = body.fundingOutpoint; } let rolloverSource; if (rolloverAddress) { - const keyCommitment = body.changes.collateralKeyCommitment; - const root = sdk.sentryCollateralRootFromCommitment(genesisHash, Buffer.from(keyCommitment, 'hex').reverse().toString('hex')); - if (current.approvedCollateralScript !== '5220' + root) throw failure('collateral_commitment_mismatch'); const old = current.node.collateralOutpoint; if (!registrations.some((entry) => entry.proTxHash === body.proTxHash && entry.collateralHash === old.txid && entry.collateralIndex === old.vout)) throw failure('node_state_changed', 409); diff --git a/lib/sentryManagement.js b/lib/sentryManagement.js index 9d5e861..ea9c553 100644 --- a/lib/sentryManagement.js +++ b/lib/sentryManagement.js @@ -154,8 +154,10 @@ function createSentryManagement({ repository, adapter, now = Date.now }) { const funded = operation === 'register' && Object.hasOwn(body.changes, 'collateralAddress'); if (Object.hasOwn(body, 'fundingOutpoint')) { checkOutpoint(body.fundingOutpoint); - if (!funded || !nonzeroHash(body.changes.collateralKeyCommitment)) throw failure('invalid_collateral'); - } else if (operation === 'register' && Object.hasOwn(body.changes, 'collateralKeyCommitment')) throw failure('invalid_collateral'); + if (!funded) throw failure('invalid_collateral'); + } + if (operation === 'register' && (funded ? !nonzeroHash(body.changes.collateralKeyCommitment) + : Object.hasOwn(body.changes, 'collateralKeyCommitment'))) throw failure('invalid_collateral'); if (Object.hasOwn(body.changes, 'boundCollateral')) { const descriptor = body.changes.boundCollateral; strictObject(descriptor, ['coldKeyCommitment', 'bootstrapOwnerRoot']); diff --git a/package-lock.json b/package-lock.json index 8577af5..f6a19e0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1808,7 +1808,7 @@ "node_modules/@sidhujag/sysweb3-sentry": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/@sidhujag/sysweb3-sentry/-/sysweb3-sentry-0.1.4.tgz", - "integrity": "sha512-Wo6/XQeh26HDUq7VwOeUvg+1ko6tmrTzIUdeghcMCCW+ttpEXh1RkZXPFdx6LqOrNkTBuh6qCY2N3LrWGiXMAw==", + "integrity": "sha512-njhRy0f6N9IUCTF5DvgKxyXQq4d5IgDLuY1AzU1fkBDtYWKXyXTUwm24Ny0jHb5lRuw3ovDqpBbW5QT3HOX+1w==", "license": "MIT", "dependencies": { "@noble/curves": "2.4.0", diff --git a/tests/sentry-codec.integration.mjs b/tests/sentry-codec.integration.mjs index ab867e8..b627ba7 100644 --- a/tests/sentry-codec.integration.mjs +++ b/tests/sentry-codec.integration.mjs @@ -96,7 +96,12 @@ test('collateral capabilities follow the preparation flag reported by Core', asy for (const preparationActive of [false, true]) { f.deployment.preparationActive = preparationActive; const caps = await f.adapter.capabilities(); - assert.equal(caps.fundedRegistration, preparationActive && era === 'pq-v4'); + assert.equal(caps.fundedRegistration, false); + f.deployment.selectedFundingRegistration = true; + assert.equal((await f.adapter.capabilities()).selectedFundingRegistration, false); + delete f.deployment.selectedFundingRegistration; + f.deployment.fundedRegistration = true; + assert.equal((await f.adapter.capabilities()).fundedRegistration, preparationActive && era === 'pq-v4'); assert.equal(caps.collateralRollover, preparationActive); for (const name of ['boundCollateralRegistration', 'selectedFundingRegistration']) { assert.equal(caps[name], false); @@ -104,6 +109,7 @@ test('collateral capabilities follow the preparation flag reported by Core', asy assert.equal((await f.adapter.capabilities())[name], preparationActive && era === 'pq-v4'); delete f.deployment[name]; } + delete f.deployment.fundedRegistration; } } }); @@ -231,21 +237,42 @@ test('after activation the existing ECDSA owner can enroll the first P2MR owner await f.adapter.authorize({ network: 'testnet', protx_hash: PROTX, prepared }, signed); }); -test('funded P2MR registration builds a signable fee PSBT with exactly the selected collateral', async () => { +test('ordinary funded registration proves the cold policy before signing the fee PSBT', async () => { const f = await fixture('pq-v4', { preparationActive: true, feeFunds: 2100000n }); const roleAddress = (role, key) => sdk.sentryP2MRAddress(sdk.sentryP2MRRoot(GENESIS, role, key), network.bech32); const collateralAddress = roleAddress('collateral', '37'.repeat(32)); - const prepared = await f.adapter.prepare({ network: 'testnet', operation: 'register', changes: { - service: '1.2.3.5:18369', collateralAddress, ownerAddress: roleAddress('owner', '24'.repeat(32)), + const cold = sdk.sentryColdKeyCommitment(GENESIS, '37'.repeat(32)); + const body = { network: 'testnet', operation: 'register', changes: { + service: '1.2.3.5:18369', collateralAddress, collateralKeyCommitment: cold, ownerAddress: roleAddress('owner', '24'.repeat(32)), votingAddress: roleAddress('voting', '4a'.repeat(32)), payoutAddress: f.payment.address, operatorRewardBasisPoints: 0, - }, xpub: 'vpub12345678901234567890', changeAddress: f.payment.address }); + }, xpub: 'vpub12345678901234567890', changeAddress: f.payment.address }; + await assert.rejects(f.adapter.prepare(body), { code: 'operation_not_supported' }); + f.deployment.fundedRegistration = true; + const management = createSentryManagement({ adapter: f.adapter, repository: { + create: (_userId, _network, _node, prepared) => prepared, + } }); + const { collateralKeyCommitment, ...withoutCommitment } = body.changes; + await assert.rejects(management.prepare(1, { ...body, changes: withoutCommitment }), { code: 'invalid_collateral' }); + await assert.rejects(f.adapter.prepare({ ...body, changes: withoutCommitment }), { code: 'invalid_collateral' }); + const boundRoot = sdk.boundCollateralP2MRRoot(GENESIS, cold, f.ownerRoot); + for (const changes of [ + { ...body.changes, collateralAddress: sdk.sentryP2MRAddress(boundRoot, network.bech32) }, + { ...body.changes, collateralKeyCommitment: '53'.repeat(32) }, + ]) { + await assert.rejects(f.adapter.prepare({ ...body, changes }), { code: 'collateral_commitment_mismatch' }); + } + const prepared = await management.prepare(1, body); assert.equal(prepared.review.authorizations.length, 0); const row = { network: 'testnet', prepared }; + delete f.deployment.fundedRegistration; + await assert.rejects(f.adapter.authorize(row, prepared.request), { code: 'operation_not_supported' }); + f.deployment.fundedRegistration = true; const { psbt } = await f.adapter.authorize(row, prepared.request); const signed = bitcoinjs.Psbt.fromBase64(psbt.psbt, { network }); signed.signAllInputs(f.payer); signed.finalizeAllInputs(); const validated = await f.adapter.validateSigned(row, signed.toBase64()); assert.equal(validated.fields.collateralAddress, collateralAddress); + assert.equal(validated.fields.fundingCollateralKeyCommitment, collateralKeyCommitment); assert.equal(validated.fields.collateralSatoshis, '1000000'); }); @@ -285,6 +312,7 @@ test('pre-funded bound registration approves with the bootstrap owner and signs test('selecting confirmed PAYMENT principal forces it into the registration and selects a separate fee input', async () => { const f = await fixture('pq-v4', { preparationActive: true }); + f.deployment.fundedRegistration = true; f.deployment.selectedFundingRegistration = true; const paymentAddress = sdk.sentryP2MRAddress('c1'.repeat(32), network.bech32); const paymentScript = Buffer.from('5220' + 'c1'.repeat(32), 'hex'); From b2620086d2cd01abdaad2ac6bc16b0d2a6798d9b Mon Sep 17 00:00:00 2001 From: jagdeep sidhu Date: Wed, 2 Dec 2026 23:14:35 -0700 Subject: [PATCH 18/18] Recheck live registration capabilities before retrying stored transactions --- lib/sentryAdapter.js | 16 ++++++++++------ tests/sentry-codec.integration.mjs | 15 ++++++++++++++- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/lib/sentryAdapter.js b/lib/sentryAdapter.js index 3d7482b..75134a1 100644 --- a/lib/sentryAdapter.js +++ b/lib/sentryAdapter.js @@ -171,6 +171,11 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient boundCollateralRegistration: active && capabilities.boundCollateralRegistration === true, selectedFundingRegistration: fundedRegistration && capabilities.selectedFundingRegistration === true }; } + function requireRegistrationModes(modes, fundedAddress, fundingOutpoint, bootstrapOwnerRoot) { + if ((fundedAddress && !modes.fundedRegistration) || + (fundingOutpoint && !modes.selectedFundingRegistration) || + (bootstrapOwnerRoot && !modes.boundCollateralRegistration)) throw failure('operation_not_supported'); + } async function context(requested, proTxHash, collateral) { const { chain, capabilities } = await assertNetwork(requested); const p2mrActive = capabilities.preparationActive === true; @@ -321,8 +326,7 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient const current = row.prepared.collateralOutpoint ? await context(row.network, undefined, row.prepared.collateralOutpoint) : await context(row.network, row.protx_hash, row.prepared.rolloverAddress ? { address: row.prepared.rolloverAddress } : undefined); - if (row.prepared.collateralOutpoint?.address && !current.fundedRegistration) throw failure('operation_not_supported'); - if (row.prepared.request.fundingOutpoint && !current.selectedFundingRegistration) throw failure('operation_not_supported'); + requireRegistrationModes(current, row.prepared.collateralOutpoint?.address, row.prepared.request.fundingOutpoint, row.prepared.request.bootstrapOwnerRoot); const anchor = ({ chain, node, registration, approvedCollateralScript }) => ({ chain, ...(node ? { node } : {}), ...(registration ? { registration } : {}), ...(approvedCollateralScript ? { approvedCollateralScript } : {}) }); if (JSON.stringify(anchor(current)) !== JSON.stringify(row.prepared.anchor)) throw failure('node_state_changed', 409); @@ -379,9 +383,7 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient : await context(body.network, body.proTxHash, rolloverAddress ? { address: rolloverAddress } : undefined); if (current.chain.era === 'pq-v4' && current.node && !current.node.pqOwnerRecord && (operation !== 'updateRegistrar' || !body.changes.ownerAddress)) throw failure('owner_enrollment_required', 409); - if (body.changes.boundCollateral && !current.boundCollateralRegistration) throw failure('operation_not_supported'); - if (fundedAddress && !current.fundedRegistration) throw failure('operation_not_supported'); - if (body.fundingOutpoint && !current.selectedFundingRegistration) throw failure('operation_not_supported'); + requireRegistrationModes(current, fundedAddress, body.fundingOutpoint, body.changes.boundCollateral?.bootstrapOwnerRoot); const paymentAccount = typeof body.xpub === 'string' && body.xpub.toLowerCase().startsWith(networkEncoding.bech32Hrp + '1z'); if (paymentAccount) { if (!current.p2mrActive || body.xpub !== body.changeAddress || !/^5220[0-9a-f]{64}$/.test(script(body.xpub))) @@ -568,10 +570,12 @@ function createSentryAdapter({ rpcCall, network, genesisHash, sdk, fundingClient return { transactionHex: tx.toHex(), txid: tx.getId(), fields }; }, async validateStored(row) { - const { capabilities } = await assertNetwork(row.network); + const { chain, capabilities } = await assertNetwork(row.network); if (typeof row.signed_hex !== 'string' || row.signed_hex.length > MAX_TX_HEX_LENGTH) throw failure('stored_transaction_invalid', 409); const tx = decode(row.signed_hex); if (tx.weight() > MAX_STANDARD_WEIGHT || tx.getId() !== row.txid) throw failure('stored_transaction_invalid', 409); + requireRegistrationModes(registrationModes(chain, capabilities), row.prepared.collateralOutpoint?.address, + row.prepared.request.fundingOutpoint, row.prepared.request.bootstrapOwnerRoot); // Recheck payout and funding rules when a reorg crosses the preparation boundary. if (capabilities.preparationActive !== true && row.prepared.p2mrActive) await liveReview(row, row.signed_hex); await checkReservedInputs(tx, row); diff --git a/tests/sentry-codec.integration.mjs b/tests/sentry-codec.integration.mjs index b627ba7..91ed548 100644 --- a/tests/sentry-codec.integration.mjs +++ b/tests/sentry-codec.integration.mjs @@ -274,6 +274,12 @@ test('ordinary funded registration proves the cold policy before signing the fee assert.equal(validated.fields.collateralAddress, collateralAddress); assert.equal(validated.fields.fundingCollateralKeyCommitment, collateralKeyCommitment); assert.equal(validated.fields.collateralSatoshis, '1000000'); + const stored = { ...row, signed_hex: validated.transactionHex, txid: validated.txid }; + await f.adapter.validateStored(stored); + delete f.deployment.fundedRegistration; + const admissionCalls = f.rpcCalls.filter(({ method }) => method === 'testmempoolaccept').length; + await assert.rejects(f.adapter.validateStored(stored), { code: 'operation_not_supported' }); + assert.equal(f.rpcCalls.filter(({ method }) => method === 'testmempoolaccept').length, admissionCalls); }); test('pre-funded bound registration approves with the bootstrap owner and signs only fee inputs', async () => { @@ -307,7 +313,10 @@ test('pre-funded bound registration approves with the bootstrap owner and signs assert.equal(Buffer.from(psbt.txInputs[0].hash).reverse().toString('hex'), f.previous.getId()); psbt.signAllInputs(f.payer); psbt.finalizeAllInputs(); - assert.equal((await f.adapter.validateSigned(row, psbt.toBase64())).txid, psbt.extractTransaction().getId()); + const tx = psbt.extractTransaction(); + assert.equal((await f.adapter.validateSigned(row, psbt.toBase64())).txid, tx.getId()); + delete f.deployment.boundCollateralRegistration; + await assert.rejects(f.adapter.validateStored({ ...row, signed_hex: tx.toHex(), txid: tx.getId() }), { code: 'operation_not_supported' }); }); test('selecting confirmed PAYMENT principal forces it into the registration and selects a separate fee input', async () => { @@ -349,6 +358,10 @@ test('selecting confirmed PAYMENT principal forces it into the registration and assert(tx.outputs.some(output => output.scriptHex === '5220' + root && output.valueSatoshis === '1000000')); const ready = await adapter.authorize({ network: 'testnet', prepared }, prepared.request); assert.equal(bitcoinjs.Psbt.fromBase64(ready.psbt.psbt, {network}).inputCount, 2); + delete f.deployment.selectedFundingRegistration; + const registration = bitcoinjs.Transaction.fromHex(prepared.request.transactionHex); + await assert.rejects(adapter.validateStored({ network: 'testnet', prepared, signed_hex: registration.toHex(), txid: registration.getId() }), + { code: 'operation_not_supported' }); }); test('a PQ vote obtains its collateral key commitment from the confirmed bound output', async () => {