Skip to content

Normalize chains to use kos codec #136

Merged
gustavocbritto merged 23 commits into
developfrom
KRS-8266-kos-rs-normalize-chains-to-use-kos-codec-for-all-chains
Apr 16, 2025
Merged

Normalize chains to use kos codec #136
gustavocbritto merged 23 commits into
developfrom
KRS-8266-kos-rs-normalize-chains-to-use-kos-codec-for-all-chains

Conversation

@camboimdev
Copy link
Copy Markdown
Contributor

@camboimdev camboimdev commented Apr 14, 2025

Summary by CodeRabbit

  • New Features

    • Added support for encoding and broadcasting transactions on multiple blockchains: Bitcoin, Ethereum, Solana, Tron, KLV, ICP, and Substrate.
    • Introduced comprehensive transaction preparation workflows for signing and broadcasting on these chains.
    • Added utilities for serialization of byte vector collections to support ICP transaction handling.
  • Refactor

    • Simplified transaction signing logic by directly signing transaction hashes across supported chains.
    • Removed detailed transaction decoding and info extraction for several chains, focusing on core signing functionality.
    • Streamlined error handling in demo and wallet components for clearer user feedback.
    • Restructured modules and dependencies to improve codebase maintainability and build stability.
    • Removed protobuf module from public API and adjusted import paths accordingly.
  • Tests

    • Added extensive tests covering transaction signing for TRX, SOL, BTC, DASH, ETH, DOT, ICP, and KLV chains.
    • Removed obsolete tests related to deprecated transaction decoding and signing flows.
  • Chores

    • Updated build scripts and dependencies, removing deprecated or unused packages.
    • Adjusted import paths and module visibility to align with new architecture.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 14, 2025

Walkthrough

This pull request refactors submodule paths, updates build configurations, and significantly expands blockchain transaction handling. Changes include renaming a submodule entry, modifying dependency specifications and build scripts, and adding new modules and functions for encoding transactions for signing and broadcasting for various chains (BTC, KLV, SOL, TRX, ETH, SUBSTRATE, ICP). Additionally, error handling improvements and test enhancements have been applied in mobile and web components, while existing signing functions in core chain implementations have been streamlined or simplified.

Changes

File(s) Change Summary
.gitmodules Renamed submodule entry from packages/kos/src/protos/tron to packages/kos-codec/src/protos/tron.
packages/kos-codec/Cargo.toml; packages/kos/Cargo.toml kos-codec: Added build script (build = "build.rs") and dependencies (rlp, prost, tiny-json-rs, prost-types, parity-scale-codec) plus a build dependency prost-build.
kos: Removed build script, prost-types, bitcoin dependency and the entire [build-dependencies] section.
packages/kos-codec/src/chains/{btc,klv,sol,trx,eth,substrate,icp}/mod.rs; packages/kos-codec/src/chains/klv/models.rs; packages/kos-codec/src/chains/sol/models.rs; packages/kos-codec/src/chains/eth/models.rs; packages/kos-codec/src/chains/substrate/models.rs Added new modules and functions encode_for_sign and encode_for_broadcast for BTC, KLV, SOL, TRX, ETH, Substrate, and ICP transactions, including associated test modules and improved model type declarations. Introduced Substrate extrinsic payload struct and encoding methods in kos-codec.
packages/kos-codec/src/chains/mod.rs Added new module declarations for btc, eth, klv, sol, substrate, trx, and icp.
packages/kos-codec/src/lib.rs; packages/kos-codec/src/protos/mod.rs Updated library to include new chain types in encoding functions. Modified protos by updating base64 import source from crate::crypto/base64 to kos::crypto/base64 and removed unused imports. Added Debug trait derivation to KosCodedAccount.
packages/kos-mobile/src/lib.rs; packages/kos-web/demo/src/components/{cryptography-demo.ts,transaction-signer.ts,wallet-generator.ts} Added new tests for transaction signing across multiple chains and enhanced error handling using type checks in cryptography actions and wallet operations.
packages/kos/src/chains/{btc,klv,sol,trx,substrate,eth,icp}/mod.rs Simplified chain-specific signing methods: directly signing using transaction hashes (with a new BTC constant), removing unnecessary decoding/encoding logic, updating get_tx_info to return errors, and cleaning up test calls in substrate. Removed decode_transaction method in TRX.
packages/kos/src/lib.rs Added extern crate alloc; for memory allocation support and removed the public protos module, thereby reducing the public API surface.
packages/kos/src/chains/sol/models.rs Removed unused imports (alloc crate items) without changing functionality.
packages/kos/src/chains/substrate/models.rs Removed old Substrate models and decoding logic, replaced by new ExtrinsicPayload struct and encoding methods in kos-codec.
packages/kos/src/chains/util.rs Added utility functions to serialize and deserialize vectors of byte vectors with associated tests.
packages/kos/src/chains/mod.rs Removed all tiny_json_rs related imports, serialization traits, and error conversions, simplifying the module.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant L as Library (encode_for_signing)
    participant C as Chain Module (BTC/KLV/SOL/TRX/ETH/SUBSTRATE/ICP)
    
    U->>L: Request transaction signing (send Transaction)
    L->>C: Dispatch to chain-specific encode_for_sign()
    C->>C: Validate & process transaction data
    C->>L: Return signed Transaction
    L->>U: Return signed Transaction
Loading
sequenceDiagram
    participant U as User
    participant L as Library (encode_for_broadcast)
    participant C as Chain Module (BTC/KLV/SOL/TRX/ETH/SUBSTRATE/ICP)
    
    U->>L: Request transaction broadcast (send Transaction)
    L->>C: Dispatch to chain-specific encode_for_broadcast()
    C->>C: Validate & update transaction with signature
    C->>L: Return broadcast-ready Transaction
    L->>U: Return updated Transaction
Loading

Possibly related PRs

  • Fix/substrate sign tx #89: Adds and fixes Substrate transaction signing and introduces ExtrinsicPayload; this PR removes and refactors Substrate signing, making them strongly related.
  • fix: browser klv tx #93: Modifies KLV chain implementation with fixes and enhancements related to decoding and encoding, related to KLV encoding/signing changes here.
  • add kos-codec as a dependency #118: Initial addition of the kos-codec package and minimal chain modules, which this PR extends extensively.

Suggested labels

@domain/proto, @domain/sdk

Suggested reviewers

  • brunocampos-ssa
  • klever-patrick

Poem

I'm a rabbit in a code-filled field,
Hopping through changes with a playful yield.
Submodules renamed and chains refined,
Dependencies added and errors redefined.
With every bite of code I delight—
A happy rabbit coding day and night! 🐇✨

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • JIRA integration encountered authorization issues. Please disconnect and reconnect the integration in the CodeRabbit UI.

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between 671b7eb and 65ecf39.

📒 Files selected for processing (1)
  • packages/kos-mobile/src/lib.rs (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: format
🔇 Additional comments (2)
packages/kos-mobile/src/lib.rs (2)

317-318: Good update to extract signature from encoded broadcast data.

This change correctly uses the signature from the encoded-to-broadcast transaction rather than directly from the signed transaction, ensuring the signature is properly formatted for the specific blockchain protocol.


532-863: Excellent test coverage for multiple blockchain protocols.

The comprehensive test suite covers various blockchain types including KLV, TRX, SOL (standard, legacy, and v0), BTC, DASH, ETH, DOT, and ICP. Each test thoroughly validates the transaction signing process by verifying chain ID, sender address, raw transaction data, and signature outputs.

This extensive coverage significantly improves confidence in the cross-chain transaction signing implementation.


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown

@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

🧹 Nitpick comments (9)
packages/kos-web/demo/src/components/transaction-signer.ts (1)

345-355: Enhanced error handling in transaction signing.

The pattern of checking error types before accessing their properties is consistently applied across the codebase, improving overall robustness and user experience.

Consider extracting this common error handling pattern into a shared utility function to reduce code duplication across these three locations in this file, as well as in the other component files.

+ private handleError(error: unknown): void {
+   if (error instanceof Error) {
+     this.showError(error.message);
+     return;
+   }
+   if (typeof error === "string") {
+     this.showError(error);
+     return;
+   }
+   
+   this.showError("An unknown error occurred");
+ }

Then replace the duplicated blocks with calls to this method:

- if (error instanceof Error) {
-   this.showError(error.message);
-   return;
- }
- if (typeof error === "string") {
-   this.showError(error);
-   return;
- }
- 
- this.showError("An unknown error occurred");
+ this.handleError(error);
packages/kos/src/chains/btc/mod.rs (1)

177-213: Review the multi-signature chunking logic and alignment with transaction inputs.

  1. The code signs each 32-byte chunk in tx.tx_hash, collecting signatures in a single array. Ensure this aligns with the intended number of inputs and expected signatures.
  2. Consider whether you need to validate the total length of tx.tx_hash to confirm it is a multiple of 32.
  3. The final signature is concatenated, which may be fine for single-key signing or lightweight multi-sign scenarios, but confirm you're not inadvertently merging multiple signatures in ways that downstream code might misinterpret.

Overall, the new signing logic is streamlined and consistent with the approach used in other chain modules.

packages/kos-codec/src/chains/sol/mod.rs (1)

42-93: Test coverage is good; consider adding negative tests.
Current tests verify correct encoding paths. Adding a test with obviously invalid data (e.g., empty blockhash or missing signatures) would confirm that error handling paths work as intended.

packages/kos-codec/src/chains/klv/mod.rs (2)

9-30: Consider unifying or centralizing empty-array handling.
The repeated logic of replacing "[]" with [""] could be encapsulated in a helper function to improve clarity and facilitate reuse, especially as both encode_for_sign and encode_for_broadcast rely on the same handling pattern.


48-94: Add an additional test for empty JSON arrays.
Although the existing tests look solid, the code includes special handling for empty arrays ("[]"→[""]). Consider adding a direct test case with literal [] in the input to ensure this transformation works as expected.

packages/kos-codec/src/chains/trx/mod.rs (2)

21-31: Validate multi-sig handling.
Appending an additional signature to the transaction’s signature vector is fine if Tron supports multi-sig in this manner. Otherwise, ensure only one signature is set or that the code handles multiple signatures properly.


49-97: Test coverage is good; consider negative cases.
Your tests look thorough for valid flows. A follow-up might be negative or boundary tests (e.g., invalid raw data, missing signature).

packages/kos-codec/src/chains/btc/mod.rs (2)

195-209: Document the 64-byte signature assumption.
The helper processes 64-byte raw signature chunks, presumably R and S in compact form. A small comment clarifying that these are pure (R, S) pairs (not DER-encoded) could help maintainers.


210-280: Tests are comprehensive; expand negative/edge coverage.
Consider adding negative tests for mismatched input lengths or unsupported script types. This ensures resilience to malformed data.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 68d9e93 and 761bb95.

⛔ Files ignored due to path filters (8)
  • Cargo.lock is excluded by !**/*.lock
  • packages/kos-codec/src/protos/generated/klv/google.protobuf.rs is excluded by !**/generated/**
  • packages/kos-codec/src/protos/generated/klv/mod.rs is excluded by !**/generated/**
  • packages/kos-codec/src/protos/generated/klv/proto.rs is excluded by !**/generated/**
  • packages/kos-codec/src/protos/generated/mod.rs is excluded by !**/generated/**
  • packages/kos-codec/src/protos/generated/trx/google.protobuf.rs is excluded by !**/generated/**
  • packages/kos-codec/src/protos/generated/trx/mod.rs is excluded by !**/generated/**
  • packages/kos-codec/src/protos/generated/trx/protocol.rs is excluded by !**/generated/**
📒 Files selected for processing (22)
  • .gitmodules (1 hunks)
  • packages/kos-codec/Cargo.toml (2 hunks)
  • packages/kos-codec/src/chains/btc/mod.rs (1 hunks)
  • packages/kos-codec/src/chains/klv/mod.rs (1 hunks)
  • packages/kos-codec/src/chains/klv/models.rs (8 hunks)
  • packages/kos-codec/src/chains/mod.rs (1 hunks)
  • packages/kos-codec/src/chains/sol/mod.rs (1 hunks)
  • packages/kos-codec/src/chains/sol/models.rs (0 hunks)
  • packages/kos-codec/src/chains/trx/mod.rs (1 hunks)
  • packages/kos-codec/src/lib.rs (3 hunks)
  • packages/kos-codec/src/protos/mod.rs (1 hunks)
  • packages/kos-mobile/src/lib.rs (3 hunks)
  • packages/kos-web/demo/src/components/cryptography-demo.ts (1 hunks)
  • packages/kos-web/demo/src/components/transaction-signer.ts (3 hunks)
  • packages/kos-web/demo/src/components/wallet-generator.ts (1 hunks)
  • packages/kos/Cargo.toml (0 hunks)
  • packages/kos/src/chains/btc/mod.rs (4 hunks)
  • packages/kos/src/chains/klv/mod.rs (3 hunks)
  • packages/kos/src/chains/sol/mod.rs (2 hunks)
  • packages/kos/src/chains/substrate/mod.rs (0 hunks)
  • packages/kos/src/chains/trx/mod.rs (4 hunks)
  • packages/kos/src/lib.rs (1 hunks)
💤 Files with no reviewable changes (3)
  • packages/kos/src/chains/substrate/mod.rs
  • packages/kos-codec/src/chains/sol/models.rs
  • packages/kos/Cargo.toml
🧰 Additional context used
🧬 Code Graph Analysis (6)
packages/kos-codec/src/protos/mod.rs (1)
packages/kos/src/crypto/base64.rs (2)
  • simple_base64_decode (33-63)
  • simple_base64_encode (2-30)
packages/kos/src/chains/klv/mod.rs (12)
packages/kos/src/crypto/hash.rs (1)
  • keccak256_digest (34-41)
packages/kos/src/chains/sol/mod.rs (1)
  • get_tx_info (83-85)
packages/kos/src/chains/btc/mod.rs (1)
  • get_tx_info (249-251)
packages/kos/src/chains/trx/mod.rs (1)
  • get_tx_info (139-141)
packages/kos/src/chains/sui/mod.rs (1)
  • get_tx_info (112-114)
packages/kos/src/chains/ada/mod.rs (1)
  • get_tx_info (166-168)
packages/kos/src/chains/apt/mod.rs (1)
  • get_tx_info (103-105)
packages/kos/src/chains/atom/mod.rs (1)
  • get_tx_info (157-159)
packages/kos/src/chains/icp/mod.rs (1)
  • get_tx_info (149-151)
packages/kos/src/chains/bch/mod.rs (1)
  • get_tx_info (195-197)
packages/kos/src/chains/mod.rs (1)
  • get_tx_info (396-396)
packages/kos/src/chains/xrp/mod.rs (1)
  • get_tx_info (169-171)
packages/kos/src/chains/trx/mod.rs (11)
packages/kos/src/chains/klv/mod.rs (1)
  • get_tx_info (105-107)
packages/kos/src/chains/sol/mod.rs (1)
  • get_tx_info (83-85)
packages/kos/src/chains/btc/mod.rs (1)
  • get_tx_info (249-251)
packages/kos/src/chains/sui/mod.rs (1)
  • get_tx_info (112-114)
packages/kos/src/chains/ada/mod.rs (1)
  • get_tx_info (166-168)
packages/kos/src/chains/apt/mod.rs (1)
  • get_tx_info (103-105)
packages/kos/src/chains/atom/mod.rs (1)
  • get_tx_info (157-159)
packages/kos/src/chains/icp/mod.rs (1)
  • get_tx_info (149-151)
packages/kos/src/chains/bch/mod.rs (1)
  • get_tx_info (195-197)
packages/kos/src/chains/mod.rs (1)
  • get_tx_info (396-396)
packages/kos/src/chains/xrp/mod.rs (1)
  • get_tx_info (169-171)
packages/kos-codec/src/chains/sol/mod.rs (3)
packages/kos-codec/src/chains/trx/mod.rs (2)
  • encode_for_sign (6-19)
  • encode_for_broadcast (21-31)
packages/kos-codec/src/chains/sol/models.rs (4)
  • decode (45-165)
  • decode (221-241)
  • encode (167-217)
  • encode (243-259)
packages/kos-codec/src/lib.rs (1)
  • encode_for_broadcast (36-57)
packages/kos-mobile/src/lib.rs (2)
packages/kos-codec/src/chains/sol/models.rs (2)
  • decode (45-165)
  • decode (221-241)
packages/kos/src/chains/substrate/models.rs (2)
  • decode (61-105)
  • decode (111-141)
packages/kos-codec/src/lib.rs (1)
packages/kos-codec/src/chains/btc/mod.rs (2)
  • encode_for_sign (4-79)
  • encode_for_broadcast (81-193)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: format
🔇 Additional comments (51)
packages/kos-web/demo/src/components/wallet-generator.ts (1)

255-266: Improved error handling implementation.

The updated error handling logic properly checks different error types before accessing their properties. This approach is more robust than directly casting to Error type, as it gracefully handles various error representations.

packages/kos-web/demo/src/components/cryptography-demo.ts (1)

129-139: Robust error handling approach.

The error handling has been improved to properly check the type of the error before accessing its properties. This prevents potential runtime errors when dealing with different types of errors and ensures users receive appropriate error messages.

packages/kos-web/demo/src/components/transaction-signer.ts (2)

238-248: Consistent error handling pattern.

The updated error handling properly checks error types, preventing potential runtime errors from incorrect type assumptions and providing better user feedback.


279-289: Improved error handling for message signing.

The error handling pattern is well-implemented and consistent with other methods in the codebase, making error reporting more robust.

packages/kos-codec/src/chains/mod.rs (1)

5-8: Modules added for new chain types - Looks good!

The addition of these four new modules (btc, klv, sol, trx) expands the codec's functionality to handle more blockchain types. This aligns well with the PR objective of normalizing chains to use the kos codec.

.gitmodules (1)

1-2: Submodule path correctly updated to kos-codec

The submodule path has been properly updated from packages/kos/src/protos/tron to packages/kos-codec/src/protos/tron, which is consistent with the restructuring mentioned in the PR summary. This ensures the Tron protocol definitions are available in the kos-codec package.

packages/kos/src/lib.rs (1)

2-2: Added extern crate alloc - Good addition for no_std support

The addition of extern crate alloc; is appropriate since this module uses #![cfg_attr(feature = "ksafe", no_std)] and needs memory allocation functionality when the standard library isn't available.

packages/kos-codec/src/protos/mod.rs (1)

3-3:

Details

✅ Verification successful

Updated imports to use kos package - Ensure dependency is configured

The import has been correctly updated to use kos::crypto::base64 instead of the local implementation. This is consistent with the PR's goal of normalizing codec usage.

Run the following to verify that kos-codec has a dependency on kos in its Cargo.toml:


🏁 Script executed:

#!/bin/bash
# Check if kos-codec properly depends on kos
grep -A 10 "dependencies" packages/kos-codec/Cargo.toml | grep "kos"

Length of output: 93


Dependency Verified: Import and Cargo.toml Configuration Correct

The updated import in packages/kos-codec/src/protos/mod.rs now correctly uses kos::crypto::base64::{simple_base64_decode, simple_base64_encode} as intended. The dependency check in packages/kos-codec/Cargo.toml confirms that the kos package is properly configured with:

kos = { workspace = true }

No further issues are identified.

packages/kos-codec/Cargo.toml (3)

10-10: Enable a custom build script.

Defining a build script in build.rs is standard practice for tasks like generating code from .proto files. This looks good.


33-34: Add build-dependency on prost-build.

Including prost-build ensures proto compilation. This aligns well with the newly added prost dependencies.


27-30:

Details

❓ Verification inconclusive

Verify new dependencies and check for security advisories.

The newly added dependencies (rlp, prost, tiny-json-rs, prost-types) look correct for handling serialization, but please verify they’re free of known vulnerabilities.


🏁 Script executed:

#!/bin/bash
# Use cargo-audit if available to check for vulnerabilities in newly added crates
cargo install --version ^0.17 cargo-audit || true
cargo audit

Length of output: 258


Manual Verification Needed for Cargo Audit

The updated dependencies in packages/kos-codec/Cargo.toml (lines 27-30) appear correctly specified for serialization tasks. However, the initial cargo audit command did not run as expected due to the absence of Cargo in the current environment. Please run cargo audit on a system where Cargo is available to verify that the new dependencies (rlp, prost, tiny-json-rs, prost-types) are free from known vulnerabilities.

packages/kos/src/chains/klv/mod.rs (4)

1-1: Import TxInfo into scope.

Bringing TxInfo into scope suggests you may return or handle transaction metadata. No issues spotted.


4-4: Include keccak256_digest for hashing.

You’re now using the keccak256_digest function, which is consistent across other chains for generating transaction hashes.


105-106: get_tx_info not supported.

Returning Err(ChainError::NotSupported) is consistent with other chain modules that don't provide transaction info.


81-81:

Details

❓ Verification inconclusive

Signing transaction with tx.tx_hash.

Directly signing tx.tx_hash matches the pattern used for other chains. Ensure the transaction hash is computed correctly and is 32 bytes.


🏁 Script executed:

#!/bin/bash
# Verifies that tx_hash is always 32 bytes in KLV transactions
rg 'tx\.tx_hash' -A 4

Length of output: 2785


Ensure 32-byte Transaction Hash Integrity

The current implementation in packages/kos/src/chains/klv/mod.rs follows the same pattern as other chains by signing tx.tx_hash directly:

        let sig = self.sign_raw(private_key, tx.tx_hash.clone())?;

Please double-check that the transaction hash generation logic guarantees a 32-byte hash for KLV transactions. If there’s any possibility of the hash not being exactly 32 bytes, consider adding an explicit validation check to prevent unexpected errors.

packages/kos-codec/src/lib.rs (4)

2-2: Added mod protos;.

Defining the protos module is presumably for .proto-related files. Please ensure it’s referenced as needed in your build script.


4-4: Import additional chain modules for multi-chain support.

This import statement broadens coverage by including btc, klv, sol, and trx. Looks consistent with the new encode methods.


28-31: Extend encode_for_signing to handle BTC, KLV, TRX, and SOL.

Supporting these chains is a beneficial expansion. Consider adding tests to ensure each chain’s encode logic behaves correctly.


51-54: Extend encode_for_broadcast to handle BTC, KLV, TRX, and SOL.

Broadcast logic is now unified for more chains. No immediate concerns; make sure each chain's broadcast path is tested.

packages/kos/src/chains/trx/mod.rs (5)

2-2: Import TxInfo for TRX chain.

Including TxInfo indicates potential for detailed transaction data, though it's currently not supported for TRX.


7-7: Use alloc::format.

Explicitly importing format is standard in no_std contexts. No issues found.


139-140: get_tx_info not supported.

Returning Err(ChainError::NotSupported) matches the approach in other chains where transaction decoding is unavailable.


150-150: Use crate::chains::Chain in tests.

This import is straightforward and ensures test code can call chain trait methods.


104-106:

Details

❓ Verification inconclusive

Sign transaction using tx.tx_hash.

Copying tx.tx_hash into a 32-byte buffer is correct for TRX—just confirm tx.tx_hash is always 32 bytes.


🏁 Script executed:

#!/bin/bash
# Ensures tx_hash is consistently 32 bytes for TRX
rg 'tx\.tx_hash' -A 3

Length of output: 2435


Verify that tx.tx_hash is always 32 bytes for TRX signing

The current implementation in packages/kos/src/chains/trx/mod.rs:

payload.copy_from_slice(&tx.tx_hash[..]);
tx.signature = secp256k1::Secp256K1::sign(&payload, &pvk_bytes)?.to_vec();

correctly copies tx.tx_hash into a 32-byte buffer for signing. Please ensure that every code path setting tx.tx_hash guarantees it will always be exactly 32 bytes. If that invariant isn’t enforced elsewhere, consider adding an explicit length check or appropriate validations to prevent potential issues.

packages/kos/src/chains/sol/mod.rs (2)

6-6: No functional issues detected on this import line.


61-61: Consider validating tx_hash before signing.
The function unconditionally signs tx_hash without checking if it is empty or malformed. Ensuring that tx_hash is non-empty can prevent cryptographic misuse or accidental signing of an invalid payload.

Would you like to add a check similar to the BTC workflow, where an empty tx_hash yields an error?

packages/kos/src/chains/btc/mod.rs (3)

2-3: No issues with modified imports.


13-13: Constant definition looks correct.
Defining ID makes the codebase more flexible and self-documenting.


36-36: Use of ID is consistent with the newly introduced constant.
This approach improves maintainability by avoiding hard-coded values.

packages/kos-codec/src/chains/sol/mod.rs (3)

1-5: Module creation is clean and well-structured.
Export statements and module references appear valid.


6-24: Validation checks for Solana transactions look solid.

  1. Verifying num_required_signatures == 1 is appropriate for single-signature use cases.
  2. Checking the blockhash for all-zero or all-ones patterns prevents signing obviously invalid transactions.
  3. Assigning the encoded message to transaction.tx_hash makes sense in Solana’s context, but confirm this is the desired “hash” reference for subsequent signing steps.

26-40: Signature encoding for broadcast is correct.

  1. Asserted signature length of 64 matches Ed25519.
  2. Replacing any prior signatures with transaction.signature is straightforward.
  3. Storing the signature in transaction.tx_hash is consistent with other chain modules that track final states in tx_hash.
packages/kos-codec/src/chains/klv/mod.rs (2)

1-8: Overall structure looks good.
No evident issues in the module declaration and imports.


32-46: Validate the signature encoding structure.
You are wrapping the Base64-encoded signature in an array with a single element (Some(Vec::from([simple_base64_encode(&transaction.signature)]))). If this chain eventually supports multiple signatures, ensure this design doesn’t conflict with multi-sig requirements.

packages/kos-codec/src/chains/trx/mod.rs (3)

1-5: No issues with imports.
All dependencies appear correctly referenced for Tron transaction decoding and hashing.


6-19: Confirm final raw_data consistency.
After computing the tx_hash, the function returns without re-encoding the transaction. If the signed raw data must reflect any modifications, verify that preserving the old transaction.raw_data is correct for Tron’s signing flow.


33-47: Fallback decoding approach is clear.
Decoding first as a full Tron transaction, then as Raw is a sensible strategy for handling partial/fallback scenarios.

packages/kos-codec/src/chains/btc/mod.rs (2)

1-3: Imports are appropriate.
No concerns with the references to bitcoin, secp256k1, or Psbt.


81-193: Broadcast flow is clear.
The approach of finalizing PSBT inputs, drawing from existing signatures, and extracting the final transaction is consistent. Just ensure the chain’s design accommodates legacy vs. segwit script finalization as you have implemented.

packages/kos-mobile/src/lib.rs (7)

524-524: Function rename to be more specific about the chain

The function has been appropriately renamed from should_sign_raw_transaction to should_sign_raw_transaction_klv to specify which chain the test is for, improving clarity as part of the normalization process.


554-583: Good addition for TRX chain support

The new test function properly verifies transaction signing for the TRX chain, asserting all required fields: chain ID, sender address, raw transaction data, and signature.


585-609: Good addition for SOL chain support

The new test function properly verifies transaction signing for the SOL chain, asserting that the raw transaction data and signature match expected values.


611-635: Good addition for SOL legacy transaction support

This test expands coverage to include legacy transaction formats for the SOL chain, which is important for backward compatibility.


637-661: Good addition for SOL v0 transaction support

This test adds coverage for SOL version 0 transactions, ensuring the system supports different transaction formats on the Solana chain.


716-741: Good addition for BTC chain support

The new test function properly verifies transaction signing for the BTC chain using SegWit transaction format, asserting that the raw transaction data matches expected values.


743-767: Good addition for DASH chain support

The test function properly verifies transaction signing for the DASH chain, ensuring cross-chain functionality is properly tested.

packages/kos-codec/src/chains/klv/models.rs (5)

8-10: Improved imports with better organization

The refactoring of imports makes the code cleaner and more maintainable by:

  1. Directly importing the protos module
  2. Using a more specific path for the simple_base64_decode function

This helps support the broader effort to normalize chain-specific code.


16-16: Simplified type references

The type references have been simplified by removing unnecessary namespace prefixes (removing crate::chains::klv::models:: in favor of direct type names). This improves code readability and maintainability.

Also applies to: 36-36, 40-40, 80-80


84-84: Added appropriate compiler annotation

The #[allow(dead_code)] annotation was added to suppress compiler warnings for unused code in the ConversionError enum, improving the cleanliness of the build output.


91-91: Simplified TryFrom implementations

All TryFrom implementations have been refactored to use direct type references rather than fully qualified paths. This is consistent with the goal of normalizing chains and using the KOS codec, making the code more maintainable and easier to read.

Also applies to: 95-95, 129-129, 133-133, 172-172, 175-175, 196-196, 200-200, 212-212, 216-216, 230-230, 234-234


113-113:

Details

❓ Verification inconclusive

Verify the base64 function works correctly

The code uses simple_base64_decode from kos::crypto::base64 instead of the previous source. Make sure that this function handles the same edge cases and provides identical behavior to the previously used function.


🏁 Script executed:

#!/bin/bash
# Find where the simple_base64_decode function is used elsewhere to confirm consistent usage
rg -A 2 'simple_base64_decode' --type rust

Length of output: 15107


Subject: Verify Consistent Handling of Base64 Edge Cases

The new implementation using simple_base64_decode from kos::crypto::base64 is now used uniformly across modules (e.g., in wallet.rs, lib.rs, substrate/mod.rs, etc.). However, please verify that its behavior—especially for edge cases such as trailing padding and malformed input—matches that of the previous implementation. Specifically:

  • Check that inputs with trailing '=' characters are trimmed and decoded correctly.
  • Ensure error responses for invalid input remain consistent with legacy behavior.
  • Consider adding or reviewing unit tests covering these edge cases to confirm no regressions occur.

Comment thread packages/kos-codec/src/chains/btc/mod.rs
Copy link
Copy Markdown

@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: 0

🧹 Nitpick comments (5)
packages/kos-codec/src/chains/mod.rs (1)

5-9: Add or confirm test coverage for new modules
These lines introduce modules for BTC, ETH, KLV, SOL, and TRX. Confirm that each is covered by unit or integration tests to ensure reliability. If test coverage is missing, consider adding it.

packages/kos-codec/src/lib.rs (1)

2-2: Consider verifying usage of protos module throughout the codebase.
If this module contains generated protobuf definitions or wrappers, ensure it's integrated into the workflow (for instance, in build scripts or code referencing). Otherwise, it might be redundant.

packages/kos-codec/src/chains/eth/mod.rs (2)

1-2: New mod models; inclusion.
Ensure relevant data structures or conversions are defined in models and used here. If not needed, consider removing the empty module reference.


7-33: encode_for_sign method for Ethereum.

  1. Clears signature as expected before generating the RLP.
  2. Sets chain_id for legacy transactions.
  3. Hashes the raw RLP for signing.
    Overall, it’s correct.

Consider verifying whether different EVM transaction types beyond “Legacy” or “London” might require separate chain ID handling in the future.

packages/kos-mobile/src/lib.rs (1)

636-661: Version 0 Solana transaction test.
Again, thorough coverage for multiple transaction versions on Solana.

You may want to expand negative tests (e.g., malformed raw data) to confirm robust error handling.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between 761bb95 and 2dd4bae.

📒 Files selected for processing (6)
  • packages/kos-codec/src/chains/eth/mod.rs (1 hunks)
  • packages/kos-codec/src/chains/eth/models.rs (1 hunks)
  • packages/kos-codec/src/chains/mod.rs (1 hunks)
  • packages/kos-codec/src/lib.rs (3 hunks)
  • packages/kos-mobile/src/lib.rs (3 hunks)
  • packages/kos/src/chains/eth/mod.rs (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages/kos/src/chains/eth/mod.rs (13)
packages/kos/src/chains/klv/mod.rs (1)
  • get_tx_info (105-107)
packages/kos/src/chains/btc/mod.rs (1)
  • get_tx_info (249-251)
packages/kos/src/chains/sol/mod.rs (1)
  • get_tx_info (83-85)
packages/kos/src/chains/trx/mod.rs (1)
  • get_tx_info (139-141)
packages/kos/src/chains/substrate/mod.rs (1)
  • get_tx_info (203-216)
packages/kos/src/chains/sui/mod.rs (1)
  • get_tx_info (112-114)
packages/kos/src/chains/ada/mod.rs (1)
  • get_tx_info (166-168)
packages/kos/src/chains/apt/mod.rs (1)
  • get_tx_info (103-105)
packages/kos/src/chains/atom/mod.rs (1)
  • get_tx_info (157-159)
packages/kos/src/chains/icp/mod.rs (1)
  • get_tx_info (149-151)
packages/kos/src/chains/mod.rs (1)
  • get_tx_info (396-396)
packages/kos/src/chains/bch/mod.rs (1)
  • get_tx_info (195-197)
packages/kos/src/chains/xrp/mod.rs (1)
  • get_tx_info (169-171)
packages/kos-codec/src/lib.rs (1)
packages/kos-codec/src/chains/btc/mod.rs (2)
  • encode_for_sign (4-79)
  • encode_for_broadcast (81-193)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: format
🔇 Additional comments (17)
packages/kos-codec/src/chains/eth/models.rs (1)

1-1: Verify import path correctness
Switching from crate::crypto::bignum::U256 to kos::crypto::bignum::U256 helps unify references under kos. Please verify that the new path is correct and doesn’t introduce any unexpected version or scoping issues.

packages/kos/src/chains/eth/mod.rs (3)

2-2: Looks good
Importing TxInfo alongside Chain and other types is consistent with the shared interface. No issues noted.


122-127: Confirm transaction hash usage
Signing tx.tx_hash.clone() aligns with the simplified logic, but please verify that tx_hash is indeed the final pre-sign hash (e.g., EIP-155 or analogous approach). If chain IDs or other fields must be included, ensure they’re embedded in this hash.


176-177: Consistent placeholder
Returning ChainError::NotSupported for get_tx_info matches the pattern in other chain implementations. No issues.

packages/kos-codec/src/lib.rs (3)

4-4: All chain modules are imported correctly.
These imports centralize chain-specific logic for signing and broadcasting. No immediate issues here.


28-32: New chain types for signing appear consistent.
Each chain type references a corresponding encode_for_sign function. Ensure that required chain options are provided when needed (e.g., mandatory fields in ChainOptions) to avoid runtime errors.


52-56: Broadcast paths align well with the newly supported chains.
The approach of referencing each chain’s broadcast method is consistent. Double-check that any chain demanding the public_key parameter is indeed provided.

packages/kos-codec/src/chains/eth/mod.rs (3)

3-6: Import statements look valid.
They reference EthereumTransaction and standard utilities for EVM. Looks good for supporting new Ethereum logic.


35-45: encode_for_broadcast sets signature and re-encodes.
The flow of assigning signature and generating the final RLP is logical. It’s good that the function leaves tx_hash alone here, since it’s set in encode_for_sign.


47-120: Test suite thoroughly covers Legacy and London transactions.

  1. Checks the computed tx_hash in encode_for_sign.
  2. Verifies raw data and signature match expected output in encode_for_broadcast.
    The coverage is solid and consistent with changes.
packages/kos-mobile/src/lib.rs (7)

524-552: KLV signing test appears to validate end-to-end logic.

  1. Generates the wallet from mnemonic.
  2. Signs the raw transaction.
  3. Asserts the final raw and signature.
    This test is comprehensive and well-named.

553-583: TRX signing test checks Tron transaction flow.
The final raw bytes and signature are asserted. Looks solid.
Ensure chain_id = 1 corresponds to Tron in your environment. Some references suggest Tron might use different chain IDs.


584-609: SOL signing test.
Handles a raw transaction, then re-serializes with an updated signature. Everything lines up with typical Solana flow.


610-635: Legacy Solana transaction test.
Nicely ensures backward-compatibility or older transaction formats.


715-741: BTC signing test.
Uses chain’s BTC ID. Confirms the final raw data is properly generated after signing.


743-767: Dash signing test closely follows the BTC pattern.
The final raw includes ECDSA signatures, which are validated. Good approach.

Double-check that the partial segwit logic used in the BTC flow doesn’t inadvertently carry over to Dash.


769-791: ETH signing test with custom chain ID.
Verifies a London transaction. This test also sets chain_id = 1 in options while the base chain is 3. Everything looks flexible.

Copy link
Copy Markdown

@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

🧹 Nitpick comments (6)
packages/kos-codec/src/chains/substrate/mod.rs (1)

8-28: Robust payload sizing logic in encode_for_sign.

The fallback to hash the input when size exceeds 256 bytes adds flexibility for large extrinsics. Ensure any chain with special size constraints is accounted for in this logic.

Optionally define a constant for the 256-byte threshold to clarify its significance:

+ const MAX_DIRECT_SIGN_SIZE: usize = 256;

- if full_unsigned_payload_scale_bytes.len() > 256 {
+ if full_unsigned_payload_scale_bytes.len() > MAX_DIRECT_SIGN_SIZE {
packages/kos-codec/src/chains/substrate/models.rs (5)

10-11: Consider documenting why dead code is allowed.

The #[allow(dead_code)] annotation suggests some fields might not be used in all contexts. Consider adding documentation explaining which fields might be unused and in what scenarios.


25-55: Inconsistency between comment and implementation in to_bytes.

The comment on line 27 mentions "version" as part of the format, but the implementation doesn't appear to include a version byte in the encoded output. Consider either updating the comment or ensuring the version is properly encoded if required.

Additionally, cloning self.call and self.era is unnecessary as extend() can work with references:

-        encoded.extend(self.call.clone());
-        encoded.extend(&self.era.clone());
+        encoded.extend(&self.call);
+        encoded.extend(&self.era);

35-40: Consider extracting app_id and mode logic to a helper method.

This conditional logic is duplicated in the encode_with_signature method. Consider extracting it to a helper method to improve maintainability.


47-52: Clarify the conditional logic with better documentation.

The comment "Use the metadata_hash if it is not set for AVAIL transactions" is a bit confusing. Consider rephrasing to something like "Include metadata_hash only for non-AVAIL transactions (when app_id is not set)".


57-91: Ensure consistent vector extension methods in encode_with_signature.

The method uses a mix of extend(), extend_from_slice(), and push() methods. Consider using consistent methods for better code readability:

-        encoded.extend_from_slice(&self.era);
-        encoded.extend_from_slice(&Compact(self.nonce).encode());
-        encoded.extend_from_slice(&Compact(self.tip).encode());
+        encoded.extend(&self.era);
+        encoded.extend(Compact(self.nonce).encode());
+        encoded.extend(Compact(self.tip).encode());

Also, when encoding with app_id:

-            encoded.extend_from_slice(Compact(app_id).encode().as_slice());
+            encoded.extend(Compact(app_id).encode());
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between 2dd4bae and e8afd3a.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (8)
  • packages/kos-codec/Cargo.toml (2 hunks)
  • packages/kos-codec/src/chains/mod.rs (1 hunks)
  • packages/kos-codec/src/chains/substrate/mod.rs (1 hunks)
  • packages/kos-codec/src/chains/substrate/models.rs (1 hunks)
  • packages/kos-codec/src/lib.rs (3 hunks)
  • packages/kos-mobile/src/lib.rs (3 hunks)
  • packages/kos/src/chains/substrate/mod.rs (4 hunks)
  • packages/kos/src/chains/substrate/models.rs (0 hunks)
💤 Files with no reviewable changes (1)
  • packages/kos/src/chains/substrate/models.rs
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/kos-codec/src/lib.rs
  • packages/kos-mobile/src/lib.rs
  • packages/kos-codec/Cargo.toml
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/kos/src/chains/substrate/mod.rs (1)
packages/kos/src/crypto/hash.rs (1)
  • blake2b_64_digest (61-68)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: format
🔇 Additional comments (11)
packages/kos-codec/src/chains/mod.rs (1)

5-10: Modules addition looks consistent.

The newly introduced modules for various blockchains (btc, eth, klv, sol, substrate, trx) align with the PR objective to normalize multiple chain codecs. No immediate concerns about these declarations.

packages/kos/src/chains/substrate/mod.rs (4)

2-3: Imports look correct.

The updated import statements properly include TxInfo and blake2b_64_digest. They match the usage below where hashing is required for transaction signing.


8-8: Ensure that tx_hash is the intended data for signing.

Replacing the detailed extrinsic construction with a direct hash signing approach is fine as long as tx_hash is correctly prepared upstream (in the codec). Verify that tx_hash is the data users expect to sign.

Would you like me to generate a script to check whether tx_hash is consistently populated via encode_for_sign prior to calling sign_tx?


129-129: NotSupported error for get_tx_info.

Returning ChainError::NotSupported disables transaction decoding. It is consistent if all decoding is meant to be handled externally, but confirm that no code depends on get_tx_info returning meaningful data.


139-139: Test imports appear valid.

The inclusion of ChainOptions for test usage is correct, enabling custom chain option parsing via options_from_browser_json.

packages/kos-codec/src/chains/substrate/mod.rs (4)

1-7: Modules and imports are logically structured.

Including models and referencing ExtrinsicPayload, KosCodedAccount, and the required hashing function keeps the codec’s scope self-contained. Good modular organization.


30-43: encode_for_broadcast is concise and clear.

Encodes the signed extrinsic by combining public key, signature, and payload. Does not appear to have errors in data handling. The direct usage of .unwrap() for decoding public_key is acceptable if upstream guarantees valid hex.


45-98: unwrap_extrinsic gracefully handles varying Substrate options.

• Validates and converts array fields safely.
• Cleanly adds optional metadata fields based on chain_id.
• Approaches error conditions via meaningful ChainError::InvalidOptions and MissingOptions.
Keep the switch on account.chain_id updated if new chain variants require different logic in future.


100-481: Extensive test coverage.

• Covers multiple chains (Dot, Ksm, Avail, Reef, Karura, Acala).
• Verifies correct hash generation and final raw data encoding.
• Ensures we do not regress on transaction serialization.
No obvious issues found; the coverage is commendable.

packages/kos-codec/src/chains/substrate/models.rs (2)

1-7: Good use of constants for transaction format flags.

The constants are well-defined with clear names that indicate their purpose in the Substrate transaction encoding process.


84-88: Good implementation of compact-encoded length prefix.

The code correctly implements the Substrate transaction format by prefixing the encoded transaction with its compact-encoded length.

Comment thread packages/kos-codec/src/chains/substrate/models.rs
Copy link
Copy Markdown

@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: 2

🔭 Outside diff range comments (1)
packages/kos-mobile/src/lib.rs (1)

525-855: 🛠️ Refactor suggestion

Add error case tests for transaction signing.

All the transaction signing tests cover only the happy path. Consider adding tests for error scenarios such as:

  • Invalid private keys
  • Invalid raw transaction data
  • Missing required options for specific chains
  • Mismatched chain IDs between account and options

These tests would help ensure robust error handling in the transaction signing flow.

🧹 Nitpick comments (5)
packages/kos/src/chains/util.rs (1)

76-95: Good test coverage for new serialization utilities.

The tests validate both the happy path and binary roundtrip integrity. Consider adding tests for edge cases like empty vectors and single-byte vectors to ensure complete coverage.

 #[cfg(test)]
 mod tests {
     use super::*;
 
     #[test]
     fn test_hex_string_to_vec() {
         let hex_str = "0x1234567890abcdef";
         let result = hex_string_to_vec(hex_str).unwrap();
         assert_eq!(result, vec![0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]);
     }
 
     #[test]
     fn test_hex_strings_to_bytes() {
         let hex_strings = vec![hex::decode("db41e41de474e2cb6d997ae5aa5de9aa81512a19d1337881363a3c481431935992a118ba863b6d00612c638b5caf7bac65cb2cf31a7d30f9c5473fcb97bf620bc006bf0760963c13c1c1478adbc326b96338060f03487ebd1c3b261dbccd8daf").unwrap(), hex::decode("db41e41de8163a3c481431935992a118ba863b6d00612c638b5caf7bac65cb2c7ebd1c3b261dbccd8daf").unwrap()];
         let result = byte_vectors_to_bytes(&hex_strings);
 
         let decoded = bytes_to_byte_vectors(result).unwrap();
         assert_eq!(hex_strings, decoded);
     }
+
+    #[test]
+    fn test_edge_cases() {
+        // Test empty vector
+        let empty: Vec<Vec<u8>> = vec![];
+        let serialized = byte_vectors_to_bytes(&empty);
+        let deserialized = bytes_to_byte_vectors(serialized).unwrap();
+        assert_eq!(empty, deserialized);
+
+        // Test vector with empty byte arrays
+        let empty_arrays = vec![vec![], vec![]];
+        let serialized = byte_vectors_to_bytes(&empty_arrays);
+        let deserialized = bytes_to_byte_vectors(serialized).unwrap();
+        assert_eq!(empty_arrays, deserialized);
+
+        // Test single-byte arrays
+        let single_bytes = vec![vec![1], vec![2]];
+        let serialized = byte_vectors_to_bytes(&single_bytes);
+        let deserialized = bytes_to_byte_vectors(serialized).unwrap();
+        assert_eq!(single_bytes, deserialized);
+    }
 }
packages/kos/src/chains/icp/mod.rs (1)

84-96: Improved transaction signing using binary serialization.

The implementation has been simplified to directly process binary data without JSON serialization/deserialization. The code properly maintains security by zeroing out private key material after use.

Consider adding more context to the error handling to aid in debugging:

-        let icp_hashes = bytes_to_byte_vectors(tx.tx_hash.clone())?;
+        let icp_hashes = bytes_to_byte_vectors(tx.tx_hash.clone())
+            .map_err(|e| ChainError::InvalidData(format!("Failed to decode ICP transaction hash: {:?}", e)))?;
packages/kos-codec/src/chains/icp/mod.rs (2)

19-26: Optimize the hash processing loop.

The current implementation handles each hash individually. Consider using a more efficient approach by directly mapping the vector.

-    let icp_hashes = container.hashes;
-
-    let mut hashes = Vec::new();
-
-    for hash_hex in icp_hashes {
-        hashes.push(hex::decode(hash_hex).unwrap());
-    }
+    let hashes = container.hashes
+        .into_iter()
+        .map(|hash_hex| hex::decode(hash_hex).map_err(|_| ChainError::DecodeHash))
+        .collect::<Result<Vec<Vec<u8>>, ChainError>>()?;

32-41: Consider strengthening the signature encoding logic.

The current implementation directly maps signatures to hex strings without validation. Consider adding checks for signature validity or handling potential corner cases.

For example, you might want to check if signatures are empty or have expected lengths before encoding them. This would provide better error messages and prevent issues downstream.

packages/kos-mobile/src/lib.rs (1)

554-855: Consider refactoring test code to reduce duplication.

The test cases for different chains follow a very similar pattern. Consider extracting common testing logic into a helper function to reduce code duplication and make future maintenance easier.

You could create a parametrized test helper like:

fn test_sign_transaction(
    chain_id: u32,
    raw_tx: &str,
    options: Option<TransactionChainOptions>,
    expected_sender: &str,
    expected_signature_prefix: &str,  // Or use a validation function
) {
    let account = generate_wallet_from_mnemonic(
        "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".to_string(),
        chain_id,
        0,
        false,
    )
    .unwrap();

    let transaction = sign_transaction(account, raw_tx.to_string(), options).unwrap();

    assert_eq!(transaction.chain_id, chain_id, "The chain_id doesn't match");
    assert_eq!(
        transaction.sender, expected_sender,
        "The sender doesn't match"
    );
    assert!(
        transaction.signature.starts_with(expected_signature_prefix),
        "The signature doesn't match expected pattern"
    );
}

Then use it in individual tests with specific parameters.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between e8afd3a and f25d1b9.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (9)
  • packages/kos-codec/src/chains/icp/mod.rs (1 hunks)
  • packages/kos-codec/src/chains/klv/mod.rs (1 hunks)
  • packages/kos-codec/src/chains/mod.rs (1 hunks)
  • packages/kos-codec/src/lib.rs (3 hunks)
  • packages/kos-mobile/src/lib.rs (4 hunks)
  • packages/kos/Cargo.toml (0 hunks)
  • packages/kos/src/chains/icp/mod.rs (3 hunks)
  • packages/kos/src/chains/mod.rs (1 hunks)
  • packages/kos/src/chains/util.rs (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/kos/Cargo.toml
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/kos-codec/src/chains/klv/mod.rs
  • packages/kos-codec/src/lib.rs
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/kos-mobile/src/lib.rs (2)
packages/kos-codec/src/chains/eth/models.rs (1)
  • decode (26-41)
packages/kos-codec/src/chains/sol/models.rs (2)
  • decode (45-165)
  • decode (221-241)
🔇 Additional comments (16)
packages/kos-codec/src/chains/mod.rs (1)

5-11: Excellent module organization to support multiple blockchain types.

The addition of these new modules (btc, eth, icp, klv, sol, substrate, trx) follows a consistent pattern with existing declarations. This modular approach provides a clean separation of encoding logic for each blockchain, making the codebase more maintainable.

packages/kos/src/chains/mod.rs (1)

20-20: Changed import to remove tiny_json_rs dependency.

The import now directly includes FromUtf8Error from alloc::string instead of relying on tiny_json_rs. This aligns with the PR's objective to normalize chains to use the kos codec and remove JSON serialization from core chain implementations.

packages/kos/src/chains/util.rs (2)

25-39: Well-implemented binary serialization utility.

This utility function efficiently serializes a vector of byte vectors using a compact binary format with explicit length prefixes. The approach is more performant than JSON serialization and well-suited for blockchain transaction data.


40-74: Robust deserialization with proper error handling.

The implementation includes thorough bounds checking to prevent buffer overruns, with appropriate error handling for malformed inputs. This is crucial for securely processing potentially untrusted blockchain data.

packages/kos/src/chains/icp/mod.rs (2)

1-1: Updated imports to use new serialization utilities.

The imports now include the necessary utility functions for binary serialization, aligning with the PR's objective to normalize chain transaction encoding.


130-130: Improved error handling clarity.

Replaced todo!() placeholder with an explicit error type, which is more informative for API consumers. This aligns with other chain implementations that have similarly updated their get_tx_info methods.

packages/kos-mobile/src/lib.rs (10)

309-310: LGTM! Extracting signature from encoded transaction.

This change ensures consistent signature extraction across all chains, aligning with the kos-codec pattern.


554-584: LGTM! Comprehensive TRX transaction signing test.

The test properly validates the TRX transaction signing flow, ensuring compatibility with the new codec implementation.


585-610: LGTM! SOL transaction signing test.

The test properly validates the Solana transaction signing flow with standard transaction format.


611-636: LGTM! SOL legacy transaction signing test.

The test properly validates the Solana legacy transaction signing flow.


637-662: LGTM! SOL v0 transaction signing test.

The test properly validates the Solana v0 transaction signing flow.


716-742: LGTM! BTC transaction signing test.

The test properly validates the Bitcoin transaction signing flow, including correct handling of input scripts and amounts.


743-768: LGTM! DASH transaction signing test.

The test properly validates the DASH transaction signing flow, which uses similar pattern to BTC but with different inputs.


770-792: LGTM! ETH transaction signing test.

The test properly validates Ethereum transaction signing with appropriate chain ID options.


793-834: LGTM! Substrate/DOT transaction signing test.

The test properly validates Substrate transaction signing with appropriate options for this complex chain type.


835-855: LGTM! ICP transaction signing test.

The test properly validates ICP transaction signing, directly testing the new codec module added in this PR.

Comment thread packages/kos-codec/src/chains/icp/mod.rs
Comment thread packages/kos-codec/src/chains/icp/mod.rs
Copy link
Copy Markdown

@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: 0

🧹 Nitpick comments (1)
packages/kos-hardware/src/lib.rs (1)

339-380: Improved transaction data serialization with proper type handling

The refactoring of rs_tx_info_to_json enhances the code by:

  1. Using a structured TransactionDetails struct with derived serialization
  2. Creating a local TransactionType enum with proper mapping from the original TxType
  3. Implementing custom serialization for the enum to ensure consistent JSON output

This approach provides better type safety and makes the JSON serialization process more maintainable and explicit compared to direct encoding.

However, consider adding a comment explaining why this local serialization approach is used instead of implementing serialization directly on the original types, which would help future maintainers understand the design decision.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between dd3451e and d461bf0.

📒 Files selected for processing (1)
  • packages/kos-hardware/src/lib.rs (2 hunks)
🔇 Additional comments (1)
packages/kos-hardware/src/lib.rs (1)

3-3: Properly organized imports for JSON serialization

The added imports set up the foundation for the refactored JSON serialization strategy. Using explicit imports from tiny_json_rs makes dependencies clear and improves maintainability by showing exactly which components are needed.

Also applies to: 14-19

…S-8266-kos-rs-normalize-chains-to-use-kos-codec-for-all-chains
@gustavocbritto gustavocbritto merged commit 77a7447 into develop Apr 16, 2025
4 checks passed
@gustavocbritto gustavocbritto deleted the KRS-8266-kos-rs-normalize-chains-to-use-kos-codec-for-all-chains branch April 16, 2025 13:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants