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