Skip to content

Commit 0053ee0

Browse files
ernestognwAmxxfrangio
authored
Move ECDSA message hash methods to its own MessageHashUtils library (#4430)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com> Co-authored-by: Francisco <fg@frang.io>
1 parent 996168f commit 0053ee0

File tree

9 files changed

+179
-111
lines changed

9 files changed

+179
-111
lines changed

.changeset/hot-dingos-kiss.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'openzeppelin-solidity': major
3+
---
4+
5+
`MessageHashUtils`: Add a new library for creating message digest to be used along with signing or recovery such as ECDSA or ERC-1271. These functions are moved from the `ECDSA` library.

contracts/utils/README.adoc

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ Finally, {Create2} contains all necessary utilities to safely use the https://bl
3434

3535
{{ECDSA}}
3636

37+
{{MessageHashUtils}}
38+
3739
{{SignatureChecker}}
3840

3941
{{MerkleProof}}

contracts/utils/cryptography/ECDSA.sol

Lines changed: 12 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33

44
pragma solidity ^0.8.19;
55

6-
import {Strings} from "../Strings.sol";
7-
86
/**
97
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
108
*
@@ -34,18 +32,6 @@ library ECDSA {
3432
*/
3533
error ECDSAInvalidSignatureS(bytes32 s);
3634

37-
function _throwError(RecoverError error, bytes32 errorArg) private pure {
38-
if (error == RecoverError.NoError) {
39-
return; // no error: do nothing
40-
} else if (error == RecoverError.InvalidSignature) {
41-
revert ECDSAInvalidSignature();
42-
} else if (error == RecoverError.InvalidSignatureLength) {
43-
revert ECDSAInvalidSignatureLength(uint256(errorArg));
44-
} else if (error == RecoverError.InvalidSignatureS) {
45-
revert ECDSAInvalidSignatureS(errorArg);
46-
}
47-
}
48-
4935
/**
5036
* @dev Returns the address that signed a hashed message (`hash`) with
5137
* `signature` or error string. This address can then be used for verification purposes.
@@ -58,7 +44,7 @@ library ECDSA {
5844
* verification to be secure: it is possible to craft signatures that
5945
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
6046
* this is by receiving a hash of the original message (which may otherwise
61-
* be too long), and then calling {toEthSignedMessageHash} on it.
47+
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
6248
*
6349
* Documentation for signature generation:
6450
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
@@ -95,7 +81,7 @@ library ECDSA {
9581
* verification to be secure: it is possible to craft signatures that
9682
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
9783
* this is by receiving a hash of the original message (which may otherwise
98-
* be too long), and then calling {toEthSignedMessageHash} on it.
84+
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
9985
*/
10086
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
10187
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
@@ -169,63 +155,17 @@ library ECDSA {
169155
}
170156

171157
/**
172-
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
173-
* produces hash corresponding to the one signed with the
174-
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
175-
* JSON-RPC method as part of EIP-191.
176-
*
177-
* See {recover}.
178-
*/
179-
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
180-
// 32 is the length in bytes of hash,
181-
// enforced by the type signature above
182-
/// @solidity memory-safe-assembly
183-
assembly {
184-
mstore(0x00, "\x19Ethereum Signed Message:\n32")
185-
mstore(0x1c, hash)
186-
message := keccak256(0x00, 0x3c)
187-
}
188-
}
189-
190-
/**
191-
* @dev Returns an Ethereum Signed Message, created from `s`. This
192-
* produces hash corresponding to the one signed with the
193-
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
194-
* JSON-RPC method as part of EIP-191.
195-
*
196-
* See {recover}.
158+
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
197159
*/
198-
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
199-
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
200-
}
201-
202-
/**
203-
* @dev Returns an Ethereum Signed Typed Data, created from a
204-
* `domainSeparator` and a `structHash`. This produces hash corresponding
205-
* to the one signed with the
206-
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
207-
* JSON-RPC method as part of EIP-712.
208-
*
209-
* See {recover}.
210-
*/
211-
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
212-
/// @solidity memory-safe-assembly
213-
assembly {
214-
let ptr := mload(0x40)
215-
mstore(ptr, hex"19_01")
216-
mstore(add(ptr, 0x02), domainSeparator)
217-
mstore(add(ptr, 0x22), structHash)
218-
data := keccak256(ptr, 0x42)
160+
function _throwError(RecoverError error, bytes32 errorArg) private pure {
161+
if (error == RecoverError.NoError) {
162+
return; // no error: do nothing
163+
} else if (error == RecoverError.InvalidSignature) {
164+
revert ECDSAInvalidSignature();
165+
} else if (error == RecoverError.InvalidSignatureLength) {
166+
revert ECDSAInvalidSignatureLength(uint256(errorArg));
167+
} else if (error == RecoverError.InvalidSignatureS) {
168+
revert ECDSAInvalidSignatureS(errorArg);
219169
}
220170
}
221-
222-
/**
223-
* @dev Returns an Ethereum Signed Data with intended validator, created from a
224-
* `validator` and `data` according to the version 0 of EIP-191.
225-
*
226-
* See {recover}.
227-
*/
228-
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
229-
return keccak256(abi.encodePacked(hex"19_00", validator, data));
230-
}
231171
}

