def give_block(self, peer_ip_port, block_count_peer): blocks = [] b = [ max(block_count_peer - 5, 0), min( self.db.get('length'), block_count_peer + self.engine.config['peers']['download_limit']) ] for i in range(b[0], b[1] + 1): blocks.append(self.db.get(i)) ntwrk.command(peer_ip_port, { 'action': 'push_block', 'blocks': blocks }, self.node_id) return 0
def ask_for_txs(self, peer_ip_port): txs = ntwrk.command(peer_ip_port, {'action': 'txs'}, self.node_id) T = self.blockchain.tx_pool() pushers = list(filter(lambda t: t not in txs, T)) for push in pushers: ntwrk.command(peer_ip_port, { 'action': 'push_tx', 'tx': push }, self.node_id) if not isinstance(txs, list): return -1 for tx in txs: self.blockchain.tx_queue.put(tx) return 0
def download_blocks(self, peer_ip_port, block_count_peer, length, node_id): b = [ max(0, length - 10), min(block_count_peer + 1, length + self.engine.config['peers']['download_limit']) ] blocks = ntwrk.command(peer_ip_port, { 'action': 'range_request', 'range': b }, self.node_id) if isinstance(blocks, list): self.blockchain.blocks_queue.put((blocks, node_id))
def peer_check(self, peer): peer_ip_port = (peer['ip'], peer['port']) greeted = ntwrk.command( peer_ip_port, { 'action': 'greetings', 'node_id': self.node_id, 'port': self.engine.config['port']['peers'], 'length': self.db.get('length'), 'diffLength': self.db.get('diffLength') }, self.node_id) if not isinstance(greeted, dict): return None if 'error' in greeted.keys(): return None peer['diffLength'] = greeted['diffLength'] peer['length'] = greeted['length'] self.account.update_peer(peer) known_length = self.db.get('known_length') if greeted['length'] > known_length: self.db.put('known_length', greeted['length']) length = self.db.get('length') diff_length = self.db.get('diffLength') size = max(len(diff_length), len(greeted['diffLength'])) us = tools.buffer_(diff_length, size) them = tools.buffer_(greeted['diffLength'], size) # This is the most important peer operation part # We are deciding what to do with this peer. We can either # send them blocks, share txs or download blocks. # Only transfer peers at every minute. peer_history = self.account.get_peer_history(peer['node_id']) if time.time() - peer_history['peer_transfer'] > 60: my_peers = self.account.get_peers() their_peers = ntwrk.command(peer_ip_port, {'action': 'peers'}, self.node_id) if type(their_peers) == list: for p in their_peers: self.account.add_peer(p, 'friend_of_mine') for p in my_peers: ntwrk.command(peer_ip_port, { 'action': 'receive_peer', 'peer': p }, self.node_id) peer_history['peer_transfer'] = time.time() self.account.set_peer_history(peer['node_id'], peer_history) if them < us: self.give_block(peer_ip_port, greeted['length']) return 1 elif us == them: self.ask_for_txs(peer_ip_port) return 2 else: self.download_blocks(peer_ip_port, greeted['length'], length, peer['node_id']) return 3