1 from __future__ import division
6 from twisted.internet import defer, protocol, reactor
7 from twisted.python import log
9 from p2pool.bitcoin import p2p as bitcoin_p2p
10 from p2pool.bitcoin import data as bitcoin_data
11 from p2pool import data as p2pool_data
12 from p2pool.util import deferral, variable, dicts
15 # 0: send hash first (high latency, low bandwidth)
16 # 1: send entire share (low latency, high bandwidth)
18 class Protocol(bitcoin_p2p.BaseProtocol):
22 def __init__(self, node):
25 self._prefix = self.node.net.PREFIX
27 max_payload_length = 1000000
28 max_net_payload_length = 2000000
38 return min(self.node.mode_var.value, self.other_mode_var.value)
40 def connectionMade(self):
41 bitcoin_p2p.BaseProtocol.connectionMade(self)
43 self.addr = self.transport.getPeer().host, self.transport.getPeer().port
50 address=self.transport.getPeer().host,
51 port=self.transport.getPeer().port,
55 address=self.transport.getHost().host,
56 port=self.transport.getHost().port,
58 nonce=self.node.nonce,
59 sub_version=self.sub_version,
60 mode=self.node.mode_var.value,
61 best_share_hash=self.node.current_work.value['best_share_hash'],
64 self.node_var_watch = self.node.mode_var.changed.watch(lambda new_mode: self.send_setmode(mode=new_mode))
66 reactor.callLater(10, self._connect_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()
73 @defer.inlineCallbacks
75 while self.connected2:
77 yield deferral.sleep(random.expovariate(1/100))
79 @defer.inlineCallbacks
81 while self.connected2:
82 self.send_addrme(port=self.node.port)
83 #print 'sending addrme'
84 yield deferral.sleep(random.expovariate(1/(100*len(self.node.peers))))
86 message_version = bitcoin_data.ComposedType([
87 ('version', bitcoin_data.StructType('<I')),
88 ('services', bitcoin_data.StructType('<Q')),
89 ('addr_to', bitcoin_data.address_type),
90 ('addr_from', bitcoin_data.address_type),
91 ('nonce', bitcoin_data.StructType('<Q')),
92 ('sub_version', bitcoin_data.VarStrType()),
93 ('mode', bitcoin_data.StructType('<I')),
94 ('best_share_hash', bitcoin_data.PossiblyNone(0, bitcoin_data.HashType())),
96 def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, best_share_hash):
97 self.other_version = version
98 self.other_services = services
99 self.other_mode_var = variable.Variable(mode)
101 if nonce == self.node.nonce:
102 #print 'Detected connection to self, disconnecting from %s:%i' % self.addr
103 self.transport.loseConnection()
105 if nonce in self.node.peers:
106 #print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
107 self.transport.loseConnection()
111 self.connected2 = True
112 self.node.got_conn(self)
117 if best_share_hash is not None:
118 self.handle_share0s(hashes=[best_share_hash])
121 message_setmode = bitcoin_data.ComposedType([
122 ('mode', bitcoin_data.StructType('<I')),
124 def handle_setmode(self, mode):
125 self.other_mode_var.set(mode)
127 message_ping = bitcoin_data.ComposedType([])
128 def handle_ping(self):
131 message_addrme = bitcoin_data.ComposedType([
132 ('port', bitcoin_data.StructType('<H')),
134 def handle_addrme(self, port):
135 host = self.transport.getPeer().host
136 #print 'addrme from', host, port
137 if host == '127.0.0.1':
138 if random.random() < .8 and self.node.peers:
139 random.choice(self.node.peers.values()).send_addrme(port=port) # services...
141 self.node.got_addr((self.transport.getPeer().host, port), self.other_services, int(time.time()))
142 if random.random() < .8 and self.node.peers:
143 random.choice(self.node.peers.values()).send_addrs(addrs=[
146 services=self.other_services,
150 timestamp=int(time.time()),
154 message_addrs = bitcoin_data.ComposedType([
155 ('addrs', bitcoin_data.ListType(bitcoin_data.ComposedType([
156 ('timestamp', bitcoin_data.StructType('<Q')),
157 ('address', bitcoin_data.address_type),
160 def handle_addrs(self, addrs):
161 for addr_record in addrs:
162 self.node.got_addr((addr_record['address']['address'], addr_record['address']['port']), addr_record['address']['services'], min(int(time.time()), addr_record['timestamp']))
163 if random.random() < .8 and self.node.peers:
164 random.choice(self.node.peers.values()).send_addrs(addrs=[addr_record])
166 message_getaddrs = bitcoin_data.ComposedType([
167 ('count', bitcoin_data.StructType('<I')),
169 def handle_getaddrs(self, count):
170 self.send_addrs(addrs=[
172 timestamp=self.node.addr_store[host, port][2],
174 services=self.node.addr_store[host, port][0],
179 random.sample(self.node.addr_store.keys(), min(count, len(self.node.addr_store)))
182 message_getshares = bitcoin_data.ComposedType([
183 ('hashes', bitcoin_data.ListType(bitcoin_data.HashType())),
184 ('parents', bitcoin_data.VarIntType()),
185 ('stops', bitcoin_data.ListType(bitcoin_data.HashType())),
187 def handle_getshares(self, hashes, parents, stops):
188 self.node.handle_get_shares(hashes, parents, stops, self)
190 message_share0s = bitcoin_data.ComposedType([
191 ('hashes', bitcoin_data.ListType(bitcoin_data.HashType())),
193 def handle_share0s(self, hashes):
194 self.node.handle_share_hashes(hashes, self)
196 message_share1as = bitcoin_data.ComposedType([
197 ('share1as', bitcoin_data.ListType(p2pool_data.share1a_type)),
199 def handle_share1as(self, share1as):
201 for share1a in share1as:
202 hash_ = bitcoin_data.block_header_type.hash256(share1a['header'])
203 if hash_ <= share1a['header']['target']:
204 print 'Dropping peer %s:%i due to invalid share' % self.addr
205 self.transport.loseConnection()
207 share = p2pool_data.Share.from_share1a(share1a)
208 share.peer = self # XXX
210 self.node.handle_shares(shares, self)
212 message_share1bs = bitcoin_data.ComposedType([
213 ('share1bs', bitcoin_data.ListType(p2pool_data.share1b_type)),
215 def handle_share1bs(self, share1bs):
217 for share1b in share1bs:
218 hash_ = bitcoin_data.block_header_type.hash256(share1b['header'])
219 if not hash_ <= share1b['header']['target']:
220 print 'Dropping peer %s:%i due to invalid share' % self.addr
221 self.transport.loseConnection()
223 share = p2pool_data.Share.from_share1b(share1b)
224 share.peer = self # XXX
226 self.node.handle_shares(shares, self)
228 def send_shares(self, shares, full=False):
232 # XXX doesn't need to send full block when it's not urgent
233 # eg. when getting history
235 if share.bitcoin_hash <= share.header['target']:
236 share1bs.append(share.as_share1b())
238 if self.mode == 0 and not full:
239 share0s.append(share.hash)
240 elif self.mode == 1 or full:
241 share1as.append(share.as_share1a())
243 raise ValueError(self.mode)
244 if share1bs: self.send_share1bs(share1bs=share1bs)
245 if share0s: self.send_share0s(hashes=share0s)
246 if share1as: self.send_share1as(share1as=share1as)
248 def connectionLost(self, reason):
249 if self.node_var_watch is not None:
250 self.node.mode_var.changed.unwatch(self.node_var_watch)
253 self.node.lost_conn(self)
255 class ServerFactory(protocol.ServerFactory):
256 def __init__(self, node):
259 def buildProtocol(self, addr):
260 p = Protocol(self.node)
264 class ClientFactory(protocol.ClientFactory):
265 def __init__(self, node):
268 def buildProtocol(self, addr):
269 p = Protocol(self.node)
273 def startedConnecting(self, connector):
274 self.node.attempt_started(connector)
276 def clientConnectionFailed(self, connector, reason):
277 self.node.attempt_failed(connector)
279 def clientConnectionLost(self, connector, reason):
280 self.node.attempt_ended(connector)
282 addrdb_key = bitcoin_data.ComposedType([
283 ('address', bitcoin_data.IPV6AddressType()),
284 ('port', bitcoin_data.StructType('>H')),
286 addrdb_value = bitcoin_data.ComposedType([
287 ('services', bitcoin_data.StructType('<Q')),
288 ('first_seen', bitcoin_data.StructType('<Q')),
289 ('last_seen', bitcoin_data.StructType('<Q')),
292 class AddrStore(dicts.DictWrapper):
293 def encode_key(self, (address, port)):
294 return addrdb_key.pack(dict(address=address, port=port))
295 def decode_key(self, encoded_key):
296 k = addrdb_key.unpack(encoded_key)
297 return k['address'], k['port']
299 def encode_value(self, (services, first_seen, last_seen)):
300 return addrdb_value.pack(dict(services=services, first_seen=first_seen, last_seen=last_seen))
301 def decode_value(self, encoded_value):
302 v = addrdb_value.unpack(encoded_value)
303 return v['services'], v['first_seen'], v['last_seen']
306 def __init__(self, current_work, port, net, addr_store=None, preferred_addrs=[], mode=0, desired_peers=10, max_attempts=100, preferred_storage=1000):
307 if addr_store is None:
312 self.addr_store = AddrStore(addr_store)
313 self.preferred_addrs = preferred_addrs
314 self.mode_var = variable.Variable(mode)
315 self.desired_peers = desired_peers
316 self.max_attempts = max_attempts
317 self.current_work = current_work
318 self.preferred_storage = preferred_storage
320 self.nonce = random.randrange(2**64)
327 raise ValueError('already running')
331 self.listen_port = reactor.listenTCP(self.port, ServerFactory(self))
336 @defer.inlineCallbacks
340 if len(self.peers) < self.desired_peers and len(self.attempts) < self.max_attempts and (len(self.preferred_addrs) or len(self.addr_store)):
341 if (random.randrange(2) and len(self.preferred_addrs)) or not len(self.addr_store):
342 host, port = random.choice(self.preferred_addrs)
344 host, port = random.choice(self.addr_store.keys())
346 if (host, port) not in self.attempts:
347 #print 'Trying to connect to', host, port
348 reactor.connectTCP(host, port, ClientFactory(self), timeout=10)
352 yield deferral.sleep(random.expovariate(1/5))
354 @defer.inlineCallbacks
358 if len(self.addr_store) < self.preferred_storage and self.peers:
359 random.choice(self.peers.values()).send_getaddrs(count=8)
363 yield deferral.sleep(random.expovariate(1/20))
367 raise ValueError('already stopped')
371 self.listen_port.stopListening()
374 def attempt_started(self, connector):
375 host, port = connector.getDestination().host, connector.getDestination().port
376 if (host, port) in self.attempts:
377 raise ValueError('already have attempt')
378 self.attempts[host, port] = connector
380 def attempt_failed(self, connector):
381 self.attempt_ended(connector)
383 def attempt_ended(self, connector):
384 host, port = connector.getDestination().host, connector.getDestination().port
385 if (host, port) not in self.attempts:
386 raise ValueError('''don't have attempt''')
387 if connector is not self.attempts[host, port]:
388 raise ValueError('wrong connector')
389 del self.attempts[host, port]
392 def got_conn(self, conn):
393 if conn.nonce in self.peers:
394 raise ValueError('already have peer')
395 self.peers[conn.nonce] = conn
397 print 'Connected to peer %s:%i' % conn.addr
399 def lost_conn(self, conn):
400 if conn.nonce not in self.peers:
401 raise ValueError('''don't have peer''')
402 if conn is not self.peers[conn.nonce]:
403 raise ValueError('wrong conn')
404 del self.peers[conn.nonce]
406 print 'Lost peer %s:%i' % conn.addr
409 def got_addr(self, (host, port), services, timestamp):
410 if (host, port) in self.addr_store:
411 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
412 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
414 self.addr_store[host, port] = services, timestamp, timestamp
416 def handle_shares(self, shares, peer):
417 print 'handle_shares', (shares, peer)
419 def handle_share_hashes(self, hashes, peer):
420 print 'handle_share_hashes', (hashes, peer)
422 def handle_get_shares(self, hashes, parents, stops, peer):
423 print 'handle_get_shares', (hashes, parents, stops, peer)
425 if __name__ == '__main__':
426 p = random.randrange(2**15, 2**16)
428 p2 = random.randrange(2**15, 2**16)
430 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())))})