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
265 changes: 265 additions & 0 deletions contracts/src/multisig/EcdsaSignerManager.compact
Original file line number Diff line number Diff line change
@@ -0,0 +1,265 @@
// SPDX-License-Identifier: MIT
// OpenZeppelin Compact Contracts v0.2.0 (multisig/EcdsaSignerManager.compact)

pragma language_version >= 0.23.0;

/**
* @module EcdsaSignerManager
* @description ECDSA signature scheme manager — the signer entrance examples
* import for ECDSA-authorized multisig. Wraps the general `SignerManager<Bytes<32>>`
* registry and adds threshold ECDSA-commitment verification on top of it.
*
* Signers are identified on-chain by commitments — `persistentHash` of an ECDSA
* public key with an instance salt and a domain separator — held in one
* `SignerManager<Bytes<32>>`. `verify` checks a parallel vector of public keys
* and signatures in a single transaction: each key is hashed into a commitment,
* checked for membership and duplicates, and its signature validated, with the
* valid count folded against the threshold.
*
* This is the ECDSA member of the per-scheme manager family. Compact cannot make
* `verify` generic over a signature scheme, so each scheme is its own manager (a
* future `SchnorrSignerManager` is a sibling) that wraps the same general
* `SignerManager` registry. Caller-authorized contracts that need no signature
* verification use `SignerManager<T>` directly (see `examples/ProposalTreasury`).
*
* The registry state (signer set, count, threshold) lives in one place — the
* underlying `SignerManager<Bytes<32>>` — and every `<#n>` circuit reads it, so
* the signer count is a single source of truth. Composing modules import the
* same `../EcdsaSignerManager` path so they share that one registry.
*
* @notice ECDSA verification is stubbed (`stubVerifySignature` always returns
* true). Replace it with `ecdsaVerify` once the Compact ECDSA primitive is
* available.
*
* @notice Duplicate detection requires that presented signer commitments form a
* **strictly increasing** sequence under Compact's `Bytes`→integer order
* (first byte is the least-significant byte — the same embedding as
* `Bytes as Field`). Equal commitments therefore fail, including non-adjacent
* duplicates such as `[A, B, A]`. Callers that present `n >= 2` public
* keys/signatures must sort them by ascending commitment under that order
* before calling `verify`.
*
* Order is total on 32-byte values. Collision of distinct hash commitments is
* negligible. Comparison is implemented as two `Uint<128>` limbs (bytes 0–15
* and 16–31) so no value overflows Compact's 248-bit `Uint` cap.
*/
module EcdsaSignerManager {
import CompactStandardLibrary;
import "./SignerManager"<Bytes<32>> prefix Signer_;

// ─── Types ──────────────────────────────────────────────────────

/**
* @description Accumulator for fold-based signature verification. Threads the
* valid count, previous commitment (strictly-increasing uniqueness for any
* `n`), and message hash through each iteration.
*/
export struct VerificationState {
validCount: Uint<8>,
prevCommitment: Bytes<32>,
msgHash: Bytes<32>
}

/**
* @description Input to `persistentHash` for computing signer commitments.
* Combines the ECDSA public key with an instance-specific salt and a domain
* separator to produce a unique, unlinkable commitment.
*/
export struct SignerCommitmentInput {
pk: Bytes<64>,
salt: Bytes<32>,
domain: Bytes<32>
}

// ─── State ──────────────────────────────────────────────────────

export ledger _instanceSalt: Bytes<32>;

// ─── Setup ──────────────────────────────────────────────────────

/**
* @description Initializes the commitment signer registry and the instance
* salt. Should be called once from the consuming contract's constructor.
*
* @param {Bytes<32>} salt - Cryptographically random instance salt.
* @param {Vector<n, Bytes<32>>} signers - The signer commitments.
* @param {Uint<8>} thresh - The minimum number of approvals required.
* @returns {[]} Empty tuple.
*/
export circuit initialize<#n>(
salt: Bytes<32>,
signers: Vector<n, Bytes<32>>,
thresh: Uint<8>
): [] {
_instanceSalt = disclose(salt);
Signer_initialize<n>(signers, thresh);
}

// ─── Verification ───────────────────────────────────────────────

/**
* @description Verifies a parallel vector of public keys and signatures and
* asserts the threshold is met. Each key is hashed into a commitment, checked
* for duplicates and registry membership, and its signature validated against
* `msgHash`; the valid count is then checked against the threshold.
*
* @notice Presented commitments must be **strictly increasing** under Compact
* `Bytes`→integer order (first byte LSB; see module notice). Sort
* `pubkeys`/`signatures` by ascending commitment before calling when `n >= 2`.
*
* Requirements:
*
* - Every public key must hash to a registered signer commitment.
* - Every signature must be valid over `msgHash`.
* - Signers must be distinct: each commitment must be strictly greater than
* the previous one in presentation order (total order on `Bytes<32>`).
* - Valid count must meet the threshold.
*
* @param {Bytes<32>} msgHash - The message hash signers signed off-chain.
* @param {Vector<n, Bytes<64>>} pubkeys - ECDSA public keys of approving signers
* (ordered by ascending commitment; first byte LSB).
* @param {Vector<n, Bytes<64>>} signatures - Signatures over `msgHash` (same order).
* @returns {[]} Empty tuple.
*/
export circuit verify<#n>(
msgHash: Bytes<32>,
pubkeys: Vector<n, Bytes<64>>,
signatures: Vector<n, Bytes<64>>
): [] {
const initialState = VerificationState {
validCount: 0 as Uint<8>,
// Zero sentinel so the first commitment need only be non-zero (hash
// commitments are effectively never zero) and later ones must strictly
// increase.
prevCommitment: pad(32, ""),
msgHash: msgHash
};

const finalState = fold(verifySignature, initialState, pubkeys, signatures);
Signer_assertThresholdMet(finalState.validCount);
}
Comment on lines +124 to +140

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Generic verify<#n> still double-counts non-adjacent duplicates.

