### GET_APP_CONFIGURATION Example Request Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/endpoints.md Example request to retrieve the XRP app's version and configuration. ```hex E0 06 00 00 00 ``` -------------------------------- ### Sequential Reading Guide Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/INDEX.md Provides a recommended reading order for new users to understand the XRP app project, starting from the README and progressing through protocol, types, errors, and API references. ```markdown 1. [README.md](./README.md) - Understand project scope 2. [endpoints.md](./endpoints.md) - Learn communication protocol 3. [types.md](./types.md) - Understand data structures 4. [errors.md](./errors.md) - Know error handling 5. Relevant API reference files for specific tasks ``` -------------------------------- ### GET_APP_CONFIGURATION Example Response Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/endpoints.md Example response indicating the XRP app version is 5.1.0. ```hex 00 05 01 00 9000 ``` -------------------------------- ### Python Usage Example for XRP Configuration Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/app-configuration.md Demonstrates how to instantiate the XRPClient and call the get_configuration method to retrieve and print the application version. ```python xrp_client = XRPClient(transport, navigator) version = xrp_client.get_configuration() print(f"App version: {version}") # Output: "App version: 5.1.0" ``` -------------------------------- ### GET_PUBLIC_KEY Example Request Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/endpoints.md Example request to retrieve a public key and address without confirmation, using secp256k1 and no chain code. ```hex E0 02 00 40 21 05 80 00 00 2C 80 00 00 90 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ``` -------------------------------- ### Install XRP App Source: https://github.com/ledgerhq/app-xrp/blob/develop/README.md Use this command to upload the XRP app to your Ledger device after building it. ```sh make load ``` -------------------------------- ### C Example: Sending GET_PUBLIC_KEY APDU (Non-Confirmed) Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/public-key-handler.md Example of how to construct and send a GET_PUBLIC_KEY APDU command without user confirmation. It specifies the BIP32 path data. ```c // Without confirmation uint8_t path_data[] = {0x05, 0x80, 0x00, 0x00, 0x2C, 0x80, 0x00, 0x00, 0x90, ...}; // Sends APDU with CLA=0xE0, INS=0x02, P1=0x00, P2=0x40, data=path_data ``` -------------------------------- ### Implementation Guide Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/INDEX.md Details the steps for implementing or modifying the XRP app, focusing on protocol, data types, handlers, error codes, and configuration. ```markdown 1. Start with protocol documentation ([endpoints.md](./endpoints.md)) 2. Understand data types ([types.md](./types.md)) 3. Review relevant handler ([api-reference/](./api-reference/)) 4. Check error codes ([errors.md](./errors.md)) 5. Review configuration if modifying app ([configuration.md](./configuration.md)) ``` -------------------------------- ### Basic CMake Setup Source: https://github.com/ledgerhq/app-xrp/blob/develop/unit-tests/CMakeLists.txt Sets the minimum CMake version and project name. Configures the C standard and build type, and defines debug flags and linker options for coverage. ```cmake cmake_minimum_required(VERSION 3.10) project(test_parser C) include(CTest) set(CMAKE_C_STANDARD 11) if (NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Debug") endif() set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -g -O0 --coverage") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} --coverage -lgcov") enable_testing() ``` -------------------------------- ### Segmented Address Display Example (Nano S) Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/field-formatting.md Illustrates how long addresses are displayed in segments on the Nano S when `DISPLAY_SEGMENTED_ADDR` is true. ```text Screen 1: "Destination:" Screen 2: "rN7n7otQDd6FczF" Screen 3: "gLdhmKWbKL7KK4h" Screen 4: "9PnU" ``` -------------------------------- ### Resolve Field Name Examples Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/field-formatting.md Illustrates the mapping of field types and IDs to their corresponding human-readable names. ```text Type=STI_UINT32, ID=0x04 → "Sequence" Type=STI_AMOUNT, ID=0x01 → "Amount" Type=STI_ACCOUNT, ID=0x03 → "Destination" Type=STI_VL, ID=0x0C → "MemoType" ``` -------------------------------- ### Reference Lookup Guide Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/INDEX.md Outlines how experienced developers can quickly find information using reference tables, direct file jumps, and cross-references. ```markdown 1. Use [By Function](#by-function) or [By Type](#by-data-type) tables 2. Jump directly to relevant API reference file 3. Cross-reference related documentation as needed ``` -------------------------------- ### C Function Signature for Get App Configuration Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/app-configuration.md This is the function signature for handling the GET_APP_CONFIGURATION APDU command. It takes a pointer to track the response buffer size. ```c void handle_get_app_configuration(volatile unsigned int *tx) ``` -------------------------------- ### Run Functional Tests with Speculos Source: https://github.com/ledgerhq/app-xrp/blob/develop/tests/README.md Starts the Speculos emulator with detailed logging and loads the automation file for functional tests. Ensure the XRP app ELF file is correctly specified. ```console ./speculos.py --log-level automation:DEBUG --automation file:$HOME/app-xrp/tests/automation.json ~/app-xrp/bin/app.elf & export LEDGER_PROXY_ADDRESS=127.0.0.1 LEDGER_PROXY_PORT=9999 pytest-3 -v -s ``` -------------------------------- ### SIGN Example Single-Packet Request Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/endpoints.md Example of a single-packet request for signing a transaction using secp256k1. ```hex E0 04 00 40 [transaction_data...] ``` -------------------------------- ### PathSet Field Formatting Example Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/field-formatting.md PathSet fields, representing payment paths, are displayed with indexed paths and steps. ```text [Path 0, Step 0] [Path 0, Step 1] [Path 1, Step 0] ``` -------------------------------- ### Hex-Encoded Public Key Example Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/field-formatting.md Public key fields are formatted as uppercase, hex-encoded byte strings. ```text 03857E2F83D6B1B8E6CF5E0B8E5E9E9E9E5E8F8D8D8D8D8D8D8D8D8D8D8D8 ``` -------------------------------- ### Issued Currency Amount Example Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/amount-formatting.md Illustrates the byte structure of an issued currency amount, including flags, mantissa, exponent, currency code, and issuer account ID. ```assembly Bytes 0: Flags and type (bit 63 = 1 for non-XRP, bit 62 = sign) Bytes 1-8: Amount mantissa (big-endian integer) Byte 9: Exponent (offset by 97 for bias) Bytes 10-29: Currency code (20 bytes) Bytes 30-49: Issuer account ID (20 bytes) Amount: 123.456 USD from Issuer rN7n7otQDd6FczFgLdhmKWbKL7KK4h9PnU Bytes: [0xB2] [0x1E 0x2D 0xA0 0x00 0x00 0x00 0x00] [0x60] [00 00 00 00 00 00 00 00 00 00 00 00 55 53 44 00 00 00 00 00] [account_id_20_bytes...] ``` -------------------------------- ### XRP Payment Transaction Formatting Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/amount-formatting.md Example of a client sending a Payment transaction and how the device parses and formats the Amount and Fee fields for display. ```python # Client sends transaction with Payment type transaction = { "TransactionType": "Payment", "Account": "rN7n7otQDd6FczFgLdhmKWbKL7KK4h9PnU", "Destination": "rLHzPsX6oXkzU2zL2SLV5DKwkQG6GJV8R5", "Amount": "1000000", # 1 XRP in drops "Fee": "12" # 12 drops } # Device receives, parses, and formats: # - Amount field → "1" (displays as decimal XRP) # - Fee field → "0.000012" (12 drops) ``` -------------------------------- ### APDU Response Format for Get App Configuration Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/app-configuration.md Details the expected response format from the APDU command for application configuration. Includes the version information and status word. ```plaintext Response: [version info: 4 bytes] [status word: 0x9000] ``` -------------------------------- ### APDU Command Format for Get App Configuration Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/app-configuration.md Specifies the APDU command structure for requesting application configuration. Includes CLA, INS, P1, P2, and data fields. ```plaintext CLA: 0xE0 INS: 0x06 (INS_GET_APP_CONFIGURATION) P1: 0x00 (ignored) P2: 0x00 (ignored) Data: (empty) ``` -------------------------------- ### Multi-signing an XRP Transaction Source: https://github.com/ledgerhq/app-xrp/blob/develop/README.md This snippet demonstrates how to construct a transaction, source external signatures, and combine them with a signature from the Ledger device for multi-signing. Ensure you have the necessary imports and functions declared from previous examples. ```javascript const transactionJSON = { Account: "r4PCuDkjuV2e23xVP8ChkVxo1aG2Ufpkjb", TransactionType: "Payment", Destination: "rTooLkitCksh5mQa67eaa2JaWHDBnHkpy", Amount: "1000000", Fee: "15", Flags: 2147483648, Sequence: 47, SigningPubKey: "", // Must be blank }; // Sourced externally from other signing parties, replace "..." with actual values. const otherSigners = [ { Signer: { Account: "...", SigningPubKey: "...", TxnSignature: "...", }, }, { Signer: { Account: "...", SigningPubKey: "...", TxnSignature: "...", }, }, ]; function retrieveSignerData(transaction) { return establishConnection() .then((xrp) => fetchAddress(xrp)) .then((context) => { return signTransaction(context, transaction).then((signature) => { return { Signer: { Account: context.account, SigningPubKey: context.publicKey, TxnSignature: signature.toUpperCase(), }, }; }); }) .catch((e) => console.log(`An error occurred (${e.message})`)); } retrieveSignerData(transactionJSON) .then((signer) => { return { ...transactionJSON, Signers: [...otherSigners, signer], }; }) .then((transaction) => console.log(transaction)) .catch((e) => console.log(`An error occurred (${e.message})`)); ``` -------------------------------- ### Fuzzing Test with Corpus Source: https://github.com/ledgerhq/app-xrp/blob/develop/tests/README.md Runs the fuzzing binary for transaction processing using a pre-populated corpus of raw transaction files. This enhances fuzzing efficiency by starting with known valid inputs. ```console mkdir -p /tmp/corpus find tests/testcases/ -name '*.raw' -exec cp '{}' /tmp/corpus/ ';' ./tests/build/fuzz_tx /tmp/corpus >/dev/null ``` -------------------------------- ### Basic XRP Payment Transaction Source: https://github.com/ledgerhq/app-xrp/blob/develop/README.md Initiates a connection to a Ledger device, fetches the XRP address, and signs a payment transaction. Ensure you have the necessary transport library (e.g., @ledgerhq/hw-transport-node-hid) installed. ```javascript import Transport from "@ledgerhq/hw-transport-node-hid"; // import Transport from "@ledgerhq/hw-transport-u2f"; // for browser import Xrp from "@ledgerhq/hw-app-xrp"; import { encode } from "ripple-binary-codec"; function establishConnection() { return Transport.create().then((transport) => new Xrp(transport)); } function fetchAddress(xrp) { return xrp.getAddress("44'/144'/0'/0/0").then((deviceData) => { return { xrp, address: deviceData.address, publicKey: deviceData.publicKey.toUpperCase(), }; }); } function signTransaction(context, transaction) { const preparedTransaction = { Account: context.address, SigningPubKey: context.publicKey, ...transaction, }; const transactionBlob = encode(preparedTransaction); console.log("Sending transaction to device for approval..."); return context.xrp.signTransaction("44'/144'/0'/0/0", transactionBlob); } const transactionJSON = { TransactionType: "Payment", Destination: "rTooLkitCksh5mQa67eaa2JaWHDBnHkpy", Amount: "1000000", Fee: "15", Flags: 2147483648, Sequence: 57, }; establishConnection() .then((xrp) => fetchAddress(xrp)) .then((context) => signTransaction(context, transactionJSON)) .then((signature) => console.log(`Signature: ${signature}`)) .catch((e) => console.log(`An error occurred (${e.message})`)); ``` -------------------------------- ### XRP Base58Check Address Example Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/field-formatting.md Account ID fields are formatted as XRP Base58Check addresses, which start with 'r'. ```text rN7n7otQDd6FczFgLdhmKWbKL7KK4h9PnU ``` -------------------------------- ### Build XRP App Source: https://github.com/ledgerhq/app-xrp/blob/develop/README.md Run this command from the repository root to build the XRP app. Ensure your development environment is configured as outlined in the Ledger development documentation. ```sh make ``` -------------------------------- ### Python XRPClient for Configuration Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/app-configuration.md The XRPClient class includes a method to retrieve the application configuration. It sends the GET_CONFIGURATION APDU and unpacks the response data. ```python class XRPClient: def get_configuration(self) -> str: reply = self._exchange(Ins.GET_CONFIGURATION) assert reply.status == Errors.SW_SUCCESS return unpack_configuration_response(reply.data) ``` -------------------------------- ### Linking Libraries for Test Executables Source: https://github.com/ledgerhq/app-xrp/blob/develop/unit-tests/CMakeLists.txt Links the 'test_printers', 'test_swap', and 'test_tx' executables to the XRP library and other required dependencies. ```cmake target_link_libraries(test_printers PRIVATE cmocka crypto ssl xrp) target_link_libraries(test_swap PRIVATE cmocka crypto ssl xrp) target_link_libraries(test_tx PRIVATE cmocka crypto ssl xrp) ``` -------------------------------- ### Build Unit Tests Source: https://github.com/ledgerhq/app-xrp/blob/develop/tests/README.md Configures and builds the unit tests for the XRP application using CMake. This step is required before running the unit tests. ```console cmake -Btests/build -Htests/ make -C tests/build/ ``` -------------------------------- ### Run Unit Tests Source: https://github.com/ledgerhq/app-xrp/blob/develop/tests/README.md Executes the compiled unit tests for the XRP application. This command assumes the tests have been successfully built. ```console make -C tests/build/ test ``` -------------------------------- ### Swap Integration Functions Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/configuration.md Provides a list of functions used for integrating with Ledger Swap, including transaction signing, address verification, and amount formatting. ```c handle_swap_sign_transaction() // Sign for swap handle_check_address() // Verify destination handle_get_printable_amount() // Format swap amount ``` -------------------------------- ### XRP APDU Protocol Instructions Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/configuration.md Lists the instruction codes used in the XRP application's APDU protocol for operations like getting public keys and signing transactions. ```c 0x02: GET_PUBLIC_KEY 0x04: SIGN 0x06: GET_APP_CONFIGURATION ``` -------------------------------- ### GET_APP_CONFIGURATION Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/endpoints.md Retrieves the current version (major, minor, patch) and test flag status of the XRP application. ```APIDOC ## GET_APP_CONFIGURATION (0x06) ### Description Retrieve application version and configuration. ### Request ``` CLA: 0xE0 INS: 0x06 P1: 0x00 P2: 0x00 Data: (empty) ``` ### Response (Success: 0x9000): ``` [test_flag] [major_version] [minor_version] [patch_version] 9000 ``` | Field | Type | Size | Description | |-------|------|------|-------------| | test_flag | uint8 | 1 byte | 0x00 = production, non-zero = test build | | major_version | uint8 | 1 byte | Major version number | | minor_version | uint8 | 1 byte | Minor version number | | patch_version | uint8 | 1 byte | Patch version number | | status | uint16 | 2 bytes | 0x9000 = success | ### Example Request: ``` E0 06 00 00 00 ``` ### Example Response: ``` 00 05 01 00 9000 ``` Version: 5.1.0 ``` -------------------------------- ### Higher-Capacity Configuration for Ledger Nano X, Stax, Flex Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/configuration.md Compile-time defines for higher-capacity devices, allowing for more transaction fields, longer field lengths, and larger transaction sizes. ```c #define MAX_FIELD_COUNT 60 // Maximum parseable fields #define MAX_FIELD_LEN 1024 // Max field display length #define MAX_RAW_TX 10000 // Max transaction size #define DISPLAY_SEGMENTED_ADDR false // Display addresses unbroken ``` -------------------------------- ### Test Executable for Swap Source: https://github.com/ledgerhq/app-xrp/blob/develop/unit-tests/CMakeLists.txt Defines the 'test_swap' executable, including its source files, swap utility headers, and core SDK headers. ```cmake add_executable(test_swap src/test_swap.c src/cx.c ../src/swap/handle_check_address.h ../src/swap/swap_utils.c ../src/swap/swap_utils.h include/bolos_target.h include/cx.h include/os.h ) ``` -------------------------------- ### Test Executable for Transactions Source: https://github.com/ledgerhq/app-xrp/blob/develop/unit-tests/CMakeLists.txt Defines the 'test_tx' executable, listing its source files and essential SDK headers. ```cmake add_executable(test_tx src/test_tx.c src/cx.c include/bolos_target.h include/cx.h include/os.h ) ``` -------------------------------- ### App Configuration Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/INDEX.md Details the APDU handler for retrieving the application's configuration and version information. ```APIDOC ## App Configuration ### Description Retrieves the version information of the XRP Ledger Wallet App. ### Function - `handle_get_app_configuration()`: Get version info. ### Response Format - Version format and response details. ``` -------------------------------- ### Makefile Version Defines Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/app-configuration.md Defines for the application's major, minor, and patch versions are set in the Makefile. These values are compiled into the application binary. ```makefile APPVERSION_M=5 # Major version APPVERSION_N=1 # Minor version APPVERSION_P=0 # Patch version ``` -------------------------------- ### Include Directories Configuration Source: https://github.com/ledgerhq/app-xrp/blob/develop/unit-tests/CMakeLists.txt Specifies the directories to include for header files during the build process. ```cmake include_directories( include ../src ../src/xrp ../src/apdu/messages ../src/apdu ) ``` -------------------------------- ### Shared Hardware Limits Configuration Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/configuration.md Compile-time defines for limits shared across all supported devices, including BIP32 path elements, array lengths, and field name lengths. ```c #define MAX_BIP32_PATH 10 // Max derivation path elements #define MAX_ARRAY_LEN 8 // Max array elements #define MAX_PATH_COUNT 6 // Max payment paths #define MAX_STEP_COUNT 8 // Max path steps #define MAX_ENC_INPUT_SIZE 26 // Max encoded data #define MAX_FIELDNAME_LEN 50 // Max field name length ``` -------------------------------- ### ledger_app.toml Test Configuration Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/configuration.md TOML configuration for tests, defining directories for unit and functional tests. ```toml [tests] unit_directory = "./unit-tests/" pytest_directory = "./tests/" ``` -------------------------------- ### GET_APP_CONFIGURATION Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/README.md Retrieves the current version and configuration of the XRP Ledger Wallet App. ```APIDOC ## GET_APP_CONFIGURATION ### Description Retrieves the current version and configuration of the XRP Ledger Wallet App. ### Method APDU Command ### Endpoint N/A (APDU Instruction) ### Parameters #### APDU Instruction Details - **CLA**: `0xE0` - **INS**: `0x06` - **P1**: Reserved - **P2**: Reserved ### Request Example (APDU command structure) ### Response #### Success Response - **AppVersion**: Major, Minor, Patch version of the app - **ConfigurationFlags**: Various configuration settings (e.g., supported features) #### Response Example (APDU response structure with app version and configuration data) ``` -------------------------------- ### Test Executable for Printers Source: https://github.com/ledgerhq/app-xrp/blob/develop/unit-tests/CMakeLists.txt Defines the 'test_printers' executable and lists its source files and necessary headers. ```cmake add_executable(test_printers src/test_printers.c src/cx.c include/bolos_target.h include/cx.h include/os.h ) ``` -------------------------------- ### XRP Library Definition Source: https://github.com/ledgerhq/app-xrp/blob/develop/unit-tests/CMakeLists.txt Defines the XRP static library by listing its source and header files. ```cmake add_library(xrp ../src/xrp/amount.c ../src/xrp/amount.h ../src/xrp/array.h ../src/xrp/fields.c ../src/xrp/fields.h ../src/xrp/field_sort.c ../src/xrp/field_sort.h ../src/xrp/flags.c ../src/xrp/flags.h ../src/xrp/fmt.c ../src/xrp/fmt.h ../src/xrp/general.c ../src/xrp/general.h ../src/xrp/number_helpers.c ../src/xrp/number_helpers.h ../src/xrp/percentage.c ../src/xrp/percentage.h ../src/xrp/readers.c ../src/xrp/readers.h ../src/xrp/ascii_strings.c ../src/xrp/ascii_strings.h ../src/xrp/time.c ../src/xrp/time.h ../src/xrp/transaction_types.h ../src/xrp/xrp_helpers.c ../src/xrp/xrp_helpers.h ../src/xrp/xrp_parse.c ../src/xrp/xrp_parse.h ) ``` -------------------------------- ### on_address_confirmed Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/public-key-handler.md Callback function executed when the user confirms the address display. It copies the pending public key context to the active context, returns the full public key response to the host, clears the confirmation pending flag, and restores the idle menu. ```APIDOC ## on_address_confirmed ### Description Called when user confirms address display. Copies pending public key context to active context and returns the full public key response to the host. Clears confirmation pending flag and restores idle menu. ### Method Callback Function ### Parameters None ``` -------------------------------- ### Documentation Conventions Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/INDEX.md Highlights key conventions used in the documentation, such as relative file paths, full C code signatures, markdown table formatting, and hex error codes. ```markdown Source file paths are relative to repository root All C code includes full signatures with parameter and return types Parameter types use exact names from source (no paraphrasing) Tables use markdown format for clarity Code examples show actual usage patterns Error codes listed in hex format with descriptions ``` -------------------------------- ### Run Verbose Unit Test Source: https://github.com/ledgerhq/app-xrp/blob/develop/tests/README.md Runs a specific unit test with verbose output enabled. Use the ARGS variable to pass flags like '-V' for verbosity and '-R' to specify the test name. ```console make -C tests/build/ test ARGS='-V -R test_tx' ``` -------------------------------- ### Memory-Constrained Configuration for Ledger Nano S Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/configuration.md Compile-time defines for memory-constrained devices like the Ledger Nano S, setting limits on transaction fields, length, and size. ```c #define MAX_FIELD_COUNT 24 // Maximum parseable fields #define MAX_FIELD_LEN 128 // Max field display length #define MAX_RAW_TX 800 // Max transaction size #define DISPLAY_SEGMENTED_ADDR true // Segment long addresses ``` -------------------------------- ### Document Format Structure Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/INDEX.md Describes the standard structure for documentation files within the project, including sections for title, overview, main content, and related references. ```markdown # Title ## Section 1: Overview (if applicable) ## Section 2: Main Content - Function signatures with full types - Parameter tables (name | type | description) - Return type and description - Error codes and conditions - Examples and usage - Source file references ## Section 3: Related Types/Functions ## Cross-references to related docs ``` -------------------------------- ### Python Function to Unpack Configuration Response Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/app-configuration.md This function unpacks the raw bytes received from the device into a human-readable version string. It asserts the expected length and format of the response data. ```python def unpack_configuration_response(reply: bytes) -> str: """Unpack reply for 'get_configuration' APDU: TEST (1) MAJOR (1) MINOR (1) PATCH (1) """ assert len(reply) == 4 test, major, minor, patch = unpack("BBBB", reply) assert test == 0x00 version = f"{major}.{minor}.{patch}" return version ``` -------------------------------- ### C Function Signature: on_address_rejected Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/public-key-handler.md Callback function invoked when the user rejects the address display. It returns an error to the host and resets device state. ```c void on_address_rejected(void) ``` -------------------------------- ### ledger_app.toml Application Configuration Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/configuration.md TOML configuration for the XRP Ledger app, specifying build directory, SDK, and target devices. ```toml [app] build_directory = "./" sdk = "C" devices = ["nanox", "nanos+", "stax", "flex", "apex_p"] ``` -------------------------------- ### Makefile Target Device Configuration Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/configuration.md Specifies the target device models for building the XRP Ledger application. These are used to select device-specific configurations. ```makefile # Target device names TARGET_NANOS # Ledger Nano S TARGET_NANOS+ # Ledger Nano S Plus TARGET_NANOX # Ledger Nano X TARGET_STAX # Ledger Stax TARGET_FLEX # Ledger Flex TARGET_APEX_P # Ledger Apex (Placeholder) ``` -------------------------------- ### APDU Handler Entry Point Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/apdu-handler.md The main entry point for processing all APDU commands. It dispatches commands to specific handlers based on the instruction code. ```c void handle_apdu(volatile unsigned int *flags, volatile unsigned int *tx) ``` -------------------------------- ### Type Definitions Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/DOCUMENTATION_SUMMARY.txt Documentation for the type definitions and constants used within the XRP Ledger Wallet App. ```APIDOC ## Type Definitions ### Transaction Related Types - **field_t**: Transaction field structure. - **field_type_t**: Field type enumeration (14 types). - **field_value_t**: Formatted field output buffer. - **field_name_t**: Field name buffer. ### Context Types - **publicKeyContext_t**: Public key context. - **transactionContext_t**: Transaction context. - **parseContext_t**: Parsing context. ### XRP Specific Types - **xrp_pubkey_t**: Compressed public key. - **xrp_address_t**: XRP address string. - **xrp_account_t**: Account ID (20 bytes). - **xrp_currency_t**: Currency code (20 bytes). - **xrp_issue_t**: Currency + Issuer pair. (and 20+ more type definitions) ``` -------------------------------- ### on_address_rejected Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/public-key-handler.md Callback function executed when the user rejects the address display. It returns an error code (0x6985) to the host, clears the confirmation pending flag, and restores the idle menu. ```APIDOC ## on_address_rejected ### Description Called when user rejects address display. Returns error code 0x6985 (security status not satisfied) to the host and clears confirmation pending flag. Restores idle menu. ### Method Callback Function ### Parameters None ``` -------------------------------- ### Check if buffer is all zeros Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/amount-formatting.md Utility function to detect zero-filled buffers. Used for currency and amount validation. ```c bool is_all_zeros(const uint8_t *data, uint8_t length) ``` -------------------------------- ### Python Test Verification of App Version Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/app-configuration.md A Python function to verify the application version returned by the device against the version defines in the Makefile. It reads the Makefile and compares the versions. ```python def verify_version(root_path: Path, version: str) -> None: """Verify the app version, based on defines in Makefile""" print(f"version: {version}") makefile = f"{root_path.parent.resolve()}/Makefile" with open(makefile, "r", encoding="utf-8") as f_p: lines = f_p.readlines() version_re = re.compile(r"^APPVERSION_(?P\w)=(?P\d)", re.I) vers_dict = {} for line in lines: info = version_re.match(line) if info: dinfo = info.groupdict() vers_dict[dinfo["part"]] = dinfo["val"] try: vers_str = f"{vers_dict['M']}.{vers_dict['N']}.{vers_dict['P']}" except KeyError: pass assert version == vers_str ``` -------------------------------- ### XRP Utility Functions Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/INDEX.md Provides a collection of utility functions for XRP-specific operations, including key compression, address derivation, and amount formatting. ```APIDOC ## XRP Utility Functions ### Description Helper functions for common XRP operations. ### Functions - `xrp_compress_public_key()`: Compresses a public key. - `get_address()`: Derives the XRP address. - `xrp_public_key_hash160()`: Computes the account ID. - `xrp_print_amount()`: Formats an amount. - `parse_bip32_path()`: Parses a BIP32 derivation path. - `get_public_key()`: Derives a public key. ``` -------------------------------- ### handle_get_public_key Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/public-key-handler.md Processes the GET_PUBLIC_KEY APDU command to derive a public key and associated address from a BIP32 derivation path. It supports user confirmation and optional chain code retrieval. ```APIDOC ## handle_get_public_key ### Description Processes the GET_PUBLIC_KEY APDU command. Derives a public key and associated address from the BIP32 derivation path. If P1_CONFIRM is set, prompts user to confirm on the device before returning. Returns compressed public key (33 bytes), address (variable length), and optionally the chain code. ### Method APDU Command ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### APDU Parameters - **p1** (`uint8_t`) - Required - Confirmation flag (P1_CONFIRM or P1_NON_CONFIRM). `0x00` (P1_NON_CONFIRM): Return public key without user confirmation. `0x01` (P1_CONFIRM): Require user confirmation on device. - **p2** (`uint8_t`) - Required - Curve selection and chain code flag. Bits 0-5: Chain code flag (0x00 = no chain code, 0x01 = include chain code). Bits 6-7: Curve selection (0x40 = P2_SECP256K1, 0x80 = P2_ED25519). - **data_buffer** (`uint8_t *`) - Required - Input buffer containing BIP32 path. - **data_length** (`uint16_t`) - Required - Length of data_buffer. - **flags** (`volatile unsigned int *`) - Required - Device state flags. - **tx** (`volatile unsigned int *`) - Required - Response buffer size. ### Response Format ``` [pubkey_length (1 byte)] [pubkey (33 bytes for compressed secp256k1)] [address_length (1 byte)] [address (variable, typically 34 bytes)] [chain_code (32 bytes, optional if P2_CHAINCODE set)] ``` ### Error Codes - `0x6A80`: Invalid path length (less than 1) - `0x6B00`: Invalid P1 parameter - `0x6985`: User confirmation still pending ``` -------------------------------- ### Runtime Storage Structure for Blind Signing Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/configuration.md Defines the structure for non-volatile memory storage, including the blind signing setting. Blind signing allows signing large transactions without full field display. ```c typedef struct internal_storage_t { uint8_t allow_blind_sign; // 0 = disabled, 1 = enabled uint8_t initialized; // 0 = not initialized, 1 = initialized } internal_storage_t; ``` -------------------------------- ### parse_bip32_path Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/public-key-handler.md Parses a BIP32 derivation path from APDU format. It validates constraints, including a maximum of 10 path elements, with each element being 4 bytes in big-endian format. ```APIDOC ## parse_bip32_path ### Description Parses a BIP32 derivation path from APDU format (big-endian uint32 elements) and validates constraints. ### Function Signature ```c bool parse_bip32_path(uint8_t *path, size_t path_length, size_t path_bytes, uint32_t *path_parsed, size_t path_parsed_length) ``` ### Parameters #### Input Parameters - **path** (`uint8_t *`) - Required - Encoded path data from APDU - **path_length** (`size_t`) - Required - Number of path elements - **path_bytes** (`size_t`) - Required - Byte length of path data #### Output Parameters - **path_parsed** (`uint32_t *`) - Required - Output array for parsed elements - **path_parsed_length** (`size_t`) - Required - Maximum elements in output array ### Constraints - Maximum 10 path elements (MAX_BIP32_PATH) - Each element is 4 bytes in big-endian format ### Example Path `m/44'/144'/0'/0/0` = `[0x8000002C, 0x80000090, 0x80000000, 0x00000000, 0x00000000]` ### Returns - `bool` - True if parsing succeeded, false on error ``` -------------------------------- ### handle_apdu Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/apdu-handler.md Main entry point for all APDU command processing. This function dispatches incoming APDU commands to their respective processors based on the instruction code (INS). It also manages transaction context to protect against instruction-change attacks. ```APIDOC ## handle_apdu ### Description Main entry point for all APDU command processing. Processes incoming APDU commands from the host and routes them to the appropriate handler based on the instruction code (INS) field. Implements transaction context management to protect against instruction-change attacks. ### Method `void` ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response void #### Response Example N/A ### Supported Instructions - `INS_GET_PUBLIC_KEY` (0x02): Retrieve public key and address - `INS_SIGN` (0x04): Sign a transaction - `INS_GET_APP_CONFIGURATION` (0x06): Get application version and configuration ### Error Codes - `0x6E00`: Invalid CLA (command class) - `0x6D00`: Unknown instruction - `0x6000` range: Transaction errors (context reset) ``` -------------------------------- ### C Function Signature: on_address_confirmed Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/public-key-handler.md Callback function invoked when the user confirms the address display. It finalizes the public key response and resets device state. ```c void on_address_confirmed(void) ``` -------------------------------- ### Compute HASH160 of Compressed Public Key Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/public-key-handler.md Computes SHA256 followed by RIPEMD160 on a compressed public key to generate a 20-byte account ID. Use this for deriving XRP account identifiers. ```c cx_err_t xrp_public_key_hash160(xrp_pubkey_t *pubkey, uint8_t *out) ``` -------------------------------- ### APDU Endpoints Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/DOCUMENTATION_SUMMARY.txt Documentation for all APDU instructions supported by the XRP application, including their request and response formats. ```APIDOC ## APDU Endpoints This section details the APDU instructions supported by the XRP application. ### GET_PUBLIC_KEY #### Description Retrieves the public key for a given XRP address. ### SIGN #### Description Signs a transaction using the device's private key. ### GET_APP_CONFIG #### Description Retrieves the application configuration, including version information. ``` -------------------------------- ### GET_PUBLIC_KEY Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/README.md Derives the public key and XRP address for a given derivation path. ```APIDOC ## GET_PUBLIC_KEY ### Description Derives the public key and XRP address for a given derivation path. ### Method APDU Command ### Endpoint N/A (APDU Instruction) ### Parameters #### APDU Instruction Details - **CLA**: `0xE0` - **INS**: `0x02` - **P1**: Path type (e.g., BIP32 path) - **P2**: Reserved #### Request Body (APDU Data field contains derivation path information) ### Request Example (APDU command structure with derivation path data) ### Response #### Success Response - **PublicKey**: Derived public key - **Address**: XRP Ledger address #### Response Example (APDU response structure with public key and address data) ``` -------------------------------- ### Parse BIP32 Path from APDU Buffer Source: https://github.com/ledgerhq/app-xrp/blob/develop/_autodocs/api-reference/public-key-handler.md Parses a BIP32 derivation path from APDU format, validating constraints on path elements and byte length. Use this to extract derivation paths from incoming commands. ```c bool parse_bip32_path(uint8_t *path, size_t path_length, size_t path_bytes, uint32_t *path_parsed, size_t path_parsed_length) ``` ```text Example Path: m/44'/144'/0'/0/0 = [0x8000002C, 0x80000090, 0x80000000, 0x00000000, 0x00000000] ```