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 p2p as bitcoin_p2p
12 from p2pool.bitcoin import data as bitcoin_data
13 from p2pool.util import deferral
15 class Protocol(bitcoin_p2p.BaseProtocol):
17 sub_version = p2pool.__version__
19 def __init__(self, node):
22 self._prefix = self.node.net.PREFIX
24 max_payload_length = 1000000
30 def connectionMade(self):
31 bitcoin_p2p.BaseProtocol.connectionMade(self)
33 self.node.conns.add(self)
35 self.addr = self.transport.getPeer().host, self.transport.getPeer().port
42 address=self.transport.getPeer().host,
43 port=self.transport.getPeer().port,
47 address=self.transport.getHost().host,
48 port=self.transport.getHost().port,
50 nonce=self.node.nonce,
51 sub_version=self.sub_version,
53 best_share_hash=self.node.current_work.value['best_share_hash'],
56 reactor.callLater(10, self._connect_timeout)
57 self.timeout_delayed = reactor.callLater(100, self._timeout)
59 def _connect_timeout(self):
60 if not self.connected2 and self.transport.connected:
61 print 'Handshake timed out, disconnecting from %s:%i' % self.addr
62 self.transport.loseConnection()
65 if not self.timeout_delayed.called:
66 self.timeout_delayed.cancel()
67 self.timeout_delayed = reactor.callLater(100, self._timeout)
70 if self.transport.connected:
71 print 'Connection timed out, disconnecting from %s:%i' % self.addr
72 self.transport.loseConnection()
74 @defer.inlineCallbacks
76 while self.connected2:
78 yield deferral.sleep(random.expovariate(1/100))
80 @defer.inlineCallbacks
82 while self.connected2:
83 self.send_addrme(port=self.node.port)
84 #print 'sending addrme'
85 yield deferral.sleep(random.expovariate(1/(100*len(self.node.peers) + 1)))
87 message_version = bitcoin_data.ComposedType([
88 ('version', bitcoin_data.StructType('<I')),
89 ('services', bitcoin_data.StructType('<Q')),
90 ('addr_to', bitcoin_data.address_type),
91 ('addr_from', bitcoin_data.address_type),
92 ('nonce', bitcoin_data.StructType('<Q')),
93 ('sub_version', bitcoin_data.VarStrType()),
94 ('mode', bitcoin_data.StructType('<I')), # always 1 for legacy compatibility
95 ('best_share_hash', bitcoin_data.PossiblyNoneType(0, bitcoin_data.HashType())),
97 def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, best_share_hash):
98 self.other_version = version
99 self.other_sub_version = sub_version[:512]
100 self.other_services = services
102 if nonce == self.node.nonce:
103 #print 'Detected connection to self, disconnecting from %s:%i' % self.addr
104 self.transport.loseConnection()
106 if nonce in self.node.peers:
107 #print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
108 self.transport.loseConnection()
112 self.connected2 = True
113 self.node.got_conn(self)
118 if best_share_hash is not None:
119 self.node.handle_share_hashes([best_share_hash], self)
121 message_ping = bitcoin_data.ComposedType([])
122 def handle_ping(self):
125 message_addrme = bitcoin_data.ComposedType([
126 ('port', bitcoin_data.StructType('<H')),
128 def handle_addrme(self, port):
129 host = self.transport.getPeer().host
130 #print 'addrme from', host, port
131 if host == '127.0.0.1':
132 if random.random() < .8 and self.node.peers:
133 random.choice(self.node.peers.values()).send_addrme(port=port) # services...
135 self.node.got_addr((self.transport.getPeer().host, port), self.other_services, int(time.time()))
136 if random.random() < .8 and self.node.peers:
137 random.choice(self.node.peers.values()).send_addrs(addrs=[
140 services=self.other_services,
144 timestamp=int(time.time()),
148 message_addrs = bitcoin_data.ComposedType([
149 ('addrs', bitcoin_data.ListType(bitcoin_data.ComposedType([
150 ('timestamp', bitcoin_data.StructType('<Q')),
151 ('address', bitcoin_data.address_type),
154 def handle_addrs(self, addrs):
155 for addr_record in addrs:
156 self.node.got_addr((addr_record['address']['address'], addr_record['address']['port']), addr_record['address']['services'], min(int(time.time()), addr_record['timestamp']))
157 if random.random() < .8 and self.node.peers:
158 random.choice(self.node.peers.values()).send_addrs(addrs=[addr_record])
160 message_getaddrs = bitcoin_data.ComposedType([
161 ('count', bitcoin_data.StructType('<I')),
163 def handle_getaddrs(self, count):
166 self.send_addrs(addrs=[
168 timestamp=self.node.addr_store[host, port][2],
170 services=self.node.addr_store[host, port][0],
175 self.node.get_good_peers(count)
178 message_getshares = bitcoin_data.ComposedType([
179 ('hashes', bitcoin_data.ListType(bitcoin_data.HashType())),
180 ('parents', bitcoin_data.VarIntType()),
181 ('stops', bitcoin_data.ListType(bitcoin_data.HashType())),
183 def handle_getshares(self, hashes, parents, stops):
184 self.node.handle_get_shares(hashes, parents, stops, self)
186 message_shares = bitcoin_data.ComposedType([
187 ('shares', bitcoin_data.ListType(p2pool_data.share_type)),
189 def handle_shares(self, shares):
192 share_obj = p2pool_data.Share.from_share(share, self.node.net)
193 share_obj.peer = self
194 res.append(share_obj)
195 self.node.handle_shares(res)
197 def sendShares(self, shares, full=False):
198 def att(f, **kwargs):
201 except bitcoin_p2p.TooLong:
202 att(f, **dict((k, v[:len(v)//2]) for k, v in kwargs.iteritems()))
203 att(f, **dict((k, v[len(v)//2:]) for k, v in kwargs.iteritems()))
205 att(self.send_shares, shares=[share.as_share() for share in shares])
207 def connectionLost(self, reason):
208 self.node.conns.remove(self)
210 self.node.lost_conn(self)
211 self.connected2 = False
213 class ServerFactory(protocol.ServerFactory):
214 def __init__(self, node):
217 def buildProtocol(self, addr):
218 if len(self.node.conns) >= self.node.max_conns:
220 p = Protocol(self.node)
224 class ClientFactory(protocol.ClientFactory):
225 def __init__(self, node):
228 def buildProtocol(self, addr):
229 p = Protocol(self.node)
233 def startedConnecting(self, connector):
234 self.node.attempt_started(connector)
236 def clientConnectionFailed(self, connector, reason):
237 self.node.attempt_failed(connector)
239 def clientConnectionLost(self, connector, reason):
240 self.node.attempt_ended(connector)
243 def __init__(self, current_work, port, net, addr_store=None, preferred_addrs=set(), desired_peers=10, max_conns=50, max_attempts=30, preferred_storage=1000):
244 if addr_store is None:
249 self.addr_store = addr_store
250 self.preferred_addrs = preferred_addrs
251 self.desired_peers = desired_peers
252 self.max_conns = max_conns
253 self.max_attempts = max_attempts
254 self.current_work = current_work
255 self.preferred_storage = preferred_storage
257 self.nonce = random.randrange(2**64)
265 raise ValueError('already running')
269 self.listen_port = reactor.listenTCP(self.port, ServerFactory(self))
274 @defer.inlineCallbacks
278 if len(self.peers) < self.desired_peers and len(self.attempts) < self.max_attempts and (len(self.preferred_addrs) or len(self.addr_store)):
279 if (random.randrange(2) and len(self.preferred_addrs)) or not len(self.addr_store):
280 host, port = random.choice(list(self.preferred_addrs))
282 (host, port), = self.get_good_peers(1)
284 if (host, port) not in self.attempts:
285 #print 'Trying to connect to', host, port
286 reactor.connectTCP(host, port, ClientFactory(self), timeout=5)
290 yield deferral.sleep(random.expovariate(1/1))
292 @defer.inlineCallbacks
296 if len(self.addr_store) < self.preferred_storage and self.peers:
297 random.choice(self.peers.values()).send_getaddrs(count=8)
301 yield deferral.sleep(random.expovariate(1/20))
305 raise ValueError('already stopped')
309 self.listen_port.stopListening()
312 def attempt_started(self, connector):
313 host, port = connector.getDestination().host, connector.getDestination().port
314 if (host, port) in self.attempts:
315 raise ValueError('already have attempt')
316 self.attempts[host, port] = connector
318 def attempt_failed(self, connector):
319 self.attempt_ended(connector)
321 def attempt_ended(self, connector):
322 host, port = connector.getDestination().host, connector.getDestination().port
323 if (host, port) not in self.attempts:
324 raise ValueError('''don't have attempt''')
325 if connector is not self.attempts[host, port]:
326 raise ValueError('wrong connector')
327 del self.attempts[host, port]
330 def got_conn(self, conn):
331 if conn.nonce in self.peers:
332 raise ValueError('already have peer')
333 self.peers[conn.nonce] = conn
335 print 'Connected to peer %s:%i. p2pool version: %i %r' % (conn.addr[0], conn.addr[1], conn.other_version, conn.other_sub_version)
337 def lost_conn(self, conn):
338 if conn.nonce not in self.peers:
339 raise ValueError('''don't have peer''')
340 if conn is not self.peers[conn.nonce]:
341 raise ValueError('wrong conn')
342 del self.peers[conn.nonce]
344 print 'Lost peer %s:%i' % (conn.addr[0], conn.addr[1])
347 def got_addr(self, (host, port), services, timestamp):
348 if (host, port) in self.addr_store:
349 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
350 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
352 self.addr_store[host, port] = services, timestamp, timestamp
354 def handle_shares(self, shares, peer):
355 print 'handle_shares', (shares, peer)
357 def handle_share_hashes(self, hashes, peer):
358 print 'handle_share_hashes', (hashes, peer)
360 def handle_get_shares(self, hashes, parents, stops, peer):
361 print 'handle_get_shares', (hashes, parents, stops, peer)
363 def get_good_peers(self, max_count):
365 return [x[0] for x in sorted(self.addr_store.iteritems(), key=lambda (k, (services, first_seen, last_seen)): -(last_seen - first_seen)/max(3600, t - last_seen)*random.expovariate(1))][:max_count]
367 if __name__ == '__main__':
368 p = random.randrange(2**15, 2**16)
370 p2 = random.randrange(2**15, 2**16)
372 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())))})