only allow one outgoing connection per /16 at a time to limit the potential for Sybil...
[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         old_dataReceived = self.dataReceived
62         def new_dataReceived(data):
63             if not self.timeout_delayed.called:
64                 self.timeout_delayed.reset(100)
65             old_dataReceived(data)
66         self.dataReceived = new_dataReceived
67     
68     def _connect_timeout(self):
69         if not self.connected2 and self.transport.connected:
70             print 'Handshake timed out, disconnecting from %s:%i' % self.addr
71             self.transport.loseConnection()
72     
73     def packetReceived(self, command, payload2):
74         if command != 'version' and not self.connected2:
75             self.transport.loseConnection()
76             return
77         
78         bitcoin_p2p.BaseProtocol.packetReceived(self, command, payload2)
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 or version < 2:
110             self.transport.loseConnection()
111             return
112         
113         self.other_version = version
114         self.other_sub_version = sub_version[:512]
115         self.other_services = services
116         
117         if nonce == self.node.nonce:
118             #print 'Detected connection to self, disconnecting from %s:%i' % self.addr
119             self.transport.loseConnection()
120             return
121         if nonce in self.node.peers:
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=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.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         res = []
206         for share in shares:
207             share_obj = p2pool_data.Share.from_share(share, self.node.net)
208             share_obj.peer = self
209             res.append(share_obj)
210         self.node.handle_shares(res, self)
211     
212     def sendShares(self, shares, full=False):
213         def att(f, **kwargs):
214             try:
215                 f(**kwargs)
216             except bitcoin_p2p.TooLong:
217                 att(f, **dict((k, v[:len(v)//2]) for k, v in kwargs.iteritems()))
218                 att(f, **dict((k, v[len(v)//2:]) for k, v in kwargs.iteritems()))
219         if shares:
220             att(self.send_shares, shares=[share.as_share() for share in shares])
221     
222     def connectionLost(self, reason):
223         if self.connected2:
224             self.factory.proto_disconnected(self, reason)
225             self.connected2 = False
226         self.factory.proto_lost_connection(self, reason)
227
228 class ServerFactory(protocol.ServerFactory):
229     def __init__(self, node, max_conns):
230         self.node = node
231         self.max_conns = max_conns
232         
233         self.conns = set()
234         self.running = False
235     
236     def buildProtocol(self, addr):
237         if len(self.conns) >= self.max_conns:
238             return None
239         p = Protocol(self.node, True)
240         p.factory = self
241         return p
242     
243     def proto_made_connection(self, proto):
244         self.conns.add(proto)
245     def proto_lost_connection(self, proto, reason):
246         self.conns.remove(proto)
247     
248     def proto_connected(self, proto):
249         self.node.got_conn(proto)
250     def proto_disconnected(self, proto, reason):
251         self.node.lost_conn(proto, reason)
252     
253     def start(self):
254         assert not self.running
255         self.running = True
256         
257         def attempt_listen():
258             if not self.running:
259                 return
260             try:
261                 self.listen_port = reactor.listenTCP(self.node.port, self)
262             except error.CannotListenError, e:
263                 print >>sys.stderr, 'Error binding to P2P port: %s. Retrying in 3 seconds.' % (e.socketError,)
264                 reactor.callLater(3, attempt_listen)
265         attempt_listen()
266     
267     def stop(self):
268         assert self.running
269         self.running = False
270         
271         self.listen_port.stopListening()
272
273 class ClientFactory(protocol.ClientFactory):
274     def __init__(self, node, desired_conns, max_attempts):
275         self.node = node
276         self.desired_conns = desired_conns
277         self.max_attempts = max_attempts
278         
279         self.attempts = set()
280         self.conns = set()
281         self.running = False
282     
283     def _host_to_ident(self, host):
284         a, b, c, d = host.split('.')
285         return a, b
286     
287     def buildProtocol(self, addr):
288         p = Protocol(self.node, False)
289         p.factory = self
290         return p
291     
292     def startedConnecting(self, connector):
293         ident = self._host_to_ident(connector.getDestination().host)
294         if ident in self.attempts:
295             raise AssertionError('already have attempt')
296         self.attempts.add(ident)
297     
298     def clientConnectionFailed(self, connector, reason):
299         self.attempts.remove(self._host_to_ident(connector.getDestination().host))
300     
301     def clientConnectionLost(self, connector, reason):
302         self.attempts.remove(self._host_to_ident(connector.getDestination().host))
303     
304     def proto_made_connection(self, proto):
305         pass
306     def proto_lost_connection(self, proto, reason):
307         pass
308     
309     def proto_connected(self, proto):
310         self.conns.add(proto)
311         self.node.got_conn(proto)
312     def proto_disconnected(self, proto, reason):
313         self.conns.remove(proto)
314         self.node.lost_conn(proto, reason)
315     
316     def start(self):
317         assert not self.running
318         self.running = True
319         self._think()
320     def stop(self):
321         assert self.running
322         self.running = False
323     
324     @defer.inlineCallbacks
325     def _think(self):
326         while self.running:
327             try:
328                 if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and self.node.addr_store:
329                     (host, port), = self.node.get_good_peers(1)
330                     
331                     if self._host_to_ident(host) not in self.attempts:
332                         #print 'Trying to connect to', host, port
333                         reactor.connectTCP(host, port, self, timeout=5)
334             except:
335                 log.err()
336             
337             yield deferral.sleep(random.expovariate(1/1))
338
339 class SingleClientFactory(protocol.ReconnectingClientFactory):
340     def __init__(self, node):
341         self.node = node
342     
343     def buildProtocol(self, addr):
344         p = Protocol(self.node, incoming=False)
345         p.factory = self
346         return p
347     
348     def proto_made_connection(self, proto):
349         pass
350     def proto_lost_connection(self, proto, reason):
351         pass
352     
353     def proto_connected(self, proto):
354         self.resetDelay()
355         self.node.got_conn(proto)
356     def proto_disconnected(self, proto, reason):
357         self.node.lost_conn(proto, reason)
358
359 class Node(object):
360     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):
361         self.best_share_hash_func = best_share_hash_func
362         self.port = port
363         self.net = net
364         self.addr_store = dict(addr_store)
365         self.connect_addrs = connect_addrs
366         self.preferred_storage = preferred_storage
367         
368         self.nonce = random.randrange(2**64)
369         self.peers = {}
370         self.clientfactory = ClientFactory(self, desired_outgoing_conns, max_outgoing_attempts)
371         self.serverfactory = ServerFactory(self, max_incoming_conns)
372         self.running = False
373     
374     def start(self):
375         if self.running:
376             raise ValueError('already running')
377         
378         self.clientfactory.start()
379         self.serverfactory.start()
380         self.singleclientconnectors = [reactor.connectTCP(addr, port, SingleClientFactory(self)) for addr, port in self.connect_addrs]
381         
382         self.running = True
383         
384         self._think2()
385     
386     @defer.inlineCallbacks
387     def _think2(self):
388         while self.running:
389             try:
390                 if len(self.addr_store) < self.preferred_storage and self.peers:
391                     random.choice(self.peers.values()).send_getaddrs(count=8)
392             except:
393                 log.err()
394             
395             yield deferral.sleep(random.expovariate(1/20))
396     
397     def stop(self):
398         if not self.running:
399             raise ValueError('already stopped')
400         
401         self.running = False
402         
403         self.clientfactory.stop()
404         self.serverfactory.stop()
405         for singleclientconnector in self.singleclientconnectors:
406             singleclientconnector.factory.stopTrying() # XXX will this disconnect a current connection?
407         del self.singleclientconnectors
408     
409     def got_conn(self, conn):
410         if conn.nonce in self.peers:
411             raise ValueError('already have peer')
412         self.peers[conn.nonce] = conn
413         
414         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)
415     
416     def lost_conn(self, conn, reason):
417         if conn.nonce not in self.peers:
418             raise ValueError('''don't have peer''')
419         if conn is not self.peers[conn.nonce]:
420             raise ValueError('wrong conn')
421         del self.peers[conn.nonce]
422         
423         print 'Lost peer %s:%i - %s' % (conn.addr[0], conn.addr[1], reason.getErrorMessage())
424     
425     
426     def got_addr(self, (host, port), services, timestamp):
427         if (host, port) in self.addr_store:
428             old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
429             self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
430         else:
431             self.addr_store[host, port] = services, timestamp, timestamp
432     
433     def handle_shares(self, shares, peer):
434         print 'handle_shares', (shares, peer)
435     
436     def handle_share_hashes(self, hashes, peer):
437         print 'handle_share_hashes', (hashes, peer)
438     
439     def handle_get_shares(self, hashes, parents, stops, peer):
440         print 'handle_get_shares', (hashes, parents, stops, peer)
441     
442     def get_good_peers(self, max_count):
443         t = time.time()
444         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]
445
446 if __name__ == '__main__':
447     p = random.randrange(2**15, 2**16)
448     for i in xrange(5):
449         p2 = random.randrange(2**15, 2**16)
450         print p, p2
451         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())))})
452         n.start()
453         p = p2
454     
455     reactor.run()