CPG-Core FSD Synchonizer

FSD — Core

A. Document controlA. Kiểm soát tài liệu

Doc IDCPG-FSD-CPG-Core_FSD_Synchonizer
VersionPhiên bản1.1
StatusTrạng tháiDraft
OwnerCPG BA / Architecture
AudienceĐối tượngBackend, QA, Product, Security, Load-test engineering, Ops
ClassificationPhân loạiInternal
Effective dateNgày hiệu lực01/12/2026
Related docs Core Index · BR/NFR Catalog

B. Version historyB. Lịch sử phiên bản

Version Date Author ChangesThay đổi
1.0 11/07/2026 Khoa Trinh Version 1.0, Initial FSD-Synchonizer (Doc02) from BR-03/BR-04
1.1 24/07/2026 Khoa Trinh Version 1.1: Added FP-CPG-BR-LED v1.1 cross-module coverage: versioned occurrence identity, transfer-mechanism matrix, failed/self/unsupported classification, provider provenance/disagreement, TRON internal-tx parity, deep-reorg freeze, distinct timestamps, durable backpressure, observability, and acceptance tests.

C. Table of contentsC. Mục lục

D. ContentD. Nội dung

1. Scope

The Sync module is the sole owner of on-chain deposit detection and finality gating for CPG. It answers: which transfers landed on watched addresses, whether those blocks are final, and when (and only when) ledger credits or un-credits may be posted - without tying the gateway to a single node provider, and without exposing the customer address list to third parties.

1.1 In scope

  • Block-scanning ingest (not per-address polling) for deposit detection
  • Phase 1 (TRON): credit engine ingests exclusively from solidified blocks (/walletsolidity* or equivalent solidified feeds)
  • Phase 2 (EVM - BSC / ETH / Polygon): configurable per-chain confirmation depth; reorg-driven booking rollback with full audit; no double-credit
  • Exactly-once credit per on-chain transfer (stable reference / FR3 handoff to ledger)
  • Catch-up block scanning and automated reconciliation after ingestion outages
  • UX intermediate state Ingested – Confirming vs usable/withdrawable balance increase only after finality
  • Multi-provider node adapters switched by configuration only; automatic primary → backup failover
  • Gateway-owned durable state: cursor, deduplication, address→VA mapping
  • Documented external endpoints, purposes, and request-volume estimates for provider plans
  • Ledger handoff: deposit_detected on finality; Phase 2 ledger transaction revert on reorg
  • Versioned occurrence/logical-transfer identity covering native, token, internal, batch, self-transfer, failed/reverted, and unsupported transfer mechanisms
  • Provider/block/receipt/raw-evidence provenance, provider-disagreement escalation, deep-reorg freeze signaling, and distinct chain/observed/finality timestamps

1.2 Out of scope

  • Ledger journal, Numscript templates, over-book prevention, and chart enforcement (FSD-Ledger)
  • Custody, HSM/MPC, xpub private-key material (Doc03 / A4 key management)
  • Deposit address issuance uniqueness (BR-02 → Ledger / account registry); Sync only consumes watched-address mappings
  • Merchant Portal / CRM UI screens (Sync may expose S2S observation APIs; UI is elsewhere)
  • Sweep, settlement, refund, and non-deposit money flows
  • Ledger business-effective ordering, period close, and database integrity controls (Ledger FSD v1.1)

1.3 Actors (S2S)

Actor Role
sync-service Scans chains, applies finality, owns cursor/dedup, posts credits / un-credits
Node providers Configured primary/backup JSON-RPC or java-tron HTTP; never own gateway state
account-service Publishes / serves watched deposit address → VA / merchant mapping
ledger-service Authoritative journal; accepts deposit_detected and revert
Platform ops Provider config, catch-up triggers, cursor inspection, alerts
Downstream UX (portal / transaction) May read observation status for Ingested – Confirming

Figure 1: Synchronizer Artifacts

1.4 Delivery phases

Phase Chains Finality model
Phase 1 tron (USDT/6, USDC/6) Solidified-only ingest; \~54–57s (19/27 SR; Appendix V4)
Phase 2 bsc, eth, polygon Configurable confirmation depth; reorg un-credit via ledger revert

