Skip to content

c-api: use safe enum conversion helpers instead of raw static_cast for C→C++ enum params #244

@fpelliccioni

Description

@fpelliccioni

Problem

The C-API bindings use static_cast<CppEnum>(c_enum_value) to convert C enum integers to C++ enum class types. If a caller passes an out-of-range integer value, static_cast produces an unspecified enum value — undefined behavior in practice.

The codebase already has safe conversion helpers (e.g. kth::network_to_cpp(kth_network_t) in helpers.hpp) that map unknown values to a sensible default (typically mainnet). Hand-written C-API code uses these helpers consistently, but the generated bindings emit raw static_cast instead.

Current behavior (generated code)

auto const net_cpp = static_cast<kth::domain::config::network>(net);

Expected behavior

auto const net_cpp = kth::network_to_cpp(net);

Or a generic pattern that works for all registered enums.

Scope

This affects every generated function that takes a C enum parameter:

  • kth_network_tconfig::network (payment_address, get_blocks, get_headers, etc.)
  • kth_script_flags_tmachine::script_flags
  • Any future enum params

Possible fix

Option A: Register a safe conversion helper per enum in the generator's _ENUM_REGISTRY, and emit calls to it instead of static_cast.

Option B: Generate a generic helper template:

template<typename CppEnum, typename CEnum>
CppEnum safe_enum_cast(CEnum value, CppEnum default_value);

Option C: Add a default case to each switch that uses the enum, returning a sensible fallback. This is what network_to_cpp already does internally.

Flagged by

Cursor Bugbot on PR #241 (comment #8).

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions