def test_account_from_keystore_without_address_and_uuid(): keystore = dict(KEYSTORE) keystore.pop("address") keystore.pop("id") account = Account(keystore) assert account.address is None account.unlock(PASSWORD) assert account.address == privatekey_to_address(PRIVKEY) assert account.uuid is None account.uuid = new_uuid = UUID(hex="1234567890abcdef1234567890abcdef") assert str(new_uuid) in repr(account)
def main(keystore_file, password, rpc_url, eth_amount, targets_file) -> None: web3 = Web3(HTTPProvider(rpc_url)) with open(keystore_file, "r") as keystore: account = Account(json.load(keystore), password, keystore_file) assert account.privkey assert account.address print("Using account:", to_checksum_address(account.address)) client = JSONRPCClient( web3, account.privkey, block_num_confirmations=DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS) targets = [t.strip() for t in targets_file] balance = client.balance(client.address) balance_needed = len(targets) * eth_amount if balance_needed * WEI_TO_ETH > balance: print( "Not enough balance to fund {} accounts with {} eth each. Need {}, have {}" .format(len(targets), eth_amount, balance_needed, balance / WEI_TO_ETH)) print("Sending {} eth to:".format(eth_amount)) for target in targets: print(" - {}".format(target)) client.send_transaction(to=target, startgas=21000, value=eth_amount * WEI_TO_ETH)
def test_account_from_keystore_and_password(): keystore = dict(KEYSTORE) keystore.pop("address") account = Account(keystore, PASSWORD) assert not account.locked assert account.address == decode_hex(KEYSTORE["address"])
def main(keystore_file, password, rpc_url, eth_amount, targets_file) -> None: web3 = Web3(HTTPProvider(rpc_url)) with open(keystore_file, "r") as keystore: account = Account(json.load(keystore), password, keystore_file) assert account.privkey, "Could not decode keystore file: wrong password" assert account.address, "Could not decode keystore file: no 'address' field found" print("Using account:", to_checksum_address(account.address)) client = JSONRPCClient( web3, account.privkey, block_num_confirmations=DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS) targets = [t.strip() for t in targets_file] balance = client.balance(client.address) balance_needed = len(targets) * eth_amount if balance_needed * WEI_TO_ETH > balance: print( "Not enough balance to fund {} accounts with {} eth each. Need {}, have {}" .format(len(targets), eth_amount, balance_needed, balance / WEI_TO_ETH)) print("Sending {} eth to:".format(eth_amount)) for target in targets: print(" - {}".format(target)) gas_price = web3.eth.gasPrice # pylint: disable=no-member client.transact( EthTransfer(to_address=target, value=eth_amount * WEI_TO_ETH, gas_price=gas_price))
def private_to_account(ctx, privatekey, password): # privatekey is provided in the console, so it's expected to be hexadecimal privatekey = safe_address_decode(privatekey) # cast the values to bytes because it is the expected type in the Crypto library password = bytes(password) privkey = bytes(privatekey) account = Account.new(password, key=privkey) print(account.dump())
def test_account_from_keystore(): keystore = dict(KEYSTORE) account = Account(keystore) assert account.locked assert account.privkey is None assert account.uuid == KEYSTORE["id"] assert account.address == decode_hex(KEYSTORE["address"]) with pytest.raises(ValueError): account.unlock("wrong-password") assert account.locked account.unlock(PASSWORD) account.unlock("wrong-password") # ignored as the account is not locked assert not account.locked assert account.privkey == PRIVKEY assert account.pubkey == privatekey_to_publickey(PRIVKEY) account.lock() assert account.locked assert account.privkey is None assert account.pubkey is None
def main(keystore_file, password, rpc_url, eth_amount, targets_file): web3 = Web3(HTTPProvider(rpc_url)) with open(keystore_file, 'r') as keystore: account = Account(json.load(keystore), password, keystore_file) print("Using account:", to_checksum_address(account.address)) client = JSONRPCClient(web3, account.privkey) targets = [t.strip() for t in targets_file] balance = client.balance(client.sender) balance_needed = len(targets) * eth_amount if balance_needed * WEI_TO_ETH > balance: print("Not enough balance to fund {} accounts with {} eth each. Need {}, have {}".format( len(targets), eth_amount, balance_needed, balance / WEI_TO_ETH, )) print("Sending {} eth to:".format(eth_amount)) for target in targets: print(" - {}".format(target)) client.send_transaction(to=target, value=eth_amount * WEI_TO_ETH)
def load_account_obj(keystore_file, password): with open(keystore_file, "r") as keystore: account = Account(json.load(keystore), password, keystore_file) log.info("Using account", account=to_checksum_address(account.address)) return account
def main( keystore_file, password, eth_rpc_url, token_address, bind_addr, public_url, redis_host, redis_port, faucet_amount_eth, faucet_amount_tokens, faucet_timeout, log_path, ): log_file_name = f'onboarding-server.{datetime.now().isoformat()}.log' log_file_name = os.path.join(log_path, log_file_name) click.secho(f'Writing log to {log_file_name}', fg='yellow') configure_logging( {'': 'INFO', 'raiden': 'DEBUG', 'onboarding_server': 'DEBUG'}, debug_log_file_name=log_file_name, _first_party_packages=frozenset(['raiden', 'onboarding_server']), ) with open(keystore_file, 'r') as keystore: account = Account(json.load(keystore), password, keystore_file) log.info("Using account", account=to_checksum_address(account.address)) client = JSONRPCClient( Web3(HTTPProvider(eth_rpc_url)), privkey=account.privkey, gas_price_strategy=fast_gas_price_strategy, ) token_ctr = _get_token_ctr(client, token_address) if public_url is None: public_url = f'http://{bind_addr}/' redis = StrictRedis(redis_host, redis_port) app = Flask(__name__) @app.route('/', methods=['GET']) def index(): return f''' <html> <body style=" background: linear-gradient(90deg, #fca09a, #fcccd3, #ffcc9d, #98ddad, #81d7ec, #a0aaed);"> <div style="float:left; width: 80%"> <h1>Raiden Hands on Workshop @ devcon iv</h1> <h2>Kovan ETH & {token_ctr.contract.call().name()} faucet</h2> </div> <div style="float:right; width: 20%"> <img src="https://raiden.network/assets/logo-black.png" /> </div> <p style="clear: both; overflow: hidden;"> To request KETH and tokens send a <code>POST</code> request to <code>{public_url}</code> with a JSON body containing <code>{{"address": "<eth-address>", "client_hash": "<client-auth-hash>"}}</code>. </p> ''' @app.route('/', methods=['POST']) def faucet(): if not request.json: log.info('Invlid request', remote=request.remote_addr) return Response('Invalid request', 406) address = request.json.get('address') client_hash = request.json.get('client_hash') if not address or not is_address(address) or not client_hash: log.info('Invlid request.', remote=request.remote_addr, address=address, client_hash=client_hash) return Response('Invalid request. address or client_hash missing.', 406) address = to_checksum_address(address) address_key = f'{REDIS_KEY_KNOWN_ADDR}:{address}' client_key = f'{REDIS_KEY_KNOWN_CLIENT}:{client_hash}' if redis.get(address_key) is not None or redis.get(client_key) is not None: log.info('Quota exceeded', address=address, client_hash=client_hash) return Response('{"result": "error", "error": "quota exceeded"}', 429, content_type='application/json') log.info('Fauceting', target=address) txhashes = [ client.send_transaction(address, faucet_amount_eth), token_ctr.transact('mintFor', faucet_amount_tokens, address) ] wait_for_txs(client, txhashes) log.info('Successfully fauceted', address=address) redis.set(address_key, '1', ex=faucet_timeout) redis.set(client_key, '1', ex=faucet_timeout) return Response('{"result": "success"}') GunicornApplication(app, {'bind': bind_addr, 'worker_class': 'gevent'}).run()
def main( scenario_file, keystore_file, password, chains, data_path, auth, mailgun_api_key, ): gevent.get_hub().exception_stream = DummyStream() scenario_basename = basename(scenario_file.name) log_file_name = f'scenario-player_{scenario_basename}_{datetime.now():%Y-%m-%dT%H:%M:%S}.log' click.secho(f'Writing log to {log_file_name}', fg='yellow') configure_logging( {'': 'INFO', 'raiden': 'DEBUG', 'scenario_player': 'DEBUG'}, debug_log_file_name=log_file_name, _first_party_packages=frozenset(['raiden', 'scenario_player']), ) log_buffer = None if sys.stdout.isatty(): log_buffer = UrwidLogWalker([]) for handler in logging.getLogger('').handlers: if isinstance(handler, logging.StreamHandler): handler.terminator = None handler.formatter = NonStringifyingProcessorFormatter( UrwidLogRenderer(), foreign_pre_chain=LOGGING_PROCESSORS, ) handler.stream = log_buffer break with open(keystore_file, 'r') as keystore: account = Account(json.load(keystore), password, keystore_file) log.info("Using account", account=to_checksum_address(account.address)) # Collect tasks collect_tasks(tasks) chain_rpc_urls = defaultdict(list) for chain_name, chain_rpc_url in chains: chain_rpc_urls[chain_name].append(chain_rpc_url) runner = ScenarioRunner(account, chain_rpc_urls, auth, Path(data_path), scenario_file) ui = ScenarioUI(runner, log_buffer, log_file_name) ui_greenlet = ui.run() success = False try: try: runner.run_scenario() success = True log.info('Run finished', result='success') send_notification_mail( runner.notification_email, f'Scenario successful {scenario_file.name}', 'Success', mailgun_api_key, ) except ScenarioAssertionError as ex: log.error('Run finished', result='assertion errors') send_notification_mail( runner.notification_email, f'Assertion mismatch in {scenario_file.name}', str(ex), mailgun_api_key, ) except ScenarioError as ex: log.error('Run finished', result='scenario error') send_notification_mail( runner.notification_email, f'Invalid scenario {scenario_file.name}', traceback.format_exc(), mailgun_api_key, ) except Exception: log.exception('Exception while running scenario') send_notification_mail( runner.notification_email, f'Error running scenario {scenario_file.name}', traceback.format_exc(), mailgun_api_key, ) finally: try: if sys.stdout.isatty(): ui.set_success(success) log.warning('Press q to exit') while not ui_greenlet.dead: gevent.sleep(1) finally: if not ui_greenlet.dead: ui_greenlet.kill(ExitMainLoop) ui_greenlet.join()
def account_file(): account = Account.new('', key="1" * 64) print(account.dump())
def main(scenario_file, keystore_file, password, rpc_url, auth, mailgun_api_key): gevent.get_hub().exception_stream = DummyStream() scenario_basename = basename(scenario_file.name) log_file_name = f'scenario-player_{scenario_basename}_{datetime.now():%Y-%m-%dT%H:%M:%S}.log' click.secho(f'Writing log to {log_file_name}', fg='yellow') configure_logging( {'': 'INFO', 'raiden': 'DEBUG', 'scenario_player': 'DEBUG'}, debug_log_file_name=log_file_name, _first_party_packages=frozenset(['raiden', 'scenario_player']), ) log_buffer = LogBuffer() for handler in logging.getLogger('').handlers: if isinstance(handler, logging.StreamHandler): handler.stream = log_buffer break with open(keystore_file, 'r') as keystore: account = Account(json.load(keystore), password, keystore_file) log.info("Using account", account=to_checksum_address(account.address)) # Collect tasks collect_tasks(tasks) runner = ScenarioRunner(account, rpc_url, auth, scenario_file) terminal = Terminal() # Disable line wrapping print(terminal.rmam, end='') gevent.spawn(_ui, terminal, runner, log_file_name, log_buffer) try: assert_errors = runner.run_scenario() if assert_errors: log.error('Run finished', result='assertion errors') else: log.info('Run finished', result='success') if runner.notification_email: if not mailgun_api_key: log.error("Can't send notification mail. No API key provided") return 1 log.info('Sending notification mail') if assert_errors: send_notification_mail( runner.notification_email, f'Unexpected channel balances in {scenario_file.name}', json.dumps(assert_errors), mailgun_api_key, ) else: send_notification_mail( runner.notification_email, f'Scenario successful {scenario_file.name}', 'Success', mailgun_api_key, ) except Exception: if runner.notification_email and mailgun_api_key: send_notification_mail( runner.notification_email, f'Error running scenario {scenario_file.name}', traceback.format_exc(), mailgun_api_key, ) log.exception('Exception while running scenario') finally: try: if terminal.is_a_tty: log.warning('Press Ctrl-C to exit') while True: gevent.sleep(1) finally: # Re-enable line wrapping print(terminal.smam, end='')