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