From fb2ba1eee953c84b05fb283fb583d7345c4cdaf5 Mon Sep 17 00:00:00 2001 From: David Kaplan Date: Fri, 4 Dec 2026 12:34:27 -0500 Subject: [PATCH] feat: verify CoinCover safe-root issuance proofs Add the shared verifier for the CoinCover root proof (guide v1.1 section 6), so the SDK can check an issued backup root itself instead of trusting wallet-platform. - verifyCoinCoverSafeRootProof: checks the signed field set, key id, enterprise and safe, the base64 DER P-256 signature over the exact received signed_payload bytes, and that the stored root pub encodes the signed public key (depth-0 xpub for secp256k1, 103-char base32 for ed25519). The payload is never re-serialised. - Attestation keys are pinned per environment next to hsmXpub and accept hex, base64 raw, base64 SPKI or PEM, because CoinCover has not published the encoding. They are empty until WCN-5246, so verification fails closed. Ticket: WCN-4832 --- modules/sdk-core/src/bitgo/environments.ts | 18 ++ .../src/bitgo/safe/coincoverRootProof.ts | 183 +++++++++++++++++ modules/sdk-core/src/bitgo/safe/index.ts | 1 + .../unit/bitgo/safe/coincoverRootProof.ts | 186 ++++++++++++++++++ 4 files changed, 388 insertions(+) create mode 100644 modules/sdk-core/src/bitgo/safe/coincoverRootProof.ts create mode 100644 modules/sdk-core/test/unit/bitgo/safe/coincoverRootProof.ts diff --git a/modules/sdk-core/src/bitgo/environments.ts b/modules/sdk-core/src/bitgo/environments.ts index bddd6299f7..25941f2b64 100644 --- a/modules/sdk-core/src/bitgo/environments.ts +++ b/modules/sdk-core/src/bitgo/environments.ts @@ -9,6 +9,12 @@ interface EnvironmentTemplate { signingAddress: string; serverXpub: string; hsmXpub: string; + /** + * Pinned CoinCover attestation public keys used to verify safe-root issuance proofs. Empty + * until the real keys arrive (WCN-5246), so verification against an environment config fails + * closed instead of accepting an unverifiable proof. + */ + coinCoverAttestationPublicKeys: readonly string[]; btcExplorerBaseUrl: string; etherscanBaseUrl: string; etherscanApiToken?: string; @@ -136,6 +142,11 @@ export const hardcodedPublicKeys = Object.freeze({ test: 'xpub661MyMwAqRbcGFKe4Bqvk4Sgric4gNFC8pUbw4tUkVjZxubjCA522gPzc1YaXb3bQVmDWc7CjG8AGNWRpcdAU38RETBh8n2bnqEU4kbV4oK', dev: 'xpub661MyMwAqRbcFWzoz8qnYRDYEFQpPLYwxVFoG6WLy3ck5ZupRGJTG4ju6yGb7Dj3ey6GsC4kstLRER2nKzgjLtmxyPgC4zHy7kVhUt6yfGn', }, + coinCoverAttestationPublicKeys: { + // The real keys arrive with WCN-5246. Empty lists keep verification failing closed. + prod: [] as readonly string[], + test: [] as readonly string[], + }, }); export type EnvironmentName = @@ -170,6 +181,7 @@ const mainnetBase: EnvironmentTemplate = { signingAddress: '1BitGo3gxRZ6mQSEH52dvCKSUgVCAH4Rja', serverXpub: hardcodedPublicKeys.serverXpub.prod, hsmXpub: hardcodedPublicKeys.hsmXpub.prod, + coinCoverAttestationPublicKeys: hardcodedPublicKeys.coinCoverAttestationPublicKeys.prod, btcExplorerBaseUrl: 'https://blockstream.info/api', etherscanBaseUrl: 'https://api.etherscan.io/v2', etherscanApiToken: process.env.ETHERSCAN_API_TOKEN, @@ -407,6 +419,7 @@ const testnetBase: EnvironmentTemplate = { signingAddress: 'msignBdFXteehDEgB6DNm7npRt7AcEZJP3', serverXpub: hardcodedPublicKeys.serverXpub.test, hsmXpub: hardcodedPublicKeys.hsmXpub.test, + coinCoverAttestationPublicKeys: hardcodedPublicKeys.coinCoverAttestationPublicKeys.test, btcExplorerBaseUrl: 'https://blockstream.info/testnet/api', etherscanBaseUrl: 'https://api.etherscan.io/v2', etherscanApiToken: process.env.ETHERSCAN_API_TOKEN, @@ -638,6 +651,7 @@ const testnetBase: EnvironmentTemplate = { const devBase: EnvironmentTemplate = Object.assign({}, testnetBase, { hsmXpub: hardcodedPublicKeys.hsmXpub.dev, + coinCoverAttestationPublicKeys: hardcodedPublicKeys.coinCoverAttestationPublicKeys.test, hmacVerificationEnforced: false, }); @@ -697,6 +711,10 @@ export const Environments: Environments = { network: process.env.BITGO_CUSTOM_BITCOIN_NETWORK as V1Network, hsmXpub: process.env.NODE_ENV === 'production' ? hardcodedPublicKeys.hsmXpub.prod : hardcodedPublicKeys.hsmXpub.test, + coinCoverAttestationPublicKeys: + process.env.NODE_ENV === 'production' + ? hardcodedPublicKeys.coinCoverAttestationPublicKeys.prod + : hardcodedPublicKeys.coinCoverAttestationPublicKeys.test, btcExplorerBaseUrl: process.env.BITGO_CUSTOM_BITCOIN_NETWORK !== 'bitcoin' ? 'https://blockstream.info/testnet/api' diff --git a/modules/sdk-core/src/bitgo/safe/coincoverRootProof.ts b/modules/sdk-core/src/bitgo/safe/coincoverRootProof.ts new file mode 100644 index 0000000000..98028dd8f9 --- /dev/null +++ b/modules/sdk-core/src/bitgo/safe/coincoverRootProof.ts @@ -0,0 +1,183 @@ +/** + * @prettier + * + * CoinCover safe-root issuance proof verification — CoinCover guide v1.1, section 6. + * + * CoinCover signs the RFC 8785 canonical JSON payload it returns as `signed_payload` with a + * P-256 attestation key. Verification must use the exact received bytes of that string: the + * payload is never re-serialised, because the signature covers those bytes and any + * canonicalisation on our side would be a different message. + */ + +import { createHash } from 'crypto'; +import { p256 } from '@noble/curves/p256'; +import { bip32 } from '@bitgo/utxo-lib'; +import { decodeDerivableEd25519Pub, isDerivableEd25519Pub } from '@bitgo/sdk-lib-safes'; +import { isValidXpub } from '../../account-lib/util/crypto'; + +export interface CoinCoverRootProof { + /** The stored root pub: a depth-0 xpub for secp256k1, a 103-char base32 pub||chainCode for ed25519. */ + pub: string; + slot: 'secp256k1Multisig' | 'ed25519Multisig'; + /** CoinCover's id for the root (`key_id` in the response; `Keychain.keyId` in WP). */ + keyId: string; + /** The response's `signed_payload`, verbatim. */ + signedPayload: string; + /** The response's base64 DER ECDSA P-256 signature. */ + signature: string; + /** BitGo's enterprise (public) id: the D5 `organisation.customer_id`. */ + enterpriseId: string; + /** The safe's public id: the D5 `package.package_id`. */ + safeId: string; + /** Pinned CoinCover attestation public keys for the environment. */ + attestationPublicKeys: readonly string[]; +} + +const SIGNED_PAYLOAD_FIELDS = ['external_customer_id', 'external_package_id', 'key_id', 'public_key']; + +function fail(check: string): never { + throw new Error(`CoinCover safe-root proof failed: ${check}`); +} + +/** + * Unwrap a DER SubjectPublicKeyInfo for P-256. The guide's illustrative verifier passes its + * `COINCOVER_ATTESTATION_KEY` straight to `crypto.verify`, which takes a KeyObject or PEM, so the + * pinned value may arrive in that form rather than as a bare point. + */ +function pointFromSpki(der: Buffer): Uint8Array { + // 30 59 · 30 13 · OIDs · 03 42 00 · 04 || x || y — 91 bytes for P-256. + const isP256Spki = der.length === 91 && der[0] === 0x30 && der[23] === 0x03 && der[26] === 0x04; + if (!isP256Spki) { + fail('unsupported attestation public key encoding'); + } + return der.subarray(26); +} + +/** + * Decode a pinned attestation key into a point p256 can verify against. CoinCover has not published + * the encoding, so accept the plausible forms: hex (33-byte compressed or 65-byte uncompressed), a + * PEM block, base64 DER SubjectPublicKeyInfo, and base64 of the raw 64-byte x||y point. Anything + * else fails closed. + */ +function parseAttestationPublicKey(encoded: string): Uint8Array { + if (/-----BEGIN [A-Z ]+-----/.test(encoded)) { + return pointFromSpki(Buffer.from(encoded.replace(/-----[^-]+-----/g, '').replace(/\s+/g, ''), 'base64')); + } + + const isHexPoint = /^[0-9a-fA-F]+$/.test(encoded) && (encoded.length === 66 || encoded.length === 130); + if (isHexPoint) { + const bytes = Buffer.from(encoded, 'hex'); + const isCompressed = bytes.length === 33 && (bytes[0] === 0x02 || bytes[0] === 0x03); + const isUncompressed = bytes.length === 65 && bytes[0] === 0x04; + if (!isCompressed && !isUncompressed) { + fail('unsupported attestation public key encoding'); + } + return bytes; + } + + const raw = Buffer.from(encoded, 'base64'); + if (raw.length === 64 && raw.toString('base64').replace(/=+$/, '') === encoded.replace(/=+$/, '')) { + return Buffer.concat([Buffer.from([0x04]), raw]); + } + if (raw.length > 0 && raw[0] === 0x30) { + return pointFromSpki(raw); + } + + fail('unsupported attestation public key encoding'); +} + +/** Parse the received payload string as-is; it is never re-serialised. */ +function parseSignedPayload(signedPayload: string): unknown { + try { + return JSON.parse(signedPayload); + } catch (e) { + fail('signed payload is not valid JSON'); + } +} + +/** Parse the base64 signature as DER; compact (P1363) and any other encoding fail here. */ +function parseSignature(encoded: string): { r: bigint; s: bigint } { + try { + return p256.Signature.fromDER(Buffer.from(encoded, 'base64')); + } catch (e) { + fail('signature encoding'); + } +} + +/** Hex of the public derivation material the stored root `pub` encodes. */ +function rootPublicKeyHex(pub: string, slot: CoinCoverRootProof['slot']): string { + switch (slot) { + case 'secp256k1Multisig': { + if (!isValidXpub(pub)) { + fail('invalid secp256k1 root xpub'); + } + const node = bip32.fromBase58(pub); + return Buffer.concat([node.publicKey, node.chainCode]).toString('hex'); + } + case 'ed25519Multisig': { + if (!isDerivableEd25519Pub(pub)) { + fail('invalid ed25519 root pub'); + } + const { pub: rawPub, chainCode } = decodeDerivableEd25519Pub(pub); + return Buffer.concat([rawPub, chainCode]).toString('hex'); + } + default: + fail('unsupported root slot'); + } +} + +/** + * Verify the CoinCover issuance proof for a safe root. Resolves when every guide v1.1 section 6 + * check passes; throws on the first failed check. + */ +export async function verifyCoinCoverSafeRootProof(proof: CoinCoverRootProof): Promise { + if (proof.attestationPublicKeys.length === 0) { + fail('no pinned attestation public keys'); + } + + const signed = parseSignedPayload(proof.signedPayload); + if (typeof signed !== 'object' || signed === null || Array.isArray(signed)) { + fail('signed payload is not a JSON object'); + } + + const fields = Object.keys(signed).sort(); + const expectedFields = SIGNED_PAYLOAD_FIELDS.slice().sort(); + if (fields.length !== expectedFields.length || fields.some((field, i) => field !== expectedFields[i])) { + fail('signed payload fields'); + } + + const payload = signed as Record; + if (payload.key_id !== proof.keyId) { + fail('key_id'); + } + if (payload.external_customer_id !== proof.enterpriseId) { + fail('external_customer_id'); + } + if (payload.external_package_id !== proof.safeId) { + fail('external_package_id'); + } + + const signature = parseSignature(proof.signature); + + const messageHash = createHash('sha256').update(Buffer.from(proof.signedPayload, 'utf8')).digest(); + const verified = proof.attestationPublicKeys.some((pinnedKey) => + p256.verify( + { r: signature.r, s: signature.s }, + messageHash, + parseAttestationPublicKey(pinnedKey), + // CoinCover's signature may be high-S, so do not reject on malleability. + { lowS: false } + ) + ); + if (!verified) { + fail('signature'); + } + + const publicKey = payload.public_key; + if (typeof publicKey !== 'string' || !/^[0-9a-f]+$/.test(publicKey)) { + fail('public_key is not lowercase hex'); + } + if (publicKey !== rootPublicKeyHex(proof.pub, proof.slot)) { + fail('public_key does not match root pub'); + } +} diff --git a/modules/sdk-core/src/bitgo/safe/index.ts b/modules/sdk-core/src/bitgo/safe/index.ts index a446c6b2c1..4b45a0c190 100644 --- a/modules/sdk-core/src/bitgo/safe/index.ts +++ b/modules/sdk-core/src/bitgo/safe/index.ts @@ -1,3 +1,4 @@ +export * from './coincoverRootProof'; export * from './derivableEd25519Pub'; export * from './iSafe'; export * from './iSafes'; diff --git a/modules/sdk-core/test/unit/bitgo/safe/coincoverRootProof.ts b/modules/sdk-core/test/unit/bitgo/safe/coincoverRootProof.ts new file mode 100644 index 0000000000..53453e2bc7 --- /dev/null +++ b/modules/sdk-core/test/unit/bitgo/safe/coincoverRootProof.ts @@ -0,0 +1,186 @@ +import 'should'; +import { createHash } from 'crypto'; +import { p256 } from '@noble/curves/p256'; +import { bip32 } from '@bitgo/utxo-lib'; +import { encodeDerivableEd25519Pub } from '@bitgo/sdk-lib-safes'; +import { type CoinCoverRootProof, verifyCoinCoverSafeRootProof } from '../../../../src/bitgo/safe/coincoverRootProof'; + +const ENTERPRISE_ID = 'enterprise-id'; +const SAFE_ID = 'safe-id'; +const KEY_ID = 'coincover-key-id'; + +// Fixed scalars keep the fixtures (and so the negative signature cases) deterministic. +const ATTESTATION_PRIVATE_KEY = Buffer.from('c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721', 'hex'); +const OTHER_ATTESTATION_PRIVATE_KEY = Buffer.from( + '6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296', + 'hex' +); +const ATTESTATION_PUBLIC_KEY = p256.getPublicKey(ATTESTATION_PRIVATE_KEY, true); +const ATTESTATION_PUBLIC_KEY_UNCOMPRESSED = p256.getPublicKey(ATTESTATION_PRIVATE_KEY, false); +const ATTESTATION_PUBLIC_KEY_HEX = Buffer.from(ATTESTATION_PUBLIC_KEY).toString('hex'); +// P-256 SubjectPublicKeyInfo, the form the guide's illustrative `crypto.verify` call implies. +const ATTESTATION_SPKI = Buffer.concat([ + Buffer.from('3059301306072a8648ce3d020106082a8648ce3d030107034200', 'hex'), + Buffer.from(ATTESTATION_PUBLIC_KEY_UNCOMPRESSED), +]); +const ATTESTATION_PEM = [ + '-----BEGIN PUBLIC KEY-----', + ...(ATTESTATION_SPKI.toString('base64').match(/.{1,64}/g) ?? []), + '-----END PUBLIC KEY-----', +].join('\n'); +const OTHER_ATTESTATION_PUBLIC_KEY_HEX = Buffer.from(p256.getPublicKey(OTHER_ATTESTATION_PRIVATE_KEY, true)).toString( + 'hex' +); + +const SECP_ROOT = bip32.fromSeed(Buffer.alloc(32, 1)); +const SECP_XPUB = SECP_ROOT.neutered().toBase58(); +const SECP_PUBLIC_KEY_HEX = Buffer.concat([SECP_ROOT.publicKey, SECP_ROOT.chainCode]).toString('hex'); + +const OTHER_SECP_ROOT = bip32.fromSeed(Buffer.alloc(32, 2)); +const OTHER_SECP_XPUB = OTHER_SECP_ROOT.neutered().toBase58(); +const OTHER_SECP_PUBLIC_KEY_HEX = Buffer.concat([OTHER_SECP_ROOT.publicKey, OTHER_SECP_ROOT.chainCode]).toString('hex'); + +const ED25519_RAW_PUB = Buffer.alloc(32, 7); +const ED25519_CHAIN_CODE = Buffer.alloc(32, 8); +const ED25519_ROOT_PUB = encodeDerivableEd25519Pub(ED25519_RAW_PUB, ED25519_CHAIN_CODE); +const ED25519_PUBLIC_KEY_HEX = Buffer.concat([ED25519_RAW_PUB, ED25519_CHAIN_CODE]).toString('hex'); + +function signPayload(payload: string, privateKey: Uint8Array = ATTESTATION_PRIVATE_KEY): string { + // noble's p256 takes the message hash, not the message: the signature is over SHA-256(payload). + const hash = createHash('sha256').update(Buffer.from(payload, 'utf8')).digest(); + return Buffer.from(p256.sign(hash, privateKey, { lowS: false }).toDERRawBytes()).toString('base64'); +} + +/** Canonical (RFC 8785) payload: keys in sorted order, as CoinCover emits them. */ +function signedPayloadWith(overrides: Record = {}): string { + return JSON.stringify({ + external_customer_id: ENTERPRISE_ID, + external_package_id: SAFE_ID, + key_id: KEY_ID, + public_key: SECP_PUBLIC_KEY_HEX, + ...overrides, + }); +} + +function buildProof(overrides: Partial = {}): CoinCoverRootProof { + const signedPayload = overrides.signedPayload ?? signedPayloadWith(); + return { + pub: SECP_XPUB, + slot: 'secp256k1Multisig', + keyId: KEY_ID, + signedPayload, + signature: signPayload(signedPayload), + enterpriseId: ENTERPRISE_ID, + safeId: SAFE_ID, + attestationPublicKeys: [ATTESTATION_PUBLIC_KEY_HEX], + ...overrides, + }; +} + +describe('verifyCoinCoverSafeRootProof', function () { + it('accepts a valid secp256k1 proof', async function () { + await verifyCoinCoverSafeRootProof(buildProof()); + }); + + it('accepts a valid ed25519 proof', async function () { + const signedPayload = signedPayloadWith({ public_key: ED25519_PUBLIC_KEY_HEX }); + await verifyCoinCoverSafeRootProof(buildProof({ signedPayload, pub: ED25519_ROOT_PUB, slot: 'ed25519Multisig' })); + }); + + it('accepts a high-S signature', async function () { + const signedPayload = signedPayloadWith(); + const hash = createHash('sha256').update(Buffer.from(signedPayload, 'utf8')).digest(); + const signature = p256.sign(hash, ATTESTATION_PRIVATE_KEY, { lowS: false }); + const highS = signature.hasHighS() ? signature : new p256.Signature(signature.r, p256.CURVE.n - signature.s); + highS.hasHighS().should.be.true(); + await verifyCoinCoverSafeRootProof( + buildProof({ signature: Buffer.from(highS.toDERRawBytes()).toString('base64') }) + ); + }); + + it('accepts every supported attestation public key encoding', async function () { + const encodings = [ + ATTESTATION_PUBLIC_KEY_HEX, + ATTESTATION_PUBLIC_KEY_HEX.toUpperCase(), + Buffer.from(ATTESTATION_PUBLIC_KEY_UNCOMPRESSED).toString('hex'), + Buffer.from(ATTESTATION_PUBLIC_KEY_UNCOMPRESSED.subarray(1)).toString('base64'), + ATTESTATION_SPKI.toString('base64'), + ATTESTATION_PEM, + ]; + for (const encoding of encodings) { + await verifyCoinCoverSafeRootProof(buildProof({ attestationPublicKeys: [encoding] })); + } + }); + + it('rejects a public_key that does not match the stored root pub', async function () { + const signedPayload = signedPayloadWith({ public_key: OTHER_SECP_PUBLIC_KEY_HEX }); + await verifyCoinCoverSafeRootProof(buildProof({ signedPayload })).should.be.rejectedWith( + /public_key does not match root pub/ + ); + }); + + it('rejects a pub that does not match public_key', async function () { + await verifyCoinCoverSafeRootProof(buildProof({ pub: OTHER_SECP_XPUB })).should.be.rejectedWith( + /public_key does not match root pub/ + ); + }); + + it('rejects a wrong key_id', async function () { + await verifyCoinCoverSafeRootProof(buildProof({ keyId: 'some-other-key' })).should.be.rejectedWith(/key_id/); + }); + + it('rejects a wrong enterprise id', async function () { + await verifyCoinCoverSafeRootProof(buildProof({ enterpriseId: 'some-other-enterprise' })).should.be.rejectedWith( + /external_customer_id/ + ); + }); + + it('rejects a wrong safe id', async function () { + await verifyCoinCoverSafeRootProof(buildProof({ safeId: 'some-other-safe' })).should.be.rejectedWith( + /external_package_id/ + ); + }); + + it('rejects an extra signed payload field', async function () { + const signedPayload = signedPayloadWith({ unexpected_field: 'value' }); + await verifyCoinCoverSafeRootProof(buildProof({ signedPayload })).should.be.rejectedWith(/signed payload fields/); + }); + + it('rejects a missing signed payload field', async function () { + const signedPayload = JSON.stringify({ + external_customer_id: ENTERPRISE_ID, + external_package_id: SAFE_ID, + key_id: KEY_ID, + }); + await verifyCoinCoverSafeRootProof(buildProof({ signedPayload })).should.be.rejectedWith(/signed payload fields/); + }); + + it('rejects a re-serialised payload with a different key order', async function () { + const signature = signPayload(signedPayloadWith()); + const signedPayload = JSON.stringify({ + key_id: KEY_ID, + public_key: SECP_PUBLIC_KEY_HEX, + external_customer_id: ENTERPRISE_ID, + external_package_id: SAFE_ID, + }); + await verifyCoinCoverSafeRootProof(buildProof({ signedPayload, signature })).should.be.rejectedWith(/signature/); + }); + + it('rejects a signature from a key that is not pinned', async function () { + await verifyCoinCoverSafeRootProof( + buildProof({ attestationPublicKeys: [OTHER_ATTESTATION_PUBLIC_KEY_HEX] }) + ).should.be.rejectedWith(/signature/); + }); + + it('rejects a compact (P1363) signature', async function () { + const der = p256.Signature.fromDER(Buffer.from(signPayload(signedPayloadWith()), 'base64')); + const compact = Buffer.from(der.toCompactRawBytes()).toString('base64'); + await verifyCoinCoverSafeRootProof(buildProof({ signature: compact })).should.be.rejectedWith(/signature encoding/); + }); + + it('rejects an empty pinned attestation key list', async function () { + await verifyCoinCoverSafeRootProof(buildProof({ attestationPublicKeys: [] })).should.be.rejectedWith( + /no pinned attestation public keys/ + ); + }); +});