style cleanup
[p2pool.git] / p2pool / bitcoin / p2p.py
index 736ce41..aaf46d6 100644 (file)
@@ -8,9 +8,10 @@ import hashlib
 import random
 import struct
 import time
-import traceback
+import zlib
 
 from twisted.internet import defer, protocol, reactor
+from twisted.python import log
 
 from . import data as bitcoin_data
 from p2pool.util import variable, datachunker, deferral
@@ -48,7 +49,7 @@ class BaseProtocol(protocol.Protocol):
                     print 'INVALID HASH'
                     continue
             
-            type_ = getattr(self, "message_" + command, None)
+            type_ = getattr(self, 'message_' + 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)
@@ -58,7 +59,7 @@ class BaseProtocol(protocol.Protocol):
                 payload2 = type_.unpack(payload)
             except:
                 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
-                traceback.print_exc()
+                log.err()
                 continue
             
             handler = getattr(self, 'handle_' + command, None)
@@ -67,21 +68,22 @@ class BaseProtocol(protocol.Protocol):
                 print 'NO HANDLER FOR', command
                 continue
             
-            #print 'RECV', command, payload2
+            #print 'RECV', command, repr(payload2)[:500]
             
             try:
                 handler(**payload2)
             except:
                 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
-                traceback.print_exc()
+                log.err()
                 continue
     
     def sendPacket(self, command, payload2):
         if len(command) >= 12:
             raise ValueError('command too long')
-        type_ = getattr(self, "message_" + command, None)
+        type_ = getattr(self, 'message_' + command, None)
         if type_ is None:
             raise ValueError('invalid command')
+        #print 'SEND', command, repr(payload2)[:500]
         payload = type_.pack(payload2)
         if self.use_checksum:
             checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
@@ -182,7 +184,7 @@ class Protocol(BaseProtocol):
             elif inv['type'] == 'block':
                 self.factory.new_block.happened(inv['hash'])
             else:
-                print "Unknown inv type", item
+                print 'Unknown inv type', item
     
     message_getdata = bitcoin_data.ComposedType([
         ('requests', bitcoin_data.ListType(bitcoin_data.ComposedType([
@@ -209,7 +211,7 @@ class Protocol(BaseProtocol):
         ('id', bitcoin_data.HashType()),
         ('order', bitcoin_data.FixedStrType(60)), # XXX
     ])
-
+    
     message_addr = bitcoin_data.ComposedType([
         ('addrs', bitcoin_data.ListType(bitcoin_data.ComposedType([
             ('timestamp', bitcoin_data.StructType('<I')),
@@ -246,22 +248,22 @@ class Protocol(BaseProtocol):
     message_reply = bitcoin_data.ComposedType([
         ('hash', bitcoin_data.HashType()),
         ('reply',  bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'success': 0, 'failure': 1, 'denied': 2})),
-        ('script', bitcoin_data.PossiblyNone("", bitcoin_data.VarStrType())),
+        ('script', bitcoin_data.PossiblyNone('', bitcoin_data.VarStrType())),
     ])
     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))
-
+    
     message_ping = bitcoin_data.ComposedType([])
     def handle_ping(self):
         pass
-
+    
     message_alert = bitcoin_data.ComposedType([
         ('message', bitcoin_data.VarStrType()),
         ('signature', bitcoin_data.VarStrType()),
     ])
     def handle_alert(self, message, signature):
-        print "ALERT:", (message, signature)
+        print 'ALERT:', (message, signature)
     
     def connectionLost(self, reason):
         if hasattr(self.factory, 'gotConnection'):
@@ -354,7 +356,7 @@ class HeightTracker(object):
                     continue
                 self.request([], tail)
             try:
-                yield self.factory.new_headers.get_deferred(timeout=1)
+                yield self.factory.new_headers.get_deferred(timeout=5)
             except defer.TimeoutError:
                 pass
     
@@ -370,7 +372,7 @@ class HeightTracker(object):
         print len(self.tracker.shares)
     
     def request(self, have, last):
-        #print "REQ", ('[' + ', '.join(map(hex, have)) + ']', hex(last) if last is not None else None)
+        #print 'REQ', ('[' + ', '.join(map(hex, have)) + ']', hex(last) if last is not None else None)
         if self.factory.conn.value is not None:
             self.factory.conn.value.send_getheaders(version=1, have=have, last=last)
     
@@ -380,8 +382,17 @@ class HeightTracker(object):
         height, last = self.tracker.get_height_and_last(block_hash)
         if last is not None:
             self.request([], last)
-            #raise ValueError(last)
-        return height, last
+            raise ValueError()
+        return height
+    
+    def get_min_height(self, block_hash):
+        height, last = self.tracker.get_height_and_last(block_hash)
+        if last is not None:
+            self.request([], last)
+        return height
+    
+    def get_highest_height(self):
+        return self.tracker.get_highest_height()
 
 if __name__ == '__main__':
     factory = ClientFactory(bitcoin_data.Mainnet)
@@ -397,6 +408,6 @@ if __name__ == '__main__':
             try:
                 print h.getHeight(0xa285c3cb2a90ac7194cca034512748289e2526d9d7ae6ee7523)
             except Exception, e:
-                traceback.print_exc()
+                log.err()
     
     reactor.run()