rgb-std 0.9.0

RGB Standard Library: high-level API for private & scalable client-validated smart contracts on Bitcoin & Lightning
Documentation
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
// RGB Standard Library: high-level API to RGB smart contracts.
// Written in 2019-2022 by
//     Dr. Maxim Orlovsky <orlovsky@lnp-bp.org>
//
// 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>.

#[macro_use]
extern crate clap;
#[macro_use]
extern crate amplify;
extern crate serde_crate as serde;

use std::fmt::{Debug, Display};
use std::fs;
use std::io::{self, Read};
use std::path::PathBuf;
use std::str::FromStr;

use amplify::hex::{FromHex, ToHex};
use bitcoin::psbt::serialize::{Deserialize, Serialize};
use bitcoin::OutPoint;
use bitcoin_scripts::taproot::{DfsOrder, DfsPath};
use bp::seals::txout::CloseMethod;
use clap::Parser;
use commit_verify::ConsensusCommit;
use electrum_client::Client as ElectrumClient;
use rgb::psbt::RgbExt;
use rgb::{Disclosure, Extension, Schema, StateTransfer, Transition};
use rgb_core::{seal, Node, Validator};
use strict_encoding::{StrictDecode, StrictEncode};
use wallet::psbt::Psbt;

#[derive(Parser, Clone, Debug)]
#[clap(
    name = "rgb",
    bin_name = "rgb",
    author,
    version,
    about = "Command-line tool for working with RGB smart contracts"
)]
pub struct Opts {
    /// Command to execute
    #[clap(subcommand)]
    pub command: Command,
}

#[derive(Subcommand, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum Command {
    /// Generate blinded UTXO value
    Blind {
        /// Method for seal closing ('tapret1st' or 'opret1st')
        #[clap(short, long, default_value = "tapret1st")]
        method: CloseMethod,

        /// Unspent transaction output to define as a blinded seal
        utxo: OutPoint,
    },

    /// Commands for working with consignments
    Consignment {
        #[clap(subcommand)]
        subcommand: ConsignmentCommand,
    },

    /// Commands for working with disclosures
    Disclosure {
        #[clap(subcommand)]
        subcommand: DisclosureCommand,
    },

    /// Commands for working with schemata
    Schema {
        #[clap(subcommand)]
        subcommand: SchemaCommand,
    },

    /// Commands for working with state extensions
    Extension {
        #[clap(subcommand)]
        subcommand: ExtensionCommand,
    },

    /// Commands for working with state transitions
    Transition {
        #[clap(subcommand)]
        subcommand: TransitionCommand,
    },

    /// Commands working with RGB-specific PSBT information
    Psbt {
        #[clap(subcommand)]
        subcommand: PsbtCommand,
    },
}

#[derive(Subcommand, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum ConsignmentCommand {
    /// Inspects the consignment structure by printing it out.
    Inspect {
        /// Formatting for the output
        #[clap(short, long, default_value = "yaml")]
        format: Format,

        /// File with consignment data
        consignment: PathBuf,
    },

    Validate {
        /// File with consignment data
        consignment: String,

        /// Address for Electrum server
        #[clap(default_value = "pandora.network:60001")]
        electrum: String,
    },
}

#[derive(Subcommand, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum DisclosureCommand {
    Convert {
        /// Consignment data; if none are given reads from STDIN
        disclosure: Option<String>,

        /// Formatting of the input data
        #[clap(short, long, default_value = "bech32")]
        input: Format,

        /// Formatting for the output
        #[clap(short, long, default_value = "yaml")]
        output: Format,
    },
}

#[derive(Subcommand, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum SchemaCommand {
    Convert {
        /// Schema data; if none are given reads from STDIN
        schema: Option<String>,

        /// Formatting of the input data
        #[clap(short, long, default_value = "bech32")]
        input: Format,

        /// Formatting for the output
        #[clap(short, long, default_value = "yaml")]
        output: Format,
    },
}

#[derive(Subcommand, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum ExtensionCommand {
    Convert {
        /// State extension data; if none are given reads from STDIN
        extension: Option<String>,

        /// Formatting of the input data
        #[clap(short, long, default_value = "bech32")]
        input: Format,

        /// Formatting for the output
        #[clap(short, long, default_value = "yaml")]
        output: Format,
    },
}

#[derive(Subcommand, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum TransitionCommand {
    Convert {
        /// State transition data; if none are given reads from STDIN
        transition: Option<String>,

        /// Formatting of the input data
        #[clap(short, long, default_value = "bech32")]
        input: Format,

        /// Formatting for the output
        #[clap(short, long, default_value = "yaml")]
        output: Format,
    },
}

