Skip to content

Commit

Permalink
fix some pep8 problems
Browse files Browse the repository at this point in the history
  • Loading branch information
LipuFei committed Sep 9, 2014
1 parent 4e5b7ef commit 9d574c6
Show file tree
Hide file tree
Showing 9 changed files with 176 additions and 124 deletions.
2 changes: 1 addition & 1 deletion bloomfilter.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,5 +309,5 @@ def bytes(self):
"""
# hex should be m_size/4, hex is 16 instead of 8 -> hence half the number of "hexes" in m_size
hex_ = '%x' % self._filter
padding = '0' * (self._m_size /4 - len(hex_))
padding = '0' * (self._m_size / 4 - len(hex_))
return unhexlify(padding + hex_)[::-1]
17 changes: 11 additions & 6 deletions candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,8 @@ def age(self, now, category=u""):
- stumble :: NOW - candidate.last_stumble
- intro :: NOW - candidate.last_intro
- discovered :: NOW - candidate.last_discovered
- none :: NOW - max(candidate.last_walk, candidate.last_stumble, candidate.last_intro, candidate.last_discovered)
- none :: NOW - max(candidate.last_walk, candidate.last_stumble,
candidate.last_intro, candidate.last_discovered)
"""
if not category:
category = self.get_category(now)
Expand All @@ -220,7 +221,7 @@ def is_eligible_for_walk(self, now):
- SELF is either walk, stumble, or intro; and
- the previous step is more than CANDIDATE_ELIGIBLE_DELAY ago.
"""
return (self._last_walk + CANDIDATE_ELIGIBLE_DELAY <= now and self.get_category(now) != u"none")
return self._last_walk + CANDIDATE_ELIGIBLE_DELAY <= now and self.get_category(now) != u"none"

@property
def last_walk(self):
Expand Down Expand Up @@ -310,20 +311,24 @@ def update(self, tunnel, lan_address, wan_address, connection_type):
self._wan_address = wan_address
# someone can also reset from a known connection_type to unknown (i.e. it now believes it is
# no longer public nor symmetric NAT)
self._connection_type = u"public" if connection_type == u"unknown" and lan_address == wan_address else connection_type
self._connection_type = u"public" if connection_type == u"unknown" and lan_address == wan_address\
else connection_type

if __debug__:
if not (self.sock_addr == self._lan_address or self.sock_addr == self._wan_address):
self._logger.error("Either LAN %s or the WAN %s should be SOCK_ADDR %s", self._lan_address, self._wan_address, self.sock_addr)
self._logger.error("Either LAN %s or the WAN %s should be SOCK_ADDR %s", self._lan_address,
self._wan_address, self.sock_addr)

def __str__(self):
if self._sock_addr == self._lan_address == self._wan_address:
return "{%s:%d}" % self._lan_address
elif self._sock_addr in (self._lan_address, self._wan_address):
return "{%s:%d %s:%d}" % (self._lan_address[0], self._lan_address[1], self._wan_address[0], self._wan_address[1])
return "{%s:%d %s:%d}" % (self._lan_address[0], self._lan_address[1], self._wan_address[0],
self._wan_address[1])
else:
# should not occur
return "{%s:%d %s:%d %s:%d}" % (self._sock_addr[0], self._sock_addr[1], self._lan_address[0], self._lan_address[1], self._wan_address[0], self._wan_address[1])
return "{%s:%d %s:%d %s:%d}" % (self._sock_addr[0], self._sock_addr[1], self._lan_address[0],
self._lan_address[1], self._wan_address[0], self._wan_address[1])


class LoopbackCandidate(Candidate):
Expand Down
42 changes: 21 additions & 21 deletions crypto.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,39 +43,39 @@ def generate_key(self, security_level):
raise NotImplementedError()

def key_to_bin(self, key):
"Convert a key to the binary format."
"""Convert a key to the binary format."""
raise NotImplementedError()

def key_to_hash(self, key):
"Get a hash representation from a key."
"""Get a hash representation from a key."""
raise NotImplementedError()

def key_from_public_bin(self, string):
"Convert a public key stored in the binary format to a key object."
"""Convert a public key stored in the binary format to a key object."""
raise NotImplementedError()

def key_from_private_bin(self, string):
"Convert a public/private keypair stored in the binary format to a key object."
"""Convert a public/private keypair stored in the binary format to a key object."""
raise NotImplementedError()

def is_valid_public_bin(self, string):
"Verify if this binary string contains a public key."
"""Verify if this binary string contains a public key."""
raise NotImplementedError()

def is_valid_private_bin(self, string):
"Verify if this binary string contains a public/private keypair."
"""Verify if this binary string contains a public/private keypair."""
raise NotImplementedError()

def is_valid_signature(self, key, string, signature):
"Verify if the signature matches the one generated by key/string pair."
"""Verify if the signature matches the one generated by key/string pair."""
raise NotImplementedError()

def create_signature(self, key, string):
"Create a signature using this key for this string."
"""Create a signature using this key for this string."""
raise NotImplementedError()

def get_signature_length(self, key):
"Get the length of a signature created using this key in bytes."
"""Get the length of a signature created using this key in bytes."""
raise NotImplementedError()


Expand All @@ -89,7 +89,7 @@ class ECCrypto(DispersyCrypto):
"""

def _progress(self, *args):
"Called when no feedback needs to be given."
"""Called when no feedback needs to be given."""
pass

@property
Expand Down Expand Up @@ -135,7 +135,7 @@ def pem_to_bin(self, pem):

@attach_runtime_statistics(u"{0.__class__.__name__}.{function_name}")
def key_to_pem(self, ec):
"Convert a key to the PEM format."
"""Convert a key to the PEM format."""
bio = BIO.MemoryBuffer()
if isinstance(ec, EC_pub):
ec.save_pub_key_bio(bio)
Expand All @@ -145,19 +145,19 @@ def key_to_pem(self, ec):

@attach_runtime_statistics(u"{0.__class__.__name__}.{function_name}")
def key_from_private_pem(self, pem, password=None):
"Get the EC from a public/private keypair stored in the PEM."
"""Get the EC from a public/private keypair stored in the PEM."""
def get_password(*args):
return password or ""
return EC.load_key_bio(BIO.MemoryBuffer(pem), get_password)

@attach_runtime_statistics(u"{0.__class__.__name__}.{function_name}")
def key_from_public_pem(self, pem):
"Get the EC from a public PEM."
"""Get the EC from a public PEM."""
return EC.load_pub_key_bio(BIO.MemoryBuffer(pem))

@attach_runtime_statistics(u"{0.__class__.__name__}.{function_name}")
def is_valid_private_pem(self, pem):
"Returns True if the input is a valid public/private keypair"
"""Returns True if the input is a valid public/private keypair"""
try:
self.key_from_private_pem(pem)
except:
Expand All @@ -166,7 +166,7 @@ def is_valid_private_pem(self, pem):

@attach_runtime_statistics(u"{0.__class__.__name__}.{function_name}")
def is_valid_public_pem(self, pem):
"Returns True if the input is a valid public key"
"""Returns True if the input is a valid public key"""
try:
self.key_from_public_pem(pem)
except:
Expand All @@ -175,18 +175,18 @@ def is_valid_public_pem(self, pem):

@attach_runtime_statistics(u"{0.__class__.__name__}.{function_name}")
def key_to_bin(self, ec):
"Convert the key to a binary format."
"""Convert the key to a binary format."""
assert isinstance(ec, (EC.EC, EC_pub)), ec
return self.pem_to_bin(self.key_to_pem(ec))

@attach_runtime_statistics(u"{0.__class__.__name__}.{function_name}")
def key_to_hash(self, ec):
"Get a hash representation from a key."
"""Get a hash representation from a key."""
return sha1(self.key_to_bin(ec.pub())).digest()

@attach_runtime_statistics(u"{0.__class__.__name__}.{function_name}")
def is_valid_private_bin(self, string):
"Returns True if the input is a valid public/private keypair stored in a binary format"
"""Returns True if the input is a valid public/private keypair stored in a binary format"""
try:
self.key_from_private_bin(string)
except:
Expand All @@ -195,7 +195,7 @@ def is_valid_private_bin(self, string):

@attach_runtime_statistics(u"{0.__class__.__name__}.{function_name}")
def is_valid_public_bin(self, string):
"Returns True if the input is a valid public key"
"""Returns True if the input is a valid public key"""
try:
self.key_from_public_bin(string)
except:
Expand All @@ -204,14 +204,14 @@ def is_valid_public_bin(self, string):

@attach_runtime_statistics(u"{0.__class__.__name__}.{function_name}")
def key_from_private_bin(self, string):
"Get the EC from a public/private keypair stored in a binary format."
"""Get the EC from a public/private keypair stored in a binary format."""
return self.key_from_private_pem("".join(("-----BEGIN EC PRIVATE KEY-----\n",
string.encode("BASE64"),
"-----END EC PRIVATE KEY-----\n")))

