don't connect to old peers. should reduce bandwidth used
[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                 continue
58             
59             type_ = getattr(self, 'message_' + command, None)
60             if type_ is None:
61                 if p2pool.DEBUG:
62                     print 'no type for', repr(command)
63                 continue
64             
65             try:
66                 self.packetReceived(command, type_.unpack(payload))
67             except:
68                 print 'RECV', command, payload[:100].encode('hex') + ('...' if len(payload) > 100 else '')
69                 log.err(None, 'Error handling message: (see RECV line)')
70                 self.transport.loseConnection()
71     
72     def packetReceived(self, command, payload2):
73         handler = getattr(self, 'handle_' + command, None)
74         if handler is None:
75             if p2pool.DEBUG:
76                 print 'no handler for', repr(command)
77             return
78         
79         if getattr(self, 'connected', True) and not getattr(self, 'disconnecting', False):
80             handler(**payload2)
81     
82     def badPeerHappened(self):
83         self.transport.loseConnection()
84     
85     def sendPacket(self, command, payload2):
86         if len(command) >= 12:
87             raise ValueError('command too long')
88         type_ = getattr(self, 'message_' + command, None)
89         if type_ is None:
90             raise ValueError('invalid command')
91         #print 'SEND', command, repr(payload2)[:500]
92         payload = type_.pack(payload2)
93         if len(payload) > self._max_payload_length:
94             raise TooLong('payload too long')
95         data = self._message_prefix + struct.pack('<12sI', command, len(payload)) + hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] + payload
96         self.traffic_happened.happened('p2p/out', len(data))
97         self.transport.write(data)
98         return self.paused_var.get_when_satisfies(lambda paused: not paused)
99     
100     def __getattr__(self, attr):
101         prefix = 'send_'
102         if attr.startswith(prefix):
103             command = attr[len(prefix):]
104             return lambda **payload2: self.sendPacket(command, payload2)
105         #return protocol.Protocol.__getattr__(self, attr)
106         raise AttributeError(attr)