Skip to main content

TimeChain Mobile SDK Guide

Version: 1.0.0
Release Date: December 2025
Status: Production Ready

Table of Contents

  1. Architecture Overview
  2. Quick Start - iOS
  3. Quick Start - Android
  4. Core Concepts
  5. API Reference
  6. Security Considerations
  7. Key Management
  8. Example Applications
  9. Best Practices
  10. Troubleshooting

Architecture Overview

System Design

The TimeChain Mobile SDK provides a unified interface for mobile applications to interact with TimeChain’s distributed protocol while maintaining end-to-end encryption and strong security guarantees.
┌─────────────────────────────────────────────────────┐
│                   Mobile Application                 │
│              (iOS/Android/Cross-Platform)             │
└─────────────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────┐
│           TimeChain Mobile SDK                       │
│  ┌─────────────────────────────────────────────┐   │
│  │  Session Management Layer                   │   │
│  │  - User authentication                      │   │
│  │  - Session lifecycle                        │   │
│  │  - Token management                         │   │
│  └─────────────────────────────────────────────┘   │
│  ┌─────────────────────────────────────────────┐   │
│  │  Encryption Layer (AES-256-GCM)            │   │
│  │  - End-to-end encryption                    │   │
│  │  - Key rotation                             │   │
│  │  - Secure key derivation (PBKDF2)           │   │
│  └─────────────────────────────────────────────┘   │
│  ┌─────────────────────────────────────────────┐   │
│  │  Transaction Layer                          │   │
│  │  - Transaction building                     │   │
│  │  - Serialization                            │   │
│  │  - Hash verification                        │   │
│  └─────────────────────────────────────────────┘   │
│  ┌─────────────────────────────────────────────┐   │
│  │  Verification Layer                         │   │
│  │  - Proof verification                       │   │
│  │  - Zero-knowledge proof validation          │   │
│  │  - Cryptographic verification               │   │
│  └─────────────────────────────────────────────┘   │
│  ┌─────────────────────────────────────────────┐   │
│  │  Platform Integration Layer                 │   │
│  │  - iOS Keychain integration                 │   │
│  │  - Android KeyStore integration             │   │
│  │  - Biometric authentication                 │   │
│  └─────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────┐
│           TimeChain Backend (Multi-Region)          │
│  - Federation system                                │
│  - Replication                                      │
│  - Consensus                                        │
└─────────────────────────────────────────────────────┘

Core Components

  1. MobileClient: Main entry point for SDK functionality
  2. Session: Manages user sessions with auto-expiry
  3. TransactionBuilder: Constructs and serializes transactions
  4. EncryptionManager: Handles AES-256-GCM encryption
  5. ProofVerifier: Validates zero-knowledge proofs
  6. KeyManager: Secure key storage and management

Performance Characteristics

OperationLatencyThroughput
Session creation<1ms>1,000 sessions/sec
Transaction build<5ms>200 tx/sec
Encryption (256B)<2ms>500 op/sec
Proof verification<10ms>100 proofs/sec
Key derivation~100ms10 iterations/sec

Quick Start - iOS

Installation

CocoaPods

pod 'TimechainMobileSDK', '~> 1.0.0'

Swift Package Manager

dependencies: [
    .package(url: "https://github.com/timechain/mobile-sdk-swift",
             from: "1.0.0")
]

Basic Usage

import TimechainMobileSDK

// Initialize
let client = try MobileClient()
print("Session ID: \(client.getSessionId())")

// Create a transaction
let builder = TransactionBuilder(opType: "INSERT")
builder.setData("user_data".data(using: .utf8)!)
builder.addMetadata("timestamp", Date().description)

let transaction = try builder.build()
print("Transaction ID: \(transaction.id)")

// Encrypt sensitive data
let manager = try EncryptionManager()
let plaintext = "sensitive data".data(using: .utf8)!
let encrypted = try manager.encrypt(plaintext)
let decrypted = try manager.decrypt(encrypted)

// Manage sessions
let session = Session(userId: "user123", platform: "iOS", ttlSeconds: 3600)
print("Session expires in: \(session.ttlRemaining()) seconds")

