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