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
29 max_net_payload_length = 2000000
39 return min(self.node.mode_var.value, self.other_mode_var.value)
41 def connectionMade(self):
42 bitcoin_p2p.BaseProtocol.connectionMade(self)
44 self.addr = self.transport.getPeer().host, self.transport.getPeer().port
51 address=self.transport.getPeer().host,
52 port=self.transport.getPeer().port,
56 address=self.transport.getHost().host,
57 port=self.transport.getHost().port,
59 nonce=self.node.nonce,
60 sub_version=self.sub_version,
61 mode=self.node.mode_var.value,
62 best_share_hash=self.node.current_work.value['best_share_hash'],
65 self.node_var_watch = self.node.mode_var.changed.watch(lambda new_mode: self.send_setmode(mode=new_mode))
67 reactor.callLater(10, self._connect_timeout)
69 def _connect_timeout(self):
70 if not self.connected2 and self.transport.connected:
71 print 'Handshake timed out, disconnecting from %s:%i' % self.addr
72 self.transport.loseConnection()
74 @defer.inlineCallbacks
76 while self.connected2:
78 yield deferral.sleep(random.expovariate(1/100))
80 @defer.inlineCallbacks
82 while self.connected2:
83 self.send_addrme(port=self.node.port)
84 #print 'sending addrme'
85 yield deferral.sleep(random.expovariate(1/(100*len(self.node.peers))))
87 message_version = bitcoin_data.ComposedType([
88 ('version', bitcoin_data.StructType('<I')),
89 ('services', bitcoin_data.StructType('<Q')),
90 ('addr_to', bitcoin_data.address_type),
91 ('addr_from', bitcoin_data.address_type),
92 ('nonce', bitcoin_data.StructType('<Q')),
93 ('sub_version', bitcoin_data.VarStrType()),
94 ('mode', bitcoin_data.StructType('<I')),
95 ('best_share_hash', bitcoin_data.PossiblyNone(0, bitcoin_data.HashType())),
97 def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, best_share_hash):
98 self.other_version = version
99 self.other_services = services
100 self.other_mode_var = variable.Variable(mode)
102 if nonce == self.node.nonce:
103 #print 'Detected connection to self, disconnecting from %s:%i' % self.addr
104 self.transport.loseConnection()
106 if nonce in self.node.peers:
107 #print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
108 self.transport.loseConnection()
112 self.connected2 = True
113 self.node.got_conn(self)
118 if best_share_hash is not None:
119 self.handle_share0s(hashes=[best_share_hash])
122 message_setmode = bitcoin_data.ComposedType([
123 ('mode', bitcoin_data.StructType('<I')),
125 def handle_setmode(self, mode):
126 self.other_mode_var.set(mode)
128 message_ping = bitcoin_data.ComposedType([])
129 def handle_ping(self):
132 message_addrme = bitcoin_data.ComposedType([
133 ('port', bitcoin_data.StructType('<H')),
135 def handle_addrme(self, port):
136 host = self.transport.getPeer().host
137 #print 'addrme from', host, port
138 if host == '127.0.0.1':
139 if random.random() < .8 and self.node.peers:
140 random.choice(self.node.peers.values()).send_addrme(port=port) # services...
142 self.node.got_addr((self.transport.getPeer().host, port), self.other_services, int(time.time()))
143 if random.random() < .8 and self.node.peers:
144 random.choice(self.node.peers.values()).send_addrs(addrs=[
147 services=self.other_services,
151 timestamp=int(time.time()),
155 message_addrs = bitcoin_data.ComposedType([
156 ('addrs', bitcoin_data.ListType(bitcoin_data.ComposedType([
157 ('timestamp', bitcoin_data.StructType('<Q')),
158 ('address', bitcoin_data.address_type),
161 def handle_addrs(self, addrs):
162 for addr_record in addrs:
163 self.node.got_addr((addr_record['address']['address'], addr_record['address']['port']), addr_record['address']['services'], min(int(time.time()), addr_record['timestamp']))
164 if random.random() < .8 and self.node.peers:
165 random.choice(self.node.peers.values()).send_addrs(addrs=[addr_record])
167 message_getaddrs = bitcoin_data.ComposedType([
168 ('count', bitcoin_data.StructType('<I')),
170 def handle_getaddrs(self, count):
173 self.send_addrs(addrs=[
175 timestamp=self.node.addr_store[host, port][2],
177 services=self.node.addr_store[host, port][0],
182 random.sample(self.node.addr_store.keys(), min(count, len(self.node.addr_store)))
185 message_getshares = bitcoin_data.ComposedType([
186 ('hashes', bitcoin_data.ListType(bitcoin_data.HashType())),
187 ('parents', bitcoin_data.VarIntType()),
188 ('stops', bitcoin_data.ListType(bitcoin_data.HashType())),
190 def handle_getshares(self, hashes, parents, stops):
191 self.node.handle_get_shares(hashes, parents, stops, self)
193 message_share0s = bitcoin_data.ComposedType([
194 ('hashes', bitcoin_data.ListType(bitcoin_data.HashType())),
196 def handle_share0s(self, hashes):
197 self.node.handle_share_hashes(hashes, self)
199 message_share1as = bitcoin_data.ComposedType([
200 ('share1as', bitcoin_data.ListType(p2pool_data.share1a_type)),
202 def handle_share1as(self, share1as):
204 for share1a in share1as:
205 hash_ = bitcoin_data.block_header_type.hash256(share1a['header'])
206 if hash_ <= share1a['header']['target']:
207 print 'Dropping peer %s:%i due to invalid share' % self.addr
208 self.transport.loseConnection()
210 share = p2pool_data.Share.from_share1a(share1a)
211 share.peer = self # XXX
213 self.node.handle_shares(shares, self)
215 message_share1bs = bitcoin_data.ComposedType([
216 ('share1bs', bitcoin_data.ListType(p2pool_data.share1b_type)),
218 def handle_share1bs(self, share1bs):
220 for share1b in share1bs:
221 hash_ = bitcoin_data.block_header_type.hash256(share1b['header'])
222 if not hash_ <= share1b['header']['target']:
223 print 'Dropping peer %s:%i due to invalid share' % self.addr
224 self.transport.loseConnection()
226 share = p2pool_data.Share.from_share1b(share1b)
227 share.peer = self # XXX
229 self.node.handle_shares(shares, self)
231 def send_shares(self, shares, full=False):
235 # XXX doesn't need to send full block when it's not urgent
236 # eg. when getting history
238 if share.bitcoin_hash <= share.header['target']:
239 share1bs.append(share.as_share1b())
241 if self.mode == 0 and not full:
242 share0s.append(share.hash)
243 elif self.mode == 1 or full:
244 share1as.append(share.as_share1a())
246 raise ValueError(self.mode)
247 def att(f, **kwargs):
250 except bitcoin_p2p.TooLong:
251 att(f, **dict((k, v[:len(v)//2]) for k, v in kwargs.iteritems()))
252 att(f, **dict((k, v[len(v)//2:]) for k, v in kwargs.iteritems()))
253 if share1bs: att(self.send_share1bs, share1bs=share1bs)
254 if share0s: att(self.send_share0s, hashes=share0s)
255 if share1as: att(self.send_share1as, share1as=share1as)
257 def connectionLost(self, reason):
258 if self.node_var_watch is not None:
259 self.node.mode_var.changed.unwatch(self.node_var_watch)
262 self.node.lost_conn(self)
264 class ServerFactory(protocol.ServerFactory):
265 def __init__(self, node):
268 def buildProtocol(self, addr):
269 p = Protocol(self.node)
273 class ClientFactory(protocol.ClientFactory):
274 def __init__(self, node):
277 def buildProtocol(self, addr):
278 p = Protocol(self.node)
282 def startedConnecting(self, connector):
283 self.node.attempt_started(connector)
285 def clientConnectionFailed(self, connector, reason):
286 self.node.attempt_failed(connector)
288 def clientConnectionLost(self, connector, reason):
289 self.node.attempt_ended(connector)
291 addrdb_key = bitcoin_data.ComposedType([
292 ('address', bitcoin_data.IPV6AddressType()),
293 ('port', bitcoin_data.StructType('>H')),
295 addrdb_value = bitcoin_data.ComposedType([
296 ('services', bitcoin_data.StructType('<Q')),
297 ('first_seen', bitcoin_data.StructType('<Q')),
298 ('last_seen', bitcoin_data.StructType('<Q')),
301 class AddrStore(dicts.DictWrapper):
302 def encode_key(self, (address, port)):
303 return addrdb_key.pack(dict(address=address, port=port))
304 def decode_key(self, encoded_key):
305 k = addrdb_key.unpack(encoded_key)
306 return k['address'], k['port']
308 def encode_value(self, (services, first_seen, last_seen)):
309 return addrdb_value.pack(dict(services=services, first_seen=first_seen, last_seen=last_seen))
310 def decode_value(self, encoded_value):
311 v = addrdb_value.unpack(encoded_value)
312 return v['services'], v['first_seen'], v['last_seen']
315 def __init__(self, current_work, port, net, addr_store=None, preferred_addrs=[], mode=0, desired_peers=10, max_attempts=100, preferred_storage=1000):
316 if addr_store is None:
321 self.addr_store = AddrStore(addr_store)
322 self.preferred_addrs = preferred_addrs
323 self.mode_var = variable.Variable(mode)
324 self.desired_peers = desired_peers
325 self.max_attempts = max_attempts
326 self.current_work = current_work
327 self.preferred_storage = preferred_storage
329 self.nonce = random.randrange(2**64)
336 raise ValueError('already running')
340 self.listen_port = reactor.listenTCP(self.port, ServerFactory(self))
345 @defer.inlineCallbacks
349 if len(self.peers) < self.desired_peers and len(self.attempts) < self.max_attempts and (len(self.preferred_addrs) or len(self.addr_store)):
350 if (random.randrange(2) and len(self.preferred_addrs)) or not len(self.addr_store):
351 host, port = random.choice(self.preferred_addrs)
353 host, port = random.choice(self.addr_store.keys())
355 if (host, port) not in self.attempts:
356 #print 'Trying to connect to', host, port
357 reactor.connectTCP(host, port, ClientFactory(self), timeout=10)
361 yield deferral.sleep(random.expovariate(1/5))
363 @defer.inlineCallbacks
367 if len(self.addr_store) < self.preferred_storage and self.peers:
368 random.choice(self.peers.values()).send_getaddrs(count=8)
372 yield deferral.sleep(random.expovariate(1/20))
376 raise ValueError('already stopped')
380 self.listen_port.stopListening()
383 def attempt_started(self, connector):
384 host, port = connector.getDestination().host, connector.getDestination().port
385 if (host, port) in self.attempts:
386 raise ValueError('already have attempt')
387 self.attempts[host, port] = connector
389 def attempt_failed(self, connector):
390 self.attempt_ended(connector)
392 def attempt_ended(self, connector):
393 host, port = connector.getDestination().host, connector.getDestination().port
394 if (host, port) not in self.attempts:
395 raise ValueError('''don't have attempt''')
396 if connector is not self.attempts[host, port]:
397 raise ValueError('wrong connector')
398 del self.attempts[host, port]
401 def got_conn(self, conn):
402 if conn.nonce in self.peers:
403 raise ValueError('already have peer')
404 self.peers[conn.nonce] = conn
406 print 'Connected to peer %s:%i' % conn.addr
408 def lost_conn(self, conn):
409 if conn.nonce not in self.peers:
410 raise ValueError('''don't have peer''')
411 if conn is not self.peers[conn.nonce]:
412 raise ValueError('wrong conn')
413 del self.peers[conn.nonce]
415 print 'Lost peer %s:%i' % conn.addr
418 def got_addr(self, (host, port), services, timestamp):
419 if (host, port) in self.addr_store:
420 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
421 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
423 self.addr_store[host, port] = services, timestamp, timestamp
425 def handle_shares(self, shares, peer):
426 print 'handle_shares', (shares, peer)
428 def handle_share_hashes(self, hashes, peer):
429 print 'handle_share_hashes', (hashes, peer)
431 def handle_get_shares(self, hashes, parents, stops, peer):
432 print 'handle_get_shares', (hashes, parents, stops, peer)
434 if __name__ == '__main__':
435 p = random.randrange(2**15, 2**16)
437 p2 = random.randrange(2**15, 2**16)
439 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())))})