
Preventing Signature Replay Attacks in Solidity
Signature-based authorization is one of the most useful patterns in Solidity. It lets users approve actions off-chain and lets contracts verify those approvals on-chain. This powers gasless approvals, meta-transactions, permit-style token flows, and off-chain order systems.
The security risk is that a valid signature can sometimes be reused more than once, or in the wrong context, if the contract does not bind it to a specific domain, action, and execution state. This is known as a signature replay attack.
What a signature replay attack is
A replay attack happens when an attacker captures a valid signed message and submits it again to trigger the same action multiple times. If the contract only checks that the signature is valid, but does not check whether it has already been used, the same authorization can be executed repeatedly.
This is especially dangerous in systems that:
- transfer tokens or ETH based on signed approvals
- mint NFTs or vouchers from signed claims
- execute meta-transactions on behalf of users
- settle off-chain orders or bids
- authorize admin actions with ECDSA signatures
The core problem is not cryptography itself. ECDSA signatures are secure when used correctly. The problem is application-level replay protection.
Common replay scenarios
Replay attacks usually appear in one of these forms:
| Scenario | What goes wrong | Typical impact |
|---|---|---|
| Same-chain replay | The same signature can be submitted twice on the same contract | Double spending, duplicate minting |
| Cross-contract replay | A signature valid for one contract is accepted by another | Unauthorized execution in a cloned or related contract |
| Cross-chain replay | A signature signed for one chain is valid on another | Actions replayed on forks or multiple deployments |
| Cross-function replay | A signature intended for one action is accepted by a different function | Unexpected state changes |
| Unlimited replay | No nonce or expiration is enforced | Signature remains usable forever |
A secure design must prevent all of these where relevant.
The security model: bind, limit, and consume
Replay resistance usually comes from three controls:
- Bind the signature to a specific domain
- contract address
- chain ID
- protocol name and version
- Bind the signature to a specific action
- function name or type hash
- parameters
- recipient
- amount
- Consume the authorization once
- nonce
- unique order ID
- bitmap or mapping of used digests
- expiration deadline
If any one of these is missing, replay risk increases.
A vulnerable example
The following contract accepts a signed message authorizing a token withdrawal. It verifies the signer, but it does not track whether the signature has already been used.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
contract VulnerableWithdraw {
using ECDSA for bytes32;
address public immutable signer;
mapping(address => uint256) public balances;
constructor(address _signer) {
signer = _signer;
}
function deposit() external payable {
balances[msg.sender] += msg.value;
}
function withdraw(
address to,
uint256 amount,
uint256 deadline,
bytes calldata signature
) external {
require(block.timestamp <= deadline, "expired");
bytes32 message = keccak256(
abi.encodePacked(msg.sender, to, amount, deadline)
).toEthSignedMessageHash();
require(message.recover(signature) == signer, "invalid signature");
require(balances[msg.sender] >= amount, "insufficient balance");
balances[msg.sender] -= amount;
payable(to).transfer(amount);
}
}
Why this is vulnerable
The signed payload includes the sender, recipient, amount, and deadline. That is good, but it is still replayable until the deadline expires. An attacker who sees the signature can call withdraw() repeatedly and drain the sender’s balance as long as the balance remains sufficient.
The contract needs a nonce or equivalent one-time-use marker.
A secure pattern with nonces
A nonce is a number or identifier that can be used only once. After a signature is consumed, the contract marks the nonce as used. Any later attempt with the same nonce fails.
A practical approach is to store a per-user nonce and require the signed message to include it.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
contract SecureWithdraw {
using ECDSA for bytes32;
address public immutable signer;
mapping(address => uint256) public balances;
mapping(address => uint256) public nonces;
constructor(address _signer) {
signer = _signer;
}
function deposit() external payable {
balances[msg.sender] += msg.value;
}
function withdraw(
address to,
uint256 amount,
uint256 deadline,
uint256 nonce,
bytes calldata signature
) external {
require(block.timestamp <= deadline, "expired");
require(nonce == nonces[msg.sender], "bad nonce");
bytes32 digest = keccak256(
abi.encode(
keccak256(
"Withdraw(address owner,address to,uint256 amount,uint256 nonce,uint256 deadline)"
),
msg.sender,
to,
amount,
nonce,
deadline
)
).toEthSignedMessageHash();
require(digest.recover(signature) == signer, "invalid signature");
require(balances[msg.sender] >= amount, "insufficient balance");
nonces[msg.sender] += 1;
balances[msg.sender] -= amount;
payable(to).transfer(amount);
}
}
Why this works
- The signature is tied to a specific owner, recipient, amount, nonce, and deadline.
- The nonce must match the current expected value.
- Once used, the nonce increments and the same signature cannot be replayed.
This is the simplest and most common replay defense.
Prefer typed structured data over ad hoc hashes
Using abi.encodePacked() with raw concatenation is fragile and can create ambiguity. For security-sensitive signatures, prefer typed structured data with explicit type hashes.
The best practice is to use EIP-712 typed data signing. It gives you:
- domain separation
- explicit field typing
- better wallet UX
- lower risk of message ambiguity
EIP-712 benefits
| Feature | eth_sign / raw hash | EIP-712 |
|---|---|---|
| Domain separation | Manual | Built in |
| Typed fields | No | Yes |
| Wallet display | Poor | Clear |
| Replay resistance | Easy to get wrong | Much safer |
| Recommended for production | Rarely | Yes |
If your protocol uses signatures for anything important, EIP-712 should usually be the default.
Domain separation is not optional
A signature should not be valid across unrelated deployments. Without domain separation, the same signed message may work on multiple contracts or chains.
At minimum, bind the signature to:
address(this)block.chainid- protocol name
- protocol version
OpenZeppelin’s EIP-712 helpers make this easier and safer.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
contract OrderBook is EIP712 {
using ECDSA for bytes32;
bytes32 private constant ORDER_TYPEHASH =
keccak256("Order(address maker,address taker,uint256 amount,uint256 nonce,uint256 deadline)");
mapping(address => uint256) public nonces;
constructor() EIP712("OrderBook", "1") {}
function verify(
address maker,
address taker,
uint256 amount,
uint256 nonce,
uint256 deadline,
bytes calldata signature
) external view returns (bool) {
bytes32 structHash = keccak256(
abi.encode(
ORDER_TYPEHASH,
maker,
taker,
amount,
nonce,
deadline
)
);
bytes32 digest = _hashTypedDataV4(structHash);
return digest.recover(signature) == maker;
}
}
Here, the digest includes the contract domain automatically. A signature for one deployment will not validate on another deployment with a different domain separator.
Replay protection patterns compared
Different protocols need different replay controls. The right choice depends on scale and execution model.
| Pattern | Best for | Pros | Cons |
|---|---|---|---|
| Per-user nonce | Simple authorization flows | Easy to reason about | Sequential only |
| Per-order unique ID | Order books, vouchers | Flexible, order-specific | Requires ID management |
| Used-digest mapping | Arbitrary signed actions | Simple to implement | Storage grows with usage |
| Bitmap nonces | High-throughput systems | Gas-efficient | More complex |
| Deadline only | Never sufficient alone | Simple | Replayable until expiry |
For most applications, a per-user nonce plus deadline is the best starting point.
Avoid cross-function replay
A signature for one action should not authorize another action. This mistake happens when multiple functions reuse the same signature format without including a function-specific type hash.
For example, a signed payload for withdraw() should not also be accepted by claimReward() just because both use (user, amount, nonce).
Best practice
- Use a distinct type hash per action
- Include all action-specific parameters
- Never reuse the same digest format across unrelated functions unless that is intentional and documented
This is especially important in contracts that support multiple signed workflows.
Handle contract upgrades carefully
If a contract is upgradeable, replay protection must survive upgrades. A common mistake is changing the signed message format or nonce logic without considering old signatures.
Safe upgrade rules
- Keep the EIP-712 domain stable unless you intentionally want to invalidate old signatures
- Preserve nonce storage layout
- Do not reuse old nonces for new semantics
- If the authorization model changes, version the domain string or type hash
A version bump is often the cleanest way to invalidate old signatures after a protocol change.
Operational best practices
Use this checklist when implementing signature-based authorization:
- Use EIP-712 for user-facing signed approvals
- Include
address(this)andblock.chainidin the domain - Add a nonce or unique order ID to every signed action
- Enforce deadlines for time-sensitive permissions
- Consume the nonce before external calls when possible
- Use distinct type hashes for distinct actions
- Reject reused signatures explicitly
- Test replay attempts in your unit tests and fuzzing suite
A good test should verify that:
- the first execution succeeds
- the second execution with the same signature fails
- the same signature fails on a different contract
- the same signature fails on a different chain ID if applicable
When deadlines are useful, and when they are not
Deadlines are helpful because they reduce the window in which a stolen signature can be abused. However, they do not prevent replay by themselves.
A signature with a deadline of one hour is still replayable for that entire hour unless it also includes a nonce or consumed identifier.
Use deadlines as a time limit, not as a replay defense.
Summary
Signature replay attacks occur when a valid authorization can be reused more than once or in the wrong context. The fix is not just “verify the signature.” You must also bind the signature to the correct domain, include all relevant action data, and consume it exactly once.
The most reliable pattern is:
- EIP-712 typed data
- domain separation
- per-action type hashes
- nonce or unique ID tracking
- deadline enforcement
If you apply those controls consistently, signature-based workflows become both flexible and safe.