Skip to content

fix(ffi): free transaction byte buffers correctly#749

Draft
thepastaclaw wants to merge 1 commit intodashpay:v0.42-devfrom
thepastaclaw:tracker-1220
Draft

fix(ffi): free transaction byte buffers correctly#749
thepastaclaw wants to merge 1 commit intodashpay:v0.42-devfrom
thepastaclaw:tracker-1220

Conversation

@thepastaclaw
Copy link
Copy Markdown
Contributor

@thepastaclaw thepastaclaw commented May 9, 2026

Fix transaction byte buffer freeing

Summary

  • Preserve the existing one-argument transaction_bytes_free C ABI.
  • Store the returned transaction byte length in a hidden prefix so the Rust free
    function can reconstruct and drop the original boxed slice layout safely.
  • Route both transaction byte producers through the same allocation helper.
  • Add unit coverage for null, empty, and non-empty buffers.

Validation

  • cargo test -p key-wallet-ffi transaction_bytes_free --lib
  • python3 contrib/verify_ffi.py
  • git diff --check
  • npx markdownlint-cli2 /tmp/pr-body.md
  • Code review gate passed with recommendation: ship.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 9, 2026

Review Change Stack

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c339bb8b-0ac9-4ede-8f4f-6dc19cd58730

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR refactors FFI transaction buffer memory management to use a hidden length prefix. Transaction serialization now allocates a buffer prefixed with a usize length field, returns a pointer past the prefix to callers, and deallocates by reading the stored prefix to reconstruct the full allocation. Documentation and tests validate the new contract.

Changes

FFI Transaction Buffer Memory Management

Layer / File(s) Summary
Buffer Layout & Allocation
key-wallet-ffi/src/transaction.rs
New TRANSACTION_BYTES_LEN_PREFIX_SIZE constant and transaction_bytes_into_ffi_buffer helper allocate a buffer with a hidden usize length prefix and return a pointer to the transaction bytes region.
Memory Deallocation
key-wallet-ffi/src/transaction.rs
transaction_bytes_free is updated to read the length prefix from memory before the caller-provided pointer, reconstruct the original boxed allocation, and safely deallocate.
Transaction Build Integration
key-wallet-ffi/src/transaction.rs
Both wallet_build_and_sign_transaction and wallet_build_and_sign_asset_lock_transaction are updated to use transaction_bytes_into_ffi_buffer for serialization and output, with Rust documentation clarifying the transaction_bytes_free freeing requirement.
FFI API Documentation
key-wallet-ffi/FFI_API.md
Documentation for transaction_bytes_free is refined to specify pointer validity constraints, and both build functions' documentation is expanded to explicitly state the freeing requirement via transaction_bytes_free(*tx_bytes_out).
Buffer Lifecycle Tests
key-wallet-ffi/src/transaction_tests.rs
New test module verifies null-pointer safety, successful deallocation of prefixed buffers, and correct length semantics for empty payloads.

🎯 3 (Moderate) | ⏱️ ~25 minutes

