1 from __future__ import division
8 from twisted.internet import defer, protocol, reactor
9 from twisted.python import failure, log
12 from p2pool import data as p2pool_data
13 from p2pool.bitcoin import data as bitcoin_data
14 from p2pool.util import deferral, p2protocol, pack, variable
16 class PeerMisbehavingError(Exception):
20 def fragment(f, **kwargs):
23 except p2protocol.TooLong:
24 fragment(f, **dict((k, v[:len(v)//2]) for k, v in kwargs.iteritems()))
25 fragment(f, **dict((k, v[len(v)//2:]) for k, v in kwargs.iteritems()))
27 class Protocol(p2protocol.Protocol):
30 max_remembered_txs_size = 2500000
32 def __init__(self, node, incoming):
33 p2protocol.Protocol.__init__(self, node.net.PREFIX, 1000000, node.traffic_happened)
35 self.incoming = incoming
37 self.other_version = None
38 self.connected2 = False
40 def connectionMade(self):
41 self.factory.proto_made_connection(self)
43 self.connection_lost_event = variable.Event()
45 self.addr = self.transport.getPeer().host, self.transport.getPeer().port
52 address=self.transport.getPeer().host,
53 port=self.transport.getPeer().port,
57 address=self.transport.getHost().host,
58 port=self.transport.getHost().port,
60 nonce=self.node.nonce,
61 sub_version=p2pool.__version__,
63 best_share_hash=self.node.best_share_hash_func(),
66 self.timeout_delayed = reactor.callLater(10, self._connect_timeout)
68 self.get_shares = deferral.GenericDeferrer(
70 func=lambda id, hashes, parents, stops: self.send_sharereq(id=id, hashes=hashes, parents=parents, stops=stops),
72 on_timeout=self.disconnect,
75 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
76 self.remote_remembered_txs_size = 0
78 self.remembered_txs = {} # view of peer's mining_txs
79 self.remembered_txs_size = 0
80 self.known_txs_cache = {}
82 def _connect_timeout(self):
83 self.timeout_delayed = None
84 print 'Handshake timed out, disconnecting from %s:%i' % self.addr
87 def packetReceived(self, command, payload2):
89 if command != 'version' and not self.connected2:
90 raise PeerMisbehavingError('first message was not version message')
91 p2protocol.Protocol.packetReceived(self, command, payload2)
92 except PeerMisbehavingError, e:
93 print 'Peer %s:%i misbehaving, will drop and ban. Reason:' % self.addr, e.message
94 self.badPeerHappened()
96 def badPeerHappened(self):
97 print "Bad peer banned:", self.addr
99 if self.transport.getPeer().host != '127.0.0.1': # never ban localhost
100 self.node.bans[self.transport.getPeer().host] = time.time() + 60*60
103 self.timeout_delayed = None
104 print 'Connection timed out, disconnecting from %s:%i' % self.addr
107 message_version = pack.ComposedType([
108 ('version', pack.IntType(32)),
109 ('services', pack.IntType(64)),
110 ('addr_to', bitcoin_data.address_type),
111 ('addr_from', bitcoin_data.address_type),
112 ('nonce', pack.IntType(64)),
113 ('sub_version', pack.VarStrType()),
114 ('mode', pack.IntType(32)), # always 1 for legacy compatibility
115 ('best_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
117 def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, best_share_hash):
118 if self.other_version is not None:
119 raise PeerMisbehavingError('more than one version message')
121 raise PeerMisbehavingError('peer too old')
123 self.other_version = version
124 self.other_sub_version = sub_version[:512]
125 self.other_services = services
127 if nonce == self.node.nonce:
128 raise PeerMisbehavingError('was connected to self')
129 if nonce in self.node.peers:
131 print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
136 self.connected2 = True
138 self.timeout_delayed.cancel()
139 self.timeout_delayed = reactor.callLater(100, self._timeout)
141 old_dataReceived = self.dataReceived
142 def new_dataReceived(data):
143 if self.timeout_delayed is not None:
144 self.timeout_delayed.reset(100)
145 old_dataReceived(data)
146 self.dataReceived = new_dataReceived
148 self.factory.proto_connected(self)
150 self._stop_thread = deferral.run_repeatedly(lambda: [
152 random.expovariate(1/100)][-1])
154 if self.node.advertise_ip:
155 self._stop_thread2 = deferral.run_repeatedly(lambda: [
156 self.send_addrme(port=self.node.serverfactory.listen_port.getHost().port) if self.node.serverfactory.listen_port is not None else None,
157 random.expovariate(1/(100*len(self.node.peers) + 1))][-1])
159 if best_share_hash is not None:
160 self.node.handle_share_hashes([best_share_hash], self)
162 def update_remote_view_of_my_known_txs(before, after):
163 added = set(after) - set(before)
164 removed = set(before) - set(after)
166 self.send_have_tx(tx_hashes=list(added))
168 self.send_losing_tx(tx_hashes=list(removed))
170 # cache forgotten txs here for a little while so latency of "losing_tx" packets doesn't cause problems
171 key = max(self.known_txs_cache) + 1 if self.known_txs_cache else 0
172 self.known_txs_cache[key] = dict((h, before[h]) for h in removed)
173 reactor.callLater(20, self.known_txs_cache.pop, key)
174 watch_id = self.node.known_txs_var.transitioned.watch(update_remote_view_of_my_known_txs)
175 self.connection_lost_event.watch(lambda: self.node.known_txs_var.transitioned.unwatch(watch_id))
177 self.send_have_tx(tx_hashes=self.node.known_txs_var.value.keys())
179 def update_remote_view_of_my_mining_txs(before, after):
180 added = set(after) - set(before)
181 removed = set(before) - set(after)
183 self.remote_remembered_txs_size += sum(100 + bitcoin_data.tx_type.packed_size(after[x]) for x in added)
184 assert self.remote_remembered_txs_size <= self.max_remembered_txs_size
185 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])
187 self.send_forget_tx(tx_hashes=list(removed))
188 self.remote_remembered_txs_size -= sum(100 + bitcoin_data.tx_type.packed_size(before[x]) for x in removed)
189 watch_id2 = self.node.mining_txs_var.transitioned.watch(update_remote_view_of_my_mining_txs)
190 self.connection_lost_event.watch(lambda: self.node.mining_txs_var.transitioned.unwatch(watch_id2))
192 self.remote_remembered_txs_size += sum(100 + bitcoin_data.tx_type.packed_size(x) for x in self.node.mining_txs_var.value.values())
193 assert self.remote_remembered_txs_size <= self.max_remembered_txs_size
194 fragment(self.send_remember_tx, tx_hashes=[], txs=self.node.mining_txs_var.value.values())
196 message_ping = pack.ComposedType([])
197 def handle_ping(self):
200 message_addrme = pack.ComposedType([
201 ('port', pack.IntType(16)),
203 def handle_addrme(self, port):
204 host = self.transport.getPeer().host
205 #print 'addrme from', host, port
206 if host == '127.0.0.1':
207 if random.random() < .8 and self.node.peers:
208 random.choice(self.node.peers.values()).send_addrme(port=port) # services...
210 self.node.got_addr((self.transport.getPeer().host, port), self.other_services, int(time.time()))
211 if random.random() < .8 and self.node.peers:
212 random.choice(self.node.peers.values()).send_addrs(addrs=[
215 services=self.other_services,
219 timestamp=int(time.time()),
223 message_addrs = pack.ComposedType([
224 ('addrs', pack.ListType(pack.ComposedType([
225 ('timestamp', pack.IntType(64)),
226 ('address', bitcoin_data.address_type),
229 def handle_addrs(self, addrs):
230 for addr_record in addrs:
231 self.node.got_addr((addr_record['address']['address'], addr_record['address']['port']), addr_record['address']['services'], min(int(time.time()), addr_record['timestamp']))
232 if random.random() < .8 and self.node.peers:
233 random.choice(self.node.peers.values()).send_addrs(addrs=[addr_record])
235 message_getaddrs = pack.ComposedType([
236 ('count', pack.IntType(32)),
238 def handle_getaddrs(self, count):
241 self.send_addrs(addrs=[
243 timestamp=int(self.node.addr_store[host, port][2]),
245 services=self.node.addr_store[host, port][0],
250 self.node.get_good_peers(count)
253 message_shares = pack.ComposedType([
254 ('shares', pack.ListType(p2pool_data.share_type)),
256 def handle_shares(self, shares):
258 for wrappedshare in shares:
259 if wrappedshare['type'] < p2pool_data.Share.VERSION: continue
260 share = p2pool_data.load_share(wrappedshare, self.node.net, self.addr)
261 if wrappedshare['type'] >= 13:
263 for tx_hash in share.share_info['new_transaction_hashes']:
264 if tx_hash in self.node.known_txs_var.value:
265 tx = self.node.known_txs_var.value[tx_hash]
267 for cache in self.known_txs_cache.itervalues():
270 print 'Transaction %064x rescued from peer latency cache!' % (tx_hash,)
273 print >>sys.stderr, 'Peer referenced unknown transaction %064x, disconnecting' % (tx_hash,)
280 result.append((share, txs))
282 self.node.handle_shares(result, self)
284 def sendShares(self, shares, tracker, known_txs, include_txs_with=[]):
287 if share.VERSION >= 13:
288 # send full transaction for every new_transaction_hash that peer does not know
289 for tx_hash in share.share_info['new_transaction_hashes']:
290 assert tx_hash in known_txs, 'tried to broadcast share without knowing all its new transactions'
291 if tx_hash not in self.remote_tx_hashes:
292 tx_hashes.add(tx_hash)
294 if share.hash in include_txs_with:
295 x = share.get_other_tx_hashes(tracker)
299 hashes_to_send = [x for x in tx_hashes if x not in self.node.mining_txs_var.value and x in known_txs]
301 new_remote_remembered_txs_size = self.remote_remembered_txs_size + sum(100 + bitcoin_data.tx_type.packed_size(known_txs[x]) for x in hashes_to_send)
302 if new_remote_remembered_txs_size > self.max_remembered_txs_size:
303 raise ValueError('shares have too many txs')
304 self.remote_remembered_txs_size = new_remote_remembered_txs_size
306 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])
308 fragment(self.send_shares, shares=[share.as_share() for share in shares])
310 self.send_forget_tx(tx_hashes=hashes_to_send)
312 self.remote_remembered_txs_size -= sum(100 + bitcoin_data.tx_type.packed_size(known_txs[x]) for x in hashes_to_send)
315 message_sharereq = pack.ComposedType([
316 ('id', pack.IntType(256)),
317 ('hashes', pack.ListType(pack.IntType(256))),
318 ('parents', pack.VarIntType()),
319 ('stops', pack.ListType(pack.IntType(256))),
321 def handle_sharereq(self, id, hashes, parents, stops):
322 shares = self.node.handle_get_shares(hashes, parents, stops, self)
324 self.send_sharereply(id=id, result='good', shares=[share.as_share() for share in shares])
325 except p2protocol.TooLong:
326 self.send_sharereply(id=id, result='too long', shares=[])
328 message_sharereply = pack.ComposedType([
329 ('id', pack.IntType(256)),
330 ('result', pack.EnumType(pack.VarIntType(), {0: 'good', 1: 'too long', 2: 'unk2', 3: 'unk3', 4: 'unk4', 5: 'unk5', 6: 'unk6'})),
331 ('shares', pack.ListType(p2pool_data.share_type)),
333 class ShareReplyError(Exception): pass
334 def handle_sharereply(self, id, result, shares):
336 res = [p2pool_data.load_share(share, self.node.net, self.addr) for share in shares if share['type'] >= p2pool_data.Share.VERSION]
338 res = failure.Failure(self.ShareReplyError(result))
339 self.get_shares.got_response(id, res)
342 message_bestblock = pack.ComposedType([
343 ('header', bitcoin_data.block_header_type),
345 def handle_bestblock(self, header):
346 self.node.handle_bestblock(header, self)
349 message_have_tx = pack.ComposedType([
350 ('tx_hashes', pack.ListType(pack.IntType(256))),
352 def handle_have_tx(self, tx_hashes):
353 #assert self.remote_tx_hashes.isdisjoint(tx_hashes)
354 self.remote_tx_hashes.update(tx_hashes)
355 while len(self.remote_tx_hashes) > 10000:
356 self.remote_tx_hashes.pop()
357 message_losing_tx = pack.ComposedType([
358 ('tx_hashes', pack.ListType(pack.IntType(256))),
360 def handle_losing_tx(self, tx_hashes):
361 #assert self.remote_tx_hashes.issuperset(tx_hashes)
362 self.remote_tx_hashes.difference_update(tx_hashes)
365 message_remember_tx = pack.ComposedType([
366 ('tx_hashes', pack.ListType(pack.IntType(256))),
367 ('txs', pack.ListType(bitcoin_data.tx_type)),
369 def handle_remember_tx(self, tx_hashes, txs):
370 for tx_hash in tx_hashes:
371 if tx_hash in self.remembered_txs:
372 print >>sys.stderr, 'Peer referenced transaction twice, disconnecting'
376 if tx_hash in self.node.known_txs_var.value:
377 tx = self.node.known_txs_var.value[tx_hash]
379 for cache in self.known_txs_cache.itervalues():
382 print 'Transaction %064x rescued from peer latency cache!' % (tx_hash,)
385 print >>sys.stderr, 'Peer referenced unknown transaction %064x, disconnecting' % (tx_hash,)
389 self.remembered_txs[tx_hash] = tx
390 self.remembered_txs_size += 100 + bitcoin_data.tx_type.packed_size(tx)
391 new_known_txs = dict(self.node.known_txs_var.value)
394 tx_hash = bitcoin_data.hash256(bitcoin_data.tx_type.pack(tx))
395 if tx_hash in self.remembered_txs:
396 print >>sys.stderr, 'Peer referenced transaction twice, disconnecting'
400 if tx_hash in self.node.known_txs_var.value and not warned:
401 print 'Peer sent entire transaction %064x that was already received' % (tx_hash,)
404 self.remembered_txs[tx_hash] = tx
405 self.remembered_txs_size += 100 + bitcoin_data.tx_type.packed_size(tx)
406 new_known_txs[tx_hash] = tx
407 self.node.known_txs_var.set(new_known_txs)
408 if self.remembered_txs_size >= self.max_remembered_txs_size:
409 raise PeerMisbehavingError('too much transaction data stored')
410 message_forget_tx = pack.ComposedType([
411 ('tx_hashes', pack.ListType(pack.IntType(256))),
413 def handle_forget_tx(self, tx_hashes):
414 for tx_hash in tx_hashes:
415 self.remembered_txs_size -= 100 + bitcoin_data.tx_type.packed_size(self.remembered_txs[tx_hash])
416 assert self.remembered_txs_size >= 0
417 del self.remembered_txs[tx_hash]
420 def connectionLost(self, reason):
421 self.connection_lost_event.happened()
422 if self.timeout_delayed is not None:
423 self.timeout_delayed.cancel()
425 self.factory.proto_disconnected(self, reason)
427 if self.node.advertise_ip:
429 self.connected2 = False
430 self.factory.proto_lost_connection(self, reason)
432 print "Peer connection lost:", self.addr, reason
433 self.get_shares.respond_all(reason)
435 @defer.inlineCallbacks
437 start = reactor.seconds()
438 yield self.get_shares(hashes=[0], parents=0, stops=[])
439 end = reactor.seconds()
440 defer.returnValue(end - start)
442 class ServerFactory(protocol.ServerFactory):
443 def __init__(self, node, max_conns):
445 self.max_conns = max_conns
449 self.listen_port = None
451 def buildProtocol(self, addr):
452 if sum(self.conns.itervalues()) >= self.max_conns or self.conns.get(self._host_to_ident(addr.host), 0) >= 3:
454 if addr.host in self.node.bans and self.node.bans[addr.host] > time.time():
456 p = Protocol(self.node, True)
459 print "Got peer connection from:", addr
462 def _host_to_ident(self, host):
463 a, b, c, d = host.split('.')
466 def proto_made_connection(self, proto):
467 ident = self._host_to_ident(proto.transport.getPeer().host)
468 self.conns[ident] = self.conns.get(ident, 0) + 1
469 def proto_lost_connection(self, proto, reason):
470 ident = self._host_to_ident(proto.transport.getPeer().host)
471 self.conns[ident] -= 1
472 if not self.conns[ident]:
473 del self.conns[ident]
475 def proto_connected(self, proto):
476 self.node.got_conn(proto)
477 def proto_disconnected(self, proto, reason):
478 self.node.lost_conn(proto, reason)
481 assert not self.running
484 def attempt_listen():
486 self.listen_port = reactor.listenTCP(self.node.port, self)
487 deferral.retry('Error binding to P2P port:', traceback=False)(attempt_listen)()
493 return self.listen_port.stopListening()
495 class ClientFactory(protocol.ClientFactory):
496 def __init__(self, node, desired_conns, max_attempts):
498 self.desired_conns = desired_conns
499 self.max_attempts = max_attempts
501 self.attempts = set()
505 def _host_to_ident(self, host):
506 a, b, c, d = host.split('.')
509 def buildProtocol(self, addr):
510 p = Protocol(self.node, False)
514 def startedConnecting(self, connector):
515 ident = self._host_to_ident(connector.getDestination().host)
516 if ident in self.attempts:
517 raise AssertionError('already have attempt')
518 self.attempts.add(ident)
520 def clientConnectionFailed(self, connector, reason):
521 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
523 def clientConnectionLost(self, connector, reason):
524 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
526 def proto_made_connection(self, proto):
528 def proto_lost_connection(self, proto, reason):
531 def proto_connected(self, proto):
532 self.conns.add(proto)
533 self.node.got_conn(proto)
534 def proto_disconnected(self, proto, reason):
535 self.conns.remove(proto)
536 self.node.lost_conn(proto, reason)
539 assert not self.running
541 self._stop_thinking = deferral.run_repeatedly(self._think)
545 self._stop_thinking()
549 if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and self.node.addr_store:
550 (host, port), = self.node.get_good_peers(1)
552 if self._host_to_ident(host) in self.attempts:
554 elif host in self.node.bans and self.node.bans[host] > time.time():
557 #print 'Trying to connect to', host, port
558 reactor.connectTCP(host, port, self, timeout=5)
562 return random.expovariate(1/1)
564 class SingleClientFactory(protocol.ReconnectingClientFactory):
565 def __init__(self, node):
568 def buildProtocol(self, addr):
569 p = Protocol(self.node, incoming=False)
573 def proto_made_connection(self, proto):
575 def proto_lost_connection(self, proto, reason):
578 def proto_connected(self, proto):
580 self.node.got_conn(proto)
581 def proto_disconnected(self, proto, reason):
582 self.node.lost_conn(proto, reason)
585 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, known_txs_var=variable.Variable({}), mining_txs_var=variable.Variable({}), advertise_ip=True):
586 self.best_share_hash_func = best_share_hash_func
589 self.addr_store = dict(addr_store)
590 self.connect_addrs = connect_addrs
591 self.preferred_storage = preferred_storage
592 self.known_txs_var = known_txs_var
593 self.mining_txs_var = mining_txs_var
594 self.advertise_ip = advertise_ip
596 self.traffic_happened = variable.Event()
597 self.nonce = random.randrange(2**64)
599 self.bans = {} # address -> end_time
600 self.clientfactory = ClientFactory(self, desired_outgoing_conns, max_outgoing_attempts)
601 self.serverfactory = ServerFactory(self, max_incoming_conns)
606 raise ValueError('already running')
608 self.clientfactory.start()
609 self.serverfactory.start()
610 self.singleclientconnectors = [reactor.connectTCP(addr, port, SingleClientFactory(self)) for addr, port in self.connect_addrs]
614 self._stop_thinking = deferral.run_repeatedly(self._think)
618 if len(self.addr_store) < self.preferred_storage and self.peers:
619 random.choice(self.peers.values()).send_getaddrs(count=8)
623 return random.expovariate(1/20)
625 @defer.inlineCallbacks
628 raise ValueError('already stopped')
632 self._stop_thinking()
633 yield self.clientfactory.stop()
634 yield self.serverfactory.stop()
635 for singleclientconnector in self.singleclientconnectors:
636 yield singleclientconnector.factory.stopTrying()
637 yield singleclientconnector.disconnect()
638 del self.singleclientconnectors
640 def got_conn(self, conn):
641 if conn.nonce in self.peers:
642 raise ValueError('already have peer')
643 self.peers[conn.nonce] = conn
645 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)
647 def lost_conn(self, conn, reason):
648 if conn.nonce not in self.peers:
649 raise ValueError('''don't have peer''')
650 if conn is not self.peers[conn.nonce]:
651 raise ValueError('wrong conn')
652 del self.peers[conn.nonce]
654 print 'Lost peer %s:%i - %s' % (conn.addr[0], conn.addr[1], reason.getErrorMessage())
657 def got_addr(self, (host, port), services, timestamp):
658 if (host, port) in self.addr_store:
659 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
660 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
662 if len(self.addr_store) < 10000:
663 self.addr_store[host, port] = services, timestamp, timestamp
665 def handle_shares(self, shares, peer):
666 print 'handle_shares', (shares, peer)
668 def handle_share_hashes(self, hashes, peer):
669 print 'handle_share_hashes', (hashes, peer)
671 def handle_get_shares(self, hashes, parents, stops, peer):
672 print 'handle_get_shares', (hashes, parents, stops, peer)
674 def handle_bestblock(self, header, peer):
675 print 'handle_bestblock', header
677 def get_good_peers(self, max_count):
679 return [x[0] for x in sorted(self.addr_store.iteritems(), key=lambda (k, (services, first_seen, last_seen)):
680 -math.log(max(3600, last_seen - first_seen))/math.log(max(3600, t - last_seen))*random.expovariate(1)