removed HeightTracker's backing
[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
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, factory):
303         self.factory = factory
304         self.tracker = forest.Tracker()
305         self.most_recent = None
306         
307         self._watch1 = self.factory.new_headers.watch(self.heard_headers)
308         self._watch2 = self.factory.new_block.watch(self.heard_block)
309         
310         self.requested = set()
311         self._clear_task = task.LoopingCall(self.requested.clear)
312         self._clear_task.start(60)
313         
314         self.last_notified_size = 0
315         
316         self.updated = variable.Event()
317         
318         self.think()
319     
320     def think(self):
321         highest_head = max(self.tracker.heads, key=lambda h: self.tracker.get_height_and_last(h)[0]) if self.tracker.heads else None
322         height, last = self.tracker.get_height_and_last(highest_head)
323         cur = highest_head
324         cur_height = height
325         have = []
326         step = 1
327         while cur is not None:
328             have.append(cur)
329             if step > cur_height:
330                 break
331             cur = self.tracker.get_nth_parent_hash(cur, step)
332             cur_height -= step
333             if len(have) > 10:
334                 step *= 2
335         if height:
336             have.append(self.tracker.get_nth_parent_hash(highest_head, height - 1))
337         if not have:
338             have.append(0)
339         self.request(have, None)
340         
341         for tail in self.tracker.tails:
342             if tail is None:
343                 continue
344             self.request([], tail)
345         for head in self.tracker.heads:
346             if head == highest_head:
347                 continue
348             self.request([head], None)
349     
350     def heard_headers(self, headers):
351         changed = False
352         for header in headers:
353             hw = HeaderWrapper.from_header(header)
354             if hw.hash in self.tracker.shares:
355                 continue
356             changed = True
357             self.tracker.add(hw)
358         if changed:
359             self.updated.happened()
360         self.think()
361         
362         if len(self.tracker.shares) > self.last_notified_size + 10:
363             print 'Have %i block headers' % len(self.tracker.shares)
364             self.last_notified_size = len(self.tracker.shares)
365     
366     def heard_block(self, block_hash):
367         self.request([], block_hash)
368     
369     @defer.inlineCallbacks
370     def request(self, have, last):
371         if (tuple(have), last) in self.requested:
372             return
373         self.requested.add((tuple(have), last))
374         (yield self.factory.getProtocol()).send_getheaders(version=1, have=have, last=last)
375     
376     def getHeight(self, block_hash):
377         height, last = self.tracker.get_height_and_last(block_hash)
378         if last is not None:
379             #self.request([], last)
380             raise ValueError()
381         return height
382     
383     def get_min_height(self, block_hash):
384         height, last = self.tracker.get_height_and_last(block_hash)
385         #if last is not None:
386         #    self.request([], last)
387         return height
388     
389     def get_dist_below_highest(self, block_hash):
390         pass
391         # 0, 1, 2, 3, 4
392     
393     def get_highest_height(self):
394         return self.tracker.get_highest_height()
395     
396     def stop(self):
397         self.factory.new_headers.unwatch(self._watch1)
398         self.factory.new_block.unwatch(self._watch2)
399         self._clear_task.stop()
400
401 if __name__ == '__main__':
402     factory = ClientFactory(bitcoin_data.BitcoinMainnet)
403     reactor.connectTCP('127.0.0.1', 8333, factory)
404     h = HeightTracker(factory)
405     
406     @repr
407     @apply
408     @defer.inlineCallbacks
409     def think():
410         while True:
411             yield deferral.sleep(1)
412             print h.get_min_height(0xa285c3cb2a90ac7194cca034512748289e2526d9d7ae6ee7523)
413     
414     reactor.run()