2023-08-14 04:54:00 +00:00
|
|
|
extern crate hashes;
|
2019-10-28 20:10:31 +00:00
|
|
|
extern crate secp256k1;
|
|
|
|
|
2023-08-14 04:54:00 +00:00
|
|
|
use hashes::{sha256, Hash};
|
2022-11-16 00:06:12 +00:00
|
|
|
use secp256k1::{ecdsa, Error, Message, PublicKey, Secp256k1, SecretKey, Signing, Verification};
|
|
|
|
|
|
|
|
fn recover<C: Verification>(
|
|
|
|
secp: &Secp256k1<C>,
|
|
|
|
msg: &[u8],
|
|
|
|
sig: [u8; 64],
|
|
|
|
recovery_id: u8,
|
|
|
|
) -> Result<PublicKey, Error> {
|
2019-10-28 20:10:31 +00:00
|
|
|
let msg = sha256::Hash::hash(msg);
|
2023-08-09 22:03:10 +00:00
|
|
|
let msg = Message::from_digest_slice(msg.as_ref())?;
|
2021-09-09 09:25:06 +00:00
|
|
|
let id = ecdsa::RecoveryId::from_i32(recovery_id as i32)?;
|
|
|
|
let sig = ecdsa::RecoverableSignature::from_compact(&sig, id)?;
|
2019-10-28 20:10:31 +00:00
|
|
|
|
2021-09-09 09:25:06 +00:00
|
|
|
secp.recover_ecdsa(&msg, &sig)
|
2019-10-28 20:10:31 +00:00
|
|
|
}
|
|
|
|
|
2022-11-16 00:06:12 +00:00
|
|
|
fn sign_recovery<C: Signing>(
|
|
|
|
secp: &Secp256k1<C>,
|
|
|
|
msg: &[u8],
|
|
|
|
seckey: [u8; 32],
|
|
|
|
) -> Result<ecdsa::RecoverableSignature, Error> {
|
2019-10-28 20:10:31 +00:00
|
|
|
let msg = sha256::Hash::hash(msg);
|
2023-08-09 22:03:10 +00:00
|
|
|
let msg = Message::from_digest_slice(msg.as_ref())?;
|
2019-10-28 20:10:31 +00:00
|
|
|
let seckey = SecretKey::from_slice(&seckey)?;
|
2021-09-09 09:25:06 +00:00
|
|
|
Ok(secp.sign_ecdsa_recoverable(&msg, &seckey))
|
2019-10-28 20:10:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let secp = Secp256k1::new();
|
|
|
|
|
|
|
|
let seckey = [
|
2022-11-16 00:06:12 +00:00
|
|
|
59, 148, 11, 85, 134, 130, 61, 253, 2, 174, 59, 70, 27, 180, 51, 107, 94, 203, 174, 253,
|
|
|
|
102, 39, 170, 146, 46, 252, 4, 143, 236, 12, 136, 28,
|
2019-10-28 20:10:31 +00:00
|
|
|
];
|
|
|
|
let pubkey = PublicKey::from_slice(&[
|
2022-11-16 00:06:12 +00:00
|
|
|
2, 29, 21, 35, 7, 198, 183, 43, 14, 208, 65, 139, 14, 112, 205, 128, 231, 245, 41, 91, 141,
|
|
|
|
134, 245, 114, 45, 63, 82, 19, 251, 210, 57, 79, 54,
|
|
|
|
])
|
|
|
|
.unwrap();
|
2019-10-28 20:10:31 +00:00
|
|
|
let msg = b"This is some message";
|
|
|
|
|
|
|
|
let signature = sign_recovery(&secp, msg, seckey).unwrap();
|
|
|
|
|
|
|
|
let (recovery_id, serialize_sig) = signature.serialize_compact();
|
|
|
|
|
2022-11-16 00:06:12 +00:00
|
|
|
assert_eq!(recover(&secp, msg, serialize_sig, recovery_id.to_i32() as u8), Ok(pubkey));
|
2019-10-28 20:10:31 +00:00
|
|
|
}
|