dragonchain/lib/dto/bnb.py
def new_from_user_input(user_input: Dict[str, Any]) -> "BinanceNetwork":  # noqa: C901
    """Create a new BinanceNetwork model from user input
    Args:
        user_input: User dictionary input (assumed already passing create_binance_interchain_schema)
    Returns:
        Instantiated BinanceNetwork client
    Raises:
        exceptions.BadRequest: With bad input
    """
    dto_version = user_input.get("version")
    if dto_version == "1":
        if not user_input.get("private_key"):
            # We need to create a private key if not provided
            user_input["private_key"] = base64.b64encode(secp256k1.PrivateKey().private_key).decode("ascii")
        else:
            try:
                # Check if user provided key is hex and convert if necessary
                if len(user_input["private_key"]) == 66:  # private keys in hex are 66 chars with leading 0x
                    user_input["private_key"] = user_input["private_key"][2:]  # Trim the 0x
                if len(user_input["private_key"]) == 64:  # private keys in hex are 64 chars
                    user_input["private_key"] = base64.b64encode(bytes.fromhex(user_input["private_key"])).decode("ascii")
                else:
                    try:  # is it a base64 key?  check!
                        secp256k1.PrivateKey(privkey=base64.b64decode(user_input["private_key"]), raw=True)
                    except Exception:
                        _log.warning("[BINANCE] Key not hex or base64... falling back to generating key from mnemonic.")
                        # not hex, not base64... at this point, assume key is a mnemonic string
                        seed = mnemonic.Mnemonic.to_seed(user_input["private_key"])
                        parent_wallet = network.keys.bip32_seed(seed)
                        child_wallet = parent_wallet.subkey_for_path("44'/714'/0'/0/0")
                        # convert secret exponent (private key) int to hex
                        key_hex = format(child_wallet.secret_exponent(), "x")
                        user_input["private_key"] = base64.b64encode(bytes.fromhex(key_hex)).decode("ascii")
            except Exception:
                _log.exception(f"[BINANCE] Exception thrown during key handling.  Bad key: {user_input['private_key']}")
                raise exceptions.BadRequest("Provided private key did not successfully decode into a valid key.")

        # check if user specified that node is a testnet
        if user_input.get("testnet") is None:
            user_input["testnet"] = True  # default to testnet
        # check for user-provided node address
        if not user_input.get("node_url"):
            # default to Dragonchain managed Binance node if not provided
            user_input["node_url"] = NODE_URL
            user_input["rpc_port"] = TESTNET_RPC_PORT if user_input.get("testnet") else MAINNET_RPC_PORT
            user_input["api_port"] = TESTNET_API_PORT if user_input.get("testnet") else MAINNET_API_PORT
        else:  # user specified NODE_URL; make sure they specified ports, too!
            if not user_input["rpc_port"] or not user_input["api_port"]:
                raise exceptions.BadRequest("Node URL specified, but RPC or API ports not specified.")
        # Create the actual client and check that the given node is reachable
        try:
            client = BinanceNetwork(
                name=user_input["name"],
                testnet=user_input["testnet"],
                node_url=user_input["node_url"],
                rpc_port=user_input["rpc_port"],
                api_port=user_input["api_port"],
                b64_private_key=user_input["private_key"],
            )
        except Exception as e:
            _log.exception("[BINANCE] Exception thrown during client creation.")
            raise exceptions.BadRequest(f"Client creation failed. Error: {e}")
        # check that the binance node is reachable (this checks both RPC and API endpoints)
        try:
            client.ping()
        except Exception as e:
            raise exceptions.BadRequest(f"Provided binance node doesn't seem reachable. Error: {e}")
        return client
    else:
        raise exceptions.BadRequest(f"User input version {dto_version} not supported")
Create a new BinanceNetwork model from user input
    Args:
        user_input: User dictionary input (assumed already passing create_binance_interchain_schema)
    Returns:
        Instantiated BinanceNetwork client
    Raises:
        exceptions.BadRequest: With bad input
    
Create a new BinanceNetwork model from user input
Create a new BinanceNetwork model from user input
def new_from_user_input(user_input: Dict[str, Any]) -> "BinanceNetwork":  
    dto_version = user_input.get("version")
    if dto_version == "1":
        if not user_input.get("private_key"):
            user_input["private_key"] = base64.b64encode(secp256k1.PrivateKey().private_key).decode("ascii")
        else:
            try:
                if len(user_input["private_key"]) == 66:  
                    user_input["private_key"] = user_input["private_key"][2:]  
                if len(user_input["private_key"]) == 64:  
                    user_input["private_key"] = base64.b64encode(bytes.fromhex(user_input["private_key"])).decode("ascii")
                else:
                    try:  
                        secp256k1.PrivateKey(privkey=base64.b64decode(user_input["private_key"]), raw=True)
                    except Exception:
                        _log.warning("[BINANCE] Key not hex or base64... falling back to generating key from mnemonic.")
                        seed = mnemonic.Mnemonic.to_seed(user_input["private_key"])
                        parent_wallet = network.keys.bip32_seed(seed)
                        child_wallet = parent_wallet.subkey_for_path("44'/714'/0'/0/0")
                        key_hex = format(child_wallet.secret_exponent(), "x")
                        user_input["private_key"] = base64.b64encode(bytes.fromhex(key_hex)).decode("ascii")
            except Exception:
                _log.exception(f"[BINANCE] Exception thrown during key handling.  Bad key: {user_input['private_key']}")
                raise exceptions.BadRequest("Provided private key did not successfully decode into a valid key.")
        if user_input.get("testnet") is None:
            user_input["testnet"] = True  
        if not user_input.get("node_url"):
            user_input["node_url"] = NODE_URL
            user_input["rpc_port"] = TESTNET_RPC_PORT if user_input.get("testnet") else MAINNET_RPC_PORT
            user_input["api_port"] = TESTNET_API_PORT if user_input.get("testnet") else MAINNET_API_PORT
        else:  
            if not user_input["rpc_port"] or not user_input["api_port"]:
                raise exceptions.BadRequest("Node URL specified, but RPC or API ports not specified.")
        try:
            client = BinanceNetwork(
                name=user_input["name"],
                testnet=user_input["testnet"],
                node_url=user_input["node_url"],
                rpc_port=user_input["rpc_port"],
                api_port=user_input["api_port"],
                b64_private_key=user_input["private_key"],
            )
        except Exception as e:
            _log.exception("[BINANCE] Exception thrown during client creation.")
            raise exceptions.BadRequest(f"Client creation failed. Error: {e}")
        try:
            client.ping()
        except Exception as e:
            raise exceptions.BadRequest(f"Provided binance node doesn't seem reachable. Error: {e}")
        return client
    else:
        raise exceptions.BadRequest(f"User input version {dto_version} not supported")
