don't flood on exceptions in network handling code
[p2pool.git] / p2pool / bitcoin / p2p.py
1 '''
2 Implementation of Bitcoin's p2p protocol
3 '''
4
5 from __future__ import division
6
7 import hashlib
8 import random
9 import struct
10 import time
11 import zlib
12
13 from twisted.internet import defer, protocol, reactor, task
14 from twisted.python import log
15
16 from . import data as bitcoin_data
17 from p2pool.util import variable, datachunker, deferral
18
19 class TooLong(Exception):
20     pass
21
22 class BaseProtocol(protocol.Protocol):
23     def connectionMade(self):
24         self.dataReceived = datachunker.DataChunker(self.dataReceiver())
25     
26     def dataReceiver(self):
27         while True:
28             start = ''
29             while start != self._prefix:
30                 start = (start + (yield 1))[-len(self._prefix):]
31             
32             command = (yield 12).rstrip('\0')
33             length, = struct.unpack('<I', (yield 4))
34             
35             if length > self.max_net_payload_length:
36                 print 'length too long'
37                 continue
38             
39             if self.use_checksum:
40                 checksum = yield 4
41             else:
42                 checksum = None
43             
44             compressed_payload = yield length
45             
46             if self.compress:
47                 try:
48                     d = zlib.decompressobj()
49                     payload = d.decompress(compressed_payload, self.max_payload_length)
50                     if d.unconsumed_tail:
51                         print 'compressed payload expanded too much'
52                         continue
53                     assert not len(payload) > self.max_payload_length
54                 except:
55                     log.err(None, 'Failure decompressing message:')
56                     continue
57             else:
58                 if len(compressed_payload) > self.max_payload_length:
59                     print 'compressed payload expanded too much'
60                     continue
61                 payload = compressed_payload
62             
63             if checksum is not None:
64                 if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] != checksum:
65                     print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
66                     print 'INVALID HASH'
67                     continue
68             
69             type_ = getattr(self, 'message_' + command, None)
70             if type_ is None:
71                 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
72                 print 'NO TYPE FOR', repr(command)
73                 continue
74             
75             try:
76                 payload2 = type_.unpack(payload)
77             except:
78                 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
79                 log.err(None, 'Error parsing message: (see RECV line)')
80                 continue
81             
82             handler = getattr(self, 'handle_' + command, None)
83             if handler is None:
84                 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
85                 print 'NO HANDLER FOR', command
86                 continue
87             
88             #print 'RECV', command, repr(payload2)[:500]
89             
90             try:
91                 handler(**payload2)
92             except:
93                 print 'RECV', command, len(payload), checksum.encode('hex')[:1000]
94                 log.err(None, 'Error handling message: (see RECV line)')
95                 continue
96     
97     def sendPacket(self, command, payload2):
98         if len(command) >= 12:
99             raise ValueError('command too long')
100         type_ = getattr(self, 'message_' + command, None)
101         if type_ is None:
102             raise ValueError('invalid command')
103         #print 'SEND', command, repr(payload2)[:500]
104         payload = type_.pack(payload2)
105         if len(payload) > self.max_payload_length:
106             raise TooLong('payload too long')
107         if self.use_checksum:
108             checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
109         else:
110             checksum = ''
111         compressed_payload = zlib.compress(payload) if self.compress else payload
112         if len(compressed_payload) > self.max_net_payload_length:
113             raise TooLong('compressed payload too long')
114         data = self._prefix + struct.pack('<12sI', command, len(compressed_payload)) + checksum + compressed_payload
115         self.transport.write(data)
116     
117     def __getattr__(self, attr):
118         prefix = 'send_'
119         if attr.startswith(prefix):
120             command = attr[len(prefix):]
121             return lambda **payload2: self.sendPacket(command, payload2)
122         #return protocol.Protocol.__getattr__(self, attr)
123         raise AttributeError(attr)
124
125 class Protocol(BaseProtocol):
126     def __init__(self, net):
127         self._prefix = net.BITCOIN_P2P_PREFIX
128     
129     version = 0
130     
131     max_payload_length = max_net_payload_length = 1000000
132     
133     compress = False
134     @property
135     def use_checksum(self):
136         return self.version >= 209
137     
138     
139     null_order = '\0'*60
140     
141     def connectionMade(self):
142         BaseProtocol.connectionMade(self)
143         
144         self.send_version(
145             version=32200,
146             services=1,
147             time=int(time.time()),
148             addr_to=dict(
149                 services=1,
150                 address=self.transport.getPeer().host,
151                 port=self.transport.getPeer().port,
152             ),
153             addr_from=dict(
154                 services=1,
155                 address=self.transport.getHost().host,
156                 port=self.transport.getHost().port,
157             ),
158             nonce=random.randrange(2**64),
159             sub_version_num='',
160             start_height=0,
161         )
162     
163     message_version = bitcoin_data.ComposedType([
164         ('version', bitcoin_data.StructType('<I')),
165         ('services', bitcoin_data.StructType('<Q')),
166         ('time', bitcoin_data.StructType('<Q')),
167         ('addr_to', bitcoin_data.address_type),
168         ('addr_from', bitcoin_data.address_type),
169         ('nonce', bitcoin_data.StructType('<Q')),
170         ('sub_version_num', bitcoin_data.VarStrType()),
171         ('start_height', bitcoin_data.StructType('<I')),
172     ])
173     def handle_version(self, version, services, time, addr_to, addr_from, nonce, sub_version_num, start_height):
174         #print 'VERSION', locals()
175         self.version_after = version
176         self.send_verack()
177     
178     message_verack = bitcoin_data.ComposedType([])
179     def handle_verack(self):
180         self.version = self.version_after
181         
182         self.ready()
183     
184     def ready(self):
185         self.check_order = deferral.GenericDeferrer(2**256, lambda id, order: self.send_checkorder(id=id, order=order))
186         self.submit_order = deferral.GenericDeferrer(2**256, lambda id, order: self.send_submitorder(id=id, order=order))
187         self.get_block = deferral.ReplyMatcher(lambda hash: self.send_getdata(requests=[dict(type='block', hash=hash)]))
188         self.get_block_header = deferral.ReplyMatcher(lambda hash: self.send_getheaders(version=1, have=[], last=hash))
189         self.get_tx = deferral.ReplyMatcher(lambda hash: self.send_getdata(requests=[dict(type='tx', hash=hash)]))
190         
191         if hasattr(self.factory, 'resetDelay'):
192             self.factory.resetDelay()
193         if hasattr(self.factory, 'gotConnection'):
194             self.factory.gotConnection(self)
195     
196     message_inv = bitcoin_data.ComposedType([
197         ('invs', bitcoin_data.ListType(bitcoin_data.ComposedType([
198             ('type', bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'tx': 1, 'block': 2})),
199             ('hash', bitcoin_data.HashType()),
200         ]))),
201     ])
202     def handle_inv(self, invs):
203         for inv in invs:
204             if inv['type'] == 'tx':
205                 self.factory.new_tx.happened(inv['hash'])
206             elif inv['type'] == 'block':
207                 self.factory.new_block.happened(inv['hash'])
208             else:
209                 print 'Unknown inv type', item
210     
211     message_getdata = bitcoin_data.ComposedType([
212         ('requests', bitcoin_data.ListType(bitcoin_data.ComposedType([
213             ('type', bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'tx': 1, 'block': 2})),
214             ('hash', bitcoin_data.HashType()),
215         ]))),
216     ])
217     message_getblocks = bitcoin_data.ComposedType([
218         ('version', bitcoin_data.StructType('<I')),
219         ('have', bitcoin_data.ListType(bitcoin_data.HashType())),
220         ('last', bitcoin_data.PossiblyNone(0, bitcoin_data.HashType())),
221     ])
222     message_getheaders = bitcoin_data.ComposedType([
223         ('version', bitcoin_data.StructType('<I')),
224         ('have', bitcoin_data.ListType(bitcoin_data.HashType())),
225         ('last', bitcoin_data.PossiblyNone(0, bitcoin_data.HashType())),
226     ])
227     message_getaddr = bitcoin_data.ComposedType([])
228     message_checkorder = bitcoin_data.ComposedType([
229         ('id', bitcoin_data.HashType()),
230         ('order', bitcoin_data.FixedStrType(60)), # XXX
231     ])
232     message_submitorder = bitcoin_data.ComposedType([
233         ('id', bitcoin_data.HashType()),
234         ('order', bitcoin_data.FixedStrType(60)), # XXX
235     ])
236     
237     message_addr = bitcoin_data.ComposedType([
238         ('addrs', bitcoin_data.ListType(bitcoin_data.ComposedType([
239             ('timestamp', bitcoin_data.StructType('<I')),
240             ('address', bitcoin_data.address_type),
241         ]))),
242     ])
243     def handle_addr(self, addrs):
244         for addr in addrs:
245             pass
246     
247     message_tx = bitcoin_data.ComposedType([
248         ('tx', bitcoin_data.tx_type),
249     ])
250     def handle_tx(self, tx):
251         self.get_tx.got_response(bitcoin_data.tx_type.hash256(tx), tx)
252     
253     message_block = bitcoin_data.ComposedType([
254         ('block', bitcoin_data.block_type),
255     ])
256     def handle_block(self, block):
257         block_hash = bitcoin_data.block_header_type.hash256(block['header'])
258         self.get_block.got_response(block_hash, block)
259         self.get_block_header.got_response(block_hash, block['header'])
260     
261     message_headers = bitcoin_data.ComposedType([
262         ('headers', bitcoin_data.ListType(bitcoin_data.block_type)),
263     ])
264     def handle_headers(self, headers):
265         for header in headers:
266             header = header['header']
267             self.get_block_header.got_response(bitcoin_data.block_header_type.hash256(header), header)
268         self.factory.new_headers.happened([header['header'] for header in headers])
269     
270     message_reply = bitcoin_data.ComposedType([
271         ('hash', bitcoin_data.HashType()),
272         ('reply',  bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'success': 0, 'failure': 1, 'denied': 2})),
273         ('script', bitcoin_data.PossiblyNone('', bitcoin_data.VarStrType())),
274     ])
275     def handle_reply(self, hash, reply, script):
276         self.check_order.got_response(hash, dict(reply=reply, script=script))
277         self.submit_order.got_response(hash, dict(reply=reply, script=script))
278     
279     message_ping = bitcoin_data.ComposedType([])
280     def handle_ping(self):
281         pass
282     
283     message_alert = bitcoin_data.ComposedType([
284         ('message', bitcoin_data.VarStrType()),
285         ('signature', bitcoin_data.VarStrType()),
286     ])
287     def handle_alert(self, message, signature):
288         print 'ALERT:', (message, signature)
289     
290     def connectionLost(self, reason):
291         if hasattr(self.factory, 'gotConnection'):
292             self.factory.gotConnection(None)
293
294 class ClientFactory(protocol.ReconnectingClientFactory):
295     protocol = Protocol
296     
297     maxDelay = 15
298     
299     def __init__(self, net):
300         self.net = net
301         self.conn = variable.Variable(None)
302         
303         self.new_block = variable.Event()
304         self.new_tx = variable.Event()
305         self.new_headers = variable.Event()
306     
307     def buildProtocol(self, addr):
308         p = self.protocol(self.net)
309         p.factory = self
310         return p
311     
312     def gotConnection(self, conn):
313         self.conn.set(conn)
314     
315     def getProtocol(self):
316         return self.conn.get_not_none()
317
318 class HeaderWrapper(object):
319     target = 0
320     __slots__ = 'hash previous_hash'.split(' ')
321     
322     def __init__(self, header):
323         self.hash = bitcoin_data.block_header_type.hash256(header)
324         self.previous_hash = header['previous_block']
325
326 class HeightTracker(object):
327     '''Point this at a factory and let it take care of getting block heights'''
328     
329     def __init__(self, factory):
330         self.factory = factory
331         self.tracker = bitcoin_data.Tracker()
332         self.most_recent = None
333         
334         self._watch1 = self.factory.new_headers.watch(self.heard_headers)
335         self._watch2 = self.factory.new_block.watch(self.heard_block)
336         
337         self.requested = set()
338         self._clear_task = task.LoopingCall(self.requested.clear)
339         self._clear_task.start(60)
340         
341         self.last_notified_size = 0
342         
343         self.updated = variable.Event()
344         
345         self.think()
346     
347     def think(self):
348         highest_head = max(self.tracker.heads, key=lambda h: self.tracker.get_height_and_last(h)[0]) if self.tracker.heads else None
349         height, last = self.tracker.get_height_and_last(highest_head)
350         cur = highest_head
351         cur_height = height
352         have = []
353         step = 1
354         while cur is not None:
355             have.append(cur)
356             if step > cur_height:
357                 break
358             cur = self.tracker.get_nth_parent_hash(cur, step)
359             cur_height -= step
360             if len(have) > 10:
361                 step *= 2
362         if height:
363             have.append(self.tracker.get_nth_parent_hash(highest_head, height - 1))
364         if not have:
365             have.append(0)
366         self.request(have, None)
367         
368         for tail in self.tracker.tails:
369             if tail is None:
370                 continue
371             self.request([], tail)
372         for head in self.tracker.heads:
373             if head == highest_head:
374                 continue
375             self.request([head], None)
376     
377     def heard_headers(self, headers):
378         changed = False
379         for header in headers:
380             hw = HeaderWrapper(header)
381             if hw.hash in self.tracker.shares:
382                 continue
383             changed = True
384             self.tracker.add(hw)
385         if changed:
386             self.updated.happened()
387         self.think()
388         
389         if len(self.tracker.shares) > self.last_notified_size + 10:
390             print 'Have %i block headers' % len(self.tracker.shares)
391             self.last_notified_size = len(self.tracker.shares)
392     
393     def heard_block(self, block_hash):
394         self.request([], block_hash)
395     
396     @defer.inlineCallbacks
397     def request(self, have, last):
398         if (tuple(have), last) in self.requested:
399             return
400         self.requested.add((tuple(have), last))
401         (yield self.factory.getProtocol()).send_getheaders(version=1, have=have, last=last)
402     
403     #@defer.inlineCallbacks
404     #XXX should defer?
405     def getHeight(self, block_hash):
406         height, last = self.tracker.get_height_and_last(block_hash)
407         if last is not None:
408             #self.request([], last)
409             raise ValueError()
410         return height
411     
412     def get_min_height(self, block_hash):
413         height, last = self.tracker.get_height_and_last(block_hash)
414         #if last is not None:
415         #    self.request([], last)
416         return height
417     
418     def get_highest_height(self):
419         return self.tracker.get_highest_height()
420     
421     def stop(self):
422         self.factory.new_headers.unwatch(self._watch1)
423         self.factory.new_block.unwatch(self._watch2)
424         self._clear_task.stop()
425
426 if __name__ == '__main__':
427     factory = ClientFactory(bitcoin_data.Mainnet)
428     reactor.connectTCP('127.0.0.1', 8333, factory)
429     h = HeightTracker(factory)
430     
431     @repr
432     @apply
433     @defer.inlineCallbacks
434     def think():
435         while True:
436             yield deferral.sleep(1)
437             print h.get_min_height(0xa285c3cb2a90ac7194cca034512748289e2526d9d7ae6ee7523)
438     
439     reactor.run()