Exemple #1
0
def transfer_speed(num_transfers=100, max_locked=100):  # pylint: disable=too-many-locals
    channels_per_node = 1
    num_nodes = 2
    num_tokens = 1

    private_keys = [
        sha3('speed:{}'.format(position)) for position in range(num_nodes)
    ]

    tokens = [
        sha3('token:{}'.format(number))[:20] for number in range(num_tokens)
    ]

    amounts = [a % 100 + 1 for a in range(1, num_transfers + 1)]

    deposit = sum(amounts)

    secrets = [str(i) for i in range(num_transfers)]

    BlockChainServiceMock._instance = True
    blockchain_service = BlockChainServiceMock(None, MOCK_REGISTRY_ADDRESS)
    BlockChainServiceMock._instance = blockchain_service  # pylint: disable=redefined-variable-type

    registry = blockchain_service.registry(MOCK_REGISTRY_ADDRESS)
    for token in tokens:
        registry.add_token(token)

    apps = create_network(private_keys, tokens, MOCK_REGISTRY_ADDRESS,
                          channels_per_node, deposit, DEFAULT_SETTLE_TIMEOUT,
                          DEFAULT_POLL_TIMEOUT, UDPTransport,
                          BlockChainServiceMock)

    app0, app1 = apps  # pylint: disable=unbalanced-tuple-unpacking
    channel0 = app0.raiden.channelgraphs[tokens[0]].address_channel.values()[0]
    channel1 = app1.raiden.channelgraphs[tokens[0]].address_channel.values()[0]

    expiration = app0.raiden.chain.block_number() + DEFAULT_REVEAL_TIMEOUT + 3

    start = time.time()

    for i, amount in enumerate(amounts):
        hashlock = sha3(secrets[i])
        locked_transfer = channel0.create_lockedtransfer(
            amount=amount,
            identifier=1,  # TODO: fill in identifier
            expiration=expiration,
            hashlock=hashlock,
        )
        app0.raiden.sign(locked_transfer)
        channel0.register_transfer(locked_transfer)
        channel1.register_transfer(locked_transfer)

        if i > max_locked:
            idx = i - max_locked
            secret = secrets[idx]
            channel0.register_secret(secret)
            channel1.register_secret(secret)

    elapsed = time.time() - start
    print('%d transfers per second' % (num_transfers / elapsed))
Exemple #2
0
def test_webui():  # pylint: disable=too-many-locals
    num_assets = 3
    num_nodes = 10

    assets_addresses = [
        sha3('webui:asset:{}'.format(number))[:20]
        for number in range(num_assets)
    ]

    private_keys = [
        sha3('webui:{}'.format(position))
        for position in range(num_nodes)
    ]

    BlockChainServiceMock._instance = True
    blockchain_service= BlockChainServiceMock(None, MOCK_REGISTRY_ADDRESS)
    # overwrite the instance
    BlockChainServiceMock._instance = blockchain_service # pylint: disable=redefined-variable-type

    registry = blockchain_service.registry(MOCK_REGISTRY_ADDRESS)

    for asset in assets_addresses:
        registry.add_asset(asset)

    channels_per_node = 2
    deposit = 100
    app_list = create_network(
        private_keys,
        assets_addresses,
        MOCK_REGISTRY_ADDRESS,
        channels_per_node,
        deposit,
        DEFAULT_SETTLE_TIMEOUT,
        UDPTransport,
        BlockChainServiceMock
    )
    app0 = app_list[0]

    addresses = [
        app.raiden.address.encode('hex')
        for app in app_list
        if app != app_list[0]
    ]

    print '\nCreated nodes: \n',
    for node in addresses:
        print node

    setup_messages_cb()

    app0_assets = getattr(app0.raiden.api, 'assets')
    print '\nAvailable assets:'
    for asset in app0_assets:
        print asset.encode('hex')
    print '\n'

    wamp = WAMPRouter(app0.raiden, 8080, ['channel', 'test'])
    wamp.run()
