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, variable
14 class TooLong(Exception):
17 class Protocol(protocol.Protocol):
18 def __init__(self, message_prefix, max_payload_length, traffic_happened=variable.Event()):
19 self._message_prefix = message_prefix
20 self._max_payload_length = max_payload_length
21 self.dataReceived2 = datachunker.DataChunker(self.dataReceiver())
22 self.traffic_happened = traffic_happened
24 def dataReceived(self, data):
25 self.traffic_happened.happened('p2p/in', len(data))
26 self.dataReceived2(data)
28 def dataReceiver(self):
31 while start != self._message_prefix:
32 start = (start + (yield 1))[-len(self._message_prefix):]
34 command = (yield 12).rstrip('\0')
35 length, = struct.unpack('<I', (yield 4))
36 if length > self._max_payload_length:
37 print 'length too large'
40 payload = yield length
42 if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] != checksum:
43 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')
44 self.badPeerHappened()
47 type_ = getattr(self, 'message_' + command, None)
50 print 'no type for', repr(command)
54 self.packetReceived(command, type_.unpack(payload))
56 print 'RECV', command, payload[:100].encode('hex') + ('...' if len(payload) > 100 else '')
57 log.err(None, 'Error handling message: (see RECV line)')
60 def packetReceived(self, command, payload2):
61 handler = getattr(self, 'handle_' + command, None)
64 print 'no handler for', repr(command)
67 if getattr(self, 'connected', True) and not getattr(self, 'disconnecting', False):
71 if hasattr(self.transport, 'abortConnection'):
72 # Available since Twisted 11.1
73 self.transport.abortConnection()
75 # This doesn't always close timed out connections! warned about in main
76 self.transport.loseConnection()
78 def badPeerHappened(self):
81 def sendPacket(self, command, payload2):
82 if len(command) >= 12:
83 raise ValueError('command too long')
84 type_ = getattr(self, 'message_' + command, None)
86 raise ValueError('invalid command')
87 #print 'SEND', command, repr(payload2)[:500]
88 payload = type_.pack(payload2)
89 if len(payload) > self._max_payload_length:
90 raise TooLong('payload too long')
91 data = self._message_prefix + struct.pack('<12sI', command, len(payload)) + hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] + payload
92 self.traffic_happened.happened('p2p/out', len(data))
93 self.transport.write(data)
95 def __getattr__(self, attr):
97 if attr.startswith(prefix):
98 command = attr[len(prefix):]
99 return lambda **payload2: self.sendPacket(command, payload2)
100 #return protocol.Protocol.__getattr__(self, attr)
101 raise AttributeError(attr)