You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
306 lines
13 KiB
306 lines
13 KiB
5 years ago
|
#!/usr/bin/env python3
|
||
|
# -*- coding: utf-8 -*-
|
||
|
"""
|
||
|
A python 3.6+ script to send a batch of transactions from a CSV file.
|
||
|
|
||
|
Note that this script must be in the same directory as the CLI binary.
|
||
|
|
||
|
Due to a possible Nonce mismatch, it is recommended to NOT have 1 'from' address/wallet
|
||
|
appear in multiple CSV files that are ran at the same time.
|
||
|
|
||
|
Example:
|
||
9 months ago
|
./wiki-csv.py /path/to/csv/file.csv --node https://api.s0.t.hmny.io/
|
||
|
./wiki-csv.py /path/to/csv/file.csv --fast -n https://api.s0.t.hmny.io/
|
||
|
./wiki-csv.py /path/to/csv/file.csv --fast --use-default-passphrase --yes -n https://api.s0.t.hmny.io/
|
||
|
./wiki-csv.py /path/to/csv/file.csv --fast --use-default-passphrase --yes --batch-size 100 -n https://api.s0.t.hmny.io/
|
||
5 years ago
|
|
||
|
Sample CSV file:
|
||
|
https://docs.google.com/spreadsheets/d/1nkF8N16S3y28cn7SM1cYJca8lzHPOzyR42S1V-OOAeQ/edit?usp=sharing
|
||
|
|
||
|
For detail help message:
|
||
9 months ago
|
./wiki-csv.py --help
|
||
5 years ago
|
|
||
|
Install with:
|
||
9 months ago
|
curl -O https://raw.githubusercontent.com/woop-chain/go-sdk/master/scripts/wiki-csv.py && chmod +x wiki-csv.py
|
||
5 years ago
|
"""
|
||
|
import sys
|
||
|
import time
|
||
|
import getpass
|
||
|
import argparse
|
||
|
import os
|
||
|
import csv
|
||
|
import subprocess
|
||
|
import urllib.request
|
||
|
import urllib.error
|
||
|
import json
|
||
5 years ago
|
import ssl
|
||
5 years ago
|
|
||
|
script_directory = os.path.dirname(os.path.realpath(__file__))
|
||
9 months ago
|
_wiki_call_and_prefix = [f"{script_directory}/wiki"]
|
||
5 years ago
|
chain_id_options = {"mainnet", "testnet", "stressnet", "partner", "dryrun"}
|
||
|
default_passphrase = ""
|
||
|
|
||
|
|
||
|
class Typgpy(str):
|
||
|
"""
|
||
|
Typography constants for pretty printing.
|
||
|
|
||
|
Note that an ENDC is needed to mark the end of a 'highlighted' text segment.
|
||
|
"""
|
||
|
HEADER = '\033[95m'
|
||
|
OKBLUE = '\033[94m'
|
||
|
OKGREEN = '\033[92m'
|
||
|
WARNING = '\033[93m'
|
||
|
FAIL = '\033[91m'
|
||
|
ENDC = '\033[0m'
|
||
|
BOLD = '\033[1m'
|
||
|
UNDERLINE = '\033[4m'
|
||
|
|
||
|
|
||
9 months ago
|
def _wiki(cli_args, timeout=200):
|
||
5 years ago
|
"""
|
||
|
Helper function to call the CLI with the given args.
|
||
|
|
||
9 months ago
|
Assumes `_setup_wiki` has been called prior to using this function.
|
||
5 years ago
|
|
||
5 years ago
|
Raises subprocess.CalledProcessError if call errored.
|
||
|
"""
|
||
5 years ago
|
assert isinstance(cli_args, list)
|
||
9 months ago
|
wiki_and_args = _wiki_call_and_prefix + [str(x) for x in cli_args]
|
||
5 years ago
|
if args.verbose:
|
||
9 months ago
|
wiki_and_args.append("--verbose")
|
||
|
return subprocess.check_output(wiki_and_args, env=os.environ, timeout=timeout).decode()
|
||
5 years ago
|
|
||
|
|
||
|
def get_shard_count(node):
|
||
|
"""
|
||
|
Fetch the number of shards on the node.
|
||
|
|
||
|
Will raise a KeyError if the RPC returns back an error.
|
||
|
Will raise a subprocess.CalledProcessError if CLI errored.
|
||
|
"""
|
||
9 months ago
|
response = _wiki(["utility", "shards", "-n", node])
|
||
5 years ago
|
return len(json.loads(response)['result'])
|
||
|
|
||
|
|
||
|
def send_transactions(transactions, batch_size, node, chain_id, timeout=40, fast=False, yes=False):
|
||
|
"""
|
||
|
Send the `transactions` where each call to the CLI is `batch_size` transactions.
|
||
|
If `fast` is enabled, the CLI will not wait for a transaction to confirm, otherwise it will
|
||
|
wait at most `timeout` seconds to confirm transaction.
|
||
|
|
||
|
One can bypass the input confirmation by enabling `yes`.
|
||
|
"""
|
||
|
print(f"{Typgpy.HEADER}Transactions to send:{Typgpy.ENDC}")
|
||
|
print(json.dumps(transactions, indent=2))
|
||
|
print(f"{Typgpy.HEADER}Transaction Count: {Typgpy.OKGREEN}{len(transactions)}{Typgpy.ENDC}")
|
||
|
print(f"{Typgpy.HEADER}Node/Endpoint: {Typgpy.OKGREEN}{node}{Typgpy.ENDC}")
|
||
|
if chain_id:
|
||
|
print(f"{Typgpy.HEADER}Chain-ID: {Typgpy.OKGREEN}{chain_id}{Typgpy.ENDC}")
|
||
|
if not yes and input("Send Transactions? [Y]/n\n> ").lower() not in {"yes", "y"}:
|
||
|
return
|
||
|
|
||
|
for i in range(0, len(transactions), batch_size):
|
||
|
batch_tx = transactions[i: i + batch_size]
|
||
9 months ago
|
temp_file = f"/tmp/wiki-csv-{hash(str(batch_tx))}.json"
|
||
5 years ago
|
batch_log_file = f"{script_directory}/batch_tx_{time.time()}.log"
|
||
|
with open(temp_file, "w") as f:
|
||
|
json.dump(batch_tx, f) # Assume to work since `transactions` should be built by `parse_csv`
|
||
|
os.chmod(temp_file, 400)
|
||
3 years ago
|
print(
|
||
|
f"{Typgpy.OKBLUE}Sending a batch of {Typgpy.OKGREEN}{len(batch_tx)}{Typgpy.OKBLUE} transaction(s){Typgpy.ENDC}")
|
||
5 years ago
|
print(f"{Typgpy.OKBLUE}Logs for this batch will be at {Typgpy.OKGREEN}{batch_log_file}{Typgpy.ENDC}")
|
||
9 months ago
|
wiki_args = ["transfer", "--file", temp_file, "--node", node]
|
||
5 years ago
|
if chain_id:
|
||
9 months ago
|
wiki_args.extend(["--chain-id", chain_id])
|
||
5 years ago
|
if fast:
|
||
9 months ago
|
wiki_args.extend(["--timeout", "0"])
|
||
5 years ago
|
else:
|
||
9 months ago
|
wiki_args.extend(["--timeout", timeout])
|
||
5 years ago
|
try:
|
||
9 months ago
|
output = _wiki(wiki_args, timeout=timeout * len(batch_tx))
|
||
5 years ago
|
except subprocess.CalledProcessError as e:
|
||
|
print(f"{Typgpy.FAIL}Transaction failure: {e}{Typgpy.ENDC}")
|
||
|
print(f"{Typgpy.FAIL}Error output: {e.output.decode()}{Typgpy.ENDC}")
|
||
|
with open(batch_log_file, "w") as f:
|
||
|
f.write(f"Sent-tx: {json.dumps(batch_tx, indent=2)}\nResponse: {e.output.decode()}")
|
||
|
raise e
|
||
|
finally:
|
||
|
os.remove(temp_file)
|
||
|
|
||
|
print(f"{Typgpy.OKGREEN}Batched transaction(s) sent successfully!{Typgpy.ENDC}")
|
||
|
print(f"{Typgpy.OKGREEN}Transaction Hashes/Receipts: {Typgpy.ENDC}{output}")
|
||
|
with open(batch_log_file, "w") as f:
|
||
|
f.write(f"Sent-tx: {json.dumps(batch_tx, indent=2)}\nResponse: {output}")
|
||
|
print(f"{Typgpy.BOLD}HOORAY! Sent all transactions!{Typgpy.ENDC}")
|
||
|
|
||
|
|
||
|
def parse_csv(path, node, use_default_passphrase=True):
|
||
|
"""
|
||
|
Parses the CSV into a list of dicts, loosely resembling the batch transaction format.
|
||
|
|
||
|
Assumes that the given path is a CSV file and that the file exists.
|
||
|
Assumes that all given CSV fields are strings.
|
||
|
"""
|
||
3 years ago
|
columns = {"from", "to", "amount", "from-shard", "to-shard", "passphrase-file", "passphrase-string", "gas-price",
|
||
|
"gas-limit"}
|
||
5 years ago
|
|
||
|
def row_filter(row):
|
||
|
valid_row = False
|
||
|
for col in columns:
|
||
|
if col not in row:
|
||
|
return False
|
||
|
if row[col]:
|
||
|
valid_row = True
|
||
|
return valid_row
|
||
|
|
||
|
data, known_from_passphrase = [], {}
|
||
|
shard_count = get_shard_count(node)
|
||
|
with open(path, 'r') as f:
|
||
|
print(f"Parsing CSV at {Typgpy.OKGREEN}{path}{Typgpy.ENDC}")
|
||
|
for i, row in enumerate(filter(row_filter, csv.DictReader(f))):
|
||
|
sys.stdout.write(f"\rParsing line {i} of {path}")
|
||
|
sys.stdout.flush()
|
||
|
try:
|
||
9 months ago
|
_wiki(["utility", "bech32-to-addr", row['from']])
|
||
|
_wiki(["utility", "bech32-to-addr", row['to']])
|
||
5 years ago
|
except subprocess.CalledProcessError as e:
|
||
|
print(f"{e.output}")
|
||
|
print(f"{Typgpy.FAIL}Address error on line {i}! From: {row['from']}; To: {row['to']}{Typgpy.ENDC}")
|
||
|
print(f"{Typgpy.WARNING}Skipping!{Typgpy.ENDC}")
|
||
|
continue
|
||
|
if not row['from-shard'] or not row['to-shard']:
|
||
|
print(f"{Typgpy.FAIL}To and/or from shard is not provided on line {i}!{Typgpy.ENDC}")
|
||
|
print(f"{Typgpy.WARNING}Skipping!{Typgpy.ENDC}")
|
||
|
continue
|
||
|
try:
|
||
|
if int(row['from-shard']) >= shard_count:
|
||
|
print(f"{Typgpy.FAIL}From shard ({row['from-shard']}) on line {i} "
|
||
|
f"is >= number of shards ({shard_count}){Typgpy.ENDC}")
|
||
|
print(f"{Typgpy.WARNING}Skipping!{Typgpy.ENDC}")
|
||
|
continue
|
||
|
if int(row['to-shard']) >= shard_count:
|
||
|
print(f"{Typgpy.FAIL}To shard ({row['to-shard']}) on line {i} "
|
||
|
f"is >= number of shards ({shard_count}){Typgpy.ENDC}")
|
||
|
print(f"{Typgpy.WARNING}Skipping!{Typgpy.ENDC}")
|
||
|
continue
|
||
|
except ValueError as e:
|
||
|
print(f"{Typgpy.FAIL}Error on line {i}: {e}{Typgpy.ENDC}")
|
||
|
print(f"{Typgpy.WARNING}Skipping!{Typgpy.ENDC}")
|
||
|
continue
|
||
|
# Required fields should be valid at this point.
|
||
|
txn = {
|
||
|
"from": row["from"],
|
||
|
"to": row["to"],
|
||
|
"amount": row["amount"],
|
||
|
"from-shard": row["from-shard"],
|
||
|
"to-shard": row["to-shard"],
|
||
|
"stop-on-error": True
|
||
|
}
|
||
|
if row['passphrase-file']:
|
||
|
txn['passphrase-file'] = row['passphrase-file']
|
||
|
elif row['passphrase-string']:
|
||
|
txn['passphrase-string'] = row['passphrase-string']
|
||
|
else:
|
||
|
if use_default_passphrase:
|
||
|
known_from_passphrase[row["from"]] = default_passphrase
|
||
|
elif row["from"] not in known_from_passphrase:
|
||
|
print()
|
||
|
prompt = f"Enter passphrase for wallet {Typgpy.OKGREEN}{row['from']}{Typgpy.ENDC}\n> "
|
||
|
known_from_passphrase[row["from"]] = getpass.getpass(prompt=prompt)
|
||
|
txn['passphrase-string'] = known_from_passphrase[row["from"]]
|
||
|
if row["gas-price"]:
|
||
|
try:
|
||
|
int(row["gas-price"])
|
||
|
txn["gas-price"] = row["gas-price"]
|
||
|
except ValueError as e:
|
||
|
print(f"{Typgpy.FAIL}Error on line {i}: {e}{Typgpy.ENDC}")
|
||
|
print(f"{Typgpy.WARNING}Skipping!{Typgpy.ENDC}")
|
||
|
continue
|
||
3 years ago
|
if row["gas-limit"]:
|
||
|
try:
|
||
|
int(row["gas-limit"])
|
||
|
txn["gas-limit"] = row["gas-limit"]
|
||
|
except ValueError as e:
|
||
|
print(f"{Typgpy.FAIL}Error on line {i}: {e}{Typgpy.ENDC}")
|
||
|
print(f"{Typgpy.WARNING}Skipping!{Typgpy.ENDC}")
|
||
|
continue
|
||
5 years ago
|
data.append(txn)
|
||
|
print("\nFinished parsing CSV!")
|
||
|
return data
|
||
|
|
||
|
|
||
|
def sanity_check(args):
|
||
|
"""
|
||
|
Sanity check before starting the scrip to terminate early.
|
||
|
"""
|
||
|
assert os.path.isfile(args.path), f"{args.path} is not a file"
|
||
|
assert os.path.exists(args.path), f"{args.path} does not exist"
|
||
|
try:
|
||
5 years ago
|
return_code = urllib.request.urlopen(args.node, context=ssl._create_unverified_context()).getcode()
|
||
5 years ago
|
except (urllib.error.HTTPError, urllib.error.URLError) as e:
|
||
|
raise RuntimeError(f"unable to connect to node {args.node}") from e
|
||
|
assert return_code == 200, f"bad response code ({return_code}) from node {args.node}"
|
||
|
if args.chain_id is not None:
|
||
|
assert args.chain_id in chain_id_options, f"{args.chain_id} not in {chain_id_options}"
|
||
|
|
||
|
|
||
9 months ago
|
def _setup_wiki():
|
||
5 years ago
|
"""
|
||
9 months ago
|
Setup `_wiki_call_and_prefix` depending on if wiki.sh exists.
|
||
5 years ago
|
"""
|
||
9 months ago
|
global _wiki_call_and_prefix
|
||
|
_wiki_call_and_prefix = [f"{script_directory}/wiki"]
|
||
5 years ago
|
try:
|
||
9 months ago
|
_wiki(["version"])
|
||
5 years ago
|
return
|
||
|
except (subprocess.CalledProcessError, FileNotFoundError):
|
||
9 months ago
|
print(f"Unable to execute wiki CLI directly at: '{_wiki_call_and_prefix[0]}'")
|
||
|
print(f"Trying to use 'wiki.sh'...")
|
||
|
if "wiki.sh" in os.listdir(script_directory):
|
||
|
_wiki_call_and_prefix = [f"{script_directory}/wiki.sh", "--"]
|
||
5 years ago
|
try:
|
||
9 months ago
|
_wiki(["version"])
|
||
5 years ago
|
return
|
||
|
except subprocess.CalledProcessError as e:
|
||
3 years ago
|
raise SystemExit(
|
||
9 months ago
|
f"'wiki.sh' is unable to execute the CLI. Try downloading the CLI with `./wiki.sh -d`.") from e
|
||
5 years ago
|
else:
|
||
9 months ago
|
raise SystemExit(f"'wiki.sh' is not found in script directory {script_directory}. ")
|
||
5 years ago
|
|
||
|
|
||
5 years ago
|
def _parse_args():
|
||
|
"""
|
||
|
Argument parser that is only used for main execution.
|
||
|
"""
|
||
9 months ago
|
parser = argparse.ArgumentParser(description='Woop CLI, transaction from CSV file wrapper script.')
|
||
5 years ago
|
parser.add_argument("path", type=str, help="The path to the CSV file.")
|
||
|
parser.add_argument("--node", "-n", dest="node", default="https://api.s0.t.hmny.io/", type=str,
|
||
|
help="The node or endpoint to send the transactions to, default: 'https://api.s0.t.hmny.io/'.")
|
||
|
parser.add_argument("--batch-size", dest="batch_size", default=4, type=int,
|
||
|
help="Number of transactions to send in 1 batch to the CLI before checking output, default: 4")
|
||
|
parser.add_argument("--timeout-per-tx", dest="timeout_per_tx", default=40, type=int,
|
||
|
help="Max time spent checking for a single transaction to confirm. Option is ignored "
|
||
|
"if --fast is enabled. Default 40.")
|
||
|
parser.add_argument("--chain-id", dest="chain_id", default=None, type=str,
|
||
|
help="The chain ID of the transactions. Default uses implicit chain ID from CLI. "
|
||
|
f"Options: {chain_id_options}")
|
||
|
parser.add_argument("--fast", action="store_true",
|
||
|
help="Send transactions without waiting for transaction confirmation.")
|
||
|
parser.add_argument("--use-default-passphrase", action="store_true",
|
||
|
help="Use default passphrase if no passphrase file or string is provided in given CSV file.")
|
||
|
parser.add_argument("--yes", action="store_true", help="Say yes to confirmation check")
|
||
|
parser.add_argument("--verbose", action="store_true", help="Enable verbose mode when sending transactions")
|
||
|
args = parser.parse_args()
|
||
|
args.path = os.path.expanduser(args.path)
|
||
|
return args
|
||
|
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
args = _parse_args()
|
||
9 months ago
|
_setup_wiki()
|
||
5 years ago
|
sanity_check(args)
|
||
|
transactions = parse_csv(args.path, args.node, use_default_passphrase=args.use_default_passphrase)
|
||
|
send_transactions(transactions, args.batch_size, args.node, args.chain_id,
|
||
|
timeout=args.timeout_per_tx, fast=args.fast, yes=args.yes)
|