Skip to content
Closed
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
28 changes: 21 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ const raw = encodeFrameTx(signed)
```

`signFrameTx` also takes an account 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.
raw-digest `sign` (or `signP256`), which covers viem's `privateKeyToAccount` and
`mnemonicToAccount`, a `toAccount` source, and your own wrapper around a hardware wallet,
an HSM, a passkey 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.

```ts
import { privateKeyToAccount } from 'viem/accounts'
Expand All @@ -67,9 +67,23 @@ 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. `signFrameTx` also handles one signer at a time, so a
transaction with entries for two different signers needs the bytes assembled by hand.
A **P256** entry is signed when the account carries a `signP256` — a raw-digest signer
returning `r || s || qx || qy` (128 bytes, any `s`). `signFrameTx` normalizes `s` to the
low half (`n − s`), which WebAuthn and passkey signers need, but does not verify the
result: scheme 2 has no address recovery, so the signer owns `r`, `s` and the embedded
key. Without a `signP256`, a P256 entry is left untouched.

```ts
const signed = await signFrameTx(tx, {
address: '0x…',
signP256: ({ hash }) => myPasskey.sign(hash), // r||s||qx||qy, s may be high
})
```

`normalizeP256Signature(sig)` is exported for building the bytes by hand. An **ARBITRARY**
entry is always left untouched — build it yourself and let `assertValidFrameTx` check it.
`signFrameTx` handles one signer at a time, so a transaction with entries for two
different signers needs the bytes assembled by hand.

## Two things that will bite you

Expand Down
30 changes: 20 additions & 10 deletions docs/DESIGN.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# frametx-kit — design

**Date:** 2026-09-06
**Status:** implemented; binding on the code in this repository. Reviewed against ethrex `hegota-testnet` @ `19c065fa8` and the live node on 2026-09-06; §5, §6 and §9 amended for the RPC surface actually served (no raw transaction bytes). §5, §7 and §8 amended 2026-09-07 to match the module graph, strict-decode surface and entry-point name as built. §7 amended 2026-09-08: the byte-offset promise is delivered by a hand-rolled `walkRlp`, not deferred.
**Status:** implemented; binding on the code in this repository. Reviewed against ethrex `hegota-testnet` @ `19c065fa8` and the live node on 2026-09-06; §5, §6 and §9 amended for the RPC surface actually served (no raw transaction bytes). §5, §7 and §8 amended 2026-09-07 to match the module graph, strict-decode surface and entry-point name as built. §7 amended 2026-09-08: the byte-offset promise is delivered by a hand-rolled `walkRlp`, not deferred. §3 and §5 amended 2026-09-08: `signFrameTx` also signs P256 entries when the account provides a `signP256`, normalizing `s` to the low half.
**Target network:** hegota-testnet, chain ID `8141`, genesis `0x7ca0f735…cd0f2332`
**Reference client:** [`lambdaclass/ethrex`, branch `hegota-testnet`](https://github.com/lambdaclass/ethrex/tree/hegota-testnet). Every `.rs`, `.py` and `docs/*.md` path cited below is a path in that repository, not in this one.

Expand Down Expand Up @@ -133,17 +133,27 @@ introspection.
### Signing

`signFrameTx(tx, signer)` takes either a raw private key or a `FrameAccount` —
`{ address, sign }`, satisfied by viem's `privateKeyToAccount` and `mnemonicToAccount`, by a
`toAccount` source, and by any wrapper around a hardware wallet, an HSM or a remote signer.
It signs exactly the entries that are SECP256K1 with an empty `msg`, over `sig_hash`, and
refuses when an entry's resolved signer is not the account's address — otherwise the result
would recover to the wrong address and be rejected at consensus with no local error.
`{ address, sign, signP256 }`, satisfied by viem's `privateKeyToAccount` and
`mnemonicToAccount`, by a `toAccount` source, and by any wrapper around a hardware wallet,
an HSM, a passkey or a remote signer. It signs the empty-`msg` entries it can: SECP256K1
entries over `sig_hash` with `sign`, and — when the account carries a `signP256` — P256
entries too, and refuses when an entry's resolved signer is not the account's address —
otherwise the result would authenticate against the wrong address and be rejected at
consensus with no local error.

A P256 signer returns `r || s || qx || qy` with any `s`; `signFrameTx` rewrites it to
low-`s` (`normalizeP256Signature`, `s → n - s` when `s > n/2`), which is a valid ECDSA
signature against the same key and the form consensus requires — WebAuthn and passkey
signers routinely emit high `s`. It does **not** verify a P256 signature: scheme 2 has no
address recovery, so the signer owns `r`, `s` and the embedded key and the library owns
only the wire form. An ARBITRARY entry, and a P256 entry with no `signP256` available, are
left untouched for the caller to fill, then `assertValidFrameTx` checks them.

**Raw-digest signing is required.** `signMessage` prefixes its argument per EIP-191, so it
cannot produce a signature over `sig_hash`, and a `JsonRpcAccount` cannot sign a raw digest
at all. Both are refused with an error rather than silently producing an unrecoverable
signature. `sign` is typed optional because it is optional on viem's own `LocalAccount`;
the check is at runtime.
at all. An account with neither `sign` nor `signP256` is refused with an error rather than
silently producing an unrecoverable signature. Both signer fields are typed optional
because `sign` is optional on viem's own `LocalAccount`; the check is at runtime.

**A returned `v` is normalized, not assumed.** viem returns 27/28; HSMs and hand-rolled
wrappers commonly return a bare 0/1. Both are accepted. An EIP-155 `v` is refused: it
Expand Down Expand Up @@ -296,7 +306,7 @@ Ten source files in dependency order. Nothing depends on anything above it.
| `rlp` | `rlpUint`, `parseRlpUint`, `byteLength`: minimal-scalar rules viem does not enforce; `walkRlp`, an offset-tracking RLP reader that rejects the non-canonical encodings `fromRlp` accepts. | `errors` |
| `envelope` | `encodeFrameTx`, `decodeFrameTx`, `validateFrameTx`. Pure, no IO. | `rlp`, `errors`, `types`, viem `toRlp` |
| `sighash` | The elision rule plus keccak256. | `envelope` |
| `signatures` | Canonical rules, signer recovery, empty-signer resolution, signing (private key or external account), `assertValidFrameTx`. | `sighash`, `envelope` |
| `signatures` | Canonical rules, signer recovery, empty-signer resolution, signing (SECP256K1 and, with a `signP256`, P256 — `normalizeP256Signature` for low-`s`), `assertValidFrameTx`. | `sighash`, `envelope` |
| `gas` | The whole of §4, parameterized by rule set. Pure, no IO. | `rlp`, `errors`, `types` only |
| `divergence` | `compareRuleSets` and the head EIP-8250 state-gas figure. | `gas` |
| `rpc` | Typed `ethrex_simulateFrameTransaction`; frame-aware transaction and receipt formatters. | `errors`, `types` only |
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export {
type FrameAccount,
assertCanonicalSignature,
assertValidFrameTx,
normalizeP256Signature,
recoverFrameSigner,
resolveSigner,
signFrameTx,
Expand Down
124 changes: 96 additions & 28 deletions src/signatures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,38 @@ export function assertCanonicalSignature(sig: FrameSignature, index: number): vo
)
}

/**
* Rewrite a P256 signature to low-`s` form: `r || s || qx || qy` (128 bytes)
* with `s` replaced by `n - s` when `s > n/2`.
*
* ECDSA is malleable — `(r, s)` and `(r, n - s)` verify the same message against
* the same key — so this keeps the signature valid while satisfying the
* consensus rule that a frame's `s` be low. `P256VERIFY` itself accepts high
* `s`, and WebAuthn and passkey signers routinely emit it, so anything wiring
* one into a frame transaction needs this or the chain rejects the transaction.
*
* The embedded public key is untouched: `(r, n - s)` recovers against the same
* `(qx, qy)`. Structurally malformed input — wrong length, `r` or `s` outside
* `(0, n)` — throws rather than being silently repaired.
*/
export function normalizeP256Signature(signature: Hex, index = 0): Hex {
const len = signatureByteLength(signature, index)
if (len !== 128)
throw new FrameEncodeError(
`signature ${index}: p256 must be 128 bytes (r||s||qx||qy), got ${len}`,
)
const r = BigInt(sliceHex(signature, 0, 32))
const s = BigInt(sliceHex(signature, 32, 64))
if (r === 0n || r >= SECP256R1_N)
throw new FrameEncodeError(`signature ${index}: r must be in (0, n)`)
if (s === 0n || s >= SECP256R1_N)
throw new FrameEncodeError(`signature ${index}: s must be in (0, n)`)

const low = s > SECP256R1_N / 2n ? SECP256R1_N - s : s
const body = signature.slice(2)
return `0x${body.slice(0, 64)}${low.toString(16).padStart(64, '0')}${body.slice(128)}` as Hex
}

/** An empty `signer` resolves to `tx.sender`, including for EVM introspection. */
export function resolveSigner(tx: FrameTransaction, index: number): Address {
const sig = tx.signatures[index]
Expand Down Expand Up @@ -145,53 +177,89 @@ function bareRecoveryId(v: bigint, index: number): bigint {
export type FrameAccount = {
address: Address
sign?: ((parameters: { hash: Hex }) => Promise<Hex>) | undefined
/**
* Sign a raw 32-byte digest with P256 / secp256r1, returning
* `r || s || qx || qy` (128 bytes) with any `s`. `signFrameTx` runs the
* result through `normalizeP256Signature`, so a WebAuthn or passkey signer
* that hands back high-`s` needs nothing extra.
*
* `signFrameTx` does not verify a P256 signature — scheme 2 has no address
* recovery — so the signer owns the correctness of `r`, `s` and the embedded
* public key; the library owns only the wire form.
*/
signP256?: ((parameters: { hash: Hex }) => Promise<Hex>) | undefined
}

/**
* Sign every empty-`msg` SECP256K1 entry over the transaction's sig-hash.
* Sign every empty-`msg` entry this account can sign, over the transaction's
* sig-hash: SECP256K1 entries with the account's `sign`, and — when the account
* carries a `signP256` — P256 entries too, normalized to low-`s`. An ARBITRARY
* entry, and a P256 entry with no `signP256` available, are left untouched.
*
* Takes either a raw private key or a `FrameAccount` — a hardware wallet, a
* KMS, an HD account, anything that signs a digest for a known address.
* KMS, an HD account, a passkey wrapper, anything that signs a digest for a
* known address.
*
* Idempotent: the sig-hash elides empty-`msg` signature bytes, so re-signing an
* already-signed transaction produces the same bytes.
* Idempotent for SECP256K1: the sig-hash elides empty-`msg` signature bytes, so
* re-signing produces the same bytes. A P256 signer that is itself
* nondeterministic is re-invoked on every call.
*/
export async function signFrameTx(
tx: FrameTransaction,
signer: Hex | FrameAccount,
): Promise<FrameTransaction> {
const account = typeof signer === 'string' ? privateKeyToAccount(signer) : signer
if (typeof account.sign !== 'function')
const account: FrameAccount =
typeof signer === 'string' ? privateKeyToAccount(signer) : signer
const sign = account.sign
const signP256 = account.signP256
if (typeof sign !== 'function' && typeof signP256 !== '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.`,
`account ${account.address} cannot sign a raw 32-byte digest: it has ` +
`neither a \`sign\` nor a \`signP256\` 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 digest = frameTxSigHash(tx)

const signatures = await Promise.all(
tx.signatures.map(async (sig, i) => {
if (sig.scheme !== 1 || sig.msg !== '0x') return sig
if (sig.msg !== '0x') return sig
if (sig.scheme !== 1 && sig.scheme !== 2) 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.
// An entry names its own signer (or, if empty, resolves to tx.sender).
// Signing it for a different address produces a signature that fails
// authentication at consensus with no local error, so it is refused here.
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 }
const assertResolvedSigner = () => {
if (!sameAddress(resolvedSigner, account.address))
throw new FrameEncodeError(
`signature ${i}: resolved signer ${resolvedSigner} does not match ` +
`the signing account ${account.address}`,
)
}

if (sig.scheme === 1) {
if (typeof sign !== 'function')
throw new FrameEncodeError(
`signature ${i}: a SECP256K1 entry needs a \`sign\` method; this ` +
`account only signs P256.`,
)
assertResolvedSigner()
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 }
}

// scheme 2 — P256. Left to the caller when no P256 signer is available,
// the same as an ARBITRARY entry.
if (typeof signP256 !== 'function') return sig
assertResolvedSigner()
const raw = await signP256({ hash: digest })
return { ...sig, signature: normalizeP256Signature(raw, i) }
}),
)

Expand Down
Loading
Loading