A rabbit hops through memory,
prefix in hand, pointer unbent,
freed without a double-take—
allocation dreams, fully spent. 🐰✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix(ffi): free transaction byte buffers correctly' directly summarizes the main change: fixing incorrect buffer freeing behavior for FFI transaction bytes.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@thepastaclaw
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 9, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@key-wallet-ffi/FFI_API.md`:
- Around line 1308-1311: The docs for the build-and-sign transaction function
refer to a parameter named `fee_rate` but the actual function signature uses
`fee_per_kb`; update all occurrences of `fee_rate` in the function description
and the Safety section to `fee_per_kb` (including the parameter list and
explanatory text) so the documentation matches the FFI signature, then
regenerate FFI_API.md to pick up the corrected source docs; reference the
documented function's parameter `fee_per_kb` and the Safety section entries for
`fee_rate` to locate and replace the mismatched names.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 32e6f687-4825-4656-87a3-c169bd9cad5c

📥 Commits

Reviewing files that changed from the base of the PR and between 34f574d and e9296b2.

📒 Files selected for processing (3)
  • key-wallet-ffi/FFI_API.md
  • key-wallet-ffi/src/transaction.rs
  • key-wallet-ffi/src/transaction_tests.rs

Comment thread key-wallet-ffi/FFI_API.md Outdated
Comment on lines +1308 to +1311
Build and sign a transaction using the wallet's managed info This is the recommended way to build transactions. It handles: - UTXO selection using coin selection algorithms - Fee calculation - Change address generation - Transaction signing # Safety - `manager` must be a valid pointer to an FFIWalletManager - `wallet` must be a valid pointer to an FFIWallet - `account_index` must be a valid BIP44 account index present in the wallet - `outputs` must be a valid pointer to an array of FFITxOutput with at least `outputs_count` elements - `fee_rate` must be a valid variant of FFIFeeRate - `fee_out` must be a valid, non-null pointer to a `u64`; on success it receives the calculated transaction fee in duffs - `tx_bytes_out` must be a valid pointer to store the transaction bytes pointer - `tx_len_out` must be a valid pointer to store the transaction length - `error` must be a valid pointer to an FFIError - On success, the returned transaction bytes must be freed by calling `transaction_bytes_free(*tx_bytes_out)`.

**Safety:**
- `manager` must be a valid pointer to an FFIWalletManager - `wallet` must be a valid pointer to an FFIWallet - `account_index` must be a valid BIP44 account index present in the wallet - `outputs` must be a valid pointer to an array of FFITxOutput with at least `outputs_count` elements - `fee_rate` must be a valid variant of FFIFeeRate - `fee_out` must be a valid, non-null pointer to a `u64`; on success it receives the calculated transaction fee in duffs - `tx_bytes_out` must be a valid pointer to store the transaction bytes pointer - `tx_len_out` must be a valid pointer to store the transaction length - `error` must be a valid pointer to an FFIError - The returned transaction bytes must be freed with `transaction_bytes_free`
- `manager` must be a valid pointer to an FFIWalletManager - `wallet` must be a valid pointer to an FFIWallet - `account_index` must be a valid BIP44 account index present in the wallet - `outputs` must be a valid pointer to an array of FFITxOutput with at least `outputs_count` elements - `fee_rate` must be a valid variant of FFIFeeRate - `fee_out` must be a valid, non-null pointer to a `u64`; on success it receives the calculated transaction fee in duffs - `tx_bytes_out` must be a valid pointer to store the transaction bytes pointer - `tx_len_out` must be a valid pointer to store the transaction length - `error` must be a valid pointer to an FFIError - On success, the returned transaction bytes must be freed by calling `transaction_bytes_free(*tx_bytes_out)`.
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot May 9, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix parameter-name mismatch in docs (fee_rate vs fee_per_kb).

Line 1308 still documents fee_rate, but the function signature uses fee_per_kb. This can confuse FFI callers.

📝 Proposed source-doc fix (then regenerate `FFI_API.md`)
--- a/key-wallet-ffi/src/transaction.rs
+++ b/key-wallet-ffi/src/transaction.rs
@@
-/// - `fee_rate` must be a valid variant of FFIFeeRate
+/// - `fee_per_kb` is the requested fee rate in duffs per kilobyte
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@key-wallet-ffi/FFI_API.md` around lines 1308 - 1311, The docs for the
build-and-sign transaction function refer to a parameter named `fee_rate` but
the actual function signature uses `fee_per_kb`; update all occurrences of
`fee_rate` in the function description and the Safety section to `fee_per_kb`
(including the parameter list and explanatory text) so the documentation matches
the FFI signature, then regenerate FFI_API.md to pick up the corrected source
docs; reference the documented function's parameter `fee_per_kb` and the Safety
section entries for `fee_rate` to locate and replace the mismatched names.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in a7d48fb: updated the source safety docs to use fee_per_kb and regenerated key-wallet-ffi/FFI_API.md.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@thepastaclaw, thanks for the update! The fee_ratefee_per_kb correction in the source docs and the regenerated FFI_API.md look good. The documentation now accurately matches the function signature.

🐇✨

(\(\
(•ᴗ•)
/づ♡

@codecov
Copy link
Copy Markdown

codecov Bot commented May 9, 2026

Codecov Report

❌ Patch coverage is 54.16667% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 71.91%. Comparing base (34f574d) to head (a7d48fb).
⚠️ Report is 1 commits behind head on v0.42-dev.

Files with missing lines Patch % Lines
key-wallet-ffi/src/transaction.rs 54.16% 11 Missing ⚠️
Additional details and impacted files
@@              Coverage Diff              @@
##           v0.42-dev     #749      +/-   ##
=============================================
+ Coverage      71.89%   71.91%   +0.02%     
=============================================
  Files            320      320              
  Lines          69473    69465       -8     
=============================================
+ Hits           49947    49957      +10     
+ Misses         19526    19508      -18     
Flag Coverage Δ
core 76.30% <ø> (ø)
ffi 46.57% <54.16%> (+0.07%) ⬆️
rpc 20.00% <ø> (ø)
spv 87.88% <ø> (+0.03%) ⬆️
wallet 71.22% <ø> (+0.03%) ⬆️
Files with missing lines Coverage Δ
key-wallet-ffi/src/transaction.rs 2.92% <54.16%> (+2.92%) ⬆️

... and 3 files with indirect coverage changes

Transaction-building FFI functions (`wallet_build_and_sign_transaction`,
`wallet_build_and_sign_asset_lock_transaction`) hand back the serialized
transaction as `Vec<u8>` -> `Box<[u8]>` -> `Box::into_raw(...) as *mut u8`.
The previous `transaction_bytes_free(*mut u8)` then reconstructed
`Box<u8>`, which is the wrong allocation layout for a boxed slice and is
undefined behavior.

Take the original length back from the caller and reconstruct the boxed
slice via `Box::from_raw(slice_from_raw_parts_mut(ptr, len))`. Null
remains a no-op. Update the safety docs on both builders and on
`transaction_bytes_free` itself, refresh `FFI_API.md`, and add focused
unit tests covering null free, freeing a `Box<[u8]>` with the matching
length, and the empty-slice case.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant