1
I’m trying to verify signed messages using Rust. lumo AI generated me this:
#[cfg(feature = "derive")]
use bitcoin::util::key::PublicKey;
use secp256k1::{Secp256k1};
pub mod messages {
use bitcoin::{
Address, PublicKey, address::Payload, hashes::{Hash, sha256d::{self, Hash as Sha256dHash}}, secp256k1::{
self,
All, // the context type we’ll use
Message
}
};
use base64::decode;
use secp256k1::{Secp256k1, ecdsa::{RecoverableSignature, RecoveryId}}; // only for convenience; you could use any Base64 lib
/// Turn the first byte of a legacy signature (27‑34) into a `RecoveryId`.
fn decode_recovery_byte(byte: u8) -> Result {
if !(27..=34).contains(&byte) {
return Err(secp256k1::Error::InvalidRecoveryId);
}
// Low‑order two bits = real recovery id (0‑3). The extra +4 (for compressed)
// is stripped automatically by the modulo operation.
RecoveryId::from_i32((byte % 4) as i32)
}
/// Compute the exact double‑SHA‑256 hash that Bitcoin‑CLI/Electrum sign.
///
/// The payload is:
///
///
fn bitcoin_message_hash(msg: &str) -> Sha256dHash {
const MAGIC: &str = "Bitcoin Signed Message:\n";
// CompactSize (varint) encoder – identical to Bitcoin Core.
fn varint_len(s: &str) -> Vec {
let mut v = Vec::new();
let len = s.len() as u64;
if len Result> {
// --------------------------------------------------------------
// 1️⃣ Decode the Base64 signature (must be exactly 65 bytes)
// --------------------------------------------------------------
let sig_bytes = decode(sig_base64.trim())?;
if sig_bytes.len() != 65 {
return Err(format!("Signature must be 65 bytes (got {})", sig_bytes.len()).into());
}
println!("c111heckingadfdsads for address");
// --------------------------------------------------------------
// 2️⃣ Split recovery byte and compact (r|s) signature
// --------------------------------------------------------------
let rec_id = decode_recovery_byte(sig_bytes[0])?;
let is_compressed = sig_bytes[0] >= 31; // true for 31‑34
let compact_sig = &sig_bytes[1..]; // 64‑byte slice (r‖s)
// --------------------------------------------------------------
// 3️⃣ Build a RecoverableSignature (bundles the rec_id)
// --------------------------------------------------------------
let recoverable = RecoverableSignature::from_compact(compact_sig, rec_id)?;
// --------------------------------------------------------------
// 4️⃣ Compute the double‑SHA‑256 hash of the message (magic prefix)
// --------------------------------------------------------------
let msg_hash = bitcoin_message_hash(message);
let secp_msg = Message::from_slice(msg_hash.as_ref())?;
// --------------------------------------------------------------
// 5️⃣ Recover the public key
// --------------------------------------------------------------
// `Secp256k1::verification_only()` gives us a read‑only context.
let secp = Secp256k1::verification_only();
let recovered_secp = secp.recover_ecdsa(&secp_msg, &recoverable)?;
let recovered_pub = PublicKey::new(recovered_secp);
println!("checkingadfdsads for address");
// --------------------------------------------------------------
// 6️⃣ Parse the supplied address (this also tells us the network)
// --------------------------------------------------------------
let supplied_addr: Address = address_str.parse::<:address>>().unwrap().assume_checked();
println!("checking for address");
// --------------------------------------------------------------
// 7️⃣ Re‑derive the address from the recovered public key
// --------------------------------------------------------------
let derived_addr = match supplied_addr.payload {
// ---------- Legacy Base58 (P2PKH) ----------
Payload::PubkeyHash(_) => {
// `p2pkh` automatically uses the compressed form if the key is
// compressed; the `is_compressed` flag we extracted earlier is only
// needed for sanity‑checking, not for address construction.
Address::p2pkh(&recovered_pub, supplied_addr.network)
}
// // ---------- Native SegWit v0 (bc1q…) ----------
// Payload::WitnessProgram {
// version: 0,
// program: ref prog,
// } if prog.len() == 20 => {
// // SegWit v0 always uses the **compressed** public key, regardless
// // of the flag in the signature. The `is_compressed` boolean is
// // therefore irrelevant for address reconstruction here.
// Address::p2wpkh(&recovered_pub, supplied_addr.network)?
// }
// Anything else (Taproot `bc1p…`, P2SH‑wrapped, multisig, etc.)
// is not supported by the legacy signed‑message format.
_ => {
return Err(format!(
"Legacy verification only supports P2PKH (1…) and native SegWit v0 (bc1q…) \
addresses. Address `{}` is of a different type.",
address_str
)
.into())
}
};
println!("{:?}", derived_addr);
println!("{:?}", supplied_addr);
// --------------------------------------------------------------
// 8️⃣ Compare the derived address with the supplied one
// --------------------------------------------------------------
Ok(derived_addr == supplied_addr)
}
}
Can anyone tell me why this code isn’t working? I’ve checked bitcoin-cli verifymessage and returned true. The Rust code is returning false. I’m using a P2PKH address. Signing with the Sparrow wallet.

