71d56ea5f3014a3a2b93b3733bf3e50114331128
[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(), 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
24     
25     def dataReceived(self, data):
26         self.traffic_happened.happened('p2p/in', len(data))
27         self.dataReceived2(data)
28     
29     def dataReceiver(self):
30         while True:
31             start = ''
32             while start != self._message_prefix:
33                 start = (start + (yield 1))[-len(self._message_prefix):]
34             
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'
39                 continue
40             checksum = yield 4
41             payload = yield length
42             
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()
46                 continue
47             
48             type_ = getattr(self, 'message_' + command, None)
49             if type_ is None:
50                 if p2pool.DEBUG:
51                     print 'no type for', repr(command)
52                 continue
53             
54             try:
55                 self.packetReceived(command, type_.unpack(payload, self.ignore_trailing_payload))
56             except:
57                 print 'RECV', command, payload[:100].encode('hex') + ('...' if len(payload) > 100 else '')
58                 log.err(None, 'Error handling message: (see RECV line)')
59                 self.disconnect()
60     
61     def packetReceived(self, command, payload2):
62         handler = getattr(self, 'handle_' + command, None)
63         if handler is None:
64             if p2pool.DEBUG:
65                 print 'no handler for', repr(command)
66             return
67         
68         if getattr(self, 'connected', True) and not getattr(self, 'disconnecting', False):
69             handler(**payload2)
70     
71     def disconnect(self):
72         if hasattr(self.transport, 'abortConnection'):
73             # Available since Twisted 11.1
74             self.transport.abortConnection()
75         else:
76             # This doesn't always close timed out connections! warned about in main
77             self.transport.loseConnection()
78     
79     def badPeerHappened(self):
80         self.disconnect()
81     
82     def sendPacket(self, command, payload2):
83         if len(command) >= 12:
84             raise ValueError('command too long')
85         type_ = getattr(self, 'message_' + command, None)
86         if type_ is 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)
95     
96     def __getattr__(self, attr):
97         prefix = 'send_'
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)