moved BaseProtocol to util.p2protocol
authorForrest Voight <forrest@forre.st>
Fri, 16 Mar 2012 19:04:12 +0000 (15:04 -0400)
committerForrest Voight <forrest@forre.st>
Fri, 16 Mar 2012 19:25:17 +0000 (15:25 -0400)
p2pool/bitcoin/p2p.py
p2pool/p2p.py
p2pool/util/p2protocol.py [new file with mode: 0644]

index 46c104f..9ac6e9e 100644 (file)
@@ -2,95 +2,17 @@
 Implementation of Bitcoin's p2p protocol
 '''
 
-from __future__ import division
-
-import hashlib
 import random
-import struct
 import time
 
 from twisted.internet import defer, protocol, reactor, task
-from twisted.python import log
 
-import p2pool
 from . import data as bitcoin_data
-from p2pool.util import datachunker, deferral, pack, variable
-
-class TooLong(Exception):
-    pass
-
-class BaseProtocol(protocol.Protocol):
-    def __init__(self, message_prefix, max_payload_length):
-        self._message_prefix = message_prefix
-        self._max_payload_length = max_payload_length
-        self.dataReceived = datachunker.DataChunker(self.dataReceiver())
-    
-    def dataReceiver(self):
-        while True:
-            start = ''
-            while start != self._message_prefix:
-                start = (start + (yield 1))[-len(self._message_prefix):]
-            
-            command = (yield 12).rstrip('\0')
-            length, = struct.unpack('<I', (yield 4))
-            if length > self._max_payload_length:
-                print 'length too large'
-                continue
-            checksum = yield 4
-            payload = yield length
-            
-            if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] != checksum:
-                print 'invalid hash for', self.transport.getPeer().host, repr(command), length, checksum.encode('hex'), hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4].encode('hex'), payload.encode('hex')
-                continue
-            
-            type_ = getattr(self, 'message_' + command, None)
-            if type_ is None:
-                if p2pool.DEBUG:
-                    print 'no type for', repr(command)
-                continue
-            
-            try:
-                self.packetReceived(command, type_.unpack(payload))
-            except:
-                print 'RECV', command, payload[:100].encode('hex') + ('...' if len(payload) > 100 else '')
-                log.err(None, 'Error handling message: (see RECV line)')
-                self.badPeerHappened()
-    
-    def packetReceived(self, command, payload2):
-        handler = getattr(self, 'handle_' + command, None)
-        if handler is None:
-            if p2pool.DEBUG:
-                print 'no handler for', repr(command)
-            return
-        
-        handler(**payload2)
-    
-    def badPeerHappened(self):
-        self.transport.loseConnection()
-    
-    def sendPacket(self, command, payload2):
-        if len(command) >= 12:
-            raise ValueError('command too long')
-        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 len(payload) > self._max_payload_length:
-            raise TooLong('payload too long')
-        self.transport.write(self._message_prefix + struct.pack('<12sI', command, len(payload)) + hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] + payload)
-    
-    def __getattr__(self, attr):
-        prefix = 'send_'
-        if attr.startswith(prefix):
-            command = attr[len(prefix):]
-            return lambda **payload2: self.sendPacket(command, payload2)
-        #return protocol.Protocol.__getattr__(self, attr)
-        raise AttributeError(attr)
+from p2pool.util import deferral, p2protocol, pack, variable
 
-class Protocol(BaseProtocol):
+class Protocol(p2protocol.Protocol):
     def __init__(self, net):
-        BaseProtocol.__init__(self, net.P2P_PREFIX, 1000000)
+        p2protocol.Protocol.__init__(self, net.P2P_PREFIX, 1000000)
     
     def connectionMade(self):
         self.send_version(
index e823864..5dd2af7 100644 (file)
@@ -8,16 +8,15 @@ from twisted.python import log
 
 import p2pool
 from p2pool import data as p2pool_data
-from p2pool.bitcoin import p2p as bitcoin_p2p
 from p2pool.bitcoin import data as bitcoin_data
-from p2pool.util import deferral, pack
+from p2pool.util import deferral, p2protocol, pack
 
 class PeerMisbehavingError(Exception):
     pass
 
-class Protocol(bitcoin_p2p.BaseProtocol):
+class Protocol(p2protocol.Protocol):
     def __init__(self, node, incoming):
-        bitcoin_p2p.BaseProtocol.__init__(self, node.net.PREFIX, 1000000)
+        p2protocol.Protocol.__init__(self, node.net.PREFIX, 1000000)
         self.node = node
         self.incoming = incoming
         
@@ -67,7 +66,7 @@ class Protocol(bitcoin_p2p.BaseProtocol):
         try:
             if command != 'version' and not self.connected2:
                 raise PeerMisbehavingError('first message was not version message')
-            bitcoin_p2p.BaseProtocol.packetReceived(self, command, payload2)
+            p2protocol.Protocol.packetReceived(self, command, payload2)
         except PeerMisbehavingError, e:
             print 'Peer %s:%i misbehaving, will drop and ban. Reason:' % self.addr, e.message
             self.badPeerHappened()
@@ -206,7 +205,7 @@ class Protocol(bitcoin_p2p.BaseProtocol):
         def att(f, **kwargs):
             try:
                 f(**kwargs)
-            except bitcoin_p2p.TooLong:
+            except p2protocol.TooLong:
                 att(f, **dict((k, v[:len(v)//2]) for k, v in kwargs.iteritems()))
                 att(f, **dict((k, v[len(v)//2:]) for k, v in kwargs.iteritems()))
         if shares:
diff --git a/p2pool/util/p2protocol.py b/p2pool/util/p2protocol.py
new file mode 100644 (file)
index 0000000..1886713
--- /dev/null
@@ -0,0 +1,84 @@
+'''
+Generic message-based protocol used by Bitcoin and P2Pool for P2P communication
+'''
+
+import hashlib
+import struct
+
+from twisted.internet import protocol
+from twisted.python import log
+
+import p2pool
+from p2pool.util import datachunker
+
+class TooLong(Exception):
+    pass
+
+class Protocol(protocol.Protocol):
+    def __init__(self, message_prefix, max_payload_length):
+        self._message_prefix = message_prefix
+        self._max_payload_length = max_payload_length
+        self.dataReceived = datachunker.DataChunker(self.dataReceiver())
+    
+    def dataReceiver(self):
+        while True:
+            start = ''
+            while start != self._message_prefix:
+                start = (start + (yield 1))[-len(self._message_prefix):]
+            
+            command = (yield 12).rstrip('\0')
+            length, = struct.unpack('<I', (yield 4))
+            if length > self._max_payload_length:
+                print 'length too large'
+                continue
+            checksum = yield 4
+            payload = yield length
+            
+            if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] != checksum:
+                print 'invalid hash for', self.transport.getPeer().host, repr(command), length, checksum.encode('hex'), hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4].encode('hex'), payload.encode('hex')
+                continue
+            
+            type_ = getattr(self, 'message_' + command, None)
+            if type_ is None:
+                if p2pool.DEBUG:
+                    print 'no type for', repr(command)
+                continue
+            
+            try:
+                self.packetReceived(command, type_.unpack(payload))
+            except:
+                print 'RECV', command, payload[:100].encode('hex') + ('...' if len(payload) > 100 else '')
+                log.err(None, 'Error handling message: (see RECV line)')
+                self.badPeerHappened()
+    
+    def packetReceived(self, command, payload2):
+        handler = getattr(self, 'handle_' + command, None)
+        if handler is None:
+            if p2pool.DEBUG:
+                print 'no handler for', repr(command)
+            return
+        
+        handler(**payload2)
+    
+    def badPeerHappened(self):
+        self.transport.loseConnection()
+    
+    def sendPacket(self, command, payload2):
+        if len(command) >= 12:
+            raise ValueError('command too long')
+        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 len(payload) > self._max_payload_length:
+            raise TooLong('payload too long')
+        self.transport.write(self._message_prefix + struct.pack('<12sI', command, len(payload)) + hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] + payload)
+    
+    def __getattr__(self, attr):
+        prefix = 'send_'
+        if attr.startswith(prefix):
+            command = attr[len(prefix):]
+            return lambda **payload2: self.sendPacket(command, payload2)
+        #return protocol.Protocol.__getattr__(self, attr)
+        raise AttributeError(attr)