urma-cli 0.2.2

Command-line program for URMA identities, wallets, Wire, archives and Git
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
use crate::{
    config::{self, IndexChoice},
    key_cli::VaultAccess,
    names_approval::{self, ApproveArgs, RequestArgs, ReviewArgs},
    names_flow::{self, Publication, names_error, names_record},
    node_cli::{NodeArgs, chain_name},
};
use bitcoin::{Block, BlockHash, Transaction, Txid, XOnlyPublicKey};
use clap::{Args, Subcommand, ValueEnum};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use std::path::{Path, PathBuf};
use urma_core::format::{PublicRecord, Urma};
use urma_names::{
    error::{NamesError, ScanError},
    index::NamesIndex,
    name::Name,
    payload::{Approval, Genesis, Mode, NameOp, OwnerOp, Payload},
    scan::{self, Registration, Source},
};
use urma_runtime::{
    error::{Error, ensure},
    node::{Node, Presence},
    plan::PlanLimits,
    storage,
};

#[derive(Subcommand)]
pub(crate) enum NamesCommand {
    #[command(about = "Scan the chain from a registry genesis into a local names index")]
    Scan(ScanArgs),
    #[command(about = "Resolve a name in the local names index of one network")]
    Resolve {
        #[command(flatten)]
        index: IndexArgs,
        name: String,
    },
    #[command(about = "List pending requests and updates with their approvals")]
    Pending {
        #[command(flatten)]
        index: IndexArgs,
    },
    #[command(about = "Request a name for a published site: encode, plan and publish")]
    Request(RequestArgs),
    #[command(
        about = "Fetch and verify a pending request's site and export every declared file (no broadcast)"
    )]
    Review(ReviewArgs),
    #[command(about = "Review a pending request or update and publish your approval")]
    Approve(ApproveArgs),
    #[command(about = "Encode a names record for publication (no broadcast)")]
    Encode {
        #[command(subcommand)]
        command: EncodeCommand,
    },
    #[command(
        about = "Prepare and quote the publication of an encoded names record (no broadcast)"
    )]
    Plan(PlanArgs),
    #[command(
        about = "Approve and publish a names record; the reveal waits for the commit's block"
    )]
    Publish(PublishArgs),
    #[command(about = "Continue the same names publication after confirmation")]
    Resume(PublishArgs),
}

#[derive(Args)]
pub(crate) struct IndexArgs {
    #[arg(
        long,
        help = "Chain name the index must belong to, for example litecoin-testnet"
    )]
    network: String,
    #[arg(long, help = "Registry genesis TXID; selects its local index")]
    registry: Option<Txid>,
    #[arg(long, help = "Explicit names index file")]
    index: Option<PathBuf>,
}

#[derive(Args)]
pub(crate) struct ScanArgs {
    #[command(flatten)]
    node: NodeArgs,
    #[arg(long, help = "Registry genesis reveal TXID")]
    genesis: Txid,
    #[arg(
        long,
        help = "Height of the block that includes the genesis reveal; read from the node when omitted"
    )]
    genesis_height: Option<u64>,
    #[arg(long, help = "Names index file; defaults to the registry's local index")]
    index: Option<PathBuf>,
    #[arg(long, default_value_t = 1000)]
    max_blocks: u64,
}

#[derive(Clone, Copy, ValueEnum)]
pub(crate) enum RegistryMode {
    Open,
    Administered,
}

#[derive(Subcommand)]
pub(crate) enum EncodeCommand {
    Genesis {
        #[arg(long, value_enum)]
        mode: RegistryMode,
        #[arg(long)]
        expiry_blocks: u32,
        #[arg(long)]
        reveal_max_blocks: u16,
        #[arg(long, default_value_t = 0)]
        threshold: u8,
        #[arg(long = "approver")]
        approvers: Vec<XOnlyPublicKey>,
        #[arg(long)]
        output: PathBuf,
    },
    Claim(OwnerArgs),
    Update(OwnerArgs),
    Renew(OwnerArgs),
    Approve {
        #[arg(long)]
        registry: Txid,
        #[arg(long, help = "Reveal TXID of the request or update being approved")]
        record_txid: Txid,
        #[arg(long, help = "The exact record file whose bytes are approved")]
        record: PathBuf,
        #[arg(long)]
        output: PathBuf,
    },
    Suspend(NameArgs),
    Restore(NameArgs),
}

