Exemplo n.º 1
0
    def __init__(self,
                 web3,
                 contract_proxy,
                 token_contract,
                 private_key: str,
                 state_filename=None,
                 n_confirmations=1) -> None:
        gevent.Greenlet.__init__(self)
        self.blockchain = Blockchain(web3,
                                     contract_proxy,
                                     self,
                                     n_confirmations=n_confirmations)
        self.receiver = privkey_to_addr(private_key)
        self.private_key = private_key
        self.contract_proxy = contract_proxy
        self.token_contract = token_contract
        self.n_confirmations = n_confirmations
        self.log = logging.getLogger('channel_manager')
        network_id = web3.version.network
        assert privkey_to_addr(self.private_key) == self.receiver.lower()

        channel_contract_address = contract_proxy.contract.address
        if state_filename is not None and os.path.isfile(state_filename):
            self.state = ChannelManagerState.load(state_filename)
        else:
            self.state = ChannelManagerState(channel_contract_address,
                                             self.receiver,
                                             network_id,
                                             filename=state_filename)

        assert self.state is not None
        if state_filename is not None:
            self.lock_state = filelock.FileLock(state_filename)
            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.lower(), self.state.receiver))
        if not is_same_address(self.state.contract_address,
                               channel_contract_address):
            raise StateContractAddrMismatch(
                '%s != %s' % (channel_contract_address.lower(),
                              self.state.contract_address.lower()))

        self.log.debug(
            'setting up channel manager, receiver=%s channel_contract=%s' %
            (self.receiver, channel_contract_address))
Exemplo n.º 2
0
def sweep_account(privkey, make_token_proxy, web3, wait_for_transaction):
    address = privkey_to_addr(privkey)
    token_proxy = make_token_proxy(privkey)
    token_balance = token_proxy.contract.call().balanceOf(address)
    if token_balance > 0:
        tx = token_proxy.create_signed_transaction('transfer',
                                                   [decode_hex(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 = Transaction(
        nonce=web3.eth.getTransactionCount(address, 'pending'),
        gasprice=GAS_PRICE,
        startgas=21000,
        to=FAUCET_ADDRESS,
        value=balance - 21000 * GAS_PRICE,
        data=b'',
        v=0, r=0, s=0
    )
    sign_transaction(tx, privkey, web3.version.network)
    tx_hash = web3.eth.sendRawTransaction(encode_hex(rlp.encode(tx)))
    wait_for_transaction(tx_hash)
    assert web3.eth.getBalance(address, 'pending') == 0, ('sweeping of account {} '
                                                          '(private key {}) failed')
Exemplo n.º 3
0
    def __init__(self,
                 web3: Web3,
                 privkey,
                 contract_address,
                 abi,
                 gas_price,
                 gas_limit,
                 tester_mode=False) -> None:
        self.web3 = web3
        self.privkey = privkey
        self.caller_address = privkey_to_addr(privkey)
        if self.web3.eth.defaultAccount == web3_empty:
            self.web3.eth.defaultAccount = self.caller_address
        self.address = contract_address
        self.abi = abi
        self.contract = self.web3.eth.contract(abi=self.abi,
                                               address=contract_address)
        self.gas_price = gas_price
        self.gas_limit = gas_limit
        self.tester_mode = tester_mode

        bytecode = web3.eth.getCode(contract_address)
        if bytecode == '0x':
            raise ValueError(
                'No contract deployed at address {}'.format(contract_address))
Exemplo n.º 4
0
def close_all_channels_cooperatively(
        client: Client, privkey_receiver: str, contract_address: 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 c.receiver == receiver_addr]
    for channel in channels:
        close_channel_cooperatively(channel, privkey_receiver, contract_address, balance)
Exemplo n.º 5
0
def main(
    ctx,
    channel_manager_address,
    ssl_key,
    ssl_cert,
    state_file,
    private_key,
    paywall_info,
    rpc_provider,
):
    if private_key is None:
        log.fatal("No private key provided")
        sys.exit(1)
    if utils.check_permission_safety(private_key) is False:
        log.fatal("Private key file %s must be readable only by its owner." %
                  (private_key))
        sys.exit(1)
    with open(private_key) as keyfile:
        private_key = keyfile.readline()[:-1]
    if not is_hex(private_key) or len(decode_hex(private_key)) != 32:
        log.fatal("Private key must be specified as 32 hex encoded bytes")
        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.json" % (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, 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 test_channel_opening(client, web3, make_account,
                         make_channel_manager_proxy, token_contract,
                         mine_sync_event, wait_for_blocks, use_tester):
    receiver1_privkey = make_account(RECEIVER_ETH_ALLOWANCE,
                                     RECEIVER_TOKEN_ALLOWANCE)
    receiver2_privkey = make_account(RECEIVER_ETH_ALLOWANCE,
                                     RECEIVER_TOKEN_ALLOWANCE)
    receiver_address = privkey_to_addr(receiver1_privkey)
    channel_manager1 = ChannelManager(
        web3,
        make_channel_manager_proxy(receiver1_privkey),
        token_contract,
        receiver1_privkey,
        n_confirmations=5)
    start_channel_manager(channel_manager1, use_tester, mine_sync_event)

    channel_manager2 = ChannelManager(
        web3,
        make_channel_manager_proxy(receiver2_privkey),
        token_contract,
        receiver2_privkey,
        n_confirmations=5)
    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
Exemplo n.º 7
0
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
Exemplo n.º 8
0
 def __init__(self, web3: Web3, privkey, contract_address, abi, gas_price, gas_limit,
              tester_mode=False) -> None:
     self.web3 = web3
     self.privkey = privkey
     self.caller_address = privkey_to_addr(privkey)
     if self.web3.eth.defaultAccount == web3_empty:
         self.web3.eth.defaultAccount = self.caller_address
     self.address = contract_address
     self.abi = abi
     self.contract = self.web3.eth.contract(abi=self.abi, address=contract_address)
     self.gas_price = gas_price
     self.gas_limit = gas_limit
     self.tester_mode = tester_mode
Exemplo n.º 9
0
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
Exemplo n.º 10
0
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.add_content(
        PaywalledProxyUrl("[A-Z]{6}", 1 * TKN_DECIMALS,
                          'http://api.bitfinex.com/v1/pubticker/',
                          [r'[A-Z]{6}']))
    app.run()
    return app
Exemplo n.º 11
0
    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(privkey, eth_allowance, token_allowance, make_token_proxy, web3,
                     wait_for_transaction)

        def finalize():
            sweep_account(privkey, make_token_proxy, 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
Exemplo n.º 12
0
def main(private_key, state_file, channel_manager_address):
    if private_key is None:
        log.fatal("No private key provided")
        sys.exit(1)
    if utils.check_permission_safety(private_key) is False:
        log.fatal("Private key file %s must be readable only by its owner." %
                  (private_key))
        sys.exit(1)
    with open(private_key) as keyfile:
        private_key = keyfile.readline()[:-1]
    print(len(decode_hex(private_key)), is_hex(private_key))
    if not is_hex(private_key) or len(decode_hex(private_key)) != 32:
        log.fatal("Private key must be specified as 32 hex encoded bytes")
        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.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(config.WEB3_PROVIDER)
    web3.eth.defaultAccount = receiver_address
    contract_proxy = make_contract_proxy(web3, private_key,
                                         config.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(state, contract_proxy)
Exemplo n.º 13
0
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 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
Exemplo n.º 14
0
def fund_account(privkey, eth_allowance, token_allowance, make_token_proxy, web3,
                 wait_for_transaction):
    address = privkey_to_addr(privkey)
    tx = Transaction(
        nonce=web3.eth.getTransactionCount(FAUCET_ADDRESS, 'pending'),
        gasprice=GAS_PRICE,
        startgas=21000,
        to=decode_hex(address),
        value=eth_allowance,
        data=b'',
        v=0, r=0, s=0
    )
    sign_transaction(tx, FAUCET_PRIVKEY, web3.version.network)
    tx_hash = web3.eth.sendRawTransaction(encode_hex(rlp.encode(tx)))
    wait_for_transaction(tx_hash)

    if token_allowance > 0:
        faucet_token_proxy = make_token_proxy(FAUCET_PRIVKEY)
        tx = faucet_token_proxy.create_signed_transaction('transfer',
                                                          [decode_hex(address), token_allowance])
        tx_hash = web3.eth.sendRawTransaction(tx)
        wait_for_transaction(tx_hash)
Exemplo n.º 15
0
def main(private_key, private_key_password_file, state_file,
         channel_manager_address):
    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.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(config.WEB3_PROVIDER)
    web3.eth.defaultAccount = receiver_address
    contract_proxy = make_contract_proxy(web3, private_key,
                                         config.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(state, contract_proxy)
Exemplo n.º 16
0
def test_different_receivers(web3, make_account, make_channel_manager_proxy,
                             token_contract, mine_sync_event, client,
                             sender_address, wait_for_blocks, use_tester,
                             state_db_path):
    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,
        make_channel_manager_proxy(receiver1_privkey),
        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,
        make_channel_manager_proxy(receiver2_privkey),
        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()
Exemplo n.º 17
0
    def __init__(self,
                 privkey: str = None,
                 key_path: str = None,
                 key_password_path: str = None,
                 channel_manager_address: str = CHANNEL_MANAGER_ADDRESS,
                 web3: Web3 = None,
                 channel_manager_proxy: ChannelContractProxy = None,
                 token_proxy: ContractProxy = None,
                 contract_metadata: dict = CONTRACT_METADATA) -> None:
        assert privkey or key_path
        assert not privkey or isinstance(privkey, str)

        # Plain copy initializations.
        self.privkey = privkey
        self.channel_manager_address = channel_manager_address
        self.web3 = web3
        self.channel_manager_proxy = channel_manager_proxy
        self.token_proxy = token_proxy

        # Load private key from file if none is specified on command line.
        if not privkey:
            self.privkey = get_private_key(key_path, key_password_path)
            assert self.privkey is not None

        self.account = privkey_to_addr(self.privkey)
        self.channels = []  # type: List[Channel]

        # Create web3 context if none is provided, either by using the proxies' context or creating
        # a new one.
        if not web3:
            if channel_manager_proxy:
                self.web3 = channel_manager_proxy.web3
                self.channel_manager_address = channel_manager_proxy.address
            elif token_proxy:
                self.web3 = token_proxy.web3
            else:
                self.web3 = Web3(RPCProvider())

        # Create missing contract proxies.
        if not channel_manager_proxy:
            channel_manager_abi = contract_metadata[CHANNEL_MANAGER_ABI_NAME][
                'abi']
            self.channel_manager_proxy = ChannelContractProxy(
                self.web3, self.privkey, channel_manager_address,
                channel_manager_abi, GAS_PRICE, GAS_LIMIT)

        token_address = self.channel_manager_proxy.contract.call().token()
        if not token_proxy:
            token_abi = contract_metadata[TOKEN_ABI_NAME]['abi']
            self.token_proxy = ContractProxy(self.web3, self.privkey,
                                             token_address, token_abi,
                                             GAS_PRICE, GAS_LIMIT)
        else:
            assert is_same_address(self.token_proxy.address, token_address)

        assert self.web3
        assert self.channel_manager_proxy
        assert self.token_proxy
        assert self.channel_manager_proxy.web3 == self.web3 == self.token_proxy.web3

        self.sync_channels()
Exemplo n.º 18
0
    def __init__(
            self,
            privkey: str = None,
            key_path: str = None,
            key_password_path: str = None,
            datadir: str = click.get_app_dir('microraiden'),
            channel_manager_address: str = CHANNEL_MANAGER_ADDRESS,
            web3: Web3 = None,
            channel_manager_proxy: ChannelContractProxy = None,
            token_proxy: ContractProxy = None,
            contract_metadata: dict = CONTRACT_METADATA
    ) -> None:
        assert privkey or key_path
        assert not privkey or isinstance(privkey, str)

        # Plain copy initializations.
        self.privkey = privkey
        self.datadir = datadir
        self.channel_manager_address = channel_manager_address
        self.web3 = web3
        self.channel_manager_proxy = channel_manager_proxy
        self.token_proxy = token_proxy

        # Load private key from file if none is specified on command line.
        if not privkey:
            self.privkey = get_private_key(key_path, key_password_path)
            assert self.privkey is not None

        os.makedirs(datadir, exist_ok=True)
        assert os.path.isdir(datadir)

        self.account = privkey_to_addr(self.privkey)
        self.channels = []  # type: List[Channel]

        # Create web3 context if none is provided, either by using the proxies' context or creating
        # a new one.
        if not web3:
            if channel_manager_proxy:
                self.web3 = channel_manager_proxy.web3
                self.channel_manager_address = channel_manager_proxy.address
            elif token_proxy:
                self.web3 = token_proxy.web3
            else:
                self.web3 = Web3(RPCProvider())

        # Create missing contract proxies.
        if not channel_manager_proxy:
            channel_manager_abi = contract_metadata[CHANNEL_MANAGER_ABI_NAME]['abi']
            self.channel_manager_proxy = ChannelContractProxy(
                self.web3,
                self.privkey,
                channel_manager_address,
                channel_manager_abi,
                GAS_PRICE,
                GAS_LIMIT
            )

        token_address = self.channel_manager_proxy.contract.call().token()
        if not token_proxy:
            token_abi = contract_metadata[TOKEN_ABI_NAME]['abi']
            self.token_proxy = ContractProxy(
                self.web3, self.privkey, token_address, token_abi, GAS_PRICE, GAS_LIMIT
            )
        else:
            assert is_same_address(self.token_proxy.address, token_address)

        assert self.web3
        assert self.channel_manager_proxy
        assert self.token_proxy
        assert self.channel_manager_proxy.web3 == self.web3 == self.token_proxy.web3

        netid = self.web3.version.network
        self.balances_filename = 'balances_{}_{}.json'.format(
            NETWORK_NAMES.get(netid, netid), self.account[:10]
        )

        self.filelock = filelock.FileLock(os.path.join(self.datadir, self.balances_filename))
        self.filelock.acquire(timeout=0)

        self.load_channels()
        self.sync_channels()
from microraiden import config
from microraiden.crypto import privkey_to_addr

# private key of the content provider
PRIVATE_KEY = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
RECEIVER_ADDRESS = privkey_to_addr(PRIVATE_KEY)
# host and port Parity/Geth serves RPC requests on
RPC_PROVIDER = 'http://172.17.0.1:8180'
# state file to store proxy state and balance proofs
STATE_FILE = "/files/%s_%s.json" % (config.CHANNEL_MANAGER_ADDRESS[:10],
                                    RECEIVER_ADDRESS[:10])
SLEEP_RELOAD = 2
Exemplo n.º 20
0
 def __init__(self, receiver1_privkey):
     self._address = privkey_to_addr(receiver1_privkey)
Exemplo n.º 21
0
def deployer_address(deployer_privkey):
    return privkey_to_addr(deployer_privkey)
Exemplo n.º 22
0
    def __init__(
        self,
        privkey: str = None,
        key_path: str = None,
        datadir: str = click.get_app_dir('microraiden'),
        channel_manager_address: str = CHANNEL_MANAGER_ADDRESS,
        token_address: str = TOKEN_ADDRESS,
        rpc: RPCProvider = None,
        web3: Web3 = None,
        channel_manager_proxy: ChannelContractProxy = None,
        token_proxy: ContractProxy = None,
        rpc_endpoint: str = 'localhost',
        rpc_port: int = 8545,
        contract_abi_path: str = os.path.join(
            os.path.dirname(os.path.dirname(__file__)), 'data/contracts.json')
    ) -> None:
        assert privkey or key_path
        assert not privkey or isinstance(privkey, str)

        # Plain copy initializations.
        self.privkey = privkey
        self.datadir = datadir
        self.channel_manager_address = channel_manager_address
        self.token_address = token_address
        self.web3 = web3
        self.channel_manager_proxy = channel_manager_proxy
        self.token_proxy = token_proxy

        # Load private key from file if none is specified on command line.
        if not privkey:
            with open(key_path) as keyfile:
                self.privkey = keyfile.readline()[:-1]

        os.makedirs(datadir, exist_ok=True)
        assert os.path.isdir(datadir)

        self.account = privkey_to_addr(self.privkey)
        self.channels = []  # type: List[Channel]

        # Create web3 context if none is provided, either by using the proxies' context or creating
        # a new one.
        if not web3:
            if channel_manager_proxy:
                self.web3 = channel_manager_proxy.web3
            elif token_proxy:
                self.web3 = token_proxy.web3
            else:
                if not rpc:
                    rpc = RPCProvider(rpc_endpoint, rpc_port)
                self.web3 = Web3(rpc)

        # Create missing contract proxies.
        if not channel_manager_proxy or not token_proxy:
            with open(contract_abi_path) as abi_file:
                contract_abis = json.load(abi_file)

            if not channel_manager_proxy:
                channel_manager_abi = contract_abis[CHANNEL_MANAGER_ABI_NAME][
                    'abi']
                self.channel_manager_proxy = ChannelContractProxy(
                    self.web3, self.privkey, channel_manager_address,
                    channel_manager_abi, GAS_PRICE, GAS_LIMIT)

            if not token_proxy:
                token_abi = contract_abis[TOKEN_ABI_NAME]['abi']
                self.token_proxy = ContractProxy(self.web3, self.privkey,
                                                 token_address, token_abi,
                                                 GAS_PRICE, GAS_LIMIT)

        assert self.web3
        assert self.channel_manager_proxy
        assert self.token_proxy
        assert self.channel_manager_proxy.web3 == self.web3 == self.token_proxy.web3

        netid = self.web3.version.network
        self.balances_filename = 'balances_{}_{}.json'.format(
            NETWORK_NAMES.get(netid, netid), self.account[:10])

        self.filelock = filelock.FileLock(
            os.path.join(self.datadir, self.balances_filename))
        self.filelock.acquire(timeout=0)

        self.load_channels()
        self.sync_channels()
Exemplo n.º 23
0
import os
from eth_utils import denoms
from microraiden.crypto import privkey_to_addr

CHANNEL_MANAGER_ADDRESS = '0xeb244b0502a2d3867e5cab2347c6e1cdeb5e1eef'
API_PATH = "/api/1"
GAS_LIMIT = 200000
GAS_PRICE = 5 * denoms.gwei

MICRORAIDEN_DIR = os.path.abspath(
    os.path.join(os.path.dirname(__file__), '../..'))
HTML_DIR = os.path.join(MICRORAIDEN_DIR, 'microraiden', 'webui')
JSLIB_DIR = os.path.join(HTML_DIR, 'js')

FAUCET_PRIVKEY = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
FAUCET_ADDRESS = privkey_to_addr(FAUCET_PRIVKEY)
FAUCET_ALLOWANCE = 10**23
INITIAL_TOKEN_SUPPLY = 10**25
SENDER_ETH_ALLOWANCE = int(0.02 * denoms.ether)
SENDER_TOKEN_ALLOWANCE = 10**20
RECEIVER_ETH_ALLOWANCE = int(0.02 * denoms.ether)
RECEIVER_TOKEN_ALLOWANCE = 0
Exemplo n.º 24
0
def client_address(client_privkey):
    return privkey_to_addr(client_privkey)
from microraiden.crypto import (
    privkey_to_addr,
    sha3_hex,
    sign,
    pubkey_to_addr,
    get_balance_message,
    sign_balance_proof,
    verify_balance_proof,
    eth_sign,
    sha3,
    addr_from_sig,
    eth_verify
)

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_sha3():
    addr1 = '0x1212121212121212121212121212121212121212'
    addr2 = '0x3434343434343434343434343434343434343434'

    assert sha3_hex('a') == '0x3ac225168df54212a25c1c01fd35bebfea408fdac2e31ddd6f80a4bbf9a5f1cb'
    assert sha3_hex('0x0a') == '0x0ef9d8f8804d174666011a394cab7901679a8944d24249fd148a6a36071151f8'
Exemplo n.º 26
0
def sender_address(sender_privkey):
    return privkey_to_addr(sender_privkey)
Exemplo n.º 27
0
def receiver_address(receiver_privkey):
    return privkey_to_addr(receiver_privkey)