reenabled bad peer banning. no longer ban for arbitrary exceptions, though
[p2pool.git] / p2pool / p2p.py
1 from __future__ import division
2
3 import math
4 import random
5 import time
6
7 from twisted.internet import defer, protocol, reactor
8 from twisted.python import failure, log
9
10 import p2pool
11 from p2pool import data as p2pool_data
12 from p2pool.bitcoin import data as bitcoin_data
13 from p2pool.util import deferral, p2protocol, pack, variable
14
15 class PeerMisbehavingError(Exception):
16     pass
17
18 class Protocol(p2protocol.Protocol):
19     def __init__(self, node, incoming):
20         p2protocol.Protocol.__init__(self, node.net.PREFIX, 1000000, node.traffic_happened)
21         self.node = node
22         self.incoming = incoming
23         
24         self.other_version = None
25         self.connected2 = False
26     
27     def connectionMade(self):
28         p2protocol.Protocol.connectionMade(self)
29         
30         self.factory.proto_made_connection(self)
31         
32         self.addr = self.transport.getPeer().host, self.transport.getPeer().port
33         
34         self.send_version(
35             version=4,
36             services=0,
37             addr_to=dict(
38                 services=0,
39                 address=self.transport.getPeer().host,
40                 port=self.transport.getPeer().port,
41             ),
42             addr_from=dict(
43                 services=0,
44                 address=self.transport.getHost().host,
45                 port=self.transport.getHost().port,
46             ),
47             nonce=self.node.nonce,
48             sub_version=p2pool.__version__,
49             mode=1,
50             best_share_hash=self.node.best_share_hash_func(),
51         )
52         
53         self.timeout_delayed = reactor.callLater(10, self._connect_timeout)
54         
55         self.get_shares = deferral.GenericDeferrer(
56             max_id=2**256,
57             func=lambda id, hashes, parents, stops: self.send_sharereq(id=id, hashes=hashes, parents=parents, stops=stops),
58             timeout=15,
59             on_timeout=self.transport.loseConnection,
60         )
61     
62     def _connect_timeout(self):
63         self.timeout_delayed = None
64         print 'Handshake timed out, disconnecting from %s:%i' % self.addr
65         self.transport.loseConnection()
66     
67     def packetReceived(self, command, payload2):
68         try:
69             if command != 'version' and not self.connected2:
70                 raise PeerMisbehavingError('first message was not version message')
71             p2protocol.Protocol.packetReceived(self, command, payload2)
72         except PeerMisbehavingError, e:
73             print 'Peer %s:%i misbehaving, will drop and ban. Reason:' % self.addr, e.message
74             self.badPeerHappened()
75     
76     def badPeerHappened(self):
77         if p2pool.DEBUG:
78             print "Bad peer banned:", self.addr
79         self.transport.loseConnection()
80         self.node.bans[self.transport.getPeer().host] = time.time() + 60*60
81     
82     def _timeout(self):
83         self.timeout_delayed = None
84         print 'Connection timed out, disconnecting from %s:%i' % self.addr
85         self.transport.loseConnection()
86     
87     message_version = pack.ComposedType([
88         ('version', pack.IntType(32)),
89         ('services', pack.IntType(64)),
90         ('addr_to', bitcoin_data.address_type),
91         ('addr_from', bitcoin_data.address_type),
92         ('nonce', pack.IntType(64)),
93         ('sub_version', pack.VarStrType()),
94         ('mode', pack.IntType(32)), # always 1 for legacy compatibility
95         ('best_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
96     ])
97     def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, best_share_hash):
98         if self.other_version is not None:
99             raise PeerMisbehavingError('more than one version message')
100         if version < 4:
101             raise PeerMisbehavingError('peer too old')
102         
103         self.other_version = version
104         self.other_sub_version = sub_version[:512]
105         self.other_services = services
106         
107         if nonce == self.node.nonce:
108             raise PeerMisbehavingError('was connected to self')
109         if nonce in self.node.peers:
110             if p2pool.DEBUG:
111                 print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
112             self.transport.loseConnection()
113             return
114         
115         self.nonce = nonce
116         self.connected2 = True
117         
118         self.timeout_delayed.cancel()
119         self.timeout_delayed = reactor.callLater(100, self._timeout)
120         
121         old_dataReceived = self.dataReceived
122         def new_dataReceived(data):
123             if self.timeout_delayed is not None:
124                 self.timeout_delayed.reset(100)
125             old_dataReceived(data)
126         self.dataReceived = new_dataReceived
127         
128         self.factory.proto_connected(self)
129         
130         self._stop_thread = deferral.run_repeatedly(lambda: [
131             self.send_ping(),
132         random.expovariate(1/100)][-1])
133         
134         self._stop_thread2 = deferral.run_repeatedly(lambda: [
135             self.send_addrme(port=self.node.port),
136         random.expovariate(1/(100*len(self.node.peers) + 1))][-1])
137         
138         if best_share_hash is not None:
139             self.node.handle_share_hashes([best_share_hash], self)
140     
141     message_ping = pack.ComposedType([])
142     def handle_ping(self):
143         pass
144     
145     message_addrme = pack.ComposedType([
146         ('port', pack.IntType(16)),
147     ])
148     def handle_addrme(self, port):
149         host = self.transport.getPeer().host
150         #print 'addrme from', host, port
151         if host == '127.0.0.1':
152             if random.random() < .8 and self.node.peers:
153                 random.choice(self.node.peers.values()).send_addrme(port=port) # services...
154         else:
155             self.node.got_addr((self.transport.getPeer().host, port), self.other_services, int(time.time()))
156             if random.random() < .8 and self.node.peers:
157                 random.choice(self.node.peers.values()).send_addrs(addrs=[
158                     dict(
159                         address=dict(
160                             services=self.other_services,
161                             address=host,
162                             port=port,
163                         ),
164                         timestamp=int(time.time()),
165                     ),
166                 ])
167     
168     message_addrs = pack.ComposedType([
169         ('addrs', pack.ListType(pack.ComposedType([
170             ('timestamp', pack.IntType(64)),
171             ('address', bitcoin_data.address_type),
172         ]))),
173     ])
174     def handle_addrs(self, addrs):
175         for addr_record in addrs:
176             self.node.got_addr((addr_record['address']['address'], addr_record['address']['port']), addr_record['address']['services'], min(int(time.time()), addr_record['timestamp']))
177             if random.random() < .8 and self.node.peers:
178                 random.choice(self.node.peers.values()).send_addrs(addrs=[addr_record])
179     
180     message_getaddrs = pack.ComposedType([
181         ('count', pack.IntType(32)),
182     ])
183     def handle_getaddrs(self, count):
184         if count > 100:
185             count = 100
186         self.send_addrs(addrs=[
187             dict(
188                 timestamp=int(self.node.addr_store[host, port][2]),
189                 address=dict(
190                     services=self.node.addr_store[host, port][0],
191                     address=host,
192                     port=port,
193                 ),
194             ) for host, port in
195             self.node.get_good_peers(count)
196         ])
197     
198     message_shares = pack.ComposedType([
199         ('shares', pack.ListType(p2pool_data.share_type)),
200     ])
201     def handle_shares(self, shares):
202         self.node.handle_shares([p2pool_data.load_share(share, self.node.net, self) for share in shares if share['type'] not in [6, 7]], self)
203     
204     def sendShares(self, shares):
205         def att(f, **kwargs):
206             try:
207                 return f(**kwargs)
208             except p2protocol.TooLong:
209                 att(f, **dict((k, v[:len(v)//2]) for k, v in kwargs.iteritems()))
210                 return att(f, **dict((k, v[len(v)//2:]) for k, v in kwargs.iteritems()))
211         if shares:
212             return att(self.send_shares, shares=[share.as_share() for share in shares])
213         else:
214             return defer.succeed(None)
215     
216     
217     message_sharereq = pack.ComposedType([
218         ('id', pack.IntType(256)),
219         ('hashes', pack.ListType(pack.IntType(256))),
220         ('parents', pack.VarIntType()),
221         ('stops', pack.ListType(pack.IntType(256))),
222     ])
223     def handle_sharereq(self, id, hashes, parents, stops):
224         shares = self.node.handle_get_shares(hashes, parents, stops, self)
225         try:
226             self.send_sharereply(id=id, result='good', shares=[share.as_share() for share in shares])
227         except p2protocol.TooLong:
228             self.send_sharereply(id=id, result='too long', shares=[])
229     
230     message_sharereply = pack.ComposedType([
231         ('id', pack.IntType(256)),
232         ('result', pack.EnumType(pack.VarIntType(), {0: 'good', 1: 'too long', 2: 'unk2', 3: 'unk3', 4: 'unk4', 5: 'unk5', 6: 'unk6'})),
233         ('shares', pack.ListType(p2pool_data.share_type)),
234     ])
235     def handle_sharereply(self, id, result, shares):
236         if result == 'good':
237             res = [p2pool_data.load_share(share, self.node.net, self) for share in shares if share['type'] not in [6, 7]]
238         else:
239             res = failure.Failure("sharereply result: " + result)
240         self.get_shares.got_response(id, res)
241     
242     message_bestblock = pack.ComposedType([
243         ('header', bitcoin_data.block_header_type),
244     ])
245     def handle_bestblock(self, header):
246         self.node.handle_bestblock(header, self)
247     
248     def connectionLost(self, reason):
249         if self.timeout_delayed is not None:
250             self.timeout_delayed.cancel()
251         if self.connected2:
252             self.factory.proto_disconnected(self, reason)
253             self._stop_thread()
254             self._stop_thread2()
255             self.connected2 = False
256         self.factory.proto_lost_connection(self, reason)
257         if p2pool.DEBUG:
258             print "Peer connection lost:", self.addr, reason
259         self.get_shares.respond_all(reason)
260     
261     @defer.inlineCallbacks
262     def do_ping(self):
263         start = reactor.seconds()
264         yield self.get_shares(hashes=[0], parents=0, stops=[])
265         end = reactor.seconds()
266         defer.returnValue(end - start)
267
268 class ServerFactory(protocol.ServerFactory):
269     def __init__(self, node, max_conns):
270         self.node = node
271         self.max_conns = max_conns
272         
273         self.conns = {}
274         self.running = False
275     
276     def buildProtocol(self, addr):
277         if sum(self.conns.itervalues()) >= self.max_conns or self.conns.get(self._host_to_ident(addr.host), 0) >= 3:
278             return None
279         if addr.host in self.node.bans and self.node.bans[addr.host] > time.time():
280             return None
281         p = Protocol(self.node, True)
282         p.factory = self
283         if p2pool.DEBUG:
284             print "Got peer connection from:", addr
285         return p
286     
287     def _host_to_ident(self, host):
288         a, b, c, d = host.split('.')
289         return a, b
290     
291     def proto_made_connection(self, proto):
292         ident = self._host_to_ident(proto.transport.getPeer().host)
293         self.conns[ident] = self.conns.get(ident, 0) + 1
294     def proto_lost_connection(self, proto, reason):
295         ident = self._host_to_ident(proto.transport.getPeer().host)
296         self.conns[ident] -= 1
297         if not self.conns[ident]:
298             del self.conns[ident]
299     
300     def proto_connected(self, proto):
301         self.node.got_conn(proto)
302     def proto_disconnected(self, proto, reason):
303         self.node.lost_conn(proto, reason)
304     
305     def start(self):
306         assert not self.running
307         self.running = True
308         
309         def attempt_listen():
310             if self.running:
311                 self.listen_port = reactor.listenTCP(self.node.port, self)
312         deferral.retry('Error binding to P2P port:', traceback=False)(attempt_listen)()
313     
314     def stop(self):
315         assert self.running
316         self.running = False
317         
318         return self.listen_port.stopListening()
319
320 class ClientFactory(protocol.ClientFactory):
321     def __init__(self, node, desired_conns, max_attempts):
322         self.node = node
323         self.desired_conns = desired_conns
324         self.max_attempts = max_attempts
325         
326         self.attempts = set()
327         self.conns = set()
328         self.running = False
329     
330     def _host_to_ident(self, host):
331         a, b, c, d = host.split('.')
332         return a, b
333     
334     def buildProtocol(self, addr):
335         p = Protocol(self.node, False)
336         p.factory = self
337         return p
338     
339     def startedConnecting(self, connector):
340         ident = self._host_to_ident(connector.getDestination().host)
341         if ident in self.attempts:
342             raise AssertionError('already have attempt')
343         self.attempts.add(ident)
344     
345     def clientConnectionFailed(self, connector, reason):
346         self.attempts.remove(self._host_to_ident(connector.getDestination().host))
347     
348     def clientConnectionLost(self, connector, reason):
349         self.attempts.remove(self._host_to_ident(connector.getDestination().host))
350     
351     def proto_made_connection(self, proto):
352         pass
353     def proto_lost_connection(self, proto, reason):
354         pass
355     
356     def proto_connected(self, proto):
357         self.conns.add(proto)
358         self.node.got_conn(proto)
359     def proto_disconnected(self, proto, reason):
360         self.conns.remove(proto)
361         self.node.lost_conn(proto, reason)
362     
363     def start(self):
364         assert not self.running
365         self.running = True
366         self._stop_thinking = deferral.run_repeatedly(self._think)
367     def stop(self):
368         assert self.running
369         self.running = False
370         self._stop_thinking()
371     
372     def _think(self):
373         try:
374             if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and self.node.addr_store:
375                 (host, port), = self.node.get_good_peers(1)
376                 
377                 if self._host_to_ident(host) in self.attempts:
378                     pass
379                 elif host in self.node.bans and self.node.bans[host] > time.time():
380                     pass
381                 else:
382                     #print 'Trying to connect to', host, port
383                     reactor.connectTCP(host, port, self, timeout=5)
384         except:
385             log.err()
386         
387         return random.expovariate(1/1)
388
389 class SingleClientFactory(protocol.ReconnectingClientFactory):
390     def __init__(self, node):
391         self.node = node
392     
393     def buildProtocol(self, addr):
394         p = Protocol(self.node, incoming=False)
395         p.factory = self
396         return p
397     
398     def proto_made_connection(self, proto):
399         pass
400     def proto_lost_connection(self, proto, reason):
401         pass
402     
403     def proto_connected(self, proto):
404         self.resetDelay()
405         self.node.got_conn(proto)
406     def proto_disconnected(self, proto, reason):
407         self.node.lost_conn(proto, reason)
408
409 class Node(object):
410     def __init__(self, best_share_hash_func, port, net, addr_store={}, connect_addrs=set(), desired_outgoing_conns=10, max_outgoing_attempts=30, max_incoming_conns=50, preferred_storage=1000, traffic_happened=variable.Event()):
411         self.best_share_hash_func = best_share_hash_func
412         self.port = port
413         self.net = net
414         self.addr_store = dict(addr_store)
415         self.connect_addrs = connect_addrs
416         self.preferred_storage = preferred_storage
417         self.traffic_happened = traffic_happened
418         
419         self.nonce = random.randrange(2**64)
420         self.peers = {}
421         self.bans = {} # address -> end_time
422         self.clientfactory = ClientFactory(self, desired_outgoing_conns, max_outgoing_attempts)
423         self.serverfactory = ServerFactory(self, max_incoming_conns)
424         self.running = False
425     
426     def start(self):
427         if self.running:
428             raise ValueError('already running')
429         
430         self.clientfactory.start()
431         self.serverfactory.start()
432         self.singleclientconnectors = [reactor.connectTCP(addr, port, SingleClientFactory(self)) for addr, port in self.connect_addrs]
433         
434         self.running = True
435         
436         self._stop_thinking = deferral.run_repeatedly(self._think)
437     
438     def _think(self):
439         try:
440             if len(self.addr_store) < self.preferred_storage and self.peers:
441                 random.choice(self.peers.values()).send_getaddrs(count=8)
442         except:
443             log.err()
444         
445         return random.expovariate(1/20)
446     
447     @defer.inlineCallbacks
448     def stop(self):
449         if not self.running:
450             raise ValueError('already stopped')
451         
452         self.running = False
453         
454         self._stop_thinking()
455         yield self.clientfactory.stop()
456         yield self.serverfactory.stop()
457         for singleclientconnector in self.singleclientconnectors:
458             yield singleclientconnector.factory.stopTrying()
459             yield singleclientconnector.disconnect()
460         del self.singleclientconnectors
461     
462     def got_conn(self, conn):
463         if conn.nonce in self.peers:
464             raise ValueError('already have peer')
465         self.peers[conn.nonce] = conn
466         
467         print '%s connection to peer %s:%i established. p2pool version: %i %r' % ('Incoming' if conn.incoming else 'Outgoing', conn.addr[0], conn.addr[1], conn.other_version, conn.other_sub_version)
468     
469     def lost_conn(self, conn, reason):
470         if conn.nonce not in self.peers:
471             raise ValueError('''don't have peer''')
472         if conn is not self.peers[conn.nonce]:
473             raise ValueError('wrong conn')
474         del self.peers[conn.nonce]
475         
476         print 'Lost peer %s:%i - %s' % (conn.addr[0], conn.addr[1], reason.getErrorMessage())
477     
478     
479     def got_addr(self, (host, port), services, timestamp):
480         if (host, port) in self.addr_store:
481             old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
482             self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
483         else:
484             self.addr_store[host, port] = services, timestamp, timestamp
485     
486     def handle_shares(self, shares, peer):
487         print 'handle_shares', (shares, peer)
488     
489     def handle_share_hashes(self, hashes, peer):
490         print 'handle_share_hashes', (hashes, peer)
491     
492     def handle_get_shares(self, hashes, parents, stops, peer):
493         print 'handle_get_shares', (hashes, parents, stops, peer)
494     
495     def handle_bestblock(self, header, peer):
496         print 'handle_bestblock', header
497     
498     def get_good_peers(self, max_count):
499         t = time.time()
500         return [x[0] for x in sorted(self.addr_store.iteritems(), key=lambda (k, (services, first_seen, last_seen)):
501             -math.log(max(3600, last_seen - first_seen))/math.log(max(3600, t - last_seen))*random.expovariate(1)
502         )][:max_count]