Energy sharing is not an unsolved physics problem. It is an unaddressed billing and accounting architecture problem. Rooftop solar inverters and EV charging stations connected to the same municipal distribution substation already share the exact same physical wires. No private cables or islanded switchboards are required to move electrons between two adjacent houses.
What is missing is a fair, high-speed, and auditable mechanism to reward the citizen whose solar panel actually sustained their neighbor's EV charge at the very second it happened. This article details the end-to-end design, telemetry pipelines, mathematical settlement algorithms, and cryptographic proofs powering our localized Energy DePIN.
01. The Street-Level Problem: The 23¢ Coincident Spread
In conventional electricity markets across Europe and North America, rooftop solar owners face a severe economic asymmetry:
- The Feed-in Tariff (FiT) Penalty: When midday sunshine produces surplus generation, the utility buys it back at a meager ~5¢/kWh.
- The Retail Grid Import Toll: A mere fifty meters away, a neighbor plugging in an electric vehicle pays the full residential retail tariff of ~28¢/kWh for electricity delivered over the exact same local transformer.
- The 23¢ Middleman Gap: The retail energy supplier pockets a 23¢ spread on electrons that never left the neighborhood, while the distribution grid operator (DSO) performed zero extra transmission work.
Our platform establishes a virtual Local Energy Community (LEC) billing overlay. When surplus coincides with local demand, neighbors clear at an equitable community mid-rate (~15¢/kWh). The solar producer earns 300% more than the utility FiT, the EV driver cuts their charging costs by nearly half, and the protocol collects a razor-thin 0.1¢/kWh ($0.001) fee to fund software infrastructure.
02. Collective Self-Consumption: Virtual Overlay, Not Rogue Wires
Many theoretical blockchain microgrid proposals make the fatal mistake of designing private, physical islanded networks. In reality, stringing private medium-voltage cables across public streets is legally prohibited in nearly every municipal jurisdiction on Earth.
Instead, our platform implements Collective Self-Consumption under statutory energy frameworks already active worldwide:
| Jurisdiction | Legal Mechanism | Operational Reality |
|---|---|---|
| European Union (RED II) | Citizen & Renewable Energy Communities | Direct statutory authorization for shared virtual self-consumption across shared substations. |
| United Kingdom | Local Energy Markets & Half-Hourly Settlement | Elexon settlement codes allow virtual supplier balancing overlays. |
| Australia | Virtual Energy Networks (VEN) & P2P Trials | Non-solar homes absorb midday solar surplus before grid spill limits trigger. |
| Switzerland | Lokale Elektrizitätsgemeinschaften (LEG) | Municipal utilities (e.g. EWZ) operate neighbor billing overlays over public distribution infrastructure. |
The Golden Rule: The public distribution grid remains untouched. The DSO maintains wire stability. Our software operates exclusively as a high-precision accounting, matching, and settlement overlay.
03. Edge Cryptography: Ed25519 Hardware Signatures
In a decentralized physical infrastructure network, trust must begin at the physical silicon. If a compromised client could inject synthetic kilowatt readings, they could drain community treasury balances.
Every meter provisioned on the network generates an Ed25519 device keypair. The public key is registered in PostgreSQL and cached in Redis. Every telemetry sample published to NATS is formatted into a strictly deterministic canonical JSON payload, hashed, and signed on the device:
# services/meter_emulator/emulate.py
payload = {
"device_pubkey": meter["device_pubkey"],
"kw_consumed": consumed,
"kw_generated": generated,
"meter_id": meter["meter_id"],
"region_id": meter["region_id"],
"role": meter["role"],
"serial_number": meter["serial_number"],
"solana_wallet": meter["solana_wallet"],
"timestamp": ts,
}
# Deterministic sort_keys=True is mandatory for cryptographic signature match
serialized = json.dumps(payload, sort_keys=True).encode("utf-8")
envelope = {
"payload": payload,
"signature": str(device.sign_message(serialized)),
}
subject = f"telemetry.energy.{meter['region_id']}.{meter['meter_id']}"
Notice the deterministic sorting: sort_keys=True ensures that whitespace and key sequence cannot cause signature verification failures when decoded by the asynchronous ingestion worker.
04. Physical Hardware: Modbus TCP Gateways & Holding Registers
To interface with certified industrial smart meters (such as Eastron SDM630 or Schneider IEM3000), we engineered a dedicated multi-meter gateway: services/modbus_bridge.
The bridge polls standard Modbus TCP holding registers over Ethernet / RS485 RTU converters, extracts active generated and consumed wattage, and constructs the cryptographic Ed25519 envelope:
- HR0 – HR1: Active Generated Watts (uint32, scaled by 0.001 to kW).
- HR2 – HR3: Active Consumed Watts (uint32, scaled by 0.001 to kW).
- Unit ID: 1 (configurable per sub-meter on RS485 multidrop loops).
05. Ingestion Bus: NATS JetStream & Durable Consumers
High-frequency telemetry must never block on a database write or risk message drops during traffic bursts. We chose NATS JetStream 2.10 as our high-performance persistence layer:
- Stream Configuration:
telemetry_streamlistens on the wildcard subjecttelemetry.energy.*.*. - Durable Consumer:
questdb_ingestorsguarantees at-least-once message delivery. If the database or worker restarts, telemetry waits safely in the JetStream buffer. - Kubernetes Horizontal Autoscaling (KEDA): The ingestion fleet scales dynamically from 2 to 20 replicas based on JetStream consumer lag (triggering when pending messages exceed 5,000).
06. The Ingestion Worker: Drop Lies, Keep Truth, Stream ILP
The ingestion worker (services/telemetry_ingestion/worker.py) executes strict defensive validation before any data touches the database:
- Verifies the Ed25519 signature against the cached device public key in Redis.
- Verifies meter status is
ACTIVE(provisioned meters cannot settle until confirmed by human operators). - Strict Role Enforcement: Solar meters (
PRODUCER) are strictly forbidden from writing consumed power; EV chargers (CONSUMER) are strictly forbidden from injecting generated power.
# services/telemetry_ingestion/worker.py
def power_columns_for_role(role: str, payload: dict) -> tuple[float, float]:
"""Persist only the physical flow matching verified hardware role."""
generated = max(0.0, float(payload.get("kw_generated") or 0))
consumed = max(0.0, float(payload.get("kw_consumed") or 0))
if role == "CONSUMER":
return 0.0, consumed
return generated, 0.0
# Dispatch via QuestDB Influx Line Protocol (ILP) on TCP 9009
with Sender(QUESTDB_HOST, QUESTDB_PORT) as sender:
sender.row(
"energy_telemetry",
symbols={"meter_id": meter_id, "region": region_id, "role": role},
columns={"kw_generated": gen_kw, "kw_consumed": con_kw},
at=TimestampNanos(timestamp_nanos)
)
sender.flush()
07. Time-Series: High-Speed Watts & Rectangle Energy Integration
A common flaw in naive IoT architectures is treating instant power (kW) samples as energy (kWh). If a sensor samples at 10 Hz and you sum the numbers, you have multiplied energy by 36,000.
Our settlement daemon (services/settlement/daemon.py) pulls new raw samples from QuestDB after the meter's stored settlement cursor and computes a mathematically sound time-weighted rectangle integral:
kWh += PowerkW × (Δt / 3600.0)
Gaps larger than 30 seconds are capped to prevent offline meters from claiming phantom kilowatt-hours upon reconnection.
08. The Settlement Engine: 5-Second Greedy Nearest-Neighbor Matching
Every 5 seconds, an asynchronous settlement worker wakes up for each active Region. It acquires an atomic distributed Redis lock (settle_lock:region:{slug}) to guarantee single-execution safety.
The matching algorithm executes in five distinct phases:
- Sort by Appetite: Most hungry EV consumers are sorted first (maximizing total cleared volume).
- Haversine Proximity Ranking: Eligible solar producers located within an 8 km radius are prioritized by great-circle distance:
haversine_distance(lat1, lon1, lat2, lon2) ≤ MATCH_RADIUS_METERS
- Greedy Volume Allocation: Clears
min(remaining_surplus, remaining_load). - Regional Fallback: Any unmatched meters without GPS coordinates are matched regionally so incomplete maps never freeze settlement.
- Utility Residual Clearing: Unmatched energy is never discarded. Leftover solar export settles against utility FiT (~5¢); leftover EV deficit settles against retail utility tariffs (~28¢).
# services/settlement/matching.py
def match_local_energy(offers: list[EnergyOffer], radius_m: float = 8000.0) -> list[EnergyFill]:
producers = [o for o in offers if o.role == "PRODUCER" and o.remaining > 0]
consumers = [o for o in offers if o.role == "CONSUMER" and o.remaining > 0]
consumers.sort(key=lambda c: c.remaining, reverse=True)
fills = []
for consumer in consumers:
if consumer.remaining <= 0:
continue
eligible = []
for prod in producers:
if prod.remaining <= 0:
continue
dist = haversine_m(consumer.lat, consumer.lng, prod.lat, prod.lng) if consumer.lat and prod.lat else 0.0
if radius_m is None or dist <= radius_m:
eligible.append((dist, prod))
eligible.sort(key=lambda x: x[0])
for dist, prod in eligible:
fill_kwh = min(consumer.remaining, prod.remaining)
consumer.remaining -= fill_kwh
prod.remaining -= fill_kwh
fills.append(build_fill(prod, consumer, fill_kwh, dist))
return fills
09. Cryptographic Settlement Proofs: Canonical SHA-256 Hashes
A major dilemma in DePIN architecture is cost: streaming every high-frequency watt onto a Layer 1 blockchain would bankrupt the network in transaction gas within minutes.
Our solution is the Interval Energy Proof. The settlement engine computes a canonical SHA-256 hash representing the exact trade parameters (producer ID, consumer ID, matched kWh, interval start timestamp, and interval end timestamp):
# services/settlement/matching.py
def energy_proof_hash(producer_id: str, consumer_id: str, kwh: Decimal, start: str, end: str) -> str:
"""Canonical SHA-256 of matched interval bound to on-chain payment."""
payload = json.dumps({
"consumer": str(consumer_id),
"interval_end": str(end or ""),
"interval_start": str(start or ""),
"kwh": format(Decimal(str(kwh)), "f"),
"producer": str(producer_id),
}, separators=(",", ":"), sort_keys=True)
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
This compact 32-byte digest is committed directly alongside the Solana token transfer. Any auditor or regulator can reconstruct the canonical JSON from the Postgres audit log and independently verify the hash against the on-chain signature.
10. Dual Ledger Execution: Redis Lab Splits vs Solana Token-2022 Hooks
The platform implements a transparent dual-ledger abstraction:
- Lab Emulator Mode (
SOLANA_MODE=emulator): Operates over an ultra-fast Redis-backed token ledger. Used in local Docker Compose clusters and automated CI pipelines to execute instant token splits without devnet faucets or gas rate limits. - Live On-Chain Mode (
SOLANA_MODE=live): Dispatches atomic Solana SPL transactions usingtransfer_checked. Supports Anchor-based Token-2022 Transfer Hook programs for hardware royalty and protocol fee distribution. - Hardware Twins via Metaplex Bubblegum: Meters support an optional on-chain physical hardware identity minted as a compressed NFT (cNFT), linking physical serial numbers to Solana accounts without expensive account rent.
11. Live Browser Streaming: Ticket-Based Server-Sent Events (SSE)
Allowing browsers to connect directly to NATS JetStream would expose internal network credentials and complicate token revocation.
Instead, our standalone gateway (services/sse_gateway) serves a dedicated EventSource endpoint:
- Django issues a cryptographic, short-lived session ticket upon page render.
- Nginx proxies
/api/v1/stream/<meter-id>/withproxy_buffering off;andX-Accel-Buffering "no";. - The ASGI SSE gateway validates the ticket against Redis, subscribes to the specific meter's NATS subject, and streams real-time watt telemetry to the dashboard with sub-second latency.
12. Operations NOC & Verification: Leaflet Maps & Staff Trust Flow
To maintain regulatory compliance and zero-trust hardware boundaries, newly provisioned meters enter the network in a PROVISIONED state.
Telemetric data from unverified hardware is monitored in the operator NOC but strictly excluded from financial settlement. Only when an authorized staff member verifies physical installation on the feeder does the meter transition to ACTIVE status and enter the 5-second matching loop.
13. Deployment Runbook: Docker Compose & Hybrid Dev Environments
The entire localized DePIN stack boots with a single command via Docker Compose:
# Clone repository and configure environment
cp .env.example .env
export DJANGO_SUPERUSER_PASSWORD="adminpassword"
# Launch complete microservices stack (Postgres, NATS, QuestDB, Redis, Django, Workers)
docker compose up --build
# Open Web Dashboard
open http://localhost/
For rapid development, the hybrid setup starts data stores in Docker and runs Python 3.11 microservices locally under a virtual environment via dev_setup.sh.
14. Field Feasibility & Regulatory Alignment: The Road Ahead
Energy DePIN is rapidly transitioning from lab prototype to field reality. Key criteria dictate successful commercialization:
- DSO Collaboration: Partnering with distribution system operators to accept signed high-frequency telemetry as a valid billing register.
- Regulated Settlement Currencies: Utilizing compliant, licensed stablecoins (e.g., EURC / USDC) pegged to local electricity fiat currencies.
- Hardware Security Modules (HSMs): Moving Ed25519 keypairs into ATECC608 secure elements embedded directly on smart meter mainboards.
15. Architectural Summary & References
By separating physical power (public grid) from high-frequency time-series logging (QuestDB) and financial settlement (Solana + SHA-256 proofs), we achieved a resilient, legally viable energy sharing protocol capable of settling local power in near real time.
Directive 2018/2001 establishing legal definitions and rights for Citizen and Renewable Energy Communities.
High-performance memory-mapped columnar time-series ingestion over TCP socket 9009.
Distributed, ultra-low-latency event persistence engine supporting durable wildcard subscriptions.
Next-generation Solana token standard supporting transfer hook programs and custom fee logic.