Skip to content
sinhsacPublic

About

Peer-to-peer local network photo and video library sync engine in Rust with mutual TLS 1.3, chunked resumable transfers, and Android MediaStore support.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

PhotoSync

License: MIT Rust Android Kotlin

PhotoSync is an offline-first, peer-to-peer photo and video library sync engine built in Rust with an Android JNI client. It transfers entire photo and video libraries directly between devices over a local network or Wi-Fi hotspot—with no cloud, no accounts, and no central server—using mutual TLS 1.3, 6-digit code-bound pairing, content-addressed deduplication, 4 MB resumable chunked transfers, and native Android MediaStore integration.


Key Features

  • Direct LAN & Hotspot Transfers: Peer-to-peer sync over Wi-Fi or a phone hotspot without internet access, using per-interface UDP multicast announcements (224.0.0.187:53411), TCP callbacks, /24 subnet-scan fallback, or direct IP address entry.
  • Mutual TLS 1.3 & Code-Bound Pairing:
    • Self-signed peer certificates (rcgen + rustls with ring) with SHA-256 certificate fingerprint pinning enforced inside the TLS 1.3 handshake.
    • Single-use 6-digit pairing codes bound to both certificate fingerprints and session nonces via HMAC-SHA256, with 5-minute expiry and a global 3-attempt limit.
    • Subsequent syncs and resumes authenticate automatically via pinned certificate fingerprints with no code re-entry.
  • Two-Tier Content-Addressed Deduplication:
    • Fast 192 KB sampled quick_hash (SHA-256(size || head 64 KB || middle 64 KB || tail 64 KB)) for rapid library indexing and manifest candidate filtering.
    • Authoritative streaming full-file SHA-256 computed in a single pass during transfer and cached in SQLite (sent_log and received_asset) so collisions never silently skip distinct files and repeat syncs skip already-present media at zero wire cost.
  • 4 MB Chunked, Resumable & Verified Transfers:
    • Sequential 4 MB chunks with per-chunk SHA-256 verification so corrupted chunks retry individually instead of restarting multi-gigabyte videos.
    • Receiver-authoritative byte-offset resume persisted at verified, flushed chunk boundaries; staging files are truncated to the committed offset and re-hashed on reconnect.
    • Bidirectional control-stream heartbeats and read/write deadlines prevent stalled half-open connections.
  • SQLite-Backed Incremental Engine:
    • Bundled SQLite (rusqlite) in WAL mode derives the pending work list via a SQL LEFT JOIN anti-join against sent_log rather than materializing a massive transfer queue.
    • Only active in-flight assets live in transfer / inbound_transfer, keeping state small and restart-safe across process kills.
  • Native Android MediaStore Integration:
    • Paginated _ID-watermark gallery enumeration (PhotoStore.kt) avoids offset-paging gaps and never loads the full library into RAM.
    • Writes incoming media to IS_PENDING = 1 MediaStore entries (Pictures/PhotoSync, Movies/PhotoSync) as direct staging files and publishes atomically with preserved DATE_TAKEN and DATE_MODIFIED timestamps only after full-file hash verification.
  • Desktop Fault-Injection Harness (psdev):
    • Exercises real TCP/TLS handshakes, MITM relay rejection, quick-key collisions, mid-asset connection cuts, bit-flip chunk corruption, misaligned chunks, peer discovery, and two-device transfers from the command line.

Tech Stack

Layer Technologies
Core Engine (photosync-core) Rust (Edition 2021, MSRV 1.88), rusqlite (bundled SQLite 3, WAL mode), sha2, hmac, serde, serde_json, uuid, thiserror, tracing
Network & Security (photosync-net) tokio, rustls (ring), tokio-rustls, rcgen, socket2, if-addrs
Android Native Bridge (photosync-android) Rust cdylib (libphotosync_android.so), jni 0.21, cargo-ndk (Android API 24+)
C FFI Bring-Up (photosync-ffi) Rust cdylib / staticlib (libphotosync)
Android App (android/) Kotlin 1.9.22, Android Gradle Plugin 8.2.0, Gradle 8.9, AndroidX AppCompat, MediaStore API

Project Structure