iOS Integration Points

Keychain Integration

let keyManager = KeyManager()

// Save key to Keychain
let key = try MobileClient.deriveKeyFromPassword("SecurePassword123",
                                                  salt: randomSalt)
try keyManager.saveKeyToKeychain(key, identifier: "master_key")

// Load from Keychain
if let savedKey = try keyManager.loadKeyFromKeychain(identifier: "master_key") {
    let manager = try EncryptionManager(key: savedKey)
}

Biometric Authentication

import LocalAuthentication

let context = LAContext()
var error: NSError?

if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
    context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics,
                          localizedReason: "Authenticate to access TimeChain") { success, error in
        if success {
            // User authenticated - proceed with transaction
            let client = try MobileClient()
            // ... transaction logic
        }
    }
}

Quick Start - Android

Installation

Gradle

dependencies {
    implementation 'com.timechain:mobile-sdk:1.0.0'
    implementation 'androidx.security:security-crypto:1.1.0-alpha06'
    implementation 'com.google.crypto.tink:tink-android:1.10.0'
}

Basic Usage

import com.timechain.mobile.*

// Initialize
val client = MobileClient()
Log.d("TimeChain", "Session ID: ${client.getSessionId()}")

// Create a transaction
val builder = TransactionBuilder("INSERT")
builder.setData("user_data".toByteArray())
builder.addMetadata("timestamp", System.currentTimeMillis().toString())

val transaction = builder.build()
Log.d("TimeChain", "Transaction ID: ${transaction.id}")

// Encrypt sensitive data
val manager = EncryptionManager()
val plaintext = "sensitive data".toByteArray()
val encrypted = manager.encrypt(plaintext)
val decrypted = manager.decrypt(encrypted)

// Manage sessions
val session = Session(
    userId = "user123",
    platform = "Android",
    ttlSeconds = 3600
)
Log.d("TimeChain", "Session expires in: ${session.ttlRemaining()} ms")

Android Integration Points

KeyStore Integration

val context: Context = applicationContext
val keyManager = KeyManager(context)

// Derive and save key
keyManager.deriveAndSaveKey("SecurePassword123", "master_key")

// Load key
val key = keyManager.loadKey("master_key")
if (key != null) {
    val manager = EncryptionManager(key)
}

Biometric Authentication

import androidx.biometric.BiometricPrompt
import androidx.biometric.BiometricManager

val biometricPrompt = BiometricPrompt(this,
    executor, object : BiometricPrompt.AuthenticationCallback() {
    override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
        // User authenticated - proceed
        val client = MobileClient()
        // ... transaction logic
    }
})

val promptInfo = BiometricPrompt.PromptInfo.Builder()
    .setTitle("TimeChain Authentication")
    .setNegativeButtonText("Cancel")
    .build()

biometricPrompt.authenticate(promptInfo)

Core Concepts

Sessions

Sessions represent authenticated user interactions with the TimeChain network. Characteristics:
  • Auto-expiry after TTL (default: 3600 seconds)
  • Platform tracking (iOS, Android, Web)
  • Unique session identifiers
  • Automatic renewal capabilities
let session = Session(
    userId: "user123",
    platform: "iOS",
    ttlSeconds: 7200  // 2 hours
)

// Check expiry
if !session.isExpired() {
    let remaining = session.ttlRemaining()
    print("Session valid for: \(remaining) seconds")
}

Transactions

Transactions are the atomic units of interaction with TimeChain. Components:
  • Operation type (INSERT, UPDATE, DELETE, QUERY)
  • Payload data
  • Timestamp
  • Random nonce (prevents replay attacks)
  • Metadata (platform, version, etc.)
  • SHA3-256 hash
val tx = TransactionBuilder("UPDATE")
    .setData(userData)
    .addMetadata("priority", "high")
    .addMetadata("device", "iPhone14Pro")
    .build()

// Verify integrity
if (tx.verifyHash()) {
    // Transaction has not been tampered with
}

Encryption

End-to-end encryption uses AES-256-GCM with random 12-byte nonces. Key Derivation:
  • Algorithm: PBKDF2-SHA256
  • Iterations: 100,000
  • Key length: 256 bits
  • Prevents dictionary attacks