#[derive(Subcommand, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum PsbtCommand {
    /// Finalize RGB bundle information in PSBT file.
    Bundle {
        /// Input file containing PSBT of the transfer witness transaction.
        psbt_in: PathBuf,

        /// Output file to save the PSBT updated with state transition(s)
        /// information. If not given, the source PSBT file is overwritten.
        psbt_out: Option<PathBuf>,

        /// Method for seal closing ('tapret1st' or 'opret1st')
        #[clap(short, long, default_value = "tapret1st")]
        method: CloseMethod,
    },

    /// Analyze PSBT file and print out all RGB-related information from it
    Analyze {
        /// File to analyze
        psbt: PathBuf,
    },
}

#[derive(ArgEnum, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, Display)]
pub enum Format {
    /// Format according to the rust debug rules
    #[display("debug")]
    Debug,

    /// Format according to default display formatting
    #[display("bech32")]
    Bech32,

    /// Format as YAML
    #[display("yaml")]
    Yaml,

    /// Format as JSON
    #[display("json")]
    Json,

    /// Format according to the strict encoding rules
    #[display("hex")]
    Hexadecimal,

    /// Format as a rust array (using hexadecimal byte values)
    #[display("rust")]
    Rust,

    /// Produce binary (raw) output
    #[display("raw")]
    Binary,

    /// Produce client-validated commitment
    #[display("commitment")]
    Commitment,
}

impl FromStr for Format {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s.trim().to_lowercase().as_str() {
            "debug" => Format::Debug,
            "bech32" => Format::Bech32,
            "yaml" => Format::Yaml,
            "json" => Format::Json,
            "hex" => Format::Hexadecimal,
            "raw" | "bin" | "binary" => Format::Binary,
            "rust" => Format::Rust,
            "commitment" => Format::Commitment,
            other => Err(format!("Unknown format: {}", other))?,
        })
    }
}

fn input_read<T>(data: Option<String>, format: Format) -> Result<T, Error>
where T: StrictDecode + for<'de> serde::Deserialize<'de> {
    // TODO: Refactor with microservices cli
    let data = data
        .map(|d| d.as_bytes().to_vec())
        .ok_or_else(String::new)
        .or_else(|_| -> Result<Vec<u8>, Error> {
            let mut buf = Vec::new();
            io::stdin().read_to_end(&mut buf)?;
            Ok(buf)
        })?;
    Ok(match format {
        Format::Yaml => serde_yaml::from_str(&String::from_utf8_lossy(&data))?,
        Format::Json => serde_json::from_str(&String::from_utf8_lossy(&data))?,
        Format::Hexadecimal => {
            T::strict_deserialize(Vec::<u8>::from_hex(&String::from_utf8_lossy(&data))?)?
        }
        Format::Binary => T::strict_deserialize(&data)?,
        _ => panic!("Can't read data from {} format", format),
    })
}

fn output_print<T>(data: T, format: Format) -> Result<(), Error>
where
    T: Debug + serde::Serialize + StrictEncode + ConsensusCommit,
    <T as ConsensusCommit>::Commitment: Display,
{
    match format {
        Format::Debug => println!("{:#?}", data),
        Format::Yaml => println!("{}", serde_yaml::to_string(&data)?),
        Format::Json => println!("{}", serde_json::to_string(&data)?),
        Format::Hexadecimal => {
            println!("{}", data.strict_serialize()?.to_hex())
        }
        Format::Rust => println!("{:#04X?}", data.strict_serialize()?),
        Format::Binary => {
            data.strict_encode(io::stdout())?;
        }
        Format::Commitment => {
            println!("{}", data.consensus_commit())
        }
        format => panic!("Can't read data in {} format", format),
    }
    Ok(())
}

#[derive(Debug, Display)]
#[display(inner)]
pub struct Error(Box<dyn std::error::Error>);

impl<E> From<E> for Error
where E: std::error::Error + 'static
{
    fn from(e: E) -> Self { Error(Box::new(e)) }
}

fn main() -> Result<(), Error> {
    let opts = Opts::parse();

    match opts.command {
        Command::Blind { utxo, method } => {
            let seal = seal::Revealed::new(method, utxo);
            println!("{}", seal.to_concealed_seal());
            println!("Blinding factor: {}", seal.blinding);
        }

        Command::Consignment { subcommand } => match subcommand {
            ConsignmentCommand::Inspect {
                format,
                consignment,
            } => {
                let transfer = StateTransfer::strict_file_load(consignment)?;
                output_print(transfer, format)?;
            }
            ConsignmentCommand::Validate {
                consignment,
                electrum,
            } => {
                let transfer = StateTransfer::strict_file_load(consignment)?;

                let electrum = ElectrumClient::new(&electrum)?;
                let status = Validator::validate(&transfer, &electrum);

                println!("{}", serde_yaml::to_string(&status)?);
            }
        },
        Command::Disclosure { subcommand } => match subcommand {
            DisclosureCommand::Convert {
                disclosure,
                input,
                output,
            } => {
                let disclosure: Disclosure = input_read(disclosure, input)?;
                output_print(disclosure, output)?;
            }
        },
        Command::Schema { subcommand } => match subcommand {
            SchemaCommand::Convert {
                schema,
                input,
                output,
            } => {
                let schema: Schema = input_read(schema, input)?;
                output_print(schema, output)?;
            }
        },
        Command::Extension { subcommand } => match subcommand {
            ExtensionCommand::Convert {
                extension,
                input,
                output,
            } => {
                let extension: Extension = input_read(extension, input)?;
                output_print(extension, output)?;
            }
        },
        Command::Transition { subcommand } => match subcommand {
            TransitionCommand::Convert {
                transition,
                input,
                output,
            } => {
                let transition: Transition = input_read(transition, input)?;
                output_print(transition, output)?;
            }
        },
        Command::Psbt { subcommand } => match subcommand {
            PsbtCommand::Bundle {
                psbt_in,
                psbt_out,
                method,
            } => {
                let psbt_bytes = fs::read(&psbt_in)?;
                let mut psbt = Psbt::deserialize(&psbt_bytes)?;

                let mut count: usize = 0;
                match method {
                    CloseMethod::TapretFirst => {
                        if let Some(output) =
                            psbt.outputs.iter_mut().find(|o| o.script.is_v1_p2tr())
                        {
                            if output.tapret_dfs_path().is_none() {
                                output.set_tapret_dfs_path(&DfsPath::with([&DfsOrder::Last]))?;
                            }
                        }
                        count = psbt.rgb_bundle_to_lnpbp4()?;
                    }
                    CloseMethod::OpretFirst => {
                        count = psbt.rgb_bundle_to_lnpbp4()?;
                        if let Some(output) =
                            psbt.outputs.iter_mut().find(|o| o.script.is_op_return())
                        {
                            if !output.is_opret_host() {
                                output.set_opret_host()?;
                            }
                        }
                    }
                    _ => {}
                };

                println!("Total {} bundles converted", count);

                let psbt_bytes = psbt.serialize();
                fs::write(psbt_out.unwrap_or(psbt_in), psbt_bytes)?;
            }
            PsbtCommand::Analyze { psbt } => {
                let psbt_bytes = fs::read(psbt)?;
                let psbt = Psbt::deserialize(&psbt_bytes)?;

                println!("contracts:");
                for contract_id in psbt.rgb_contract_ids() {
                    println!("- contract_id: {}", contract_id);
                    if let Some(contract) = psbt.rgb_contract(contract_id)? {
                        println!("  - source: {}", contract);
                    } else {
                        println!("  - warning: contract source is absent");
                    }
                    println!("  - transitions:");
                    for node_id in psbt.rgb_node_ids(contract_id) {
                        if let Some(transition) = psbt.rgb_transition(node_id)? {
                            println!("    - {}", transition.strict_serialize()?.to_hex());
                        } else {
                            println!("    - warning: transition is absent");
                        }
                    }
                    println!("  - used in:");
                    for (node_id, vin) in psbt.rgb_contract_consumers(contract_id)? {
                        println!("    - input: {}", vin);
                        println!("      node_id: {}", node_id);
                    }
                }

                println!("bundles:");
                for (contract_id, bundle) in psbt.rgb_bundles()? {
                    println!("- contract_id: {}", contract_id);
                    println!("  bundle_id: {}", bundle.bundle_id());
                    println!("    - revealed: # nodes");
                    for transition in bundle.known_transitions() {
                        println!(
                            "      - {}: {}",
                            transition.node_id(),
                            transition.strict_serialize()?.to_hex()
                        );
                    }
                    println!("    - concealed: # nodes and inputs");
                    for (node_id, vins) in bundle.concealed_iter() {
                        println!("      - {}: {:?}", node_id, vins);
                    }
                }

                println!("proprietary: # all proprietary keys");
                println!("- global:");
                for (key, value) in psbt.proprietary {
                    let prefix = String::from_utf8(key.prefix.clone())
                        .unwrap_or_else(|_| key.prefix.to_hex());
                    println!(
                        "  - {}/{:#04x}/{}: {}",
                        prefix,
                        key.subtype,
                        key.key.to_hex(),
                        value.to_hex()
                    );
                }
                println!("- inputs:");
                for (no, input) in psbt.inputs.iter().enumerate() {
                    println!("  - {}:", no);
                    for (key, value) in &input.proprietary {
                        let prefix = String::from_utf8(key.prefix.clone())
                            .unwrap_or_else(|_| key.prefix.to_hex());
                        println!(
                            "    - {}/{:#04x}/{}: {}",
                            prefix,
                            key.subtype,
                            key.key.to_hex(),
                            value.to_hex()
                        );
                    }
                }
                println!("- outputs:");
                for (no, output) in psbt.outputs.iter().enumerate() {
                    println!("  - {}:", no);
                    for (key, value) in &output.proprietary {
                        let prefix = String::from_utf8(key.prefix.clone())
                            .unwrap_or_else(|_| key.prefix.to_hex());
                        println!(
                            "    - {}/{:#04x}/{}: {}",
                            prefix,
                            key.subtype,
                            key.key.to_hex(),
                            value.to_hex()
                        );
                    }
                }
            }
        },
    }

    Ok(())
}