What is ecrecover in Solidity?
A dive into the waters of signatures for smart contracts
Ever wondered what the hell the deal is with the ecrecover
command in Solidity?
It's all about signatures and keys...

What is ecrecover ?
You may have seen ecrecover
in a Solidity contract before and wondered what exactly the deal with this was. Well you came across the EVM precompile ecrecover. A precompile just means a common functionality for smart contracts which has been compiled, so Ethereum nodes can run this efficiently. From a contract's perspective this is just a single command like an opcode.
Look at the following code:
function recoverSignerFromSignature(uint8 v, bytes32 r, bytes32 s, bytes32 hash) external {
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
}
This is essentially how one would use it, though there's more to it than this. Don't actually use above code in production as Patricio Palladino correctly pointed out. The correct way is shown in the last examples at the bottom of this post.

So what does all this mean? Assuming you are familiar with the basic concepts of public key cryptography, this will be easy to understand.
You may know that whenever you send a transaction to the Ethereum network, you have to sign this transaction with your private key. Naturally it makes sense to assume that Ethereum nodes have some way to verify a signature.
This functionality of verifying a signature was added to the smart contract itself. With this you can verify much more than just the transaction signature itself. In fact you can pass any data to a smart contract, hash it and then verify its signature against the data. The signature in the code above is the combination of v, r and s.
Why would I need this?
We've actually discussed several examples of how one would use this before. Those included
Essentially you can verify signed data which doesn't have to come from the transaction signer.
Which signing standards should I use?

First we need to decide on the type of signature. Yes that's right. While only for the ecrecover part this doesn't matter, for the parts around it there have been several standards that can be used by a client to sign data using an Ethereum key:
- eth_sign
- personal_sign
- EIP-712
eth_sign is for signing arbitrary data. This makes it the most powerful, the simplest (just sign data), but also the most dangerous. The big problem here is that you could get users to sign data which is actually a transaction. Imagine you have users login to your service, but you make them sign data which is actually a transaction that is 'Send 5 ETH form user to attacker'. A transaction just consists of bytes after all and people are likely to not check what this string of characters they are signing actually means. What seems like a harmless sign in just became an attack to steal funds. So generally usage of eth_sign directly is discouraged.
personal_sign was later added to solve this issue. The method prefixed any signed data with "\x19Ethereum Signed Message:\n" which meant if one was to sign transaction data, the added prefix string would make it an invalid transaction.
For more complex use cases, in particular when used in a smart contract, the EIP-712 standard was created. The standard changed over time, but the currently last version which is supported by MetaMask is signTypedData_v4. Or you could use a specific library like eip-712. The main problem EIP-712 solves is to ensure users know exactly what they are signing, for which contract address and network, and that each signature can only ever be used once at maximum. In short, this is done by signing hashes of all required configuration data (address, chain id, version, data types) + the actual data itself. ERC20-Permit is a great example on how to use it.
All functions can be used when interacting with MetaMask, see examples here. Alternatively they are available in the eth-sig-util library.
So back to the question 'Which signing standards should I use?'. From a contract's perspective use the latest EIP-712 standard! eth_sign is not safe and personal_sign is mostly useful for implementing user sign in features. In your contracts stick to EIP-712.
How to implement EIP-712
Now let's see how to implement EIP-712 in Solidity. The rough idea is
- compute a domain hash which captures the configuration data of contract address and chainId
- compute typed data hash
- combine both hashes and use it inside ecrecover
I would personally also recommend adding a nonce and deadline value which prevent replay attacks and ensure execution within a specific time. Those are not part of EIP-712 standard directly, but can easily be added. Below you'll find an example how to do all that and then execute a function with the parameters on the contract itself.
function executeMyFunctionFromSignature(
uint8 v,
bytes32 r,
bytes32 s,
address owner,
uint256 myParam,
uint256 deadline
) external {
bytes32 eip712DomainHash = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes("MyContractName")),
keccak256(bytes("1")),
block.chainid,
address(this)
)
);
bytes32 hashStruct = keccak256(
abi.encode(
keccak256("MyFunction(address owner,uint256 myParam,uint256 nonce,uint256 deadline)"),
owner,
myParam,
nonces[owner],
deadline
)
);
bytes32 hash = keccak256(abi.encodePacked("\x19\x01", eip712DomainHash, hashStruct));
address signer = ecrecover(hash, v, r, s);
require(signer == owner, "MyFunction: invalid signature");
require(signer != address(0), "ECDSA: invalid signature");
require(block.timestamp < deadline, "MyFunction: signed transaction expired");
nonces[owner]++;
_myFunction(owner, myParam);
}
Security issues with ecrecover + solution
There are a few problems with ecrecover which are not present in above code, but which you should be aware of.
- In some cases ecrecover can return a random address instead of 0 for an invalid signature. This is prevented above by the owner address inside the typed data.
- Signature are malleable, meaning you might be able to create a second also valid signature for the same data. In our case we are not using the signature data itself (which one may do as an id for example).
- An attacker can construct a hash and signature that look valid if the hash is not computed within the contract itself.
In practice I would recommend once again to use the Openzeppelin contracts. Their ECDSA implementation solves all three problems and they have an EIP-712 implementation (still a draft but usable in my opinion). Not only is this easier to use, but they also have further improvements:
- caching mechanism for eip712DomainHash, so it's only calculated whenever chainId changes (so usually just once)
- additional security checks for the signature as mentioned above
- ability to send signature as string
The code from above would then be reduced to this:
import "@openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin-contracts/contracts/utils/cryptography/draft-EIP712.sol";
contract MyContract is EIP712 {
function executeMyFunctionFromSignature(
bytes memory signature,
address owner,
uint256 myParam,
uint256 deadline
) external {
bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
keccak256("MyFunction(address owner,uint256 myParam,uint256 nonce,uint256 deadline)"),
owner,
myParam,
nonces[owner],
deadline
)));
address signer = ECDSA.recover(digest, signature);
require(signer == owner, "MyFunction: invalid signature");
require(signer != address(0), "ECDSA: invalid signature");
require(block.timestamp < deadline, "MyFunction: signed transaction expired");
nonces[owner]++;
_myFunction(owner, myParam);
}
}
That's it. Again this is the currently latest v4 standard of EIP-712. If you come across EIP-712 implementations in other contracts, be aware of which version is used.
Also as a last note, debugging invalid signatures can be very painful as any small difference in any value will lead to an invalid signature, but you don't know which of the data might be wrong. So make sure to double check all your input if you ever run into invalid signatures.
Another interesting standard is EIP-1271. Since smart contracts in Ethereum don't have a private key behind them, they cannot create those v, r, s signatures. But with this standard it's still possible to have signatures created by a contract itself, see the bottom of my previous post here.
Solidity Developer
More great blog posts from Markus Waas
How to use ChatGPT with Solidity
Using the Solidity Scholar and other GPT tips
How to integrate Uniswap 4 and create custom hooks
Let's dive into Uniswap v4's new features and integration
How to integrate Wormhole in your smart contracts
Entering a New Era of Blockchain Interoperability
Solidity Deep Dive: New Opcode 'Prevrandao'
All you need to know about the latest opcode addition
How Ethereum scales with Arbitrum Nitro and how to use it
A blockchain on a blockchain deep dive
The Ultimate Merkle Tree Guide in Solidity
Everything you need to know about Merkle trees and their future
The New Decentralized The Graph Network
What are the new features and how to use it
zkSync Guide - The future of Ethereum scaling
How the zero-knowledge tech works and how to use it
Exploring the Openzeppelin CrossChain Functionality
What is the new CrossChain support and how can you use it.
Deploying Solidity Contracts in Hedera
What is Hedera and how can you use it.
Writing ERC-20 Tests in Solidity with Foundry
Blazing fast tests, no more BigNumber.js, only Solidity
ERC-4626: Extending ERC-20 for Interest Management
How the newly finalized standard works and can help you with Defi
Advancing the NFT standard: ERC721-Permit
And how to avoid the two step approve + transferFrom with ERC721-Permit (EIP-4494)
Moonbeam: The EVM of Polkadot
Deploying and onboarding users to Moonbeam or Moonriver
Advanced MultiSwap: How to better arbitrage with Solidity
Making multiple swaps across different decentralized exchanges in a single transaction
Deploying Solidity Smart Contracts to Solana
What is Solana and how can you deploy Solidity smart contracts to it?
Smock 2: The powerful mocking tool for Hardhat
Features of smock v2 and how to use them with examples
How to deploy on Evmos: The first EVM chain on Cosmos
Deploying and onboarding users to Evmos
EIP-2535: A standard for organizing and upgrading a modular smart contract system.
Multi-Facet Proxies for full control over your upgrades
MultiSwap: How to arbitrage with Solidity
Making multiple swaps across different decentralized exchanges in a single transaction
The latest tech for scaling your contracts: Optimism
How the blockchain on a blockchain works and how to use it
Ultimate Performance: The Aurora Layer2 Network
Deploying and onboarding users to the Aurora Network powered by NEAR Protocol
How to use Binance Smart Chain in your Dapp
Deploying and onboarding users to the Binance Smart Chain (BSC)
Using the new Uniswap v3 in your contracts
What's new in Uniswap v3 and how to integrate Uniswap v3
What's coming in the London Hardfork?
Looking at all the details of the upcoming fork
Welcome to the Matrix of blockchain
How to get alerted *before* getting hacked and prevent it
The Ultimate Ethereum Mainnet Deployment Guide
All you need to know to deploy to the Ethereum mainnet
SushiSwap Explained!
Looking at the implementation details of SushiSwap
Solidity Fast Track 2: Continue Learning Solidity Fast
Continuing to learn Solidity fast with the advanced basics
What's coming in the Berlin Hardfork?
Looking at all the details of the upcoming fork
Using 1inch ChiGas tokens to reduce transaction costs
What are gas tokens and example usage for Uniswap v2
Openzeppelin Contracts v4 in Review
Taking a look at the new Openzeppelin v4 Release
EIP-3156: Creating a standard for Flash Loans
A new standard for flash loans unifying the interface + wrappers for existing ecosystems
Tornado.cash: A story of anonymity and zk-SNARKs
What is Tornado.cash, how to use it and the future
High Stakes Roulette on Ethereum
Learn by Example: Building a secure High Stakes Roulette
How to implement generalized meta transactions
We'll explore a powerful design for meta transactions based on 0x
Utilizing Bitmaps to dramatically save on Gas
A simple pattern which can save you a lot of money
Using the new Uniswap v2 as oracle in your contracts
How does the Uniswap v2 oracle function and how to integrate with it
Smock: The powerful mocking tool for Hardhat
Features of smock and how to use them with examples
How to build and use ERC-721 tokens in 2021
An intro for devs to the uniquely identifying token standard and its future
Trustless token management with Set Protocol
How to integrate token sets in your contracts
Exploring the new Solidity 0.8 Release
And how to upgrade your contracts to Solidity 0.8
How to build and use ERC-1155 tokens
An intro to the new standard for having many tokens in one
Leveraging the power of Bitcoins with RSK
Learn how RSK works and how to deploy your smart contracts to it
Solidity Fast Track: Learn Solidity Fast
'Learn X in Y minutes' this time with X = Solidity 0.7 and Y = 20
Sourcify: The future of a Decentralized Etherscan
Learn how to use the new Sourcify infrastructure today
Integrating the 0x API into your contracts
How to automatically get the best prices via 0x
How to build and use ERC-777 tokens
An intro to the new upgraded standard for ERC-20 tokens
COMP Governance Explained
How Compound's Decentralized Governance is working under the hood
How to prevent stuck tokens in contracts
And other use cases for the popular EIP-165
Understanding the World of Automated Smart Contract Analyzers
What are the best tools today and how can you use them?
A Long Way To Go: On Gasless Tokens and ERC20-Permit
And how to avoid the two step approve + transferFrom with ERC20-Permit (EIP-2612)!
Smart Contract Testing with Waffle 3
What are the features of Waffle and how to use them.
How to use xDai in your Dapp
Deploying and onboarding users to xDai to avoid the high gas costs
Stack Too Deep
Three words of horror
Integrating the new Chainlink contracts
How to use the new price feeder oracles
TheGraph: Fixing the Web3 data querying
Why we need TheGraph and how to use it
Adding Typescript to Truffle and Buidler
How to use TypeChain to utilize the powers of Typescript in your project
Integrating Balancer in your contracts
What is Balancer and how to use it
Navigating the pitfalls of securely interacting with ERC20 tokens
Figuring out how to securely interact might be harder than you think
Why you should automatically generate interests from user funds
How to integrate Aave and similar systems in your contracts
How to use Polygon (Matic) in your Dapp
Deploying and onboarding users to Polygon to avoid the high gas costs
Migrating from Truffle to Buidler
And why you should probably keep both.
Contract factories and clones
How to deploy contracts within contracts as easily and gas-efficient as possible
How to use IPFS in your Dapp?
Using the interplanetary file system in your frontend and contracts
Downsizing contracts to fight the contract size limit
What can you do to prevent your contracts from getting too large?
Using EXTCODEHASH to secure your systems
How to safely integrate anyone's smart contract
Using the new Uniswap v2 in your contracts
What's new in Uniswap v2 and how to integrate Uniswap v2
Solidity and Truffle Continuous Integration Setup
How to setup Travis or Circle CI for Truffle testing along with useful plugins.
Upcoming Devcon 2021 and other events
The Ethereum Foundation just announced the next Devcon in 2021 in Colombia
The Year of the 20: Creating an ERC20 in 2020
How to use the latest and best tools to create an ERC-20 token contract
How to get a Solidity developer job?
There are many ways to get a Solidity job and it might be easier than you think!
Design Pattern Solidity: Mock contracts for testing
Why you should make fun of your contracts
Kickstart your Dapp frontend development with create-eth-app
An overview on how to use the app and its features
The big picture of Solidity and Blockchain development in 2020
Overview of the most important technologies, services and tools that you need to know
Design Pattern Solidity: Free up unused storage
Why you should clean up after yourself
How to setup Solidity Developer Environment on Windows
What you need to know about developing on Windows
Avoiding out of gas for Truffle tests
How you do not have to worry about gas in tests anymore
Design Pattern Solidity: Stages
How you can design stages in your contract
Web3 1.2.5: Revert reason strings
How to use the new feature
Gaining back control of the internet
How Ocelot is decentralizing cloud computing
Devcon 5 - Review
Impressions from the conference
Devcon 5 - Information, Events, Links, Telegram
What you need to know
Design Pattern Solidity: Off-chain beats on-chain
Why you should do as much as possible off-chain
Design Pattern Solidity: Initialize Contract after Deployment
How to use the Initializable pattern
Consensys Blockchain Jobs Report
What the current blockchain job market looks like
Provable — Randomness Oracle
How the Oraclize random number generator works
Solidity Design Patterns: Multiply before Dividing
Why the correct order matters!
Devcon 5 Applications closing in one week
Devcon 5 Applications closing
Randomness and the Blockchain
How to achieve secure randomness for Solidity smart contracts?