-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathbootstrap.sh.bak
More file actions
executable file
·2339 lines (1949 loc) · 74.8 KB
/
bootstrap.sh.bak
File metadata and controls
executable file
·2339 lines (1949 loc) · 74.8 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
#!/bin/bash
#
#
# ▄▄▄▄▄▄
# ███▀▀▀██▄ nesaorg/bootstrap
# ███ ███ ███████ ███████ █████
# ███ ███ ██ ██ ██ ██
# ▄▄▄ ███ █████ ███████ ███████
# ███ ███ ██ ██ ██ ██
# ███ ███ ███████ ███████ ██ ██
#
#
# noteworthy conventions: variables that are exported to the config file or the container environment files are in all caps
#
# vars
#
trap 'trap " " SIGINT SIGTERM SIGHUP; kill 0; wait; sigterm_handler' SIGINT SIGTERM SIGHUP
# ---- global bootstrap logging (captures ALL stdout/err while keeping the screen interactive) ----
DEFAULT_WORKDIR="${HOME}/.nesa"
LOG_DIR="${DEFAULT_WORKDIR}/logs"
mkdir -p "${LOG_DIR}"
# Mirror STDOUT and STDERR to file; only the copy to file is timestamped.
# This preserves gum's interactive UI on the terminal.
# exec > >(tee >(awk '{ printf "[%s] %s\n", strftime("%Y-%m-%dT%H:%M:%SZ"), $0; fflush() }' >> "${LOG_DIR}/bootstrap.log"))
# exec 2> >(tee >(awk '{ printf "[%s] %s\n", strftime("%Y-%m-%dT%H:%M:%SZ"), $0; fflush() }' >> "${LOG_DIR}/bootstrap.log") >&2)
# -----------------------------------------------------------------------------------------------
LOG_FILE="${LOG_DIR}/bootstrap.log"
_ts() { date -u +"%Y-%m-%dT%H:%M:%SZ"; }
log_line() { printf "[%s] %s\n" "$(_ts)" "$*" >>"$LOG_FILE"; }
log_stream() { while IFS= read -r line; do printf "[%s] %s\n" "$(_ts)" "$line" >>"$LOG_FILE"; done; }
run_and_log() {
local title="$1"
shift
log_line "BEGIN: $title — $*"
if gum spin -s line --title "$title" -- "$@" 2> >(log_stream) | log_stream; then
log_line "END: $title (ok)"
return 0
else
log_line "END: $title (fail)"
return 1
fi
}
DEFAULT_WORKDIR="${HOME}/.nesa"
LOG_DIR="${DEFAULT_WORKDIR}/logs"
ENV_DIR="${DEFAULT_WORKDIR}/env"
mkdir -p "${DEFAULT_WORKDIR}" "${LOG_DIR}" "${ENV_DIR}"
: > "${LOG_DIR}/bootstrap.log"
touch "${ENV_DIR}/base.env" "${ENV_DIR}/orchestrator.env" "${DEFAULT_WORKDIR}/.env"
sigterm_handler() {
printf "\n Aborting node setup. Cleaning up...\n"
# Add any additional cleanup tasks here
echo
exit 1
}
# set -x
terminal_size=$(stty size)
terminal_height=${terminal_size% *}
terminal_width=${terminal_size#* }
prompt_height=${PROMPT_HEIGHT:-1}
main_color=43
link_color=69
logo=$(gum style ' ▄▄▄▄▄▄
███▀▀▀██▄
███ ███
███ ███
▄▄▄ ███
███ ███
███ ███')
CHAIN_ID="nesa-testnet-3"
domain="test.nesa.sh"
chain_container="ghcr.io/nesaorg/nesachain:testnet-latest"
import_key_expect_url="https://raw.githubusercontent.com/nesaorg/bootstrap/master/import_key.expect"
node_id_file="$HOME/.nesa/identity/node_id.id"
miner_type_none=0
miner_type_non_distributed=1
miner_type_distributed=2
miner_type_agnostic=3
distributed_type_none=0
distributed_type_new_swarm=1
distributed_type_existing_swarm=2
distributed_type_agnostic=3
# this will never load from the env file, but if they know to override it via ENV vars then they can
WORKING_DIRECTORY=${WORKING_DIRECTORY:-"$DEFAULT_WORKDIR"}
env_dir="$WORKING_DIRECTORY/env"
orchestrator_env_file="$env_dir/orchestrator.env"
base_env_file="$env_dir/base.env"
config_env_file="$env_dir/.env"
init_pwd=$PWD # so they can get back to where they started!
status="booting" # lol not really doing anything with this currently
ORC_PORT=31333
MONIKER=${MONIKER:-$(hostname -s)}
#
# basic helper functions
#
# print if the output fits on screen
print_test() {
local no_color
local max_length
no_color=$(printf '%b' "${1}" | sed -e 's/\x1B\[[0-9;]*[JKmsu]//g')
max_length=$(max_line_length "$no_color")
[ "$(printf '%s' "${no_color}" | wc -l)" -gt $((terminal_height - prompt_height)) ] && return 1
[ "$max_length" -gt "$terminal_width" ] && return 1
gum style --align center --width="${terminal_width}" "${1}" ''
printf '%b' "\033[A"
}
update_header() {
local dashboard_url
local op_dashboard_url
local public_key
local current_width
local header
# Re-read terminal size in case it changed
terminal_size=$(stty size 2>/dev/null || echo "24 80")
terminal_height=${terminal_size% *}
terminal_width=${terminal_size#* }
if [[ "$NODE_ID" == "pending..." ]]; then
dashboard_url="https://node.nesa.ai"
else
dashboard_url="https://node.nesa.ai/nodes/$NODE_ID"
fi
if [[ -n "$NODE_PRIV_KEY" ]]; then
public_key=$(generate_public_key "$NODE_PRIV_KEY")
op_dashboard_url="https://node.nesa.ai/$public_key/list"
else
public_key="pending..."
op_dashboard_url="pending..."
fi
# Minimum width for horizontal layout (logo + spacer + info panel)
local min_horizontal_width=100
if [[ "$terminal_width" -ge "$min_horizontal_width" ]]; then
# Wide terminal: horizontal layout (logo on left, info on right)
info=$(gum style "[1;38;5;${main_color}m ${MONIKER}[0m.${domain}
----------------
[1;38;5;${main_color}mnode id: [0m${NODE_ID}
[1;38;5;${main_color}mpublic key: [0m${public_key}
[1;38;5;${main_color}mdashboard: [0;38;5;${link_color}m${dashboard_url}[0m
[1;38;5;${main_color}mop dash: [0;38;5;${link_color}m${op_dashboard_url}[0m
[1;38;5;${main_color}mstatus: [0m${status}")
header=$(gum join --horizontal --align top "${logo}" ' ' "${info}")
else
# Narrow terminal: vertical layout (logo on top, info below)
# Truncate long values to fit
local max_val_width=$((terminal_width - 16))
local trunc_node_id="${NODE_ID}"
local trunc_pubkey="${public_key}"
local trunc_dashboard="${dashboard_url}"
local trunc_op_dash="${op_dashboard_url}"
if [[ ${#NODE_ID} -gt $max_val_width ]]; then
trunc_node_id="${NODE_ID:0:$((max_val_width-3))}..."
fi
if [[ ${#public_key} -gt $max_val_width ]]; then
trunc_pubkey="${public_key:0:$((max_val_width-3))}..."
fi
if [[ ${#dashboard_url} -gt $max_val_width ]]; then
trunc_dashboard="${dashboard_url:0:$((max_val_width-3))}..."
fi
if [[ ${#op_dashboard_url} -gt $max_val_width ]]; then
trunc_op_dash="${op_dashboard_url:0:$((max_val_width-3))}..."
fi
info=$(gum style "[1;38;5;${main_color}m${MONIKER}[0m.${domain}
----------------
[1;38;5;${main_color}mnode id: [0m${trunc_node_id}
[1;38;5;${main_color}mpublic key: [0m${trunc_pubkey}
[1;38;5;${main_color}mdashboard: [0;38;5;${link_color}m${trunc_dashboard}[0m
[1;38;5;${main_color}mop dash: [0;38;5;${link_color}m${trunc_op_dash}[0m
[1;38;5;${main_color}mstatus: [0m${status}")
header=$(gum join --vertical --align center "${logo}" "${info}")
fi
echo -e "\n"
print_test "${header}"
echo -e "\n"
}
# check if a command exists
command_exists() {
command -v "$1" >/dev/null 2>&1
}
# error handling function
handle_install_failure() {
echo "Failed to install Gum using available methods due to permissions or unsupported OS..."
echo "Please install Gum manually by visiting: https://github.com/charmbracelet/gum"
exit 1
}
# install gum using Go
install_gum_go() {
echo "Installing Gum using Go..."
go install github.com/charmbracelet/gum@latest || handle_install_failure
}
# install gum based on the operating system and availability of Go
install_gum() {
# Try to install using Go if available
if command_exists go; then
install_gum_go
return
fi
case "$(uname -s)" in
Darwin)
echo "Installing Gum using Homebrew..."
brew install gum || handle_install_failure
;;
Linux)
if command_exists apt-get; then
echo "Installing Gum on Ubuntu/Debian..."
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://repo.charm.sh/apt/gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/charm.gpg
echo "deb [signed-by=/etc/apt/keyrings/charm.gpg] https://repo.charm.sh/apt/ * *" | sudo tee /etc/apt/sources.list.d/charm.list
sudo apt update && sudo apt install gum || handle_install_failure
elif command_exists pacman; then
echo "Installing Gum using pacman..."
sudo pacman -S gum || handle_install_failure
elif command_exists nix-env; then
echo "Installing Gum using Nix..."
nix-env -iA nixpkgs.gum || handle_install_failure
else
handle_install_failure
fi
;;
CYGWIN* | MINGW32* | MSYS* | MINGW*)
if command_exists winget; then
echo "Installing Gum using WinGet..."
winget install charmbracelet.gum || handle_install_failure
elif command_exists scoop; then
echo "Installing Gum using Scoop..."
scoop install charm-gum || handle_install_failure
else
handle_install_failure
fi
;;
*)
handle_install_failure
;;
esac
}
log_line "[STAGE 1]: checking deps (gum, jq, python)"
check_gum_installed() {
if ! command_exists gum; then
echo "Attempting to install gum..."
install_gum
fi
}
check_jq_installed() {
if ! command -v jq &>/dev/null; then
install_jq
fi
}
install_jq() {
case "$(uname -s)" in
Linux)
if command -v apt-get &>/dev/null; then
gum spin -s line --title "Installing jq with apt-get..." -- sudo apt-get update && sudo apt-get install -y jq
elif command -v yum &>/dev/null; then
gum spin -s line --title "Installing jq with yum..." -- sudo yum install -y jq
elif command -v pacman &>/dev/null; then
gum spin -s line --title "Installing jq with pacman..." -- sudo pacman -Sy jq
elif command -v zypper &>/dev/null; then
gum spin -s line --title "Installing jq with zypper..." -- sudo zypper install -y jq
elif command -v dnf &>/dev/null; then
gum spin -s line --title "Installing jq with dnf..." -- sudo dnf install -y jq
else
echo "Package manager not found. Please install jq manually."
exit 1
fi
;;
Darwin)
if command -v brew &>/dev/null; then
gum spin -s line --title "Installing jq with brew..." -- brew install jq
else
echo "Homebrew is not installed. Please install jq manually."
exit 1
fi
;;
*)
echo "Unsupported OS. Please install jq manually."
exit 1
;;
esac
}
# check if Docker is installed
check_docker_installed() {
if ! command_exists docker; then
echo "Docker is not installed. Please install Docker and try again."
exit 1
fi
}
check_python_and_ecdsa() {
if ! command -v python3 &>/dev/null; then
echo "Python 3 is not installed. Please install Python 3 and try again."
exit 1
fi
# Check and install required Python libraries
local missing_libs=()
if ! python3 -c "import ecdsa" &>/dev/null; then
missing_libs+=("ecdsa")
fi
if ! python3 -c "import base58" &>/dev/null; then
missing_libs+=("base58")
fi
if ! python3 -c "from cryptography.hazmat.primitives.asymmetric import ed25519" &>/dev/null; then
missing_libs+=("cryptography")
fi
if ! python3 -c "import mospy" &>/dev/null; then
missing_libs+=("mospy-wallet")
fi
if ! python3 -c "import httpx" &>/dev/null; then
missing_libs+=("httpx")
fi
if ! python3 -c "import betterproto" &>/dev/null; then
missing_libs+=("betterproto")
fi
if [ ${#missing_libs[@]} -gt 0 ]; then
echo "Installing required Python libraries: ${missing_libs[*]}..."
pip3 install "${missing_libs[@]}"
fi
}
# TODO: handle the need for sudo here -.-
# check_nvidia_installed() {
# if ! command_exists nvidia-smi; then
# echo "NVIDIA drivers are not installed. Please install NVIDIA drivers and try again."
# exit 1
# fi
# if ! command_exists nvidia-container-runtime; then
# sudo curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg \
# && sudo curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list | \
# sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | \
# sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list
# sudo apt-get update
# sudo apt-get install -y nvidia-container-toolkit
# sudo nvidia-ctk runtime configure --runtime=docker
# sudo systemctl restart docker
# fi
# }
# calculate max line length of the input
max_line_length() {
local max_len
local line_len
max_len=0
IFS=$'\n'
for line in $1; do
line_len=${#line}
if ((line_len > max_len)); then
max_len=$line_len
fi
done
echo "$max_len"
}
download_import_key_expect() {
# curl -o import_key.expect "$IMPORT_KEY_EXPECT_URL"
cp import_key.expect "$WORKING_DIRECTORY/"
chmod +x "$WORKING_DIRECTORY/import_key.expect"
}
get_linux_info() {
local name version kernel architecture cpu cores ram disk_avail gpu gpu_count gpu_memory
if [ -f /etc/os-release ]; then
. /etc/os-release
name=$NAME
version=$VERSION
else
name="Not Available"
version="Not Available"
fi
kernel=$(uname -r)
architecture=$(uname -m)
cpu=$(lscpu | grep 'Model name' | awk -F: '{print $2}' | sed 's/^ *//')
cores=$(lscpu | grep '^CPU(s):' | awk '{print $2}')
ram=$(free -h | grep Mem | awk '{print $2}')
disk_avail=$(df -h --total | grep total | awk '{print $4}')
gpu=$(lspci | grep -i -e '3D controller' -e 'VGA compatible controller' | grep -i -e nvidia -e amd | awk -F: '{print $3}' | sed 's/^ *//')
gpu_count=$(lspci | grep -i -e '3D controller' -e 'VGA compatible controller' | grep -i -e nvidia -e amd | wc -l | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
gpu_memory=$(nvidia-smi --query-gpu=memory.total --format=csv,noheader,nounits 2>/dev/null | awk '{total += $1} END {print total " MB"}')
if [ -z "$gpu_memory" ]; then
gpu_memory=$(lshw -C display 2>/dev/null | grep -i size | awk '{print $2 " " $3}' | head -n 1)
fi
NODE_OS="Linux $version"
NODE_ARCH="$architecture"
NODE_CPU="$cpu"
NODE_CORES="$cores"
NODE_GPU="${gpu:-NA}"
NODE_GPU_COUNT="${gpu_count:-0}"
NODE_RAM="$ram"
NODE_VRAM="${gpu_memory:-NA}"
NODE_DISK_AVAIL="$disk_avail"
}
get_macos_info() {
local product_version build_version architecture cpu cores ram disk_avail gpu gpu_count gpu_memory
product_version=$(sw_vers -productVersion)
build_version=$(sw_vers -buildVersion)
architecture=$(uname -m)
cpu=$(sysctl -n machdep.cpu.brand_string)
cores=$(sysctl -n hw.ncpu)
ram=$(sysctl -n hw.memsize | awk '{print $1/1024/1024/1024 " GB"}')
disk_avail=$(df -h / | grep / | awk '{print $4}')
gpu=$(system_profiler SPDisplaysDataType | grep 'Chipset Model' | awk -F: '{print $2}' | sed 's/^ *//')
gpu_count=$(system_profiler SPDisplaysDataType | grep 'Chipset Model' | wc -l | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
gpu_memory=$(system_profiler SPDisplaysDataType | grep 'VRAM' | awk -F: '{total += $2} END {print total " MB"}' | sed 's/^ *//')
NODE_OS="MacOS $product_version ($build_version)"
NODE_ARCH="$architecture"
NODE_CPU="$cpu"
NODE_CORES="$cores"
NODE_GPU="${gpu:-NA}"
NODE_GPU_COUNT="${gpu_count:-0}"
NODE_RAM="$ram"
NODE_VRAM="${gpu_memory:-NA}"
NODE_DISK_AVAIL="$disk_avail"
}
get_windows_info() {
local caption version architecture cpu cores ram disk_avail gpu gpu_count gpu_memory
caption=$(wmic os get Caption /value | awk -F= '{print $2}')
version=$(wmic os get Version /value | awk -F= '{print $2}')
architecture=$(wmic os get OSArchitecture /value | awk -F= '{print $2}')
cpu=$(wmic cpu get name /value | awk -F= '{print $2}')
cores=$(wmic cpu get NumberOfCores /value | awk -F= '{print $2}')
ram=$(wmic computersystem get totalphysicalmemory /value | awk -F= '{print $2/1024/1024/1024 " GB"}')
disk_avail=$(wmic logicaldisk get size,freespace,caption | awk '{if ($1 == "C:") print $3/1024/1024/1024 " GB"}')
gpu=$(wmic path win32_videocontroller get name /value | awk -F= '{print $2}')
gpu_count=$(wmic path win32_videocontroller get name /value | grep -c "Name" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
gpu_memory=$(wmic path win32_videocontroller get AdapterRAM /value | awk -F= '{total += $2} END {print total/1024/1024 " MB"}')
NODE_OS="Windows $caption $version"
NODE_ARCH="$architecture"
NODE_CPU="$cpu"
NODE_CORES="$cores"
NODE_GPU="${gpu:-NA}"
NODE_GPU_COUNT="${gpu_count:-0}"
NODE_RAM="$ram"
NODE_VRAM="${gpu_memory:-NA}"
NODE_DISK_AVAIL="$disk_avail"
}
get_wsl_info() {
local name version kernel architecture cpu cores ram disk_avail gpu gpu_count gpu_memory
if [ -f /etc/os-release ]; then
. /etc/os-release
name=$NAME
version=$VERSION
else
name="Not Available"
version="Not Available"
fi
kernel=$(uname -r)
architecture=$(uname -m)
cpu=$(grep -m1 'model name' /proc/cpuinfo | awk -F: '{print $2}' | sed 's/^ *//')
cores=$(grep -c '^processor' /proc/cpuinfo)
ram=$(free -h | grep Mem | awk '{print $2}')
disk_avail=$(df -h --total | grep total | awk '{print $4}')
if command -v nvidia-smi &>/dev/null; then
gpu=$(nvidia-smi --query-gpu=name --format=csv,noheader)
gpu_count=$(nvidia-smi --query-gpu=name --format=csv,noheader | wc -l)
gpu_memory=$(nvidia-smi --query-gpu=memory.total --format=csv,noheader,nounits | awk '{total += $1} END {print total " MB"}')
else
gpu="NA"
gpu_count=0
gpu_memory="NA"
fi
NODE_OS="WSL $version ($kernel)"
NODE_ARCH="$architecture"
NODE_CPU="$cpu"
NODE_CORES="$cores"
NODE_GPU="${gpu:-NA}"
NODE_GPU_COUNT="${gpu_count:-0}"
NODE_RAM="$ram"
NODE_VRAM="${gpu_memory:-NA}"
NODE_DISK_AVAIL="$disk_avail"
}
log_line "[STAGE 2]: detecting hardware capabilities"
detect_hardware_capabilities() {
case "$(uname -s)" in
Linux)
if grep -q Microsoft /proc/version; then
get_wsl_info
else
get_linux_info
fi
;;
Darwin)
get_macos_info
;;
CYGWIN* | MINGW* | MSYS*)
get_windows_info
;;
*)
echo "Unsupported platform"
;;
esac
}
log_line "[STAGE 3]: setup work dir"
setup_work_dir() {
if [ ! -d "$WORKING_DIRECTORY" ]; then
mkdir -p "$WORKING_DIRECTORY"
fi
cd "$WORKING_DIRECTORY" || {
echo -e "Error changing to working directory: $WORKING_DIRECTORY"
exit 1
}
setup_docker_repository
}
setup_docker_repository() {
if [ ! -d "docker" ]; then
gum spin -s line --title "Cloning the nesaorg/docker repository..." -- git clone https://github.com/nesaorg/docker.git
else
cd docker
gum spin -s line --title "Pulling latest updates from nesaorg/docker repository..." -- git pull
cd ..
fi
# Create symlink for env directory
if [ -d "docker" ]; then
ln -sfn "$env_dir" "docker/env"
else
echo "Error: Docker directory does not exist."
exit 1
fi
}
get_swarms_map() {
local url="https://lcd.test.nesa.ai/nesachain/dht/get_orchestrators"
local json_data
local excluded_node_ids
local exclude_node_ids_json
local map=()
excluded_node_ids=(
"QmbtSFavybyKNkP2MAhVftA4S7tAW5HXvbKGiX9hHx9XqF|mistralai|Mixtral-8x7B-Instruct-v0.1"
"QmR58ndfebR3LXNxT5qx3FgXMkb4AptjpDM83r1CXfAhAw|mistralai|Mixtral-8x7B-Instruct-v0.1"
"Qmc6GZVS41EzzU5j13cy1pL3HjhwJfaf1N71cjp2zt18HX|Orenguteng|Llama-3-8B-Lexi-Uncensored"
"QmR4Gi37D1cPnihhkvRG9kRGtBtXYxwAYo92x6y1FYxmij|bigscience|bloom-560m"
"QmeCvBP1N3BqDiQc7hGxNFgrtguVHncqGKChJJeMZtsM8C|randommodel"
"QmUxwnuEKAEY9CnB4tEPKvmwK6h6pmuSN3V28vQ9A3s8qQ|randommodel22"
)
exclude_node_ids_json=$(printf '%s\n' "${excluded_node_ids[@]}" | jq -R . | jq -s .)
json_data=$(curl -s "$url")
map=$(echo "$json_data" | jq -r --argjson exclude_node_ids "$exclude_node_ids_json" '
.orchestrators |
map(select(.node_id | (contains("/") | not))) |
map(select(.node_id as $id | $exclude_node_ids | index($id) | not)) |
map(
{
"node_id": (.node_id | split("|")[0]),
"organization": (.node_id | split("|")[1]),
"model_name": (.node_id | split("|")[2]),
"model_id": ((.node_id | split("|")[1]) + "/" + (.node_id | split("|")[2]))
}
)
')
echo "$map"
}
get_model_names() {
local map="$1"
local model_names
model_names=$(echo "$map" | jq -r '.[] | .model_id' | sort | uniq)
echo "$model_names"
}
get_node_id() {
local map="$1"
local model_id="$2"
local node_id
node_id=$(echo "$map" | jq -r --arg model_id "$model_id" '
.[] | select(.model_id == $model_id) | .node_id
')
echo "$node_id"
}
create_combined_node_id() {
local map="$1"
local model_id="$2"
local node_info
node_info=$(echo "$map" | jq -r --arg model_id "$model_id" '
.[] | select(.model_id == $model_id) | "\(.node_id)|\(.organization)|\(.model_name)"
')
echo "$node_info"
}
fetch_network_address() {
local recreated_node_id="$1"
local url="https://lcd.test.nesa.ai/nesachain/dht/get_node/$recreated_node_id"
local json_data
local network_address
json_data=$(curl -s "$url")
network_address=$(echo "$json_data" | jq -r '.node.network_address')
echo "$network_address"
}
generate_public_key() {
local private_key="$1"
python3 -c "
import ecdsa
def strip_0x_prefix(key_hex):
return key_hex[2:] if key_hex.startswith('0x') else key_hex
def private_key_to_public_key(private_key_hex):
private_key_hex = strip_0x_prefix(private_key_hex)
private_key_bytes = bytes.fromhex(private_key_hex)
sk = ecdsa.SigningKey.from_string(private_key_bytes, curve=ecdsa.SECP256k1)
vk = sk.get_verifying_key()
public_key_compressed = b'\x02' + vk.to_string()[:32] if vk.to_string()[-1] % 2 == 0 else b'\x03' + vk.to_string()[:32]
return public_key_compressed.hex()
print(private_key_to_public_key('$private_key'))
"
}
# Derive wallet address from private key (bech32 format)
derive_wallet_address() {
local private_key="$1"
local prefix="${2:-nesa}"
python3 -c "
import hashlib
import ecdsa
def bech32_polymod(values):
GEN = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
chk = 1
for v in values:
b = chk >> 25
chk = (chk & 0x1ffffff) << 5 ^ v
for i in range(5):
chk ^= GEN[i] if ((b >> i) & 1) else 0
return chk
def bech32_hrp_expand(hrp):
return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp]
def bech32_create_checksum(hrp, data):
values = bech32_hrp_expand(hrp) + data
polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ 1
return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]
def bech32_encode(hrp, data):
combined = data + bech32_create_checksum(hrp, data)
return hrp + '1' + ''.join([\"qpzry9x8gf2tvdw0s3jn54khce6mua7l\"[d] for d in combined])
def convertbits(data, frombits, tobits, pad=True):
acc = 0
bits = 0
ret = []
maxv = (1 << tobits) - 1
for value in data:
acc = (acc << frombits) | value
bits += frombits
while bits >= tobits:
bits -= tobits
ret.append((acc >> bits) & maxv)
if pad:
if bits:
ret.append((acc << (tobits - bits)) & maxv)
return ret
def strip_0x_prefix(key_hex):
return key_hex[2:] if key_hex.startswith('0x') else key_hex
def private_key_to_address(private_key_hex, prefix='$prefix'):
private_key_hex = strip_0x_prefix(private_key_hex)
private_key_bytes = bytes.fromhex(private_key_hex)
sk = ecdsa.SigningKey.from_string(private_key_bytes, curve=ecdsa.SECP256k1)
vk = sk.get_verifying_key()
public_key_compressed = b'\x02' + vk.to_string()[:32] if vk.to_string()[-1] % 2 == 0 else b'\x03' + vk.to_string()[:32]
sha256_hash = hashlib.sha256(public_key_compressed).digest()
ripemd160_hash = hashlib.new('ripemd160', sha256_hash).digest()
five_bit_data = convertbits(ripemd160_hash, 8, 5)
return bech32_encode(prefix, five_bit_data)
print(private_key_to_address('$private_key'))
"
}
# Generate NODE_ID from private key (deterministic derivation)
# Algorithm: SHA256(priv_key) -> Ed25519 seed -> Ed25519 pubkey -> SHA256 -> Base58
generate_node_id() {
local private_key="$1"
python3 -c "
import hashlib
import base58
from cryptography.hazmat.primitives.asymmetric import ed25519
from cryptography.hazmat.primitives import serialization
def strip_0x_prefix(key_hex):
return key_hex[2:] if key_hex.startswith('0x') else key_hex
def derive_node_id(private_key_hex):
private_key_hex = strip_0x_prefix(private_key_hex)
private_key_bytes = bytes.fromhex(private_key_hex)
# Derive Ed25519 seed from secp256k1 private key
seed = hashlib.sha256(private_key_bytes).digest()
# Create Ed25519 key from seed
ed_private_key = ed25519.Ed25519PrivateKey.from_private_bytes(seed)
ed_public_key = ed_private_key.public_key()
# Get raw public key bytes
public_bytes = ed_public_key.public_bytes(
encoding=serialization.Encoding.Raw,
format=serialization.PublicFormat.Raw
)
# Hash and encode
public_key_hash = hashlib.sha256(public_bytes).digest()
return base58.b58encode(public_key_hash).decode('utf-8')
print(derive_node_id('$private_key'))
"
}
# Check wallet balance (UNES tokens)
check_wallet_balance() {
local wallet_address="$1"
local lcd_url="https://lcd.dev.nesa.ai"
log_line "Checking wallet balance for ${wallet_address}"
# Query balance via LCD REST API
local balance_endpoint="${lcd_url}/cosmos/bank/v1beta1/balances/${wallet_address}"
local json_data
local http_code
json_data=$(curl -s -w "\n%{http_code}" "$balance_endpoint" 2>&1)
http_code=$(echo "$json_data" | tail -1)
json_data=$(echo "$json_data" | sed '$d')
if [ "$http_code" != "200" ]; then
local err_msg="HTTP $http_code"
if [ -n "$json_data" ]; then
local api_err=$(echo "$json_data" | jq -r '.message // .error // empty' 2>/dev/null)
[ -n "$api_err" ] && err_msg="$err_msg: $api_err"
fi
echo "error|0|0|${err_msg}"
log_line "Error querying balance: $err_msg"
return 1
fi
# Extract UNES balance
local unes_balance
unes_balance=$(echo "$json_data" | jq -r '.balances[] | select(.denom == "unes") | .amount' 2>/dev/null)
if [ -z "$unes_balance" ] || [ "$unes_balance" = "null" ]; then
unes_balance="0"
fi
# Convert from microunes to UNES (use awk for consistent formatting with leading zeros)
local unes_display
unes_display=$(awk "BEGIN {printf \"%.6f\", $unes_balance / 1000000}")
echo "ok|$unes_balance|$unes_display"
}
# Check miner deposit status
check_miner_deposit() {
local node_id="$1"
local lcd_url="https://lcd.dev.nesa.ai"
log_line "Checking miner deposit for node ${node_id}"
# Query miner via LCD REST API
local miner_endpoint="${lcd_url}/nesachain/dht/get_miner/${node_id}"
local json_data
local http_code
json_data=$(curl -s -w "\n%{http_code}" "$miner_endpoint" 2>&1)
http_code=$(echo "$json_data" | tail -1)
json_data=$(echo "$json_data" | sed '$d')
# Check for API-level errors (returned in JSON even with HTTP 200)
local api_code
api_code=$(echo "$json_data" | jq -r '.code // 0' 2>/dev/null)
if [ "$http_code" != "200" ] || [ "$api_code" != "0" ]; then
local err_msg="HTTP $http_code"
if [ -n "$json_data" ]; then
local api_err=$(echo "$json_data" | jq -r '.message // .error // empty' 2>/dev/null)
[ -n "$api_err" ] && err_msg="$api_err"
fi
# If error is "miner not found", treat it as not registered (not an error)
if [[ "$err_msg" == *"miner not found"* ]]; then
echo "ok|0|0|not_registered|unes"
return 0
fi
echo "error|0|0|not_registered|unes|${err_msg}"
log_line "Error querying miner: $err_msg"
return 1
fi
# Check if miner exists
local miner_exists
miner_exists=$(echo "$json_data" | jq -r '.miner' 2>/dev/null)
if [ "$miner_exists" = "null" ] || [ -z "$miner_exists" ]; then
echo "ok|0|0|not_registered|unes"
return 0
fi
# Extract deposit information
local deposit_amount
local deposit_denom
local bond_status
deposit_amount=$(echo "$json_data" | jq -r '.miner.deposit.amount // "0"')
deposit_denom=$(echo "$json_data" | jq -r '.miner.deposit.denom // "unes"')
bond_status=$(echo "$json_data" | jq -r '.miner.bond_status // 0')
# Convert bond status to readable format (handles both numeric and string enum)
case "$bond_status" in
0|"BOND_STATUS_UNBONDED") bond_status="unbonded" ;;
1|"BOND_STATUS_UNBONDING") bond_status="unbonding" ;;
2|"BOND_STATUS_BONDED") bond_status="bonded" ;;
*) bond_status="unknown" ;;
esac
# Convert from microunes to UNES (use awk for consistent formatting with leading zeros)
local deposit_display
deposit_display=$(awk "BEGIN {printf \"%.6f\", $deposit_amount / 1000000}")
echo "ok|$deposit_amount|$deposit_display|$bond_status|$deposit_denom"
}
# Check if node is registered on chain
# Returns: ok|registered or ok|not_registered or error|message
check_node_registered() {
local node_id="$1"
local lcd_url="https://lcd.dev.nesa.ai"
log_line "Checking node registration for ${node_id}"
local node_endpoint="${lcd_url}/nesachain/dht/get_node/${node_id}"
local json_data
local http_code
json_data=$(curl -s -w "\n%{http_code}" "$node_endpoint" 2>&1)
http_code=$(echo "$json_data" | tail -1)
json_data=$(echo "$json_data" | sed '$d')
local api_code
api_code=$(echo "$json_data" | jq -r '.code // 0' 2>/dev/null)
if [ "$http_code" != "200" ] || [ "$api_code" != "0" ]; then
local err_msg="HTTP $http_code"
if [ -n "$json_data" ]; then
local api_err=$(echo "$json_data" | jq -r '.message // .error // empty' 2>/dev/null)
[ -n "$api_err" ] && err_msg="$api_err"
fi
# "node not found" means not registered
if [[ "$err_msg" == *"node not found"* ]] || [[ "$err_msg" == *"not found"* ]]; then
echo "ok|not_registered"
return 0
fi
echo "error|${err_msg}"
return 1
fi
local node_exists
node_exists=$(echo "$json_data" | jq -r '.node.node_id // empty' 2>/dev/null)
if [ -z "$node_exists" ]; then
echo "ok|not_registered"
else
echo "ok|registered"
fi
}
# Register node on chain (MsgRegisterNode)
# Returns: success|tx_hash or error|message
register_node() {
local node_id="$1"
local private_key="$2"
local public_name="${3:-nesa-miner}"
local version="${4:-v1.0.0}"
local network_address="${5:-127.0.0.1:8080}"
local vram="${6:-8000000000}"
local network_rps="${7:-100.0}"
log_line "Registering node: node_id=$node_id"
python3 << PYEOF
import sys
import json
from dataclasses import dataclass
import betterproto
from mospy import Account, Transaction
from mospy.clients import HTTPClient
from google.protobuf import any_pb2 as any_pb
# Define MsgRegisterNode
@dataclass(eq=False, repr=False)
class MsgRegisterNode(betterproto.Message):
creator: str = betterproto.string_field(1)
node_id: str = betterproto.string_field(2)
public_name: str = betterproto.string_field(3)
version: str = betterproto.string_field(4)
network_address: str = betterproto.string_field(5)
wallet_address: str = betterproto.string_field(6)
vram: int = betterproto.uint64_field(7)
network_rps: float = betterproto.double_field(8)
using_relay: bool = betterproto.bool_field(9)
try:
private_key = "${private_key}"
node_id = "${node_id}"
public_name = "${public_name}"
version = "${version}"
network_address = "${network_address}"
vram = int(${vram})
network_rps = float(${network_rps})
# Create account
account = Account(private_key=private_key, hrp="nesa")
wallet_address = account.address