made HeightTracker._think and _think2 catch any errors
[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
12 from twisted.internet import defer, protocol, reactor, task
13 from twisted.python import log
14
15 from . import data as bitcoin_data, getwork
16 from p2pool.util import variable, datachunker, deferral, forest
17
18 class TooLong(Exception):
19     pass
20
21 class BaseProtocol(protocol.Protocol):
22     def connectionMade(self):
23         self.dataReceived = datachunker.DataChunker(self.dataReceiver())
24     
25     def dataReceiver(self):
26         while True:
27             start = ''
28             while start != self._prefix:
29                 start = (start + (yield 1))[-len(self._prefix):]
30             
31             command = (yield 12).rstrip('\0')
32             length, = struct.unpack('<I', (yield 4))
33             
34             if length > self.max_payload_length:
35                 print 'length too large'
36                 continue
37             
38             if self.use_checksum:
39                 checksum = yield 4
40             else:
41                 checksum = None
42             
43             payload = yield length
44             
45             if checksum is not None:
46                 if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] != checksum:
47                     print 'invalid hash for', repr(command), checksum.encode('hex') if checksum is not None else None, repr(payload[:100].encode('hex')), len(payload)
48                     continue
49             
50             type_ = getattr(self, 'message_' + command, None)
51             if type_ is None:
52                 print 'no type for', repr(command)
53                 continue
54             
55             try:
56                 payload2 = type_.unpack(payload)
57             except:
58                 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
59                 log.err(None, 'Error parsing message: (see RECV line)')
60                 continue
61             
62             handler = getattr(self, 'handle_' + command, None)
63             if handler is None:
64                 print 'no handler for', repr(command)
65                 continue
66             
67             try:
68                 handler(**payload2)
69             except:
70                 print 'RECV', command, repr(payload2)[:100]
71                 log.err(None, 'Error handling message: (see RECV line)')
72                 continue
73             
74             self.gotPacket()
75     
76     def gotPacket(self):
77         pass
78     
79     def sendPacket(self, command, payload2):
80         if len(command) >= 12:
81             raise ValueError('command too long')
82         type_ = getattr(self, 'message_' + command, None)
83         if type_ is None:
84             raise ValueError('invalid command')
85         #print 'SEND', command, repr(payload2)[:500]
86         payload = type_.pack(payload2)
87         if len(payload) > self.max_payload_length:
88             raise TooLong('payload too long')
89         if self.use_checksum:
90             checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
91         else:
92             checksum = ''
93         data = self._prefix + struct.pack('<12sI', command, len(payload)) + checksum + payload
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)
103
104 class Protocol(BaseProtocol):
105     def __init__(self, net):
106         self._prefix = net.BITCOIN_P2P_PREFIX
107     
108     version = 0
109     
110     max_payload_length = 1000000
111     
112     @property
113     def use_checksum(self):
114         return self.version >= 209
115     
116     def connectionMade(self):
117         BaseProtocol.connectionMade(self)
118         
119         self.send_version(
120             version=32200,
121             services=1,
122             time=int(time.time()),
123             addr_to=dict(
124                 services=1,
125                 address=self.transport.getPeer().host,
126                 port=self.transport.getPeer().port,
127             ),
128             addr_from=dict(
129                 services=1,
130                 address=self.transport.getHost().host,
131                 port=self.transport.getHost().port,
132             ),
133             nonce=random.randrange(2**64),
134             sub_version_num='',
135             start_height=0,
136         )
137     
138     message_version = bitcoin_data.ComposedType([
139         ('version', bitcoin_data.StructType('<I')),
140         ('services', bitcoin_data.StructType('<Q')),
141         ('time', bitcoin_data.StructType('<Q')),
142         ('addr_to', bitcoin_data.address_type),
143         ('addr_from', bitcoin_data.address_type),
144         ('nonce', bitcoin_data.StructType('<Q')),
145         ('sub_version_num', bitcoin_data.VarStrType()),
146         ('start_height', bitcoin_data.StructType('<I')),
147     ])
148     def handle_version(self, version, services, time, addr_to, addr_from, nonce, sub_version_num, start_height):
149         #print 'VERSION', locals()
150         self.version_after = version
151         self.send_verack()
152     
153     message_verack = bitcoin_data.ComposedType([])
154     def handle_verack(self):
155         self.version = self.version_after
156         
157         self.ready()
158     
159     def ready(self):
160         self.get_block = deferral.ReplyMatcher(lambda hash: self.send_getdata(requests=[dict(type='block', hash=hash)]))
161         self.get_block_header = deferral.ReplyMatcher(lambda hash: self.send_getheaders(version=1, have=[], last=hash))
162         self.get_tx = deferral.ReplyMatcher(lambda hash: self.send_getdata(requests=[dict(type='tx', hash=hash)]))
163         
164         if hasattr(self.factory, 'resetDelay'):
165             self.factory.resetDelay()
166         if hasattr(self.factory, 'gotConnection'):
167             self.factory.gotConnection(self)
168     
169     message_inv = bitcoin_data.ComposedType([
170         ('invs', bitcoin_data.ListType(bitcoin_data.ComposedType([
171             ('type', bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'tx': 1, 'block': 2})),
172             ('hash', bitcoin_data.HashType()),
173         ]))),
174     ])
175     def handle_inv(self, invs):
176         for inv in invs:
177             if inv['type'] == 'tx':
178                 self.factory.new_tx.happened(inv['hash'])
179             elif inv['type'] == 'block':
180                 self.factory.new_block.happened(inv['hash'])
181             else:
182                 print 'Unknown inv type', item
183     
184     message_getdata = bitcoin_data.ComposedType([
185         ('requests', bitcoin_data.ListType(bitcoin_data.ComposedType([
186             ('type', bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'tx': 1, 'block': 2})),
187             ('hash', bitcoin_data.HashType()),
188         ]))),
189     ])
190     message_getblocks = bitcoin_data.ComposedType([
191         ('version', bitcoin_data.StructType('<I')),
192         ('have', bitcoin_data.ListType(bitcoin_data.HashType())),
193         ('last', bitcoin_data.PossiblyNoneType(0, bitcoin_data.HashType())),
194     ])
195     message_getheaders = bitcoin_data.ComposedType([
196         ('version', bitcoin_data.StructType('<I')),
197         ('have', bitcoin_data.ListType(bitcoin_data.HashType())),
198         ('last', bitcoin_data.PossiblyNoneType(0, bitcoin_data.HashType())),
199     ])
200     message_getaddr = bitcoin_data.ComposedType([])
201     message_checkorder = bitcoin_data.ComposedType([
202         ('id', bitcoin_data.HashType()),
203         ('order', bitcoin_data.FixedStrType(60)), # XXX
204     ])
205     message_submitorder = bitcoin_data.ComposedType([
206         ('id', bitcoin_data.HashType()),
207         ('order', bitcoin_data.FixedStrType(60)), # XXX
208     ])
209     
210     message_addr = bitcoin_data.ComposedType([
211         ('addrs', bitcoin_data.ListType(bitcoin_data.ComposedType([
212             ('timestamp', bitcoin_data.StructType('<I')),
213             ('address', bitcoin_data.address_type),
214         ]))),
215     ])
216     def handle_addr(self, addrs):
217         for addr in addrs:
218             pass
219     
220     message_tx = bitcoin_data.ComposedType([
221         ('tx', bitcoin_data.tx_type),
222     ])
223     def handle_tx(self, tx):
224         self.get_tx.got_response(bitcoin_data.tx_type.hash256(tx), tx)
225     
226     message_block = bitcoin_data.ComposedType([
227         ('block', bitcoin_data.block_type),
228     ])
229     def handle_block(self, block):
230         block_hash = bitcoin_data.block_header_type.hash256(block['header'])
231         self.get_block.got_response(block_hash, block)
232         self.get_block_header.got_response(block_hash, block['header'])
233     
234     message_headers = bitcoin_data.ComposedType([
235         ('headers', bitcoin_data.ListType(bitcoin_data.block_type)),
236     ])
237     def handle_headers(self, headers):
238         for header in headers:
239             header = header['header']
240             self.get_block_header.got_response(bitcoin_data.block_header_type.hash256(header), header)
241         self.factory.new_headers.happened([header['header'] for header in headers])
242     
243     message_reply = bitcoin_data.ComposedType([
244         ('hash', bitcoin_data.HashType()),
245         ('reply',  bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'success': 0, 'failure': 1, 'denied': 2})),
246         ('script', bitcoin_data.PossiblyNoneType('', bitcoin_data.VarStrType())),
247     ])
248     
249     message_ping = bitcoin_data.ComposedType([])
250     def handle_ping(self):
251         pass
252     
253     message_alert = bitcoin_data.ComposedType([
254         ('message', bitcoin_data.VarStrType()),
255         ('signature', bitcoin_data.VarStrType()),
256     ])
257     def handle_alert(self, message, signature):
258         print 'ALERT:', (message, signature)
259     
260     def connectionLost(self, reason):
261         if hasattr(self.factory, 'gotConnection'):
262             self.factory.gotConnection(None)
263
264 class ClientFactory(protocol.ReconnectingClientFactory):
265     protocol = Protocol
266     
267     maxDelay = 1
268     
269     def __init__(self, net):
270         self.net = net
271         self.conn = variable.Variable(None)
272         
273         self.new_block = variable.Event()
274         self.new_tx = variable.Event()
275         self.new_headers = variable.Event()
276     
277     def buildProtocol(self, addr):
278         p = self.protocol(self.net)
279         p.factory = self
280         return p
281     
282     def gotConnection(self, conn):
283         self.conn.set(conn)
284     
285     def getProtocol(self):
286         return self.conn.get_not_none()
287
288 class HeaderWrapper(object):
289     target = 2**256 - 1
290     __slots__ = 'hash previous_hash'.split(' ')
291     
292     @classmethod
293     def from_header(cls, header):
294         return cls(bitcoin_data.block_header_type.hash256(header), header['previous_block'])
295     
296     def __init__(self, hash, previous_hash):
297         self.hash, self.previous_hash = hash, previous_hash
298
299 class HeightTracker(object):
300     '''Point this at a factory and let it take care of getting block heights'''
301     
302     def __init__(self, rpc_proxy, factory, backlog_needed=1000):
303         self._rpc_proxy = rpc_proxy
304         self._factory = factory
305         self._backlog_needed = backlog_needed
306         
307         self._tracker = forest.Tracker()
308         
309         self._watch1 = self._factory.new_headers.watch(self._heard_headers)
310         self._watch2 = self._factory.new_block.watch(self._heard_block)
311         
312         self._requested = set()
313         self._clear_task = task.LoopingCall(self._requested.clear)
314         self._clear_task.start(60)
315         
316         self._last_notified_size = 0
317         
318         self.updated = variable.Event()
319         
320         self._think_task = task.LoopingCall(self._think).start(15)
321         self._think2_task = task.LoopingCall(self._think2).start(15)
322     
323     def _think(self):
324         try:
325             highest_head = max(self._tracker.heads, key=lambda h: self._tracker.get_height_and_last(h)[0]) if self._tracker.heads else None
326             if highest_head is None:
327                 return # wait for think2
328             height, last = self._tracker.get_height_and_last(highest_head)
329             if height < self._backlog_needed:
330                 self._request(last)
331         except:
332             log.err(None, 'Error in HeightTracker._think:')
333     
334     @defer.inlineCallbacks
335     def _think2(self):
336         try:
337             ba = getwork.BlockAttempt.from_getwork((yield self._rpc_proxy.rpc_getwork()))
338             self._request(ba.previous_block)
339         except:
340             log.err(None, 'Error in HeightTracker._think2:')
341     
342     def _heard_headers(self, headers):
343         changed = False
344         for header in headers:
345             hw = HeaderWrapper.from_header(header)
346             if hw.hash in self._tracker.shares:
347                 continue
348             changed = True
349             self._tracker.add(hw)
350         if changed:
351             self.updated.happened()
352         self._think()
353         
354         if len(self._tracker.shares) >= self._last_notified_size + 100:
355             print 'Have %i/%i block headers' % (len(self._tracker.shares), self._backlog_needed)
356             self._last_notified_size = len(self._tracker.shares)
357     
358     def _heard_block(self, block_hash):
359         self._request(block_hash)
360     
361     @defer.inlineCallbacks
362     def _request(self, last):
363         if last in self._tracker.shares:
364             return
365         if last in self._requested:
366             return
367         self._requested.add(last)
368         (yield self._factory.getProtocol()).send_getheaders(version=1, have=[], last=last)
369     
370     def get_height_rel_highest(self, block_hash):
371         # callers: highest height can change during yields!
372         height, last = self._tracker.get_height_and_last(block_hash)
373         if last not in self._tracker.tails:
374             return -1e300
375         return height - max(self._tracker.get_height(head_hash) for head_hash in self._tracker.tails[last])
376     
377     def stop(self):
378         self._factory.new_headers.unwatch(self._watch1)
379         self._factory.new_block.unwatch(self._watch2)
380         self._clear_task.stop()
381         self._think_task.stop()
382         self._think2_task.stop()
383
384 if __name__ == '__main__':
385     factory = ClientFactory(bitcoin_data.BitcoinMainnet)
386     reactor.connectTCP('127.0.0.1', 8333, factory)
387     h = HeightTracker(factory)
388     
389     @repr
390     @apply
391     @defer.inlineCallbacks
392     def think():
393         while True:
394             yield deferral.sleep(1)
395             print h.get_min_height(0xa285c3cb2a90ac7194cca034512748289e2526d9d7ae6ee7523)
396     
397     reactor.run()