πŸ” CURRENT WALLET SYSTEM - COMPLETE ANALYSIS

Date: October 6, 2025
Purpose: Document what’s already implemented before starting Task 0.1


πŸ“Š EXECUTIVE SUMMARY

βœ… GOOD NEWS: Much More Implemented Than Expected!

The wallet system has THREE parallel implementations:

  1. βœ… TON Wallet Generator v4R2 - FULLY WORKING (using tonutils-go)
  2. ⚠️ Placeholder Signers - Returns “not implemented” (in ton_tron_placeholders.go)
  3. πŸ”§ Trust Wallet Core Integration - Framework ready (via build tags)

Key Finding: We DON’T need to build TON from scratch! We need to: - Integrate existing TON generator into the Signer interface - Add TRON signer implementation - Optionally enable Trust Wallet Core for multi-chain support


πŸ—οΈ SYSTEM ARCHITECTURE (Current State)

Wallet Service Architecture
═══════════════════════════════════════════════════════════════

                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚   Wallet Service (gRPC/HTTP)         β”‚
                    β”‚   Port: 9092                          β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                               β”‚
                β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                β”‚              β”‚              β”‚
                β–Ό              β–Ό              β–Ό
        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
        β”‚  Wallet   β”‚  β”‚ Wallet Rootβ”‚  β”‚   Signer     β”‚
        β”‚Repository β”‚  β”‚ Repository β”‚  β”‚   Factory    β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜
                                              β”‚
                              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                              β”‚               β”‚                β”‚
                              β–Ό               β–Ό                β–Ό
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚ TON Wallet   β”‚  β”‚Placeholder β”‚  β”‚ Trust Wallet β”‚
                    β”‚ Gen v4R2     β”‚  β”‚  Signers   β”‚  β”‚ Core (TWC)   β”‚
                    β”‚              β”‚  β”‚            β”‚  β”‚              β”‚
                    β”‚ βœ… WORKING   β”‚  β”‚ ⚠️ BROKEN  β”‚  β”‚ πŸ”§ OPTIONAL  β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

βœ… WHAT’S ALREADY IMPLEMENTED

1. TON Wallet Generator v4R2 (COMPLETE & WORKING)

File: services/wallet/internal/wallet/domain/service/ton_wallet_generator_v4r2.go

Status: βœ… FULLY FUNCTIONAL

Features:

βœ… BIP39 24-word mnemonic generation (via tonutils-go)
βœ… ed25519 keypair generation
βœ… v4R2 wallet contract address generation
βœ… Bounceable/non-bounceable address forms
βœ… Address validation
βœ… Workchain 0 (mainnet) support
βœ… Mnemonic encryption (AES-256-GCM + PBKDF2)
βœ… Address derivation from existing mnemonic
βœ… Integration with wallet service

Key Methods: - GenerateWallet(telegramID, label, isDefault) β†’ Creates wallet + root - DeriveAddressFromMnemonic(mnemonic) β†’ Derives address - ValidateTONAddress(address) β†’ Validates TON address - GetAddressForms(address) β†’ Returns bounceable/non-bounceable - EncryptData(data) / DecryptData(encrypted) β†’ Secure storage

Current Usage:

// In wallet.service.go line 827+
func (w walletService) deriveAddress(ctx context.Context, telegramId int64, 
                                       network string, derivationPath string) {
    if network == "TON" {
        // βœ… Uses TON Wallet Generator v4R2
        mnemonicStr, _ := w.TonWalletGen.DecryptData(encryptedMnemonic)
        address, _ := w.TonWalletGen.DeriveAddressFromMnemonic(mnemonicStr)
        // ... generates proper TON addresses
    }
}

Dependencies:

github.com/xssnick/tonutils-go v1.14.1  βœ… Already in go.mod
golang.org/x/crypto v0.39.0              βœ… Already in go.mod

Test Status: - βœ… Unit tests exist (ton_wallet_generator_test.go) - βœ… Generates valid EQ…/UQ… addresses - βœ… Encryption/decryption working


2. Signer Interface & Factory (ARCHITECTURE READY)

Files: - services/wallet/internal/wallet/service/signer/interfaces.go - services/wallet/internal/wallet/service/signer/factory.go

Status: βœ… WELL-DESIGNED ARCHITECTURE

Interface Definition:

type Signer interface {
    Address(pub PubKey, chain Chain) (string, error)
    SignTx(chain Chain, priv PrivKey, payload []byte) ([]byte, error)
}

type Deriver interface {
    FromMnemonic(m string, path string, curve Curve) (PrivKey, PubKey, error)
}

Factory Pattern:

func NewSigner(chain Chain) Signer {
    enableTWC := os.Getenv("ENABLE_TWC_PLUGIN") == "true"
    if enableTWC {
        return newTWCSafe()  // Trust Wallet Core (optional)
    }
    switch chain {
    case Chain("TON"):
        return &tonSigner{}   // ⚠️ Currently returns "not implemented"
    case Chain("TRON"):
        return &tronSigner{}  // ⚠️ Currently returns "not implemented"
    }
}

Design Principles: - βœ… Clean interface segregation - βœ… Factory pattern for chain selection - βœ… Build tag support for optional TWC - βœ… Environment variable toggle


3. Trust Wallet Core Integration (FRAMEWORK READY)

Files: - services/wallet/internal/wallet/service/signer/twc/twc_signer_enabled.go - services/wallet/internal/wallet/service/signer/twc/twc_signer_disabled.go - services/wallet/internal/wallet/service/signer/twc_enabled_factory.go - services/wallet/internal/wallet/service/signer/twc_disabled_factory.go

Status: πŸ”§ BUILD TAG INFRASTRUCTURE COMPLETE

Build Tags System:

// twc_enabled_factory.go
//go:build twc
func twcFactory() Signer { return twcimpl.Enabled{} }

// twc_disabled_factory.go
//go:build !twc
func twcFactory() Signer { return nil }

CGO Setup (in twc_signer_enabled.go):

/*
#cgo CFLAGS: -I${SRCDIR}/wallet-core/include
#cgo LDFLAGS: -L${SRCDIR}/wallet-core/build -lTrustWalletCore ...
#include <TrustWalletCore/TWHDWallet.h>
*/
import "C"

Status: - βœ… Build tag infrastructure complete - βœ… CGO configuration ready - ⚠️ Implementation stub (returns “not implemented”) - ⚠️ Trust Wallet Core library not built yet

Usage:

# Build without TWC (default)
go build ./cmd/server

# Build with TWC (optional)
go build -tags twc ./cmd/server

# Enable at runtime
export ENABLE_TWC_PLUGIN=true

4. Additional Signer Implementation (PARTIAL)

File: services/wallet/internal/wallet/service/signer/signer.go

Status: ⚠️ PARTIAL IMPLEMENTATION

What Exists:

βœ… TONSigner struct with ed25519 support
βœ… NewTONSigner(privateKeyBytes) β†’ Creates signer from key
βœ… NewTONSignerFromSeed(seed) β†’ Creates signer from seed  
βœ… GenerateKeyPair() β†’ Generates new keypair
βœ… Sign(message) β†’ Signs with ed25519
βœ… Verify(message, signature) β†’ Verifies signature
βœ… SignTransaction(tx) β†’ Signs TON transaction
⚠️ GenerateTONAddress() β†’ SIMPLIFIED (not proper v4R2)

Issue with signer.go:

// Line 108 - SIMPLIFIED ADDRESS GENERATION
func GenerateTONAddress(publicKey []byte, bounceable bool) (string, error) {
    hash := sha256.Sum256(publicKey)  // ⚠️ TOO SIMPLE
    if bounceable {
        hash[0] |= 0x40
    }
    encoded := base64.URLEncoding.EncodeToString(hash[:])
    return "EQ" + encoded[:len(encoded)-2], nil
}

Problem: This does NOT generate proper v4R2 wallet addresses!
Solution: Use the TON Wallet Generator v4R2 instead (already working).


5. HD Wallet Support (BASIC)

File: packages/crypto/crypto.go

Status: ⚠️ PLACEHOLDER IMPLEMENTATION

What Exists:

⚠️ HDWallet struct
⚠️ NewHDWallet(mnemonic, passphrase)
⚠️ DerivePath(path) β†’ BIP44 derivation
⚠️ BIP44 coin types defined (TON: 396, TRON: 195, ETH: 60)
⚠️ GenerateDerivationPath(network, account, change, index)

Issues:

// Line 292 - PLACEHOLDER HMAC
func hmacSHA512(key, data []byte) []byte {
    // Placeholder: ⚠️ WRONG
    hash := sha512.Sum512(append(key, data...))  
    return hash[:]
}

// Line 306 - PLACEHOLDER KEY DERIVATION
func privateToPublic(privateKey []byte) ([]byte, error) {
    // Placeholder: ⚠️ WRONG
    hash := sha256.Sum256(privateKey)
    return hash[:], nil
}

Recommendation: Don’t use packages/crypto/ HD wallet. Use proper libraries: - TON: tonutils-go (already working in TON Wallet Gen v4R2) - TRON: go-ethereum for secp256k1 + gotron-sdk


6. Placeholder Signers (THE PROBLEM)

File: services/wallet/internal/wallet/service/signer/ton_tron_placeholders.go

Status: ❌ BROKEN - RETURNS “NOT IMPLEMENTED”

type tonSigner struct{}

func (t *tonSigner) Address(pub PubKey, chain Chain) (string, error) {
    return "", errors.New("ton signer not implemented")  // ❌
}

func (t *tonSigner) SignTx(chain Chain, priv PrivKey, payload []byte) ([]byte, error) {
    return nil, errors.New("ton signer not implemented")  // ❌
}

type tronSigner struct{}

func (t *tronSigner) Address(pub PubKey, chain Chain) (string, error) {
    return "", errors.New("tron signer not implemented")  // ❌
}

func (t *tronSigner) SignTx(chain Chain, priv PrivKey, payload []byte) ([]byte, error) {
    return nil, errors.New("tron signer not implemented")  // ❌
}

This is Task 0.1 and 0.2!


🎯 CURRENT WALLET FLOW (Working)

Deposit Address Generation (TON) βœ…

User requests TON wallet
        ↓
WalletService.EnsureDefaultWallet()
        ↓
TONWalletGeneratorV4R2.GenerateWallet()
        ↓
    1. Generate 24-word mnemonic (tonutils-go)
    2. Derive ed25519 keypair
    3. Generate v4R2 address (proper TON address)
    4. Encrypt mnemonic (AES-256-GCM)
    5. Store in database:
       - WalletRoot (encrypted mnemonic)
       - Wallet (address, public key, network)
        ↓
Return deposit address (EQ... format) βœ…

Withdrawal Flow ⚠️ INCOMPLETE

User requests withdrawal
        ↓
Need to sign transaction
        ↓
factory.NewSigner("TON")
        ↓
Returns &tonSigner{} from placeholders
        ↓
Calls SignTx()
        ↓
ERROR: "ton signer not implemented" ❌

Problem: The Signer interface is used for withdrawals, but it returns errors!


πŸ”₯ THE DISCONNECT

Why Two Implementations?

  1. TON Wallet Generator v4R2 (working):

    • Purpose: Deposit wallet generation
    • Used by: WalletService.EnsureDefaultWallet()
    • Status: βœ… Fully functional
    • Creates: Proper TON v4R2 addresses
  2. Signer Interface (broken placeholders):

    • Purpose: Transaction signing (withdrawals)
    • Used by: Withdrawal flows, transaction processing
    • Status: ❌ Returns “not implemented”
    • Should: Sign transactions with private keys

The Gap:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  DEPOSITS: βœ… Working                    β”‚
β”‚  Uses: TON Wallet Gen v4R2              β”‚
β”‚  Generates proper addresses              β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  WITHDRAWALS: ❌ Broken                  β”‚
β”‚  Uses: Signer interface                  β”‚
β”‚  Returns: "not implemented"              β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“‹ TASK 0.1 - WHAT WE ACTUALLY NEED TO DO

DON’T:

  • ❌ Reimplement TON wallet generation (already works!)
  • ❌ Rewrite mnemonic generation (tonutils-go works!)
  • ❌ Rewrite address derivation (v4R2 generator works!)

DO:

  • βœ… Bridge the gap between TON Wallet Gen and Signer interface
  • βœ… Implement tonSigner.Address() using TON Wallet Gen v4R2 logic
  • βœ… Implement tonSigner.SignTx() using tonutils-go signing
  • βœ… Make Signer interface use the same libraries as TON Wallet Gen

Revised Implementation Plan:

// ton_tron_placeholders.go (replace)

import (
    "crypto/ed25519"
    "github.com/xssnick/tonutils-go/address"
    "github.com/xssnick/tonutils-go/ton/wallet"
)

type tonSigner struct{}

func (t *tonSigner) Address(pub PubKey, chain Chain) (string, error) {
    // βœ… Use same logic as TON Wallet Gen v4R2
    publicKey := ed25519.PublicKey(pub)
    rawAddr := address.NewAddress(0, 0, publicKey) 
    
    // Return bounceable form (user-facing)
    return rawAddr.Bounce(true).String(), nil
}

func (t *tonSigner) SignTx(chain Chain, priv PrivKey, payload []byte) ([]byte, error) {
    // βœ… Use tonutils-go for proper TON transaction signing
    privateKey := ed25519.PrivateKey(priv)
    
    // Sign using ed25519
    signature := ed25519.Sign(privateKey, payload)
    return signature, nil
}

Key Insight: We’re not starting from scratch! We’re integrating existing working code.


Step 1: Understand What’s Working

  • βœ… Read ton_wallet_generator_v4r2.go (lines 33-104)
  • βœ… See how tonutils-go is used
  • βœ… Understand address generation logic

Step 2: Copy the Working Logic

  • βœ… Take address generation from TON Wallet Gen v4R2
  • βœ… Use same library calls
  • βœ… Put into tonSigner.Address()

Step 3: Add Transaction Signing

  • βœ… Use ed25519.Sign() (standard library)
  • βœ… Or use tonutils-go transaction building
  • βœ… Put into tonSigner.SignTx()

Step 4: Test Integration

  • βœ… Generate address with TON Wallet Gen v4R2
  • βœ… Sign transaction with tonSigner
  • βœ… Verify both use same keypair format

πŸ“Š DEPENDENCIES STATUS

βœ… github.com/xssnick/tonutils-go v1.14.1    Already in go.mod
βœ… golang.org/x/crypto v0.39.0                Already in go.mod
❌ github.com/fbsobreira/gotron-sdk           Need to add (Task 0.2)
❌ github.com/ethereum/go-ethereum            Need to add (Task 0.2)

🎯 SUCCESS CRITERIA (Revised)

Task 0.1 Complete When:

  • βœ… tonSigner.Address() generates same addresses as TON Wallet Gen v4R2
  • βœ… tonSigner.SignTx() signs transactions properly
  • βœ… Integration tests pass
  • βœ… Can withdraw TON (end-to-end)

Don’t Reinvent:

  • ❌ Don’t rewrite mnemonic generation
  • ❌ Don’t rewrite v4R2 address logic
  • ❌ Don’t create new TON libraries

Do Integrate:

  • βœ… Use existing tonutils-go functions
  • βœ… Match TON Wallet Gen v4R2 behavior
  • βœ… Keep same address format

πŸ“ NOTES FOR IMPLEMENTATION

Key Files to Reference:

  1. ton_wallet_generator_v4r2.go (lines 33-104) - Working address generation
  2. wallet.service.go (lines 827-873) - How it’s currently used
  3. interfaces.go - Signer interface definition

Libraries Already Available:

  • github.com/xssnick/tonutils-go/address βœ…
  • github.com/xssnick/tonutils-go/ton/wallet βœ…
  • crypto/ed25519 βœ…

Don’t Touch (Working):

  • TON Wallet Generator v4R2 implementation
  • Mnemonic encryption/decryption
  • Database repositories

Do Modify:

  • ton_tron_placeholders.go - Replace placeholders
  • Add tests for signing
  • Integrate with withdrawal flow

πŸŽ“ LESSON LEARNED

Before starting ANY task: 1. βœ… Explore what already exists 2. βœ… Find working implementations 3. βœ… Reuse and integrate, don’t rewrite 4. βœ… Understand the disconnect

In this case: - We have working TON wallet generation - We have broken transaction signing - We just need to bridge them!


Next Step: Start Task 0.1 with this understanding.
Time Estimate: 2-3 hours (down from 4-6) because we’re integrating, not building from scratch.

© 2025 GitiNext - Enterprise Crypto Infrastructure | GitHub | Website