Ejemplo n.º 1
0
def test_default_http_client_topup(doggo_proxy,
                                   default_http_client: DefaultHTTPClient,
                                   receiver_privkey):

    # Create a channel that has just enough capacity for one transfer.
    default_http_client.initial_deposit = lambda x: 0
    check_response(default_http_client.run('doggo.jpg'))

    client = default_http_client.client
    open_channels = client.get_open_channels()
    assert len(open_channels) == 1
    channel1 = open_channels[0]
    assert channel1 == default_http_client.channel
    assert channel1.balance_sig
    assert channel1.balance == channel1.deposit

    # Do another payment. Topup should occur.
    check_response(default_http_client.run('doggo.jpg'))
    open_channels = client.get_open_channels()
    assert len(open_channels) == 1
    channel2 = open_channels[0]
    assert channel2 == default_http_client.channel
    assert channel2.balance_sig
    assert channel2.balance < channel2.deposit
    assert channel1 == channel2
    close_channel_cooperatively(channel1, receiver_privkey,
                                client.channel_manager_address)
Ejemplo n.º 2
0
def run(key_path, key_password_path, resource):
    # create the client
    with Client(key_path=key_path, key_password_path=key_password_path) as client:
        m2mclient = DefaultHTTPClient(
            client,
            'localhost',
            5000
        )

        # Get the resource. If payment is required, client will attempt to create
        # a channel or will use existing one.
        status, headers, body = m2mclient.run(resource)
        if status == requests.codes.OK:
            if re.match('^text\/', headers['Content-Type']):
                logging.info("got the resource %s type=%s\n%s" % (
                    resource,
                    headers.get('Content-Type', '???'),
                    body))
            else:
                logging.info("got the resource %s type=%s" % (
                    resource,
                    headers.get('Content-Type', '???')))
        else:
            logging.error("error getting the resource. code=%d body=%s" %
                          (status, body.decode().strip()))
Ejemplo n.º 3
0
def test_resource_request(doggo_proxy, default_http_client: DefaultHTTPClient):
    requests = 1000
    default_http_client.initial_deposit = lambda x: (requests + 1) * x

    # First transfer creates channel on-chain => exclude from profiling.
    response = default_http_client.run('doggo.jpg')
    assert response.decode().strip() == '"HI I AM A DOGGO"'

    t_start = time.time()
    for i in range(requests):
        log.debug('Transfer {}'.format(i))
        response = default_http_client.run('doggo.jpg')
        assert response.decode().strip() == '"HI I AM A DOGGO"'
    t_diff = time.time() - t_start

    log.info("{} requests in {} ({} rps)".format(
        requests, datetime.timedelta(seconds=t_diff), requests / t_diff))
Ejemplo n.º 4
0
def test_default_http_client_close(doggo_proxy,
                                   default_http_client: DefaultHTTPClient):

    client = default_http_client.client
    check_response(default_http_client.run('doggo.jpg'))
    default_http_client.close_active_channel()
    open_channels = client.get_open_channels()
    assert len(open_channels) == 0
Ejemplo n.º 5
0
def test_default_http_client_existing_channel(
        doggo_proxy, default_http_client: DefaultHTTPClient, receiver_privkey,
        receiver_address):

    client = default_http_client.client
    channel = client.open_channel(receiver_address, 50)
    check_response(default_http_client.run('doggo.jpg'))
    assert channel.balance == 2
    assert channel.deposit == 50
    close_channel_cooperatively(channel, receiver_privkey,
                                client.channel_manager_address)
def test_default_http_client_existing_channel_topup(
        doggo_proxy, default_http_client: DefaultHTTPClient, receiver_privkey,
        receiver_address):
    logging.basicConfig(level=logging.INFO)

    client = default_http_client.client
    default_http_client.topup_deposit = lambda x: 13
    channel = client.open_channel(receiver_address, 1)
    check_response(default_http_client.run('doggo.jpg'))
    assert channel.balance == 2
    assert channel.deposit == 13
    close_channel_cooperatively(channel, receiver_privkey)
Ejemplo n.º 7
0
def test_cheating_client(doggo_proxy, default_http_client: DefaultHTTPClient):
    """this test scenario where client sends less funds than what is requested
        by the server. In such case, a "RDN-Invalid-Amount=1" header should
        be sent in a server's reply
    """

    #  patch default http client to use price lower than the server suggests
    def patched_payment(self: DefaultHTTPClient, receiver: str, price: int,
                        balance: int, balance_sig: bytes,
                        channel_manager_address: str):
        self.invalid_amount_received = 0
        return DefaultHTTPClient.on_payment_requested(
            self, receiver, price + self.price_adjust, balance, balance_sig,
            channel_manager_address)

    def patched_on_invalid_amount(self: DefaultHTTPClient):
        DefaultHTTPClient.on_invalid_amount(self)
        self.invalid_amount_received = 1

    default_http_client.on_invalid_amount = types.MethodType(
        patched_on_invalid_amount, default_http_client)
    default_http_client.on_payment_requested = types.MethodType(
        patched_payment, default_http_client)

    # correct amount
    default_http_client.price_adjust = 0
    response = default_http_client.run('doggo.jpg')
    check_response(response)
    assert default_http_client.invalid_amount_received == 0
    # underpay
    default_http_client.price_adjust = -1
    response = default_http_client.run('doggo.jpg')
    assert response is None
    assert default_http_client.invalid_amount_received == 1
    # overpay
    default_http_client.price_adjust = 1
    response = default_http_client.run('doggo.jpg')
    assert response is None
    assert default_http_client.invalid_amount_received == 1