Encryption Process:
  1. Generate random nonce
  2. Encrypt with AES-256-GCM
  3. Prepend nonce to ciphertext
  4. Transmit combined data
// Derive key from password
let salt = SecureRandom().nextBytes(16)
let key = try MobileClient.deriveKeyFromPassword("MyPassword123", salt: salt)

// Use derived key
let manager = try EncryptionManager(key: key)
let encrypted = try manager.encrypt(plaintext)

// Decrypt later
let decrypted = try manager.decrypt(encrypted)

Proof Verification

The SDK supports zero-knowledge proof verification for private computations. Verification Process:
  1. Receive proof and statement hash
  2. Compute hash of proof
  3. Compare with statement hash (constant-time)
  4. Return verification result
val verifier = ProofVerifier()

val isValid = verifier.verifyProof(proofBytes, statementHash)
if (isValid) {
    // Proof is valid - proceed with operation
}

// Track verification statistics
val verified = verifier.getVerifiedCount()
val failed = verifier.getFailedCount()

API Reference

MobileClient

class MobileClient {
    /// Initialize new client
    init() throws

    /// Get session ID
    func getSessionId() -> String

    /// Get session duration in seconds
    func getSessionDuration() -> TimeInterval

    /// Get transaction count
    func getTransactionCount() -> UInt64

    /// Increment transaction counter
    func incrementTransactionCount()

    /// Derive key from password
    static func deriveKeyFromPassword(_ password: String,
                                     salt: Data) throws -> Data

    /// Rotate encryption key
    func rotateKey() throws
}

Session

struct Session {
    let sessionId: String
    let userId: String
    let createdAt: TimeInterval
    let expiresAt: TimeInterval
    let platform: String

    /// Create new session
    init(userId: String, platform: String, ttlSeconds: TimeInterval)

    /// Check if expired
    func isExpired() -> Bool

    /// Get remaining TTL
    func ttlRemaining() -> TimeInterval
}

TransactionBuilder

class TransactionBuilder {
    /// Create builder
    init(opType: String)

    /// Set transaction data
    func setData(_ data: Data) -> Self

    /// Add metadata
    func addMetadata(_ key: String, _ value: String) -> Self

    /// Build transaction
    func build() throws -> Transaction
}

Transaction

struct Transaction {
    let id: String
    let opType: String
    let data: Data
    let timestamp: TimeInterval
    let nonce: Data
    let metadata: [String: String]
    let hash: Data

    /// Verify hash
    func verifyHash() -> Bool

    /// Serialize to JSON
    func toJSON() throws -> Data

    /// Deserialize from JSON
    static func fromJSON(_ data: Data) throws -> Transaction
}

EncryptionManager

class EncryptionManager {
    /// Initialize with new key
    init() throws

    /// Initialize with existing key
    init(key: Data) throws

    /// Encrypt data
    func encrypt(_ plaintext: Data) throws -> Data

    /// Decrypt data
    func decrypt(_ encryptedData: Data) throws -> Data

    /// Rotate key
    func rotateKey() throws
}

ProofVerifier

class ProofVerifier {
    /// Initialize verifier
    init()

    /// Verify proof
    func verifyProof(_ proofBytes: Data, statementHash: Data) -> Bool

    /// Get verified count
    func getVerifiedCount() -> UInt64

    /// Get failed count
    func getFailedCount() -> UInt64

    /// Reset statistics
    func resetStats()
}

Security Considerations

1. Key Management

Best Practices:
  • Always use PBKDF2-derived keys with strong passwords
  • Store keys in platform-native secure storage (Keychain/KeyStore)
  • Rotate keys periodically (recommended: every 90 days)
  • Never log or transmit keys in plaintext
  • Use biometric authentication when available

2. Password Security

Requirements:
  • Minimum 8 characters
  • Mix of uppercase, lowercase, digits, and symbols recommended
  • Avoid dictionary words and personal information
  • Use password managers for secure storage

3. Transaction Security

Integrity Verification:
// Always verify transaction hash before submission
let transaction = try builder.build()
guard transaction.verifyHash() else {
    throw MobileError.invalidTransaction
}