def new_from_user_input ( user_input : Dict [ str , Any ] ) -> "BinanceNetwork" : dto_version = user_input . get ( "version" ) if dto_version == "1" : if not user_input . get ( "private_key" ) : user_input [ "private_key" ] = base64 . b64encode ( secp256k1 . PrivateKey ( ) . private_key ) . decode ( "ascii" ) else : try : if len ( user_input [ "private_key" ] ) == 66 : user_input [ "private_key" ] = user_input [ "private_key" ] [ 2 : ] if len ( user_input [ "private_key" ] ) == 64 : user_input [ "private_key" ] = base64 . b64encode ( bytes . fromhex ( user_input [ "private_key" ] ) ) . decode ( "ascii" ) else : try : secp256k1 . PrivateKey ( privkey = base64 . b64decode ( user_input [ "private_key" ] ) , raw = True ) except Exception : _log . warning ( "[BINANCE] Key not hex or base64... falling back to generating key from mnemonic." ) seed = mnemonic . Mnemonic . to_seed ( user_input [ "private_key" ] ) parent_wallet = network . keys . bip32_seed ( seed ) child_wallet = parent_wallet . subkey_for_path ( "44'/714'/0'/0/0" ) key_hex = format ( child_wallet . secret_exponent ( ) , "x" ) user_input [ "private_key" ] = base64 . b64encode ( bytes . fromhex ( key_hex ) ) . decode ( "ascii" ) except Exception : _log . exception ( f"[BINANCE] Exception thrown during key handling.  Bad key: {user_input['private_key']}" ) raise exceptions . BadRequest ( "Provided private key did not successfully decode into a valid key." ) if user_input . get ( "testnet" ) is None : user_input [ "testnet" ] = True if not user_input . get ( "node_url" ) : user_input [ "node_url" ] = NODE_URL user_input [ "rpc_port" ] = TESTNET_RPC_PORT if user_input . get ( "testnet" ) else MAINNET_RPC_PORT user_input [ "api_port" ] = TESTNET_API_PORT if user_input . get ( "testnet" ) else MAINNET_API_PORT else : if not user_input [ "rpc_port" ] or not user_input [ "api_port" ] : raise exceptions . BadRequest ( "Node URL specified, but RPC or API ports not specified." ) try : client = BinanceNetwork ( name = user_input [ "name" ] , testnet = user_input [ "testnet" ] , node_url = user_input [ "node_url" ] , rpc_port = user_input [ "rpc_port" ] , api_port = user_input [ "api_port" ] , b64_private_key = user_input [ "private_key" ] , ) except Exception as e : _log . exception ( "[BINANCE] Exception thrown during client creation." ) raise exceptions . BadRequest ( f"Client creation failed. Error: {e}" ) try : client . ping ( ) except Exception as e : raise exceptions . BadRequest ( f"Provided binance node doesn't seem reachable. Error: {e}" ) return client else : raise exceptions . BadRequest ( f"User input version {dto_version} not supported" )
Create a new BinanceNetwork model from user input
Create a new BinanceNetwork model from user input
# noqa: C901 """Create a new BinanceNetwork model from user input
    Args:
        user_input: User dictionary input (assumed already passing create_binance_interchain_schema)
    Returns:
        Instantiated BinanceNetwork client
    Raises:
        exceptions.BadRequest: With bad input
    """ # We need to create a private key if not provided # Check if user provided key is hex and convert if necessary # private keys in hex are 66 chars with leading 0x # Trim the 0x # private keys in hex are 64 chars # is it a base64 key?  check! # not hex, not base64... at this point, assume key is a mnemonic string # convert secret exponent (private key) int to hex # check if user specified that node is a testnet # default to testnet # check for user-provided node address # default to Dragonchain managed Binance node if not provided # user specified NODE_URL; make sure they specified ports, too! # Create the actual client and check that the given node is reachable # check that the binance node is reachable (this checks both RPC and API endpoints)
Instantiated BinanceNetwork client
Instantiated BinanceNetwork client
With bad input
With bad input
exceptions.BadRequest
user_input
Dict[str, Any]
User dictionary input (assumed already passing create_binance_interchain_schema)
User dictionary input ( assumed already passing create_binance_interchain_schema )