diff --git a/README.md b/README.md index 45bcea5..686f473 100644 --- a/README.md +++ b/README.md @@ -80,22 +80,23 @@ assertValidFrameTx(signed) const raw = encodeFrameTx(signed) ``` -`signFrameTx` also takes a `FrameSigner` instead of a key — anything with an `address` and a -raw-digest `sign`, which covers viem's `privateKeyToAccount` and `mnemonicToAccount`, a -`toAccount` source, and your own wrapper around a hardware wallet, an HSM or a remote -signer. It signs every SECP256K1 entry whose `msg` is empty, and refuses if the entry's -resolved signer is not that account's address. +`signFrameTx` also takes a `FrameAccountOwner` instead of a key. This includes viem's +`privateKeyToAccount` and `mnemonicToAccount`, a `toAccount` source, the tagged owner from +`privateKeyToP256Account`, and viem accounts backed by hardware wallets, HSMs or remote signers. +It signs every ECDSA entry whose `msg` is empty and refuses if either the signature scheme +or resolved signer does not match the supplied owner. ```ts -import { privateKeyToAccount } from 'viem/accounts' +import { privateKeyToAccount, toAccount } from 'viem/accounts' const signed = await signFrameTx(tx, privateKeyToAccount(privateKey)) -// a remote signer needs nothing else: -const signed = await signFrameTx(tx, { +// Wrap a remote signer as a viem Account: +const remoteAccount = toAccount({ address: '0x…', sign: ({ hash }) => myKms.signDigest(hash), // r||s||v, v as 27/28 or a bare 0/1 }) +const signed = await signFrameTx(tx, remoteAccount) ``` A raw-digest `sign` is required. `signMessage` will not do: it EIP-191-prefixes its @@ -103,9 +104,48 @@ argument, so the signature recovers to nothing. A `JsonRpcAccount` (a browser wa cannot sign a raw digest at all — both are refused with an error rather than producing a transaction the chain silently rejects. -P256 and ARBITRARY entries are left untouched; build those signatures yourself and let -`assertValidFrameTx` check them. The low-level `signFrameTx` handles one signer at a time; -`signFrameTransaction` coordinates a sender and an optional `FramePayerAccount`. +The same restriction applies to P-256 signers. WebCrypto's ECDSA API hashes its input +internally, so passing the frame sig-hash to it signs `SHA-256(frameSigHash)`, not the +frame sig-hash itself. Passkeys/WebAuthn sign authenticator data and client data rather +than an arbitrary 32-byte digest. Use a P-256 backend that explicitly supports raw or +prehashed ECDSA digests; `privateKeyToP256Account` does so for a local private scalar. + +ARBITRARY entries are left untouched; build those signatures yourself and let +`assertValidFrameTx` check them. The low-level `signFrameTx` handles one owner and +signature scheme at a time; `signFrameTransaction` coordinates a sender and an optional +`FramePayerAccount`. + +For an EIP-7702 delegated account authorized by P-256, create a signer from its raw +32-byte private scalar and resolve the delegated EOA separately. P-256 signatures are +made directly over the frame sig-hash, normalized to low `s`, checked locally, and encoded +as `r || s || qx || qy`. + +```ts +import { + privateKeyToP256Account, + toP256FrameAccount, +} from '@jaw.id/frametx-kit' + +const owner = privateKeyToP256Account(p256PrivateKey) +const account = await toP256FrameAccount({ + client, + address: delegatedEoa, + owner, +}) +``` + +To exercise a PEM-backed delegated account end to end against the Ethrex testnet: + +```bash +RPC_URL=https://rpc1.privacy.ethrex.xyz \ +SENDER=0x... \ +RECIPIENT=0x... \ +P256_PRIVATE_KEY_PATH=/absolute/path/to/p256-private.pem \ +bun run scripts/send-eth-p256.ts +``` + +The script checks that the PEM-derived identity equals the delegated account's on-chain +`p256Signer()`, then sends through the high-level `sendFrameTransaction` action. Sending walks the strict path for you — `assertValidFrameTx`, `encodeFrameTx`, `eth_sendRawTransaction` — and checks that the hash the node returns is `keccak256` of the diff --git a/bun.lock b/bun.lock index f1e175d..802c88a 100644 --- a/bun.lock +++ b/bun.lock @@ -4,6 +4,9 @@ "workspaces": { "": { "name": "frames-ts", + "dependencies": { + "ox": "^0.14.45", + }, "devDependencies": { "@semantic-release/changelog": "^7.0.0", "@semantic-release/git": "^11.0.1", diff --git a/docs/DESIGN.md b/docs/DESIGN.md index c913158..6d4193a 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -26,7 +26,7 @@ Not supported: blob-carrying transaction must be broadcast in the EIP-7594 wrapper, which the library does not produce. - **UTXO frames** (mode 5, EIP-8312), inert on this chain. -- **P256 and ARBITRARY signing.** Both are validated, neither is produced by `signFrameTx`. +- **ARBITRARY signing.** It is validated but not produced by this library. ## 2. The envelope @@ -94,9 +94,10 @@ invalidates the transaction at consensus. `signFrameTx` normalizes whatever a si returns into this form. **Signer resolution.** An empty `signer` resolves to `tx.sender` for SECP256K1 and P256. -`signFrameTx` signs every empty-`msg` SECP256K1 entry whose resolved signer is the signing -account, and refuses a signer that cannot sign a raw digest (EIP-191 `signMessage`, JSON-RPC -accounts) rather than produce a signature that recovers to nothing. +`signFrameTx` signs every empty-`msg` entry of the owner's scheme (SECP256K1 for a viem +account, P256 for a P-256 owner) whose resolved signer is the owner, leaves entries of the +other scheme as they are, and refuses a signer that cannot sign a raw digest (EIP-191 +`signMessage`, JSON-RPC accounts) rather than produce a signature that recovers to nothing. ## 4. Gas @@ -146,6 +147,12 @@ strategy; `toFrameAccount` resolves it into a `FrameAccount`. from `eth_getTransactionCount`, other keys from `NONCE_MANAGER` via `eth_getStorageAt`, empty validation data, and one empty-`msg`, empty-`signer` SECP256K1 entry. +`toP256FrameAccount` targets an EIP-7702 delegated EOA whose validation code authorizes a +P-256 signer. It emits one empty-`msg` P256 entry with the explicit signer identity +`last20Bytes(keccak256(qx || qy))` at index `0`. Its signer signs the already-computed +frame sig-hash directly, without applying SHA-256 a second time, normalizes `s` low, and +encodes `r || s || qx || qy`. + A `FramePayerAccountImplementation` supplies `getAddress()`, `getPayData(tx)`, `getSignatureEntries(tx)` and `signFrameTransaction(tx)`; `toFramePayerAccount` resolves it into a `FramePayerAccount`. `toEoaFramePayerAccount` implements the protocol's codeless diff --git a/package.json b/package.json index 3a918ee..79e4048 100644 --- a/package.json +++ b/package.json @@ -73,6 +73,9 @@ "test:watch": "vitest", "typecheck": "tsc --noEmit" }, + "dependencies": { + "ox": "^0.14.45" + }, "peerDependencies": { "viem": "^2.21.0" }, diff --git a/scripts/send-eth-p256.ts b/scripts/send-eth-p256.ts new file mode 100644 index 0000000..ca8356e --- /dev/null +++ b/scripts/send-eth-p256.ts @@ -0,0 +1,173 @@ +/** + * Send native ETH from an EIP-7702 delegated EOA using a P-256-authorized + * EIP-8141 frame transaction. + * + * Required: + * SENDER=0x... + * RECIPIENT=0x... + * P256_PRIVATE_KEY_PATH=/absolute/path/to/p256-private.pem + * + * Optional: + * RPC_URL=https://rpc1.privacy.ethrex.xyz + * AMOUNT_ETH=0.000001 + * P256_PRIVATE_KEY_PASSPHRASE=... + * P256_SIGNER_IDENTITY=0x... independently assert the expected identity + */ +import { createPrivateKey } from 'node:crypto' +import { readFileSync } from 'node:fs' +import { + type Hex, + createPublicClient, + decodeFunctionResult, + encodeFunctionData, + formatEther, + getAddress, + http, + isAddressEqual, + parseEther, +} from 'viem' +import { + hegotaTestnet, + parseRpcFrameReceipt, + privateKeyToP256Account, + sendFrameTransaction, + toP256FrameAccount, + type FrameRpcClient, + type RpcFrameReceiptJson, +} from '../src/index.js' + +const RECEIPT_TIMEOUT_MS = 120_000 +const P256_ACCOUNT_ABI = [ + { + type: 'function', + name: 'p256Signer', + stateMutability: 'view', + inputs: [], + outputs: [{ name: '', type: 'address' }], + }, +] as const + +function requiredEnv(name: string): string { + const value = process.env[name] + if (!value) throw new Error(`${name} is required`) + return value +} + +function loadP256PrivateKey(path: string): Hex { + const pem = readFileSync(path) + const passphrase = process.env.P256_PRIVATE_KEY_PASSPHRASE + const key = createPrivateKey( + passphrase === undefined ? pem : { key: pem, passphrase }, + ) + const jwk = key.export({ format: 'jwk' }) + if (jwk.kty !== 'EC' || jwk.crv !== 'P-256' || jwk.d === undefined) + throw new Error('P256_PRIVATE_KEY_PATH must contain a P-256 private PEM key') + + const privateKey = `0x${Buffer.from(jwk.d, 'base64url').toString('hex')}` as Hex + if (!/^0x[0-9a-f]{64}$/.test(privateKey)) + throw new Error('P-256 private scalar must be exactly 32 bytes') + return privateKey +} + +async function waitForFrameReceipt( + client: FrameRpcClient, + hash: Hex, +): Promise { + const deadline = Date.now() + RECEIPT_TIMEOUT_MS + while (Date.now() < deadline) { + const receipt = (await client.request({ + method: 'eth_getTransactionReceipt', + params: [hash], + })) as RpcFrameReceiptJson | null + if (receipt !== null) return receipt + await new Promise((resolve) => setTimeout(resolve, 1_000)) + } + throw new Error( + `transaction ${hash} was not mined within ${RECEIPT_TIMEOUT_MS / 1_000}s`, + ) +} + +async function main(): Promise { + const rpcUrl = process.env.RPC_URL ?? 'https://rpc1.privacy.ethrex.xyz' + const sender = getAddress(requiredEnv('SENDER')) + const recipient = getAddress(requiredEnv('RECIPIENT')) + const amount = parseEther(process.env.AMOUNT_ETH ?? '0.000001') + const owner = privateKeyToP256Account( + loadP256PrivateKey(requiredEnv('P256_PRIVATE_KEY_PATH')), + ) + + const expectedIdentity = process.env.P256_SIGNER_IDENTITY + if ( + expectedIdentity !== undefined && + !isAddressEqual(owner.address, getAddress(expectedIdentity)) + ) + throw new Error( + `PEM signer identity ${owner.address} does not match P256_SIGNER_IDENTITY ${expectedIdentity}`, + ) + + const client = createPublicClient({ + chain: hegotaTestnet, + transport: http(rpcUrl), + }) + const code = await client.getCode({ address: sender }) + if (code === undefined || !code.toLowerCase().startsWith('0xef0100')) + throw new Error(`sender ${sender} does not have an EIP-7702 delegation`) + + const signerCall = await client.call({ + to: sender, + data: encodeFunctionData({ abi: P256_ACCOUNT_ABI, functionName: 'p256Signer' }), + }) + if (signerCall.data === undefined) + throw new Error(`p256Signer() returned no data for ${sender}`) + const configuredSigner = decodeFunctionResult({ + abi: P256_ACCOUNT_ABI, + functionName: 'p256Signer', + data: signerCall.data, + }) + if (!isAddressEqual(configuredSigner, owner.address)) + throw new Error( + `delegated account authorizes ${configuredSigner}, but the PEM identity is ${owner.address}`, + ) + + const account = await toP256FrameAccount({ client, address: sender, owner }) + const [senderBalanceBefore, recipientBalanceBefore] = await Promise.all([ + client.getBalance({ address: sender }), + client.getBalance({ address: recipient }), + ]) + + console.log(`sender: ${sender}`) + console.log(`recipient: ${recipient}`) + console.log(`amount: ${formatEther(amount)} ETH`) + console.log(`P-256 signer: ${owner.address}`) + + const submittedHash = await sendFrameTransaction( + account, + [{ to: recipient, value: amount }], + { + limits: { + validation: { execution: 100_000n, state: 0n }, + calls: [{ execution: 30_000n, state: 200_000n }], + }, + }, + ) + + console.log(`submitted: ${submittedHash}`) + const rpcReceipt = await waitForFrameReceipt(client, submittedHash) + const receipt = parseRpcFrameReceipt(rpcReceipt) + const [senderBalanceAfter, recipientBalanceAfter] = await Promise.all([ + client.getBalance({ address: sender }), + client.getBalance({ address: recipient }), + ]) + + console.log('payer:', receipt.payer) + console.log('frames:', receipt.frameReceipts) + console.log(`sender delta: ${formatEther(senderBalanceAfter - senderBalanceBefore)} ETH`) + console.log( + `recipient delta: ${formatEther(recipientBalanceAfter - recipientBalanceBefore)} ETH`, + ) +} + +main().catch((error: unknown) => { + console.error(error instanceof Error ? error.message : error) + process.exitCode = 1 +}) diff --git a/src/accounts/toP256FrameAccount.ts b/src/accounts/toP256FrameAccount.ts new file mode 100644 index 0000000..785ddb4 --- /dev/null +++ b/src/accounts/toP256FrameAccount.ts @@ -0,0 +1,100 @@ +import { + type Address, + type Chain, + type Client, + type JsonRpcAccount, + type LocalAccount, + type Transport, + isAddressEqual, +} from 'viem' +import { FrameEncodeError } from '../errors.js' +import { getFrameNonceSeq } from '../nonce.js' +import type { P256FrameSigner } from '../p256.js' +import { signFrameSignature } from '../signatures.js' +import type { FrameTransaction } from '../types.js' +import { toFrameAccount } from './toFrameAccount.js' +import type { FrameAccount, FrameAccountImplementation } from './types.js' + +export type P256FrameAccountImplementation< + chain extends Chain | undefined = Chain | undefined, + owner extends P256FrameSigner = P256FrameSigner, + extend extends object = object, +> = FrameAccountImplementation + +export type ToP256FrameAccountParameters< + chain extends Chain | undefined = Chain | undefined, + owner extends P256FrameSigner = P256FrameSigner, + extend extends object = object, +> = { + client: Client + /** EIP-7702 delegated EOA represented by this frame account. */ + address: Address + owner: owner + extend?: extend | undefined +} + +export type ToP256FrameAccountReturnType< + chain extends Chain | undefined = Chain | undefined, + owner extends P256FrameSigner = P256FrameSigner, + extend extends object = object, +> = FrameAccount> + +/** Create a direct-execution frame account authorized by a P-256 signer. */ +export async function toP256FrameAccount< + chain extends Chain | undefined, + owner extends P256FrameSigner, + extend extends object = object, +>( + parameters: ToP256FrameAccountParameters, +): Promise> { + const { address, client, owner } = parameters + + return toFrameAccount({ + client, + owner, + execution: { type: 'direct' }, + ...(parameters.extend === undefined ? {} : { extend: parameters.extend }), + async getAddress() { + return address + }, + async getNonce(nonceParameters = {}) { + return getFrameNonceSeq(client, { address, ...nonceParameters }) + }, + async getValidationData() { + return '0x' + }, + async getSignatureEntries() { + return [ + { + scheme: 2, + signer: owner.address, + msg: '0x', + signature: '0x', + }, + ] + }, + async signFrameTransaction(transaction: FrameTransaction) { + if (!isAddressEqual(transaction.sender, address)) + throw new FrameEncodeError( + `transaction sender ${transaction.sender} does not match P-256 frame account ${address}`, + ) + + const prepared = + transaction.signatures.length === 0 + ? { + ...transaction, + signatures: [ + { + scheme: 2 as const, + signer: owner.address, + msg: '0x' as const, + signature: '0x' as const, + }, + ], + } + : transaction + + return signFrameSignature(prepared, 0, owner) + }, + }) +} diff --git a/src/accounts/types.ts b/src/accounts/types.ts index 98ceadb..87aa75f 100644 --- a/src/accounts/types.ts +++ b/src/accounts/types.ts @@ -14,6 +14,9 @@ import type { FrameSignature, FrameTransaction, } from '../types.js' +import type { P256FrameSigner } from '../p256.js' + +export type FrameAccountOwner = Account | P256FrameSigner export type FrameCall = { to: Address @@ -40,7 +43,7 @@ export type DirectFrameExecution = { } export type FramePayerAccountImplementation< - owner extends Account | undefined = Account | undefined, + owner extends FrameAccountOwner | undefined = FrameAccountOwner | undefined, extend extends object = object, > = { /** Account or signer that controls the payer. */ @@ -73,7 +76,7 @@ export type FramePaymasterParameters< /** Account-specific behavior required to construct and sign frame transactions. */ export type FrameAccountImplementation< chain extends Chain | undefined = Chain | undefined, - owner extends Account | undefined = Account | undefined, + owner extends FrameAccountOwner | undefined = FrameAccountOwner | undefined, extend extends object = object, > = { /** Client used to read account and nonce state. */ diff --git a/src/index.ts b/src/index.ts index aff6edb..4cf2825 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,6 +5,7 @@ export { type DirectFrameExecution, type FrameAccount, type FrameAccountImplementation, + type FrameAccountOwner, type FrameCall, type FramePaymasterParameters, type FramePayerAccount, @@ -36,6 +37,12 @@ export { type ToEoaFrameAccountReturnType, toEoaFrameAccount, } from './accounts/toEoaFrameAccount.js' +export { + type P256FrameAccountImplementation, + type ToP256FrameAccountParameters, + type ToP256FrameAccountReturnType, + toP256FrameAccount, +} from './accounts/toP256FrameAccount.js' export { type GetFrameNonceSeqParameters, NONCE_MANAGER, @@ -69,10 +76,14 @@ export { EXPIRY_VERIFIER, } from './envelope.js' export { frameTxSigHash } from './sighash.js' +export { + type P256FrameSigner, + p256SignerIdentity, + privateKeyToP256Account, +} from './p256.js' export { SECP256K1_N, SECP256R1_N, - type FrameSigner, assertCanonicalSignature, assertValidFrameTx, recoverFrameSigner, diff --git a/src/p256.ts b/src/p256.ts new file mode 100644 index 0000000..dd284ff --- /dev/null +++ b/src/p256.ts @@ -0,0 +1,92 @@ +import { + type Address, + type Hex, + concatHex, + getAddress, + keccak256, + numberToHex, + size, + sliceHex, +} from 'viem' +import * as P256 from 'ox/P256' +import { FrameEncodeError } from './errors.js' + +export type P256FrameSigner = { + type: 'p256' + /** `last20Bytes(keccak256(qx || qy))`. */ + address: Address + /** Uncompressed SEC1 public key encoded as `0x04 || qx || qy`. */ + publicKey: Hex + /** Sign an already-hashed 32-byte digest as `r || s` without hashing it again. */ + sign: (parameters: { hash: Hex }) => Promise +} + +function assertBytes32(value: Hex, label: string): void { + if (size(value) !== 32) + throw new FrameEncodeError(`${label} must be exactly 32 bytes`) +} + +function oxPublicKey(publicKey: Hex) { + if (size(publicKey) !== 65 || sliceHex(publicKey, 0, 1) !== '0x04') + throw new FrameEncodeError( + 'P-256 public key must be 65-byte uncompressed SEC1 data (0x04 || qx || qy)', + ) + const qx = sliceHex(publicKey, 1, 33) + const qy = sliceHex(publicKey, 33, 65) + const value = { + prefix: 4 as const, + x: BigInt(qx), + y: BigInt(qy), + } + + try { + P256.noble.ProjectivePoint.fromHex(publicKey.slice(2)) + } catch { + throw new FrameEncodeError('P-256 public key is not a point on the curve') + } + return value +} + +/** Derive the EIP-8141 P-256 signer identity from an uncompressed public key. */ +export function p256SignerIdentity(publicKey: Hex): Address { + oxPublicKey(publicKey) + return getAddress(sliceHex(keccak256(sliceHex(publicKey, 1)), 12)) +} + +/** Create a raw-digest P-256 signer from a 32-byte private scalar. */ +export function privateKeyToP256Account(privateKey: Hex): P256FrameSigner { + assertBytes32(privateKey, 'P-256 private key') + + let point: ReturnType + try { + point = P256.getPublicKey({ privateKey }) + } catch { + throw new FrameEncodeError('P-256 private key is not a valid scalar') + } + + const publicKey = concatHex([ + '0x04', + numberToHex(point.x, { size: 32 }), + numberToHex(point.y, { size: 32 }), + ]) + + return { + type: 'p256', + address: p256SignerIdentity(publicKey), + publicKey, + async sign({ hash }) { + assertBytes32(hash, 'P-256 signing hash') + // The frame sig-hash is already a digest. `hash` is deliberately omitted, + // otherwise Ox would SHA-256 it again before ECDSA signing. + const { r, s } = P256.sign({ + payload: hash, + privateKey, + extraEntropy: false, + }) + return concatHex([ + numberToHex(r, { size: 32 }), + numberToHex(s, { size: 32 }), + ]) + }, + } +} diff --git a/src/signatures.ts b/src/signatures.ts index 8996f90..5be2a42 100644 --- a/src/signatures.ts +++ b/src/signatures.ts @@ -1,7 +1,22 @@ -import { type Address, type Hex, recoverAddress, sliceHex } from 'viem' +import { + type Account, + type Address, + type Hex, + concatHex, + numberToHex, + recoverAddress, + size, + sliceHex, +} from 'viem' import { privateKeyToAccount } from 'viem/accounts' +import * as P256 from 'ox/P256' +import type { FrameAccountOwner } from './accounts/types.js' import { sameAddress, validateFrameTx } from './envelope.js' import { FrameEncodeError, FrameRlpError } from './errors.js' +import { + type P256FrameSigner, + p256SignerIdentity, +} from './p256.js' import { byteLength } from './rlp.js' import { frameTxSigHash } from './sighash.js' import type { FrameSignature, FrameTransaction } from './types.js' @@ -130,62 +145,146 @@ function bareRecoveryId(v: bigint, index: number): bigint { ) } -/** - * Anything that can sign a raw 32-byte digest for a known address: viem's - * `privateKeyToAccount` and `mnemonicToAccount`, a `toAccount` source, or a - * hand-rolled wrapper around a hardware wallet, an HSM or a remote signer. - * - * `sign` is optional because it is optional on viem's own `LocalAccount` — a - * `toAccount` source need not provide it — so requiring it here would reject - * every `LocalAccount` at the type level. `signFrameTx` checks for it instead. - * - * `signMessage` is deliberately not an accepted substitute: it prefixes its - * argument per EIP-191, so it cannot produce a signature over a sig-hash. - */ -export type FrameSigner = { - address: Address - sign?: ((parameters: { hash: Hex }) => Promise) | undefined +function resolveFrameSigner(signer: Hex | FrameAccountOwner): FrameAccountOwner { + return typeof signer === 'string' ? privateKeyToAccount(signer) : signer } -function resolveFrameSigner(signer: Hex | FrameSigner): FrameSigner { - return typeof signer === 'string' ? privateKeyToAccount(signer) : signer +function signerScheme(signer: FrameAccountOwner): 1 | 2 { + return signer.type === 'p256' ? 2 : 1 } -/** Sign one empty-message SECP256K1 entry without requiring other entries to be complete. */ -export async function signFrameSignature( +function schemeName(scheme: number): string { + if (scheme === 1) return 'SECP256K1' + if (scheme === 2) return 'P256' + return 'ARBITRARY' +} + +function assertSignerMatches( tx: FrameTransaction, index: number, - signer: Hex | FrameSigner, -): Promise { - const account = resolveFrameSigner(signer) - if (typeof account.sign !== 'function') + signer: FrameAccountOwner, +): void { + const resolvedSigner = resolveSigner(tx, index) + if (!sameAddress(resolvedSigner, signer.address)) throw new FrameEncodeError( - `account ${account.address} cannot sign a raw 32-byte digest: it has no ` + + `signature ${index}: resolved signer ${resolvedSigner} does not match ` + + `the signing account ${signer.address}`, + ) +} + +async function signSecp256k1Entry( + tx: FrameTransaction, + index: number, + signer: Account, + digest: Hex, +): Promise { + if (typeof signer.sign !== 'function') + throw new FrameEncodeError( + `account ${signer.address} cannot sign a raw 32-byte digest: it has no ` + '`sign` method. A JSON-RPC account cannot sign one at all, and ' + '`signMessage` is not a substitute — it EIP-191-prefixes its argument.', ) + assertSignerMatches(tx, index, signer) + const entry = tx.signatures[index]! + const flat = await signer.sign({ hash: digest }) + const r = sliceHex(flat, 0, 32) + const s = sliceHex(flat, 32, 64) + const v = bareRecoveryId(BigInt(sliceHex(flat, 64, 65)), index) + const signature = `0x${v.toString(16).padStart(2, '0')}${r.slice(2)}${s.slice(2)}` as Hex + return { ...entry, signature } +} + +async function signP256Entry( + tx: FrameTransaction, + index: number, + signer: P256FrameSigner, + digest: Hex, +): Promise { + const derivedIdentity = p256SignerIdentity(signer.publicKey) + if (!sameAddress(derivedIdentity, signer.address)) + throw new FrameEncodeError( + `P-256 signer address ${signer.address} does not match public key identity ${derivedIdentity}`, + ) + + assertSignerMatches(tx, index, signer) + const entry = tx.signatures[index]! + const compactSignature = await signer.sign({ hash: digest }) + if (size(compactSignature) !== 64) + throw new FrameEncodeError( + `signature ${index}: P-256 signer must return exactly 64 bytes (r || s)`, + ) + const r = BigInt(sliceHex(compactSignature, 0, 32)) + const returnedS = BigInt(sliceHex(compactSignature, 32, 64)) + if (r <= 0n || r >= SECP256R1_N) + throw new FrameEncodeError(`signature ${index}: signer returned r outside (0, n)`) + if (returnedS <= 0n || returnedS >= SECP256R1_N) + throw new FrameEncodeError(`signature ${index}: signer returned s outside (0, n)`) + + const s = returnedS > SECP256R1_N / 2n ? SECP256R1_N - returnedS : returnedS + const publicKey = { + prefix: 4 as const, + x: BigInt(sliceHex(signer.publicKey, 1, 33)), + y: BigInt(sliceHex(signer.publicKey, 33, 65)), + } + if (!P256.verify({ payload: digest, publicKey, signature: { r, s } })) + throw new FrameEncodeError( + `signature ${index}: signer returned a signature that does not verify against its public key`, + ) + + return { + ...entry, + signature: concatHex([ + numberToHex(r, { size: 32 }), + numberToHex(s, { size: 32 }), + sliceHex(signer.publicKey, 1), + ]), + } +} + +async function signFrameEntry( + tx: FrameTransaction, + index: number, + signer: FrameAccountOwner, + digest: Hex, +): Promise { const entry = tx.signatures[index] if (entry === undefined) throw new FrameEncodeError(`no signature at index ${index}`) - if (entry.scheme !== 1 || entry.msg !== '0x') + if (entry.msg !== '0x' || entry.scheme === 0) throw new FrameEncodeError( - `signature ${index}: slot signing requires SECP256K1 with an empty msg`, + `signature ${index}: slot signing requires SECP256K1 or P256 with an empty msg`, ) - const resolvedSigner = entry.signer ?? tx.sender - if (!sameAddress(resolvedSigner, account.address)) + const ownerScheme = signerScheme(signer) + if (entry.scheme !== ownerScheme) throw new FrameEncodeError( - `signature ${index}: resolved signer ${resolvedSigner} does not match ` + - `the signing account ${account.address}`, + `signature ${index}: ${schemeName(entry.scheme)} entry cannot be signed by ` + + `a ${schemeName(ownerScheme)} owner`, ) - const flat = await account.sign({ hash: frameTxSigHash(tx) }) - const r = sliceHex(flat, 0, 32) - const s = sliceHex(flat, 32, 64) - const v = bareRecoveryId(BigInt(sliceHex(flat, 64, 65)), index) - const signature = `0x${v.toString(16).padStart(2, '0')}${r.slice(2)}${s.slice(2)}` as Hex - const signedEntry = { ...entry, signature } + return ownerScheme === 2 + ? signP256Entry(tx, index, signer as P256FrameSigner, digest) + : signSecp256k1Entry(tx, index, signer as Account, digest) +} + +/** Sign one empty-message SECP256K1 or P256 entry. */ +export async function signFrameSignature( + tx: FrameTransaction, + index: number, + signer: Hex | FrameAccountOwner, +): Promise { + const account = resolveFrameSigner(signer) + + const entry = tx.signatures[index] + if (entry === undefined) + throw new FrameEncodeError(`no signature at index ${index}`) + const signedEntry = await signFrameEntry( + tx, + index, + account, + frameTxSigHash(tx), + ) assertCanonicalSignature(signedEntry, index) const signatures = [...tx.signatures] @@ -194,50 +293,30 @@ export async function signFrameSignature( } /** - * Sign every empty-`msg` SECP256K1 entry over the transaction's sig-hash. + * Sign every empty-`msg` SECP256K1 or P256 entry over the transaction's sig-hash. * - * Takes either a raw private key or a `FrameSigner` — a hardware wallet, a - * KMS, an HD account, anything that signs a digest for a known address. + * Takes either a raw private key or a `FrameAccountOwner`. A secp256k1 owner + * must be a viem `Account`; a P-256 owner is created by + * `privateKeyToP256Account` or implements the same interface. * * Idempotent: the sig-hash elides empty-`msg` signature bytes, so re-signing an * already-signed transaction produces the same bytes. */ export async function signFrameTx( tx: FrameTransaction, - signer: Hex | FrameSigner, + signer: Hex | FrameAccountOwner, ): Promise { const account = resolveFrameSigner(signer) - if (typeof account.sign !== 'function') - throw new FrameEncodeError( - `account ${account.address} cannot sign a raw 32-byte digest: it has no ` + - `\`sign\` method. A JSON-RPC account cannot sign one at all, and ` + - `\`signMessage\` is not a substitute — it EIP-191-prefixes its argument.`, - ) - const sign = account.sign + const scheme = signerScheme(account) const digest = frameTxSigHash(tx) const signatures = await Promise.all( tx.signatures.map(async (sig, i) => { - if (sig.scheme !== 1 || sig.msg !== '0x') return sig - - // An entry names its own signer (or, if empty, resolves to tx.sender). Signing - // it with this key when that resolved signer is some OTHER address would - // produce a signature that recovers to the wrong address — a transaction the - // chain rejects at consensus, with no error from this library unless we check. - const resolvedSigner = sig.signer ?? tx.sender - if (!sameAddress(resolvedSigner, account.address)) - throw new FrameEncodeError( - `signature ${i}: resolved signer ${resolvedSigner} does not match ` + - `the signing account ${account.address}`, - ) - - const flat = await sign({ hash: digest }) - // viem returns r||s||v with v in {27,28}; the frame layout is v||r||s with a bare id. - const r = sliceHex(flat, 0, 32) - const s = sliceHex(flat, 32, 64) - const v = bareRecoveryId(BigInt(sliceHex(flat, 64, 65)), i) - const signature = `0x${v.toString(16).padStart(2, '0')}${r.slice(2)}${s.slice(2)}` as Hex - return { ...sig, signature } + // Entries of another scheme belong to another owner, e.g. a P-256 sender + // signed earlier with `signFrameSignature` while this call signs a secp256k1 + // payer, so they are left as they are. + if (sig.scheme !== scheme || sig.msg !== '0x') return sig + return signFrameEntry(tx, i, account, digest) }), ) diff --git a/test/accounts.test.ts b/test/accounts.test.ts index 694292e..fdc2a88 100644 --- a/test/accounts.test.ts +++ b/test/accounts.test.ts @@ -1,12 +1,13 @@ import { describe, expect, test } from 'vitest' -import { createClient, custom, getAddress } from 'viem' +import { createClient, custom, getAddress, size } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' import { toFrameAccount } from '../src/accounts/toFrameAccount.js' import { toEoaFrameAccount } from '../src/accounts/toEoaFrameAccount.js' import { toEoaFramePayerAccount } from '../src/accounts/toEoaFramePayerAccount.js' import { toFramePayerAccount } from '../src/accounts/toFramePayerAccount.js' -import { recoverFrameSigner } from '../src/signatures.js' +import { privateKeyToP256Account } from '../src/p256.js' +import { recoverFrameSigner, signFrameSignature } from '../src/signatures.js' import type { FrameTransaction } from '../src/types.js' import { GOLDEN_TX } from './fixtures/golden.js' @@ -154,6 +155,33 @@ describe('toFramePayerAccount', () => { expect(payer.implementationName).toBe('test-payer') expect(await payer.getPayData(GOLDEN_TX)).toBe('0xabcd') }) + + test('accepts a P-256 owner and signs a payer-owned scheme-2 entry', async () => { + const owner = privateKeyToP256Account(`0x${'01'.padStart(64, '0')}`) + const payerAddress = getAddress('0x0000000000000000000000000000000000009999') + const payer = await toFramePayerAccount({ + owner, + getAddress: async () => payerAddress, + getPayData: async () => '0x', + getSignatureEntries: async () => [ + { scheme: 2, signer: owner.address, msg: '0x', signature: '0x' }, + ], + signFrameTransaction: async (transaction) => + signFrameSignature(transaction, 1, owner), + }) + const transaction = { + ...GOLDEN_TX, + signatures: [ + GOLDEN_TX.signatures[0]!, + { scheme: 2 as const, signer: owner.address, msg: '0x' as const, signature: '0x' as const }, + ], + } + + const signed = await payer.signFrameTransaction(transaction) + + expect(payer.owner).toBe(owner) + expect(size(signed.signatures[1]!.signature)).toBe(128) + }) }) describe('toEoaFrameAccount', () => { diff --git a/test/p256.test.ts b/test/p256.test.ts new file mode 100644 index 0000000..76c44a7 --- /dev/null +++ b/test/p256.test.ts @@ -0,0 +1,202 @@ +import { describe, expect, test } from 'vitest' +import { + concatHex, + createClient, + custom, + getAddress, + numberToHex, + sliceHex, +} from 'viem' +import { mainnet } from 'viem/chains' +import * as P256 from 'ox/P256' +import { toP256FrameAccount } from '../src/accounts/toP256FrameAccount.js' +import { FrameEncodeError } from '../src/errors.js' +import { + type P256FrameSigner, + p256SignerIdentity, + privateKeyToP256Account, +} from '../src/p256.js' +import { frameTxSigHash } from '../src/sighash.js' +import { + SECP256R1_N, + assertCanonicalSignature, + signFrameSignature, +} from '../src/signatures.js' +import { GOLDEN_TX } from './fixtures/golden.js' + +const PRIVATE_KEY = numberToHex(1n, { size: 32 }) +const DELEGATED_EOA = getAddress('0x0000000000000000000000000000000000001234') + +describe('P-256 signer identity', () => { + test('private scalar 1 derives the published P-256 generator coordinates', () => { + const signer = privateKeyToP256Account(PRIVATE_KEY) + + expect(signer.type).toBe('p256') + expect(signer.publicKey).toBe( + '0x046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296' + + '4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5', + ) + }) + + test('derives the independently pinned last-20-byte keccak identity', () => { + const signer = privateKeyToP256Account(PRIVATE_KEY) + + expect(signer.address.toLowerCase()).toBe( + '0xd3a9f047ad43d7e2e4e7e491f1fe2e657a2651b6', + ) + expect(p256SignerIdentity(signer.publicKey)).toBe(signer.address) + }) + + test('rejects a public key that is not on P-256', () => { + expect(() => + p256SignerIdentity( + concatHex([ + '0x04', + numberToHex(1n, { size: 32 }), + numberToHex(1n, { size: 32 }), + ]), + ), + ).toThrow(/not a point on the curve/) + }) +}) + +describe('signFrameSignature with a P-256 owner', () => { + test('signs the raw frame sig-hash as r || s || qx || qy', async () => { + const signer = privateKeyToP256Account(PRIVATE_KEY) + const unsigned = { + ...GOLDEN_TX, + sender: DELEGATED_EOA, + signatures: [ + { + scheme: 2 as const, + signer: signer.address, + msg: '0x' as const, + signature: '0x' as const, + }, + ], + } + const hash = frameTxSigHash(unsigned) + const signed = await signFrameSignature(unsigned, 0, signer) + const bytes = signed.signatures[0]!.signature + + expect(bytes.length).toBe(2 + 128 * 2) + expect(sliceHex(bytes, 64, 128)).toBe(sliceHex(signer.publicKey, 1)) + expect(() => assertCanonicalSignature(signed.signatures[0]!, 0)).not.toThrow() + + const signature = { + r: BigInt(sliceHex(bytes, 0, 32)), + s: BigInt(sliceHex(bytes, 32, 64)), + } + const publicKey = { + prefix: 4 as const, + x: BigInt(sliceHex(signer.publicKey, 1, 33)), + y: BigInt(sliceHex(signer.publicKey, 33, 65)), + } + expect(P256.verify({ payload: hash, publicKey, signature })).toBe(true) + expect(P256.verify({ payload: hash, publicKey, signature, hash: true })).toBe(false) + }) + + test('normalizes a valid high-s signer response', async () => { + const base = privateKeyToP256Account(PRIVATE_KEY) + const signer: P256FrameSigner = { + ...base, + async sign(parameters) { + const signature = await base.sign(parameters) + return concatHex([ + sliceHex(signature, 0, 32), + numberToHex(SECP256R1_N - BigInt(sliceHex(signature, 32, 64)), { + size: 32, + }), + ]) + }, + } + const unsigned = { + ...GOLDEN_TX, + sender: DELEGATED_EOA, + signatures: [ + { scheme: 2 as const, signer: signer.address, msg: '0x' as const, signature: '0x' as const }, + ], + } + const signed = await signFrameSignature(unsigned, 0, signer) + const s = BigInt(sliceHex(signed.signatures[0]!.signature, 32, 64)) + + expect(s).toBeLessThanOrEqual(SECP256R1_N / 2n) + }) + + test('rejects a signer response that does not verify', async () => { + const base = privateKeyToP256Account(PRIVATE_KEY) + const signer: P256FrameSigner = { + ...base, + async sign() { + return concatHex([ + numberToHex(1n, { size: 32 }), + numberToHex(1n, { size: 32 }), + ]) + }, + } + const unsigned = { + ...GOLDEN_TX, + sender: DELEGATED_EOA, + signatures: [ + { scheme: 2 as const, signer: signer.address, msg: '0x' as const, signature: '0x' as const }, + ], + } + + await expect(signFrameSignature(unsigned, 0, signer)).rejects.toThrow( + /does not verify/, + ) + }) +}) + +describe('toP256FrameAccount', () => { + test('prepares and signs scheme-2 entry zero for a delegated EOA', async () => { + const signer = privateKeyToP256Account(PRIVATE_KEY) + const client = createClient({ + chain: mainnet, + transport: custom({ async request() {} }), + }) + const account = await toP256FrameAccount({ + client, + address: DELEGATED_EOA, + owner: signer, + }) + const entries = await account.getSignatureEntries(GOLDEN_TX) + const unsigned = { + ...GOLDEN_TX, + sender: DELEGATED_EOA, + signatures: [...entries], + } + const signed = await account.signFrameTransaction(unsigned) + + expect(account.address).toBe(DELEGATED_EOA) + expect(account.owner).toBe(signer) + expect(signed.signatures[0]).toMatchObject({ + scheme: 2, + signer: signer.address, + msg: '0x', + }) + expect(signed.signatures[0]!.signature).toBe( + concatHex([ + sliceHex(signed.signatures[0]!.signature, 0, 64), + sliceHex(signer.publicKey, 1), + ]), + ) + }) + + test('rejects a transaction for a different sender', async () => { + const signer = privateKeyToP256Account(PRIVATE_KEY) + const client = createClient({ + chain: mainnet, + transport: custom({ async request() {} }), + }) + const account = await toP256FrameAccount({ + client, + address: DELEGATED_EOA, + owner: signer, + }) + + await expect(account.signFrameTransaction(GOLDEN_TX)).rejects.toThrow( + FrameEncodeError, + ) + }) +}) diff --git a/test/signatures.test.ts b/test/signatures.test.ts index ee8a893..d8ada79 100644 --- a/test/signatures.test.ts +++ b/test/signatures.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from 'vitest' import type { Address, Hex } from 'viem' -import { privateKeyToAccount } from 'viem/accounts' +import { privateKeyToAccount, toAccount } from 'viem/accounts' +import { privateKeyToP256Account } from '../src/p256.js' import { SECP256K1_N, SECP256R1_N, @@ -8,6 +9,7 @@ import { assertValidFrameTx, recoverFrameSigner, resolveSigner, + signFrameSignature, signFrameTx, } from '../src/signatures.js' import { FrameEncodeError } from '../src/errors.js' @@ -180,6 +182,18 @@ describe('signFrameTx and recoverFrameSigner', () => { expect(() => assertCanonicalSignature(signed.signatures[0]!, 0)).not.toThrow() }) + test('preserves the published scheme-1 signing bytes', async () => { + const account = privateKeyToAccount(PRIVATE_KEY) + const tx = { ...GOLDEN_TX, sender: account.address, + signatures: [{ scheme: 1 as const, signer: null, msg: '0x' as const, signature: '0x' as const }] } + const signed = await signFrameTx(tx, PRIVATE_KEY) + + expect(signed.signatures[0]!.signature).toBe( + '0x00ba2811495d0849ea73518ef0d3300622d85d4b7f80b68743b0b7d0d254df00' + + 'ac29c77311f162c523bd114d22484b6b08f856e157832705afd925dbc244358e13', + ) + }) + test('signing is stable under the elision rule', async () => { const account = privateKeyToAccount(PRIVATE_KEY) const tx = { ...GOLDEN_TX, sender: account.address, @@ -358,14 +372,12 @@ describe('signFrameTx with an account', () => { expect(viaAccount.signatures[0]!.signature).toBe(viaKey.signatures[0]!.signature) }) - // What a KMS or hardware wrapper looks like: an address and a raw-digest signer, - // with none of viem's other account surface. - test('signs with a bare { address, sign } remote signer', async () => { + test('signs with a remote signer wrapped as a viem account', async () => { const inner = privateKeyToAccount(PRIVATE_KEY) - const remote = { - address: inner.address, + const remote = toAccount({ + ...inner, sign: ({ hash }: { hash: Hex }) => inner.sign({ hash }), - } + }) const signed = await signFrameTx(oneEmptyEntry(inner.address), remote) expect(await recoverFrameSigner(signed, 0)).toBe(inner.address) }) @@ -373,13 +385,13 @@ describe('signFrameTx with an account', () => { test('signs over the transaction sig-hash, not some other digest', async () => { const inner = privateKeyToAccount(PRIVATE_KEY) const seen: Hex[] = [] - const remote = { - address: inner.address, + const remote = toAccount({ + ...inner, sign: ({ hash }: { hash: Hex }) => { seen.push(hash) return inner.sign({ hash }) }, - } + }) const tx = oneEmptyEntry(inner.address) await signFrameTx(tx, remote) expect(seen).toEqual([frameTxSigHash(tx)]) @@ -418,6 +430,80 @@ describe('signFrameTx with an account', () => { const signed = await signFrameTx(tx, account) expect(signed.signatures[0]).toEqual(p256) }) + + test('signs a secp256k1 payer after the P256 sender slot was signed', async () => { + const owner = privateKeyToP256Account(`0x${'01'.padStart(64, '0')}`) + const payer = privateKeyToAccount(PRIVATE_KEY) + const tx = { + ...GOLDEN_TX, + signatures: [ + { scheme: 2 as const, signer: owner.address, msg: '0x' as const, signature: '0x' as const }, + { scheme: 1 as const, signer: payer.address, msg: '0x' as const, signature: '0x' as const }, + ], + } + const senderSigned = await signFrameSignature(tx, 0, owner) + const signed = await signFrameTx(senderSigned, payer) + + expect(signed.signatures[0]).toEqual(senderSigned.signatures[0]) + expect(await recoverFrameSigner(signed, 1)).toBe(payer.address) + }) + + test('signs a P256 sender after the secp256k1 payer slot was signed', async () => { + const owner = privateKeyToP256Account(`0x${'01'.padStart(64, '0')}`) + const payer = privateKeyToAccount(PRIVATE_KEY) + const tx = { + ...GOLDEN_TX, + signatures: [ + { scheme: 2 as const, signer: owner.address, msg: '0x' as const, signature: '0x' as const }, + { scheme: 1 as const, signer: payer.address, msg: '0x' as const, signature: '0x' as const }, + ], + } + const payerSigned = await signFrameSignature(tx, 1, payer) + const signed = await signFrameTx(payerSigned, owner) + + expect(signed.signatures[1]).toEqual(payerSigned.signatures[1]) + expect(signed.signatures[0]!.signature).toHaveLength(2 + 128 * 2) + }) + + test('rejects a P256 slot for a secp256k1 owner', async () => { + const account = privateKeyToAccount(PRIVATE_KEY) + const tx = { + ...GOLDEN_TX, + sender: account.address, + signatures: [{ scheme: 2 as const, signer: null, msg: '0x' as const, signature: '0x' as const }], + } + await expect(signFrameSignature(tx, 0, account)).rejects.toThrow( + /P256 entry cannot be signed by a SECP256K1 owner/, + ) + }) + + test('signs a P256 entry through the shared signFrameTx path', async () => { + const owner = privateKeyToP256Account(`0x${'01'.padStart(64, '0')}`) + const tx = { + ...GOLDEN_TX, + signatures: [ + { + scheme: 2 as const, + signer: owner.address, + msg: '0x' as const, + signature: '0x' as const, + }, + ], + } + const signed = await signFrameTx(tx, owner) + + expect(signed.signatures[0]!.signature).toHaveLength(2 + 128 * 2) + expect(() => assertCanonicalSignature(signed.signatures[0]!, 0)).not.toThrow() + }) + + test('rejects a SECP256K1 entry for a P256 owner', async () => { + const owner = privateKeyToP256Account(`0x${'01'.padStart(64, '0')}`) + const tx = oneEmptyEntry(owner.address) + + await expect(signFrameSignature(tx, 0, owner)).rejects.toThrow( + /SECP256K1 entry cannot be signed by a P256 owner/, + ) + }) }) // Only the account path can reach these: `privateKeyToAccount` always returns @@ -425,8 +511,12 @@ describe('signFrameTx with an account', () => { // recovery id. Getting this wrong writes a malformed `v` byte into a signature // the chain rejects at consensus, so it is checked rather than assumed. describe('signFrameTx recovery-id normalization', () => { - const signerReturning = (address: Address, vByte: string, flat: Hex) => ({ - address, + const signerReturning = ( + inner: ReturnType, + vByte: string, + flat: Hex, + ) => toAccount({ + ...inner, sign: async () => `0x${flat.slice(2, 130)}${vByte}` as Hex, }) @@ -443,7 +533,7 @@ describe('signFrameTx recovery-id normalization', () => { const v27 = BigInt(`0x${flat.slice(130)}`) const bare = (v27 - 27n).toString(16).padStart(2, '0') - const viaBare = await signFrameTx(tx, signerReturning(inner.address, bare, flat)) + const viaBare = await signFrameTx(tx, signerReturning(inner, bare, flat)) const viaPrefixed = await signFrameTx(tx, inner) expect(viaBare.signatures[0]!.signature).toBe(viaPrefixed.signatures[0]!.signature) }) @@ -459,7 +549,7 @@ describe('signFrameTx recovery-id normalization', () => { } const flat = await inner.sign({ hash: frameTxSigHash(tx) }) await expect( - signFrameTx(tx, signerReturning(inner.address, '25', flat)), + signFrameTx(tx, signerReturning(inner, '25', flat)), ).rejects.toThrow(/signer returned v=37/) }) })