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)')
74 def sendPacket(self, command, payload2):
75 if len(command) >= 12:
76 raise ValueError('command too long')
77 type_ = getattr(self, 'message_' + command, None)
79 raise ValueError('invalid command')
80 #print 'SEND', command, repr(payload2)[:500]
81 payload = type_.pack(payload2)
82 if len(payload) > self.max_payload_length:
83 raise TooLong('payload too long')
85 checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
88 data = self._prefix + struct.pack('<12sI', command, len(payload)) + checksum + payload
89 self.transport.write(data)
91 def __getattr__(self, attr):
93 if attr.startswith(prefix):
94 command = attr[len(prefix):]
95 return lambda **payload2: self.sendPacket(command, payload2)
96 #return protocol.Protocol.__getattr__(self, attr)
97 raise AttributeError(attr)
99 class Protocol(BaseProtocol):
100 def __init__(self, net):
101 self._prefix = net.BITCOIN_P2P_PREFIX
105 max_payload_length = 1000000
108 def use_checksum(self):
109 return self.version >= 209
114 def connectionMade(self):
115 BaseProtocol.connectionMade(self)
120 time=int(time.time()),
123 address=self.transport.getPeer().host,
124 port=self.transport.getPeer().port,
128 address=self.transport.getHost().host,
129 port=self.transport.getHost().port,
131 nonce=random.randrange(2**64),
136 message_version = bitcoin_data.ComposedType([
137 ('version', bitcoin_data.StructType('<I')),
138 ('services', bitcoin_data.StructType('<Q')),
139 ('time', bitcoin_data.StructType('<Q')),
140 ('addr_to', bitcoin_data.address_type),
141 ('addr_from', bitcoin_data.address_type),
142 ('nonce', bitcoin_data.StructType('<Q')),
143 ('sub_version_num', bitcoin_data.VarStrType()),
144 ('start_height', bitcoin_data.StructType('<I')),
146 def handle_version(self, version, services, time, addr_to, addr_from, nonce, sub_version_num, start_height):
147 #print 'VERSION', locals()
148 self.version_after = version
151 message_verack = bitcoin_data.ComposedType([])
152 def handle_verack(self):
153 self.version = self.version_after
158 self.check_order = deferral.GenericDeferrer(2**256, lambda id, order: self.send_checkorder(id=id, order=order))
159 self.submit_order = deferral.GenericDeferrer(2**256, lambda id, order: self.send_submitorder(id=id, order=order))
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)]))
164 if hasattr(self.factory, 'resetDelay'):
165 self.factory.resetDelay()
166 if hasattr(self.factory, 'gotConnection'):
167 self.factory.gotConnection(self)
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()),
175 def handle_inv(self, 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'])
182 print 'Unknown inv type', item
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()),
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())),
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())),
200 message_getaddr = bitcoin_data.ComposedType([])
201 message_checkorder = bitcoin_data.ComposedType([
202 ('id', bitcoin_data.HashType()),
203 ('order', bitcoin_data.FixedStrType(60)), # XXX
205 message_submitorder = bitcoin_data.ComposedType([
206 ('id', bitcoin_data.HashType()),
207 ('order', bitcoin_data.FixedStrType(60)), # XXX
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),
216 def handle_addr(self, addrs):
220 message_tx = bitcoin_data.ComposedType([
221 ('tx', bitcoin_data.tx_type),
223 def handle_tx(self, tx):
224 self.get_tx.got_response(bitcoin_data.tx_type.hash256(tx), tx)
226 message_block = bitcoin_data.ComposedType([
227 ('block', bitcoin_data.block_type),
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'])
234 message_headers = bitcoin_data.ComposedType([
235 ('headers', bitcoin_data.ListType(bitcoin_data.block_type)),
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])
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())),
248 def handle_reply(self, hash, reply, script):
249 self.check_order.got_response(hash, dict(reply=reply, script=script))
250 self.submit_order.got_response(hash, dict(reply=reply, script=script))
252 message_ping = bitcoin_data.ComposedType([])
253 def handle_ping(self):
256 message_alert = bitcoin_data.ComposedType([
257 ('message', bitcoin_data.VarStrType()),
258 ('signature', bitcoin_data.VarStrType()),
260 def handle_alert(self, message, signature):
261 print 'ALERT:', (message, signature)
263 def connectionLost(self, reason):
264 if hasattr(self.factory, 'gotConnection'):
265 self.factory.gotConnection(None)
267 class ClientFactory(protocol.ReconnectingClientFactory):
272 def __init__(self, net):
274 self.conn = variable.Variable(None)
276 self.new_block = variable.Event()
277 self.new_tx = variable.Event()
278 self.new_headers = variable.Event()
280 def buildProtocol(self, addr):
281 p = self.protocol(self.net)
285 def gotConnection(self, conn):
288 def getProtocol(self):
289 return self.conn.get_not_none()
291 class HeaderWrapper(object):
293 __slots__ = 'hash previous_hash'.split(' ')
296 def from_header(cls, header):
297 return cls(bitcoin_data.block_header_type.hash256(header), header['previous_block'])
299 def __init__(self, hash, previous_hash):
300 self.hash, self.previous_hash = hash, previous_hash
302 class HeightTracker(object):
303 '''Point this at a factory and let it take care of getting block heights'''
305 def __init__(self, factory, backing):
306 self.factory = factory
307 self.tracker = bitcoin_data.Tracker()
308 self.backing = backing
309 self.most_recent = None
311 self._watch1 = self.factory.new_headers.watch(self.heard_headers)
312 self._watch2 = self.factory.new_block.watch(self.heard_block)
314 self.requested = set()
315 self._clear_task = task.LoopingCall(self.requested.clear)
316 self._clear_task.start(60)
318 self.last_notified_size = 0
320 self.updated = variable.Event()
326 def _load_backing(self):
327 open(self.backing, 'ab').close()
328 with open(self.backing, 'rb') as f:
332 hash, previous_hash, checksum = (int(x, 16) for x in line.strip().split(' '))
334 print "skipping over bad data in headers.dat"
336 if (hash - previous_hash) % 2**256 != checksum:
337 print "checksum failed"
339 if previous_hash == 0: previous_hash = None
341 if count % 10000 == 0 and count: print count
342 if hash not in self.tracker.shares:
343 self.tracker.add(HeaderWrapper(hash, previous_hash))
346 highest_head = max(self.tracker.heads, key=lambda h: self.tracker.get_height_and_last(h)[0]) if self.tracker.heads else None
347 height, last = self.tracker.get_height_and_last(highest_head)
352 while cur is not None:
354 if step > cur_height:
356 cur = self.tracker.get_nth_parent_hash(cur, step)
361 have.append(self.tracker.get_nth_parent_hash(highest_head, height - 1))
364 self.request(have, None)
366 for tail in self.tracker.tails:
369 self.request([], tail)
370 for head in self.tracker.heads:
371 if head == highest_head:
373 self.request([head], None)
375 def heard_headers(self, headers):
377 b = open(self.backing, 'ab')
378 for header in headers:
379 hw = HeaderWrapper.from_header(header)
380 if hw.hash in self.tracker.shares:
384 hash, prev = hw.hash, 0 if hw.previous_hash is None else hw.previous_hash
385 b.write('%x %x %x\n' % (hash, prev, (hash - prev) % 2**256))
388 self.updated.happened()
391 if len(self.tracker.shares) > self.last_notified_size + 10:
392 print 'Have %i block headers' % len(self.tracker.shares)
393 self.last_notified_size = len(self.tracker.shares)
395 def heard_block(self, block_hash):
396 self.request([], block_hash)
398 @defer.inlineCallbacks
399 def request(self, have, last):
400 if (tuple(have), last) in self.requested:
402 self.requested.add((tuple(have), last))
403 (yield self.factory.getProtocol()).send_getheaders(version=1, have=have, last=last)
405 def getHeight(self, block_hash):
406 height, last = self.tracker.get_height_and_last(block_hash)
408 #self.request([], last)
412 def get_min_height(self, block_hash):
413 height, last = self.tracker.get_height_and_last(block_hash)
414 #if last is not None:
415 # self.request([], last)
418 def get_highest_height(self):
419 return self.tracker.get_highest_height()
422 self.factory.new_headers.unwatch(self._watch1)
423 self.factory.new_block.unwatch(self._watch2)
424 self._clear_task.stop()
426 if __name__ == '__main__':
427 factory = ClientFactory(bitcoin_data.Mainnet)
428 reactor.connectTCP('127.0.0.1', 8333, factory)
429 h = HeightTracker(factory)
433 @defer.inlineCallbacks
436 yield deferral.sleep(1)
437 print h.get_min_height(0xa285c3cb2a90ac7194cca034512748289e2526d9d7ae6ee7523)