1 from __future__ import division
7 from twisted.internet import defer, reactor, protocol, task
15 # 0: send hash first (high latency, low bandwidth)
16 # 1: send entire share (low latency, high bandwidth)
20 d = pygame.display.set_mode((512, 512))
21 task.LoopingCall(pygame.display.update).start(.1)
22 def draw_circle(id, color=(255,0,0)):
24 pygame.draw.circle(d, (255, 0, 0), (hash(id)%512, hash(id)//512%512), 4)
25 def draw_line(id, id2, color):
27 pygame.draw.line(d, color, (hash(id)%512, hash(id)//512%512), (hash(id2)%512, hash(id2)//512%512))
29 draw_circle = draw_line = lambda *args, **kwargs: None
31 class Protocol(bitcoin_p2p.BaseProtocol):
35 def __init__(self, node):
41 return 'f77cea5d16a2183f'.decode('hex')
43 return '95ec1eda53c5e716'.decode('hex')
48 'version': bitcoin_p2p.ComposedType([
49 ('version', bitcoin_p2p.StructType('<I')),
50 ('services', bitcoin_p2p.StructType('<Q')),
51 ('addr_to', bitcoin_p2p.address),
52 ('addr_from', bitcoin_p2p.address),
53 ('nonce', bitcoin_p2p.StructType('<Q')),
54 ('sub_version', bitcoin_p2p.VarStrType()),
55 ('mode', bitcoin_p2p.StructType('<I')),
56 ('state', bitcoin_p2p.ComposedType([
57 ('chain_id', p2pool.chain_id_type),
58 ('highest', bitcoin_p2p.ComposedType([
59 ('hash', bitcoin_p2p.HashType()),
60 ('height', bitcoin_p2p.StructType('<Q')),
65 'update_mode': bitcoin_p2p.ComposedType([
66 ('mode', bitcoin_p2p.StructType('<I')),
69 'ping': bitcoin_p2p.ComposedType([]),
71 'addrme': bitcoin_p2p.ComposedType([
72 ('port', bitcoin_p2p.StructType('<H')),
74 'addrs': bitcoin_p2p.ComposedType([
75 ('addrs', bitcoin_p2p.ListType(bitcoin_p2p.ComposedType([
76 ('timestamp', bitcoin_p2p.StructType('<Q')),
77 ('address', bitcoin_p2p.address),
80 'getaddrs': bitcoin_p2p.ComposedType([
81 ('count', bitcoin_p2p.StructType('<I')),
84 'getsharestohighest': bitcoin_p2p.ComposedType([
85 ('chain_id', p2pool.chain_id_type),
86 ('have', bitcoin_p2p.ListType(bitcoin_p2p.HashType())),
88 'getshares': bitcoin_p2p.ComposedType([
89 ('chain_id', p2pool.chain_id_type),
90 ('hashes', bitcoin_p2p.ListType(bitcoin_p2p.HashType())),
93 'share0s': bitcoin_p2p.ComposedType([
94 ('chains', bitcoin_p2p.ListType(bitcoin_p2p.ComposedType([
95 ('chain_id', p2pool.chain_id_type),
96 ('hashes', bitcoin_p2p.ListType(bitcoin_p2p.HashType())),
99 'share1s': bitcoin_p2p.ComposedType([
100 ('share1s', bitcoin_p2p.ListType(p2pool.share1)),
102 'share2s': bitcoin_p2p.ComposedType([
103 ('share2s', bitcoin_p2p.ListType(bitcoin_p2p.block)),
108 node_var_watch = None
113 return min(self.node.mode_var.value, self.other_mode_var.value)
115 def connectionMade(self):
116 bitcoin_p2p.BaseProtocol.connectionMade(self)
117 if isinstance(self.factory, ClientFactory):
118 draw_line(self.node.port, self.transport.getPeer().port, (128, 128, 128))
120 chain = self.node.current_work.value['current_chain']
121 highest_share2 = chain.get_highest_share2()
123 version=self.version,
127 address='::ffff:' + self.transport.getPeer().host,
128 port=self.transport.getPeer().port,
132 address='::ffff:' + self.transport.getHost().host,
133 port=self.transport.getHost().port,
135 nonce=self.node.nonce,
136 sub_version=self.sub_version,
137 mode=self.node.mode_var.value,
139 chain_id=p2pool.chain_id_type.unpack(chain.chain_id_data),
141 hash=highest_share2.share.hash if highest_share2 is not None else 2**256-1,
142 height=highest_share2.height if highest_share2 is not None else 0,
147 self.node_var_watch = self.node.mode_var.changed.watch(lambda new_mode: self.send_set_mode(mode=new_mode))
152 reactor.callLater(10, self._connect_timeout)
154 def _connect_timeout(self):
155 if not self.connected2 and self.transport.connected:
156 print "Handshake timed out, disconnecting"
157 self.transport.loseConnection()
159 @defer.inlineCallbacks
161 while self.connected2:
163 yield util.sleep(random.expovariate(1/100))
165 @defer.inlineCallbacks
167 while self.connected2:
168 self.send_addrme(port=self.node.port)
169 yield util.sleep(random.expovariate(1/100))
171 def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, state):
172 self.other_version = version
173 self.other_services = services
174 self.other_mode_var = util.Variable(mode)
176 if nonce == self.node.nonce:
177 #print "Detected connection to self, disconnecting"
178 self.transport.loseConnection()
182 self.connected2 = True
183 self.node.got_conn(self, services)
185 if state['highest']['hash'] != 2**256 - 1:
186 self.handle_share0s(chains=[dict(
187 chain_id=state['chain_id'],
188 hashes=[state['highest']['hash']],
191 if isinstance(self.factory, ClientFactory):
192 draw_line(self.node.port, self.transport.getPeer().port, (0, 255, 0))
194 def handle_set_mode(self, mode):
195 self.other_mode_var.set(mode)
197 def handle_ping(self):
200 def handle_addrme(self, port):
201 self.node.got_addr(('::ffff:' + self.transport.getPeer().host, port), self.other_services, int(time.time()))
202 if random.random() < .7 and self.node.peers:
203 random.choice(self.node.peers.values()).send_addrs(addrs=[dict(address=dict(services=self.other_services, address='::ffff:' + self.transport.getPeer().host, port=port), timestamp=int(time.time()))])
204 def handle_addrs(self, addrs):
205 for addr_record in addrs:
206 self.node.got_addr((addr_record['address']['address'], addr_record['address']['port']), addr_record['address']['services'], min(int(time.time()), addr_record['timestamp']))
207 if random.random() < .7 and self.node.peers:
208 random.choice(self.node.peers.values()).send_addrs(addrs=[addr_record])
209 def handle_getaddrs(self, count):
210 self.send_addrs(addrs=[
212 timestamp=self.node.addr_store[host, port][2],
214 services=self.node.addr_store[host, port][0],
219 random.sample(self.node.addr_store.keys(), min(count, len(self.node.addr_store)))
222 def handle_getsharestohighest(self, chain_id, have):
223 self.node.handle_get_shares_to_highest(chain_id, have, self)
225 def handle_getshares(self, chain_id, hashes):
226 self.node.handle_get_shares(chain_id, hashes, self)
228 def handle_share0s(self, chains):
230 for hash_ in chain['hashes']:
231 self.node.handle_share_hash(p2pool.chain_id_type.pack(chain['chain_id']), hash_, self)
232 def handle_share1s(self, share1s):
233 for share1 in share1s:
234 hash_ = bitcoin_p2p.block_hash(share1['header'])
235 if hash_ <= conv.bits_to_target(share1['header']['bits']):
236 print "Dropping peer %s:%i due to invalid share" % (self.transport.getPeer().host, self.transport.getPeer().port)
237 self.transport.loseConnection()
239 share = p2pool.Share(share1['header'], gentx=share1['gentx'])
240 self.node.handle_share(share)
241 def handle_share2s(self, share2s):
242 for share2 in share2s:
243 hash_ = bitcoin_p2p.block_hash(share2['header'])
244 if not hash_ <= conv.bits_to_target(share1['header']['bits']):
245 print "Dropping peer %s:%i due to invalid share" % (self.transport.getPeer().host, self.transport.getPeer().port)
246 self.transport.loseConnection()
248 share = p2pool.Share(share1['header'], txns=share1['txns'])
249 self.node.handle_share(share)
251 def send_share(self, share):
252 if share.hash <= conv.bits_to_target(share.header['bits']):
253 self.send_share2s(share2s=[share.as_block()])
256 self.send_share0s(chains=[dict(
257 chain_id=p2pool.chain_id_type.unpack(share.chain_id_data),
261 self.send_share1s(share1s=[dict(
266 raise ValueError(self.mode)
268 def connectionLost(self, reason):
269 if self.node_var_watch is not None:
270 self.node.mode_var.changed.unwatch(self.node_var_watch)
273 self.node.lost_conn(self)
275 if isinstance(self.factory, ClientFactory):
276 draw_line(self.node.port, self.transport.getPeer().port, (255, 0, 0))
278 class ServerFactory(protocol.ServerFactory):
279 def __init__(self, node):
282 def buildProtocol(self, addr):
283 p = Protocol(self.node)
287 class ClientFactory(protocol.ClientFactory):
288 def __init__(self, node):
291 def buildProtocol(self, addr):
292 p = Protocol(self.node)
296 def startedConnecting(self, connector):
297 self.node.attempt_started(connector)
299 def clientConnectionFailed(self, connector, reason):
300 self.node.attempt_failed(connector)
302 def clientConnectionLost(self, connector, reason):
303 self.node.attempt_ended(connector)
305 addrdb_key = bitcoin_p2p.ComposedType([
306 ('address', bitcoin_p2p.IPV6AddressType()),
307 ('port', bitcoin_p2p.StructType('>H')),
309 addrdb_value = bitcoin_p2p.ComposedType([
310 ('services', bitcoin_p2p.StructType('<Q')),
311 ('first_seen', bitcoin_p2p.StructType('<Q')),
312 ('last_seen', bitcoin_p2p.StructType('<Q')),
315 class AddrStore(util.DictWrapper):
316 def encode_key(self, (address, port)):
317 return addrdb_key.pack(dict(address=address, port=port))
318 def decode_key(self, encoded_key):
319 k = addrdb_key.unpack(encoded_key)
320 return k['address'], k['port']
322 def encode_value(self, (services, first_seen, last_seen)):
323 return addrdb_value.pack(dict(services=services, first_seen=first_seen, last_seen=last_seen))
324 def decode_value(self, encoded_value):
325 v = addrdb_value.unpack(encoded_value)
326 return v['services'], v['first_seen'], v['last_seen']
329 def __init__(self, current_work, port, testnet, addr_store=None, preferred_addrs=[], mode=0, desired_peers=10, max_attempts=100):
330 if addr_store is None:
334 self.testnet = testnet
335 self.addr_store = AddrStore(addr_store)
336 self.preferred_addrs = preferred_addrs
337 self.mode_var = util.Variable(mode)
338 self.desired_peers = desired_peers
339 self.max_attempts = max_attempts
340 self.current_work = current_work
342 self.nonce = random.randrange(2**64)
347 draw_circle(self.port)
351 raise ValueError("already running")
355 self.listen_port = reactor.listenTCP(self.port, ServerFactory(self))
360 @defer.inlineCallbacks
364 if len(self.peers) < self.desired_peers and len(self.attempts) < self.max_attempts and (len(self.preferred_addrs) or len(self.addr_store)):
365 if (random.randrange(2) and len(self.preferred_addrs)) or not len(self.addr_store):
366 host, port = random.choice(self.preferred_addrs)
368 host2, port = random.choice(self.addr_store.keys())
370 if not host2.startswith(prefix):
371 raise ValueError("invalid address")
372 host = host2[len(prefix):]
374 if (host, port) not in self.attempts and (host, port) not in self.peers:
375 reactor.connectTCP(host, port, ClientFactory(self), timeout=10)
377 traceback.print_exc()
379 yield util.sleep(random.expovariate(1/5))
381 @defer.inlineCallbacks
385 if len(self.addr_store) < self.preferred_addrs and self.peers:
386 random.choice(self.peers.values()).send_getaddrs(count=8)
388 traceback.print_exc()
390 yield util.sleep(random.expovariate(1/20))
394 raise ValueError("already stopped")
398 self.listen_port.stopListening()
401 def attempt_started(self, connector):
402 host, port = connector.getDestination().host, connector.getDestination().port
403 if (host, port) in self.attempts:
404 raise ValueError("already have attempt")
405 self.attempts[host, port] = connector
407 def attempt_failed(self, connector):
408 self.attempt_ended(connector)
410 def attempt_ended(self, connector):
411 host, port = connector.getDestination().host, connector.getDestination().port
412 if (host, port) not in self.attempts:
413 raise ValueError("don't have attempt")
414 if connector is not self.attempts[host, port]:
415 raise ValueError("wrong connector")
416 del self.attempts[host, port]
419 def got_conn(self, conn, services):
420 host, port = conn.transport.getPeer().host, conn.transport.getPeer().port
421 if (host, port) in self.peers:
422 raise ValueError("already have peer")
423 self.peers[host, port] = conn
425 print "Connected to peer %s:%i" % (host, port)
427 def lost_conn(self, conn):
428 host, port = conn.transport.getPeer().host, conn.transport.getPeer().port
429 if (host, port) not in self.peers:
430 raise ValueError("don't have peer")
431 if conn is not self.peers[host, port]:
432 raise ValueError("wrong conn")
433 del self.peers[host, port]
435 print "Lost peer %s:%i" % (host, port)
438 def got_addr(self, (host, port), services, timestamp):
439 if (host, port) in self.addr_store:
440 old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
441 self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
443 self.addr_store[host, port] = services, timestamp, timestamp
445 def handle_get_shares_to_highest(self, chain_id_data, have, peer):
448 def handle_get_shares(self, chain_id_data, hashes, peer):
451 def handle_share_hash(self, chain_id_data, hash, peer):
454 if __name__ == '__main__':
455 p = random.randrange(2**15, 2**16)
457 p2 = random.randrange(2**15, 2**16)
459 n = Node(p2, True, {addrdb_key.pack(dict(address='::ffff:' + '127.0.0.1', port=p)): addrdb_value.pack(dict(services=0, first_seen=int(time.time())-10, last_seen=int(time.time())))})