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