Ejemplo n.º 8
0
def run(api_endpoint, api_port, **kwargs):
    exclude_kwargs = {'close_channels'}
    kwargs_client = {
        key: value
        for key, value in kwargs.items() if value and key not in exclude_kwargs
    }
    with Client(**kwargs_client) as client:
        m2mclient = DefaultHTTPClient(client, api_endpoint, api_port)
        resource = m2mclient.run('doggo.jpg')
        log.info('Response: {}'.format(resource))

        if kwargs['close_channels'] is True:
            for channel in client.channels:
                if channel.state == Channel.State.open:
                    channel.close_channel()
Ejemplo n.º 9
0
def test_default_http_client(doggo_proxy,
                             default_http_client: DefaultHTTPClient,
                             sender_address, receiver_privkey,
                             receiver_address):

    check_response(default_http_client.run('doggo.jpg'))

    client = default_http_client.client
    open_channels = client.get_open_channels()
    assert len(open_channels) == 1

    channel = open_channels[0]
    assert channel == default_http_client.channel
    assert channel.balance_sig
    assert channel.balance < channel.deposit
    assert channel.sender == sender_address
    assert channel.receiver == receiver_address
    close_channel_cooperatively(channel, receiver_privkey,
                                client.channel_manager_address)
Ejemplo n.º 10
0
def test_coop_close(doggo_proxy, default_http_client: DefaultHTTPClient,
                    sender_address, receiver_privkey, receiver_address):

    check_response(default_http_client.run('doggo.jpg'))

    client = default_http_client.client
    open_channels = client.get_open_channels()
    assert len(open_channels) == 1

    channel = open_channels[0]
    import requests
    reply = requests.get('http://localhost:5000/api/1/channels/%s/%s' %
                         (channel.sender, channel.block))
    assert reply.status_code == 200
    json_reply = json.loads(reply.text)

    request_data = {'balance': json_reply['balance']}
    reply = requests.delete('http://localhost:5000/api/1/channels/%s/%s' %
                            (channel.sender, channel.block),
                            data=request_data)

    assert reply.status_code == 200
    close_channel_cooperatively(channel, receiver_privkey,
                                client.channel_manager_address)
Ejemplo n.º 11
0
class ETHTickerClient(ttk.Frame):
    def __init__(
            self,
            sender_privkey: str,
            httpclient: DefaultHTTPClient = None
    ):
        self.root = tkinter.Tk()
        ttk.Frame.__init__(self, self.root)
        self.root.title('µRaiden ETH Ticker')
        self.root.protocol('WM_DELETE_WINDOW', self.close)
        self.pack()
        self.pricevar = tkinter.StringVar(value='0.00 USD')
        ttk.Label(self, textvariable=self.pricevar, font=('Helvetica', '72')).pack()

        if httpclient:
            self.httpclient = httpclient
            self.client = httpclient.client
        else:
            self.client = Client(sender_privkey)
            self.httpclient = DefaultHTTPClient(
                self.client,
                'localhost',
                5000,
                initial_deposit=lambda x: 10 * x,
                topup_deposit=lambda x: 5 * x
            )

        self.active_query = False
        self.running = False

    def run(self):
        self.running = True
        self.root.after(1000, self.query_price)
        self.root.mainloop()

    def query_price(self):
        if not self.running:
            return
        self.active_query = True

        response = self.httpclient.run('ETHUSD')
        if response:
            ticker = json.loads(response.decode())
            price = float(ticker['last_price'])
            log.info('New price received: {:.2f} USD'.format(price))
            self.pricevar.set('{:.2f} USD'.format(price))
        else:
            log.warning('No response.')

        if self.running:
            self.root.after(5000, self.query_price)
        self.active_query = False

    def close(self):
        log.info('Shutting down gracefully.')
        self.running = False
        self.root.destroy()
        self.httpclient.stop()
        # Sloppy handling of thread joining but works for this small demo.
        while self.active_query:
            gevent.sleep(1)

        self.httpclient.close_active_channel()
        self.client.close()
Ejemplo n.º 12
0
def test_ssl_client(doggo_proxy, default_http_client: DefaultHTTPClient):
    default_http_client.use_ssl = True
    with disable_ssl_check():
        check_response(default_http_client.run('doggo.jpg'))
    with pytest.raises(SSLError):
        check_response(default_http_client.run('doggo.jpg'))