redgold 0.1.0

A relative proof conflict resolution & irreversibility service with trust modeling custodial pooling and executor contracts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
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)
}

// Failed to read details
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)
}


/*

trezorctl get_public_node -n "m/44'/0'/0'/0/0"

Please confirm action on your Trezor device.
node.depth: 5
node.fingerprint: <etc>
node.child_num: 0
node.chain_code: <etc>
node.public_key: <your_key_here>
xpub: <your_key_here>
 */

#[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_depth =
    //     vec.get(0).ok_or(
    //     // hm.get("node.depth").ok_or(
    //     Err(error_info("Failed to find node.depth output line".to_string()))?
    // )?.parse::<u32>().error_info("Failed to parse node.depth")?;
    //
    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();
    //     vec.get("node.public_key").ok_or(
    //     // hm.get("node.public_key").ok_or(
    //     Err(error_info("Failed to find node.public_key output line".to_string()))?
    // )?.clone();
    //
    // let node_fingerprint = hm.get("node.fingerprint").ok_or(
    //     Err(error_info("Failed to find node.fingerprint output line".to_string()))?
    // )?.clone();
    // let node_child_num = hm.get("node.child_num").ok_or(
    //     Err(error_info("Failed to find node.child_num output line".to_string()))?
    // )?.parse::<u32>().error_info("Failed to parse node.child_num")?;
    // let node_chain_code = hm.get("node.chain_code").ok_or(
    //     Err(error_info("Failed to find node.chain_code output line".to_string()))?
    // )?.clone();
    //
    // let xpub = hm.get("xpub").ok_or(
    //     Err(error_info("Failed to find xpub output line".to_string()))?
    // )?.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()
}


/// Message signing

#[derive(Clone)]
pub struct SignMessageResponse {
    // message: String,
    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())
    }
}

/*

trezorctl sign-message -n "m/44'/0'/0'/0/0" "ahoy"

Please confirm action on your Trezor device.
message: ahoy
address: <some_address>
signature: <some_signature>
 */
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();
    // Strange error here happens when attempting to use hashmap keys, they match but it doesn't work
    // May be a string encoding issue?
    // Either way order preserving vec works for now.
    // let sig = hm.get("signature").ok_or(
    //     Err(error_info("Failed to find signature output line".to_string()))?
    // )?;
    // let message = hm.get("message").ok_or(
    //     Err(error_info("Failed to find message output line".to_string()))?
    // )?.clone();
    // let address = hm.get("address").ok_or(
    //     Err(error_info("Failed to find address output line".to_string()))?
    // )?.clone();
    let signature = base64::decode(sig).error_info("Failed to decode base64 signature")?;
    tracing::debug!("signature length: {:?}", signature.len());
    // let message = base64::decode(message).error_info("Failed to decode base64 message")?;
    Ok(SignMessageResponse{
        // message,
        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()
}

/// This returns a hardened xpub so it doesn't expose other accounts
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();
}

/// Primary function used for finding getting an extended public key
/// This supplies us with the information required to construct all public keys
/// for a given account
/// This is one of two dependencies on the trezor device and the primary interface for external
/// usage
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 prepare_message(tx: Transact) -> String {
//     format!("{}{}", SIGN_MESSAGE_HEADER, msg)
// }


/// PublicKey here should ideally be derived from an xpub requested earlier in the process
/// And needs to match the supplied path
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");
}


/// Debug / local testing and verification

#[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();
    // let xpub = node.xpub().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());
    // let proof = Proof::from(res, sig);
    // proof.verify(&vec).unwrap();
    // println!("Verified proof");

}

/*
Is this accurate??
https://bitcoin.stackexchange.com/questions/38351/ecdsa-v-r-s-what-is-v/38909
31 compressed public key, y-parity 0, magnitude of x lower than the curve order
32 compressed public key, y-parity 1, magnitude of x lower than the curve order
33 compressed public key, y-parity 0, magnitude of x greater than the curve order
34 compressed public key, y-parity 1, magnitude of x greater than the curve order


    if not utils.BITCOIN_ONLY and coin.decred:
        h = utils.HashWriter(blake256())
    else:
        h = utils.HashWriter(sha256())
    if not coin.signed_message_header:
        raise wire.DataError("Empty message header not allowed.")
    write_compact_size(h, len(coin.signed_message_header))
    h.extend(coin.signed_message_header.encode())
    write_compact_size(h, len(message))
    h.extend(message)
    ret = h.get_digest()
    if coin.sign_hash_double:
        ret = sha256(ret).digest()
    return ret


    message = msg.message
    address_n = msg.address_n
    script_type = msg.script_type or InputScriptType.SPENDADDRESS

    await validate_path(
        ctx, keychain, address_n, validate_path_against_script_type(coin, msg)
    )

    node = keychain.derive(address_n)
    address = get_address(script_type, coin, node)
    await confirm_signverify(
        ctx,
        coin.coin_shortcut,
        decode_message(message),
        address_short(coin, address),
        verify=False,
    )

    seckey = node.private_key()

    digest = message_digest(coin, message)
    signature = secp256k1.sign(seckey, digest)

    if script_type == InputScriptType.SPENDADDRESS:
        script_type_info = 0
    elif script_type == InputScriptType.SPENDP2SHWITNESS:
        script_type_info = 4
    elif script_type == InputScriptType.SPENDWITNESS:
        script_type_info = 8
    else:
        raise wire.ProcessError("Unsupported script type")

    # Add script type information to the recovery byte.
    if script_type_info != 0 and not msg.no_script_type:
        signature = bytes([signature[0] + script_type_info]) + signature[1:]

    return MessageSignature(address=address, signature=signature)

/// Hash message for signature using Bitcoin's message signing format
pub fn signed_msg_hash(msg: &str) -> sha256d::Hash {
    sha256d::Hash::hash(
        &[
            MSG_SIGN_PREFIX,
            &encode::serialize(&encode::VarInt(msg.len() as u64)),
            msg.as_bytes(),
        ]
        .concat(),
    )
}



 */