Exemple #3
0
def test_webui():  # pylint: disable=too-many-locals
    num_assets = 3
    num_nodes = 10

    assets_addresses = [
        sha3('webui:asset:{}'.format(number))[:20]
        for number in range(num_assets)
    ]

    private_keys = [
        sha3('webui:{}'.format(position)) for position in range(num_nodes)
    ]

    BlockChainServiceMock._instance = True
    blockchain_service = BlockChainServiceMock(None, MOCK_REGISTRY_ADDRESS)
    # overwrite the instance
    BlockChainServiceMock._instance = blockchain_service  # pylint: disable=redefined-variable-type

    registry = blockchain_service.registry(MOCK_REGISTRY_ADDRESS)

    for asset in assets_addresses:
        registry.add_asset(asset)

    channels_per_node = 2
    deposit = 100
    app_list = create_network(private_keys, assets_addresses,
                              MOCK_REGISTRY_ADDRESS, channels_per_node,
                              deposit, DEFAULT_SETTLE_TIMEOUT, UDPTransport,
                              BlockChainServiceMock)
    app0 = app_list[0]

    addresses = [
        app.raiden.address.encode('hex') for app in app_list
        if app != app_list[0]
    ]

    print '\nCreated nodes: \n',
    for node in addresses:
        print node

    setup_messages_cb()

    app0_assets = getattr(app0.raiden.api, 'assets')
    print '\nAvailable assets:'
    for asset in app0_assets:
        print asset.encode('hex')
    print '\n'

    wamp = WAMPRouter(app0.raiden, 8080, ['channel', 'test'])
    wamp.run()
Exemple #4
0
def create_sequential_network(num_nodes, deposit, asset, transport_class=None):
    """ Create a fully connected network with `num_nodes`, the nodes are
    connect sequentially.

    Returns:
        A list of apps of size `num_nodes`, with the property that every
        sequential pair in the list has an open channel with `deposit` for each
        participant.
    """
    if num_nodes < 2:
        raise ValueError('cannot create a network with less than two nodes')

    host = '127.0.0.10'

    random.seed(42)

    discovery = PredictiveDiscovery((
        (host, num_nodes, INITIAL_PORT),
    ))

    blockchain_service = BlockChainServiceMock()
    blockchain_service.new_channel_manager_contract(asset_address=asset)

    apps = []
    for idx in range(num_nodes):
        port = INITIAL_PORT + idx

        app = mk_app(
            blockchain_service,
            discovery,
            transport_class or UDPTransport,
            port=port,
            host=host,
        )
        apps.append(app)

    for first, second in zip(apps[:-1], apps[1:]):
        netcontract_address = blockchain_service.new_netting_contract(
            asset,
            first.raiden.address,
            second.raiden.address,
        )

        for address in [first.raiden.address, second.raiden.address]:
            blockchain_service.deposit(
                asset,
                netcontract_address,
                address,
                deposit,
            )

    for app in apps:
        app.raiden.setup_asset(asset, app.config['reveal_timeout'])

    return apps
Exemple #5
0
def create_sequential_network(num_nodes, deposit, asset, transport_class=None):
    """ Create a fully connected network with `num_nodes`, the nodes are
    connect sequentially.

    Returns:
        A list of apps of size `num_nodes`, with the property that every
        sequential pair in the list has an open channel with `deposit` for each
        participant.
    """
    if num_nodes < 2:
        raise ValueError('cannot create a network with less than two nodes')

    host = '127.0.0.10'

    random.seed(42)

    discovery = PredictiveDiscovery((
        (host, num_nodes, INITIAL_PORT),
    ))

    blockchain_service = BlockChainServiceMock()
    blockchain_service.new_channel_manager_contract(asset_address=asset)

    apps = []
    for idx in range(num_nodes):
        port = INITIAL_PORT + idx

        app = mk_app(
            blockchain_service,
            discovery,
            transport_class or UDPTransport,
            port=port,
            host=host,
        )
        apps.append(app)

    for first, second in zip(apps[:-1], apps[1:]):
        netcontract_address = blockchain_service.new_netting_contract(
            asset,
            first.raiden.address,
            second.raiden.address,
        )

        for address in [first.raiden.address, second.raiden.address]:
            blockchain_service.deposit(
                asset,
                netcontract_address,
                address,
                deposit,
            )

    for app in apps:
        app.raiden.setup_asset(asset, app.config['reveal_timeout'])

    return apps
Exemple #6
0
def blockchain_service(request, registry_address):
    """ A mock blockchain for faster testing. """

    # pylint: disable=protected-access
    def _cleanup():
        BlockChainServiceMock._instance = None

    request.addfinalizer(_cleanup)

    # allows the fixture to instantiate the blockchain
    BlockChainServiceMock._instance = True

    blockchain_service = BlockChainServiceMock(None, registry_address)

    # overwrite the instance
    BlockChainServiceMock._instance = blockchain_service  # pylint: disable=redefined-variable-type

    return blockchain_service
Exemple #7
0
def create_network(num_nodes=8, num_assets=1, channels_per_node=3, transport_class=None):
    """ Initialize a local test network using the UDP protocol.

    Note:
        The generated network will use two subnets, 127.0.0.10 and 127.0.0.11,
        for this test to work both virtual interfaces must be created prior to
        the test execution::

            ifconfig lo:0 127.0.0.10
            ifconfig lo:1 127.0.0.11
    """
    # pylint: disable=too-many-locals

    # TODO: check if the loopback interfaces exists

    random.seed(1337)

    if channels_per_node > num_nodes:
        raise ValueError("Can't create more channels than nodes")

    client_hosts = ['127.0.0.10', '127.0.0.11']

    # if num_nodes it is not even
    half_of_nodes = int(ceil(num_nodes / 2))

    # globals
    discovery = PredictiveDiscovery((
        (host, half_of_nodes, INITIAL_PORT)
        for host in client_hosts
    ))

    # The mock needs to be atomic since all app's will use the same instance,
    # for the real application the syncronization is done by the JSON-RPC
    # server
    blockchain_service = BlockChainServiceMock()

    # Each app instance is a Node in the network
    apps = []
    for host in client_hosts:
        for idx in range(half_of_nodes):
            port = INITIAL_PORT + idx

            app = mk_app(
                blockchain_service,
                discovery,
                transport_class or UDPTransport,
                port=port,
                host=host,
            )

            apps.append(app)

    for i in range(num_assets):
        asset_address = sha3('asset:%d' % i)[:20]
        blockchain_service.new_channel_manager_contract(asset_address=asset_address)

    asset_list = blockchain_service.asset_addresses
    assert len(asset_list) == num_assets

    create_network_channels(blockchain_service, asset_list, apps, channels_per_node)

    for app in apps:
        for asset_address in asset_list:
            app.raiden.setup_asset(asset_address, app.config['reveal_timeout'])

    return apps
