kaleido-cli 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,874 @@
1
+ """Node lifecycle commands — wraps docker-compose."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from enum import StrEnum
7
+ from pathlib import Path
8
+ from typing import Annotated
9
+
10
+ import typer
11
+
12
+ from kaleido_cli.commands.node_swap import node_swap_app
13
+ from kaleido_cli.config import (
14
+ DEFAULT_BITCOIND_RPC_HOST,
15
+ DEFAULT_BITCOIND_RPC_PASSWORD,
16
+ DEFAULT_BITCOIND_RPC_PORT,
17
+ DEFAULT_BITCOIND_RPC_USERNAME,
18
+ DEFAULT_INDEXER_URL,
19
+ DEFAULT_NETWORK,
20
+ DEFAULT_PROXY_ENDPOINT,
21
+ DEFAULT_REGTEST_BITCOIND_RPC_HOST,
22
+ DEFAULT_REGTEST_BITCOIND_RPC_PASSWORD,
23
+ DEFAULT_REGTEST_BITCOIND_RPC_PORT,
24
+ DEFAULT_REGTEST_BITCOIND_RPC_USERNAME,
25
+ DEFAULT_REGTEST_INDEXER_URL,
26
+ DEFAULT_REGTEST_PROXY_ENDPOINT,
27
+ )
28
+ from kaleido_cli.context import get_client, state
29
+ from kaleido_cli.docker_manager import (
30
+ COMPOSE_FILE,
31
+ DEFAULT_SPAWN_DIR,
32
+ RLN_IMAGE,
33
+ DockerManager,
34
+ SpawnConfig,
35
+ SpawnManager,
36
+ compose_images,
37
+ find_free_base_ports,
38
+ list_spawn_names,
39
+ upgrade_compose,
40
+ )
41
+ from kaleido_cli.output import (
42
+ is_interactive,
43
+ output_model,
44
+ print_error,
45
+ print_info,
46
+ print_success,
47
+ print_warning,
48
+ )
49
+ from kaleido_cli.utils.errors import raise_cli_error
50
+
51
+ node_app = typer.Typer(
52
+ no_args_is_help=True,
53
+ rich_markup_mode="rich",
54
+ help=(
55
+ "Manage named RGB Lightning Node environments via Docker.\n\n"
56
+ "[bold]Creating an environment:[/bold]\n"
57
+ " [cyan]kaleido setup[/cyan] — create one mutinynet node with defaults\n"
58
+ " [cyan]kaleido setup <network>[/cyan] — create one node on a specific network\n"
59
+ " [cyan]kaleido node create[/cyan] — wizard: configure ports, network\n\n"
60
+ "[bold]Managing environments:[/bold]\n"
61
+ " [cyan]kaleido node list[/cyan] — list all environments with their node URLs\n"
62
+ " [cyan]kaleido node up <name>[/cyan] — start containers\n"
63
+ " [cyan]kaleido node stop <name>[/cyan] — stop containers\n"
64
+ " [cyan]kaleido node down <name>[/cyan] — stop and remove containers\n"
65
+ " [cyan]kaleido node logs <name>[/cyan] — stream logs\n"
66
+ " [cyan]kaleido node ps <name>[/cyan] — show container status\n"
67
+ " [cyan]kaleido node clean <name>[/cyan] — remove volumes (irreversible)\n\n"
68
+ "[bold]Switching between nodes:[/bold]\n"
69
+ " [cyan]kaleido node use <name>[/cyan] — point node-url at node 1 of an environment\n"
70
+ " [cyan]kaleido node use <name> --node 2[/cyan] — point at a specific node index\n\n"
71
+ "[bold]After starting:[/bold]\n"
72
+ " [cyan]kaleido node init[/cyan] — initialize node wallet (once)\n"
73
+ " [cyan]kaleido node unlock[/cyan] — unlock wallet after restart\n"
74
+ " [cyan]kaleido node shutdown[/cyan] — gracefully shut down the node process\n"
75
+ " [cyan]kaleido node info[/cyan] — show node details\n"
76
+ " [cyan]kaleido node network[/cyan] — show network height/details\n"
77
+ " [cyan]kaleido node swap pubkey[/cyan] — show the local taker pubkey\n"
78
+ " [cyan]kaleido node swap init[/cyan] — run low-level local node swap flows\n"
79
+ ),
80
+ )
81
+
82
+ node_app.add_typer(node_swap_app, name="swap")
83
+
84
+
85
+ class ChainSyncMode(StrEnum):
86
+ """How LDK follows the chain — RLN 0.9.0's `ldk_chain_sync` modes."""
87
+
88
+ BLOCK = "block"
89
+ TRANSACTION = "transaction"
90
+
91
+
92
+ # ---------------------------------------------------------------------------
93
+ # Helpers
94
+ # ---------------------------------------------------------------------------
95
+
96
+
97
+ def _base_spawn_dir() -> Path:
98
+ """Base directory where named environments live."""
99
+ d = state.config.spawn_dir
100
+ return Path(d).expanduser().resolve() if d else DEFAULT_SPAWN_DIR
101
+
102
+
103
+ def _dm(name: str) -> DockerManager:
104
+ """Return a DockerManager for the named environment."""
105
+ return DockerManager(str(_base_spawn_dir() / name))
106
+
107
+
108
+ def _resolve_name(name: str | None) -> str:
109
+ """If *name* is None/empty, auto-resolve from available environments."""
110
+ if name:
111
+ return name
112
+ names = list_spawn_names(_base_spawn_dir())
113
+ if not names:
114
+ print_error("No environments found. Run 'kaleido node create' first.")
115
+ raise typer.Exit(1)
116
+ if len(names) == 1:
117
+ print_info(f"Using environment: [bold]{names[0]}[/bold]")
118
+ return names[0]
119
+ print_error("Multiple environments exist — specify one:")
120
+ for n in names:
121
+ print_info(f" kaleido node <cmd> {n}")
122
+ print_info("See 'kaleido node list' for details.")
123
+ raise typer.Exit(1)
124
+
125
+
126
+ def _prompt_unlock_service_profile() -> str:
127
+ while True:
128
+ raw = typer.prompt(
129
+ "Bitcoin services profile: [S]ignet defaults, [R]egtest defaults, [C]ustom",
130
+ default="S",
131
+ )
132
+ choice = raw.strip().lower()
133
+ if choice in {"s", "signet", "mutinynet", "signetcustom"}:
134
+ return "signet"
135
+ if choice in {"r", "regtest"}:
136
+ return "regtest"
137
+ if choice in {"c", "custom", "o", "other"}:
138
+ return "custom"
139
+ print_error("Choose S for signet, R for regtest, or C for custom.")
140
+
141
+
142
+ def _prompt_chain_sync_mode(default: ChainSyncMode) -> ChainSyncMode:
143
+ default_key = "B" if default is ChainSyncMode.BLOCK else "T"
144
+ while True:
145
+ raw = typer.prompt(
146
+ "Chain sync: [B]lock via bitcoind, [T]ransaction via the indexer only",
147
+ default=default_key,
148
+ )
149
+ choice = raw.strip().lower()
150
+ if choice in {"b", "block", "blocksync"}:
151
+ return ChainSyncMode.BLOCK
152
+ if choice in {"t", "transaction", "transactionsync"}:
153
+ return ChainSyncMode.TRANSACTION
154
+ print_error("Choose B for block sync or T for transaction sync.")
155
+
156
+
157
+ # ---------------------------------------------------------------------------
158
+ # Environment management
159
+ # ---------------------------------------------------------------------------
160
+
161
+
162
+ @node_app.command(
163
+ "create",
164
+ epilog=(
165
+ "[bold]Examples[/bold]\n\n"
166
+ " Wizard with a new name:\n"
167
+ " [cyan]kaleido node create[/cyan]\n"
168
+ " [cyan]kaleido node create myenv[/cyan]\n\n"
169
+ " Then start with:\n"
170
+ " [cyan]kaleido node up myenv[/cyan]"
171
+ ),
172
+ )
173
+ def node_create(
174
+ name: Annotated[
175
+ str | None,
176
+ typer.Argument(
177
+ help="Environment name (directory under ~/.kaleido by default). Prompted if omitted."
178
+ ),
179
+ ] = None,
180
+ ) -> None:
181
+ """[bold]Wizard:[/bold] configure and generate a named compose environment."""
182
+ from ..config import save_config
183
+
184
+ print_info("\n Kaleido Node Create Wizard")
185
+ print_info(" " + "─" * 38)
186
+
187
+ # ── Base environment directory ───────────────────────────────────────────
188
+ default_base = str(state.config.spawn_dir or DEFAULT_SPAWN_DIR)
189
+ spawn_base_input = typer.prompt(
190
+ " Base directory for environments",
191
+ default=default_base,
192
+ )
193
+ base = Path(spawn_base_input).expanduser().resolve()
194
+ if str(base) != str(Path(default_base).expanduser().resolve()):
195
+ state.config.spawn_dir = str(base)
196
+ save_config(state.config)
197
+ print_info(f" Saved environment base directory → {base}")
198
+
199
+ # ── Environment name ─────────────────────────────────────────────────────
200
+ resolved_name: str
201
+ if name:
202
+ resolved_name = name
203
+ else:
204
+ existing = list_spawn_names(base)
205
+ if existing:
206
+ print_info(
207
+ " Existing environments: " + ", ".join(f"[bold]{n}[/bold]" for n in existing)
208
+ )
209
+ resolved_name = typer.prompt(" Environment name", default="default")
210
+
211
+ env_dir = base / resolved_name
212
+ if (env_dir / "docker-compose.yml").exists():
213
+ overwrite = typer.confirm(
214
+ f" Environment '{resolved_name}' already exists at {env_dir}. Overwrite?",
215
+ default=False,
216
+ )
217
+ if not overwrite:
218
+ print_info(" Aborted.")
219
+ raise typer.Exit(0)
220
+
221
+ # ── Node count ───────────────────────────────────────────────────────────
222
+ count = typer.prompt(" How many RGB Lightning Nodes?", default=1, type=int)
223
+
224
+ # ── Network ──────────────────────────────────────────────────────────────
225
+ network = typer.prompt(" Bitcoin network", default=state.config.network or DEFAULT_NETWORK)
226
+
227
+ # ── Node ports ───────────────────────────────────────────────────────────
228
+ print_info(" ── Node ports ────────────────────────────────────────")
229
+ free_daemon, free_peer = find_free_base_ports(count, base, exclude_env=resolved_name)
230
+ daemon_base = typer.prompt(
231
+ f" Base daemon API port ({free_daemon}–{free_daemon + count - 1})",
232
+ default=free_daemon,
233
+ type=int,
234
+ )
235
+ peer_base = typer.prompt(
236
+ f" Base LDK peer port ({free_peer}–{free_peer + count - 1})",
237
+ default=free_peer,
238
+ type=int,
239
+ )
240
+
241
+ # ── Summary ───────────────────────────────────────────────────────────────
242
+ print_info("")
243
+ print_info(" ── Summary ───────────────────────────────────────────")
244
+ print_info(f" Name : [bold]{resolved_name}[/bold]")
245
+ print_info(f" Directory : {env_dir}")
246
+ print_info(f" Nodes : {count}")
247
+ print_info(f" Network : {network}")
248
+ print_info(f" Daemon API : localhost:{daemon_base}–{daemon_base + count - 1}")
249
+ print_info(f" LDK peers : localhost:{peer_base}–{peer_base + count - 1}")
250
+ print_info("")
251
+
252
+ start_now = typer.confirm(" Start containers now?", default=True)
253
+
254
+ # ── Generate + optionally start ───────────────────────────────────────────
255
+ cfg = SpawnConfig(
256
+ name=resolved_name,
257
+ count=count,
258
+ network=network,
259
+ disable_authentication=True,
260
+ base_daemon_port=daemon_base,
261
+ base_peer_port=peer_base,
262
+ spawn_base_dir=str(base),
263
+ )
264
+
265
+ manager = SpawnManager(cfg)
266
+ rc = manager.spawn(start=start_now)
267
+
268
+ if rc == 0:
269
+ if not start_now:
270
+ print_info(f"\n Compose file written → {env_dir}")
271
+ print_info(f" Start with: [cyan]kaleido node up {resolved_name}[/cyan]")
272
+ else:
273
+ print_success(f" Environment '{resolved_name}' started ({count} node(s)).")
274
+ print_info("")
275
+ for i, url in enumerate(manager.node_urls(), start=1):
276
+ print_info(f" Node {i} API : {url}")
277
+ print_info("")
278
+ print_info(" Next steps:")
279
+ print_info(f" 1. [cyan]kaleido node use {resolved_name}[/cyan]")
280
+ print_info(" 2. [cyan]kaleido node init[/cyan]")
281
+ print_info(" 3. [cyan]kaleido node unlock[/cyan]")
282
+ raise typer.Exit(rc)
283
+
284
+
285
+ @node_app.command("list")
286
+ def node_list() -> None:
287
+ """List all named environments and their node URLs."""
288
+ base = _base_spawn_dir()
289
+ names = list_spawn_names(base)
290
+ if not names:
291
+ print_warning(f"No environments found in {base}")
292
+ print_info("Run 'kaleido node create' to create one.")
293
+ return
294
+ print_info(f"Environments in [bold]{base}[/bold]:\n")
295
+ for n in names:
296
+ env_dir = base / n
297
+ urls = _dm(n).node_urls()
298
+ print_info(f" [bold]{n}[/bold] → {env_dir}")
299
+ if urls:
300
+ for i, url in enumerate(urls, start=1):
301
+ marker = "[green]●[/green]" if url == state.config.node_url else "[dim]○[/dim]"
302
+ print_info(f" {marker} node {i}: {url}")
303
+ else:
304
+ print_info(" [dim](no nodes detected in compose)[/dim]")
305
+
306
+
307
+ @node_app.command(
308
+ "use",
309
+ epilog=(
310
+ "[bold]Examples[/bold]\n\n"
311
+ " Use node 1 of the default environment:\n"
312
+ " [cyan]kaleido node use default[/cyan]\n\n"
313
+ " Use node 2 of 'myenv' (multi-node setup):\n"
314
+ " [cyan]kaleido node use myenv --node 2[/cyan]\n\n"
315
+ " Then interact with it:\n"
316
+ " [cyan]kaleido node unlock[/cyan]\n"
317
+ " [cyan]kaleido wallet balance[/cyan]"
318
+ ),
319
+ )
320
+ def node_use(
321
+ name: Annotated[
322
+ str | None,
323
+ typer.Argument(help="Environment name. Auto-detected if only one exists."),
324
+ ] = None,
325
+ node: Annotated[
326
+ int,
327
+ typer.Option("--node", "-n", help="1-based index of the node to select (default: 1)."),
328
+ ] = 1,
329
+ ) -> None:
330
+ """Set node-url in config to point at a node in a named environment."""
331
+ from ..config import save_config
332
+
333
+ name = _resolve_name(name)
334
+ urls = _dm(name).node_urls()
335
+ if not urls:
336
+ print_error(f"No nodes found in environment '{name}'. Is the compose file present?")
337
+ raise typer.Exit(1)
338
+ if node < 1 or node > len(urls):
339
+ print_error(
340
+ f"Node {node} does not exist in '{name}' — environment has {len(urls)} node(s)."
341
+ )
342
+ raise typer.Exit(1)
343
+ url = urls[node - 1]
344
+ state.config.node_url = url
345
+ save_config(state.config)
346
+ print_success(f"node-url → {url}")
347
+ print_info("Run [cyan]kaleido node unlock[/cyan] to activate the wallet.")
348
+
349
+
350
+ # ---------------------------------------------------------------------------
351
+ # Docker lifecycle (scoped by environment name)
352
+ # ---------------------------------------------------------------------------
353
+
354
+
355
+ @node_app.command(
356
+ "up",
357
+ epilog=(
358
+ "[bold]Examples[/bold]\n\n"
359
+ " [cyan]kaleido node up default[/cyan] Start the default environment\n"
360
+ " [cyan]kaleido node up myenv[/cyan] Start a named environment\n"
361
+ " [cyan]kaleido node up[/cyan] Auto-detect if only one environment exists"
362
+ ),
363
+ )
364
+ def node_up(
365
+ name: Annotated[
366
+ str | None,
367
+ typer.Argument(
368
+ help="Environment name (from 'kaleido node list'). Auto-detected if only one exists."
369
+ ),
370
+ ] = None,
371
+ ) -> None:
372
+ """Start containers for a named environment (docker compose up -d)."""
373
+ name = _resolve_name(name)
374
+ dm = _dm(name)
375
+ if not dm._validate():
376
+ raise typer.Exit(1)
377
+ outdated = compose_images(dm.compose_dir / COMPOSE_FILE) - {RLN_IMAGE}
378
+ if outdated:
379
+ print_warning(
380
+ f"'{name}' runs {', '.join(sorted(outdated))}; "
381
+ f"run 'kaleido node upgrade {name}' to move to {RLN_IMAGE}."
382
+ )
383
+ print_info(f"Starting environment '{name}' …")
384
+ rc = dm._run(["up", "-d"])
385
+ if rc == 0:
386
+ print_success(f"Environment '{name}' is up.")
387
+ else:
388
+ raise typer.Exit(rc)
389
+
390
+
391
+ @node_app.command(
392
+ "upgrade",
393
+ epilog=(
394
+ "[bold]Examples[/bold]\n\n"
395
+ " [cyan]kaleido node upgrade default[/cyan] Upgrade and restart\n"
396
+ " [cyan]kaleido node upgrade default --no-start[/cyan] Only rewrite the compose file\n\n"
397
+ "[dim]Node data is kept. Unlock the node again after it restarts.[/dim]"
398
+ ),
399
+ )
400
+ def node_upgrade(
401
+ name: Annotated[
402
+ str | None,
403
+ typer.Argument(help="Environment name. Auto-detected if only one exists."),
404
+ ] = None,
405
+ start: Annotated[
406
+ bool,
407
+ typer.Option("--start/--no-start", help="Recreate the containers after upgrading."),
408
+ ] = True,
409
+ ) -> None:
410
+ """Move an environment to the RGB Lightning Node image this CLI targets."""
411
+ name = _resolve_name(name)
412
+ dm = _dm(name)
413
+ if not dm._validate():
414
+ raise typer.Exit(1)
415
+ changed = upgrade_compose(dm.compose_dir / COMPOSE_FILE)
416
+ if not changed:
417
+ print_success(f"Environment '{name}' already uses {RLN_IMAGE}.")
418
+ return
419
+ for service, old in changed:
420
+ print_info(f"{service}: {old} → {RLN_IMAGE}")
421
+ if not start:
422
+ print_info(f"Compose file updated. Start with: kaleido node up {name}")
423
+ return
424
+ rc = dm._run(["up", "-d"])
425
+ if rc != 0:
426
+ raise typer.Exit(rc)
427
+ print_success(f"Environment '{name}' upgraded. Unlock it with: kaleido node unlock")
428
+
429
+
430
+ @node_app.command(
431
+ "stop",
432
+ epilog=(
433
+ " [cyan]kaleido node stop <name>[/cyan] Stop containers (data preserved).\n"
434
+ " [cyan]kaleido node stop[/cyan] Auto-detect environment."
435
+ ),
436
+ )
437
+ def node_stop(
438
+ name: Annotated[
439
+ str | None,
440
+ typer.Argument(help="Environment name. Auto-detected if only one exists."),
441
+ ] = None,
442
+ ) -> None:
443
+ """Stop running containers (without removing them)."""
444
+ name = _resolve_name(name)
445
+ rc = _dm(name).stop()
446
+ if rc == 0:
447
+ print_success(f"Environment '{name}' stopped.")
448
+ else:
449
+ raise typer.Exit(rc)
450
+
451
+
452
+ @node_app.command(
453
+ "shutdown",
454
+ epilog=" [cyan]kaleido node shutdown[/cyan] Gracefully shut down the configured node process.",
455
+ )
456
+ def node_shutdown() -> None:
457
+ """Gracefully shut down the configured node."""
458
+ asyncio.run(_node_shutdown())
459
+
460
+
461
+ async def _node_shutdown() -> None:
462
+ try:
463
+ client = get_client(require_node=True)
464
+ await client.rln.shutdown()
465
+ print_success("Node shutdown initiated.")
466
+ except Exception as e:
467
+ raise_cli_error(e)
468
+
469
+
470
+ @node_app.command(
471
+ "down",
472
+ epilog=" [cyan]kaleido node down <name>[/cyan] Stop and remove containers + networks.",
473
+ )
474
+ def node_down(
475
+ name: Annotated[
476
+ str | None,
477
+ typer.Argument(help="Environment name. Auto-detected if only one exists."),
478
+ ] = None,
479
+ ) -> None:
480
+ """Stop and remove containers and networks (volumes are preserved)."""
481
+ name = _resolve_name(name)
482
+ rc = _dm(name).down()
483
+ if rc == 0:
484
+ print_success(f"Environment '{name}' containers removed.")
485
+ else:
486
+ raise typer.Exit(rc)
487
+
488
+
489
+ @node_app.command("ps")
490
+ def node_ps(
491
+ name: Annotated[
492
+ str | None,
493
+ typer.Argument(help="Environment name. Auto-detected if only one exists."),
494
+ ] = None,
495
+ ) -> None:
496
+ """List container status for an environment."""
497
+ name = _resolve_name(name)
498
+ _dm(name).ps()
499
+
500
+
501
+ @node_app.command(
502
+ "logs",
503
+ epilog=(
504
+ "[bold]Examples[/bold]\n\n"
505
+ " Stream all logs:\n"
506
+ " [cyan]kaleido node logs default[/cyan]\n\n"
507
+ " Stream logs for one service:\n"
508
+ " [cyan]kaleido node logs myenv --service rgb_node_1[/cyan]\n\n"
509
+ " Print and exit:\n"
510
+ " [cyan]kaleido node logs default --no-follow[/cyan]"
511
+ ),
512
+ )
513
+ def node_logs(
514
+ name: Annotated[
515
+ str | None,
516
+ typer.Argument(help="Environment name. Auto-detected if only one exists."),
517
+ ] = None,
518
+ service: Annotated[
519
+ str | None,
520
+ typer.Option(
521
+ "--service",
522
+ "-s",
523
+ help="Filter to a specific service (e.g. rgb_node_1, rgb_node_2).",
524
+ ),
525
+ ] = None,
526
+ no_follow: Annotated[
527
+ bool, typer.Option("--no-follow", help="Print existing logs and exit.")
528
+ ] = False,
529
+ ) -> None:
530
+ """Stream logs from an environment's containers."""
531
+ name = _resolve_name(name)
532
+ _dm(name).logs(service=service, follow=not no_follow)
533
+
534
+
535
+ @node_app.command(
536
+ "clean",
537
+ epilog=(
538
+ " [red bold]Irreversible[/red bold] — deletes all data volumes.\n"
539
+ " [cyan]kaleido node clean <name> --yes[/cyan] Skip confirmation."
540
+ ),
541
+ )
542
+ def node_clean(
543
+ name: Annotated[
544
+ str | None,
545
+ typer.Argument(help="Environment name. Auto-detected if only one exists."),
546
+ ] = None,
547
+ yes: Annotated[bool, typer.Option("--yes", "-y", help="Skip confirmation prompt.")] = False,
548
+ ) -> None:
549
+ """[red]Remove all data volumes for an environment (irreversible).[/red]"""
550
+ name = _resolve_name(name)
551
+ if not yes:
552
+ confirmed = typer.confirm(
553
+ f"Delete all blockchain & node data for environment '{name}'? This cannot be undone."
554
+ )
555
+ if not confirmed:
556
+ print_info("Aborted.")
557
+ raise typer.Exit(0)
558
+ dm = _dm(name)
559
+ dm.down()
560
+ dm.clean()
561
+
562
+
563
+ # ---------------------------------------------------------------------------
564
+ # Node API (via SDK) — use node-url from config / --node-url flag
565
+ # ---------------------------------------------------------------------------
566
+
567
+
568
+ @node_app.command("info")
569
+ def node_info() -> None:
570
+ """Display node information from /nodeinfo."""
571
+ asyncio.run(_node_info())
572
+
573
+
574
+ async def _node_info() -> None:
575
+ try:
576
+ client = get_client(require_node=True)
577
+ info = await client.rln.get_node_info()
578
+ output_model(info, title="Node Info")
579
+ except Exception as e:
580
+ raise_cli_error(e)
581
+
582
+
583
+ @node_app.command("network")
584
+ def node_network() -> None:
585
+ """Display network information from /networkinfo."""
586
+ asyncio.run(_node_network())
587
+
588
+
589
+ async def _node_network() -> None:
590
+ try:
591
+ client = get_client(require_node=True)
592
+ net = await client.rln.get_network_info()
593
+ output_model(net, title="Network Info")
594
+ except Exception as e:
595
+ raise_cli_error(e)
596
+
597
+
598
+ @node_app.command(
599
+ "init",
600
+ epilog=(
601
+ "[bold]Examples[/bold]\n\n"
602
+ " Create a new wallet password interactively:\n"
603
+ " [cyan]kaleido node init[/cyan]\n\n"
604
+ " Pass password directly:\n"
605
+ " [cyan]kaleido node init --password mysecret[/cyan]"
606
+ ),
607
+ )
608
+ def node_init(
609
+ password: Annotated[
610
+ str | None,
611
+ typer.Option(
612
+ "--password",
613
+ "-p",
614
+ help="Wallet password. Prompted securely if omitted.",
615
+ hide_input=True,
616
+ ),
617
+ ] = None,
618
+ mnemonic: Annotated[
619
+ str | None,
620
+ typer.Option("--mnemonic", help="Optional mnemonic phrase to restore during init."),
621
+ ] = None,
622
+ ) -> None:
623
+ """Initialize a new node wallet (run once after first start)."""
624
+ resolved_password: str
625
+ if password is not None:
626
+ resolved_password = password
627
+ else:
628
+ resolved_password = typer.prompt(
629
+ "Create a new wallet password", hide_input=True, confirmation_prompt=True
630
+ )
631
+ asyncio.run(_node_init(resolved_password, mnemonic))
632
+
633
+
634
+ async def _node_init(password: str, mnemonic: str | None) -> None:
635
+ from kaleido_sdk.rln import InitRequest
636
+
637
+ try:
638
+ client = get_client(require_node=True)
639
+ response = await client.rln.init_wallet(InitRequest(password=password, mnemonic=mnemonic))
640
+ print_success("Wallet initialized.")
641
+ output_model(response, title="Init Response")
642
+ except Exception as e:
643
+ print_error(f"Error initializing wallet: {e}")
644
+ raise typer.Exit(1)
645
+
646
+
647
+ @node_app.command(
648
+ "unlock",
649
+ epilog=(
650
+ "[bold]Examples[/bold]\n\n"
651
+ " Simple unlock (choose signet, regtest, or custom services):\n"
652
+ " [cyan]kaleido node unlock[/cyan]\n\n"
653
+ " Non-interactive signet defaults:\n"
654
+ " [cyan]kaleido --agent node unlock --password mysecret[/cyan]\n\n"
655
+ " Sync from the indexer, without a bitcoind:\n"
656
+ " [cyan]kaleido node unlock --chain-sync transaction \\\n"
657
+ " --indexer-url electrum.example.com:50001[/cyan]\n\n"
658
+ " Regtest defaults:\n"
659
+ " [cyan]kaleido node unlock --bitcoind-user user --bitcoind-pass password \\\n"
660
+ " --bitcoind-host regtest-bitcoind.rgbtools.org --bitcoind-port 80 \\\n"
661
+ " --indexer-url electrum.rgbtools.org:50041[/cyan]\n\n"
662
+ " Override bitcoind credentials:\n"
663
+ " [cyan]kaleido node unlock --bitcoind-user alice --bitcoind-pass hunter2[/cyan]\n\n"
664
+ " Full custom override:\n"
665
+ " [cyan]kaleido node unlock \\\n"
666
+ " --bitcoind-host 192.168.1.100 --bitcoind-port 18443 \\\n"
667
+ " --bitcoind-user alice --bitcoind-pass hunter2 \\\n"
668
+ " --indexer-url tcp://192.168.1.100:50001 \\\n"
669
+ " --proxy-endpoint http://192.168.1.100:3000[/cyan]\n\n"
670
+ " With Lightning peer announcement:\n"
671
+ " [cyan]kaleido node unlock --announce-alias 'MyNode' --announce-address '203.0.113.42:9735'[/cyan]"
672
+ ),
673
+ )
674
+ def node_unlock(
675
+ password: Annotated[
676
+ str | None,
677
+ typer.Option(
678
+ "--password",
679
+ "-p",
680
+ help="Wallet password. Prompted securely if omitted.",
681
+ hide_input=True,
682
+ ),
683
+ ] = None,
684
+ chain_sync: Annotated[
685
+ ChainSyncMode,
686
+ typer.Option(
687
+ "--chain-sync",
688
+ help="How LDK follows the chain: 'block' via bitcoind, 'transaction' via the indexer.",
689
+ ),
690
+ ] = ChainSyncMode.BLOCK,
691
+ bitcoind_pass: Annotated[
692
+ str,
693
+ typer.Option(
694
+ "--bitcoind-pass",
695
+ help="bitcoind RPC password. Ignored with --chain-sync transaction.",
696
+ hide_input=True,
697
+ ),
698
+ ] = DEFAULT_BITCOIND_RPC_PASSWORD,
699
+ bitcoind_user: Annotated[
700
+ str,
701
+ typer.Option("--bitcoind-user", help="bitcoind RPC username."),
702
+ ] = DEFAULT_BITCOIND_RPC_USERNAME,
703
+ bitcoind_host: Annotated[
704
+ str,
705
+ typer.Option("--bitcoind-host", help="bitcoind RPC host."),
706
+ ] = DEFAULT_BITCOIND_RPC_HOST,
707
+ bitcoind_port: Annotated[
708
+ int,
709
+ typer.Option("--bitcoind-port", help="bitcoind RPC port."),
710
+ ] = DEFAULT_BITCOIND_RPC_PORT,
711
+ indexer_url: Annotated[
712
+ str,
713
+ typer.Option(
714
+ "--indexer-url",
715
+ help="Indexer URL — Esplora (https://…) or Electrum (host:port).",
716
+ ),
717
+ ] = DEFAULT_INDEXER_URL,
718
+ proxy_endpoint: Annotated[
719
+ str,
720
+ typer.Option("--proxy-endpoint", help="RGB proxy endpoint."),
721
+ ] = DEFAULT_PROXY_ENDPOINT,
722
+ announce_alias: Annotated[
723
+ str,
724
+ typer.Option("--announce-alias", help="Lightning peer alias to announce."),
725
+ ] = "",
726
+ announce_address: Annotated[
727
+ list[str],
728
+ typer.Option(
729
+ "--announce-address",
730
+ help="Public address(es) for Lightning peer discovery (can be repeated).",
731
+ ),
732
+ ] = [],
733
+ ) -> None:
734
+ """Unlock the node wallet."""
735
+ resolved_password: str
736
+ if password is not None:
737
+ resolved_password = password
738
+ else:
739
+ resolved_password = typer.prompt("Wallet password", hide_input=True)
740
+
741
+ if is_interactive():
742
+ profile = _prompt_unlock_service_profile()
743
+ chain_sync = _prompt_chain_sync_mode(chain_sync)
744
+ if profile == "signet":
745
+ bitcoind_user = DEFAULT_BITCOIND_RPC_USERNAME
746
+ bitcoind_pass = DEFAULT_BITCOIND_RPC_PASSWORD
747
+ bitcoind_host = DEFAULT_BITCOIND_RPC_HOST
748
+ bitcoind_port = DEFAULT_BITCOIND_RPC_PORT
749
+ indexer_url = DEFAULT_INDEXER_URL
750
+ proxy_endpoint = DEFAULT_PROXY_ENDPOINT
751
+ elif profile == "regtest":
752
+ bitcoind_user = DEFAULT_REGTEST_BITCOIND_RPC_USERNAME
753
+ bitcoind_pass = DEFAULT_REGTEST_BITCOIND_RPC_PASSWORD
754
+ bitcoind_host = DEFAULT_REGTEST_BITCOIND_RPC_HOST
755
+ bitcoind_port = DEFAULT_REGTEST_BITCOIND_RPC_PORT
756
+ indexer_url = DEFAULT_REGTEST_INDEXER_URL
757
+ proxy_endpoint = DEFAULT_REGTEST_PROXY_ENDPOINT
758
+ else:
759
+ if chain_sync is ChainSyncMode.BLOCK:
760
+ bitcoind_user = typer.prompt("bitcoind RPC username", default=bitcoind_user)
761
+ bitcoind_pass = typer.prompt(
762
+ "bitcoind RPC password", default=bitcoind_pass, hide_input=True
763
+ )
764
+ bitcoind_host = typer.prompt("bitcoind RPC host", default=bitcoind_host)
765
+ bitcoind_port = typer.prompt("bitcoind RPC port", default=bitcoind_port, type=int)
766
+ indexer_url = typer.prompt(
767
+ "Indexer URL (Esplora https:// or Electrum host:port)", default=indexer_url
768
+ )
769
+ proxy_endpoint = typer.prompt("RGB proxy endpoint", default=proxy_endpoint)
770
+ raw = typer.prompt("[OPTIONAL] Lightning announce alias (Enter to skip)", default="")
771
+ if raw.strip():
772
+ announce_alias = raw.strip()
773
+ raw = typer.prompt("[OPTIONAL] Lightning announce address (Enter to skip)", default="")
774
+ if raw.strip():
775
+ announce_address = [raw.strip()]
776
+
777
+ asyncio.run(
778
+ _node_unlock(
779
+ password=resolved_password,
780
+ chain_sync=chain_sync,
781
+ bitcoind_user=bitcoind_user,
782
+ bitcoind_pass=bitcoind_pass,
783
+ bitcoind_host=bitcoind_host,
784
+ bitcoind_port=bitcoind_port,
785
+ indexer_url=indexer_url,
786
+ proxy_endpoint=proxy_endpoint,
787
+ announce_alias=announce_alias,
788
+ announce_addresses=announce_address,
789
+ )
790
+ )
791
+
792
+
793
+ async def _node_unlock(
794
+ password: str,
795
+ chain_sync: ChainSyncMode,
796
+ bitcoind_user: str,
797
+ bitcoind_pass: str,
798
+ bitcoind_host: str,
799
+ bitcoind_port: int,
800
+ indexer_url: str,
801
+ proxy_endpoint: str,
802
+ announce_alias: str,
803
+ announce_addresses: list[str],
804
+ ) -> None:
805
+ from kaleido_sdk.rln import (
806
+ LdkBlockSyncConfig,
807
+ LdkChainSyncBlockSync,
808
+ LdkChainSyncTransactionSync,
809
+ LdkTransactionSyncConfig,
810
+ UnlockRequest,
811
+ )
812
+
813
+ ldk_chain_sync: LdkChainSyncBlockSync | LdkChainSyncTransactionSync
814
+ if chain_sync is ChainSyncMode.TRANSACTION:
815
+ ldk_chain_sync = LdkChainSyncTransactionSync(
816
+ mode="TransactionSync",
817
+ config=LdkTransactionSyncConfig(indexer_url=indexer_url),
818
+ )
819
+ else:
820
+ ldk_chain_sync = LdkChainSyncBlockSync(
821
+ mode="BlockSync",
822
+ config=LdkBlockSyncConfig(
823
+ bitcoind_rpc_username=bitcoind_user,
824
+ bitcoind_rpc_password=bitcoind_pass,
825
+ bitcoind_rpc_host=bitcoind_host,
826
+ bitcoind_rpc_port=bitcoind_port,
827
+ ),
828
+ )
829
+
830
+ try:
831
+ client = get_client(require_node=True)
832
+ req = UnlockRequest(
833
+ password=password,
834
+ ldk_chain_sync=ldk_chain_sync,
835
+ indexer_url=indexer_url,
836
+ announce_alias=announce_alias,
837
+ announce_addresses=announce_addresses,
838
+ )
839
+
840
+ await client.rln.unlock_wallet(req)
841
+ print_success("Wallet unlocked.")
842
+
843
+ # Show what was configured
844
+ if chain_sync is ChainSyncMode.BLOCK:
845
+ print_info(f"Connected to bitcoind: {bitcoind_user}@{bitcoind_host}:{bitcoind_port}")
846
+ else:
847
+ print_info("Following the chain from the indexer (no bitcoind).")
848
+ if indexer_url:
849
+ print_info(f"Connected to indexer: {indexer_url}")
850
+ if proxy_endpoint:
851
+ print_info(f"Connected to RGB proxy: {proxy_endpoint}")
852
+ if announce_alias:
853
+ print_info(f"Announcing as: [bold]{announce_alias}[/bold]")
854
+ if announce_addresses:
855
+ for addr in announce_addresses:
856
+ print_info(f"Announcing address: {addr}")
857
+ except Exception as e:
858
+ print_error(f"Error unlocking wallet: {e}")
859
+ raise typer.Exit(1)
860
+
861
+
862
+ @node_app.command("lock")
863
+ def node_lock() -> None:
864
+ """Lock the node wallet."""
865
+ asyncio.run(_node_lock())
866
+
867
+
868
+ async def _node_lock() -> None:
869
+ try:
870
+ client = get_client(require_node=True)
871
+ await client.rln.lock_wallet()
872
+ print_success("Wallet locked.")
873
+ except Exception as e:
874
+ raise_cli_error(e)