cleanup
authorforrest <forrest@470744a7-cac9-478e-843e-5ec1b25c69e8>
Thu, 16 Jun 2011 16:07:23 +0000 (16:07 +0000)
committerforrest <forrest@470744a7-cac9-478e-843e-5ec1b25c69e8>
Thu, 16 Jun 2011 16:07:23 +0000 (16:07 +0000)
git-svn-id: svn://forre.st/p2pool@1346 470744a7-cac9-478e-843e-5ec1b25c69e8

bitcoin_p2p.py
conv.py
db.py
expiring_dict.py
jsonrpc.py
main.py
p2p.py
p2pool.py
util.py
worker_interface.py

index 698d9bf..8971577 100644 (file)
@@ -1,6 +1,6 @@
-"""
+'''
 Implementation of Bitcoin's p2p protocol
-"""
+'''
 
 from __future__ import division
 
@@ -29,7 +29,7 @@ class Type(object):
         
         if not ignore_extra:
             if f.tell() != len(data):
-                raise LateEnd("underread " + repr((self, data)))
+                raise LateEnd('underread ' + repr((self, data)))
         
         return obj
     
@@ -56,10 +56,10 @@ class VarIntType(Type):
         data = file.read(1)
         if len(data) != 1:
             raise EarlyEnd()
-        first, = struct.unpack("<B", data)
-        if first == 0xff: desc = "<Q"
-        elif first == 0xfe: desc = "<I"
-        elif first == 0xfd: desc = "<H"
+        first, = struct.unpack('<B', data)
+        if first == 0xff: desc = '<Q'
+        elif first == 0xfe: desc = '<I'
+        elif first == 0xfd: desc = '<H'
         else: return first
         length = struct.calcsize(desc)
         data = file.read(length)
@@ -69,22 +69,22 @@ class VarIntType(Type):
     
     def write(self, file, item):
         if item < 0xfd:
-            file.write(struct.pack("<B", item))
+            file.write(struct.pack('<B', item))
         elif item <= 0xffff:
-            file.write(struct.pack("<BH", 0xfd, item))
+            file.write(struct.pack('<BH', 0xfd, item))
         elif item <= 0xffffffff:
-            file.write(struct.pack("<BI", 0xfe, item))
+            file.write(struct.pack('<BI', 0xfe, item))
         elif item <= 0xffffffffffffffff:
-            file.write(struct.pack("<BQ", 0xff, item))
+            file.write(struct.pack('<BQ', 0xff, item))
         else:
-            raise ValueError("int too large for varint")
+            raise ValueError('int too large for varint')
 
 class VarStrType(Type):
     def read(self, file):
         length = VarIntType().read(file)
         res = file.read(length)
         if len(res) != length:
-            raise EarlyEnd("var str not long enough %r" % ((length, len(res), res),))
+            raise EarlyEnd('var str not long enough %r' % ((length, len(res), res),))
         return res
     
     def write(self, file, item):
@@ -98,12 +98,12 @@ class FixedStrType(Type):
     def read(self, file):
         res = file.read(self.length)
         if len(res) != self.length:
-            raise EarlyEnd("early EOF!")
+            raise EarlyEnd('early EOF!')
         return res
     
     def write(self, file, item):
         if len(item) != self.length:
-            raise ValueError("incorrect length!")
+            raise ValueError('incorrect length!')
         file.write(item)
 
 class EnumType(Type):
@@ -114,7 +114,7 @@ class EnumType(Type):
         self.keys = {}
         for k, v in values.iteritems():
             if v in self.keys:
-                raise ValueError("duplicate value in values")
+                raise ValueError('duplicate value in values')
             self.keys[v] = k
     
     def read(self, file):
@@ -127,7 +127,7 @@ class HashType(Type):
     def read(self, file):
         data = file.read(256//8)
         if len(data) != 256//8:
-            raise EarlyEnd("incorrect length!")
+            raise EarlyEnd('incorrect length!')
         return int(data[::-1].encode('hex'), 16)
     
     def write(self, file, item):
@@ -137,7 +137,7 @@ class ShortHashType(Type):
     def read(self, file):
         data = file.read(160//8)
         if len(data) != 160//8:
-            raise EarlyEnd("incorrect length!")
+            raise EarlyEnd('incorrect length!')
         return int(data[::-1].encode('hex'), 16)
     
     def write(self, file, item):
@@ -263,12 +263,12 @@ class BaseProtocol(protocol.Protocol):
     
     def dataReceiver(self):
         while True:
-            start = ""
+            start = ''
             while start != self._prefix:
                 start = (start + (yield 1))[-len(self._prefix):]
             
             command = (yield 12).rstrip('\0')
-            length, = struct.unpack("<I", (yield 4))
+            length, = struct.unpack('<I', (yield 4))
             
             if self.use_checksum:
                 checksum = yield 4
@@ -279,52 +279,52 @@ class BaseProtocol(protocol.Protocol):
             
             if checksum is not None:
                 if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] != checksum:
-                    print "RECV", command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
-                    print "INVALID HASH"
+                    print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
+                    print 'INVALID HASH'
                     continue
             
             type_ = self.message_types.get(command, None)
             if type_ is None:
-                print "RECV", command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
-                print "NO TYPE FOR", repr(command)
+                print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
+                print 'NO TYPE FOR', repr(command)
                 continue
             
             try:
                 payload2 = type_.unpack(payload)
             except:
-                print "RECV", command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
+                print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
                 traceback.print_exc()
                 continue
             
-            handler = getattr(self, "handle_" + command, None)
+            handler = getattr(self, 'handle_' + command, None)
             if handler is None:
-                print "RECV", command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
-                print "NO HANDLER FOR", command
+                print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
+                print 'NO HANDLER FOR', command
                 continue
             
-            #print "RECV", command, payload2
+            #print 'RECV', command, payload2
             
             try:
                 handler(**payload2)
             except:
-                print "RECV", command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
+                print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
                 traceback.print_exc()
                 continue
     
     def sendPacket(self, command, payload2={}):
         payload = self.message_types[command].pack(payload2)
         if len(command) >= 12:
-            raise ValueError("command too long")
+            raise ValueError('command too long')
         if self.use_checksum:
             checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
         else:
-            checksum = ""
-        data = self._prefix + struct.pack("<12sI", command, len(payload)) + checksum + payload
+            checksum = ''
+        data = self._prefix + struct.pack('<12sI', command, len(payload)) + checksum + payload
         self.transport.write(data)
-        #print "SEND", command, payload2
+        #print 'SEND', command, payload2
     
     def __getattr__(self, attr):
-        prefix = "send_"
+        prefix = 'send_'
         if attr.startswith(prefix):
             command = attr[len(prefix):]
             return lambda **payload2: self.sendPacket(command, payload2)
@@ -364,13 +364,13 @@ class Protocol(BaseProtocol):
         ]),
         'inv': ComposedType([
             ('invs', ListType(ComposedType([
-                ('type', EnumType(StructType('<I'), {"tx": 1, "block": 2})),
+                ('type', EnumType(StructType('<I'), {'tx': 1, 'block': 2})),
                 ('hash', HashType()),
             ]))),
         ]),
         'getdata': ComposedType([
             ('requests', ListType(ComposedType([
-                ('type', EnumType(StructType('<I'), {"tx": 1, "block": 2})),
+                ('type', EnumType(StructType('<I'), {'tx': 1, 'block': 2})),
                 ('hash', HashType()),
             ]))),
         ]),
@@ -434,12 +434,12 @@ class Protocol(BaseProtocol):
                 port=self.transport.getHost().port,
             ),
             nonce=random.randrange(2**64),
-            sub_version_num="",
+            sub_version_num='',
             start_height=0,
         )
     
     def handle_version(self, version, services, time, addr_to, addr_from, nonce, sub_version_num, start_height):
-        #print "VERSION", locals()
+        #print 'VERSION', locals()
         self.version_after = version
         self.send_verack()
     
@@ -449,29 +449,29 @@ class Protocol(BaseProtocol):
         # connection ready
         self.check_order = util.GenericDeferrer(2**256, lambda id, order: self.send_checkorder(id=id, order=order))
         self.submit_order = util.GenericDeferrer(2**256, lambda id, order: self.send_submitorder(id=id, order=order))
-        self.get_block = util.ReplyMatcher(lambda hash: self.send_getdata(requests=[dict(type="block", hash=hash)]))
-        self.get_block_header = util.ReplyMatcher(lambda hash: self.send_getdata(requests=[dict(type="block", hash=hash)]))
+        self.get_block = util.ReplyMatcher(lambda hash: self.send_getdata(requests=[dict(type='block', hash=hash)]))
+        self.get_block_header = util.ReplyMatcher(lambda hash: self.send_getdata(requests=[dict(type='block', hash=hash)]))
         
-        if hasattr(self.factory, "resetDelay"):
+        if hasattr(self.factory, 'resetDelay'):
             self.factory.resetDelay()
-        if hasattr(self.factory, "gotConnection"):
+        if hasattr(self.factory, 'gotConnection'):
             self.factory.gotConnection(self)
     
     def handle_inv(self, invs):
         for inv in invs:
-            #print "INV", item['type'], hex(item['hash'])
+            #print 'INV', item['type'], hex(item['hash'])
             self.send_getdata(requests=[inv])
     
     def handle_addr(self, addrs):
         for addr in addrs:
-            pass#print "ADDR", addr
+            pass#print 'ADDR', addr
     
     def handle_reply(self, hash, reply, script):
         self.check_order.got_response(hash, dict(reply=reply, script=script))
         self.submit_order.got_response(hash, dict(reply=reply, script=script))
     
     def handle_tx(self, tx):
-        pass#print "TX", hex(merkle_hash([tx])), tx
+        pass#print 'TX', hex(merkle_hash([tx])), tx
     
     def handle_block(self, block):
         self.get_block.got_response(block_hash(block['header']), block)
@@ -481,7 +481,7 @@ class Protocol(BaseProtocol):
         pass
     
     def connectionLost(self, reason):
-        if hasattr(self.factory, "gotConnection"):
+        if hasattr(self.factory, 'gotConnection'):
             self.factory.gotConnection(None)
 
 class ProtocolInv(Protocol):
@@ -492,19 +492,19 @@ class ProtocolInv(Protocol):
         for inv in requests:
             type_, hash_ = inv['type'], inv['hash']
             if (type_, hash_) in self.inv:
-                print "bitcoind requested %s %x, sent" % (type_, hash_)
+                print 'bitcoind requested %s %x, sent' % (type_, hash_)
                 self.sendPacket(type_, {type_: self.inv[(type_, hash_)]})
             else:
-                print "bitcoind requested %s %x, but not found" % (type_, hash_)
+                print 'bitcoind requested %s %x, but not found' % (type_, hash_)
     
     def addInv(self, type_, data):
         if self.inv is None: self.inv = {}
-        if type_ == "block":
+        if type_ == 'block':
             hash_ = block_hash(data['header'])
-        elif type_ == "tx":
+        elif type_ == 'tx':
             hash_ = merkle_hash([data])
         else:
-            raise ValueError("invalid type: %r" % (type_,))
+            raise ValueError('invalid type: %r' % (type_,))
         self.inv[(type_, hash_)] = data
         self.send_inv(invs=[dict(type=type_, hash=hash_)])
 
@@ -550,8 +550,8 @@ class ClientFactory(protocol.ReconnectingClientFactory):
         
         return df
 
-if __name__ == "__main__":
+if __name__ == '__main__':
     factory = ClientFactory()
-    reactor.connectTCP("127.0.0.1", 8333, factory)
+    reactor.connectTCP('127.0.0.1', 8333, factory)
     
     reactor.run()
diff --git a/conv.py b/conv.py
index 89a353b..48dec9d 100644 (file)
--- a/conv.py
+++ b/conv.py
@@ -1,6 +1,6 @@
-"""
+'''
 Representation of a getwork request/reply
-"""
+'''
 
 from __future__ import division
 
@@ -22,41 +22,41 @@ class BlockAttempt(object):
         self.version, self.previous_block, self.merkle_root, self.timestamp, self.bits = version, previous_block, merkle_root, timestamp, bits
     
     def __repr__(self):
-        return "<BlockAttempt %s>" % (' '.join('%s=%s' % (k, hex(v))) for k, v in self.__dict__.iteritems())
+        return '<BlockAttempt %s>' % (' '.join('%s=%s' % (k, hex(v))) for k, v in self.__dict__.iteritems())
     
     def __eq__(self, other):
         if not isinstance(other, BlockAttempt):
-            raise ValueError("comparisons only valid with other BlockAttempts")
+            raise ValueError('comparisons only valid with other BlockAttempts')
         return self.__dict__ == other.__dict__
     
     def __ne__(self, other):
         return not (self == other)
     
     def __repr__(self):
-        return "BlockAttempt(%s)" % (', '.join('%s=%r' % (k, v) for k, v in self.__dict__.iteritems()),)
+        return 'BlockAttempt(%s)' % (', '.join('%s=%r' % (k, v) for k, v in self.__dict__.iteritems()),)
     
     def getwork(self, target_multiplier=1, _check=2):
         target = bits_to_target(self.bits) * target_multiplier
         
         previous_block2 = reverse_chunks('%064x' % self.previous_block, 8).decode('hex')
         merkle_root2 = reverse_chunks('%064x' % self.merkle_root, 8).decode('hex')
-        data = struct.pack(">I32s32sIII", self.version, previous_block2, merkle_root2, self.timestamp, self.bits, 0).encode('hex') + "000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000"
+        data = struct.pack('>I32s32sIII', self.version, previous_block2, merkle_root2, self.timestamp, self.bits, 0).encode('hex') + '000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000'
         
         previous_block3 = ('%064x' % self.previous_block).decode('hex')[::-1]
         merkle_root3 = ('%064x' % self.merkle_root).decode('hex')[::-1]
-        data2 = struct.pack("<I32s32s", self.version, previous_block3, merkle_root3)
+        data2 = struct.pack('<I32s32s', self.version, previous_block3, merkle_root3)
         
         getwork = {
-            "data": data,
-            "hash1": "00000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000010000",
-            "target": ('%064x' % (target,)).decode('hex')[::-1].encode('hex'),
-            "midstate": reverse_chunks(sha256.process(data2[:64])[::-1], 4).encode('hex'),
+            'data': data,
+            'hash1': '00000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000010000',
+            'target': ('%064x' % (target,)).decode('hex')[::-1].encode('hex'),
+            'midstate': reverse_chunks(sha256.process(data2[:64])[::-1], 4).encode('hex'),
         }
         
         if _check:
             self2 = self.__class__.from_getwork(getwork, _check=_check - 1, _check_multiplier=target_multiplier)
             if self2 != self:
-                raise ValueError("failed check - input invalid or implementation error")
+                raise ValueError('failed check - input invalid or implementation error')
         
         return getwork
     
@@ -70,17 +70,17 @@ class BlockAttempt(object):
         if _check:
             getwork2 = ba.getwork(_check_multiplier, _check=_check - 1)
             if getwork2 != getwork:
-                raise ValueError("failed check - input invalid or implementation error")
+                raise ValueError('failed check - input invalid or implementation error')
         
         return ba
 
 def decode_data(data):
-    version, previous_block, merkle_root, timestamp, bits, nonce = struct.unpack(">I32s32sIII", data[:160].decode('hex'))
+    version, previous_block, merkle_root, timestamp, bits, nonce = struct.unpack('>I32s32sIII', data[:160].decode('hex'))
     previous_block = int(reverse_chunks(previous_block.encode('hex'), 8), 16)
     merkle_root = int(reverse_chunks(merkle_root.encode('hex'), 8), 16)
     return dict(version=version, previous_block=previous_block, merkle_root=merkle_root, timestamp=timestamp, bits=bits, nonce=nonce)
 
-if __name__ == "__main__":
+if __name__ == '__main__':
     ba = BlockAttempt(
         1,
         0x000000000000148135e10208db85abb62754341a392eab1f186aab077a831cf7,
@@ -91,8 +91,8 @@ if __name__ == "__main__":
     ba.getwork(1, 100)
     ba.getwork(10, 100)
     ba.from_getwork({
-        "target": "0000000000000000000000000000000000000000000000f2b944000000000000",
-        "midstate": "5982f893102dec03e374b472647c4f19b1b6d21ae4b2ac624f3d2f41b9719404",
-        "hash1": "00000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000010000",
-        "data": "0000000163930d52a5ffca79b29b95a659a302cd4e1654194780499000002274000000002e133d9e51f45bc0886d05252038e421e82bff18b67dc14b90d9c3c2f422cd5c4dd4598e1a44b9f200000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000"
+        'target': '0000000000000000000000000000000000000000000000f2b944000000000000',
+        'midstate': '5982f893102dec03e374b472647c4f19b1b6d21ae4b2ac624f3d2f41b9719404',
+        'hash1': '00000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000010000',
+        'data': '0000000163930d52a5ffca79b29b95a659a302cd4e1654194780499000002274000000002e133d9e51f45bc0886d05252038e421e82bff18b67dc14b90d9c3c2f422cd5c4dd4598e1a44b9f200000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000'
 }, _check=100)
diff --git a/db.py b/db.py
index b2a57c1..3e484d7 100644 (file)
--- a/db.py
+++ b/db.py
@@ -8,11 +8,11 @@ class SQLiteDict(object):
         self._db.execute('CREATE TABLE IF NOT EXISTS %s(key BLOB PRIMARY KEY NOT NULL, value BLOB NOT NULL)' % (self._table,))
     
     def __len__(self):
-        for row in self._db.execute("SELECT COUNT(key) FROM %s" % (self._table,)):
+        for row in self._db.execute('SELECT COUNT(key) FROM %s' % (self._table,)):
             return row[0]
     
     def __iter__(self):
-        for row in self._db.execute("SELECT key FROM %s" % (self._table,)):
+        for row in self._db.execute('SELECT key FROM %s' % (self._table,)):
             yield str(row[0])
     def iterkeys(self):
         return iter(self)
@@ -20,19 +20,19 @@ class SQLiteDict(object):
         return list(self)
     
     def itervalues(self):
-        for row in self._db.execute("SELECT value FROM %s" % (self._table,)):
+        for row in self._db.execute('SELECT value FROM %s' % (self._table,)):
             yield str(row[0])
     def values(self):
         return list(self.itervalues)
     
     def iteritems(self):
-        for row in self._db.execute("SELECT key, value FROM %s" % (self._table,)):
+        for row in self._db.execute('SELECT key, value FROM %s' % (self._table,)):
             yield (str(row[0]), str(row[1]))
     def items(self):
         return list(self.iteritems())
     
     def __setitem__(self, key, value):
-        if self._db.execute("SELECT key FROM %s where key=?" % (self._table,), (buffer(key),)).fetchone() is None:
+        if self._db.execute('SELECT key FROM %s where key=?' % (self._table,), (buffer(key),)).fetchone() is None:
             self._db.execute('INSERT INTO %s (key, value) VALUES (?, ?)' % (self._table,), (buffer(key), buffer(value)))
         else:
             self._db.execute('UPDATE %s SET value=? WHERE key=?' % (self._table,), (buffer(value), buffer(key)))
@@ -45,4 +45,4 @@ class SQLiteDict(object):
             return str(row[0])
     
     def __delitem__(self, key):
-        self._db.execute("DELETE FROM %s WHERE key=?" % (self._table,), (buffer(key),))
+        self._db.execute('DELETE FROM %s WHERE key=?' % (self._table,), (buffer(key),))
index 9bf7bfb..ddc9fed 100644 (file)
@@ -19,7 +19,7 @@ class Node(object):
     @staticmethod
     def connect(prev, next):
         if prev.next is not None or next.prev is not None:
-            raise ValueError("node already connected")
+            raise ValueError('node already connected')
         prev.next, next.prev = next, prev
     
     def replace(self, contents):
@@ -27,7 +27,7 @@ class Node(object):
     
     def delete(self):
         if self.prev.next is None or self.next.prev is None:
-            raise ValueError("node not connected")
+            raise ValueError('node not connected')
         self.prev.next, self.next.prev = self.next, self.prev
         self.next = self.prev = None
 
@@ -41,7 +41,7 @@ class LinkedList(object):
             self.append(item)
     
     def __repr__(self):
-        return "LinkedList(%r)" % (list(self),)
+        return 'LinkedList(%r)' % (list(self),)
     
     def __len__(self):
         return sum(1 for x in self)
@@ -67,13 +67,13 @@ class LinkedList(object):
             for i in xrange(-index):
                 cur = cur.prev
                 if cur is self.start:
-                    raise IndexError("index out of range")
+                    raise IndexError('index out of range')
         else:
             cur = self.start
             for i in xrange(index + 1):
                 cur = cur.next
                 if cur is self.end:
-                    raise IndexError("index out of range")
+                    raise IndexError('index out of range')
         return cur
     
     def appendleft(self, item):
@@ -85,14 +85,14 @@ class LinkedList(object):
     def popleft(self):
         node = self.start.next
         if node is self.end:
-            raise IndexError("popleft from empty")
+            raise IndexError('popleft from empty')
         node.delete()
         return node.contents
     
     def pop(self):
         node = self.end.prev
         if node is self.start:
-            raise IndexError("pop from empty")
+            raise IndexError('pop from empty')
         node.delete()
         return node.contents
 
@@ -107,7 +107,7 @@ class ExpiringDict(object):
     
     def __repr__(self):
         reactor.callLater(0, self.expire)
-        return "ExpiringDict" + repr(self.__dict__)
+        return 'ExpiringDict' + repr(self.__dict__)
     
     def __len__(self):
         reactor.callLater(0, self.expire)
@@ -115,7 +115,7 @@ class ExpiringDict(object):
     
     _nothing = object()
     def touch(self, key, value=_nothing):
-        "Updates expiry node, optionally replacing value, returning new value"
+        'Updates expiry node, optionally replacing value, returning new value'
         if value is self._nothing or key in self.d:
             node, old_value = self.d[key]
             node.delete()
@@ -180,13 +180,13 @@ if __name__ == '__main__':
     time.sleep(1)
     
     x[1] = 2
-    print "x[1] = 2"
+    print 'x[1] = 2'
     print x
     
     time.sleep(1)
     
     x[1] = 3
-    print "x[1] = 3"
+    print 'x[1] = 3'
     print x
     
     time.sleep(5)
index d578e2b..1eb33d0 100644 (file)
@@ -12,12 +12,12 @@ import util
 class Error(Exception):
     def __init__(self, code, message, data=None):
         if not isinstance(code, int):
-            raise TypeError("code must be an int")
+            raise TypeError('code must be an int')
         if not isinstance(message, unicode):
-            raise TypeError("message must be a unicode")
+            raise TypeError('message must be a unicode')
         self._code, self._message, self._data = code, message, data
     def __str__(self):
-        return "%i %s %r" % (self._code, self._message, self._data)
+        return '%i %s %r' % (self._code, self._message, self._data)
     def _to_obj(self):
         return {
             'code': self._code,
@@ -38,10 +38,10 @@ class Proxy(object):
             'Content-Type': 'text/json',
         }
         if self._auth is not None:
-            headers['Authorization'] = "Basic " + base64.b64encode(':'.join(self._auth))
+            headers['Authorization'] = 'Basic ' + base64.b64encode(':'.join(self._auth))
         resp = json.loads((yield client.getPage(
             url=self._url,
-            method="POST",
+            method='POST',
             headers=headers,
             postdata=json.dumps({
                 'jsonrpc': '2.0',
@@ -52,7 +52,7 @@ class Proxy(object):
         )))
         
         if resp['id'] != id_:
-            raise ValueError("invalid id")
+            raise ValueError('invalid id')
         if 'error' in resp and resp['error'] is not None:
             raise Error(resp['error'])
         defer.returnValue(resp['result'])
@@ -78,7 +78,7 @@ class Server(util.DeferredResource):
             try:
                 req = json.loads(data)
             except Exception:
-                raise RemoteError(-32700, u"Parse error")
+                raise RemoteError(-32700, u'Parse error')
         except Error, e:
             # id unknown
             request.write(json.dumps({
@@ -99,11 +99,11 @@ class Server(util.DeferredResource):
                 if not isinstance(params, list):
                     raise ValueError()
             except Exception:
-                raise Error(-32600, u"Invalid Request")
+                raise Error(-32600, u'Invalid Request')
             
-            method_name = "rpc_" + method
+            method_name = 'rpc_' + method
             if not hasattr(self, method_name):
-                raise Error(-32601, u"Method not found")
+                raise Error(-32601, u'Method not found')
             method_meth = getattr(self, method_name)
             
             df = defer.maybeDeferred(method_meth, *params)
@@ -116,9 +116,9 @@ class Server(util.DeferredResource):
             except Error, e:
                 raise e
             except Exception, e:
-                print "Squelched JSON method error:"
+                print 'Squelched JSON method error:'
                 traceback.print_exc()
-                raise Error(-32099, u"Unknown error")
+                raise Error(-32099, u'Unknown error')
             
             request.write(json.dumps({
                 'jsonrpc': '2.0',
diff --git a/main.py b/main.py
index bc5f909..0ed47d3 100644 (file)
--- a/main.py
+++ b/main.py
@@ -214,7 +214,7 @@ def main(args):
                 if factory.conn is not None:
                     factory.conn.addInv('block', share.as_block())
                 else:
-                    print "No bitcoind connection! Erp!"
+                    print 'No bitcoind connection! Erp!'
             
             chain = get_chain(share.chain_id_data)
             res = chain.accept(share, net)
@@ -331,7 +331,7 @@ def main(args):
             chain = new_work['current_chain']
             for share2 in chain.share2s.itervalues():
                 if not share2.shared:
-                    print "Sharing share of switched to chain. Hash:", share2.share.hash
+                    print 'Sharing share of switched to chain. Hash:', share2.share.hash
                     share_share2(share2)
             for hash, peer in chain.request_map.iteritems():
                 if hash not in chain.share2s:
@@ -373,7 +373,7 @@ def main(args):
                 print "Couldn't link returned work's merkle root with its transactions - should only happen if you recently restarted p2pool"
                 return False
             share = p2pool.Share(header=header, txns=transactions)
-            print "GOT SHARE! %x" % (share.hash,)
+            print 'GOT SHARE! %x' % (share.hash,)
             try:
                 p2p_share(share)
             except:
diff --git a/p2p.py b/p2p.py
index 5fad2d5..2c47050 100644 (file)
--- a/p2p.py
+++ b/p2p.py
@@ -4,7 +4,7 @@ import random
 import time
 import traceback
 
-from twisted.internet import defer, protocol, reactor, task
+from twisted.internet import defer, protocol, reactor
 
 import bitcoin_p2p
 import conv
@@ -17,7 +17,7 @@ import util
 
 class Protocol(bitcoin_p2p.BaseProtocol):
     version = 0
-    sub_version = ""
+    sub_version = ''
     
     def __init__(self, node):
         self.node = node
@@ -135,7 +135,7 @@ class Protocol(bitcoin_p2p.BaseProtocol):
     
     def _connect_timeout(self):
         if not self.connected2 and self.transport.connected:
-            print "Handshake timed out, disconnecting"
+            print 'Handshake timed out, disconnecting'
             self.transport.loseConnection()
     
     @defer.inlineCallbacks
@@ -148,7 +148,7 @@ class Protocol(bitcoin_p2p.BaseProtocol):
     def _think2(self):
         while self.connected2:
             self.send_addrme(port=self.node.port)
-            print "sending addrme"
+            print 'sending addrme'
             yield util.sleep(random.expovariate(1/100))
     
     def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, state):
@@ -157,11 +157,11 @@ class Protocol(bitcoin_p2p.BaseProtocol):
         self.other_mode_var = util.Variable(mode)
         
         if nonce == self.node.nonce:
-            #print "Detected connection to self, disconnecting"
+            #print 'Detected connection to self, disconnecting'
             self.transport.loseConnection()
             return
         if nonce in self.node.peers:
-            print "Detected duplicate connection, disconnecting"
+            print 'Detected duplicate connection, disconnecting'
             self.transport.loseConnection()
             return
         
@@ -186,7 +186,7 @@ class Protocol(bitcoin_p2p.BaseProtocol):
     
     def handle_addrme(self, port):
         host = self.transport.getPeer().host
-        print "addrme from", host, port
+        print 'addrme from', host, port
         if host == '127.0.0.1':
             if random.random() < .7 and self.node.peers:
                 random.choice(self.node.peers.values()).send_addrme(port=port) # services...
@@ -235,7 +235,7 @@ class Protocol(bitcoin_p2p.BaseProtocol):
         for share1 in share1s:
             hash_ = bitcoin_p2p.block_hash(share1['header'])
             if hash_ <= conv.bits_to_target(share1['header']['bits']):
-                print "Dropping peer %s:%i due to invalid share" % (self.transport.getPeer().host, self.transport.getPeer().port)
+                print 'Dropping peer %s:%i due to invalid share' % (self.transport.getPeer().host, self.transport.getPeer().port)
                 self.transport.loseConnection()
                 return
             share = p2pool.Share(share1['header'], gentx=share1['gentx'])
@@ -244,7 +244,7 @@ class Protocol(bitcoin_p2p.BaseProtocol):
         for share2 in share2s:
             hash_ = bitcoin_p2p.block_hash(share2['header'])
             if not hash_ <= conv.bits_to_target(share2['header']['bits']):
-                print "Dropping peer %s:%i due to invalid share" % (self.transport.getPeer().host, self.transport.getPeer().port)
+                print 'Dropping peer %s:%i due to invalid share' % (self.transport.getPeer().host, self.transport.getPeer().port)
                 self.transport.loseConnection()
                 return
             share = p2pool.Share(share2['header'], txns=share2['txns'])
@@ -345,7 +345,7 @@ class Node(object):
     
     def start(self):
         if self.running:
-            raise ValueError("already running")
+            raise ValueError('already running')
         
         self.running = True
         
@@ -365,11 +365,11 @@ class Node(object):
                         host2, port = random.choice(self.addr_store.keys())
                         prefix = '::ffff:'
                         if not host2.startswith(prefix):
-                            raise ValueError("invalid address")
+                            raise ValueError('invalid address')
                         host = host2[len(prefix):]
                     
                     if (host, port) not in self.attempts:
-                        print "Trying to connect to", host, port
+                        print 'Trying to connect to', host, port
                         reactor.connectTCP(host, port, ClientFactory(self), timeout=10)
             except:
                 traceback.print_exc()
@@ -389,7 +389,7 @@ class Node(object):
     
     def stop(self):
         if not self.running:
-            raise ValueError("already stopped")
+            raise ValueError('already stopped')
         
         self.running = False
         
@@ -399,7 +399,7 @@ class Node(object):
     def attempt_started(self, connector):
         host, port = connector.getDestination().host, connector.getDestination().port
         if (host, port) in self.attempts:
-            raise ValueError("already have attempt")
+            raise ValueError('already have attempt')
         self.attempts[host, port] = connector
     
     def attempt_failed(self, connector):
@@ -410,25 +410,25 @@ class Node(object):
         if (host, port) not in self.attempts:
             raise ValueError("don't have attempt")
         if connector is not self.attempts[host, port]:
-            raise ValueError("wrong connector")
+            raise ValueError('wrong connector')
         del self.attempts[host, port]
     
     
     def got_conn(self, conn):
         if conn.nonce in self.peers:
-            raise ValueError("already have peer")
+            raise ValueError('already have peer')
         self.peers[conn.nonce] = conn
         
-        print "Connected to peer %s:%i" % (conn.transport.getPeer().host, conn.transport.getPeer().port)
+        print 'Connected to peer %s:%i' % (conn.transport.getPeer().host, conn.transport.getPeer().port)
     
     def lost_conn(self, conn):
         if conn.nonce not in self.peers:
             raise ValueError("don't have peer")
         if conn is not self.peers[conn.nonce]:
-            raise ValueError("wrong conn")
+            raise ValueError('wrong conn')
         del self.peers[conn.nonce]
         
-        print "Lost peer %s:%i" % (conn.transport.getPeer().host, conn.transport.getPeer().port)
+        print 'Lost peer %s:%i' % (conn.transport.getPeer().host, conn.transport.getPeer().port)
     
     
     def got_addr(self, (host, port), services, timestamp):
@@ -439,16 +439,16 @@ class Node(object):
             self.addr_store[host, port] = services, timestamp, timestamp
     
     def handle_share(self, share, peer):
-        print "handle_share", (share, peer)
+        print 'handle_share', (share, peer)
     
     def handle_share_hash(self, chain_id_data, hash, peer):
-        print "handle_share_hash", (chain_id_data, hash, peer)
+        print 'handle_share_hash', (chain_id_data, hash, peer)
     
     def handle_get_to_best(self, chain_id_data, have, peer):
-        print "handle_get_to_best", (chain_id_data, have, peer)
+        print 'handle_get_to_best', (chain_id_data, have, peer)
     
     def handle_get_shares(self, chain_id_data, hashes, peer):
-        print "handle_get_shares", (chain_id_data, hashes, peer)
+        print 'handle_get_shares', (chain_id_data, hashes, peer)
 
 if __name__ == '__main__':
     p = random.randrange(2**15, 2**16)
index 0991a17..5427a5c 100644 (file)
--- a/p2pool.py
+++ b/p2pool.py
@@ -77,12 +77,12 @@ class Share(object):
                     print '%x' % header['merkle_root']
                     raise ValueError("gentx doesn't match header")
             else:
-                raise ValueError("need either txns or gentx")
+                raise ValueError('need either txns or gentx')
         else:
             self.gentx = txns_to_gentx(txns)
             if gentx is not None:
                 if gentx != self.gentx:
-                    raise ValueError("invalid gentx")
+                    raise ValueError('invalid gentx')
         
         self.coinbase = coinbase_type.unpack(self.gentx['tx']['tx_ins'][0]['script'], ignore_extra=True)
         self.previous_share_hash = self.coinbase['previous_p2pool_share_hash'] if self.coinbase['previous_p2pool_share_hash'] != 2**256 - 1 else None
@@ -90,7 +90,7 @@ class Share(object):
     
     def as_block(self):
         if self.txns is None:
-            raise ValueError("share does not contain all txns")
+            raise ValueError('share does not contain all txns')
         return dict(header=self.header, txns=self.txns)
     
     def as_share1(self):
@@ -117,7 +117,7 @@ class Share(object):
         return Share2(self, shares, height)
 
 class Share2(object):
-    """Share with associated data"""
+    '''Share with associated data'''
     
     def __init__(self, share, shares, height):
         self.share = share
diff --git a/util.py b/util.py
index f9b14b4..410f740 100644 (file)
--- a/util.py
+++ b/util.py
@@ -18,7 +18,7 @@ class DeferredResource(resource.Resource):
         
         def finish_error(fail):
             request.setResponseCode(500) # won't do anything if already written to
-            request.write("---ERROR---")
+            request.write('---ERROR---')
             request.finish()
             fail.printTraceback()
         
@@ -84,9 +84,9 @@ def median(x):
     return (y[left] + y[right])/2
 
 class StringBuffer(object):
-    "Buffer manager with great worst-case behavior"
+    'Buffer manager with great worst-case behavior'
     
-    def __init__(self, data=""):
+    def __init__(self, data=''):
         self.buf = collections.deque([data])
         self.buf_len = len(data)
         self.pos = 0
@@ -100,7 +100,7 @@ class StringBuffer(object):
     
     def get(self, wants):
         if self.buf_len - self.pos < wants:
-            raise IndexError("not enough data")
+            raise IndexError('not enough data')
         data = []
         while wants:
             seg = self.buf[0][self.pos:self.pos+wants]
@@ -124,10 +124,10 @@ def _DataChunker(receiver):
         else:
             buf.add((yield))
 def DataChunker(receiver):
-    """
+    '''
     Produces a function that accepts data that is input into a generator
     (receiver) in response to the receiver yielding the size of data to wait on
-    """
+    '''
     x = _DataChunker(receiver)
     x.next()
     return x.send
