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
15 class PeerMisbehavingError(Exception):
18 class Protocol(p2protocol.Protocol):
19 def __init__(self, node, incoming):
20 p2protocol.Protocol.__init__(self, node.net.PREFIX, 1000000)
22 self.incoming = incoming
24 self.other_version = None
25 self.connected2 = False
27 self.get_shares = deferral.GenericDeferrer(2**256, lambda id, hashes, parents, stops: self.send_sharereq(id=id, hashes=hashes, parents=parents, stops=stops))
29 def connectionMade(self):
30 p2protocol.Protocol.connectionMade(self)
32 self.factory.proto_made_connection(self)
34 self.addr = self.transport.getPeer().host, self.transport.getPeer().port
41 address=self.transport.getPeer().host,
42 port=self.transport.getPeer().port,
46 address=self.transport.getHost().host,
47 port=self.transport.getHost().port,
49 nonce=self.node.nonce,
50 sub_version=p2pool.__version__,
52 best_share_hash=self.node.best_share_hash_func(),
55 self.timeout_delayed = reactor.callLater(10, self._connect_timeout)
57 def _connect_timeout(self):
58 self.timeout_delayed = None
59 print 'Handshake timed out, disconnecting from %s:%i' % self.addr
60 self.transport.loseConnection()
62 def packetReceived(self, command, payload2):
64 if command != 'version' and not self.connected2:
65 raise PeerMisbehavingError('first message was not version message')
66 p2protocol.Protocol.packetReceived(self, command, payload2)
67 except PeerMisbehavingError, e:
69 print 'Peer %s:%i misbehaving, will drop and ban. Reason:' % self.addr, e.message
70 self.badPeerHappened()
72 def badPeerHappened(self):
75 print "Bad peer banned:", self.addr
76 self.transport.loseConnection()
77 self.node.bans[self.transport.getPeer().host] = time.time() + 60*60
80 self.timeout_delayed = None
81 print 'Connection timed out, disconnecting from %s:%i' % self.addr
82 self.transport.loseConnection()
84 message_version = pack.ComposedType([
85 ('version', pack.IntType(32)),
86 ('services', pack.IntType(64)),
87 ('addr_to', bitcoin_data.address_type),
88 ('addr_from', bitcoin_data.address_type),
89 ('nonce', pack.IntType(64)),
90 ('sub_version', pack.VarStrType()),
91 ('mode', pack.IntType(32)), # always 1 for legacy compatibility
92 ('best_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
94 def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, best_share_hash):
95 if self.other_version is not None:
96 raise PeerMisbehavingError('more than one version message')
98 raise PeerMisbehavingError('peer too old')
100 self.other_version = version
101 self.other_sub_version = sub_version[:512]
102 self.other_services = services
104 if nonce == self.node.nonce:
105 raise PeerMisbehavingError('was connected to self')
106 if nonce in self.node.peers:
108 print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
109 self.transport.loseConnection()
113 self.connected2 = True
115 self.timeout_delayed.cancel()
116 self.timeout_delayed = reactor.callLater(100, self._timeout)
118 old_dataReceived = self.dataReceived
119 def new_dataReceived(data):
120 if self.timeout_delayed is not None:
121 self.timeout_delayed.reset(100)
122 old_dataReceived(data)
123 self.dataReceived = new_dataReceived
125 self.factory.proto_connected(self)
127 self._stop_thread = deferral.run_repeatedly(lambda: [
129 random.expovariate(1/100)][-1])
131 self._stop_thread2 = deferral.run_repeatedly(lambda: [
132 self.send_addrme(port=self.node.port),
133 random.expovariate(1/(100*len(self.node.peers) + 1))][-1])
135 if best_share_hash is not None:
136 self.node.handle_share_hashes([best_share_hash], self)
138 message_ping = pack.ComposedType([])
139 def handle_ping(self):
142 message_addrme = pack.ComposedType([
143 ('port', pack.IntType(16)),
145 def handle_addrme(self, port):
146 host = self.transport.getPeer().host
147 #print 'addrme from', host, port
148 if host == '127.0.0.1':
149 if random.random() < .8 and self.node.peers:
150 random.choice(self.node.peers.values()).send_addrme(port=port) # services...
152 self.node.got_addr((self.transport.getPeer().host, port), self.other_services, int(time.time()))
153 if random.random() < .8 and self.node.peers:
154 random.choice(self.node.peers.values()).send_addrs(addrs=[
157 services=self.other_services,
161 timestamp=int(time.time()),
165 message_addrs = pack.ComposedType([
166 ('addrs', pack.ListType(pack.ComposedType([
167 ('timestamp', pack.IntType(64)),
168 ('address', bitcoin_data.address_type),
171 def handle_addrs(self, addrs):
172 for addr_record in addrs:
173 self.node.got_addr((addr_record['address']['address'], addr_record['address']['port']), addr_record['address']['services'], min(int(time.time()), addr_record['timestamp']))
174 if random.random() < .8 and self.node.peers:
175 random.choice(self.node.peers.values()).send_addrs(addrs=[addr_record])
177 message_getaddrs = pack.ComposedType([
178 ('count', pack.IntType(32)),
180 def handle_getaddrs(self, count):
183 self.send_addrs(addrs=[
185 timestamp=int(self.node.addr_store[host, port][2]),
187 services=self.node.addr_store[host, port][0],
192 self.node.get_good_peers(count)
195 message_getshares = pack.ComposedType([
196 ('hashes', pack.ListType(pack.IntType(256))),
197 ('parents', pack.VarIntType()),
198 ('stops', pack.ListType(pack.IntType(256))),
200 def handle_getshares(self, hashes, parents, stops):
201 self.sendShares(self.node.handle_get_shares(hashes, parents, stops, self))
203 message_shares = pack.ComposedType([
204 ('shares', pack.ListType(p2pool_data.share_type)),
206 def handle_shares(self, shares):
207 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)
209 def sendShares(self, shares):
210 def att(f, **kwargs):
213 except p2protocol.TooLong:
214 att(f, **dict((k, v[:len(v)//2]) for k, v in kwargs.iteritems()))
215 return att(f, **dict((k, v[len(v)//2:]) for k, v in kwargs.iteritems()))
217 return att(self.send_shares, shares=[share.as_share() for share in shares])
219 return defer.succeed(None)
222 message_sharereq = pack.ComposedType([
223 ('id', pack.IntType(256)),
224 ('hashes', pack.ListType(pack.IntType(256))),
225 ('parents', pack.VarIntType()),
226 ('stops', pack.ListType(pack.IntType(256))),
228 def handle_sharereq(self, id, hashes, parents, stops):
229 shares = self.node.handle_get_shares(hashes, parents, stops, self)
231 self.send_sharereply(id=id, result='good', shares=[share.as_share() for share in shares])
232 except p2protocol.TooLong:
233 self.send_sharereply(id=id, result='too long', shares=[])
235 message_sharereply = pack.ComposedType([
236 ('id', pack.IntType(256)),
237 ('result', pack.EnumType(pack.VarIntType(), {0: 'good', 1: 'too long', 2: 'unk2', 3: 'unk3', 4: 'unk4', 5: 'unk5', 6: 'unk6'})),
238 ('shares', pack.ListType(p2pool_data.share_type)),
240 def handle_sharereply(self, id, result, shares):
244 res = failure.Failure("sharereply result: " + result)
245 self.get_shares.got_response(id, res)
247 message_bestblock = pack.ComposedType([
248 ('header', bitcoin_data.block_header_type),
250 def handle_bestblock(self, header):
251 self.node.handle_bestblock(header, self)
253 def connectionLost(self, reason):
254 if self.timeout_delayed is not None:
255 self.timeout_delayed.cancel()
257 self.factory.proto_disconnected(self, reason)
260 self.connected2 = False
261 self.factory.proto_lost_connection(self, reason)
263 print "Peer connection lost:", self.addr, reason
264 self.get_shares.respond_all(reason)
266 @defer.inlineCallbacks
268 start = reactor.seconds()
269 yield self.get_shares(hashes=[0], parents=0, stops=[])
270 end = reactor.seconds()
271 defer.returnValue(end - start)
273 class ServerFactory(protocol.ServerFactory):
274 def __init__(self, node, max_conns):
276 self.max_conns = max_conns
281 def buildProtocol(self, addr):
282 if sum(self.conns.itervalues()) >= self.max_conns or self.conns.get(self._host_to_ident(addr.host), 0) >= 3:
284 if addr.host in self.node.bans and self.node.bans[addr.host] > time.time():
286 p = Protocol(self.node, True)
289 print "Got peer connection from:", addr
292 def _host_to_ident(self, host):
293 a, b, c, d = host.split('.')
296 def proto_made_connection(self, proto):
297 ident = self._host_to_ident(proto.transport.getPeer().host)
298 self.conns[ident] = self.conns.get(ident, 0) + 1
299 def proto_lost_connection(self, proto, reason):
300 ident = self._host_to_ident(proto.transport.getPeer().host)
301 self.conns[ident] -= 1
302 if not self.conns[ident]:
303 del self.conns[ident]
305 def proto_connected(self, proto):
306 self.node.got_conn(proto)
307 def proto_disconnected(self, proto, reason):
308 self.node.lost_conn(proto, reason)
311 assert not self.running
314 def attempt_listen():
316 self.listen_port = reactor.listenTCP(self.node.port, self)
317 deferral.retry('Error binding to P2P port:', traceback=False)(attempt_listen)()
323 return self.listen_port.stopListening()
325 class ClientFactory(protocol.ClientFactory):
326 def __init__(self, node, desired_conns, max_attempts):
328 self.desired_conns = desired_conns
329 self.max_attempts = max_attempts
331 self.attempts = set()
335 def _host_to_ident(self, host):
336 a, b, c, d = host.split('.')
339 def buildProtocol(self, addr):
340 p = Protocol(self.node, False)
344 def startedConnecting(self, connector):
345 ident = self._host_to_ident(connector.getDestination().host)
346 if ident in self.attempts:
347 raise AssertionError('already have attempt')
348 self.attempts.add(ident)
350 def clientConnectionFailed(self, connector, reason):
351 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
353 def clientConnectionLost(self, connector, reason):
354 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
356 def proto_made_connection(self, proto):
358 def proto_lost_connection(self, proto, reason):
361 def proto_connected(self, proto):
362 self.conns.add(proto)
363 self.node.got_conn(proto)
364 def proto_disconnected(self, proto, reason):
365 self.conns.remove(proto)
366 self.node.lost_conn(proto, reason)
369 assert not self.running
371 self._stop_thinking = deferral.run_repeatedly(self._think)
375 self._stop_thinking()
379 if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and self.node.addr_store:
380 (host, port), = self.node.get_good_peers(1)
382 if self._host_to_ident(host) in self.attempts:
384 elif host in self.node.bans and self.node.bans[host] > time.time():
387 #print 'Trying to connect to', host, port
388 reactor.connectTCP(host, port, self, timeout=5)
392 return random.expovariate(1/1)
394 class SingleClientFactory(protocol.ReconnectingClientFactory):
395 def __init__(self, node):
398 def buildProtocol(self, addr):
399 p = Protocol(self.node, incoming=False)
403 def proto_made_connection(self, proto):
405 def proto_lost_connection(self, proto, reason):
408 def proto_connected(self, proto):
410 self.node.got_conn(proto)
411 def proto_disconnected(self, proto, reason):
412 self.node.lost_conn(proto, reason)
415 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):
416 self.best_share_hash_func = best_share_hash_func
419 self.addr_store = dict(addr_store)
420 self.connect_addrs = connect_addrs
421 self.preferred_storage = preferred_storage
423 self.nonce = random.randrange(2**64)
425 self.bans = {} # address -> end_time
426 self.clientfactory = ClientFactory(self, desired_outgoing_conns, max_outgoing_attempts)
427 self.serverfactory = ServerFactory(self, max_incoming_conns)
432 raise ValueError('already running')
434 self.clientfactory.start()
435 self.serverfactory.start()
436 self.singleclientconnectors = [reactor.connectTCP(addr, port, SingleClientFactory(self)) for addr, port in self.connect_addrs]
440 self._stop_thinking = deferral.run_repeatedly(self._think)
444 if len(self.addr_store) < self.preferred_storage and self.peers:
445 random.choice(self.peers.values()).send_getaddrs(count=8)
449 return random.expovariate(1/20)
451 @defer.inlineCallbacks
454 raise ValueError('already stopped')
458 self._stop_thinking()
459 yield self.clientfactory.stop()
460 yield self.serverfactory.stop()
461 for singleclientconnector in self.singleclientconnectors:
462 yield singleclientconnector.factory.stopTrying()
463 yield singleclientconnector.disconnect()
464 del self.singleclientconnectors
466 def got_conn(self, conn):
467 if conn.nonce in self.peers:
468 raise ValueError('already have peer')
469 self.peers[conn.nonce] = conn
471 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)
473 def lost_conn(self, conn, reason):
474 if conn.nonce not in self.peers:
475 raise ValueError('''don't have peer''')
476 if conn is not self.peers[conn.nonce]:
477 raise ValueError('wrong conn')
478 del self.peers[conn.nonce]
480 print 'Lost peer %s:%i - %s' % (conn.addr[0], conn.addr[1], reason.getErrorMessage())
483 def got_addr(self, (host, port), services, timestamp):
484 if (host, port) in self.addr_store:
485 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
486 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
488 self.addr_store[host, port] = services, timestamp, timestamp
490 def handle_shares(self, shares, peer):
491 print 'handle_shares', (shares, peer)
493 def handle_share_hashes(self, hashes, peer):
494 print 'handle_share_hashes', (hashes, peer)
496 def handle_get_shares(self, hashes, parents, stops, peer):
497 print 'handle_get_shares', (hashes, parents, stops, peer)
499 def handle_bestblock(self, header, peer):
500 print 'handle_bestblock', header
502 def get_good_peers(self, max_count):
504 return [x[0] for x in sorted(self.addr_store.iteritems(), key=lambda (k, (services, first_seen, last_seen)):
505 -math.log(max(3600, last_seen - first_seen))/math.log(max(3600, t - last_seen))*random.expovariate(1)