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
16 from . import data as bitcoin_data, getwork
17 from p2pool.util import variable, datachunker, deferral, forest
19 class TooLong(Exception):
22 class BaseProtocol(protocol.Protocol):
23 def connectionMade(self):
24 self.dataReceived = datachunker.DataChunker(self.dataReceiver())
26 def dataReceiver(self):
29 while start != self._prefix:
30 start = (start + (yield 1))[-len(self._prefix):]
32 command = (yield 12).rstrip('\0')
33 length, = struct.unpack('<I', (yield 4))
35 if length > self.max_payload_length:
36 print 'length too large'
44 payload = yield length
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)
51 type_ = getattr(self, 'message_' + command, None)
54 print 'no type for', repr(command)
58 payload2 = type_.unpack(payload)
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)')
64 handler = getattr(self, 'handle_' + command, None)
67 print 'no handler for', repr(command)
73 print 'RECV', command, repr(payload2)[:100]
74 log.err(None, 'Error handling message: (see RECV line)')
82 def sendPacket(self, command, payload2):
83 if len(command) >= 12:
84 raise ValueError('command too long')
85 type_ = getattr(self, 'message_' + command, 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')
93 checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
96 data = self._prefix + struct.pack('<12sI', command, len(payload)) + checksum + payload
97 self.transport.write(data)
99 def __getattr__(self, attr):
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)
107 class Protocol(BaseProtocol):
108 def __init__(self, net):
109 self._prefix = net.P2P_PREFIX
113 max_payload_length = 1000000
116 def use_checksum(self):
117 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.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)]))
167 if hasattr(self.factory, 'resetDelay'):
168 self.factory.resetDelay()
169 if hasattr(self.factory, 'gotConnection'):
170 self.factory.gotConnection(self)
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()),
178 def handle_inv(self, 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'])
185 print 'Unknown inv type', item
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()),
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())),
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())),
203 message_getaddr = bitcoin_data.ComposedType([])
205 message_addr = bitcoin_data.ComposedType([
206 ('addrs', bitcoin_data.ListType(bitcoin_data.ComposedType([
207 ('timestamp', bitcoin_data.StructType('<I')),
208 ('address', bitcoin_data.address_type),
211 def handle_addr(self, addrs):
215 message_tx = bitcoin_data.ComposedType([
216 ('tx', bitcoin_data.tx_type),
218 def handle_tx(self, tx):
219 self.get_tx.got_response(bitcoin_data.tx_type.hash256(tx), tx)
221 message_block = bitcoin_data.ComposedType([
222 ('block', bitcoin_data.block_type),
224 def handle_block(self, block):
225 block_hash = bitcoin_data.block_header_type.hash256(block['header'])
226 self.get_block.got_response(block_hash, block)
227 self.get_block_header.got_response(block_hash, block['header'])
229 message_headers = bitcoin_data.ComposedType([
230 ('headers', bitcoin_data.ListType(bitcoin_data.block_type)),
232 def handle_headers(self, headers):
233 for header in headers:
234 header = header['header']
235 self.get_block_header.got_response(bitcoin_data.block_header_type.hash256(header), header)
236 self.factory.new_headers.happened([header['header'] for header in headers])
238 message_reply = bitcoin_data.ComposedType([
239 ('hash', bitcoin_data.HashType()),
240 ('reply', bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'success': 0, 'failure': 1, 'denied': 2})),
241 ('script', bitcoin_data.PossiblyNoneType('', bitcoin_data.VarStrType())),
244 message_ping = bitcoin_data.ComposedType([])
245 def handle_ping(self):
248 message_alert = bitcoin_data.ComposedType([
249 ('message', bitcoin_data.VarStrType()),
250 ('signature', bitcoin_data.VarStrType()),
252 def handle_alert(self, message, signature):
253 print 'ALERT:', (message, signature)
255 def connectionLost(self, reason):
256 if hasattr(self.factory, 'gotConnection'):
257 self.factory.gotConnection(None)
259 class ClientFactory(protocol.ReconnectingClientFactory):
264 def __init__(self, net):
266 self.conn = variable.Variable(None)
268 self.new_block = variable.Event()
269 self.new_tx = variable.Event()
270 self.new_headers = variable.Event()
272 def buildProtocol(self, addr):
273 p = self.protocol(self.net)
277 def gotConnection(self, conn):
280 def getProtocol(self):
281 return self.conn.get_not_none()
283 class HeaderWrapper(object):
285 __slots__ = 'hash previous_hash'.split(' ')
288 def from_header(cls, header):
289 return cls(bitcoin_data.block_header_type.hash256(header), header['previous_block'])
291 def __init__(self, hash, previous_hash):
292 self.hash, self.previous_hash = hash, previous_hash
294 class HeightTracker(object):
295 '''Point this at a factory and let it take care of getting block heights'''
297 def __init__(self, rpc_proxy, factory, backlog_needed=1000):
298 self._rpc_proxy = rpc_proxy
299 self._factory = factory
300 self._backlog_needed = backlog_needed
302 self._tracker = forest.Tracker()
304 self._watch1 = self._factory.new_headers.watch(self._heard_headers)
305 self._watch2 = self._factory.new_block.watch(self._heard_block)
307 self._requested = set()
308 self._clear_task = task.LoopingCall(self._requested.clear)
309 self._clear_task.start(60)
311 self._last_notified_size = 0
313 self.updated = variable.Event()
315 self._think_task = task.LoopingCall(self._think)
316 self._think_task.start(15)
317 self._think2_task = task.LoopingCall(self._think2)
318 self._think2_task.start(15)
322 highest_head = max(self._tracker.heads, key=lambda h: self._tracker.get_height_and_last(h)[0]) if self._tracker.heads else None
323 if highest_head is None:
324 return # wait for think2
325 height, last = self._tracker.get_height_and_last(highest_head)
326 if height < self._backlog_needed:
329 log.err(None, 'Error in HeightTracker._think:')
331 @defer.inlineCallbacks
334 ba = getwork.BlockAttempt.from_getwork((yield self._rpc_proxy.rpc_getwork()))
335 self._request(ba.previous_block)
337 log.err(None, 'Error in HeightTracker._think2:')
339 def _heard_headers(self, headers):
341 for header in headers:
342 hw = HeaderWrapper.from_header(header)
343 if hw.hash in self._tracker.shares:
346 self._tracker.add(hw)
348 self.updated.happened()
351 if len(self._tracker.shares) >= self._last_notified_size + 100:
352 print 'Have %i/%i block headers' % (len(self._tracker.shares), self._backlog_needed)
353 self._last_notified_size = len(self._tracker.shares)
355 def _heard_block(self, block_hash):
356 self._request(block_hash)
358 @defer.inlineCallbacks
359 def _request(self, last):
360 if last in self._tracker.shares:
362 if last in self._requested:
364 self._requested.add(last)
365 (yield self._factory.getProtocol()).send_getheaders(version=1, have=[], last=last)
367 def get_height_rel_highest(self, block_hash):
368 # callers: highest height can change during yields!
369 height, last = self._tracker.get_height_and_last(block_hash)
370 if last not in self._tracker.tails:
372 return height - max(self._tracker.get_height(head_hash) for head_hash in self._tracker.tails[last])
375 self._factory.new_headers.unwatch(self._watch1)
376 self._factory.new_block.unwatch(self._watch2)
377 self._clear_task.stop()
378 self._think_task.stop()
379 self._think2_task.stop()
381 if __name__ == '__main__':
382 from . import networks
383 factory = ClientFactory(networks.BitcoinMainnet)
384 reactor.connectTCP('127.0.0.1', 8333, factory)
388 @defer.inlineCallbacks
391 print (yield (yield factory.getProtocol()).get_block(0x000000000000003aaaf7638f9f9c0d0c60e8b0eb817dcdb55fd2b1964efc5175))
392 except defer.TimeoutError: