Skip to content

Commit

Permalink
Add sign_message() method
Browse files Browse the repository at this point in the history
  • Loading branch information
rantan committed Oct 31, 2024
1 parent e25174a commit a5b4b15
Showing 1 changed file with 94 additions and 2 deletions.
96 changes: 94 additions & 2 deletions tapyrus-wallet-ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,18 @@ use std::io::{Read, Write};
use std::str::FromStr;
use std::sync::{Arc, Mutex, MutexGuard};
use std::{fs, io};
use std::collections::BTreeMap;
use tdk_wallet::tapyrus::secp256k1::hashes::Hash;
use tdk_wallet::tapyrus::secp256k1::hashes::sha256;
use tdk_wallet::miniscript::descriptor::DescriptorSecretKey;
use tdk_wallet::tapyrus::secp256k1::Message;
use tdk_wallet::tapyrus::secp256k1::ThirtyTwoByteHash;
use tdk_esplora::esplora_client;
use tdk_esplora::esplora_client::deserialize;
use tdk_esplora::EsploraExt;
use tdk_sqlite::{rusqlite::Connection, Store};
use tdk_wallet::descriptor::Descriptor;
use tdk_wallet::tapyrus::bip32::Xpriv;
use tdk_wallet::descriptor::{Descriptor, DescriptorPublicKey};
use tdk_wallet::tapyrus::bip32::{ChildNumber, Xpriv};
use tdk_wallet::tapyrus::consensus::serialize;
use tdk_wallet::tapyrus::hex::{DisplayHex, FromHex};
use tdk_wallet::tapyrus::script::color_identifier::ColorIdentifier;
Expand All @@ -20,6 +26,8 @@ use tdk_wallet::template::Bip44;
use tdk_wallet::wallet::tx_builder::AddUtxoError;
use tdk_wallet::wallet::NewOrLoadError;
use tdk_wallet::{tapyrus, KeychainKind, SignOptions, Wallet};
use tdk_wallet::miniscript::ToPublicKey;
use tdk_wallet::signer::SignerId;

#[derive(PartialEq, Clone, Debug)]
pub(crate) enum Network {
Expand Down Expand Up @@ -794,6 +802,73 @@ impl HdWallet {
})?;
Ok(())
}

// pub fn check_trust_layer_refund(&self, txid: String, public_key: String, contract: String, color_id: String) -> Result<(), CheckTrustLayerRefundError> {
// let wallet = self.get_wallet();
// let txid = txid
// .parse::<MalFixTxid>()
// .map_err(|_| CheckTrustLayerRefundError::FailedToParseTxid { txid })?;
// let public_key = PublicKey::from_str(&public_key)
// .map_err(|_| CheckTrustLayerRefundError::FailedToParsePublicKey)?;
// let contract = contract.as_bytes().to_vec();
// let color_id = ColorIdentifier::from_str(&color_id)
// .map_err(|_| CheckTrustLayerRefundError::InvalidColorId)?;
// wallet.check_trust_layer_refund(&txid, &public_key, &contract, color_id).map_err(|e| {
// CheckTrustLayerRefundError::ContractError {
// cause: e.to_string(),
// }
// })?;
// Ok(())
//
// }

pub fn sign_message(&self, public_key: String, message: String) -> String {
let wallet = self.get_wallet();
let public_key = PublicKey::from_str(&public_key).unwrap();
let message_bytes = message.as_bytes();
let message_hash: sha256::Hash = Hash::hash(message_bytes);
let message = Message::from(message_hash);

println!("signer id: {:?}", SignerId::PkHash(public_key.pubkey_hash().into()));
println!("publickey: {:?}", public_key.to_string());

// use descriptor.find_derivation_index_for_spk
let keychains: BTreeMap<_, _> = wallet.keychains().collect();
let descriptor = keychains.get(&KeychainKind::External).unwrap();
let script_buf = ScriptBuf::new_p2pkh(&public_key.pubkey_hash());
let spk = script_buf.as_script();
let next_index = wallet.spk_index().next_index(&KeychainKind::External).unwrap().0;
println!("last index: {:?}", next_index);
if let Some((index, desc)) = descriptor.find_derivation_index_for_spk(wallet.secp_ctx(), &spk, 0..next_index).unwrap() {
println!("index: {:?}", index);
println!("desc: {:?}", desc);

let signers = wallet.get_signers(KeychainKind::External);
let key_map = signers.as_key_map(wallet.secp_ctx());
println!("key map count: {:?}", key_map.iter().count());
let (_, secret) = key_map.iter().next().unwrap();
match secret {
DescriptorSecretKey::XPrv(xprv) => {
let path = xprv.derivation_path.extend(&[ChildNumber::from_normal_idx(index).unwrap()]);
println!("xprv.derivation_path: {:?}", xprv.derivation_path);
println!("xpub: {:?}", xprv.xkey.to_priv().public_key(wallet.secp_ctx()).to_string());
let derived_xprv = xprv.xkey.derive_priv(wallet.secp_ctx(), &path).unwrap();
println!("publickey: {:?}", derived_xprv.to_priv().public_key(wallet.secp_ctx()).to_string());
let secp = wallet.secp_ctx();
let sig = secp.sign_ecdsa(&message, &derived_xprv.private_key);
return sig.serialize_der().to_lower_hex_string();
}
_ => { unreachable!("Invalid private key type"); }
}
}

// if let Some((keychain, index)) = wallet.spk_index().index_of_spk(ScriptBuf::new_p2pkh(&public_key.pubkey_hash()).as_script()) {
// println!("keychain: {:?}", keychain);
// println!("index: {:?}", index);
// }

return "".to_string();
}
}

fn initialize_or_load_master_key(file_path: &str, network: tapyrus::Network) -> io::Result<Xpriv> {
Expand Down Expand Up @@ -1151,4 +1226,21 @@ mod test {
100
);
}

#[test]
fn test_sign_message() {
let wallet = get_wallet();
let message = "message".to_string();

let GetNewAddressResult { .. } = wallet.get_new_address(None).unwrap();
let GetNewAddressResult { .. } = wallet.get_new_address(None).unwrap();
let GetNewAddressResult { .. } = wallet.get_new_address(None).unwrap();
let GetNewAddressResult { .. } = wallet.get_new_address(None).unwrap();
let GetNewAddressResult { .. } = wallet.get_new_address(None).unwrap();

let GetNewAddressResult { public_key, .. } = wallet.get_new_address(None).unwrap();
let sig = wallet.sign_message(public_key, message);

println!("sig: {}", sig);
}
}

0 comments on commit a5b4b15

Please sign in to comment.