DEV Community

Cover image for Unlocking a Secret Fund Based on Your Physical Location Using the Haversine Formula
DEVANSHU PATIL
DEVANSHU PATIL

Posted on

Unlocking a Secret Fund Based on Your Physical Location Using the Haversine Formula

Unlocking a Secret Fund Based on Your Physical Location Using the Haversine Formula

Authentication in mobile security is traditionally divided into three classic factors:

  1. Something you know (a PIN or password).
  2. Something you have (a hardware security key or physical phone).
  3. Something you are (a biometric fingerprint or facial scan).

In personal finance, these three factors cover 99% of daily scenarios.

However, consider an extreme threat model: Coercion or Device Theft in Public.

If your phone is snatched while walking down a street, or if you are pressured to unlock your phone in an unfamiliar setting, an attacker has your physical phone ("something you have") and might coerce your PIN ("something you know") or force your thumb onto the sensor ("something you are").

To provide a true safe haven for confidential emergency funds, FinLedger introduced a fourth factor: Somewhere you are (Physical Geofencing) (VaultLocationProvider.kt, VaultTrustedLocation.kt).

When Geofencing is activated in the Secret Vault:

  • The vault can only be unlocked when physically located inside a trusted geographic zone (such as your home or office).
  • If the device is outside that zone—even by 500 meters—the vault locks down completely. Even if someone holds the correct master PIN, the vault refuses to mount.

Here is how FinLedger implemented on-device physical geofencing using pure Kotlin spherical trigonometry and Android's native LocationManager without third-party tracking SDKs.

The Cloud-Free Geofencing Architecture

Commercial apps that implement geofencing usually rely on cloud-tethered location SDKs or Google Play Services Location APIs.

These SDKs carry severe privacy risks: they frequently stream device telemetry, Wi-Fi BSSID beacons, and continuous background GPS coordinates to remote analytics servers.

For a privacy-first finance application, transmitting your home GPS coordinates to a cloud server is unacceptable.

In FinLedger, geofencing is 100% offline and on-demand:

flowchart TD
    subgraph OfflineGeofence["FinLedger 100% Offline Geofence Engine"]
        UserUnlocks["User Attempts to Unlock Secret Vault"] --> PermissionCheck{"Location Permission Granted?"}

        PermissionCheck -->|No| BlockPerm["Block Unlock:
        'Geofencing is enabled. Location permission required.'"]

        PermissionCheck -->|Yes| HardwareGPS["Query Native Android LocationManager
        (GPS_PROVIDER & NETWORK_PROVIDER)"]

        HardwareGPS --> MockCheck{"Anti-Spoofing Check:
        Is location.isFromMockProvider() true?"}

        MockCheck -->|YES: Spoofed GPS!| BlockMock["REJECT UNLOCK:
        'Mock location detected. Vault access denied.'"]

        MockCheck -->|NO: Genuine Hardware GPS| HaversineMath["Calculate Spherical Distance:
        Haversine Formula in Pure Kotlin (< 2 microseconds)"]

        HaversineMath --> RadiusCheck{"Is distance <= trustedRadiusMeters?"}

        RadiusCheck -->|Inside Zone (e.g. 150m)| Permit["PERMIT PIN AUTHENTICATION"]
        RadiusCheck -->|Outside Zone (e.g. 2.4 km)| Deny["HARD LOCKOUT:
        'Device is outside trusted physical zone.'"]
    end

Let's examine how each safeguard functions in detail:

The Mathematical Engine: The Haversine Formula

Because the Earth is an oblate spheroid, calculating the distance between two GPS coordinates cannot be done with simple Cartesian Pythagorean distance ($\sqrt{\Delta x^2 + \Delta y^2}$). On a sphere, Cartesian distance produces massive distortion as you move away from the equator.

FinLedger calculates geodesic distance using the Haversine Formula:

$$a = \sin^2\left(\frac{\Delta \phi}{2}\right) + \cos(\phi_1) \cdot \cos(\phi_2) \cdot \sin^2\left(\frac{\Delta \lambda}{2}\right)$$

$$c = 2 \cdot \arctan2\left(\sqrt{a}, \sqrt{1-a}\right)$$

$$d = R \cdot c$$

Where:

  • $\phi_1, \phi_2$ are the latitudes of the current device location and the trusted anchor in radians.
  • $\Delta \phi$ is the latitude delta, and $\Delta \lambda$ is the longitude delta.
  • $R$ is Earth's mean radius ($6,371,000$ meters).
  • $d$ is the spherical distance in meters.

Implemented in pure Kotlin using standard kotlin.math primitives (sin, cos, atan2, sqrt):

  • The entire distance calculation executes in under 2 microseconds on a mobile CPU.
  • It consumes zero network calls and allocates zero heap objects.
  • It delivers meter-level distance accuracy anywhere on the globe.

Anti-Spoofing: Defeating Fake GPS Apps

On Android, a common technique used by attackers to bypass location restrictions is running a "Fake GPS" or "Mock Location" application via Android Developer Options.

In DefaultVaultLocationProvider.kt, FinLedger enforces a strict anti-spoofing guard:

  • On modern Android devices, the engine inspects location.isMock (or location.isFromMockProvider()).
  • If developer-mode GPS spoofing is detected, the engine aborts immediately: DeviceLocationResult.Error("Mock location detected. Geofenced vaults require genuine hardware GPS.")
  • The vault cannot be tricked by software spoofers.

Zero Background Location Tracking

Many location-based apps drain device batteries by running continuous background GPS listeners 24 hours a day.

FinLedger respects your battery and your privacy:

  • The app has zero background location daemons.
  • Location hardware is queried strictly on-demand for five seconds at the exact moment you attempt to open the vault.
  • Once the coordinates are acquired and verified against the Haversine formula, the GPS hardware is immediately powered down, ensuring zero battery drain and zero persistent tracking.

Key Takeaway

Physical location can be one of the most powerful security barriers in modern mobile computing—if it is implemented with respect for user privacy.

By combining native Android hardware providers, anti-spoofing guards, and the mathematical precision of the Haversine formula, FinLedger's geofenced vault ensures that your most private financial reserves remain physically anchored to the places you trust most.


FinLedger is a privacy-first, offline-first personal finance application for Android that models bank accounts, credit cards, and cash without double-counting.

Explore FinLedger on Google Play: https://play.google.com/store/apps/details?id=com.devanshufinance.app

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

This is a neat fourth factor, Devanshu — location as an authentication factor is underused, and doing it fully offline without a tracking SDK is the right call for a finance app.

The part I kept thinking about is the 500-meter hard cutoff. GPS drift indoors can easily be tens of meters, and a genuine user standing at the edge of their home zone could be pushed outside it by a bad fix — exactly the moment they might need an emergency fund. Do you build any grace into the boundary, like hysteresis or a second attempt with a fresh fix, or is it a strict single check?

And the five-second on-demand window: on a cold start indoors, a GPS fix can take longer than five seconds to arrive. When no fix comes back in that window, does the vault fail closed and stay locked, or does it retry the acquisition before giving up?