Untitled

Anonymous
plain_text
02/24/2026 6:30 AM
6.0 KB
13
Indexable
    def register_entity_endpoint(self):
        """
        Entity miner registration.
        """
        start_time = time.time()

        # 1. Validate API key
        api_key = self._get_api_key_safe()
        if not self.is_valid_api_key(api_key):
            return jsonify({'error': 'Unauthorized access'}), 401

        # 2. Use cached wallet or fall back to per-request loading
        if self._coldkey and self._hotkey and self._validator_url:
            coldkey = self._coldkey
            hotkey = self._hotkey
            validator_url = self._validator_url
        else:
            try:
                secrets = ValiUtils.get_secrets(secrets_path=MinerConfig.get_secrets_file_path())
                wallet_name = secrets.get('wallet_name')
                wallet_hotkey = secrets.get('wallet_hotkey')
                wallet_password = ValiUtils.get_secret('wallet_password', secrets_path=MinerConfig.get_secrets_file_path())
                validator_url = secrets.get('validator_url')

                if not all([wallet_name, wallet_hotkey, wallet_password, validator_url]):
                    del wallet_password
                    return jsonify({
                        'status': 'error',
                        'message': 'Missing wallet configuration in secrets file'
                    }), 500

                wallet = Wallet(name=wallet_name, hotkey=wallet_hotkey)
                coldkey = wallet.get_coldkey(password=wallet_password)
                hotkey = wallet.hotkey
                del wallet_password
            except Exception as e:
                bt.logging.error(f"Error loading wallet secrets: {e}")
                return jsonify({'status': 'error', 'message': 'Failed to load wallet configuration'}), 500

        # 3. Sign message
        try:
            # Build message dict - CRITICAL: must use sort_keys=True for deterministic ordering
            message_dict = {
                "entity_coldkey": coldkey.ss58_address,
                "entity_hotkey": hotkey.ss58_address,
            }
            message = json.dumps(message_dict, sort_keys=True).encode('utf-8')

            # Sign with coldkey
            signature = coldkey.sign(message).hex()
        except Exception as e:
            bt.logging.error(f"Error signing message: {e}")
            return jsonify({'status': 'error', 'message': f'Wallet error: {str(e)}'}), 500

        # 4. Send request to validator
        try:
            payload = {
                "entity_hotkey": hotkey.ss58_address,
                "entity_coldkey": coldkey.ss58_address,
                "signature": signature,
            }

            async def register_entity():
                # 1. Initialize the Connector
                from aiohttp_socks import ProxyConnector
                connector = ProxyConnector.from_url("socks5://127.0.0.1:2001", rdns=True)

                # 2. Pass the connector to the ClientSession
                async with aiohttp.ClientSession(connector=connector) as session:
                    try:
                        # 3. Perform the POST request
                        async with session.post(
                            f"{validator_url}/entity/register",
                            json=payload,
                            headers={"Content-Type": "application/json"},
                            timeout=aiohttp.ClientTimeout(total=60)
                        ) as response:
                            return response.status, await response.json()
                            
                    except Exception as e:
                        print(f"An error occurred: {e}")
            
            status_code, response_data = asyncio.run(register_entity())

            # Return validator response
            if status_code == 200:
                return jsonify(response_data), 200
            else:
                error_message = response_data.get('error', 'Unknown error from validator')
                return jsonify({
                    'status': 'error',
                    'message': error_message
                }), status_code

        except requests.exceptions.Timeout:
            return jsonify({'status': 'error', 'message': 'Request to validator timed out'}), 504

        except requests.exceptions.ConnectionError:
            return jsonify({'status': 'error', 'message': 'Could not connect to validator'}), 503

        except Exception as e:
            return jsonify({'status': 'error', 'message': f'Validator communication error: {str(e)}'}), 500
Editor is loading...
Leave a Comment