Repository navigation
Expand file tree
/
Copy pathsystem.py
More file actions
2130 lines (1838 loc) · 94.4 KB
/
Copy pathsystem.py
File metadata and controls
2130 lines (1838 loc) · 94.4 KB
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
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import os
import shutil
import subprocess
import tempfile
from datetime import datetime, timedelta
from decimal import Decimal
from getpass import getpass
from importlib.resources import files
from pathlib import Path
from typing import Optional
from rich.console import Console
import typer
import time
from eth_account import Account
from rich.prompt import Confirm
from dincli.cli.contract_utils import erc20_abi, router_abi
from dincli.cli.utils import (CACHE_DIR, CONFIG_DIR,
CONFIG_FILE, WORKER_CACHE_DIR,
print_tx_info,
SUPPORTED_IPFS_PROVIDERS, _get_password,
_confirm_or_exit, _clean_optional_string,
get_config, get_demo_private_key,
get_env_key, is_ethereum_address,
load_cid_services, load_config,
load_din_info, normalize_ipfs_provider,
resolve_ipfs_config, resolve_task_coordinator_address,
save_config, save_din_info,
validate_account_name, wallet_path_for_name,
atomic_write_wallet, resolve_wallet_path,
list_accounts, get_active_account_name, load_account,
_extract_keystore)
from dincli.services import bridge as bridge_service
dataset_app = typer.Typer(help="Manage federated datasets.")
app = typer.Typer(help="System utilities for DIN CLI.")
# Register the dataset group under system_app
app.add_typer(dataset_app, name="dataset")
def _is_inside_container() -> bool:
"""Return True when running inside a Docker container (/.dockerenv is the canonical marker)."""
return Path("/.dockerenv").exists()
def initialize_directories():
"""
Create user-level config and cache dirs if they do not exist.
Call this explicitly (e.g. from CLI or first-run code), not on import.
"""
os.makedirs(CONFIG_DIR, exist_ok=True)
os.makedirs(CACHE_DIR, exist_ok=True)
os.makedirs(WORKER_CACHE_DIR, exist_ok=True)
print(f"Initialized directories:\n- Config: {CONFIG_DIR}\n- Cache: {CACHE_DIR} \n- Worker Cache: {WORKER_CACHE_DIR}")
@app.callback(invoke_without_command=True)
def system(
ctx: typer.Context,
eth_balance: bool = typer.Option(
False,
"--eth-balance",
help="Show ETH balance for your wallet or a given address."
),
address: str = typer.Option(
None,
"--address",
help="Ethereum address to query. If not provided, uses your connected wallet."
),
):
# If the subcommand is one that doesn't need an account, we skip the default setup logic
if ctx.invoked_subcommand in ["register-wallet", "connect-wallet", "connect-demo-wallet", "init", "welcome", "where", "configure-network", "configure-demo", "configure-ipfs", "read-wallet", "show-index", "din-info", "import-deployments", "configure-logging", "dump-abi", "reset-all", "todo", "dataset", "send-eth", "run-worker-counting", "run-node-counting", "list-accounts", "set-wallet", "bridge-eth", "verify-deployment"]:
return
effective_network, w3, account, console = ctx.obj.get_en_w3_account_console()
# Early exit if neither balance flag is set
if not (eth_balance):
return # let subcommands run, or do nothing
if address:
target_address = w3.to_checksum_address(address)
else:
target_address = account.address
console.print(f"\n[green]Target Account Address:[/green] {target_address}")
# Fetch ETH balance if requested
if eth_balance:
balance_wei = w3.eth.get_balance(target_address)
balance_eth = w3.from_wei(balance_wei, "ether")
console.print(f"[green]ETH Balance:[/green] {balance_eth} ETH")
@app.command()
def where(ctx: typer.Context):
"""Print where dincli is installed."""
typer.secho("dincli is installed at: ", fg="green", nl=False)
typer.secho(f"{files('dincli')}", fg="magenta")
@app.command("run-node-counting")
def run_node_counting():
"""Run the counting task."""
typer.echo("Running the counting task...")
n = 0
while True:
n += 1
time.sleep(1)
typer.echo(f"DIN Node Count: {n}")
@app.command("run-worker-counting")
def run_worker_counting(
count: int = typer.Option(10, "--count", "-n", help="Number of counts (0 for infinite)"),
delay: float = typer.Option(1.0, "--delay", "-d", help="Seconds between counts"),
):
"""Run a counting task inside the DIN worker container."""
from dincli.cli.worker import ensure_worker_image, write_worker_job, WORKER_IMAGE
console = Console()
try:
ensure_worker_image(console)
except RuntimeError as e:
console.print(f"[bold red]{e}[/bold red]")
raise typer.Exit(1)
model_dir = Path(CACHE_DIR / "model_tmp")
model_dir.mkdir(parents=True, exist_ok=True)
(model_dir / "manifest.json").write_text("{}\n", encoding="utf-8")
svc_dir = model_dir / "services"
svc_dir.mkdir()
svc_src = Path(str(files("dincli"))) / "services" / "counting_service.py"
shutil.copy(svc_src, svc_dir / "counting_service.py")
job_path, output_dir = write_worker_job(
model_dir / "jobs",
"counting",
{
"network": "local",
"model_base_dir": "/din/model",
"manifest_path": "/din/model/manifest.json",
"role": "system",
"service_path": "services/counting_service.py",
"function_name": "run_counting",
"kwargs": {"count": count, "delay": delay},
},
)
cmd = [
"docker", "run", "--rm",
"--name", "din-worker-counting",
"--user", f"{os.getuid()}:{os.getgid()}",
"-e", "HOME=/tmp",
"--network", "none",
"-v", f"{model_dir.resolve()}:/din/model:ro",
"-v", f"{job_path.resolve()}:/din/job/job.json:ro",
"-v", f"{output_dir.resolve()}:/din/output:rw",
WORKER_IMAGE,
]
console.print("[bold cyan]Starting worker counting container (Ctrl+C to stop)...[/bold cyan]")
try:
subprocess.run(cmd, check=False)
except KeyboardInterrupt:
console.print("\n[yellow]Worker counting stopped.[/yellow]")
@app.command()
def welcome():
"""Print welcome message."""
typer.echo("Welcome to DIN CLI!")
@app.command("get-cache-dir")
def get_cache_dir():
"""Print cache directory paths used by dincli."""
if _is_inside_container():
typer.echo("Environment: DIN node container")
typer.echo("(DIN_STATE_DIR is bind-mounted at the identical host path, so paths below are valid on the host daemon too)")
else:
typer.echo("Environment: host")
typer.echo(f"Cache Directory: {CACHE_DIR}")
typer.echo(f"Worker Node Cache Directory: {WORKER_CACHE_DIR}")
@app.command("get-config-dir")
def get_config_dir():
"""Print config directory path used by dincli."""
if _is_inside_container():
typer.echo("Environment: DIN node container")
typer.echo("(DIN_STATE_DIR is bind-mounted at the identical host path, so path below is valid on the host daemon too)")
else:
typer.echo("Environment: host")
typer.echo(f"Config Directory: {CONFIG_DIR}")
@app.command("init")
def initialize():
"""Initialize DIN CLI by creating config/cache directories and a config file with demo mode off."""
initialize_directories()
if not CONFIG_FILE.exists():
CONFIG_FILE.write_text(json.dumps({"demo_mode": False}, indent=4) + "\n", encoding="utf-8")
Console().print(f"[green]✅ Created config file (demo mode off) at: {CONFIG_FILE}[/green]")
@app.command("configure-network")
def configure_network(ctx: typer.Context):
"""
Configure the default blockchain network for DIN CLI.
"""
effective_network, console = ctx.obj.network, ctx.obj.console
config = load_config()
config["network"] = effective_network
save_config(config)
console.print(f"[green]Network configured successfully: {effective_network}[/green]")
# ---------------------------------------------------------------------------
# Wallet model — registration vs. connection
# ---------------------------------------------------------------------------
# Wallets are *registered* once (key material stored under a name) and then
# *connected* (made the active wallet) as often as needed:
#
# dincli system register-wallet ... write key material to
# <CONFIG_DIR>/wallets/wallet_<name>.json
# dincli system connect-wallet NAME flip the persistent active-wallet
# pointer (config "wallet_name");
# never touches key material, never
# prompts for a secret
#
# Every command resolves the active wallet via utils.get_active_account_name()
# with this precedence (first hit wins):
#
# 1. dincli --wallet <name> global flag — this invocation only
# 2. DIN_WALLET_NAME environment variable
# 3. config "wallet_name" persisted by connect-wallet (or set-wallet)
# 4. "default" wallets/wallet_default.json, falling back to
# the legacy single-wallet <CONFIG_DIR>/wallet.json
#
# The private key is only decrypted (DIN_WALLET_PASSWORD or password prompt)
# when a command actually needs to sign — see utils.load_account().
def _refuse_real_wallet_in_demo_lane(console, resolved: str) -> None:
"""Refuse connect-demo-wallet on a real (encrypted) wallet, pointing at connect-wallet."""
console.print(
f"[red]❌ '{resolved}' is not a demo wallet — connect-demo-wallet only "
f"connects wallets created via `connect-demo-wallet`.[/red]"
)
console.print(f"[yellow]Did you mean:[/yellow] dincli system connect-wallet {resolved}")
raise typer.Exit(1)
def _is_existing_real_wallet(name: str) -> bool:
"""True if `name` resolves to an existing, readable wallet file that is not demo-format.
Invalid names, missing files and unreadable files return False so the caller's
normal error path reports them.
"""
try:
wallet_path, exists = resolve_wallet_path(validate_account_name(name))
if not exists:
return False
with open(wallet_path) as f:
return json.load(f).get("demo_mode") is not True
except (ValueError, OSError, json.JSONDecodeError, AttributeError):
return False
def _connect_registered_wallet(console, name: str, require_demo: Optional[bool] = None) -> str:
"""Persist `name` as the active wallet (config "wallet_name").
Pure pointer flip: requires the wallet file to already exist, never writes
key material, never prompts for a secret. Returns the validated name.
require_demo, when not None, restricts which lane `name` must belong to:
True requires the plaintext demo format (connect-demo-wallet), False
requires the encrypted real-wallet format (connect-wallet) — refusing on a
mismatch keeps demo and real accounts from ever being activated through
the wrong command. None (the default) applies no restriction.
"""
try:
resolved = validate_account_name(name)
except ValueError as e:
console.print(f"[red]❌ {e}[/red]")
raise typer.Exit(1)
wallet_path, exists = resolve_wallet_path(resolved)
if not exists:
if require_demo is True:
console.print(
f"[red]❌ Demo wallet '{resolved}' not found. "
f"Run `dincli system connect-demo-wallet {resolved} --account N` first.[/red]"
)
else:
console.print(
f"[red]❌ Wallet '{resolved}' not found. "
f"Run `dincli system register-wallet --name {resolved}` first.[/red]"
)
registered = [e["name"] for e in list_accounts(resolved)]
if registered:
console.print(f"[yellow]Registered wallets:[/yellow] {', '.join(registered)}")
raise typer.Exit(1)
# Read once — used for both the demo-lane check below and the address
# display at the end (present in demo, wrapper, and legacy-keystore
# formats; fall back gracefully if unreadable).
try:
with open(wallet_path) as f:
wallet_data = json.load(f)
except (json.JSONDecodeError, OSError):
wallet_data = {}
address = wallet_data.get("address", "unknown")
is_demo = wallet_data.get("demo_mode") is True
if require_demo is True and not is_demo:
_refuse_real_wallet_in_demo_lane(console, resolved)
if require_demo is False and is_demo:
console.print(
f"[red]❌ '{resolved}' is a demo wallet — connect-wallet refuses to activate it, "
f"to keep demo accounts out of the real-account path.[/red]"
)
console.print(f"[yellow]Did you mean:[/yellow] dincli system connect-demo-wallet {resolved}")
raise typer.Exit(1)
config = load_config()
config["wallet_name"] = resolved
save_config(config)
console.print(f"[green]✅ Active wallet set to '{resolved}'[/green] ({address})")
console.print("[dim]`dincli --wallet <name>` or DIN_WALLET_NAME still override this per invocation.[/dim]")
return resolved
@app.command("connect-wallet")
def connect_wallet(ctx: typer.Context,
name: str = typer.Argument("default", help="Registered wallet name to make active (default: 'default')"),
):
"""
Connect (activate) a registered named wallet.
Persists the choice in config ("wallet_name") so every subsequent dincli
invocation on this machine uses that wallet. This is purely a pointer
flip: no key material is read, written, or decrypted, and nothing is
prompted — so switching between named wallets is always safe and silent.
Active-wallet resolution priority (first hit wins):
\b
1. dincli --wallet <name> global flag, this invocation only
2. DIN_WALLET_NAME environment variable
3. config "wallet_name" <- what this command sets
4. 'default'
The wallet must already be registered:
\b
dincli system register-wallet --name validator --keystore ks.json
dincli system connect-wallet validator # switch to it
dincli system connect-wallet # switch back to 'default'
Real accounts only — refuses to activate a demo wallet (one created via
`connect-demo-wallet`). Use `connect-demo-wallet` for those instead.
"""
# Direct callers (e.g. tests) may omit the argument; Typer then passes an
# ArgumentInfo object — normalize to the CLI default.
if not isinstance(name, str):
name = "default"
# Guard against a common trap: `--wallet X` is the global per-invocation
# override (GlobalOptionsGroup hoists it to the root callback), so it never
# reaches this command — `connect-wallet --wallet X` just falls back to the
# positional default. If the override names a different wallet than the
# argument, the user almost certainly meant the positional form.
override = ctx.obj.wallet_name
if override and override != name:
ctx.obj.console.print(
f"[red]❌ `--wallet {override}` overrides the active wallet for this "
f"invocation only — it does not choose the wallet to connect.[/red]"
)
ctx.obj.console.print(
f"[yellow]Did you mean:[/yellow] dincli system connect-wallet {override}"
)
raise typer.Exit(1)
resolved = _connect_registered_wallet(ctx.obj.console, name, require_demo=False)
# Keep the in-process context consistent for the rest of this invocation.
ctx.obj.select_wallet(resolved)
@app.command("connect-demo-wallet")
def connect_demo_wallet(ctx: typer.Context,
name: str = typer.Argument("demo-default", help="Demo wallet name to connect (default: 'demo-default')"),
account: Optional[int] = typer.Option(None, "--account", "-a", help="Hardhat dev account index — (re)creates `name` from this index before connecting"),
yes: bool = typer.Option(False, "--yes", "-y", help="Skip the confirmation prompt when overwriting an existing named demo wallet"),
):
"""
Connect a well-known Hardhat dev account for local testing only.
With --account, this is a one-shot: no separate step needed. There is no
`register-demo-wallet` — this command both creates and connects.
\b
dincli system connect-demo-wallet --account 0 # create+connect 'demo-default' from index 0
dincli system connect-demo-wallet bob --account 1 # create+connect as 'bob'
dincli system connect-demo-wallet bob # reconnect an already-connected demo wallet by name
Requires demo mode on (`dincli system configure-demo --mode yes`). Stores the
key in PLAINTEXT — these keys are publicly derivable, never fund this address
on a real network. For your own wallet, use `register-wallet` + `connect-wallet`
instead.
"""
console = ctx.obj.console
yes = yes if isinstance(yes, bool) else False
if not isinstance(name, str):
name = "demo-default"
if not isinstance(account, int):
account = None
# Reconnecting by name to a real (encrypted) wallet: refuse with the specific
# "not a demo wallet" message before the demo-mode check. Turning demo mode
# on would not make this command accept it, so "Demo mode is off" misleads.
if account is None and _is_existing_real_wallet(name):
_refuse_real_wallet_in_demo_lane(console, validate_account_name(name))
if not get_config("demo_mode"):
console.print(
"[red]❌ Demo mode is off — connect-demo-wallet only works with demo "
"mode on.[/red]"
)
console.print(
"[yellow]Run `dincli system configure-demo --mode yes` first, or use "
"`dincli system register-wallet` / `connect-wallet` to connect your own key.[/yellow]"
)
raise typer.Exit(1)
# Guard against the same `--wallet X` trap connect-wallet guards against.
override = ctx.obj.wallet_name
if override and override != name:
console.print(
f"[red]❌ `--wallet {override}` overrides the active wallet for this "
f"invocation only — it does not choose the wallet to connect.[/red]"
)
console.print(
f"[yellow]Did you mean:[/yellow] dincli system connect-demo-wallet {override}"
)
raise typer.Exit(1)
if account is not None:
# One-shot: (re)create `name` from the given dev-account index, then connect it.
try:
resolved_name = validate_account_name(name)
except ValueError as e:
console.print(f"[red]❌ {e}[/red]")
raise typer.Exit(1)
target_path = wallet_path_for_name(resolved_name)
if target_path.exists() and not yes:
console.print(f"[yellow]A wallet named '{resolved_name}' already exists at {target_path}.[/yellow]")
if not typer.confirm("Overwrite it?"):
console.print("[yellow]Aborted. Existing wallet left unchanged.[/yellow]")
raise typer.Exit(0)
console.print(f"[green] ⚙️ Connecting demo wallet...[/green]")
console.print(f"[cyan]Saving as:[/cyan] {resolved_name}")
try:
privatekey = get_demo_private_key(account)
except (FileNotFoundError, IndexError) as e:
console.print(f"[red]❌ {e}[/red]")
raise typer.Exit(1)
acct = Account.from_key(privatekey)
wallet_data = {
"address": acct.address,
"private_key": privatekey, # ⚠️ PLAINTEXT — ONLY FOR MOCK!
"demo_mode": True
}
atomic_write_wallet(target_path, wallet_data)
console.print(f"[green]✅ Wallet saved in DEMO MODE (plaintext)![/green]")
console.print(f"[yellow]Address:[/yellow] {acct.address}")
console.print(f"[cyan]Wallet File:[/cyan] {target_path}")
resolved = _connect_registered_wallet(console, resolved_name, require_demo=True)
else:
# Pure pointer-flip to an already-connected demo wallet.
resolved = _connect_registered_wallet(console, name, require_demo=True)
# Keep the in-process context consistent for the rest of this invocation.
ctx.obj.select_wallet(resolved)
@app.command("set-wallet", deprecated=True)
def set_wallet(ctx: typer.Context, name: str = typer.Argument(..., help="Wallet name to set as the persistent default")):
"""(Deprecated) Alias of `connect-wallet`."""
console = ctx.obj.console
console.print("[yellow]`set-wallet` is deprecated — use `dincli system connect-wallet <name>`.[/yellow]")
_connect_registered_wallet(console, name, require_demo=False)
@app.command("configure-demo")
def configure_demo(ctx: typer.Context,
mode: str = typer.Option("yes", "--mode", help="Set demo mode: yes or no")
):
"""
Enable/disable demo mode (plaintext wallet storage, no password).
Useful for Hardhat/local testing.
"""
console = ctx.obj.console
if mode.lower() not in ("yes", "no"):
console.print("[red]Mode must be 'yes' or 'no'[/red]")
raise typer.Exit(1)
enable = mode.lower() == "yes"
config = load_config()
config["demo_mode"] = enable
save_config(config)
status = "enabled" if enable else "disabled"
console.print(f"[green]Demo mode {status}.[/green]")
if enable:
console.print("[red]⚠️ Wallets will be stored in plaintext. Do NOT use with real keys![/red]")
@app.command("configure-logging")
def configure_logging(ctx: typer.Context,
level: str = typer.Option("info", "--level", help="Set log level: debug | info | warning | error | critical")
):
"""
Configure the log level for DIN CLI.
"""
console = ctx.obj.console
if level.lower() not in ("debug", "info", "warning", "error", "critical"):
console.print("[red]Level must be 'debug', 'info', 'warning', 'error', or 'critical'[/red]")
raise typer.Exit(1)
config = load_config()
config["log_level"] = level.lower()
save_config(config)
console.print(f"[green]Log level set to {level}.[/green]")
@app.command("register-wallet")
def register_wallet(ctx: typer.Context,
privatekey: Optional[str] = typer.Argument(None, help="Your Ethereum private key (0x...)"),
key_file: Optional[Path] = typer.Option(None, "--key-file", "-f", help="Path to file containing private key"),
account: Optional[int] = typer.Option(None, "--account", "-a", help="Hardhat dev account index (0-69)"),
keystore: Optional[Path] = typer.Option(None, "--keystore", help="Import a standard Ethereum JSON keystore file"),
name: Optional[str] = typer.Option("default", "--name", "-n", help="Label for the saved keystore (default 'default')"),
yes: bool = typer.Option(False, "--yes", "-y", help="Skip the confirmation prompt when overwriting an existing named wallet"),
connect: bool = typer.Option(False, "--connect", "-c", help="Also make this wallet the active one (same as running `connect-wallet <name>` afterwards)"),
):
"""
Register a wallet: store key material under a name (create or import).
The key comes from exactly ONE of the following sources — passing more
than one is an error, passing none falls through to the hidden prompt:
\b
--keystore FILE import a standard Ethereum JSON keystore
--account N dev-account index: reads ETH_PRIVATE_KEY_<N> from the
environment/.env
--key-file FILE read the raw private key (0x...) from a file
PRIVATEKEY positional argument (insecure: shell history/logs)
(none) interactive hidden prompt <- recommended
Real accounts only — refuses to run while demo mode is on. For local
Hardhat testing, use `dincli system connect-demo-wallet` instead.
\b
Storage (at <CONFIG_DIR>/wallets/wallet_<name>.json): always an encrypted
keystore; the encryption password comes from DIN_WALLET_PASSWORD if set,
else a create/confirm prompt.
Registering does NOT switch the active wallet — pass --connect, or run
`dincli system connect-wallet <name>` afterwards. (--name defaults to
'default', which is also the final fallback of the active-wallet
resolution, so a plain `register-wallet` sets up the wallet used when
nothing else is selected.)
An existing wallet with the same name is only overwritten after
confirmation (skip with --yes).
\b
Examples:
dincli system register-wallet # prompt, save as 'default'
dincli system register-wallet --keystore ks.json --name validator
dincli system register-wallet --key-file ~/.dincli/wallet.key
dincli system register-wallet --account 3 --name acct3 --connect
"""
console = ctx.obj.console
if get_config("demo_mode"):
console.print(
"[red]❌ Demo mode is on — register-wallet refuses to run, to avoid ever "
"touching a real key while demo mode is active.[/red]"
)
console.print(
"[yellow]Run `dincli system configure-demo --mode no` first, or use "
"`dincli system connect-demo-wallet` for local Hardhat testing.[/yellow]"
)
raise typer.Exit(1)
# Direct callers (e.g. tests) may omit --yes/--connect; Typer then passes an
# OptionInfo object (truthy), which would silently bypass the overwrite guard
# below (or trigger an unwanted connect). Normalize to real bools so the
# behavior is the same on direct calls.
yes = yes if isinstance(yes, bool) else False
connect = connect if isinstance(connect, bool) else False
# Validate account name
try:
resolved_name = validate_account_name(name or "default")
except ValueError as e:
console.print(f"[red]❌ {e}[/red]")
raise typer.Exit(1)
# Validate mutual exclusivity
auth_methods = [
(privatekey, "private key argument"),
(key_file, "key file"),
(account, "account index"),
(keystore, "keystore file"),
]
provided_methods = [n for val, n in auth_methods if val is not None]
if len(provided_methods) > 1:
console.print(f"[red]❌ Please specify only one of: {', '.join(provided_methods)}.[/red]")
raise typer.Exit(1)
source = "created"
# --- keystore import: non-secret validation only ---
# Runs before the overwrite guard so a missing/malformed keystore fails fast
# without prompting, and so no secret (passphrase) is requested before the
# overwrite decision. The passphrase/decrypt happen after the guard, below.
inner_keystore = None
if keystore is not None:
keystore = keystore.expanduser()
if not keystore.exists():
console.print(f"[red]❌ Keystore file not found: {keystore}[/red]")
raise typer.Exit(1)
try:
with open(keystore, 'r') as f:
imported_ks = json.load(f)
except (json.JSONDecodeError, OSError) as e:
console.print(f"[red]❌ Failed to read keystore file: {e}[/red]")
raise typer.Exit(1)
try:
inner_keystore = _extract_keystore(imported_ks)
except ValueError:
console.print("[red]❌ File does not contain a recognisable keystore.[/red]")
raise typer.Exit(1)
source = "imported"
# --- overwrite guard ---
# Confirm before overwriting an existing named keystore, and before any secret
# prompt. Keys on the exact file to be written (a legacy wallet.json for the
# 'default' name is a non-destructive migration and intentionally not guarded).
target_path = wallet_path_for_name(resolved_name)
if target_path.exists() and not yes:
console.print(f"[yellow]A wallet named '{resolved_name}' already exists at {target_path}.[/yellow]")
if not typer.confirm("Overwrite it?"):
console.print("[yellow]Aborted. Existing wallet left unchanged.[/yellow]")
raise typer.Exit(0)
console.print(f"[green] ⚙️ Registering wallet...[/green]")
console.print(f"[cyan]Saving as:[/cyan] {resolved_name}")
# --- resolve secret material ---
if keystore is not None:
# Uses the keystore already extracted above — no re-read/re-parse.
passphrase = getpass("Keystore passphrase: ")
try:
decrypted_key = Account.decrypt(inner_keystore, passphrase)
except ValueError:
console.print("[red]❌ Wrong passphrase or corrupted keystore.[/red]")
raise typer.Exit(1)
acct = Account.from_key(decrypted_key)
address = acct.address
elif account is not None:
privatekey = get_env_key("ETH_PRIVATE_KEY_"+str(account))
if privatekey is None:
raise typer.Exit(1)
elif key_file is not None:
# Load from file
key_file = key_file.expanduser()
if not key_file.exists():
console.print(f"[red]❌ Key file not found: {key_file}[/red]")
raise typer.Exit(1)
try:
with open(key_file, 'r') as f:
privatekey = f.read().strip()
except Exception as e:
console.print(f"[red]❌ Failed to read key file: {e}[/red]")
raise typer.Exit(1)
elif privatekey is not None:
# Explicit argument
console.print("[yellow]⚠️ Warning: Providing private key as argument is insecure (saved in shell history). Use interactive mode or --key-file instead.[/yellow]")
else:
# Interactive prompt
console.print("[cyan]Enter your Ethereum private key (input will be hidden):[/cyan]")
privatekey = getpass("Private Key: ").strip()
# For non-keystore paths: validate key format and derive address
if keystore is None:
if not privatekey.startswith("0x") or len(privatekey) != 66:
console.print("[red]❌ Invalid private key format! Must be 0x + 64 hex chars.[/red]")
raise typer.Exit(1)
# Ensure config dir exists
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
if keystore is None:
acct = Account.from_key(privatekey)
address = acct.address
if keystore is not None:
ks_payload = inner_keystore
else:
# is_new_wallet=True: never reuse a stale in-memory-cached password when
# creating/overwriting a wallet; force the create/confirm flow (env var
# DIN_WALLET_PASSWORD is still honored for automation).
password = _get_password(resolved_name, False, is_new_wallet=True)
if password == "":
password = getpass("Create wallet password: ")
confirm = getpass("Confirm password: ")
if password != confirm:
console.print("[red]Passwords do not match![/red]")
raise typer.Exit()
ks_payload = Account.encrypt(privatekey, password)
wrapper = {
"version": 1,
"address": address,
"keystore": ks_payload,
"source": source,
"name": resolved_name,
}
wallet_path = wallet_path_for_name(resolved_name)
atomic_write_wallet(wallet_path, wrapper)
console.print(f"[green]Wallet {resolved_name} registered successfully![/green]")
console.print(f"[green]Wallet Account Address:[/green] {address}")
console.print(f"[green]Encrypted keystore saved at:[/green] {wallet_path}")
# Registration never switches the active wallet implicitly — only via
# --connect (see the wallet-model comment above for the resolution order).
if connect:
_connect_registered_wallet(console, resolved_name)
elif resolved_name != "default":
console.print(
f"[dim]Run `dincli system connect-wallet {resolved_name}` to make it the active wallet.[/dim]"
)
@app.command("read-wallet")
def read_wallet(ctx: typer.Context,
name: Optional[str] = typer.Option(None, "--name", "-n", help="Wallet name")
):
"""
Read and display wallet info.
In demo mode, shows private key. Otherwise, shows only address (after decrypting).
"""
console = ctx.obj.console
if not isinstance(name, str):
name = None
if name is not None:
wallet_to_read_name = name
active = False
else:
wallet_to_read_name = ctx.obj.resolved_wallet_name
active = True
wallet_path, exists = resolve_wallet_path(wallet_to_read_name)
if not exists:
console.print(f"[red]No wallet found for '{wallet_to_read_name}'. Run `dincli system register-wallet` first.[/red]")
raise typer.Exit(1)
with open(wallet_path) as f:
data = json.load(f)
# Check if it's demo mode (plaintext)
if isinstance(data, dict) and data.get("demo_mode") is True:
console.print("[bold green]🔐 Wallet (Demo Mode - Plaintext)[/bold green]")
console.print(f"[green]Wallet Name:[/green] {wallet_to_read_name} {'[bold green](active)[/bold green]' if active else ''}")
console.print(f"[yellow]Address:[/yellow] {data['address']}")
console.print(f"[red]Private Key:[/red] {data['private_key']}")
console.print("[cyan]⚠️ This key is stored in plaintext — for local testing only![/cyan]")
return
try:
# Decrypt the *requested* wallet, not the active one — ctx.obj.account
# always resolves the active wallet and would ignore --name.
acct = load_account(wallet_to_read_name)
console.print(f"[green]Wallet Name:[/green] {wallet_to_read_name} {'[bold green](active)[/bold green]' if active else ''}")
console.print(f"[green]Address:[/green] {acct.address}")
console.print("[green]✅ Wallet decrypted successfully.[/green]")
except Exception as e:
console.print(f"[red]❌ {e}[/red]")
raise typer.Exit(1)
@app.command("list-accounts")
def list_managed_accounts(ctx: typer.Context):
"""
List all named wallet accounts and their addresses (no decrypt needed).
Marks the currently active wallet.
"""
console = ctx.obj.console
active_name = ctx.obj.resolved_wallet_name
accounts = list_accounts(active_name)
if not accounts:
console.print("[yellow]No wallets found. Run `dincli system register-wallet` to create one.[/yellow]")
return
console.print("[bold cyan]Named wallets:[/bold cyan]")
for e in accounts:
marker = "[green](active)[/green]" if e["active"] else ""
source_tag = f" ({e['source']})" if e.get("source") not in ("unknown",) else ""
console.print(f" [bold]{e['name']}[/bold] → {e['address']}{source_tag} {marker}")
console.print(f"\n[dim]Active wallet name:[/dim] {active_name}")
@app.command("send-eth")
def send_eth(
ctx: typer.Context,
amount: str = typer.Option(..., "--amount", "-a", help="Amount of ETH to send (in ETH)"),
to: str = typer.Option(..., "--to", "-t", help="Recipient address"),
yes: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation prompt"),
):
"""
Send ETH to an address.
"""
effective_network, w3, account, console = ctx.obj.get_en_w3_account_console()
# Validate recipient address
try:
to = w3.to_checksum_address(to)
except Exception:
console.print(f"[bold red]✗ Invalid recipient address: {to}[/bold red]")
raise typer.Exit(1)
# Convert amount to wei
try:
amount_wei = w3.to_wei(amount, "ether")
except Exception as e:
console.print(f"[bold red]✗ Invalid amount '{amount}': {e}[/bold red]")
raise typer.Exit(1)
# Check sender balance
balance_wei = w3.eth.get_balance(account.address)
if balance_wei < amount_wei:
balance_eth = w3.from_wei(balance_wei, "ether")
console.print(f"[bold red]✗ Insufficient balance. Have {balance_eth} ETH, tried to send {amount} ETH.[/bold red]")
raise typer.Exit(1)
# Confirmation prompt
if not yes:
console.print(f"\n[bold yellow] From:[/bold yellow] {account.address}")
console.print(f"[bold yellow] To:[/bold yellow] {to}")
console.print(f"[bold yellow]Amount:[/bold yellow] {amount} ETH")
console.print(f"[bold yellow] Net:[/bold yellow] {effective_network}\n")
confirmed = typer.confirm("Confirm transaction?")
if not confirmed:
console.print("[yellow]Aborted.[/yellow]")
raise typer.Exit(0)
# Build and send raw ETH transfer
try:
tx_params = ctx.obj.get_tx_params()
tx_params.update({"to": to, "value": amount_wei, "from": account.address})
tx_params["gas"] = int(w3.eth.estimate_gas(tx_params) * 1.1)
signed_tx = account.sign_transaction(tx_params)
console.print(f"[bold green]Sending {amount} ETH to {to}...[/bold green]")
tx_hash = w3.eth.send_raw_transaction(signed_tx.raw_transaction)
print_tx_info(tx_hash, effective_network)
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
if receipt.status == 1:
console.print(f"[bold green] ✓ Successfully sent {amount} ETH to {to}[/bold green]")
else:
console.print(f"[bold red]✗ Transaction failed (reverted)[/bold red]")
raise typer.Exit(1)
except typer.Exit:
raise
except Exception as e:
console.print(f"[bold red]✗ Transaction failed: {e}[/bold red]")
raise typer.Exit(1)
@app.command("show-index")
def show_index(ctx: typer.Context,
address: str = typer.Option(..., "--address", "-a", help="Address of the contract"),
):
"""
Show the index of the the account address in demo mode.
"""
from dincli.cli.utils import get_demo_account_index
console = ctx.obj.console
try:
index = get_demo_account_index(address)
console.print(f"[green]Account Index:[/green] {index}")
except ValueError as e:
console.print(f"[red]{e}[/red]")
raise typer.Exit(1)
except FileNotFoundError as e:
console.print(f"[red]{e}[/red]")
raise typer.Exit(1)
@app.command("din-info")
def din_info(ctx: typer.Context,
coordinator: bool = typer.Option(False, "--coordinator", help="Show coordinator address"),
token: bool = typer.Option(False, "--token", help="Show DIN token address"),
stake: bool = typer.Option(False, "--stake", help="Show staking contract"),
representative: bool = typer.Option(False, "--representative", help="Show representative logic"),
registry: bool = typer.Option(False, "--registry", help="Show registry contract"),
treasury: bool = typer.Option(False, "--treasury", help="Show treasury contract"),
fee_router: bool = typer.Option(False, "--fee-router", help="Show fee router contract"),
emission: bool = typer.Option(False, "--emission", help="Show emission contract"),
):
# Resolve effective network
effective_network, _, _, console = ctx.obj.get_en_w3_account_console()
data = load_din_info()[effective_network]
# Print requested info
if coordinator:
console.print(f"[cyan]Coordinator:[/cyan] {data.get('coordinator', 'N/A')}")
if token:
console.print(f"[green]DIN Token:[/green] {data.get('token', 'N/A')}")
if stake:
console.print(f"[yellow]Staking Contract:[/yellow] {data.get('stake', 'N/A')}")
if representative:
console.print(f"[magenta]Representative:[/magenta] {data.get('representative', 'N/A')}")
if registry:
console.print(f"[magenta]Registry:[/magenta] {data.get('registry', 'N/A')}")
if treasury:
console.print(f"[blue]Treasury:[/blue] {data.get('treasury', 'N/A')}")
if fee_router:
console.print(f"[blue]Fee Router:[/blue] {data.get('fee_router', 'N/A')}")
if emission:
console.print(f"[blue]Emission:[/blue] {data.get('emission', 'N/A')}")
if not any([coordinator, token, stake, representative, registry, treasury, fee_router, emission]):
console.print(f"[cyan]Coordinator:[/cyan] {data.get('coordinator', 'N/A')}")
console.print(f"[green]DIN Token:[/green] {data.get('token', 'N/A')}")
console.print(f"[yellow]Staking Contract:[/yellow] {data.get('stake', 'N/A')}")
console.print(f"[magenta]Representative:[/magenta] {data.get('representative', 'N/A')}")
console.print(f"[magenta]Registry:[/magenta] {data.get('registry', 'N/A')}")
if data.get("treasury"):
console.print(f"[blue]Treasury:[/blue] {data.get('treasury')}")
if data.get("fee_router"):
console.print(f"[blue]Fee Router:[/blue] {data.get('fee_router')}")
if data.get("emission"):
console.print(f"[blue]Emission:[/blue] {data.get('emission')}")
# ---------------------------------------------------------------------------
# Platform deployments import
# ---------------------------------------------------------------------------
# The platform contracts (DinTreasury, DinToken, DinCoordinator,
# DinValidatorStake, DINModelRegistry, DinFeeRouter, DinEmission) are
# transparent proxies. INTERIM bootstrap flow: proxy deployment + initialize +
# wiring is done by a toolchain script running the OpenZeppelin upgrades
# validation:
#
# cd foundry && forge script script/DeployPlatform.s.sol --rpc-url <rpc> --broadcast ... # primary
# cd hardhat && npx hardhat run scripts/deploy-platform.ts --network <net> # secondary
#
# Each script records the proxy addresses in <toolchain>/deployments/<net>.json
# (same schema); `dincli system import-deployments` maps that file into
# din_info.json so all dincli commands resolve the deployed platform.
#
# NOTE — this is not the target architecture. The decision record
# Documentation/technical/upgradable-contracts/proxy-deployment-architecture.md
# chose native web3.py proxy deployment inside `dinrep deploy` (its Option C;
# backlog: Developer/issues/dincli-native-proxy-deployment.md). Once that
# lands, this command demotes to a secondary sync utility for script-driven
# deployments/upgrades and for adopting already-deployed networks. Either way
# din_info.json stays the contract with the rest of dincli.
# dincli network name → deploy-toolchain network name (standalone `npx hardhat