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