Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions modules/sdk-core/src/bitgo/environments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 =
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -638,6 +651,7 @@ const testnetBase: EnvironmentTemplate = {

const devBase: EnvironmentTemplate = Object.assign({}, testnetBase, {
hsmXpub: hardcodedPublicKeys.hsmXpub.dev,
coinCoverAttestationPublicKeys: hardcodedPublicKeys.coinCoverAttestationPublicKeys.test,
hmacVerificationEnforced: false,
});

Expand Down Expand Up @@ -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'
Expand Down
183 changes: 183 additions & 0 deletions modules/sdk-core/src/bitgo/safe/coincoverRootProof.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
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<string, unknown>;
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');
}
}
1 change: 1 addition & 0 deletions modules/sdk-core/src/bitgo/safe/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './coincoverRootProof';
export * from './derivableEd25519Pub';
export * from './iSafe';
export * from './iSafes';
Expand Down
Loading
Loading