Phase 1 acceptance does not depend on Phase 2 code. Shared contracts (cursor, dedup key, ledger reference, provider adapter interface) are designed once so Phase 2 plugs in without redesigning TRON.

2. Business Requirement

# Need (summary) Solution location in this FSD
BR-03 (§5.3) Fast credit without crediting unfinalized funds; EVM reorg-safe un-credit Flow §3; FEAT-FIN-*; UC-DEP / UC-REORG; Data §6
BR-04 (§5.4) No single-provider dependency; config switch; no address-list leak FEAT-PRV-01; FEAT-CUR-01; §7.11 external endpoints; §8.2
FP-CPG-BR-LED v1.1 Deep transfer identity, finality/reorg incident response, chain provenance, ordering timestamps, and evidence/observability §2.3; §3.9–§3.10; §4.4; §6.6; §7.13; §8.3

Hard blockers (must be proven in architecture + tests): BR-03 AC1, AC3, AC4; BR-04 AC1–AC3.
Ledger FR3 (idempotency) and FR10 (credit-finality) are enforced at Sync; ledger only accepts posts that Sync asserts as finalized (FSD-Ledger §2).

2.1 BR → FSD coverage matrix

ID Level Coverage in this FSD
BR-03 AC1 TRON solidified-only credit HARD FEAT-FIN-01; §3.3; UC-DEP-01; test: credit path never reads unsolidified tip
BR-03 AC2 EVM confirm depth + reorg rollback HARD (Phase 2) FEAT-FIN-02; §3.4; UC-REORG-01; configurable confirmations.{chain}
BR-03 AC3 Exactly-once credit (FR3) HARD FEAT-DED-01; FEAT-CRD-01; UC-IDM-01; reference \= tx identity
BR-03 AC4 Catch-up + reconciliation HARD FEAT-GAP-01; §3.6; UC-GAP-01
BR-03 AC5 Confirming UX vs withdrawable HARD FEAT-UX-01; §3.4 / §3.5; UC-UX-01
BR-04 AC1 Config-only provider switch HARD FEAT-PRV-01; UC-PRV-01
BR-04 AC2 Auto failover, no loss/dup HARD FEAT-PRV-01; FEAT-DED-01; UC-PRV-02
BR-04 AC3 Gateway owns cursor/dedup/mapping HARD FEAT-CUR-01; §6 Data Model
BR-04 AC4 Document external endpoints IMPORTANT §7.11 External endpoints catalog
BR-04 AC5 Provider SLA / certs / RPD estimate IMPORTANT §7.11 + Appendix refs V2, V9
FR3 (Ledger) Sync must not invent new reference HARD §3.7 Crash recovery; FEAT-CRD-01
FR10 (Ledger) Credit-finality owned by Sync HARD FEAT-FIN-01 / FEAT-FIN-02; ledger accepts finalized only

2.2 Verified reference anchors (from BR appendix)

Ref Relevance to Sync
V2 TronGrid free: 15 req/s + 100k req/day; throttling \~5 qps - prefer paid/portable providers for prod
V3 Event plugins help but still need gap scanning; Sync baseline is block scan
V4 TRON solidified ≈ 54–57s; no protocol reorg after solidification
V9 Chainstack / QuickNode: /walletsolidity, SOC 2 / ISO; block scan \~60k req/day ≈ 1.8M/month; no third-party TRON event-push

2.3 FP-CPG-BR-LED v1.1 cross-module coverage

BR-L Sync disposition Updated feature / section
L03 Sync owns versioned occurrence identity, receipt-local locators, internal transfer locators, transfer-mechanism classification, exclusion of failed/reverted transfers, self-transfer classification, and inbound logical-transfer rules. §3.9; FEAT-IDN-01; FEAT-MECH-01; §6.6
L05 TRON remains solidified-only. EVM model A (credit after configured finality) is the default. Deep reorg or canonical uncertainty freezes affected scope and enters incident recovery. §3.3–§3.4; §3.10; FEAT-DEEP-01
L06 Sync provides observation-to-credit lifecycle evidence, gap/replay status, provider provenance, and discrepancy/freeze signals. Full reconciliation equations remain Reconciliation-owned. FEAT-GAP-01; FEAT-PROV-01; FEAT-OBS-S01
L17 Sync records chain block time, observed time, finality time, and stable sequence/height context. Ledger owns business-effective and commit ordering. FEAT-TIM-01; §6.6
L18 Provider ID, block hash, receipt status, raw-evidence digest, disagreement policy, and TRON internal-transaction parity are required. FEAT-PROV-01; FEAT-PRV-02; FEAT-INT-01; §8.3
L22 Cursor/finality lag, credit latency, provider health/disagreement, quarantine, reorg, and replay metrics plus alert/dashboard/runbook are deliverables. FEAT-OBS-S01; §7.13
L23.5 Scanner and ledger-handoff events remain durable during ledger backpressure; no monetary observation is dropped or silently skipped. FEAT-BKP-S01