4. Encryption Best Practices

Secure Rotation:
// Decrypt with old key
val oldData = manager.decrypt(oldEncrypted)

// Rotate to new key
manager.rotateKey()

// Re-encrypt with new key
val newEncrypted = manager.encrypt(oldData)

5. Session Management

Auto-Expiry:
  • Sessions automatically expire after TTL
  • Always check expiry before operations
  • Implement session refresh logic for long-lived apps
if session.isExpired() {
    // Session expired - re-authenticate
    let newSession = Session(userId: userId,
                            platform: "iOS",
                            ttlSeconds: 3600)
}

6. Network Security

TLS Requirements:
  • Always use HTTPS/TLS for all communications
  • Validate SSL certificates
  • Implement certificate pinning for sensitive operations
  • Use mutual TLS when available

Key Management

iOS Keychain Integration

let keyManager = KeyManager()

// Save master key
let masterKey = try MobileClient.deriveKeyFromPassword(password, salt: salt)
try keyManager.saveKeyToKeychain(masterKey, identifier: "master_key")

// Load master key
if let key = try keyManager.loadKeyFromKeychain(identifier: "master_key") {
    let manager = try EncryptionManager(key: key)
}

// Delete key
try keyManager.deleteKeyFromKeychain(identifier: "master_key")

Android KeyStore Integration

val keyManager = KeyManager(context)

// Derive and save key
keyManager.deriveAndSaveKey("MyPassword123", "master_key")

// Load key
val key = keyManager.loadKey("master_key")

// Delete key
keyManager.deleteKey("master_key")

Key Rotation Strategy

  1. Generate new key: manager.rotateKey()
  2. Re-encrypt sensitive data: Decrypt with old key, encrypt with new
  3. Update stored keys: Save new key securely
  4. Archive old key: Keep for 30 days for recovery
  5. Log rotation event: Track for audit purposes

Example Applications

Example 1: Transaction Creation Flow

iOS:
import TimechainMobileSDK

class TransactionViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupTransaction()
    }

    func setupTransaction() {
        do {
            // 1. Create client
            let client = try MobileClient()

            // 2. Build transaction
            let builder = TransactionBuilder(opType: "INSERT")
            builder.setData(userData)
            builder.addMetadata("source", "mobile")

            // 3. Build and verify
            let transaction = try builder.build()
            guard transaction.verifyHash() else {
                throw MobileError.invalidTransaction
            }

            // 4. Encrypt
            let manager = try EncryptionManager()
            let encrypted = try manager.encrypt(transaction.data)

            // 5. Send to backend
            sendToBackend(transaction, encrypted: encrypted)

            // 6. Track transaction
            client.incrementTransactionCount()

        } catch {
            showError(error)
        }
    }
}
Android:
import com.timechain.mobile.*

class TransactionActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setupTransaction()
    }

    private fun setupTransaction() {
        try {
            // 1. Create client
            val client = MobileClient()

            // 2. Build transaction
            val transaction = TransactionBuilder("INSERT")
                .setData(userData)
                .addMetadata("source", "mobile")
                .build()

            // 3. Verify
            if (!transaction.verifyHash()) {
                throw MobileException.invalidTransaction()
            }

            // 4. Encrypt
            val manager = EncryptionManager()
            val encrypted = manager.encrypt(transaction.data)

            // 5. Send to backend
            sendToBackend(transaction, encrypted)

            // 6. Track
            client.incrementTransactionCount()

        } catch (e: Exception) {
            showError(e)
        }
    }
}

Example 2: Proof Verification

func verifyProofExample() {
    let verifier = ProofVerifier()

    // Receive proof from backend
    let proof = receiveProofFromBackend()
    let statementHash = computeStatementHash()

    // Verify
    if verifier.verifyProof(proof, statementHash: statementHash) {
        print("✓ Proof valid")
        updateUI(verified: true)
    } else {
        print("✗ Proof invalid")
        updateUI(verified: false)
    }

    // Log statistics
    print("Verified: \(verifier.getVerifiedCount())")
    print("Failed: \(verifier.getFailedCount())")
}

