forked from arkade-os/rust-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
1266 lines (1097 loc) · 40.3 KB
/
main.rs
File metadata and controls
1266 lines (1097 loc) · 40.3 KB
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![allow(clippy::print_stdout)]
#![allow(clippy::large_enum_variant)]
use anyhow::bail;
use anyhow::Context;
use anyhow::Result;
use ark_core::batch;
use ark_core::batch::create_and_sign_forfeit_txs;
use ark_core::batch::generate_nonce_tree;
use ark_core::batch::sign_batch_tree;
use ark_core::batch::sign_commitment_psbt;
use ark_core::boarding_output::list_boarding_outpoints;
use ark_core::boarding_output::BoardingOutpoints;
use ark_core::coin_select::select_vtxos;
use ark_core::history;
use ark_core::history::generate_incoming_vtxo_transaction_history;
use ark_core::history::generate_outgoing_vtxo_transaction_history;
use ark_core::history::sort_transactions_by_created_at;
use ark_core::proof_of_funds;
use ark_core::send;
use ark_core::send::build_offchain_transactions;
use ark_core::send::sign_ark_transaction;
use ark_core::send::sign_checkpoint_transaction;
use ark_core::send::OffchainTransactions;
use ark_core::server::BatchTreeEventType;
use ark_core::server::GetVtxosRequest;
use ark_core::server::StreamEvent;
use ark_core::server::VirtualTxOutPoint;
use ark_core::vtxo::list_virtual_tx_outpoints;
use ark_core::vtxo::VirtualTxOutPoints;
use ark_core::ArkAddress;
use ark_core::BoardingOutput;
use ark_core::ExplorerUtxo;
use ark_core::TxGraph;
use ark_core::Vtxo;
use bitcoin::address::NetworkUnchecked;
use bitcoin::hashes::sha256;
use bitcoin::hashes::Hash;
use bitcoin::hex::DisplayHex;
use bitcoin::key::Keypair;
use bitcoin::key::Secp256k1;
use bitcoin::psbt;
use bitcoin::secp256k1;
use bitcoin::secp256k1::schnorr;
use bitcoin::secp256k1::PublicKey;
use bitcoin::secp256k1::SecretKey;
use bitcoin::Amount;
use bitcoin::Denomination;
use bitcoin::OutPoint;
use bitcoin::TxOut;
use bitcoin::Txid;
use bitcoin::XOnlyPublicKey;
use clap::Parser;
use clap::Subcommand;
use futures::StreamExt;
use jiff::Timestamp;
use rand::thread_rng;
use serde::Deserialize;
use std::collections::HashMap;
use std::fs;
use std::str::FromStr;
use tokio::task::block_in_place;
#[derive(Parser)]
#[command(name = "ark-sample")]
#[command(about = "An Ark client in your terminal")]
struct Cli {
/// Path to the configuration file.
#[arg(short, long, default_value = "ark.config.toml")]
config: String,
/// Path to the seed file.
#[arg(short, long, default_value = "ark.seed")]
seed: String,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Show the balance.
Balance,
/// Show the transaction history.
TransactionHistory,
/// Generate a boarding address.
BoardingAddress,
/// Generate an Ark address.
OffchainAddress,
/// Send coins to one or multiple Ark addresses.
SendToArkAddresses {
/// Where to send the coins to.
addresses_and_amounts: AddressesAndAmounts,
},
/// Transform boarding outputs and VTXOs into fresh, confirmed VTXOs.
Settle,
/// Subscribe to notifications for an Ark address.
Subscribe {
/// The Ark address to subscribe to.
address: ArkAddressCli,
},
/// Send on-chain to address
SendOnchain {
/// Where to send the funds to
address: bitcoin::Address<NetworkUnchecked>,
/// How many sats to send.
amount: u64,
},
}
#[derive(Clone)]
struct ArkAddressCli(ArkAddress);
impl FromStr for ArkAddressCli {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let address = ArkAddress::decode(s)?;
Ok(Self(address))
}
}
#[derive(Clone)]
struct AddressesAndAmounts(Vec<(ArkAddress, Amount)>);
impl FromStr for AddressesAndAmounts {
type Err = anyhow::Error;
fn from_str(input: &str) -> Result<Self, Self::Err> {
let parts: Vec<&str> = input.split(',').collect();
if !parts.len().is_multiple_of(2) {
bail!("invalid input: expected comma-separated pairs of <address,amount in sats>");
}
let mut addresses_and_amounts = Vec::with_capacity(parts.len() / 2);
for pair in parts.chunks(2) {
let addr_raw = pair[0];
let amt_raw = pair[1];
let addr = ArkAddress::decode(addr_raw)
.with_context(|| format!("failed to decode Ark address: {addr_raw}"))?;
let amount = Amount::from_str_in(amt_raw, Denomination::Satoshi)
.with_context(|| format!("failed to parse amount (sats): {amt_raw}"))?;
addresses_and_amounts.push((addr, amount));
}
Ok(Self(addresses_and_amounts))
}
}
#[derive(Deserialize)]
struct Config {
ark_server_url: String,
esplora_url: String,
}
#[tokio::main]
async fn main() -> Result<()> {
init_tracing();
rustls::crypto::ring::default_provider()
.install_default()
.expect("Failed to install rustls crypto provider");
let cli = Cli::parse();
let seed = fs::read_to_string(cli.seed)?;
let sk = SecretKey::from_str(&seed)?;
let config = fs::read_to_string(cli.config)?;
let config: Config = toml::from_str(&config)?;
let secp = Secp256k1::new();
let pk = PublicKey::from_secret_key(&secp, &sk);
let ark_server_url = config.ark_server_url;
// Create and connect the appropriate client based on feature flags
#[cfg(feature = "rest-client")]
let client = {
tracing::info!("Starting Ark sample with rest client");
ark_rest::Client::new(ark_server_url)
};
#[cfg(not(feature = "rest-client"))]
let mut client = {
tracing::info!("Starting Ark sample with grpc client");
let mut grpc_client = ark_grpc::Client::new(ark_server_url);
grpc_client.connect().await?;
grpc_client
};
let server_info = client.get_info().await?;
let esplora_client = EsploraClient::new(&config.esplora_url)?;
// In this example we use the same script for all VTXOs.
let vtxo = Vtxo::new_default(
&secp,
server_info.pk.into(),
pk.into(),
server_info.unilateral_exit_delay,
server_info.network,
)?;
// In this example we use the same script for all boarding outputs.
let boarding_output = BoardingOutput::new(
&secp,
server_info.pk.x_only_public_key().0,
pk.x_only_public_key().0,
server_info.boarding_exit_delay,
server_info.network,
)?;
let runtime = tokio::runtime::Handle::current();
let find_outpoints_fn =
|address: &bitcoin::Address| -> Result<Vec<ExplorerUtxo>, ark_core::Error> {
block_in_place(|| {
runtime.block_on(async {
let outpoints = esplora_client
.find_outpoints(address)
.await
.map_err(ark_core::Error::ad_hoc)?;
Ok(outpoints)
})
})
};
match &cli.command {
Commands::Balance => {
let virtual_tx_outpoints = {
let spendable_vtxos =
spendable_vtxos(&client, std::slice::from_ref(&vtxo), false).await?;
list_virtual_tx_outpoints(find_outpoints_fn, spendable_vtxos)?
};
let boarding_outpoints =
list_boarding_outpoints(find_outpoints_fn, &[boarding_output])?;
println!(
"Offchain balance: spendable = {}, expired = {}",
virtual_tx_outpoints.spendable_balance(),
virtual_tx_outpoints.expired_balance()
);
println!(
"Boarding balance: spendable = {}, expired = {}, pending = {}",
boarding_outpoints.spendable_balance(),
boarding_outpoints.expired_balance(),
boarding_outpoints.pending_balance()
);
}
Commands::TransactionHistory => {
let txs: Vec<history::Transaction> = transaction_history(
&client,
&esplora_client,
&[boarding_output.address().clone()],
&[vtxo],
)
.await?;
if txs.is_empty() {
println!("No transactions found");
}
for tx in txs.iter() {
println!("{}\n", pretty_print_transaction(tx)?);
}
}
Commands::BoardingAddress => {
let boarding_address = boarding_output.address();
println!("Send coins to this on-chain address: {boarding_address}\n");
println!(
"Once confirmed, you will have {} seconds to exchange the boarding output for a VTXO.",
boarding_output.exit_delay_duration().as_secs()
);
}
Commands::OffchainAddress => {
let offchain_address = vtxo.to_ark_address();
println!("Send VTXOs to this offchain address: {offchain_address}\n");
}
Commands::Settle => {
let virtual_tx_outpoints = {
let spendable_vtxos =
spendable_vtxos(&client, std::slice::from_ref(&vtxo), true).await?;
list_virtual_tx_outpoints(find_outpoints_fn, spendable_vtxos)?
};
let boarding_outpoints =
list_boarding_outpoints(find_outpoints_fn, &[boarding_output])?;
let res = settle(
&client,
&server_info,
sk,
virtual_tx_outpoints,
boarding_outpoints,
vtxo.to_ark_address(),
)
.await;
match res {
Ok(Some(txid)) => {
println!(
"Settled boarding outputs and VTXOs into new VTXOs.\n\n Batch TXID: {txid}\n"
);
}
Ok(None) => {
println!("No boarding outputs or VTXOs can be settled at the moment.");
}
Err(e) => {
println!("Failed to settle boarding outputs and VTXOs: {e:#}");
}
}
}
Commands::SendToArkAddresses {
addresses_and_amounts,
} => {
let addresses_and_amounts = &addresses_and_amounts.0;
let total_amount = addresses_and_amounts
.iter()
.map(|(_, amount)| *amount)
.sum();
let virtual_tx_outpoints = {
let spendable_vtxos =
spendable_vtxos(&client, std::slice::from_ref(&vtxo), false).await?;
list_virtual_tx_outpoints(find_outpoints_fn, spendable_vtxos)?
};
let selected_outpoints = {
let virtual_tx_outpoints = virtual_tx_outpoints
.spendable
.iter()
.map(|(outpoint, _)| ark_core::coin_select::VirtualTxOutPoint {
outpoint: outpoint.outpoint,
expire_at: outpoint.expires_at,
amount: outpoint.amount,
})
.collect::<Vec<_>>();
select_vtxos(virtual_tx_outpoints, total_amount, server_info.dust, true)?
};
let vtxo_inputs = virtual_tx_outpoints
.spendable
.into_iter()
.filter(|(outpoint, _)| {
selected_outpoints
.iter()
.any(|o| o.outpoint == outpoint.outpoint)
})
.map(|(outpoint, vtxo)| {
let (forfeit_script, control_block) = vtxo.forfeit_spend_info()?;
anyhow::Ok(send::VtxoInput::new(
forfeit_script,
None,
control_block,
vtxo.tapscripts(),
vtxo.script_pubkey(),
outpoint.amount,
outpoint.outpoint,
))
})
.collect::<Result<Vec<_>, _>>()?;
let change_address = vtxo.to_ark_address();
let secp = Secp256k1::new();
let kp = Keypair::from_secret_key(&secp, &sk);
let outputs = addresses_and_amounts
.iter()
.map(|(address, amount)| (address, *amount))
.collect::<Vec<_>>();
let OffchainTransactions {
mut ark_tx,
checkpoint_txs,
} = build_offchain_transactions(
outputs.as_slice(),
Some(&change_address),
&vtxo_inputs,
&server_info,
)?;
let sign_fn =
|_: &mut psbt::Input,
msg: secp256k1::Message|
-> Result<(schnorr::Signature, XOnlyPublicKey), ark_core::Error> {
let sig = Secp256k1::new().sign_schnorr_no_aux_rand(&msg, &kp);
let pk = kp.x_only_public_key().0;
Ok((sig, pk))
};
for i in 0..checkpoint_txs.len() {
sign_ark_transaction(
sign_fn,
&mut ark_tx,
&checkpoint_txs
.iter()
.map(|(_, output, outpoint, _)| (output.clone(), *outpoint))
.collect::<Vec<_>>(),
i,
)?;
}
let ark_txid = ark_tx.unsigned_tx.compute_txid();
let mut res = client
.submit_offchain_transaction_request(
ark_tx,
checkpoint_txs
.into_iter()
.map(|(psbt, _, _, _)| psbt)
.collect(),
)
.await
.context("failed to submit offchain transaction request")?;
for checkpoint_psbt in res.signed_checkpoint_txs.iter_mut() {
let vtxo_input = vtxo_inputs
.iter()
.find(|input| {
checkpoint_psbt.unsigned_tx.input[0].previous_output == input.outpoint()
})
.with_context(|| {
format!(
"could not find VTXO input for checkpoint transaction {}",
checkpoint_psbt.unsigned_tx.compute_txid(),
)
})?;
sign_checkpoint_transaction(sign_fn, checkpoint_psbt, vtxo_input)?;
}
client
.finalize_offchain_transaction(ark_txid, res.signed_checkpoint_txs)
.await
.context("failed to finalize offchain transaction")?;
let all_addresses = addresses_and_amounts
.iter()
.map(|(address, _)| address.encode())
.collect::<Vec<_>>();
println!("Sent {total_amount} to {all_addresses:?} in transaction {ark_txid}",);
}
Commands::Subscribe { address } => {
println!("Subscribing to address: {}", address.0);
// First subscribe to the address to get a subscription ID
let subscription_id = client.subscribe_to_scripts(vec![address.0], None).await?;
println!("Subscription ID: {subscription_id}",);
// Now get the subscription stream
let mut subscription_stream = client.get_subscription(subscription_id).await?;
println!("Listening for notifications... Press Ctrl+C to stop");
// Process subscription responses as they come in
while let Some(result) = subscription_stream.next().await {
match result {
Ok(response) => {
let psbt = if let Some(psbt) = response.tx {
psbt
} else {
let fetched = client
.get_virtual_txs(vec![response.txid.to_string()], None)
.await?;
fetched.txs.into_iter().next().context("no txs")?
};
let tx = &psbt.unsigned_tx;
let output = tx.output.to_vec().iter().find_map(|out| {
if out.script_pubkey == address.0.to_p2tr_script_pubkey() {
Some(out.clone())
} else {
None
}
});
match output {
None => {
println!(
"Received subscription response did not include our address"
);
}
Some(output) => {
println!("Received subscription response:");
println!(" TXID: {}", tx.compute_txid());
println!(" Output Value: {:?}", output.value);
println!(" Output Address: {:?}", address.0.encode());
}
}
println!("---");
}
Err(e) => {
println!("Error receiving subscription response: {e}");
break;
}
}
}
println!("Subscription stream ended");
}
Commands::SendOnchain { address, amount } => {
let address = address.clone().assume_checked();
let address_string = address.to_string();
let amount = Amount::from_sat(*amount);
println!("Collaboratively redeeming {amount} to {address_string}");
let change_address = vtxo.to_ark_address();
let virtual_tx_outpoints = {
let spendable_vtxos =
spendable_vtxos(&client, std::slice::from_ref(&vtxo), true).await?;
list_virtual_tx_outpoints(find_outpoints_fn, spendable_vtxos)?
};
let res = collaboratively_redeem(
&client,
&server_info,
sk,
address,
change_address,
amount,
virtual_tx_outpoints,
)
.await;
match res {
Ok(Some(txid)) => {
println!("Sending onchain successful.\n\n Batch TXID: {txid}\n");
}
Ok(None) => {
println!("No boarding outputs or VTXOs can be settled at the moment.");
}
Err(e) => {
println!("Failed to send onchain: {e:#}");
}
}
}
}
Ok(())
}
async fn collaboratively_redeem(
#[cfg(feature = "rest-client")] client: &ark_rest::Client,
#[cfg(not(feature = "rest-client"))] client: &ark_grpc::Client,
server_info: &ark_core::server::Info,
sk: SecretKey,
address: bitcoin::Address,
change_address: ArkAddress,
amount: Amount,
vtxos: VirtualTxOutPoints,
) -> Result<Option<Txid>> {
if vtxos.spendable.is_empty() {
bail!("No spendable vtxos found");
}
let batch_inputs = vtxos
.spendable
.clone()
.into_iter()
.map(|(virtual_tx_outpoint, vtxo)| {
anyhow::Ok(proof_of_funds::Input::new(
virtual_tx_outpoint.outpoint,
vtxo.exit_delay(),
TxOut {
value: virtual_tx_outpoint.amount,
script_pubkey: vtxo.script_pubkey(),
},
vtxo.tapscripts(),
vtxo.owner_pk(),
vtxo.exit_spend_info()?,
false,
))
})
.collect::<Result<Vec<_>, _>>()?;
let change_amount = vtxos
.spendable_balance()
.checked_sub(amount)
.context("Not enough spendable balance")?;
let mut batch_outputs = Vec::new();
batch_outputs.push(proof_of_funds::Output::Onchain(TxOut {
value: amount,
script_pubkey: address.script_pubkey(),
}));
if change_amount > server_info.dust {
batch_outputs.push(proof_of_funds::Output::Offchain(TxOut {
value: change_amount,
script_pubkey: change_address.to_p2tr_script_pubkey(),
}))
} else if change_amount > Amount::ZERO {
tracing::info!(
"omitting offchain change {} as it is <= dust {}",
change_amount,
server_info.dust
);
}
let vtxo_inputs = vtxos
.spendable
.clone()
.into_iter()
.map(|(outpoint, vtxo)| {
batch::VtxoInput::new(
vtxo,
outpoint.amount,
outpoint.outpoint,
outpoint.is_recoverable(),
)
})
.collect::<Vec<_>>();
let topics = vtxos
.spendable
.iter()
.map(|(o, _)| o.outpoint.to_string())
.collect();
execute_batch(
client,
server_info,
sk,
batch_inputs,
batch_outputs,
vtxo_inputs,
vec![],
topics,
)
.await
}
async fn spendable_vtxos(
#[cfg(feature = "rest-client")] client: &ark_rest::Client,
#[cfg(not(feature = "rest-client"))] client: &ark_grpc::Client,
vtxos: &[Vtxo],
include_recoverable_vtxos: bool,
) -> Result<HashMap<Vtxo, Vec<VirtualTxOutPoint>>> {
let mut spendable_vtxos = HashMap::new();
for vtxo in vtxos.iter() {
let request = GetVtxosRequest::new_for_addresses(&[vtxo.to_ark_address()]);
// The VTXOs for the given Ark address that the Ark server tells us about.
let list = client.list_vtxos(request).await?;
let spendable = if include_recoverable_vtxos {
list.spendable_with_recoverable()
} else {
list.spendable().to_vec()
};
spendable_vtxos.insert(vtxo.clone(), spendable);
}
Ok(spendable_vtxos)
}
async fn settle(
#[cfg(feature = "rest-client")] client: &ark_rest::Client,
#[cfg(not(feature = "rest-client"))] client: &ark_grpc::Client,
server_info: &ark_core::server::Info,
sk: SecretKey,
vtxos: VirtualTxOutPoints,
boarding_outputs: BoardingOutpoints,
to_address: ArkAddress,
) -> Result<Option<Txid>> {
if vtxos.spendable.is_empty() && boarding_outputs.spendable.is_empty() {
return Ok(None);
}
let batch_inputs = {
let boarding_inputs = boarding_outputs.spendable.clone().into_iter().map(
|(outpoint, amount, boarding_output)| {
proof_of_funds::Input::new(
outpoint,
boarding_output.exit_delay(),
TxOut {
value: amount,
script_pubkey: boarding_output.script_pubkey(),
},
boarding_output.tapscripts(),
boarding_output.owner_pk(),
boarding_output.exit_spend_info(),
true,
)
},
);
let vtxo_inputs = vtxos
.spendable
.clone()
.into_iter()
.map(|(virtual_tx_outpoint, vtxo)| {
anyhow::Ok(proof_of_funds::Input::new(
virtual_tx_outpoint.outpoint,
vtxo.exit_delay(),
TxOut {
value: virtual_tx_outpoint.amount,
script_pubkey: vtxo.script_pubkey(),
},
vtxo.tapscripts(),
vtxo.owner_pk(),
vtxo.exit_spend_info()?,
false,
))
})
.collect::<Result<Vec<_>, _>>()?;
boarding_inputs.chain(vtxo_inputs).collect::<Vec<_>>()
};
let spendable_amount = boarding_outputs.spendable_balance() + vtxos.spendable_balance();
let batch_outputs = vec![proof_of_funds::Output::Offchain(TxOut {
value: spendable_amount,
script_pubkey: to_address.to_p2tr_script_pubkey(),
})];
let vtxo_inputs = vtxos
.spendable
.clone()
.into_iter()
.map(|(outpoint, vtxo)| {
batch::VtxoInput::new(
vtxo,
outpoint.amount,
outpoint.outpoint,
outpoint.is_recoverable(),
)
})
.collect::<Vec<_>>();
let onchain_inputs = boarding_outputs
.spendable
.into_iter()
.map(|(outpoint, amount, boarding_output)| {
batch::OnChainInput::new(boarding_output, amount, outpoint)
})
.collect::<Vec<_>>();
let topics = vtxos
.spendable
.iter()
.map(|(o, _)| o.outpoint.to_string())
.collect();
execute_batch(
client,
server_info,
sk,
batch_inputs,
batch_outputs,
vtxo_inputs,
onchain_inputs,
topics,
)
.await
}
pub struct EsploraClient {
esplora_client: esplora_client::AsyncClient,
}
#[derive(Clone, Copy, Debug)]
pub struct SpendStatus {
pub spend_txid: Option<Txid>,
}
impl EsploraClient {
pub fn new(url: &str) -> Result<Self> {
let builder = esplora_client::Builder::new(url);
let esplora_client = builder.build_async()?;
Ok(Self { esplora_client })
}
async fn find_outpoints(&self, address: &bitcoin::Address) -> Result<Vec<ExplorerUtxo>> {
let script_pubkey = address.script_pubkey();
let txs = self
.esplora_client
.scripthash_txs(&script_pubkey, None)
.await?;
let outputs = txs
.into_iter()
.flat_map(|tx| {
let txid = tx.txid;
tx.vout
.iter()
.enumerate()
.filter(|(_, v)| v.scriptpubkey == script_pubkey)
.map(|(i, v)| ExplorerUtxo {
outpoint: OutPoint {
txid,
vout: i as u32,
},
amount: Amount::from_sat(v.value),
confirmation_blocktime: tx.status.block_time,
// Assume the output is unspent until we dig deeper, further down.
is_spent: false,
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
let mut utxos = Vec::new();
for output in outputs.iter() {
let outpoint = output.outpoint;
let status = self
.esplora_client
.get_output_status(&outpoint.txid, outpoint.vout as u64)
.await?;
match status {
Some(esplora_client::OutputStatus { spent: false, .. }) | None => {
utxos.push(*output);
}
Some(esplora_client::OutputStatus { spent: true, .. }) => {
utxos.push(ExplorerUtxo {
is_spent: true,
..*output
});
}
}
}
Ok(utxos)
}
async fn get_output_status(&self, txid: &Txid, vout: u32) -> Result<SpendStatus> {
let status = self
.esplora_client
.get_output_status(txid, vout as u64)
.await?;
Ok(SpendStatus {
spend_txid: status.and_then(|s| s.txid),
})
}
}
async fn transaction_history(
#[cfg(feature = "rest-client")] client: &ark_rest::Client,
#[cfg(not(feature = "rest-client"))] client: &ark_grpc::Client,
onchain_explorer: &EsploraClient,
boarding_addresses: &[bitcoin::Address],
vtxos: &[Vtxo],
) -> Result<Vec<history::Transaction>> {
let mut boarding_transactions = Vec::new();
let mut boarding_commitment_transactions = Vec::new();
for boarding_address in boarding_addresses.iter() {
let outpoints = onchain_explorer.find_outpoints(boarding_address).await?;
for ExplorerUtxo {
outpoint,
amount,
confirmation_blocktime,
..
} in outpoints.iter()
{
let confirmed_at = confirmation_blocktime.map(|t| t as i64);
boarding_transactions.push(history::Transaction::Boarding {
txid: outpoint.txid,
amount: *amount,
confirmed_at,
});
let status = onchain_explorer
.get_output_status(&outpoint.txid, outpoint.vout)
.await?;
if let Some(spend_txid) = status.spend_txid {
boarding_commitment_transactions.push(spend_txid);
}
}
}
let mut incoming_transactions = Vec::new();
let mut outgoing_transactions = Vec::new();
for vtxo in vtxos.iter() {
let request = GetVtxosRequest::new_for_addresses(&[vtxo.to_ark_address()]);
let vtxo_list = client.list_vtxos(request).await?;
let mut new_incoming_transactions = generate_incoming_vtxo_transaction_history(
vtxo_list.spent(),
vtxo_list.spendable(),
&boarding_commitment_transactions,
)?;
incoming_transactions.append(&mut new_incoming_transactions);
let relevant_txs =
generate_outgoing_vtxo_transaction_history(vtxo_list.spent(), vtxo_list.spendable())?;
for relevant_tx in relevant_txs {
match relevant_tx {
history::OutgoingTransaction::Complete(tx) => outgoing_transactions.push(tx),
history::OutgoingTransaction::Incomplete(incomplete_tx) => {
let request =
GetVtxosRequest::new_for_outpoints(&[incomplete_tx.first_outpoint()]);
let list = client.list_vtxos(request).await?;
if let Some(spend_tx_vtxo) = list.all().first() {
let tx = incomplete_tx.finish(spend_tx_vtxo)?;
outgoing_transactions.push(tx);
}
}
}
}
}
let mut txs = [
boarding_transactions,
incoming_transactions,
outgoing_transactions,
]
.concat();
sort_transactions_by_created_at(&mut txs);
Ok(txs)
}
fn pretty_print_transaction(tx: &history::Transaction) -> Result<String> {
let print_str = match tx {
history::Transaction::Boarding {
txid,
amount,
confirmed_at,
} => {
let time = match confirmed_at {
Some(t) => format!("{}", Timestamp::from_second(*t)?),
None => "Pending confirmation".to_string(),
};
format!(
"Type: Boarding\n\
TXID: {txid}\n\
Status: Received\n\
Amount: {amount}\n\
Time: {time}"
)
}
history::Transaction::Commitment {
txid,
amount,
created_at,
} => {
let status = match amount.is_positive() {
true => "Received",
false => "Sent",
};
let amount = amount.abs();
let time = Timestamp::from_second(*created_at)?;
format!(
"Type: Commitment\n\
TXID: {txid}\n\
Status: {status}\n\
Amount: {amount}\n\
Time: {time}"
)
}
history::Transaction::Ark {
txid,
amount,
is_settled,
created_at,
} => {
let status = match amount.is_positive() {
true => "Received",
false => "Sent",
};
let settlement = match is_settled {
true => "Confirmed",
false => "Pending",
};
let amount = amount.abs();
let time = Timestamp::from_second(*created_at)?;
format!(
"Type: Ark\n\
TXID: {txid}\n\
Status: {status}\n\
Settlement: {settlement}\n\
Amount: {amount}\n\
Time: {time}"
)