3. Flow

Sync never mutates ledger balances except via documented ledger APIs. Amounts and account addresses follow Formance notation as defined in FSD-Ledger (e.g. USDT/6 1000000).

3.0 System context


Figure 2: Synchronizer flow

3.1 Provider ingest and failover

Item Detail
Actor sync-service
Trigger Continuous poll / scan loop; health probe failures
Behavior Adapter selects primary from config. On timeout, 5xx, or consecutive error threshold, switch to backup without process redeploy. Resume from gateway-owned cursor, not provider memory.
Success Blocks continue to advance; no skipped finalized deposits; no duplicate observations for same (chain, tx_hash, log_index), no duplicate observations for the same versioned occurrence key
Failure Both providers down → pause advance, alert, retain cursor; catch-up on recovery (§3.6)

Portability rule (BR-04): TRON adapters call only standard java-tron surfaces (/wallet*, /walletsolidity*, optional gRPC equivalents). EVM adapters (Phase 2) call standard JSON-RPC (eth_getBlockByNumber, eth_getLogs, etc.). Provider-specific proprietary “address webhook” APIs are forbidden for detection (they would leak or require publishing the address list).

3.2 Block scan loop

Item Detail
Actor sync-service
Steps 1) Load watched-address set from gateway DB / account-service sync. 2) Fetch next block(s) from active provider at/behind finality tip. 3) Parse transfers (native + TRC20/ERC20). 4) Filter locally against the watched set. 5) Upsert deposit_observation. 6) Persist cursor.
Constraint Customer address list is never sent as a query filter to the provider
Throughput Sized to stay within provider plan (see §7.12); backpressure if lag grows

3.3 TRON finality (Phase 1) - solidified-only credit

Item Detail
Actor sync-service
Rule The credit path reads only solidified chain data. Tip / unsolidified blocks may be scanned for early ingested_confirming UX (§3.5) but must not call ledger deposit_detected.
Target latency \~1 minute end-to-end on TRON (solidified ≈ 54–57s + processing)
Ledger On solidification match: POST deposit_detected with reference \= on-chain transfer identity (FSD-Ledger §3.1)
Proof Architecture + tests must show credit engine never binds to unsolidified endpoints for booking

3.4 EVM finality and reorg (Phase 2)

Item Detail
Actor sync-service
Confirmations confirmations.bsc / confirmations.eth / confirmations.polygon - integers in config
Provisional When inclusion depth ≥ 1 (or product rule): status ingested_confirming (UX only)
Credit When depth ≥ configured threshold: POST deposit_detected; status credited; store ledger transaction_id
Reorg If block/tx disappears or amount/log changes before or after credit: mark reorged; if already credited, call ledger POST .../transactions/{id}/revert; prevent second credit for same logical transfer on replacement path using dedup + audit
Audit Observation row + ledger revert log must reconstruct who/when/why un-credited

3.5 Exactly-once credit and UX states

Observation status User-visible (allowed) Withdrawable / usable ledger balance
ingested_confirming Yes - “Ingested – Confirming” No increase
credited Yes - credited / available per product Yes (via ledger volumes)
reorged Yes - reversed / under review Prior credit reversed
ignored Ops only N/A

Idempotency key material: production reference \= canonical versioned occurrence_id; Idempotency-Key matches or deterministically derives from that identity. tx_hash remains provenance. Sync must never mint a new reference for the same inclusion-specific occurrence. Reorg/re-inclusion or an approved early-credit recovery uses a new, explicitly linked booking_attempt_id.

3.6 Catch-up and reconciliation

Item Detail
Trigger Process restart; provider outage; detected cursor lag vs solidified/final tip; ops force catch-up
Behavior From durable scan_cursor, scan forward until caught up; rate-limit to provider quotas
Reconciliation Periodic job: for a block-height window, re-fetch blocks, recompute expected observations vs DB; alert on missing/extra; repair by upsert + ledger replay with same reference
Success No permanent gaps; duplicates suppressed by unique key

3.7 Crash recovery contract

  1. Observe on-chain transfer; compute stable reference.
  2. Persist observation (at least ingested_confirming or pending credit) before or in the same transactional boundary as cursor advance where feasible.
  3. On finality, POST ledger with that reference / Idempotency-Key.
  4. If crash after ledger success but before local credited update: on restart, replay same reference → ledger idempotent hit; mark local credited.
  5. If crash before ledger success: replay POST with same reference → exactly one booking.

3.8 Correction path (Phase 2 reorg)

Un-credit is only via ledger transaction revert (append-only). Sync records reorged and links ledger_tx_id / revert_tx_id. No silent DELETE of ledger history.

3.9 Canonical occurrence and logical-transfer identity

Sync constructs a versioned inclusion-specific occurrence and a separate logical-transfer identity. The occurrence identifies exactly what appeared in a particular canonical block; the logical transfer supports controlled linkage without heuristic merging.

Transfer class mechanism Locator rule
EVM ERC-20/721 event evm_log Receipt-local matching-log ordinal; do not depend on a provider-global index.
EVM ERC-1155 batch item evm_erc1155_batch Receipt-local log ordinal + batch-item ordinal.
EVM internal/native trace evm_trace Canonical traceAddress plus trace type/version.
TRON TRC-20 event tron_log Receipt-local contract-event ordinal.
TRON internal transaction tron_internal Provider-verified internal_tx_id with parity checks.
Native top-level transfer native_tx Canonical top-level locator.

Proposed format: occurrence_id \= v1:{network}:{tx_hash}:{mechanism}:{locator}:{block_hash}. logical_transfer_id is separate. Different tx hashes are not merged heuristically; suspected replacement/replay relationships are recorded as reviewable links. Unsupported mechanisms are persisted in quarantine with a reason code rather than silently ignored.
Failed EVM receipts, reverted traces, rejected TRON internal transactions, zero-value/non-transfer artifacts, and invalid token contracts cannot create a credit. When both endpoints are watched, classify the movement as internal/self-transfer and do not create a customer deposit credit.

3.10 Deep reorg, provider disagreement, and incident freeze

  1. TRON booking uses solidified data only.
  2. EVM default model A: booking occurs only after configured finality/canonical checks. Model B early credit is disabled in v1 unless separately approved.
  3. If providers disagree on block hash, receipt status, transfer content, or finality, Sync does not credit. It records provider_disagreement, retries/quorum-checks, and escalates after the configured threshold.
  4. A reorg beyond the expected finality envelope, or invalidation of an already credited occurrence, creates an incident, signals Ledger write-layer freeze for the affected chain/asset/account scope, and performs append-only ledger revert when safe.
  5. If early-credit model B is ever enabled, un-credit and re-credit use distinct booking_attempt_id values linked to the same logical transfer; a new attempt does not overwrite the original occurrence.

4. Features

4.1 Detection and finality

FEAT-SCN-01 Block scanner

  • Continuous block-range fetch via provider adapter; parse native and token transfers; local address filter.
  • Acceptance: Deposits to watched addresses appear as observations; unwatched ignored; address list not present in outbound provider request params.
  • Phase: 1 (TRON) + 2 (EVM).

FEAT-FIN-01 TRON solidified gate

  • Credit engine bound exclusively to solidified data sources.
  • Acceptance: Integration/unit tests fail if unsolidified tip is used for deposit_detected; latency target \~1 minute documented in ops runbook.
  • Phase: 1.

FEAT-FIN-02 EVM confirmation depth + reorg un-credit

  • Per-chain configurable confirmations; reorg detection; ledger revert; no double-credit.
  • Acceptance: Simulated reorg fixtures reverse booking, leave audit trail, and reject duplicate credit of replaced tx.
  • Phase: 2.

FEAT-DED-01 Deduplication / exactly-once

  • Unique constraint on the versioned occurrence key (network, tx_hash, mechanism, locator, block_hash); ledger reference aligned to occurrence_id.
  • Acceptance: Replay of same transfer yields one observation and one ledger credit (idempotent hit).
  • Phase: 1+.

FEAT-UX-01 Confirming vs credited exposure

  • Observation API / events expose ingested_confirming before finality; Sync does not increase usable balance until credit.
  • Acceptance: UC-UX-01; withdrawable balance unchanged until credited.
  • Phase: 1 (optional early tip scan for confirming); 2 (required for EVM path).

4.2 Provider and state ownership

FEAT-PRV-01 Multi-provider adapter + config failover

  • Primary/backup endpoints and credentials via config/Vault; identical standard API surface; automatic failover; config-only switch mid-flight resumes from cursor.
  • Acceptance: UC-PRV-01, UC-PRV-02; no code change to swap provider URL/key.
  • Phase: 1+.

FEAT-CUR-01 Gateway-owned cursor

  • Durable scan_cursor per chain (and optional shard) in gateway DB; providers are stateless from CPG’s perspective.
  • Acceptance: Kill primary mid-scan; backup continues without rewind that causes dups or skip that causes permanent loss (catch-up allowed).
  • Phase: 1+.

FEAT-GAP-01 Catch-up + reconciliation

  • Resume from cursor after outage; scheduled reconcile window; alerts on mismatch.
  • Acceptance: UC-GAP-01; injected gap repaired within SLO.
  • Phase: 1+.

4.3 Ledger handoff

FEAT-CRD-01 Ledger credit handoff

  • On finality: POST /v2/cpg/transactions with template deposit_detected, vars per FSD-Ledger §7.3; metadata includes chain, tx_hash, asset, network.
  • Acceptance: VA balance increases once; duplicate POST is idempotent.
  • Phase: 1+.

FEAT-UNC-01 Ledger un-credit on reorg (Phase 2)

  • Call ledger revert for credited deposits invalidated by reorg; update observation.
  • Acceptance: UC-REORG-01.
  • Phase: 2.

4.4 Identity, provenance, integrity, and backpressure features

FEAT-IDN-01 Versioned occurrence identity

  • Unique constraint on (network, tx_hash, mechanism, locator, block_hash) and deterministic occurrence_id encoding version.
  • Cross-service test vectors ensure Sync, Ledger metadata, and reconciliation artifacts refer to the same occurrence.

FEAT-MECH-01 Transfer-mechanism matrix and quarantine

  • Versioned per-chain matrix defines supported native/token/internal/batch mechanisms and required provider/node capabilities.
  • Unsupported or malformed candidates are quarantined with reason code/evidence; silent drop is prohibited.
  • Failed/reverted/rejected and self-transfer cases have explicit classifications.

FEAT-PROV-01 Chain-data provenance

  • Every observation records provider ID/slot, endpoint class, block hash/height, receipt status, finality policy/version, raw-evidence digest, and optional immutable evidence-object URI.
  • Ledger receives the minimum provenance metadata/digest required for traceability.

FEAT-PRV-02 Provider disagreement and quorum escalation

  • Config defines compare/quorum rules for critical facts. Disagreement blocks credit and creates an auditable incident/escalation.
  • Provider failover alone must not convert disagreement into acceptance.

FEAT-INT-01 TRON internal-transaction retention/parity

  • Production providers/nodes must expose/store required internal-transaction evidence. Startup/readiness verifies capability.
  • Parity test compares internal transaction identity/content across primary and backup providers before enabling credit for that mechanism.

FEAT-DEEP-01 Deep-reorg response

  • Beyond-finality reorg/canonical uncertainty triggers affected-scope freeze, incident workflow, evidence preservation, and controlled ledger revert/recovery.

FEAT-TIM-01 Distinct chain timestamps

  • Record chain_block_time, observed_at, finality_at, and scan/height sequence separately. No state transition is ordered solely by wall-clock timestamp.

FEAT-BKP-S01 Durable scanner/credit backpressure

  • Observations and credit tasks persist before cursor advancement. If Ledger throttles or is unavailable, the durable queue retains tasks and cursor state cannot falsely indicate unrecoverable completion.
  • Overload/failover tests prove zero lost monetary observations and idempotent replay.

FEAT-OBS-S01 Sync observability handoff

  • Metrics: scan/cursor/finality lag, observation-to-credit latency, provider health/failover/disagreement, quarantine count/reasons, replay/idempotency results, deep-reorg/freeze signals, ledger queue depth/age, and raw-evidence storage failures.
  • Alert rules, dashboard, incident runbook, catch-up runbook, and provider-capability checklist are acceptance artifacts.

5. Usecases

Detailed use-case catalog for this module is maintained under 08_UC:Catalog use case chi tiết của module này được quản lý tại 08_UC:

6. Data Requirement (Data Model)

chain_observation

Field Type Required Description
id Integer No Primary key
chain String Yes Blockchain slug (e.g. bsc, ethereum, polygon, tron)
network String Yes Network label / chain network
tx_hash String Yes Related blockchain transaction hash
log_index String Yes Log index
from_address String Yes From address
to_address String Yes To address
asset String Yes Invoice settlement asset symbol
amount_minor String Yes Amount minor
block_number Integer Yes Block number
observed_at DateTime Yes Observed at

outbox

Field Type Required Description
id Integer No Primary key
event_id String Yes Event id
topic String Yes Topic
partition_key String Yes Partition key
body JSON Yes Body
created_at DateTime Yes Created timestamp (UTC)
published_at DateTime No Published at

7. Endpoints and Payloads

Method Route Description Request Response
GET /api/v1/sync/health Health / job status {} {status}
POST /api/v1/sync/{transaction_hash} Trigger sync for tx hash {transaction_hash} {result}

8. Security

8.1 Application security (Doc03)

Fleet-wide application security is defined in Doc03 - Application Security.
Apply as baseline for the sync-service:

Doc03 area Relevance
Part A trust zones / identity planes Money-movement zone; Sync is S2S only
G1–G9 General controls Auth patterns, secrets (Vault), logging, SDLC, S2S discipline
APPSEC-ID-09 Ledger client Bearer API key (pkg/ledgerclient)
APPSEC-ID-13 Secrets injection (Vault CSI) for provider keys + ledger key
APPSEC-ID-16 Input validation on ops APIs
B0 inventory / S8 money path Sync listed as money-movement; outbound timeouts required
Logging / PII No API keys, tokens, or bulk customer address exports in logs

8.2 Specific security (Sync module)

Control Requirement Status / notes
Address-list privacy Detection via block scan + local filter; never pass customer address list to third-party node APIs BR-04; FEAT-SCN-01
Provider portability Standard APIs only; switch via config/Vault; no vendor lock-in in credit path BR-04 AC1
Failover integrity Auto backup; cursor/dedup in gateway DB prevent loss and duplicates BR-04 AC2–AC3
Finality before usable credit TRON solidified-only booking; EVM threshold before deposit_detected BR-03 AC1–AC2, AC5
Reorg audit (Phase 2) Ledger revert + observation reorged; reconstructible trail BR-03 AC2
Exactly-once Unique observation key + ledger reference / Idempotency-Key BR-03 AC3; FR3
AuthN ops APIs No public browser access; Bearer/mTLS; least-privilege ops vs read Doc03 CC6
Ledger AuthN Only via LEDGER_API_KEY / approved client APPSEC-ID-09
Secrets Provider and ledger credentials via Vault; never commit or log G4 / APPSEC-ID-13
Cursor integrity Treat cursor/dedup DB as high-integrity; restrict write roles BR-04 AC3

8.3 Provider integrity, evidence, and incident controls

Control v1.1 requirement
Evidence authenticity Canonicalize and hash raw block/receipt/log/trace evidence; protect object-store evidence from overwrite/deletion according to retention policy.
Provider disagreement Credentials/failover do not imply trust. Critical disagreement blocks credit and requires quorum/escalation.
Transfer-mechanism capability Startup/readiness verifies enabled provider/node capabilities, including TRON internal-transaction retention when used.
Freeze authorization Sync may request a scoped incident freeze with evidence, but Ledger/ops policy authorizes and enforces the control state.
Identity normalization Normalization/version test vectors are reviewed as security-sensitive code; changing the identity version requires migration and collision analysis.
Data minimization Do not send the watched-address list to providers; evidence/logs avoid unnecessary customer identifiers.

E. ReferencesE. Tham chiếu