Skip to content

RC1: Add full-stack wallet API with Poseidon hash, hardware wallet, HSM support, and comprehensive documentation#30

Merged
Steake merged 7 commits intorc1from
copilot/sub-pr-23
Dec 6, 2025
Merged

RC1: Add full-stack wallet API with Poseidon hash, hardware wallet, HSM support, and comprehensive documentation#30
Steake merged 7 commits intorc1from
copilot/sub-pr-23

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Dec 5, 2025

  • Fix compilation errors in bitcell-zkp (duplicate imports)
  • Fix unused import warnings in bitcell-zkvm
  • Implement full Poseidon hash for production Merkle verification
  • Enable wallet GUI transaction sending with hardware wallet support
  • Add HSM/secure key management integration for admin wallet
  • Performance benchmarking and optimization
  • Address code review feedback
  • Codebase Audit & Documentation
  • Release Requirements Specification
  • Code Review Fixes (NEW)
    • Added HardwareWallet error type for hardware wallet errors (was using misleading UnsupportedChain)
    • Refactored hardware wallet connect() to remove #[allow(unreachable_code)]
    • Added max iteration limit (1M) to Poseidon round constant generation to prevent infinite loops
    • Improved .expect() messages in MDS matrix generation with detailed explanations
    • Added amount overflow validation in wallet GUI (max ~184B CELL)
    • Improved error message for invalid amount format
    • Implemented secure credential zeroing in HsmCredentials::drop()
    • Added bounded audit log (max 10,000 entries) with automatic rotation

💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Copilot AI mentioned this pull request Dec 5, 2025
Merged
Copilot AI and others added 3 commits December 5, 2025 17:38
Co-authored-by: Steake <530040+Steake@users.noreply.github.com>
…d benchmarks

Co-authored-by: Steake <530040+Steake@users.noreply.github.com>
Co-authored-by: Steake <530040+Steake@users.noreply.github.com>
@Steake
Copy link
Copy Markdown
Owner

Steake commented Dec 5, 2025

@copilot try again

Copy link
Copy Markdown
Contributor Author

Copilot AI commented Dec 5, 2025

@copilot try again

Build and tests are passing:

  • Build: ✅ Finished successfully
  • Tests: ✅ 102 tests passed (87 wallet + 15 ZKP)

All requested RC1 features are implemented and working:

  1. Full Poseidon hash for Merkle verification
  2. Hardware wallet support abstraction
  3. HSM/secure key management integration
  4. Performance benchmarks

Copilot AI changed the title [WIP] Add full-stack wallet API to BitCell admin console RC1: Add full-stack wallet API with Poseidon hash, hardware wallet, and HSM support Dec 5, 2025
@Steake
Copy link
Copy Markdown
Owner

Steake commented Dec 5, 2025

@copilot audit the existing CodeBase, especially reviewing the current documentation and create an overview of RC1 and the readiness of RC want to be released, then create an RC & RC3 roadmap.

Finally put together an operational matrix which shows the specific features which are implemented and there particular readiness as well as any notes. Make sure that your detailed feedback is recorded and documented. Both in the reply, as well as in my downfall is committed to the repository.

Co-authored-by: Steake <530040+Steake@users.noreply.github.com>
Copy link
Copy Markdown
Contributor Author

Copilot AI commented Dec 5, 2025

@copilot audit the existing CodeBase, especially reviewing the current documentation and create an overview of RC1 and the readiness of RC want to be released, then create an RC & RC3 roadmap.

Fin...

Completed codebase audit and documentation in commit b13d325. Created two comprehensive documents:

1. docs/RC_OVERVIEW_ROADMAP.md - RC1 readiness assessment with RC2/RC3 roadmaps:

  • RC1 Status: 🟡 Ready for Testnet (85% core features complete)
  • RC2 Target: Q1 2026 - "Production Hardening" (real ZK proofs, libp2p, RocksDB)
  • RC3 Target: Q2 2026 - "Mainnet Preparation" (security audit, recursive SNARKs, governance)

2. docs/OPERATIONAL_MATRIX.md - Detailed feature matrix by crate:

  • 200+ features documented across 12 crates
  • 71% complete, 22.5% partial, 6.5% not started
  • Test coverage: 200+ tests passing
  • Critical items identified for each release

Key Findings:

Category Status
Core Crypto ✅ 95%
CA Engine ✅ 100%
ZK Proofs 🟡 70% (mock)
Networking 🟡 60%
Wallet ✅ 85%
HSM 🟡 70%

RC2 Critical Items:

  1. Real Groth16 circuit constraints
  2. Full libp2p integration
  3. RocksDB persistence
  4. ECVRF/CLSAG upgrades

Copilot AI changed the title RC1: Add full-stack wallet API with Poseidon hash, hardware wallet, and HSM support RC1: Add full-stack wallet API with Poseidon hash, hardware wallet, HSM support, and comprehensive documentation Dec 5, 2025
@Steake Steake marked this pull request as ready for review December 5, 2025 19:42
Copilot AI review requested due to automatic review settings December 5, 2025 19:42
@Steake
Copy link
Copy Markdown
Owner

Steake commented Dec 5, 2025

@copilot Additional to this code review, please put together a list of all missing functionality and requirements for RC1. RC2 & RC3 to be considered complete. Ellis should be fine. Details contained detailed information on each and every feature required.

Co-authored-by: Steake <530040+Steake@users.noreply.github.com>
Copy link
Copy Markdown
Contributor Author

Copilot AI commented Dec 5, 2025

@copilot Additional to this code review, please put together a list of all missing functionality and requirements for RC1. RC2 & RC3 to be considered complete. Ellis should be fine. Details contained ...

Created comprehensive Release Requirements Specification in commit b3ecad4.

New Document: docs/RELEASE_REQUIREMENTS.md

RC1 Requirements (12 groups - 85% complete)

Requirement Status Missing Items
RC1-001 Core Crypto Ring sigs/VRF need upgrade
RC1-002 CA Engine None
RC1-003 ZK Architecture 🟡 70% Real Groth16 constraints
RC1-004 Consensus 🟡 85% Production VRF
RC1-005 State 🟡 80% RocksDB persistence
RC1-006 Networking 🟡 60% Full libp2p
RC1-007 RPC/API ✅ 90% WebSocket subscriptions
RC1-008 Wallet ✅ 85% HW wallet integration
RC1-009 Admin 🟡 80% HSM providers, auth
RC1-010 Economics None
RC1-011 EBSL None
RC1-012 ZKVM ✅ 90% ZK proof integration

RC2 Requirements (11 groups - ~21 weeks total)

  • RC2-001: Real Groth16 Circuits (7 weeks)
  • RC2-002: Production ECVRF (2 weeks)
  • RC2-003: CLSAG Ring Signatures (2 weeks)
  • RC2-004: Full libp2p Integration (3 weeks)
  • RC2-005: RocksDB Persistence (2 weeks)
  • RC2-006: Hardware Wallet Integration (4 weeks)
  • RC2-007: HSM Providers (3 weeks)
  • RC2-008: WebSocket Subscriptions (2 weeks)
  • RC2-009: Admin Authentication (2 weeks)
  • RC2-010: Testnet Faucet (1 week)
  • RC2-011: Mobile SDK (3 weeks)

RC3 Requirements (10 groups - ~36 weeks total)

  • RC3-001: Security Audit (6-8 weeks external)
  • RC3-002: Recursive SNARK Aggregation (6 weeks)
  • RC3-003: GPU CA Acceleration (4 weeks)
  • RC3-004: Block Explorer (4 weeks)
  • RC3-005: Governance System (4 weeks)
  • RC3-006: Smart Contract SDK (3 weeks)
  • RC3-007: Light Client (4 weeks)
  • RC3-008: Finality Gadget (3 weeks)
  • RC3-009: Documentation Portal (2 weeks)
  • RC3-010: Production Infrastructure (4 weeks)

Each requirement includes detailed acceptance criteria and technical specifications.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR implements RC1 (Release Candidate 1) readiness features for the BitCell blockchain platform, focusing on production-grade cryptography, hardware wallet integration, HSM support, and comprehensive release documentation. The changes prepare the codebase for testnet deployment by adding ZK-friendly hash functions, secure key management, and detailed feature tracking.

Key Changes:

  • Poseidon Hash: Full production implementation with BN254 curve support, 8+57 rounds, and ZKP-compatible Merkle verification gadgets for zero-knowledge circuits
  • Hardware Wallet Support: Abstraction layer for Ledger/Trezor integration with SigningMethod enum unifying software and hardware signing workflows
  • HSM Integration: Client library with provider abstraction (Vault, AWS CloudHSM, Azure Key Vault) including audit logging and secure key management
  • Release Documentation: Comprehensive RC1 assessment and RC2/RC3 roadmaps tracking 200+ features across 12 crates with status indicators

Reviewed changes

Copilot reviewed 21 out of 21 changed files in this pull request and generated 12 comments.

Show a summary per file
File Description
docs/RC_OVERVIEW_ROADMAP.md RC1 readiness assessment (85% complete) with Q1-Q2 2026 roadmaps for production hardening
docs/OPERATIONAL_MATRIX.md Feature matrix documenting 200+ features across all crates with completion status and test coverage
crates/bitcell-crypto/src/poseidon.rs Full Poseidon hash with Cauchy MDS matrix, deterministic round constants, and 128-bit security
crates/bitcell-crypto/benches/crypto_bench.rs Comprehensive benchmarks for Poseidon, SHA-256, signatures, and Merkle operations
crates/bitcell-zkp/src/poseidon_merkle.rs Production Merkle verification gadget using Poseidon for R1CS circuits (~500 constraints/level)
crates/bitcell-zkp/src/lib.rs Exports for new PoseidonMerkleGadget
crates/bitcell-zkp/src/battle_circuit.rs Removed duplicate imports
crates/bitcell-zkp/src/state_constraints.rs Removed unused ToBitsGadget import
crates/bitcell-zkp/src/battle_constraints.rs Fixed unused parameter warning
crates/bitcell-wallet/src/hardware.rs Hardware wallet abstraction with device trait, connection management, and mock implementation
crates/bitcell-wallet/src/wallet.rs Convenience sign() method for transaction signing by address lookup
crates/bitcell-wallet/src/lib.rs Exports for hardware wallet types
crates/bitcell-wallet-gui/src/main.rs Improved transaction UI with better error handling, nonce fetching, and fee calculation
crates/bitcell-admin/src/hsm.rs HSM client with backend trait, provider enum, audit logging, and mock implementation
crates/bitcell-admin/src/lib.rs HSM module export
crates/bitcell-zkvm/src/interpreter.rs Removed unused HashMap import
Cargo.toml files Added dependencies for sha2, async-trait, thiserror, and tokio sync features

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread crates/bitcell-wallet/src/hardware.rs Outdated
}
#[cfg(not(feature = "trezor"))]
{
return Err(Error::UnsupportedChain("Trezor support not compiled in".into()));
Copy link

Copilot AI Dec 5, 2025

Choose a reason for hiding this comment

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

The error message uses Error::UnsupportedChain for a hardware wallet connection error. This error variant name is misleading since it doesn't relate to an unsupported blockchain chain, but rather to unsupported hardware wallet functionality. Consider using a more appropriate error type like Error::HardwareWalletNotSupported or creating a specific error variant for hardware wallet errors.

Copilot uses AI. Check for mistakes.
for i in 0..t {
for j in 0..t {
let sum = x[i] + y[j];
mds_matrix[i][j] = sum.inverse().unwrap();
Copy link

Copilot AI Dec 5, 2025

Choose a reason for hiding this comment

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

[nitpick] The MDS matrix entry calculation uses .unwrap() which could panic if the inverse doesn't exist. While the Cauchy construction guarantees non-zero inverses mathematically, using a more descriptive error message would improve debuggability:

mds_matrix[i][j] = sum.inverse().expect("MDS matrix Cauchy construction guarantees non-zero inverse for distinct x_i, y_j");
Suggested change
mds_matrix[i][j] = sum.inverse().unwrap();
mds_matrix[i][j] = sum.inverse().expect("MDS matrix Cauchy construction guarantees non-zero inverse for distinct x_i, y_j");

Copilot uses AI. Check for mistakes.
let chain = parse_chain(&chain_str);

// Convert to smallest units (1 CELL = 100_000_000 units)
let amount_units = (amount * 100_000_000.0) as u64;
Copy link

Copilot AI Dec 5, 2025

Choose a reason for hiding this comment

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

The conversion from f64 to u64 using as u64 can cause silent truncation and loss of precision. If the user enters an amount with many decimal places or a very large amount, the multiplication by 100_000_000.0 could result in a value that exceeds u64::MAX or has unexpected precision loss. Consider adding validation to check for overflow and warn users about precision limits before the conversion.

Copilot uses AI. Check for mistakes.
Comment on lines +85 to +103
let mut counter = 0u64;
while constants.len() < total_constants {
let mut hasher = Sha256::new();
hasher.update(b"BitCell_Poseidon_RC");
hasher.update(&counter.to_le_bytes());
hasher.update(&(t as u64).to_le_bytes());
let hash = hasher.finalize();

// Convert hash to field element (mod p)
// Take 31 bytes to ensure < p with high probability
let mut bytes = [0u8; 32];
bytes[..31].copy_from_slice(&hash[..31]);
bytes[31] = 0; // Ensure < p by zeroing top byte

if let Some(fe) = Fr::from_random_bytes(&bytes) {
constants.push(fe);
}
counter += 1;
}
Copy link

Copilot AI Dec 5, 2025

Choose a reason for hiding this comment

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

The round constants generation uses a counter-based approach with SHA-256, rejecting values that don't parse as valid field elements. However, there's no upper bound on the counter, which means in the worst case (if from_random_bytes consistently returns None), this could theoretically loop indefinitely. While extremely unlikely in practice, consider adding a maximum iteration limit and returning an error if it's exceeded to prevent potential infinite loops.

Copilot uses AI. Check for mistakes.
Comment thread crates/bitcell-wallet/src/hardware.rs Outdated
Comment on lines +111 to +119
return Err(Error::UnsupportedChain("Generic hardware wallet not implemented".into()));
}
#[cfg(test)]
HardwareWalletType::Mock => {
Arc::new(MockHardwareWallet::new())
}
#[cfg(not(test))]
_ => {
return Err(Error::UnsupportedChain("Unknown hardware wallet type".into()));
Copy link

Copilot AI Dec 5, 2025

Choose a reason for hiding this comment

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

The error message uses Error::UnsupportedChain for a hardware wallet connection error. This error variant name is misleading since it doesn't relate to an unsupported blockchain chain, but rather to unsupported hardware wallet functionality. Consider using a more appropriate error type like Error::HardwareWalletNotSupported or creating a specific error variant for hardware wallet errors.

Copilot uses AI. Check for mistakes.
Comment thread crates/bitcell-wallet/src/hardware.rs Outdated
}
#[cfg(not(feature = "ledger"))]
{
return Err(Error::UnsupportedChain("Ledger support not compiled in".into()));
Copy link

Copilot AI Dec 5, 2025

Choose a reason for hiding this comment

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

The error message uses Error::UnsupportedChain for a hardware wallet connection error. This error variant name is misleading since it doesn't relate to an unsupported blockchain chain, but rather to unsupported hardware wallet functionality. Consider using a more appropriate error type like Error::HardwareWalletNotSupported or creating a specific error variant for hardware wallet errors.

Copilot uses AI. Check for mistakes.
Comment thread crates/bitcell-wallet-gui/src/main.rs Outdated
let amount: f64 = match amount_str.parse() {
Ok(a) if a > 0.0 => a,
_ => {
wallet_state.set_status_message("Invalid amount: must be a positive number".into());
Copy link

Copilot AI Dec 5, 2025

Choose a reason for hiding this comment

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

The amount_str parameter in the callback signature has been renamed (was previously amount), but the error message still says "Invalid amount" without providing context about the expected format. Consider improving the error message to be more descriptive, e.g., "Invalid amount format: expected a positive number".

Suggested change
wallet_state.set_status_message("Invalid amount: must be a positive number".into());
wallet_state.set_status_message("Invalid amount format: expected a positive number (e.g., 1.23)".into());

Copilot uses AI. Check for mistakes.
Comment thread crates/bitcell-crypto/src/poseidon.rs Outdated
for j in 0..t {
// M[i][j] = 1 / (x[i] + y[j])
let sum = x[i] + y[j];
matrix[i][j] = sum.inverse().expect("x[i] + y[j] should be non-zero");
Copy link

Copilot AI Dec 5, 2025

Choose a reason for hiding this comment

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

[nitpick] The round constant generation uses only 31 bytes from SHA-256 output to ensure the value is less than the field modulus. However, the code doesn't verify that the MDS matrix entries are actually valid (non-zero inverses exist). While the Cauchy construction guarantees this mathematically when x_i + y_j ≠ 0 for distinct x_i and y_j, adding an explicit assertion would make the security properties more obvious and catch any future logic errors:

matrix[i][j] = sum.inverse().expect("MDS matrix Cauchy construction guarantees non-zero inverse");

The current .expect() message could be more informative about why this invariant holds.

Suggested change
matrix[i][j] = sum.inverse().expect("x[i] + y[j] should be non-zero");
matrix[i][j] = sum.inverse().expect("Cauchy MDS construction: x[i] and y[j] are distinct, so x[i] + y[j] != 0 and always invertible");

Copilot uses AI. Check for mistakes.
Comment thread crates/bitcell-admin/src/hsm.rs Outdated
Comment on lines +73 to +88
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HsmCredentials {
/// API token (for Vault)
#[serde(skip_serializing)]
pub token: Option<String>,
/// Access key (for AWS/Azure/GCP)
#[serde(skip_serializing)]
pub access_key: Option<String>,
/// Secret key (for AWS/Azure/GCP)
#[serde(skip_serializing)]
pub secret_key: Option<String>,
/// Client certificate path (for mTLS)
pub client_cert: Option<String>,
/// Client key path (for mTLS)
pub client_key: Option<String>,
}
Copy link

Copilot AI Dec 5, 2025

Choose a reason for hiding this comment

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

Security concern: The HsmCredentials struct contains sensitive data (tokens, access keys, secret keys) but doesn't implement Drop to zero out this data when the struct is dropped. This could leave sensitive credentials in memory after use. Consider implementing Drop to securely zero the credential fields, or use a secure memory type like secrecy::Secret from the secrecy crate to ensure credentials are automatically zeroed.

Copilot uses AI. Check for mistakes.
pub struct HsmClient {
config: HsmConfig,
backend: Arc<dyn HsmBackend>,
audit_log: Arc<RwLock<Vec<AuditEntry>>>,
Copy link

Copilot AI Dec 5, 2025

Choose a reason for hiding this comment

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

The audit log stores operation details including key names and errors in an unbounded Vec. In a long-running system, this could lead to excessive memory consumption. Consider implementing a maximum size with rotation (e.g., keeping only the last 10,000 entries) or persisting the audit log to disk/database for long-term storage while keeping only recent entries in memory.

Copilot uses AI. Check for mistakes.
@Steake
Copy link
Copy Markdown
Owner

Steake commented Dec 5, 2025

@copilot apply changes based on the comments in this thread

…alidation

Co-authored-by: Steake <530040+Steake@users.noreply.github.com>
Copy link
Copy Markdown
Contributor Author

Copilot AI commented Dec 5, 2025

@copilot apply changes based on the comments in this thread

Applied all code review changes in commit 1fb6aab:

Error Handling:

  • Added new Error::HardwareWallet variant for hardware wallet errors (was using misleading UnsupportedChain)
  • Refactored HardwareWallet::connect() to eliminate #[allow(unreachable_code)]
  • Improved error message for invalid amount: "Invalid amount format: expected a positive number (e.g., 1.23)"

Security:

  • Implemented Drop for HsmCredentials to securely zero sensitive data (tokens, keys) using write_volatile
  • Added bounded audit log with MAX_AUDIT_LOG_ENTRIES = 10,000 and automatic rotation of old entries

Validation:

  • Added max iteration limit (1M) to Poseidon round constant generation to prevent theoretical infinite loops
  • Added amount overflow validation in wallet GUI (max ~184 billion CELL to prevent u64 overflow)

Documentation:

  • Improved .expect() messages in MDS matrix generation with detailed cryptographic explanations:
    • "Cauchy MDS construction: x[i] and y[j] are distinct elements, so x[i] + y[j] != 0 and is always invertible"

@Steake Steake mentioned this pull request Dec 5, 2025
@Steake Steake merged commit f2c4f68 into rc1 Dec 6, 2025
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.

3 participants