-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path18_5_main-sendtx.rs
88 lines (64 loc) · 2.13 KB
/
18_5_main-sendtx.rs
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
use bitcoincore_rpc::{json, Auth, Client, RpcApi};
use bitcoincore_rpc::bitcoin::{Amount};
use std::collections::HashMap;
fn main() {
let rpc = Client::new(
"http://localhost:18332".to_string(),
Auth::UserPass("StandUp".to_string(), "6305f1b2dbb3bc5a16cd0f4aac7e1eba".to_string()),
)
.unwrap();
let balance = rpc.get_balance(None, None).unwrap();
println!("Balance: {:?} BTC", balance.as_btc());
// 0. Generate a recipient address
let myaddress = rpc
.get_new_address(Option::Some("BlockchainCommons"), Option::Some(json::AddressType::Bech32))
.unwrap();
println!("address: {:?}", myaddress);
// 1. List UTXOs
let unspent = rpc
.list_unspent(
None,
None,
None,
None,
Option::Some(json::ListUnspentQueryOptions {
minimum_amount: Option::Some(Amount::from_btc(0.01).unwrap()),
maximum_amount: None,
maximum_count: None,
minimum_sum_amount: None,
}),
)
.unwrap();
let selected_tx = &unspent[0];
println!("selected unspent transaction: {:#?}", selected_tx);
// 2. Populate Variables
let selected_utxos = json::CreateRawTransactionInput {
txid: selected_tx.txid,
vout: selected_tx.vout,
sequence: None,
};
let unspent_amount = selected_tx.amount;
let amount = unspent_amount - Amount::from_btc(0.00001).unwrap();
let mut output = HashMap::new();
output.insert(
myaddress.to_string(),
amount,
);
// 3. Create Raw Transaction
let unsigned_tx = rpc
.create_raw_transaction(&[selected_utxos], &output, None, None)
.unwrap();
println!("unsigned tx {:#?}", unsigned_tx);
// 4. Sign Transaction
let signed_tx = rpc
.sign_raw_transaction_with_wallet(&unsigned_tx, None, None)
.unwrap();
println!("signed tx {:?}", signed_tx.transaction().unwrap());
// 5. Send Transaction
let txid_sent = rpc
.send_raw_transaction(&signed_tx.transaction().unwrap())
.unwrap();
println!("{:?}", txid_sent);
// 6. Cleanup
let unspent_amount = selected_tx.amount;
}