Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 53 additions & 37 deletions raiden/api/wamp_server.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
import os
import json
import types
import inspect

Expand All @@ -21,7 +21,7 @@

def register_pubsub_with_callback(func=None):
if isinstance(func, types.FunctionType):
func._callback_pubsub = func.__name__ + "_status"
func._callback_pubsub = func.__name__ + '_status' # pylint: disable=protected-access
return func


Expand All @@ -39,8 +39,8 @@ def __init__(self, ws, extra):

def register_pubsub(self, topic):
assert isinstance(topic, str)
self.protocol.register_pubsub(
"http://localhost:{}/raiden#{}".format(self.port, topic))
url = 'http://localhost:{}/raiden#{}'.format(self.port, topic)
self.protocol.register_pubsub(url) # pylint: disable=no-member
print 'Publish URI created: /raiden#{}'.format(topic)

def on_open(self):
Expand All @@ -50,18 +50,20 @@ def on_open(self):
# this is the place where the event topics are defined that don't correspond to
# a callback event

self.protocol.register_object(
"http://localhost:{}/raiden#".format(self.port), self)
url = "http://localhost:{}/raiden#".format(self.port), self
self.protocol.register_object(url) # pylint: disable=no-member

for topic in self.event_topics:
self.register_pubsub(topic)

# register all functions in self decorated with @register_callback_pubsub
# the uri will be the method name suffixed with '_status'
# e.g. topic for 'transfer()' status will be '#transfer_status'
for k in inspect.getmembers(self, inspect.ismethod):
if '_callback_pubsub' in k[1].__dict__:
self.register_pubsub(k[1]._callback_pubsub)
print "WAMP registration complete\n"
self.register_pubsub(k[1]._callback_pubsub) # pylint: disable=protected-access

print 'WAMP registration complete\n'

def on_message(self, message):
# FIXME: handle client reload/reconnect
Expand All @@ -71,7 +73,7 @@ def on_message(self, message):
return
super(WebSocketAPI, self).on_message(message)

def on_close(self, reason):
def on_close(self, reason): # pylint: disable=unused-argument,arguments-differ
print "closed"

# application:
Expand All @@ -80,13 +82,18 @@ def status_callback(self, _, status, id, topic, reason=None):
topic name guidelines:
'transfer_callb' - for inititated transfers (used in webui-JS)
"""
# pylint: disable=redefined-builtin, invalid-name

data = [id, status, reason]

# 7 - 'publish'
message = [7, "http://localhost:{}/raiden#{}".format(self.port, topic), data]
self.publish(message)
return True

def callback_with_exception(self, id, topic, reason=None):
# pylint: disable=redefined-builtin, invalid-name

if not reason:
reason = 'UNKNOWN'
self.status_callback(None, False, id, topic, reason=reason)
Expand All @@ -97,8 +104,8 @@ def publish(self, message):
7 - 'WAMP publish'
"""
print message
assert type(message) is list and len(message) == 3
self.protocol.pubsub_action(message)
assert isinstance(message, list) and len(message) == 3
self.protocol.pubsub_action(message) # pylint: disable=no-member

# refactor to API
@export_rpc
Expand All @@ -110,15 +117,17 @@ def get_assets(self):
def get_address(self):
return self.address

def print_callback(_, status):
def print_callback(self, status): # pylint: disable=no-self-use
print status


@register_pubsub_with_callback
@register_pubsub_with_callback # noqa
@export_rpc
def transfer(self, asset_address, amount, target, callback_id):
""" wraps around the APIs transfer() method to introduce additional PubSub and callback features
To get access to the raw API method, this method would have to be renamed
"""
Wraps around the APIs transfer() method to introduce additional
PubSub and callback features.

To get access to the raw API method, this method would have to be renamed
"""
# TODO: check all possible errors and pass them to the WAMP-Protocol
publish_topic = 'transfer_status'
Expand Down Expand Up @@ -161,7 +170,7 @@ def transfer(self, asset_address, amount, target, callback_id):
self.callback_with_exception(callback_id, publish_topic, reason='UNKNOWN')
raise

def _dispatch_additional_instance_methods(self, instance):
def _dispatch_additional_instance_methods(self, instance): # pylint: disable=invalid-name
""" dispatches all methods from the api that aren't already defined in WebSocketAPI"""
# self_methods = set([attr for attr in dir(self) if is_method(self, attr)])
self_methods = [k[0] for k in inspect.getmembers(self, inspect.ismethod)
Expand All @@ -171,8 +180,9 @@ def _dispatch_additional_instance_methods(self, instance):
if '_callback_pubsub' in k[1].__dict__]
methods_difference = list(set(instance_methods) - set(self_methods))
map(export_rpc, methods_difference)
self.protocol.register_object(
"http://localhost:{}/raiden#".format(self.port), instance) # XXX check for name collisions

url = 'http://localhost:{}/raiden#'.format(self.port)
self.protocol.register_object(url, instance) # XXX check for name collisions


class WAMPRouter(object):
Expand All @@ -185,10 +195,9 @@ def __init__(self, raiden, port, events=None):
self.port = port
self.events = events or [] # XXX check syntax

def make_static_application(self, basepath, staticdir):
def make_static_application(self, basepath, staticdir): # pylint: disable=no-self-use
def content_type(path):
"""Guess mime-type
"""
"""Guess mime-type. """

