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