1 from __future__ import division
7 from twisted.internet import defer, protocol, reactor
8 from twisted.python import failure, 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, variable
15 class PeerMisbehavingError(Exception):
19 def fragment(f, **kwargs):
22 except p2protocol.TooLong:
23 att(f, **dict((k, v[:len(v)//2]) for k, v in kwargs.iteritems()))
24 return att(f, **dict((k, v[len(v)//2:]) for k, v in kwargs.iteritems()))
26 class Protocol(p2protocol.Protocol):
27 max_remembered_txs_size = 2500000
29 def __init__(self, node, incoming):
30 p2protocol.Protocol.__init__(self, node.net.PREFIX, 1000000, node.traffic_happened)
32 self.incoming = incoming
34 self.other_version = None
35 self.connected2 = False
37 def connectionMade(self):
38 p2protocol.Protocol.connectionMade(self)
40 self.factory.proto_made_connection(self)
42 self.connection_lost_event = variable.Event()
44 self.addr = self.transport.getPeer().host, self.transport.getPeer().port
51 address=self.transport.getPeer().host,
52 port=self.transport.getPeer().port,
56 address=self.transport.getHost().host,
57 port=self.transport.getHost().port,
59 nonce=self.node.nonce,
60 sub_version=p2pool.__version__,
62 best_share_hash=self.node.best_share_hash_func(),
65 self.timeout_delayed = reactor.callLater(10, self._connect_timeout)
67 self.get_shares = deferral.GenericDeferrer(
69 func=lambda id, hashes, parents, stops: self.send_sharereq(id=id, hashes=hashes, parents=parents, stops=stops),
71 on_timeout=self.transport.loseConnection,
74 self.remote_tx_hashes = set() # view of peer's known_txs # not actually initially empty, but sending txs instead of tx hashes won't hurt
75 self.remote_remembered_txs_size = 0
77 self.remembered_txs = {} # view of peer's mining_txs
78 self.remembered_txs_size = 0
79 self.known_txs_cache = {}
81 def _connect_timeout(self):
82 self.timeout_delayed = None
83 print 'Handshake timed out, disconnecting from %s:%i' % self.addr
84 self.transport.loseConnection()
86 def packetReceived(self, command, payload2):
88 if command != 'version' and not self.connected2:
89 raise PeerMisbehavingError('first message was not version message')
90 p2protocol.Protocol.packetReceived(self, command, payload2)
91 except PeerMisbehavingError, e:
92 print 'Peer %s:%i misbehaving, will drop and ban. Reason:' % self.addr, e.message
93 self.badPeerHappened()
95 def badPeerHappened(self):
97 print "Bad peer banned:", self.addr
98 self.transport.loseConnection()
99 self.node.bans[self.transport.getPeer().host] = time.time() + 60*60
102 self.timeout_delayed = None
103 print 'Connection timed out, disconnecting from %s:%i' % self.addr
104 self.transport.loseConnection()
106 message_version = pack.ComposedType([
107 ('version', pack.IntType(32)),
108 ('services', pack.IntType(64)),
109 ('addr_to', bitcoin_data.address_type),
110 ('addr_from', bitcoin_data.address_type),
111 ('nonce', pack.IntType(64)),
112 ('sub_version', pack.VarStrType()),
113 ('mode', pack.IntType(32)), # always 1 for legacy compatibility
114 ('best_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
116 def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, best_share_hash):
117 if self.other_version is not None:
118 raise PeerMisbehavingError('more than one version message')
120 raise PeerMisbehavingError('peer too old')
122 self.other_version = version
123 self.other_sub_version = sub_version[:512]
124 self.other_services = services
126 if nonce == self.node.nonce:
127 raise PeerMisbehavingError('was connected to self')
128 if nonce in self.node.peers:
130 print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
131 self.transport.loseConnection()
135 self.connected2 = True
137 self.timeout_delayed.cancel()
138 self.timeout_delayed = reactor.callLater(100, self._timeout)
140 old_dataReceived = self.dataReceived
141 def new_dataReceived(data):
142 if self.timeout_delayed is not None:
143 self.timeout_delayed.reset(100)
144 old_dataReceived(data)
145 self.dataReceived = new_dataReceived
147 self.factory.proto_connected(self)
149 self._stop_thread = deferral.run_repeatedly(lambda: [
151 random.expovariate(1/100)][-1])
153 self._stop_thread2 = deferral.run_repeatedly(lambda: [
154 self.send_addrme(port=self.node.port),
155 random.expovariate(1/(100*len(self.node.peers) + 1))][-1])
157 if best_share_hash is not None:
158 self.node.handle_share_hashes([best_share_hash], self)
160 def update_remote_view_of_my_known_txs(before, after):
161 added = set(after) - set(before)
162 removed = set(before) - set(after)
164 self.send_have_tx(tx_hashes=list(added))
166 self.send_losing_tx(tx_hashes=list(removed))
168 # cache forgotten txs here for a little while so latency of "losing_tx" packets doesn't cause problems
169 key = max(self.known_txs_cache) + 1 if self.known_txs_cache else 0
170 self.known_txs_cache[key] = dict((h, before[h]) for h in removed)
171 reactor.callLater(20, self.known_txs_cache.pop, key)
172 watch_id = self.node.known_txs_var.transitioned.watch(update_remote_view_of_my_known_txs)
173 self.connection_lost_event.watch(lambda: self.node.known_txs_var.transitioned.unwatch(watch_id))
175 self.send_have_tx(tx_hashes=self.node.known_txs_var.value.keys())
177 def update_remote_view_of_my_mining_txs(before, after):
178 added = set(after) - set(before)
179 removed = set(before) - set(after)
181 self.remote_remembered_txs_size += sum(len(bitcoin_data.tx_type.pack(after[x])) for x in added)
182 assert self.remote_remembered_txs_size <= self.max_remembered_txs_size
183 fragment(self.send_remember_tx, tx_hashes=[x for x in added if x in self.remote_tx_hashes], txs=[after[x] for x in added if x not in self.remote_tx_hashes])
185 self.send_forget_tx(tx_hashes=removed)
186 self.remote_remembered_txs_size -= sum(len(bitcoin_data.tx_type.pack(before[x])) for x in removed)
187 watch_id2 = self.node.mining_txs_var.transitioned.watch(update_remote_view_of_my_mining_txs)
188 self.connection_lost_event.watch(lambda: self.node.mining_txs_var.transitioned.unwatch(watch_id2))
190 self.remote_remembered_txs_size += sum(len(bitcoin_data.tx_type.pack(x)) for x in self.node.mining_txs_var.value.values())
191 assert self.remote_remembered_txs_size <= self.max_remembered_txs_size
192 fragment(self.send_remember_tx, tx_hashes=[], txs=self.node.mining_txs_var.value.values())
194 message_ping = pack.ComposedType([])
195 def handle_ping(self):
198 message_addrme = pack.ComposedType([
199 ('port', pack.IntType(16)),
201 def handle_addrme(self, port):
202 host = self.transport.getPeer().host
203 #print 'addrme from', host, port
204 if host == '127.0.0.1':
205 if random.random() < .8 and self.node.peers:
206 random.choice(self.node.peers.values()).send_addrme(port=port) # services...
208 self.node.got_addr((self.transport.getPeer().host, port), self.other_services, int(time.time()))
209 if random.random() < .8 and self.node.peers:
210 random.choice(self.node.peers.values()).send_addrs(addrs=[
213 services=self.other_services,
217 timestamp=int(time.time()),
221 message_addrs = pack.ComposedType([
222 ('addrs', pack.ListType(pack.ComposedType([
223 ('timestamp', pack.IntType(64)),
224 ('address', bitcoin_data.address_type),
227 def handle_addrs(self, addrs):
228 for addr_record in addrs:
229 self.node.got_addr((addr_record['address']['address'], addr_record['address']['port']), addr_record['address']['services'], min(int(time.time()), addr_record['timestamp']))
230 if random.random() < .8 and self.node.peers:
231 random.choice(self.node.peers.values()).send_addrs(addrs=[addr_record])
233 message_getaddrs = pack.ComposedType([
234 ('count', pack.IntType(32)),
236 def handle_getaddrs(self, count):
239 self.send_addrs(addrs=[
241 timestamp=int(self.node.addr_store[host, port][2]),
243 services=self.node.addr_store[host, port][0],
248 self.node.get_good_peers(count)
251 message_shares = pack.ComposedType([
252 ('shares', pack.ListType(p2pool_data.share_type)),
254 def handle_shares(self, shares):
255 self.node.handle_shares([p2pool_data.load_share(share, self.node.net, self) for share in shares if share['type'] not in [6, 7]], self)
257 def sendShares(self, shares, tracker, known_txs, include_txs_with=[]):
259 return defer.succeed(None)
263 if share.hash in include_txs_with:
264 tx_hashes.update(share.get_other_tx_hashes(tracker))
266 hashes_to_send = [x for x in tx_hashes if x not in self.node.mining_txs_var.value and x in known_txs]
268 new_remote_remembered_txs_size = self.remote_remembered_txs_size + sum(len(bitcoin_data.tx_type.pack(known_txs[x])) for x in hashes_to_send)
269 if new_remote_remembered_txs_size > self.max_remembered_txs_size:
270 raise ValueError('shares have too many txs')
271 self.remote_remembered_txs_size = new_remote_remembered_txs_size
273 fragment(self.send_remember_tx, tx_hashes=[x for x in hashes_to_send if x in self.remote_tx_hashes], txs=[known_txs[x] for x in hashes_to_send if x not in self.remote_tx_hashes])
274 fragment(self.send_shares, shares=[share.as_share() for share in shares])
275 res = self.send_forget_tx(tx_hashes=hashes_to_send)
277 self.remote_remembered_txs_size -= sum(len(bitcoin_data.tx_type.pack(known_txs[x])) for x in hashes_to_send)
282 message_sharereq = pack.ComposedType([
283 ('id', pack.IntType(256)),
284 ('hashes', pack.ListType(pack.IntType(256))),
285 ('parents', pack.VarIntType()),
286 ('stops', pack.ListType(pack.IntType(256))),
288 def handle_sharereq(self, id, hashes, parents, stops):
289 shares = self.node.handle_get_shares(hashes, parents, stops, self)
291 self.send_sharereply(id=id, result='good', shares=[share.as_share() for share in shares])
292 except p2protocol.TooLong:
293 self.send_sharereply(id=id, result='too long', shares=[])
295 message_sharereply = pack.ComposedType([
296 ('id', pack.IntType(256)),
297 ('result', pack.EnumType(pack.VarIntType(), {0: 'good', 1: 'too long', 2: 'unk2', 3: 'unk3', 4: 'unk4', 5: 'unk5', 6: 'unk6'})),
298 ('shares', pack.ListType(p2pool_data.share_type)),
300 def handle_sharereply(self, id, result, shares):
302 res = [p2pool_data.load_share(share, self.node.net, self) for share in shares if share['type'] not in [6, 7]]
304 res = failure.Failure("sharereply result: " + result)
305 self.get_shares.got_response(id, res)
308 message_bestblock = pack.ComposedType([
309 ('header', bitcoin_data.block_header_type),
311 def handle_bestblock(self, header):
312 self.node.handle_bestblock(header, self)
315 message_have_tx = pack.ComposedType([
316 ('tx_hashes', pack.ListType(pack.IntType(256))),
318 def handle_have_tx(self, tx_hashes):
319 self.remote_tx_hashes.update(tx_hashes)
320 message_losing_tx = pack.ComposedType([
321 ('tx_hashes', pack.ListType(pack.IntType(256))),
323 def handle_losing_tx(self, tx_hashes):
324 self.remote_tx_hashes.difference_update(tx_hashes)
327 message_remember_tx = pack.ComposedType([
328 ('tx_hashes', pack.ListType(pack.IntType(256))),
329 ('txs', pack.ListType(bitcoin_data.tx_type)),
331 def handle_remember_tx(self, tx_hashes, txs):
332 for tx_hash in tx_hashes:
333 if tx_hash not in self.remembered_txs:
334 if tx_hash in self.node.known_txs_var.value:
335 tx = self.node.known_txs_var.value[tx_hash]
337 for cache in self.known_txs_cache.itervalues():
340 print 'Transaction rescued from peer latency cache!'
343 print >>sys.stderr, 'Peer referenced unknown transaction, disconnecting'
344 self.transport.loseConnection()
347 self.remembered_txs[tx_hash] = tx
348 self.remembered_txs_size += len(bitcoin_data.tx_type.pack(tx))
349 new_known_txs = dict(self.node.known_txs_var.value)
351 tx_hash = bitcoin_data.hash256(bitcoin_data.tx_type.pack(tx))
352 if tx_hash not in self.remembered_txs:
353 self.remembered_txs[tx_hash] = tx
354 self.remembered_txs_size += len(bitcoin_data.tx_type.pack(tx))
355 new_known_txs[tx_hash] = tx
356 self.node.known_txs_var.set(new_known_txs)
357 if self.remembered_txs_size >= self.max_remembered_txs_size:
358 raise PeerMisbehavingError('too much transaction data stored')
359 message_forget_tx = pack.ComposedType([
360 ('tx_hashes', pack.ListType(pack.IntType(256))),
362 def handle_forget_tx(self, tx_hashes):
363 for tx_hash in tx_hashes:
364 self.remembered_txs_size -= len(bitcoin_data.tx_type.pack(self.remembered_txs[tx_hash]))
365 assert self.remembered_txs_size >= 0
366 del self.remembered_txs[tx_hash]
369 def connectionLost(self, reason):
370 self.connection_lost_event.happened()
371 if self.timeout_delayed is not None:
372 self.timeout_delayed.cancel()
374 self.factory.proto_disconnected(self, reason)
377 self.connected2 = False
378 self.factory.proto_lost_connection(self, reason)
380 print "Peer connection lost:", self.addr, reason
381 self.get_shares.respond_all(reason)
383 @defer.inlineCallbacks
385 start = reactor.seconds()
386 yield self.get_shares(hashes=[0], parents=0, stops=[])
387 end = reactor.seconds()
388 defer.returnValue(end - start)
390 class ServerFactory(protocol.ServerFactory):
391 def __init__(self, node, max_conns):
393 self.max_conns = max_conns
398 def buildProtocol(self, addr):
399 if sum(self.conns.itervalues()) >= self.max_conns or self.conns.get(self._host_to_ident(addr.host), 0) >= 3:
401 if addr.host in self.node.bans and self.node.bans[addr.host] > time.time():
403 p = Protocol(self.node, True)
406 print "Got peer connection from:", addr
409 def _host_to_ident(self, host):
410 a, b, c, d = host.split('.')
413 def proto_made_connection(self, proto):
414 ident = self._host_to_ident(proto.transport.getPeer().host)
415 self.conns[ident] = self.conns.get(ident, 0) + 1
416 def proto_lost_connection(self, proto, reason):
417 ident = self._host_to_ident(proto.transport.getPeer().host)
418 self.conns[ident] -= 1
419 if not self.conns[ident]:
420 del self.conns[ident]
422 def proto_connected(self, proto):
423 self.node.got_conn(proto)
424 def proto_disconnected(self, proto, reason):
425 self.node.lost_conn(proto, reason)
428 assert not self.running
431 def attempt_listen():
433 self.listen_port = reactor.listenTCP(self.node.port, self)
434 deferral.retry('Error binding to P2P port:', traceback=False)(attempt_listen)()
440 return self.listen_port.stopListening()
442 class ClientFactory(protocol.ClientFactory):
443 def __init__(self, node, desired_conns, max_attempts):
445 self.desired_conns = desired_conns
446 self.max_attempts = max_attempts
448 self.attempts = set()
452 def _host_to_ident(self, host):
453 a, b, c, d = host.split('.')
456 def buildProtocol(self, addr):
457 p = Protocol(self.node, False)
461 def startedConnecting(self, connector):
462 ident = self._host_to_ident(connector.getDestination().host)
463 if ident in self.attempts:
464 raise AssertionError('already have attempt')
465 self.attempts.add(ident)
467 def clientConnectionFailed(self, connector, reason):
468 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
470 def clientConnectionLost(self, connector, reason):
471 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
473 def proto_made_connection(self, proto):
475 def proto_lost_connection(self, proto, reason):
478 def proto_connected(self, proto):
479 self.conns.add(proto)
480 self.node.got_conn(proto)
481 def proto_disconnected(self, proto, reason):
482 self.conns.remove(proto)
483 self.node.lost_conn(proto, reason)
486 assert not self.running
488 self._stop_thinking = deferral.run_repeatedly(self._think)
492 self._stop_thinking()
496 if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and self.node.addr_store:
497 (host, port), = self.node.get_good_peers(1)
499 if self._host_to_ident(host) in self.attempts:
501 elif host in self.node.bans and self.node.bans[host] > time.time():
504 #print 'Trying to connect to', host, port
505 reactor.connectTCP(host, port, self, timeout=5)
509 return random.expovariate(1/1)
511 class SingleClientFactory(protocol.ReconnectingClientFactory):
512 def __init__(self, node):
515 def buildProtocol(self, addr):
516 p = Protocol(self.node, incoming=False)
520 def proto_made_connection(self, proto):
522 def proto_lost_connection(self, proto, reason):
525 def proto_connected(self, proto):
527 self.node.got_conn(proto)
528 def proto_disconnected(self, proto, reason):
529 self.node.lost_conn(proto, reason)
532 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, traffic_happened=variable.Event(), known_txs_var=variable.Variable({}), mining_txs_var=variable.Variable({})):
533 self.best_share_hash_func = best_share_hash_func
536 self.addr_store = dict(addr_store)
537 self.connect_addrs = connect_addrs
538 self.preferred_storage = preferred_storage
539 self.traffic_happened = traffic_happened
540 self.known_txs_var = known_txs_var
541 self.mining_txs_var = mining_txs_var
543 self.nonce = random.randrange(2**64)
545 self.bans = {} # address -> end_time
546 self.clientfactory = ClientFactory(self, desired_outgoing_conns, max_outgoing_attempts)
547 self.serverfactory = ServerFactory(self, max_incoming_conns)
552 raise ValueError('already running')
554 self.clientfactory.start()
555 self.serverfactory.start()
556 self.singleclientconnectors = [reactor.connectTCP(addr, port, SingleClientFactory(self)) for addr, port in self.connect_addrs]
560 self._stop_thinking = deferral.run_repeatedly(self._think)
564 if len(self.addr_store) < self.preferred_storage and self.peers:
565 random.choice(self.peers.values()).send_getaddrs(count=8)
569 return random.expovariate(1/20)
571 @defer.inlineCallbacks
574 raise ValueError('already stopped')
578 self._stop_thinking()
579 yield self.clientfactory.stop()
580 yield self.serverfactory.stop()
581 for singleclientconnector in self.singleclientconnectors:
582 yield singleclientconnector.factory.stopTrying()
583 yield singleclientconnector.disconnect()
584 del self.singleclientconnectors
586 def got_conn(self, conn):
587 if conn.nonce in self.peers:
588 raise ValueError('already have peer')
589 self.peers[conn.nonce] = conn
591 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)
593 def lost_conn(self, conn, reason):
594 if conn.nonce not in self.peers:
595 raise ValueError('''don't have peer''')
596 if conn is not self.peers[conn.nonce]:
597 raise ValueError('wrong conn')
598 del self.peers[conn.nonce]
600 print 'Lost peer %s:%i - %s' % (conn.addr[0], conn.addr[1], reason.getErrorMessage())
603 def got_addr(self, (host, port), services, timestamp):
604 if (host, port) in self.addr_store:
605 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
606 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
608 self.addr_store[host, port] = services, timestamp, timestamp
610 def handle_shares(self, shares, peer):
611 print 'handle_shares', (shares, peer)
613 def handle_share_hashes(self, hashes, peer):
614 print 'handle_share_hashes', (hashes, peer)
616 def handle_get_shares(self, hashes, parents, stops, peer):
617 print 'handle_get_shares', (hashes, parents, stops, peer)
619 def handle_bestblock(self, header, peer):
620 print 'handle_bestblock', header
622 def get_good_peers(self, max_count):
624 return [x[0] for x in sorted(self.addr_store.iteritems(), key=lambda (k, (services, first_seen, last_seen)):
625 -math.log(max(3600, last_seen - first_seen))/math.log(max(3600, t - last_seen))*random.expovariate(1)