if path.endswith(".css"):
return "text/css"
Expand All @@ -201,7 +210,7 @@ def content_type(path):
else:
return "application/octet-stream"

def not_found(environ, start_response):
def not_found(environ, start_response): # pylint: disable=unused-argument
start_response('404 Not Found', [('content-type', 'text/html')])
return ["""<html><h1>Page not Found</h1><p>
That page is unknown. Return to
Expand All @@ -223,31 +232,38 @@ def app(environ, start_response):
return not_found(environ, start_response)
return app

def serve_index(self, environ, start_response):
def serve_index(self, environ, start_response): # pylint: disable=unused-argument
path = os.path.join(self.path, 'webui/index.html')
start_response("200 OK", [("Content-Type", "text/html")])
return open(path).readlines()

def run(self):
static_path = os.path.join(self.path, 'webui') # XXX naming

routes = [('^/static/', self.make_static_application('/static/', static_path)),
('^/$', self.serve_index),
('^/ws$', WebSocketAPI)
]
routes = [
('^/static/', self.make_static_application('/static/', static_path)),
('^/$', self.serve_index),
('^/ws$', WebSocketAPI)
]

data = {
'raiden': self.raiden,
'port': self.port,
'events': self.events
}

data = {'raiden': self.raiden,
'port': self.port,
'events': self.events
}
resource = Resource(routes, extra=data)

server = WebSocketServer(("", self.port), resource, debug=True)
host_port = ('', self.port)
server = WebSocketServer(
host_port,
resource,
debug=True,
)
server.serve_forever()

def stop():
def stop(self):
raise NotImplementedError()

"""
Tuple index out of range when the receivers address is shorter than 40(?) chars
"""

# Tuple index out of range when the receivers address is shorter than 40(?) chars
5 changes: 4 additions & 1 deletion raiden/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,10 @@ def app(address,
accmgr = AccountManager(keystore_path)
if not accmgr.address_in_keystore(address):
addresses = list(accmgr.accounts.keys())
formatted_addresses = ["[{:3d}] - 0x{}".format(idx, addr) for idx, addr in enumerate(addresses)]
formatted_addresses = [
'[{:3d}] - 0x{}'.format(idx, addr)
for idx, addr in enumerate(addresses)
]

should_prompt = True
while should_prompt:
Expand Down
3 changes: 2 additions & 1 deletion raiden/benchmark/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import print_function


def print_serialization(pstats): # pylint: disable=too-many-locals
Expand All @@ -16,7 +17,7 @@ def print_serialization(pstats): # pylint: disable=too-many-locals
# total calls count recursion
# total time is the time for the function itself (excluding subcalls)
# accumulated_time is the time of the function plus the subcalls
primitive_calls, total_calls, total_time, acc_time, callers = data # pylint: disable=unused-variable
primitive_calls, total_calls, total_time, acc_time, _ = data

if primitive_calls != total_calls:
calls = '{}/{}'.format(total_calls, primitive_calls)
Expand Down
4 changes: 3 additions & 1 deletion raiden/encoding/encoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ def validate(self, value):
raise ValueError('value is not an integer')

if self.minimum > value or self.maximum < value:
msg = '{} is outside the valide range [{},{}]'.format(value, self.minimum, self.maximum)
msg = (
'{} is outside the valide range [{},{}]'
).format(value, self.minimum, self.maximum)
raise ValueError(msg)

if PY2:
Expand Down
6 changes: 5 additions & 1 deletion raiden/encoding/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,11 @@ def __setattr__(self, name, value):

length = len(value)
if length > field.size_bytes:
raise ValueError('value with length {length} for {attr} is to big'.format(length=length, attr=name))
msg = 'value with length {length} for {attr} is too big'.format(
length=length,
attr=name,
)
raise ValueError(msg)
elif length < field.size_bytes:
pad_size = field.size_bytes - length
pad_value = b'\x00' * pad_size
Expand Down
6 changes: 5 additions & 1 deletion raiden/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -586,7 +586,9 @@ def __init__(self, identifier, nonce, asset, transferred_amount, recipient,
self.initiator = initiator

def __repr__(self):
return '<{} [asset:{} nonce:{} transferred_amount:{} lock_amount:{} hash:{} locksroot:{}]>'.format(
representation = (
'<{} [asset:{} nonce:{} transferred_amount:{} lock_amount:{} hash:{} locksroot:{}]>'
).format(
self.__class__.__name__,
pex(self.asset),
self.nonce,
Expand All @@ -596,6 +598,8 @@ def __repr__(self):
pex(self.locksroot),
)

return representation

@staticmethod
def unpack(packed):
lock = Lock(
Expand Down
3 changes: 3 additions & 0 deletions raiden/network/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,15 @@ class ContractDiscovery(Discovery):
"""On chain smart contract raiden node discovery: allows to register endpoints (host, port) for
your ethereum-/raiden-address and looking up endpoints for other ethereum-/raiden-addressess.
"""

def __init__(
self,
blockchainservice,
discovery_contract_address,
poll_timeout=DEFAULT_POLL_TIMEOUT):

super(ContractDiscovery, self).__init__()

self.chain = blockchainservice
self.poll_timeout = poll_timeout

Expand Down
Loading