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):
28 max_remembered_txs_size = 2500000
30 def __init__(self, node, incoming):
31 p2protocol.Protocol.__init__(self, node.net.PREFIX, 1000000, node.traffic_happened)
33 self.incoming = incoming
35 self.other_version = None
36 self.connected2 = False
38 def connectionMade(self):
39 self.factory.proto_made_connection(self)
41 self.connection_lost_event = variable.Event()
43 self.addr = self.transport.getPeer().host, self.transport.getPeer().port
50 address=self.transport.getPeer().host,
51 port=self.transport.getPeer().port,
55 address=self.transport.getHost().host,
56 port=self.transport.getHost().port,
58 nonce=self.node.nonce,
59 sub_version=p2pool.__version__,
61 best_share_hash=self.node.best_share_hash_func(),
64 self.timeout_delayed = reactor.callLater(10, self._connect_timeout)
66 self.get_shares = deferral.GenericDeferrer(
68 func=lambda id, hashes, parents, stops: self.send_sharereq(id=id, hashes=hashes, parents=parents, stops=stops),
70 on_timeout=self.transport.loseConnection,
73 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
74 self.remote_remembered_txs_size = 0
76 self.remembered_txs = {} # view of peer's mining_txs
77 self.remembered_txs_size = 0
78 self.known_txs_cache = {}
80 def _connect_timeout(self):
81 self.timeout_delayed = None
82 print 'Handshake timed out, disconnecting from %s:%i' % self.addr
83 if hasattr(self.transport, 'abortConnection'):
84 # Available since Twisted 11.1
85 self.transport.abortConnection()
87 # This doesn't always close timed out connections!
88 self.transport.loseConnection()
90 def packetReceived(self, command, payload2):
92 if command != 'version' and not self.connected2:
93 raise PeerMisbehavingError('first message was not version message')
94 p2protocol.Protocol.packetReceived(self, command, payload2)
95 except PeerMisbehavingError, e:
96 print 'Peer %s:%i misbehaving, will drop and ban. Reason:' % self.addr, e.message
97 self.badPeerHappened()
99 def badPeerHappened(self):
101 print "Bad peer banned:", self.addr
102 self.transport.loseConnection()
103 if self.transport.getPeer().host != '127.0.0.1': # never ban localhost
104 self.node.bans[self.transport.getPeer().host] = time.time() + 60*60
107 self.timeout_delayed = None
108 print 'Connection timed out, disconnecting from %s:%i' % self.addr
109 if hasattr(self.transport, 'abortConnection'):
110 # Available since Twisted 11.1
111 self.transport.abortConnection()
113 # This doesn't always close timed out connections!
114 self.transport.loseConnection()
116 message_version = pack.ComposedType([
117 ('version', pack.IntType(32)),
118 ('services', pack.IntType(64)),
119 ('addr_to', bitcoin_data.address_type),
120 ('addr_from', bitcoin_data.address_type),
121 ('nonce', pack.IntType(64)),
122 ('sub_version', pack.VarStrType()),
123 ('mode', pack.IntType(32)), # always 1 for legacy compatibility
124 ('best_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
126 def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, best_share_hash):
127 if self.other_version is not None:
128 raise PeerMisbehavingError('more than one version message')
130 raise PeerMisbehavingError('peer too old')
132 self.other_version = version
133 self.other_sub_version = sub_version[:512]
134 self.other_services = services
136 if nonce == self.node.nonce:
137 raise PeerMisbehavingError('was connected to self')
138 if nonce in self.node.peers:
140 print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
141 self.transport.loseConnection()
145 self.connected2 = True
147 self.timeout_delayed.cancel()
148 self.timeout_delayed = reactor.callLater(100, self._timeout)
150 old_dataReceived = self.dataReceived
151 def new_dataReceived(data):
152 if self.timeout_delayed is not None:
153 self.timeout_delayed.reset(100)
154 old_dataReceived(data)
155 self.dataReceived = new_dataReceived
157 self.factory.proto_connected(self)
159 self._stop_thread = deferral.run_repeatedly(lambda: [
161 random.expovariate(1/100)][-1])
163 self._stop_thread2 = deferral.run_repeatedly(lambda: [
164 self.send_addrme(port=self.node.serverfactory.listen_port.getHost().port) if self.node.serverfactory.listen_port is not None else None,
165 random.expovariate(1/(100*len(self.node.peers) + 1))][-1])
167 if best_share_hash is not None:
168 self.node.handle_share_hashes([best_share_hash], self)
170 if self.other_version < 8:
173 def update_remote_view_of_my_known_txs(before, after):
174 added = set(after) - set(before)
175 removed = set(before) - set(after)
177 self.send_have_tx(tx_hashes=list(added))
179 self.send_losing_tx(tx_hashes=list(removed))
181 # cache forgotten txs here for a little while so latency of "losing_tx" packets doesn't cause problems
182 key = max(self.known_txs_cache) + 1 if self.known_txs_cache else 0
183 self.known_txs_cache[key] = dict((h, before[h]) for h in removed)
184 reactor.callLater(20, self.known_txs_cache.pop, key)
185 watch_id = self.node.known_txs_var.transitioned.watch(update_remote_view_of_my_known_txs)
186 self.connection_lost_event.watch(lambda: self.node.known_txs_var.transitioned.unwatch(watch_id))
188 self.send_have_tx(tx_hashes=self.node.known_txs_var.value.keys())
190 def update_remote_view_of_my_mining_txs(before, after):
191 added = set(after) - set(before)
192 removed = set(before) - set(after)
194 self.remote_remembered_txs_size += sum(100 + bitcoin_data.tx_type.packed_size(after[x]) for x in added)
195 assert self.remote_remembered_txs_size <= self.max_remembered_txs_size
196 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])
198 self.send_forget_tx(tx_hashes=list(removed))
199 self.remote_remembered_txs_size -= sum(100 + bitcoin_data.tx_type.packed_size(before[x]) for x in removed)
200 watch_id2 = self.node.mining_txs_var.transitioned.watch(update_remote_view_of_my_mining_txs)
201 self.connection_lost_event.watch(lambda: self.node.mining_txs_var.transitioned.unwatch(watch_id2))
203 self.remote_remembered_txs_size += sum(100 + bitcoin_data.tx_type.packed_size(x) for x in self.node.mining_txs_var.value.values())
204 assert self.remote_remembered_txs_size <= self.max_remembered_txs_size
205 fragment(self.send_remember_tx, tx_hashes=[], txs=self.node.mining_txs_var.value.values())
207 message_ping = pack.ComposedType([])
208 def handle_ping(self):
211 message_addrme = pack.ComposedType([
212 ('port', pack.IntType(16)),
214 def handle_addrme(self, port):
215 host = self.transport.getPeer().host
216 #print 'addrme from', host, port
217 if host == '127.0.0.1':
218 if random.random() < .8 and self.node.peers:
219 random.choice(self.node.peers.values()).send_addrme(port=port) # services...
221 self.node.got_addr((self.transport.getPeer().host, port), self.other_services, int(time.time()))
222 if random.random() < .8 and self.node.peers:
223 random.choice(self.node.peers.values()).send_addrs(addrs=[
226 services=self.other_services,
230 timestamp=int(time.time()),
234 message_addrs = pack.ComposedType([
235 ('addrs', pack.ListType(pack.ComposedType([
236 ('timestamp', pack.IntType(64)),
237 ('address', bitcoin_data.address_type),
240 def handle_addrs(self, addrs):
241 for addr_record in addrs:
242 self.node.got_addr((addr_record['address']['address'], addr_record['address']['port']), addr_record['address']['services'], min(int(time.time()), addr_record['timestamp']))
243 if random.random() < .8 and self.node.peers:
244 random.choice(self.node.peers.values()).send_addrs(addrs=[addr_record])
246 message_getaddrs = pack.ComposedType([
247 ('count', pack.IntType(32)),
249 def handle_getaddrs(self, count):
252 self.send_addrs(addrs=[
254 timestamp=int(self.node.addr_store[host, port][2]),
256 services=self.node.addr_store[host, port][0],
261 self.node.get_good_peers(count)
264 message_shares = pack.ComposedType([
265 ('shares', pack.ListType(p2pool_data.share_type)),
267 def handle_shares(self, shares):
268 self.node.handle_shares([p2pool_data.load_share(share, self.node.net, self.addr) for share in shares if share['type'] >= 9], self)
270 def sendShares(self, shares, tracker, known_txs, include_txs_with=[]):
271 if self.other_version >= 8:
274 if share.hash in include_txs_with:
275 x = share.get_other_tx_hashes(tracker)
279 hashes_to_send = [x for x in tx_hashes if x not in self.node.mining_txs_var.value and x in known_txs]
281 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)
282 if new_remote_remembered_txs_size > self.max_remembered_txs_size:
283 raise ValueError('shares have too many txs')
284 self.remote_remembered_txs_size = new_remote_remembered_txs_size
286 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])
288 fragment(self.send_shares, shares=[share.as_share() for share in shares])
290 if self.other_version >= 8:
291 self.send_forget_tx(tx_hashes=hashes_to_send)
293 self.remote_remembered_txs_size -= sum(100 + bitcoin_data.tx_type.packed_size(known_txs[x]) for x in hashes_to_send)
296 message_sharereq = pack.ComposedType([
297 ('id', pack.IntType(256)),
298 ('hashes', pack.ListType(pack.IntType(256))),
299 ('parents', pack.VarIntType()),
300 ('stops', pack.ListType(pack.IntType(256))),
302 def handle_sharereq(self, id, hashes, parents, stops):
303 shares = self.node.handle_get_shares(hashes, parents, stops, self)
305 self.send_sharereply(id=id, result='good', shares=[share.as_share() for share in shares])
306 except p2protocol.TooLong:
307 self.send_sharereply(id=id, result='too long', shares=[])
309 message_sharereply = pack.ComposedType([
310 ('id', pack.IntType(256)),
311 ('result', pack.EnumType(pack.VarIntType(), {0: 'good', 1: 'too long', 2: 'unk2', 3: 'unk3', 4: 'unk4', 5: 'unk5', 6: 'unk6'})),
312 ('shares', pack.ListType(p2pool_data.share_type)),
314 def handle_sharereply(self, id, result, shares):
316 res = [p2pool_data.load_share(share, self.node.net, self.addr) for share in shares if share['type'] >= 9]
318 res = failure.Failure("sharereply result: " + result)
319 self.get_shares.got_response(id, res)
322 message_bestblock = pack.ComposedType([
323 ('header', bitcoin_data.block_header_type),
325 def handle_bestblock(self, header):
326 self.node.handle_bestblock(header, self)
329 message_have_tx = pack.ComposedType([
330 ('tx_hashes', pack.ListType(pack.IntType(256))),
332 def handle_have_tx(self, tx_hashes):
333 #assert self.remote_tx_hashes.isdisjoint(tx_hashes)
334 self.remote_tx_hashes.update(tx_hashes)
335 while len(self.remote_tx_hashes) > 10000:
336 self.remote_tx_hashes.pop()
337 message_losing_tx = pack.ComposedType([
338 ('tx_hashes', pack.ListType(pack.IntType(256))),
340 def handle_losing_tx(self, tx_hashes):
341 #assert self.remote_tx_hashes.issuperset(tx_hashes)
342 self.remote_tx_hashes.difference_update(tx_hashes)
345 message_remember_tx = pack.ComposedType([
346 ('tx_hashes', pack.ListType(pack.IntType(256))),
347 ('txs', pack.ListType(bitcoin_data.tx_type)),
349 def handle_remember_tx(self, tx_hashes, txs):
350 for tx_hash in tx_hashes:
351 if tx_hash in self.remembered_txs:
352 print >>sys.stderr, 'Peer referenced transaction twice, disconnecting'
353 self.transport.loseConnection()
356 if tx_hash in self.node.known_txs_var.value:
357 tx = self.node.known_txs_var.value[tx_hash]
359 for cache in self.known_txs_cache.itervalues():
362 print 'Transaction %064x rescued from peer latency cache!' % (tx_hash,)
365 print >>sys.stderr, 'Peer referenced unknown transaction %064x, disconnecting' % (tx_hash,)
366 self.transport.loseConnection()
369 self.remembered_txs[tx_hash] = tx
370 self.remembered_txs_size += 100 + bitcoin_data.tx_type.packed_size(tx)
371 new_known_txs = dict(self.node.known_txs_var.value)
374 tx_hash = bitcoin_data.hash256(bitcoin_data.tx_type.pack(tx))
375 if tx_hash in self.remembered_txs:
376 print >>sys.stderr, 'Peer referenced transaction twice, disconnecting'
377 self.transport.loseConnection()
380 if tx_hash in self.node.known_txs_var.value and not warned:
381 print 'Peer sent entire transaction %064x that was already received' % (tx_hash,)
384 self.remembered_txs[tx_hash] = tx
385 self.remembered_txs_size += 100 + bitcoin_data.tx_type.packed_size(tx)
386 new_known_txs[tx_hash] = tx
387 self.node.known_txs_var.set(new_known_txs)
388 if self.remembered_txs_size >= self.max_remembered_txs_size:
389 raise PeerMisbehavingError('too much transaction data stored')
390 message_forget_tx = pack.ComposedType([
391 ('tx_hashes', pack.ListType(pack.IntType(256))),
393 def handle_forget_tx(self, tx_hashes):
394 for tx_hash in tx_hashes:
395 self.remembered_txs_size -= 100 + bitcoin_data.tx_type.packed_size(self.remembered_txs[tx_hash])
396 assert self.remembered_txs_size >= 0
397 del self.remembered_txs[tx_hash]
400 def connectionLost(self, reason):
401 self.connection_lost_event.happened()
402 if self.timeout_delayed is not None:
403 self.timeout_delayed.cancel()
405 self.factory.proto_disconnected(self, reason)
408 self.connected2 = False
409 self.factory.proto_lost_connection(self, reason)
411 print "Peer connection lost:", self.addr, reason
412 self.get_shares.respond_all(reason)
414 @defer.inlineCallbacks
416 start = reactor.seconds()
417 yield self.get_shares(hashes=[0], parents=0, stops=[])
418 end = reactor.seconds()
419 defer.returnValue(end - start)
421 class ServerFactory(protocol.ServerFactory):
422 def __init__(self, node, max_conns):
424 self.max_conns = max_conns
428 self.listen_port = None
430 def buildProtocol(self, addr):
431 if sum(self.conns.itervalues()) >= self.max_conns or self.conns.get(self._host_to_ident(addr.host), 0) >= 3:
433 if addr.host in self.node.bans and self.node.bans[addr.host] > time.time():
435 p = Protocol(self.node, True)
438 print "Got peer connection from:", addr
441 def _host_to_ident(self, host):
442 a, b, c, d = host.split('.')
445 def proto_made_connection(self, proto):
446 ident = self._host_to_ident(proto.transport.getPeer().host)
447 self.conns[ident] = self.conns.get(ident, 0) + 1
448 def proto_lost_connection(self, proto, reason):
449 ident = self._host_to_ident(proto.transport.getPeer().host)
450 self.conns[ident] -= 1
451 if not self.conns[ident]:
452 del self.conns[ident]
454 def proto_connected(self, proto):
455 self.node.got_conn(proto)
456 def proto_disconnected(self, proto, reason):
457 self.node.lost_conn(proto, reason)
460 assert not self.running
463 def attempt_listen():
465 self.listen_port = reactor.listenTCP(self.node.port, self)
466 deferral.retry('Error binding to P2P port:', traceback=False)(attempt_listen)()
472 return self.listen_port.stopListening()
474 class ClientFactory(protocol.ClientFactory):
475 def __init__(self, node, desired_conns, max_attempts):
477 self.desired_conns = desired_conns
478 self.max_attempts = max_attempts
480 self.attempts = set()
484 def _host_to_ident(self, host):
485 a, b, c, d = host.split('.')
488 def buildProtocol(self, addr):
489 p = Protocol(self.node, False)
493 def startedConnecting(self, connector):
494 ident = self._host_to_ident(connector.getDestination().host)
495 if ident in self.attempts:
496 raise AssertionError('already have attempt')
497 self.attempts.add(ident)
499 def clientConnectionFailed(self, connector, reason):
500 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
502 def clientConnectionLost(self, connector, reason):
503 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
505 def proto_made_connection(self, proto):
507 def proto_lost_connection(self, proto, reason):
510 def proto_connected(self, proto):
511 self.conns.add(proto)
512 self.node.got_conn(proto)
513 def proto_disconnected(self, proto, reason):
514 self.conns.remove(proto)
515 self.node.lost_conn(proto, reason)
518 assert not self.running
520 self._stop_thinking = deferral.run_repeatedly(self._think)
524 self._stop_thinking()
528 if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and self.node.addr_store:
529 (host, port), = self.node.get_good_peers(1)
531 if self._host_to_ident(host) in self.attempts:
533 elif host in self.node.bans and self.node.bans[host] > time.time():
536 #print 'Trying to connect to', host, port
537 reactor.connectTCP(host, port, self, timeout=5)
541 return random.expovariate(1/1)
543 class SingleClientFactory(protocol.ReconnectingClientFactory):
544 def __init__(self, node):
547 def buildProtocol(self, addr):
548 p = Protocol(self.node, incoming=False)
552 def proto_made_connection(self, proto):
554 def proto_lost_connection(self, proto, reason):
557 def proto_connected(self, proto):
559 self.node.got_conn(proto)
560 def proto_disconnected(self, proto, reason):
561 self.node.lost_conn(proto, reason)
564 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({})):
565 self.best_share_hash_func = best_share_hash_func
568 self.addr_store = dict(addr_store)
569 self.connect_addrs = connect_addrs
570 self.preferred_storage = preferred_storage
571 self.known_txs_var = known_txs_var
572 self.mining_txs_var = mining_txs_var
574 self.traffic_happened = variable.Event()
575 self.nonce = random.randrange(2**64)
577 self.bans = {} # address -> end_time
578 self.clientfactory = ClientFactory(self, desired_outgoing_conns, max_outgoing_attempts)
579 self.serverfactory = ServerFactory(self, max_incoming_conns)
584 raise ValueError('already running')
586 self.clientfactory.start()
587 self.serverfactory.start()
588 self.singleclientconnectors = [reactor.connectTCP(addr, port, SingleClientFactory(self)) for addr, port in self.connect_addrs]
592 self._stop_thinking = deferral.run_repeatedly(self._think)
596 if len(self.addr_store) < self.preferred_storage and self.peers:
597 random.choice(self.peers.values()).send_getaddrs(count=8)
601 return random.expovariate(1/20)
603 @defer.inlineCallbacks
606 raise ValueError('already stopped')
610 self._stop_thinking()
611 yield self.clientfactory.stop()
612 yield self.serverfactory.stop()
613 for singleclientconnector in self.singleclientconnectors:
614 yield singleclientconnector.factory.stopTrying()
615 yield singleclientconnector.disconnect()
616 del self.singleclientconnectors
618 def got_conn(self, conn):
619 if conn.nonce in self.peers:
620 raise ValueError('already have peer')
621 self.peers[conn.nonce] = conn
623 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)
625 def lost_conn(self, conn, reason):
626 if conn.nonce not in self.peers:
627 raise ValueError('''don't have peer''')
628 if conn is not self.peers[conn.nonce]:
629 raise ValueError('wrong conn')
630 del self.peers[conn.nonce]
632 print 'Lost peer %s:%i - %s' % (conn.addr[0], conn.addr[1], reason.getErrorMessage())
635 def got_addr(self, (host, port), services, timestamp):
636 if (host, port) in self.addr_store:
637 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
638 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
640 if len(self.addr_store) < 10000:
641 self.addr_store[host, port] = services, timestamp, timestamp
643 def handle_shares(self, shares, peer):
644 print 'handle_shares', (shares, peer)
646 def handle_share_hashes(self, hashes, peer):
647 print 'handle_share_hashes', (hashes, peer)
649 def handle_get_shares(self, hashes, parents, stops, peer):
650 print 'handle_get_shares', (hashes, parents, stops, peer)
652 def handle_bestblock(self, header, peer):
653 print 'handle_bestblock', header
655 def get_good_peers(self, max_count):
657 return [x[0] for x in sorted(self.addr_store.iteritems(), key=lambda (k, (services, first_seen, last_seen)):
658 -math.log(max(3600, last_seen - first_seen))/math.log(max(3600, t - last_seen))*random.expovariate(1)