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):
171 self.send_addrs(addrs=[
173 timestamp=self.node.addr_store[host, port][2],
175 services=self.node.addr_store[host, port][0],
180 random.sample(self.node.addr_store.keys(), min(count, len(self.node.addr_store)))
183 message_getshares = bitcoin_data.ComposedType([
184 ('hashes', bitcoin_data.ListType(bitcoin_data.HashType())),
185 ('parents', bitcoin_data.VarIntType()),
186 ('stops', bitcoin_data.ListType(bitcoin_data.HashType())),
188 def handle_getshares(self, hashes, parents, stops):
189 self.node.handle_get_shares(hashes, parents, stops, self)
191 message_share0s = bitcoin_data.ComposedType([
192 ('hashes', bitcoin_data.ListType(bitcoin_data.HashType())),
194 def handle_share0s(self, hashes):
195 self.node.handle_share_hashes(hashes, self)
197 message_share1as = bitcoin_data.ComposedType([
198 ('share1as', bitcoin_data.ListType(p2pool_data.share1a_type)),
200 def handle_share1as(self, share1as):
202 for share1a in share1as:
203 hash_ = bitcoin_data.block_header_type.hash256(share1a['header'])
204 if hash_ <= share1a['header']['target']:
205 print 'Dropping peer %s:%i due to invalid share' % self.addr
206 self.transport.loseConnection()
208 share = p2pool_data.Share.from_share1a(share1a)
209 share.peer = self # XXX
211 self.node.handle_shares(shares, self)
213 message_share1bs = bitcoin_data.ComposedType([
214 ('share1bs', bitcoin_data.ListType(p2pool_data.share1b_type)),
216 def handle_share1bs(self, share1bs):
218 for share1b in share1bs:
219 hash_ = bitcoin_data.block_header_type.hash256(share1b['header'])
220 if not hash_ <= share1b['header']['target']:
221 print 'Dropping peer %s:%i due to invalid share' % self.addr
222 self.transport.loseConnection()
224 share = p2pool_data.Share.from_share1b(share1b)
225 share.peer = self # XXX
227 self.node.handle_shares(shares, self)
229 def send_shares(self, shares, full=False):
233 # XXX doesn't need to send full block when it's not urgent
234 # eg. when getting history
236 if share.bitcoin_hash <= share.header['target']:
237 share1bs.append(share.as_share1b())
239 if self.mode == 0 and not full:
240 share0s.append(share.hash)
241 elif self.mode == 1 or full:
242 share1as.append(share.as_share1a())
244 raise ValueError(self.mode)
245 if share1bs: self.send_share1bs(share1bs=share1bs)
246 if share0s: self.send_share0s(hashes=share0s)
247 if share1as: self.send_share1as(share1as=share1as)
249 def connectionLost(self, reason):
250 if self.node_var_watch is not None:
251 self.node.mode_var.changed.unwatch(self.node_var_watch)
254 self.node.lost_conn(self)
256 class ServerFactory(protocol.ServerFactory):
257 def __init__(self, node):
260 def buildProtocol(self, addr):
261 p = Protocol(self.node)
265 class ClientFactory(protocol.ClientFactory):
266 def __init__(self, node):
269 def buildProtocol(self, addr):
270 p = Protocol(self.node)
274 def startedConnecting(self, connector):
275 self.node.attempt_started(connector)
277 def clientConnectionFailed(self, connector, reason):
278 self.node.attempt_failed(connector)
280 def clientConnectionLost(self, connector, reason):
281 self.node.attempt_ended(connector)
283 addrdb_key = bitcoin_data.ComposedType([
284 ('address', bitcoin_data.IPV6AddressType()),
285 ('port', bitcoin_data.StructType('>H')),
287 addrdb_value = bitcoin_data.ComposedType([
288 ('services', bitcoin_data.StructType('<Q')),
289 ('first_seen', bitcoin_data.StructType('<Q')),
290 ('last_seen', bitcoin_data.StructType('<Q')),
293 class AddrStore(dicts.DictWrapper):
294 def encode_key(self, (address, port)):
295 return addrdb_key.pack(dict(address=address, port=port))
296 def decode_key(self, encoded_key):
297 k = addrdb_key.unpack(encoded_key)
298 return k['address'], k['port']
300 def encode_value(self, (services, first_seen, last_seen)):
301 return addrdb_value.pack(dict(services=services, first_seen=first_seen, last_seen=last_seen))
302 def decode_value(self, encoded_value):
303 v = addrdb_value.unpack(encoded_value)
304 return v['services'], v['first_seen'], v['last_seen']
307 def __init__(self, current_work, port, net, addr_store=None, preferred_addrs=[], mode=0, desired_peers=10, max_attempts=100, preferred_storage=1000):
308 if addr_store is None:
313 self.addr_store = AddrStore(addr_store)
314 self.preferred_addrs = preferred_addrs
315 self.mode_var = variable.Variable(mode)
316 self.desired_peers = desired_peers
317 self.max_attempts = max_attempts
318 self.current_work = current_work
319 self.preferred_storage = preferred_storage
321 self.nonce = random.randrange(2**64)
328 raise ValueError('already running')
332 self.listen_port = reactor.listenTCP(self.port, ServerFactory(self))
337 @defer.inlineCallbacks
341 if len(self.peers) < self.desired_peers and len(self.attempts) < self.max_attempts and (len(self.preferred_addrs) or len(self.addr_store)):
342 if (random.randrange(2) and len(self.preferred_addrs)) or not len(self.addr_store):
343 host, port = random.choice(self.preferred_addrs)
345 host, port = random.choice(self.addr_store.keys())
347 if (host, port) not in self.attempts:
348 #print 'Trying to connect to', host, port
349 reactor.connectTCP(host, port, ClientFactory(self), timeout=10)
353 yield deferral.sleep(random.expovariate(1/5))
355 @defer.inlineCallbacks
359 if len(self.addr_store) < self.preferred_storage and self.peers:
360 random.choice(self.peers.values()).send_getaddrs(count=8)
364 yield deferral.sleep(random.expovariate(1/20))
368 raise ValueError('already stopped')
372 self.listen_port.stopListening()
375 def attempt_started(self, connector):
376 host, port = connector.getDestination().host, connector.getDestination().port
377 if (host, port) in self.attempts:
378 raise ValueError('already have attempt')
379 self.attempts[host, port] = connector
381 def attempt_failed(self, connector):
382 self.attempt_ended(connector)
384 def attempt_ended(self, connector):
385 host, port = connector.getDestination().host, connector.getDestination().port
386 if (host, port) not in self.attempts:
387 raise ValueError('''don't have attempt''')
388 if connector is not self.attempts[host, port]:
389 raise ValueError('wrong connector')
390 del self.attempts[host, port]
393 def got_conn(self, conn):
394 if conn.nonce in self.peers:
395 raise ValueError('already have peer')
396 self.peers[conn.nonce] = conn
398 print 'Connected to peer %s:%i' % conn.addr
400 def lost_conn(self, conn):
401 if conn.nonce not in self.peers:
402 raise ValueError('''don't have peer''')
403 if conn is not self.peers[conn.nonce]:
404 raise ValueError('wrong conn')
405 del self.peers[conn.nonce]
407 print 'Lost peer %s:%i' % conn.addr
410 def got_addr(self, (host, port), services, timestamp):
411 if (host, port) in self.addr_store:
412 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
413 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
415 self.addr_store[host, port] = services, timestamp, timestamp
417 def handle_shares(self, shares, peer):
418 print 'handle_shares', (shares, peer)
420 def handle_share_hashes(self, hashes, peer):
421 print 'handle_share_hashes', (hashes, peer)
423 def handle_get_shares(self, hashes, parents, stops, peer):
424 print 'handle_get_shares', (hashes, parents, stops, peer)
426 if __name__ == '__main__':
427 p = random.randrange(2**15, 2**16)
429 p2 = random.randrange(2**15, 2**16)
431 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())))})