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