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 reactor.callLater(10, self._connect_timeout)
52 self.timeout_delayed = reactor.callLater(100, self._timeout)
54 old_dataReceived = self.dataReceived
55 def new_dataReceived(data):
56 if not self.timeout_delayed.called:
57 self.timeout_delayed.reset(100)
58 old_dataReceived(data)
59 self.dataReceived = new_dataReceived
61 def _connect_timeout(self):
62 if not self.connected2 and self.transport.connected:
63 print 'Handshake timed out, disconnecting from %s:%i' % self.addr
64 self.transport.loseConnection()
66 def packetReceived(self, command, payload2):
68 if command != 'version' and not self.connected2:
69 raise PeerMisbehavingError('first message was not version message')
70 p2protocol.Protocol.packetReceived(self, command, payload2)
71 except PeerMisbehavingError, e:
72 print 'Peer %s:%i misbehaving, will drop and ban. Reason:' % self.addr, e.message
73 self.badPeerHappened()
75 def badPeerHappened(self):
77 print "Bad peer banned:", self.addr
78 self.transport.loseConnection()
79 self.node.bans[self.transport.getPeer().host] = time.time() + 60*60
82 if self.transport.connected:
83 print 'Connection timed out, disconnecting from %s:%i' % self.addr
84 self.transport.loseConnection()
86 @defer.inlineCallbacks
88 while self.connected2:
90 yield deferral.sleep(random.expovariate(1/100))
92 @defer.inlineCallbacks
94 while self.connected2:
95 self.send_addrme(port=self.node.port)
96 #print 'sending addrme'
97 yield deferral.sleep(random.expovariate(1/(100*len(self.node.peers) + 1)))
99 message_version = pack.ComposedType([
100 ('version', pack.IntType(32)),
101 ('services', pack.IntType(64)),
102 ('addr_to', bitcoin_data.address_type),
103 ('addr_from', bitcoin_data.address_type),
104 ('nonce', pack.IntType(64)),
105 ('sub_version', pack.VarStrType()),
106 ('mode', pack.IntType(32)), # always 1 for legacy compatibility
107 ('best_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
109 def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, best_share_hash):
110 if self.other_version is not None:
111 raise PeerMisbehavingError('more than one version message')
113 raise PeerMisbehavingError('peer too old')
115 self.other_version = version
116 self.other_sub_version = sub_version[:512]
117 self.other_services = services
119 if nonce == self.node.nonce:
120 raise PeerMisbehavingError('was connected to self')
121 if nonce in self.node.peers:
123 print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
124 self.transport.loseConnection()
128 self.connected2 = True
129 self.factory.proto_connected(self)
134 if best_share_hash is not None:
135 self.node.handle_share_hashes([best_share_hash], self)
137 message_ping = pack.ComposedType([])
138 def handle_ping(self):
141 message_addrme = pack.ComposedType([
142 ('port', pack.IntType(16)),
144 def handle_addrme(self, port):
145 host = self.transport.getPeer().host
146 #print 'addrme from', host, port
147 if host == '127.0.0.1':
148 if random.random() < .8 and self.node.peers:
149 random.choice(self.node.peers.values()).send_addrme(port=port) # services...
151 self.node.got_addr((self.transport.getPeer().host, port), self.other_services, int(time.time()))
152 if random.random() < .8 and self.node.peers:
153 random.choice(self.node.peers.values()).send_addrs(addrs=[
156 services=self.other_services,
160 timestamp=int(time.time()),
164 message_addrs = pack.ComposedType([
165 ('addrs', pack.ListType(pack.ComposedType([
166 ('timestamp', pack.IntType(64)),
167 ('address', bitcoin_data.address_type),
170 def handle_addrs(self, addrs):
171 for addr_record in addrs:
172 self.node.got_addr((addr_record['address']['address'], addr_record['address']['port']), addr_record['address']['services'], min(int(time.time()), addr_record['timestamp']))
173 if random.random() < .8 and self.node.peers:
174 random.choice(self.node.peers.values()).send_addrs(addrs=[addr_record])
176 message_getaddrs = pack.ComposedType([
177 ('count', pack.IntType(32)),
179 def handle_getaddrs(self, count):
182 self.send_addrs(addrs=[
184 timestamp=int(self.node.addr_store[host, port][2]),
186 services=self.node.addr_store[host, port][0],
191 self.node.get_good_peers(count)
194 message_getshares = pack.ComposedType([
195 ('hashes', pack.ListType(pack.IntType(256))),
196 ('parents', pack.VarIntType()),
197 ('stops', pack.ListType(pack.IntType(256))),
199 def handle_getshares(self, hashes, parents, stops):
200 self.sendShares(self.node.handle_get_shares(hashes, parents, stops, self))
202 message_shares = pack.ComposedType([
203 ('shares', pack.ListType(p2pool_data.share_type)),
205 def handle_shares(self, shares):
206 self.node.handle_shares([p2pool_data.load_share(share, self.node.net, self) for share in shares], self)
208 def sendShares(self, shares):
209 def att(f, **kwargs):
212 except p2protocol.TooLong:
213 att(f, **dict((k, v[:len(v)//2]) for k, v in kwargs.iteritems()))
214 att(f, **dict((k, v[len(v)//2:]) for k, v in kwargs.iteritems()))
216 att(self.send_shares, shares=[share.as_share() for share in shares])
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):
238 self.node.handle_share_reply(id, result, shares, self)
241 def connectionLost(self, reason):
243 self.factory.proto_disconnected(self, reason)
244 self.connected2 = False
245 self.factory.proto_lost_connection(self, reason)
247 print "Peer connection lost:", self.addr, reason
249 class ServerFactory(protocol.ServerFactory):
250 def __init__(self, node, max_conns):
252 self.max_conns = max_conns
257 def buildProtocol(self, addr):
258 if sum(self.conns.itervalues()) >= self.max_conns or self.conns.get(self._host_to_ident(addr.host), 0) >= 3:
260 if addr.host in self.node.bans and self.node.bans[addr.host] > time.time():
262 p = Protocol(self.node, True)
265 print "Got peer connection from:", addr
268 def _host_to_ident(self, host):
269 a, b, c, d = host.split('.')
272 def proto_made_connection(self, proto):
273 ident = self._host_to_ident(proto.transport.getPeer().host)
274 self.conns[ident] = self.conns.get(ident, 0) + 1
275 def proto_lost_connection(self, proto, reason):
276 ident = self._host_to_ident(proto.transport.getPeer().host)
277 self.conns[ident] -= 1
278 if not self.conns[ident]:
279 del self.conns[ident]
281 def proto_connected(self, proto):
282 self.node.got_conn(proto)
283 def proto_disconnected(self, proto, reason):
284 self.node.lost_conn(proto, reason)
287 assert not self.running
290 def attempt_listen():
292 self.listen_port = reactor.listenTCP(self.node.port, self)
293 deferral.retry('Error binding to P2P port:', traceback=False)(attempt_listen)()
299 self.listen_port.stopListening()
301 class ClientFactory(protocol.ClientFactory):
302 def __init__(self, node, desired_conns, max_attempts):
304 self.desired_conns = desired_conns
305 self.max_attempts = max_attempts
307 self.attempts = set()
311 def _host_to_ident(self, host):
312 a, b, c, d = host.split('.')
315 def buildProtocol(self, addr):
316 p = Protocol(self.node, False)
320 def startedConnecting(self, connector):
321 ident = self._host_to_ident(connector.getDestination().host)
322 if ident in self.attempts:
323 raise AssertionError('already have attempt')
324 self.attempts.add(ident)
326 def clientConnectionFailed(self, connector, reason):
327 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
329 def clientConnectionLost(self, connector, reason):
330 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
332 def proto_made_connection(self, proto):
334 def proto_lost_connection(self, proto, reason):
337 def proto_connected(self, proto):
338 self.conns.add(proto)
339 self.node.got_conn(proto)
340 def proto_disconnected(self, proto, reason):
341 self.conns.remove(proto)
342 self.node.lost_conn(proto, reason)
345 assert not self.running
352 @defer.inlineCallbacks
356 if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and self.node.addr_store:
357 (host, port), = self.node.get_good_peers(1)
359 if self._host_to_ident(host) in self.attempts:
361 elif host in self.node.bans and self.node.bans[host] > time.time():
364 #print 'Trying to connect to', host, port
365 reactor.connectTCP(host, port, self, timeout=5)
369 yield deferral.sleep(random.expovariate(1/1))
371 class SingleClientFactory(protocol.ReconnectingClientFactory):
372 def __init__(self, node):
375 def buildProtocol(self, addr):
376 p = Protocol(self.node, incoming=False)
380 def proto_made_connection(self, proto):
382 def proto_lost_connection(self, proto, reason):
385 def proto_connected(self, proto):
387 self.node.got_conn(proto)
388 def proto_disconnected(self, proto, reason):
389 self.node.lost_conn(proto, reason)
392 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):
393 self.best_share_hash_func = best_share_hash_func
396 self.addr_store = dict(addr_store)
397 self.connect_addrs = connect_addrs
398 self.preferred_storage = preferred_storage
400 self.nonce = random.randrange(2**64)
402 self.bans = {} # address -> end_time
403 self.clientfactory = ClientFactory(self, desired_outgoing_conns, max_outgoing_attempts)
404 self.serverfactory = ServerFactory(self, max_incoming_conns)
409 raise ValueError('already running')
411 self.clientfactory.start()
412 self.serverfactory.start()
413 self.singleclientconnectors = [reactor.connectTCP(addr, port, SingleClientFactory(self)) for addr, port in self.connect_addrs]
419 @defer.inlineCallbacks
423 if len(self.addr_store) < self.preferred_storage and self.peers:
424 random.choice(self.peers.values()).send_getaddrs(count=8)
428 yield deferral.sleep(random.expovariate(1/20))
432 raise ValueError('already stopped')
436 self.clientfactory.stop()
437 self.serverfactory.stop()
438 for singleclientconnector in self.singleclientconnectors:
439 singleclientconnector.factory.stopTrying() # XXX will this disconnect a current connection?
440 del self.singleclientconnectors
442 def got_conn(self, conn):
443 if conn.nonce in self.peers:
444 raise ValueError('already have peer')
445 self.peers[conn.nonce] = conn
447 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)
449 def lost_conn(self, conn, reason):
450 if conn.nonce not in self.peers:
451 raise ValueError('''don't have peer''')
452 if conn is not self.peers[conn.nonce]:
453 raise ValueError('wrong conn')
454 del self.peers[conn.nonce]
456 print 'Lost peer %s:%i - %s' % (conn.addr[0], conn.addr[1], reason.getErrorMessage())
459 def got_addr(self, (host, port), services, timestamp):
460 if (host, port) in self.addr_store:
461 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
462 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
464 self.addr_store[host, port] = services, timestamp, timestamp
466 def handle_shares(self, shares, peer):
467 print 'handle_shares', (shares, peer)
469 def handle_share_hashes(self, hashes, peer):
470 print 'handle_share_hashes', (hashes, peer)
472 def handle_get_shares(self, hashes, parents, stops, peer):
473 print 'handle_get_shares', (hashes, parents, stops, peer)
475 def handle_share_reply(self, id, result, shares, peer):
476 raise PeerMisbehavingError('sent share reply without being sent a request')
478 def get_good_peers(self, max_count):
480 return [x[0] for x in sorted(self.addr_store.iteritems(), key=lambda (k, (services, first_seen, last_seen)):
481 -math.log(max(3600, last_seen - first_seen))/math.log(max(3600, t - last_seen))*random.expovariate(1)