made WorkerBridge use broadcast_share instead of its own implementation
[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
13
14 class TooLong(Exception):
15     pass
16
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())
22     
23     def dataReceiver(self):
24         while True:
25             start = ''
26             while start != self._message_prefix:
27                 start = (start + (yield 1))[-len(self._message_prefix):]
28             
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'
33                 continue
34             checksum = yield 4
35             payload = yield length
36             
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')
39                 continue
40             
41             type_ = getattr(self, 'message_' + command, None)
42             if type_ is None:
43                 if p2pool.DEBUG:
44                     print 'no type for', repr(command)
45                 continue
46             
47             try:
48                 self.packetReceived(command, type_.unpack(payload))
49             except:
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()
53     
54     def packetReceived(self, command, payload2):
55         handler = getattr(self, 'handle_' + command, None)
56         if handler is None:
57             if p2pool.DEBUG:
58                 print 'no handler for', repr(command)
59             return
60         
61         handler(**payload2)
62     
63     def badPeerHappened(self):
64         self.transport.loseConnection()
65     
66     def sendPacket(self, command, payload2):
67         if len(command) >= 12:
68             raise ValueError('command too long')
69         type_ = getattr(self, 'message_' + command, None)
70         if type_ is 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)
77     
78     def __getattr__(self, attr):
79         prefix = 'send_'
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)