1 from __future__ import division
7 from twisted.internet import defer, protocol, reactor
8 from twisted.python import 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 def connectionMade(self):
28 self.factory.proto_made_connection(self)
30 self.addr = self.transport.getPeer().host, self.transport.getPeer().port
37 address=self.transport.getPeer().host,
38 port=self.transport.getPeer().port,
42 address=self.transport.getHost().host,
43 port=self.transport.getHost().port,
45 nonce=self.node.nonce,
46 sub_version=p2pool.__version__,
48 best_share_hash=self.node.best_share_hash_func(),
51 self.timeout_delayed = reactor.callLater(10, self._connect_timeout)
53 def _connect_timeout(self):
54 self.timeout_delayed = None
55 print 'Handshake timed out, disconnecting from %s:%i' % self.addr
56 self.transport.loseConnection()
58 def packetReceived(self, command, payload2):
60 if command != 'version' and not self.connected2:
61 raise PeerMisbehavingError('first message was not version message')
62 p2protocol.Protocol.packetReceived(self, command, payload2)
63 except PeerMisbehavingError, e:
65 print 'Peer %s:%i misbehaving, will drop and ban. Reason:' % self.addr, e.message
66 self.badPeerHappened()
68 def badPeerHappened(self):
71 print "Bad peer banned:", self.addr
72 self.transport.loseConnection()
73 self.node.bans[self.transport.getPeer().host] = time.time() + 60*60
76 self.timeout_delayed = None
77 print 'Connection timed out, disconnecting from %s:%i' % self.addr
78 self.transport.loseConnection()
80 message_version = pack.ComposedType([
81 ('version', pack.IntType(32)),
82 ('services', pack.IntType(64)),
83 ('addr_to', bitcoin_data.address_type),
84 ('addr_from', bitcoin_data.address_type),
85 ('nonce', pack.IntType(64)),
86 ('sub_version', pack.VarStrType()),
87 ('mode', pack.IntType(32)), # always 1 for legacy compatibility
88 ('best_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
90 def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, best_share_hash):
91 if self.other_version is not None:
92 raise PeerMisbehavingError('more than one version message')
94 raise PeerMisbehavingError('peer too old')
96 self.other_version = version
97 self.other_sub_version = sub_version[:512]
98 self.other_services = services
100 if nonce == self.node.nonce:
101 raise PeerMisbehavingError('was connected to self')
102 if nonce in self.node.peers:
104 print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
105 self.transport.loseConnection()
109 self.connected2 = True
111 self.timeout_delayed.cancel()
112 self.timeout_delayed = reactor.callLater(100, self._timeout)
114 old_dataReceived = self.dataReceived
115 def new_dataReceived(data):
116 if self.timeout_delayed is not None:
117 self.timeout_delayed.reset(100)
118 old_dataReceived(data)
119 self.dataReceived = new_dataReceived
121 self.factory.proto_connected(self)
123 self._stop_thread = deferral.run_repeatedly(lambda: [
125 random.expovariate(1/100)][-1])
127 self._stop_thread2 = deferral.run_repeatedly(lambda: [
128 self.send_addrme(port=self.node.port),
129 random.expovariate(1/(100*len(self.node.peers) + 1))][-1])
131 if best_share_hash is not None:
132 self.node.handle_share_hashes([best_share_hash], self)
134 message_ping = pack.ComposedType([])
135 def handle_ping(self):
138 message_addrme = pack.ComposedType([
139 ('port', pack.IntType(16)),
141 def handle_addrme(self, port):
142 host = self.transport.getPeer().host
143 #print 'addrme from', host, port
144 if host == '127.0.0.1':
145 if random.random() < .8 and self.node.peers:
146 random.choice(self.node.peers.values()).send_addrme(port=port) # services...
148 self.node.got_addr((self.transport.getPeer().host, port), self.other_services, int(time.time()))
149 if random.random() < .8 and self.node.peers:
150 random.choice(self.node.peers.values()).send_addrs(addrs=[
153 services=self.other_services,
157 timestamp=int(time.time()),
161 message_addrs = pack.ComposedType([
162 ('addrs', pack.ListType(pack.ComposedType([
163 ('timestamp', pack.IntType(64)),
164 ('address', bitcoin_data.address_type),
167 def handle_addrs(self, addrs):
168 for addr_record in addrs:
169 self.node.got_addr((addr_record['address']['address'], addr_record['address']['port']), addr_record['address']['services'], min(int(time.time()), addr_record['timestamp']))
170 if random.random() < .8 and self.node.peers:
171 random.choice(self.node.peers.values()).send_addrs(addrs=[addr_record])
173 message_getaddrs = pack.ComposedType([
174 ('count', pack.IntType(32)),
176 def handle_getaddrs(self, count):
179 self.send_addrs(addrs=[
181 timestamp=int(self.node.addr_store[host, port][2]),
183 services=self.node.addr_store[host, port][0],
188 self.node.get_good_peers(count)
191 message_getshares = pack.ComposedType([
192 ('hashes', pack.ListType(pack.IntType(256))),
193 ('parents', pack.VarIntType()),
194 ('stops', pack.ListType(pack.IntType(256))),
196 def handle_getshares(self, hashes, parents, stops):
197 self.sendShares(self.node.handle_get_shares(hashes, parents, stops, self))
199 message_shares = pack.ComposedType([
200 ('shares', pack.ListType(p2pool_data.share_type)),
202 def handle_shares(self, shares):
203 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)
205 def sendShares(self, shares):
206 def att(f, **kwargs):
209 except p2protocol.TooLong:
210 att(f, **dict((k, v[:len(v)//2]) for k, v in kwargs.iteritems()))
211 att(f, **dict((k, v[len(v)//2:]) for k, v in kwargs.iteritems()))
213 att(self.send_shares, shares=[share.as_share() for share in shares])
216 message_sharereq = pack.ComposedType([
217 ('id', pack.IntType(256)),
218 ('hashes', pack.ListType(pack.IntType(256))),
219 ('parents', pack.VarIntType()),
220 ('stops', pack.ListType(pack.IntType(256))),
222 def handle_sharereq(self, id, hashes, parents, stops):
223 shares = self.node.handle_get_shares(hashes, parents, stops, self)
225 self.send_sharereply(id=id, result='good', shares=[share.as_share() for share in shares])
226 except p2protocol.TooLong:
227 self.send_sharereply(id=id, result='too long', shares=[])
229 message_sharereply = pack.ComposedType([
230 ('id', pack.IntType(256)),
231 ('result', pack.EnumType(pack.VarIntType(), {0: 'good', 1: 'too long', 2: 'unk2', 3: 'unk3', 4: 'unk4', 5: 'unk5', 6: 'unk6'})),
232 ('shares', pack.ListType(p2pool_data.share_type)),
234 def handle_sharereply(self, id, result, shares):
235 self.node.handle_share_reply(id, result, shares, self)
237 message_bestblock = pack.ComposedType([
238 ('header', bitcoin_data.block_header_type),
240 def handle_bestblock(self, header):
241 self.node.handle_bestblock(header, self)
243 def connectionLost(self, reason):
244 if self.timeout_delayed is not None:
245 self.timeout_delayed.cancel()
247 self.factory.proto_disconnected(self, reason)
250 self.connected2 = False
251 self.factory.proto_lost_connection(self, reason)
253 print "Peer connection lost:", self.addr, reason
255 class ServerFactory(protocol.ServerFactory):
256 def __init__(self, node, max_conns):
258 self.max_conns = max_conns
263 def buildProtocol(self, addr):
264 if sum(self.conns.itervalues()) >= self.max_conns or self.conns.get(self._host_to_ident(addr.host), 0) >= 3:
266 if addr.host in self.node.bans and self.node.bans[addr.host] > time.time():
268 p = Protocol(self.node, True)
271 print "Got peer connection from:", addr
274 def _host_to_ident(self, host):
275 a, b, c, d = host.split('.')
278 def proto_made_connection(self, proto):
279 ident = self._host_to_ident(proto.transport.getPeer().host)
280 self.conns[ident] = self.conns.get(ident, 0) + 1
281 def proto_lost_connection(self, proto, reason):
282 ident = self._host_to_ident(proto.transport.getPeer().host)
283 self.conns[ident] -= 1
284 if not self.conns[ident]:
285 del self.conns[ident]
287 def proto_connected(self, proto):
288 self.node.got_conn(proto)
289 def proto_disconnected(self, proto, reason):
290 self.node.lost_conn(proto, reason)
293 assert not self.running
296 def attempt_listen():
298 self.listen_port = reactor.listenTCP(self.node.port, self)
299 deferral.retry('Error binding to P2P port:', traceback=False)(attempt_listen)()
305 return self.listen_port.stopListening()
307 class ClientFactory(protocol.ClientFactory):
308 def __init__(self, node, desired_conns, max_attempts):
310 self.desired_conns = desired_conns
311 self.max_attempts = max_attempts
313 self.attempts = set()
317 def _host_to_ident(self, host):
318 a, b, c, d = host.split('.')
321 def buildProtocol(self, addr):
322 p = Protocol(self.node, False)
326 def startedConnecting(self, connector):
327 ident = self._host_to_ident(connector.getDestination().host)
328 if ident in self.attempts:
329 raise AssertionError('already have attempt')
330 self.attempts.add(ident)
332 def clientConnectionFailed(self, connector, reason):
333 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
335 def clientConnectionLost(self, connector, reason):
336 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
338 def proto_made_connection(self, proto):
340 def proto_lost_connection(self, proto, reason):
343 def proto_connected(self, proto):
344 self.conns.add(proto)
345 self.node.got_conn(proto)
346 def proto_disconnected(self, proto, reason):
347 self.conns.remove(proto)
348 self.node.lost_conn(proto, reason)
351 assert not self.running
353 self._stop_thinking = deferral.run_repeatedly(self._think)
357 self._stop_thinking()
361 if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and self.node.addr_store:
362 (host, port), = self.node.get_good_peers(1)
364 if self._host_to_ident(host) in self.attempts:
366 elif host in self.node.bans and self.node.bans[host] > time.time():
369 #print 'Trying to connect to', host, port
370 reactor.connectTCP(host, port, self, timeout=5)
374 return random.expovariate(1/1)
376 class SingleClientFactory(protocol.ReconnectingClientFactory):
377 def __init__(self, node):
380 def buildProtocol(self, addr):
381 p = Protocol(self.node, incoming=False)
385 def proto_made_connection(self, proto):
387 def proto_lost_connection(self, proto, reason):
390 def proto_connected(self, proto):
392 self.node.got_conn(proto)
393 def proto_disconnected(self, proto, reason):
394 self.node.lost_conn(proto, reason)
397 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):
398 self.best_share_hash_func = best_share_hash_func
401 self.addr_store = dict(addr_store)
402 self.connect_addrs = connect_addrs
403 self.preferred_storage = preferred_storage
405 self.nonce = random.randrange(2**64)
407 self.bans = {} # address -> end_time
408 self.clientfactory = ClientFactory(self, desired_outgoing_conns, max_outgoing_attempts)
409 self.serverfactory = ServerFactory(self, max_incoming_conns)
414 raise ValueError('already running')
416 self.clientfactory.start()
417 self.serverfactory.start()
418 self.singleclientconnectors = [reactor.connectTCP(addr, port, SingleClientFactory(self)) for addr, port in self.connect_addrs]
422 self._stop_thinking = deferral.run_repeatedly(self._think)
426 if len(self.addr_store) < self.preferred_storage and self.peers:
427 random.choice(self.peers.values()).send_getaddrs(count=8)
431 return random.expovariate(1/20)
433 @defer.inlineCallbacks
436 raise ValueError('already stopped')
440 self._stop_thinking()
441 yield self.clientfactory.stop()
442 yield self.serverfactory.stop()
443 for singleclientconnector in self.singleclientconnectors:
444 yield singleclientconnector.factory.stopTrying()
445 yield singleclientconnector.disconnect()
446 del self.singleclientconnectors
448 def got_conn(self, conn):
449 if conn.nonce in self.peers:
450 raise ValueError('already have peer')
451 self.peers[conn.nonce] = conn
453 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)
455 def lost_conn(self, conn, reason):
456 if conn.nonce not in self.peers:
457 raise ValueError('''don't have peer''')
458 if conn is not self.peers[conn.nonce]:
459 raise ValueError('wrong conn')
460 del self.peers[conn.nonce]
462 print 'Lost peer %s:%i - %s' % (conn.addr[0], conn.addr[1], reason.getErrorMessage())
465 def got_addr(self, (host, port), services, timestamp):
466 if (host, port) in self.addr_store:
467 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
468 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
470 self.addr_store[host, port] = services, timestamp, timestamp
472 def handle_shares(self, shares, peer):
473 print 'handle_shares', (shares, peer)
475 def handle_share_hashes(self, hashes, peer):
476 print 'handle_share_hashes', (hashes, peer)
478 def handle_get_shares(self, hashes, parents, stops, peer):
479 print 'handle_get_shares', (hashes, parents, stops, peer)
481 def handle_share_reply(self, id, result, shares, peer):
482 raise PeerMisbehavingError('sent share reply without being sent a request')
484 def handle_bestblock(self, header, peer):
485 print 'handle_bestblock', header
487 def get_good_peers(self, max_count):
489 return [x[0] for x in sorted(self.addr_store.iteritems(), key=lambda (k, (services, first_seen, last_seen)):
490 -math.log(max(3600, last_seen - first_seen))/math.log(max(3600, t - last_seen))*random.expovariate(1)