2 Generic message-based protocol used by Bitcoin and P2Pool for P2P communication
8 from twisted.internet import protocol
9 from twisted.python import log
12 from p2pool.util import datachunker
14 class TooLong(Exception):
17 class Protocol(protocol.Protocol):
18 def __init__(self, message_prefix, max_payload_length):
19 self._message_prefix = message_prefix
20 self._max_payload_length = max_payload_length
21 self.dataReceived = datachunker.DataChunker(self.dataReceiver())
23 def dataReceiver(self):
26 while start != self._message_prefix:
27 start = (start + (yield 1))[-len(self._message_prefix):]
29 command = (yield 12).rstrip('\0')
30 length, = struct.unpack('<I', (yield 4))
31 if length > self._max_payload_length:
32 print 'length too large'
35 payload = yield length
37 if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] != checksum:
38 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')
41 type_ = getattr(self, 'message_' + command, None)
44 print 'no type for', repr(command)
48 self.packetReceived(command, type_.unpack(payload))
50 print 'RECV', command, payload[:100].encode('hex') + ('...' if len(payload) > 100 else '')
51 log.err(None, 'Error handling message: (see RECV line)')
52 self.badPeerHappened()
54 def packetReceived(self, command, payload2):
55 handler = getattr(self, 'handle_' + command, None)
58 print 'no handler for', repr(command)
63 def badPeerHappened(self):
64 self.transport.loseConnection()
66 def sendPacket(self, command, payload2):
67 if len(command) >= 12:
68 raise ValueError('command too long')
69 type_ = getattr(self, 'message_' + command, None)
71 raise ValueError('invalid command')
72 #print 'SEND', command, repr(payload2)[:500]
73 payload = type_.pack(payload2)
74 if len(payload) > self._max_payload_length:
75 raise TooLong('payload too long')
76 self.transport.write(self._message_prefix + struct.pack('<12sI', command, len(payload)) + hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] + payload)
78 def __getattr__(self, attr):
80 if attr.startswith(prefix):
81 command = attr[len(prefix):]
82 return lambda **payload2: self.sendPacket(command, payload2)
83 #return protocol.Protocol.__getattr__(self, attr)
84 raise AttributeError(attr)