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