#[derive(Args)]
pub(crate) struct OwnerArgs {
    #[arg(long)]
    registry: Txid,
    #[arg(long)]
    name: String,
    #[arg(
        long,
        default_value = "0000000000000000000000000000000000000000000000000000000000000000",
        help = "Publication root TXID; all zero reserves the name (open registries only)"
    )]
    target: Txid,
    #[arg(long)]
    output: PathBuf,
}

#[derive(Args)]
pub(crate) struct NameArgs {
    #[arg(long)]
    registry: Txid,
    #[arg(long)]
    name: String,
    #[arg(long)]
    output: PathBuf,
}

#[derive(Args)]
pub(crate) struct PlanArgs {
    #[command(flatten)]
    access: VaultAccess,
    #[command(flatten)]
    node: NodeArgs,
    #[arg(long, help = "Encoded names record file")]
    record: PathBuf,
    #[arg(long, default_value = "names-plan.json")]
    output: PathBuf,
    #[arg(long, default_value_t = 1)]
    fee_rate: u64,
    #[arg(long, default_value_t = 100_000)]
    max_fee: u64,
}

#[derive(Args)]
pub(crate) struct PublishArgs {
    #[command(flatten)]
    node: NodeArgs,
    #[arg(long, default_value = "names-plan.json")]
    plan: PathBuf,
    #[arg(short, long, help = "Approve the displayed exact plan and fee")]
    yes: bool,
    #[arg(long, default_value = "names-progress.json")]
    journal: PathBuf,
    #[arg(long, help = "Names index for the reveal window; defaults to the registry's")]
    index: Option<PathBuf>,
    #[arg(
        long,
        help = "Stay in the foreground until the commit and the reveal are confirmed"
    )]
    watch: bool,
}

struct NodeSource<'a>(&'a Node);

impl Source for NodeSource<'_> {
    type Error = Error;

    fn genesis(&self) -> Result<BlockHash, Error> {
        Ok(self.0.chain().genesis()?.0)
    }
    fn tip_height(&self) -> Result<u64, Error> {
        self.0.tip_height()
    }
    fn block_hash(&self, height: u64) -> Result<BlockHash, Error> {
        self.0.block_hash(height)
    }
    fn block(&self, height: u64) -> Result<Block, Error> {
        self.0.block(height)
    }
    fn transaction(&self, txid: Txid) -> Result<Transaction, Error> {
        self.0.transaction(txid)
    }
}

pub(crate) fn run(command: NamesCommand) -> Result<Value, Error> {
    match command {
        NamesCommand::Scan(args) => scan(args),
        NamesCommand::Resolve { index, name } => resolve(index, &name),
        NamesCommand::Pending { index } => pending(index),
        NamesCommand::Request(args) => names_approval::request(args),
        NamesCommand::Review(args) => names_approval::review(args),
        NamesCommand::Approve(args) => names_approval::approve(args),
        NamesCommand::Encode { command } => encode(command),
        NamesCommand::Plan(args) => plan(args),
        NamesCommand::Publish(args) | NamesCommand::Resume(args) => publish(args),
    }
}

fn names_result<T>(result: Result<T, NamesError>) -> Result<T, Error> {
    result.map_err(names_error)
}

fn scan_result<T>(result: Result<T, ScanError<Error>>) -> Result<T, Error> {
    match result {
        Ok(value) => Ok(value),
        Err(ScanError::Source(cause)) => Err(cause),
        Err(ScanError::Names(cause)) => Err(names_error(cause)),
    }
}

pub(crate) fn confirmed_height(node: &Node, txid: Txid) -> Result<u64, Error> {
    match node.presence(txid)? {
        Presence::Confirmed { height, .. } => Ok(height),
        Presence::Mempool | Presence::Missing => Err(Error::Missing(format!(
            "{txid} has no confirmed inclusion on {}",
            node.chain().label()
        ))),
    }
}

pub(crate) fn sync_index(
    node: &Node,
    genesis: Txid,
    path: &Path,
    max_blocks: u64,
) -> Result<scan::ScanReport, Error> {
    node.require_txindex()?;
    let network = chain_name(node.chain())?;
    let genesis_height = confirmed_height(node, genesis)?;
    for parent in path.parent().iter() {
        if !parent.as_os_str().is_empty() {
            std::fs::create_dir_all(parent)?;
        }
    }
    scan_result(scan::sync(
        &NodeSource(node),
        path,
        Registration {
            network: &network,
            genesis,
            genesis_height,
        },
        max_blocks,
    ))
}

fn scan(args: ScanArgs) -> Result<Value, Error> {
    let node = args.node.connect()?;
    let network = chain_name(node.chain())?;
    let observed = confirmed_height(&node, args.genesis)?;
    for requested in args.genesis_height.iter() {
        ensure!(
            *requested == observed,
            "genesis {} is confirmed at height {observed}, not {requested}",
            args.genesis
        );
    }
    let path = config::names_index(
        IndexChoice {
            path: args.index,
            registry: Some(args.genesis),
        },
        &network,
    )?;
    let report = sync_index(&node, args.genesis, &path, args.max_blocks)?;
    let mut value = serde_json::to_value(report)?;
    value["index"] = json!(path);
    Ok(value)
}

pub(crate) fn load_index(network: &str, path: &Path) -> Result<NamesIndex, Error> {
    let index = names_result(NamesIndex::load(path))?;
    ensure!(
        index.network == network,
        "names index {} belongs to {}, not {network}",
        path.display(),
        index.network
    );
    Ok(index)
}

fn open_index(args: IndexArgs) -> Result<NamesIndex, Error> {
    let path = config::names_index(
        IndexChoice {
            path: args.index,
            registry: args.registry,
        },
        &args.network,
    )?;
    load_index(&args.network, &path)
}

pub(crate) fn pending_records(index: &NamesIndex, name: &str) -> Result<Vec<Value>, Error> {
    let mut rows = Vec::new();
    for (txid, record) in index.registry.pending() {
        if !name.is_empty() && record.name.as_str() != name {
            continue;
        }
        rows.push(json!({"txid": txid.to_string(), "record": serde_json::to_value(record)?}));
    }
    Ok(rows)
}

fn resolve(args: IndexArgs, name: &str) -> Result<Value, Error> {
    resolution(&open_index(args)?, &Name::normalize(name)?)
}

pub(crate) fn resolution(index: &NamesIndex, name: &Name) -> Result<Value, Error> {
    Ok(json!({
        "network": index.network,
        "registry": index.registry.genesis().to_string(),
        "genesis_height": index.registry.genesis_height(),
        "height": index.registry.height(),
        "block_hash": index.tip_hash(),
        "name": name.as_str(),
        "resolution": serde_json::to_value(index.registry.resolve(name))?,
        "pending": pending_records(index, name.as_str())?,
        "locally_cached": true,
    }))
}

fn pending(args: IndexArgs) -> Result<Value, Error> {
    let index = open_index(args)?;
    Ok(json!({
        "network": index.network,
        "registry": index.registry.genesis().to_string(),
        "height": index.registry.height(),
        "pending": pending_records(&index, "")?,
    }))
}

fn owner_op(args: &OwnerArgs) -> Result<OwnerOp, Error> {
    Ok(OwnerOp {
        registry: args.registry,
        salt: rand::random(),
        name: Name::normalize(&args.name)?,
        target: args.target,
    })
}

fn name_op(args: &NameArgs) -> Result<NameOp, Error> {
    Ok(NameOp {
        registry: args.registry,
        name: Name::normalize(&args.name)?,
    })
}

