Skip to content
This repository has been archived by the owner on Oct 19, 2024. It is now read-only.

added from_bytes for Wallet type #1983

Merged
merged 3 commits into from
Dec 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@

- `eth-keystore-rs` crate updated. Allow an optional name for the to-be-generated
keystore file [#910](https://github.com/gakonst/ethers-rs/pull/910)
- [1983](https://github.com/gakonst/ethers-rs/pull/1983) Added a `from_bytes` function for the `Wallet` type.

### 0.6.0

Expand Down
20 changes: 20 additions & 0 deletions ethers-signers/src/wallet/private_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,13 @@ impl Wallet<SigningKey> {
let address = secret_key_to_address(&signer);
Self { signer, address, chain_id: 1 }
}

/// Creates a new Wallet instance from a raw scalar value (big endian).
pub fn from_bytes(bytes: &[u8]) -> Result<Self, WalletError> {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: impl AsRef<[u8]> is slightly better but no need

let signer = SigningKey::from_bytes(bytes)?;
let address = secret_key_to_address(&signer);
Ok(Self { signer, address, chain_id: 1 })
}
}

impl PartialEq for Wallet<SigningKey> {
Expand Down Expand Up @@ -305,4 +312,17 @@ mod tests {
Address::from_str("6813Eb9362372EEF6200f3b1dbC3f819671cBA69").expect("Decoding failed")
);
}

#[test]
fn key_from_bytes() {
let wallet: Wallet<SigningKey> =
"0000000000000000000000000000000000000000000000000000000000000001".parse().unwrap();

let key_as_bytes = wallet.signer.to_bytes();
let wallet_from_bytes = Wallet::from_bytes(&key_as_bytes).unwrap();

assert_eq!(wallet.address, wallet_from_bytes.address);
assert_eq!(wallet.chain_id, wallet_from_bytes.chain_id);
assert_eq!(wallet.signer, wallet_from_bytes.signer);
}
}