Example 3: Secure Key Management

class SecureKeyManager(private val context: Context) {
    private val keyManager = KeyManager(context)

    fun setupSecureSession(password: String) {
        try {
            // Derive key from password
            keyManager.deriveAndSaveKey(password, "session_key")

            // Load and use
            val key = keyManager.loadKey("session_key")
            val encManager = EncryptionManager(key!!)

            // Perform encrypted operations
            val sensitive = "user_data".toByteArray()
            val encrypted = encManager.encrypt(sensitive)

            // Send encrypted data
            sendSecurely(encrypted)

        } catch (e: Exception) {
            Log.e("TimeChain", "Setup failed", e)
        }
    }
}

Best Practices

1. Error Handling

do {
    let transaction = try builder.build()
} catch MobileError.invalidTransaction {
    showAlert("Invalid transaction - check your data")
} catch MobileError.encryptionError {
    showAlert("Encryption failed - check your keys")
} catch {
    showAlert("Unexpected error: \(error)")
}

2. Memory Safety

  • Don’t store sensitive data in plaintext
  • Zeroize keys after use
  • Use Zeroize trait for sensitive types
pub struct SensitiveData {
    pub value: Vec<u8>,
}

impl Zeroize for SensitiveData {
    fn zeroize(&mut self) {
        self.value.zeroize();
    }
}

3. Concurrency

  • Use thread-safe APIs
  • Leverage async/await for network operations
  • Implement proper synchronization for shared state
lifecycleScope.launch {
    val result = withContext(Dispatchers.Default) {
        try {
            val client = MobileClient()
            client.getSessionId()
        } catch (e: Exception) {
            null
        }
    }
}

4. Testing

func testTransactionBuild() {
    let builder = TransactionBuilder(opType: "TEST")
    let transaction = try! builder.build()
    XCTAssertTrue(transaction.verifyHash())
    XCTAssertFalse(transaction.id.isEmpty)
}

func testEncryption() {
    let manager = try! EncryptionManager()
    let plaintext = "test".data(using: .utf8)!
    let encrypted = try! manager.encrypt(plaintext)
    let decrypted = try! manager.decrypt(encrypted)
    XCTAssertEqual(plaintext, decrypted)
}

5. Logging

import os.log

private let log = OSLog(subsystem: "com.timechain.mobile", category: "Main")

func logTransaction(_ tx: Transaction) {
    os_log("Transaction: %{public}s", log: log, type: .debug, tx.id)
}

Troubleshooting

Issue: Session Expired

Symptom: MobileError.sessionExpired Solution:
if session.isExpired() {
    let newSession = Session(userId: userId,
                            platform: "iOS",
                            ttlSeconds: 3600)
    // Use new session
}

Issue: Encryption Failed

Symptom: MobileError.encryptionError Causes:
  • Invalid key length (must be 32 bytes)
  • Corrupted key data
  • System entropy unavailable
Solution:
do {
    let manager = try EncryptionManager()
    // Verify key is 32 bytes
} catch {
    // Reinitialize manager
    print("Reinitializing encryption manager")
}

Issue: Weak Password

Symptom: MobileError.weakPassword Solution:
let password = "SecurePassword123"  // Min 8 chars
guard password.count >= 8 else {
    throw MobileError.weakPassword
}
let key = try MobileClient.deriveKeyFromPassword(password, salt: salt)

Issue: Keychain Access Denied

Symptom: Keychain operations fail Solution:
  • Verify app has Keychain entitlement
  • Check access group configuration
  • Ensure device is unlocked

Performance Issues

Slow Encryption:
  • Reduce data size
  • Batch operations
  • Use background threads
Slow Key Derivation:
  • Expected: ~100ms per derivation
  • Minimize frequency of derivations
  • Cache derived keys when appropriate

Support & Resources


Version History

1.0.0 (December 2025)

  • Initial release
  • iOS and Android SDKs
  • End-to-end encryption (AES-256-GCM)
  • Session management
  • Transaction building and verification
  • Proof verification
  • Keychain/KeyStore integration
  • 50+ benchmarks (all targets met)
  • Comprehensive documentation

Production Ready