-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.sh
More file actions
1957 lines (1743 loc) · 70.9 KB
/
install.sh
File metadata and controls
1957 lines (1743 loc) · 70.9 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
#!/usr/bin/env bash
# Push Validator Manager (Go) — Installer with binary download + guided start
#
# This script installs the Push Validator Manager by downloading pre-built binaries
# from GitHub Releases. Use --dev for development builds from source.
#
# Examples:
# bash install.sh # default: download binaries, init+start, wait for sync
# bash install.sh --no-reset --no-start # install only
# bash install.sh --dev # build from current repo checkout (dev mode)
# bash install.sh --dev-dir /path/to/repo # build from specific directory
# PNM_REF=v1.0.0 bash install.sh # download specific version of push-validator
# PCHAIN_REF=v1.0.0 bash install.sh # download specific version of pchaind
set -euo pipefail
IFS=$'\n\t'
# Styling and output functions
CYAN='\033[0;36m'; GREEN='\033[0;32m'; YELLOW='\033[0;33m'; RED='\033[0;31m'; BOLD='\033[1m'; DIM='\033[2m'; NC='\033[0m'
NO_COLOR="${NO_COLOR:-}"
VERBOSE="${VERBOSE:-no}"
# Disable colors if NO_COLOR is set or not a terminal
if [[ -n "$NO_COLOR" ]] || [[ ! -t 1 ]]; then
CYAN=''; GREEN=''; YELLOW=''; RED=''; BOLD=''; DIM=''; NC=''
fi
# Prevent terminal background color queries from polluting output
# This tells charmbracelet/termenv libraries the background color,
# avoiding OSC 11 queries that cause ^[]11;rgb:... responses in iTerm2
export COLORFGBG="${COLORFGBG:-0;15}"
status() { echo -e "${CYAN}$*${NC}"; }
ok() {
if [[ $PHASE_START_TIME -gt 0 ]]; then
local delta=$(($(date +%s) - PHASE_START_TIME))
local unit="s"
local time_val=$delta
# Show milliseconds for sub-second times
if [[ $delta -eq 0 ]]; then
time_val="<1"
unit="s"
fi
echo -e " ${GREEN}✓ $* (${time_val}${unit})${NC}"
else
echo -e " ${GREEN}✓ $*${NC}"
fi
}
ok_sub() { echo -e " ${GREEN}✓ $*${NC}"; } # 4-space indent for nested sub-items
warn() { echo -e " ${YELLOW}⚠ $*${NC}"; }
err() { echo -e " ${RED}✗ $*${NC}"; }
phase() { echo -e "\n${BOLD}${CYAN}▸ $*${NC}"; }
step() { echo -e " ${DIM}→${NC} $*"; }
step_sub() { echo -e " ${DIM}→${NC} $*"; } # 4-space indent for nested sub-steps
verbose() { [[ "$VERBOSE" = "yes" ]] && echo -e " ${DIM}$*${NC}" || true; }
# Helper: Shorten path for display (replace $HOME with ~)
short_path() { echo "${1/#$HOME/\~}"; }
# Helper: Indent output lines (adds 2-space prefix)
indent_output() {
while IFS= read -r line; do
if [[ -n "$line" ]]; then
echo " $line"
else
echo ""
fi
done
}
# Helper: Find timeout command (macOS needs gtimeout)
timeout_cmd() {
if command -v timeout >/dev/null 2>&1; then
echo "timeout"
elif command -v gtimeout >/dev/null 2>&1; then
echo "gtimeout"
else
echo ""
fi
}
# Helper: Get file size in bytes (portable: macOS + Linux)
get_file_size() {
local file="$1"
if [[ ! -f "$file" ]]; then
echo 0
return
fi
# macOS: stat -f%z, Linux: stat -c%s, fallback: wc -c
stat -f%z "$file" 2>/dev/null || stat -c%s "$file" 2>/dev/null || wc -c < "$file" | tr -d ' '
}
# Helper: Format byte count to human-readable (matches Go FormatBytes: 1024-based)
format_bytes() {
awk "BEGIN {
b = $1
if (b >= 1073741824) printf \"%.1fGB\", b/1073741824
else if (b >= 1048576) printf \"%.1fMB\", b/1048576
else if (b >= 1024) printf \"%.1fKB\", b/1024
else printf \"%dB\", b
}"
}
# Helper: Format bytes/sec to human-readable speed (matches Go FormatSpeed)
format_speed() {
awk "BEGIN {
s = $1
if (s >= 1073741824) printf \"%.1fGB/s\", s/1073741824
else if (s >= 1048576) printf \"%.1fMB/s\", s/1048576
else if (s >= 1024) printf \"%.1fKB/s\", s/1024
else printf \"%.0fB/s\", s
}"
}
# Helper: Format seconds to duration string (matches Go formatDuration)
format_eta() {
local sec=$1
if [[ $sec -lt 0 ]]; then
printf "--"
elif [[ $sec -lt 60 ]]; then
printf "%ds" "$sec"
elif [[ $sec -lt 3600 ]]; then
printf "%dm%ds" "$((sec / 60))" "$((sec % 60))"
else
printf "%dh%dm" "$((sec / 3600))" "$(((sec % 3600) / 60))"
fi
}
# Helper: Render one frame of the progress bar (matches Go ui.ProgressBar)
# Arguments: current_bytes total_bytes start_epoch
render_progress_bar() {
local current=$1 total=$2 start_epoch=$3
local indent=" "
if [[ $total -le 0 ]]; then
printf "\r%sDownloading... %s\033[K" "$indent" "$(format_bytes "$current")"
return
fi
# Percentage
local pct
pct=$(awk "BEGIN {printf \"%.1f\", ($current / $total) * 100}")
# Speed and ETA
local now elapsed speed eta
now=$(date +%s)
elapsed=$((now - start_epoch))
if [[ $elapsed -gt 0 ]]; then
speed=$((current / elapsed))
else
speed=0
fi
if [[ $speed -gt 0 && $current -lt $total ]]; then
local remaining=$(( (total - current) / speed ))
eta=$(format_eta "$remaining")
elif [[ $current -ge $total ]]; then
eta="0s"
else
eta="--"
fi
# Bar width (matches Go: min(40, max(10, term_width - 56 - indent_len)))
local term_width=80
if command -v tput >/dev/null 2>&1; then
local tw
tw=$(tput cols 2>/dev/null || echo 80)
[[ $tw -gt 0 ]] && term_width=$tw
fi
local bar_width=$((term_width - 56 - ${#indent}))
[[ $bar_width -lt 10 ]] && bar_width=10
[[ $bar_width -gt 40 ]] && bar_width=40
# Filled/unfilled counts
local filled unfilled
filled=$(awk "BEGIN {v=int(($pct / 100) * $bar_width); if(v>$bar_width) v=$bar_width; if(v<0) v=0; print v}")
unfilled=$((bar_width - filled))
# Unicode detection (fallback to ASCII)
local fill_char unfill_char
if [[ "${LANG:-}${LC_ALL:-}" == *[Uu][Tt][Ff]* ]]; then
fill_char=$'\xe2\x96\x88' # █ (U+2588)
unfill_char=$'\xe2\x96\x91' # ░ (U+2591)
else
fill_char="#"
unfill_char="-"
fi
# Build bar string
local bar_str=""
local i
for ((i = 0; i < filled; i++)); do bar_str+="$fill_char"; done
for ((i = 0; i < unfilled; i++)); do bar_str+="$unfill_char"; done
# Format values
local cur_fmt tot_fmt spd_fmt
cur_fmt=$(format_bytes "$current")
tot_fmt=$(format_bytes "$total")
spd_fmt=$(format_speed "$speed")
printf "\r%s[%s] %5s%% %s/%s %s ETA %s\033[K" \
"$indent" "$bar_str" "$pct" "$cur_fmt" "$tot_fmt" "$spd_fmt" "$eta"
}
# Helper: Download a file with Go-style progress bar
# Arguments: url output_file
# Returns: 0 on success, non-zero on failure
download_with_progress() {
local url="$1" output_file="$2"
local total_size=0 use_curl=1
if command -v curl >/dev/null 2>&1; then
use_curl=1
elif command -v wget >/dev/null 2>&1; then
use_curl=0
else
return 1
fi
# Non-TTY fallback: simple download with percentage lines at 10% intervals
if [[ ! -t 1 ]]; then
if [[ $use_curl -eq 1 ]]; then
# Get size for percentage reporting
total_size=$(curl -sLI "$url" 2>/dev/null | grep -i '^content-length:' | tail -1 | awk '{print $2}' | tr -d '\r\n' || true)
total_size=${total_size:-0}
curl -sL -o "$output_file" "$url" < /dev/null &
else
total_size=$(wget --spider --server-response "$url" 2>&1 | grep -i 'content-length:' | tail -1 | awk '{print $2}' | tr -d '\r\n' || true)
total_size=${total_size:-0}
wget -q -O "$output_file" "$url" < /dev/null &
fi
local dl_pid=$!
local last_threshold=-1
while kill -0 "$dl_pid" 2>/dev/null; do
if [[ -f "$output_file" && $total_size -gt 0 ]]; then
local cur
cur=$(get_file_size "$output_file")
local threshold=$(( (cur * 100 / total_size) / 10 * 10 ))
if [[ $threshold -gt $last_threshold ]]; then
last_threshold=$threshold
printf " Downloading... %d%%\n" "$threshold"
fi
fi
sleep 1
done
wait "$dl_pid" || true
return $?
fi
# TTY mode: show progress bar
# Get Content-Length via HEAD request (follows redirects)
if [[ $use_curl -eq 1 ]]; then
total_size=$(curl -sLI "$url" 2>/dev/null | grep -i '^content-length:' | tail -1 | awk '{print $2}' | tr -d '\r\n' || true)
else
total_size=$(wget --spider --server-response "$url" 2>&1 | grep -i 'content-length:' | tail -1 | awk '{print $2}' | tr -d '\r\n' || true)
fi
total_size=${total_size:-0}
# Start download in background (silent)
local start_epoch dl_pid
start_epoch=$(date +%s)
if [[ $use_curl -eq 1 ]]; then
curl -sL -o "$output_file" "$url" < /dev/null &
dl_pid=$!
else
wget -q -O "$output_file" "$url" < /dev/null &
dl_pid=$!
fi
# Poll file size and render progress bar
local current_size=0
while kill -0 "$dl_pid" 2>/dev/null; do
if [[ -f "$output_file" ]]; then
current_size=$(get_file_size "$output_file")
fi
render_progress_bar "$current_size" "$total_size" "$start_epoch"
sleep 0.2 2>/dev/null || sleep 1
done
# Capture exit code
local dl_exit=0
wait "$dl_pid" || dl_exit=$?
# Final frame (100% if successful)
if [[ $dl_exit -eq 0 && -f "$output_file" ]]; then
current_size=$(get_file_size "$output_file")
[[ $total_size -eq 0 ]] && total_size=$current_size
render_progress_bar "$current_size" "$total_size" "$start_epoch"
fi
printf "\n"
return $dl_exit
}
# Helper: Check if node is running
node_running() {
local TO; TO=$(timeout_cmd)
local status_json
if [[ -n "$TO" ]]; then
status_json=$($TO 2 "$MANAGER_BIN" status --output json < /dev/null 2>/dev/null || echo "{}")
else
status_json=$("$MANAGER_BIN" status --output json < /dev/null 2>/dev/null || echo "{}")
fi
if command -v jq >/dev/null 2>&1; then
echo "$status_json" | jq -er '.node.running // .running // false' >/dev/null 2>&1 && return 0 || return 1
else
echo "$status_json" | grep -q '"running"[[:space:]]*:[[:space:]]*true' && return 0 || return 1
fi
}
# Helper: Stop all running node processes with verification
stop_all_processes() {
local timeout="${1:-15}"
local use_sudo=""
step "Stopping any running node processes..."
# Determine if we need sudo (processes may be owned by root)
if [[ $(id -u) -ne 0 ]]; then
if pgrep -f "pchaind|cosmovisor|push-validator" >/dev/null 2>&1; then
use_sudo="sudo"
fi
fi
# 1. Try graceful stop via manager first
if [[ -x "$MANAGER_BIN" ]]; then
$use_sudo "$MANAGER_BIN" stop < /dev/null >/dev/null 2>&1 || true
sleep 2
fi
# 2. Kill push-validator processes (logs, etc.)
$use_sudo pkill -f "push-validator" 2>/dev/null || true
# 3. Kill cosmovisor processes
$use_sudo pkill -f "cosmovisor.*run" 2>/dev/null || true
# 4. Kill pchaind processes
$use_sudo pkill -f "pchaind.*start" 2>/dev/null || true
# 5. Wait and verify all processes stopped
local elapsed=0
while [[ $elapsed -lt $timeout ]]; do
if ! pgrep -f "cosmovisor.*run" >/dev/null 2>&1 && \
! pgrep -f "pchaind.*start" >/dev/null 2>&1 && \
! pgrep -f "push-validator" >/dev/null 2>&1; then
ok "All processes stopped"
return 0
fi
sleep 1
((elapsed++))
done
# 6. Force kill if still running
verbose "Processes still running, force killing..."
$use_sudo pkill -9 -f "push-validator" 2>/dev/null || true
$use_sudo pkill -9 -f "cosmovisor.*run" 2>/dev/null || true
$use_sudo pkill -9 -f "pchaind.*start" 2>/dev/null || true
sleep 1
# 7. Final check
if pgrep -f "cosmovisor.*run" >/dev/null 2>&1 || \
pgrep -f "pchaind.*start" >/dev/null 2>&1; then
err "Failed to stop all processes"
return 1
fi
ok "All processes stopped"
return 0
}
# Helper: Check if any node processes are running (cosmovisor, pchaind, or push-validator)
any_node_running() {
pgrep -f "cosmovisor.*run" >/dev/null 2>&1 && return 0
pgrep -f "pchaind.*start" >/dev/null 2>&1 && return 0
pgrep -f "push-validator" >/dev/null 2>&1 && return 0
# Also check via manager status if available
if [[ -x "$MANAGER_BIN" ]]; then
node_running && return 0
fi
return 1
}
# Helper: Check if current node consensus key already exists in validator set
node_is_validator() {
local result
if ! result=$("$MANAGER_BIN" register-validator --check-only --output json < /dev/null 2>/dev/null); then
return 1
fi
if command -v jq >/dev/null 2>&1; then
local flag
flag=$(echo "$result" | jq -r '.registered // false' 2>/dev/null || echo "false")
[[ "$flag" == "true" ]] && return 0 || return 1
else
echo "$result" | grep -q '"registered"[[:space:]]*:[[:space:]]*true' && return 0 || return 1
fi
}
# Helper: Print useful commands
print_useful_cmds() {
echo
echo "Useful commands:"
echo " push-validator status # Check node status"
echo " push-validator logs # View logs"
echo " push-validator stop # Stop the node"
echo " push-validator restart # Restart the node"
echo " push-validator register-validator # Register as validator"
echo
}
# Helper: Prompt for user confirmation
prompt_yes_no() {
local prompt="$1"
local default="${2:-n}"
local response
if [[ "$default" == "y" ]]; then
echo -n "$prompt [Y/n]: "
else
echo -n "$prompt [y/N]: "
fi
read -r response
response=${response:-$default}
case "$response" in
[yY][eE][sS]|[yY]) return 0 ;;
*) return 1 ;;
esac
}
# Helper: Update shell profile with Go PATH
update_shell_profile() {
local go_install_dir="$1"
local profile_updated=0
# Detect shell and profile files
local shell_name="${SHELL##*/}"
local profile_files=()
case "$shell_name" in
bash)
profile_files=("$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile")
;;
zsh)
profile_files=("$HOME/.zshrc" "$HOME/.zprofile")
;;
*)
profile_files=("$HOME/.profile" "$HOME/.bashrc")
;;
esac
local go_path_line="export PATH=\"$go_install_dir/bin:\$PATH\""
for profile in "${profile_files[@]}"; do
if [[ -f "$profile" ]]; then
# Check if Go path already exists
if ! grep -q "$go_install_dir/bin" "$profile" 2>/dev/null; then
echo "" >> "$profile"
echo "# Added by Push Chain installer" >> "$profile"
echo "$go_path_line" >> "$profile"
profile_updated=1
verbose "Updated $profile with Go PATH"
break
else
verbose "Go PATH already in $profile"
profile_updated=1 # Mark as updated since PATH already exists
break
fi
fi
done
# Create .profile if no profile exists
if [[ $profile_updated -eq 0 ]] && [[ ${#profile_files[@]} -gt 0 ]]; then
local default_profile="${profile_files[0]}"
echo "" >> "$default_profile"
echo "# Added by Push Chain installer" >> "$default_profile"
echo "$go_path_line" >> "$default_profile"
verbose "Created $default_profile with Go PATH"
fi
# Export for current session
export PATH="$go_install_dir/bin:$PATH"
}
# Helper: Install Go automatically
install_go() {
local go_version="1.23.3"
local arch
local os="linux"
local download_url
local install_dir
local use_sudo=0
local temp_dir
# Detect architecture
case "$(uname -m)" in
x86_64|amd64)
arch="amd64"
;;
aarch64|arm64)
arch="arm64"
;;
armv7l)
arch="armv6l"
;;
*)
err "Unsupported architecture: $(uname -m)"
return 1
;;
esac
# Detect OS (already set to linux, but keeping for future macOS support)
if [[ "$OSTYPE" == "darwin"* ]]; then
os="darwin"
fi
download_url="https://go.dev/dl/go${go_version}.${os}-${arch}.tar.gz"
# Determine installation directory and sudo requirement
if [[ -w "/usr/local" ]]; then
install_dir="/usr/local"
use_sudo=0
elif command -v sudo >/dev/null 2>&1 && sudo -n true 2>/dev/null; then
install_dir="/usr/local"
use_sudo=1
else
# Install to user's home directory
install_dir="$HOME/.local"
use_sudo=0
mkdir -p "$install_dir"
fi
phase "Installing Go ${go_version}"
# Check if Go already exists at target location
if [[ -d "$install_dir/go" ]]; then
step "Backing up existing Go installation"
if [[ $use_sudo -eq 1 ]]; then
sudo mv "$install_dir/go" "$install_dir/go.backup.$(date +%s)" || true
else
mv "$install_dir/go" "$install_dir/go.backup.$(date +%s)" || true
fi
fi
# Create temp directory for download
temp_dir=$(mktemp -d)
trap "rm -rf '$temp_dir'" EXIT
step "Downloading Go ${go_version} for ${os}/${arch}"
if ! download_with_progress "$download_url" "$temp_dir/go.tar.gz"; then
err "Failed to download Go"
return 1
fi
step "Extracting Go to $install_dir"
if [[ $use_sudo -eq 1 ]]; then
sudo tar -C "$install_dir" -xzf "$temp_dir/go.tar.gz" || {
err "Failed to extract Go"
return 1
}
else
tar -C "$install_dir" -xzf "$temp_dir/go.tar.gz" || {
err "Failed to extract Go"
return 1
}
fi
# Update PATH for current session and shell profile
step "Updating PATH environment"
update_shell_profile "$install_dir/go"
# Verify installation
if "$install_dir/go/bin/go" version < /dev/null >/dev/null 2>&1; then
local installed_version
installed_version=$("$install_dir/go/bin/go" version < /dev/null | awk '{print $3}')
ok "Go installed successfully: $installed_version"
echo
echo -e "${GREEN}Go has been installed to: $install_dir/go${NC}"
echo -e "${YELLOW}Note: You may need to restart your shell or run: source ~/.bashrc${NC}"
echo
trap - EXIT # Clear the EXIT trap before returning
return 0
else
err "Go installation verification failed"
trap - EXIT # Clear the EXIT trap before returning
return 1
fi
}
# Install Go 1.23 to a temporary directory (for cosmovisor build with Go 1.26+ systems)
install_temp_go() {
local go_version="1.23.3"
local temp_dir="$1"
local arch os download_url
case "$(uname -m)" in
x86_64|amd64) arch="amd64" ;;
aarch64|arm64) arch="arm64" ;;
*) return 1 ;;
esac
os="linux"
[[ "$OSTYPE" == "darwin"* ]] && os="darwin"
download_url="https://go.dev/dl/go${go_version}.${os}-${arch}.tar.gz"
mkdir -p "$temp_dir"
if command -v curl >/dev/null 2>&1; then
curl -sL "$download_url" | tar -xzf - -C "$temp_dir" 2>/dev/null
else
wget -qO- "$download_url" | tar -xzf - -C "$temp_dir" 2>/dev/null
fi
[[ -x "$temp_dir/go/bin/go" ]]
}
# Helper: Download pchaind binary from GitHub releases
download_pchaind() {
local os arch version download_url checksum_url temp_dir filename ver_num
# Detect OS
case "$(uname -s)" in
Linux) os="linux" ;;
Darwin) os="darwin" ;;
*)
verbose "Unsupported OS for pre-built binary: $(uname -s)"
return 1
;;
esac
# Detect architecture
case "$(uname -m)" in
x86_64|amd64) arch="amd64" ;;
aarch64|arm64) arch="arm64" ;;
*)
verbose "Unsupported architecture for pre-built binary: $(uname -m)"
return 1
;;
esac
# Get version (use PCHAIN_REF if it looks like a version tag, otherwise fetch latest stable release)
if [[ "$PCHAIN_REF" =~ ^v[0-9] ]]; then
version="$PCHAIN_REF"
step "Using specified version: $version"
else
step "Fetching latest release version"
if command -v curl >/dev/null 2>&1; then
# Only use /releases/latest (stable releases, not pre-releases)
version=$(curl -sL https://api.github.com/repos/pushchain/push-chain-node/releases/latest 2>/dev/null | grep '"tag_name"' | head -1 | sed 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/' || true)
fi
if [[ -z "$version" ]]; then
verbose "Could not determine latest release version (no stable release found)"
return 1
fi
verbose "Latest release: $version"
fi
# Strip 'v' prefix for filename (v0.0.1 -> 0.0.1)
ver_num="${version#v}"
# Build download URL
# Format: push-chain_<version>_<os>_<arch>.tar.gz
filename="push-chain_${ver_num}_${os}_${arch}.tar.gz"
download_url="https://github.com/pushchain/push-chain-node/releases/download/${version}/${filename}"
checksum_url="${download_url}.sha256"
step "Downloading pchaind ${version} for ${os}/${arch}"
verbose "URL: $download_url"
# Create temp directory
temp_dir=$(mktemp -d)
# Use a subshell trap to clean up temp dir
(
trap "rm -rf '$temp_dir'" EXIT
# Download tarball with Go-style progress bar
if ! download_with_progress "$download_url" "$temp_dir/$filename"; then
verbose "Download failed"
exit 1
fi
# Verify file was downloaded and has content
if [[ ! -s "$temp_dir/$filename" ]]; then
verbose "Downloaded file is empty or missing"
exit 1
fi
# Verify checksum (optional but recommended)
if curl -sL -o "$temp_dir/checksum.sha256" "$checksum_url" 2>/dev/null && [[ -s "$temp_dir/checksum.sha256" ]]; then
step "Verifying checksum"
local expected_sum actual_sum
expected_sum=$(cat "$temp_dir/checksum.sha256" | awk '{print $1}')
if command -v sha256sum >/dev/null 2>&1; then
actual_sum=$(sha256sum "$temp_dir/$filename" | awk '{print $1}')
elif command -v shasum >/dev/null 2>&1; then
actual_sum=$(shasum -a 256 "$temp_dir/$filename" | awk '{print $1}')
fi
if [[ -n "$actual_sum" && -n "$expected_sum" ]]; then
if [[ "$expected_sum" != "$actual_sum" ]]; then
err "Checksum mismatch! Expected: $expected_sum, Got: $actual_sum"
exit 1
fi
ok "Checksum verified"
fi
else
verbose "Checksum file not available, skipping verification"
fi
# Extract tarball
step "Extracting binary"
if ! tar -xzf "$temp_dir/$filename" -C "$temp_dir" 2>/dev/null; then
verbose "Failed to extract tarball"
exit 1
fi
# Find pchaind binary in extracted files
local binary
binary=$(find "$temp_dir" -name "pchaind" -type f 2>/dev/null | head -1)
if [[ -z "$binary" || ! -f "$binary" ]]; then
verbose "pchaind binary not found in archive"
exit 1
fi
# Install binary directly to cosmovisor genesis directory
mkdir -p "$COSMOVISOR_GENESIS_BIN"
mkdir -p "$COSMOVISOR_DIR/upgrades"
rm -f "$COSMOVISOR_GENESIS_BIN/pchaind" 2>/dev/null || true
cp "$binary" "$COSMOVISOR_GENESIS_BIN/pchaind"
chmod +x "$COSMOVISOR_GENESIS_BIN/pchaind"
# Also copy libwasmvm if present (required on macOS)
local wasmlib
wasmlib=$(find "$temp_dir" -name "libwasmvm.dylib" -type f 2>/dev/null | head -1)
if [[ -n "$wasmlib" && -f "$wasmlib" ]]; then
rm -f "$COSMOVISOR_GENESIS_BIN/libwasmvm.dylib" 2>/dev/null || true
cp "$wasmlib" "$COSMOVISOR_GENESIS_BIN/libwasmvm.dylib"
fi
exit 0
)
local result=$?
# Clean up temp dir (in case subshell didn't)
rm -rf "$temp_dir" 2>/dev/null || true
if [[ $result -eq 0 ]]; then
# Verify installation
if [[ -x "$COSMOVISOR_GENESIS_BIN/pchaind" ]]; then
local installed_version
installed_version=$("$COSMOVISOR_GENESIS_BIN/pchaind" version < /dev/null 2>&1 | head -1 || echo "")
if [[ -n "$installed_version" ]]; then
ok "Installed pchaind ($installed_version)"
else
ok "Installed pchaind ${version}"
fi
return 0
fi
fi
return 1
}
# Helper: Download push-validator binary from GitHub releases
download_push_validator() {
local os arch version download_url checksum_url temp_dir filename ver_num
# Detect OS
case "$(uname -s)" in
Linux) os="linux" ;;
Darwin) os="darwin" ;;
*)
verbose "Unsupported OS for pre-built binary: $(uname -s)"
return 1
;;
esac
# Detect architecture
case "$(uname -m)" in
x86_64|amd64) arch="amd64" ;;
aarch64|arm64) arch="arm64" ;;
*)
verbose "Unsupported architecture for pre-built binary: $(uname -m)"
return 1
;;
esac
# Get version (use PNM_REF if it looks like a version tag, otherwise fetch latest release)
if [[ "$PNM_REF" =~ ^v[0-9] ]]; then
version="$PNM_REF"
step "Using specified version: $version"
else
step "Fetching latest release version"
if command -v curl >/dev/null 2>&1; then
version=$(curl -sL https://api.github.com/repos/pushchain/push-validator-cli/releases/latest 2>/dev/null | grep '"tag_name"' | head -1 | sed 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/' || true)
fi
if [[ -z "$version" ]]; then
verbose "Could not determine latest release version (no stable release found)"
return 1
fi
verbose "Latest release: $version"
fi
# Strip 'v' prefix for filename (v0.1.0 -> 0.1.0)
ver_num="${version#v}"
# Build download URL
# Format: push-validator_<version>_<os>_<arch>.tar.gz
filename="push-validator_${ver_num}_${os}_${arch}.tar.gz"
download_url="https://github.com/pushchain/push-validator-cli/releases/download/${version}/${filename}"
checksum_url="https://github.com/pushchain/push-validator-cli/releases/download/${version}/checksums.txt"
step "Downloading push-validator ${version} for ${os}/${arch}"
verbose "URL: $download_url"
# Create temp directory
temp_dir=$(mktemp -d)
# Use a subshell trap to clean up temp dir
(
trap "rm -rf '$temp_dir'" EXIT
# Download tarball with Go-style progress bar
if ! download_with_progress "$download_url" "$temp_dir/$filename"; then
verbose "Download failed"
exit 1
fi
# Verify file was downloaded and has content
if [[ ! -s "$temp_dir/$filename" ]]; then
verbose "Downloaded file is empty or missing"
exit 1
fi
# Verify checksum
if curl -sL -o "$temp_dir/checksums.txt" "$checksum_url" 2>/dev/null && [[ -s "$temp_dir/checksums.txt" ]]; then
step "Verifying checksum"
local expected_sum actual_sum
# Extract checksum for our specific file from checksums.txt
expected_sum=$(grep "$filename" "$temp_dir/checksums.txt" 2>/dev/null | awk '{print $1}' || true)
if command -v sha256sum >/dev/null 2>&1; then
actual_sum=$(sha256sum "$temp_dir/$filename" | awk '{print $1}')
elif command -v shasum >/dev/null 2>&1; then
actual_sum=$(shasum -a 256 "$temp_dir/$filename" | awk '{print $1}')
fi
if [[ -n "$actual_sum" && -n "$expected_sum" ]]; then
if [[ "$expected_sum" != "$actual_sum" ]]; then
err "Checksum mismatch! Expected: $expected_sum, Got: $actual_sum"
exit 1
fi
ok "Checksum verified"
fi
else
verbose "Checksum file not available, skipping verification"
fi
# Extract tarball
step "Extracting binary"
if ! tar -xzf "$temp_dir/$filename" -C "$temp_dir" 2>/dev/null; then
verbose "Failed to extract tarball"
exit 1
fi
# Find push-validator binary in extracted files
local binary
binary=$(find "$temp_dir" -name "push-validator" -type f 2>/dev/null | head -1)
if [[ -z "$binary" || ! -f "$binary" ]]; then
verbose "push-validator binary not found in archive"
exit 1
fi
# Install binary to target location
mkdir -p "$(dirname "$MANAGER_BIN")"
rm -f "$MANAGER_BIN" 2>/dev/null || true
cp "$binary" "$MANAGER_BIN"
chmod +x "$MANAGER_BIN"
exit 0
)
local result=$?
# Clean up temp dir (in case subshell didn't)
rm -rf "$temp_dir" 2>/dev/null || true
if [[ $result -eq 0 ]]; then
# Verify installation
if [[ -x "$MANAGER_BIN" ]]; then
local installed_version
installed_version=$("$MANAGER_BIN" version < /dev/null 2>&1 | awk '{print $2}' || echo "")
if [[ -n "$installed_version" ]]; then
ok "Installed push-validator ($installed_version)"
else
ok "Installed push-validator ${version}"
fi
return 0
fi
fi
return 1
}
clean_data_and_preserve_keys() {
local mode="$1"
local suffix="${2:-1}"
local wallet_backup
local validator_backup
wallet_backup=$(mktemp -d 2>/dev/null || echo "/tmp/pchain-wallet-backup-$$-$suffix")
validator_backup=$(mktemp -d 2>/dev/null || echo "/tmp/pchain-validator-backup-$$-$suffix")
if [[ "$mode" == "initial" ]]; then
if [[ -d "$HOME_DIR" ]]; then
step "Backing up wallet keys (your account credentials)"
mkdir -p "$wallet_backup"
local backed_wallet=0
for keyring_dir in "$HOME_DIR"/keyring-*; do
if [[ -d "$keyring_dir" ]]; then
cp -r "$keyring_dir" "$wallet_backup/" 2>/dev/null || true
backed_wallet=1
fi
done
if [[ $backed_wallet -eq 1 ]]; then
ok "Wallets backed up"
fi
fi
if [[ -d "$HOME_DIR/config" ]]; then
step "Backing up validator keys"
mkdir -p "$validator_backup"
cp "$HOME_DIR/config/priv_validator_key.json" "$validator_backup/" 2>/dev/null || true
cp "$HOME_DIR/config/node_key.json" "$validator_backup/" 2>/dev/null || true
if [[ -n "$(ls -A "$validator_backup" 2>/dev/null)" ]]; then
ok "Validator keys backed up"
fi
fi
else
step "Backing up wallet and validator keys"
mkdir -p "$wallet_backup" "$validator_backup"
for keyring_dir in "$HOME_DIR"/keyring-*; do
if [[ -d "$keyring_dir" ]]; then
cp -r "$keyring_dir" "$wallet_backup/" 2>/dev/null || true
fi
done
cp "$HOME_DIR/config/priv_validator_key.json" "$validator_backup/" 2>/dev/null || true
cp "$HOME_DIR/config/node_key.json" "$validator_backup/" 2>/dev/null || true
ok "Keys backed up to temporary location"
fi
if [[ "$mode" == "initial" ]]; then
step "Removing old installation"
rm -rf "$ROOT_DIR" 2>/dev/null || true
rm -rf "$HOME_DIR/data" 2>/dev/null || true
# Note: snapshot-cache/ is intentionally preserved to avoid re-downloading
rm -f "$HOME_DIR/pchaind.pid" 2>/dev/null || true
rm -f "$MANAGER_BIN" 2>/dev/null || true
rm -f "$INSTALL_BIN_DIR/pchaind" 2>/dev/null || true
rm -f "$HOME_DIR/.initial_state_sync" 2>/dev/null || true
rm -f "$HOME_DIR/.snapshot_downloaded" 2>/dev/null || true
rm -f "$HOME_DIR/config/config.toml" 2>/dev/null || true
rm -f "$HOME_DIR/config/app.toml" 2>/dev/null || true
rm -f "$HOME_DIR/config/addrbook.json" 2>/dev/null || true
rm -f "$HOME_DIR/config/genesis.json" 2>/dev/null || true
rm -f "$HOME_DIR/config/config.toml."*.bak 2>/dev/null || true
else
step "Cleaning all chain data (fixing potential corruption)"
rm -rf "$HOME_DIR/data" 2>/dev/null || true
# Note: snapshot-cache/ is intentionally preserved to avoid re-downloading
rm -f "$HOME_DIR/.initial_state_sync" 2>/dev/null || true
rm -f "$HOME_DIR/.snapshot_downloaded" 2>/dev/null || true
mkdir -p "$HOME_DIR/data"
echo '{"height":"0","round":0,"step":0}' > "$HOME_DIR/data/priv_validator_state.json"
fi
if [[ "$mode" == "initial" ]]; then
if [[ -d "$wallet_backup" && -n "$(ls -A "$wallet_backup" 2>/dev/null)" ]]; then
step "Restoring wallets"
mkdir -p "$HOME_DIR"
cp -r "$wallet_backup"/. "$HOME_DIR/" 2>/dev/null || true
ok "Wallets restored"
fi
if [[ -d "$validator_backup" && -n "$(ls -A "$validator_backup" 2>/dev/null)" ]]; then
step "Restoring validator keys"
mkdir -p "$HOME_DIR/config"
cp -r "$validator_backup"/. "$HOME_DIR/config/" 2>/dev/null || true
ok "Validator keys restored"
fi
else
step "Restoring wallet and validator keys"
mkdir -p "$HOME_DIR" "$HOME_DIR/config"
cp -r "$wallet_backup"/. "$HOME_DIR/" 2>/dev/null || true
cp "$validator_backup"/priv_validator_key.json "$HOME_DIR/config/" 2>/dev/null || true
cp "$validator_backup"/node_key.json "$HOME_DIR/config/" 2>/dev/null || true
echo "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$HOME_DIR/.initial_state_sync"
ok "Keys restored successfully"
fi
rm -rf "$wallet_backup" "$validator_backup" 2>/dev/null || true