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_share1as = bitcoin_data.ComposedType([
210 ('share1as', bitcoin_data.ListType(p2pool_data.share1a_type)),
212 def handle_share1as(self, share1as):
214 for share1a in share1as:
215 if self.node.net.BITCOIN_POW_FUNC(share1a['header']) <= share1a['header']['target']:
216 print 'Dropping peer %s:%i due to invalid share' % self.addr
217 self.transport.loseConnection()
219 share = p2pool_data.Share.from_share1a(share1a, self.node.net)
220 share.peer = self # XXX
222 self.node.handle_shares(shares, self)
224 message_share1bs = bitcoin_data.ComposedType([
225 ('share1bs', bitcoin_data.ListType(p2pool_data.share1b_type)),
227 def handle_share1bs(self, share1bs):
229 for share1b in share1bs:
230 if not self.node.net.BITCOIN_POW_FUNC(share1a['header']) <= share1b['header']['target']:
231 print 'Dropping peer %s:%i due to invalid share' % self.addr
232 self.transport.loseConnection()
234 share = p2pool_data.Share.from_share1b(share1b, self.node.net)
235 share.peer = self # XXX
237 self.node.handle_shares(shares, self)
239 def send_shares(self, shares, full=False):
243 # XXX doesn't need to send full block when it's not urgent
244 # eg. when getting history
246 if share.bitcoin_hash <= share.header['target']:
247 share1bs.append(share.as_share1b())
249 if self.mode == 0 and not full:
250 share0s.append(share.hash)
251 elif self.mode == 1 or full:
252 share1as.append(share.as_share1a())
254 raise ValueError(self.mode)
255 def att(f, **kwargs):
258 except bitcoin_p2p.TooLong:
259 att(f, **dict((k, v[:len(v)//2]) for k, v in kwargs.iteritems()))
260 att(f, **dict((k, v[len(v)//2:]) for k, v in kwargs.iteritems()))
261 if share1bs: att(self.send_share1bs, share1bs=share1bs)
262 if share0s: att(self.send_share0s, hashes=share0s)
263 if share1as: att(self.send_share1as, share1as=share1as)
265 def connectionLost(self, reason):
266 if self.node_var_watch is not None:
267 self.node.mode_var.changed.unwatch(self.node_var_watch)
270 self.node.lost_conn(self)
272 class ServerFactory(protocol.ServerFactory):
273 def __init__(self, node):
276 def buildProtocol(self, addr):
277 p = Protocol(self.node)
281 class ClientFactory(protocol.ClientFactory):
282 def __init__(self, node):
285 def buildProtocol(self, addr):
286 p = Protocol(self.node)
290 def startedConnecting(self, connector):
291 self.node.attempt_started(connector)
293 def clientConnectionFailed(self, connector, reason):
294 self.node.attempt_failed(connector)
296 def clientConnectionLost(self, connector, reason):
297 self.node.attempt_ended(connector)
299 addrdb_key = bitcoin_data.ComposedType([
300 ('address', bitcoin_data.IPV6AddressType()),
301 ('port', bitcoin_data.StructType('>H')),
303 addrdb_value = bitcoin_data.ComposedType([
304 ('services', bitcoin_data.StructType('<Q')),
305 ('first_seen', bitcoin_data.StructType('<Q')),
306 ('last_seen', bitcoin_data.StructType('<Q')),
309 class AddrStore(dicts.DictWrapper):
310 def encode_key(self, (address, port)):
311 return addrdb_key.pack(dict(address=address, port=port))
312 def decode_key(self, encoded_key):
313 k = addrdb_key.unpack(encoded_key)
314 return k['address'], k['port']
316 def encode_value(self, (services, first_seen, last_seen)):
317 return addrdb_value.pack(dict(services=services, first_seen=first_seen, last_seen=last_seen))
318 def decode_value(self, encoded_value):
319 v = addrdb_value.unpack(encoded_value)
320 return v['services'], v['first_seen'], v['last_seen']
323 def __init__(self, current_work, port, net, addr_store=None, preferred_addrs=set(), mode=0, desired_peers=10, max_attempts=100, preferred_storage=1000):
324 if addr_store is None:
329 self.addr_store = AddrStore(addr_store)
330 self.preferred_addrs = preferred_addrs
331 self.mode_var = variable.Variable(mode)
332 self.desired_peers = desired_peers
333 self.max_attempts = max_attempts
334 self.current_work = current_work
335 self.preferred_storage = preferred_storage
337 self.nonce = random.randrange(2**64)
344 raise ValueError('already running')
348 self.listen_port = reactor.listenTCP(self.port, ServerFactory(self))
353 @defer.inlineCallbacks
357 if len(self.peers) < self.desired_peers and len(self.attempts) < self.max_attempts and (len(self.preferred_addrs) or len(self.addr_store)):
358 if (random.randrange(2) and len(self.preferred_addrs)) or not len(self.addr_store):
359 host, port = random.choice(list(self.preferred_addrs))
361 host, port = random.choice(self.addr_store.keys())
363 if (host, port) not in self.attempts:
364 #print 'Trying to connect to', host, port
365 reactor.connectTCP(host, port, ClientFactory(self), timeout=10)
369 yield deferral.sleep(random.expovariate(1/5))
371 @defer.inlineCallbacks
375 if len(self.addr_store) < self.preferred_storage and self.peers:
376 random.choice(self.peers.values()).send_getaddrs(count=8)
380 yield deferral.sleep(random.expovariate(1/20))
384 raise ValueError('already stopped')
388 self.listen_port.stopListening()
391 def attempt_started(self, connector):
392 host, port = connector.getDestination().host, connector.getDestination().port
393 if (host, port) in self.attempts:
394 raise ValueError('already have attempt')
395 self.attempts[host, port] = connector
397 def attempt_failed(self, connector):
398 self.attempt_ended(connector)
400 def attempt_ended(self, connector):
401 host, port = connector.getDestination().host, connector.getDestination().port
402 if (host, port) not in self.attempts:
403 raise ValueError('''don't have attempt''')
404 if connector is not self.attempts[host, port]:
405 raise ValueError('wrong connector')
406 del self.attempts[host, port]
409 def got_conn(self, conn):
410 if conn.nonce in self.peers:
411 raise ValueError('already have peer')
412 self.peers[conn.nonce] = conn
414 print 'Connected to peer %s:%i. p2pool version: %r' % (conn.addr[0], conn.addr[1], conn.other_sub_version)
416 def lost_conn(self, conn):
417 if conn.nonce not in self.peers:
418 raise ValueError('''don't have peer''')
419 if conn is not self.peers[conn.nonce]:
420 raise ValueError('wrong conn')
421 del self.peers[conn.nonce]
423 print 'Lost peer %s:%i' % (conn.addr[0], conn.addr[1])
426 def got_addr(self, (host, port), services, timestamp):
427 if (host, port) in self.addr_store:
428 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
429 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
431 self.addr_store[host, port] = services, timestamp, timestamp
433 def handle_shares(self, shares, peer):
434 print 'handle_shares', (shares, peer)
436 def handle_share_hashes(self, hashes, peer):
437 print 'handle_share_hashes', (hashes, peer)
439 def handle_get_shares(self, hashes, parents, stops, peer):
440 print 'handle_get_shares', (hashes, parents, stops, peer)
442 if __name__ == '__main__':
443 p = random.randrange(2**15, 2**16)
445 p2 = random.randrange(2**15, 2**16)
447 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())))})