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