@@ -217,14 +217,14 @@ class DeferredCacher(object):
 
 def pubkey_to_address(pubkey, testnet):
     if len(pubkey) != 65:
-        raise ValueError("invalid pubkey")
+        raise ValueError('invalid pubkey')
     version = 111 if testnet else 0
     key_hash = chr(version) + hashlib.new('ripemd160', hashlib.sha256(pubkey).digest()).digest()
     checksum = hashlib.sha256(hashlib.sha256(key_hash).digest()).digest()[:4]
     return base58_encode(key_hash + checksum)
 
 def base58_encode(data):
-    return "1"*(len(data) - len(data.lstrip(chr(0)))) + natural_to_string(string_to_natural(data), "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
+    return '1'*(len(data) - len(data.lstrip(chr(0)))) + natural_to_string(string_to_natural(data), '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz')
 
 def natural_to_string(n, alphabet=None, min_width=1):
     if alphabet is None:
index fd8480c..d781e15 100644 (file)
@@ -42,13 +42,7 @@ class WorkerInterface(jsonrpc.Server):
         self.putChild('', self)
     
     def rpc_getwork(self, data=None):
-        try:
-            if data is not None:
-                return self.response_callback(data)
-            
-            res = self.compute(self.work.value)
-            
-            return res
-        except:
-            import traceback
-            traceback.print_exc()
+        if data is not None:
+            return self.response_callback(data)
+        
+        return self.compute(self.work.value)