fn genesis_payload(
    mode: RegistryMode,
    expiry_blocks: u32,
    reveal_max_blocks: u16,
    threshold: u8,
    mut approvers: Vec<XOnlyPublicKey>,
) -> Payload {
    approvers.sort_by_key(XOnlyPublicKey::serialize);
    let mode = match mode {
        RegistryMode::Open => Mode::Open,
        RegistryMode::Administered => Mode::Administered,
    };
    Payload::Genesis(Genesis {
        mode,
        expiry_blocks,
        reveal_max_blocks,
        threshold,
        approvers,
    })
}

fn encode(command: EncodeCommand) -> Result<Value, Error> {
    let (payload, output) = match command {
        EncodeCommand::Genesis {
            mode,
            expiry_blocks,
            reveal_max_blocks,
            threshold,
            approvers,
            output,
        } => (
            genesis_payload(mode, expiry_blocks, reveal_max_blocks, threshold, approvers),
            output,
        ),
        EncodeCommand::Claim(args) => (Payload::Claim(owner_op(&args)?), args.output),
        EncodeCommand::Update(args) => (Payload::Update(owner_op(&args)?), args.output),
        EncodeCommand::Renew(args) => (Payload::Renew(owner_op(&args)?), args.output),
        EncodeCommand::Approve {
            registry,
            record_txid,
            record,
            output,
        } => {
            let bytes = storage::read_bounded(&record, Urma::MAX_PUBLIC_BYTES)?;
            let referenced = names_record(&bytes)?;
            ensure!(
                matches!(referenced, Payload::Claim(..) | Payload::Update(..)),
                "approvals reference a request or an update record"
            );
            let approval = Approval {
                registry,
                record_txid,
                record_sha256: Sha256::digest(&bytes).into(),
            };
            (Payload::Approve(approval), output)
        }
        EncodeCommand::Suspend(args) => (Payload::Suspend(name_op(&args)?), args.output),
        EncodeCommand::Restore(args) => (Payload::Restore(name_op(&args)?), args.output),
    };
    write_record(&payload, &output)
}

pub(crate) fn write_record(payload: &Payload, output: &Path) -> Result<Value, Error> {
    let bytes = payload.to_record()?.encode()?;
    storage::write_new(output, &bytes)?;
    Ok(json!({
        "status": "encoded",
        "kind": 12,
        "profile": "URMANAM1",
        "op": payload.op(),
        "bytes": bytes.len(),
        "record_sha256": hex::encode(Sha256::digest(&bytes)),
        "output": output,
    }))
}

pub(crate) fn plan_record(
    node: &Node,
    access: &VaultAccess,
    record: &Path,
    output: &Path,
    limits: PlanLimits,
) -> Result<Value, Error> {
    let bytes = storage::read_bounded(record, Urma::MAX_PUBLIC_BYTES)?;
    let payload = names_record(&bytes)?;
    let vault = access.open()?;
    let signer = vault.keyring().active()?;
    let plan =
        urma_runtime::plan::prepare_atomic(node, &signer, &PublicRecord::decode(&bytes)?, limits)?;
    plan.save_new(output)?;
    Ok(json!({
        "status": "prepared",
        "plan": output,
        "plan_id": plan.id()?,
        "author": plan.author,
        "op": payload.op(),
        "record_sha256": hex::encode(Sha256::digest(&bytes)),
        "total_fee": plan.total_fee,
        "maximum_fee": plan.maximum_fee,
        "broadcast": false,
    }))
}

fn plan(args: PlanArgs) -> Result<Value, Error> {
    let node = args.node.connect()?;
    plan_record(
        &node,
        &args.access,
        &args.record,
        &args.output,
        PlanLimits {
            fee_rate: args.fee_rate,
            max_fee: args.max_fee,
            max_records: 1,
        },
    )
}

fn publish(args: PublishArgs) -> Result<Value, Error> {
    let node = args.node.connect()?;
    names_flow::follow(
        &node,
        Publication {
            plan: &args.plan,
            journal: &args.journal,
            index: args.index,
            label: "Publish names record",
            yes: args.yes,
            watch: args.watch,
        },
    )
}