From 8f4f8262edf02eec1e4fd9ddad55d72b10a3fff4 Mon Sep 17 00:00:00 2001
From: Piotr Roslaniec
Date: Mon, 16 Nov 2026 20:59:35 +0100
Subject: [PATCH] fix(solidity): revalidate DKG results at approval and harden
the DKG validator
WalletRegistry approval now re-runs the DKG validator on the committed
result and rejects a result that fails validation instead of registering
a wallet. The read-only isDkgResultValid view answers (false,
"validation reverted") instead of reverting.
EcdsaDkgValidator tightens its input checks: bounds on the misbehaved and
signing member indices and the members count, an on-curve check for the
group public key, and signature recovery that returns false on malformed
signatures.
initializeV2_1 binds the validator for proxies upgraded from an earlier
implementation. It is restricted to the proxy admin and requires an idle
DKG. Storage layout is unchanged. Existing tests are updated for the
revalidation gas cost and the new error messages.
---
.../ecdsa/contracts/EcdsaDkgValidator.sol | 76 ++++-
solidity/ecdsa/contracts/WalletRegistry.sol | 181 +++++++++---
.../ecdsa/contracts/libraries/EcdsaDkg.sol | 64 ++++-
solidity/ecdsa/test/DKGValidator.test.ts | 272 +++++++++++++++++-
.../test/WalletRegistry.Inactivity.test.ts | 15 +-
.../WalletRegistry.WalletCreation.test.ts | 134 ++++++---
.../ecdsa/test/WalletRegistry.Wallets.test.ts | 75 ++++-
solidity/ecdsa/test/utils/wallets.ts | 39 ++-
8 files changed, 715 insertions(+), 141 deletions(-)
diff --git a/solidity/ecdsa/contracts/EcdsaDkgValidator.sol b/solidity/ecdsa/contracts/EcdsaDkgValidator.sol
index fb02b3e28a..9085f5d240 100644
--- a/solidity/ecdsa/contracts/EcdsaDkgValidator.sol
+++ b/solidity/ecdsa/contracts/EcdsaDkgValidator.sol
@@ -23,7 +23,6 @@
pragma solidity 0.8.17;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
-import "@keep-network/random-beacon/contracts/libraries/BytesLib.sol";
import "@keep-network/sortition-pools/contracts/SortitionPool.sol";
import "./libraries/EcdsaDkg.sol";
@@ -38,16 +37,15 @@ import "./libraries/EcdsaDkg.sol";
/// using a free contract call and challenge the result if the
/// validation fails.
contract EcdsaDkgValidator {
- using BytesLib for bytes;
using ECDSA for bytes32;
/// @dev Size of a group in DKG.
uint256 public constant groupSize = 100;
- /// @dev The minimum number of group members needed to interact according to
- /// the protocol to produce a signature. The adversary can not learn
- /// anything about the key as long as it does not break into
- /// groupThreshold+1 of members.
+ /// @dev The minimum number of signatures a result must carry: a count of
+ /// signing positions, not distinct operators, because `selectGroup`
+ /// samples with replacement. The adversary can not learn anything
+ /// about the key with fewer than groupThreshold+1 positions.
uint256 public constant groupThreshold = 51;
/// @dev The minimum number of active and properly behaving group members
@@ -64,6 +62,10 @@ contract EcdsaDkgValidator {
/// DKG result.
uint256 public constant signatureByteSize = 65;
+ // secp256k1 field prime modulus p = 2^256 - 2^32 - 977
+ uint256 internal constant P =
+ 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
+
SortitionPool public immutable sortitionPool;
constructor(SortitionPool _sortitionPool) {
@@ -116,15 +118,41 @@ contract EcdsaDkgValidator {
return (false, "Malformed group public key");
}
+ uint256 x = uint256(bytes32(result.groupPubKey[:32]));
+ uint256 y = uint256(bytes32(result.groupPubKey[32:]));
+ // Unreachable with this curve: 7 is a quadratic non-residue mod P, so
+ // y^2 == x^3 + 7 has no solution at x = 0. Defence in depth only.
+ if (
+ x == 0 ||
+ x >= P ||
+ y >= P ||
+ mulmod(y, y, P) != addmod(mulmod(mulmod(x, x, P), x, P), 7, P)
+ ) {
+ return (false, "Malformed group public key");
+ }
+
+ if (result.members.length != groupSize) {
+ return (false, "Unexpected members count");
+ }
+
// The number of misbehaved members can not exceed the threshold.
// Misbehaved member indices needs to be unique, between [1, groupSize],
// and sorted in ascending order.
uint8[] calldata misbehavedMembersIndices = result
.misbehavedMembersIndices;
- if (groupSize - misbehavedMembersIndices.length < activeThreshold) {
+ // `length > groupSize` is checked explicitly before the subtraction:
+ // the subtraction is unchecked-safe only up to `groupSize`, and
+ // `misbehavedMembersIndices` is not bounded by its (uint8) element type.
+ if (
+ misbehavedMembersIndices.length > groupSize ||
+ groupSize - misbehavedMembersIndices.length < activeThreshold
+ ) {
return (false, "Too many members misbehaving during DKG");
}
- if (misbehavedMembersIndices.length > 1) {
+ // `length > 0` rather than `length > 1`: a one-element list is range
+ // checked too, so a lone out-of-range index is rejected here instead of
+ // underflowing on `indices[i] - 1` later.
+ if (misbehavedMembersIndices.length > 0) {
if (
misbehavedMembersIndices[0] < 1 ||
misbehavedMembersIndices[misbehavedMembersIndices.length - 1] >
@@ -232,6 +260,11 @@ contract EcdsaDkgValidator {
signingMembersIndices.length
);
for (uint256 i = 0; i < signingMembersIndices.length; i++) {
+ require(
+ signingMembersIndices[i] > 0 &&
+ signingMembersIndices[i] <= result.members.length,
+ "Signing member index out of bounds"
+ );
signingMemberIds[i] = result.members[signingMembersIndices[i] - 1];
}
@@ -243,13 +276,23 @@ contract EcdsaDkgValidator {
uint256 signaturesCount = result.signatures.length / signatureByteSize;
for (uint256 i = 0; i < signaturesCount; i++) {
- current = result.signatures.slice(
- signatureByteSize * i,
- signatureByteSize
- );
- address recoveredAddress = hash.recover(current);
+ // Slice the calldata directly. BytesLib.slice takes `bytes
+ // memory`, so calling it on calldata copied the whole signatures
+ // blob into memory on every iteration, a cost that grows with
+ // the square of the signature count.
+ current = result.signatures[signatureByteSize *
+ i:signatureByteSize * (i + 1)];
+
+ // `tryRecover` rather than `recover`: malformed `s`/`v` values are
+ // reported instead of reverting, so a signed-but-invalid result
+ // fails validation rather than taking this call down.
+ (address recoveredAddress, ECDSA.RecoverError recoverError) = hash
+ .tryRecover(current);
- if (signingMemberAddresses[i] != recoveredAddress) {
+ if (
+ recoverError != ECDSA.RecoverError.NoError ||
+ signingMemberAddresses[i] != recoveredAddress
+ ) {
return false;
}
}
@@ -259,6 +302,11 @@ contract EcdsaDkgValidator {
/// @notice Performs validation of hashed group members that actively took
/// part in DKG.
+ /// @dev The misbehaved member indices must be strictly ascending, unique,
+ /// and within [1, result.members.length] for this single-pass loop to
+ /// be correct; `validateFields` enforces all of that, plus
+ /// `result.members.length == groupSize`, before `validateMembersHash`
+ /// is reached through `validate`.
/// @param result DKG result
/// @return true if calculated result's group members hash matches with the
/// one that is challenged.
diff --git a/solidity/ecdsa/contracts/WalletRegistry.sol b/solidity/ecdsa/contracts/WalletRegistry.sol
index 55fd9a8e26..4c9d292bc4 100644
--- a/solidity/ecdsa/contracts/WalletRegistry.sol
+++ b/solidity/ecdsa/contracts/WalletRegistry.sol
@@ -34,6 +34,7 @@ import "@threshold-network/solidity-contracts/contracts/staking/IApplication.sol
import "@threshold-network/solidity-contracts/contracts/staking/IStaking.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
+import "@openzeppelin/contracts/utils/StorageSlot.sol";
contract WalletRegistry is
IWalletRegistry,
@@ -55,9 +56,9 @@ contract WalletRegistry is
/// @notice Slashing amount for submitting a malicious DKG result. Every
/// DKG result submitted can be challenged for the time of
/// `dkg.resultChallengePeriodLength`. If the DKG result submitted
- /// is challenged and proven to be malicious, the operator who
- /// submitted the malicious result is slashed for
- /// `_maliciousDkgResultSlashingAmount`.
+ /// is challenged and proven to be malicious, this amount is
+ /// requested from the staking contract for the submitting
+ /// operator, which on mainnet today applies no penalty.
uint96 internal _maliciousDkgResultSlashingAmount;
/// @notice Percentage of the staking contract malicious behavior
@@ -269,11 +270,17 @@ contract WalletRegistry is
/// @notice Raised when caller is not the authorized random beacon contract.
error CallerNotRandomBeacon();
+ /// @notice Raised when caller is not the proxy's own admin (ProxyAdmin).
+ error CallerNotProxyAdmin();
+
// Validation Errors
/// @notice Raised when allowlist address provided is zero address.
error AllowlistAddressZero();
+ /// @notice Raised when DKG validator address provided is zero address.
+ error DkgValidatorAddressZero();
+
/// @notice Raised when querying an operator that has not been registered.
error UnknownOperator();
@@ -449,6 +456,61 @@ contract WalletRegistry is
allowlist = Allowlist(_allowlist);
}
+ /// @notice EIP-1967 storage slot holding the proxy's admin address (the
+ /// ProxyAdmin contract), per https://eips.ethereum.org/EIPS/eip-1967:
+ /// `bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)`.
+ bytes32 private constant _ADMIN_SLOT =
+ 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
+
+ /// @notice Binds the DKG validator used by approval-time revalidation, for
+ /// WalletRegistry proxies upgraded from an earlier implementation.
+ /// `EcdsaDkg.Data.dkgValidator` is written only by `EcdsaDkg.init`
+ /// at deployment and has no other setter, so an upgrade needs this
+ /// entry point to move the pointer.
+ /// @dev Adds no storage: `dkgValidator` is an existing `EcdsaDkg.Data`
+ /// field. Uses `reinitializer(3)`: version 1 is `initialize`, version 2
+ /// is `initializeV2`.
+ ///
+ /// Restricted to the proxy's own admin, read live from the EIP-1967
+ /// admin slot, rather than to governance. `TransparentUpgradeableProxy`
+ /// only reaches implementation code with `msg.sender == admin` from
+ /// inside `upgradeAndCall`'s bundled delegatecall; a direct call from
+ /// the admin reverts at the proxy, so this can only ever run from a
+ /// genuine atomic upgrade.
+ ///
+ /// Install this implementation with `upgradeAndCall`, not with a bare
+ /// `upgradeTo`. On an upgraded proxy slot 152 already holds the
+ /// previous validator, so a bare `upgradeTo` leaves V2.1 approval
+ /// running against the unhardened validator: `approveResult` then
+ /// revalidates with it, which can revert on a malformed result or
+ /// accept one the hardened validator rejects. The approval hardening
+ /// therefore depends on this initializer having run. After execution,
+ /// check that `Initialized(3)` was emitted and that slot 152 holds the
+ /// new validator.
+ ///
+ /// The DKG must be IDLE: no in-flight attempt may straddle the change
+ /// of validation rules.
+ /// @param _dkgValidator Address of the hardened DKG validator contract.
+ // The version suffix is the upgrade convention that `upgradeAndCall`
+ // targets; `initializeV21` would read as a different version number.
+ // solhint-disable-next-line func-name-mixedcase
+ function initializeV2_1(DKGValidator _dkgValidator)
+ external
+ reinitializer(3)
+ {
+ if (msg.sender != StorageSlot.getAddressSlot(_ADMIN_SLOT).value) {
+ revert CallerNotProxyAdmin();
+ }
+ if (address(_dkgValidator) == address(0)) {
+ revert DkgValidatorAddressZero();
+ }
+ if (dkg.currentState() != DKG.State.IDLE) {
+ revert CurrentStateNotIdle();
+ }
+
+ dkg.dkgValidator = _dkgValidator;
+ }
+
/// @notice Withdraws application rewards for the given staking provider.
/// Rewards are withdrawn to the beneficiary returned by
/// `rolesOf(stakingProvider)` on the current authorization source.
@@ -864,20 +926,37 @@ contract WalletRegistry is
dkg.submitResult(dkgResult);
}
- /// @notice Approves DKG result. Can be called when the challenge period for
- /// the submitted result is finished. Considers the submitted result
- /// as valid, bans misbehaved group members from the sortition pool
- /// rewards, and completes the group creation by activating the
- /// candidate group. For the first `resultSubmissionTimeout` blocks
- /// after the end of the challenge period can be called only by the
- /// DKG result submitter. After that time, can be called by anyone.
- /// A new wallet based on the DKG result details.
+ /// @notice Approves DKG result once the challenge period has finished:
+ /// bans misbehaved group members from the sortition pool rewards
+ /// and activates the candidate group as a new wallet. For the first
+ /// `submitterPrecedencePeriodLength` blocks after the challenge
+ /// period only the submitter can approve a valid result; after
+ /// that, anyone can. Any account can reject an invalid result
+ /// inside that window, because revalidation runs first.
+ /// @dev The result is revalidated against `dkgValidator` at approval time,
+ /// before the submitter precedence check. When the validator returns
+ /// false or reverts, the result is rejected instead of approved: the
+ /// DKG returns to `AWAITING_RESULT`, no wallet is created, and the
+ /// rejection reaches the same seize path as a justified challenge,
+ /// which on mainnet applies no penalty (see below).
/// @param dkgResult Result to approve. Must match the submitted result
/// stored during `submitDkgResult`.
function approveDkgResult(DKG.Result calldata dkgResult) external {
uint256 gasStart = gasleft();
uint32[] memory misbehavedMembers = dkg.approveResult(dkgResult);
+ if (dkg.currentState() == DKG.State.AWAITING_RESULT) {
+ // `approveResult` rejected the result, which returns the DKG to
+ // AWAITING_RESULT and leaves `submittedResultHash` cleared. The
+ // submitter index was in range when the result was submitted, so
+ // reading it here cannot panic.
+ _punishMaliciousDkgResultSubmitter(
+ keccak256(abi.encode(dkgResult)),
+ dkgResult.members[dkgResult.submitterMemberIndex - 1]
+ );
+ return;
+ }
+
(bytes32 walletID, bytes32 publicKeyX, bytes32 publicKeyY) = wallets
.addWallet(dkgResult.membersHash, dkgResult.groupPubKey);
@@ -959,6 +1038,23 @@ contract WalletRegistry is
uint32 maliciousDkgResultSubmitterId
) = dkg.challengeResult(dkgResult);
+ _punishMaliciousDkgResultSubmitter(
+ maliciousDkgResultHash,
+ maliciousDkgResultSubmitterId
+ );
+ }
+
+ /// @notice Applies the consequences of a DKG result proven malicious, either
+ /// by `challengeDkgResult` or by an approval-time rejection in
+ /// `approveDkgResult`: attempts to slash the submitter and requires
+ /// enough gas to be left for that attempt to have been possible.
+ /// @param maliciousDkgResultHash Hash of the malicious DKG result.
+ /// @param maliciousDkgResultSubmitterId Sortition pool identifier of the
+ /// malicious submitter.
+ function _punishMaliciousDkgResultSubmitter(
+ bytes32 maliciousDkgResultHash,
+ uint32 maliciousDkgResultSubmitterId
+ ) private {
address maliciousDkgResultSubmitterAddress = sortitionPool
.getIDOperator(maliciousDkgResultSubmitterId);
@@ -967,35 +1063,22 @@ contract WalletRegistry is
maliciousDkgResultSubmitterAddress
);
- // NOT MIGRATED: Slashing call remains on TokenStaking for pragmatic
- // reasons, not functional requirements.
- //
- // Critical Context - TokenStaking.seize() is a STUB (TIP-100):
- // - Function ONLY emits NotificationReceived event
- // - NO token operations, NO storage mutations, NO economic penalty
- // - Both TokenStaking.seize() and Allowlist.seize() provide symbolic
- // slashing only (event emission for monitoring)
- // - Actual enforcement mechanism: DAO governance via requestWeightDecrease()
- //
- // Migration Decision Rationale:
- // - Bytecode cost: 100-200 bytes to route through Allowlist
- // - Benefit: Zero (both contracts provide identical symbolic behavior)
- // - Event preservation: TokenStaking event includes amount/rewardMultiplier
- // fields for monitoring continuity (though values are symbolic)
- // - Risk: Zero implementation risk (no code changes = no bugs)
+ // The slash goes to `staking`, the immutable contract the registry was
+ // deployed with (TokenStaking), not to `allowlist`.
//
- // Historical Note: The presence of staking.seize() may create a false
- // impression of economic slashing. In reality, economic slashing was
- // removed in TIP-100 implementation. This call exists for event telemetry
- // and DAO governance coordination only.
- //
- // Stakeholder Decision: Pragmatic choice to save bytecode and avoid
- // implementation risk for functionally equivalent routing options.
-
- // Attempt to slash malicious submitter. Slashing may fail silently
- // if the staking contract reverts, but challenge must complete
- // regardless. Bytecode optimization: empty catch block reduces
- // contract size by ~800 bytes (see commit 412a8e6d).
+ // On mainnet today this punishes nothing. The TokenStaking behind the
+ // deployed proxy has no `processSlashing`, its `notifiersTreasury()` is
+ // zero, and the live operators' legacy authorization for this
+ // application is zero after the migration to `Allowlist`, so `seize`
+ // queues no slashing event and pays the notifier no reward. The call
+ // succeeds without an economic effect; the call and the
+ // `DkgMaliciousResultSlashed` event below are monitoring data only.
+ // The configured amount and reward multiplier are recorded, not
+ // enforced: a challenged or rejected submitter keeps its stake and its
+ // authorization, and clearing the result costs only the caller's gas.
+
+ // Slashing may fail silently if the staking contract reverts, but the
+ // punishment must complete regardless.
// slither-disable-next-line reentrancy-events
try
staking.seize(
@@ -1011,9 +1094,8 @@ contract WalletRegistry is
maliciousDkgResultSubmitterAddress
);
} catch {
- // Should never happen but we want to ensure a non-critical path
- // failure from an external contract does not stop the challenge
- // to complete.
+ // The staking call is non-critical: its failure must not stop the
+ // cleanup from completing.
emit DkgMaliciousResultSlashingFailed(
maliciousDkgResultHash,
_maliciousDkgResultSlashingAmount,
@@ -1023,14 +1105,19 @@ contract WalletRegistry is
// Due to EIP-150, 1/64 of the gas is not forwarded to the call, and
// will be kept to execute the remaining operations in the function
- // after the call inside the try-catch.
+ // after the call inside the try-catch. This applies to the validator
+ // call made before this function by both callers: `challengeResult`
+ // and the approval-time revalidation in `approveResult`.
//
// To ensure there is no way for the caller to manipulate gas limit in
// such a way that the call inside try-catch fails with out-of-gas and
// the rest of the function is executed with the remaining 1/64 of gas,
// we require an extra gas amount to be left at the end of the call to
- // `challengeDkgResult`. This check enforces EIP-150 gas protection by
- // ensuring sufficient gas remains for safe execution.
+ // `challengeDkgResult` and of an approval-time rejection in
+ // `approveDkgResult`. A validator revert counts as a justified
+ // challenge in `challengeResult` and as a rejection in `approveResult`,
+ // so without this check a caller could pick a gas limit that makes a
+ // valid result look invalid.
if (gasleft() < dkg.parameters.resultChallengeExtraGas) {
revert NotEnoughExtraGasLeft();
}
@@ -1470,8 +1557,8 @@ contract WalletRegistry is
/// a malicious DKG result. Every DKG result submitted can be
/// challenged for the time of `dkg.resultChallengePeriodLength`.
/// If the DKG result submitted is challenged and proven to be
- /// malicious, the operator who submitted the malicious result is
- /// slashed for `_maliciousDkgResultSlashingAmount`.
+ /// malicious, it is requested for the submitting operator and on
+ /// mainnet today applies no penalty.
function slashingParameters()
external
view
diff --git a/solidity/ecdsa/contracts/libraries/EcdsaDkg.sol b/solidity/ecdsa/contracts/libraries/EcdsaDkg.sol
index ade4ced153..85c4c1a5e8 100644
--- a/solidity/ecdsa/contracts/libraries/EcdsaDkg.sol
+++ b/solidity/ecdsa/contracts/libraries/EcdsaDkg.sol
@@ -314,13 +314,32 @@ library EcdsaDkg {
complete(self);
}
- /// @notice Approves DKG result. Can be called when the challenge period for
- /// the submitted result is finished. Considers the submitted result
- /// as valid. For the first `submitterPrecedencePeriodLength`
- /// blocks after the end of the challenge period can be called only
- /// by the DKG result submitter. After that time, can be called by
- /// anyone.
- /// @dev Can be called after a challenge period for the submitted result.
+ /// @notice Rejects a DKG result during approval when validator revalidation
+ /// fails. Performs the same cleanup and submission-timeout rebase as
+ /// a successful challenge, returning the DKG to `AWAITING_RESULT`.
+ /// @param reason Rejection reason string.
+ function rejectResultAtApproval(Data storage self, string memory reason)
+ private
+ {
+ emit DkgResultChallenged(self.submittedResultHash, msg.sender, reason);
+
+ // Adjust DKG result submission block start, so submission stage starts
+ // from the beginning, exactly as `challengeResult` does.
+ self.resultSubmissionStartBlockOffset = block.number - self.startBlock;
+
+ submittedResultCleanup(self);
+ }
+
+ /// @notice Approves DKG result once the challenge period has finished.
+ /// For the first `submitterPrecedencePeriodLength` blocks only
+ /// the submitter can approve a valid result; after that, anyone
+ /// can. Any account can reject an invalid result inside that
+ /// window, because the revalidation below runs first.
+ /// @dev Revalidates the result with `dkgValidator` before the submitter
+ /// precedence check. If validation returns false or reverts the
+ /// result is rejected: the DKG returns to `AWAITING_RESULT` and an
+ /// empty `misbehavedMembers` array is returned, which the caller
+ /// detects by the state change.
/// @param result Result to approve. Must match the submitted result stored
/// during `submitResult`.
/// @return misbehavedMembers Identifiers of members who misbehaved during DKG.
@@ -346,6 +365,16 @@ library EcdsaDkg {
"Result under approval is different than the submitted one"
);
+ // Submission does not validate the result body, so this is the last
+ // point at which the group public key can be checked against the
+ // operators' signatures before it is installed as an active wallet.
+ // `isResultValid` answers a validator revert as an invalid result.
+ (bool isValid, string memory errorMsg) = isResultValid(self, result);
+ if (!isValid) {
+ rejectResultAtApproval(self, errorMsg);
+ return misbehavedMembers;
+ }
+
// Extract submitter member address. Submitter member index is in
// range [1, groupSize] so we need to -1 when fetching identifier from members
// array.
@@ -448,6 +477,9 @@ library EcdsaDkg {
}
/// @notice Checks if DKG result is valid for the current DKG.
+ /// @dev A validator revert is answered as an invalid result rather than
+ /// propagated: callers use this view to decide whether to challenge,
+ /// and a reverting read cannot be acted upon.
/// @param result DKG result.
/// @return True if the result is valid. If the result is invalid it returns
/// false and an error message.
@@ -458,7 +490,23 @@ library EcdsaDkg {
{
require(self.startBlock > 0, "DKG has not been started");
- return self.dkgValidator.validate(result, self.seed, self.startBlock);
+ // Slither 0.8.3 parses the variables of a `try` returns clause as
+ // uninitialized function locals and reports the validated values as
+ // an ignored return and a use before declaration. These three
+ // findings are tool false positives on a well-formed try/catch.
+ // slither-disable-next-line unused-return
+ try
+ self.dkgValidator.validate(result, self.seed, self.startBlock)
+ returns (
+ // slither-disable-next-line uninitialized-local,variable-scope
+ bool isValid,
+ // slither-disable-next-line uninitialized-local,variable-scope
+ string memory errorMsg
+ ) {
+ return (isValid, errorMsg);
+ } catch {
+ return (false, "validation reverted");
+ }
}
/// @notice Set setSeedTimeout parameter.
diff --git a/solidity/ecdsa/test/DKGValidator.test.ts b/solidity/ecdsa/test/DKGValidator.test.ts
index b6522dd6b5..4960901e91 100644
--- a/solidity/ecdsa/test/DKGValidator.test.ts
+++ b/solidity/ecdsa/test/DKGValidator.test.ts
@@ -25,6 +25,21 @@ import type {
const { createSnapshot, restoreSnapshot } = helpers.snapshot
+// secp256k1 field prime, `2**256 - 2**32 - 977`.
+const SECP256K1_P = BigNumber.from(
+ "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"
+)
+
+// Encodes a fabricated group public key. Both coordinates are encoded as
+// 32-byte words, so the key passes the length check at submission time even
+// when a coordinate is not a canonical field element.
+function encodeGroupPublicKey(x: BigNumber, y: BigNumber): string {
+ return ethers.utils.hexConcat([
+ ethers.utils.zeroPad(x.toHexString(), 32),
+ ethers.utils.zeroPad(y.toHexString(), 32),
+ ])
+}
+
describe("EcdsaDkgValidator", () => {
const dkgSeed: BigNumber = BigNumber.from(
"31415926535897932384626433832795028841971693993751058209749445923078164062862"
@@ -359,8 +374,116 @@ describe("EcdsaDkgValidator", () => {
await expect(result.errorMsg).to.equal("Malformed group public key")
})
})
+
+ context("when x is not a canonical field element", () => {
+ it("should return validation error", async () => {
+ // `x = P + 1` reduces to 1 modulo P and `y` is chosen so that
+ // `y^2 = 1 + 7 = 8`, so the curve equation holds for the reduced
+ // coordinates. Only the `x >= P` bound rejects this key.
+ const key = encodeGroupPublicKey(
+ SECP256K1_P.add(1),
+ BigNumber.from(
+ "0x4218f20ae6c646b363db68605822fb14264ca8d2587fdd6fbc750d587e76a7ee"
+ )
+ )
+
+ const result = await testValidateFields(
+ selectedOperators,
+ key,
+ noMisbehaved
+ )
+
+ await expect(result.isValid).to.be.false
+ await expect(result.errorMsg).to.equal("Malformed group public key")
+ })
+ })
+
+ context("when y is not a canonical field element", () => {
+ it("should return validation error", async () => {
+ // `y = P + 1` reduces to 1 modulo P. `x` is a cube root of `-6`
+ // modulo P, so `x^3 + 7 = 1 = y^2` for the reduced coordinates.
+ // Only the `y >= P` bound rejects this key.
+ const key = encodeGroupPublicKey(
+ BigNumber.from(
+ "0x1fe1e5ef3fceb5c135ab7741333ce5a6e80d68167653f6b2b24bcbcfaaaff507"
+ ),
+ SECP256K1_P.add(1)
+ )
+
+ const result = await testValidateFields(
+ selectedOperators,
+ key,
+ noMisbehaved
+ )
+
+ await expect(result.isValid).to.be.false
+ await expect(result.errorMsg).to.equal("Malformed group public key")
+ })
+ })
+
+ // The curve equation is a single comparison, so the two sides of it need
+ // their own cases: `y^2 < x^3 + 7` is still unequal, and a `<` or `>`
+ // mutant of the equality test accepts one side each. Both coordinates
+ // below are canonical field elements and `x` is not zero, so only the
+ // equation decides.
+ context("when y^2 is below x^3 + 7", () => {
+ it("should return validation error", async () => {
+ // `x = 1`, `y = 2`: `y^2 = 4` and `x^3 + 7 = 8`.
+ const key = encodeGroupPublicKey(BigNumber.from(1), BigNumber.from(2))
+
+ const result = await testValidateFields(
+ selectedOperators,
+ key,
+ noMisbehaved
+ )
+
+ await expect(result.isValid).to.be.false
+ await expect(result.errorMsg).to.equal("Malformed group public key")
+ })
+ })
+
+ context("when y^2 is above x^3 + 7", () => {
+ it("should return validation error", async () => {
+ // `x = 1`, `y = 3`: `y^2 = 9` and `x^3 + 7 = 8`.
+ const key = encodeGroupPublicKey(BigNumber.from(1), BigNumber.from(3))
+
+ const result = await testValidateFields(
+ selectedOperators,
+ key,
+ noMisbehaved
+ )
+
+ await expect(result.isValid).to.be.false
+ await expect(result.errorMsg).to.equal("Malformed group public key")
+ })
+ })
})
+ context(
+ "when misbehaved indices leave exactly the active threshold members",
+ () => {
+ it("should pass", async () => {
+ const activeThreshold = (await validator.activeThreshold()).toNumber()
+ // The rejecting case below uses 11 indices, leaving 89 active
+ // members. Ten indices leave exactly `activeThreshold` (90) active
+ // members, the accepting side of the `activeThreshold` guard.
+ const atThreshold = [2, 4, 15, 17, 50, 53, 64, 72, 84, 86]
+ await expect(atThreshold).to.have.lengthOf(
+ constants.groupSize - activeThreshold
+ )
+
+ const result = await testValidateFields(
+ selectedOperators,
+ groupPublicKey,
+ atThreshold
+ )
+
+ await expect(result.isValid).to.be.true
+ await expect(result.errorMsg).to.equal("")
+ })
+ }
+ )
+
context("when misbehaved array is malformed", () => {
context("when index is less than one", async () => {
it("should return validation error", async () => {
@@ -698,6 +821,60 @@ describe("EcdsaDkgValidator", () => {
})
})
+ // The address comparison is a single `!=`, so a relational mutant of it
+ // rejects only one side of a mismatch: `>` accepts a recovered address
+ // above the signing member's and `<` accepts one below. Each side needs a
+ // signature from a key that sorts on that side, which the deterministic
+ // Hardhat accounts do not guarantee, so the key is searched at run time.
+ const testMismatchedSignature = async (side: "above" | "below") => {
+ const dkgResult = await prepareDkgResult(
+ selectedOperators,
+ selectedOperators,
+ groupPublicKey,
+ noMisbehaved,
+ dkgStartBlock
+ )
+ // The hash `validateSignatures` signs over, without the EIP-191 prefix
+ // `signMessage` adds on both sides.
+ const resultHash = ethers.utils.keccak256(
+ ethers.utils.defaultAbiCoder.encode(
+ ["uint256", "bytes", "uint8[]", "uint256"],
+ [hardhatNetworkId, groupPublicKey, noMisbehaved, dkgStartBlock]
+ )
+ )
+ const signature = await foreignSignature(
+ selectedOperators[0].signer.address,
+ resultHash,
+ side
+ )
+ // Only the first signature changes; every other member still signs the
+ // same valid result.
+ dkgResult.signatures = ethers.utils.hexConcat([
+ signature,
+ ethers.utils.hexDataSlice(dkgResult.signatures, 65),
+ ])
+
+ return validator.validateSignatures(dkgResult, dkgStartBlock)
+ }
+
+ context(
+ "when a signature recovers an address above the signing member's",
+ () => {
+ it("should fail the validation", async () => {
+ await expect(await testMismatchedSignature("above")).to.be.false
+ })
+ }
+ )
+
+ context(
+ "when a signature recovers an address below the signing member's",
+ () => {
+ it("should fail the validation", async () => {
+ await expect(await testMismatchedSignature("below")).to.be.false
+ })
+ }
+ )
+
context("when signatures contain wrong result hash", () => {
const signWithWrongResultHash = async (signingOperators: Operator[]) => {
const wrongResultHash = ethers.utils.keccak256(
@@ -746,7 +923,7 @@ describe("EcdsaDkgValidator", () => {
})
context("when signatures consist of random bytes", () => {
- it("should revert", async () => {
+ it("should answer false instead of reverting", async () => {
const numberOfSignatures = constants.groupThreshold
const signatureHexStrLength = 2 * 65
const dkgResult = await prepareDkgResult(
@@ -762,14 +939,105 @@ describe("EcdsaDkgValidator", () => {
)}`
dkgResult.signatures = wrongSignatures
+ // 0xaaaa... has an out-of-range `s`, which ECDSA.recover rejects with
+ // a revert. A validator that reverts cannot be acted on, so
+ // validateSignatures answers false instead.
+ const isValid = await validator.validateSignatures(
+ dkgResult,
+ dkgStartBlock
+ )
+
+ await expect(isValid).to.be.false
+ })
+ })
+
+ context("when a signature recovery fails", () => {
+ it("should answer false instead of comparing zero addresses", async () => {
+ const dkgResult = await prepareDkgResult(
+ selectedOperators,
+ selectedOperators,
+ groupPublicKey,
+ noMisbehaved,
+ dkgStartBlock
+ )
+
+ // Member id 0 has no operator in the sortition pool, so
+ // `getIDOperators` answers address(0) for it. A signature with `v` 0
+ // fails recovery and answers address(0) as well, so the address
+ // comparison alone would pass; only the `recoverError` check rejects
+ // the result.
+ dkgResult.members = [0]
+ dkgResult.signingMembersIndices = [1]
+ dkgResult.signatures = ethers.utils.hexConcat([
+ ethers.utils.hexZeroPad("0x01", 32),
+ ethers.utils.hexZeroPad("0x01", 32),
+ "0x00",
+ ])
+
+ const isValid = await validator.validateSignatures(
+ dkgResult,
+ dkgStartBlock
+ )
+
+ await expect(isValid).to.be.false
+ })
+ })
+
+ context("when a signing member index is past the members array", () => {
+ it("should revert with 'Signing member index out of bounds'", async () => {
+ const dkgResult = await prepareDkgResult(
+ selectedOperators,
+ selectedOperators,
+ groupPublicKey,
+ noMisbehaved,
+ dkgStartBlock
+ )
+ // `validateFields` bounds the indices against `groupSize`, but
+ // `validateSignatures` is public and can be called on a result whose
+ // members array is shorter than the declared indices.
+ dkgResult.members = dkgResult.members.slice(0, 2)
+
await expect(
validator.validateSignatures(dkgResult, dkgStartBlock)
- ).to.be.revertedWith("ECDSA: invalid signature 's' value")
+ ).to.be.revertedWith("Signing member index out of bounds")
+
+ // Reached through `validate`, the same shape is answered as an
+ // invalid result rather than reverting.
+ const [isValid, errorMsg] = await validator.validate(
+ dkgResult,
+ dkgSeed,
+ dkgStartBlock
+ )
+ await expect(isValid).to.be.false
+ expect(errorMsg).to.equal("Unexpected members count")
})
})
})
})
+// Signs `resultHash` with a key whose address is above or below `bound`. The
+// private keys are small integers, so the search is deterministic; 1000 of them
+// straddle any fixed address with overwhelming probability.
+async function foreignSignature(
+ bound: string,
+ resultHash: string,
+ side: "above" | "below"
+): Promise {
+ const boundValue = BigNumber.from(bound.toLowerCase())
+ for (let k = 1; k < 1000; k++) {
+ const wallet = new ethers.Wallet(
+ ethers.utils.hexZeroPad(ethers.utils.hexlify(k), 32)
+ )
+ const value = BigNumber.from(wallet.address.toLowerCase())
+ const matches =
+ side === "above" ? value.gt(boundValue) : value.lt(boundValue)
+ if (matches) {
+ return wallet.signMessage(ethers.utils.arrayify(resultHash))
+ }
+ }
+ throw new Error(`no private key with an address ${side} ${bound}`)
+}
+
function shuffle(operators: Operator[]): Operator[] {
return operators
.map((v) => ({ v, sort: Math.random() }))
diff --git a/solidity/ecdsa/test/WalletRegistry.Inactivity.test.ts b/solidity/ecdsa/test/WalletRegistry.Inactivity.test.ts
index 60af82ad2f..076b3f27f8 100644
--- a/solidity/ecdsa/test/WalletRegistry.Inactivity.test.ts
+++ b/solidity/ecdsa/test/WalletRegistry.Inactivity.test.ts
@@ -55,6 +55,18 @@ describe("WalletRegistry - Inactivity", () => {
const heartbeatFailed = true
const noHeartbeatFailure = false
+ // Fixed relay entry for the `notifyOperatorInactivity` gas assertions. A
+ // random DKG seed selects a different group, and the gas the call measures
+ // moved by up to ~5 percent between otherwise identical runs, outside the
+ // assertion tolerance. A fixed seed keeps the gas assertions deterministic.
+ const fixedRelayEntry = ethers.BigNumber.from(
+ ethers.utils.keccak256(
+ ethers.utils.toUtf8Bytes(
+ "WalletRegistry.notifyOperatorInactivity gas seed"
+ )
+ )
+ )
+
before(async () => {
// eslint-disable-next-line @typescript-eslint/no-extra-semi
;({ walletRegistry, sortitionPool, randomBeacon, walletOwner, thirdParty } =
@@ -63,7 +75,8 @@ describe("WalletRegistry - Inactivity", () => {
walletRegistry,
walletOwner.wallet,
randomBeacon,
- walletPublicKey
+ walletPublicKey,
+ fixedRelayEntry
))
membersIDs = members.map((member) => member.id)
diff --git a/solidity/ecdsa/test/WalletRegistry.WalletCreation.test.ts b/solidity/ecdsa/test/WalletRegistry.WalletCreation.test.ts
index a9153f42ae..254b5d8027 100644
--- a/solidity/ecdsa/test/WalletRegistry.WalletCreation.test.ts
+++ b/solidity/ecdsa/test/WalletRegistry.WalletCreation.test.ts
@@ -14,7 +14,7 @@ import {
} from "./utils/dkg"
import { selectGroup, hashUint32Array } from "./utils/groups"
import { createNewWallet } from "./utils/wallets"
-import { submitRelayEntry } from "./utils/randomBeacon"
+import { fakeRandomBeacon, submitRelayEntry } from "./utils/randomBeacon"
import { assertGasUsed } from "./helpers/gas"
import { legacyTokenStakingAt } from "./utils/operators"
@@ -79,6 +79,29 @@ describe("WalletRegistry - Wallet Creation", async () => {
)
const walletID: string = ethers.utils.keccak256(groupPublicKey)
+ // Fixed relay entry for the `approveDkgResult` suite. Randomizing the DKG
+ // seed changes the selected group and the ordering of members, signatures,
+ // and signing indices; that changes calldata zero bytes and the storage
+ // slots the approval-time revalidation touches, shifting the measured gas
+ // by up to ~20k between otherwise identical runs.
+ const fixedRelayEntry = ethers.BigNumber.from(
+ ethers.utils.keccak256(
+ ethers.utils.toUtf8Bytes("WalletRegistry.approveDkgResult gas seed")
+ )
+ )
+
+ // Fixed relay entry for the `challengeDkgResult` suite. The gas of a
+ // challenge depends on the selected group: `selectGroup` samples with
+ // replacement, and a repeated operator is a warm storage read in the
+ // validator's member lookup where its first appearance was a cold one. A
+ // random relay entry moved the measured gas between 428,517 and 452,517; a
+ // fixed seed keeps the gas assertion deterministic.
+ const fixedChallengeRelayEntry = ethers.BigNumber.from(
+ ethers.utils.keccak256(
+ ethers.utils.toUtf8Bytes("WalletRegistry.challengeDkgResult gas seed")
+ )
+ )
+
const stubDkgResult: DkgResult = {
submitterMemberIndex: 1,
groupPubKey: ecdsaData.group1.publicKey,
@@ -1556,7 +1579,18 @@ describe("WalletRegistry - Wallet Creation", async () => {
before("submit relay entry", async () => {
await createSnapshot()
- ;({ startBlock, dkgSeed } = await submitRelayEntry(walletRegistry))
+ // The group selected from the DKG seed decides the calldata
+ // zero-byte count and the sortition pool slots approval
+ // revalidation touches, so a random relay entry moved the gas
+ // measured in this context by up to ~20k between runs. A fixed
+ // seed keeps the gas assertions deterministic.
+ const randomBeaconMock = await fakeRandomBeacon(walletRegistry)
+ // eslint-disable-next-line no-underscore-dangle
+ const tx = await walletRegistry
+ .connect(randomBeaconMock.wallet)
+ .__beaconCallback(fixedRelayEntry, 0)
+ startBlock = tx.blockNumber
+ dkgSeed = fixedRelayEntry
})
after(async () => {
@@ -1712,15 +1746,12 @@ describe("WalletRegistry - Wallet Creation", async () => {
)
})
- it("should use close to 286 000 gas", async () => {
- // Was 274 000 while the wallet owner was a smock fake, which
- // cost nothing to call. It is a `MockContract` now, so the
- // dispatch through its fallback is real work: ~12k, with call
- // recording already switched off for this suite. The +/- 1000
- // still catches a WalletRegistry-side regression, it is just
- // measured from a higher floor. In production the wallet owner
- // is a real contract and costs more than either figure.
- await assertGasUsed(tx, 286_000)
+ it("should use close to 1 795 000 gas", async () => {
+ // Was 286 000 before approval-time revalidation: the approval
+ // now reruns the DKG validator, whose dominant cost is
+ // recovering the group signatures. The reimbursement meters
+ // this portion, so the submitter is still made whole.
+ await assertGasUsed(tx, 1_795_000)
})
})
@@ -2067,8 +2098,13 @@ describe("WalletRegistry - Wallet Creation", async () => {
)
})
- it("should use close to 330 000 gas", async () => {
- await assertGasUsed(tx, 330_000, 15_000)
+ it("should use close to 1 991 000 gas", async () => {
+ // Includes the revalidation of a result with misbehaved
+ // members, on top of the signature recovery. The relay entry is
+ // pinned, so the measured value is stable; 5,000 leaves room
+ // for small benign changes in the approval path while staying
+ // far below the cost of a second revalidation.
+ await assertGasUsed(tx, 1_991_000, 5_000)
})
})
@@ -2109,8 +2145,11 @@ describe("WalletRegistry - Wallet Creation", async () => {
await expect(tx).to.not.be.reverted
})
- it("should use close to 330 000 gas", async () => {
- await assertGasUsed(await tx, 330_000, 15_000)
+ it("should use close to 254 000 gas", async () => {
+ // Duplicate misbehaved indices are caught by the hardened
+ // validator at approval, so this takes the rejection path
+ // instead of installing a wallet.
+ await assertGasUsed(await tx, 254_000, 15_000)
})
}
)
@@ -2365,9 +2404,15 @@ describe("WalletRegistry - Wallet Creation", async () => {
before("submit relay entry", async () => {
await createSnapshot()
- ;({ startBlock, dkgSeed } = await submitRelayEntry(
- walletRegistry
- ))
+ // Pinned: a random relay entry changes the selected group and
+ // therefore the gas measured in the gas assertion below.
+ const randomBeaconMock = await fakeRandomBeacon(walletRegistry)
+ // eslint-disable-next-line no-underscore-dangle
+ const tx = await walletRegistry
+ .connect(randomBeaconMock.wallet)
+ .__beaconCallback(fixedChallengeRelayEntry, 0)
+ startBlock = tx.blockNumber
+ dkgSeed = fixedChallengeRelayEntry
})
after(async () => {
@@ -2598,15 +2643,14 @@ describe("WalletRegistry - Wallet Creation", async () => {
)
})
- context.skip(
- "with dkg result submitted with unrecoverable signatures (skipped: no processSlashing on dev TokenStaking)",
+ context(
+ "with dkg result submitted with unrecoverable signatures",
async () => {
let dkgResultHash: string
let dkgResult: DkgResult
let submitter: SignerWithAddress
let challengeTx: ContractTransaction
- let slashingTx: ContractTransaction
before(async () => {
await createSnapshot()
@@ -2622,11 +2666,6 @@ describe("WalletRegistry - Wallet Creation", async () => {
challengeTx = await walletRegistry
.connect(thirdParty)
.challengeDkgResult(dkgResult)
-
- slashingTx = await legacyTokenStakingAt(
- staking,
- thirdParty
- ).processSlashing(1)
})
after(async () => {
@@ -2639,7 +2678,7 @@ describe("WalletRegistry - Wallet Creation", async () => {
.withArgs(
dkgResultHash,
await thirdParty.getAddress(),
- "validation reverted"
+ "Invalid signatures"
)
})
@@ -2659,7 +2698,14 @@ describe("WalletRegistry - Wallet Creation", async () => {
.withArgs(thirdParty.address, 0)
})
- it("should slash malicious result submitter", async () => {
+ // The slashing queue stays empty in Allowlist mode, so
+ // `processSlashing` reverts with "Nothing to process".
+ it.skip("should slash malicious result submitter (skipped: dev TokenStaking queues no slashing event)", async () => {
+ const slashingTx = await legacyTokenStakingAt(
+ staking,
+ thirdParty
+ ).processSlashing(1)
+
const stakingProvider =
await walletRegistry.operatorToStakingProvider(
submitter.address
@@ -2669,8 +2715,12 @@ describe("WalletRegistry - Wallet Creation", async () => {
.withArgs(stakingProvider, to1e18(400), false)
})
- it("should use close to 462 000 gas", async () => {
- await assertGasUsed(challengeTx, 462_000, 30_000)
+ it("should use close to 432 500 gas", async () => {
+ // Measured with the pinned relay entry above: the selected
+ // group decides how many member lookups are warm reads, so
+ // a random seed moved this value between 426k and 445k. The
+ // assertion guards the challenge path, not the seed.
+ await assertGasUsed(challengeTx, 432_500, 5_000)
})
}
)
@@ -3138,15 +3188,14 @@ describe("WalletRegistry - Wallet Creation", async () => {
)
})
- context.skip(
- "with dkg result submitted with unrecoverable signatures (skipped: no processSlashing on dev TokenStaking)",
+ context(
+ "with dkg result submitted with unrecoverable signatures",
async () => {
let dkgResultHash: string
let dkgResult: DkgResult
let submitter: SignerWithAddress
let challengeTx: ContractTransaction
- let slashingTx: ContractTransaction
before(async () => {
await createSnapshot()
@@ -3162,11 +3211,6 @@ describe("WalletRegistry - Wallet Creation", async () => {
challengeTx = await walletRegistry
.connect(thirdParty)
.challengeDkgResult(dkgResult)
-
- slashingTx = await legacyTokenStakingAt(
- staking,
- thirdParty
- ).processSlashing(1)
})
after(async () => {
@@ -3179,7 +3223,7 @@ describe("WalletRegistry - Wallet Creation", async () => {
.withArgs(
dkgResultHash,
await thirdParty.getAddress(),
- "validation reverted"
+ "Invalid signatures"
)
})
@@ -3193,7 +3237,14 @@ describe("WalletRegistry - Wallet Creation", async () => {
.withArgs(dkgResultHash, to1e18(400), submitter.address)
})
- it("should slash malicious result submitter", async () => {
+ // The slashing queue stays empty in Allowlist mode, so
+ // `processSlashing` reverts with "Nothing to process".
+ it.skip("should slash malicious result submitter (skipped: dev TokenStaking queues no slashing event)", async () => {
+ const slashingTx = await legacyTokenStakingAt(
+ staking,
+ thirdParty
+ ).processSlashing(1)
+
const stakingProvider =
await walletRegistry.operatorToStakingProvider(
submitter.address
@@ -3394,7 +3445,8 @@ describe("WalletRegistry - Wallet Creation", async () => {
context("with invalid result", async () => {
it("should return false and an error message", async () => {
- const expectedValidationResult = [false, "Malformed signatures array"]
+ // The members array holds 4 entries, not `groupSize`.
+ const expectedValidationResult = [false, "Unexpected members count"]
const validationResult = await walletRegistry.isDkgResultValid(
stubDkgResult
diff --git a/solidity/ecdsa/test/WalletRegistry.Wallets.test.ts b/solidity/ecdsa/test/WalletRegistry.Wallets.test.ts
index 7847995171..878a043c34 100644
--- a/solidity/ecdsa/test/WalletRegistry.Wallets.test.ts
+++ b/solidity/ecdsa/test/WalletRegistry.Wallets.test.ts
@@ -27,6 +27,7 @@ const validTestData = [
publicKey: ecdsaData.group1.publicKey,
expectedWalletID:
"0xa6602e554b8cf7c23538fd040e4ff3520ec680e5e5ce9a075259e613a3e5aa79",
+ useDkg: true,
},
{
context: "with leading zeros",
@@ -34,6 +35,9 @@ const validTestData = [
"0x000000440cc47779235ccb76d669590c2cd20c7e431f97e17a1093faf03291c473e661a208a8a565ca1e384059bd2ff7ff6886df081ff1229250099d388c83df",
expectedWalletID:
"0xd13b4fe9e69dde1520091494b27aab6c48a0058967551a25c525c843be472589",
+ // Not a point on secp256k1: approval-time DKG result revalidation rejects
+ // it, so this case registers the wallet directly.
+ useDkg: false,
},
{
context: "with trailing zeros",
@@ -41,6 +45,7 @@ const validTestData = [
"0x9a0544440cc47779235ccb76d669590c2cd20c7e431f97e17a1093faf03291c473e661a208a8a565ca1e384059bd2ff7ff6886df081ff1229250099d00000000",
expectedWalletID:
"0x525e77a3052a07734c5736074a94b71dd9149650ef6a4c57dac696a3e287d03c",
+ useDkg: false,
},
{
context: "with zeros in the middle",
@@ -48,6 +53,7 @@ const validTestData = [
"0x9a0544440cc47779235ccb76d669590c2cd20c7e431f97e17a1093faf0320000000061a208a8a565ca1e384059bd2ff7ff6886df081ff1229250099d388c83df",
expectedWalletID:
"0xa8b7226c57b544536f7bf805ef75c7b831488398da117644839f650c5be6cbe0",
+ useDkg: false,
},
]
@@ -57,6 +63,16 @@ describe("WalletRegistry - Wallets", async () => {
let walletOwner: Mock
let thirdParty: SignerWithAddress
+ // Fixed relay entry for the `isWalletMember` suite, which asserts on the
+ // operator at position 7 not being the one at position 6. The sortition pool
+ // can select the same operator at two positions for a random seed, so the
+ // assertion was flaky.
+ const fixedWalletSeed = ethers.BigNumber.from(
+ ethers.utils.keccak256(
+ ethers.utils.toUtf8Bytes("WalletRegistry.isWalletMember wallet seed")
+ )
+ )
+
before("load test fixture", async () => {
// eslint-disable-next-line @typescript-eslint/no-extra-semi
;({ walletRegistry, randomBeacon, walletOwner, thirdParty } =
@@ -68,16 +84,32 @@ describe("WalletRegistry - Wallets", async () => {
context("with valid public key", async () => {
validTestData.forEach((test) => {
let walletID: string
- let dkgResult: DkgResult
+ let membersIdsHash: string
before("create a wallet", async () => {
await createSnapshot()
- ;({ walletID, dkgResult } = await createNewWallet(
- walletRegistry,
- walletOwner.wallet,
- randomBeacon,
- test.publicKey
- ))
+
+ if (test.useDkg) {
+ let dkgResult: DkgResult
+ ;({ walletID, dkgResult } = await createNewWallet(
+ walletRegistry,
+ walletOwner.wallet,
+ randomBeacon,
+ test.publicKey
+ ))
+ membersIdsHash = hashUint32Array(dkgResult.members)
+ } else {
+ // A key that is not on the curve cannot reach the registry
+ // through the DKG any more, so register it directly to keep
+ // covering wallet ID derivation and the stored fields for keys
+ // with zero bytes.
+ membersIdsHash = hashUint32Array([1, 2, 3])
+ walletID = ethers.utils.keccak256(test.publicKey)
+ await walletRegistry.forceAddWallet(
+ test.publicKey,
+ membersIdsHash
+ )
+ }
})
after(async () => {
@@ -90,7 +122,7 @@ describe("WalletRegistry - Wallets", async () => {
expect(
wallet.membersIdsHash,
"unexpected members ids hash"
- ).to.be.equal(hashUint32Array(dkgResult.members))
+ ).to.be.equal(membersIdsHash)
expect(wallet.publicKeyX, "unexpected public key X").to.be.equal(
ethers.utils.hexDataSlice(test.publicKey, 0, 32)
@@ -261,12 +293,23 @@ describe("WalletRegistry - Wallets", async () => {
before("create a wallet", async () => {
await createSnapshot()
- ;({ walletID } = await createNewWallet(
- walletRegistry,
- walletOwner.wallet,
- randomBeacon,
- walletPublicKey
- ))
+
+ if (test.useDkg) {
+ // eslint-disable-next-line @typescript-eslint/no-extra-semi
+ ;({ walletID } = await createNewWallet(
+ walletRegistry,
+ walletOwner.wallet,
+ randomBeacon,
+ walletPublicKey
+ ))
+ } else {
+ // Off-curve key: see the note on `validTestData`.
+ walletID = ethers.utils.keccak256(walletPublicKey)
+ await walletRegistry.forceAddWallet(
+ walletPublicKey,
+ hashUint32Array([1, 2, 3])
+ )
+ }
})
after(async () => {
@@ -394,7 +437,9 @@ describe("WalletRegistry - Wallets", async () => {
;({ walletID, members } = await createNewWallet(
walletRegistry,
walletOwner.wallet,
- randomBeacon
+ randomBeacon,
+ ecdsaData.group1.publicKey,
+ fixedWalletSeed
))
walletMembersIDs = members.map((member) => member.id)
diff --git a/solidity/ecdsa/test/utils/wallets.ts b/solidity/ecdsa/test/utils/wallets.ts
index f7d4558136..6473744b63 100644
--- a/solidity/ecdsa/test/utils/wallets.ts
+++ b/solidity/ecdsa/test/utils/wallets.ts
@@ -4,12 +4,13 @@ import { params } from "../fixtures"
import ecdsaData from "../data/ecdsa"
import { noMisbehaved, signAndSubmitCorrectDkgResult } from "./dkg"
+import { submitRelayEntry } from "./randomBeacon"
import type { Mock } from "../helpers/mock"
import type { DkgResult } from "./dkg"
import type { IRandomBeacon, WalletRegistry } from "../../typechain"
import type { Operator } from "./operators"
-import type { BytesLike, ContractTransaction, Signer } from "ethers"
+import type { BigNumber, BytesLike, ContractTransaction, Signer } from "ethers"
const { mineBlocks } = helpers.time
const { keccak256 } = ethers.utils
@@ -19,25 +20,37 @@ export async function createNewWallet(
walletRegistry: WalletRegistry,
walletOwner: Signer,
randomBeacon: Mock,
- publicKey: BytesLike = ecdsaData.group1.publicKey
+ publicKey: BytesLike = ecdsaData.group1.publicKey,
+ // Optional fixed relay entry. Callers that assert on positions within the
+ // selected group pass one, because a random seed can select the same
+ // operator at two positions.
+ relayEntry?: BigNumber
): Promise<{
members: Operator[]
dkgResult: DkgResult
walletID: string
tx: ContractTransaction
}> {
- const requestNewWalletTx = await walletRegistry
- .connect(walletOwner)
- .requestNewWallet()
+ await walletRegistry.connect(walletOwner).requestNewWallet()
- const relayEntry = ethers.utils.randomBytes(32)
+ let startBlock: number
+ let dkgSeed: BigNumber
- const dkgSeed = ethers.BigNumber.from(keccak256(relayEntry))
-
- // eslint-disable-next-line no-underscore-dangle
- await walletRegistry
- .connect(randomBeacon.wallet)
- .__beaconCallback(relayEntry, 0)
+ if (relayEntry) {
+ // eslint-disable-next-line no-underscore-dangle
+ const tx = await walletRegistry
+ .connect(randomBeacon.wallet)
+ .__beaconCallback(relayEntry, 0)
+ startBlock = tx.blockNumber
+ dkgSeed = relayEntry
+ } else {
+ // The seed the DKG is validated against is the relay entry itself, as
+ // passed to `__beaconCallback`; `submitRelayEntry` returns exactly that
+ // value.
+ const entry = await submitRelayEntry(walletRegistry, randomBeacon)
+ startBlock = entry.startBlock
+ dkgSeed = entry.dkgSeed
+ }
const {
dkgResult,
@@ -47,7 +60,7 @@ export async function createNewWallet(
walletRegistry,
publicKey,
dkgSeed,
- requestNewWalletTx.blockNumber,
+ startBlock,
noMisbehaved
)