def __init__( self, web3: Web3, channel_manager_contract: Contract, token_contract: Contract, private_key: str, state_filename: str = None, n_confirmations=1 ) -> None: gevent.Greenlet.__init__(self) self.blockchain = Blockchain( web3, channel_manager_contract, self, n_confirmations=n_confirmations ) self.receiver = privkey_to_addr(private_key) self.private_key = private_key self.channel_manager_contract = channel_manager_contract self.token_contract = token_contract self.n_confirmations = n_confirmations self.log = logging.getLogger('channel_manager') network_id = int(web3.version.network) assert is_same_address(privkey_to_addr(self.private_key), self.receiver) # check contract version self.check_contract_version() if state_filename not in (None, ':memory:') and os.path.isfile(state_filename): self.state = ChannelManagerState.load(state_filename) else: self.state = ChannelManagerState(state_filename) self.state.setup_db( network_id, channel_manager_contract.address, self.receiver ) assert self.state is not None if state_filename not in (None, ':memory:'): self.lock_state = filelock.FileLock(state_filename + '.lock') try: self.lock_state.acquire(timeout=0) except filelock.Timeout: raise StateFileLocked("state file %s is locked by another process" % state_filename) if network_id != self.state.network_id: raise NetworkIdMismatch("Network id mismatch: state=%d, backend=%d" % ( self.state.network_id, network_id)) if not is_same_address(self.receiver, self.state.receiver): raise StateReceiverAddrMismatch('%s != %s' % (self.receiver, self.state.receiver)) if not is_same_address(self.state.contract_address, channel_manager_contract.address): raise StateContractAddrMismatch('%s != %s' % ( channel_manager_contract.address, self.state.contract_address)) self.log.debug('setting up channel manager, receiver=%s channel_contract=%s' % (self.receiver, channel_manager_contract.address))
def __init__(self, web3: Web3, channel_manager_contract: Contract, token_contract: Contract, private_key: str, state_filename: str = None, n_confirmations=1) -> None: gevent.Greenlet.__init__(self) self.blockchain = Blockchain(web3, channel_manager_contract, self, n_confirmations=n_confirmations) self.receiver = privkey_to_addr(private_key) self.private_key = private_key self.channel_manager_contract = channel_manager_contract self.token_contract = token_contract self.n_confirmations = n_confirmations self.log = logging.getLogger('channel_manager') network_id = int(web3.version.network) assert is_same_address(privkey_to_addr(self.private_key), self.receiver) # check contract version self.check_contract_version() if state_filename not in ( None, ':memory:') and os.path.isfile(state_filename): self.state = ChannelManagerState.load(state_filename) else: self.state = ChannelManagerState(state_filename) self.state.setup_db(network_id, channel_manager_contract.address, self.receiver) assert self.state is not None if state_filename not in (None, ':memory:'): self.lock_state = filelock.FileLock(state_filename + '.lock') try: self.lock_state.acquire(timeout=0) except filelock.Timeout: raise StateFileLocked( "state file %s is locked by another process" % state_filename) if network_id != self.state.network_id: raise NetworkIdMismatch( "Network id mismatch: state=%d, backend=%d" % (self.state.network_id, network_id)) if not is_same_address(self.receiver, self.state.receiver): raise StateReceiverAddrMismatch( '%s != %s' % (self.receiver, self.state.receiver)) if not is_same_address(self.state.contract_address, channel_manager_contract.address): raise StateContractAddrMismatch('%s != %s' % (channel_manager_contract.address, self.state.contract_address)) self.log.debug( 'setting up channel manager, receiver=%s channel_contract=%s' % (self.receiver, channel_manager_contract.address))
def main( rpc_provider: HTTPProvider, private_key: str, private_key_password_file: str, state_file: str, channel_manager_address: str, minimum_amount: int, gas_price: int, ): if minimum_amount <= 0: click.echo('Minimum amount need to be at least 1') sys.exit(1) private_key = utils.get_private_key(private_key, private_key_password_file) if private_key is None: sys.exit(1) receiver_address = utils.privkey_to_addr(private_key) web3 = Web3(HTTPProvider(rpc_provider, request_kwargs={'timeout': 60})) config.NETWORK_CFG.set_defaults(int(web3.version.network)) web3.eth.defaultAccount = receiver_address channel_manager_address = ( channel_manager_address or config.NETWORK_CFG.channel_manager_address ) channel_manager_contract = make_channel_manager_contract(web3, channel_manager_address) if not state_file: state_file_name = "%s_%s.db" % ( channel_manager_address[:10], receiver_address[:10] ) app_dir = click.get_app_dir('microraiden') if not os.path.exists(app_dir): click.echo('No state file or directory found!') sys.exit(1) state_file = os.path.join(app_dir, state_file_name) try: click.echo('Loading state file from {}'.format(state_file)) state = ChannelManagerState.load(state_file) except StateFileException: click.echo('Error reading state file') traceback.print_exc() sys.exit(1) if not is_same_address(state.receiver, receiver_address): click.echo('Private key does not match receiver address in state file') sys.exit(1) elif not is_same_address(state.contract_address, channel_manager_address): click.echo('Channel manager contract address mismatch') sys.exit(1) click.echo('Withdrawing all paid tokens with at least {} due from ' 'receiver {}'.format(minimum_amount, receiver_address)) withdraw_from_channels( private_key, state, channel_manager_contract, minimum_amount, gas_price * denoms.gwei if gas_price else None, )
def sweep_account(private_key: str, faucet_address: str, token_contract: Contract, web3: Web3, wait_for_transaction): address = privkey_to_addr(private_key) log.info('Sweeping account {}'.format(address)) token_balance = token_contract.call().balanceOf(address) if token_balance > 0: tx = create_signed_contract_transaction( private_key, token_contract, 'transfer', [faucet_address, token_balance]) try: tx_hash = web3.eth.sendRawTransaction(tx) except ValueError as e: if e.args[0]['message'].startswith('Insufficient funds.'): pass else: raise else: wait_for_transaction(tx_hash) assert token_contract.call().balanceOf(address) == 0 balance = web3.eth.getBalance(address) if balance < POT_GAS_LIMIT * GAS_PRICE: return tx = create_signed_transaction(private_key, web3, to=faucet_address, value=balance - POT_GAS_LIMIT * GAS_PRICE, gas_limit=POT_GAS_LIMIT) tx_hash = web3.eth.sendRawTransaction(tx) wait_for_transaction(tx_hash) assert web3.eth.getBalance(address) == 0, ( 'Sweeping of account {} (private key {}) failed.'.format( address, private_key))
def create_signed_transaction( private_key: str, web3: Web3, to: str, value: int=0, data=b'', nonce_offset: int = 0, gas_price: int = GAS_PRICE, gas_limit: int = GAS_LIMIT ) -> str: """ Creates a signed on-chain transaction compliant with EIP155. """ tx = create_transaction( web3=web3, from_=privkey_to_addr(private_key), to=to, value=value, data=data, nonce_offset=nonce_offset, gas_price=gas_price, gas_limit=gas_limit ) sign_transaction(tx, private_key, web3.version.network) return encode_hex(rlp.encode(tx))
def create_signed_contract_transaction( private_key: str, contract: Contract, func_name: str, args: List[Any], value: int = 0, nonce_offset: int = 0, gas_price: Union[int, None] = None, gas_limit: int = NETWORK_CFG.GAS_LIMIT) -> str: """ Creates a signed on-chain contract transaction compliant with EIP155. """ if gas_price is None: gas_price = NETWORK_CFG.GAS_PRICE tx = create_contract_transaction(contract=contract, from_=privkey_to_addr(private_key), func_name=func_name, args=args, value=value, nonce_offset=nonce_offset, gas_price=gas_price, gas_limit=gas_limit) sign_transaction(tx, private_key, int(contract.web3.version.network)) # sign_transaction(tx, private_key, 1337) return encode_hex(rlp.encode(tx))
def create_signed_transaction( private_key: str, web3: Web3, to: str, value: int=0, data=b'', nonce_offset: int = 0, gas_price: Union[int, None] = None, gas_limit: int = NETWORK_CFG.POT_GAS_LIMIT ) -> str: """ Creates a signed on-chain transaction compliant with EIP155. """ if gas_price is None: gas_price = NETWORK_CFG.GAS_PRICE tx = create_transaction( web3=web3, from_=privkey_to_addr(private_key), to=to, value=value, data=data, nonce_offset=nonce_offset, gas_price=gas_price, gas_limit=gas_limit ) sign_transaction(tx, private_key, int(web3.version.network)) return encode_hex(rlp.encode(tx))
def sweep_account(private_key: str, token_contract: Contract, web3: Web3, wait_for_transaction): address = privkey_to_addr(private_key) token_balance = token_contract.call().balanceOf(address) if token_balance > 0: tx = create_signed_contract_transaction( private_key, token_contract, 'transfer', [FAUCET_ADDRESS, token_balance]) try: tx_hash = web3.eth.sendRawTransaction(tx) except ValueError as e: if e.args[0]['message'].startswith('Insufficient funds.'): pass else: raise else: wait_for_transaction(tx_hash) balance = web3.eth.getBalance(address, 'pending') if balance < 21000 * GAS_PRICE: return tx = create_signed_transaction(private_key, web3, to=FAUCET_ADDRESS, value=balance - 21000 * GAS_PRICE, gas_limit=21000) tx_hash = web3.eth.sendRawTransaction(tx) wait_for_transaction(tx_hash) assert web3.eth.getBalance(address, 'pending') == 0, ( 'Sweeping of account {} (private key {}) failed.'.format( address, private_key))
def create_signed_contract_transaction( private_key: str, contract: Contract, func_name: str, args: List[Any], value: int=0, nonce_offset: int = 0, gas_price: Union[int, None] = None, gas_limit: int = NETWORK_CFG.GAS_LIMIT ) -> str: """ Creates a signed on-chain contract transaction compliant with EIP155. """ if gas_price is None: gas_price = NETWORK_CFG.GAS_PRICE tx = create_contract_transaction( contract=contract, from_=privkey_to_addr(private_key), func_name=func_name, args=args, value=value, nonce_offset=nonce_offset, gas_price=gas_price, gas_limit=gas_limit ) sign_transaction(tx, private_key, int(contract.web3.version.network)) return encode_hex(rlp.encode(tx))
def test_channel_opening(client: Client, web3: Web3, make_account, private_keys: List[str], channel_manager_contract, token_contract, mine_sync_event, wait_for_blocks, use_tester, state_db_path): receiver1_privkey = make_account(RECEIVER_ETH_ALLOWANCE, RECEIVER_TOKEN_ALLOWANCE, private_keys[2]) receiver2_privkey = make_account(RECEIVER_ETH_ALLOWANCE, RECEIVER_TOKEN_ALLOWANCE, private_keys[3]) receiver_address = privkey_to_addr(receiver1_privkey) # make sure channel_manager1 is terminated properly, otherwise Blockchain will be running # in the background, ruining other tests' results channel_manager1 = ChannelManager(web3, channel_manager_contract, token_contract, receiver1_privkey, n_confirmations=5, state_filename=state_db_path) start_channel_manager(channel_manager1, use_tester, mine_sync_event) channel_manager2 = ChannelManager(web3, channel_manager_contract, token_contract, receiver2_privkey, n_confirmations=5, state_filename=state_db_path) start_channel_manager(channel_manager2, use_tester, mine_sync_event) channel_manager1.wait_sync() channel_manager2.wait_sync() blockchain = channel_manager1.blockchain channel = client.open_channel(receiver_address, 10) # should be in unconfirmed channels wait_for_blocks(1) gevent.sleep(blockchain.poll_interval) assert (channel.sender, channel.block) not in channel_manager1.channels assert (channel.sender, channel.block) in channel_manager1.unconfirmed_channels channel_rec = channel_manager1.unconfirmed_channels[channel.sender, channel.block] assert is_same_address(channel_rec.receiver, receiver_address) assert is_same_address(channel_rec.sender, channel.sender) assert channel_rec.mtime == channel_rec.ctime # should be confirmed after n blocks wait_for_blocks(blockchain.n_confirmations) gevent.sleep(blockchain.poll_interval) assert (channel.sender, channel.block) in channel_manager1.channels channel_rec = channel_manager1.channels[channel.sender, channel.block] assert is_same_address(channel_rec.receiver, receiver_address) assert is_same_address(channel_rec.sender, channel.sender) assert channel_rec.balance == 0 assert channel_rec.last_signature is None assert channel_rec.is_closed is False assert channel_rec.settle_timeout == -1 # should not appear in other channel manager assert (channel.sender, channel.block) not in channel_manager2.channels assert (channel.sender, channel.block) not in channel_manager2.unconfirmed_channels channel_manager1.stop() channel_manager2.stop()
def main( ctx, channel_manager_address, ssl_key, ssl_cert, gas_price, state_file, private_key, private_key_password_file, paywall_info, rpc_provider, ): private_key = utils.get_private_key(private_key, private_key_password_file) if private_key is None: sys.exit(1) receiver_address = privkey_to_addr(private_key) constants.paywall_html_dir = paywall_info while True: try: web3 = Web3( HTTPProvider(rpc_provider, request_kwargs={'timeout': 60})) NETWORK_CFG.set_defaults(int(web3.version.network)) channel_manager_address = to_checksum_address( channel_manager_address or NETWORK_CFG.CHANNEL_MANAGER_ADDRESS) if gas_price is not None: NETWORK_CFG.gas_price = gas_price if not state_file: state_file_name = "%s_%s.db" % (channel_manager_address[:10], receiver_address[:10]) app_dir = click.get_app_dir('microraiden') if not os.path.exists(app_dir): os.makedirs(app_dir) state_file = os.path.join(app_dir, state_file_name) app = make_paywalled_proxy( private_key, state_file, contract_address=channel_manager_address, web3=web3) except StateFileLocked as ex: log.warning('Another uRaiden process is already running (%s)!' % str(ex)) except InsecureStateFile as ex: msg = ( 'The permission bits of the state file (%s) are set incorrectly (others can ' 'read or write) or you are not the owner. For reasons of security, ' 'startup is aborted.' % state_file) log.fatal(msg) raise except NetworkIdMismatch as ex: log.fatal(str(ex)) raise except requests.exceptions.ConnectionError as ex: log.warning("Ethereum node refused connection: %s" % str(ex)) else: break sleep(constants.SLEEP_RELOAD) ctx.obj = app
def main( rpc_provider: HTTPProvider, private_key: str, private_key_password_file: str, state_file: str, channel_manager_address: str, minimum_amount: int, gas_price: int, ): if minimum_amount <= 0: click.echo('Minimum amount need to be at least 1') sys.exit(1) private_key = utils.get_private_key(private_key, private_key_password_file) if private_key is None: sys.exit(1) receiver_address = utils.privkey_to_addr(private_key) web3 = Web3(HTTPProvider(rpc_provider, request_kwargs={'timeout': 60})) config.NETWORK_CFG.set_defaults(int(web3.version.network)) web3.eth.defaultAccount = receiver_address channel_manager_address = (channel_manager_address or config.NETWORK_CFG.channel_manager_address) channel_manager_contract = make_channel_manager_contract( web3, channel_manager_address) if not state_file: state_file_name = "%s_%s.db" % (channel_manager_address[:10], receiver_address[:10]) app_dir = click.get_app_dir('microraiden') if not os.path.exists(app_dir): click.echo('No state file or directory found!') sys.exit(1) state_file = os.path.join(app_dir, state_file_name) try: click.echo('Loading state file from {}'.format(state_file)) state = ChannelManagerState.load(state_file) except StateFileException: click.echo('Error reading state file') traceback.print_exc() sys.exit(1) if not is_same_address(state.receiver, receiver_address): click.echo('Private key does not match receiver address in state file') sys.exit(1) elif not is_same_address(state.contract_address, channel_manager_address): click.echo('Channel manager contract address mismatch') sys.exit(1) click.echo('Withdrawing all paid tokens with at least {} due from ' 'receiver {}'.format(minimum_amount, receiver_address)) withdraw_from_channels( private_key, state, channel_manager_contract, minimum_amount, gas_price * denoms.gwei if gas_price else None, )
def __init__(self, private_key: str, web3: Web3, channel_manager_address: str): self.private_key = private_key self.address = privkey_to_addr(private_key) self.web3 = web3 self.channel_manager = web3.eth.contract( address=channel_manager_address, abi=CONTRACT_METADATA[CHANNEL_MANAGER_NAME]['abi'])
def main( ctx, channel_manager_address, ssl_key, ssl_cert, gas_price, state_file, private_key, private_key_password_file, paywall_info, rpc_provider, ): private_key = utils.get_private_key(private_key, private_key_password_file) if private_key is None: sys.exit(1) receiver_address = privkey_to_addr(private_key) constants.paywall_html_dir = paywall_info while True: try: web3 = Web3(HTTPProvider(rpc_provider, request_kwargs={'timeout': 60})) NETWORK_CFG.set_defaults(int(web3.version.network)) channel_manager_address = to_checksum_address( channel_manager_address or NETWORK_CFG.CHANNEL_MANAGER_ADDRESS ) if gas_price is not None: NETWORK_CFG.gas_price = gas_price if not state_file: state_file_name = "%s_%s.db" % ( channel_manager_address[:10], receiver_address[:10] ) app_dir = click.get_app_dir('microraiden') if not os.path.exists(app_dir): os.makedirs(app_dir) state_file = os.path.join(app_dir, state_file_name) app = make_paywalled_proxy(private_key, state_file, contract_address=channel_manager_address, web3=web3) except StateFileLocked as ex: log.warning('Another uRaiden process is already running (%s)!' % str(ex)) except InsecureStateFile as ex: msg = ('The permission bits of the state file (%s) are set incorrectly (others can ' 'read or write) or you are not the owner. For reasons of security, ' 'startup is aborted.' % state_file) log.fatal(msg) raise except NetworkIdMismatch as ex: log.fatal(str(ex)) raise except requests.exceptions.ConnectionError as ex: log.warning("Ethereum node refused connection: %s" % str(ex)) else: break sleep(constants.SLEEP_RELOAD) ctx.obj = app
def close_channels(private_key: str, password_path: str, resource: str, channel_manager_address: str = None, web3: Web3 = None, retry_interval: float = 5, endpoint_url: str = 'http://0.0.0.0:5010', close_channel: bool = False): # Create the client session. session = Session(endpoint_url=endpoint_url, private_key=private_key, key_password_path=password_path, channel_manager_address=channel_manager_address, web3=web3, retry_interval=retry_interval, close_channel_on_exit=close_channel) #conn = Client(monitor_address) #conn.send('share') ##print(conn.recv()) #conn.close() print("Private Key:", private_key) addr = privkey_to_addr(private_key) print("Address:", addr) # response = requests.get('http://0.0.0.0:5000/api/1/channels/{}'.format(addr)) #response = session.get('{}/api/1/channels/{}'.format('http://0.0.0.0:5000', addr)) #print(response) response = session.get('{}/{}'.format('http://0.0.0.0:5010', resource)) print(response) print(response.text) print(response.content) print(response.headers) # time.sleep(4) response = session.get('{}/{}'.format('http://0.0.0.0:5010', resource)) print(response) print(response.text) print(response.content) print(response.headers) time.sleep(4) response = session.get('{}/{}'.format('http://0.0.0.0:5010', resource)) print(response) print(response.text) print(response.content) print(response.headers) # time.sleep(10) session.channel.close(balance=session.channel.balance - 1)
def main(): web3 = Web3(HTTPProvider(config['web3path'])) NETWORK_CFG.set_defaults(int(web3.version.network)) private_key = get_private_key('./dragonstone-rinkeby') log.info('This private key %s', private_key) log.info('This address %s', privkey_to_addr(private_key)) channel_manager = make_channel_manager(private_key, config['manager'], './db/echo_server.db', web3, 'localhost', 6001) run(private_key=private_key, channel_manager=channel_manager)
def start_proxy(receiver_privkey: str) -> PaywalledProxy: state_file_name = '{}_{}.json'.format(CHANNEL_MANAGER_ADDRESS, privkey_to_addr(receiver_privkey)) app_dir = click.get_app_dir('microraiden') if not os.path.exists(app_dir): os.makedirs(app_dir) app = make_paywalled_proxy(receiver_privkey, os.path.join(app_dir, state_file_name)) app.run() return app
def close_all_channels_cooperatively(client: Client, privkey_receiver: str, balance: int = None): receiver_addr = privkey_to_addr(privkey_receiver) client.sync_channels() channels = [ c for c in client.channels if c.state != Channel.State.closed and is_same_address(c.receiver, receiver_addr) ] for channel in channels: close_channel_cooperatively(channel, privkey_receiver, balance)
def main(close_channel: bool = True, ): w3 = Web3(HTTPProvider(config['web3path'])) NETWORK_CFG.set_defaults(int(w3.version.network)) private_key = get_private_key('./dragonstone-rinkeby-02-03') print("Web3 Provider:", config['web3path']) #print('Private Key :', config['private-key']) log.info('This private key %s', private_key) log.info('This address %s', privkey_to_addr(private_key)) # print('Password Path:', config['password-path']) # print('Resource Reqd:', config['resource']) # print('Manager Addr:', config['manager']) # print('Close Channel:', close_channel) close_channels(private_key, config['manager'], config['monitor'], w3)
def create_signed_transaction( web3: Web3, private_key: str, to: str, value: int, ) -> str: tx = create_transaction(web3=web3, from_=privkey_to_addr(private_key), to=to, value=value) sign_transaction(tx, private_key, int(web3.version.network)) return encode_hex(rlp.encode(tx))
def main( ctx, channel_manager_address, ssl_key, ssl_cert, state_file, private_key, private_key_password_file, paywall_info, rpc_provider, ): private_key = utils.get_private_key(private_key, private_key_password_file) if private_key is None: sys.exit(1) receiver_address = privkey_to_addr(private_key) channel_manager_address = channel_manager_address or config.CHANNEL_MANAGER_ADDRESS if not state_file: state_file_name = "%s_%s.db" % (channel_manager_address[:10], receiver_address[:10]) app_dir = click.get_app_dir('microraiden') if not os.path.exists(app_dir): os.makedirs(app_dir) state_file = os.path.join(app_dir, state_file_name) config.paywall_html_dir = paywall_info web3 = Web3(HTTPProvider(rpc_provider, request_kwargs={'timeout': 60})) try: app = make_paywalled_proxy(private_key, state_file, contract_address=channel_manager_address, web3=web3) except StateFileLocked as ex: log.fatal('Another uRaiden process is already running (%s)!' % str(ex)) sys.exit(1) except InsecureStateFile as ex: msg = ( 'The permission bits of the state file (%s) are set incorrectly (others can ' 'read or write) or you are not the owner. For reasons of security, ' 'startup is aborted.' % state_file) log.fatal(msg) sys.exit(1) except NetworkIdMismatch as ex: log.fatal(str(ex)) sys.exit(1) except requests.exceptions.ConnectionError as ex: log.fatal("Ethereum node refused connection: %s" % str(ex)) sys.exit(1) ctx.obj = app
def close_all_channels_cooperatively( client: Client, private_keys: List[str], contract_address: str, balance: int=None ): addresses_to_keys = { to_checksum_address(privkey_to_addr(private_key)): private_key for private_key in private_keys } client.sync_channels() closable_channels = [c for c in client.channels if c.state != Channel.State.closed] log.info('Closing {} channels.'.format(len(closable_channels))) for channel in closable_channels: private_key = addresses_to_keys.get(to_checksum_address(channel.receiver)) if private_key is not None: close_channel_cooperatively(channel, private_key, contract_address, balance)
def get_tokens(): web3 = Web3(HTTPProvider(config['web3path'])) private_key = get_private_key('./dragonstone-rinkeby-02-03') log.info('This private key %s', private_key) log.info('This address %s', privkey_to_addr(private_key)) token_address = config['token'] token_abi = constants.CONTRACT_METADATA[constants.TOKEN_ABI_NAME]['abi'] token_contract = web3.eth.contract(abi=token_abi, address=token_address) raw_tx = create_signed_contract_transaction(private_key, token_contract, 'mint', [], 100000000000000000) web3.eth.sendRawTransaction(raw_tx) log.info('bought tokens from custom token')
def sweep_account( private_key: str, faucet_address: str, token_contract: Contract, web3: Web3, wait_for_transaction ): address = privkey_to_addr(private_key) log.info('Sweeping account {}'.format(address)) token_balance = token_contract.call().balanceOf(address) if token_balance > 0: tx = create_signed_contract_transaction( private_key, token_contract, 'transfer', [ faucet_address, token_balance ] ) try: tx_hash = web3.eth.sendRawTransaction(tx) except ValueError as e: if e.args[0]['message'].startswith('Insufficient funds.'): pass else: raise else: wait_for_transaction(tx_hash) assert token_contract.call().balanceOf(address) == 0 balance = web3.eth.getBalance(address) if balance < NETWORK_CFG.POT_GAS_LIMIT * NETWORK_CFG.GAS_PRICE: return tx = create_signed_transaction( private_key, web3, to=faucet_address, value=balance - NETWORK_CFG.POT_GAS_LIMIT * NETWORK_CFG.GAS_PRICE, gas_limit=NETWORK_CFG.POT_GAS_LIMIT ) tx_hash = web3.eth.sendRawTransaction(tx) wait_for_transaction(tx_hash) assert web3.eth.getBalance(address) == 0, ( 'Sweeping of account {} (private key {}) failed.'.format(address, private_key) )
def account_factory(eth_allowance, token_allowance): privkey = random_private_key(1000) address = privkey_to_addr(privkey) if use_tester: ethereum.tester.accounts.append(decode_hex(address)) ethereum.tester.keys.append(decode_hex(privkey)) fund_account(address, eth_allowance, token_allowance, token_contract, web3, wait_for_transaction) def finalize(): sweep_account(privkey, token_contract, web3, wait_for_transaction) if use_tester: ethereum.tester.accounts.remove(decode_hex(address)) ethereum.tester.keys.remove(decode_hex(privkey)) request.addfinalizer(finalize) return privkey
def close_all_channels_cooperatively(client: Client, private_keys: List[str], contract_address: str, balance: int = None): addresses_to_keys = { to_checksum_address(privkey_to_addr(private_key)): private_key for private_key in private_keys } client.sync_channels() closable_channels = [ c for c in client.channels if c.state != Channel.State.closed ] log.info('Closing {} channels.'.format(len(closable_channels))) for channel in closable_channels: private_key = addresses_to_keys.get( to_checksum_address(channel.receiver)) if private_key is not None: close_channel_cooperatively(channel, private_key, contract_address, balance)
def test_eth_sign_typed_data_eip(): # Test cases from the EIP: # https://github.com/0xProject/EIPs/blob/01dfc0f9a4122d8ad8817c503447cab8efa8a6c4/EIPS/eip-signTypedData.md#test-cases privkey = 'f2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257d' addr = '0x5409ed021d9299bf6814279a6a1411a7e866a631' assert is_same_address(addr, privkey_to_addr(privkey)) typed_data = [('string', 'message', 'Hi, Alice!')] msg = eth_sign_typed_data_message_eip(typed_data) assert encode_hex( msg ) == '0xe18794748cc6d73634d578f6a83f752bee11a0c9853d76bd0111d67a9b555a2c' sig = eth_sign_typed_data_eip(privkey, typed_data) sig_expected = '0x1a4ca93acf066a580f097690246e6c85d1deeb249194f6d3c2791f3aecb6adf8' \ '714ca4a0f12512ddd2a4f2393ea0c3b2c856279ba4929a5a34ae6859689428061b' assert encode_hex(sig) == sig_expected typed_data = [('uint', 'value', 42)] msg = eth_sign_typed_data_message_eip(typed_data) assert encode_hex( msg ) == '0x6cb1c2645d841a0a3d142d1a2bdaa27015cc77f442e17037015b0350e468a957' sig = eth_sign_typed_data_eip(privkey, typed_data) sig_expected = '0x87c5b6a9f3a758babcc9140a96ae07957c6c9109af65bf139266cded52da49e6' \ '3df6af6f7daef588218e156bc83b95e0bfcfa8e72843cf4cf8c67c3ca11c3fd11b' assert encode_hex(sig) == sig_expected typed_data = [('uint', 'value', 42), ('string', 'message', 'Hi, Alice!'), ('bool', 'removed', False)] msg = eth_sign_typed_data_message_eip(typed_data) assert encode_hex( msg ) == '0x36c3ed8591950e33dc4777bb455ab1a3e4223f84c42172a1ff2e200d5e25ee2e' sig = eth_sign_typed_data_eip(privkey, typed_data) sig_expected = '0x466a5a021225b681836e9951d2e603a37a605850ca26da0692ca532d4d1581d6' \ '031e2e3754fe31036e3a56d7e37fb6f598f7ab7a5cdd87aa04c9811c8b6209f31b' assert encode_hex(sig) == sig_expected
def main( rpc_provider: HTTPProvider, private_key: str, private_key_password_file: str, state_file: str, channel_manager_address: str ): private_key = utils.get_private_key(private_key, private_key_password_file) if private_key is None: sys.exit(1) receiver_address = privkey_to_addr(private_key) if not state_file: state_file_name = "%s_%s.json" % (channel_manager_address[:10], receiver_address[:10]) app_dir = click.get_app_dir('microraiden') state_file = os.path.join(app_dir, state_file_name) web3 = Web3(HTTPProvider(rpc_provider, request_kwargs={'timeout': 60})) web3.eth.defaultAccount = receiver_address channel_manager_address = ( channel_manager_address or config.CHANNEL_MANAGER_ADDRESS[web3.version.network] ) channel_manager_contract = make_channel_manager_contract(web3, channel_manager_address) try: click.echo('Loading state file from {}'.format(state_file)) state = ChannelManagerState.load(state_file) except StateFileException: click.echo('Error reading state file') traceback.print_exc() sys.exit(1) if not is_same_address(state.receiver, receiver_address): click.echo('Private key does not match receiver address in state file') sys.exit(1) elif not is_same_address(state.contract_address, channel_manager_address): click.echo('Channel manager contract address mismatch') sys.exit(1) click.echo('Closing all open channels with valid balance proofs for ' 'receiver {}'.format(receiver_address)) close_open_channels(private_key, state, channel_manager_contract)
def __init__( self, private_key: str, web3: Web3, channel_manager_address: str ): self.private_key = private_key self.address = privkey_to_addr(private_key) self.web3 = web3 self.channel_manager = web3.eth.contract( address=channel_manager_address, abi=CONTRACT_METADATA[CHANNEL_MANAGER_ABI_NAME]['abi'] ) token_address = self.channel_manager.call().token() self.token = web3.eth.contract( address=token_address, abi=CONTRACT_METADATA[TOKEN_ABI_NAME]['abi'] )
def test_eth_sign_typed_data_eip(): # Test cases from the EIP: # https://github.com/0xProject/EIPs/blob/01dfc0f9a4122d8ad8817c503447cab8efa8a6c4/EIPS/eip-signTypedData.md#test-cases privkey = 'f2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257d' addr = '0x5409ed021d9299bf6814279a6a1411a7e866a631' assert is_same_address(addr, privkey_to_addr(privkey)) typed_data = [('string', 'message', 'Hi, Alice!')] msg = eth_sign_typed_data_message_eip(typed_data) assert encode_hex(msg) == '0xe18794748cc6d73634d578f6a83f752bee11a0c9853d76bd0111d67a9b555a2c' sig = eth_sign_typed_data_eip(privkey, typed_data) sig_expected = '0x1a4ca93acf066a580f097690246e6c85d1deeb249194f6d3c2791f3aecb6adf8' \ '714ca4a0f12512ddd2a4f2393ea0c3b2c856279ba4929a5a34ae6859689428061b' assert encode_hex(sig) == sig_expected typed_data = [('uint', 'value', 42)] msg = eth_sign_typed_data_message_eip(typed_data) assert encode_hex(msg) == '0x6cb1c2645d841a0a3d142d1a2bdaa27015cc77f442e17037015b0350e468a957' sig = eth_sign_typed_data_eip(privkey, typed_data) sig_expected = '0x87c5b6a9f3a758babcc9140a96ae07957c6c9109af65bf139266cded52da49e6' \ '3df6af6f7daef588218e156bc83b95e0bfcfa8e72843cf4cf8c67c3ca11c3fd11b' assert encode_hex(sig) == sig_expected typed_data = [ ('uint', 'value', 42), ('string', 'message', 'Hi, Alice!'), ('bool', 'removed', False) ] msg = eth_sign_typed_data_message_eip(typed_data) assert encode_hex(msg) == '0x36c3ed8591950e33dc4777bb455ab1a3e4223f84c42172a1ff2e200d5e25ee2e' sig = eth_sign_typed_data_eip(privkey, typed_data) sig_expected = '0x466a5a021225b681836e9951d2e603a37a605850ca26da0692ca532d4d1581d6' \ '031e2e3754fe31036e3a56d7e37fb6f598f7ab7a5cdd87aa04c9811c8b6209f31b' assert encode_hex(sig) == sig_expected
def account_factory(eth_allowance: int, token_allowance: int, private_key: str): address = privkey_to_addr(private_key) if use_tester: ethereum.tester.accounts.append(decode_hex(address)) ethereum.tester.keys.append(decode_hex(private_key)) fund_account( address, eth_allowance, token_allowance, token_contract, web3, wait_for_transaction, faucet_private_key ) def finalize(): sweep_account(private_key, faucet_address, token_contract, web3, wait_for_transaction) if use_tester: ethereum.tester.accounts.remove(decode_hex(address)) ethereum.tester.keys.remove(decode_hex(private_key)) request.addfinalizer(finalize) return private_key
def create_signed_contract_transaction(private_key: str, contract: Contract, func_name: str, args: List[Any], value: int = 0, nonce_offset: int = 0, gas_price: Union[int, None] = None, gas_limit: int = NETWORK_CFG.GAS_LIMIT): if gas_price is None: gas_price = NETWORK_CFG.GAS_PRICE data = create_transaction_data(contract, func_name, args) w3 = contract.web3 signed_txn = w3.eth.account.signTransaction( dict( nonce=w3.eth.getTransactionCount(privkey_to_addr(private_key)), gasPrice=gas_price, gas=gas_limit, to=contract.address, value=value, data=data, ), private_key, ) return signed_txn.rawTransaction
def sender_address(sender_privkey): return privkey_to_addr(sender_privkey)
def client_address(client_privkey): return privkey_to_addr(client_privkey)
def receiver_address(receiver_privkey): return privkey_to_addr(receiver_privkey)
def faucet_address(faucet_private_key: str): return privkey_to_addr(faucet_private_key)
def test_different_receivers( web3: Web3, make_account, private_keys: List[str], channel_manager_contract: Contract, token_contract: Contract, mine_sync_event, client: Client, sender_address: str, wait_for_blocks, use_tester: bool, state_db_path: str ): if not use_tester: pytest.skip('This test takes several hours on real blockchains.') receiver1_privkey = make_account( RECEIVER_ETH_ALLOWANCE, RECEIVER_TOKEN_ALLOWANCE, private_keys[2] ) receiver2_privkey = make_account( RECEIVER_ETH_ALLOWANCE, RECEIVER_TOKEN_ALLOWANCE, private_keys[3] ) receiver1_address = privkey_to_addr(receiver1_privkey) channel_manager1 = ChannelManager( web3, channel_manager_contract, token_contract, receiver1_privkey, n_confirmations=5, state_filename=state_db_path ) start_channel_manager(channel_manager1, use_tester, mine_sync_event) channel_manager2 = ChannelManager( web3, channel_manager_contract, token_contract, receiver2_privkey, n_confirmations=5, state_filename=state_db_path ) start_channel_manager(channel_manager2, use_tester, mine_sync_event) channel_manager1.wait_sync() channel_manager2.wait_sync() blockchain = channel_manager1.blockchain assert channel_manager2.blockchain.n_confirmations == blockchain.n_confirmations assert channel_manager2.blockchain.poll_interval == blockchain.poll_interval # unconfirmed open channel = client.open_channel(receiver1_address, 10) wait_for_blocks(1) gevent.sleep(blockchain.poll_interval) assert (sender_address, channel.block) in channel_manager1.unconfirmed_channels assert (sender_address, channel.block) not in channel_manager2.unconfirmed_channels # confirmed open wait_for_blocks(blockchain.n_confirmations) gevent.sleep(blockchain.poll_interval) assert (sender_address, channel.block) in channel_manager1.channels assert (sender_address, channel.block) not in channel_manager2.channels # unconfirmed topup channel.topup(5) wait_for_blocks(1) gevent.sleep(blockchain.poll_interval) channel_rec = channel_manager1.channels[sender_address, channel.block] assert len(channel_rec.unconfirmed_topups) == 1 assert channel_rec.deposit == 10 # confirmed topup wait_for_blocks(blockchain.n_confirmations) gevent.sleep(blockchain.poll_interval) channel_rec = channel_manager1.channels[sender_address, channel.block] assert len(channel_rec.unconfirmed_topups) == 0 assert channel_rec.deposit == 15 # closing channel.close() wait_for_blocks(blockchain.n_confirmations) gevent.sleep(blockchain.poll_interval) channel_rec = channel_manager1.channels[sender_address, channel.block] assert channel_rec.is_closed is True # settlement block_before = web3.eth.blockNumber wait_for_blocks(channel_rec.settle_timeout - block_before) channel.settle() wait_for_blocks(blockchain.n_confirmations) gevent.sleep(blockchain.poll_interval) assert (sender_address, channel.block) not in channel_manager1.channels channel_manager1.stop() channel_manager2.stop()
def test_channel_opening( client: Client, web3: Web3, make_account, private_keys: List[str], channel_manager_contract, token_contract, mine_sync_event, wait_for_blocks, use_tester, state_db_path ): receiver1_privkey = make_account( RECEIVER_ETH_ALLOWANCE, RECEIVER_TOKEN_ALLOWANCE, private_keys[2] ) receiver2_privkey = make_account( RECEIVER_ETH_ALLOWANCE, RECEIVER_TOKEN_ALLOWANCE, private_keys[3] ) receiver_address = privkey_to_addr(receiver1_privkey) # make sure channel_manager1 is terminated properly, otherwise Blockchain will be running # in the background, ruining other tests' results channel_manager1 = ChannelManager( web3, channel_manager_contract, token_contract, receiver1_privkey, n_confirmations=5, state_filename=state_db_path ) start_channel_manager(channel_manager1, use_tester, mine_sync_event) channel_manager2 = ChannelManager( web3, channel_manager_contract, token_contract, receiver2_privkey, n_confirmations=5, state_filename=state_db_path ) start_channel_manager(channel_manager2, use_tester, mine_sync_event) channel_manager1.wait_sync() channel_manager2.wait_sync() blockchain = channel_manager1.blockchain channel = client.open_channel(receiver_address, 10) # should be in unconfirmed channels wait_for_blocks(1) gevent.sleep(blockchain.poll_interval) assert (channel.sender, channel.block) not in channel_manager1.channels assert (channel.sender, channel.block) in channel_manager1.unconfirmed_channels channel_rec = channel_manager1.unconfirmed_channels[channel.sender, channel.block] assert is_same_address(channel_rec.receiver, receiver_address) assert is_same_address(channel_rec.sender, channel.sender) assert channel_rec.mtime == channel_rec.ctime # should be confirmed after n blocks wait_for_blocks(blockchain.n_confirmations) gevent.sleep(blockchain.poll_interval) assert (channel.sender, channel.block) in channel_manager1.channels channel_rec = channel_manager1.channels[channel.sender, channel.block] assert is_same_address(channel_rec.receiver, receiver_address) assert is_same_address(channel_rec.sender, channel.sender) assert channel_rec.balance == 0 assert channel_rec.last_signature is None assert channel_rec.is_closed is False assert channel_rec.settle_timeout == -1 # should not appear in other channel manager assert (channel.sender, channel.block) not in channel_manager2.channels assert (channel.sender, channel.block) not in channel_manager2.unconfirmed_channels channel_manager1.stop() channel_manager2.stop()
def test_different_receivers( web3: Web3, make_account, channel_manager_contract: Contract, token_contract: Contract, mine_sync_event, client: Client, sender_address: str, wait_for_blocks, use_tester: bool, state_db_path: str ): receiver1_privkey = make_account(RECEIVER_ETH_ALLOWANCE, RECEIVER_TOKEN_ALLOWANCE) receiver2_privkey = make_account(RECEIVER_ETH_ALLOWANCE, RECEIVER_TOKEN_ALLOWANCE) receiver1_address = privkey_to_addr(receiver1_privkey) channel_manager1 = ChannelManager( web3, channel_manager_contract, token_contract, receiver1_privkey, n_confirmations=5, state_filename=state_db_path ) start_channel_manager(channel_manager1, use_tester, mine_sync_event) channel_manager2 = ChannelManager( web3, channel_manager_contract, token_contract, receiver2_privkey, n_confirmations=5, state_filename=state_db_path ) start_channel_manager(channel_manager2, use_tester, mine_sync_event) channel_manager1.wait_sync() channel_manager2.wait_sync() blockchain = channel_manager1.blockchain assert channel_manager2.blockchain.n_confirmations == blockchain.n_confirmations assert channel_manager2.blockchain.poll_interval == blockchain.poll_interval # unconfirmed open channel = client.open_channel(receiver1_address, 10) wait_for_blocks(1) gevent.sleep(blockchain.poll_interval) assert (sender_address, channel.block) in channel_manager1.unconfirmed_channels assert (sender_address, channel.block) not in channel_manager2.unconfirmed_channels # confirmed open wait_for_blocks(blockchain.n_confirmations) gevent.sleep(blockchain.poll_interval) assert (sender_address, channel.block) in channel_manager1.channels assert (sender_address, channel.block) not in channel_manager2.channels # unconfirmed topup channel.topup(5) wait_for_blocks(1) gevent.sleep(blockchain.poll_interval) channel_rec = channel_manager1.channels[sender_address, channel.block] assert len(channel_rec.unconfirmed_topups) == 1 assert channel_rec.deposit == 10 # confirmed topup wait_for_blocks(blockchain.n_confirmations) gevent.sleep(blockchain.poll_interval) channel_rec = channel_manager1.channels[sender_address, channel.block] assert len(channel_rec.unconfirmed_topups) == 0 assert channel_rec.deposit == 15 # closing channel.close() wait_for_blocks(blockchain.n_confirmations) gevent.sleep(blockchain.poll_interval) channel_rec = channel_manager1.channels[sender_address, channel.block] assert channel_rec.is_closed is True # settlement block_before = web3.eth.blockNumber wait_for_blocks(channel_rec.settle_timeout - block_before) channel.settle() wait_for_blocks(blockchain.n_confirmations) gevent.sleep(blockchain.poll_interval) assert (sender_address, channel.block) not in channel_manager1.channels channel_manager1.stop() channel_manager2.stop()
def deployer_address(deployer_privkey): return privkey_to_addr(deployer_privkey)
def __init__(self, receiver1_privkey): self._address = privkey_to_addr(receiver1_privkey)
pubkey_to_addr, sign_balance_proof, verify_balance_proof, eth_sign, keccak256, addr_from_sig, eth_verify, eth_sign_typed_data_message_eip, eth_sign_typed_data_eip, pack, sign_close, verify_closing_sig ) SENDER_PRIVATE_KEY = '0xa0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0' SENDER_ADDR = privkey_to_addr(SENDER_PRIVATE_KEY) RECEIVER_PRIVATE_KEY = '0xb1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1' RECEIVER_ADDR = privkey_to_addr(RECEIVER_PRIVATE_KEY) def test_encode_hex(): assert isinstance(encode_hex(b''), str) assert isinstance(decode_hex(''), bytes) def test_pack(): assert pack(False) == b'\x00' assert pack(True) == b'\x01' def test_keccak256():
import pytest # noqa: F401 from coincurve import PublicKey from eth_utils import encode_hex, decode_hex, is_same_address from web3.contract import Contract from microraiden.utils import ( privkey_to_addr, keccak256_hex, sign, pubkey_to_addr, sign_balance_proof, verify_balance_proof, eth_sign, keccak256, addr_from_sig, eth_verify, eth_sign_typed_data_message_eip, eth_sign_typed_data_eip, pack, sign_close, verify_closing_sig) SENDER_PRIVATE_KEY = '0xa0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0' SENDER_ADDR = privkey_to_addr(SENDER_PRIVATE_KEY) RECEIVER_PRIVATE_KEY = '0xb1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1' RECEIVER_ADDR = privkey_to_addr(RECEIVER_PRIVATE_KEY) def test_encode_hex(): assert isinstance(encode_hex(b''), str) assert isinstance(decode_hex(''), bytes) def test_pack(): assert pack(False) == b'\x00' assert pack(True) == b'\x01' def test_keccak256(): addr1 = '0x1212121212121212121212121212121212121212' addr2 = '0x3434343434343434343434343434343434343434'