forked from spacesprotocol/spaces
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspace-cli.rs
775 lines (751 loc) · 24.9 KB
/
space-cli.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
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
extern crate core;
use std::{fs, path::PathBuf, str::FromStr};
use clap::{Parser, Subcommand};
use jsonrpsee::{
core::{client::Error, ClientError},
http_client::{HttpClient, HttpClientBuilder},
};
use protocol::{
bitcoin::{Amount, FeeRate, OutPoint, Txid},
hasher::KeyHasher,
slabel::SLabel,
};
use serde::{Deserialize, Serialize};
use spaced::{
config::{default_spaces_rpc_port, ExtendedNetwork},
rpc::{
BidParams, ExecuteParams, OpenParams, RegisterParams, RpcClient, RpcWalletRequest,
RpcWalletTxBuilder, SendCoinsParams, TransferSpacesParams,
},
store::Sha256,
wallets::AddressKind,
};
use spaced::rpc::SignedMessage;
use wallet::bitcoin::secp256k1::schnorr::Signature;
use wallet::export::WalletExport;
use wallet::Listing;
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
pub struct Args {
/// Bitcoin network to use
#[arg(long, env = "SPACED_CHAIN", default_value = "mainnet")]
chain: ExtendedNetwork,
/// Spaced RPC URL [default: based on specified chain]
#[arg(long)]
spaced_rpc_url: Option<String>,
/// Specify wallet to use
#[arg(long, short, global = true, default_value = "default")]
wallet: String,
/// Custom dust amount in sat for bid outputs
#[arg(long, short, global = true)]
dust: Option<u64>,
/// Force invalid transaction (for testing only)
#[arg(long, global = true, default_value = "false")]
force: bool,
/// Skip tx checker (not recommended)
#[arg(long, global = true, default_value = "false")]
skip_tx_check: bool,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug, Clone)]
enum Commands {
/// Generate a new wallet
#[command(name = "createwallet")]
CreateWallet,
/// Load a wallet
#[command(name = "loadwallet")]
LoadWallet,
/// Export a wallet
#[command(name = "exportwallet")]
ExportWallet {
// Destination path to export json file
path: PathBuf,
},
/// Import a wallet
#[command(name = "importwallet")]
ImportWallet {
// Wallet json file to import
path: PathBuf,
},
/// Export a wallet
#[command(name = "getwalletinfo")]
GetWalletInfo,
/// Export a wallet
#[command(name = "getserverinfo")]
GetServerInfo,
/// Open an auction
Open {
/// Space name
space: String,
/// Amount in sats
#[arg(default_value = "1000")]
initial_bid: u64,
/// Fee rate to use in sat/vB
#[arg(long, short)]
fee_rate: Option<u64>,
},
/// Place a bid
Bid {
/// Space name
space: String,
/// Amount in satoshi
amount: u64,
/// Fee rate to use in sat/vB
#[arg(long, short)]
fee_rate: Option<u64>,
#[arg(long, short, default_value = "false")]
confirmed_only: bool,
},
/// Register a won auction
Register {
/// Space name
space: String,
/// Recipient address
address: Option<String>,
/// Fee rate to use in sat/vB
#[arg(long, short)]
fee_rate: Option<u64>,
},
/// Get space info
#[command(name = "getspace")]
GetSpace {
/// The space name
space: String,
},
/// Transfer ownership of a set of spaces to the given name or address
#[command(
name = "transfer",
override_usage = "space-cli transfer [SPACES]... --to <SPACE-OR-ADDRESS>"
)]
Transfer {
/// Spaces to send
#[arg(display_order = 0)]
spaces: Vec<String>,
/// Recipient space name or address (must be a space address)
#[arg(long, display_order = 1)]
to: String,
/// Fee rate to use in sat/vB
#[arg(long, short)]
fee_rate: Option<u64>,
},
/// Renew ownership of a space
#[command(name = "renew", )]
Renew {
/// Spaces to renew
#[arg(display_order = 0)]
spaces: Vec<String>,
/// Fee rate to use in sat/vB
#[arg(long, short)]
fee_rate: Option<u64>,
},
/// Estimates the minimum bid needed for a rollout within the given target blocks
#[command(name = "estimatebid")]
EstimateBid {
/// Rollout within target blocks
#[arg(default_value = "0")]
target: usize,
},
/// Send the specified amount of BTC to the given name or address
#[command(
name = "send",
override_usage = "space-cli send <AMOUNT> --to <SPACE-OR-ADDRESS>"
)]
SendCoins {
/// Amount to send in satoshi
#[arg(display_order = 0)]
amount: u64,
/// Recipient space name or address
#[arg(long, display_order = 1)]
to: String,
/// Fee rate to use in sat/vB
#[arg(long, short)]
fee_rate: Option<u64>,
},
/// Get wallet balance
#[command(name = "balance")]
Balance,
/// Pre-create outputs that can be auctioned off during the bidding process
#[command(name = "createbidouts")]
CreateBidOuts {
/// Number of output pairs to create
/// Each pair can be used to make a bid
pairs: u8,
/// Fee rate to use in sat/vB
#[arg(long, short)]
fee_rate: Option<u64>,
},
/// Bump the fee for a transaction created by this wallet
#[command(name = "bumpfee")]
BumpFee {
txid: Txid,
/// Fee rate to use in sat/vB
#[arg(long, short)]
fee_rate: u64,
},
/// Buy a space from the specified listing
#[command(name = "buy")]
Buy {
/// The space to buy
space: String,
/// The listing price
price: u64,
/// The seller's signature
#[arg(long)]
signature: String,
/// The seller's address
#[arg(long)]
seller: String,
/// Fee rate to use in sat/vB
#[arg(long, short)]
fee_rate: Option<u64>,
},
/// Sign a message using the owner address of the specified space
#[command(name = "signmessage")]
SignMessage {
/// The space to use
space: String,
/// The message to sign
message: String,
},
/// Verify a message using the owner address of the specified space
#[command(name = "verifymessage")]
VerifyMessage {
/// The space to verify
space: String,
/// The message to verify
message: String,
/// The signature to verify
#[arg(long)]
signature: String,
},
/// List a space you own for sale
#[command(name = "sell")]
Sell {
/// The space to sell
space: String,
/// Amount in satoshis
price: u64,
},
/// Verify a listing
#[command(name = "verifylisting")]
VerifyListing {
/// The space to buy
space: String,
/// The listing price
price: u64,
/// The seller's signature
#[arg(long)]
signature: String,
/// The seller's address
#[arg(long)]
seller: String,
},
/// Get a spaceout - a Bitcoin output relevant to the Spaces protocol.
#[command(name = "getspaceout")]
GetSpaceOut {
/// The OutPoint
outpoint: OutPoint,
},
/// Get the estimated rollout batch for the specified interval
#[command(name = "getrollout")]
GetRollout {
// Get the estimated rollout for the target interval. Every ~144 blocks (a rollout interval),
// 10 spaces are released for auction. Specify 0 [default] for the coming interval, 1
// for the interval after and so on.
#[arg(default_value = "0")]
target_interval: usize,
},
/// Associate the specified data with a given space (not recommended use Fabric instead)
/// If for whatever reason it's not possible to use other protocols, then you may use this.
#[command(name = "setrawfallback")]
SetRawFallback {
/// Space name
space: String,
/// Hex encoded data
data: String,
/// Fee rate to use in sat/vB
#[arg(long, short)]
fee_rate: Option<u64>,
},
/// List last transactions
#[command(name = "listtransactions")]
ListTransactions {
#[arg(default_value = "10")]
count: usize,
#[arg(default_value = "0")]
skip: usize,
},
/// List won spaces including ones
/// still in auction with a winning bid
#[command(name = "listspaces")]
ListSpaces,
/// List unspent auction outputs i.e. outputs that can be
/// auctioned off in the bidding process
#[command(name = "listbidouts")]
ListBidOuts,
/// List unspent coins owned by wallet
#[command(name = "listunspent")]
ListUnspent,
/// Get a new Bitcoin address suitable for receiving spaces and coins
/// (Spaces compatible bitcoin wallets only)
#[command(name = "getnewspaceaddress")]
GetSpaceAddress,
/// Get a new Bitcoin address suitable for receiving coins
/// compatible with most bitcoin wallets
#[command(name = "getnewaddress")]
GetCoinAddress,
/// Force spend an output owned by wallet (for testing only)
#[command(name = "forcespend")]
ForceSpend {
outpoint: OutPoint,
#[arg(long, short)]
fee_rate: u64,
},
/// DNS encodes the space and calculates the SHA-256 hash
#[command(name = "hashspace")]
HashSpace { space: String },
}
struct SpaceCli {
wallet: String,
dust: Option<Amount>,
force: bool,
skip_tx_check: bool,
network: ExtendedNetwork,
rpc_url: String,
client: HttpClient,
}
impl SpaceCli {
async fn configure() -> anyhow::Result<(Self, Args)> {
let mut args = Args::parse();
if args.spaced_rpc_url.is_none() {
args.spaced_rpc_url = Some(default_spaced_rpc_url(&args.chain));
}
let client = HttpClientBuilder::default().build(args.spaced_rpc_url.clone().unwrap())?;
Ok((
Self {
wallet: args.wallet.clone(),
dust: args.dust.map(|d| Amount::from_sat(d)),
force: args.force,
skip_tx_check: args.skip_tx_check,
network: args.chain,
rpc_url: args.spaced_rpc_url.clone().unwrap(),
client,
},
args,
))
}
async fn send_request(
&self,
req: Option<RpcWalletRequest>,
bidouts: Option<u8>,
fee_rate: Option<u64>,
confirmed_only: bool,
) -> Result<(), ClientError> {
let fee_rate = fee_rate.map(|fee| FeeRate::from_sat_per_vb(fee).unwrap());
let result = self
.client
.wallet_send_request(
&self.wallet,
RpcWalletTxBuilder {
bidouts,
requests: match req {
None => vec![],
Some(req) => vec![req],
},
fee_rate,
dust: self.dust,
force: self.force,
confirmed_only,
skip_tx_check: self.skip_tx_check,
},
)
.await?;
println!(
"{}",
serde_json::to_string_pretty(&result).expect("serialize")
);
Ok(())
}
}
fn normalize_space(space: &str) -> String {
let lowercase = space.to_ascii_lowercase();
if lowercase.starts_with('@') {
lowercase
} else {
format!("@{}", lowercase)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct RpcError {
code: i32,
message: String,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let (cli, args) = SpaceCli::configure().await?;
let result = handle_commands(&cli, args.command).await;
match result {
Ok(_) => {}
Err(error) => match ClientError::from(error) {
Error::Call(rpc) => {
let error = RpcError {
code: rpc.code(),
message: rpc.message().to_string(),
};
println!(
"{}",
serde_json::to_string_pretty(&error).expect("serialize")
);
}
Error::Transport(err) => {
println!(
"Transport error: {}: Rpc url: {} (network: {})",
err, cli.rpc_url, cli.network
);
}
Error::RestartNeeded(err) => {
println!("Restart needed: {}", err);
}
Error::ParseError(err) => {
println!("Parse error: {}", err);
}
Error::InvalidSubscriptionId => {
println!("Invalid subscription ID");
}
Error::InvalidRequestId(err) => {
println!("Invalid request ID: {}", err);
}
Error::RequestTimeout => {
println!("Request timeout");
}
Error::MaxSlotsExceeded => {
println!("Max concurrent requests exceeded");
}
Error::Custom(msg) => {
println!("Custom error: {}", msg);
}
Error::HttpNotImplemented => {
println!("HTTP not implemented");
}
Error::EmptyBatchRequest(err) => {
println!("Empty batch request: {}", err);
}
Error::RegisterMethod(err) => {
println!("Register method error: {}", err);
}
},
}
Ok(())
}
fn hash_space(spaceish: &str) -> anyhow::Result<String> {
let space = normalize_space(&spaceish);
let sname = SLabel::from_str(&space)?;
Ok(hex::encode(Sha256::hash(sname.as_ref())))
}
async fn handle_commands(
cli: &SpaceCli,
command: Commands,
) -> std::result::Result<(), ClientError> {
match command {
Commands::GetRollout {
target_interval: target,
} => {
let data = cli.client.get_rollout(target).await?;
println!("{}", serde_json::to_string_pretty(&data)?);
}
Commands::EstimateBid { target } => {
let response = cli.client.estimate_bid(target).await?;
println!("{} sat", Amount::from_sat(response).to_sat());
}
Commands::GetSpace { space } => {
let space_hash = hash_space(&space).map_err(|e| ClientError::Custom(e.to_string()))?;
let response = cli.client.get_space(&space_hash).await?;
println!("{}", serde_json::to_string_pretty(&response)?);
}
Commands::GetSpaceOut { outpoint } => {
let response = cli.client.get_spaceout(outpoint).await?;
println!("{}", serde_json::to_string_pretty(&response)?);
}
Commands::CreateWallet => {
cli.client.wallet_create(&cli.wallet).await?;
}
Commands::LoadWallet => {
cli.client.wallet_load(&cli.wallet).await?;
}
Commands::ImportWallet { path } => {
let content =
fs::read_to_string(path).map_err(|e| ClientError::Custom(e.to_string()))?;
let wallet: WalletExport = serde_json::from_str(&content)?;
cli.client.wallet_import(wallet).await?;
}
Commands::ExportWallet { path } => {
let result = cli.client.wallet_export(&cli.wallet).await?;
let content = serde_json::to_string_pretty(&result).expect("result");
fs::write(path, content).map_err(|e| {
ClientError::Custom(format!("Could not save to path: {}", e.to_string()))
})?;
}
Commands::GetWalletInfo => {
let result = cli.client.wallet_get_info(&cli.wallet).await?;
println!("{}", serde_json::to_string_pretty(&result).expect("result"));
}
Commands::GetServerInfo => {
let result = cli.client.get_server_info().await?;
println!("{}", serde_json::to_string_pretty(&result).expect("result"));
}
Commands::Open {
ref space,
initial_bid,
fee_rate,
} => {
cli.send_request(
Some(RpcWalletRequest::Open(OpenParams {
name: normalize_space(space),
amount: initial_bid,
})),
None,
fee_rate,
false,
)
.await?
}
Commands::Bid {
space,
amount,
fee_rate,
confirmed_only,
} => {
cli.send_request(
Some(RpcWalletRequest::Bid(BidParams {
name: normalize_space(&space),
amount,
})),
None,
fee_rate,
confirmed_only,
)
.await?
}
Commands::CreateBidOuts { pairs, fee_rate } => {
cli.send_request(None, Some(pairs), fee_rate, false).await?
}
Commands::Register {
space,
address,
fee_rate,
} => {
cli.send_request(
Some(RpcWalletRequest::Register(RegisterParams {
name: normalize_space(&space),
to: address,
})),
None,
fee_rate,
false,
)
.await?
}
Commands::Renew { spaces, fee_rate } => {
let spaces: Vec<_> = spaces.into_iter().map(|s| normalize_space(&s)).collect();
cli.send_request(
Some(RpcWalletRequest::Transfer(TransferSpacesParams {
spaces,
to: None,
})),
None,
fee_rate,
false,
)
.await?
}
Commands::Transfer {
spaces,
to,
fee_rate,
} => {
let spaces: Vec<_> = spaces.into_iter().map(|s| normalize_space(&s)).collect();
cli.send_request(
Some(RpcWalletRequest::Transfer(TransferSpacesParams {
spaces,
to: Some(to),
})),
None,
fee_rate,
false,
)
.await?
}
Commands::SendCoins {
amount,
to,
fee_rate,
} => {
cli.send_request(
Some(RpcWalletRequest::SendCoins(SendCoinsParams {
amount: Amount::from_sat(amount),
to,
})),
None,
fee_rate,
false,
)
.await?
}
Commands::SetRawFallback {
mut space,
data,
fee_rate,
} => {
space = normalize_space(&space);
let data = match hex::decode(data) {
Ok(data) => data,
Err(e) => {
return Err(ClientError::Custom(format!(
"Could not hex decode data: {}",
e
)))
}
};
let space_script = protocol::script::SpaceScript::create_set_fallback(data.as_slice());
cli.send_request(
Some(RpcWalletRequest::Execute(ExecuteParams {
context: vec![space],
space_script,
})),
None,
fee_rate,
false,
)
.await?;
}
Commands::ListUnspent => {
let spaces = cli.client.wallet_list_unspent(&cli.wallet).await?;
println!("{}", serde_json::to_string_pretty(&spaces)?);
}
Commands::ListBidOuts => {
let spaces = cli.client.wallet_list_bidouts(&cli.wallet).await?;
println!("{}", serde_json::to_string_pretty(&spaces)?);
}
Commands::ListTransactions { count, skip } => {
let txs = cli
.client
.wallet_list_transactions(&cli.wallet, count, skip)
.await?;
println!("{}", serde_json::to_string_pretty(&txs)?);
}
Commands::ListSpaces => {
let spaces = cli.client.wallet_list_spaces(&cli.wallet).await?;
println!("{}", serde_json::to_string_pretty(&spaces)?);
}
Commands::Balance => {
let balance = cli.client.wallet_get_balance(&cli.wallet).await?;
println!("{}", serde_json::to_string_pretty(&balance)?);
}
Commands::GetCoinAddress => {
let response = cli
.client
.wallet_get_new_address(&cli.wallet, AddressKind::Coin)
.await?;
println!("{}", response);
}
Commands::GetSpaceAddress => {
let response = cli
.client
.wallet_get_new_address(&cli.wallet, AddressKind::Space)
.await?;
println!("{}", response);
}
Commands::BumpFee { txid, fee_rate } => {
let fee_rate = FeeRate::from_sat_per_vb(fee_rate).expect("valid fee rate");
let response = cli
.client
.wallet_bump_fee(&cli.wallet, txid, fee_rate, cli.skip_tx_check)
.await?;
println!("{}", serde_json::to_string_pretty(&response)?);
}
Commands::ForceSpend { outpoint, fee_rate } => {
let result = cli
.client
.wallet_force_spend(
&cli.wallet,
outpoint,
FeeRate::from_sat_per_vb(fee_rate).unwrap(),
)
.await?;
println!("{}", serde_json::to_string_pretty(&result).expect("result"));
}
Commands::HashSpace { space } => {
println!(
"{}",
hash_space(&space).map_err(|e| ClientError::Custom(e.to_string()))?
);
}
Commands::Buy { space, price, signature, seller, fee_rate } => {
let listing = Listing {
space: normalize_space(&space),
price,
seller,
signature: Signature::from_slice(hex::decode(signature)
.map_err(|_| ClientError::Custom("Signature must be in hex format".to_string()))?.as_slice())
.map_err(|_| ClientError::Custom("Invalid signature".to_string()))?,
};
let result = cli
.client
.wallet_buy(
&cli.wallet,
listing,
fee_rate.map(|rate| FeeRate::from_sat_per_vb(rate).expect("valid fee rate")),
cli.skip_tx_check,
).await?;
println!("{}", serde_json::to_string_pretty(&result).expect("result"));
}
Commands::Sell { space, price, } => {
let result = cli
.client
.wallet_sell(
&cli.wallet,
space,
price,
).await?;
println!("{}", serde_json::to_string_pretty(&result).expect("result"));
}
Commands::VerifyListing { space, price, signature, seller } => {
let listing = Listing {
space: normalize_space(&space),
price,
seller,
signature: Signature::from_slice(hex::decode(signature)
.map_err(|_| ClientError::Custom("Signature must be in hex format".to_string()))?.as_slice())
.map_err(|_| ClientError::Custom("Invalid signature".to_string()))?,
};
let result = cli
.client
.verify_listing(listing).await?;
println!("{}", serde_json::to_string_pretty(&result).expect("result"));
}
Commands::SignMessage { mut space, message } => {
space = normalize_space(&space);
let result = cli.client
.wallet_sign_message(&cli.wallet, &space, protocol::Bytes::new(message.as_bytes().to_vec())).await?;
println!("{}", result.signature);
}
Commands::VerifyMessage { mut space, message, signature } => {
space = normalize_space(&space);
let raw = hex::decode(signature)
.map_err(|_| ClientError::Custom("Invalid signature".to_string()))?;
let signature = Signature::from_slice(raw.as_slice())
.map_err(|_| ClientError::Custom("Invalid signature".to_string()))?;
let result = cli.client.verify_message(SignedMessage {
space,
message: protocol::Bytes::new(message.as_bytes().to_vec()),
signature,
}).await?;
println!("{}", serde_json::to_string_pretty(&result).expect("result"));
}
}
Ok(())
}
fn default_spaced_rpc_url(chain: &ExtendedNetwork) -> String {
format!("http://127.0.0.1:{}", default_spaces_rpc_port(chain))
}