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(), ignore_trailing_payload=False):
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
23 self.ignore_trailing_payload = ignore_trailing_payload
25 def dataReceived(self, data):
26 self.traffic_happened.happened('p2p/in', len(data))
27 self.dataReceived2(data)
29 def dataReceiver(self):
32 while start != self._message_prefix:
33 start = (start + (yield 1))[-len(self._message_prefix):]
35 command = (yield 12).rstrip('\0')
36 length, = struct.unpack('<I', (yield 4))
37 if length > self._max_payload_length:
38 print 'length too large'
41 payload = yield length
43 if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] != checksum:
44 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')
45 self.badPeerHappened()
48 type_ = getattr(self, 'message_' + command, None)
51 print 'no type for', repr(command)
55 self.packetReceived(command, type_.unpack(payload, self.ignore_trailing_payload))
57 print 'RECV', command, payload[:100].encode('hex') + ('...' if len(payload) > 100 else '')
58 log.err(None, 'Error handling message: (see RECV line)')
61 def packetReceived(self, command, payload2):
62 handler = getattr(self, 'handle_' + command, None)
65 print 'no handler for', repr(command)
68 if getattr(self, 'connected', True) and not getattr(self, 'disconnecting', False):
72 if hasattr(self.transport, 'abortConnection'):
73 # Available since Twisted 11.1
74 self.transport.abortConnection()
76 # This doesn't always close timed out connections! warned about in main
77 self.transport.loseConnection()
79 def badPeerHappened(self):
82 def sendPacket(self, command, payload2):
83 if len(command) >= 12:
84 raise ValueError('command too long')
85 type_ = getattr(self, 'message_' + command, None)
87 raise ValueError('invalid command')
88 #print 'SEND', command, repr(payload2)[:500]
89 payload = type_.pack(payload2)
90 if len(payload) > self._max_payload_length:
91 raise TooLong('payload too long')
92 data = self._message_prefix + struct.pack('<12sI', command, len(payload)) + hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] + payload
93 self.traffic_happened.happened('p2p/out', len(data))
94 self.transport.write(data)
96 def __getattr__(self, attr):
98 if attr.startswith(prefix):
99 command = attr[len(prefix):]
100 return lambda **payload2: self.sendPacket(command, payload2)
101 #return protocol.Protocol.__getattr__(self, attr)
102 raise AttributeError(attr)