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.BITCOIN_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([])
204 message_checkorder = bitcoin_data.ComposedType([
205 ('id', bitcoin_data.HashType()),
206 ('order', bitcoin_data.FixedStrType(60)), # XXX
208 message_submitorder = bitcoin_data.ComposedType([
209 ('id', bitcoin_data.HashType()),
210 ('order', bitcoin_data.FixedStrType(60)), # XXX
213 message_addr = bitcoin_data.ComposedType([
214 ('addrs', bitcoin_data.ListType(bitcoin_data.ComposedType([
215 ('timestamp', bitcoin_data.StructType('<I')),
216 ('address', bitcoin_data.address_type),
219 def handle_addr(self, addrs):
223 message_tx = bitcoin_data.ComposedType([
224 ('tx', bitcoin_data.tx_type),
226 def handle_tx(self, tx):
227 self.get_tx.got_response(bitcoin_data.tx_type.hash256(tx), tx)
229 message_block = bitcoin_data.ComposedType([
230 ('block', bitcoin_data.block_type),
232 def handle_block(self, block):
233 block_hash = bitcoin_data.block_header_type.hash256(block['header'])
234 self.get_block.got_response(block_hash, block)
235 self.get_block_header.got_response(block_hash, block['header'])
237 message_headers = bitcoin_data.ComposedType([
238 ('headers', bitcoin_data.ListType(bitcoin_data.block_type)),
240 def handle_headers(self, headers):
241 for header in headers:
242 header = header['header']
243 self.get_block_header.got_response(bitcoin_data.block_header_type.hash256(header), header)
244 self.factory.new_headers.happened([header['header'] for header in headers])
246 message_reply = bitcoin_data.ComposedType([
247 ('hash', bitcoin_data.HashType()),
248 ('reply', bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'success': 0, 'failure': 1, 'denied': 2})),
249 ('script', bitcoin_data.PossiblyNoneType('', bitcoin_data.VarStrType())),
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, rpc_proxy, factory, backlog_needed=1000):
306 self._rpc_proxy = rpc_proxy
307 self._factory = factory
308 self._backlog_needed = backlog_needed
310 self._tracker = forest.Tracker()
312 self._watch1 = self._factory.new_headers.watch(self._heard_headers)
313 self._watch2 = self._factory.new_block.watch(self._heard_block)
315 self._requested = set()
316 self._clear_task = task.LoopingCall(self._requested.clear)
317 self._clear_task.start(60)
319 self._last_notified_size = 0
321 self.updated = variable.Event()
323 self._think_task = task.LoopingCall(self._think)
324 self._think_task.start(15)
325 self._think2_task = task.LoopingCall(self._think2)
326 self._think2_task.start(15)
330 highest_head = max(self._tracker.heads, key=lambda h: self._tracker.get_height_and_last(h)[0]) if self._tracker.heads else None
331 if highest_head is None:
332 return # wait for think2
333 height, last = self._tracker.get_height_and_last(highest_head)
334 if height < self._backlog_needed:
337 log.err(None, 'Error in HeightTracker._think:')
339 @defer.inlineCallbacks
342 ba = getwork.BlockAttempt.from_getwork((yield self._rpc_proxy.rpc_getwork()))
343 self._request(ba.previous_block)
345 log.err(None, 'Error in HeightTracker._think2:')
347 def _heard_headers(self, headers):
349 for header in headers:
350 hw = HeaderWrapper.from_header(header)
351 if hw.hash in self._tracker.shares:
354 self._tracker.add(hw)
356 self.updated.happened()
359 if len(self._tracker.shares) >= self._last_notified_size + 100:
360 print 'Have %i/%i block headers' % (len(self._tracker.shares), self._backlog_needed)
361 self._last_notified_size = len(self._tracker.shares)
363 def _heard_block(self, block_hash):
364 self._request(block_hash)
366 @defer.inlineCallbacks
367 def _request(self, last):
368 if last in self._tracker.shares:
370 if last in self._requested:
372 self._requested.add(last)
373 (yield self._factory.getProtocol()).send_getheaders(version=1, have=[], last=last)
375 def get_height_rel_highest(self, block_hash):
376 # callers: highest height can change during yields!
377 height, last = self._tracker.get_height_and_last(block_hash)
378 if last not in self._tracker.tails:
380 return height - max(self._tracker.get_height(head_hash) for head_hash in self._tracker.tails[last])
383 self._factory.new_headers.unwatch(self._watch1)
384 self._factory.new_block.unwatch(self._watch2)
385 self._clear_task.stop()
386 self._think_task.stop()
387 self._think2_task.stop()
389 if __name__ == '__main__':
390 from . import networks
391 factory = ClientFactory(networks.BitcoinMainnet)
392 reactor.connectTCP('127.0.0.1', 8333, factory)
396 @defer.inlineCallbacks
399 print (yield (yield factory.getProtocol()).get_block(0x000000000000003aaaf7638f9f9c0d0c60e8b0eb817dcdb55fd2b1964efc5175))
400 except defer.TimeoutError: