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