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, pack
19 class TooLong(Exception):
22 class BaseProtocol(protocol.Protocol):
23 def __init__(self, message_prefix, max_payload_length):
24 self._message_prefix = message_prefix
25 self._max_payload_length = max_payload_length
26 self.dataReceived = datachunker.DataChunker(self.dataReceiver())
28 def dataReceiver(self):
31 while start != self._message_prefix:
32 start = (start + (yield 1))[-len(self._message_prefix):]
34 command = (yield 12).rstrip('\0')
35 length, = struct.unpack('<I', (yield 4))
36 if length > self._max_payload_length:
37 print 'length too large'
40 payload = yield length
42 if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] != checksum:
43 print 'invalid hash for', self.transport.getPeer().host, repr(command), length, checksum.encode('hex'), hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4].encode('hex'), payload.encode('hex')
46 type_ = getattr(self, 'message_' + command, None)
49 print 'no type for', repr(command)
53 self.packetReceived(command, type_.unpack(payload))
55 print 'RECV', command, payload[:100].encode('hex') + ('...' if len(payload) > 100 else '')
56 log.err(None, 'Error handling message: (see RECV line)')
57 self.transport.loseConnection()
59 def packetReceived(self, command, payload2):
60 handler = getattr(self, 'handle_' + command, None)
63 print 'no handler for', repr(command)
68 def sendPacket(self, command, payload2):
69 if len(command) >= 12:
70 raise ValueError('command too long')
71 type_ = getattr(self, 'message_' + command, None)
73 raise ValueError('invalid command')
74 #print 'SEND', command, repr(payload2)[:500]
75 payload = type_.pack(payload2)
76 if len(payload) > self._max_payload_length:
77 raise TooLong('payload too long')
78 self.transport.write(self._message_prefix + struct.pack('<12sI', command, len(payload)) + hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] + payload)
80 def __getattr__(self, attr):
82 if attr.startswith(prefix):
83 command = attr[len(prefix):]
84 return lambda **payload2: self.sendPacket(command, payload2)
85 #return protocol.Protocol.__getattr__(self, attr)
86 raise AttributeError(attr)
88 class Protocol(BaseProtocol):
89 def __init__(self, net):
90 BaseProtocol.__init__(self, net.P2P_PREFIX, 1000000)
92 def connectionMade(self):
96 time=int(time.time()),
99 address=self.transport.getPeer().host,
100 port=self.transport.getPeer().port,
104 address=self.transport.getHost().host,
105 port=self.transport.getHost().port,
107 nonce=random.randrange(2**64),
112 message_version = pack.ComposedType([
113 ('version', pack.IntType(32)),
114 ('services', pack.IntType(64)),
115 ('time', pack.IntType(64)),
116 ('addr_to', bitcoin_data.address_type),
117 ('addr_from', bitcoin_data.address_type),
118 ('nonce', pack.IntType(64)),
119 ('sub_version_num', pack.VarStrType()),
120 ('start_height', pack.IntType(32)),
122 def handle_version(self, version, services, time, addr_to, addr_from, nonce, sub_version_num, start_height):
125 message_verack = pack.ComposedType([])
126 def handle_verack(self):
127 self.get_block = deferral.ReplyMatcher(lambda hash: self.send_getdata(requests=[dict(type='block', hash=hash)]))
128 self.get_block_header = deferral.ReplyMatcher(lambda hash: self.send_getheaders(version=1, have=[], last=hash))
129 self.get_tx = deferral.ReplyMatcher(lambda hash: self.send_getdata(requests=[dict(type='tx', hash=hash)]))
131 if hasattr(self.factory, 'resetDelay'):
132 self.factory.resetDelay()
133 if hasattr(self.factory, 'gotConnection'):
134 self.factory.gotConnection(self)
136 message_inv = pack.ComposedType([
137 ('invs', pack.ListType(pack.ComposedType([
138 ('type', pack.EnumType(pack.IntType(32), {'tx': 1, 'block': 2})),
139 ('hash', pack.IntType(256)),
142 def handle_inv(self, invs):
144 if inv['type'] == 'tx':
145 self.factory.new_tx.happened(inv['hash'])
146 elif inv['type'] == 'block':
147 self.factory.new_block.happened(inv['hash'])
149 print 'Unknown inv type', item
151 message_getdata = pack.ComposedType([
152 ('requests', pack.ListType(pack.ComposedType([
153 ('type', pack.EnumType(pack.IntType(32), {'tx': 1, 'block': 2})),
154 ('hash', pack.IntType(256)),
157 message_getblocks = pack.ComposedType([
158 ('version', pack.IntType(32)),
159 ('have', pack.ListType(pack.IntType(256))),
160 ('last', pack.PossiblyNoneType(0, pack.IntType(256))),
162 message_getheaders = pack.ComposedType([
163 ('version', pack.IntType(32)),
164 ('have', pack.ListType(pack.IntType(256))),
165 ('last', pack.PossiblyNoneType(0, pack.IntType(256))),
167 message_getaddr = pack.ComposedType([])
169 message_addr = pack.ComposedType([
170 ('addrs', pack.ListType(pack.ComposedType([
171 ('timestamp', pack.IntType(32)),
172 ('address', bitcoin_data.address_type),
175 def handle_addr(self, addrs):
179 message_tx = pack.ComposedType([
180 ('tx', bitcoin_data.tx_type),
182 def handle_tx(self, tx):
183 self.get_tx.got_response(bitcoin_data.hash256(bitcoin_data.tx_type.pack(tx)), tx)
185 message_block = pack.ComposedType([
186 ('block', bitcoin_data.block_type),
188 def handle_block(self, block):
189 block_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(block['header']))
190 self.get_block.got_response(block_hash, block)
191 self.get_block_header.got_response(block_hash, block['header'])
193 message_headers = pack.ComposedType([
194 ('headers', pack.ListType(bitcoin_data.block_type)),
196 def handle_headers(self, headers):
197 for header in headers:
198 header = header['header']
199 self.get_block_header.got_response(bitcoin_data.hash256(bitcoin_data.block_header_type.pack(header)), header)
200 self.factory.new_headers.happened([header['header'] for header in headers])
202 message_ping = pack.ComposedType([])
203 def handle_ping(self):
206 message_alert = pack.ComposedType([
207 ('message', pack.VarStrType()),
208 ('signature', pack.VarStrType()),
210 def handle_alert(self, message, signature):
211 print 'ALERT:', (message, signature)
213 def connectionLost(self, reason):
214 if hasattr(self.factory, 'gotConnection'):
215 self.factory.gotConnection(None)
216 print 'Bitcoin connection lost. Reason:', reason.getErrorMessage()
218 class ClientFactory(protocol.ReconnectingClientFactory):
223 def __init__(self, net):
225 self.conn = variable.Variable(None)
227 self.new_block = variable.Event()
228 self.new_tx = variable.Event()
229 self.new_headers = variable.Event()
231 def buildProtocol(self, addr):
232 p = self.protocol(self.net)
236 def gotConnection(self, conn):
239 def getProtocol(self):
240 return self.conn.get_not_none()
242 class HeaderWrapper(object):
244 __slots__ = 'hash previous_hash'.split(' ')
247 def from_header(cls, header):
248 return cls(bitcoin_data.hash256(bitcoin_data.block_header_type.pack(header)), header['previous_block'])
250 def __init__(self, hash, previous_hash):
251 self.hash, self.previous_hash = hash, previous_hash
253 class HeightTracker(object):
254 '''Point this at a factory and let it take care of getting block heights'''
256 def __init__(self, rpc_proxy, factory, backlog_needed):
257 self._rpc_proxy = rpc_proxy
258 self._factory = factory
259 self._backlog_needed = backlog_needed
261 self._tracker = forest.Tracker()
263 self._watch1 = self._factory.new_headers.watch(self._heard_headers)
264 self._watch2 = self._factory.new_block.watch(self._request)
266 self._requested = set()
267 self._clear_task = task.LoopingCall(self._requested.clear)
268 self._clear_task.start(60)
270 self._last_notified_size = 0
272 self.updated = variable.Event()
274 self._think_task = task.LoopingCall(self._think)
275 self._think_task.start(15)
276 self._think2_task = task.LoopingCall(self._think2)
277 self._think2_task.start(15)
278 self.best_hash = None
282 highest_head = max(self._tracker.heads, key=lambda h: self._tracker.get_height_and_last(h)[0]) if self._tracker.heads else None
283 if highest_head is None:
284 return # wait for think2
285 height, last = self._tracker.get_height_and_last(highest_head)
286 if height < self._backlog_needed:
289 log.err(None, 'Error in HeightTracker._think:')
291 @defer.inlineCallbacks
294 ba = getwork.BlockAttempt.from_getwork((yield self._rpc_proxy.rpc_getwork()))
295 self._request(ba.previous_block)
296 self.best_hash = ba.previous_block
298 log.err(None, 'Error in HeightTracker._think2:')
300 def _heard_headers(self, headers):
302 for header in headers:
303 hw = HeaderWrapper.from_header(header)
304 if hw.hash in self._tracker.shares:
307 self._tracker.add(hw)
309 self.updated.happened()
312 if len(self._tracker.shares) >= self._last_notified_size + 100:
313 print 'Have %i/%i block headers' % (len(self._tracker.shares), self._backlog_needed)
314 self._last_notified_size = len(self._tracker.shares)
316 @defer.inlineCallbacks
317 def _request(self, last):
318 if last in self._tracker.shares:
320 if last in self._requested:
322 self._requested.add(last)
323 (yield self._factory.getProtocol()).send_getheaders(version=1, have=[], last=last)
325 def get_height_rel_highest(self, block_hash):
326 # callers: highest height can change during yields!
327 best_height, best_last = self._tracker.get_height_and_last(self.best_hash)
328 height, last = self._tracker.get_height_and_last(block_hash)
329 if last != best_last:
330 return -1000000000 # XXX hack
331 return height - best_height
333 if __name__ == '__main__':
334 from . import networks
335 factory = ClientFactory(networks.BitcoinMainnet)
336 reactor.connectTCP('127.0.0.1', 8333, factory)
340 @defer.inlineCallbacks
343 print (yield (yield factory.getProtocol()).get_block(0x000000000000003aaaf7638f9f9c0d0c60e8b0eb817dcdb55fd2b1964efc5175))
344 except defer.TimeoutError: