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):
22 self.incoming = incoming
24 self._prefix = self.node.net.PREFIX
26 max_payload_length = 1000000
32 def connectionMade(self):
33 bitcoin_p2p.BaseProtocol.connectionMade(self)
35 self.factory.proto_made_connection(self)
37 self.addr = self.transport.getPeer().host, self.transport.getPeer().port
44 address=self.transport.getPeer().host,
45 port=self.transport.getPeer().port,
49 address=self.transport.getHost().host,
50 port=self.transport.getHost().port,
52 nonce=self.node.nonce,
53 sub_version=self.sub_version,
55 best_share_hash=self.node.best_share_hash_func(),
58 reactor.callLater(10, self._connect_timeout)
59 self.timeout_delayed = reactor.callLater(100, self._timeout)
61 old_dataReceived = self.dataReceived
62 self.dataReceived = lambda data: (self.timeout_delayed.reset(100) if not self.timeout_delayed.called else None, old_dataReceived(data))[0]
64 def _connect_timeout(self):
65 if not self.connected2 and self.transport.connected:
66 print 'Handshake timed out, disconnecting from %s:%i' % self.addr
67 self.transport.loseConnection()
69 def packetReceived(self, command, payload2):
70 if command != 'version' and not self.connected2:
71 self.transport.loseConnection()
74 bitcoin_p2p.BaseProtocol.packetReceived(self, command, payload2)
77 if self.transport.connected:
78 print 'Connection timed out, disconnecting from %s:%i' % self.addr
79 self.transport.loseConnection()
81 @defer.inlineCallbacks
83 while self.connected2:
85 yield deferral.sleep(random.expovariate(1/100))
87 @defer.inlineCallbacks
89 while self.connected2:
90 self.send_addrme(port=self.node.port)
91 #print 'sending addrme'
92 yield deferral.sleep(random.expovariate(1/(100*len(self.node.peers) + 1)))
94 message_version = pack.ComposedType([
95 ('version', pack.IntType(32)),
96 ('services', pack.IntType(64)),
97 ('addr_to', bitcoin_data.address_type),
98 ('addr_from', bitcoin_data.address_type),
99 ('nonce', pack.IntType(64)),
100 ('sub_version', pack.VarStrType()),
101 ('mode', pack.IntType(32)), # always 1 for legacy compatibility
102 ('best_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
104 def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, best_share_hash):
105 if self.other_version is not None or version < 2:
106 self.transport.loseConnection()
109 self.other_version = version
110 self.other_sub_version = sub_version[:512]
111 self.other_services = services
113 if nonce == self.node.nonce:
114 #print 'Detected connection to self, disconnecting from %s:%i' % self.addr
115 self.transport.loseConnection()
117 if nonce in self.node.peers:
118 #print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
119 self.transport.loseConnection()
123 self.connected2 = True
124 self.factory.proto_connected(self)
129 if best_share_hash is not None:
130 self.node.handle_share_hashes([best_share_hash], self)
132 message_ping = pack.ComposedType([])
133 def handle_ping(self):
136 message_addrme = pack.ComposedType([
137 ('port', pack.IntType(16)),
139 def handle_addrme(self, port):
140 host = self.transport.getPeer().host
141 #print 'addrme from', host, port
142 if host == '127.0.0.1':
143 if random.random() < .8 and self.node.peers:
144 random.choice(self.node.peers.values()).send_addrme(port=port) # services...
146 self.node.got_addr((self.transport.getPeer().host, port), self.other_services, int(time.time()))
147 if random.random() < .8 and self.node.peers:
148 random.choice(self.node.peers.values()).send_addrs(addrs=[
151 services=self.other_services,
155 timestamp=int(time.time()),
159 message_addrs = pack.ComposedType([
160 ('addrs', pack.ListType(pack.ComposedType([
161 ('timestamp', pack.IntType(64)),
162 ('address', bitcoin_data.address_type),
165 def handle_addrs(self, addrs):
166 for addr_record in addrs:
167 self.node.got_addr((addr_record['address']['address'], addr_record['address']['port']), addr_record['address']['services'], min(int(time.time()), addr_record['timestamp']))
168 if random.random() < .8 and self.node.peers:
169 random.choice(self.node.peers.values()).send_addrs(addrs=[addr_record])
171 message_getaddrs = pack.ComposedType([
172 ('count', pack.IntType(32)),
174 def handle_getaddrs(self, count):
177 self.send_addrs(addrs=[
179 timestamp=self.node.addr_store[host, port][2],
181 services=self.node.addr_store[host, port][0],
186 self.node.get_good_peers(count)
189 message_getshares = pack.ComposedType([
190 ('hashes', pack.ListType(pack.IntType(256))),
191 ('parents', pack.VarIntType()),
192 ('stops', pack.ListType(pack.IntType(256))),
194 def handle_getshares(self, hashes, parents, stops):
195 self.node.handle_get_shares(hashes, parents, stops, self)
197 message_shares = pack.ComposedType([
198 ('shares', pack.ListType(p2pool_data.share_type)),
200 def handle_shares(self, shares):
203 share_obj = p2pool_data.Share.from_share(share, self.node.net)
204 share_obj.peer = self
205 res.append(share_obj)
206 self.node.handle_shares(res, self)
208 def sendShares(self, shares, full=False):
209 def att(f, **kwargs):
212 except bitcoin_p2p.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])
218 def connectionLost(self, reason):
220 self.factory.proto_disconnected(self)
221 self.connected2 = False
222 self.factory.proto_lost_connection(self)
224 class ServerFactory(protocol.ServerFactory):
225 def __init__(self, node, max_conns):
227 self.max_conns = max_conns
232 def buildProtocol(self, addr):
233 if len(self.conns) >= self.max_conns:
235 p = Protocol(self.node, True)
239 def proto_made_connection(self, proto):
240 self.conns.add(proto)
241 def proto_lost_connection(self, proto):
242 self.conns.remove(proto)
244 def proto_connected(self, proto):
245 self.node.got_conn(proto)
246 def proto_disconnected(self, proto):
247 self.node.lost_conn(proto)
250 assert not self.running
253 def attempt_listen():
257 self.listen_port = reactor.listenTCP(self.node.port, self)
258 except error.CannotListenError, e:
259 print >>sys.stderr, 'Error binding to P2P port: %s. Retrying in 3 seconds.' % (e.socketError,)
260 reactor.callLater(3, attempt_listen)
267 self.listen_port.stopListening()
269 class ClientFactory(protocol.ClientFactory):
270 def __init__(self, node, desired_conns, max_attempts):
272 self.desired_conns = desired_conns
273 self.max_attempts = max_attempts
279 def buildProtocol(self, addr):
280 p = Protocol(self.node, False)
284 def startedConnecting(self, connector):
285 host, port = connector.getDestination().host, connector.getDestination().port
286 if (host, port) in self.attempts:
287 raise ValueError('already have attempt')
288 self.attempts[host, port] = connector
290 def clientConnectionFailed(self, connector, reason):
291 self.clientConnectionLost(connector, reason)
293 def clientConnectionLost(self, connector, reason):
294 host, port = connector.getDestination().host, connector.getDestination().port
295 if (host, port) not in self.attempts:
296 raise ValueError('''don't have attempt''')
297 if connector is not self.attempts[host, port]:
298 raise ValueError('wrong connector')
299 del self.attempts[host, port]
301 def proto_made_connection(self, proto):
303 def proto_lost_connection(self, proto):
306 def proto_connected(self, proto):
307 self.conns.add(proto)
308 self.node.got_conn(proto)
309 def proto_disconnected(self, proto):
310 self.conns.remove(proto)
311 self.node.lost_conn(proto)
314 assert not self.running
321 @defer.inlineCallbacks
325 if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and self.node.addr_store:
326 (host, port), = self.node.get_good_peers(1)
328 if (host, port) not in self.attempts:
329 #print 'Trying to connect to', host, port
330 reactor.connectTCP(host, port, self, timeout=5)
334 yield deferral.sleep(random.expovariate(1/1))
336 class SingleClientFactory(protocol.ReconnectingClientFactory):
337 def __init__(self, node):
340 def buildProtocol(self, addr):
341 p = Protocol(self.node, incoming=False)
345 def proto_made_connection(self, proto):
347 def proto_lost_connection(self, proto):
350 def proto_connected(self, proto):
352 self.node.got_conn(proto)
353 def proto_disconnected(self, proto):
354 self.node.lost_conn(proto)
357 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):
358 self.best_share_hash_func = best_share_hash_func
361 self.addr_store = dict(addr_store)
362 self.connect_addrs = connect_addrs
363 self.preferred_storage = preferred_storage
365 self.nonce = random.randrange(2**64)
367 self.clientfactory = ClientFactory(self, desired_outgoing_conns, max_outgoing_attempts)
368 self.serverfactory = ServerFactory(self, max_incoming_conns)
373 raise ValueError('already running')
375 self.clientfactory.start()
376 self.serverfactory.start()
377 self.singleclientconnectors = [reactor.connectTCP(addr, port, SingleClientFactory(self)) for addr, port in self.connect_addrs]
383 @defer.inlineCallbacks
387 if len(self.addr_store) < self.preferred_storage and self.peers:
388 random.choice(self.peers.values()).send_getaddrs(count=8)
392 yield deferral.sleep(random.expovariate(1/20))
396 raise ValueError('already stopped')
400 self.clientfactory.stop()
401 self.serverfactory.stop()
402 for singleclientconnector in self.singleclientconnectors:
403 singleclientconnector.factory.stopTrying() # XXX will this disconnect a current connection?
404 del self.singleclientconnectors
406 def got_conn(self, conn):
407 if conn.nonce in self.peers:
408 raise ValueError('already have peer')
409 self.peers[conn.nonce] = conn
411 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)
413 def lost_conn(self, conn):
414 if conn.nonce not in self.peers:
415 raise ValueError('''don't have peer''')
416 if conn is not self.peers[conn.nonce]:
417 raise ValueError('wrong conn')
418 del self.peers[conn.nonce]
420 print 'Lost peer %s:%i' % (conn.addr[0], conn.addr[1])
423 def got_addr(self, (host, port), services, timestamp):
424 if (host, port) in self.addr_store:
425 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
426 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
428 self.addr_store[host, port] = services, timestamp, timestamp
430 def handle_shares(self, shares, peer):
431 print 'handle_shares', (shares, peer)
433 def handle_share_hashes(self, hashes, peer):
434 print 'handle_share_hashes', (hashes, peer)
436 def handle_get_shares(self, hashes, parents, stops, peer):
437 print 'handle_get_shares', (hashes, parents, stops, peer)
439 def get_good_peers(self, max_count):
441 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]
443 if __name__ == '__main__':
444 p = random.randrange(2**15, 2**16)
446 p2 = random.randrange(2**15, 2**16)
448 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())))})