ban peers that send a message with an invalid hash, since continually reconnecting...
[p2pool.git] / p2pool / util / p2protocol.py
1 '''
2 Generic message-based protocol used by Bitcoin and P2Pool for P2P communication
3 '''
4
5 import hashlib
6 import struct
7
8 from twisted.internet import protocol
9 from twisted.python import log
10
11 import p2pool
12 from p2pool.util import datachunker, variable
13
14 class TooLong(Exception):
15     pass
16
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.paused_var = variable.Variable(False)
23         self.traffic_happened = traffic_happened
24     
25     def connectionMade(self):
26         self.transport.registerProducer(self, True)
27     
28     def pauseProducing(self):
29         self.paused_var.set(True)
30     
31     def resumeProducing(self):
32         self.paused_var.set(False)
33     
34     def stopProducing(self):
35         pass
36     
37     def dataReceived(self, data):
38         self.traffic_happened.happened('p2p/in', len(data))
39         self.dataReceived2(data)
40     
41     def dataReceiver(self):
42         while True:
43             start = ''
44             while start != self._message_prefix:
45                 start = (start + (yield 1))[-len(self._message_prefix):]
46             
47             command = (yield 12).rstrip('\0')
48             length, = struct.unpack('<I', (yield 4))
49             if length > self._max_payload_length:
50                 print 'length too large'
51                 continue
52             checksum = yield 4
53             payload = yield length
54             
55             if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] != checksum:
56                 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')
57                 self.badPeerHappened()
58                 continue
59             
60             type_ = getattr(self, 'message_' + command, None)
61             if type_ is None:
62                 if p2pool.DEBUG:
63                     print 'no type for', repr(command)
64                 continue
65             
66             try:
67                 self.packetReceived(command, type_.unpack(payload))
68             except:
69                 print 'RECV', command, payload[:100].encode('hex') + ('...' if len(payload) > 100 else '')
70                 log.err(None, 'Error handling message: (see RECV line)')
71                 self.transport.loseConnection()
72     
73     def packetReceived(self, command, payload2):
74         handler = getattr(self, 'handle_' + command, None)
75         if handler is None:
76             if p2pool.DEBUG:
77                 print 'no handler for', repr(command)
78             return
79         
80         if getattr(self, 'connected', True) and not getattr(self, 'disconnecting', False):
81             handler(**payload2)
82     
83     def badPeerHappened(self):
84         self.transport.loseConnection()
85     
86     def sendPacket(self, command, payload2):
87         if len(command) >= 12:
88             raise ValueError('command too long')
89         type_ = getattr(self, 'message_' + command, None)
90         if type_ is None:
91             raise ValueError('invalid command')
92         #print 'SEND', command, repr(payload2)[:500]
93         payload = type_.pack(payload2)
94         if len(payload) > self._max_payload_length:
95             raise TooLong('payload too long')
96         data = self._message_prefix + struct.pack('<12sI', command, len(payload)) + hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] + payload
97         self.traffic_happened.happened('p2p/out', len(data))
98         self.transport.write(data)
99         return self.paused_var.get_when_satisfies(lambda paused: not paused)
100     
101     def __getattr__(self, attr):
102         prefix = 'send_'
103         if attr.startswith(prefix):
104             command = attr[len(prefix):]
105             return lambda **payload2: self.sendPacket(command, payload2)
106         #return protocol.Protocol.__getattr__(self, attr)
107         raise AttributeError(attr)