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