1 from __future__ import division
6 from twisted.internet import defer, protocol, reactor
7 from twisted.python import log
10 from p2pool import data as p2pool_data
11 from p2pool.bitcoin import data as bitcoin_data
12 from p2pool.util import deferral, p2protocol, pack
14 class PeerMisbehavingError(Exception):
17 class Protocol(p2protocol.Protocol):
18 def __init__(self, node, incoming):
19 p2protocol.Protocol.__init__(self, node.net.PREFIX, 1000000)
21 self.incoming = incoming
23 self.other_version = None
24 self.connected2 = False
26 def connectionMade(self):
27 self.factory.proto_made_connection(self)
29 self.addr = self.transport.getPeer().host, self.transport.getPeer().port
36 address=self.transport.getPeer().host,
37 port=self.transport.getPeer().port,
41 address=self.transport.getHost().host,
42 port=self.transport.getHost().port,
44 nonce=self.node.nonce,
45 sub_version=p2pool.__version__,
47 best_share_hash=self.node.best_share_hash_func(),
50 reactor.callLater(10, self._connect_timeout)
51 self.timeout_delayed = reactor.callLater(100, self._timeout)
53 old_dataReceived = self.dataReceived
54 def new_dataReceived(data):
55 if not self.timeout_delayed.called:
56 self.timeout_delayed.reset(100)
57 old_dataReceived(data)
58 self.dataReceived = new_dataReceived
60 def _connect_timeout(self):
61 if not self.connected2 and self.transport.connected:
62 print 'Handshake timed out, disconnecting from %s:%i' % self.addr
63 self.transport.loseConnection()
65 def packetReceived(self, command, payload2):
67 if command != 'version' and not self.connected2:
68 raise PeerMisbehavingError('first message was not version message')
69 p2protocol.Protocol.packetReceived(self, command, payload2)
70 except PeerMisbehavingError, e:
71 print 'Peer %s:%i misbehaving, will drop and ban. Reason:' % self.addr, e.message
72 self.badPeerHappened()
74 def badPeerHappened(self):
76 print "Bad peer banned:", self.addr
77 self.transport.loseConnection()
78 self.node.bans[self.transport.getPeer().host] = time.time() + 60*60
81 if self.transport.connected:
82 print 'Connection timed out, disconnecting from %s:%i' % self.addr
83 self.transport.loseConnection()
85 @defer.inlineCallbacks
87 while self.connected2:
89 yield deferral.sleep(random.expovariate(1/100))
91 @defer.inlineCallbacks
93 while self.connected2:
94 self.send_addrme(port=self.node.port)
95 #print 'sending addrme'
96 yield deferral.sleep(random.expovariate(1/(100*len(self.node.peers) + 1)))
98 message_version = pack.ComposedType([
99 ('version', pack.IntType(32)),
100 ('services', pack.IntType(64)),
101 ('addr_to', bitcoin_data.address_type),
102 ('addr_from', bitcoin_data.address_type),
103 ('nonce', pack.IntType(64)),
104 ('sub_version', pack.VarStrType()),
105 ('mode', pack.IntType(32)), # always 1 for legacy compatibility
106 ('best_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
108 def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, best_share_hash):
109 if self.other_version is not None:
110 raise PeerMisbehavingError('more than one version message')
112 raise PeerMisbehavingError('peer too old')
114 self.other_version = version
115 self.other_sub_version = sub_version[:512]
116 self.other_services = services
118 if nonce == self.node.nonce:
119 raise PeerMisbehavingError('was connected to self')
120 if nonce in self.node.peers:
122 print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
123 self.transport.loseConnection()
127 self.connected2 = True
128 self.factory.proto_connected(self)
133 if best_share_hash is not None:
134 self.node.handle_share_hashes([best_share_hash], self)
136 message_ping = pack.ComposedType([])
137 def handle_ping(self):
140 message_addrme = pack.ComposedType([
141 ('port', pack.IntType(16)),
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...
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=[
155 services=self.other_services,
159 timestamp=int(time.time()),
163 message_addrs = pack.ComposedType([
164 ('addrs', pack.ListType(pack.ComposedType([
165 ('timestamp', pack.IntType(64)),
166 ('address', bitcoin_data.address_type),
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])
175 message_getaddrs = pack.ComposedType([
176 ('count', pack.IntType(32)),
178 def handle_getaddrs(self, count):
181 self.send_addrs(addrs=[
183 timestamp=int(self.node.addr_store[host, port][2]),
185 services=self.node.addr_store[host, port][0],
190 self.node.get_good_peers(count)
193 message_getshares = pack.ComposedType([
194 ('hashes', pack.ListType(pack.IntType(256))),
195 ('parents', pack.VarIntType()),
196 ('stops', pack.ListType(pack.IntType(256))),
198 def handle_getshares(self, hashes, parents, stops):
199 self.sendShares(self.node.handle_get_shares(hashes, parents, stops, self))
201 message_shares = pack.ComposedType([
202 ('shares', pack.ListType(p2pool_data.share_type)),
204 def handle_shares(self, shares):
205 self.node.handle_shares([p2pool_data.load_share(share, self.node.net, self) for share in shares], self)
207 def sendShares(self, shares):
208 def att(f, **kwargs):
211 except p2protocol.TooLong:
212 att(f, **dict((k, v[:len(v)//2]) for k, v in kwargs.iteritems()))
213 att(f, **dict((k, v[len(v)//2:]) for k, v in kwargs.iteritems()))
215 att(self.send_shares, shares=[share.as_share() for share in shares])
218 message_sharereq = pack.ComposedType([
219 ('id', pack.IntType(256)),
220 ('hashes', pack.ListType(pack.IntType(256))),
221 ('parents', pack.VarIntType()),
222 ('stops', pack.ListType(pack.IntType(256))),
224 def handle_sharereq(self, id, hashes, parents, stops):
225 shares = self.node.handle_get_shares(hashes, parents, stops, self)
227 self.send_sharereply(id=id, result='good', shares=[share.as_share() for share in shares])
228 except p2protocol.TooLong:
229 self.send_sharereply(id=id, result='too long', shares=[])
231 message_sharereply = pack.ComposedType([
232 ('id', pack.IntType(256)),
233 ('result', pack.EnumType(pack.VarIntType(), {'good': 0, 'too long': 1, 'unk2': 2, 'unk2': 3, 'unk2': 4, 'unk2': 5, 'unk2': 6})),
234 ('shares', pack.ListType(p2pool_data.share_type)),
236 def handle_sharereply(self, id, result, shares):
237 self.node.handle_share_reply(id, result, shares, self)
240 def connectionLost(self, reason):
242 self.factory.proto_disconnected(self, reason)
243 self.connected2 = False
244 self.factory.proto_lost_connection(self, reason)
246 print "Peer connection lost:", self.addr, reason
248 class ServerFactory(protocol.ServerFactory):
249 def __init__(self, node, max_conns):
251 self.max_conns = max_conns
256 def buildProtocol(self, addr):
257 if sum(self.conns.itervalues()) >= self.max_conns or self.conns.get(self._host_to_ident(addr.host), 0) >= 3:
259 if addr.host in self.node.bans and self.node.bans[addr.host] > time.time():
261 p = Protocol(self.node, True)
264 print "Got peer connection from:", addr
267 def _host_to_ident(self, host):
268 a, b, c, d = host.split('.')
271 def proto_made_connection(self, proto):
272 ident = self._host_to_ident(proto.transport.getPeer().host)
273 self.conns[ident] = self.conns.get(ident, 0) + 1
274 def proto_lost_connection(self, proto, reason):
275 ident = self._host_to_ident(proto.transport.getPeer().host)
276 self.conns[ident] -= 1
277 if not self.conns[ident]:
278 del self.conns[ident]
280 def proto_connected(self, proto):
281 self.node.got_conn(proto)
282 def proto_disconnected(self, proto, reason):
283 self.node.lost_conn(proto, reason)
286 assert not self.running
289 def attempt_listen():
291 self.listen_port = reactor.listenTCP(self.node.port, self)
292 deferral.retry('Error binding to P2P port:', traceback=False)(attempt_listen)()
298 self.listen_port.stopListening()
300 class ClientFactory(protocol.ClientFactory):
301 def __init__(self, node, desired_conns, max_attempts):
303 self.desired_conns = desired_conns
304 self.max_attempts = max_attempts
306 self.attempts = set()
310 def _host_to_ident(self, host):
311 a, b, c, d = host.split('.')
314 def buildProtocol(self, addr):
315 p = Protocol(self.node, False)
319 def startedConnecting(self, connector):
320 ident = self._host_to_ident(connector.getDestination().host)
321 if ident in self.attempts:
322 raise AssertionError('already have attempt')
323 self.attempts.add(ident)
325 def clientConnectionFailed(self, connector, reason):
326 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
328 def clientConnectionLost(self, connector, reason):
329 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
331 def proto_made_connection(self, proto):
333 def proto_lost_connection(self, proto, reason):
336 def proto_connected(self, proto):
337 self.conns.add(proto)
338 self.node.got_conn(proto)
339 def proto_disconnected(self, proto, reason):
340 self.conns.remove(proto)
341 self.node.lost_conn(proto, reason)
344 assert not self.running
351 @defer.inlineCallbacks
355 if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and self.node.addr_store:
356 (host, port), = self.node.get_good_peers(1)
358 if self._host_to_ident(host) in self.attempts:
360 elif host in self.node.bans and self.node.bans[host] > time.time():
363 #print 'Trying to connect to', host, port
364 reactor.connectTCP(host, port, self, timeout=5)
368 yield deferral.sleep(random.expovariate(1/1))
370 class SingleClientFactory(protocol.ReconnectingClientFactory):
371 def __init__(self, node):
374 def buildProtocol(self, addr):
375 p = Protocol(self.node, incoming=False)
379 def proto_made_connection(self, proto):
381 def proto_lost_connection(self, proto, reason):
384 def proto_connected(self, proto):
386 self.node.got_conn(proto)
387 def proto_disconnected(self, proto, reason):
388 self.node.lost_conn(proto, reason)
391 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):
392 self.best_share_hash_func = best_share_hash_func
395 self.addr_store = dict(addr_store)
396 self.connect_addrs = connect_addrs
397 self.preferred_storage = preferred_storage
399 self.nonce = random.randrange(2**64)
401 self.bans = {} # address -> end_time
402 self.clientfactory = ClientFactory(self, desired_outgoing_conns, max_outgoing_attempts)
403 self.serverfactory = ServerFactory(self, max_incoming_conns)
408 raise ValueError('already running')
410 self.clientfactory.start()
411 self.serverfactory.start()
412 self.singleclientconnectors = [reactor.connectTCP(addr, port, SingleClientFactory(self)) for addr, port in self.connect_addrs]
418 @defer.inlineCallbacks
422 if len(self.addr_store) < self.preferred_storage and self.peers:
423 random.choice(self.peers.values()).send_getaddrs(count=8)
427 yield deferral.sleep(random.expovariate(1/20))
431 raise ValueError('already stopped')
435 self.clientfactory.stop()
436 self.serverfactory.stop()
437 for singleclientconnector in self.singleclientconnectors:
438 singleclientconnector.factory.stopTrying() # XXX will this disconnect a current connection?
439 del self.singleclientconnectors
441 def got_conn(self, conn):
442 if conn.nonce in self.peers:
443 raise ValueError('already have peer')
444 self.peers[conn.nonce] = conn
446 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)
448 def lost_conn(self, conn, reason):
449 if conn.nonce not in self.peers:
450 raise ValueError('''don't have peer''')
451 if conn is not self.peers[conn.nonce]:
452 raise ValueError('wrong conn')
453 del self.peers[conn.nonce]
455 print 'Lost peer %s:%i - %s' % (conn.addr[0], conn.addr[1], reason.getErrorMessage())
458 def got_addr(self, (host, port), services, timestamp):
459 if (host, port) in self.addr_store:
460 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
461 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
463 self.addr_store[host, port] = services, timestamp, timestamp
465 def handle_shares(self, shares, peer):
466 print 'handle_shares', (shares, peer)
468 def handle_share_hashes(self, hashes, peer):
469 print 'handle_share_hashes', (hashes, peer)
471 def handle_get_shares(self, hashes, parents, stops, peer):
472 print 'handle_get_shares', (hashes, parents, stops, peer)
474 def handle_share_reply(self, id, result, shares, peer):
475 raise PeerMisbehavingError('sent share reply without being sent a request')
477 def get_good_peers(self, max_count):
479 return [x[0] for x in sorted(self.addr_store.iteritems(), key=lambda (k, (services, first_seen, last_seen)): -max(3600, last_seen - first_seen)/max(3600, t - last_seen)*random.expovariate(1))][:max_count]
481 if __name__ == '__main__':
482 p = random.randrange(2**15, 2**16)
484 p2 = random.randrange(2**15, 2**16)
486 n = Node(p2, True, {addrdb_key.pack(dict(address='127.0.0.1', port=p)): addrdb_value.pack(dict(services=0, first_seen=int(time.time())-10, last_seen=int(time.time())))})