use redgold_common::log::init_logger_once;
use crate::util::keys::{public_key_from_bytes, ToPublicKeyFromLib};
use bdk::bitcoin::util::bip32::ExtendedPubKey;
use bdk::bitcoin::util::psbt::serialize::Serialize;
use itertools::{all, Itertools};
use redgold_common_no_wasm::cmd::{run_cmd, run_cmd_safe};
use redgold_common_no_wasm::tx_new::TransactionBuilderSupport;
use redgold_keys::proof_support::{ProofSupport, PublicKeySupport};
use redgold_keys::transaction_support::InputSupport;
use redgold_keys::TestConstants;
use redgold_schema::conf::node_config::NodeConfig;
use redgold_schema::helpers::easy_json::EasyJson;
use redgold_schema::helpers::with_metadata_hashable::WithMetadataHashable;
use redgold_schema::observability::errors::EnhanceErrorInfo;
use redgold_schema::proto_serde::ProtoSerde;
use redgold_schema::structs::{AddressInfo, CurrencyAmount, ErrorInfo, Hash, Input, NetworkEnvironment, Output, Proof, Signature, Transaction, UtxoEntry, UtxoId};
use redgold_schema::tx::tx_builder::TransactionBuilder;
use redgold_schema::{error_info, structs, ErrorInfoContext, RgResult, SafeOption};
use std::collections::HashMap;
use std::str::FromStr;
use std::string::ToString;
const MISSING_DEVICE: &str = "Failed to find a Trezor device";
const TREZORCTL: &str = "trezorctl";
pub fn trezor_cmd(args: Vec<&str>) -> Result<String, ErrorInfo> {
let res = run_cmd_safe(TREZORCTL, args)?;
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,
pub(crate) 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) -> RgResult<ExtendedPubKey> {
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,
})
}
#[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,
})
}
pub const DEFAULT_ACCOUNT_NUM: u32 = 50;
pub fn default_pubkey_path() -> String {
format!("m/44'/0'/{}'/0/0", DEFAULT_ACCOUNT_NUM)
}
pub fn default_xpub_path() -> String {
format!("m/44'/0'/{}'", DEFAULT_ACCOUNT_NUM)
}
pub fn default_pubkey() -> Result<structs::PublicKey, ErrorInfo> {
get_public_node(default_pubkey_path())?.public_key()
}
pub fn default_xpub() -> Result<String, ErrorInfo> {
Ok(get_public_node(default_pubkey_path())?.xpub)
}
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 = trezor_bitcoin_standard_path(account_num, non_standard_coin_type, change, index);
get_public_node(path)?.public_key()
}
pub fn trezor_bitcoin_standard_path(account_num: u32, non_standard_coin_type: Option<String>, change: u32, index: u32) -> String {
format!("{}/{}/{}",
standard_xpub_path(account_num, non_standard_coin_type),
change.to_string(),
index.to_string()
)
}
pub fn trezor_proof(hash: &Hash, public: structs::PublicKey, path: String) -> Result<Proof, ErrorInfo> {
let msg = redgold_keys::btc::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_signature_only(hash)?;
Ok(proof)
}
pub async fn sign_transaction(transaction: &mut Transaction, public: structs::PublicKey, path: String)
-> Result<Transaction, ErrorInfo> {
let hash: Hash = transaction.signable_hash();
let ser_transaction = transaction.json_or();
let all_addrs = public.to_all_addresses()?;
for i in transaction.inputs.iter_mut() {
let enriched_output = i.output
.safe_get_msg("Failed to get output on transaction input")
.with_detail("input", i.json_or())
.with_detail("transaction", ser_transaction.clone())?;
let output_enriched_address = enriched_output.address
.safe_get_msg("Failed to get address")?;
if all_addrs.contains(&output_enriched_address) {
let proof = trezor_proof(&hash, public.clone(), path.clone())?;
let proof1 = proof.clone();
i.proof.push(proof1);
i.verify_assuming_enriched(&hash)?;
}
}
Ok(transaction.clone())
}
pub async fn sign_bitcoin_transaction(json_str: String) -> Result<String, ErrorInfo> {
trezor_cmd(vec!["btc", "sign-tx", &*json_str])
}
pub async fn sign_input(i: &mut Input, public: &structs::PublicKey, path: String, hash: &Hash)
-> Result<Input, ErrorInfo> {
let proof = trezor_proof(&hash, public.clone(), path.clone())?;
let proof1 = proof.clone();
i.proof.push(proof1);
Ok(i.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().hex();
let hash = Hash::from_string_calculate("test");
let utxo = UtxoEntry{
utxo_id: Some(UtxoId::new(&hash, 0)),
output: Some(Output::new(&address, 100)),
time: 0,
};
let ai = AddressInfo{
address: None,
utxo_entries: vec![utxo],
balance: 0,
recent_transactions: vec![],
balances: vec![],
};
let nc = NodeConfig::default();
let mut tb = TransactionBuilder::new(&nc);
tb.with_address_info(ai);
let destination = address.clone();
let amount = CurrencyAmount::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() {
}