# central-ledger

[![Git Commit](https://img.shields.io/github/last-commit/mojaloop/central-ledger.svg?style=flat)](https://github.com/mojaloop/central-ledger/commits/main)
[![Git Releases](https://img.shields.io/github/release/mojaloop/central-ledger.svg?style=flat)](https://github.com/mojaloop/central-ledger/releases)
[![Docker pulls](https://img.shields.io/docker/pulls/mojaloop/central-ledger.svg?style=flat)](https://hub.docker.com/r/mojaloop/central-ledger)
[![Npm Version](https://img.shields.io/npm/v/@mojaloop/central-ledger.svg?style=flat)](https://www.npmjs.com/package/@mojaloop/central-ledger)
[![NPM Vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/@mojaloop/central-ledger.svg?style=flat)](https://www.npmjs.com/package/@mojaloop/central-ledger)
[![CircleCI](https://circleci.com/gh/mojaloop/central-ledger.svg?style=svg)](https://app.circleci.com/pipelines/github/mojaloop/central-ledger)

The central ledger is a series of services that facilitate clearing and settlement of transfers between DFSPs, including the following functions:

- Brokering real-time messaging for funds clearing
- Maintaining net positions for a deferred net settlement
- Propagating scheme-level and off-transfer fees

The following documentation represents the services, APIs and endpoints responsible for various ledger functions.

## Contents

- [central-ledger](#central-ledger)
  - [Contents](#contents)
  - [Running Locally](#running-locally)
  - [Configuration](#configuration)
    - [Environment variables](#environment-variables)
  - [API](#api)
  - [Logging](#logging)
  - [Tests](#tests)
  - [Development environment](#development-environment)
  - [Auditing Dependencies](#auditing-dependencies)
  - [Container Scans](#container-scans)
  - [Automated Releases](#automated-releases)
    - [Potential problems](#potential-problems)

## Docker Image

### Official Packaged Release

This package is available as a pre-built docker image on Docker Hub: [https://hub.docker.com/r/mojaloop/central-ledger](https://hub.docker.com/r/mojaloop/central-ledger)

### Build from Source

You can also build it directly from source: [https://github.com/mojaloop/central-ledger](hhttps://github.com/mojaloop/central-ledger)

However, take note of the default argument in the [Dockerfile](./Dockerfile) for `NODE_VERSION`:

```dockerfile
ARG NODE_VERSION=lts-alpine
```

It is recommend that you set the `NODE_VERSION` argument against the version set in the local [.nvmrc](./.nvmrc).

This can be done using the following command: `npm run docker:build`

Or via docker build directly:

```bash
docker build \
  --build-arg NODE_VERSION="$(cat .nvmrc)-alpine3.19" \
  -t mojaloop/ml-api-adapter:local \
  .
```

## Running Locally

Please follow the instruction in [Onboarding Document](Onboarding.md) to setup and run the service locally.

## Configuration

### Environment variables

The Central Ledger has many options that can be configured through environment variables.

| Environment variable | Description | Example values |
| -------------------- | ----------- | ------ |
| CLEDG\_DATABASE_URI   | The connection string for the database the central ledger will use. Postgres is currently the only supported database. | postgres://\<username>:\<password>@localhost:5432/central_ledger |
| CLEDG\_PORT | The port the API server will run on. | 3000 |
| CLEDG\_ADMIN_PORT | The port the Admin server will run on. | 3001 |
| CLEDG\_HOSTNAME | The URI that will be used to create and validate links to resources on the central ledger.  | <http://central-ledger> |
| CLEDG\_ENABLE\_BASIC_AUTH | Flag to enable basic auth protection on endpoints that require authorization. Username and password would be the account name and password. | false |
| CLEDG\_ENABLE\_TOKEN_AUTH | Flag to enable token protection on endpoints that require authorization. To create a token, reference the [API documentation](API.md). | false |
| CLEDG\_LEDGER\_ACCOUNT_NAME | Name of the account setup to receive fees owed to the central ledger. If the account doesn't exist, it will be created on start up. | LedgerName |
| CLEDG\_LEDGER\_ACCOUNT_PASSWORD | Password of the account setup to receive fees owed to the central ledger.  | LedgerPassword |
| CLEDG\_ADMIN_KEY | Key used for admin access to endpoints that require validation. | AdminKey |
| CLEDG\_ADMIN_SECRET | Secret used for admin access to endpoints that require validation. Secret also used to sign JWTs used for Admin API. | AdminSecret |
| CLEDG\_TOKEN_EXPIRATION | Time in milliseconds for Admin API tokens to expire. | 3600000 |
| CLEDG\_EXPIRES_TIMEOUT | Time in milliseconds to determine how often transfer expiration process runs. | 5000 |
| CLEDG\_AMOUNT__PRECISION | Numeric value used to determine precision recorded for transfer amounts on this ledger. | 10 |
| CLEDG\_AMOUNT__SCALE | Numeric value used to determine scale recorded for transfer amounts on this ledger. | 2 |

### ERROR_HANDLING_AJV_JOI_PARITY

**Set `ERROR_HANDLING_AJV_JOI_PARITY=true` for this service.**

The Settlement API (`src/settlement`) was migrated from `hapi-openapi` (joi request validation) to `openapi-backend` (ajv), and `@mojaloop/central-services-error-handling` was updated from 13.1.7 to 13.2.0. 13.2.0 makes the ajv mapping that matches joi's opt-in behind this environment variable ([central-services-error-handling#216](https://github.com/mojaloop/central-services-error-handling/issues/216)), so leaving it unset changes the FSPIOP error code this service returns for requests that used to fail joi validation:

| ajv keyword (openapi-backend) | unset / `false` | `ERROR_HANDLING_AJV_JOI_PARITY=true` | joi (before the migration) |
| ----------------------------- | --------------- | ------------------------------------ | -------------------------- |
| `enum`, `const`, `format`, `pattern` | 3100 Generic validation error | **3101 Malformed syntax** | 3101 Malformed syntax |
| `type` | 3101 Malformed syntax | 3101 Malformed syntax | 3101 Malformed syntax |
| `required` | 3102 Missing mandatory element | 3102 Missing mandatory element | 3102 Missing mandatory element |
| `additionalProperties` | 3103 Too many elements | 3103 Too many elements | 3103 Too many elements |

Why it matters here: `src/settlement/interface/swagger.json` constrains the settlement window and settlement `state` query parameters with `enum` (`OPEN`, `CLOSED`, `PENDING_SETTLEMENT`, ...), the settlement update payload `state` with `enum` (`ABORTED`, `INVALID`), and `fromDateTime`/`toDateTime` with `format: date-time`. Those requests returned 3101 before the migration (Golden Path 'Check Settlements Error #956'); with the flag unset they return 3100.

With the flag set, both `errorInformation.errorCode` and the `errorDescription` prefix (`Malformed syntax - ...`) match the pre-migration responses. The detail after the dash is generated by ajv and is worded differently to joi's.

The Admin API (`src/api`) still validates with joi on the hapi routes, so its error codes are unaffected either way.

The variable is read from `process.env` on every call and has no `config/default.json` equivalent, so set it in the service's runtime environment - the container `env` in the deployment values, or the `environment:` block of `docker-compose.yml`:

```bash
ERROR_HANDLING_AJV_JOI_PARITY=true
```

### Kafka Position Event Type Action Topic Map

In some cases, you might want to publish position type messages onto a customized topic name that
diverges from the defaults.

You can configure the customized topic names in the config. Each position action key
refers to position messages with associated actions.

NOTE: Only POSITION.PREPARE and POSITION.COMMIT is supported at this time, with additional event-type-actions being added later when required.

```
  "KAFKA": {
    "EVENT_TYPE_ACTION_TOPIC_MAP" : {
      "POSITION":{
        "PREPARE": "topic-transfer-position-batch",
        "COMMIT": "topic-transfer-position-batch"
      }
    }
  }
```

### Batch Processing Configuration Guide

Batch processing can be enabled in the transfer execution flow. Follow the steps below to enable batch processing for a more efficient transfer execution:

Note: The position messages with action 'FX_PREPARE', 'FX_COMMIT' and 'FX_TIMEOUT_RESERVED' are only supported in batch processing.

- **Step 1:** **Create a New Kafka Topic**

  Create a new Kafka topic named `topic-transfer-position-batch` to handle batch processing events.
- **Step 2:** **Configure Action Type Mapping**

  Point the prepare handler to the newly created topic for the action types that are supported in batch processing using the `KAFKA.EVENT_TYPE_ACTION_TOPIC_MAP` configuration as shown below:
  ```
    "KAFKA": {
      "EVENT_TYPE_ACTION_TOPIC_MAP" : {
        "POSITION":{
          "PREPARE": "topic-transfer-position-batch",
          "BULK_PREPARE": "topic-transfer-position",
          "COMMIT": "topic-transfer-position-batch",
          "FX_COMMIT": "topic-transfer-position-batch",
          "BULK_COMMIT": "topic-transfer-position",
          "RESERVE": "topic-transfer-position",
          "FX_PREPARE": "topic-transfer-position-batch",
          "TIMEOUT_RESERVED": "topic-transfer-position-batch",
          "FX_TIMEOUT_RESERVED": "topic-transfer-position-batch"
        }
      }
    }
  ```
  _NOTE_: `BULK_PREPARE` configuration property is added to aid routing of `bulk-prepare` events to non-batch handler since the batch handler does not support `bulk-prepare` events.

- **Step 3:** **Run Batch Processing Handlers**

  Run the position batch handler along with the existing position handler using the following configuration options:
  - **Configure Event Type Action Topic Map for Batch Handler:**

      Configure the `EVENT_TYPE_ACTION_TOPIC_MAP` parameter for the position batch handler to consume events from the new topic (topic-transfer-position-batch).

  - **Set Batch Size:**

      Adjust the batch size using the parameter `KAFKA.CONSUMER.TRANSFER.POSITION_BATCH.config.options.batchSize`. This parameter determines the number of messages fetched in each batch.

  - **Set Consume Timeout:**

      Configure the consume timeout using the parameter `KAFKA.CONSUMER.TRANSFER.POSITION_BATCH.config.options.consumeTimeout`. This parameter specifies the number of milliseconds to wait for a batch of messages to be fetched if the specified batch size of messages is not immediately available.

Example Command to Run Handlers:
```
node src/handlers/index.js handler --positionbatch
```

## API

For endpoint documentation, see the [API documentation](API.md).

For help preparing and executing transfers, see the [Transfer Guide](TransferGuide.md)

## Logging

Logs are sent to standard output by default.

## Tests

Tests include unit, functional, and integration.

Running the tests:

```bash
    npm run test:all
```

Tests include code coverage via istanbul. See the test/ folder for testing scripts.

### Integration Tests

Integration tests end with `.int.ts`. Each test has a [harness](./src/testing//harness.ts) which
brings up a file in an isolated testing environment.

#### Running using `run.ts`:

```bash
npm run test:integration
```

#### Run a single test

To run a single integration test file, you can simply pass in the file to `node --test` like so:

```bash
node --test --require ts-node/register <path to file>
```

For example, to run `src/domain/participant/index.int.ts`:
```bash
node --test --require ts-node/register src/domain/participant/index.int.ts
```

#### Settlement scenario

[`src/settlement/models/settlement/facade.int.ts`](./src/settlement/models/settlement/facade.int.ts)
runs one deferred net settlement from end to end against the harness database and Kafka. The unit tests
of the settlement models stub knex, so this is the test that executes their SQL.

It calls the same services the Settlement API handlers and the `deferredSettlement` handler call, in the
order a hub operator would trigger them. It does not go through HTTP or through the
`topic-deferredsettlement-close` consumer: the harness starts neither.

```mermaid
sequenceDiagram
    autonumber
    participant T as Test
    participant H as Transfer handlers<br/>(prepare, position, fulfil)
    participant W as Settlement window<br/>service
    participant S as Settlement<br/>service
    participant DB as MariaDB
    participant K as topic-notification-event

    Note over T,DB: Setup: hub accounts and a DEFERRED / NET / MULTILATERAL model for USD and for EUR, dfsp_a, and dfsp_b whose USD net debit cap was raised once

    T->>H: pay dfsp_a to dfsp_b 100 USD, pay dfsp_b to dfsp_a 30 USD
    H->>DB: both transfers fulfilled in window 1 (OPEN)
    T->>W: process(window 1)
    W->>DB: window 1 PROCESSING, window 2 OPEN
    T->>H: pay dfsp_b to dfsp_a 20 USD
    H->>DB: transfer fulfilled in window 2

    T->>DB: zero one position change of window 1
    T->>W: close(window 1)
    W--xT: refused, debits and credits do not balance
    T->>DB: assert window 1 still PROCESSING and nothing aggregated, then restore the row

    T->>W: close(window 1)
    W->>DB: aggregate window 1 into settlementContentAggregation
    W->>DB: window 1 CLOSED
    T->>DB: assert a closedDate, and one row per account and role, summing to zero

    T->>S: settlementEventTrigger(window 1)
    S->>DB: settlement PENDING_SETTLEMENT, dfsp_a owes 70, dfsp_b is owed 70

    T->>S: putById(accounts, PS_TRANSFERS_RECORDED)
    S->>DB: account states and settlement transfers
    T->>DB: assert settlement state, and positions unchanged

    T->>DB: in a second transaction, lock the position of dfsp_b
    T->>S: putById(accounts, PS_TRANSFERS_RESERVED)
    S->>DB: lock the settlement, then wait for the position of dfsp_b
    T->>DB: in the second transaction, ask for the settlement
    DB--xS: deadlock, transaction rolled back
    T->>DB: roll back the second transaction
    S->>DB: retry: account states, settlement transfers, position of dfsp_b
    S-->>K: position change notification for dfsp_b
    T->>DB: assert one deadlock and one retry, settlement state and positions, and that the net debit cap of dfsp_b is untouched

    loop PS_TRANSFERS_COMMITTED, SETTLED
        T->>S: putById(accounts, state)
        S->>DB: account states, settlement transfers, positions
        S-->>K: position change notification (COMMITTED only)
        T->>DB: assert settlement state and positions
    end

    T->>DB: assert settlement, window 1 and its content SETTLED

    T->>H: pay dfsp_a to dfsp_b 50 EUR
    H->>DB: transfer fulfilled in window 2
    T->>W: process(window 2)
    W->>DB: window 2 PROCESSING, window 3 OPEN
    T->>DB: add 10 to a USD position change of window 2, take 10 from an EUR one
    T->>W: close(window 2)
    W--xT: refused, neither currency balances although their total does
    T->>DB: assert window 2 still PROCESSING and nothing aggregated, then restore the rows
    T->>W: close(window 2)
    W->>DB: window 2 CLOSED, aggregated per currency
```

Run it on its own with:

```bash
node --test --require ts-node/register src/settlement/models/settlement/facade.int.ts
```

In CI it runs with every other `.int.ts` file in CircleCI's `Integration tests` job, through
`npm run test:integration`.

What it cannot show:

- Behaviour specific to MySQL, because the harness runs MariaDB as `root`. In particular, closing a
  window creates a temporary table, for which the service's database user needs the
  `CREATE TEMPORARY TABLES` privilege.
- The wait of `WINDOW_AGGREGATION.CLOSE_DELAY_MS` before a window is closed. That happens in the
  `deferredSettlement` handler, which the test does not go through; the handler's unit test covers it.
- A deadlock anywhere but on the position of the net recipient in the reserve step, where the test
  stages one, and a deadlock that outlasts `DEADLOCK.RETRIES`. The unit tests of the settlement facade
  cover those, with transactions that fail with the deadlock error of the database driver.

### Running Functional Tests

If you want to run functional tests locally utilizing the [ml-core-test-harness](https://github.com/mojaloop/ml-core-test-harness), you can run the following commands:

```bash
export NODE_VERSION="$(cat .nvmrc)-alpine"
docker build \
  --build-arg NODE_VERSION=$NODE_VERSION \
  -t mojaloop/central-ledger:local \
  .
```

```bash
npm run test:functional
```

By default this will clone the [ml-core-test-harness](https://github.com/mojaloop/ml-core-test-harness) into `$ML_CORE_TEST_HARNESS_DIR`.

See default values as specified in the [test-functional.sh](./test/scripts/test-functional.sh) script.

Check test container logs for test results into `$ML_CORE_TEST_HARNESS_DIR` directory.

If you want to not have the [ml-core-test-harness](https://github.com/mojaloop/ml-core-test-harness) shutdown automatically by the script, make sure you set the following env var `export ML_CORE_TEST_SKIP_SHUTDOWN=true`.

By doing so, you are then able access TTK UI using the following URI: <http://localhost:9660>.

Or alternatively, you can monitor the `ttk-func-ttk-tests-1` (See `ML_CORE_TEST_HARNESS_TEST_FUNC_CONT_NAME` in the [test-functional.sh](./test/scripts/test-functional.sh) script) container for test results with the following command:

```bash
docker logs -f ttk-func-ttk-tests-1
```

TTK Test files:

- **Test Collection**: `$ML_CORE_TEST_HARNESS_DIR/docker/ml-testing-toolkit/test-cases/collections/tests/p2p.json`
- **Env Config**: `$ML_CORE_TEST_HARNESS_DIR//docker/ml-testing-toolkit/test-cases/environments/default-env.json`

Configuration modifiers:

- **central-ledger**: [./docker/config-modifier/configs/central-ledger.js](./docker/config-modifier/configs/central-ledger.js)

## Development environment

  Start Docker dependant Services

  ```bash
  docker compose -f ./docker-compose.yml -f docker-compose.dev.yml up -d
  ```

  Start local Central-Ledger Service

  ```bash
  npm start
  ```

  Populate Test Data

  ```bash
  sh ./test/util/scripts/populateTestData.sh
  ```

  View Logs for Mockserver (i.e. Payee Receiver) and ML-API-Adapter:

  ```bash
  docker logs -f mockserver
  docker logs -f cl_ml-api-adapter
  ```

  Postman Test Collection: [./test/util/postman/CL-Local Docker Test.postman_collection.json](./test/util/postman/CL-Local%20Docker%20Test.postman_collection.json)

## Auditing Dependencies

We use `audit-ci` along with `npm audit` to check dependencies for node vulnerabilities, and keep track of resolved dependencies with an `audit-ci.jsonc` file.

To start a new resolution process, run:

```bash
npm run audit:fix
```

You can then check to see if the CI will pass based on the current dependencies with:

```bash
npm run audit:check
```

The [audit-ci.jsonc](./audit-ci.jsonc) contains any audit-exceptions that cannot be fixed to ensure that CircleCI will build correctly.

## Container Scans

As part of our CI/CD process, we use grype a vulnerability scanner for container images and filesystems upon release.

If you find your release builds are failing, please review Mojaloop orb with grype image scan at [container scanning](https://github.com/mojaloop/ci-config-orb-build?tab=readme-ov-file#vulnerability-image-scan-configuration) and review [grype_image_scan.yml](https://github.com/mojaloop/ci-config-orb-build/blob/main/src/jobs/grype_image_scan.yml) job.

For more information on grype, refer to:

- [Grype](https://github.com/anchore/grype)

## Automated Releases

As part of our CI/CD process, we use a combination of CircleCI, standard-version
npm package and github-release CircleCI orb to automatically trigger our releases
and image builds. This process essentially mimics a manual tag and release.

On a merge to main, CircleCI is configured to use the mojaloopci github account
to push the latest generated CHANGELOG and package version number.

Once those changes are pushed, CircleCI will pull the updated main, tag and
push a release triggering another subsequent build that also publishes a docker image.

### Potential problems

- There is a case where the merge to main workflow will resolve successfully, triggering
  a release. Then that tagged release workflow subsequently failing due to the image scan,
  audit check, vulnerability check or other "live" checks.

  This will leave main without an associated published build. Fixes that require
  a new merge will essentially cause a skip in version number or require a clean up
  of the main branch to the commit before the CHANGELOG and bump.

  This may be resolved by relying solely on the previous checks of the
  merge to main workflow to assume that our tagged release is of sound quality.
  We are still mulling over this solution since catching bugs/vulnerabilities/etc earlier
  is a boon.

- It is unknown if a race condition might occur with multiple merges with main in
  quick succession, but this is a suspected edge case.