The fold only rejects commitment == state.prevCommitment. For n >= 3, an approval list like [A, B, A] increments validCount three times and can satisfy a 3-of-3 threshold with only two distinct signers. Either hard-cap this API to two presented signers for now, or add full uniqueness enforcement before exposing the generic entrypoint.

Also applies to: 187-206

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@contracts/src/multisig/EcdsaSignerManager.compact` around lines 113 - 126,
The generic verify<`#n`> entrypoint in EcdsaSignerManager.compact still allows
non-adjacent duplicate approvals to be counted multiple times, so tighten
uniqueness handling before threshold checks. Either constrain verify<`#n`> to only
support up to two presented signers, or update verifySignature/fold-based
processing to enforce full uniqueness across the entire pubkeys/signatures set
instead of only comparing against state.prevCommitment, and apply the same fix
to the other verify entrypoint mentioned in the diff.


/**
* @description Computes a signer commitment from an ECDSA public key. Pure —
* callable off-chain by the deployer to compute the constructor commitments.
*
* The commitment is `persistentHash(pk, salt, "multisig:signer:")`, where the
* salt is instance-specific (prevents cross-contract correlation) and the
* domain provides separation.
*
* @param {Bytes<64>} pk - The ECDSA public key.
* @param {Bytes<32>} salt - The instance salt.
* @returns {Bytes<32>} The signer commitment.
*/
export pure circuit _calculateSignerId(pk: Bytes<64>, salt: Bytes<32>): Bytes<32> {
return persistentHash<SignerCommitmentInput>(SignerCommitmentInput {
pk: pk,
salt: salt,
domain: pad(32, "multisig:signer:")
});
}

// ─── View ───────────────────────────────────────────────────────

/**
* @description Returns the number of registered signers.
* @returns {Uint<8>} The signer count.
*/
export circuit getSignerCount(): Uint<8> {
return Signer_getSignerCount();
}

/**
* @description Returns the approval threshold.
* @returns {Uint<8>} The threshold.
*/
export circuit getThreshold(): Uint<8> {
return Signer_getThreshold();
}

/**
* @description Returns whether the given commitment is a registered signer.
* @param {Bytes<32>} account - The commitment to check.
* @returns {Boolean} True if registered.
*/
export circuit isSigner(account: Bytes<32>): Boolean {
return Signer_isSigner(account);
}

// ─── Internal ───────────────────────────────────────────────────

/**
* @description Fold callback. Verifies one signer's approval: derives the
* commitment, enforces strictly-increasing commitments (distinct signers for
* any `n`), checks registry membership, and validates the signature.
*
* @param {VerificationState} state - Accumulator threaded through fold.
* @param {Bytes<64>} pubkey - The signer's ECDSA public key.
* @param {Bytes<64>} signature - The signer's signature over `msgHash`.
* @returns {VerificationState} Updated accumulator.
*/
circuit verifySignature(
state: VerificationState,
pubkey: Bytes<64>,
signature: Bytes<64>
): VerificationState {
const commitment = _calculateSignerId(pubkey, _instanceSalt);

// Distinct signers for any n: require strictly increasing commitments
// under Bytes→integer order (first byte LSB). Equals (including
// non-adjacent repeats) fail. Callers must present pubkeys sorted.
assert(
isStrictlyGreaterCommitment(commitment, state.prevCommitment),
"EcdsaSignerManager: duplicate or unsorted signer"
);

Signer_assertSigner(commitment);

// TODO: Replace with ecdsaVerify when the Compact ECDSA primitive is available
assert(stubVerifySignature(pubkey, state.msgHash, signature), "EcdsaSignerManager: invalid signature");

return VerificationState {
validCount: state.validCount + 1 as Uint<8>,
prevCommitment: commitment,
msgHash: state.msgHash
};
}

/**
* @description Stub for ECDSA signature verification. Always returns true.
* MUST be replaced before any non-test deployment.
*/
circuit stubVerifySignature(
pubkey: Bytes<64>,
msgHash: Bytes<32>,
signature: Bytes<64>
): Boolean {
return true;
Comment thread
0xisk marked this conversation as resolved.
}

/**
* @description True iff `a` is strictly greater than `b` under Compact's
* `Bytes`→integer embedding (first byte is least-significant — same as
* `Bytes as Field`).
*
* Compact allows `>` only on `Uint`, not on `Field` or `Bytes`. A full
* 32-byte value can exceed `Uint<248>` (runtime cast overflow), so we split
* into two 16-byte little-endian limbs, each fitting in `Uint<128>`, and
* compare high then low. Equal high limbs fall through to the low limb so
* the order is total on 32-byte values.
*
* @param {Bytes<32>} a - Candidate commitment.
* @param {Bytes<32>} b - Previous commitment in presentation order.
* @returns {Boolean} True if a > b.
*/
pure circuit isStrictlyGreaterCommitment(a: Bytes<32>, b: Bytes<32>): Boolean {
// Bytes→Uint: first byte of the slice is the least-significant byte.
// 16 bytes always fit in Uint<128> (max 2^128-1).
const aLow = slice<16>(a, 0) as Uint<128>;
const aHigh = slice<16>(a, 16) as Uint<128>;
const bLow = slice<16>(b, 0) as Uint<128>;
const bHigh = slice<16>(b, 16) as Uint<128>;
return (aHigh > bHigh) || ((aHigh == bHigh) && (aLow > bLow));
}
}

Loading