-
Notifications
You must be signed in to change notification settings - Fork 23
/
i.py
1254 lines (960 loc) · 39.4 KB
/
i.py
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 os
import sys
import argparse
import subprocess
import platform
import random
import textwrap
import urllib.request as urlrq
import ssl
import json
import tempfile
from enum import Enum
DEFAULT_OSMOSIS_HOME = os.path.expanduser("~/.osmosisd")
DEFAULT_MONIKER = "osmosis"
NETWORK_CHOICES = ['osmosis-1', 'osmo-test-5']
INSTALL_CHOICES = ['node', 'client', 'localosmosis']
PRUNING_CHOICES = ['default', 'nothing', 'everything']
MAINNET_VERSION = "27.0.1"
TESTNET_VERSION = "27.0.1"
# CLI arguments
parser = argparse.ArgumentParser(description="Osmosis Installer")
parser.add_argument(
"--home",
type=str,
help=f"Osmosis installation location",
)
parser.add_argument(
'-m',
"--moniker",
type=str,
help="Moniker name for the node (Default: 'osmosis')",
)
parser.add_argument(
'-v',
'--verbose',
action='store_true',
help="Enable verbose output",
dest="verbose"
)
parser.add_argument(
'-o',
'--overwrite',
action='store_true',
help="Overwrite existing Osmosis home and binary without prompt",
dest="overwrite"
)
parser.add_argument(
'-n',
'--network',
type=str,
choices=NETWORK_CHOICES,
help=f"Network to join: {NETWORK_CHOICES})",
)
parser.add_argument(
'-p',
'--pruning',
type=str,
choices=PRUNING_CHOICES,
help=f"Pruning settings: {PRUNING_CHOICES})",
)
parser.add_argument(
'-i',
'--install',
type=str,
choices=INSTALL_CHOICES,
help=f"Which installation to do: {INSTALL_CHOICES})",
)
parser.add_argument(
"--binary_path",
type=str,
help=f"Path where to download the binary",
default="/usr/local/bin"
)
parser.add_argument(
'-c',
'--cosmovisor',
action='store_true',
help="Install cosmovisor"
)
parser.add_argument(
'-s',
'--service',
action='store_true',
help="Setup systemd service (Linux only)"
)
args = parser.parse_args()
# Choices
class InstallChoice(str, Enum):
NODE = "1"
CLIENT = "2"
LOCALOSMOSIS = "3"
class NetworkChoice(str, Enum):
MAINNET = "1"
TESTNET = "2"
class PruningChoice(str, Enum):
DEFAULT = "1"
NOTHING = "2"
EVERYTHING = "3"
class Answer(str, Enum):
YES = "1"
NO = "2"
# Network configurations
class Network:
def __init__(self, chain_id, version, genesis_url, binary_url, peers, rpc_node, addrbook_url, snapshot_url):
self.chain_id = chain_id
self.version = version
self.genesis_url = genesis_url
self.binary_url = binary_url
self.peers = peers
self.rpc_node = rpc_node
self.addrbook_url = addrbook_url
self.snapshot_url = snapshot_url
TESTNET = Network(
chain_id = "osmo-test-5",
version = f"v${TESTNET_VERSION}",
genesis_url = "https://osmosis.fra1.digitaloceanspaces.com/osmo-test-5/genesis.json",
binary_url = {
"linux": {
"amd64": f"https://osmosis.fra1.digitaloceanspaces.com/binaries/v{TESTNET_VERSION}/osmosisd-{TESTNET_VERSION}-linux-amd64",
"arm64": f"https://osmosis.fra1.digitaloceanspaces.com/binaries/v{TESTNET_VERSION}/osmosisd-{TESTNET_VERSION}-linux-arm64"
},
"darwin": {
"amd64": f"https://osmosis.fra1.digitaloceanspaces.com/binaries/v{TESTNET_VERSION}/osmosisd-{TESTNET_VERSION}-darwin-amd64",
"arm64": f"https://osmosis.fra1.digitaloceanspaces.com/binaries/v{TESTNET_VERSION}/osmosisd-{TESTNET_VERSION}-darwin-arm64"
},
},
peers = [
"[email protected]:26656",
"[email protected]:26656",
"[email protected]:26656",
"[email protected]:26656",
"ade4d8bc,[email protected]:12556",
],
rpc_node = "https://rpc.testnet.osmosis.zone:443",
addrbook_url = "https://rpc.testnet.osmosis.zone/addrbook",
snapshot_url = "https://snapshots.testnet.osmosis.zone/latest"
)
MAINNET = Network(
chain_id = "osmosis-1",
version = f"v{MAINNET_VERSION}",
genesis_url = "https://osmosis.fra1.digitaloceanspaces.com/osmosis-1/genesis.json",
binary_url = {
"linux": {
"amd64": f"https://osmosis.fra1.digitaloceanspaces.com/binaries/v{MAINNET_VERSION}/osmosisd-{MAINNET_VERSION}-linux-amd64",
"arm64": f"https://osmosis.fra1.digitaloceanspaces.com/binaries/v{MAINNET_VERSION}/osmosisd-{MAINNET_VERSION}-linux-arm64"
},
"darwin": {
"amd64": f"https://osmosis.fra1.digitaloceanspaces.com/binaries/v{MAINNET_VERSION}/osmosisd-{MAINNET_VERSION}-darwin-amd64",
"arm64": f"https://osmosis.fra1.digitaloceanspaces.com/binaries/v{MAINNET_VERSION}/osmosisd-{MAINNET_VERSION}-darwin-arm64"
},
},
peers = None,
rpc_node = "https://rpc.osmosis.zone:443",
addrbook_url = "https://rpc.osmosis.zone/addrbook",
snapshot_url = "https://snapshots.osmosis.zone/latest"
)
COSMOVISOR_URL = {
"darwin": {
"amd64": "https://osmosis.fra1.digitaloceanspaces.com/binaries/cosmovisor/cosmovisor-v1.2.0-darwin-amd64",
"arm64": "https://osmosis.fra1.digitaloceanspaces.com/binaries/cosmovisor/cosmovisor-v1.2.0-darwin-arm64"
},
"linux": {
"amd64": "https://osmosis.fra1.digitaloceanspaces.com/binaries/cosmovisor/cosmovisor-v1.2.0-linux-amd64",
"arm64": "https://osmosis.fra1.digitaloceanspaces.com/binaries/cosmovisor/cosmovisor-v1.2.0-linux-arm64"
}
}
# Terminal utils
class bcolors:
OKGREEN = '\033[92m'
RED = '\033[91m'
ENDC = '\033[0m'
PURPLE = '\033[95m'
def clear_screen():
os.system('clear')
# Messages
def welcome_message():
print(bcolors.OKGREEN + """
██████╗ ███████╗███╗ ███╗ ██████╗ ███████╗██╗███████╗
██╔═══██╗██╔════╝████╗ ████║██╔═══██╗██╔════╝██║██╔════╝
██║ ██║███████╗██╔████╔██║██║ ██║███████╗██║███████╗
██║ ██║╚════██║██║╚██╔╝██║██║ ██║╚════██║██║╚════██║
╚██████╔╝███████║██║ ╚═╝ ██║╚██████╔╝███████║██║███████║
╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝╚══════╝
Welcome to the Osmosis node installer!
For more information, please visit https://docs.osmosis.zone
If you have an old Osmosis installation,
- backup any important data before proceeding
- ensure that no osmosis services are running in the background
""" + bcolors.ENDC)
def client_complete_message(osmosis_home):
print(bcolors.OKGREEN + """
✨ Congratulations! You have successfully completed setting up an Osmosis client! ✨
""" + bcolors.ENDC)
print("🧪 Try running: " + bcolors.OKGREEN + f"osmosisd status --home {osmosis_home}" + bcolors.ENDC)
print()
def node_complete_message(using_cosmovisor, using_service, osmosis_home):
print(bcolors.OKGREEN + """
✨ Congratulations! You have successfully completed setting up an Osmosis node! ✨
""" + bcolors.ENDC)
if using_service:
if using_cosmovisor:
print("🧪 To start the cosmovisor service run: ")
print(bcolors.OKGREEN + f"sudo systemctl start cosmovisor" + bcolors.ENDC)
else:
print("🧪 To start the osmosisd service run: ")
print(bcolors.OKGREEN + f"sudo systemctl start osmosisd" + bcolors.ENDC)
else:
if using_cosmovisor:
print("🧪 To start cosmovisor run: ")
print(bcolors.OKGREEN + f"DAEMON_NAME=osmosisd DAEMON_HOME={osmosis_home} cosmovisor run start" + bcolors.ENDC)
else:
print("🧪 To start osmosisd run: ")
print(bcolors.OKGREEN + f"osmosisd start --home {osmosis_home}" + bcolors.ENDC)
print()
# Options
def select_install():
# Check if setup is specified in args
if args.install:
if args.install == "node":
choice = InstallChoice.NODE
elif args.install == "client":
choice = InstallChoice.CLIENT
elif args.install == "localosmosis":
choice = InstallChoice.LOCALOSMOSIS
else:
print(bcolors.RED + f"Invalid setup {args.install}. Please choose a valid setup.\n" + bcolors.ENDC)
sys.exit(1)
else:
print(bcolors.OKGREEN + """
Please choose the desired installation:
1) node - run an osmosis node and join mainnet or testnet
2) client - setup osmosisd to query a public node
3) localosmosis - setup a local osmosis development node
💡 You can select the installation using the --install flag.
""" + bcolors.ENDC)
while True:
choice = input("Enter your choice, or 'exit' to quit: ").strip()
if choice.lower() == "exit":
print("Exiting the program...")
sys.exit(0)
if choice not in [InstallChoice.NODE, InstallChoice.CLIENT, InstallChoice.LOCALOSMOSIS]:
print("Invalid input. Please choose a valid option.")
else:
break
if args.verbose:
clear_screen()
print(f"Chosen install: {INSTALL_CHOICES[int(choice) - 1]}")
clear_screen()
return choice
def select_network():
"""
Selects a network based on user input or command-line arguments.
Returns:
chosen_network (NetworkChoice): The chosen network, either MAINNET or TESTNET.
Raises:
SystemExit: If an invalid network is specified or the user chooses to exit the program.
"""
# Check if network is specified in args
if args.network:
if args.network == MAINNET.chain_id:
choice = NetworkChoice.MAINNET
elif args.network == TESTNET.chain_id:
choice = NetworkChoice.TESTNET
else:
print(bcolors.RED + f"Invalid network {args.network}. Please choose a valid network." + bcolors.ENDC)
sys.exit(1)
# If not, ask the user to choose a network
else:
print(bcolors.OKGREEN + f"""
Please choose the desired network:
1) Mainnet ({MAINNET.chain_id})
2) Testnet ({TESTNET.chain_id})
💡 You can select the network using the --network flag.
""" + bcolors.ENDC)
while True:
choice = input("Enter your choice, or 'exit' to quit: ").strip()
if choice.lower() == "exit":
print("Exiting the program...")
sys.exit(0)
if choice not in [NetworkChoice.MAINNET, NetworkChoice.TESTNET]:
print(bcolors.RED + "Invalid input. Please choose a valid option. Accepted values: [ 1 , 2 ] \n" + bcolors.ENDC)
else:
break
if args.verbose:
clear_screen()
print(f"Chosen network: {NETWORK_CHOICES[int(choice) - 1]}")
clear_screen()
return choice
def select_osmosis_home():
"""
Selects the path for running the 'osmosisd init --home <SELECTED_HOME>' command.
Returns:
osmosis_home (str): The selected path.
"""
if args.home:
osmosis_home = args.home
else:
default_home = os.path.expanduser("~/.osmosisd")
print(bcolors.OKGREEN + f"""
Do you want to install Osmosis in the default location?:
1) Yes, use default location {DEFAULT_OSMOSIS_HOME} (recommended)
2) No, specify custom location
💡 You can specify the home using the --home flag.
""" + bcolors.ENDC)
while True:
choice = input("Enter your choice, or 'exit' to quit: ").strip()
if choice.lower() == "exit":
print("Exiting the program...")
sys.exit(0)
if choice == Answer.YES:
osmosis_home = default_home
break
elif choice == Answer.NO:
while True:
custom_home = input("Enter the path for Osmosis home: ").strip()
if custom_home != "":
osmosis_home = custom_home
break
else:
print("Invalid path. Please enter a valid directory.")
break
else:
print("Invalid choice. Please enter 1 or 2.")
clear_screen()
return osmosis_home
def select_moniker():
"""
Selects the moniker for the Osmosis node.
Returns:
moniker (str): The selected moniker.
"""
if args.moniker:
moniker = args.moniker
else:
print(bcolors.OKGREEN + f"""
Do you want to use the default moniker?
1) Yes, use default moniker ({DEFAULT_MONIKER})
2) No, specify custom moniker
💡 You can specify the moniker using the --moniker flag.
""" + bcolors.ENDC)
while True:
choice = input("Enter your choice, or 'exit' to quit: ").strip()
if choice.lower() == "exit":
print("Exiting the program...")
sys.exit(0)
if choice == Answer.YES:
moniker = DEFAULT_MONIKER
break
elif choice == Answer.NO:
while True:
custom_moniker = input("Enter the custom moniker: ")
if custom_moniker.strip() != "":
moniker = custom_moniker
break
else:
print("Invalid moniker. Please enter a valid moniker.")
break
else:
print("Invalid choice. Please enter 1 or 2.")
clear_screen()
return moniker
def initialize_osmosis_home(osmosis_home, moniker):
"""
Initializes the Osmosis home directory with the specified moniker.
Args:
osmosis_home (str): The chosen home directory.
moniker (str): The moniker for the Osmosis node.
"""
if not args.overwrite:
while True:
print(bcolors.OKGREEN + f"""
Do you want to initialize the Osmosis home directory at '{osmosis_home}'?
""" + bcolors.ENDC, end="")
print(bcolors.RED + f"""
⚠️ All contents of the directory will be deleted.
""" + bcolors.ENDC, end="")
print(bcolors.OKGREEN + f"""
1) Yes, proceed with initialization
2) No, quit
💡 You can overwrite the osmosis home using --overwrite flag.
""" + bcolors.ENDC)
choice = input("Enter your choice, or 'exit' to quit: ").strip()
if choice.lower() == "exit":
print("Exiting the program...")
sys.exit(0)
if choice == Answer.YES:
break
elif choice == Answer.NO:
sys.exit(0)
else:
print("Invalid choice. Please enter 1 or 2.")
print(f"Initializing Osmosis home directory at '{osmosis_home}'...")
try:
subprocess.run(
["rm", "-rf", osmosis_home],
stderr=subprocess.DEVNULL, check=True)
subprocess.run(
["osmosisd", "init", moniker, "-o", "--home", osmosis_home],
stderr=subprocess.DEVNULL, check=True)
print("Initialization completed successfully.")
except subprocess.CalledProcessError as e:
print("Initialization failed.")
print("Please check if the home directory is valid and has write permissions.")
print(e)
sys.exit(1)
clear_screen()
def select_pruning(osmosis_home):
"""
Allows the user to choose pruning settings and performs actions based on the selected option.
"""
# Check if pruning settings are specified in args
if args.pruning:
if args.pruning == "default":
choice = PruningChoice.DEFAULT
elif args.pruning == "nothing":
choice = PruningChoice.NOTHING
elif args.pruning == "everything":
choice = PruningChoice.EVERYTHING
else:
print(bcolors.RED + f"Invalid pruning setting {args.pruning}. Please choose a valid setting.\n" + bcolors.ENDC)
sys.exit(1)
else:
print(bcolors.OKGREEN + """
Please choose your desired pruning settings:
1) Default: (keep last 100,000 states to query the last week worth of data and prune at 100 block intervals)
2) Nothing: (keep everything, select this if running an archive node)
3) Everything: (keep last 10,000 states and prune at a random prime block interval)
💡 You can select the pruning settings using the --pruning flag.
""" + bcolors.ENDC)
while True:
choice = input("Enter your choice, or 'exit' to quit: ").strip()
if choice.lower() == "exit":
print("Exiting the program...")
sys.exit(0)
if choice not in [PruningChoice.DEFAULT, PruningChoice.NOTHING, PruningChoice.EVERYTHING]:
print("Invalid input. Please choose a valid option.")
else:
break
if args.verbose:
clear_screen()
print(f"Chosen setting: {PRUNING_CHOICES[int(choice) - 1]}")
app_toml = os.path.join(osmosis_home, "config", "app.toml")
if choice == PruningChoice.DEFAULT:
# Nothing to do
pass
elif choice == PruningChoice.NOTHING:
subprocess.run(["sed -i -E 's/pruning = \"default\"/pruning = \"nothing\"/g' " + app_toml], shell=True)
elif choice == PruningChoice.EVERYTHING:
primeNum = random.choice([x for x in range(11, 97) if not [t for t in range(2, x) if not x % t]])
subprocess.run(["sed -i -E 's/pruning = \"default\"/pruning = \"custom\"/g' " + app_toml], shell=True)
subprocess.run(["sed -i -E 's/pruning-keep-recent = \"0\"/pruning-keep-recent = \"10000\"/g' " + app_toml], shell=True)
subprocess.run(["sed -i -E 's/pruning-interval = \"0\"/pruning-interval = \"" + str(primeNum) + "\"/g' " + app_toml], shell=True)
else:
print(bcolors.RED + f"Invalid pruning setting {choice}. Please choose a valid setting.\n" + bcolors.ENDC)
sys.exit(1)
clear_screen()
def customize_config(home, network):
"""
Customizes the TOML configurations based on the network.
Args:
home (str): The home directory.
network (str): The network identifier.
"""
# osmo-test-5 configuration
if network == NetworkChoice.TESTNET:
# patch client.toml
client_toml = os.path.join(home, "config", "client.toml")
with open(client_toml, "r") as config_file:
lines = config_file.readlines()
for i, line in enumerate(lines):
if line.startswith("chain-id"):
lines[i] = f'chain-id = "{TESTNET.chain_id}"\n'
elif line.startswith("node"):
lines[i] = f'node = "{TESTNET.rpc_node}"\n'
with open(client_toml, "w") as config_file:
config_file.writelines(lines)
# patch config.toml
config_toml = os.path.join(home, "config", "config.toml")
peers = ','.join(TESTNET.peers)
subprocess.run(["sed -i -E 's/persistent_peers = \"\"/persistent_peers = \"" + peers + "\"/g' " + config_toml], shell=True)
# osmosis-1 configuration
elif network == NetworkChoice.MAINNET:
client_toml = os.path.join(home, "config", "client.toml")
with open(client_toml, "r") as config_file:
lines = config_file.readlines()
for i, line in enumerate(lines):
if line.startswith("chain-id"):
lines[i] = f'chain-id = "{MAINNET.chain_id}"\n'
elif line.startswith("node"):
lines[i] = f'node = "{MAINNET.rpc_node}"\n'
with open(client_toml, "w") as config_file:
config_file.writelines(lines)
else:
print(bcolors.RED + f"Invalid network {network}. Please choose a valid setting.\n" + bcolors.ENDC)
sys.exit(1)
clear_screen()
def download_binary(network):
"""
Downloads the binary for the specified network based on the operating system and architecture.
Args:
network (NetworkChoice): The network type, either MAINNET or TESTNET.
Raises:
SystemExit: If the binary download URL is not available for the current operating system and architecture.
"""
binary_path = os.path.join(args.binary_path, "osmosisd")
if not args.overwrite:
# Check if osmosisd is already installed
try:
subprocess.run([binary_path, "version"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print("osmosisd is already installed at " + bcolors.OKGREEN + f"{binary_path}" + bcolors.ENDC)
while True:
choice = input("Do you want to skip the download or overwrite the binary? (skip/overwrite): ").strip().lower()
if choice == "skip":
print("Skipping download.")
return
elif choice == "overwrite":
print("Proceeding with overwrite.")
break
else:
print("Invalid input. Please enter 'skip' or 'overwrite'.")
except FileNotFoundError:
print("osmosisd is not installed. Proceeding with download.")
operating_system = platform.system().lower()
architecture = platform.machine()
if architecture == "x86_64":
architecture = "amd64"
elif architecture == "aarch64":
architecture = "arm64"
if architecture not in ["arm64", "amd64"]:
print(f"Unsupported architecture {architecture}.")
sys.exit(1)
if network == NetworkChoice.TESTNET:
binary_urls = TESTNET.binary_url
else:
binary_urls = MAINNET.binary_url
if operating_system in binary_urls and architecture in binary_urls[operating_system]:
binary_url = binary_urls[operating_system][architecture]
else:
print(f"Binary download URL not available for {operating_system}/{architecture}")
sys.exit(0)
try:
print("Downloading " + bcolors.PURPLE + "osmosisd" + bcolors.ENDC, end="\n\n")
print("from " + bcolors.OKGREEN + f"{binary_url}" + bcolors.ENDC, end=" ")
print("to " + bcolors.OKGREEN + f"{binary_path}" + bcolors.ENDC)
print()
print(bcolors.OKGREEN + "💡 You can change the path using --binary_path" + bcolors.ENDC)
subprocess.run(["wget", binary_url, "-q", "-O", "/tmp/osmosisd"], check=True)
os.chmod("/tmp/osmosisd", 0o755)
if platform.system() == "Linux":
subprocess.run(["sudo", "mv", "/tmp/osmosisd", binary_path], check=True)
subprocess.run(["sudo", "chown", f"{os.environ['USER']}:{os.environ['USER']}", binary_path], check=True)
subprocess.run(["sudo", "chmod", "+x", binary_path], check=True)
else:
subprocess.run(["mv", "/tmp/osmosisd", binary_path], check=True)
# Test binary
subprocess.run(["osmosisd", "version"], check=True)
print("Binary downloaded successfully.")
except subprocess.CalledProcessError as e:
print(e)
print("Failed to download the binary.")
sys.exit(1)
clear_screen()
def download_genesis(network, osmosis_home):
"""
Downloads the genesis file for the specified network.
Args:
network (NetworkChoice): The network type, either MAINNET or TESTNET.
osmosis_home (str): The path to the Osmosis home directory.
Raises:
SystemExit: If the genesis download URL is not available for the current network.
"""
if network == NetworkChoice.TESTNET:
genesis_url = TESTNET.genesis_url
else:
genesis_url = MAINNET.genesis_url
if genesis_url:
try:
print("Downloading " + bcolors.PURPLE + "genesis.json" + bcolors.ENDC + f" from {genesis_url}")
genesis_path = os.path.join(osmosis_home, "config", "genesis.json")
subprocess.run(["wget", genesis_url, "-q", "-O", genesis_path], check=True)
print("Genesis downloaded successfully.\n")
except subprocess.CalledProcessError:
print("Failed to download the genesis.")
sys.exit(1)
def download_addrbook(network, osmosis_home):
"""
Downloads the addrbook for the specified network.
Args:
network (NetworkChoice): The network type, either MAINNET or TESTNET.
osmosis_home (str): The path to the Osmosis home directory.
Raises:
SystemExit: If the genesis download URL is not available for the current network.
"""
if network == NetworkChoice.TESTNET:
addrbook_url = TESTNET.addrbook_url
else:
addrbook_url = MAINNET.addrbook_url
if addrbook_url:
try:
print("Downloading " + bcolors.PURPLE + "addrbook.json" + bcolors.ENDC + f" from {addrbook_url}")
addrbook_path = os.path.join(osmosis_home, "config", "addrbook.json")
subprocess.run(["wget", addrbook_url, "-q", "-O", addrbook_path], check=True)
print("Addrbook downloaded successfully.")
except subprocess.CalledProcessError:
print("Failed to download the addrbook.")
sys.exit(1)
clear_screen()
def download_snapshot(network, osmosis_home):
"""
Downloads the snapshot for the specified network.
Args:
network (NetworkChoice): The network type, either MAINNET or TESTNET.
osmosis_home (str): The path to the Osmosis home directory.
Raises:
SystemExit: If the genesis download URL is not available for the current network.
"""
def install_snapshot_prerequisites():
"""
Installs the prerequisites: Homebrew (brew) package manager and lz4 compression library.
Args:
osmosis_home (str): The path of the Osmosis home directory.
"""
while True:
print(bcolors.OKGREEN + f"""
To download the snapshot, we need the lz4 compression library.
Do you want me to install it?
1) Yes, install lz4
2) No, continue without installing lz4
""" + bcolors.ENDC)
choice = input("Enter your choice, or 'exit' to quit: ").strip()
if choice.lower() == "exit":
print("Exiting the program...")
sys.exit(0)
if choice == Answer.YES:
break
elif choice == Answer.NO:
clear_screen()
return
else:
print("Invalid choice. Please enter 1 or 2.")
operating_system = platform.system().lower()
if operating_system == "linux":
print("Installing lz4...")
subprocess.run(["sudo apt-get install wget liblz4-tool aria2 -y"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True)
else:
print("Installing Homebrew...")
subprocess.run(['bash', '-c', '$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)'])
print("Installing lz4...")
subprocess.run(['brew', 'install', 'lz4'])
print("Installation completed successfully.")
clear_screen()
def parse_snapshot_info(network):
"""
Creates a dictionary containing the snapshot information for the specified network.
It merges the snapshot information from the osmosis official snapshot JSON and
quicksync from chianlayer https://dl2.quicksync.io/json/osmosis.json
Returns:
dict: Dictionary containing the parsed snapshot information.
"""
snapshot_info = []
if network == NetworkChoice.TESTNET:
snapshot_url = TESTNET.snapshot_url
chain_id = TESTNET.chain_id
quicksync_prefix = "osmotestnet-5"
elif network == NetworkChoice.MAINNET:
snapshot_url = MAINNET.snapshot_url
chain_id = MAINNET.chain_id
quicksync_prefix = "osmosis-1"
else:
print(f"Invalid network choice - {network}")
sys.exit(1)
# Set SSL context
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
req = urlrq.Request(snapshot_url, headers={'User-Agent': 'Mozilla/5.0'})
resp = urlrq.urlopen(req, context=context)
latest_snapshot_url = resp.read().decode()
snapshot_info.append({
"network": chain_id,
"mirror": "Germany",
"url": latest_snapshot_url.rstrip('\n'),
"type": "pruned",
"provider": "osmosis"
})
# Parse quicksync snapshot json
try:
url = "https://dl2.quicksync.io/json/osmosis.json"
resp = urlrq.urlopen(url, context=context)
data = resp.read().decode()
snapshots = json.loads(data)
for snapshot in snapshots:
if not snapshot["file"].startswith(quicksync_prefix):
continue
snapshot_info.append({
"network": chain_id,
"mirror": snapshot["mirror"],
"url": snapshot["url"],
"type": snapshot["network"],
"provider": "chainlayer"
})
except (urlrq.URLError, json.JSONDecodeError) as e:
print(f"Error: Failed to fetch or parse snapshot JSON - {e}")
return snapshot_info
def print_snapshot_download_info(snapshot_info):
"""
Prints the information about the snapshot download.
"""
print(bcolors.OKGREEN + f"""
Choose one of the following snapshots:
""" + bcolors.ENDC)
# Prepare table headers
column_widths = [1, 12, 12, 12]
headers = ["#", "Provider", "Location", "Type"]
header_row = " | ".join(f"{header:{width}}" for header, width in zip(headers, column_widths))
# Print table header
print(header_row)
print("-" * len(header_row))
# Print table content
for idx, snapshot in enumerate(snapshot_info):
row_data = [str(idx + 1), snapshot["provider"], snapshot["mirror"], snapshot["type"]]
wrapped_data = [textwrap.fill(data, width=width) for data, width in zip(row_data, column_widths)]
formatted_row = " | ".join(f"{data:{width}}" for data, width in zip(wrapped_data, column_widths))
print(formatted_row)
print()
install_snapshot_prerequisites()
snapshots = parse_snapshot_info(network)
while True:
print_snapshot_download_info(snapshots)
choice = input("Enter your choice, or 'exit' to quit: ").strip()
if choice.lower() == "exit":
print("Exiting the program...")
sys.exit(0)
if int(choice) < 0 or int(choice) > len(snapshots):
clear_screen()
print(bcolors.RED + "Invalid input. Please choose a valid option." + bcolors.ENDC)
else:
break
snapshot_url = snapshots[int(choice) - 1]['url']
try:
print(f"\n🔽 Downloading snapshots from {snapshot_url}")
download_process = subprocess.Popen(["wget", "-q", "-O", "-", snapshot_url], stdout=subprocess.PIPE)
lz4_process = subprocess.Popen(["lz4", "-d"], stdin=download_process.stdout, stdout=subprocess.PIPE)
tar_process = subprocess.Popen(["tar", "-C", osmosis_home, "-xf", "-"], stdin=lz4_process.stdout, stdout=subprocess.PIPE)
tar_process.wait()
print("Snapshot download and extraction completed successfully.")
except subprocess.CalledProcessError as e:
print("Failed to download the snapshot.")
print(f"Error: {e}")
sys.exit(1)
clear_screen()
def download_cosmovisor(osmosis_home):
"""
Downloads and installs cosmovisor.
Returns:
use_cosmovisor(bool): Whether to use cosmovisor or not.
"""
if not args.cosmovisor:
print(bcolors.OKGREEN + f"""
Do you want to install cosmovisor?
1) Yes, download and install cosmovisor (default)
2) No
💡 You can specify the cosmovisor setup using the --cosmovisor flag.
""" + bcolors.ENDC)
while True:
choice = input("Enter your choice, or 'exit' to quit: ").strip()
if choice.lower() == "exit":