1 from __future__ import division
7 from twisted.internet import defer, protocol, reactor
8 from twisted.python import failure, log
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, variable
15 class PeerMisbehavingError(Exception):
18 class Protocol(p2protocol.Protocol):
19 def __init__(self, node, incoming):
20 p2protocol.Protocol.__init__(self, node.net.PREFIX, 1000000, node.traffic_happened)
22 self.incoming = incoming
24 self.other_version = None
25 self.connected2 = False
27 def connectionMade(self):
28 p2protocol.Protocol.connectionMade(self)
30 self.factory.proto_made_connection(self)
32 self.addr = self.transport.getPeer().host, self.transport.getPeer().port
39 address=self.transport.getPeer().host,
40 port=self.transport.getPeer().port,
44 address=self.transport.getHost().host,
45 port=self.transport.getHost().port,
47 nonce=self.node.nonce,
48 sub_version=p2pool.__version__,
50 best_share_hash=self.node.best_share_hash_func(),
53 self.timeout_delayed = reactor.callLater(10, self._connect_timeout)
55 self.get_shares = deferral.GenericDeferrer(
57 func=lambda id, hashes, parents, stops: self.send_sharereq(id=id, hashes=hashes, parents=parents, stops=stops),
59 on_timeout=self.transport.loseConnection,
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()
67 def packetReceived(self, command, payload2):
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:
74 print 'Peer %s:%i misbehaving, will drop and ban. Reason:' % self.addr, e.message
75 self.badPeerHappened()
77 def badPeerHappened(self):
80 print "Bad peer banned:", self.addr
81 self.transport.loseConnection()
82 self.node.bans[self.transport.getPeer().host] = time.time() + 60*60
85 self.timeout_delayed = None
86 print 'Connection timed out, disconnecting from %s:%i' % self.addr
87 self.transport.loseConnection()
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))),
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')
103 raise PeerMisbehavingError('peer too old')
105 self.other_version = version
106 self.other_sub_version = sub_version[:512]
107 self.other_services = services
109 if nonce == self.node.nonce:
110 raise PeerMisbehavingError('was connected to self')
111 if nonce in self.node.peers:
113 print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
114 self.transport.loseConnection()
118 self.connected2 = True
120 self.timeout_delayed.cancel()
121 self.timeout_delayed = reactor.callLater(100, self._timeout)
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
130 self.factory.proto_connected(self)
132 self._stop_thread = deferral.run_repeatedly(lambda: [
134 random.expovariate(1/100)][-1])
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])
140 if best_share_hash is not None:
141 self.node.handle_share_hashes([best_share_hash], self)
143 message_ping = pack.ComposedType([])
144 def handle_ping(self):
147 message_addrme = pack.ComposedType([
148 ('port', pack.IntType(16)),
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...
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=[
162 services=self.other_services,
166 timestamp=int(time.time()),
170 message_addrs = pack.ComposedType([
171 ('addrs', pack.ListType(pack.ComposedType([
172 ('timestamp', pack.IntType(64)),
173 ('address', bitcoin_data.address_type),
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])
182 message_getaddrs = pack.ComposedType([
183 ('count', pack.IntType(32)),
185 def handle_getaddrs(self, count):
188 self.send_addrs(addrs=[
190 timestamp=int(self.node.addr_store[host, port][2]),
192 services=self.node.addr_store[host, port][0],
197 self.node.get_good_peers(count)
200 message_shares = pack.ComposedType([
201 ('shares', pack.ListType(p2pool_data.share_type)),
203 def handle_shares(self, shares):
204 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 def sendShares(self, shares):
207 def att(f, **kwargs):
210 except p2protocol.TooLong:
211 att(f, **dict((k, v[:len(v)//2]) for k, v in kwargs.iteritems()))
212 return att(f, **dict((k, v[len(v)//2:]) for k, v in kwargs.iteritems()))
214 return att(self.send_shares, shares=[share.as_share() for share in shares])
216 return defer.succeed(None)
219 message_sharereq = pack.ComposedType([
220 ('id', pack.IntType(256)),
221 ('hashes', pack.ListType(pack.IntType(256))),
222 ('parents', pack.VarIntType()),
223 ('stops', pack.ListType(pack.IntType(256))),
225 def handle_sharereq(self, id, hashes, parents, stops):
226 shares = self.node.handle_get_shares(hashes, parents, stops, self)
228 self.send_sharereply(id=id, result='good', shares=[share.as_share() for share in shares])
229 except p2protocol.TooLong:
230 self.send_sharereply(id=id, result='too long', shares=[])
232 message_sharereply = pack.ComposedType([
233 ('id', pack.IntType(256)),
234 ('result', pack.EnumType(pack.VarIntType(), {0: 'good', 1: 'too long', 2: 'unk2', 3: 'unk3', 4: 'unk4', 5: 'unk5', 6: 'unk6'})),
235 ('shares', pack.ListType(p2pool_data.share_type)),
237 def handle_sharereply(self, id, result, shares):
239 res = [p2pool_data.load_share(share, self.node.net, self) for share in shares if share['type'] not in [6, 7]]
241 res = failure.Failure("sharereply result: " + result)
242 self.get_shares.got_response(id, res)
244 message_bestblock = pack.ComposedType([
245 ('header', bitcoin_data.block_header_type),
247 def handle_bestblock(self, header):
248 self.node.handle_bestblock(header, self)
250 def connectionLost(self, reason):
251 if self.timeout_delayed is not None:
252 self.timeout_delayed.cancel()
254 self.factory.proto_disconnected(self, reason)
257 self.connected2 = False
258 self.factory.proto_lost_connection(self, reason)
260 print "Peer connection lost:", self.addr, reason
261 self.get_shares.respond_all(reason)
263 @defer.inlineCallbacks
265 start = reactor.seconds()
266 yield self.get_shares(hashes=[0], parents=0, stops=[])
267 end = reactor.seconds()
268 defer.returnValue(end - start)
270 class ServerFactory(protocol.ServerFactory):
271 def __init__(self, node, max_conns):
273 self.max_conns = max_conns
278 def buildProtocol(self, addr):
279 if sum(self.conns.itervalues()) >= self.max_conns or self.conns.get(self._host_to_ident(addr.host), 0) >= 3:
281 if addr.host in self.node.bans and self.node.bans[addr.host] > time.time():
283 p = Protocol(self.node, True)
286 print "Got peer connection from:", addr
289 def _host_to_ident(self, host):
290 a, b, c, d = host.split('.')
293 def proto_made_connection(self, proto):
294 ident = self._host_to_ident(proto.transport.getPeer().host)
295 self.conns[ident] = self.conns.get(ident, 0) + 1
296 def proto_lost_connection(self, proto, reason):
297 ident = self._host_to_ident(proto.transport.getPeer().host)
298 self.conns[ident] -= 1
299 if not self.conns[ident]:
300 del self.conns[ident]
302 def proto_connected(self, proto):
303 self.node.got_conn(proto)
304 def proto_disconnected(self, proto, reason):
305 self.node.lost_conn(proto, reason)
308 assert not self.running
311 def attempt_listen():
313 self.listen_port = reactor.listenTCP(self.node.port, self)
314 deferral.retry('Error binding to P2P port:', traceback=False)(attempt_listen)()
320 return self.listen_port.stopListening()
322 class ClientFactory(protocol.ClientFactory):
323 def __init__(self, node, desired_conns, max_attempts):
325 self.desired_conns = desired_conns
326 self.max_attempts = max_attempts
328 self.attempts = set()
332 def _host_to_ident(self, host):
333 a, b, c, d = host.split('.')
336 def buildProtocol(self, addr):
337 p = Protocol(self.node, False)
341 def startedConnecting(self, connector):
342 ident = self._host_to_ident(connector.getDestination().host)
343 if ident in self.attempts:
344 raise AssertionError('already have attempt')
345 self.attempts.add(ident)
347 def clientConnectionFailed(self, connector, reason):
348 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
350 def clientConnectionLost(self, connector, reason):
351 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
353 def proto_made_connection(self, proto):
355 def proto_lost_connection(self, proto, reason):
358 def proto_connected(self, proto):
359 self.conns.add(proto)
360 self.node.got_conn(proto)
361 def proto_disconnected(self, proto, reason):
362 self.conns.remove(proto)
363 self.node.lost_conn(proto, reason)
366 assert not self.running
368 self._stop_thinking = deferral.run_repeatedly(self._think)
372 self._stop_thinking()
376 if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and self.node.addr_store:
377 (host, port), = self.node.get_good_peers(1)
379 if self._host_to_ident(host) in self.attempts:
381 elif host in self.node.bans and self.node.bans[host] > time.time():
384 #print 'Trying to connect to', host, port
385 reactor.connectTCP(host, port, self, timeout=5)
389 return random.expovariate(1/1)
391 class SingleClientFactory(protocol.ReconnectingClientFactory):
392 def __init__(self, node):
395 def buildProtocol(self, addr):
396 p = Protocol(self.node, incoming=False)
400 def proto_made_connection(self, proto):
402 def proto_lost_connection(self, proto, reason):
405 def proto_connected(self, proto):
407 self.node.got_conn(proto)
408 def proto_disconnected(self, proto, reason):
409 self.node.lost_conn(proto, reason)
412 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, traffic_happened=variable.Event()):
413 self.best_share_hash_func = best_share_hash_func
416 self.addr_store = dict(addr_store)
417 self.connect_addrs = connect_addrs
418 self.preferred_storage = preferred_storage
419 self.traffic_happened = traffic_happened
421 self.nonce = random.randrange(2**64)
423 self.bans = {} # address -> end_time
424 self.clientfactory = ClientFactory(self, desired_outgoing_conns, max_outgoing_attempts)
425 self.serverfactory = ServerFactory(self, max_incoming_conns)
430 raise ValueError('already running')
432 self.clientfactory.start()
433 self.serverfactory.start()
434 self.singleclientconnectors = [reactor.connectTCP(addr, port, SingleClientFactory(self)) for addr, port in self.connect_addrs]
438 self._stop_thinking = deferral.run_repeatedly(self._think)
442 if len(self.addr_store) < self.preferred_storage and self.peers:
443 random.choice(self.peers.values()).send_getaddrs(count=8)
447 return random.expovariate(1/20)
449 @defer.inlineCallbacks
452 raise ValueError('already stopped')
456 self._stop_thinking()
457 yield self.clientfactory.stop()
458 yield self.serverfactory.stop()
459 for singleclientconnector in self.singleclientconnectors:
460 yield singleclientconnector.factory.stopTrying()
461 yield singleclientconnector.disconnect()
462 del self.singleclientconnectors
464 def got_conn(self, conn):
465 if conn.nonce in self.peers:
466 raise ValueError('already have peer')
467 self.peers[conn.nonce] = conn
469 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)
471 def lost_conn(self, conn, reason):
472 if conn.nonce not in self.peers:
473 raise ValueError('''don't have peer''')
474 if conn is not self.peers[conn.nonce]:
475 raise ValueError('wrong conn')
476 del self.peers[conn.nonce]
478 print 'Lost peer %s:%i - %s' % (conn.addr[0], conn.addr[1], reason.getErrorMessage())
481 def got_addr(self, (host, port), services, timestamp):
482 if (host, port) in self.addr_store:
483 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
484 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
486 self.addr_store[host, port] = services, timestamp, timestamp
488 def handle_shares(self, shares, peer):
489 print 'handle_shares', (shares, peer)
491 def handle_share_hashes(self, hashes, peer):
492 print 'handle_share_hashes', (hashes, peer)
494 def handle_get_shares(self, hashes, parents, stops, peer):
495 print 'handle_get_shares', (hashes, parents, stops, peer)
497 def handle_bestblock(self, header, peer):
498 print 'handle_bestblock', header
500 def get_good_peers(self, max_count):
502 return [x[0] for x in sorted(self.addr_store.iteritems(), key=lambda (k, (services, first_seen, last_seen)):
503 -math.log(max(3600, last_seen - first_seen))/math.log(max(3600, t - last_seen))*random.expovariate(1)