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) + 1)))
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_sub_version = sub_version
100 self.other_services = services
101 self.other_mode_var = variable.Variable(mode)
103 if nonce == self.node.nonce:
104 #print 'Detected connection to self, disconnecting from %s:%i' % self.addr
105 self.transport.loseConnection()
107 if nonce in self.node.peers:
108 #print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
109 self.transport.loseConnection()
113 self.connected2 = True
114 self.node.got_conn(self)
119 if best_share_hash is not None:
120 self.handle_share0s(hashes=[best_share_hash])
123 message_setmode = bitcoin_data.ComposedType([
124 ('mode', bitcoin_data.StructType('<I')),
126 def handle_setmode(self, mode):
127 self.other_mode_var.set(mode)
129 message_ping = bitcoin_data.ComposedType([])
130 def handle_ping(self):
133 message_addrme = bitcoin_data.ComposedType([
134 ('port', bitcoin_data.StructType('<H')),
136 def handle_addrme(self, port):
137 host = self.transport.getPeer().host
138 #print 'addrme from', host, port
139 if host == '127.0.0.1':
140 if random.random() < .8 and self.node.peers:
141 random.choice(self.node.peers.values()).send_addrme(port=port) # services...
143 self.node.got_addr((self.transport.getPeer().host, port), self.other_services, int(time.time()))
144 if random.random() < .8 and self.node.peers:
145 random.choice(self.node.peers.values()).send_addrs(addrs=[
148 services=self.other_services,
152 timestamp=int(time.time()),
156 message_addrs = bitcoin_data.ComposedType([
157 ('addrs', bitcoin_data.ListType(bitcoin_data.ComposedType([
158 ('timestamp', bitcoin_data.StructType('<Q')),
159 ('address', bitcoin_data.address_type),
162 def handle_addrs(self, addrs):
163 for addr_record in addrs:
164 self.node.got_addr((addr_record['address']['address'], addr_record['address']['port']), addr_record['address']['services'], min(int(time.time()), addr_record['timestamp']))
165 if random.random() < .8 and self.node.peers:
166 random.choice(self.node.peers.values()).send_addrs(addrs=[addr_record])
168 message_getaddrs = bitcoin_data.ComposedType([
169 ('count', bitcoin_data.StructType('<I')),
171 def handle_getaddrs(self, count):
174 self.send_addrs(addrs=[
176 timestamp=self.node.addr_store[host, port][2],
178 services=self.node.addr_store[host, port][0],
183 random.sample(self.node.addr_store.keys(), min(count, len(self.node.addr_store)))
186 message_getshares = bitcoin_data.ComposedType([
187 ('hashes', bitcoin_data.ListType(bitcoin_data.HashType())),
188 ('parents', bitcoin_data.VarIntType()),
189 ('stops', bitcoin_data.ListType(bitcoin_data.HashType())),
191 def handle_getshares(self, hashes, parents, stops):
192 self.node.handle_get_shares(hashes, parents, stops, self)
194 message_share0s = bitcoin_data.ComposedType([
195 ('hashes', bitcoin_data.ListType(bitcoin_data.HashType())),
197 def handle_share0s(self, hashes):
198 self.node.handle_share_hashes(hashes, self)
200 message_share1as = bitcoin_data.ComposedType([
201 ('share1as', bitcoin_data.ListType(p2pool_data.share1a_type)),
203 def handle_share1as(self, share1as):
205 for share1a in share1as:
206 hash_ = bitcoin_data.block_header_type.hash256(share1a['header'])
207 if hash_ <= share1a['header']['target']:
208 print 'Dropping peer %s:%i due to invalid share' % self.addr
209 self.transport.loseConnection()
211 share = p2pool_data.Share.from_share1a(share1a)
212 share.peer = self # XXX
214 self.node.handle_shares(shares, self)
216 message_share1bs = bitcoin_data.ComposedType([
217 ('share1bs', bitcoin_data.ListType(p2pool_data.share1b_type)),
219 def handle_share1bs(self, share1bs):
221 for share1b in share1bs:
222 hash_ = bitcoin_data.block_header_type.hash256(share1b['header'])
223 if not hash_ <= share1b['header']['target']:
224 print 'Dropping peer %s:%i due to invalid share' % self.addr
225 self.transport.loseConnection()
227 share = p2pool_data.Share.from_share1b(share1b)
228 share.peer = self # XXX
230 self.node.handle_shares(shares, self)
232 def send_shares(self, shares, full=False):
236 # XXX doesn't need to send full block when it's not urgent
237 # eg. when getting history
239 if share.bitcoin_hash <= share.header['target']:
240 share1bs.append(share.as_share1b())
242 if self.mode == 0 and not full:
243 share0s.append(share.hash)
244 elif self.mode == 1 or full:
245 share1as.append(share.as_share1a())
247 raise ValueError(self.mode)
248 def att(f, **kwargs):
251 except bitcoin_p2p.TooLong:
252 att(f, **dict((k, v[:len(v)//2]) for k, v in kwargs.iteritems()))
253 att(f, **dict((k, v[len(v)//2:]) for k, v in kwargs.iteritems()))
254 if share1bs: att(self.send_share1bs, share1bs=share1bs)
255 if share0s: att(self.send_share0s, hashes=share0s)
256 if share1as: att(self.send_share1as, share1as=share1as)
258 def connectionLost(self, reason):
259 if self.node_var_watch is not None:
260 self.node.mode_var.changed.unwatch(self.node_var_watch)
263 self.node.lost_conn(self)
265 class ServerFactory(protocol.ServerFactory):
266 def __init__(self, node):
269 def buildProtocol(self, addr):
270 p = Protocol(self.node)
274 class ClientFactory(protocol.ClientFactory):
275 def __init__(self, node):
278 def buildProtocol(self, addr):
279 p = Protocol(self.node)
283 def startedConnecting(self, connector):
284 self.node.attempt_started(connector)
286 def clientConnectionFailed(self, connector, reason):
287 self.node.attempt_failed(connector)
289 def clientConnectionLost(self, connector, reason):
290 self.node.attempt_ended(connector)
292 addrdb_key = bitcoin_data.ComposedType([
293 ('address', bitcoin_data.IPV6AddressType()),
294 ('port', bitcoin_data.StructType('>H')),
296 addrdb_value = bitcoin_data.ComposedType([
297 ('services', bitcoin_data.StructType('<Q')),
298 ('first_seen', bitcoin_data.StructType('<Q')),
299 ('last_seen', bitcoin_data.StructType('<Q')),
302 class AddrStore(dicts.DictWrapper):
303 def encode_key(self, (address, port)):
304 return addrdb_key.pack(dict(address=address, port=port))
305 def decode_key(self, encoded_key):
306 k = addrdb_key.unpack(encoded_key)
307 return k['address'], k['port']
309 def encode_value(self, (services, first_seen, last_seen)):
310 return addrdb_value.pack(dict(services=services, first_seen=first_seen, last_seen=last_seen))
311 def decode_value(self, encoded_value):
312 v = addrdb_value.unpack(encoded_value)
313 return v['services'], v['first_seen'], v['last_seen']
316 def __init__(self, current_work, port, net, addr_store=None, preferred_addrs=[], mode=0, desired_peers=10, max_attempts=100, preferred_storage=1000):
317 if addr_store is None:
322 self.addr_store = AddrStore(addr_store)
323 self.preferred_addrs = preferred_addrs
324 self.mode_var = variable.Variable(mode)
325 self.desired_peers = desired_peers
326 self.max_attempts = max_attempts
327 self.current_work = current_work
328 self.preferred_storage = preferred_storage
330 self.nonce = random.randrange(2**64)
337 raise ValueError('already running')
341 self.listen_port = reactor.listenTCP(self.port, ServerFactory(self))
346 @defer.inlineCallbacks
350 if len(self.peers) < self.desired_peers and len(self.attempts) < self.max_attempts and (len(self.preferred_addrs) or len(self.addr_store)):
351 if (random.randrange(2) and len(self.preferred_addrs)) or not len(self.addr_store):
352 host, port = random.choice(self.preferred_addrs)
354 host, port = random.choice(self.addr_store.keys())
356 if (host, port) not in self.attempts:
357 #print 'Trying to connect to', host, port
358 reactor.connectTCP(host, port, ClientFactory(self), timeout=10)
362 yield deferral.sleep(random.expovariate(1/5))
364 @defer.inlineCallbacks
368 if len(self.addr_store) < self.preferred_storage and self.peers:
369 random.choice(self.peers.values()).send_getaddrs(count=8)
373 yield deferral.sleep(random.expovariate(1/20))
377 raise ValueError('already stopped')
381 self.listen_port.stopListening()
384 def attempt_started(self, connector):
385 host, port = connector.getDestination().host, connector.getDestination().port
386 if (host, port) in self.attempts:
387 raise ValueError('already have attempt')
388 self.attempts[host, port] = connector
390 def attempt_failed(self, connector):
391 self.attempt_ended(connector)
393 def attempt_ended(self, connector):
394 host, port = connector.getDestination().host, connector.getDestination().port
395 if (host, port) not in self.attempts:
396 raise ValueError('''don't have attempt''')
397 if connector is not self.attempts[host, port]:
398 raise ValueError('wrong connector')
399 del self.attempts[host, port]
402 def got_conn(self, conn):
403 if conn.nonce in self.peers:
404 raise ValueError('already have peer')
405 self.peers[conn.nonce] = conn
407 print 'Connected to peer %s:%i %r' % (conn.addr[0], conn.addr[1], conn.other_sub_version)
409 def lost_conn(self, conn):
410 if conn.nonce not in self.peers:
411 raise ValueError('''don't have peer''')
412 if conn is not self.peers[conn.nonce]:
413 raise ValueError('wrong conn')
414 del self.peers[conn.nonce]
416 print 'Lost peer %s:%i' % (conn.addr[0], conn.addr[1])
419 def got_addr(self, (host, port), services, timestamp):
420 if (host, port) in self.addr_store:
421 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
422 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
424 self.addr_store[host, port] = services, timestamp, timestamp
426 def handle_shares(self, shares, peer):
427 print 'handle_shares', (shares, peer)
429 def handle_share_hashes(self, hashes, peer):
430 print 'handle_share_hashes', (hashes, peer)
432 def handle_get_shares(self, hashes, parents, stops, peer):
433 print 'handle_get_shares', (hashes, parents, stops, peer)
435 if __name__ == '__main__':
436 p = random.randrange(2**15, 2**16)
438 p2 = random.randrange(2**15, 2**16)
440 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())))})