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 return 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 p2protocol.Protocol.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.transport.loseConnection,
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
85 self.transport.loseConnection()
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):
98 print "Bad peer banned:", self.addr
99 self.transport.loseConnection()
100 if self.transport.getPeer().host != '127.0.0.1': # never ban localhost
101 self.node.bans[self.transport.getPeer().host] = time.time() + 60*60
104 self.timeout_delayed = None
105 print 'Connection timed out, disconnecting from %s:%i' % self.addr
106 self.transport.loseConnection()
108 message_version = pack.ComposedType([
109 ('version', pack.IntType(32)),
110 ('services', pack.IntType(64)),
111 ('addr_to', bitcoin_data.address_type),
112 ('addr_from', bitcoin_data.address_type),
113 ('nonce', pack.IntType(64)),
114 ('sub_version', pack.VarStrType()),
115 ('mode', pack.IntType(32)), # always 1 for legacy compatibility
116 ('best_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
118 def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, best_share_hash):
119 if self.other_version is not None:
120 raise PeerMisbehavingError('more than one version message')
122 raise PeerMisbehavingError('peer too old')
124 self.other_version = version
125 self.other_sub_version = sub_version[:512]
126 self.other_services = services
128 if nonce == self.node.nonce:
129 raise PeerMisbehavingError('was connected to self')
130 if nonce in self.node.peers:
132 print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
133 self.transport.loseConnection()
137 self.connected2 = True
139 self.timeout_delayed.cancel()
140 self.timeout_delayed = reactor.callLater(100, self._timeout)
142 old_dataReceived = self.dataReceived
143 def new_dataReceived(data):
144 if self.timeout_delayed is not None:
145 self.timeout_delayed.reset(100)
146 old_dataReceived(data)
147 self.dataReceived = new_dataReceived
149 self.factory.proto_connected(self)
151 self._stop_thread = deferral.run_repeatedly(lambda: [
153 random.expovariate(1/100)][-1])
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 if self.other_version < 8:
165 def update_remote_view_of_my_known_txs(before, after):
166 added = set(after) - set(before)
167 removed = set(before) - set(after)
169 self.send_have_tx(tx_hashes=list(added))
171 self.send_losing_tx(tx_hashes=list(removed))
173 # cache forgotten txs here for a little while so latency of "losing_tx" packets doesn't cause problems
174 key = max(self.known_txs_cache) + 1 if self.known_txs_cache else 0
175 self.known_txs_cache[key] = dict((h, before[h]) for h in removed)
176 reactor.callLater(20, self.known_txs_cache.pop, key)
177 watch_id = self.node.known_txs_var.transitioned.watch(update_remote_view_of_my_known_txs)
178 self.connection_lost_event.watch(lambda: self.node.known_txs_var.transitioned.unwatch(watch_id))
180 self.send_have_tx(tx_hashes=self.node.known_txs_var.value.keys())
182 def update_remote_view_of_my_mining_txs(before, after):
183 added = set(after) - set(before)
184 removed = set(before) - set(after)
186 self.remote_remembered_txs_size += sum(100 + bitcoin_data.tx_type.packed_size(after[x]) for x in added)
187 assert self.remote_remembered_txs_size <= self.max_remembered_txs_size
188 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])
190 self.send_forget_tx(tx_hashes=list(removed))
191 self.remote_remembered_txs_size -= sum(100 + bitcoin_data.tx_type.packed_size(before[x]) for x in removed)
192 watch_id2 = self.node.mining_txs_var.transitioned.watch(update_remote_view_of_my_mining_txs)
193 self.connection_lost_event.watch(lambda: self.node.mining_txs_var.transitioned.unwatch(watch_id2))
195 self.remote_remembered_txs_size += sum(100 + bitcoin_data.tx_type.packed_size(x) for x in self.node.mining_txs_var.value.values())
196 assert self.remote_remembered_txs_size <= self.max_remembered_txs_size
197 fragment(self.send_remember_tx, tx_hashes=[], txs=self.node.mining_txs_var.value.values())
199 message_ping = pack.ComposedType([])
200 def handle_ping(self):
203 message_addrme = pack.ComposedType([
204 ('port', pack.IntType(16)),
206 def handle_addrme(self, port):
207 host = self.transport.getPeer().host
208 #print 'addrme from', host, port
209 if host == '127.0.0.1':
210 if random.random() < .8 and self.node.peers:
211 random.choice(self.node.peers.values()).send_addrme(port=port) # services...
213 self.node.got_addr((self.transport.getPeer().host, port), self.other_services, int(time.time()))
214 if random.random() < .8 and self.node.peers:
215 random.choice(self.node.peers.values()).send_addrs(addrs=[
218 services=self.other_services,
222 timestamp=int(time.time()),
226 message_addrs = pack.ComposedType([
227 ('addrs', pack.ListType(pack.ComposedType([
228 ('timestamp', pack.IntType(64)),
229 ('address', bitcoin_data.address_type),
232 def handle_addrs(self, addrs):
233 for addr_record in addrs:
234 self.node.got_addr((addr_record['address']['address'], addr_record['address']['port']), addr_record['address']['services'], min(int(time.time()), addr_record['timestamp']))
235 if random.random() < .8 and self.node.peers:
236 random.choice(self.node.peers.values()).send_addrs(addrs=[addr_record])
238 message_getaddrs = pack.ComposedType([
239 ('count', pack.IntType(32)),
241 def handle_getaddrs(self, count):
244 self.send_addrs(addrs=[
246 timestamp=int(self.node.addr_store[host, port][2]),
248 services=self.node.addr_store[host, port][0],
253 self.node.get_good_peers(count)
256 message_shares = pack.ComposedType([
257 ('shares', pack.ListType(p2pool_data.share_type)),
259 def handle_shares(self, shares):
260 self.node.handle_shares([p2pool_data.load_share(share, self.node.net, self) for share in shares if share['type'] >= 9], self)
262 def sendShares(self, shares, tracker, known_txs, include_txs_with=[]):
264 return defer.succeed(None)
266 if self.other_version >= 8:
269 if share.hash in include_txs_with:
270 x = share.get_other_tx_hashes(tracker)
274 hashes_to_send = [x for x in tx_hashes if x not in self.node.mining_txs_var.value and x in known_txs]
276 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)
277 if new_remote_remembered_txs_size > self.max_remembered_txs_size:
278 raise ValueError('shares have too many txs')
279 self.remote_remembered_txs_size = new_remote_remembered_txs_size
281 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])
283 res = fragment(self.send_shares, shares=[share.as_share() for share in shares])
285 if self.other_version >= 8:
286 res = self.send_forget_tx(tx_hashes=hashes_to_send)
288 self.remote_remembered_txs_size -= sum(100 + bitcoin_data.tx_type.packed_size(known_txs[x]) for x in hashes_to_send)
293 message_sharereq = pack.ComposedType([
294 ('id', pack.IntType(256)),
295 ('hashes', pack.ListType(pack.IntType(256))),
296 ('parents', pack.VarIntType()),
297 ('stops', pack.ListType(pack.IntType(256))),
299 def handle_sharereq(self, id, hashes, parents, stops):
300 shares = self.node.handle_get_shares(hashes, parents, stops, self)
302 self.send_sharereply(id=id, result='good', shares=[share.as_share() for share in shares])
303 except p2protocol.TooLong:
304 self.send_sharereply(id=id, result='too long', shares=[])
306 message_sharereply = pack.ComposedType([
307 ('id', pack.IntType(256)),
308 ('result', pack.EnumType(pack.VarIntType(), {0: 'good', 1: 'too long', 2: 'unk2', 3: 'unk3', 4: 'unk4', 5: 'unk5', 6: 'unk6'})),
309 ('shares', pack.ListType(p2pool_data.share_type)),
311 def handle_sharereply(self, id, result, shares):
313 res = [p2pool_data.load_share(share, self.node.net, self) for share in shares if share['type'] >= 9]
315 res = failure.Failure("sharereply result: " + result)
316 self.get_shares.got_response(id, res)
319 message_bestblock = pack.ComposedType([
320 ('header', bitcoin_data.block_header_type),
322 def handle_bestblock(self, header):
323 self.node.handle_bestblock(header, self)
326 message_have_tx = pack.ComposedType([
327 ('tx_hashes', pack.ListType(pack.IntType(256))),
329 def handle_have_tx(self, tx_hashes):
330 #assert self.remote_tx_hashes.isdisjoint(tx_hashes)
331 self.remote_tx_hashes.update(tx_hashes)
332 while len(self.remote_tx_hashes) > 10000:
333 self.remote_tx_hashes.pop()
334 message_losing_tx = pack.ComposedType([
335 ('tx_hashes', pack.ListType(pack.IntType(256))),
337 def handle_losing_tx(self, tx_hashes):
338 #assert self.remote_tx_hashes.issuperset(tx_hashes)
339 self.remote_tx_hashes.difference_update(tx_hashes)
342 message_remember_tx = pack.ComposedType([
343 ('tx_hashes', pack.ListType(pack.IntType(256))),
344 ('txs', pack.ListType(bitcoin_data.tx_type)),
346 def handle_remember_tx(self, tx_hashes, txs):
347 for tx_hash in tx_hashes:
348 if tx_hash in self.remembered_txs:
349 print >>sys.stderr, 'Peer referenced transaction twice, disconnecting'
350 self.transport.loseConnection()
353 if tx_hash in self.node.known_txs_var.value:
354 tx = self.node.known_txs_var.value[tx_hash]
356 for cache in self.known_txs_cache.itervalues():
359 print 'Transaction rescued from peer latency cache!'
362 print >>sys.stderr, 'Peer referenced unknown transaction, disconnecting'
363 self.transport.loseConnection()
366 self.remembered_txs[tx_hash] = tx
367 self.remembered_txs_size += 100 + bitcoin_data.tx_type.packed_size(tx)
368 new_known_txs = dict(self.node.known_txs_var.value)
371 tx_hash = bitcoin_data.hash256(bitcoin_data.tx_type.pack(tx))
372 if tx_hash in self.remembered_txs:
373 print >>sys.stderr, 'Peer referenced transaction twice, disconnecting'
374 self.transport.loseConnection()
377 if tx_hash in self.node.known_txs_var.value and not warned:
378 print 'Peer sent entire transaction that was already received'
381 self.remembered_txs[tx_hash] = tx
382 self.remembered_txs_size += 100 + bitcoin_data.tx_type.packed_size(tx)
383 new_known_txs[tx_hash] = tx
384 self.node.known_txs_var.set(new_known_txs)
385 if self.remembered_txs_size >= self.max_remembered_txs_size:
386 raise PeerMisbehavingError('too much transaction data stored')
387 message_forget_tx = pack.ComposedType([
388 ('tx_hashes', pack.ListType(pack.IntType(256))),
390 def handle_forget_tx(self, tx_hashes):
391 for tx_hash in tx_hashes:
392 self.remembered_txs_size -= 100 + bitcoin_data.tx_type.packed_size(self.remembered_txs[tx_hash])
393 assert self.remembered_txs_size >= 0
394 del self.remembered_txs[tx_hash]
397 def connectionLost(self, reason):
398 self.connection_lost_event.happened()
399 if self.timeout_delayed is not None:
400 self.timeout_delayed.cancel()
402 self.factory.proto_disconnected(self, reason)
405 self.connected2 = False
406 self.factory.proto_lost_connection(self, reason)
408 print "Peer connection lost:", self.addr, reason
409 self.get_shares.respond_all(reason)
411 @defer.inlineCallbacks
413 start = reactor.seconds()
414 yield self.get_shares(hashes=[0], parents=0, stops=[])
415 end = reactor.seconds()
416 defer.returnValue(end - start)
418 class ServerFactory(protocol.ServerFactory):
419 def __init__(self, node, max_conns):
421 self.max_conns = max_conns
425 self.listen_port = None
427 def buildProtocol(self, addr):
428 if sum(self.conns.itervalues()) >= self.max_conns or self.conns.get(self._host_to_ident(addr.host), 0) >= 3:
430 if addr.host in self.node.bans and self.node.bans[addr.host] > time.time():
432 p = Protocol(self.node, True)
435 print "Got peer connection from:", addr
438 def _host_to_ident(self, host):
439 a, b, c, d = host.split('.')
442 def proto_made_connection(self, proto):
443 ident = self._host_to_ident(proto.transport.getPeer().host)
444 self.conns[ident] = self.conns.get(ident, 0) + 1
445 def proto_lost_connection(self, proto, reason):
446 ident = self._host_to_ident(proto.transport.getPeer().host)
447 self.conns[ident] -= 1
448 if not self.conns[ident]:
449 del self.conns[ident]
451 def proto_connected(self, proto):
452 self.node.got_conn(proto)
453 def proto_disconnected(self, proto, reason):
454 self.node.lost_conn(proto, reason)
457 assert not self.running
460 def attempt_listen():
462 self.listen_port = reactor.listenTCP(self.node.port, self)
463 deferral.retry('Error binding to P2P port:', traceback=False)(attempt_listen)()
469 return self.listen_port.stopListening()
471 class ClientFactory(protocol.ClientFactory):
472 def __init__(self, node, desired_conns, max_attempts):
474 self.desired_conns = desired_conns
475 self.max_attempts = max_attempts
477 self.attempts = set()
481 def _host_to_ident(self, host):
482 a, b, c, d = host.split('.')
485 def buildProtocol(self, addr):
486 p = Protocol(self.node, False)
490 def startedConnecting(self, connector):
491 ident = self._host_to_ident(connector.getDestination().host)
492 if ident in self.attempts:
493 raise AssertionError('already have attempt')
494 self.attempts.add(ident)
496 def clientConnectionFailed(self, connector, reason):
497 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
499 def clientConnectionLost(self, connector, reason):
500 self.attempts.remove(self._host_to_ident(connector.getDestination().host))
502 def proto_made_connection(self, proto):
504 def proto_lost_connection(self, proto, reason):
507 def proto_connected(self, proto):
508 self.conns.add(proto)
509 self.node.got_conn(proto)
510 def proto_disconnected(self, proto, reason):
511 self.conns.remove(proto)
512 self.node.lost_conn(proto, reason)
515 assert not self.running
517 self._stop_thinking = deferral.run_repeatedly(self._think)
521 self._stop_thinking()
525 if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and self.node.addr_store:
526 (host, port), = self.node.get_good_peers(1)
528 if self._host_to_ident(host) in self.attempts:
530 elif host in self.node.bans and self.node.bans[host] > time.time():
533 #print 'Trying to connect to', host, port
534 reactor.connectTCP(host, port, self, timeout=5)
538 return random.expovariate(1/1)
540 class SingleClientFactory(protocol.ReconnectingClientFactory):
541 def __init__(self, node):
544 def buildProtocol(self, addr):
545 p = Protocol(self.node, incoming=False)
549 def proto_made_connection(self, proto):
551 def proto_lost_connection(self, proto, reason):
554 def proto_connected(self, proto):
556 self.node.got_conn(proto)
557 def proto_disconnected(self, proto, reason):
558 self.node.lost_conn(proto, reason)
561 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({})):
562 self.best_share_hash_func = best_share_hash_func
565 self.addr_store = dict(addr_store)
566 self.connect_addrs = connect_addrs
567 self.preferred_storage = preferred_storage
568 self.known_txs_var = known_txs_var
569 self.mining_txs_var = mining_txs_var
571 self.traffic_happened = variable.Event()
572 self.nonce = random.randrange(2**64)
574 self.bans = {} # address -> end_time
575 self.clientfactory = ClientFactory(self, desired_outgoing_conns, max_outgoing_attempts)
576 self.serverfactory = ServerFactory(self, max_incoming_conns)
581 raise ValueError('already running')
583 self.clientfactory.start()
584 self.serverfactory.start()
585 self.singleclientconnectors = [reactor.connectTCP(addr, port, SingleClientFactory(self)) for addr, port in self.connect_addrs]
589 self._stop_thinking = deferral.run_repeatedly(self._think)
593 if len(self.addr_store) < self.preferred_storage and self.peers:
594 random.choice(self.peers.values()).send_getaddrs(count=8)
598 return random.expovariate(1/20)
600 @defer.inlineCallbacks
603 raise ValueError('already stopped')
607 self._stop_thinking()
608 yield self.clientfactory.stop()
609 yield self.serverfactory.stop()
610 for singleclientconnector in self.singleclientconnectors:
611 yield singleclientconnector.factory.stopTrying()
612 yield singleclientconnector.disconnect()
613 del self.singleclientconnectors
615 def got_conn(self, conn):
616 if conn.nonce in self.peers:
617 raise ValueError('already have peer')
618 self.peers[conn.nonce] = conn
620 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)
622 def lost_conn(self, conn, reason):
623 if conn.nonce not in self.peers:
624 raise ValueError('''don't have peer''')
625 if conn is not self.peers[conn.nonce]:
626 raise ValueError('wrong conn')
627 del self.peers[conn.nonce]
629 print 'Lost peer %s:%i - %s' % (conn.addr[0], conn.addr[1], reason.getErrorMessage())
632 def got_addr(self, (host, port), services, timestamp):
633 if (host, port) in self.addr_store:
634 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
635 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
637 self.addr_store[host, port] = services, timestamp, timestamp
639 def handle_shares(self, shares, peer):
640 print 'handle_shares', (shares, peer)
642 def handle_share_hashes(self, hashes, peer):
643 print 'handle_share_hashes', (hashes, peer)
645 def handle_get_shares(self, hashes, parents, stops, peer):
646 print 'handle_get_shares', (hashes, parents, stops, peer)
648 def handle_bestblock(self, header, peer):
649 print 'handle_bestblock', header
651 def get_good_peers(self, max_count):
653 return [x[0] for x in sorted(self.addr_store.iteritems(), key=lambda (k, (services, first_seen, last_seen)):
654 -math.log(max(3600, last_seen - first_seen))/math.log(max(3600, t - last_seen))*random.expovariate(1)