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:
- Phase 0-1: Build native Go signers (TON, TRON) - validate approach
- Phase 2: Enable TWC for production - leverage battle-tested code
- 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
- Trust Wallet Core: https://github.com/trustwallet/wallet-core
- Documentation: https://developer.trustwallet.com/wallet-core
- Supported Chains: https://developer.trustwallet.com/wallet-core/supported-blockchains
- CGO Documentation: https://pkg.go.dev/cmd/cgo
Status: Framework ready, implementation pending after Phase 1 completion.