use std::collections::HashMap;
use std::str::FromStr;
use std::string::ToString;
use bitcoin::secp256k1;
use bitcoin::secp256k1::recovery::{RecoverableSignature, RecoveryId};
use bitcoin::secp256k1::{Message, Secp256k1};
use bitcoin::util::bip32::{ChildNumber, DerivationPath, ExtendedPubKey};
use bitcoin::util::psbt::serialize::Serialize;
use itertools::Itertools;
use tracing_subscriber::fmt::format;
use redgold_schema::{error_info, ErrorInfoContext, SafeBytesAccess, SafeOption, structs, TestConstants, util, WithMetadataHashable};
use redgold_schema::structs::{AddressInfo, ErrorInfo, Hash, Output, Proof, Signature, Transaction, TransactionAmount, UtxoEntry};
use redgold_schema::transaction::amount_data;
use redgold_schema::transaction_builder::TransactionBuilder;
use redgold_schema::util::mnemonic_words::HDPathCursor;
use redgold_schema::util::sign;
use crate::genesis::create_genesis_transaction;
use crate::util::cmd::run_cmd;
use crate::util::keys::{public_key_from_bytes, ToPublicKey, ToPublicKeyFromLib};
use crate::util::{init_logger, init_logger_once, sha256_str};
const MISSING_DEVICE: &str = "Failed to find a Trezor device";
const TREZORCTL: &str = "trezorctl";
pub fn trezor_cmd(args: Vec<&str>) -> Result<String, ErrorInfo> {
tracing::debug!("Running trezor cmd with args {:?}", args.clone());
let res = run_cmd(TREZORCTL, args);
tracing::debug!("Trezor command raw output: {:?}", res.clone());
if res.0.contains(MISSING_DEVICE) {
Err(error_info("Failed to find a Trezor device".to_string()))?;
}
Ok(res.0)
}
pub fn trezor_list_devices() -> Result<Option<String>, ErrorInfo> {
let res = trezor_cmd(vec!["list"])?;
let res = if res.is_empty() {
None
} else {
let strr = res.split("\n")
.filter(|l| {
!(l.contains("Failed to read details") || l.trim().is_empty())
})
.next()
.map(|l| l.to_string());
strr
};
Ok(res)
}
#[ignore]
#[test]
fn test_list_devices() {
let res = trezor_list_devices();
println!("Trezor list devices: {:?}", res);
assert!(res.is_ok());
}
pub fn parse_output(output: String) -> (HashMap<String, String>, Vec<(String, String)>) {
let mut hm = HashMap::default();
let mut vec = Vec::default();
let lines = output.lines();
for mut l in lines.map(|l| l.split(": ")) {
if let Some(k) = l.next() {
if let Some(v) = l.next() {
let tuple = (k.to_string(), v.to_string());
vec.push(tuple);
hm.insert(k.to_string(), v.to_string());
}
}
}
(hm, vec)
}
pub fn run_trezor_cmd(args: Vec<&str>) -> Result<(HashMap<String, String>, Vec<(String, String)>), ErrorInfo> {
let res = trezor_cmd(args)?;
let map = parse_output(res);
println!("Parsed output: {:?}", map.clone());
Ok(map)
}
#[derive(Clone, Debug)]
pub struct PublicNodeResponse {
node_depth: u32,
node_fingerprint: String,
node_child_num: u32,
node_chain_code: String,
node_public_key: String,
xpub: String
}
impl PublicNodeResponse {
pub fn public_key(&self) -> Result<structs::PublicKey, ErrorInfo> {
let h = hex::decode(&self.node_public_key).error_info("Failed to decode public key")?;
let public_key_parse_test = public_key_from_bytes(&h).error_info("Failed to parse public key")?;
Ok(public_key_parse_test.to_struct_public_key())
}
pub fn xpub(&self) -> anyhow::Result<ExtendedPubKey, ErrorInfo> {
ExtendedPubKey::from_str(&self.xpub).error_info("Failed to parse xpub")
}
}
pub fn get_public_node(path: String) -> Result<PublicNodeResponse, ErrorInfo> {
let (hm, vec) = run_trezor_cmd(vec!["get-public-node", "-n", &path])?;
println!("keys: {:?}", hm.keys());
let node_public_key = vec.get(4).safe_get_msg("no public key")?.1.clone();
let xpub = vec.get(5).safe_get_msg("no xpub")?.1.clone();
Ok(PublicNodeResponse{
node_depth: 0,
node_fingerprint: "".to_string(),
node_child_num: 0,
node_chain_code: "".to_string(),
node_public_key,
xpub,
})
}
pub fn get_public_key(cursor: HDPathCursor) -> Result<structs::PublicKey, ErrorInfo> {
let res = get_public_node(cursor.to_string())?;
res.public_key()
}
#[derive(Clone)]
pub struct SignMessageResponse {
address: String,
signature: Vec<u8>,
}
impl SignMessageResponse {
pub fn recovery_id(&self) -> i32 {
self.signature[0] as i32 - 31
}
pub fn signature_vec(&self) -> Vec<u8> {
self.signature[1..].to_vec()
}
pub fn signature(&self) -> Signature {
Signature::hardware(self.signature_vec())
}
}
pub fn sign_message(path: String, input_message: String) -> Result<SignMessageResponse, ErrorInfo> {
let res = trezor_cmd(vec!["sign-message", "-n", &path, &input_message])?;
let (_, vec) = parse_output(res);
let message = vec.get(0).safe_get_msg("no message")?.1.clone();
let address = vec.get(1).safe_get_msg("no address")?.1.clone();
let sig = vec.get(2).safe_get_msg("no signature")?.1.clone();
let signature = base64::decode(sig).error_info("Failed to decode base64 signature")?;
tracing::debug!("signature length: {:?}", signature.len());
Ok(SignMessageResponse{
address,
signature,
})
}
const DEFAULT_ACCOUNT_NUM: u32 = 50;
pub fn default_pubkey_path() -> String {
format!("m/44'/0'/{}'/0/0", DEFAULT_ACCOUNT_NUM)
}
pub fn default_pubkey() -> Result<structs::PublicKey, ErrorInfo> {
get_public_node(default_pubkey_path())?.public_key()
}
pub fn standard_xpub_path(account_num: u32, non_standard_coin_type: Option<String>) -> String {
let coin_type = non_standard_coin_type.unwrap_or("0".to_string()).to_string();
return format!("m/44'/{}'/{}'", coin_type, account_num.to_string()).to_string();
}
pub fn get_standard_xpub(account_num: u32, non_standard_coin_type: Option<String>) -> Result<String, ErrorInfo> {
Ok(get_public_node(standard_xpub_path(account_num, non_standard_coin_type))?.xpub)
}
pub fn get_standard_public_key(
account_num: u32,
non_standard_coin_type: Option<String>,
change: u32,
index: u32
) -> Result<structs::PublicKey, ErrorInfo> {
let path = format!("{}/{}/{}",
standard_xpub_path(account_num, non_standard_coin_type),
change.to_string(),
index.to_string()
);
get_public_node(path)?.public_key()
}
pub fn trezor_proof(hash: &Hash, public: structs::PublicKey, path: String) -> Result<Proof, ErrorInfo> {
let msg = util::bitcoin_message_signer::message_from_hash(hash);
let signature = sign_message(path, msg)?;
let sig = signature.signature();
let proof = Proof::from(public, sig);
proof.verify(hash)?;
Ok(proof)
}
pub async fn sign_transaction(transaction: &mut Transaction, public: structs::PublicKey, path: String)
-> Result<Transaction, ErrorInfo> {
let hash: Hash = transaction.hash_or();
let addr = public.address()?;
for i in transaction.inputs.iter_mut() {
let proof = trezor_proof(&hash, public.clone(), path.clone())?;
let output = i.output
.safe_get_msg("Failed to get output")?;
let o = output.address
.safe_get_msg("Failed to get address")?;
if o == &addr {
let proof1 = proof.clone();
i.proof.push(proof1);
i.verify_proof(&addr, &hash)?;
}
}
Ok(transaction.clone())
}
#[ignore]
#[tokio::test]
async fn debug_sign_tx () {
init_logger_once();
let tc = TestConstants::new();
let pk = default_pubkey().expect("pk");
let address = pk.address().expect("a");
let addr = address.clone().address.safe_bytes().expect("");
let utxo = UtxoEntry{
transaction_hash: Hash::from_string_calculate("test").vec(),
output_index: 0,
address: addr.clone(),
output: Some(Output{
address: Some(address.clone()),
product_id: None,
counter_party_proofs: vec![],
data: amount_data(100),
contract: None,
}),
time: 0,
};
let ai = AddressInfo{
address: None,
utxo_entries: vec![utxo],
balance: 0,
recent_transactions: vec![]
};
let mut tb = TransactionBuilder::new();
tb.with_address_info(ai);
let destination = address.clone();
let amount = TransactionAmount::from(5);
tb.with_output(&destination, &amount);
let res = tb.build().expect("tx");
sign_transaction(&mut res.clone(), pk, default_pubkey_path())
.await.expect("sign");
}
#[ignore]
#[test]
pub fn trezor_test() {
let cursor = HDPathCursor::from( 0, 0, 0, 0);
let node = get_public_node(cursor.to_string()).unwrap();
let res = node.public_key().unwrap();
println!("Got public key {}", res.hex().expect(""));
let msg = "ahoy";
let signature = sign_message(cursor.to_string(), msg.to_string()).unwrap();
let _sig = Signature::ecdsa(signature.signature_vec());
}