contracts/utils/cryptography/EIP712.sol

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,17 @@
33

44
pragma solidity ^0.8.19;
55

6-
import {ECDSA} from "./ECDSA.sol";
6+
import {MessageHashUtils} from "./MessageHashUtils.sol";
77
import {ShortStrings, ShortString} from "../ShortStrings.sol";
88
import {IERC5267} from "../../interfaces/IERC5267.sol";
99

1010
/**
1111
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
1212
*
13-
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
14-
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
15-
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
13+
* The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
14+
* encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
15+
* does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
16+
* produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
1617
*
1718
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
1819
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
@@ -25,7 +26,7 @@ import {IERC5267} from "../../interfaces/IERC5267.sol";
2526
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
2627
*
2728
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
28-
* separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
29+
* separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
2930
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
3031
*
3132
* @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
@@ -104,7 +105,7 @@ abstract contract EIP712 is IERC5267 {
104105
* ```
105106
*/
106107
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
107-
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
108+
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
108109
}
109110

110111
/**
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
// SPDX-License-Identifier: MIT
2+
3+
pragma solidity ^0.8.19;
4+
5+
import {Strings} from "../Strings.sol";
6+
7+
/**
8+
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
9+
*
10+
* The library provides methods for generating a hash of a message that conforms to the
11+
* https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
12+
* specifications.
13+
*/
14+
library MessageHashUtils {
15+
/**
16+
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
17+
* `0x45` (`personal_sign` messages).
18+
*
19+
* The digest is calculated by prefixing a bytes32 `messageHash` with
20+
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
21+
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
22+
*
23+
* NOTE: The `hash` parameter is intended to be the result of hashing a raw message with
24+
* keccak256, althoguh any bytes32 value can be safely used because the final digest will
25+
* be re-hashed.
26+
*
27+
* See {ECDSA-recover}.
28+
*/
29+
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
30+
/// @solidity memory-safe-assembly
31+
assembly {
32+
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
33+
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
34+
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
35+
}
36+
}
37+
38+
/**
39+
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
40+
* `0x45` (`personal_sign` messages).
41+
*
42+
* The digest is calculated by prefixing an arbitrary `message` with
43+
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
44+
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
45+
*
46+
* See {ECDSA-recover}.
47+
*/
48+
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32 digest) {
49+
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(message.length), message));
50+
}
51+
52+
/**
53+
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
54+
* `0x00` (data with intended validator).
55+
*
56+
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
57+
* `validator` address. Then hashing the result.
58+
*
59+
* See {ECDSA-recover}.
60+
*/
61+
function toDataWithIntendedValidatorHash(
62+
address validator,
63+
bytes memory data
64+
) internal pure returns (bytes32 digest) {
65+
return keccak256(abi.encodePacked(hex"19_00", validator, data));
66+
}
67+
68+
/**
69+
* @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
70+
*
71+
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
72+
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
73+
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
74+
*
75+
* See {ECDSA-recover}.
76+
*/
77+
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
78+
/// @solidity memory-safe-assembly
79+
assembly {
80+
let ptr := mload(0x40)
81+
mstore(ptr, hex"19_01")
82+
mstore(add(ptr, 0x02), domainSeparator)
83+
mstore(add(ptr, 0x22), structHash)
84+
digest := keccak256(ptr, 0x42)
85+
}
86+
}
87+
}

docs/modules/ROOT/pages/utilities.adoc

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,12 @@ The OpenZeppelin Contracts provide a ton of useful utilities that you can use in
99

1010
xref:api:utils.adoc#ECDSA[`ECDSA`] provides functions for recovering and managing Ethereum account ECDSA signatures. These are often generated via https://web3js.readthedocs.io/en/v1.7.3/web3-eth.html#sign[`web3.eth.sign`], and are a 65 byte array (of type `bytes` in Solidity) arranged the following way: `[[v (1)], [r (32)], [s (32)]]`.
1111

12-
The data signer can be recovered with xref:api:utils.adoc#ECDSA-recover-bytes32-bytes-[`ECDSA.recover`], and its address compared to verify the signature. Most wallets will hash the data to sign and add the prefix '\x19Ethereum Signed Message:\n', so when attempting to recover the signer of an Ethereum signed message hash, you'll want to use xref:api:utils.adoc#ECDSA-toEthSignedMessageHash-bytes32-[`toEthSignedMessageHash`].
12+
The data signer can be recovered with xref:api:utils.adoc#ECDSA-recover-bytes32-bytes-[`ECDSA.recover`], and its address compared to verify the signature. Most wallets will hash the data to sign and add the prefix '\x19Ethereum Signed Message:\n', so when attempting to recover the signer of an Ethereum signed message hash, you'll want to use xref:api:utils.adoc#MessageHashUtils-toEthSignedMessageHash-bytes32-[`toEthSignedMessageHash`].
1313

1414
[source,solidity]
1515
----
1616
using ECDSA for bytes32;
17+
using MessageHashUtils for bytes32;
1718
1819
function _verify(bytes32 data, bytes memory signature, address account) internal pure returns (bool) {
1920
return data
@@ -22,7 +23,7 @@ function _verify(bytes32 data, bytes memory signature, address account) internal
2223
}
2324
----
2425

25-
WARNING: Getting signature verification right is not trivial: make sure you fully read and understand xref:api:utils.adoc#ECDSA[`ECDSA`]'s documentation.
26+
WARNING: Getting signature verification right is not trivial: make sure you fully read and understand xref:api:utils.adoc#MessageHashUtils[`MessageHashUtils`]'s and xref:api:utils.adoc#ECDSA[`ECDSA`]'s documentation.
2627

2728
=== Verifying Merkle Proofs
2829

scripts/upgradeable/upgradeable.patch

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -126,20 +126,20 @@ index df141192..1cf90ad1 100644
126126
"keywords": [
127127
"solidity",
128128
diff --git a/contracts/utils/cryptography/EIP712.sol b/contracts/utils/cryptography/EIP712.sol
129-
index ff34e814..a9d08d5c 100644
129+
index 36f076e5..90c1db78 100644
130130
--- a/contracts/utils/cryptography/EIP712.sol
131131
+++ b/contracts/utils/cryptography/EIP712.sol
132132
@@ -4,7 +4,6 @@
133133
pragma solidity ^0.8.19;
134134

135-
import {ECDSA} from "./ECDSA.sol";
135+
import {MessageHashUtils} from "./MessageHashUtils.sol";
136136
-import {ShortStrings, ShortString} from "../ShortStrings.sol";
137137
import {IERC5267} from "../../interfaces/IERC5267.sol";
138138

139139
/**
140-
@@ -27,28 +26,18 @@ import {IERC5267} from "../../interfaces/IERC5267.sol";
140+
@@ -28,28 +27,18 @@ import {IERC5267} from "../../interfaces/IERC5267.sol";
141141
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
142-
* separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
142+
* separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
143143
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
144144
- *
145145
- * @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
@@ -170,7 +170,7 @@ index ff34e814..a9d08d5c 100644
170170

171171
/**
172172
* @dev Initializes the domain separator and parameter caches.
173-
@@ -63,29 +52,23 @@ abstract contract EIP712 is IERC5267 {
173+
@@ -64,29 +53,23 @@ abstract contract EIP712 is IERC5267 {
174174
* contract upgrade].
175175
*/
176176
constructor(string memory name, string memory version) {
@@ -208,7 +208,7 @@ index ff34e814..a9d08d5c 100644
208208
}
209209

210210
/**
211-
@@ -124,6 +107,10 @@ abstract contract EIP712 is IERC5267 {
211+
@@ -125,6 +108,10 @@ abstract contract EIP712 is IERC5267 {
212212
uint256[] memory extensions
213213
)
214214
{
@@ -219,7 +219,7 @@ index ff34e814..a9d08d5c 100644
219219
return (
220220
hex"0f", // 01111
221221
_EIP712Name(),
222-
@@ -138,22 +125,62 @@ abstract contract EIP712 is IERC5267 {
222+
@@ -139,22 +126,62 @@ abstract contract EIP712 is IERC5267 {
223223
/**
224224
* @dev The name parameter for the EIP712 domain.
225225
*

test/utils/cryptography/ECDSA.test.js

Lines changed: 1 addition & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
require('@openzeppelin/test-helpers');
22
const { expectRevertCustomError } = require('../../helpers/customError');
3-
const { toEthSignedMessageHash, toDataWithIntendedValidatorHash } = require('../../helpers/sign');
3+
const { toEthSignedMessageHash } = require('../../helpers/sign');
44

55
const { expect } = require('chai');
66

@@ -9,7 +9,6 @@ const ECDSA = artifacts.require('$ECDSA');
99
const TEST_MESSAGE = web3.utils.sha3('OpenZeppelin');
1010
const WRONG_MESSAGE = web3.utils.sha3('Nope');
1111
const NON_HASH_MESSAGE = '0x' + Buffer.from('abcd').toString('hex');
12-
const RANDOM_ADDRESS = web3.utils.toChecksumAddress(web3.utils.randomHex(20));
1312

1413
function to2098Format(signature) {
1514
const long = web3.utils.hexToBytes(signature);
@@ -243,26 +242,4 @@ contract('ECDSA', function (accounts) {
243242
expect(() => to2098Format(highSSignature)).to.throw("invalid signature 's' value");
244243
});
245244
});
246-
247-
context('toEthSignedMessageHash', function () {
248-
it('prefixes bytes32 data correctly', async function () {
249-
expect(await this.ecdsa.methods['$toEthSignedMessageHash(bytes32)'](TEST_MESSAGE)).to.equal(
250-
toEthSignedMessageHash(TEST_MESSAGE),
251-
);
252-
});
253-
254-
it('prefixes dynamic length data correctly', async function () {
255-
expect(await this.ecdsa.methods['$toEthSignedMessageHash(bytes)'](NON_HASH_MESSAGE)).to.equal(
256-
toEthSignedMessageHash(NON_HASH_MESSAGE),
257-
);
258-
});
259-
});
260-
261-
context('toDataWithIntendedValidatorHash', function () {
262-
it('returns the hash correctly', async function () {
263-
expect(
264-
await this.ecdsa.methods['$toDataWithIntendedValidatorHash(address,bytes)'](RANDOM_ADDRESS, NON_HASH_MESSAGE),
265-
).to.equal(toDataWithIntendedValidatorHash(RANDOM_ADDRESS, NON_HASH_MESSAGE));
266-
});
267-
});
268245
});

0 commit comments

Comments
 (0)