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, variable, dicts
16 # 0: send hash first (high latency, low bandwidth)
17 # 1: send entire share (low latency, high bandwidth)
19 class Protocol(bitcoin_p2p.BaseProtocol):
21 sub_version = p2pool.__version__
23 def __init__(self, node):
26 self._prefix = self.node.net.PREFIX
28 max_payload_length = 1000000
37 return min(self.node.mode_var.value, self.other_mode_var.value)
39 def connectionMade(self):
40 bitcoin_p2p.BaseProtocol.connectionMade(self)
42 self.addr = self.transport.getPeer().host, self.transport.getPeer().port
49 address=self.transport.getPeer().host,
50 port=self.transport.getPeer().port,
54 address=self.transport.getHost().host,
55 port=self.transport.getHost().port,
57 nonce=self.node.nonce,
58 sub_version=self.sub_version,
59 mode=self.node.mode_var.value,
60 best_share_hash=self.node.current_work.value['best_share_hash'],
63 self.node_var_watch = self.node.mode_var.changed.watch(lambda new_mode: self.send_setmode(mode=new_mode))
65 reactor.callLater(10, self._connect_timeout)
66 self.timeout_delayed = reactor.callLater(100, self._timeout)
68 def _connect_timeout(self):
69 if not self.connected2 and self.transport.connected:
70 print 'Handshake timed out, disconnecting from %s:%i' % self.addr
71 self.transport.loseConnection()
74 if not self.timeout_delayed.called:
75 self.timeout_delayed.cancel()
76 self.timeout_delayed = reactor.callLater(100, self._timeout)
79 if self.transport.connected:
80 print 'Connection timed out, disconnecting from %s:%i' % self.addr
81 self.transport.loseConnection()
83 @defer.inlineCallbacks
85 while self.connected2:
87 yield deferral.sleep(random.expovariate(1/100))
89 @defer.inlineCallbacks
91 while self.connected2:
92 self.send_addrme(port=self.node.port)
93 #print 'sending addrme'
94 yield deferral.sleep(random.expovariate(1/(100*len(self.node.peers) + 1)))
96 message_version = bitcoin_data.ComposedType([
97 ('version', bitcoin_data.StructType('<I')),
98 ('services', bitcoin_data.StructType('<Q')),
99 ('addr_to', bitcoin_data.address_type),
100 ('addr_from', bitcoin_data.address_type),
101 ('nonce', bitcoin_data.StructType('<Q')),
102 ('sub_version', bitcoin_data.VarStrType()),
103 ('mode', bitcoin_data.StructType('<I')),
104 ('best_share_hash', bitcoin_data.PossiblyNoneType(0, bitcoin_data.HashType())),
106 def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, best_share_hash):
107 self.other_version = version
108 self.other_sub_version = sub_version[:512]
109 self.other_services = services
110 self.other_mode_var = variable.Variable(mode)
112 if nonce == self.node.nonce:
113 #print 'Detected connection to self, disconnecting from %s:%i' % self.addr
114 self.transport.loseConnection()
116 if nonce in self.node.peers:
117 #print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
118 self.transport.loseConnection()
122 self.connected2 = True
123 self.node.got_conn(self)
128 if best_share_hash is not None:
129 self.handle_share0s(hashes=[best_share_hash])
132 message_setmode = bitcoin_data.ComposedType([
133 ('mode', bitcoin_data.StructType('<I')),
135 def handle_setmode(self, mode):
136 self.other_mode_var.set(mode)
138 message_ping = bitcoin_data.ComposedType([])
139 def handle_ping(self):
142 message_addrme = bitcoin_data.ComposedType([
143 ('port', bitcoin_data.StructType('<H')),
145 def handle_addrme(self, port):
146 host = self.transport.getPeer().host
147 #print 'addrme from', host, port
148 if host == '127.0.0.1':
149 if random.random() < .8 and self.node.peers:
150 random.choice(self.node.peers.values()).send_addrme(port=port) # services...
152 self.node.got_addr((self.transport.getPeer().host, port), self.other_services, int(time.time()))
153 if random.random() < .8 and self.node.peers:
154 random.choice(self.node.peers.values()).send_addrs(addrs=[
157 services=self.other_services,
161 timestamp=int(time.time()),
165 message_addrs = bitcoin_data.ComposedType([
166 ('addrs', bitcoin_data.ListType(bitcoin_data.ComposedType([
167 ('timestamp', bitcoin_data.StructType('<Q')),
168 ('address', bitcoin_data.address_type),
171 def handle_addrs(self, addrs):
172 for addr_record in addrs:
173 self.node.got_addr((addr_record['address']['address'], addr_record['address']['port']), addr_record['address']['services'], min(int(time.time()), addr_record['timestamp']))
174 if random.random() < .8 and self.node.peers:
175 random.choice(self.node.peers.values()).send_addrs(addrs=[addr_record])
177 message_getaddrs = bitcoin_data.ComposedType([
178 ('count', bitcoin_data.StructType('<I')),
180 def handle_getaddrs(self, count):
183 self.send_addrs(addrs=[
185 timestamp=self.node.addr_store[host, port][2],
187 services=self.node.addr_store[host, port][0],
192 random.sample(self.node.addr_store.keys(), min(count, len(self.node.addr_store)))
195 message_getshares = bitcoin_data.ComposedType([
196 ('hashes', bitcoin_data.ListType(bitcoin_data.HashType())),
197 ('parents', bitcoin_data.VarIntType()),
198 ('stops', bitcoin_data.ListType(bitcoin_data.HashType())),
200 def handle_getshares(self, hashes, parents, stops):
201 self.node.handle_get_shares(hashes, parents, stops, self)
203 message_share0s = bitcoin_data.ComposedType([
204 ('hashes', bitcoin_data.ListType(bitcoin_data.HashType())),
206 def handle_share0s(self, hashes):
207 self.node.handle_share_hashes(hashes, self)
209 message_shares = bitcoin_data.ComposedType([
210 ('shares', bitcoin_data.ListType(p2pool_data.new_share_type)),
212 def handle_shares(self, shares):
213 self.node.handle_shares([p2pool_data.Share.from_share(x, self.node.net) for x in shares], self)
215 message_share1as = bitcoin_data.ComposedType([
216 ('share1as', bitcoin_data.ListType(p2pool_data.share1a_type)),
218 def handle_share1as(self, share1as):
220 for share1a in share1as:
221 if self.node.net.BITCOIN_POW_FUNC(share1a['header']) <= share1a['header']['target']:
222 print 'Dropping peer %s:%i due to invalid share' % self.addr
223 self.transport.loseConnection()
225 share = p2pool_data.Share.from_share1a(share1a, self.node.net)
226 share.peer = self # XXX
228 self.node.handle_shares(shares, self)
230 message_share1bs = bitcoin_data.ComposedType([
231 ('share1bs', bitcoin_data.ListType(p2pool_data.share1b_type)),
233 def handle_share1bs(self, share1bs):
235 for share1b in share1bs:
236 if not self.node.net.BITCOIN_POW_FUNC(share1a['header']) <= share1b['header']['target']:
237 print 'Dropping peer %s:%i due to invalid share' % self.addr
238 self.transport.loseConnection()
240 share = p2pool_data.Share.from_share1b(share1b, self.node.net)
241 share.peer = self # XXX
243 self.node.handle_shares(shares, self)
245 def sendShares(self, shares, full=False):
250 # XXX doesn't need to send full block when it's not urgent
251 # eg. when getting history
253 if isinstance(share, p2pool_data.NewShare):
254 new_shares.append(share.as_share())
256 if share.pow_hash <= share.header['target']:
257 share1bs.append(share.as_share1b())
259 if self.mode == 0 and not full:
260 share0s.append(share.hash)
261 elif self.mode == 1 or full:
262 share1as.append(share.as_share1a())
264 raise ValueError(self.mode)
265 def att(f, **kwargs):
268 except bitcoin_p2p.TooLong:
269 att(f, **dict((k, v[:len(v)//2]) for k, v in kwargs.iteritems()))
270 att(f, **dict((k, v[len(v)//2:]) for k, v in kwargs.iteritems()))
271 if share0s: att(self.send_share0s, hashes=share0s)
272 if share1as: att(self.send_share1as, share1as=share1as)
273 if share1bs: att(self.send_share1bs, share1bs=share1bs)
274 if new_shares: att(self.send_shares, shares=new_shares)
276 def connectionLost(self, reason):
277 if self.node_var_watch is not None:
278 self.node.mode_var.changed.unwatch(self.node_var_watch)
281 self.node.lost_conn(self)
283 class ServerFactory(protocol.ServerFactory):
284 def __init__(self, node):
287 def buildProtocol(self, addr):
288 p = Protocol(self.node)
292 class ClientFactory(protocol.ClientFactory):
293 def __init__(self, node):
296 def buildProtocol(self, addr):
297 p = Protocol(self.node)
301 def startedConnecting(self, connector):
302 self.node.attempt_started(connector)
304 def clientConnectionFailed(self, connector, reason):
305 self.node.attempt_failed(connector)
307 def clientConnectionLost(self, connector, reason):
308 self.node.attempt_ended(connector)
310 addrdb_key = bitcoin_data.ComposedType([
311 ('address', bitcoin_data.IPV6AddressType()),
312 ('port', bitcoin_data.StructType('>H')),
314 addrdb_value = bitcoin_data.ComposedType([
315 ('services', bitcoin_data.StructType('<Q')),
316 ('first_seen', bitcoin_data.StructType('<Q')),
317 ('last_seen', bitcoin_data.StructType('<Q')),
320 class AddrStore(dicts.DictWrapper):
321 def encode_key(self, (address, port)):
322 return addrdb_key.pack(dict(address=address, port=port))
323 def decode_key(self, encoded_key):
324 k = addrdb_key.unpack(encoded_key)
325 return k['address'], k['port']
327 def encode_value(self, (services, first_seen, last_seen)):
328 return addrdb_value.pack(dict(services=services, first_seen=first_seen, last_seen=last_seen))
329 def decode_value(self, encoded_value):
330 v = addrdb_value.unpack(encoded_value)
331 return v['services'], v['first_seen'], v['last_seen']
334 def __init__(self, current_work, port, net, addr_store=None, preferred_addrs=set(), mode=0, desired_peers=10, max_attempts=100, preferred_storage=1000):
335 if addr_store is None:
340 self.addr_store = AddrStore(addr_store)
341 self.preferred_addrs = preferred_addrs
342 self.mode_var = variable.Variable(mode)
343 self.desired_peers = desired_peers
344 self.max_attempts = max_attempts
345 self.current_work = current_work
346 self.preferred_storage = preferred_storage
348 self.nonce = random.randrange(2**64)
355 raise ValueError('already running')
359 self.listen_port = reactor.listenTCP(self.port, ServerFactory(self))
364 @defer.inlineCallbacks
368 if len(self.peers) < self.desired_peers and len(self.attempts) < self.max_attempts and (len(self.preferred_addrs) or len(self.addr_store)):
369 if (random.randrange(2) and len(self.preferred_addrs)) or not len(self.addr_store):
370 host, port = random.choice(list(self.preferred_addrs))
372 host, port = random.choice(self.addr_store.keys())
374 if (host, port) not in self.attempts:
375 #print 'Trying to connect to', host, port
376 reactor.connectTCP(host, port, ClientFactory(self), timeout=10)
380 yield deferral.sleep(random.expovariate(1/5))
382 @defer.inlineCallbacks
386 if len(self.addr_store) < self.preferred_storage and self.peers:
387 random.choice(self.peers.values()).send_getaddrs(count=8)
391 yield deferral.sleep(random.expovariate(1/20))
395 raise ValueError('already stopped')
399 self.listen_port.stopListening()
402 def attempt_started(self, connector):
403 host, port = connector.getDestination().host, connector.getDestination().port
404 if (host, port) in self.attempts:
405 raise ValueError('already have attempt')
406 self.attempts[host, port] = connector
408 def attempt_failed(self, connector):
409 self.attempt_ended(connector)
411 def attempt_ended(self, connector):
412 host, port = connector.getDestination().host, connector.getDestination().port
413 if (host, port) not in self.attempts:
414 raise ValueError('''don't have attempt''')
415 if connector is not self.attempts[host, port]:
416 raise ValueError('wrong connector')
417 del self.attempts[host, port]
420 def got_conn(self, conn):
421 if conn.nonce in self.peers:
422 raise ValueError('already have peer')
423 self.peers[conn.nonce] = conn
425 print 'Connected to peer %s:%i. p2pool version: %r' % (conn.addr[0], conn.addr[1], conn.other_sub_version)
427 def lost_conn(self, conn):
428 if conn.nonce not in self.peers:
429 raise ValueError('''don't have peer''')
430 if conn is not self.peers[conn.nonce]:
431 raise ValueError('wrong conn')
432 del self.peers[conn.nonce]
434 print 'Lost peer %s:%i' % (conn.addr[0], conn.addr[1])
437 def got_addr(self, (host, port), services, timestamp):
438 if (host, port) in self.addr_store:
439 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
440 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
442 self.addr_store[host, port] = services, timestamp, timestamp
444 def handle_shares(self, shares, peer):
445 print 'handle_shares', (shares, peer)
447 def handle_share_hashes(self, hashes, peer):
448 print 'handle_share_hashes', (hashes, peer)
450 def handle_get_shares(self, hashes, parents, stops, peer):
451 print 'handle_get_shares', (hashes, parents, stops, peer)
453 if __name__ == '__main__':
454 p = random.randrange(2**15, 2**16)
456 p2 = random.randrange(2**15, 2**16)
458 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())))})