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
38 if checksum is not None:
39 if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] != checksum:
40 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
44 type_ = getattr(self, "message_" + command, None)
46 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
47 print 'NO TYPE FOR', repr(command)
51 payload2 = type_.unpack(payload)
53 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
57 handler = getattr(self, 'handle_' + command, None)
59 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
60 print 'NO HANDLER FOR', command
63 #print 'RECV', command, payload2
68 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
72 def sendPacket(self, command, payload2={}):
73 type_ = getattr(self, "message_" + command, None)
75 raise ValueError('invalid command')
76 payload = type_.pack(payload2)
77 if len(command) >= 12:
78 raise ValueError('command too long')
80 checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
83 data = self._prefix + struct.pack('<12sI', command, len(payload)) + checksum + payload
84 self.transport.write(data)
85 #print 'SEND', command, payload2
87 def __getattr__(self, attr):
89 if attr.startswith(prefix):
90 command = attr[len(prefix):]
91 return lambda **payload2: self.sendPacket(command, payload2)
92 #return protocol.Protocol.__getattr__(self, attr)
93 raise AttributeError(attr)
95 class Protocol(BaseProtocol):
96 def __init__(self, net):
97 self._prefix = net.BITCOIN_P2P_PREFIX
102 def use_checksum(self):
103 return self.version >= 209
105 message_version = bitcoin_data.ComposedType([
106 ('version', bitcoin_data.StructType('<I')),
107 ('services', bitcoin_data.StructType('<Q')),
108 ('time', bitcoin_data.StructType('<Q')),
109 ('addr_to', bitcoin_data.address_type),
110 ('addr_from', bitcoin_data.address_type),
111 ('nonce', bitcoin_data.StructType('<Q')),
112 ('sub_version_num', bitcoin_data.VarStrType()),
113 ('start_height', bitcoin_data.StructType('<I')),
115 message_verack = bitcoin_data.ComposedType([])
116 message_addr = bitcoin_data.ComposedType([
117 ('addrs', bitcoin_data.ListType(bitcoin_data.ComposedType([
118 ('timestamp', bitcoin_data.StructType('<I')),
119 ('address', bitcoin_data.address_type),
122 message_inv = bitcoin_data.ComposedType([
123 ('invs', bitcoin_data.ListType(bitcoin_data.ComposedType([
124 ('type', bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'tx': 1, 'block': 2})),
125 ('hash', bitcoin_data.HashType()),
128 message_getdata = bitcoin_data.ComposedType([
129 ('requests', bitcoin_data.ListType(bitcoin_data.ComposedType([
130 ('type', bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'tx': 1, 'block': 2})),
131 ('hash', bitcoin_data.HashType()),
134 message_getblocks = bitcoin_data.ComposedType([
135 ('version', bitcoin_data.StructType('<I')),
136 ('have', bitcoin_data.ListType(bitcoin_data.HashType())),
137 ('last', bitcoin_data.HashType()),
139 message_getheaders = bitcoin_data.ComposedType([
140 ('version', bitcoin_data.StructType('<I')),
141 ('have', bitcoin_data.ListType(bitcoin_data.HashType())),
142 ('last', bitcoin_data.HashType()),
144 message_tx = bitcoin_data.ComposedType([
145 ('tx', bitcoin_data.tx_type),
147 message_block = bitcoin_data.ComposedType([
148 ('block', bitcoin_data.block_type),
150 message_headers = bitcoin_data.ComposedType([
151 ('headers', bitcoin_data.ListType(bitcoin_data.block_header_type)),
153 message_getaddr = bitcoin_data.ComposedType([])
154 message_checkorder = bitcoin_data.ComposedType([
155 ('id', bitcoin_data.HashType()),
156 ('order', bitcoin_data.FixedStrType(60)), # XXX
158 message_submitorder = bitcoin_data.ComposedType([
159 ('id', bitcoin_data.HashType()),
160 ('order', bitcoin_data.FixedStrType(60)), # XXX
162 message_reply = bitcoin_data.ComposedType([
163 ('hash', bitcoin_data.HashType()),
164 ('reply', bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'success': 0, 'failure': 1, 'denied': 2})),
165 ('script', bitcoin_data.VarStrType()),
167 message_ping = bitcoin_data.ComposedType([])
168 message_alert = bitcoin_data.ComposedType([
169 ('message', bitcoin_data.VarStrType()),
170 ('signature', bitcoin_data.VarStrType()),
175 def connectionMade(self):
176 BaseProtocol.connectionMade(self)
181 time=int(time.time()),
184 address='::ffff:' + self.transport.getPeer().host,
185 port=self.transport.getPeer().port,
189 address='::ffff:' + self.transport.getHost().host,
190 port=self.transport.getHost().port,
192 nonce=random.randrange(2**64),
197 def handle_version(self, version, services, time, addr_to, addr_from, nonce, sub_version_num, start_height):
198 #print 'VERSION', locals()
199 self.version_after = version
202 def handle_verack(self):
203 self.version = self.version_after
206 self.check_order = deferral.GenericDeferrer(2**256, lambda id, order: self.send_checkorder(id=id, order=order))
207 self.submit_order = deferral.GenericDeferrer(2**256, lambda id, order: self.send_submitorder(id=id, order=order))
208 self.get_block = deferral.ReplyMatcher(lambda hash: self.send_getdata(requests=[dict(type='block', hash=hash)]))
209 self.get_block_header = deferral.ReplyMatcher(lambda hash: self.send_getdata(requests=[dict(type='block', hash=hash)]))
211 if hasattr(self.factory, 'resetDelay'):
212 self.factory.resetDelay()
213 if hasattr(self.factory, 'gotConnection'):
214 self.factory.gotConnection(self)
216 def handle_inv(self, invs):
218 #print 'INV', item['type'], hex(item['hash'])
219 self.send_getdata(requests=[inv])
221 def handle_addr(self, addrs):
223 pass#print 'ADDR', addr
225 def handle_reply(self, hash, reply, script):
226 self.check_order.got_response(hash, dict(reply=reply, script=script))
227 self.submit_order.got_response(hash, dict(reply=reply, script=script))
229 def handle_tx(self, tx):
230 #print 'TX', hex(merkle_hash([tx])), tx
231 self.factory.new_tx.happened(tx)
233 def handle_block(self, block):
234 self.get_block.got_response(bitcoin_data.block_hash(block['header']), block)
235 self.factory.new_block.happened(block)
237 def handle_ping(self):
240 def connectionLost(self, reason):
241 if hasattr(self.factory, 'gotConnection'):
242 self.factory.gotConnection(None)
244 class ClientFactory(protocol.ReconnectingClientFactory):
249 def __init__(self, net):
251 self.conn = variable.Variable(None)
253 self.new_block = variable.Event()
254 self.new_tx = variable.Event()
256 def buildProtocol(self, addr):
257 p = self.protocol(self.net)
261 def gotConnection(self, conn):
264 def getProtocol(self):
265 return self.conn.get_not_none()
267 if __name__ == '__main__':
268 factory = ClientFactory()
269 reactor.connectTCP('127.0.0.1', 8333, factory)