def transfer_speed(num_transfers=100, max_locked=100):  # pylint: disable=too-many-locals
    channels_per_node = 1
    num_nodes = 2
    num_assets = 1

    private_keys = [
        sha3('speed:{}'.format(position))
        for position in range(num_nodes)
    ]

    assets = [
        sha3('asset:{}'.format(number))[:20]
        for number in range(num_assets)
    ]

    amounts = [
        a % 100 + 1
        for a in range(1, num_transfers + 1)
    ]

    deposit = sum(amounts)

    secrets = [
        str(i)
        for i in range(num_transfers)
    ]

    BlockChainServiceMock._instance = True
    blockchain_service = BlockChainServiceMock(None, MOCK_REGISTRY_ADDRESS)
    BlockChainServiceMock._instance = blockchain_service  # pylint: disable=redefined-variable-type

    registry = blockchain_service.registry(MOCK_REGISTRY_ADDRESS)
    for asset in assets:
        registry.add_asset(asset)

    apps = create_network(
        private_keys,
        assets,
        MOCK_REGISTRY_ADDRESS,
        channels_per_node,
        deposit,
        DEFAULT_SETTLE_TIMEOUT,
        DEFAULT_POLL_TIMEOUT,
        UDPTransport,
        BlockChainServiceMock
    )

    app0, app1 = apps  # pylint: disable=unbalanced-tuple-unpacking
    channel0 = app0.raiden.get_manager_by_asset_address(assets[0]).address_channel.values()[0]
    channel1 = app1.raiden.get_manager_by_asset_address(assets[0]).address_channel.values()[0]

    expiration = app0.raiden.chain.block_number() + DEFAULT_REVEAL_TIMEOUT + 3

    start = time.time()

    for i, amount in enumerate(amounts):
        hashlock = sha3(secrets[i])
        locked_transfer = channel0.create_lockedtransfer(
            amount=amount,
            identifier=1,  # TODO: fill in identifier
            expiration=expiration,
            hashlock=hashlock,
        )
        app0.raiden.sign(locked_transfer)
        channel0.register_transfer(locked_transfer)
        channel1.register_transfer(locked_transfer)

        if i > max_locked:
            idx = i - max_locked
            secret = secrets[idx]
            channel0.register_secret(secret)
            channel1.register_secret(secret)

    elapsed = time.time() - start
    print('%d transfers per second' % (num_transfers / elapsed))
def test_new_netting_contract():
    # pylint: disable=line-too-long,too-many-statements
    client = BlockChainServiceMock()

    asset_address = make_address()
    peer1_address = make_address()
    peer2_address = make_address()
    peer3_address = make_address()

    contract_address = client.new_channel_manager_contract(asset_address)
    assert isaddress(contract_address)

    # sanity
    assert client.addresses_by_asset(asset_address) == []
    assert client.nettingaddresses_by_asset_participant(
        asset_address,
        peer1_address,
    ) == []
    assert client.nettingaddresses_by_asset_participant(
        asset_address,
        peer2_address
    ) == []
    assert client.nettingaddresses_by_asset_participant(
        asset_address,
        peer3_address
    ) == []

    # create one channel
    netting1_address = client.new_netting_contract(asset_address, peer1_address, peer2_address)

    # check contract state
    assert isaddress(netting1_address)
    assert client.isopen(asset_address, netting1_address) is False
    assert client.partner(asset_address, netting1_address, peer1_address) == peer2_address
    assert client.partner(asset_address, netting1_address, peer2_address) == peer1_address

    # check channels
    assert sorted(client.addresses_by_asset(asset_address)[0]) == sorted([peer1_address, peer2_address])

    assert client.nettingaddresses_by_asset_participant(
        asset_address,
        peer1_address
    ) == [netting1_address]
    assert client.nettingaddresses_by_asset_participant(
        asset_address,
        peer2_address
    ) == [netting1_address]
    assert client.nettingaddresses_by_asset_participant(asset_address, peer3_address) == []

    # cant recreate the existing channel
    with pytest.raises(Exception):
        client.new_netting_contract(asset_address, peer1_address, peer2_address)

    # create other chanel
    netting2_address = client.new_netting_contract(asset_address, peer1_address, peer3_address)

    assert isaddress(netting2_address)
    assert client.isopen(asset_address, netting2_address) is False
    assert client.partner(asset_address, netting2_address, peer1_address) == peer3_address
    assert client.partner(asset_address, netting2_address, peer3_address) == peer1_address

    channel_list = client.addresses_by_asset(asset_address)
    expected_channels = [
        sorted([peer1_address, peer2_address]),
        sorted([peer1_address, peer3_address]),
    ]

    for channel in channel_list:
        assert sorted(channel) in expected_channels

    assert sorted(client.nettingaddresses_by_asset_participant(asset_address, peer1_address)) == sorted([
        netting1_address,
        netting2_address,
    ])
    assert client.nettingaddresses_by_asset_participant(asset_address, peer2_address) == [netting1_address]
    assert client.nettingaddresses_by_asset_participant(asset_address, peer3_address) == [netting2_address]

    client.deposit(asset_address, netting1_address, peer1_address, 100)
    assert client.isopen(asset_address, netting1_address) is False
    assert client.isopen(asset_address, netting2_address) is False

    # with pytest.raises(Exception):
    #    client.deposit(asset_address, netting1_address, peer1_address, 100)

    client.deposit(asset_address, netting2_address, peer1_address, 70)
    assert client.isopen(asset_address, netting1_address) is False
    assert client.isopen(asset_address, netting2_address) is False

    client.deposit(asset_address, netting1_address, peer2_address, 130)
    assert client.isopen(asset_address, netting1_address) is True
    assert client.isopen(asset_address, netting2_address) is False

    # we need to allow the settlement of the channel even if no transfers were
    # made
    peer1_last_sent_transfer = None
    peer2_last_sent_transfer = None

    client.close(
        asset_address,
        netting1_address,
        peer1_address,
        peer1_last_sent_transfer,
        peer2_last_sent_transfer,
    )

    # with pytest.raises(Exception):
    #     client.close(asset_address, netting2_address, peer1_address, peer1_last_sent_transfers)

    assert client.isopen(asset_address, netting1_address) is False
    assert client.isopen(asset_address, netting2_address) is False

    client.deposit(asset_address, netting2_address, peer3_address, 21)

    assert client.isopen(asset_address, netting1_address) is False
    assert client.isopen(asset_address, netting2_address) is True

    client.update_transfer(asset_address, netting1_address, peer2_address, peer2_last_sent_transfer)

    assert client.isopen(asset_address, netting1_address) is False
    assert client.isopen(asset_address, netting2_address) is True
def test_new_netting_contract():
    # pylint: disable=line-too-long,too-many-statements
    client = BlockChainServiceMock()

    asset_address = make_address()
    peer1_address = make_address()
    peer2_address = make_address()
    peer3_address = make_address()

    contract_address = client.new_channel_manager_contract(asset_address)
    assert isaddress(contract_address)

    # sanity
    assert client.addresses_by_asset(asset_address) == []
    assert client.nettingaddresses_by_asset_participant(
        asset_address,
        peer1_address,
    ) == []
    assert client.nettingaddresses_by_asset_participant(
        asset_address, peer2_address) == []
    assert client.nettingaddresses_by_asset_participant(
        asset_address, peer3_address) == []

    # create one channel
    netting1_address = client.new_netting_contract(asset_address,
                                                   peer1_address,
                                                   peer2_address)

    # check contract state
    assert isaddress(netting1_address)
    assert client.isopen(asset_address, netting1_address) is False
    assert client.partner(asset_address, netting1_address,
                          peer1_address) == peer2_address
    assert client.partner(asset_address, netting1_address,
                          peer2_address) == peer1_address

    # check channels
    assert sorted(client.addresses_by_asset(asset_address)[0]) == sorted(
        [peer1_address, peer2_address])

    assert client.nettingaddresses_by_asset_participant(
        asset_address, peer1_address) == [netting1_address]
    assert client.nettingaddresses_by_asset_participant(
        asset_address, peer2_address) == [netting1_address]
    assert client.nettingaddresses_by_asset_participant(
        asset_address, peer3_address) == []

    # cant recreate the existing channel
    with pytest.raises(Exception):
        client.new_netting_contract(asset_address, peer1_address,
                                    peer2_address)

    # create other chanel
    netting2_address = client.new_netting_contract(asset_address,
                                                   peer1_address,
                                                   peer3_address)

    assert isaddress(netting2_address)
    assert client.isopen(asset_address, netting2_address) is False
    assert client.partner(asset_address, netting2_address,
                          peer1_address) == peer3_address
    assert client.partner(asset_address, netting2_address,
                          peer3_address) == peer1_address

    channel_list = client.addresses_by_asset(asset_address)
    expected_channels = [
        sorted([peer1_address, peer2_address]),
        sorted([peer1_address, peer3_address]),
    ]

    for channel in channel_list:
        assert sorted(channel) in expected_channels

    assert sorted(
        client.nettingaddresses_by_asset_participant(
            asset_address, peer1_address)) == sorted([
                netting1_address,
                netting2_address,
            ])
    assert client.nettingaddresses_by_asset_participant(
        asset_address, peer2_address) == [netting1_address]
    assert client.nettingaddresses_by_asset_participant(
        asset_address, peer3_address) == [netting2_address]

    client.deposit(asset_address, netting1_address, peer1_address, 100)
    assert client.isopen(asset_address, netting1_address) is False
    assert client.isopen(asset_address, netting2_address) is False

    # with pytest.raises(Exception):
    #    client.deposit(asset_address, netting1_address, peer1_address, 100)

    client.deposit(asset_address, netting2_address, peer1_address, 70)
    assert client.isopen(asset_address, netting1_address) is False
    assert client.isopen(asset_address, netting2_address) is False

    client.deposit(asset_address, netting1_address, peer2_address, 130)
    assert client.isopen(asset_address, netting1_address) is True
    assert client.isopen(asset_address, netting2_address) is False

    # we need to allow the settlement of the channel even if no transfers were
    # made
    peer1_last_sent_transfer = None
    peer2_last_sent_transfer = None

    client.close(
        asset_address,
        netting1_address,
        peer1_address,
        peer1_last_sent_transfer,
        peer2_last_sent_transfer,
    )

    # with pytest.raises(Exception):
    #     client.close(asset_address, netting2_address, peer1_address, peer1_last_sent_transfers)

    assert client.isopen(asset_address, netting1_address) is False
    assert client.isopen(asset_address, netting2_address) is False

    client.deposit(asset_address, netting2_address, peer3_address, 21)

    assert client.isopen(asset_address, netting1_address) is False
    assert client.isopen(asset_address, netting2_address) is True

    client.update_transfer(asset_address, netting1_address, peer2_address,
                           peer2_last_sent_transfer)

    assert client.isopen(asset_address, netting1_address) is False
    assert client.isopen(asset_address, netting2_address) is True
