2 Implementation of Bitcoin's p2p protocol
5 from __future__ import division
12 from twisted.internet import defer, protocol, reactor, task
13 from twisted.python import log
15 from . import data as bitcoin_data
16 from p2pool.util import variable, datachunker, deferral
18 class TooLong(Exception):
21 class BaseProtocol(protocol.Protocol):
22 def connectionMade(self):
23 self.dataReceived = datachunker.DataChunker(self.dataReceiver())
25 def dataReceiver(self):
28 while start != self._prefix:
29 start = (start + (yield 1))[-len(self._prefix):]
31 command = (yield 12).rstrip('\0')
32 length, = struct.unpack('<I', (yield 4))
34 if length > self.max_payload_length:
35 print 'length too large'
43 payload = yield length
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)
50 type_ = getattr(self, 'message_' + command, None)
52 print 'no type for', repr(command)
56 payload2 = type_.unpack(payload)
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)')
62 handler = getattr(self, 'handle_' + command, None)
64 print 'no handler for', repr(command)
70 print 'RECV', command, repr(payload2)[:100]
71 log.err(None, 'Error handling message: (see RECV line)')
79 def sendPacket(self, command, payload2):
80 if len(command) >= 12:
81 raise ValueError('command too long')
82 type_ = getattr(self, 'message_' + command, 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')
90 checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
93 data = self._prefix + struct.pack('<12sI', command, len(payload)) + checksum + payload
94 self.transport.write(data)
96 def __getattr__(self, attr):
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)
104 class Protocol(BaseProtocol):
105 def __init__(self, net):
106 self._prefix = net.BITCOIN_P2P_PREFIX
110 max_payload_length = 1000000
113 def use_checksum(self):
114 return self.version >= 209
119 def connectionMade(self):
120 BaseProtocol.connectionMade(self)
125 time=int(time.time()),
128 address=self.transport.getPeer().host,
129 port=self.transport.getPeer().port,
133 address=self.transport.getHost().host,
134 port=self.transport.getHost().port,
136 nonce=random.randrange(2**64),
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')),
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
156 message_verack = bitcoin_data.ComposedType([])
157 def handle_verack(self):
158 self.version = self.version_after
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)]))
169 if hasattr(self.factory, 'resetDelay'):
170 self.factory.resetDelay()
171 if hasattr(self.factory, 'gotConnection'):
172 self.factory.gotConnection(self)
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()),
180 def handle_inv(self, 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'])
187 print 'Unknown inv type', item
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()),
195 message_getblocks = 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())),
200 message_getheaders = bitcoin_data.ComposedType([
201 ('version', bitcoin_data.StructType('<I')),
202 ('have', bitcoin_data.ListType(bitcoin_data.HashType())),
203 ('last', bitcoin_data.PossiblyNoneType(0, bitcoin_data.HashType())),
205 message_getaddr = bitcoin_data.ComposedType([])
206 message_checkorder = bitcoin_data.ComposedType([
207 ('id', bitcoin_data.HashType()),
208 ('order', bitcoin_data.FixedStrType(60)), # XXX
210 message_submitorder = bitcoin_data.ComposedType([
211 ('id', bitcoin_data.HashType()),
212 ('order', bitcoin_data.FixedStrType(60)), # XXX
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),
221 def handle_addr(self, addrs):
225 message_tx = bitcoin_data.ComposedType([
226 ('tx', bitcoin_data.tx_type),
228 def handle_tx(self, tx):
229 self.get_tx.got_response(bitcoin_data.tx_type.hash256(tx), tx)
231 message_block = bitcoin_data.ComposedType([
232 ('block', bitcoin_data.block_type),
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'])
239 message_headers = bitcoin_data.ComposedType([
240 ('headers', bitcoin_data.ListType(bitcoin_data.block_type)),
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])
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.PossiblyNoneType('', bitcoin_data.VarStrType())),
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))
257 message_ping = bitcoin_data.ComposedType([])
258 def handle_ping(self):
261 message_alert = bitcoin_data.ComposedType([
262 ('message', bitcoin_data.VarStrType()),
263 ('signature', bitcoin_data.VarStrType()),
265 def handle_alert(self, message, signature):
266 print 'ALERT:', (message, signature)
268 def connectionLost(self, reason):
269 if hasattr(self.factory, 'gotConnection'):
270 self.factory.gotConnection(None)
272 class ClientFactory(protocol.ReconnectingClientFactory):
277 def __init__(self, net):
279 self.conn = variable.Variable(None)
281 self.new_block = variable.Event()
282 self.new_tx = variable.Event()
283 self.new_headers = variable.Event()
285 def buildProtocol(self, addr):
286 p = self.protocol(self.net)
290 def gotConnection(self, conn):
293 def getProtocol(self):
294 return self.conn.get_not_none()
296 class HeaderWrapper(object):
298 __slots__ = 'hash previous_hash'.split(' ')
301 def from_header(cls, header):
302 return cls(bitcoin_data.block_header_type.hash256(header), header['previous_block'])
304 def __init__(self, hash, previous_hash):
305 self.hash, self.previous_hash = hash, previous_hash
307 class HeightTracker(object):
308 '''Point this at a factory and let it take care of getting block heights'''
310 def __init__(self, factory, backing):
311 self.factory = factory
312 self.tracker = bitcoin_data.Tracker()
313 self.backing = backing
314 self.most_recent = None
316 self._watch1 = self.factory.new_headers.watch(self.heard_headers)
317 self._watch2 = self.factory.new_block.watch(self.heard_block)
319 self.requested = set()
320 self._clear_task = task.LoopingCall(self.requested.clear)
321 self._clear_task.start(60)
323 self.last_notified_size = 0
325 self.updated = variable.Event()
331 def _load_backing(self):
332 open(self.backing, 'ab').close()
333 with open(self.backing, 'rb') as f:
337 hash, previous_hash, checksum = (int(x, 16) for x in line.strip().split(' '))
339 print "skipping over bad data in headers.dat"
341 if (hash - previous_hash) % 2**256 != checksum:
342 print "checksum failed"
344 if previous_hash == 0: previous_hash = None
346 if count % 10000 == 0 and count: print count
347 if hash not in self.tracker.shares:
348 self.tracker.add(HeaderWrapper(hash, previous_hash))
351 highest_head = max(self.tracker.heads, key=lambda h: self.tracker.get_height_and_last(h)[0]) if self.tracker.heads else None
352 height, last = self.tracker.get_height_and_last(highest_head)
357 while cur is not None:
359 if step > cur_height:
361 cur = self.tracker.get_nth_parent_hash(cur, step)
366 have.append(self.tracker.get_nth_parent_hash(highest_head, height - 1))
369 self.request(have, None)
371 for tail in self.tracker.tails:
374 self.request([], tail)
375 for head in self.tracker.heads:
376 if head == highest_head:
378 self.request([head], None)
380 def heard_headers(self, headers):
382 b = open(self.backing, 'ab')
383 for header in headers:
384 hw = HeaderWrapper.from_header(header)
385 if hw.hash in self.tracker.shares:
389 hash, prev = hw.hash, 0 if hw.previous_hash is None else hw.previous_hash
390 b.write('%x %x %x\n' % (hash, prev, (hash - prev) % 2**256))
393 self.updated.happened()
396 if len(self.tracker.shares) > self.last_notified_size + 10:
397 print 'Have %i block headers' % len(self.tracker.shares)
398 self.last_notified_size = len(self.tracker.shares)
400 def heard_block(self, block_hash):
401 self.request([], block_hash)
403 @defer.inlineCallbacks
404 def request(self, have, last):
405 if (tuple(have), last) in self.requested:
407 self.requested.add((tuple(have), last))
408 (yield self.factory.getProtocol()).send_getheaders(version=1, have=have, last=last)
410 def getHeight(self, block_hash):
411 height, last = self.tracker.get_height_and_last(block_hash)
413 #self.request([], last)
417 def get_min_height(self, block_hash):
418 height, last = self.tracker.get_height_and_last(block_hash)
419 #if last is not None:
420 # self.request([], last)
423 def get_highest_height(self):
424 return self.tracker.get_highest_height()
427 self.factory.new_headers.unwatch(self._watch1)
428 self.factory.new_block.unwatch(self._watch2)
429 self._clear_task.stop()
431 if __name__ == '__main__':
432 factory = ClientFactory(bitcoin_data.Mainnet)
433 reactor.connectTCP('127.0.0.1', 8333, factory)
434 h = HeightTracker(factory)
438 @defer.inlineCallbacks
441 yield deferral.sleep(1)
442 print h.get_min_height(0xa285c3cb2a90ac7194cca034512748289e2526d9d7ae6ee7523)