@attach_runtime_statistics(u"{0.__class__.__name__}.{function_name}")
def key_from_public_bin(self, string):
"Get the EC from a public key in binary format."
"""Get the EC from a public key in binary format."""
return self.key_from_public_pem("".join(("-----BEGIN PUBLIC KEY-----\n",
string.encode("BASE64"),
"-----END PUBLIC KEY-----\n")))
Expand Down
2 changes: 1 addition & 1 deletion discovery/bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def load_addresses_from_file(filename):
"""
Reads FILENAME and returns the hosts therein, otherwise returns an empty list.
"""
addresses = []
addresses = list()
try:
for line in open(filename, "r"):
line = line.strip()
Expand Down
2 changes: 1 addition & 1 deletion discovery/community.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Written by Niels Zeilemaker, Egbert Bouman
import logging
import os
from random import shuffle, random, choice as random_choice
from random import shuffle, random
from time import time

from twisted.internet import reactor
Expand Down
22 changes: 14 additions & 8 deletions endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,8 @@ def dispersythread_data_came_in(self, packets, timestamp, cache=True):
def send(self, candidates, packets):
assert self._dispersy, "Should not be called before open(...)"
assert isinstance(candidates, (tuple, list, set)), type(candidates)
assert all(isinstance(candidate, Candidate) for candidate in candidates), [type(candidate) for candidate in candidates]
assert all(isinstance(candidate, Candidate) for candidate in candidates),\
[type(candidate) for candidate in candidates]
assert isinstance(packets, (tuple, list, set)), type(packets)
assert all(isinstance(packet, str) for packet in packets), [type(packet) for packet in packets]
assert all(len(packet) > 0 for packet in packets), [len(packet) for packet in packets]
Expand Down Expand Up @@ -258,7 +259,7 @@ def __init__(self, port, ip="0.0.0.0"):
self._running = False
self._add_task = lambda task, delay = 0.0, id = "": None
self._sendqueue_lock = threading.RLock()
self._sendqueue = []
self._sendqueue = list()

# _THREAD and _THREAD are set during open(...)
self._thread = None
Expand Down Expand Up @@ -300,7 +301,8 @@ def close(self, timeout=10.0):

else:
if self._thread.is_alive():
self._logger.debug("the endpoint thread is still running (use timeout > 0.0 to ensure the thread stops)")
self._logger.debug("the endpoint thread is still running"
" (use timeout > 0.0 to ensure the thread stops)")
result = False

try:
Expand Down Expand Up @@ -346,9 +348,11 @@ def _loop(self):

finally:
if packets:
self._logger.debug('%d came in, %d bytes in total', len(packets), sum(len(packet) for _, packet in packets))
self._logger.debug('%d came in, %d bytes in total',
len(packets), sum(len(packet) for _, packet in packets))
self.data_came_in(packets)


class ManualEnpoint(StandaloneEndpoint):

def __init__(self, *args, **kwargs):
Expand All @@ -357,19 +361,20 @@ def __init__(self, *args, **kwargs):
self.received_packets = []

def data_came_in(self, packets):
self._logger.debug('added %d packets to receivequeue, %d packets are queued in total', len(packets), len(packets) + len(self.received_packets))
self._logger.debug('added %d packets to receivequeue, %d packets are queued in total',
len(packets), len(packets) + len(self.received_packets))

with self.receive_lock:
self.received_packets.extend(packets)

def clear_receive_queue(self):
with self.receive_lock:
packets = self.received_packets
self.received_packets = []
self.received_packets = list()

if packets:
self._logger.debug('returning %d packets, %d bytes in total',
len(packets), sum(len(packet) for _, packet in packets))
len(packets), sum(len(packet) for _, packet in packets))
return packets

def process_receive_queue(self):
Expand All @@ -381,6 +386,7 @@ def process_packets(self, packets, cache=True):
self._logger.debug('processing %d packets', len(packets))
StandaloneEndpoint.data_came_in(self, packets, cache=cache)


class TunnelEndpoint(Endpoint):

def __init__(self, swift_process):
Expand All @@ -398,7 +404,7 @@ def close(self, timeout=0.0):
return super(TunnelEndpoint, self).close(timeout)

def get_address(self):
return ("0.0.0.0", self._swift.listenport)
return "0.0.0.0", self._swift.listenport

def send(self, candidates, packets, prefix=None):
assert self._dispersy, "Should not be called before open(...)"
Expand Down
Loading

0 comments on commit 9d574c6

Please sign in to comment.