|
2 | 2 | //!
|
3 | 3 | //! This is how some external user would use rust-miniscript
|
4 | 4 |
|
| 5 | +extern crate bitcoincore_rpc; |
| 6 | +extern crate log; |
| 7 | + |
| 8 | +extern crate bitcoin; |
| 9 | +extern crate miniscript; |
| 10 | + |
| 11 | +use bitcoincore_rpc::{json, Auth, Client, RpcApi}; |
| 12 | + |
| 13 | +use bitcoin::secp256k1; |
| 14 | +use bitcoin::util::bip143; |
| 15 | +use bitcoin::util::psbt; |
| 16 | +use bitcoin::util::psbt::PartiallySignedTransaction as Psbt; |
| 17 | +use bitcoin::{Amount, OutPoint, Transaction, TxIn, TxOut, Txid}; |
| 18 | +mod read_file; |
| 19 | +use miniscript::miniscript::iter; |
| 20 | +use miniscript::DescriptorTrait; |
| 21 | +use miniscript::MiniscriptKey; |
| 22 | +use miniscript::{Miniscript, Segwitv0}; |
| 23 | +use std::collections::BTreeMap; |
| 24 | + |
| 25 | +struct StdLogger; |
| 26 | + |
| 27 | +impl log::Log for StdLogger { |
| 28 | + fn enabled(&self, metadata: &log::Metadata) -> bool { |
| 29 | + metadata.target().contains("jsonrpc") || metadata.target().contains("bitcoincore_rpc") |
| 30 | + } |
| 31 | + |
| 32 | + fn log(&self, record: &log::Record) { |
| 33 | + if self.enabled(record.metadata()) { |
| 34 | + println!( |
| 35 | + "[{}][{}]: {}", |
| 36 | + record.level(), |
| 37 | + record.metadata().target(), |
| 38 | + record.args() |
| 39 | + ); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + fn flush(&self) {} |
| 44 | +} |
| 45 | + |
| 46 | +static LOGGER: StdLogger = StdLogger; |
| 47 | + |
| 48 | +/// Quickly create a BTC amount. |
| 49 | +fn btc<F: Into<f64>>(btc: F) -> Amount { |
| 50 | + Amount::from_btc(btc.into()).unwrap() |
| 51 | +} |
| 52 | + |
| 53 | +fn get_rpc_url() -> String { |
| 54 | + return std::env::var("RPC_URL").expect("RPC_URL must be set"); |
| 55 | +} |
| 56 | + |
| 57 | +fn get_auth() -> bitcoincore_rpc::Auth { |
| 58 | + if let Ok(cookie) = std::env::var("RPC_COOKIE") { |
| 59 | + return Auth::CookieFile(cookie.into()); |
| 60 | + } else if let Ok(user) = std::env::var("RPC_USER") { |
| 61 | + return Auth::UserPass(user, std::env::var("RPC_PASS").unwrap_or_default()); |
| 62 | + } else { |
| 63 | + panic!("Either RPC_COOKIE or RPC_USER + RPC_PASS must be set."); |
| 64 | + }; |
| 65 | +} |
| 66 | + |
| 67 | +// Find the Outpoint by value. |
| 68 | +// Ideally, we should find by scriptPubkey, but this |
| 69 | +// works for temp test case |
| 70 | +fn get_vout(cl: &Client, txid: Txid, value: u64) -> (OutPoint, TxOut) { |
| 71 | + let tx = cl |
| 72 | + .get_transaction(&txid, None) |
| 73 | + .unwrap() |
| 74 | + .transaction() |
| 75 | + .unwrap(); |
| 76 | + for (i, txout) in tx.output.into_iter().enumerate() { |
| 77 | + if txout.value == value { |
| 78 | + return (OutPoint::new(txid, i as u32), txout); |
| 79 | + } |
| 80 | + } |
| 81 | + unreachable!("Only call get vout on functions which have the expected outpoint"); |
| 82 | +} |
| 83 | + |
5 | 84 | fn main() {
|
6 |
| - () |
| 85 | + log::set_logger(&LOGGER) |
| 86 | + .map(|()| log::set_max_level(log::LevelFilter::max())) |
| 87 | + .unwrap(); |
| 88 | + |
| 89 | + let rpc_url = format!("{}/wallet/testwallet", get_rpc_url()); |
| 90 | + let auth = get_auth(); |
| 91 | + |
| 92 | + let cl = Client::new(&rpc_url, auth).unwrap(); |
| 93 | + |
| 94 | + // 0.21 does not create default wallet.. |
| 95 | + cl.create_wallet("testwallet", None, None, None, None) |
| 96 | + .unwrap(); |
| 97 | + |
| 98 | + let testdata = read_file::TestData::new_fixed_data(50); |
| 99 | + let ms_vec = read_file::parse_miniscripts(&testdata.pubdata); |
| 100 | + let sks = testdata.secretdata.sks; |
| 101 | + let pks = testdata.pubdata.pks; |
| 102 | + // Generate some blocks |
| 103 | + let blocks = cl |
| 104 | + .generate_to_address(500, &cl.get_new_address(None, None).unwrap()) |
| 105 | + .unwrap(); |
| 106 | + assert_eq!(blocks.len(), 500); |
| 107 | + |
| 108 | + // Next send some btc to each address corresponding to the miniscript |
| 109 | + let mut txids = vec![]; |
| 110 | + for ms in ms_vec.iter() { |
| 111 | + let wsh = miniscript::Descriptor::new_wsh(ms.clone()).unwrap(); |
| 112 | + let txid = cl |
| 113 | + .send_to_address( |
| 114 | + &wsh.address(bitcoin::Network::Regtest).unwrap(), |
| 115 | + btc(1), |
| 116 | + None, |
| 117 | + None, |
| 118 | + None, |
| 119 | + None, |
| 120 | + None, |
| 121 | + None, |
| 122 | + ) |
| 123 | + .unwrap(); |
| 124 | + txids.push(txid); |
| 125 | + } |
| 126 | + // Wait for the funds to mature. |
| 127 | + let blocks = cl |
| 128 | + .generate_to_address(50, &cl.get_new_address(None, None).unwrap()) |
| 129 | + .unwrap(); |
| 130 | + assert_eq!(blocks.len(), 50); |
| 131 | + // Create a PSBT for each transaction. |
| 132 | + // Spend one input and spend one output for simplicity. |
| 133 | + let mut psbts = vec![]; |
| 134 | + for (ms, txid) in ms_vec.iter().zip(txids) { |
| 135 | + let mut psbt = Psbt { |
| 136 | + global: psbt::Global { |
| 137 | + unsigned_tx: Transaction { |
| 138 | + version: 2, |
| 139 | + lock_time: 1_603_866_330, // time at 10/28/2020 @ 6:25am (UTC) |
| 140 | + input: vec![], |
| 141 | + output: vec![], |
| 142 | + }, |
| 143 | + unknown: BTreeMap::new(), |
| 144 | + proprietary: BTreeMap::new(), |
| 145 | + xpub: BTreeMap::new(), |
| 146 | + version: 0, |
| 147 | + }, |
| 148 | + inputs: vec![], |
| 149 | + outputs: vec![], |
| 150 | + }; |
| 151 | + // figure out the outpoint from the txid |
| 152 | + let (outpoint, witness_utxo) = get_vout(&cl, txid, btc(1.0).as_sat()); |
| 153 | + let mut txin = TxIn::default(); |
| 154 | + txin.previous_output = outpoint; |
| 155 | + // set the sequence to a non-final number for the locktime transactions to be |
| 156 | + // processed correctly. |
| 157 | + // We waited 50 blocks, keep 49 for safety |
| 158 | + txin.sequence = 49; |
| 159 | + psbt.global.unsigned_tx.input.push(txin); |
| 160 | + // Get a new script pubkey from the node so that |
| 161 | + // the node wallet tracks the receiving transaction |
| 162 | + // and we can check it by gettransaction RPC. |
| 163 | + let addr = cl |
| 164 | + .get_new_address(None, Some(json::AddressType::Bech32)) |
| 165 | + .unwrap(); |
| 166 | + psbt.global.unsigned_tx.output.push(TxOut { |
| 167 | + value: 99_999_000, |
| 168 | + script_pubkey: addr.script_pubkey(), |
| 169 | + }); |
| 170 | + let mut input = psbt::Input::default(); |
| 171 | + input.witness_utxo = Some(witness_utxo); |
| 172 | + input.witness_script = Some(ms.encode()); |
| 173 | + psbt.inputs.push(input); |
| 174 | + psbt.outputs.push(psbt::Output::default()); |
| 175 | + psbts.push(psbt); |
| 176 | + } |
| 177 | + |
| 178 | + let mut spend_txids = vec![]; |
| 179 | + // Sign the transactions with all keys |
| 180 | + // AKA the signer role of psbt |
| 181 | + for i in 0..psbts.len() { |
| 182 | + // Get all the pubkeys and the corresponding secret keys |
| 183 | + let ms: Miniscript<miniscript::bitcoin::PublicKey, Segwitv0> = |
| 184 | + Miniscript::parse_insane(psbts[i].inputs[0].witness_script.as_ref().unwrap()).unwrap(); |
| 185 | + |
| 186 | + let sks_reqd: Vec<_> = ms |
| 187 | + .iter_pk_pkh() |
| 188 | + .map(|pk_pkh| match pk_pkh { |
| 189 | + iter::PkPkh::PlainPubkey(pk) => sks[pks.iter().position(|&x| x == pk).unwrap()], |
| 190 | + iter::PkPkh::HashedPubkey(hash) => { |
| 191 | + sks[pks |
| 192 | + .iter() |
| 193 | + .position(|&pk| pk.to_pubkeyhash() == hash) |
| 194 | + .unwrap()] |
| 195 | + } |
| 196 | + }) |
| 197 | + .collect(); |
| 198 | + // Get the required sighash message |
| 199 | + let amt = btc(1).as_sat(); |
| 200 | + let mut sighash_cache = bip143::SigHashCache::new(&psbts[i].global.unsigned_tx); |
| 201 | + let sighash_ty = bitcoin::SigHashType::All; |
| 202 | + let sighash = sighash_cache.signature_hash(0, &ms.encode(), amt, sighash_ty); |
| 203 | + |
| 204 | + // requires both signing and verification because we check the tx |
| 205 | + // after we psbt extract it |
| 206 | + let secp = secp256k1::Secp256k1::new(); |
| 207 | + let msg = secp256k1::Message::from_slice(&sighash[..]).unwrap(); |
| 208 | + |
| 209 | + // Finally construct the signature and add to psbt |
| 210 | + for sk in sks_reqd { |
| 211 | + let sig = secp.sign(&msg, &sk); |
| 212 | + let pk = pks[sks.iter().position(|&x| x == sk).unwrap()]; |
| 213 | + let mut sig = sig.serialize_der().to_vec(); |
| 214 | + sig.push(0x01u8); //sighash all flag |
| 215 | + psbts[i].inputs[0].partial_sigs.insert(pk, sig); |
| 216 | + } |
| 217 | + // Add the hash preimages to the psbt |
| 218 | + psbts[i].inputs[0].sha256_preimages.insert( |
| 219 | + testdata.pubdata.sha256, |
| 220 | + testdata.secretdata.sha256_pre.to_vec(), |
| 221 | + ); |
| 222 | + psbts[i].inputs[0].hash256_preimages.insert( |
| 223 | + testdata.pubdata.hash256, |
| 224 | + testdata.secretdata.hash256_pre.to_vec(), |
| 225 | + ); |
| 226 | + println!("{}", ms); |
| 227 | + psbts[i].inputs[0].hash160_preimages.insert( |
| 228 | + testdata.pubdata.hash160, |
| 229 | + testdata.secretdata.hash160_pre.to_vec(), |
| 230 | + ); |
| 231 | + psbts[i].inputs[0].ripemd160_preimages.insert( |
| 232 | + testdata.pubdata.ripemd160, |
| 233 | + testdata.secretdata.ripemd160_pre.to_vec(), |
| 234 | + ); |
| 235 | + // Finalize the transaction using psbt |
| 236 | + // Let miniscript do it's magic! |
| 237 | + if let Err(e) = miniscript::psbt::finalize_mall(&mut psbts[i], &secp) { |
| 238 | + // All miniscripts should satisfy |
| 239 | + panic!("Could not satisfy: error{} ms:{} at ind:{}", e, ms, i); |
| 240 | + } else { |
| 241 | + let tx = miniscript::psbt::extract(&psbts[i], &secp).unwrap(); |
| 242 | + |
| 243 | + // Send the transactions to bitcoin node for mining. |
| 244 | + // Regtest mode has standardness checks |
| 245 | + // Check whether the node accepts the transactions |
| 246 | + let txid = cl |
| 247 | + .send_raw_transaction(&tx) |
| 248 | + .expect(&format!("{} send tx failed for ms {}", i, ms)); |
| 249 | + spend_txids.push(txid); |
| 250 | + } |
| 251 | + } |
| 252 | + // Finally mine the blocks and await confirmations |
| 253 | + let _blocks = cl |
| 254 | + .generate_to_address(10, &cl.get_new_address(None, None).unwrap()) |
| 255 | + .unwrap(); |
| 256 | + // Get the required transactions from the node mined in the blocks. |
| 257 | + for txid in spend_txids { |
| 258 | + // Check whether the transaction is mined in blocks |
| 259 | + // Assert that the confirmations are > 0. |
| 260 | + let num_conf = cl.get_transaction(&txid, None).unwrap().info.confirmations; |
| 261 | + assert!(num_conf > 0); |
| 262 | + } |
7 | 263 | }
|
0 commit comments