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):
215 share_obj = p2pool_data.NewShare.from_share(share, self.node.net)
216 share_obj.peer = self
217 res.append(share_obj)
218 self.node.handle_shares(res)
220 def sendShares(self, shares, full=False):
223 # XXX doesn't need to send full block when it's not urgent
224 # eg. when getting history
226 if self.mode == 0 and not full and not share.pow_hash <= share.header['target']:
227 share0s.append(share.hash)
228 elif self.mode == 1 or full:
229 new_shares.append(share.as_share())
231 raise ValueError(self.mode)
232 def att(f, **kwargs):
235 except bitcoin_p2p.TooLong:
236 att(f, **dict((k, v[:len(v)//2]) for k, v in kwargs.iteritems()))
237 att(f, **dict((k, v[len(v)//2:]) for k, v in kwargs.iteritems()))
238 if share0s: att(self.send_share0s, hashes=share0s)
239 if new_shares: att(self.send_shares, shares=new_shares)
241 def connectionLost(self, reason):
242 if self.node_var_watch is not None:
243 self.node.mode_var.changed.unwatch(self.node_var_watch)
246 self.node.lost_conn(self)
248 class ServerFactory(protocol.ServerFactory):
249 def __init__(self, node):
252 def buildProtocol(self, addr):
253 p = Protocol(self.node)
257 class ClientFactory(protocol.ClientFactory):
258 def __init__(self, node):
261 def buildProtocol(self, addr):
262 p = Protocol(self.node)
266 def startedConnecting(self, connector):
267 self.node.attempt_started(connector)
269 def clientConnectionFailed(self, connector, reason):
270 self.node.attempt_failed(connector)
272 def clientConnectionLost(self, connector, reason):
273 self.node.attempt_ended(connector)
275 addrdb_key = bitcoin_data.ComposedType([
276 ('address', bitcoin_data.IPV6AddressType()),
277 ('port', bitcoin_data.StructType('>H')),
279 addrdb_value = bitcoin_data.ComposedType([
280 ('services', bitcoin_data.StructType('<Q')),
281 ('first_seen', bitcoin_data.StructType('<Q')),
282 ('last_seen', bitcoin_data.StructType('<Q')),
285 class AddrStore(dicts.DictWrapper):
286 def encode_key(self, (address, port)):
287 return addrdb_key.pack(dict(address=address, port=port))
288 def decode_key(self, encoded_key):
289 k = addrdb_key.unpack(encoded_key)
290 return k['address'], k['port']
292 def encode_value(self, (services, first_seen, last_seen)):
293 return addrdb_value.pack(dict(services=services, first_seen=first_seen, last_seen=last_seen))
294 def decode_value(self, encoded_value):
295 v = addrdb_value.unpack(encoded_value)
296 return v['services'], v['first_seen'], v['last_seen']
299 def __init__(self, current_work, port, net, addr_store=None, preferred_addrs=set(), mode=0, desired_peers=10, max_attempts=100, preferred_storage=1000):
300 if addr_store is None:
305 self.addr_store = AddrStore(addr_store)
306 self.preferred_addrs = preferred_addrs
307 self.mode_var = variable.Variable(mode)
308 self.desired_peers = desired_peers
309 self.max_attempts = max_attempts
310 self.current_work = current_work
311 self.preferred_storage = preferred_storage
313 self.nonce = random.randrange(2**64)
320 raise ValueError('already running')
324 self.listen_port = reactor.listenTCP(self.port, ServerFactory(self))
329 @defer.inlineCallbacks
333 if len(self.peers) < self.desired_peers and len(self.attempts) < self.max_attempts and (len(self.preferred_addrs) or len(self.addr_store)):
334 if (random.randrange(2) and len(self.preferred_addrs)) or not len(self.addr_store):
335 host, port = random.choice(list(self.preferred_addrs))
337 host, port = random.choice(self.addr_store.keys())
339 if (host, port) not in self.attempts:
340 #print 'Trying to connect to', host, port
341 reactor.connectTCP(host, port, ClientFactory(self), timeout=10)
345 yield deferral.sleep(random.expovariate(1/5))
347 @defer.inlineCallbacks
351 if len(self.addr_store) < self.preferred_storage and self.peers:
352 random.choice(self.peers.values()).send_getaddrs(count=8)
356 yield deferral.sleep(random.expovariate(1/20))
360 raise ValueError('already stopped')
364 self.listen_port.stopListening()
367 def attempt_started(self, connector):
368 host, port = connector.getDestination().host, connector.getDestination().port
369 if (host, port) in self.attempts:
370 raise ValueError('already have attempt')
371 self.attempts[host, port] = connector
373 def attempt_failed(self, connector):
374 self.attempt_ended(connector)
376 def attempt_ended(self, connector):
377 host, port = connector.getDestination().host, connector.getDestination().port
378 if (host, port) not in self.attempts:
379 raise ValueError('''don't have attempt''')
380 if connector is not self.attempts[host, port]:
381 raise ValueError('wrong connector')
382 del self.attempts[host, port]
385 def got_conn(self, conn):
386 if conn.nonce in self.peers:
387 raise ValueError('already have peer')
388 self.peers[conn.nonce] = conn
390 print 'Connected to peer %s:%i. p2pool version: %r' % (conn.addr[0], conn.addr[1], conn.other_sub_version)
392 def lost_conn(self, conn):
393 if conn.nonce not in self.peers:
394 raise ValueError('''don't have peer''')
395 if conn is not self.peers[conn.nonce]:
396 raise ValueError('wrong conn')
397 del self.peers[conn.nonce]
399 print 'Lost peer %s:%i' % (conn.addr[0], conn.addr[1])
402 def got_addr(self, (host, port), services, timestamp):
403 if (host, port) in self.addr_store:
404 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
405 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
407 self.addr_store[host, port] = services, timestamp, timestamp
409 def handle_shares(self, shares, peer):
410 print 'handle_shares', (shares, peer)
412 def handle_share_hashes(self, hashes, peer):
413 print 'handle_share_hashes', (hashes, peer)
415 def handle_get_shares(self, hashes, parents, stops, peer):
416 print 'handle_get_shares', (hashes, parents, stops, peer)
418 if __name__ == '__main__':
419 p = random.randrange(2**15, 2**16)
421 p2 = random.randrange(2**15, 2**16)
423 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())))})