Exemple #11
0
def create_network(num_nodes=8, num_assets=1, channels_per_node=3, transport_class=None):
    """ Initialize a local test network using the UDP protocol.

    Note:
        The generated network will use two subnets, 127.0.0.10 and 127.0.0.11,
        for this test to work both virtual interfaces must be created prior to
        the test execution::

            ifconfig lo:0 127.0.0.10
            ifconfig lo:1 127.0.0.11
    """
    # pylint: disable=too-many-locals

    # TODO: check if the loopback interfaces exists

    random.seed(1337)

    if channels_per_node > num_nodes:
        raise ValueError("Can't create more channels than nodes")

    client_hosts = ['127.0.0.10', '127.0.0.11']

    # if num_nodes it is not even
    half_of_nodes = int(ceil(num_nodes / 2))

    # globals
    discovery = PredictiveDiscovery((
        (host, half_of_nodes, INITIAL_PORT)
        for host in client_hosts
    ))

    # The mock needs to be atomic since all app's will use the same instance,
    # for the real application the syncronization is done by the JSON-RPC
    # server
    blockchain_service = BlockChainServiceMock()

    # Each app instance is a Node in the network
    apps = []
    for host in client_hosts:
        for idx in range(half_of_nodes):
            port = INITIAL_PORT + idx

            app = mk_app(
                blockchain_service,
                discovery,
                transport_class or UDPTransport,
                port=port,
                host=host,
            )

            apps.append(app)

    for i in range(num_assets):
        asset_address = sha3('asset:%d' % i)[:20]
        blockchain_service.new_channel_manager_contract(asset_address=asset_address)

    asset_list = blockchain_service.asset_addresses
    assert len(asset_list) == num_assets

    create_network_channels(blockchain_service, asset_list, apps, channels_per_node)

    for app in apps:
        for asset_address in asset_list:
            app.raiden.setup_asset(asset_address, app.config['reveal_timeout'])

    return apps