forked from RGB-WG/rgb-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfungible.rs
523 lines (464 loc) · 16.6 KB
/
fungible.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
// RGB standard library
// Written in 2020 by
// Dr. Maxim Orlovsky <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the MIT License
// along with this software.
// If not, see <https://opensource.org/licenses/MIT>.
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use lnpbp::bitcoin::consensus::{Decodable, Encodable};
use lnpbp::bitcoin::util::psbt::PartiallySignedTransaction;
use lnpbp::bitcoin::OutPoint;
use lnpbp::bp::blind::OutpointReveal;
use lnpbp::bp::psbt::ProprietaryKeyMap;
use lnpbp::client_side_validation::Conceal;
use lnpbp::rgb::prelude::*;
use lnpbp::strict_encoding::strict_encode;
use super::{Error, OutputFormat, Runtime};
use crate::api::fungible::{AcceptApi, Issue, TransferApi};
use crate::api::{reply, Reply};
use crate::fungible::{Asset, Invoice, Outcoincealed, Outcoins, Outpoint};
use crate::util::file::ReadWrite;
use crate::DataFormat;
#[derive(Clap, Clone, Debug, Display)]
#[display(Debug)]
pub enum Command {
/// Lists all known assets
List {
/// Format for information output
#[clap(short, long, arg_enum, default_value = "yaml")]
format: OutputFormat,
/// List all asset details
#[clap(short, long)]
long: bool,
},
Import {
/// Bech32 representation of the asset genesis
asset: Genesis,
},
Export {
/// Bech32 representation of the asset ID (contract id of the asset
/// genesis)
#[clap(parse(try_from_str = ContractId::from_bech32_str))]
asset: ContractId,
},
/// Creates a new asset
Issue(Issue),
/// Create an invoice
Invoice(InvoiceCli),
/// Do a transfer of some requested asset to another party
Transfer(TransferCli),
/// Do a transfer of some requested asset to another party
Validate {
/// Consignment file
consignment: PathBuf,
},
/// Accepts an incoming payment
Accept {
/// Consignment file
consignment: PathBuf,
/// Locally-controlled outpoint (specified when the invoice was
/// created)
outpoint: OutPoint,
/// Outpoint blinding factor (generated when the invoice was created)
blinding_factor: u64,
},
Forget {
/// Bitcoin transaction output that was spent and which data
/// has to be forgotten
outpoint: OutPoint,
},
}
#[derive(Clap, Clone, PartialEq, Debug, Display)]
#[display(Debug)]
pub struct InvoiceCli {
/// Assets
#[clap(parse(try_from_str = ContractId::from_bech32_str))]
pub asset: ContractId,
/// Amount
pub amount: f32,
/// Receive assets to a given bitcoin address or UTXO
pub outpoint: OutPoint,
}
#[derive(Clap, Clone, PartialEq, Debug, Display)]
#[display(Debug)]
pub struct TransferCli {
/// Asset inputs
#[clap(short = 'i', long = "input", min_values = 1)]
pub inputs: Vec<OutPoint>,
/// Adds additional asset allocations; MUST use transaction inputs
/// controlled by the local party
#[clap(short, long)]
pub allocate: Vec<Outcoins>,
/// Invoice to pay
pub invoice: Invoice,
/// Read partially-signed transaction prototype
pub prototype: PathBuf,
/// File to save consignment to
pub consignment: PathBuf,
/// File to save updated partially-signed bitcoin transaction to
pub transaction: PathBuf,
}
impl Command {
pub fn exec(self, runtime: Runtime) -> Result<(), Error> {
match self {
Command::List { format, long } => {
self.exec_list(runtime, format, long)
}
Command::Import { ref asset } => {
self.exec_import(runtime, asset.clone())
}
Command::Export { asset } => self.exec_export(runtime, asset),
Command::Invoice(invoice) => invoice.exec(runtime),
Command::Issue(issue) => issue.exec(runtime),
Command::Transfer(transfer) => transfer.exec(runtime),
Command::Validate { ref consignment } => {
self.exec_validate(runtime, consignment.clone())
}
Command::Accept {
ref consignment,
outpoint,
blinding_factor,
} => self.exec_accept(
runtime,
consignment.clone(),
outpoint,
blinding_factor,
),
Command::Forget { outpoint } => self.exec_forget(runtime, outpoint),
}
}
fn exec_list(
&self,
mut runtime: Runtime,
output_format: OutputFormat,
long: bool,
) -> Result<(), Error> {
match &*runtime.list(output_format)? {
Reply::Failure(failure) => {
eprintln!("Server returned error: {}", failure);
}
Reply::Sync(reply::SyncFormat(input_format, data)) => {
let assets: Vec<Asset> = match input_format {
DataFormat::Yaml => serde_yaml::from_slice(&data)?,
DataFormat::Json => serde_json::from_slice(&data)?,
DataFormat::Toml => toml::from_slice(&data)?,
DataFormat::StrictEncode => unimplemented!(),
};
let short: Vec<HashMap<&str, String>> = assets
.iter()
.map(|a| {
map! {
"id" => a.id().to_bech32_string(),
"ticker" => a.ticker().clone(),
"name" => a.name().clone()
}
})
.collect();
let long_str: String;
let short_str: String;
match output_format {
OutputFormat::Yaml => {
long_str = serde_yaml::to_string(&assets)?;
short_str = serde_yaml::to_string(&short)?;
}
OutputFormat::Json => {
long_str = serde_json::to_string(&assets)?;
short_str = serde_json::to_string(&short)?;
}
OutputFormat::Toml => {
long_str = toml::to_string(&assets)?;
short_str = toml::to_string(&short)?;
}
_ => unimplemented!(),
}
if long {
println!("{}", long_str);
} else {
println!("{}", short_str);
}
}
_ => {
eprintln!(
"Unexpected server error; probably you connecting with outdated client version"
);
}
}
Ok(())
}
fn exec_import(
&self,
mut runtime: Runtime,
genesis: Genesis,
) -> Result<(), Error> {
info!("Importing asset ...");
match &*runtime.import(genesis)? {
Reply::Failure(failure) => {
eprintln!("Server returned error: {}", failure);
}
Reply::Success => {
eprintln!("Asset successfully imported");
}
_ => {
eprintln!(
"Unexpected server error; probably you connecting with outdated client version"
);
}
}
Ok(())
}
fn exec_export(
&self,
mut runtime: Runtime,
asset_id: ContractId,
) -> Result<(), Error> {
info!("Exporting asset ...");
match &*runtime.export(asset_id)? {
Reply::Failure(failure) => {
eprintln!("Server returned error: {}", failure);
}
Reply::Genesis(genesis) => {
eprintln!("Asset successfully exported. Use this information for sharing:");
println!("{}", genesis);
}
_ => {
eprintln!(
"Unexpected server error; probably you connecting with outdated client version"
);
}
}
Ok(())
}
fn exec_validate(
&self,
mut runtime: Runtime,
filename: PathBuf,
) -> Result<(), Error> {
info!("Validating asset transfer...");
debug!("Reading consignment from file {:?}", &filename);
let consignment =
Consignment::read_file(filename.clone()).map_err(|err| {
Error::InputFileFormatError(
format!("{:?}", filename),
format!("{}", err),
)
})?;
trace!("{:?}", strict_encode(&consignment));
match &*runtime.validate(consignment)? {
Reply::Failure(failure) => {
eprintln!("Server returned error: {}", failure);
}
Reply::Success => {
eprintln!("Asset transfer successfully validated.");
}
_ => {
eprintln!(
"Unexpected server error; probably you connecting with outdated client version"
);
}
}
Ok(())
}
fn exec_accept(
&self,
mut runtime: Runtime,
filename: PathBuf,
outpoint: OutPoint,
blinding_factor: u64,
) -> Result<(), Error> {
info!("Accepting asset transfer...");
debug!("Reading consignment from file {:?}", &filename);
let consignment =
Consignment::read_file(filename.clone()).map_err(|err| {
Error::InputFileFormatError(
format!("{:?}", filename),
format!("{}", err),
)
})?;
trace!("{:?}", strict_encode(&consignment));
let api = if let Some((_, outpoint_hash)) = consignment.endpoints.get(0)
{
let outpoint_reveal = OutpointReveal {
blinding: blinding_factor,
txid: outpoint.txid,
vout: outpoint.vout as u32,
};
if outpoint_reveal.conceal() != *outpoint_hash {
eprintln!("The provided outpoint and blinding factors does not match outpoint from the consignment");
Err(Error::DataInconsistency)?
}
AcceptApi {
consignment,
reveal_outpoints: vec![outpoint_reveal],
}
} else {
eprintln!("Currently, this command-line tool is unable to accept consignments containing more than a single locally-controlled output point");
Err(Error::UnsupportedFunctionality)?
};
match &*runtime.accept(api)? {
Reply::Failure(failure) => {
eprintln!("Server returned error: {}", failure);
}
Reply::Success => {
eprintln!("Asset transfer successfully accepted.");
}
_ => {
eprintln!(
"Unexpected server error; probably you connecting with outdated client version"
);
}
}
Ok(())
}
fn exec_forget(
&self,
mut runtime: Runtime,
outpoint: OutPoint,
) -> Result<(), Error> {
info!(
"Forgetting assets allocated to specific bitcoin transaction output that was spent..."
);
match &*runtime.forget(outpoint)? {
Reply::Failure(failure) => {
eprintln!("Server returned error: {}", failure);
}
Reply::Success => {
eprintln!("Assets are removed from the stash.");
}
_ => {
eprintln!(
"Unexpected server error; probably you connecting with outdated client version"
);
}
}
Ok(())
}
}
impl Issue {
pub fn exec(self, mut runtime: Runtime) -> Result<(), Error> {
info!("Issuing asset ...");
debug!("{}", self.clone());
let reply = runtime.issue(self)?;
info!("Reply: {}", reply);
// TODO: Wait for the information from push notification
/*let (asset, genesis) = match reply {
};
debug!("Asset information:\n {:?}\n", asset);
trace!("Genesis contract:\n {:?}\n", genesis);
eprintln!("Asset successfully issued. Use this information for sharing:");
println!("{}", genesis);*/
Ok(())
}
}
impl InvoiceCli {
pub fn exec(self, _: Runtime) -> Result<(), Error> {
info!("Generating invoice ...");
debug!("{}", self.clone());
let outpoint_reveal = OutpointReveal::from(self.outpoint);
let invoice = Invoice {
contract_id: self.asset,
outpoint: Outpoint::BlindedUtxo(outpoint_reveal.conceal()),
amount: self.amount,
};
eprint!("Invoice: ");
println!("{}", invoice);
eprint!("Outpoint blinding factor: ");
println!("{}", outpoint_reveal.blinding);
Ok(())
}
}
impl TransferCli {
#[allow(unreachable_code)]
pub fn exec(self, mut runtime: Runtime) -> Result<(), Error> {
info!("Transferring asset ...");
debug!("{}", self.clone());
let seal_confidential = match self.invoice.outpoint {
Outpoint::BlindedUtxo(outpoint_hash) => outpoint_hash,
Outpoint::Address(_address) => {
// To do a pay-to-address, we need to spend some bitcoins,
// which we have to take from somewhere. While payee can
// provide us with additional input, it's not part of the
// invoicing protocol + does not make a lot of sense, since
// the same input can be simply used by Utxo scheme
unimplemented!();
SealDefinition::WitnessVout {
vout: 0,
blinding: 0,
}
.conceal()
}
};
debug!(
"Reading partially-signed transaction from file {:?}",
self.prototype
);
let filepath = format!("{:?}", &self.prototype);
let file = fs::File::open(self.prototype)
.map_err(|_| Error::InputFileIoError(format!("{:?}", filepath)))?;
let mut psbt = PartiallySignedTransaction::consensus_decode(file)
.map_err(|err| {
Error::InputFileFormatError(
format!("{:?}", filepath),
format!("{}", err),
)
})?;
for (index, output) in &mut psbt.outputs.iter_mut().enumerate() {
if let Some(key) = output.hd_keypaths.keys().next() {
let key = key.clone();
output.insert_proprietary_key(
b"RGB".to_vec(),
PSBT_OUT_PUBKEY,
vec![],
&key.key,
);
debug!("Output #{} commitment key will be {}", index, key);
} else {
warn!(
"No public key information found for output #{}; \
LNPBP1/2 commitment will be impossible.\
In order to allow commitment pls add known keys derivation \
information to PSBT output map",
index
);
}
}
trace!("{:?}", psbt);
let api = TransferApi {
psbt,
contract_id: self.invoice.contract_id,
inputs: self.inputs,
ours: self.allocate,
theirs: vec![Outcoincealed {
coins: self.invoice.amount,
seal_confidential,
}],
};
let reply = runtime.transfer(api)?;
info!("Reply: {}", reply);
match &*reply {
Reply::Failure(failure) => {
eprintln!("Transfer failed: {}", failure);
}
Reply::Transfer(transfer) => {
trace!("{:?}", strict_encode(&transfer.consignment));
transfer.consignment.write_file(self.consignment.clone())?;
let out_file = fs::File::create(&self.transaction)
.expect("can't create output transaction file");
transfer.psbt.consensus_encode(out_file)?;
println!(
"Transfer succeeded, consignment data are written to {:?}, partially signed witness transaction to {:?}",
self.consignment, self.transaction
);
}
_ => (),
}
Ok(())
}
}