Skip to content

Commit

Permalink
Adding ExpandPath as argparse Action + cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
pbukva committed Jun 12, 2024
1 parent f4e0c4c commit 99b33df
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 141 deletions.
14 changes: 6 additions & 8 deletions scripts/devgenesis.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import sys
from genesis_helpers import (
get_balance,
get_path,
get_unjailed_validator,
set_balance,
ensure_account,
Expand All @@ -22,12 +21,13 @@
get_account_address_by_name,
get_account,
pubkey_to_bech32_address,
ExpandPath,
)
from replace_validator import replace_validator_keys_recur
from replace_validator import replace_validator_keys_recursive
from typing import Tuple


DEFAULT_HOME_PATH = os.path.expanduser("~") + "/.fetchd"
DEFAULT_HOME_PATH = os.path.expanduser("~/.fetchd")
DEFAULT_VALIDATOR_KEY_NAME = "validator"
FUND_BALANCE = 10**23
DEFAULT_VOTING_PERIOD = "60s"
Expand All @@ -45,8 +45,8 @@ def parse_commandline() -> Tuple[ap.Namespace, ap.ArgumentParser]:
"--home",
help="The path to the local node data i.e. ~/.fetchd",
default=DEFAULT_HOME_PATH,
)
parser.add_argument("genesis_file_path", type=str, help="The path to the genesis file")
action=ExpandPath)
parser.add_argument("genesis_file_path", type=str, help="The path to the genesis file", action=ExpandPath)

subparsers = parser.add_subparsers(help='sub-command help')

Expand All @@ -65,7 +65,6 @@ def parse_commandline() -> Tuple[ap.Namespace, ap.ArgumentParser]:
The updated genesis will be written under node_home_dir/config/genesis.json, allowing
the local chain to be started with."""
)
#parser_single_validator.add_argument("genesis", type=get_path, help="The path to the genesis file",)
parser_single_validator.add_argument(
"--validator_key_name",
help="The name of the local key to use for the validator",
Expand All @@ -82,7 +81,6 @@ def parse_commandline() -> Tuple[ap.Namespace, ap.ArgumentParser]:
'replace_validator_keys',
help='Replace consensus and operator keys of given validator',
description="This script replaces a validator in the genesis file based on provided public keys and addresses.")
#parser_replace_validator_keys.add_argument("genesis", type=str, help="The path to the genesis file")
parser_replace_validator_keys.add_argument(
"src_validator_pubkey",
type=str,
Expand Down Expand Up @@ -269,7 +267,7 @@ def replace_validator_keys(args: ap.Namespace):
"New operator account already existed before - it is recommended to generate new operator key"
)

replace_validator_keys_recur(
replace_validator_keys_recursive(
genesis=genesis,
src_validator_pubkey=args.src_validator_pubkey,
dest_validator_pubkey=args.dest_validator_pubkey,
Expand Down
7 changes: 7 additions & 0 deletions scripts/genesis_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@
import bech32
import sys
from Crypto.Hash import RIPEMD160 # type: ignore # nosec
from argparse import Action


class ExpandPath(Action):
def __call__(self, parser, namespace, values, option_string=None):
path = os.path.abspath(os.path.expanduser(values))
setattr(namespace, self.dest, path)


def sha256(contents: bytes) -> bytes:
Expand Down
45 changes: 43 additions & 2 deletions scripts/poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions scripts/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ authors = ["Jiří Vestfál <jiri.vestfal@fetch.ai>"]
[tool.poetry.dependencies]
python = "^3.10"
bech32 = "1.2.0"
#pycrypto = "2.6.1"
pycryptodome = "3.20.0"

[build-system]
requires = ["poetry-core"]
Expand Down
137 changes: 6 additions & 131 deletions scripts/replace_validator.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
#import json
#import re
from typing import Optional, Mapping, Any

from typing import Mapping, Any
from genesis_helpers import (
#load_json_file,
get_staking_validator_info,
validator_pubkey_to_valcons_address,
validator_pubkey_to_hex_address,
Expand All @@ -14,123 +12,6 @@
)


#def replace_validator_keys(genesis_file_path: str,
# src_validator_pubkey: str,
# dest_validator_pubkey: str,
# dest_validator_operator_pubkey: str,
# output_genesis_file_path: Optional[str] = None,
# ):
# print(" Genesis Path:", genesis_file_path)
# print("Source Validator PK:", src_validator_pubkey)
# print("Destination Validator PK:", dest_validator_pubkey)
# print("Destination Operator PK:", dest_validator_operator_pubkey)
#
# # Load the genesis file
# print("Reading genesis file...")
# genesis = load_json_file(genesis_file_path)
# print("Reading genesis file...complete")
#
# # Input values #
# target_staking_val_info = get_staking_validator_info(
# genesis, src_validator_pubkey
# )
# target_val_info = get_validator_info(genesis, src_validator_pubkey)
#
# target_val_pubkey = target_staking_val_info["consensus_pubkey"]["key"]
# target_consensus_address = validator_pubkey_to_valcons_address(target_val_pubkey)
#
# target_operator_address = target_staking_val_info["operator_address"]
# target_operator_base_address = convert_to_base(target_operator_address)
#
# # Output values #
# dest_validator_hex_addr = validator_pubkey_to_hex_address(
# dest_validator_pubkey
# )
# dest_consensus_address = validator_pubkey_to_valcons_address(
# dest_validator_pubkey
# )
#
# dest_operator_base_address = pubkey_to_bech32_address(
# dest_validator_operator_pubkey, "fetch"
# )
# dest_operator_valoper_address = convert_to_valoper(dest_operator_base_address)
#
# # Replacements
#
# # Replace validator hex address and pubkey
# target_val_info["address"] = dest_validator_hex_addr
# target_val_info["pub_key"]["value"] = dest_validator_pubkey
# target_staking_val_info["consensus_pubkey"]["key"] = dest_validator_pubkey
#
# # Ensure that operator is not already registered in auth module:
# new_operator_has_account = get_account(genesis, dest_operator_base_address)
#
# if new_operator_has_account:
# print(
# "New operator account already existed before - it is recommended to generate new operator key"
# )
#
# # Replace operator account pubkey
# if not new_operator_has_account:
# target_operator_account = get_account(genesis, target_operator_base_address)
# # Replace pubkey if present
# if target_operator_account["pub_key"]:
# new_pubkey = {
# "@type": "/cosmos.crypto.secp256k1.PubKey",
# "key": dest_validator_operator_pubkey,
# }
# target_operator_account["pub_key"] = new_pubkey
#
# # Brute force replacement of all remaining occurrences
# genesis_dump = json.dumps(genesis)
#
# # Convert validator valcons address
# genesis_dump = re.sub(
# target_consensus_address, dest_consensus_address, genesis_dump
# )
#
# # Convert operator valoper address
# genesis_dump = re.sub(
# target_operator_address,
# dest_operator_valoper_address,
# genesis_dump,
# )
#
# # Convert operator base account address
# genesis_dump = re.sub(
# target_operator_base_address,
# dest_operator_base_address,
# genesis_dump,
# )
#
# genesis = json.loads(genesis_dump)
#
# # Save the modified genesis file
# if output_genesis_file_path is None:
# output_genesis_file_path = genesis_file_path
# print(f"Writing modified genesis file to {output_genesis_file_path}...")
# with open(output_genesis_file_path, "w") as f:
# json.dump(genesis, f)
# print("Modified genesis file written successfully.")


#def iterate_json(json_obj: Mapping[str, Any], change_value_predicate: Callable[[Union[str, int], Any], Optional[Any]]):
# if isinstance(json_obj, dict):
# for key, value in json_obj.items():
# res_val = change_value_predicate(key, value)
# if res_val is not None:
# value = res_val
# json_obj[key] = value
# iterate_json(value, change_value_predicate)
# elif isinstance(json_obj, list):
# for idx, value in enumerate(json_obj):
# res_val = change_value_predicate(idx, value)
# if res_val is not None:
# value = res_val
# json_obj[idx] = value
# iterate_json(value, change_value_predicate)


def iterate_json_generator(json_obj: Mapping[str, Any]):
if isinstance(json_obj, dict):
for key, value in json_obj.items():
Expand All @@ -142,11 +23,10 @@ def iterate_json_generator(json_obj: Mapping[str, Any]):
yield from iterate_json_generator(value)


def replace_validator_keys_recur(genesis: Mapping[str, Any],
src_validator_pubkey: str,
dest_validator_pubkey: str,
dest_validator_operator_pubkey: str,
):
def replace_validator_keys_recursive(genesis: Mapping[str, Any],
src_validator_pubkey: str,
dest_validator_pubkey: str,
dest_validator_operator_pubkey: str):
# Input values #
target_staking_val_info = get_staking_validator_info(
genesis, src_validator_pubkey
Expand Down Expand Up @@ -182,11 +62,6 @@ def replace_validator_keys_recur(genesis: Mapping[str, Any],
# Ensure that operator is not already registered in auth module:
new_operator_has_account = get_account(genesis, dest_operator_base_address)

#if new_operator_has_account:
# print(
# "New operator account already existed before - it is recommended to generate new operator key"
# )

# Replace operator account pubkey
if not new_operator_has_account:
target_operator_account = get_account(genesis, target_operator_base_address)
Expand Down

0 comments on commit 99b33df

Please sign in to comment.