Skip to content

Commit

Permalink
Merge pull request #6 from Phala-Network/recover
Browse files Browse the repository at this point in the history
Add back Accounts::recover
  • Loading branch information
kvinwang authored May 6, 2023
2 parents 1c9c456 + f5a92b6 commit 40ec5e2
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "pink-web3"
version = "0.20.1"
version = "0.20.2"
description = "Ethereum JSON-RPC client for pink."
homepage = "https://github.com/Phala-Network/pink-web3"
repository = "https://github.com/Phala-Network/pink-web3"
Expand Down
32 changes: 32 additions & 0 deletions src/api/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ impl<T: Transport> Accounts<T> {
mod accounts_signing {
use super::*;
use crate::prelude::*;
use crate::types::{RecoveryMessage, Recovery};
use crate::{
api::Web3,
error,
Expand Down Expand Up @@ -161,6 +162,37 @@ mod accounts_signing {
signature: signature_bytes,
}
}

/// Recovers the Ethereum address which was used to sign the given data.
///
/// Recovery signature data uses 'Electrum' notation, this means the `v`
/// value is expected to be either `27` or `28`.
pub fn recover<R>(&self, recovery: R) -> error::Result<Address>
where
R: Into<Recovery>,
{
let recovery = recovery.into();
let message_hash = match recovery.message {
RecoveryMessage::Data(ref message) => self.hash_message(message),
RecoveryMessage::Hash(hash) => hash,
};
let (signature, recovery_id) = recovery
.as_signature()
.ok_or(error::Error::Recovery(signing::RecoveryError::InvalidSignature))?;

let mut recoverable_signature: [u8; 65] = [0; 65];
recoverable_signature[..64].copy_from_slice(&signature[..]);
recoverable_signature[64] = recovery_id as u8;

let mut pub_key = [0; 33];
ink_env::ecdsa_recover(&recoverable_signature, message_hash.as_fixed_bytes(), &mut pub_key)
.or(Err(error::Error::Recovery(signing::RecoveryError::InvalidSignature)))?;

let mut address = [0; 20];
ink_env::ecdsa_to_eth_address(&pub_key, &mut address)
.or(Err(error::Error::Recovery(signing::RecoveryError::InvalidSignature)))?;
Ok(address.into())
}
}
/// A transaction used for RLP encoding, hashing and signing.
#[derive(Debug)]
Expand Down

0 comments on commit 40ec5e2

Please sign in to comment.