2 Implementation of Bitcoin's p2p protocol
5 from __future__ import division
13 from twisted.internet import protocol, reactor
15 from . import data as bitcoin_data
16 from p2pool.util import variable, datachunker, deferral
18 class BaseProtocol(protocol.Protocol):
19 def connectionMade(self):
20 self.dataReceived = datachunker.DataChunker(self.dataReceiver())
22 def dataReceiver(self):
25 while start != self._prefix:
26 start = (start + (yield 1))[-len(self._prefix):]
28 command = (yield 12).rstrip('\0')
29 length, = struct.unpack('<I', (yield 4))
36 payload = yield length
40 payload = zlib.decompress(payload)
42 print 'FAILURE DECOMPRESSING'
45 if checksum is not None:
46 if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] != checksum:
47 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
51 type_ = getattr(self, "message_" + command, None)
53 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
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)
64 handler = getattr(self, 'handle_' + command, None)
66 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
67 print 'NO HANDLER FOR', command
70 #print 'RECV', command, payload2
75 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
79 def sendPacket(self, command, payload2):
80 if len(command) >= 12:
81 raise ValueError('command too long')
82 type_ = getattr(self, "message_" + command, None)
84 raise ValueError('invalid command')
85 payload = type_.pack(payload2)
87 checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
91 payload = zlib.compress(payload)
92 data = self._prefix + struct.pack('<12sI', command, len(payload)) + checksum + payload
93 self.transport.write(data)
95 def __getattr__(self, attr):
97 if attr.startswith(prefix):
98 command = attr[len(prefix):]
99 return lambda **payload2: self.sendPacket(command, payload2)
100 #return protocol.Protocol.__getattr__(self, attr)
101 raise AttributeError(attr)
103 class Protocol(BaseProtocol):
104 def __init__(self, net):
105 self._prefix = net.BITCOIN_P2P_PREFIX
111 def use_checksum(self):
112 return self.version >= 209
117 def connectionMade(self):
118 BaseProtocol.connectionMade(self)
123 time=int(time.time()),
126 address=self.transport.getPeer().host,
127 port=self.transport.getPeer().port,
131 address=self.transport.getHost().host,
132 port=self.transport.getHost().port,
134 nonce=random.randrange(2**64),
139 message_version = bitcoin_data.ComposedType([
140 ('version', bitcoin_data.StructType('<I')),
141 ('services', bitcoin_data.StructType('<Q')),
142 ('time', bitcoin_data.StructType('<Q')),
143 ('addr_to', bitcoin_data.address_type),
144 ('addr_from', bitcoin_data.address_type),
145 ('nonce', bitcoin_data.StructType('<Q')),
146 ('sub_version_num', bitcoin_data.VarStrType()),
147 ('start_height', bitcoin_data.StructType('<I')),
149 def handle_version(self, version, services, time, addr_to, addr_from, nonce, sub_version_num, start_height):
150 #print 'VERSION', locals()
151 self.version_after = version
154 message_verack = bitcoin_data.ComposedType([])
155 def handle_verack(self):
156 self.version = self.version_after
159 self.check_order = deferral.GenericDeferrer(2**256, lambda id, order: self.send_checkorder(id=id, order=order))
160 self.submit_order = deferral.GenericDeferrer(2**256, lambda id, order: self.send_submitorder(id=id, order=order))
161 self.get_block = deferral.ReplyMatcher(lambda hash: self.send_getdata(requests=[dict(type='block', hash=hash)]))
162 self.get_block_header = deferral.ReplyMatcher(lambda hash: self.send_getheaders(version=1, have=[], last=hash))
163 self.get_tx = deferral.ReplyMatcher(lambda hash: self.send_getdata(requests=[dict(type='tx', hash=hash)]))
165 if hasattr(self.factory, 'resetDelay'):
166 self.factory.resetDelay()
167 if hasattr(self.factory, 'gotConnection'):
168 self.factory.gotConnection(self)
170 message_inv = bitcoin_data.ComposedType([
171 ('invs', bitcoin_data.ListType(bitcoin_data.ComposedType([
172 ('type', bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'tx': 1, 'block': 2})),
173 ('hash', bitcoin_data.HashType()),
176 def handle_inv(self, invs):
178 if inv['type'] == 'tx':
179 self.factory.new_tx.happened(inv['hash'])
180 elif inv['type'] == 'block':
181 self.factory.new_block.happened(inv['hash'])
183 print "Unknown inv type", item
185 message_getdata = bitcoin_data.ComposedType([
186 ('requests', bitcoin_data.ListType(bitcoin_data.ComposedType([
187 ('type', bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'tx': 1, 'block': 2})),
188 ('hash', bitcoin_data.HashType()),
191 message_getblocks = bitcoin_data.ComposedType([
192 ('version', bitcoin_data.StructType('<I')),
193 ('have', bitcoin_data.ListType(bitcoin_data.HashType())),
194 ('last', bitcoin_data.HashType()),
196 message_getheaders = bitcoin_data.ComposedType([
197 ('version', bitcoin_data.StructType('<I')),
198 ('have', bitcoin_data.ListType(bitcoin_data.HashType())),
199 ('last', bitcoin_data.HashType()),
201 message_getaddr = bitcoin_data.ComposedType([])
202 message_checkorder = bitcoin_data.ComposedType([
203 ('id', bitcoin_data.HashType()),
204 ('order', bitcoin_data.FixedStrType(60)), # XXX
206 message_submitorder = bitcoin_data.ComposedType([
207 ('id', bitcoin_data.HashType()),
208 ('order', bitcoin_data.FixedStrType(60)), # XXX
211 message_addr = bitcoin_data.ComposedType([
212 ('addrs', bitcoin_data.ListType(bitcoin_data.ComposedType([
213 ('timestamp', bitcoin_data.StructType('<I')),
214 ('address', bitcoin_data.address_type),
217 def handle_addr(self, addrs):
221 message_tx = bitcoin_data.ComposedType([
222 ('tx', bitcoin_data.tx_type),
224 def handle_tx(self, tx):
225 self.get_block.got_response(bitcoin_data.tx_type.hash256(tx), tx)
227 message_block = bitcoin_data.ComposedType([
228 ('block', bitcoin_data.block_type),
230 def handle_block(self, block):
231 self.get_block.got_response(bitcoin_data.block_header_type.hash256(block['header']), block)
233 message_headers = bitcoin_data.ComposedType([
234 ('headers', bitcoin_data.ListType(bitcoin_data.block_header_type)),
236 def handle_headers(self, headers):
237 for header in headers:
238 self.get_block_header.got_response(bitcoin_data.block_hash(header), header)
240 message_reply = bitcoin_data.ComposedType([
241 ('hash', bitcoin_data.HashType()),
242 ('reply', bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'success': 0, 'failure': 1, 'denied': 2})),
243 ('script', bitcoin_data.VarStrType()),
245 def handle_reply(self, hash, reply, script):
246 self.check_order.got_response(hash, dict(reply=reply, script=script))
247 self.submit_order.got_response(hash, dict(reply=reply, script=script))
249 message_ping = bitcoin_data.ComposedType([])
250 def handle_ping(self):
253 message_alert = bitcoin_data.ComposedType([
254 ('message', bitcoin_data.VarStrType()),
255 ('signature', bitcoin_data.VarStrType()),
257 def handle_alert(self, message, signature):
258 print "ALERT:", (message, signature)
260 def connectionLost(self, reason):
261 if hasattr(self.factory, 'gotConnection'):
262 self.factory.gotConnection(None)
264 class ClientFactory(protocol.ReconnectingClientFactory):
269 def __init__(self, net):
271 self.conn = variable.Variable(None)
273 self.new_block = variable.Event()
274 self.new_tx = variable.Event()
276 def buildProtocol(self, addr):
277 p = self.protocol(self.net)
281 def gotConnection(self, conn):
284 def getProtocol(self):
285 return self.conn.get_not_none()
287 if __name__ == '__main__':
288 factory = ClientFactory()
289 reactor.connectTCP('127.0.0.1', 8333, factory)
293 @defer.inlineCallbacks
295 (yield factory.getProtocol())