Skip to content

Commit

Permalink
fix(forge): new error message for vm.addr() when passing invalid priv…
Browse files Browse the repository at this point in the history
…ate keys (#2164)

* fix(forge): new error message for vm.addr() when passing invalid private keys

* using curve order from the dependency and better error messages

* Apply suggestions from code review

Co-authored-by: Georgios Konstantopoulos <me@gakonst.com>
  • Loading branch information
0xvv and gakonst committed Jun 30, 2022
1 parent 49f35c7 commit 0b20196
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
14 changes: 13 additions & 1 deletion evm/src/executor/inspector/cheatcodes/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ use crate::abi::HEVMCalls;
use bytes::{BufMut, Bytes, BytesMut};
use ethers::{
abi::{AbiEncode, Address, Token},
prelude::{k256::ecdsa::SigningKey, Lazy, LocalWallet, Signer, H160},
core::k256::elliptic_curve::Curve,
prelude::{
k256::{ecdsa::SigningKey, elliptic_curve::bigint::Encoding, Secp256k1},
Lazy, LocalWallet, Signer, H160,
},
types::{NameOrAddress, H256, U256},
utils,
utils::keccak256,
Expand All @@ -26,6 +30,10 @@ fn addr(private_key: U256) -> Result<Bytes, Bytes> {
return Err("Private key cannot be 0.".to_string().encode().into())
}

if private_key > U256::from_big_endian(&Secp256k1::ORDER.to_be_bytes()) {
return Err("Private key must be less than 115792089237316195423570985008687907852837564279074904382605163141518161494337 (the secp256k1 curve order).".to_string().encode().into())
}

let mut bytes: [u8; 32] = [0; 32];
private_key.to_big_endian(&mut bytes);

Expand All @@ -39,6 +47,10 @@ fn sign(private_key: U256, digest: H256, chain_id: U256) -> Result<Bytes, Bytes>
return Err("Private key cannot be 0.".to_string().encode().into())
}

if private_key > U256::from_big_endian(&Secp256k1::ORDER.to_be_bytes()) {
return Err("Private key must be less than 115792089237316195423570985008687907852837564279074904382605163141518161494337 (the secp256k1 curve order).".to_string().encode().into())
}

let mut bytes: [u8; 32] = [0; 32];
private_key.to_big_endian(&mut bytes);

Expand Down
3 changes: 2 additions & 1 deletion forge/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,8 @@ which implements the following methods:

- `function addr(uint sk) public returns (address addr)` Derives an ethereum
address from the private key `sk`. Note that `hevm.addr(0)` will fail with
`BadCheatCode` as `0` is an invalid ECDSA private key.
`BadCheatCode` as `0` is an invalid ECDSA private key. `sk` values above the
secp256k1 curve order, near the max uint256 value will also fail.

- `function ffi(string[] calldata) external returns (bytes memory)` Executes the
arguments as a command in the system shell and returns stdout. Note that this
Expand Down

0 comments on commit 0b20196

Please sign in to comment.