photosync/
├── Cargo.toml                 # Rust workspace configuration
├── rust-toolchain.toml        # Pinned Rust 1.88.0 toolchain (rustfmt, clippy)
├── app_info.md                # Full product & technical specification (EN)
├── app_info_vi.md             # Technical specification (VI)
├── schema/
│   └── 001_initial.sql        # SQLite schema (peers, sessions, catalog, transfers)
├── crates/
│   ├── core/                  # Platform-agnostic sync engine, SQLite catalog, chunking, pairing, protocol
│   ├── net/                   # Mutual TLS 1.3, UDP multicast & subnet discovery, framed link, orchestrator
│   ├── android/               # Android JNI bridge implementing MediaStore LibrarySource/LibrarySink
│   ├── ffi/                   # Minimal C FFI bring-up library (cdylib + staticlib)
│   └── dev/                   # Desktop test & fault-injection CLI harness (`psdev`)
├── android/                   # Android bring-up app (Kotlin + Gradle `cargoNdkBuild` integration)
│   └── app/src/main/kotlin/app/photosync/
│       ├── MainActivity.kt    # Bring-up activity (self-check, scan, receive, send)
│       ├── Native.kt          # Kotlin JNI bindings to `libphotosync_android.so`
│       └── PhotoStore.kt      # MediaStore read/write & atomic IS_PENDING staging
└── tools/
    └── make-fixtures.ps1      # PowerShell script to generate dated JPEG fixtures for gallery tests

Prerequisites

Desktop / Core Workspace

Android App Build

  • JDK 17+ (bytecode targets JVM 17)
  • Android SDK (platform 34, minSdk = 24, targetSdk = 34) & Android NDK (ANDROID_NDK_HOME or SDK ndk/ directory)
  • cargo-ndk and Rust Android targets (default arm64-v8a):
    cargo install cargo-ndk
    rustup target add aarch64-linux-android

Getting Started & Usage

1. Build the Rust Workspace

cargo build

Note: crates/android is excluded from default-members in Cargo.toml because it uses Android JNI and std::os::fd. Host builds compile photosync-core, photosync-net, photosync-ffi, and photosync-dev (psdev).

2. Run the Desktop Harness (psdev)

Run engine self-checks, security checks, and fault-injection workflows directly on your machine:

# Verify SQLite linking, schema migrations, and candidate anti-join invariants
cargo run -p photosync-dev -- selfcheck

# Verify code-bound HMAC authentication, MITM resistance, expiry, and 3-attempt budget
cargo run -p photosync-dev -- pairing

# Exercise real TCP + mutual TLS 1.3 handshakes (honest, MITM relay, fingerprint mismatch)
cargo run -p photosync-dev -- handshake

# Inspect local network interfaces visible to discovery
cargo run -p photosync-dev -- netinfo

# Generate a 45 MB pseudorandom fixture and test clean, cut/resume, bit-flip corrupt, and misaligned chunk handling
cargo run -p photosync-dev -- fixture devdata/sample.bin 45
cargo run -p photosync-dev -- transfer devdata/sample.bin all

# Test quick-key collision safety (two distinct files with identical size/head/middle/tail)
cargo run -p photosync-dev -- collide devdata/src
cargo run -p photosync-dev -- scan devdata/src
cargo run -p photosync-dev -- status

# End-to-end sync, mid-asset cut & codeless resume, and UDP multicast discovery sync
cargo run -p photosync-dev -- sync devdata/src devdata/dst
cargo run -p photosync-dev -- resume-session devdata/src devdata/dst
cargo run -p photosync-dev -- discover devdata/src devdata/dst

Run two separate processes (or two devices on the same LAN) in Send / Receive roles:

# On the receiving machine (prints a 6-digit pairing code and announces over UDP multicast)
cargo run -p photosync-dev -- serve ./received_photos

# On the sending machine (discovers the receiver automatically, or pass an explicit IP:port)
cargo run -p photosync-dev -- send ./source_photos 482913
cargo run -p photosync-dev -- send ./source_photos 482913 192.168.1.19:53411

On Windows, you can also generate real dated JPEG fixtures for Android gallery verification:

.\tools\make-fixtures.ps1 -OutDir devdata\src

3. Build the Android App

Gradle automatically invokes cargo ndk via the cargoNdkBuild task in android/app/build.gradle.kts (--platform 24 is required for getifaddrs in Android Bionic):

cd android
# Windows
gradlew.bat assembleDebug
# Or specify multiple ABIs (e.g., for an emulator)
gradlew.bat assembleDebug -Ppsync.abis=arm64-v8a,x86_64

To compile only the Android JNI library manually:

cargo ndk -t arm64-v8a --platform 24 -o android/app/src/main/jniLibs build -p photosync-android --release

To compile the C FFI bring-up library (photosync-ffi) for Android ABIs:

cargo ndk -t arm64-v8a -t armeabi-v7a -t x86_64 -o jniLibs build -p photosync-ffi --release

Architecture & Documentation

  • app_info.md — Complete product & technical specification (discovery, mutual TLS 1.3, code-bound auth, chunked resume, SQLite state, platform constraints, and architectural decision log).
  • app_info_vi.md — Vietnamese specification reference.
  • schema/001_initial.sql — Annotated initial SQLite schema.

License

This project is licensed under the MIT License — see the LICENSE file for details.

About

Peer-to-peer local network photo and video library sync engine in Rust with mutual TLS 1.3, chunked resumable transfers, and Android MediaStore support.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages