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