# PLAIS Chain

`aisfor-chain` operates the canonical PLAIS Besu QBFT mainnet and retains the
earlier proof, reward, and simulation ledgers as segregated legacy services for
the AISFOR network:

- AISFOR
- AISTALK
- AISGROUP
- AISMALL

## Canonical Mainnet Status

- Chain ID: `20260718`
- Client and consensus: Hyperledger Besu `26.6.1`, QBFT
- Validator topology: four validator identities on four independently attested hosts
- Native asset: PLAIS Coin (`PLAIS`), 18 decimals
- Technical launch gate: 11/11 checks passed on 2026-08-04
- Current control state: `AWAITING_EXPLICIT_LAUNCH_APPROVAL`

The canonical chain is technically operational and producing blocks. Public
RPC, external deposits and withdrawals, operator signing, multichain transfers,
validator key delivery, and automatic client rollout remain locked until their
separate approval, security, legal, and exchange-integration gates are complete.

The legacy proof ledger API, node participant registry, point reward ledger,
and mock-chain records described below are not the canonical PLAIS asset ledger.
They remain available for historical compatibility, service proofs, and
controlled simulation only.

## Documents

- `docs/GLOBAL_CHAIN_PLAN.md`: implementation roadmap
- `docs/INTEGRATION_MAP.md`: service integration map
- `docs/WHITEPAPER.md`: PLAI Chain English whitepaper source
- `docs/WHITEPAPER_KO.md`: PLAI Chain Korean whitepaper source
- `docs/TOKEN_DISTRIBUTION_POLICY.md`: canonical allocation, circulation, lockup, and vesting policy
- `docs/TOKEN_DISTRIBUTION_POLICY_KO.md`: Korean distribution policy

## Port

Default port: `4317`

The port is intentionally outside common app ports such as `3000`, `5173`, `8000`, and `8080` to reduce conflict with existing services.

Override it with:

```powershell
$env:PORT=4318
npm start
```

## Install And Run

```powershell
npm install
npm start
```

Development mode:

```powershell
npm run dev
```

End-to-end callback test:

```powershell
npm run test:e2e-callback
```

This legacy integration test creates one test source row in each service,
submits proofs, finalizes simulation blocks, and verifies that each source row
stores `chainConfirmed=true`. It does not write to the canonical PLAIS asset
ledger.

## PM2 Operation

AISFOR-CHAIN is registered in PM2 as:

```powershell
pm2 status aisfor-chain
pm2 restart aisfor-chain
pm2 logs aisfor-chain
```

The current PM2 process list has been saved with `pm2 save`.

## Persistence

The mock ledger is persisted to:

```text
D:\aisfor-chain\data\ledger.json
```

This file stores proof ledger rows, mock chain transactions, point ledger entries, and sealed mock blocks so PM2 restarts do not wipe the current mock ledger.

## Mock Block Chain

AISFOR-CHAIN seals proof rows into mock blocks.

Each block contains:

- `height`
- `previousHash`
- `proofIds`
- `transactionIds`
- `merkleRoot`
- `blockHash`

Pending proofs can be mined manually:

```powershell
Invoke-RestMethod -Method Post -Uri http://localhost:4317/api/block/mine
```

The server also auto-mines when pending proofs reach `AISFOR_CHAIN_AUTO_MINE_SIZE`.
Default: `3`.

Node economy transactions, such as pledge, reward, and slash events, are also sealed into blocks as standalone mock chain transactions.

## Mock Validator Finality

Mock blocks can move from `PENDING_VALIDATION` to `FINALIZED_MOCK`.

Validator eligibility is based on node participant state:

- node status is `active` or `warning`
- locked pledge points are greater than or equal to `AISFOR_CHAIN_MIN_VALIDATOR_STAKE`

Finality flow:

1. Assign eligible validators to a block.
2. Validators submit `approve` or `reject` votes.
3. The block is finalized when approval threshold is met.
4. Approving validators receive a mock validator reward.

Development one-shot finalization:

```powershell
Invoke-RestMethod -Method Post -Uri http://localhost:4317/api/block/3/mock-finalize
```

## Node Economy Ledger

Node participants support mock economic events:

- `NODE_PLEDGE_LOCKED`
- `NODE_REWARD`
- `NODE_SLASH`

Each event updates the node balance fields, creates a node economy ledger row, creates a mock chain transaction, and stores the `txHash`.

Rewards and slashes also create point ledger entries:

- reward: positive points
- slash: negative points

## Chain Confirmation Callbacks

When a block reaches `FINALIZED_MOCK`, AISFOR-CHAIN creates callback events for proofs included in that block.

If a service callback URL is configured, AISFOR-CHAIN sends an HTTP `POST`.
If no callback URL is configured, the event is stored as `MOCK_DELIVERED` for development.

Callback URL environment variables:

- `AISFOR_CHAIN_CALLBACK_AISFOR`
- `AISFOR_CHAIN_CALLBACK_AISTALK`
- `AISFOR_CHAIN_CALLBACK_AISGROUP`
- `AISFOR_CHAIN_CALLBACK_AISMALL`

Optional callback secret variables:

- `AISFOR_CHAIN_CALLBACK_SECRET`
- `AISFOR_CHAIN_CALLBACK_SECRET_AISFOR`
- `AISFOR_CHAIN_CALLBACK_SECRET_AISTALK`
- `AISFOR_CHAIN_CALLBACK_SECRET_AISGROUP`
- `AISFOR_CHAIN_CALLBACK_SECRET_AISMALL`

AISFOR receiver example:

```powershell
$env:AISFOR_CHAIN_CALLBACK_AISFOR="http://localhost:5108/internal/aisfor-chain/callback"
$env:AISFOR_CHAIN_CALLBACK_AISTALK="http://localhost:5110/internal/aisfor-chain/callback"
$env:AISFOR_CHAIN_CALLBACK_AISGROUP="http://localhost:5118/internal/aisfor-chain/callback"
$env:AISFOR_CHAIN_CALLBACK_AISMALL="http://localhost:3700/internal/aisfor-chain/callback"
```

Callback payload includes:

- `chainConfirmed`
- `chainStatus`
- `blockHeight`
- `blockHash`
- `proofId`
- `externalProofId`
- `transactionId`
- `txHash`

## Endpoints

- `GET /health`
- `GET /api/proof`
- `GET /api/proof/stats/summary`
- `POST /api/proof`
- `GET /api/proof/:proofId`
- `GET /api/tx`
- `POST /api/tx`
- `GET /api/tx/:txId`
- `GET /api/block`
- `GET /api/block/stats/summary`
- `GET /api/block/pending/proofs`
- `POST /api/block/mine`
- `GET /api/block/verify`
- `GET /api/block/validators/eligible`
- `GET /api/block/:blockId`
- `GET /api/block/:blockId/votes`
- `POST /api/block/:blockId/assign-validators`
- `POST /api/block/:blockId/vote`
- `POST /api/block/:blockId/mock-finalize`
- `GET /api/contract`
- `GET /api/auth-status`
- `GET /api/node`
- `GET /api/node/economy`
- `GET /api/node/economy/stats`
- `GET /api/node/:nodeId`
- `POST /api/node/register`
- `POST /api/node/:nodeId/heartbeat`
- `POST /api/node/:nodeId/status`
- `POST /api/node/:nodeId/pledge`
- `POST /api/node/:nodeId/reward`
- `POST /api/node/:nodeId/slash`
- `GET /api/callback`
- `GET /api/callback/stats/summary`
- `GET /api/callback/:callbackId`
- `POST /api/callback/:callbackId/retry`
- `GET /admin`

## Example Proof

```powershell
Invoke-RestMethod -Method Post -Uri http://localhost:4317/api/proof -ContentType 'application/json' -Body '{
  "sourceService": "AISFOR",
  "proofType": "CHUNK_VERIFIED",
  "actorId": "aisfor-user-123",
  "deviceId": "pc-001",
  "nodeId": "node-abc",
  "externalProofId": "aisfor-proof-789",
  "idempotencyKey": "AISFOR:aisfor-proof-789",
  "chunkHash": "a3f7c2b8f0a1e6d4c9b5a8e7f6d5c4b3a2f1e0d9c8b7a6f5e4d3c2b1a0f9e8d7",
  "metadata": {
    "backupJobId": "backup-456"
  }
}'
```

## Proof Contract

AISFOR is the identity and account master. AISFOR-CHAIN does not create users or manage passwords. Every proof should use the AISFOR account id in `actorId`.

Supported `sourceService` values:

- `AISFOR`
- `AISTALK`
- `AISGROUP`
- `AISMALL`

Supported `proofType` values:

- `SYNC_BACKUP`
- `NODE_ONLINE`
- `CHUNK_STORED`
- `CHUNK_VERIFIED`
- `CHUNK_REPAIRED`
- `APP_ACTIVITY`
- `MESSAGE_CREATED`
- `GROUP_ACTIVITY`
- `MALL_ACTIVITY`
- `POINT_REWARD`
- `STORAGE_PROOF_LOG`
- `POINT_LEDGER_EVENT`
- `BLOCKCHAIN_PROOF_BUNDLE`

Common payload fields:

- `sourceService`: service that produced the proof
- `proofType`: normalized proof action
- `actorId`: AISFOR user id used across every AISFOR network service
- `targetId`: optional service object id such as chat, group, order, or backup job
- `deviceId`: AISFOR sync-client PC device id
- `nodeId`: AISFOR node participant id
- `externalProofId`: proof id from the source service
- `idempotencyKey`: duplicate prevention key from the source service
- `contentHash`: generic content hash
- `chunkHash`: encrypted chunk SHA256 hash
- `payloadHash`: source service payload hash
- `proofHash`: source proof hash
- `bundleHash`: AISFOR `BlockchainProofBundle.bundleHash`
- `merkleRoot`: backup or proof bundle root hash
- `metadata`: service-specific JSON data

## AISFOR First Anchor

AISFOR already has internal proof chains:

- `StorageProofLog.proofHash`
- `PointLedger.pointProofHash`
- `BlockchainProofBundle.bundleHash`

The first production-style integration should submit `BLOCKCHAIN_PROOF_BUNDLE` from AISFOR to AISFOR-CHAIN, using:

- `externalProofId`: AISFOR `BlockchainProofBundle.bundleKey`
- `contentHash`: AISFOR `BlockchainProofBundle.combinedRootHash`
- `bundleHash`: AISFOR `BlockchainProofBundle.bundleHash`
- `payloadHash`: AISFOR `BlockchainProofBundle.payloadHash`
- `idempotencyKey`: `AISFOR:BUNDLE:<bundleKey>`

## Service Authentication

Proof submission supports service authentication. Development mode is open by default. Before connecting real services, set:

```powershell
$env:AISFOR_CHAIN_AUTH_REQUIRED=1
$env:AISFOR_CHAIN_KEY_AISFOR="replace-with-a-secret"
```

Then submit proofs with:

- `X-AISFOR-SERVICE: AISFOR`
- `X-AISFOR-API-KEY: <service secret>`

`X-AISFOR-SIGNATURE` is also supported for HMAC-based requests.

## Next Connection Plan

1. AISFOR bundle submission to `POST /api/proof`: done.
2. Service authentication for trusted node participants: initial implementation done.
3. AISTALK, AISGROUP, and AISMALL proof producers: initial hooks done.
4. File-backed mock ledger persistence: done.
5. Mock block sealing with `previousHash`, `merkleRoot`, and `blockHash`: done.
6. Node participant pledge/reward/slash economy ledger with mock chain tx: done.
7. Mock validator assignment, vote ledger, and finality reward flow: done.
8. Webhook-style chain confirmation callback ledger: initial implementation done.
9. Add callback receiver APIs to AISFOR, AISTALK, AISGROUP, and AISMALL: done.
10. End-to-end chain confirmation callback test across all four services: passed.
11. Database-backed canonical ledger adapters and guarded migration tooling are implemented; the file-backed simulation ledger remains a segregated legacy archive.
12. The Besu QBFT network is the canonical PLAIS asset ledger; `services/mockChainAdapter.js` is retained only for legacy simulation compatibility.
