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
161 self.check_order = deferral.GenericDeferrer(2**256, lambda id, order: self.send_checkorder(id=id, order=order))
162 self.submit_order = deferral.GenericDeferrer(2**256, lambda id, order: self.send_submitorder(id=id, order=order))
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.PossiblyNone(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.PossiblyNone(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_block.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 self.get_block.got_response(bitcoin_data.block_header_type.hash256(block['header']), block)
235 message_headers = bitcoin_data.ComposedType([
236 ('headers', bitcoin_data.ListType(bitcoin_data.block_type)),
238 def handle_headers(self, headers):
239 for header in headers:
240 header = header['header']
242 self.get_block_header.got_response(bitcoin_data.block_header_type.hash256(header), header)
244 message_reply = bitcoin_data.ComposedType([
245 ('hash', bitcoin_data.HashType()),
246 ('reply', bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'success': 0, 'failure': 1, 'denied': 2})),
247 ('script', bitcoin_data.PossiblyNone("", bitcoin_data.VarStrType())),
249 def handle_reply(self, hash, reply, script):
250 self.check_order.got_response(hash, dict(reply=reply, script=script))
251 self.submit_order.got_response(hash, dict(reply=reply, script=script))
253 message_ping = bitcoin_data.ComposedType([])
254 def handle_ping(self):
257 message_alert = bitcoin_data.ComposedType([
258 ('message', bitcoin_data.VarStrType()),
259 ('signature', bitcoin_data.VarStrType()),
261 def handle_alert(self, message, signature):
262 print "ALERT:", (message, signature)
264 def connectionLost(self, reason):
265 if hasattr(self.factory, 'gotConnection'):
266 self.factory.gotConnection(None)
268 class ClientFactory(protocol.ReconnectingClientFactory):
273 def __init__(self, net):
275 self.conn = variable.Variable(None)
277 self.new_block = variable.Event()
278 self.new_tx = 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 if __name__ == '__main__':
292 factory = ClientFactory()
293 reactor.connectTCP('127.0.0.1', 8333, factory)
297 @defer.inlineCallbacks
299 (yield factory.getProtocol())