removed checkorder, submit order Bitcoin p2p messages and FixedStrType
[p2pool.git] / p2pool / bitcoin / p2p.py
1 '''
2 Implementation of Bitcoin's p2p protocol
3 '''
4
5 from __future__ import division
6
7 import hashlib
8 import random
9 import struct
10 import time
11
12 from twisted.internet import defer, protocol, reactor, task
13 from twisted.python import log
14
15 import p2pool
16 from . import data as bitcoin_data, getwork
17 from p2pool.util import variable, datachunker, deferral, forest
18
19 class TooLong(Exception):
20     pass
21
22 class BaseProtocol(protocol.Protocol):
23     def connectionMade(self):
24         self.dataReceived = datachunker.DataChunker(self.dataReceiver())
25     
26     def dataReceiver(self):
27         while True:
28             start = ''
29             while start != self._prefix:
30                 start = (start + (yield 1))[-len(self._prefix):]
31             
32             command = (yield 12).rstrip('\0')
33             length, = struct.unpack('<I', (yield 4))
34             
35             if length > self.max_payload_length:
36                 print 'length too large'
37                 continue
38             
39             if self.use_checksum:
40                 checksum = yield 4
41             else:
42                 checksum = None
43             
44             payload = yield length
45             
46             if checksum is not None:
47                 if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] != checksum:
48                     print 'invalid hash for', repr(command), checksum.encode('hex') if checksum is not None else None, repr(payload[:100].encode('hex')), len(payload)
49                     continue
50             
51             type_ = getattr(self, 'message_' + command, None)
52             if type_ is None:
53                 if p2pool.DEBUG:
54                     print 'no type for', repr(command)
55                 continue
56             
57             try:
58                 payload2 = type_.unpack(payload)
59             except:
60                 print 'RECV', command, checksum.encode('hex') if checksum is not None else None, repr(payload.encode('hex')), len(payload)
61                 log.err(None, 'Error parsing message: (see RECV line)')
62                 continue
63             
64             handler = getattr(self, 'handle_' + command, None)
65             if handler is None:
66                 if p2pool.DEBUG:
67                     print 'no handler for', repr(command)
68                 continue
69             
70             try:
71                 handler(**payload2)
72             except:
73                 print 'RECV', command, repr(payload2)[:100]
74                 log.err(None, 'Error handling message: (see RECV line)')
75                 continue
76             
77             self.gotPacket()
78     
79     def gotPacket(self):
80         pass
81     
82     def sendPacket(self, command, payload2):
83         if len(command) >= 12:
84             raise ValueError('command too long')
85         type_ = getattr(self, 'message_' + command, None)
86         if type_ is None:
87             raise ValueError('invalid command')
88         #print 'SEND', command, repr(payload2)[:500]
89         payload = type_.pack(payload2)
90         if len(payload) > self.max_payload_length:
91             raise TooLong('payload too long')
92         if self.use_checksum:
93             checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
94         else:
95             checksum = ''
96         data = self._prefix + struct.pack('<12sI', command, len(payload)) + checksum + payload
97         self.transport.write(data)
98     
99     def __getattr__(self, attr):
100         prefix = 'send_'
101         if attr.startswith(prefix):
102             command = attr[len(prefix):]
103             return lambda **payload2: self.sendPacket(command, payload2)
104         #return protocol.Protocol.__getattr__(self, attr)
105         raise AttributeError(attr)
106
107 class Protocol(BaseProtocol):
108     def __init__(self, net):
109         self._prefix = net.P2P_PREFIX
110     
111     version = 0
112     
113     max_payload_length = 1000000
114     
115     @property
116     def use_checksum(self):
117         return self.version >= 209
118     
119     def connectionMade(self):
120         BaseProtocol.connectionMade(self)
121         
122         self.send_version(
123             version=32200,
124             services=1,
125             time=int(time.time()),
126             addr_to=dict(
127                 services=1,
128                 address=self.transport.getPeer().host,
129                 port=self.transport.getPeer().port,
130             ),
131             addr_from=dict(
132                 services=1,
133                 address=self.transport.getHost().host,
134                 port=self.transport.getHost().port,
135             ),
136             nonce=random.randrange(2**64),
137             sub_version_num='',
138             start_height=0,
139         )
140     
141     message_version = bitcoin_data.ComposedType([
142         ('version', bitcoin_data.StructType('<I')),
143         ('services', bitcoin_data.StructType('<Q')),
144         ('time', bitcoin_data.StructType('<Q')),
145         ('addr_to', bitcoin_data.address_type),
146         ('addr_from', bitcoin_data.address_type),
147         ('nonce', bitcoin_data.StructType('<Q')),
148         ('sub_version_num', bitcoin_data.VarStrType()),
149         ('start_height', bitcoin_data.StructType('<I')),
150     ])
151     def handle_version(self, version, services, time, addr_to, addr_from, nonce, sub_version_num, start_height):
152         #print 'VERSION', locals()
153         self.version_after = version
154         self.send_verack()
155     
156     message_verack = bitcoin_data.ComposedType([])
157     def handle_verack(self):
158         self.version = self.version_after
159         
160         self.ready()
161     
162     def ready(self):
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)]))
166         
167         if hasattr(self.factory, 'resetDelay'):
168             self.factory.resetDelay()
169         if hasattr(self.factory, 'gotConnection'):
170             self.factory.gotConnection(self)
171     
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()),
176         ]))),
177     ])
178     def handle_inv(self, invs):
179         for inv in 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'])
184             else:
185                 print 'Unknown inv type', item
186     
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()),
191         ]))),
192     ])
193     message_getblocks = bitcoin_data.ComposedType([
194         ('version', bitcoin_data.StructType('<I')),
195         ('have', bitcoin_data.ListType(bitcoin_data.HashType())),
196         ('last', bitcoin_data.PossiblyNoneType(0, bitcoin_data.HashType())),
197     ])
198     message_getheaders = bitcoin_data.ComposedType([
199         ('version', bitcoin_data.StructType('<I')),
200         ('have', bitcoin_data.ListType(bitcoin_data.HashType())),
201         ('last', bitcoin_data.PossiblyNoneType(0, bitcoin_data.HashType())),
202     ])
203     message_getaddr = bitcoin_data.ComposedType([])
204     
205     message_addr = bitcoin_data.ComposedType([
206         ('addrs', bitcoin_data.ListType(bitcoin_data.ComposedType([
207             ('timestamp', bitcoin_data.StructType('<I')),
208             ('address', bitcoin_data.address_type),
209         ]))),
210     ])
211     def handle_addr(self, addrs):
212         for addr in addrs:
213             pass
214     
215     message_tx = bitcoin_data.ComposedType([
216         ('tx', bitcoin_data.tx_type),
217     ])
218     def handle_tx(self, tx):
219         self.get_tx.got_response(bitcoin_data.tx_type.hash256(tx), tx)
220     
221     message_block = bitcoin_data.ComposedType([
222         ('block', bitcoin_data.block_type),
223     ])
224     def handle_block(self, block):
225         block_hash = bitcoin_data.block_header_type.hash256(block['header'])
226         self.get_block.got_response(block_hash, block)
227         self.get_block_header.got_response(block_hash, block['header'])
228     
229     message_headers = bitcoin_data.ComposedType([
230         ('headers', bitcoin_data.ListType(bitcoin_data.block_type)),
231     ])
232     def handle_headers(self, headers):
233         for header in headers:
234             header = header['header']
235             self.get_block_header.got_response(bitcoin_data.block_header_type.hash256(header), header)
236         self.factory.new_headers.happened([header['header'] for header in headers])
237     
238     message_reply = bitcoin_data.ComposedType([
239         ('hash', bitcoin_data.HashType()),
240         ('reply',  bitcoin_data.EnumType(bitcoin_data.StructType('<I'), {'success': 0, 'failure': 1, 'denied': 2})),
241         ('script', bitcoin_data.PossiblyNoneType('', bitcoin_data.VarStrType())),
242     ])
243     
244     message_ping = bitcoin_data.ComposedType([])
245     def handle_ping(self):
246         pass
247     
248     message_alert = bitcoin_data.ComposedType([
249         ('message', bitcoin_data.VarStrType()),
250         ('signature', bitcoin_data.VarStrType()),
251     ])
252     def handle_alert(self, message, signature):
253         print 'ALERT:', (message, signature)
254     
255     def connectionLost(self, reason):
256         if hasattr(self.factory, 'gotConnection'):
257             self.factory.gotConnection(None)
258
259 class ClientFactory(protocol.ReconnectingClientFactory):
260     protocol = Protocol
261     
262     maxDelay = 1
263     
264     def __init__(self, net):
265         self.net = net
266         self.conn = variable.Variable(None)
267         
268         self.new_block = variable.Event()
269         self.new_tx = variable.Event()
270         self.new_headers = variable.Event()
271     
272     def buildProtocol(self, addr):
273         p = self.protocol(self.net)
274         p.factory = self
275         return p
276     
277     def gotConnection(self, conn):
278         self.conn.set(conn)
279     
280     def getProtocol(self):
281         return self.conn.get_not_none()
282
283 class HeaderWrapper(object):
284     target = 2**256 - 1
285     __slots__ = 'hash previous_hash'.split(' ')
286     
287     @classmethod
288     def from_header(cls, header):
289         return cls(bitcoin_data.block_header_type.hash256(header), header['previous_block'])
290     
291     def __init__(self, hash, previous_hash):
292         self.hash, self.previous_hash = hash, previous_hash
293
294 class HeightTracker(object):
295     '''Point this at a factory and let it take care of getting block heights'''
296     
297     def __init__(self, rpc_proxy, factory, backlog_needed=1000):
298         self._rpc_proxy = rpc_proxy
299         self._factory = factory
300         self._backlog_needed = backlog_needed
301         
302         self._tracker = forest.Tracker()
303         
304         self._watch1 = self._factory.new_headers.watch(self._heard_headers)
305         self._watch2 = self._factory.new_block.watch(self._heard_block)
306         
307         self._requested = set()
308         self._clear_task = task.LoopingCall(self._requested.clear)
309         self._clear_task.start(60)
310         
311         self._last_notified_size = 0
312         
313         self.updated = variable.Event()
314         
315         self._think_task = task.LoopingCall(self._think)
316         self._think_task.start(15)
317         self._think2_task = task.LoopingCall(self._think2)
318         self._think2_task.start(15)
319     
320     def _think(self):
321         try:
322             highest_head = max(self._tracker.heads, key=lambda h: self._tracker.get_height_and_last(h)[0]) if self._tracker.heads else None
323             if highest_head is None:
324                 return # wait for think2
325             height, last = self._tracker.get_height_and_last(highest_head)
326             if height < self._backlog_needed:
327                 self._request(last)
328         except:
329             log.err(None, 'Error in HeightTracker._think:')
330     
331     @defer.inlineCallbacks
332     def _think2(self):
333         try:
334             ba = getwork.BlockAttempt.from_getwork((yield self._rpc_proxy.rpc_getwork()))
335             self._request(ba.previous_block)
336         except:
337             log.err(None, 'Error in HeightTracker._think2:')
338     
339     def _heard_headers(self, headers):
340         changed = False
341         for header in headers:
342             hw = HeaderWrapper.from_header(header)
343             if hw.hash in self._tracker.shares:
344                 continue
345             changed = True
346             self._tracker.add(hw)
347         if changed:
348             self.updated.happened()
349         self._think()
350         
351         if len(self._tracker.shares) >= self._last_notified_size + 100:
352             print 'Have %i/%i block headers' % (len(self._tracker.shares), self._backlog_needed)
353             self._last_notified_size = len(self._tracker.shares)
354     
355     def _heard_block(self, block_hash):
356         self._request(block_hash)
357     
358     @defer.inlineCallbacks
359     def _request(self, last):
360         if last in self._tracker.shares:
361             return
362         if last in self._requested:
363             return
364         self._requested.add(last)
365         (yield self._factory.getProtocol()).send_getheaders(version=1, have=[], last=last)
366     
367     def get_height_rel_highest(self, block_hash):
368         # callers: highest height can change during yields!
369         height, last = self._tracker.get_height_and_last(block_hash)
370         if last not in self._tracker.tails:
371             return -1e300
372         return height - max(self._tracker.get_height(head_hash) for head_hash in self._tracker.tails[last])
373     
374     def stop(self):
375         self._factory.new_headers.unwatch(self._watch1)
376         self._factory.new_block.unwatch(self._watch2)
377         self._clear_task.stop()
378         self._think_task.stop()
379         self._think2_task.stop()
380
381 if __name__ == '__main__':
382     from . import networks
383     factory = ClientFactory(networks.BitcoinMainnet)
384     reactor.connectTCP('127.0.0.1', 8333, factory)
385     
386     @repr
387     @apply
388     @defer.inlineCallbacks
389     def think():
390         try:
391             print (yield (yield factory.getProtocol()).get_block(0x000000000000003aaaf7638f9f9c0d0c60e8b0eb817dcdb55fd2b1964efc5175))
392         except defer.TimeoutError:
393             print "timeout"
394         reactor.stop()
395     
396     reactor.run()