Blockchain-Anchored Crowd Sensing FastAPI · Solidity · Hardhat · Python · Merkle Trees
ChainSense is a hybrid off-chain/on-chain prototype for mobile crowd sensing. Signed sensing records go to a FastAPI aggregator, which keeps them encrypted off-chain, groups them into batches, and anchors a 32-byte commitment per batch in a Solidity contract. Merkle batching lets an authorized reader prove that one record belongs to a committed batch without putting raw sensing data on-chain.
- Authenticated input: clients sign every record with a secp256k1 key (EIP-712). Only registered clients are accepted.
- Replay protection: nonces are persisted per client, and timestamps must fall inside a ±300 s window.
- Encrypted at rest: payloads, salts and signatures are sealed with AES-256-GCM. The key lives outside the repo.
- Unambiguous, salted Merkle tree: domain-separated leaves and nodes, no duplicate-leaf ambiguity, strict proof checks.
- Crash-safe commits: persistent batch IDs and a persisted signed-transaction state machine with recovery.
- Hardened contract: authorized aggregators only, write-once batch IDs, validated inputs.
- Benchmark modes: direct per-record commits, flat batch-hash commits, and Merkle batch commits.
| Actor | Can | Must not be able to |
|---|---|---|
| Network attacker / unregistered device | Send arbitrary HTTP requests; replay captured requests | Inject records, replay a captured record (even after a restart), or read records/proofs |
| Registered client | Submit its own signed records | Submit as another client, reuse a nonce, or backdate/postdate beyond the window |
| Other chain account | Send transactions to BatchCommit |
Commit, overwrite or pre-empt a batch |
| Observer of chain, DB file, logs or the metrics CSV | Read everything there | Learn payloads, or guess low-entropy readings from stored or on-chain hashes |
| Holder of the DB file without the data key | Modify rows | Change a record undetected (GCM tag + position-bound AAD + on-chain root) |
| Crash, RPC timeout, dropped or reverted transaction | Interrupt any step | Lose an accepted record or batch, commit a batch twice, or mark a wrong on-chain value as confirmed |
Trusted: the aggregator process and its host, the data-key file, the reader token, the aggregator's chain key, and the contract owner key. Out of scope: truthfulness of sensor readings, a malicious aggregator operator, client key theft on the device, and availability/DoS.
client (secp256k1 key) aggregator chain
────────────────────── ────────── ─────
GET /domain ───────────────────────────────▶ chain_id, contract, aggregator address
sign EIP-712 SensingRecord{clientId, sha256(payload), timestampMs, nonce, aggregator}
(domain: name, version, chainId, verifyingContract)
POST /submit ──────────────────────────────▶ 1 schema check (no input echoed on error)
2 client registered? → 401 unknown client
3 recover signer == registered → 401 invalid signature
4 |now − ts| ≤ 300 s → 400 stale or future timestamp
5 ONE SQLite transaction:
insert (client, nonce) → 409 nonce already used
place in OPEN batch (leaf_index)
insert record: salted leaf hash +
AES-GCM(payload‖salt‖signature, AAD=client,nonce,batch,index)
if full: compute commitment, state SEALED
6 committer: sign tx → persist SIGNED(raw tx, hash, nonce)
→ broadcast → receipt → read slot ───────▶ commitBatch(id, hash32, size, mode)
→ CONFIRMED only if hash, size, mode match ◀─ getBatch(id)
POST /verify, GET /batches/{id}/proof
(Authorization: Bearer <reader token>) ──▶ rebuild tree from stored leaves, check root,
size and mode against chain, decrypt + verify leaf
Leaf and commitment encoding (crypto/merkle.py, crypto/records.py):
record = len‖"chainsense.record.v1" ‖ len‖client_id ‖ len‖canonical_json(payload) ‖ len‖uint64(ts_ms) ‖ len‖uint256(nonce) ‖ len‖sig65leaf = SHA256(0x00 ‖ salt32 ‖ record)andnode = SHA256(0x01 ‖ L ‖ R). An odd node is promoted, never paired with itself.- Flat-hash mode:
SHA256(0x02 ‖ uint32(count) ‖ leaf_0 ‖ … ‖ leaf_n-1). Direct mode commits its single salted leaf. - Verifiers must supply
leaf_count. An out-of-range index or a proof of the wrong length is rejected.
Batch states (servers/storage.py, servers/committer.py): OPEN → SEALED → SIGNED → CONFIRMED. If a transaction reverts while the slot is still empty, the batch goes back to SEALED and is re-signed, up to MCS_MAX_COMMIT_ATTEMPTS, then FAILED. If the slot holds a different commitment, the batch becomes CONFLICT. Recovery runs at startup and after every sealed batch:
- A transaction with a receipt is finalized.
- A transaction still pending in the mempool is waited on and never re-sent.
- An unknown transaction has its same signed bytes re-broadcast.
- If the transaction's nonce was used by another transaction, the batch is re-signed.
- A revert on a filled slot leads to a re-read of the slot.
Batch IDs come from one SQLite AUTOINCREMENT sequence shared by every mode, so they are never 0 and never reused, including across restarts.
All keys stay out of the repository. data/, keys/, *.db, *.key and .env are gitignored, and the scripts refuse paths inside the repo.
- Data key (AES-256-GCM):
python scripts/gen_data_key.py ~/.config/chainsense/data.key # 0600, 64 hex chars export MCS_DATA_KEY_FILE=~/.config/chainsense/data.key
- Reader token for
/verifyand/batches/{id}/proof. If it is unset, all reads are refused.export MCS_READER_TOKEN=$(python -c "import secrets;print(secrets.token_urlsafe(32))")
- Aggregator chain key (
MCS_PRIVATE_KEY): the account that sendscommitBatch. The contract owner must authorize it:Hardhat's published dev keys are refused unless the RPC host iscd blockchain && npx hardhat node # terminal 1 MCS_AGGREGATOR_ADDRESS=0x<aggregator address> npx hardhat run scripts/deploy.js --network localhost
localhost/127.0.0.1/::1and the chain ID is 31337 (servers/devkeys.py). - Client keys: each client gets its own secp256k1 key. Only the address is stored on the server.
python scripts/register_client.py --count 20 # keys → ~/.config/chainsense/clients/<id>.key (0600)
python -m venv .venv && .venv/bin/pip install -r requirements.txt pytest httpx
(cd blockchain && npm ci && npx hardhat compile)
# configure .env from .env.example (contract address, aggregator key, data key path, reader token)
uvicorn servers.aggregator:app --port 8000
python -m clients.multi_client_runner # signs with the registered keys
curl -X POST -H "Authorization: Bearer $MCS_READER_TOKEN" "http://127.0.0.1:8000/verify?batch_id=1&record_index=0"python -m pytest tests -q # starts its own Hardhat node on a free port for chain tests
(cd blockchain && npx hardhat test) # contract tests on Hardhat's EVMThe service-level tests use an in-memory FakeChain with the contract's write-once semantics, because they need to be fast and to inject faults. Contract, recovery, crash-point, plaintext-on-chain and end-to-end tests run against a real local Hardhat node.
python benchmark_methods.py --rpc http://127.0.0.1:8547 was run on 2026-11-26 against a freshly deployed hardened contract on a local Hardhat node (chain 31337). It used 2,000 synthetic records per mode and batch size 20. Every record went through the full pipeline: signing, verification, encryption, salted leaves, persistent batches and the committer. Raw per-transaction data is in logs/benchmarks/benchmark_results.csv, which holds only numeric metrics: no records, salts, hashes or keys.
| Mode | Transactions | Records | Total gas | Gas per record |
|---|---|---|---|---|
| Direct | 2,000 | 2,000 | 201,277,112 | 100,638.56 |
| Flat batch hash (batch size 20) | 100 | 2,000 | 10,061,720 | 5,030.86 |
| Merkle batch (batch size 20) | 100 | 2,000 | 10,061,732 | 5,030.87 |
Previous run, on the unhardened contract: direct 143,510.46, flat-hash 7,177.91 and Merkle 7,179.10 gas per record.
- Why gas fell: the hardened contract packs each batch into 2 storage slots. It no longer stores a redundant
batchIdor a stringmode, andmodeis auint8. This outweighs the two extra storage reads it now does (authorization and the write-once check). - Direct-mode outlier: the most expensive transaction was the first one (117,721 gas), which sets
totalBatchesfrom zero to nonzero. The median was 100,633. - Savings: Merkle batching cut gas per record by 95.0% compared with direct commits, about the same percentage as before. Merkle and flat-hash cost the same within 12 gas in total; the difference comes from calldata zero bytes in the random commitments. Merkle's benefit is per-record inclusion proofs.
- Caveat: these numbers come from a local Hardhat network with synthetic records. They are not public-chain fees and not a real sensor deployment.
- Trusted aggregator: the aggregator sees plaintext while ingesting and holds the data key. A compromised aggregator host can read all records and can refuse or reorder submissions. Commitments give tamper evidence after commitment, not censorship resistance.
- Single shared reader token: reads are all-or-nothing behind one bearer token. There are no per-client or per-record access rights, no token rotation tooling and no TLS termination. Run behind HTTPS.
- Metadata leaks: client ID, nonce, timestamp, batch position and ciphertext length are stored in clear. On-chain, the batch size, mode, time and aggregator address are public.
- Data key handling: one static key with no rotation or KMS/HSM. The key file permissions (0600) are set on creation but not checked when loaded.
- Canonical JSON: payload hashing uses Python's canonical JSON (sorted keys, compact, no NaN). Clients written in other languages must produce identical bytes, floats in particular.
- Clock skew and nonce table: the ±300 s window assumes roughly synced client clocks. The nonce table grows forever (no pruning).
- Same-hash pre-emption: confirmation requires a matching hash, size and mode. If another authorized aggregator wrote the identical commitment first, it would also count as confirmed. Only owner-approved aggregators can write, so this is accepted.
- One database per contract: batch IDs are unique within one database. If a fresh database points at a contract that already holds commitments, the batches become
CONFLICTinstead of being overwritten. SetMCS_BATCH_ID_BASEin that case. - Single process: recovery and nonce serialization assume one aggregator process per chain account. Several committer threads in one process are tested; several processes sharing one key are not supported.
- Unfinished parts: the contract has no upgrade or pause mechanism and its ownership is a single EOA. Sensor truthfulness, Sybil resistance in client registration, and the adaptive batching design direction are not implemented.
Results are from the final run on 2026-11-26: python -m pytest tests -v gave 133 passed, and npx hardhat test gave 12 passing. Contract tests are in blockchain/test/BatchCommit.test.js; all other tests are in tests/.
| Weakness | Fix | Test(s) | Result |
|---|---|---|---|
| Anyone could commit | onlyAggregator allow-list managed by the owner |
rejects an unauthorized commit, rejects commits after the aggregator is revoked, only lets the owner manage aggregators (Hardhat); test_unauthorized_commit_rejected_on_real_chain |
Pass |
| Batches could be overwritten / duplicate IDs | Write-once slot, BatchAlreadyCommitted |
rejects overwriting an existing batch ID (duplicate ID) (Hardhat); test_overwrite_and_duplicate_id_rejected_on_real_chain |
Pass |
| Zero hash / zero size / invalid mode accepted | Custom-error checks; uint8 mode 1–3; batch ID ≠ 0; direct mode size = 1 |
rejects a zero commit hash, rejects a zero batch size, rejects invalid modes, rejects batch ID 0, rejects a direct-mode batch whose size is not 1 (Hardhat) |
Pass |
| Batch IDs in memory only; direct mode always 0 | SQLite AUTOINCREMENT sequence shared by all modes |
test_direct_mode_batch_ids_nonzero_and_unique, test_batch_ids_persist_across_restarts_and_modes, test_batch_id_base_configurable |
Pass |
| Failed or timed-out transaction lost or duplicated a batch | Signed tx persisted before broadcast; pending-aware recovery; same-bytes rebroadcast; revert → re-read slot; confirm only if hash, size and mode match | test_crash_between_state_changes[after_sign, after_persist_signed, after_broadcast, after_receipt], test_crash_after_seal_before_send, test_receipt_timeout_then_recovery_without_resend, test_dropped_transaction_is_rebroadcast, test_resend_that_reverts_on_filled_slot_rereads_slot, test_mismatching_onchain_slot_is_conflict_not_confirmed[×3], test_reverted_transaction_is_retried, test_gives_up_after_max_attempts, test_chain_failure_does_not_lose_accepted_record |
Pass |
| Account nonce races under concurrency | tx_lock around nonce allocation + sign + persist + broadcast; compare-and-set SEALED→SIGNED |
test_concurrent_commits_serialize_account_nonces |
Pass |
| Non-atomic batching; partial batch lost on restart | Record placement and sealing in one BEGIN IMMEDIATE transaction; OPEN batches persisted with their target size |
test_concurrent_records_assigned_atomically, test_partial_batch_survives_restart, test_partial_batch_keeps_its_target_size_after_config_change, test_store_failure_rolls_back_everything[after_nonce, after_record, after_seal, before_commit] |
Pass |
Signatures never checked (dummy_signature) |
EIP-712 secp256k1 over client ID, payload hash, timestamp, nonce, aggregator, chain ID, contract; registered clients only | test_invalid_signature_rejected, test_garbage_signature_rejected, test_dummy_signature_rejected, test_signature_from_other_registered_client_rejected, test_signature_covers_field[×3], test_signature_covers_client_id, test_signature_bound_to_domain[chain_id, aggregator, contract], test_malformed_submission_rejected[×8] |
Pass |
| Unknown clients accepted | Client registry (address per client ID) | test_unknown_client_rejected |
Pass |
| Replayed records accepted | Unique (client_id, nonce) in the same DB transaction as the record |
test_replayed_record_rejected, test_same_nonce_new_payload_still_rejected, test_same_nonce_different_clients_allowed |
Pass |
| Stale or future timestamps accepted | ±300 s window (configurable) | test_stale_timestamp_rejected, test_future_timestamp_rejected, test_timestamp_inside_window_accepted |
Pass |
| Replay possible after restart | Nonces persisted in SQLite | test_replay_rejected_after_restart |
Pass |
| Concurrent duplicate submissions | DB unique constraint under BEGIN IMMEDIATE |
test_concurrent_duplicate_submissions_accept_exactly_one |
Pass |
| Failed request could burn a nonce or leave partial rows | All checks before the transaction; all-or-nothing transaction | test_invalid_signature_does_not_consume_nonce, test_stale_request_does_not_consume_nonce, test_store_failure_rolls_back_everything[×4] |
Pass |
| Payloads stored or logged in plaintext | AES-256-GCM sealing (payload, salt, signature) with position-bound AAD; no payloads in logs or 422 bodies | test_plaintext_absent_from_database, test_plaintext_absent_from_logs |
Pass |
| Raw data on-chain | Only commitBatch(uint256, bytes32, uint256, uint8) |
test_plaintext_absent_from_chain |
Pass |
| Records and proofs readable without authorization | Bearer token (constant-time compare); reads disabled if unset | test_unauthorized_reads_rejected[×3], test_reads_disabled_without_configured_token, test_authorized_read_returns_verifiable_record |
Pass |
| Tampered ciphertext undetected | GCM tag + AAD; verify reports an integrity failure | test_tampered_ciphertext_detected, test_ciphertext_swapped_between_rows_detected, test_wrong_data_key_cannot_decrypt |
Pass |
| Keys could live in the repo | Data-key writer and loader, and the client-key writer, refuse repo paths; files created 0600; gitignore | test_data_key_inside_repo_refused |
Pass |
| Hardhat dev keys usable on any chain | Host check before network access, then chain-ID check, in client, deployer and benchmark | test_dev_keys_refused_off_local_chain[×5], test_chain_client_refuses_dev_key_for_remote_rpc, test_deploy_refuses_dev_key_for_remote_rpc, test_benchmark_refuses_non_local_rpc, test_dev_keys_match_hardhat_accounts |
Pass |
| Low-entropy values guessable from hashes | 32-byte random salt per leaf, stored encrypted | test_low_entropy_value_not_guessable_from_leaf, test_salting_hides_low_entropy_values |
Pass |
| Ambiguous leaf encoding | Length-prefixed, fixed-width record encoding | test_record_encoding_is_unambiguous |
Pass |
| No leaf/node domain separation | 0x00 leaf / 0x01 node / 0x02 flat prefixes, raw 32-byte children |
test_leaf_and_node_use_distinct_prefixes, test_internal_node_cannot_be_presented_as_leaf |
Pass |
Duplicate-leaf ambiguity ([a,b,c] = [a,b,c,c]) |
Odd-node promotion; leaf count stored and checked | test_duplicate_last_leaf_changes_root, test_phantom_duplicate_index_is_rejected, test_odd_levels_promote_instead_of_duplicate[×7], test_wrong_leaf_count_rejected |
Pass |
| Out-of-range index / wrong proof length accepted | Range check against leaf count; exact expected proof length | test_out_of_range_index_rejected[×5], test_index_wraparound_rejected, test_wrong_proof_length_rejected, test_malformed_proof_element_rejected |
Pass |
| Tampered proofs or stored leaves | Recompute against on-chain root | test_tampered_proof_element_rejected, test_tampered_stored_leaf_hash_detected, test_verify_rejects_record_changed_after_tree_creation |
Pass |
| Flat-hash mode unsalted and ambiguous | Same salted leaves + count prefix | test_flat_hash_is_salted_and_count_bound, test_flat_hash_mode_uses_salted_unambiguous_leaves |
Pass |
| Batches and proofs lost on restart | All state in SQLite; proofs rebuilt from stored leaves and checked against the chain | test_end_to_end_verification_after_restart, test_partial_batch_survives_restart |
Pass |
| On-chain mismatch checks (migrated) | Verify compares root, size and mode with the chain | test_verify_rejects_missing_blockchain_commitment, test_verify_rejects_on_chain_root_mismatch, test_verify_rejects_on_chain_batch_size_mismatch, test_verify_rejects_on_chain_mode_mismatch, test_verify_reports_chain_outage, test_verify_rejects_unconfirmed_batch |
Pass |
| Original suite (migrated, all assertions kept) | — | test_stats_starts_empty, test_verify_rejects_invalid_batch_id, test_verify_rejects_invalid_record_index, test_verify_rejects_non_merkle_mode, test_verify_accepts_valid_merkle_proof, test_batch_size[1, 2, 3, 5, 20, 21, 100] |
Pass |
blockchain/ BatchCommit.sol, Hardhat tests, deploy script
clients/ Signing simulated clients
crypto/ Record encoding, salted Merkle tree, EIP-712 signing, AES-GCM sealing
servers/ FastAPI app, service, SQLite store, committer, chain client, dev-key guard
scripts/ Data-key generation and client registration
tests/ pytest suite (FakeChain + real Hardhat node)
logs/benchmarks/ Recorded benchmark results (metrics only)
See LICENSE.