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