1 from __future__ import division
7 from twisted.internet import defer, error, protocol, reactor
8 from twisted.python import log
11 from p2pool import data as p2pool_data
12 from p2pool.bitcoin import p2p as bitcoin_p2p
13 from p2pool.bitcoin import data as bitcoin_data
14 from p2pool.util import deferral, pack
16 class Protocol(bitcoin_p2p.BaseProtocol):
18 sub_version = p2pool.__version__
20 def __init__(self, node, incoming):
21 bitcoin_p2p.BaseProtocol.__init__(self, node.net.PREFIX, 1000000)
23 self.incoming = incoming
28 def connectionMade(self):
29 self.factory.proto_made_connection(self)
31 self.addr = self.transport.getPeer().host, self.transport.getPeer().port
38 address=self.transport.getPeer().host,
39 port=self.transport.getPeer().port,
43 address=self.transport.getHost().host,
44 port=self.transport.getHost().port,
46 nonce=self.node.nonce,
47 sub_version=self.sub_version,
49 best_share_hash=self.node.best_share_hash_func(),
52 reactor.callLater(10, self._connect_timeout)
53 self.timeout_delayed = reactor.callLater(100, self._timeout)
55 old_dataReceived = self.dataReceived
56 def new_dataReceived(data):
57 if not self.timeout_delayed.called:
58 self.timeout_delayed.reset(100)
59 old_dataReceived(data)
60 self.dataReceived = new_dataReceived
62 def _connect_timeout(self):
63 if not self.connected2 and self.transport.connected:
64 print 'Handshake timed out, disconnecting from %s:%i' % self.addr
65 self.transport.loseConnection()
67 def packetReceived(self, command, payload2):
68 if command != 'version' and not self.connected2:
69 self.transport.loseConnection()
72 bitcoin_p2p.BaseProtocol.packetReceived(self, command, payload2)
75 if self.transport.connected:
76 print 'Connection timed out, disconnecting from %s:%i' % self.addr
77 self.transport.loseConnection()
79 @defer.inlineCallbacks
81 while self.connected2:
83 yield deferral.sleep(random.expovariate(1/100))
85 @defer.inlineCallbacks
87 while self.connected2:
88 self.send_addrme(port=self.node.port)
89 #print 'sending addrme'
90 yield deferral.sleep(random.expovariate(1/(100*len(self.node.peers) + 1)))
92 message_version = pack.ComposedType([
93 ('version', pack.IntType(32)),
94 ('services', pack.IntType(64)),
95 ('addr_to', bitcoin_data.address_type),
96 ('addr_from', bitcoin_data.address_type),
97 ('nonce', pack.IntType(64)),
98 ('sub_version', pack.VarStrType()),
99 ('mode', pack.IntType(32)), # always 1 for legacy compatibility
100 ('best_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
102 def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, best_share_hash):
103 if self.other_version is not None or version < 2:
104 self.transport.loseConnection()
107 self.other_version = version
108 self.other_sub_version = sub_version[:512]
109 self.other_services = services
111 if nonce == self.node.nonce:
112 #print 'Detected connection to self, disconnecting from %s:%i' % self.addr
113 self.transport.loseConnection()
115 if nonce in self.node.peers:
116 #print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
117 self.transport.loseConnection()
121 self.connected2 = True
122 self.factory.proto_connected(self)
127 if best_share_hash is not None:
128 self.node.handle_share_hashes([best_share_hash], self)
130 message_ping = pack.ComposedType([])
131 def handle_ping(self):
134 message_addrme = pack.ComposedType([
135 ('port', pack.IntType(16)),
137 def handle_addrme(self, port):
138 host = self.transport.getPeer().host
139 #print 'addrme from', host, port
140 if host == '127.0.0.1':
141 if random.random() < .8 and self.node.peers:
142 random.choice(self.node.peers.values()).send_addrme(port=port) # services...
144 self.node.got_addr((self.transport.getPeer().host, port), self.other_services, int(time.time()))
145 if random.random() < .8 and self.node.peers:
146 random.choice(self.node.peers.values()).send_addrs(addrs=[
149 services=self.other_services,
153 timestamp=int(time.time()),
157 message_addrs = pack.ComposedType([
158 ('addrs', pack.ListType(pack.ComposedType([
159 ('timestamp', pack.IntType(64)),
160 ('address', bitcoin_data.address_type),
163 def handle_addrs(self, addrs):
164 for addr_record in addrs:
165 self.node.got_addr((addr_record['address']['address'], addr_record['address']['port']), addr_record['address']['services'], min(int(time.time()), addr_record['timestamp']))
166 if random.random() < .8 and self.node.peers:
167 random.choice(self.node.peers.values()).send_addrs(addrs=[addr_record])
169 message_getaddrs = pack.ComposedType([
170 ('count', pack.IntType(32)),
172 def handle_getaddrs(self, count):
175 self.send_addrs(addrs=[
177 timestamp=self.node.addr_store[host, port][2],
179 services=self.node.addr_store[host, port][0],
184 self.node.get_good_peers(count)
187 message_getshares = pack.ComposedType([
188 ('hashes', pack.ListType(pack.IntType(256))),
189 ('parents', pack.VarIntType()),
190 ('stops', pack.ListType(pack.IntType(256))),
192 def handle_getshares(self, hashes, parents, stops):
193 self.node.handle_get_shares(hashes, parents, stops, self)
195 message_shares = pack.ComposedType([
196 ('shares', pack.ListType(p2pool_data.share_type)),
198 def handle_shares(self, shares):
201 share_obj = p2pool_data.Share.from_share(share, self.node.net)
202 share_obj.peer = self
203 res.append(share_obj)
204 self.node.handle_shares(res, self)
206 def sendShares(self, shares, full=False):
207 def att(f, **kwargs):
210 except bitcoin_p2p.TooLong:
211 att(f, **dict((k, v[:len(v)//2]) for k, v in kwargs.iteritems()))
212 att(f, **dict((k, v[len(v)//2:]) for k, v in kwargs.iteritems()))
214 att(self.send_shares, shares=[share.as_share() for share in shares])
216 def connectionLost(self, reason):
218 self.factory.proto_disconnected(self, reason)
219 self.connected2 = False
220 self.factory.proto_lost_connection(self, reason)
222 class ServerFactory(protocol.ServerFactory):
223 def __init__(self, node, max_conns):
225 self.max_conns = max_conns
230 def buildProtocol(self, addr):
231 if sum(self.conns.itervalues()) >= self.max_conns or self.conns.get(self._host_to_ident(addr.host), 0) >= 3:
233 p = Protocol(self.node, True)
237 def _host_to_ident(self, host):
238 a, b, c, d = host.split('.')
241 def proto_made_connection(self, proto):
242 ident = self._host_to_ident(proto.transport.getPeer().host)
243 self.conns[ident] = self.conns.get(ident, 0) + 1
244 def proto_lost_connection(self, proto, reason):
245 ident = self._host_to_ident(proto.transport.getPeer().host)
246 self.conns[ident] -= 1
247 if not self.conns[ident]:
248 del self.conns[ident]
250 def proto_connected(self, proto):
251 self.node.got_conn(proto)
252 def proto_disconnected(self, proto, reason):
253 self.node.lost_conn(proto, reason)
256 assert not self.running
259 def attempt_listen():
263 self.listen_port = reactor.listenTCP(self.node.port, self)
264 except error.CannotListenError, e:
265 print >>sys.stderr, 'Error binding to P2P port: %s. Retrying in 3 seconds.' % (e.socketError,)
266 reactor.callLater(3, attempt_listen)
273 self.listen_port.stopListening()
275 class ClientFactory(protocol.ClientFactory):
276 def __init__(self, node, desired_conns, max_attempts):
278 self.desired_conns = desired_conns
279 self.max_attempts = max_attempts
281 self.attempts = set()
285 def _host_to_ident(self, host):
286 a, b, c, d = host.split('.')
289 def buildProtocol(self, addr):
290 p = Protocol(self.node, False)
294 def startedConnecting(self, connector):
295 ident = self._host_to_ident(connector.getDestination().host)
296 if ident in self.attempts:
297 raise AssertionError('already have attempt')
298 self.attempts.add(ident)
300 def clientConnectionFailed(self, connector, reason):
301 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
303 def clientConnectionLost(self, connector, reason):
304 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
306 def proto_made_connection(self, proto):
308 def proto_lost_connection(self, proto, reason):
311 def proto_connected(self, proto):
312 self.conns.add(proto)
313 self.node.got_conn(proto)
314 def proto_disconnected(self, proto, reason):
315 self.conns.remove(proto)
316 self.node.lost_conn(proto, reason)
319 assert not self.running
326 @defer.inlineCallbacks
330 if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and self.node.addr_store:
331 (host, port), = self.node.get_good_peers(1)
333 if self._host_to_ident(host) not in self.attempts:
334 #print 'Trying to connect to', host, port
335 reactor.connectTCP(host, port, self, timeout=5)
339 yield deferral.sleep(random.expovariate(1/1))
341 class SingleClientFactory(protocol.ReconnectingClientFactory):
342 def __init__(self, node):
345 def buildProtocol(self, addr):
346 p = Protocol(self.node, incoming=False)
350 def proto_made_connection(self, proto):
352 def proto_lost_connection(self, proto, reason):
355 def proto_connected(self, proto):
357 self.node.got_conn(proto)
358 def proto_disconnected(self, proto, reason):
359 self.node.lost_conn(proto, reason)
362 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):
363 self.best_share_hash_func = best_share_hash_func
366 self.addr_store = dict(addr_store)
367 self.connect_addrs = connect_addrs
368 self.preferred_storage = preferred_storage
370 self.nonce = random.randrange(2**64)
372 self.clientfactory = ClientFactory(self, desired_outgoing_conns, max_outgoing_attempts)
373 self.serverfactory = ServerFactory(self, max_incoming_conns)
378 raise ValueError('already running')
380 self.clientfactory.start()
381 self.serverfactory.start()
382 self.singleclientconnectors = [reactor.connectTCP(addr, port, SingleClientFactory(self)) for addr, port in self.connect_addrs]
388 @defer.inlineCallbacks
392 if len(self.addr_store) < self.preferred_storage and self.peers:
393 random.choice(self.peers.values()).send_getaddrs(count=8)
397 yield deferral.sleep(random.expovariate(1/20))
401 raise ValueError('already stopped')
405 self.clientfactory.stop()
406 self.serverfactory.stop()
407 for singleclientconnector in self.singleclientconnectors:
408 singleclientconnector.factory.stopTrying() # XXX will this disconnect a current connection?
409 del self.singleclientconnectors
411 def got_conn(self, conn):
412 if conn.nonce in self.peers:
413 raise ValueError('already have peer')
414 self.peers[conn.nonce] = conn
416 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)
418 def lost_conn(self, conn, reason):
419 if conn.nonce not in self.peers:
420 raise ValueError('''don't have peer''')
421 if conn is not self.peers[conn.nonce]:
422 raise ValueError('wrong conn')
423 del self.peers[conn.nonce]
425 print 'Lost peer %s:%i - %s' % (conn.addr[0], conn.addr[1], reason.getErrorMessage())
428 def got_addr(self, (host, port), services, timestamp):
429 if (host, port) in self.addr_store:
430 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
431 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
433 self.addr_store[host, port] = services, timestamp, timestamp
435 def handle_shares(self, shares, peer):
436 print 'handle_shares', (shares, peer)
438 def handle_share_hashes(self, hashes, peer):
439 print 'handle_share_hashes', (hashes, peer)
441 def handle_get_shares(self, hashes, parents, stops, peer):
442 print 'handle_get_shares', (hashes, parents, stops, peer)
444 def get_good_peers(self, max_count):
446 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]
448 if __name__ == '__main__':
449 p = random.randrange(2**15, 2**16)
451 p2 = random.randrange(2**15, 2**16)
453 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())))})