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 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))
34 if length > self.max_payload_length:
35 print 'length too large'
38 payload = yield length
40 if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] != checksum:
41 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')
44 type_ = getattr(self, 'message_' + command, None)
47 print 'no type for', repr(command)
51 payload2 = type_.unpack(payload)
53 print 'RECV', command, repr(payload.encode('hex')), len(payload)
54 log.err(None, 'Error parsing message: (see RECV line)')
57 self.packetReceived(command, payload2)
59 def packetReceived(self, command, payload2):
60 handler = getattr(self, 'handle_' + command, None)
63 print 'no handler for', repr(command)
69 print 'RECV', command, repr(payload2)[:100]
70 log.err(None, 'Error handling message: (see RECV line)')
72 def sendPacket(self, command, payload2):
73 if len(command) >= 12:
74 raise ValueError('command too long')
75 type_ = getattr(self, 'message_' + command, None)
77 raise ValueError('invalid command')
78 #print 'SEND', command, repr(payload2)[:500]
79 payload = type_.pack(payload2)
80 if len(payload) > self.max_payload_length:
81 raise TooLong('payload too long')
82 self.transport.write(self._prefix + struct.pack('<12sI', command, len(payload)) + hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] + payload)
84 def __getattr__(self, attr):
86 if attr.startswith(prefix):
87 command = attr[len(prefix):]
88 return lambda **payload2: self.sendPacket(command, payload2)
89 #return protocol.Protocol.__getattr__(self, attr)
90 raise AttributeError(attr)
92 class Protocol(BaseProtocol):
93 def __init__(self, net):
94 self._prefix = net.P2P_PREFIX
96 max_payload_length = 1000000
98 def connectionMade(self):
99 BaseProtocol.connectionMade(self)
104 time=int(time.time()),
107 address=self.transport.getPeer().host,
108 port=self.transport.getPeer().port,
112 address=self.transport.getHost().host,
113 port=self.transport.getHost().port,
115 nonce=random.randrange(2**64),
120 message_version = pack.ComposedType([
121 ('version', pack.IntType(32)),
122 ('services', pack.IntType(64)),
123 ('time', pack.IntType(64)),
124 ('addr_to', bitcoin_data.address_type),
125 ('addr_from', bitcoin_data.address_type),
126 ('nonce', pack.IntType(64)),
127 ('sub_version_num', pack.VarStrType()),
128 ('start_height', pack.IntType(32)),
130 def handle_version(self, version, services, time, addr_to, addr_from, nonce, sub_version_num, start_height):
133 message_verack = pack.ComposedType([])
134 def handle_verack(self):
135 self.get_block = deferral.ReplyMatcher(lambda hash: self.send_getdata(requests=[dict(type='block', hash=hash)]))
136 self.get_block_header = deferral.ReplyMatcher(lambda hash: self.send_getheaders(version=1, have=[], last=hash))
137 self.get_tx = deferral.ReplyMatcher(lambda hash: self.send_getdata(requests=[dict(type='tx', hash=hash)]))
139 if hasattr(self.factory, 'resetDelay'):
140 self.factory.resetDelay()
141 if hasattr(self.factory, 'gotConnection'):
142 self.factory.gotConnection(self)
144 message_inv = pack.ComposedType([
145 ('invs', pack.ListType(pack.ComposedType([
146 ('type', pack.EnumType(pack.IntType(32), {'tx': 1, 'block': 2})),
147 ('hash', pack.IntType(256)),
150 def handle_inv(self, invs):
152 if inv['type'] == 'tx':
153 self.factory.new_tx.happened(inv['hash'])
154 elif inv['type'] == 'block':
155 self.factory.new_block.happened(inv['hash'])
157 print 'Unknown inv type', item
159 message_getdata = pack.ComposedType([
160 ('requests', pack.ListType(pack.ComposedType([
161 ('type', pack.EnumType(pack.IntType(32), {'tx': 1, 'block': 2})),
162 ('hash', pack.IntType(256)),
165 message_getblocks = pack.ComposedType([
166 ('version', pack.IntType(32)),
167 ('have', pack.ListType(pack.IntType(256))),
168 ('last', pack.PossiblyNoneType(0, pack.IntType(256))),
170 message_getheaders = pack.ComposedType([
171 ('version', pack.IntType(32)),
172 ('have', pack.ListType(pack.IntType(256))),
173 ('last', pack.PossiblyNoneType(0, pack.IntType(256))),
175 message_getaddr = pack.ComposedType([])
177 message_addr = pack.ComposedType([
178 ('addrs', pack.ListType(pack.ComposedType([
179 ('timestamp', pack.IntType(32)),
180 ('address', bitcoin_data.address_type),
183 def handle_addr(self, addrs):
187 message_tx = pack.ComposedType([
188 ('tx', bitcoin_data.tx_type),
190 def handle_tx(self, tx):
191 self.get_tx.got_response(bitcoin_data.hash256(bitcoin_data.tx_type.pack(tx)), tx)
193 message_block = pack.ComposedType([
194 ('block', bitcoin_data.block_type),
196 def handle_block(self, block):
197 block_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(block['header']))
198 self.get_block.got_response(block_hash, block)
199 self.get_block_header.got_response(block_hash, block['header'])
201 message_headers = pack.ComposedType([
202 ('headers', pack.ListType(bitcoin_data.block_type)),
204 def handle_headers(self, headers):
205 for header in headers:
206 header = header['header']
207 self.get_block_header.got_response(bitcoin_data.hash256(bitcoin_data.block_header_type.pack(header)), header)
208 self.factory.new_headers.happened([header['header'] for header in headers])
210 message_ping = pack.ComposedType([])
211 def handle_ping(self):
214 message_alert = pack.ComposedType([
215 ('message', pack.VarStrType()),
216 ('signature', pack.VarStrType()),
218 def handle_alert(self, message, signature):
219 print 'ALERT:', (message, signature)
221 def connectionLost(self, reason):
222 if hasattr(self.factory, 'gotConnection'):
223 self.factory.gotConnection(None)
224 print 'Bitcoin connection lost. Reason:', reason.getErrorMessage()
226 class ClientFactory(protocol.ReconnectingClientFactory):
231 def __init__(self, net):
233 self.conn = variable.Variable(None)
235 self.new_block = variable.Event()
236 self.new_tx = variable.Event()
237 self.new_headers = variable.Event()
239 def buildProtocol(self, addr):
240 p = self.protocol(self.net)
244 def gotConnection(self, conn):
247 def getProtocol(self):
248 return self.conn.get_not_none()
250 class HeaderWrapper(object):
252 __slots__ = 'hash previous_hash'.split(' ')
255 def from_header(cls, header):
256 return cls(bitcoin_data.hash256(bitcoin_data.block_header_type.pack(header)), header['previous_block'])
258 def __init__(self, hash, previous_hash):
259 self.hash, self.previous_hash = hash, previous_hash
261 class HeightTracker(object):
262 '''Point this at a factory and let it take care of getting block heights'''
264 def __init__(self, rpc_proxy, factory, backlog_needed):
265 self._rpc_proxy = rpc_proxy
266 self._factory = factory
267 self._backlog_needed = backlog_needed
269 self._tracker = forest.Tracker()
271 self._watch1 = self._factory.new_headers.watch(self._heard_headers)
272 self._watch2 = self._factory.new_block.watch(self._request)
274 self._requested = set()
275 self._clear_task = task.LoopingCall(self._requested.clear)
276 self._clear_task.start(60)
278 self._last_notified_size = 0
280 self.updated = variable.Event()
282 self._think_task = task.LoopingCall(self._think)
283 self._think_task.start(15)
284 self._think2_task = task.LoopingCall(self._think2)
285 self._think2_task.start(15)
286 self.best_hash = None
290 highest_head = max(self._tracker.heads, key=lambda h: self._tracker.get_height_and_last(h)[0]) if self._tracker.heads else None
291 if highest_head is None:
292 return # wait for think2
293 height, last = self._tracker.get_height_and_last(highest_head)
294 if height < self._backlog_needed:
297 log.err(None, 'Error in HeightTracker._think:')
299 @defer.inlineCallbacks
302 ba = getwork.BlockAttempt.from_getwork((yield self._rpc_proxy.rpc_getwork()))
303 self._request(ba.previous_block)
304 self.best_hash = ba.previous_block
306 log.err(None, 'Error in HeightTracker._think2:')
308 def _heard_headers(self, headers):
310 for header in headers:
311 hw = HeaderWrapper.from_header(header)
312 if hw.hash in self._tracker.shares:
315 self._tracker.add(hw)
317 self.updated.happened()
320 if len(self._tracker.shares) >= self._last_notified_size + 100:
321 print 'Have %i/%i block headers' % (len(self._tracker.shares), self._backlog_needed)
322 self._last_notified_size = len(self._tracker.shares)
324 @defer.inlineCallbacks
325 def _request(self, last):
326 if last in self._tracker.shares:
328 if last in self._requested:
330 self._requested.add(last)
331 (yield self._factory.getProtocol()).send_getheaders(version=1, have=[], last=last)
333 def get_height_rel_highest(self, block_hash):
334 # callers: highest height can change during yields!
335 best_height, best_last = self._tracker.get_height_and_last(self.best_hash)
336 height, last = self._tracker.get_height_and_last(block_hash)
337 if last != best_last:
338 return -1000000000 # XXX hack
339 return height - best_height
341 if __name__ == '__main__':
342 from . import networks
343 factory = ClientFactory(networks.BitcoinMainnet)
344 reactor.connectTCP('127.0.0.1', 8333, factory)
348 @defer.inlineCallbacks
351 print (yield (yield factory.getProtocol()).get_block(0x000000000000003aaaf7638f9f9c0d0c60e8b0eb817dcdb55fd2b1964efc5175))
352 except defer.TimeoutError: