Trust Wallet Core Integration

๐ŸŽฏ Overview

Trust Wallet Core (TWC) is the ultimate goal for production deployment, providing battle-tested multi-chain support for 50+ blockchains.

Status: ๐Ÿ”ง Framework Ready - Implementation Pending
Priority: After native signers tested (Phase 2+)


๐Ÿ—๏ธ Architecture

Dual-Path Strategy

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚              Signer Factory (factory.go)                     โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  NewSigner(chain) โ†’ checks ENABLE_TWC_PLUGIN env var        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
               โ”‚
      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
      โ”‚                  โ”‚
      โ–ผ                  โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ Native Path โ”‚   โ”‚   TWC Path   โ”‚
โ”‚  (Default)  โ”‚   โ”‚  (Optional)  โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค   โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ tonSigner   โ”‚   โ”‚  TWC Signer  โ”‚
โ”‚ tronSigner  โ”‚   โ”‚   (CGO)      โ”‚
โ”‚ ethSigner   โ”‚   โ”‚ Build: -tags โ”‚
โ”‚ Pure Go     โ”‚   โ”‚      twc     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Why Dual Path?

Aspect Native Go Trust Wallet Core
Speed Fast (no CGO) Slightly slower (CGO overhead)
Build Simple (go build) Complex (CMake, C++ deps)
Chains 3-4 (manual impl) 50+ (out of box)
Testing Easy (pure Go) Complex (C++ deps)
Production Good for TON/TRON Best for all chains
Maintenance We maintain Trust Wallet maintains

Strategy:

  1. Phase 0-1: Build native Go signers (TON, TRON) - validate approach
  2. Phase 2: Enable TWC for production - leverage battle-tested code
  3. Phase 3: Use TWC for new chains (ETH, BSC, Solana, etc.)

๐Ÿ”ง CGO Integration (Already Built!)

Build Tags System

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

//go:build twc

package signers

import twcimpl "github.com/gitinext/gitinext-golang/services/wallet/internal/wallet/service/signer/twc"

func twcFactory() Signer {
    return twcimpl.Enabled{}
}

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

//go:build !twc

package signers

func twcFactory() Signer {
    return nil
}

CGO Configuration

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

//go:build twc

package twc

/*
#cgo CFLAGS: -I${SRCDIR}/wallet-core/include
#cgo LDFLAGS: -L${SRCDIR}/wallet-core/build -L${SRCDIR}/wallet-core/build/trezor-crypto \
  -lTrustWalletCore -lprotobuf -lTrezorCrypto -lc++ -lm
#include <TrustWalletCore/TWHDWallet.h>
#include <TrustWalletCore/TWPrivateKey.h>
#include <TrustWalletCore/TWPublicKey.h>
*/
import "C"

Infrastructure Ready:

  • โœ… CGO flags configured
  • โœ… Header includes specified
  • โœ… Library linking paths defined
  • โœ… Build tags properly set

๐Ÿ—๏ธ Trust Wallet Core Build Process

Prerequisites

# Install CMake
sudo apt-get install cmake

# Install C++ compiler
sudo apt-get install build-essential

# Install dependencies
sudo apt-get install libboost-all-dev libprotobuf-dev protobuf-compiler

Build Trust Wallet Core

# Clone Trust Wallet Core (if not already in services/wallet/internal/wallet/service/signer/twc/)
cd services/wallet/internal/wallet/service/signer/twc
git clone https://github.com/trustwallet/wallet-core.git

# Build
cd wallet-core
cmake -H. -Bbuild -DCMAKE_BUILD_TYPE=Release
make -C build

Makefile Integration (Already Done!)

# Build wallet with TWC
build-wallet-twc:
	@echo "Building wallet binary with TWC support..."
	@mkdir -p $(BIN)
	@$(GO) build -tags "$(TAGS) twc" -ldflags "$(LDFLAGS)" \
		-o $(BIN)/wallet-twc ./$(WALLET_DIR)/cmd/server
	@echo "โœ… Wallet with TWC built"

# Docker build with TWC
docker-build-wallet-twc:
	@echo "Building wallet Docker image with TWC..."
	@docker build -t registry.nextgiti.cloud:5000/wallet:$(VERSION)-twc \
		--build-arg BUILD_TAGS="twc" -f $(WALLET_DIR)/Dockerfile .
	@echo "โœ… Wallet with TWC Docker image built"

Usage

# Build without TWC (default - pure Go)
make build-wallet

# Build with TWC (optional)
make build-wallet-twc

# Run with TWC enabled
export ENABLE_TWC_PLUGIN=true
./bin/wallet-twc

# Or docker
docker run -e ENABLE_TWC_PLUGIN=true registry.nextgiti.cloud:5000/wallet:latest-twc

๐Ÿ“ Implementation Roadmap

Phase 0-1: Native Signers (Testing Phase)

Goal: Validate architecture with pure Go implementations

Tasks:

  • โœ… Implement TON signer (tonutils-go)
  • โœ… Implement TRON signer (gotron-sdk)
  • โœ… Test end-to-end (deposits + withdrawals)
  • โœ… Validate addresses match standard wallets
  • โœ… Benchmark performance

Why First?

  • Simpler to test and debug
  • No C++ compilation complexity
  • Validates our signer interface design
  • Proves database integration works

Phase 2: Enable TWC (Production Ready)

Goal: Replace native signers with TWC for production

Tasks:

  • [ ] Complete TWC signer implementation
  • [ ] Implement TWC wrapper for all methods
  • [ ] Add memory zeroing after signing
  • [ ] Golden vector tests (TWC vs native)
  • [ ] Performance benchmarks
  • [ ] Production deployment

Implementation:

// services/wallet/internal/wallet/service/signer/twc/twc_signer_enabled.go

//go:build twc

package twc

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

import (
    "fmt"
    "unsafe"
)

type Enabled struct{}

// FromMnemonic derives key from mnemonic using TWC
func (e Enabled) FromMnemonic(mnemonic, path string, curve string) ([]byte, []byte, error) {
    // Convert Go string to C string
    cMnemonic := C.CString(mnemonic)
    defer C.free(unsafe.Pointer(cMnemonic))

    cPassword := C.CString("")
    defer C.free(unsafe.Pointer(cPassword))

    // Create HD Wallet
    wallet := C.TWHDWalletCreateWithMnemonic(cMnemonic, cPassword)
    if wallet == nil {
        return nil, nil, fmt.Errorf("failed to create HD wallet")
    }
    defer C.TWHDWalletDelete(wallet)

    // Derive key at path
    cPath := C.CString(path)
    defer C.free(unsafe.Pointer(cPath))

    key := C.TWHDWalletGetKeyForCoin(wallet, getCoinType(curve))
    if key == nil {
        return nil, nil, fmt.Errorf("failed to derive key")
    }
    defer C.TWPrivateKeyDelete(key)

    // Get private key bytes
    privData := C.TWPrivateKeyData(key)
    privBytes := C.GoBytes(unsafe.Pointer(C.TWDataBytes(privData)), C.int(C.TWDataSize(privData)))

    // Get public key bytes
    pubKey := C.TWPrivateKeyGetPublicKey(key, C.TWPublicKeyTypeSECP256k1)
    pubData := C.TWPublicKeyData(pubKey)
    pubBytes := C.GoBytes(unsafe.Pointer(C.TWDataBytes(pubData)), C.int(C.TWDataSize(pubData)))

    // Zero sensitive memory
    C.TWDataDelete(privData)
    C.TWPublicKeyDelete(pubKey)
    C.TWDataDelete(pubData)

    return privBytes, pubBytes, nil
}

// Address generates address from public key using TWC
func (e Enabled) Address(pub []byte, chain string) (string, error) {
    coinType := getCoinTypeFromChain(chain)

    // Create public key
    pubKeyData := C.TWDataCreateWithBytes((*C.uchar)(unsafe.Pointer(&pub[0])), C.ulong(len(pub)))
    defer C.TWDataDelete(pubKeyData)

    pubKey := C.TWPublicKeyCreateWithData(pubKeyData, C.TWPublicKeyTypeSECP256k1)
    if pubKey == nil {
        return "", fmt.Errorf("invalid public key")
    }
    defer C.TWPublicKeyDelete(pubKey)

    // Derive address
    addressData := C.TWCoinTypeDeriveAddress(coinType, pubKey)
    defer C.TWStringDelete(addressData)

    address := C.GoString(C.TWStringUTF8Bytes(addressData))
    return address, nil
}

// SignTx signs transaction using TWC
func (e Enabled) SignTx(chain string, priv []byte, payload []byte) ([]byte, error) {
    coinType := getCoinTypeFromChain(chain)

    // Create private key
    privKeyData := C.TWDataCreateWithBytes((*C.uchar)(unsafe.Pointer(&priv[0])), C.ulong(len(priv)))
    defer C.TWDataDelete(privKeyData)

    privKey := C.TWPrivateKeyCreateWithData(privKeyData)
    if privKey == nil {
        return nil, fmt.Errorf("invalid private key")
    }
    defer C.TWPrivateKeyDelete(privKey)

    // Sign transaction
    inputData := C.TWDataCreateWithBytes((*C.uchar)(unsafe.Pointer(&payload[0])), C.ulong(len(payload)))
    defer C.TWDataDelete(inputData)

    outputData := C.TWAnySignerSign(inputData, coinType)
    defer C.TWDataDelete(outputData)

    signed := C.GoBytes(unsafe.Pointer(C.TWDataBytes(outputData)), C.int(C.TWDataSize(outputData)))

    return signed, nil
}

func getCoinType(curve string) C.enum_TWCoinType {
    switch curve {
    case "ed25519":
        return C.TWCoinTypeTON
    case "secp256k1":
        return C.TWCoinTypeTron
    default:
        return C.TWCoinTypeBitcoin
    }
}

func getCoinTypeFromChain(chain string) C.enum_TWCoinType {
    switch chain {
    case "TON", "TON_TESTNET":
        return C.TWCoinTypeTON
    case "TRON", "TRON_TESTNET":
        return C.TWCoinTypeTron
    case "ETH", "ETHEREUM":
        return C.TWCoinTypeEthereum
    case "BSC", "BINANCE":
        return C.TWCoinTypeSmartChain
    default:
        return C.TWCoinTypeBitcoin
    }
}

โœ… Benefits of TWC

For Development:

  • โœ… 50+ blockchains support out-of-box
  • โœ… Battle-tested (used by Trust Wallet, Binance, etc.)
  • โœ… Regular updates and security patches
  • โœ… Extensive test vectors
  • โœ… Cross-platform (iOS, Android, Web, Server)

For Operations:

  • โœ… Single signing interface for all chains
  • โœ… Proven security (audited code)
  • โœ… Memory zeroing built-in
  • โœ… Consistent behavior across chains
  • โœ… Well-documented

For Users:

  • โœ… Addresses match standard wallets (Trust Wallet, MetaMask, etc.)
  • โœ… Can import seed to any TWC-based wallet
  • โœ… Multi-chain support seamless
  • โœ… Future-proof (new chains added regularly)

๐Ÿ”„ Migration Strategy

Phase 0-1: Native Signers (Weeks 1-2)

Goal: Validate architecture

Implement:
  โœ“ TON signer (tonutils-go)
  โœ“ TRON signer (gotron-sdk)

Test:
  โœ“ End-to-end deposit โ†’ withdrawal
  โœ“ Address generation correctness
  โœ“ Signature validity
  โœ“ Performance benchmarks

Deliverable:
  โœ“ Proven signer interface design
  โœ“ Working database integration
  โœ“ Performance baseline

Phase 2: Enable TWC (Week 3)

Goal: Production-ready multi-chain support

Implement:
  โ–ก Complete TWC signer
  โ–ก Memory management
  โ–ก Error handling

Test:
  โ–ก Golden vector tests (TWC vs native)
  โ–ก Performance comparison
  โ–ก Memory leak tests
  โ–ก Cross-chain consistency

Deliverable:
  โ–ก TWC signer ready for production
  โ–ก Performance acceptable (< 10% slower than native)
  โ–ก All chains supported

Phase 3: Production Deployment (Week 4+)

Deploy:
  โ–ก Build with -tags twc
  โ–ก Enable ENABLE_TWC_PLUGIN=true
  โ–ก Shadow mode (TWC + native in parallel)
  โ–ก Compare outputs
  โ–ก Gradual rollout

Monitor:
  โ–ก Signing performance
  โ–ก Memory usage
  โ–ก Error rates
  โ–ก Chain coverage

Migrate:
  โ–ก 100% traffic to TWC
  โ–ก Deprecate native signers (keep as fallback)

๐Ÿ› ๏ธ Build Instructions

Local Development

# Install TWC (first time only)
cd services/wallet/internal/wallet/service/signer/twc
./scripts/build-wallet-core.sh

# Build wallet with TWC
cd /opt/cryptotel/enterprise/stacks/gitinext/gitinext-golang
make build-wallet-twc

# Run
export ENABLE_TWC_PLUGIN=true
./bin/wallet-twc

Docker Build

# Build image with TWC
make docker-build-wallet-twc

# Push to registry
make docker-push-wallet-twc

# Run
docker run -e ENABLE_TWC_PLUGIN=true \
  registry.nextgiti.cloud:5000/wallet:latest-twc

Multi-stage Dockerfile (Production)

# Stage 1: Build Trust Wallet Core
FROM ubuntu:22.04 AS wallet-core-builder

RUN apt-get update && apt-get install -y \
    cmake build-essential libboost-all-dev \
    libprotobuf-dev protobuf-compiler git

WORKDIR /wallet-core
RUN git clone https://github.com/trustwallet/wallet-core.git .
RUN cmake -H. -Bbuild -DCMAKE_BUILD_TYPE=Release
RUN make -C build -j$(nproc)

# Stage 2: Build Go service
FROM golang:1.25-alpine AS go-builder

# Install build deps
RUN apk add --no-cache gcc g++ musl-dev

WORKDIR /app
COPY . .

# Copy TWC libraries from stage 1
COPY --from=wallet-core-builder /wallet-core/build /app/wallet-core/build
COPY --from=wallet-core-builder /wallet-core/include /app/wallet-core/include

# Build with twc tag
RUN CGO_ENABLED=1 go build -tags twc -o server ./services/wallet/cmd/server

# Stage 3: Runtime
FROM gcr.io/distroless/base-debian12:nonroot

COPY --from=go-builder /app/server /app/server
COPY --from=wallet-core-builder /wallet-core/build/libTrustWalletCore.so /usr/lib/

EXPOSE 9092
ENTRYPOINT ["/app/server"]

๐Ÿงช Testing Strategy

Golden Vector Tests

func TestTWCvsNative_TON(t *testing.T) {
    mnemonic := "abandon abandon ... art"

    // Generate with native
    nativeSigner := &tonSigner{}
    nativeAddr, _ := nativeSigner.Address(pubKey, Chain("TON"))

    // Generate with TWC
    twcSigner := &twc.Enabled{}
    twcAddr, _ := twcSigner.Address(pubKey, "TON")

    // MUST match
    assert.Equal(t, nativeAddr, twcAddr, "Addresses must match")
}

func TestTWCvsNative_Signing(t *testing.T) {
    // Sign same transaction with both
    nativeSig, _ := nativeSigner.SignTx(chain, priv, payload)
    twcSig, _ := twcSigner.SignTx(chain, priv, payload)

    // Both signatures should be valid
    assert.True(t, verifySignature(nativeSig))
    assert.True(t, verifySignature(twcSig))
}

Performance Benchmarks

func BenchmarkNative_Signing(b *testing.B) {
    for i := 0; i < b.N; i++ {
        nativeSigner.SignTx(chain, priv, payload)
    }
}

func BenchmarkTWC_Signing(b *testing.B) {
    for i := 0; i < b.N; i++ {
        twcSigner.SignTx(chain, priv, payload)
    }
}

// Target: TWC < 10% slower than native

๐Ÿ” Security Considerations

Memory Management

// TWC handles memory zeroing automatically
// But we should verify:

func (e Enabled) SignTx(chain string, priv []byte, payload []byte) ([]byte, error) {
    // Create private key
    privKey := createTWCPrivateKey(priv)
    defer C.TWPrivateKeyDelete(privKey)  // โœ… Cleanup

    // Sign
    signature := signWithTWC(privKey, payload)

    // TWC zeros private key memory on delete
    // Verify with memory profiling in tests

    return signature, nil
}

Audit Trail

// Log TWC usage for audit
logger.Info("Using TWC signer",
    zap.String("chain", chain),
    zap.String("version", getTWCVersion()),
    zap.Bool("twc_enabled", true),
)

๐Ÿ“Š Monitoring

Metrics

# Signer selection
signer_used_total{type="native|twc", chain}

# TWC performance
twc_signing_duration_seconds{chain}
twc_memory_usage_bytes{chain}
twc_errors_total{chain, error_type}

# Comparison
signer_performance_ratio{native_vs_twc, chain}

๐Ÿš€ Production Deployment

Rollout Strategy

Week 1-2: Native signers only
  โ†“
Week 3: Build TWC binary
  โ†“
Week 4: Shadow mode (both run, compare outputs)
  โ†“
Week 5: Canary deployment (10% traffic โ†’ TWC)
  โ†“
Week 6: Full rollout (100% โ†’ TWC)
  โ†“
Week 7+: Deprecate native (keep as fallback)

Feature Flag

# Environment variable controls which signer
export ENABLE_TWC_PLUGIN=true   # Use TWC
export ENABLE_TWC_PLUGIN=false  # Use native (default)

# Can toggle without redeployment
# Just restart service with different env var

๐ŸŽฏ Success Criteria

TWC Integration Complete When:

  • โœ… Build succeeds with -tags twc
  • โœ… All chains (TON, TRON, ETH, BSC) work
  • โœ… Addresses match Trust Wallet app
  • โœ… Signatures are valid on-chain
  • โœ… Performance acceptable (< 10% slower)
  • โœ… Memory leaks not detected
  • โœ… Golden tests pass (TWC == native for TON/TRON)
  • โœ… Production deployment successful
  • โœ… Can switch between native/TWC via env var

๐Ÿ“– References


Status: Framework ready, implementation pending after Phase 1 completion.

© 2025 GitiNext - Enterprise Crypto Infrastructure | GitHub | Website