def run(): try: aergo1 = herapy.Aergo() aergo2 = herapy.Aergo() aergo3 = herapy.Aergo() aergo4 = herapy.Aergo() print("------ Connect AERGO -----------") """ aergo1.connect('localhost:17801') aergo2.connect('localhost:17802') aergo3.connect('localhost:17803') """ aergo1.connect('ec2-52-56-86-84.eu-west-2.compute.amazonaws.com:17845') aergo2.connect('ec2-13-57-31-165.us-west-1.compute.amazonaws.com:17845') aergo3.connect('ec2-3-86-18-207.compute-1.amazonaws.com:17845') aergo4.connect('ec2-54-180-100-160.ap-northeast-2.compute.amazonaws.com:17845') print("------ Get Blockchain Status -----------") best_block_hash, best_block_height = aergo1.get_blockchain_status() print("(aergo1) Best Block Hash = {}".format(best_block_hash)) print("(aergo1) Best Block Height = {}".format(best_block_height)) best_block_hash, best_block_height = aergo2.get_blockchain_status() print("(aergo2) Best Block Hash = {}".format(best_block_hash)) print("(aergo2) Best Block Height = {}".format(best_block_height)) best_block_hash, best_block_height = aergo3.get_blockchain_status() print("(aergo3) Best Block Hash = {}".format(best_block_hash)) print("(aergo3) Best Block Height = {}".format(best_block_height)) best_block_hash, best_block_height = aergo4.get_blockchain_status() print("(aergo4) Best Block Hash = {}".format(best_block_hash)) print("(aergo4) Best Block Height = {}".format(best_block_height)) print("------ Get Block Status -----------") best_block_height = best_block_height - 2 block1 = aergo1.get_block(block_height=best_block_height) print("Aergo 1:\n{}".format(str(block1.hash))) block2 = aergo2.get_block(block_height=best_block_height) print("Aergo 2:\n{}".format(str(block2.hash))) block3 = aergo3.get_block(block_height=best_block_height) print("Aergo 3:\n{}".format(str(block3.hash))) block4 = aergo4.get_block(block_height=best_block_height) print("Aergo 4:\n{}".format(str(block4.hash))) aergo1.disconnect() aergo2.disconnect() aergo3.disconnect() aergo4.disconnect() except Exception as e: eprint(e) traceback.print_exception(*sys.exc_info())
def register_account(self, account_name: str, keystore_path: str, password: str = None, addr: str = None) -> str: """Register and exported account to config.json""" try: self.config_data('wallet', account_name) except KeyError: # if KeyError then account doesn't already exists if addr is None: aergo = herapy.Aergo() with open(keystore_path, "r") as f: keystore = f.read() account = aergo.import_account_from_keystore(keystore, password, skip_state=True, skip_self=True) addr = str(account.address) self.config_data('wallet', account_name, value={}) self.config_data('wallet', account_name, 'addr', value=addr) self.config_data('wallet', account_name, 'keystore', value=keystore_path) self.save_config() return addr error = "Error: account name '{}' already exists".format(account_name) raise InvalidArgumentsError(error)
def run(): try: aergo = herapy.Aergo() print("------ Connect AERGO -----------") aergo.connect('localhost:7845', tls_ca_cert="./cert/rootca.crt", tls_cert="./cert/client.pem", tls_key="./cert/client.key") print("------ Get Node Info -----------") node_state = aergo.get_node_state() print("Node State: {}".format(str(node_state))) node_info = aergo.get_node_info() print("Node Info: {}".format(str(node_info))) print("------ Get Blockchain Info -----------") blockchain_info = aergo.get_chain_info() print("Blockchain Info: {}".format(str(blockchain_info))) blockchain_info = aergo.get_chain_info(with_consensus_info=False) print("Blockchain Info: {}".format(str(blockchain_info))) print("------ Get Consensus Info -----------") consensus_info = aergo.get_consensus_info() print("Consensus Info: {}".format(str(consensus_info))) print("------ Disconnect AERGO -----------") aergo.disconnect() except Exception as e: eprint(e) traceback.print_exception(*sys.exc_info())
def run(): try: aergo = herapy.Aergo() print("------ Connect AERGO -----------") aergo.connect('localhost:7845') print("------ Get Block Meta Stream -----------") stream = aergo.receive_block_stream() i = 0 while i < 3: block = next(stream) print('[{}] block: {}'.format(i, str(block))) i += 1 print("------ Get Block Stream -----------") stream = aergo.receive_block_stream() i = 0 while i < 3: block = next(stream) print('[{}] block: {}'.format(i, str(block))) i += 1 print("------ Disconnect AERGO -----------") aergo.disconnect() except Exception as e: eprint(e) traceback.print_exception(*sys.exc_info())
def __init__(self, ip_port: str, config_file_path: str, aergo_net: str, eth_net: str, privkey_name: str, privkey_pwd: str = None, root_path: str = './') -> None: """ UnfreezeService unfreezes native aergo for users that have initiated a transfer by locking aergo erc20 but don't already have aergo native to pay for the fee. """ self.config_file_path = config_file_path self.aergo_net = aergo_net self.eth_net = eth_net config_data = self.load_config_data() self.bridge_eth = \ config_data['networks'][eth_net]['bridges'][aergo_net]['addr'] self.bridge_aergo = \ config_data['networks'][aergo_net]['bridges'][eth_net]['addr'] aergo_erc20 = \ config_data['networks'][eth_net]['tokens']['aergo_erc20']['addr'] self.aergo_erc20_bytes = bytes.fromhex(aergo_erc20[2:]) logger.info("\"Ethereum bridge contract: %s\"", self.bridge_eth) logger.info("\"Aergo bridge contract: %s\"", self.bridge_aergo) logger.info("\"Aergo ERC20: %s\"", aergo_erc20) # connect aergo provider self.hera = herapy.Aergo() aergo_ip = config_data['networks'][aergo_net]['ip'] self.hera.connect(aergo_ip) # connect eth provider eth_ip = config_data['networks'][eth_net]['ip'] self.web3 = Web3(Web3.HTTPProvider(eth_ip)) eth_poa = config_data['networks'][eth_net]['isPOA'] if eth_poa: self.web3.middleware_onion.inject(geth_poa_middleware, layer=0) assert self.web3.isConnected() # load signer if privkey_pwd is None: privkey_pwd = getpass("Decrypt exported private key '{}'\n" "Password: "******"r") as f: keystore = f.read() self.hera.import_account_from_keystore(keystore, privkey_pwd) self.address = str(self.hera.account.address) logger.info("\"Unfreezer Address: %s\"", self.address) # query unfreeze fee unfreeze_fee_q = self.hera.query_sc_state(self.bridge_aergo, ["_sv__unfreezeFee"]) self.unfreeze_fee = int( json.loads(unfreeze_fee_q.var_proofs[0].value)['_bignum']) logger.info("\"Unfreeze fee for broadcaster: %saer\"", self.unfreeze_fee)
def run(): try: print("------ Set Sender Account -----------") sender_json = '{"address": "AmNW9YMMm48jTxX5Yee6tRYLpuptWdg3cqbD2CVoee1YcUGBHfad", "enc_key": "47QHSuhBTZ4b7nbw2zJz5EARyQ4XS8gDxhFDeu5mYeKNqfHhwRutUmja3WRxV1suB12eWBeDZ"}' sender_account = herapy.Account.from_json(sender_json, password='******') print( " > Sender Account before connecting: {}".format(sender_account)) print(" > address: {}".format(sender_account.address)) print(" > private key: {}".format(sender_account.private_key)) aergo = herapy.Aergo() print("------ Connect AERGO -----------") aergo.connect('localhost:7845') print("------ Set Sender Account -----------") aergo.account = sender_account aergo.get_account() print(" > Sender Account after connecting: {}".format(aergo.account)) print("------ Set Receiver Account -----------") receiver_json = '{"address": "AmMPQqRJ4pd8bS9xdkw5pjExtLjaUXaYGB5kagzHu4A9ckKgnBV2"}' receiver_account = herapy.Account.from_json(receiver_json) receiver_account = aergo.get_account(account=receiver_account) print(" > Receiver Account: {}".format(receiver_account)) print("------ Simple Transfer -----------") simple_tx, result = aergo.transfer(to_address=receiver_account.address, amount=10000000000) print(" > simple TX[{}]".format(simple_tx.calculate_hash())) print("{}".format(str(simple_tx))) print(" > result: ", result) if result.status != herapy.CommitStatus.TX_OK: eprint(" > ERROR[{0}]: {1}".format(result.status, result.detail)) aergo.disconnect() return else: print(" > result[{0}] : {1}".format(result.tx_id, result.status.name)) print("------ Check Account Info #1 -----------") aergo.get_account() print(" > Sender Account: {}".format(aergo.account)) receiver_account = aergo.get_account(receiver_account) print(" > Receiver Account: {}".format(receiver_account)) time.sleep(3) print("------ Check Account Info #2 -----------") aergo.get_account() print(" > Sender Account: {}".format(aergo.account)) receiver_account = aergo.get_account(receiver_account) print(" > Receiver Account: {}".format(receiver_account)) print("------ Disconnect AERGO -----------") aergo.disconnect() except Exception as e: eprint(e) traceback.print_exception(*sys.exc_info())
def run(): try: aergo = herapy.Aergo() print("------ Connect AERGO -----------") aergo.connect('localhost:7845') address = "AmPwBMCcYbqyetVmAupjtzR8GgnTAVduZAVE9SnJPzjhWEmhjSef" print("------ Fund a second account to pass test in testmode -------") sender_private_key = "6hbRWgddqcg2ZHE5NipM1xgwBDAKqLnCKhGvADWrWE18xAbX8sW" aergo.new_account(private_key=sender_private_key) simple_tx, result = aergo.send_payload(to_address=address, amount=10, payload=None, retry_nonce=3) if result.status != herapy.CommitStatus.TX_OK: eprint(" > ERROR[{0}]: {1}".format(result.status, result.detail)) else: print(" > result[{0}] : {1}".format(result.tx_id, result.status.name)) print("------ Get Account State -----------") best_block_hash, best_block_height = aergo.get_blockchain_status() block = aergo.get_block(best_block_hash) root = block.blocks_root_hash account = aergo.get_account(address=address, proof=True, root=root) account2 = aergo.get_account(address=address, proof=True, compressed=False, root=root) print("account = {}".format(account)) print("account.balance = {}".format(account.balance.aergo)) print("account2 = {}".format(account2)) print("account2.balance = {}".format(account2.balance.aergo)) print("------ Verify inclusion proof -----------") print("valid inclusion proof compressed: ", account.verify_proof(root)) print("valid inclusion proof: ", account2.verify_proof(root)) print("------ Verify Non inclusion proof -----------") address = "AmMejL8z3wW2doksBzzMiWM2xTb6WtZniLkLyxwqWKiLJKK8Yvqd" account = aergo.get_account(address=address, proof=True, root=root) account2 = aergo.get_account(address=address, proof=True, compressed=False, root=root) print(account) print(account2) print("valid exclusion proof compressed: ", account.verify_proof(root)) print("valid exclusion proof: ", account2.verify_proof(root)) print("------ Disconnect AERGO -----------") aergo.disconnect() except Exception: traceback.print_exception(*sys.exc_info())
def __init__( self, keystore: str, privkey_name: str, privkey_pwd: str ) -> None: self.hera = herapy.Aergo() self.hera.import_account_from_keystore( keystore, privkey_pwd, skip_state=True) self.address = str(self.hera.account.address)
def run(): try: aergo = herapy.Aergo() print("------ Export New Account -----------") aergo.new_account() new_exp_txt = aergo.export_account(password="******") print("Exported txt is {}".format(new_exp_txt)) print("------ Import Account -----------") try: aergo.import_account(new_exp_txt, password='******') except herapy.errors.GeneralException: print("It should be failed.") print("------ Import Account -----------") try: account = aergo.import_account(new_exp_txt, password='******') print("Account private key is {}".format(account.private_key)) print("Account address is {}".format(account.address)) except herapy.errors.GeneralException: print("It should be failed.") print("------ Import Account with Exported Data -----------") #exported_txt = "485ccQXjmT3JeUHV16n16LzAJhhfHHkv9HU9k7c5PeJDyPMAdLcCu8Yqws19UzMP4K4Rq2MkQ" exported_txt = "MNxKz7jPTaWW8xZc6HSbgTPXDj6yGq6PrLbboSyV5psBfKyRmbo5qoVHgWTEXucisaUy8Y3PGf4UBc" print("Exported Data is {}".format(exported_txt)) account = aergo.import_account(exported_txt, password='******') print("Account private key is {}".format(account.private_key)) print("Account address is {}".format(account.address)) print("------ Export Account -----------") new_exp_txt = aergo.export_account(password='******') print("Exported txt is {}".format(new_exp_txt)) print("------ Connect AERGO -----------") aergo.connect('localhost:7845') print("------ Get Account State -----------") a = aergo.get_account(address=account.address) print(" > account state of Import account") print(" - balance = {}".format(a.balance)) print(" - nonce = {}".format(a.nonce)) print(" - code hash = {}".format(a.code_hash)) print(" - storage root = {}".format(a.storage_root)) print("------ Disconnect AERGO -----------") aergo.disconnect() except Exception as e: eprint(e) traceback.print_exception(*sys.exc_info())
def auto_update_oracle(from_chain, to_chain, wallet): hera = herapy.Aergo() hera.connect(wallet.config_data('networks', to_chain, 'ip')) oracle = wallet.config_data('networks', to_chain, 'bridges', from_chain, 'oracle') bridge = wallet.config_data('networks', to_chain, 'bridges', from_chain, 'addr') default = wallet.config_data('wallet', 'default', 'addr') oracle_before = query_oracle(hera, bridge) assert oracle == oracle_before # set oracle to 'default' account in test_config new_oracle = default wallet.config_data('networks', to_chain, 'bridges', from_chain, 'oracle', value=new_oracle) wallet.save_config() # wait for changes to be reflacted _, current_height = hera.get_blockchain_status() # waite for anchor containing our transfer stream = hera.receive_event_stream(bridge, "oracleUpdate", start_block_no=current_height) next(stream) stream.stop() oracle_after = query_oracle(hera, bridge) assert oracle_after == default time.sleep(10) wallet.config_data('networks', to_chain, 'bridges', from_chain, 'oracle', value=oracle) wallet.save_config() # transfer bridge ownership back to oracle # set aergo signer keystore_path = wallet.config_data('wallet', 'default', 'keystore') with open(keystore_path, "r") as f: keystore = f.read() hera.import_account_from_keystore(keystore, '1234') tx, _ = hera.call_sc(bridge, "oracleUpdate", args=[oracle]) hera.wait_tx_result(tx.tx_hash) oracle_after = query_oracle(hera, bridge) assert oracle == oracle_after
def __init__( self, config_file_path: str, aergo_net: str, eth_net: str, aergo_ip: str, eth_ip: str, root_path: str, ) -> None: self.config_file_path = config_file_path config_data = load_config_data(config_file_path) self.aergo_net = aergo_net self.eth_net = eth_net self.hera = herapy.Aergo() self.hera.connect(aergo_ip) self.web3 = Web3(Web3.HTTPProvider(eth_ip)) eth_poa = config_data['networks'][eth_net]['isPOA'] if eth_poa: self.web3.middleware_onion.inject(geth_poa_middleware, layer=0) assert self.web3.isConnected() # remember bridge contracts # eth bridge contract bridge_abi_path = (config_data['networks'][eth_net]['bridges'] [aergo_net]['bridge_abi']) with open(root_path + bridge_abi_path, "r") as f: bridge_abi = f.read() eth_bridge_addr = ( config_data['networks'][eth_net]['bridges'][aergo_net]['addr']) self.eth_bridge = self.web3.eth.contract(address=eth_bridge_addr, abi=bridge_abi) # eth oracle contract oracle_abi_path = (config_data['networks'][eth_net]['bridges'] [aergo_net]['oracle_abi']) with open(root_path + oracle_abi_path, "r") as f: oracle_abi = f.read() self.eth_oracle_addr = ( config_data['networks'][eth_net]['bridges'][aergo_net]['oracle']) self.eth_oracle = self.web3.eth.contract(address=self.eth_oracle_addr, abi=oracle_abi) # aergo bridge contract self.aergo_bridge = ( config_data['networks'][aergo_net]['bridges'][eth_net]['addr']) # aergo oracle contract self.aergo_oracle = ( config_data['networks'][aergo_net]['bridges'][eth_net]['oracle'])
def _load_priv_key(self, account_name: str = 'default', password: str = None) -> str: """ Load and maybe prompt user password to decrypt keystore.""" keystore_path = self.config_data('wallet', account_name, 'keystore') with open(keystore_path, "r") as f: keystore = f.read() if password is None: password = getpass( "Decrypt exported private key '{}'\nPassword: ".format( account_name)) aergo = herapy.Aergo() account = aergo.import_account_from_keystore(keystore, password, skip_state=True, skip_self=True) priv_key = str(account.private_key) return priv_key
def auto_update_validators(from_chain, to_chain, wallet): hera = herapy.Aergo() hera.connect(wallet.config_data('networks', to_chain, 'ip')) t_anchor_aergo = wallet.config_data('networks', to_chain, 'bridges', from_chain, 't_anchor') oracle = wallet.config_data('networks', to_chain, 'bridges', from_chain, 'oracle') validators_before = wallet.config_data('validators') aergo_validators_before = [val['addr'] for val in validators_before] aergo_validators = query_validators(hera, oracle) assert aergo_validators == aergo_validators_before # add a validator aergo_nonce_before = int( hera.query_sc_state(oracle, ["_sv__nonce"]).var_proofs[0].value) new_validators = validators_before + [validators_before[0]] wallet.config_data('validators', value=new_validators) wallet.save_config() # wait for changes to be reflacted nonce = aergo_nonce_before while nonce <= aergo_nonce_before + 2: time.sleep(t_anchor_aergo) nonce = int( hera.query_sc_state(oracle, ["_sv__nonce"]).var_proofs[0].value) aergo_validators = query_validators(hera, oracle) assert aergo_validators == \ aergo_validators_before + [aergo_validators_before[0]] # remove added validator aergo_nonce_before = int( hera.query_sc_state(oracle, ["_sv__nonce"]).var_proofs[0].value) wallet.config_data('validators', value=new_validators[:-1]) wallet.save_config() # wait for changes to be reflacted nonce = aergo_nonce_before while nonce <= aergo_nonce_before + 2: time.sleep(t_anchor_aergo) nonce = int( hera.query_sc_state(oracle, ["_sv__nonce"]).var_proofs[0].value) aergo_validators = query_validators(hera, oracle) assert aergo_validators == aergo_validators_before
def check_aergo_conn_info(target, exported_key, password): aergo = herapy.Aergo() aergo.connect(target) if exported_key is None: if password is None: letters = string.ascii_letters letters += string.digits password = ''.join(random.choice(letters) for _ in range(20)) aergo.new_account() else: aergo.import_account(exported_data=exported_key, password=password) exported_key = aergo.export_account(password=password) out_print(" > Account Info") out_print(" - Exported Key: %s" % exported_key) out_print(" - Password: %s" % password) return aergo
def create_account(self, account_name: str, keystore_path: str, password: str = None) -> str: if password is None: while True: password = getpass( "Create a password for '{}': ".format(account_name)) confirm = getpass("Confirm password: "******"Passwords don't match, try again") aergo = herapy.Aergo() aergo.new_account(skip_state=True) keystore = aergo.export_account_to_keystore(password) with open(keystore_path, 'w') as f: json.dump(keystore, f, indent=4) addr = self.register_account(account_name, keystore_path=keystore_path, password=password) return addr
def deploy_oracle( config_path: str, lua_bytecode_path: str, sol_bytecode_path: str, eth_net: str, aergo_net: str, privkey_name: str = None, privkey_pwd: str = None, ) -> None: """ Deploy brige contract on Aergo and Ethereum.""" with open(config_path, "r") as f: config_data = json.load(f) with open(lua_bytecode_path, "r") as f: lua_bytecode = f.read()[:-1] with open(sol_bytecode_path, "r") as f: sol_bytecode = f.read() bridge_abi_path = \ config_data['networks'][eth_net]['bridges'][aergo_net]['bridge_abi'] oracle_abi_path = \ config_data['networks'][eth_net]['bridges'][aergo_net]['oracle_abi'] bridge_eth_addr = \ config_data['networks'][eth_net]['bridges'][aergo_net]['addr'] bridge_aergo_addr = \ config_data['networks'][aergo_net]['bridges'][eth_net]['addr'] t_anchor_aergo = \ config_data['networks'][aergo_net]['bridges'][eth_net]['t_anchor'] t_final_aergo = \ config_data['networks'][aergo_net]['bridges'][eth_net]['t_final'] t_anchor_eth = \ config_data['networks'][eth_net]['bridges'][aergo_net]['t_anchor'] t_final_eth = \ config_data['networks'][eth_net]['bridges'][aergo_net]['t_final'] bridge_aergo_trie_key = \ hashlib.sha256(decode_address(bridge_aergo_addr)).digest() print("bridge key aergo: 0x{}".format(bridge_aergo_trie_key.hex())) # bridge_eth_address is used instead of bridge_eth_trie_key because # crypto.verifyProof() already hashes the key # bridge_eth_trie_key = \ # "0x" + keccak(bytes.fromhex(bridge_eth_addr[2:])).hex() # print("bridge key eth: ", bridge_eth_trie_key) with open(bridge_abi_path, "r") as f: bridge_abi = f.read() with open(oracle_abi_path, "r") as f: oracle_abi = f.read() if privkey_name is None: privkey_name = 'proposer' # get validators from config file aergo_validators = [] eth_validators = [] for validator in config_data['validators']: eth_validators.append(Web3.toChecksumAddress(validator['eth-addr'])) aergo_validators.append(validator['addr']) print('aergo validators : ', aergo_validators) print('ethereum validators : ', eth_validators) print("------ DEPLOY ORACLE BETWEEN Aergo & Ethereum -----------") print("------ Connect AERGO -----------") aergo = herapy.Aergo() aergo.connect(config_data['networks'][aergo_net]['ip']) print("------ Connect Web3 -----------") ip = config_data['networks'][eth_net]['ip'] w3 = Web3(Web3.HTTPProvider(ip)) eth_poa = config_data['networks'][eth_net]['isPOA'] if eth_poa: w3.middleware_onion.inject(geth_poa_middleware, layer=0) assert w3.isConnected() print("------ Set Sender Account -----------") if privkey_pwd is None: privkey_pwd = getpass( "Decrypt Aergo private key '{}'\nPassword: "******" > Sender Address Aergo: {}".format(aergo.account.address)) keystore = config_data["wallet-eth"][privkey_name]['keystore'] with open(keystore, "r") as f: encrypted_key = f.read() if privkey_pwd is None: privkey_pwd = getpass( "Decrypt Ethereum keystore '{}'\nPassword: "******" > Sender Address Ethereum: {}".format(sender)) print("------ Deploy Aergo SC -----------") payload = herapy.utils.decode_address(lua_bytecode) args = [ aergo_validators, bridge_aergo_addr, bridge_eth_addr, t_anchor_aergo, t_final_aergo ] tx, result = aergo.deploy_sc(amount=0, payload=payload, args=args) if result.status != herapy.CommitStatus.TX_OK: print(" > ERROR[{0}]: {1}".format(result.status, result.detail)) aergo.disconnect() return print(" > result[{0}] : {1}".format(result.tx_id, result.status.name)) result = aergo.wait_tx_result(tx.tx_hash) if result.status != herapy.TxResultStatus.CREATED: print(" > ERROR[{0}]:{1}: {2}".format(result.contract_address, result.status, result.detail)) aergo.disconnect() return aergo_oracle = result.contract_address print("------ Deploy Ethereum SC -----------") receipt = deploy_contract(sol_bytecode, oracle_abi, w3, 8000000, 20, privkey, eth_validators, bridge_eth_addr, bridge_aergo_trie_key, t_anchor_eth, t_final_eth) eth_oracle = receipt.contractAddress print(" > Oracle Address Ethereum: {}".format(eth_oracle)) print(" > Oracle Address Aergo: {}".format(aergo_oracle)) print("------ Store bridge addresses in test_config.json -----------") (config_data['networks'][eth_net]['bridges'][aergo_net]['oracle'] ) = eth_oracle (config_data['networks'][aergo_net]['bridges'][eth_net]['oracle'] ) = aergo_oracle with open(config_path, "w") as f: json.dump(config_data, f, indent=4, sort_keys=True) print("------ Transfer bridge control to oracles -----------") tx, result = aergo.call_sc(bridge_aergo_addr, "oracleUpdate", args=[aergo_oracle], amount=0) if result.status != herapy.CommitStatus.TX_OK: print("oracleUpdate Tx commit failed : {}".format(result)) # Check oracle transfer success result = aergo.wait_tx_result(tx.tx_hash) if result.status != herapy.TxResultStatus.SUCCESS: print("oracleUpdate Tx execution failed : {}".format(result)) eth_bridge = w3.eth.contract(address=bridge_eth_addr, abi=bridge_abi) next_nonce = w3.eth.getTransactionCount(acct.address) construct_txn = eth_bridge.functions.oracleUpdate( eth_oracle).buildTransaction({ 'chainId': w3.eth.chainId, 'from': acct.address, 'nonce': next_nonce, 'gas': 50000, 'gasPrice': w3.toWei(2, 'gwei') }) signed = acct.sign_transaction(construct_txn) tx_hash = w3.eth.sendRawTransaction(signed.rawTransaction) receipt = w3.eth.waitForTransactionReceipt(tx_hash) if receipt.status != 1: print("Oracle update execution failed: {}".format(receipt)) print("------ Disconnect AERGO -----------") aergo.disconnect()
def _connect_aergo(self, network_name: str) -> herapy.Aergo: aergo = herapy.Aergo() aergo.connect(self.config_data('networks', network_name, 'ip')) return aergo
from datetime import datetime import json import sys import aergo.herapy as herapy assert len(sys.argv) == 2, "Please provide password to encrypt key" password = sys.argv[1] print('Generating a new json keystore...') hera = herapy.Aergo() hera.new_account() keystore = hera.export_account_to_keystore(password) print(keystore) hera.import_account_from_keystore(keystore, password, True) print("Decryption test OK: ", hera.get_address()) time = str(datetime.utcnow().isoformat('T', 'seconds')) ks_file_name = "{addr}__{time}__keystore.json".format( addr=keystore['aergo_address'], time=time) print("Storing file in: ", ks_file_name) with open(ks_file_name, 'w') as f: json.dump(keystore, f, indent=4)
def run(): print("------ Payload -----------") """ -- Define global variables. state.var { a = state.value(), b = state.array(3), c = state.map(), } function constructor(name) a:set("a_" .. name) b[1] = "b_" .. name c["init"] = "c_" .. name c[string.char(0x01)] = name c[fromhex('61')] = name end function fromhex(str) return (str:gsub('..', function (cc) return string.char(tonumber(cc, 16)) end)) end function set_name(key, name) if key == "a" then a:set(name) elseif key == "b" then b[2] = name else c['name'] = name end end function get_name(key) if key == "a" then return a:get() elseif key == "b" then return b[2] else return c['name'] end end function say_hello() a:set("hello A") b[3] = "hello B" c["hello"] = "hello C" end abi.register(set_name, get_name, say_hello) """ payload_str = "MyFxtNVdegMvf25CroFLsQs1H8mNXEdTwT7QTHYakg8gx8EJdivi87GJpLu9RUmEB7kECTMhcEeNYNRF7uW1rozSCBJameJZejrs2u39E57zebBCmTvp4331tAeVTQzr5B4PCt6xVd9UtU4kCBiL4Jfi8YJpu9jE3cJ5qpW39yZCoaSNMRWEsoDLePn1tBxnvvKTzP37o7Zges9gLoThS6G7ioH6cFQhSxV9fPBoPfE1b6zMoSi97tyaDDc1XjDJ4YCLLBhaVeN55ZY5ayjajBCoKXGTUp8yiQNkGx3Jy5YwYPZxnvtiYxzpoKZtYz3nA6QRgkC16ecFtGBM8GYzFhYoDQpse24yjQfqwH5SkQh6EHGzUaCzX7AahivvjkyAtdpS5kfbJqquYUoYHoqXXLcLTj5CZ9Wzck6mdq25o8sQmM8DBnQ3DX6QQyyY9agCcRHYkK5Zr52vDmigsXS1qXJfDvBmrUTsvXFMfPE3EZUV5PaYTNubS7AGjReWQpou5FCpkshoAdfoiLLHTa1yCZJdCbjv8gpPWJCeivFbUo6Y2Xp41HreLExnZHHpEeZvEgat8ArA24ardELWWiVeE9ZkW3VE7gReDUJNWStZBrASNje7N8GsHhdvdKSKGJ8LAFkF4MrDSH4hPpjZkK6PJBu2jCuX9VoMUcR3p6RJ6NZFf7JudiWEkkZx7kULbeN31rpAhm3bXgFnU8eiamQk4ddY2Qur6kfzjCTmdu9SUwi71b778LsmxsosqbpoFnbvUhBuZKrjuNA1uJdhSoErDe6RkpkP5bm6asszpNK7zBu5iUyn1VepnbCyG2zWdeK7UQufcLGQh8yFamY2FqKpBkxaXkSFyfSjE41VT2mgGFhkMdz4E5ddmPjSg4RGYw33V1tCq3sRtFRe34zR3HrRsr54yFLLMbS1tyzt6tMREAghhTgXaKt9akigkeunczpntdRcBFzNgGqBx2BHyBXaRPzUWWdouvCBjaUzeZuxKVhodU1uts6tHQJWjk4yvgSmDB1mooTaYTuHAWgCLrjUEMyTNZWkdsgKkxfZtV5Q8rbqJ8FGQvSCucXDjFyCy5XPf5GNxhvdj7qYuewMxMM428qF6cR8MBqCo9LX85iRPCKdSVksAedk1GWehVAzwqGMGgMAE21P1EzCdTf3khhkXNT5xxYHtYVGtFUoWPKqi5Xr1jc6h3yYVPjXuUvYPPCDYQU6mboSSAfr211XFsJS42WRF2xHVFRn3jT76kgqfNxbCfXeWrcRVJfLcwE9FACfXGbp7GdUUZbcYKjCCjJ68W6qznwbZuph9oCiPsM1Y4A4UaesSwoijVUHxwSgZc1uJWjBBzuV1APQGTW7Z6DhfoZKfKhtDabTQhrafoUB9ZCbCqqDdTSGBufYRJ6qsSqTfr15YEyKgzdy5juRrXADF17P3f4XCeerD5N8neUjsUfVa8BWFuQfDWeHskzGWtLQnVs2qfhqM8tUefuMBEp2vG3CgRe247WKDLPPHpPeeern7PWiJgf5JzRt9h3brCcQy5qp39KKznEdrVrS6iNMEBK5qjtPHSqFbdSkkYEbqRp6gdisSPGFS2jraXFi2x" payload = herapy.utils.decode_address(payload_str) try: aergo = herapy.Aergo() print("------ Connect AERGO -----------") aergo.connect('localhost:7845') print("------ Set Sender Account -----------") sender_private_key = "6hbRWgddqcg2ZHE5NipM1xgwBDAKqLnCKhGvADWrWE18xAbX8sW" sender_account = aergo.new_account(private_key=sender_private_key) print(" > Sender Address: {}".format(sender_account.address)) print( herapy.utils.convert_bytes_to_int_str(bytes( sender_account.address))) aergo.get_account() print(" > account state of Sender") print(" - balance = {}".format(sender_account.balance)) print(" - nonce = {}".format(sender_account.nonce)) print(" - code hash = {}".format(sender_account.code_hash)) print(" - storage root = {}".format( sender_account.storage_root)) print("------ Deploy SC -----------") tx, result = aergo.deploy_sc(amount=0, payload=payload, args=1234) print(" > TX: {}".format(tx.tx_hash)) print("{}".format(herapy.utils.convert_tx_to_json(tx))) if result.status != herapy.CommitStatus.TX_OK: eprint(" > ERROR[{0}]: {1}".format(result.status, result.detail)) aergo.disconnect() return else: print(" > result[{0}] : {1}".format(result.tx_id, result.status.name)) print(herapy.utils.convert_bytes_to_int_str(bytes(tx.tx_hash))) time.sleep(3) print("------ Check deployment of SC -----------") print(" > TX: {}".format(tx.tx_hash)) result = aergo.get_tx_result(tx.tx_hash) if result.status != herapy.TxResultStatus.CREATED: eprint(" > ERROR[{0}]:{1}: {2}".format(result.contract_address, result.status, result.detail)) aergo.disconnect() return sc_address = result.contract_address print(" > SC Address: {}".format(sc_address)) print("------ Query SC State Var with Proof -----------") best_block_hash, best_block_height = aergo.get_blockchain_status() block = aergo.get_block(best_block_hash) root = block.blocks_root_hash sc_state = aergo.query_sc_state(sc_address, ["_sv_a"], root=root) sc_root = sc_state.account.state_proof.state.storageRoot print("Variable Proof: {}".format( sc_state.var_proofs.verify_var_proof( sc_root, sc_state.var_proofs[0], hashlib.sha256(bytes("_sv_a", 'latin-1')).digest()))) print("Variables Proof: {}".format( sc_state.var_proofs.verify_proof(root=sc_root))) print("Total Proof: {}".format(sc_state.verify_proof(root))) storage_keys = [ "_sv_a", "_sv_b-1", "_sv_c-init", "_sv_c-\x01", "_sv_c-a" ] sc_state = aergo.query_sc_state(sc_address, storage_keys, root=root) print("Proof: {}".format(sc_state.verify_proof(root))) for i, vp in enumerate(sc_state.var_proofs): print("[{0}] Variable Proof: {1}".format( i, sc_state.var_proofs.verify_var_proof( sc_root, vp, hashlib.sha256(bytes(storage_keys[i], 'latin-1')).digest()))) print(" var_proof.key = {}".format(vp.key)) print(" var_proof.value = {}".format(vp.value)) print(" var_proof.inclusion = {}".format(vp.inclusion)) print(" var_proof.proof_key = {}".format(vp.proofKey)) print(" var_proof.proof_value = {}".format(vp.proofVal)) print(" var_proof.bitmap = {}".format(vp.bitmap)) print(" var_proof.height = {}".format(vp.height)) sc_var_a = SCStateVar(var_name="a") sc_var_b = SCStateVar(var_name="b", array_index=1) sc_var_c = SCStateVar(var_name="c", map_key='init') sc_state = aergo.query_sc_state(sc_address, [sc_var_a, sc_var_b, sc_var_c], root=root, compressed=False) print("Proof: {}".format(sc_state.verify_proof(root))) sc_state = aergo.query_sc_state(sc_address, ['not', 'included', 'var'], root=root) for i, vp in enumerate(sc_state.var_proofs): print("var[{}]".format(i)) print(" key: {}".format(vp.key)) print(" inclusion? {}".format(vp.inclusion)) print("not inclusion? Proof = {}".format(sc_state.verify_proof(root))) sc_state = aergo.query_sc_state(sc_address, ['not', 'included', 'var'], root=root, compressed=False) for i, vp in enumerate(sc_state.var_proofs): print("var[{}]".format(i)) print(" key: {}".format(vp.key)) print(" inclusion? {}".format(vp.inclusion)) print("not inclusion? Proof = {}".format(sc_state.verify_proof(root))) address = "AmMejL8z3wW2doksBzzMiWM2xTb6WtZniLkLyxwqWKiLJKK8Yvqd" sc_state = aergo.query_sc_state(address, ["_sv_a"], root=root) sc_root = sc_state.account.state_proof.state.storageRoot print("Number of Variable Proofs = {}".format(len( sc_state.var_proofs))) print("Variables Proof: {}".format( sc_state.var_proofs.verify_proof(root=sc_root))) print("Total Proof: {}".format(sc_state.verify_proof(root))) print("------ Disconnect AERGO -----------") aergo.disconnect() except Exception as e: eprint(e) traceback.print_exception(*sys.exc_info())
def __init__(self, config_data, privkey_name, privkey_pwd): aergo_privkey = \ config_data['wallet'][privkey_name]['priv_key'] self.hera = herapy.Aergo() self.hera.import_account(aergo_privkey, privkey_pwd) self.address = str(self.hera.account.address)
def run(): print("------ Payload -----------") """ function constructor(name) contract.event("movie", "robocop", 1, "I'll be back") end function movie_event(name) contract.event("movie", "arnold", 2, "It's mine") contract.event("movie", "terminator", 3, "No, it's mine") end function ani_event(name) contract.event("a-time!!") contract.event("a-time!!", "pinn", "Adventure time!!", false, bignum.number("999999999999999"), {"princess bubble gum", 1}) contract.event("a-time!!", "Jake", "Adventure time!!", false, {"whatever", 1, {true, false}, bignum.number("999999999999999")}) contract.event("movie", "yoda", 3, "i'm not the ani character.") end abi.register(movie_event, ani_event) """ payload_str = "D1ZsfUyj4q8GA6AtbW81TzSTSvqaeUvcsePsaZufptRK5qSb83fyXRWdEgGhLWs17JfRNrM4iLjGe54fkyvsyjHVgFCHqTzJWK4Yz8uQwRqzF5x1g1twZ3jPP1XtJ95y43RD48qXGoeeoDsmmNErQJCux6d4eLZwE344bz5hM1DdWEd22yE6ogC37RLRtRZ5FFKm3HkxaM67G7VqWfsX5t2Tmd23Myn62hkAdNWjSBaWizqyi6ENB3VD2YJGG82bVeq9a4zMQdK58Wxnfcfqo14Vo9Y9jsY8A5QYNRi6uotRfiYt3LFrPjPBWgyQRn4qFQypSW5vfgFZvv9VBdFPGgoMN5zeBp7VNWXvE5o8CGAf3fuFu2gCGLS4DfCtQe7VNnsCUi7U1AdmdupqoxMHM6kCfEtk77YyiaaSTm4xUSt7R2hwzs2Xnfh8CLxMaH2cg3rsWF4fefs5KvnjN3F1q43og6BueK66o8NssyY41kAtincbYhDC8oHaBkMTdXD6mkhb3QECwn8dh8k9a3KTys1tdUzf99nqpK5YrAcZFDjbrmmmtcBYwZg6zdRAkQnJptvr25HzeHMfbfERH8P1XzYmjqYynFvUNv4utuWZ7avS2xvJoZph3nSa8Xuhbdw6TFLVCDZVfZB6j8kQbJnb1DoEEtvhPHLMP4StcgiE9grGQuduZ5iHYtS8Nk696Fq6Y9gzp19bWD3VKarq1XuueM6FNrzCQNY22nov4mxbM8vcxp4axdjmZNWLcdttFycazorxCNbn1YBQFzGPGzstJPN72RB9dxV17cb1TuREKTF7mVLLeahgHsY4eVnA1m5Z8U7tFKswRDTGeXv6vCt7MstVBztdd4sRfHTXKdFCgfoQk2zwzGS8FEVgxAP3Y4Tip4nuQd8hVyTiaApFmNnkD9byxUNCc44Tr9LAnRycc239HGpZjWBwsJvmb4jsY2fuEELXfSgQf4yZhnbcPC4DYPQLDRXc8E6DdLzixMk7cAfUZqododk9SWzjB9FSKtzVYWiKuyg2uZoRaxDmrtZpe6pXL8F4pzt2P2HEG6jyFn5MT9PBWhkj11vqAjWpdRgNAbTKEb5zk9ZeER9YUAT8etk2VFpAGqmGnv9CTEQr2rfDQeNgNYzoy44mNZonhi4n4zo9h2HmrSsatWa8oxbJJYihGs7zD65TiqRfnKg43Xx5qD" payload = herapy.utils.decode_address(payload_str) print(''.join('{:d} '.format(x) for x in payload)) byte_code_len = int.from_bytes(payload[:4], byteorder='little') print("payload: byte code length = ", byte_code_len) try: aergo = herapy.Aergo() print("------ Connect AERGO -----------") aergo.connect('localhost:7845') print("------ Set Sender Account -----------") sender_private_key = "6hbRWgddqcg2ZHE5NipM1xgwBDAKqLnCKhGvADWrWE18xAbX8sW" sender_account = aergo.new_account(private_key=sender_private_key) print(" > Sender Address: {}".format(sender_account.address)) print( herapy.utils.convert_bytes_to_int_str(bytes( sender_account.address))) print("------ Deploy SC -----------") tx, result = aergo.deploy_sc(amount=0, payload=payload, args=1234) print(" > TX: {}".format(tx.tx_hash)) print("{}".format(herapy.utils.convert_tx_to_json(tx))) if result.status != herapy.CommitStatus.TX_OK: eprint(" > ERROR[{0}]: {1}".format(result.status, result.detail)) aergo.disconnect() return else: print(" > result[{0}] : {1}".format(result.tx_id, result.status.name)) print(herapy.utils.convert_bytes_to_int_str(bytes(tx.tx_hash))) time.sleep(3) print("------ Check deployment of SC -----------") print(" > TX: {}".format(tx.tx_hash)) result = aergo.get_tx_result(tx.tx_hash) if result.status != herapy.TxResultStatus.CREATED: eprint(" > ERROR[{0}]:{1}: {2}".format(result.contract_address, result.status, result.detail)) aergo.disconnect() return sc_address = result.contract_address print(" > SC Address: {}".format(sc_address)) print("------ Get reading events threads -----------") movie_event_stream = aergo.receive_event_stream(sc_address, "movie", start_block_no=0) movie_thread = Thread(target=read_movie_event_stream, args=[movie_event_stream]) movie_thread.start() print("------ Call SC -----------") tx, result = aergo.call_sc(sc_address, "movie_event") print("movie_event tx hash: {}".format(str(tx.tx_hash))) time.sleep(3) print("------ Cancel 'movie' event stream -----------") movie_event_stream.cancel() while True: if movie_event_stream.stopped: break time.sleep(3) print("------ Disconnect AERGO -----------") aergo.disconnect() except Exception as e: eprint(e) traceback.print_exception(*sys.exc_info())
def run(): try: aergo = herapy.Aergo() print("------ Connect AERGO -----------") aergo.connect('localhost:7845') print("------ Set Sender Account -----------") sender_private_key = "eHoEcHnaxpGpgzknXjuwon8VFVrLkKHC4FckGuGkQ8depiDDfyUAWC3L" sender_account = aergo.new_account(private_key=sender_private_key) print(" > Sender Address: {}".format(sender_account.address)) aergo.get_account() print(" > account state of Sender") print(" - balance = {}".format(sender_account.balance)) print(" - nonce = {}".format(sender_account.nonce)) print(" - code hash = {}".format(sender_account.code_hash)) print(" - storage root = {}".format( sender_account.storage_root)) print("------ Set Receiver Account -----------") receiver_address = "AmMPQqRJ4pd8bS9xdkw5pjExtLjaUXaYGB5kagzHu4A9ckKgnBV2" print(" > Receiver Address: {}".format(receiver_address)) receiver_account = aergo.get_account(address=receiver_address) print(" > account state of Sender") print(" - balance = {}".format(receiver_account.balance)) print(" - nonce = {}".format(receiver_account.nonce)) print(" - code hash = {}".format(receiver_account.code_hash)) print(" - storage root = {}".format( receiver_account.storage_root)) print("------ Simple Send Tx -----------") simple_tx, result = aergo.send_payload(to_address=receiver_address, amount=10, payload=None, retry_nonce=3) print(" > simple TX[{}]".format(simple_tx.calculate_hash())) print("{}".format(str(simple_tx))) print(" > result: ", result) if result.status != herapy.CommitStatus.TX_OK: eprint(" > ERROR[{0}]: {1}".format(result.status, result.detail)) aergo.disconnect() return else: print(" > result[{0}] : {1}".format(result.tx_id, result.status.name)) time.sleep(2) # Can check TX in mem pool or block after some sec later print("------ Check TX in Aergo -----------", flush=True) tx = aergo.get_tx(simple_tx.tx_hash) print(" TX from Aergo: ", str(tx)) tx = tx.block.get_tx(tx.index_in_block) print(" TX in Block: ", str(tx)) time.sleep(3) print("------ Check TX status -----------") print(" > TX: {}".format(str(simple_tx.tx_hash))) tx_result = aergo.get_tx_result(simple_tx.tx_hash) print(" result: ", tx_result) if tx_result.status != herapy.TxResultStatus.SUCCESS: eprint(" > ERROR[{0}]:{1}: {2}".format(tx_result.contract_address, tx_result.status, tx_result.detail)) aergo.disconnect() return print("------ Get Sender Account Info -----------") aergo.get_account() print(" > account state of Sender") print(" - balance = {}".format(sender_account.balance)) print(" - nonce = {}".format(sender_account.nonce)) print(" - code hash = {}".format(sender_account.code_hash)) print(" - storage root = {}".format( sender_account.storage_root)) print("------ Create Tx -----------") tx = herapy.Transaction(from_address=bytes(sender_account.address), nonce=sender_account.nonce + 1, amount=10) tx.to_address = herapy.utils.decode_address(receiver_address) tx.chain_id = aergo.chain_id print(" > unsigned TX Hash: {}".format(tx.tx_hash)) print(" > unsigned TX : {}".format( herapy.utils.convert_tx_to_formatted_json(tx))) print("------ Sign Tx -----------") tx.sign = sender_account.sign_msg_hash( tx.calculate_hash(including_sign=False)) print(" > TX Signature: {}".format(tx.sign_str)) print(" > TX Hash: {}".format(tx.tx_hash)) print(" > TX : {}".format( herapy.utils.convert_tx_to_formatted_json(tx))) print("------ Send Tx -----------") tx, result = aergo.send_tx(tx) print("{}".format(herapy.utils.convert_tx_to_formatted_json(tx))) if result.status != herapy.CommitStatus.TX_OK: eprint(" > ERROR[{0}]: {1}".format(result.status, result.detail)) aergo.disconnect() return else: print(" > result[{0}] : {1}".format(result.tx_id, result.status.name)) # wait to generate a block time.sleep(3) aergo.get_account() print(" > account state of Sender") print(" - balance = {}".format(sender_account.balance)) print(" - nonce = {}".format(sender_account.nonce)) print(" - code hash = {}".format(sender_account.code_hash)) print(" - storage root = {}".format( sender_account.storage_root)) print("------ Disconnect AERGO -----------") aergo.disconnect() except Exception as e: eprint(e) traceback.print_exception(*sys.exc_info())
def __init__(self, config_file_path: str, aergo_from: str, aergo_to: str, is_from_mainnet: bool, privkey_name: str = None, privkey_pwd: str = None, anchoring_on: bool = False, auto_update: bool = False, oracle_update: bool = False, bridge_anchoring: bool = True) -> None: threading.Thread.__init__(self, name=aergo_to + " proposer") self.config_file_path = config_file_path self.config_data = self.load_config_data() self.is_from_mainnet = is_from_mainnet self.anchoring_on = anchoring_on self.auto_update = auto_update self.oracle_update = oracle_update self.bridge_anchoring = bridge_anchoring self.aergo_from = aergo_from self.aergo_to = aergo_to self.hera_from = herapy.Aergo() self.hera_to = herapy.Aergo() self.hera_from.connect(self.config_data['networks'][aergo_from]['ip']) self.hera_to.connect(self.config_data['networks'][aergo_to]['ip']) self.bridge_from = \ (self.config_data['networks'][aergo_from]['bridges'][aergo_to] ['addr']) self.bridge_to = \ (self.config_data['networks'][aergo_to]['bridges'][aergo_from] ['addr']) self.oracle_to = \ (self.config_data['networks'][aergo_to]['bridges'][aergo_from] ['oracle']) self.oracle_to_id = query_id(self.hera_to, self.oracle_to) validators = query_validators(self.hera_to, self.oracle_to) logger.info("\"%s Validators: %s\"", self.aergo_to, validators) # create all channels with validators self.channels: List[grpc._channel.Channel] = [] self.stubs: List[BridgeOperatorStub] = [] assert len(validators) == len(self.config_data['validators']), \ "Validators in config file must match bridge validators " \ "when starting (current validators connection needed to make "\ "updates).\nExpected validators: {}".format(validators) for i, validator in enumerate(self.config_data['validators']): assert validators[i] == validator['addr'], \ "Validators in config file must match bridge validators " \ "when starting (current validators connection needed to make "\ "updates).\nExpected validators: {}".format(validators) ip = validator['ip'] channel = grpc.insecure_channel(ip) stub = BridgeOperatorStub(channel) self.channels.append(channel) self.stubs.append(stub) self.pool = Pool(len(self.stubs)) # get the current t_anchor and t_final for both sides of bridge self.t_anchor, self.t_final = query_tempo( self.hera_to, self.oracle_to, ["_sv__tAnchor", "_sv__tFinal"]) logger.info("\"%s (t_final=%s) -> %s : t_anchor=%s\"", aergo_from, self.t_final, aergo_to, self.t_anchor) if not anchoring_on and not auto_update: # if anchoring and auto update are off, use proposer as monitoring # system return logger.info("\"Set Sender Account\"") if privkey_name is None: privkey_name = 'proposer' keystore_path = self.config_data['wallet'][privkey_name]['keystore'] with open(keystore_path, "r") as f: keystore = f.read() if privkey_pwd is None: while True: try: privkey_pwd = getpass("Decrypt exported private key '{}'\n" "Password: "******"\"Wrong password, try again\"") else: self.hera_to.import_account_from_keystore(keystore, privkey_pwd) logger.info("\"%s Proposer Address: %s\"", aergo_to, self.hera_to.account.address)
def deploy_oracle(config_file_path: str, payload_str: str, net1: str, net2: str, privkey_name: str = None, privkey_pwd: str = None) -> None: payload = herapy.utils.decode_address(payload_str) with open(config_file_path, "r") as f: config_data = json.load(f) print("------ DEPLOY ORACLE BETWEEN {} & {} -----------".format( net1, net2)) aergo1 = herapy.Aergo() aergo2 = herapy.Aergo() print("------ Connect AERGO -----------") aergo1.connect(config_data['networks'][net1]['ip']) aergo2.connect(config_data['networks'][net2]['ip']) print("------ Set Sender Account -----------") if privkey_name is None: privkey_name = 'proposer' if privkey_pwd is None: privkey_pwd = getpass( "Decrypt Aergo keystore: '{}'\nPassword: "******"r") as f: keystore1 = f.read() with open(keystore_path2, "r") as f: keystore2 = f.read() aergo1.import_account_from_keystore(keystore1, privkey_pwd) aergo2.import_account_from_keystore(keystore2, privkey_pwd) print(" > Sender Address: {}".format(aergo1.account.address)) print("------ Deploy SC -----------") # get validators from config file validators = [] for validator in config_data['validators']: validators.append(validator['addr']) print('validators : ', validators) bridge1 = config_data['networks'][net1]['bridges'][net2]['addr'] bridge2 = config_data['networks'][net2]['bridges'][net1]['addr'] bridge_trie_key1 = \ "0x" + hashlib.sha256(decode_address(bridge1)).digest().hex() bridge_trie_key2 = \ "0x" + hashlib.sha256(decode_address(bridge2)).digest().hex() t_anchor1 = config_data['networks'][net1]['bridges'][net2]['t_anchor'] t_final1 = config_data['networks'][net1]['bridges'][net2]['t_final'] t_anchor2 = config_data['networks'][net2]['bridges'][net1]['t_anchor'] t_final2 = config_data['networks'][net2]['bridges'][net1]['t_final'] # get already deployed bridge addresses from config,json tx1, result1 = aergo1.deploy_sc( amount=0, payload=payload, args=[validators, bridge1, bridge_trie_key2, t_anchor1, t_final1]) tx2, result2 = aergo2.deploy_sc( amount=0, payload=payload, args=[validators, bridge2, bridge_trie_key1, t_anchor2, t_final2]) if result1.status != herapy.CommitStatus.TX_OK: print(" > ERROR[{0}]: {1}".format(result1.status, result1.detail)) aergo1.disconnect() aergo2.disconnect() return print(" > result[{0}] : {1}".format(result1.tx_id, result1.status.name)) if result2.status != herapy.CommitStatus.TX_OK: print(" > ERROR[{0}]: {1}".format(result2.status, result2.detail)) aergo1.disconnect() aergo2.disconnect() return print(" > result[{0}] : {1}".format(result2.tx_id, result2.status.name)) print("------ Check deployment of SC -----------") result1 = aergo1.wait_tx_result(tx1.tx_hash) if result1.status != herapy.TxResultStatus.CREATED: print(" > ERROR[{0}]:{1}: {2}".format(result1.contract_address, result1.status, result1.detail)) aergo1.disconnect() aergo2.disconnect() return result2 = aergo2.wait_tx_result(tx2.tx_hash) if result2.status != herapy.TxResultStatus.CREATED: print(" > ERROR[{0}]:{1}: {2}".format(result2.contract_address, result2.status, result2.detail)) aergo1.disconnect() aergo2.disconnect() return oracle1 = result1.contract_address oracle2 = result2.contract_address print(" > Oracle Address {}: {}".format(net1, oracle1)) print(" > Oracle Address {}: {}".format(net2, oracle2)) print("------ Store bridge addresses in config.json -----------") config_data['networks'][net1]['bridges'][net2]['oracle'] = oracle1 config_data['networks'][net2]['bridges'][net1]['oracle'] = oracle2 with open(config_file_path, "w") as f: json.dump(config_data, f, indent=4, sort_keys=True) print("------ Transfer bridge control to oracles -----------") tx1, result1 = aergo1.call_sc(bridge1, "oracleUpdate", args=[oracle1], amount=0) tx2, result2 = aergo2.call_sc(bridge2, "oracleUpdate", args=[oracle2], amount=0) if result1.status != herapy.CommitStatus.TX_OK: print("oracleUpdate Tx commit failed : {}".format(result1)) aergo1.disconnect() aergo2.disconnect() return if result2.status != herapy.CommitStatus.TX_OK: print("oracleUpdate Tx commit failed : {}".format(result2)) aergo1.disconnect() aergo2.disconnect() return # Check oracle transfer success result1 = aergo1.wait_tx_result(tx1.tx_hash) if result1.status != herapy.TxResultStatus.SUCCESS: print("oracleUpdate Tx execution failed : {}".format(result1)) aergo1.disconnect() aergo2.disconnect() return result2 = aergo2.wait_tx_result(tx2.tx_hash) if result2.status != herapy.TxResultStatus.SUCCESS: print("oracleUpdate Tx execution failed : {}".format(result2)) aergo1.disconnect() aergo2.disconnect() return print("------ Disconnect AERGO -----------") aergo1.disconnect() aergo2.disconnect()
def deploy_bridge( config_path: str, lua_bytecode_path: str, sol_bytecode_path: str, eth_net: str, aergo_net: str, aergo_erc20: str = 'aergo_erc20', privkey_name: str = None, privkey_pwd: str = None, ) -> None: """ Deploy brige contract on Aergo and Ethereum.""" with open(config_path, "r") as f: config_data = json.load(f) with open(lua_bytecode_path, "r") as f: lua_bytecode = f.read()[:-1] with open(sol_bytecode_path, "r") as f: sol_bytecode = f.read() bridge_abi_path = \ config_data['networks'][eth_net]['bridges'][aergo_net]['bridge_abi'] with open(bridge_abi_path, "r") as f: bridge_abi = f.read() if privkey_name is None: privkey_name = 'proposer' t_anchor_aergo = \ config_data['networks'][aergo_net]['bridges'][eth_net]['t_anchor'] t_final_aergo = \ config_data['networks'][aergo_net]['bridges'][eth_net]['t_final'] t_anchor_eth = \ config_data['networks'][eth_net]['bridges'][aergo_net]['t_anchor'] t_final_eth = \ config_data['networks'][eth_net]['bridges'][aergo_net]['t_final'] unfreeze_fee = \ config_data['networks'][aergo_net]['bridges'][eth_net]['unfreeze_fee'] aergo_erc20_addr = \ config_data['networks'][eth_net]['tokens'][aergo_erc20]['addr'] print("------ DEPLOY BRIDGE BETWEEN Aergo & Ethereum -----------") print("------ Connect Hera and Web3 providers -----------") aergo = herapy.Aergo() aergo.connect(config_data['networks'][aergo_net]['ip']) ip = config_data['networks'][eth_net]['ip'] w3 = Web3(Web3.HTTPProvider(ip)) eth_poa = config_data['networks'][eth_net]['isPOA'] if eth_poa: w3.middleware_onion.inject(geth_poa_middleware, layer=0) assert w3.isConnected() print("------ Set Sender Account -----------") if privkey_pwd is None: privkey_pwd = getpass( "Decrypt Aergo private key '{}'\nPassword: "******"r") as f: keystore = f.read() aergo.import_account_from_keystore(keystore, privkey_pwd) print(" > Sender Address Aergo: {}".format(aergo.account.address)) keystore_path = config_data["wallet-eth"][privkey_name]['keystore'] with open(keystore_path, "r") as f: keystore = f.read() if privkey_pwd is None: privkey_pwd = getpass( "Decrypt Ethereum keystore '{}'\nPassword: "******" > Sender Address Ethereum: {}".format(sender)) print("------ Deploy Aergo SC -----------") payload = herapy.utils.decode_address(lua_bytecode) args = \ [aergo_erc20_addr[2:].lower(), t_anchor_aergo, t_final_aergo, {"_bignum": str(unfreeze_fee)}] tx, result = aergo.deploy_sc(amount=0, payload=payload, args=args) if result.status != herapy.CommitStatus.TX_OK: print(" > ERROR[{0}]: {1}".format(result.status, result.detail)) aergo.disconnect() return print(" > result[{0}] : {1}".format(result.tx_id, result.status.name)) result = aergo.wait_tx_result(tx.tx_hash) if result.status != herapy.TxResultStatus.CREATED: print(" > ERROR[{0}]:{1}: {2}".format(result.contract_address, result.status, result.detail)) aergo.disconnect() return aergo_bridge = result.contract_address print("------ Deploy Ethereum SC -----------") receipt = deploy_contract(sol_bytecode, bridge_abi, w3, 8000000, 20, privkey, t_anchor_eth, t_final_eth) eth_bridge = receipt.contractAddress print(" > Bridge Address Ethereum: {}".format(eth_bridge)) print(" > Bridge Address Aergo: {}".format(aergo_bridge)) print("------ Store bridge addresses in test_config.json -----------") (config_data['networks'][eth_net]['bridges'][aergo_net]['addr'] ) = eth_bridge (config_data['networks'][aergo_net]['bridges'][eth_net]['addr'] ) = aergo_bridge with open(config_path, "w") as f: json.dump(config_data, f, indent=4, sort_keys=True) print("------ Disconnect AERGO -----------") aergo.disconnect()
def __init__(self, config_file_path: str, aergo_net: str, eth_net: str, privkey_name: str = None, privkey_pwd: str = None, anchoring_on: bool = False, auto_update: bool = False, oracle_update: bool = False, root_path: str = './', eth_gas_price: int = None, bridge_anchoring: bool = True) -> None: threading.Thread.__init__(self, name="EthProposerClient") if eth_gas_price is None: eth_gas_price = 10 self.config_file_path = config_file_path config_data = load_config_data(config_file_path) self.eth_net = eth_net self.aergo_net = aergo_net self.anchoring_on = anchoring_on self.auto_update = auto_update self.oracle_update = oracle_update self.bridge_anchoring = bridge_anchoring logger.info("\"Connect Aergo and Ethereum providers\"") self.hera = herapy.Aergo() self.hera.connect(config_data['networks'][aergo_net]['ip']) # Web3 instance for reading blockchains state, shared with # EthValConnect. ip = config_data['networks'][eth_net]['ip'] self.web3 = Web3(Web3.HTTPProvider(ip)) eth_poa = config_data['networks'][eth_net]['isPOA'] if eth_poa: self.web3.middleware_onion.inject(geth_poa_middleware, layer=0) assert self.web3.isConnected() # bridge contract bridge_abi_path = (config_data['networks'][eth_net]['bridges'] [aergo_net]['bridge_abi']) with open(root_path + bridge_abi_path, "r") as f: bridge_abi = f.read() eth_bridge_address = ( config_data['networks'][eth_net]['bridges'][aergo_net]['addr']) self.eth_bridge = self.web3.eth.contract(address=eth_bridge_address, abi=bridge_abi) # oracle contract oracle_abi_path = (config_data['networks'][eth_net]['bridges'] [aergo_net]['oracle_abi']) with open(root_path + oracle_abi_path, "r") as f: oracle_abi = f.read() eth_oracle_address = ( config_data['networks'][eth_net]['bridges'][aergo_net]['oracle']) self.eth_oracle = self.web3.eth.contract(address=eth_oracle_address, abi=oracle_abi) self.aergo_bridge = ( config_data['networks'][aergo_net]['bridges'][eth_net]['addr']) # get the current t_anchor and t_final for anchoring on etherem self.t_anchor = self.eth_bridge.functions._tAnchor().call() self.t_final = self.eth_bridge.functions._tFinal().call() logger.info("\"%s (t_final=%s ) -> %s : t_anchor=%s\"", aergo_net, self.t_final, eth_net, self.t_anchor) if privkey_name is None: privkey_name = 'proposer' keystore = config_data["wallet-eth"][privkey_name]['keystore'] with open(root_path + keystore, "r") as f: encrypted_key = f.read() if privkey_pwd is None: privkey_pwd = getpass("Decrypt Ethereum keystore '{}'\n" "Password: "******"\"Connect to EthValidators\"") self.val_connect = EthValConnect(config_data, self.web3, eth_oracle_address, oracle_abi)
def run(): try: aergo = herapy.Aergo() aergo.new_account(skip_state=True) print("------ Connect AERGO -----------") aergo.connect('localhost:7845') print("------ Get Accounts without State in Node -----------") accounts = aergo.get_node_accounts(skip_state=True) for i, account in enumerate(accounts): print(" > account state : {}".format(account)) print(" - balance") print(" + aergo = {}".format( account.balance.aergo)) print(" + gaer = {}".format( account.balance.gaer)) print(" + aer = {}".format( account.balance.aer)) print(" - nonce = {}".format(account.nonce)) print(" - code hash = {}".format( account.code_hash)) print(" - storage root = {}".format( account.storage_root)) print(" - sql recovery point = {}".format( account.sql_recovery_point)) print("------ Get Accounts in Node -----------") accounts = aergo.get_node_accounts() for i, account in enumerate(accounts): print(" > account state : {}".format(account)) print(" - balance") print(" + aergo = {}".format( account.balance.aergo)) print(" + gaer = {}".format( account.balance.gaer)) print(" + aer = {}".format( account.balance.aer)) print(" - nonce = {}".format(account.nonce)) print(" - code hash = {}".format( account.code_hash)) print(" - storage root = {}".format( account.storage_root)) print(" - sql recovery point = {}".format( account.sql_recovery_point)) print("------ Create Account -----------") account = aergo.new_account() print("Private Key = {}".format(account.private_key)) print("Public Key = {}".format(account.public_key)) print("Address = {}".format(account.address)) print("------ Get Account State -----------") aergo.get_account() print(" > account state in 'aergo'") print(" - balance") print(" + aergo = {}".format( account.balance.aergo)) print(" + gaer = {}".format(account.balance.gaer)) print(" + aer = {}".format(account.balance.aer)) print(" - nonce = {}".format(account.nonce)) print(" - code hash = {}".format(account.code_hash)) print(" - storage root = {}".format(account.storage_root)) print(" - sql recovery point = {}".format( account.sql_recovery_point)) print(account) print("------ Get Configured Account -----------") accounts = [ { "private_key": "eHoEcHnaxpGpgzknXjuwon8VFVrLkKHC4FckGuGkQ8depiDDfyUAWC3L", "address": "AmPZKCJpT98V9Tc8dBUbRg78M1jgoB1ZEh97Rs1r5KewPcCiURf7", }, ] for i, account in enumerate(accounts): print(" [{}]".format(i)) print(" > private key : {}".format(account['private_key'])) print(" > address : {}".format(account['address'])) # check account state a = aergo.get_account(address=account['address']) print(" > account state : {}".format(a)) print(" - balance") print(" + aergo = {}".format(a.balance.aergo)) print(" + gaer = {}".format(a.balance.gaer)) print(" + aer = {}".format(a.balance.aer)) print(" - nonce = {}".format(a.nonce)) print(" - code hash = {}".format(a.code_hash)) print(" - storage root = {}".format(a.storage_root)) print(" - sql recovery point = {}".format( a.sql_recovery_point)) print("------ Disconnect AERGO -----------") aergo.disconnect() except Exception as e: eprint(e) traceback.print_exception(*sys.exc_info())
def run(): try: aergo = herapy.Aergo() print("------ Connect AERGO -----------") aergo.connect('localhost:7845') print("------ Get Node Info -----------") node_state = aergo.get_node_state() print("Node State: {}".format(str(node_state))) node_info = aergo.get_node_info() print("Node Info: {}".format(str(node_info))) print("------ Get Blockchain Info -----------") blockchain_info = aergo.get_chain_info() print("Blockchain Info: {}".format(str(blockchain_info))) blockchain_info = aergo.get_chain_info(with_consensus_info=False) print("Blockchain Info: {}".format(str(blockchain_info))) print("------ Get Consensus Info -----------") consensus_info = aergo.get_consensus_info() print("Consensus Info: {}".format(str(consensus_info))) print("------ Get Blockchain Status -----------") blockchain_status = aergo.get_status() print("Blockchain Status: {}".format(str(blockchain_status))) print("Best Block Hash = {}".format( str(blockchain_status.best_block_hash))) print("Best Block Height = {}".format( blockchain_status.best_block_height)) print("Best Chain ID Hash = {}".format( blockchain_status.best_chain_id_hash)) print("base58(Best Chain ID Hash) = {}".format( blockchain_status.best_chain_id_hash_b58)) consensus_info = blockchain_status.consensus_info print("Consensus Info = {}".format(consensus_info)) print("Consensus Info: type = {}".format(consensus_info.type)) print("Consensus Info: status = {}".format(consensus_info.status)) print("Consensus Info: LIB hash = {}".format(consensus_info.lib_hash)) print("Consensus Info: LIB no = {}".format(consensus_info.lib_no)) best_block_hash, best_block_height = aergo.get_blockchain_status() print("Best Block Hash = {}".format(best_block_hash)) print("str(Best Block Hash) = {}".format(str(best_block_hash))) print("bytes(Best Block Hash) = {}".format(bytes(best_block_hash))) print("int(Best Block Hash) = {}".format( convert_bytes_to_int_str(bytes(best_block_hash)))) print("hex(Best Block Hash) = {}".format( convert_bytes_to_hex_str(bytes(best_block_hash)))) print("Best Block Height = {}".format(best_block_height)) print("------ Get Blockchain Headers -----------") block_headers = aergo.get_block_headers(block_height=best_block_height, offset=best_block_height - 1) for i, b in enumerate(block_headers): print('[{}] block: {}'.format(i, str(b))) print("------ Get Blockchain metas -----------") block_metas = aergo.get_block_metas(block_height=best_block_height, offset=best_block_height - 1) for i, b in enumerate(block_metas): print('[{}] block: {}'.format( i, json.dumps(b.json(header_only=True), indent=2))) print("------ Get Block Status -----------") block = aergo.get_block(best_block_hash) print("Block Chain ID Hash = ", block.chain_id_hash) print("base58(Block Chain ID Hash) = ", block.chain_id_hash_b58) print("Block Hash = ", block.hash) print(" Height = ", block.height) print(" Timestamp = ", block.timestamp) print(" Blocks Root Hash = ", block.blocks_root_hash) print(" Txs Root Hash = ", block.txs_root_hash) print(" Confirm = ", block.confirms) print(" Pub Key = ", block.public_key) print(" Sign = ", block.sign) print(" previous block hash =\n{}".format(block.prev)) print(" Txs = ", block.tx_list) print(json.dumps(block.json(), indent=2)) block = aergo.get_block(block_height=best_block_height) print(block) print("Block Hash = ", block.hash) print(" Height = ", block.height) print(" Timestamp = ", block.timestamp) print(" Blocks Root Hash = ", block.blocks_root_hash) print(" Txs Root Hash = ", block.txs_root_hash) print(" Confirm = ", block.confirms) print(" Pub Key = ", block.public_key) print(" Sign = ", block.sign) print(" previous block hash =\n{}".format(block.prev)) print(" Txs = ", block.tx_list) print("------ Get Peers -----------") # definition of peer needs to describe. peers = aergo.get_peers() for p in peers: print(p) print("------ Get Node State -----------") node_state = aergo.get_node_state() print(node_state) node_state_fmt_txt = json.dumps(node_state, indent=2, sort_keys=True) print(node_state_fmt_txt) print("------ Disconnect AERGO -----------") aergo.disconnect() except Exception as e: eprint(e) traceback.print_exception(*sys.exc_info())
def run(): print("------ Payload -----------") """ -- Define global variables. state.var { a = state.value(), } function constructor(name) a:set(name) end function set_name(name) a:set(name) end function get_name() return a:get() end function test_array(array) a:set(array[1]) end function say_hello() a:set("hello") end abi.register(set_name, get_name, test_array, say_hello) """ payload_str = "2bTAKwCcCqs1n91vFF5YnBBcaTLNsxhqzGgM8vcVAG3HqQLp1uZZSwvmnj8CEEm9GTvogDf3r6ioqHjbfBisjRzwUJxr6msFuf4vVuzbWEXtbShu43ZpLbJdT1NECStCEDGFPRsn3pc7jQ1FumPGB9GwGY7Y7wNN1t4kLMQPNxJCmDFAwLA6BAyCGpzW2g5rtHuWodTMTposF4EBRxbvsXYWvrDYLTK7JGbDsq4neBzXVtmJjereb7i6fX8Fug1LJ9GgYskTKdqcBjugxEoipjsAALtnr7mcUPoPFygbQzXbHsW13UwjhBxKsEvWYZm1hC8QxCeiRbHdx8VY5ES2ugR8Dt4uhiboAbaLofpnGRcPofgFGXiwDfESQgNZBjHP1DeEzh7gGh6fzABcw3LSjQLC9RETFWyUnWY3dU4iqH3PsVNhBFgHCUepBBphvwPT6UoictgsWzsnFdf1peiDsfXFE9uSTKWDCMhqgaETSLZdn8QiGBwMvZ1pEkP6xmh9389mFXCZ4ERNGUGkk6xNfN7xdZhRCeXxZupgtNDREX5PrHPveXEMbzThAMV7Rqzy3MazDaCFxjkbUVgQjWsHYhwEBRMvYSd2p621nZzcb9GFbh9tpXhwoLYpLp89Qhi9oTy61AD2GVFgQmdWF9neD1GvauVkCNFzWmEUkdSU3F6yBRwBm2cs8oJEieFu1zETLsMyXydTN5WqHFuGs2PaV1XRwPVRLeYiwo2xmgJMssHaGtR8pmb8TrQpTJbJdgreCVn8GiGzYizvEcRz9m8aFdompJ2m2QR7TDLCCjZx2UqRJdcQZmyxEAtzjnCCgD7Gwj95ZHkFxzoEEHTLYbG6uaneRrQWnzabAaRe2392qJnEkiNug9gkdJfsRFapbVxupH9zkoAmFP5xoWeGrkknUw61E4tX" payload = herapy.utils.decode_address(payload_str) print(''.join('{:d} '.format(x) for x in payload)) byte_code_len = int.from_bytes(payload[:4], byteorder='little') print("payload: byte code length = ", byte_code_len) try: aergo = herapy.Aergo() print("------ Connect AERGO -----------") aergo.connect('localhost:7845') print("------ Set Sender Account -----------") sender_private_key = "6hbRWgddqcg2ZHE5NipM1xgwBDAKqLnCKhGvADWrWE18xAbX8sW" sender_account = aergo.new_account(private_key=sender_private_key) print(" > Sender Address: {}".format(sender_account.address)) print( herapy.utils.convert_bytes_to_int_str(bytes( sender_account.address))) aergo.get_account() print(" > account state of Sender") print(" - balance = {}".format(sender_account.balance)) print(" - nonce = {}".format(sender_account.nonce)) print(" - code hash = {}".format(sender_account.code_hash)) print(" - storage root = {}".format( sender_account.storage_root)) print("------ Set Receiver Account -----------") receiver_address = "AmNHbk46L5ZaFH942mxDrunhUb34S8xRd7ygNnqaW5nqJDt5ugKD" print(" > Receiver Address: {}".format(receiver_address)) print("------ Deploy SC -----------") tx, result = aergo.deploy_sc(amount=0, payload=payload, args=1234) print(" > TX: {}".format(tx.tx_hash)) print("{}".format(herapy.utils.convert_tx_to_json(tx))) if result.status != herapy.CommitStatus.TX_OK: eprint(" > ERROR[{0}]: {1}".format(result.status, result.detail)) aergo.disconnect() return else: print(" > result[{0}] : {1}".format(result.tx_id, result.status.name)) print(herapy.utils.convert_bytes_to_int_str(bytes(tx.tx_hash))) time.sleep(3) aergo.get_account() print("------ Check deployment of SC -----------") print(" > TX: {}".format(tx.tx_hash)) result = aergo.get_tx_result(tx.tx_hash) if result.status != herapy.TxResultStatus.CREATED: eprint(" > ERROR[{0}]:{1}: {2}".format(result.contract_address, result.status, result.detail)) aergo.disconnect() return sc_address = result.contract_address print(" > SC Address: {}".format(sc_address)) print("------ Fail SC -----------") tx, result = aergo.call_sc(sc_address, "set_none") time.sleep(3) result = aergo.get_tx_result(tx.tx_hash) print(" > ERROR[{0}]:{1}: {2}".format(result.contract_address, result.status, result.detail)) print("------ Query SC -----------") result = aergo.query_sc(sc_address, "get_name") print(result) print("------ Call SC -----------") tx, result = aergo.call_sc(sc_address, "test_array", args=[["a", "b"]]) print("-------Wait for tx result--------") result = aergo.wait_tx_result(tx.tx_hash) if result.status != herapy.TxResultStatus.SUCCESS: eprint(" > ERROR[{0}]:{1}: {2}".format(result.contract_address, result.status, result.detail)) aergo.disconnect() return print("------ Check result of Call SC -----------") print(" > TX: {}".format(tx.tx_hash)) result = aergo.get_tx_result(tx.tx_hash) if result.status != herapy.TxResultStatus.SUCCESS: eprint(" > ERROR[{0}]:{1}: {2}".format(result.contract_address, result.status, result.detail)) aergo.disconnect() return print("------ Query SC -----------") result = aergo.query_sc(sc_address, "get_name") print(result) print("------- Get smart contract abi --------") abi = aergo.get_abi(sc_address) print(abi.functions[0]) print("------ Disconnect AERGO -----------") aergo.disconnect() except Exception as e: eprint(e) traceback.print_exception(*sys.exc_info())
def __init__( self, config_file_path: str, aergo1: str, aergo2: str, privkey_name: str = None, privkey_pwd: str = None, validator_index: int = 0, anchoring_on: bool = False, auto_update: bool = False, oracle_update: bool = False, ) -> None: """ aergo1 is considered to be the mainnet side of the bridge. Proposers should set anchor.is_from_mainnet accordingly """ self.config_file_path = config_file_path config_data = self.load_config_data() self.aergo1 = aergo1 self.aergo2 = aergo2 self.hera1 = herapy.Aergo() self.hera2 = herapy.Aergo() self.anchoring_on = anchoring_on self.auto_update = auto_update self.oracle_update = oracle_update self.hera1.connect(config_data['networks'][aergo1]['ip']) self.hera2.connect(config_data['networks'][aergo2]['ip']) self.validator_index = validator_index self.bridge1 = \ config_data['networks'][aergo1]['bridges'][aergo2]['addr'] self.bridge2 = \ config_data['networks'][aergo2]['bridges'][aergo1]['addr'] self.oracle1 = \ config_data['networks'][aergo1]['bridges'][aergo2]['oracle'] self.oracle2 = \ config_data['networks'][aergo2]['bridges'][aergo1]['oracle'] self.id1 = query_id(self.hera1, self.oracle1) self.id2 = query_id(self.hera2, self.oracle2) # check validators are correct validators1 = query_validators(self.hera1, self.oracle1) validators2 = query_validators(self.hera2, self.oracle2) assert validators1 == validators2, \ "Validators should be the same on both sides of bridge" logger.info("\"Bridge validators : %s\"", validators1) # get the current t_anchor and t_final for both sides of bridge t_anchor1, t_final1 = query_tempo( self.hera1, self.oracle1, ["_sv__tAnchor", "_sv__tFinal"] ) t_anchor2, t_final2 = query_tempo( self.hera2, self.oracle2, ["_sv__tAnchor", "_sv__tFinal"] ) logger.info( "\"%s <- %s (t_final=%s) : t_anchor=%s\"", aergo1, aergo2, t_final1, t_anchor1 ) logger.info( "\"%s (t_final=%s) -> %s : t_anchor=%s\"", aergo1, t_final2, aergo2, t_anchor2 ) if auto_update: logger.warning( "\"WARNING: This validator will vote for settings update in " "config.json\"" ) if len(validators1) != len(validators2): logger.warning( "\"WARNING: different number of validators on both sides " "of the bridge\"" ) if len(config_data['validators']) != len(validators1): logger.warning( "\"WARNING: This validator is voting for a new set of %s " "validators\"", aergo1 ) if len(config_data['validators']) != len(validators2): logger.warning( "\"WARNING: This validator is voting for a new set of %s " "validators\"", aergo2 ) for i, validator in enumerate(config_data['validators']): try: if validator['addr'] != validators1[i]: logger.warning( "\"WARNING: This validator is voting for a new set" " of %s validators\"", aergo1 ) except IndexError: # new validators index larger than current validators pass try: if validator['addr'] != validators2[i]: logger.warning( "\"WARNING: This validator is voting for a new set" " of %s validators\"", aergo2 ) except IndexError: # new validators index larger than current validators pass t_anchor1_c = (config_data['networks'][aergo1] ['bridges'][aergo2]['t_anchor']) t_final1_c = (config_data['networks'][aergo1] ['bridges'][aergo2]['t_final']) t_anchor2_c = (config_data['networks'][aergo2]['bridges'] [aergo1]['t_anchor']) t_final2_c = (config_data['networks'][aergo2]['bridges'] [aergo1]['t_final']) if t_anchor1_c != t_anchor1: logger.warning( "\"WARNING: This validator is voting to update anchoring" " periode of %s on %s\"", aergo2, aergo1 ) if t_final1_c != t_final1: logger.warning( "\"WARNING: This validator is voting to update finality " " of %s on %s\"", aergo2, aergo1 ) if t_anchor2_c != t_anchor2: logger.warning( "\"WARNING: This validator is voting to update anchoring" " periode of %s on %s\"", aergo1, aergo2 ) if t_final2_c != t_final2: logger.warning( "\"WARNING: This validator is voting to update finality " " of %s on %s\"", aergo1, aergo2 ) if privkey_name is None: privkey_name = 'validator' keystore_path = config_data['wallet'][privkey_name]['keystore'] with open(keystore_path, "r") as f: keystore = f.read() if privkey_pwd is None: while True: try: privkey_pwd = getpass("Decrypt exported private key '{}'\n" "Password: "******"\"Wrong password, try again\"") else: self.hera1.import_account_from_keystore(keystore, privkey_pwd) self.hera2.import_account_from_keystore(keystore, privkey_pwd) self.address = str(self.hera1.account.address) logger.info("\"Validator Address: %s\"", self.address)