fixed "peer too old" warning message, which previously was displayed as "peer sent...
[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 PeerMisbehavingError(Exception):
16     pass
17
18 class Protocol(bitcoin_p2p.BaseProtocol):
19     def __init__(self, node, incoming):
20         bitcoin_p2p.BaseProtocol.__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=3,
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         reactor.callLater(10, self._connect_timeout)
52         self.timeout_delayed = reactor.callLater(100, self._timeout)
53         
54         old_dataReceived = self.dataReceived
55         def new_dataReceived(data):
56             if not self.timeout_delayed.called:
57                 self.timeout_delayed.reset(100)
58             old_dataReceived(data)
59         self.dataReceived = new_dataReceived
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         try:
68             if command != 'version' and not self.connected2:
69                 raise PeerMisbehavingError('first message was not version message')
70             bitcoin_p2p.BaseProtocol.packetReceived(self, command, payload2)
71         except PeerMisbehavingError, e:
72             print 'Peer %s:%i misbehaving, will drop and ban. Reason:' % self.addr, e.message
73             self.badPeerHappened()
74     
75     def badPeerHappened(self):
76         self.transport.loseConnection()
77         self.node.bans[self.transport.getPeer().host] = time.time() + 60*60
78     
79     def _timeout(self):
80         if self.transport.connected:
81             print 'Connection timed out, disconnecting from %s:%i' % self.addr
82             self.transport.loseConnection()
83     
84     @defer.inlineCallbacks
85     def _think(self):
86         while self.connected2:
87             self.send_ping()
88             yield deferral.sleep(random.expovariate(1/100))
89     
90     @defer.inlineCallbacks
91     def _think2(self):
92         while self.connected2:
93             self.send_addrme(port=self.node.port)
94             #print 'sending addrme'
95             yield deferral.sleep(random.expovariate(1/(100*len(self.node.peers) + 1)))
96     
97     message_version = pack.ComposedType([
98         ('version', pack.IntType(32)),
99         ('services', pack.IntType(64)),
100         ('addr_to', bitcoin_data.address_type),
101         ('addr_from', bitcoin_data.address_type),
102         ('nonce', pack.IntType(64)),
103         ('sub_version', pack.VarStrType()),
104         ('mode', pack.IntType(32)), # always 1 for legacy compatibility
105         ('best_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
106     ])
107     def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, best_share_hash):
108         if self.other_version is not None:
109             raise PeerMisbehavingError('more than one version message')
110         if version < 2:
111             raise PeerMisbehavingError('peer too old')
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             raise PeerMisbehavingError('was connected to self')
119         if nonce in self.node.peers:
120             #print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
121             self.transport.loseConnection()
122             return
123         
124         self.nonce = nonce
125         self.connected2 = True
126         self.factory.proto_connected(self)
127         
128         self._think()
129         self._think2()
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=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.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.Share.from_share(share, self.node.net, self) for share in shares], self)
204     
205     def sendShares(self, shares):
206         def att(f, **kwargs):
207             try:
208                 f(**kwargs)
209             except bitcoin_p2p.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     def connectionLost(self, reason):
216         if self.connected2:
217             self.factory.proto_disconnected(self, reason)
218             self.connected2 = False
219         self.factory.proto_lost_connection(self, reason)
220
221 class ServerFactory(protocol.ServerFactory):
222     def __init__(self, node, max_conns):
223         self.node = node
224         self.max_conns = max_conns
225         
226         self.conns = {}
227         self.running = False
228     
229     def buildProtocol(self, addr):
230         if sum(self.conns.itervalues()) >= self.max_conns or self.conns.get(self._host_to_ident(addr.host), 0) >= 3:
231             return None
232         if addr.host in self.node.bans and self.node.bans[addr.host] > time.time():
233             return None
234         p = Protocol(self.node, True)
235         p.factory = self
236         return p
237     
238     def _host_to_ident(self, host):
239         a, b, c, d = host.split('.')
240         return a, b
241     
242     def proto_made_connection(self, proto):
243         ident = self._host_to_ident(proto.transport.getPeer().host)
244         self.conns[ident] = self.conns.get(ident, 0) + 1
245     def proto_lost_connection(self, proto, reason):
246         ident = self._host_to_ident(proto.transport.getPeer().host)
247         self.conns[ident] -= 1
248         if not self.conns[ident]:
249             del self.conns[ident]
250     
251     def proto_connected(self, proto):
252         self.node.got_conn(proto)
253     def proto_disconnected(self, proto, reason):
254         self.node.lost_conn(proto, reason)
255     
256     def start(self):
257         assert not self.running
258         self.running = True
259         
260         def attempt_listen():
261             if self.running:
262                 self.listen_port = reactor.listenTCP(self.node.port, self)
263         deferral.retry('Error binding to P2P port:', traceback=False)(attempt_listen)()
264     
265     def stop(self):
266         assert self.running
267         self.running = False
268         
269         self.listen_port.stopListening()
270
271 class ClientFactory(protocol.ClientFactory):
272     def __init__(self, node, desired_conns, max_attempts):
273         self.node = node
274         self.desired_conns = desired_conns
275         self.max_attempts = max_attempts
276         
277         self.attempts = set()
278         self.conns = set()
279         self.running = False
280     
281     def _host_to_ident(self, host):
282         a, b, c, d = host.split('.')
283         return a, b
284     
285     def buildProtocol(self, addr):
286         p = Protocol(self.node, False)
287         p.factory = self
288         return p
289     
290     def startedConnecting(self, connector):
291         ident = self._host_to_ident(connector.getDestination().host)
292         if ident in self.attempts:
293             raise AssertionError('already have attempt')
294         self.attempts.add(ident)
295     
296     def clientConnectionFailed(self, connector, reason):
297         self.attempts.remove(self._host_to_ident(connector.getDestination().host))
298     
299     def clientConnectionLost(self, connector, reason):
300         self.attempts.remove(self._host_to_ident(connector.getDestination().host))
301     
302     def proto_made_connection(self, proto):
303         pass
304     def proto_lost_connection(self, proto, reason):
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, reason):
311         self.conns.remove(proto)
312         self.node.lost_conn(proto, reason)
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 self._host_to_ident(host) in self.attempts:
330                         pass
331                     elif host in self.node.bans and self.node.bans[host] > time.time():
332                         pass
333                     else:
334                         #print 'Trying to connect to', host, port
335                         reactor.connectTCP(host, port, self, timeout=5)
336             except:
337                 log.err()
338             
339             yield deferral.sleep(random.expovariate(1/1))
340
341 class SingleClientFactory(protocol.ReconnectingClientFactory):
342     def __init__(self, node):
343         self.node = node
344     
345     def buildProtocol(self, addr):
346         p = Protocol(self.node, incoming=False)
347         p.factory = self
348         return p
349     
350     def proto_made_connection(self, proto):
351         pass
352     def proto_lost_connection(self, proto, reason):
353         pass
354     
355     def proto_connected(self, proto):
356         self.resetDelay()
357         self.node.got_conn(proto)
358     def proto_disconnected(self, proto, reason):
359         self.node.lost_conn(proto, reason)
360
361 class Node(object):
362     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):
363         self.best_share_hash_func = best_share_hash_func
364         self.port = port
365         self.net = net
366         self.addr_store = dict(addr_store)
367         self.connect_addrs = connect_addrs
368         self.preferred_storage = preferred_storage
369         
370         self.nonce = random.randrange(2**64)
371         self.peers = {}
372         self.bans = {} # address -> end_time
373         self.clientfactory = ClientFactory(self, desired_outgoing_conns, max_outgoing_attempts)
374         self.serverfactory = ServerFactory(self, max_incoming_conns)
375         self.running = False
376     
377     def start(self):
378         if self.running:
379             raise ValueError('already running')
380         
381         self.clientfactory.start()
382         self.serverfactory.start()
383         self.singleclientconnectors = [reactor.connectTCP(addr, port, SingleClientFactory(self)) for addr, port in self.connect_addrs]
384         
385         self.running = True
386         
387         self._think2()
388     
389     @defer.inlineCallbacks
390     def _think2(self):
391         while self.running:
392             try:
393                 if len(self.addr_store) < self.preferred_storage and self.peers:
394                     random.choice(self.peers.values()).send_getaddrs(count=8)
395             except:
396                 log.err()
397             
398             yield deferral.sleep(random.expovariate(1/20))
399     
400     def stop(self):
401         if not self.running:
402             raise ValueError('already stopped')
403         
404         self.running = False
405         
406         self.clientfactory.stop()
407         self.serverfactory.stop()
408         for singleclientconnector in self.singleclientconnectors:
409             singleclientconnector.factory.stopTrying() # XXX will this disconnect a current connection?
410         del self.singleclientconnectors
411     
412     def got_conn(self, conn):
413         if conn.nonce in self.peers:
414             raise ValueError('already have peer')
415         self.peers[conn.nonce] = conn
416         
417         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)
418     
419     def lost_conn(self, conn, reason):
420         if conn.nonce not in self.peers:
421             raise ValueError('''don't have peer''')
422         if conn is not self.peers[conn.nonce]:
423             raise ValueError('wrong conn')
424         del self.peers[conn.nonce]
425         
426         print 'Lost peer %s:%i - %s' % (conn.addr[0], conn.addr[1], reason.getErrorMessage())
427     
428     
429     def got_addr(self, (host, port), services, timestamp):
430         if (host, port) in self.addr_store:
431             old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
432             self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
433         else:
434             self.addr_store[host, port] = services, timestamp, timestamp
435     
436     def handle_shares(self, shares, peer):
437         print 'handle_shares', (shares, peer)
438     
439     def handle_share_hashes(self, hashes, peer):
440         print 'handle_share_hashes', (hashes, peer)
441     
442     def handle_get_shares(self, hashes, parents, stops, peer):
443         print 'handle_get_shares', (hashes, parents, stops, peer)
444     
445     def get_good_peers(self, max_count):
446         t = time.time()
447         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]
448
449 if __name__ == '__main__':
450     p = random.randrange(2**15, 2**16)
451     for i in xrange(5):
452         p2 = random.randrange(2**15, 2**16)
453         print p, p2
454         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())))})
455         n.start()
456         p = p2
457     
458     reactor.run()