good chain choosing scheme
[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 traceback
12 import zlib
13
14 from twisted.internet import defer, protocol, reactor
15
16 from . import data as bitcoin_data
17 from p2pool.util import variable, datachunker, deferral
18
19 class BaseProtocol(protocol.Protocol):
20     def connectionMade(self):
21         self.dataReceived = datachunker.DataChunker(self.dataReceiver())
22     
23     def dataReceiver(self):
24         while True:
25             start = ''
26             while start != self._prefix:
27                 start = (start + (yield 1))[-len(self._prefix):]
28             
29             command = (yield 12).rstrip('\0')
30             length, = struct.unpack('<I', (yield 4))
31             
32             if self.use_checksum:
33                 checksum = yield 4
34             else:
35                 checksum = None
36             
37             payload = yield length
38             
39             if self.compress:
40                 try:
41                     payload = zlib.decompress(payload)
42                 except:
43                     print 'FAILURE DECOMPRESSING'
44                     continue
45             
46             if checksum is not None:
47                 if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] != checksum:
48                     print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
49                     print 'INVALID HASH'
50                     continue
51             
52             type_ = getattr(self, "message_" + command, None)
53             if type_ is None:
54                 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
55                 print 'NO TYPE FOR', repr(command)
56                 continue
57             
58             try:
59                 payload2 = type_.unpack(payload)
60             except:
61                 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
62                 traceback.print_exc()
63                 continue
64             
65             handler = getattr(self, 'handle_' + command, None)
66             if handler is None:
67                 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
68                 print 'NO HANDLER FOR', command
69                 continue
70             
71             #print 'RECV', command, repr(payload2)[:500]
72             
73             try:
74                 handler(**payload2)
75             except:
76                 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
77                 traceback.print_exc()
78                 continue
79     
80     def sendPacket(self, command, payload2):
81         if len(command) >= 12:
82             raise ValueError('command too long')
83         type_ = getattr(self, "message_" + command, None)
84         if type_ is None:
85             raise ValueError('invalid command')
86         #print 'SEND', command, repr(payload2)[:500]
87         payload = type_.pack(payload2)
88         if self.use_checksum:
89             checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
90         else:
91             checksum = ''
92         if self.compress:
93             payload = zlib.compress(payload)
94         data = self._prefix + struct.pack('<12sI', command, len(payload)) + checksum + payload
95         self.transport.write(data)
96     
97     def __getattr__(self, attr):
98         prefix = 'send_'
99         if attr.startswith(prefix):
100             command = attr[len(prefix):]
101             return lambda **payload2: self.sendPacket(command, payload2)
102         #return protocol.Protocol.__getattr__(self, attr)
103         raise AttributeError(attr)
104
105 class Protocol(BaseProtocol):
106     def __init__(self, net):
107         self._prefix = net.BITCOIN_P2P_PREFIX
108     
109     version = 0
110     
111     compress = False
112     @property
113     def use_checksum(self):
114         return self.version >= 209
115     
116     
117     null_order = '\0'*60
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.check_order = deferral.GenericDeferrer(2**256, lambda id, order: self.send_checkorder(id=id, order=order))
164         self.submit_order = deferral.GenericDeferrer(2**256, lambda id, order: self.send_submitorder(id=id, order=order))
165         self.get_block = deferral.ReplyMatcher(lambda hash: self.send_getdata(requests=[dict(type='block', hash=hash)]))
166         self.get_block_header = deferral.ReplyMatcher(lambda hash: self.send_getheaders(version=1, have=[], last=hash))
167         self.get_tx = deferral.ReplyMatcher(lambda hash: self.send_getdata(requests=[dict(type='tx', hash=hash)]))
168         
169         if hasattr(self.factory, 'resetDelay'):
170             self.factory.resetDelay()
171         if hasattr(self.factory, 'gotConnection'):
172             self.factory.gotConnection(self)
173     
174     message_inv = bitcoin_data.ComposedType([
175         ('invs', bitcoin_data.ListType(bitcoin_data.ComposedType([
176             ('type', bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'tx': 1, 'block': 2})),
177             ('hash', bitcoin_data.HashType()),
178         ]))),
179     ])
180     def handle_inv(self, invs):
181         for inv in invs:
182             if inv['type'] == 'tx':
183                 self.factory.new_tx.happened(inv['hash'])
184             elif inv['type'] == 'block':
185                 self.factory.new_block.happened(inv['hash'])
186             else:
187                 print "Unknown inv type", item
188     
189     message_getdata = bitcoin_data.ComposedType([
190         ('requests', bitcoin_data.ListType(bitcoin_data.ComposedType([
191             ('type', bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'tx': 1, 'block': 2})),
192             ('hash', bitcoin_data.HashType()),
193         ]))),
194     ])
195     message_getblocks = bitcoin_data.ComposedType([
196         ('version', bitcoin_data.StructType('<I')),
197         ('have', bitcoin_data.ListType(bitcoin_data.HashType())),
198         ('last', bitcoin_data.PossiblyNone(0, bitcoin_data.HashType())),
199     ])
200     message_getheaders = bitcoin_data.ComposedType([
201         ('version', bitcoin_data.StructType('<I')),
202         ('have', bitcoin_data.ListType(bitcoin_data.HashType())),
203         ('last', bitcoin_data.PossiblyNone(0, bitcoin_data.HashType())),
204     ])
205     message_getaddr = bitcoin_data.ComposedType([])
206     message_checkorder = bitcoin_data.ComposedType([
207         ('id', bitcoin_data.HashType()),
208         ('order', bitcoin_data.FixedStrType(60)), # XXX
209     ])
210     message_submitorder = bitcoin_data.ComposedType([
211         ('id', bitcoin_data.HashType()),
212         ('order', bitcoin_data.FixedStrType(60)), # XXX
213     ])
214     
215     message_addr = bitcoin_data.ComposedType([
216         ('addrs', bitcoin_data.ListType(bitcoin_data.ComposedType([
217             ('timestamp', bitcoin_data.StructType('<I')),
218             ('address', bitcoin_data.address_type),
219         ]))),
220     ])
221     def handle_addr(self, addrs):
222         for addr in addrs:
223             pass
224     
225     message_tx = bitcoin_data.ComposedType([
226         ('tx', bitcoin_data.tx_type),
227     ])
228     def handle_tx(self, tx):
229         self.get_tx.got_response(bitcoin_data.tx_type.hash256(tx), tx)
230     
231     message_block = bitcoin_data.ComposedType([
232         ('block', bitcoin_data.block_type),
233     ])
234     def handle_block(self, block):
235         block_hash = bitcoin_data.block_header_type.hash256(block['header'])
236         self.get_block.got_response(block_hash, block)
237         self.get_block_header.got_response(block_hash, block['header'])
238     
239     message_headers = bitcoin_data.ComposedType([
240         ('headers', bitcoin_data.ListType(bitcoin_data.block_type)),
241     ])
242     def handle_headers(self, headers):
243         for header in headers:
244             header = header['header']
245             self.get_block_header.got_response(bitcoin_data.block_header_type.hash256(header), header)
246         self.factory.new_headers.happened([header['header'] for header in headers])
247     
248     message_reply = bitcoin_data.ComposedType([
249         ('hash', bitcoin_data.HashType()),
250         ('reply',  bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'success': 0, 'failure': 1, 'denied': 2})),
251         ('script', bitcoin_data.PossiblyNone("", bitcoin_data.VarStrType())),
252     ])
253     def handle_reply(self, hash, reply, script):
254         self.check_order.got_response(hash, dict(reply=reply, script=script))
255         self.submit_order.got_response(hash, dict(reply=reply, script=script))
256     
257     message_ping = bitcoin_data.ComposedType([])
258     def handle_ping(self):
259         pass
260     
261     message_alert = bitcoin_data.ComposedType([
262         ('message', bitcoin_data.VarStrType()),
263         ('signature', bitcoin_data.VarStrType()),
264     ])
265     def handle_alert(self, message, signature):
266         print "ALERT:", (message, signature)
267     
268     def connectionLost(self, reason):
269         if hasattr(self.factory, 'gotConnection'):
270             self.factory.gotConnection(None)
271
272 class ClientFactory(protocol.ReconnectingClientFactory):
273     protocol = Protocol
274     
275     maxDelay = 15
276     
277     def __init__(self, net):
278         self.net = net
279         self.conn = variable.Variable(None)
280         
281         self.new_block = variable.Event()
282         self.new_tx = variable.Event()
283         self.new_headers = variable.Event()
284     
285     def buildProtocol(self, addr):
286         p = self.protocol(self.net)
287         p.factory = self
288         return p
289     
290     def gotConnection(self, conn):
291         self.conn.set(conn)
292     
293     def getProtocol(self):
294         return self.conn.get_not_none()
295
296 class HeaderWrapper(object):
297     def __init__(self, header):
298         self.hash = bitcoin_data.block_header_type.hash256(header)
299         self.previous_hash = header['previous_block']
300
301 class HeightTracker(object):
302     '''Point this at a factory and let it take care of getting block heights'''
303     # XXX think keeps object alive
304     
305     def __init__(self, factory):
306         self.factory = factory
307         self.tracker = bitcoin_data.Tracker()
308         self.most_recent = None
309         
310         self.factory.new_headers.watch(self.heard_headers)
311         
312         self.think()
313     
314     @defer.inlineCallbacks
315     def think(self):
316         last = None
317         yield self.factory.getProtocol()
318         while True:
319             highest_head = max(self.tracker.heads, key=lambda h: self.tracker.get_height_and_last(h)[0]) if self.tracker.heads else None
320             it = self.tracker.get_chain_known(highest_head)
321             have = []
322             step = 1
323             try:
324                 cur = it.next()
325             except StopIteration:
326                 cur = None
327             while True:
328                 if cur is None:
329                     break
330                 have.append(cur.hash)
331                 for i in xrange(step): # XXX inefficient
332                     try:
333                         cur = it.next()
334                     except StopIteration:
335                         break
336                 else:
337                     if len(have) > 10:
338                         step *= 2
339                     continue
340                 break
341             chain = list(self.tracker.get_chain_known(highest_head))
342             if chain:
343                 have.append(chain[-1].hash)
344             if not have:
345                 have.append(0)
346             if have == last:
347                 yield deferral.sleep(1)
348                 last = None
349                 continue
350             
351             last = have
352             good_tails = [x for x in self.tracker.tails if x is not None]
353             self.request(have, random.choice(good_tails) if good_tails else None)
354             for tail in self.tracker.tails:
355                 if tail is None:
356                     continue
357                 self.request([], tail)
358             try:
359                 yield self.factory.new_headers.get_deferred(timeout=5)
360             except defer.TimeoutError:
361                 pass
362     
363     def heard_headers(self, headers):
364         header2s = map(HeaderWrapper, headers)
365         for header2 in header2s:
366             self.tracker.add(header2)
367         if header2s:
368             if self.tracker.get_height_and_last(header2s[-1].hash)[1] is None:
369                 self.most_recent = header2s[-1].hash
370                 if random.random() < .6:
371                     self.request([header2s[-1].hash], None)
372         print len(self.tracker.shares)
373     
374     def request(self, have, last):
375         #print "REQ", ('[' + ', '.join(map(hex, have)) + ']', hex(last) if last is not None else None)
376         if self.factory.conn.value is not None:
377             self.factory.conn.value.send_getheaders(version=1, have=have, last=last)
378     
379     #@defer.inlineCallbacks
380     #XXX should defer
381     def getHeight(self, block_hash):
382         height, last = self.tracker.get_height_and_last(block_hash)
383         if last is not None:
384             self.request([], last)
385             raise ValueError()
386         return height
387     
388     def get_min_height(self, block_hash):
389         height, last = self.tracker.get_height_and_last(block_hash)
390         if last is not None:
391             self.request([], last)
392         return height
393     
394     def get_highest_height(self):
395         return self.tracker.get_highest_height()
396
397 if __name__ == '__main__':
398     factory = ClientFactory(bitcoin_data.Mainnet)
399     reactor.connectTCP('127.0.0.1', 8333, factory)
400     h = HeightTracker(factory)
401     
402     @repr
403     @apply
404     @defer.inlineCallbacks
405     def think():
406         while True:
407             yield deferral.sleep(1)
408             try:
409                 print h.getHeight(0xa285c3cb2a90ac7194cca034512748289e2526d9d7ae6ee7523)
410             except Exception, e:
411                 traceback.print_exc()
412     
413     reactor.run()