openapi: 3.1.0
info:
  title: FIL Exchange API
  version: "1.0"
  summary: Member-facing v1 API of the FIL Exchange.
  description: |
    The FIL Exchange lets member companies share fraud records (contributions), flag records that are wrong,
    and query the records of other members.

    ## Response envelope

    Every JSON answer has the same envelope:

    ```json
    {"status": {"code": 0, "name": "Ok"}, "data": {}}
    ```

    On success `status.code` is `0` and `data` holds the result. On an error the HTTP status is 4xx or 5xx,
    `status.code` is the numbered error from the table below (it is not the HTTP status), `status.name` is its
    name, `status.message` is a text for humans, and `data` is always present: `null`, a text with details, or an
    object (the sign-in answer with code 80).
    Decide on `status.code`, not on `status.message`.

    ## Sessions

    1. Sign in with `POST /auth/api/v1/authentication-management/session`. The answer carries an access token
       and a refresh token.
    2. Send the access token as `Authorization: Bearer <accessToken>` on every other route.
    3. The access token lives 5 minutes. Before it expires, call
       `PATCH /auth/api/v1/authentication-management/session` with `Authorization: Bearer <refreshToken>`.
       The refresh token lives 24 hours. A refresh replaces both tokens: the access token issued before it
       stops working at once.
    4. Sign out with `POST /auth/api/v1/authentication-management/logout`.

    A user has two key pairs. The authorization key pair signs the sign-in. The signing key pair signs upload
    and flag transactions.

    ## Uploading and flagging

    Both take two calls. The assemble call checks the request and answers with an unsigned transaction as hex.
    Sign that transaction with the signing key pair and send the signed transaction, as hex in a plain text
    body, to the submit call. Sending the same signed transaction again within 30 days returns the first
    answer and changes nothing.

    ## Error codes

    | HTTP | Code | Name | Meaning |
    |---|---|---|---|
    | 500 | 1 | `InternalError` | The request failed on the server side. Retry later. |
    | 401 | 2 | `InvalidSignature` | Sign-in: the signature does not match, or the public key is not the one registered for the user. Other routes: the token signature is not valid. |
    | 404 | 3 | `UserNotFound` | No user with this email. |
    | 401 | 4 | `InvalidBearer` | The `Authorization` header is missing or is not `Bearer <token>`, or the session has ended. |
    | 401 | 5 | `InvalidRefreshToken` | The refresh token is not valid: already used, or its session has ended. |
    | 401 | 6 | `TokenExpired` | The token has expired. |
    | 400 | 9 | `UnknownFraudTypeError` | The transaction names a fraud type that does not exist. |
    | 400 | 11 | `ArgumentNotValid` | A value has the wrong form: an identifier or a date. |
    | 400 | 12 | `MessageNotReadable` | The request body is missing, is not readable, or lacks a required member. |
    | 400 | 15 | `InvalidTransaction` | The transaction cannot be read or applied. `data` says why. |
    | 400 | 16 | `InvalidInstructionType` | The transaction has the wrong content, or an identifier does not fit its fraud type. |
    | 422 | 17 | `InvalidToken` | The token cannot be read. |
    | 422 | 18 | `InvalidPublicKey` | Sign-in: the public key is not 32 bytes of hex. |
    | 422 | 19 | `SignatureDecodeError` | Sign-in: the signature is not hex. |
    | 503 | 24 | `TriggerNotFoundError` | The upload limit period is not configured. |
    | 404 | 27 | `MetadataKeyNotFoundError` | A setting of the company or the platform is not configured. |
    | 400 | 28 | `IncorrectMetadataError` | The record lifetime of a fraud type is not configured. |
    | 404 | 32 | `AssetDefinitionNotFoundError` | Flag assemble: no such record. |
    | 503 | 34 | `RewardsTableNotSetError` | The reward tables or the upload limit are not configured. |
    | 400 | 36 | `DuplicateError` | A record with this id is already stored. Assemble again. |
    | 400 | 38 | `PrivilegedContributionModificationError` | A privileged record cannot be flagged. |
    | 404 | 43 | `PeerNotFoundError` | The company of the caller does not exist. |
    | 403 | 48 | `NotEnoughCreditsError` | The query could not be charged. Retry. |
    | 400 | 49 | `MalformedParametersError` | A query parameter has the wrong type. |
    | 400 | 54 | `InvalidContributionCountryCodeError` | A country code is not valid for the entry. |
    | 503 | 57 | `ContributionPricesNotSetError` | The prices are not configured. |
    | 403 | 59 | `AccessDeniedError` | The user is blocked or not yet approved, or asks for data of another user. |
    | 404 | 60 | `ContributionNotFoundError` | No such record. |
    | 409 | 61 | `ExpiredContributionFlagError` | The record has expired or is already flagged. |
    | 428 | 63 | `TwoFactorAuthenticationCodeMissingError` | Sign-in: a one-time code was emailed earlier and is still valid, or `method` is `totp` and `authCode` is missing. Send the code as `authCode`. |
    | 422 | 64 | `TwoFactorInvalidAuthenticationTokenError` | Sign-in: the one-time code is wrong. |
    | 428 | 65 | `TwoFactorAuthenticationMissingButNotifiedError` | Sign-in: a one-time code has just been emailed. Send it as `authCode`. |
    | 503 | 66 | `ContributionTimeToLiveTableNotSetError` | The record lifetimes are not configured. |
    | 400 | 70 | `ContributionSourceError` | `sourcePeerId` is not a company the caller may name. |
    | 503 | 73 | `ContributionRewardSplitRatioNotSetError` | The reward split is not configured. |
    | 409 | 75 | `TwoFactorAuthenticationStatusError` | Sign-in: the request names a sign-in method that is not set up for the account. |
    | 403 | 79 | `DomainLimitExceededError` | The upload limit of the company does not cover the upload. |
    | 428 | 80 | `TwoFactorRequiredError` | Sign-in: the second step is an authenticator app or a passkey. `data` is an object that lists the methods. |

servers:
  - url: https://backend.fraudintelligencelimited.com
    description: FIL Exchange

tags:
  - name: Session
    description: Sign in, refresh the tokens, sign out.
  - name: Account
    description: Details of the signed-in user.
  - name: Balance and limit
    description: Token balance and upload limit of the caller's company.
  - name: Contributions
    description: Upload, flag, look up, query and download fraud records.
  - name: Rates
    description: Query prices and reward tables.

security:
  - bearerAuth: []

paths:
  /auth/api/v1/authentication-management/session:
    post:
      operationId: signIn
      tags: [Session]
      summary: Sign in
      description: |
        Opens a session for a user who proves possession of the registered authorization key pair.

        The signature is computed as follows:

        1. Take the BLAKE2b-256 digest of the email (UTF-8 bytes).
        2. Set the lowest bit of the last digest byte (`digest[31] |= 1`).
        3. Sign the 32 digest bytes with Ed25519, using the private key of the authorization key pair.
        4. Send the signature as hex.

        When the user has the emailed one-time code turned on, the first call without `authCode` answers 428
        with code 65 and a code is emailed. Repeat the call with the same body plus `authCode`.
        A code is valid for 5 minutes and works once. Another code can be emailed one minute after the last one;
        until then a call without `authCode` answers 428 with code 63. A call with `authCode` when no valid code
        exists also emails a fresh code and answers 428 with code 65.

        When the method asked first for the user is an authenticator app or a passkey, the first call answers
        428 with code 80. Its `data` is an object: `methods` lists the second steps the user has set up
        (`passkey`, `totp`, `email`), `preferred` names the one asked first, and `passkey` holds the options for
        a browser when the user has a passkey. Repeat the call with `method` and `authCode`:

        - `method: totp` with the 6-digit code of the authenticator app. Without `authCode` the call answers
          428 with code 63.
        - `method: email` to use the emailed code, when the user has it set up.
        - A passkey is answered by a browser and cannot be used by an API client. For an account that an
          integration signs in with, set up the emailed code or the authenticator app.

        A `method` that is not set up for the user answers 409 with code 75.

        Send `email` exactly as it was registered. Send `authPublicKeyHex` as lower-case hex without a prefix.

        The answer carries the access token (valid 5 minutes) and the refresh token (valid 24 hours).
        A user who is registered but not yet approved can sign in, but can only read the own account and sign out.
        The tokens carry the state of the user at the time they were issued: after approval, the other routes
        open with the next token, from a refresh or a sign-in.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SignInRequest'
            examples:
              firstStep:
                summary: Sign in
                value:
                  email: alice@example.com
                  signature: 5b1c0e7a9d3f42865b1c0e7a9d3f42865b1c0e7a9d3f42865b1c0e7a9d3f42865b1c0e7a9d3f42865b1c0e7a9d3f42865b1c0e7a9d3f42865b1c0e7a9d3f4286
                  authPublicKeyHex: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
              withCode:
                summary: Sign in with the emailed one-time code
                value:
                  email: alice@example.com
                  signature: 5b1c0e7a9d3f42865b1c0e7a9d3f42865b1c0e7a9d3f42865b1c0e7a9d3f42865b1c0e7a9d3f42865b1c0e7a9d3f42865b1c0e7a9d3f42865b1c0e7a9d3f4286
                  authPublicKeyHex: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
                  authCode: "123456"
              withAuthenticator:
                summary: Sign in with the code of the authenticator app
                value:
                  email: alice@example.com
                  signature: 5b1c0e7a9d3f42865b1c0e7a9d3f42865b1c0e7a9d3f42865b1c0e7a9d3f42865b1c0e7a9d3f42865b1c0e7a9d3f42865b1c0e7a9d3f42865b1c0e7a9d3f4286
                  authPublicKeyHex: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
                  method: totp
                  authCode: "123456"
      responses:
        '200':
          $ref: '#/components/responses/Tokens'
        '400':
          description: The body is not JSON, or `email`, `signature` or `authPublicKeyHex` is missing or empty.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                notReadable:
                  $ref: '#/components/examples/MessageNotReadable'
        '401':
          description: The signature does not match the email and key, or the key is not the one registered for the user.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                wrongSignature:
                  summary: Code 2, the signature does not match
                  value:
                    status: {code: 2, name: InvalidSignature, message: "Signature of the user `alice@example.com` was incorrect"}
                    data: null
                keyNotRegistered:
                  summary: Code 2, the key is not registered for the user
                  value:
                    status: {code: 2, name: InvalidSignature, message: "Provided public key does not belong to the user `alice@example.com` "}
                    data: null
        '403':
          description: The user is blocked.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                blocked:
                  $ref: '#/components/examples/Blocked'
        '404':
          description: No user with this email.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                userNotFound:
                  $ref: '#/components/examples/UserNotFound'
        '409':
          description: The request names a sign-in method that is not set up for the user.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                methodNotSetUp:
                  summary: Code 75, the method is not set up
                  value:
                    status: {code: 75, name: TwoFactorAuthenticationStatusError, message: "This sign-in method is not set up for user: alice@example_telco"}
                    data: null
        '422':
          description: The signature or the public key cannot be decoded, or the one-time code is wrong.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                signatureNotHex:
                  summary: Code 19, the signature is not hex
                  value:
                    status: {code: 19, name: SignatureDecodeError, message: "Failed to decode signature of the user `alice@example.com`"}
                    data: null
                keyNotValid:
                  summary: Code 18, the public key is not 32 bytes of hex
                  value:
                    status: {code: 18, name: InvalidPublicKey, message: "Public key of the user `alice@example.com` was incorrect"}
                    data: null
                wrongCode:
                  summary: Code 64, the one-time code is wrong
                  value:
                    status: {code: 64, name: TwoFactorInvalidAuthenticationTokenError, message: Incorrect 2FA code}
                    data: null
        '428':
          description: The second step is required. Repeat the call with the code as `authCode`, and with `method` when the answer has code 80.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                codeSent:
                  summary: Code 65, a code has just been emailed
                  value:
                    status: {code: 65, name: TwoFactorAuthenticationMissingButNotifiedError, message: 2FA code required}
                    data: null
                codeStillValid:
                  summary: Code 63, a code emailed earlier is still valid
                  value:
                    status:
                      code: 63
                      name: TwoFactorAuthenticationCodeMissingError
                      message: "2FA code required. Code remaining validity time: 270 seconds. Another code can be requested in 30 seconds."
                    data: null
                authenticatorRequired:
                  summary: Code 80, the second step is an authenticator app
                  value:
                    status: {code: 80, name: TwoFactorRequiredError, message: A second sign-in step is required}
                    data:
                      methods: [totp]
                      preferred: totp
        '500':
          $ref: '#/components/responses/InternalError'
    patch:
      operationId: refreshSession
      tags: [Session]
      summary: Refresh the tokens
      description: |
        Exchanges the refresh token for another access token and refresh token. Send the refresh token, not the
        access token, in the `Authorization` header. The request has no body.

        A refresh replaces both tokens: the refresh token works once, and the access token issued with it stops
        working at once. Repeating the same refresh within one minute returns the same pair of tokens, so a client that
        lost the answer can retry. After one minute a used refresh token answers 401 with code 5.
      security:
        - refreshToken: []
      responses:
        '200':
          $ref: '#/components/responses/Tokens'
        '401':
          description: The header is missing or malformed, or the refresh token is expired, already used, or its session has ended.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                missingHeader:
                  $ref: '#/components/examples/MissingHeader'
                invalidRefreshToken:
                  summary: Code 5, the refresh token is already used or its session has ended
                  value:
                    status: {code: 5, name: InvalidRefreshToken, message: Invalid refresh token}
                    data: null
                expired:
                  $ref: '#/components/examples/TokenExpired'
                tokenSignature:
                  $ref: '#/components/examples/TokenSignature'
        '404':
          description: The user of the token does not exist.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                userNotFound:
                  $ref: '#/components/examples/UserNotFound'
        '422':
          $ref: '#/components/responses/TokenNotReadable'
        '500':
          $ref: '#/components/responses/InternalError'

  /auth/api/v1/authentication-management/logout:
    post:
      operationId: signOut
      tags: [Session]
      summary: Sign out
      description: |
        Ends the session the access token belongs to. The access token and the refresh token of the session stop
        working. The request has no body.
      responses:
        '200':
          $ref: '#/components/responses/Empty'
        '401':
          description: The header is missing or malformed, the token is expired, or the session has already ended.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                missingHeader:
                  $ref: '#/components/examples/MissingHeader'
                sessionEnded:
                  $ref: '#/components/examples/SessionEnded'
                expired:
                  $ref: '#/components/examples/TokenExpired'
                tokenSignature:
                  $ref: '#/components/examples/TokenSignature'
                sessionNotFound:
                  summary: Code 5, the session of the token is not found
                  value:
                    status:
                      code: 5
                      name: InvalidRefreshToken
                      message: "Refresh token with `00000000-0000-4000-8000-000000000001` access token ID not found"
                    data: null
        '403':
          $ref: '#/components/responses/ForbiddenBlocked'
        '422':
          $ref: '#/components/responses/TokenNotReadable'
        '500':
          $ref: '#/components/responses/InternalError'

  /auth/api/v1/peer-management/account:
    get:
      operationId: getAccount
      tags: [Account]
      summary: Get own account
      description: |
        Returns the details of the signed-in user and of the user's company. A user can read only the own
        account. A user who is not yet approved can call this route; `peerOperatingCountry`, `peerType`,
        `peerConnectionType`, `peerGroup`, `isPrivileged`, `subscriptionType` and `subscriptionExpiryDate` are
        then `null`. `peerCompanyName` and `irohaPubKeyHex` are always present.
      parameters:
        - name: accountId
          in: query
          required: false
          description: Account of the signed-in user, in the form `name@company`. Optional. Any other account answers 403 with code 59.
          schema:
            type: string
          example: admin@example_telco
        - name: email
          in: query
          required: false
          description: Email of the signed-in user. Without it the account of the session is returned. Any other email answers 403 with code 59.
          schema:
            type: string
            format: email
          example: alice@example.com
      responses:
        '200':
          description: The account.
          content:
            application/json:
              schema:
                type: object
                required: [status, data]
                properties:
                  status:
                    $ref: '#/components/schemas/StatusOk'
                  data:
                    $ref: '#/components/schemas/Account'
              examples:
                account:
                  summary: An approved user
                  value:
                    status: {code: 0, name: Ok}
                    data:
                      irohaPubKeyHex: fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210
                      peerCompanyName: Example Telco
                      peerOperatingCountry: GB
                      peerType: MEDIUM_TELCO
                      peerConnectionType: Web
                      peerGroup: null
                      isPrivileged: false
                      subscriptionType: FREEMIUM
                      subscriptionExpiryDate: null
                      email: alice@example.com
                      accountId: admin@example_telco
                      authPubKeyHex: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
                      salt: 00112233445566778899aabbccddeeff
                      role: ROLE_DOMAIN_ADMIN
                      status: ACTIVE
                      phoneNumber: "+447700900123"
                      firstName: Alice
                      lastName: Example
                      roleName: Analyst
                      registrationDate: "2025-01-15T09:30:00Z"
                      twoFactorAuthEnabled: false
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: The user is blocked, or `email` names another user.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                otherUser:
                  summary: Code 59, the email of another user
                  value:
                    status: {code: 59, name: AccessDeniedError, message: "Access denied, cannot get other user's data"}
                    data: null
                blocked:
                  $ref: '#/components/examples/Blocked'
        '404':
          description: The user does not exist.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                userNotFound:
                  $ref: '#/components/examples/UserNotFound'
        '422':
          $ref: '#/components/responses/TokenNotReadable'
        '500':
          $ref: '#/components/responses/InternalError'

  /data/api/v1/wallet-management/balance:
    get:
      operationId: getBalance
      tags: [Balance and limit]
      summary: Get the token balance
      description: Returns the token balance of the caller's company. Rewards add to it; charged queries and downloads take from it.
      parameters:
        - name: peerId
          in: query
          required: false
          description: Id of the caller's company. Optional. Any other company answers 403 with code 59.
          schema:
            type: string
          example: example_telco
      responses:
        '200':
          description: The balance.
          content:
            application/json:
              schema:
                type: object
                required: [status, data]
                properties:
                  status:
                    $ref: '#/components/schemas/StatusOk'
                  data:
                    $ref: '#/components/schemas/Balance'
              examples:
                balance:
                  summary: Balance of the company
                  value:
                    status: {code: 0, name: Ok}
                    data:
                      tokenId: {definitionId: "credit#admin", accountId: admin@example_telco}
                      balance: 685
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/TokenNotReadable'
        '500':
          $ref: '#/components/responses/InternalError'

  /data/api/v1/peer-management/limit:
    get:
      operationId: getUploadLimit
      tags: [Balance and limit]
      summary: Get the upload limit
      description: |
        Returns how many records the caller's company has stored in the current period, how many it may store
        per period, and when the count is reset. Every record an upload stores counts as one, whatever the
        size of its range.

        `total` is the limit set on the platform for a company. `used` is `total` minus what the company has
        left, and is never below 0.
      parameters:
        - name: accountId
          in: query
          required: false
          description: Account of the signed-in user, in the form `name@company`. Optional. Any other account answers 403 with code 59.
          schema:
            type: string
          example: admin@example_telco
      responses:
        '200':
          description: The upload limit.
          content:
            application/json:
              schema:
                type: object
                required: [status, data]
                properties:
                  status:
                    $ref: '#/components/schemas/StatusOk'
                  data:
                    $ref: '#/components/schemas/UploadLimit'
              examples:
                limit:
                  summary: 2 of 1,000,000 records used, reset every 30 days
                  value:
                    status: {code: 0, name: Ok}
                    data:
                      used: 2
                      total: 1000000
                      updatePeriod: 2592000
                      nextUpdate: "2026-02-01T00:00:00Z"
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: The company has no upload limit configured.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                limitNotFound:
                  summary: Code 27, no limit for the company
                  value:
                    status: {code: 27, name: MetadataKeyNotFoundError, message: "Domain `example_telco` limit metadata not found"}
                    data: null
        '422':
          $ref: '#/components/responses/TokenNotReadable'
        '500':
          $ref: '#/components/responses/InternalError'
        '503':
          description: The upload limit or its period is not configured on the platform.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                limitNotSet:
                  summary: Code 34, the limit is not configured
                  value:
                    status: {code: 34, name: RewardsTableNotSetError, message: Global reward limit not set}
                    data: null
                periodNotSet:
                  summary: Code 24, the period is not configured
                  value:
                    status: {code: 24, name: TriggerNotFoundError, message: Trigger period not found}
                    data: null

  /data/api/v1/contribution-management/contribution/assemble:
    post:
      operationId: assembleUpload
      tags: [Contributions]
      summary: Assemble an upload
      description: |
        Checks the entries and answers with the unsigned upload transaction as hex. Nothing is stored.
        Sign the transaction with the signing key pair and send it to
        `POST /data/api/v1/contribution-management/contribution`.

        The body is a JSON array of up to 5000 entries.

        The identifier decides which fraud types an entry can carry:

        | Identifier | Form | Fraud types |
        |---|---|---|
        | Phone number | E.164 with `+`, or a range `+first-+last` | `Wangiri`, `IRSF`, `SMSA2P`, `Flashcall`, `Scam` |
        | Device (IMEI) | 15 digits with a correct check digit | `StolenDevice` |
        | IPv4 address | dotted, or a range `first-last` | `IPFraud` |
        | Email address or URL | as written | `Scam` |

        A range must not run backwards.

        Countries: `origination` and `destination` are ISO 3166-1 alpha-2 codes. A member that is left out
        counts as an empty text. An empty `origination` is accepted only for `Scam` and for numbers that start
        with `+882` or `+883`. An empty `destination` is accepted only for `Scam`. Every other entry needs both
        codes, and `null` is never accepted: the call answers 400 with code 54.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: array
              maxItems: 5000
              items:
                $ref: '#/components/schemas/UploadEntry'
            examples:
              threeEntries:
                summary: A number, a range of numbers and a device
                value:
                  - id: "+447700900201"
                    fraudType: Wangiri
                    origination: GB
                    destination: GB
                  - id: "+447700900210-+447700900219"
                    fraudType: IRSF
                    origination: GB
                    destination: FR
                  - id: "356938035643809"
                    fraudType: StolenDevice
                    origination: GB
                    destination: GB
              scam:
                summary: A scam URL without countries
                value:
                  - id: https://scam.example.com/login
                    fraudType: Scam
                    origination: ""
                    destination: ""
              forSource:
                summary: An entry uploaded for another company
                value:
                  - id: 198.51.100.9
                    fraudType: IPFraud
                    origination: DK
                    destination: PT
                    sourcePeerId: example_vendor
      responses:
        '200':
          $ref: '#/components/responses/Transaction'
        '400':
          description: The body or an entry is not valid.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                notReadable:
                  $ref: '#/components/examples/MessageNotReadable'
                identifier:
                  $ref: '#/components/examples/ArgumentNotValid'
                tooMany:
                  $ref: '#/components/examples/TooManyEntries'
                typeMismatch:
                  $ref: '#/components/examples/TypeMismatch'
                country:
                  $ref: '#/components/examples/InvalidCountry'
                source:
                  $ref: '#/components/examples/InvalidSource'
                lifetimeMissing:
                  $ref: '#/components/examples/LifetimeMissing'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/TokenNotReadable'
        '500':
          $ref: '#/components/responses/InternalError'
        '503':
          description: The reward tables or the record lifetimes are not configured on the platform.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                rewardsNotSet:
                  $ref: '#/components/examples/RewardsNotSet'
                lifetimesNotSet:
                  $ref: '#/components/examples/LifetimesNotSet'

  /data/api/v1/contribution-management/contribution:
    post:
      operationId: submitUpload
      tags: [Contributions]
      summary: Submit an upload
      description: |
        Applies a signed upload transaction. The body is the signed transaction as hex, as plain text. Do not
        wrap it in JSON quotes.

        A record the company already holds active (same `id` and `fraudType`) is not stored and not rewarded
        again. `tokenIds` has one element per entry, in the order of the entries; for an entry that was already
        held it carries the id of the stored record.

        The reward is paid per identifier: a range counts every value in it. The rate is the one of the
        uploader's company type (see the reward tables). For an entry with another company as `sourcePeerId`
        the reward is split between the two companies by the split ratio.

        Every stored record takes one from the upload limit of the company. When the limit does not cover the
        records to store, the call answers 403 with code 79 and nothing is stored.

        Sending the same signed transaction again within 30 days returns the first answer and changes nothing.
      requestBody:
        required: true
        content:
          text/plain:
            schema:
              type: string
              description: The signed transaction as hex. White space is ignored.
            examples:
              signedTransaction:
                summary: Signed transaction (shortened)
                value: 04a1b2c3d4e5f60718293a4b5c6d7e8f04a1b2c3d4e5f60718293a4b5c6d7e8f
      responses:
        '200':
          description: The upload is applied.
          content:
            application/json:
              schema:
                type: object
                required: [status, data]
                properties:
                  status:
                    $ref: '#/components/schemas/StatusOk'
                  data:
                    $ref: '#/components/schemas/UploadResult'
              examples:
                uploaded:
                  summary: Three entries stored
                  value:
                    status: {code: 0, name: Ok}
                    data:
                      tokenIds:
                        - {definitionId: "00000000-0000-7000-8000-000000000001#contribution", accountId: admin@example_telco}
                        - {definitionId: "00000000-0000-7000-8000-000000000002#contribution", accountId: admin@example_telco}
                        - {definitionId: "00000000-0000-7000-8000-000000000003#contribution", accountId: admin@example_telco}
                      rewarded: 120
                alreadyHeld:
                  summary: The only entry was already held
                  value:
                    status: {code: 0, name: Ok}
                    data:
                      tokenIds:
                        - {definitionId: "00000000-0000-7000-8000-000000000001#contribution", accountId: admin@example_telco}
                      rewarded: 0
        '400':
          description: The body is empty, or the transaction or one of its entries is not valid.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                emptyBody:
                  $ref: '#/components/examples/MessageNotReadable'
                transaction:
                  $ref: '#/components/examples/TransactionNotReadable'
                tooMany:
                  $ref: '#/components/examples/TooManyEntries'
                content:
                  $ref: '#/components/examples/InstructionType'
                typeMismatch:
                  $ref: '#/components/examples/TypeMismatch'
                fraudType:
                  summary: Code 9, a fraud type that does not exist
                  value:
                    status: {code: 9, name: UnknownFraudTypeError, message: Could not resolve fraud type by code}
                    data: null
                identifier:
                  $ref: '#/components/examples/ArgumentNotValid'
                country:
                  $ref: '#/components/examples/InvalidCountry'
                source:
                  $ref: '#/components/examples/InvalidSource'
                duplicate:
                  summary: Code 36, a record id of the transaction is already stored
                  value:
                    status: {code: 36, name: DuplicateError, message: Entity already exists}
                    data: null
                lifetimeMissing:
                  $ref: '#/components/examples/LifetimeMissing'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: The user is blocked or not yet approved, or the upload limit is exceeded.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                limitExceeded:
                  summary: Code 79, the upload limit is exceeded
                  value:
                    status:
                      code: 79
                      name: DomainLimitExceededError
                      message: "Domain `example_telco` upload limit exceeded: remaining 10, requested 25"
                    data: null
                blocked:
                  $ref: '#/components/examples/Blocked'
                notApproved:
                  $ref: '#/components/examples/NotApproved'
        '404':
          description: The company of the caller does not exist, or the reward split is not configured.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                peerNotFound:
                  $ref: '#/components/examples/PeerNotFound'
                splitNotFound:
                  summary: Code 27, the reward split is not configured
                  value:
                    status: {code: 27, name: MetadataKeyNotFoundError, message: Contribution reward split ratio key not found}
                    data: null
        '422':
          $ref: '#/components/responses/TokenNotReadable'
        '500':
          $ref: '#/components/responses/InternalError'
        '503':
          description: The reward tables or the record lifetimes are not configured on the platform.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                rewardsNotSet:
                  $ref: '#/components/examples/RewardsNotSet'
                lifetimesNotSet:
                  $ref: '#/components/examples/LifetimesNotSet'
    get:
      operationId: queryContributions
      tags: [Contributions]
      summary: Query contributions
      description: |
        Returns the records that match the filters, latest upload first, and charges the company for the
        records it sees for the first time.

        What is returned: active and flagged records that have not expired. A privileged record is returned
        only to its own company and to the companies it has approved.

        What is charged, with `fetch-mode=DEFAULT`:

        - Own records are free and counted in `details.self`.
        - Records bought before are free and counted in `details.old`.
        - Records of a privileged company that approved the caller's company are free and counted in `details.new`.
        - Every other record is bought and counted in `details.new`. The price is per identifier: a range costs
          the price times the number of values in it. Email addresses and URLs cost nothing.
        - A record the balance does not cover is not returned. It is counted in
          `details.contributionsNotReturned` and its cost is added to `details.contributionsNotReturnedCost`.

        Companies on the `TRIAL` and `PAID` subscriptions are not charged.

        The counters of the answer are in `details`.

        Repeat `ft`, `org` and `dst` to pass several values, for example `?ft=Wangiri&ft=IRSF`.
      parameters:
        - $ref: '#/components/parameters/Size'
        - $ref: '#/components/parameters/From'
        - $ref: '#/components/parameters/To'
        - $ref: '#/components/parameters/FraudTypes'
        - $ref: '#/components/parameters/Originations'
        - $ref: '#/components/parameters/Destinations'
        - $ref: '#/components/parameters/FetchMode'
        - $ref: '#/components/parameters/ConfidenceScore'
      responses:
        '200':
          description: The matching records and what the query cost.
          content:
            application/json:
              schema:
                type: object
                required: [status, data]
                properties:
                  status:
                    $ref: '#/components/schemas/StatusOk'
                  data:
                    $ref: '#/components/schemas/QueryResult'
              examples:
                bought:
                  summary: One record bought
                  value:
                    status: {code: 0, name: Ok}
                    data:
                      contributions:
                        - id: "+447700900301-+447700900301"
                          fraudType: Wangiri
                          origination: IS
                          destination: NZ
                          expiryDate: "2026-03-16T10:00:00Z"
                          fraudStatus: Active
                          confidenceIndex: null
                          isPrivileged: false
                          peerId: example_vendor
                          flagger: null
                          timestamp: "2026-01-15T10:00:00Z"
                          flagTimestamp: null
                          assetDefinitionId: 00000000-0000-7000-8000-000000000001
                          sourcePeerId: example_vendor
                      details:
                        self: 0
                        old: 0
                        new: 1
                        newWithConfidenceIndex: 0
                        creditsSpent: 1
                        balanceLeft: 19
                        contributionsNotReturned: 0
                        contributionsNotReturnedCost: 0
                noTokens:
                  summary: The balance covers nothing
                  value:
                    status: {code: 0, name: Ok}
                    data:
                      contributions: []
                      details:
                        self: 0
                        old: 0
                        new: 0
                        newWithConfidenceIndex: 0
                        creditsSpent: 0
                        balanceLeft: 0
                        contributionsNotReturned: 4
                        contributionsNotReturnedCost: 4
        '400':
          $ref: '#/components/responses/BadQuery'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/ForbiddenOrNotCharged'
        '404':
          $ref: '#/components/responses/PeerNotFound'
        '422':
          $ref: '#/components/responses/TokenNotReadable'
        '500':
          $ref: '#/components/responses/InternalError'
        '503':
          $ref: '#/components/responses/PricesNotSet'

  /data/api/v1/contribution-management/contribution/flag/assemble:
    patch:
      operationId: assembleFlag
      tags: [Contributions]
      summary: Assemble a flag
      description: |
        Checks the records to flag and answers with the unsigned flag transaction as hex. Nothing is changed.
        Sign the transaction with the signing key pair and send it to
        `PATCH /data/api/v1/contribution-management/contribution/flag`.

        Name a record by the `assetDefinitionId` of a query or lookup answer, or by the `definitionId` of an
        upload answer. Up to 5000 records per request.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/FlagRequest'
            examples:
              byAssetDefinitionId:
                summary: By the assetDefinitionId of a query or lookup answer
                value:
                  assetDefinitionIds:
                    - 00000000-0000-7000-8000-000000000001
              byDefinitionId:
                summary: By the definitionId of an upload answer
                value:
                  assetDefinitionIds:
                    - "00000000-0000-7000-8000-000000000001#contribution"
      responses:
        '200':
          $ref: '#/components/responses/Transaction'
        '400':
          description: The body is not valid, names too many records, or names a privileged record.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                notReadable:
                  $ref: '#/components/examples/MessageNotReadable'
                tooMany:
                  $ref: '#/components/examples/TooManyEntries'
                privileged:
                  $ref: '#/components/examples/PrivilegedRecord'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: A named record does not exist.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                notFound:
                  summary: Code 32, no such record
                  value:
                    status:
                      code: 32
                      name: AssetDefinitionNotFoundError
                      message: "Asset definition `00000000-0000-7000-8000-000000000009` not found"
                    data: null
        '409':
          $ref: '#/components/responses/ExpiredOrFlagged'
        '422':
          $ref: '#/components/responses/TokenNotReadable'
        '500':
          $ref: '#/components/responses/InternalError'
        '503':
          description: The reward tables are not configured on the platform.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                rewardsNotSet:
                  $ref: '#/components/examples/RewardsNotSet'

  /data/api/v1/contribution-management/contribution/flag:
    patch:
      operationId: submitFlag
      tags: [Contributions]
      summary: Submit a flag
      description: |
        Applies a signed flag transaction: the named records become `Flagged`. The body is the signed
        transaction as hex, as plain text. Do not wrap it in JSON quotes.

        The reward is paid per identifier of every flagged record, at the flagging rate of the caller's company
        type. Records the company uploaded itself, or that name it as the source, are flagged without a reward.
        A record can be flagged once. When one record of the transaction cannot be flagged, nothing is flagged.

        Sending the same signed transaction again within 30 days returns the first answer and changes nothing.
      requestBody:
        required: true
        content:
          text/plain:
            schema:
              type: string
              description: The signed transaction as hex. White space is ignored.
            examples:
              signedTransaction:
                summary: Signed transaction (shortened)
                value: 04a1b2c3d4e5f60718293a4b5c6d7e8f04a1b2c3d4e5f60718293a4b5c6d7e8f
      responses:
        '200':
          description: The flag is applied.
          content:
            application/json:
              schema:
                type: object
                required: [status, data]
                properties:
                  status:
                    $ref: '#/components/schemas/StatusOk'
                  data:
                    $ref: '#/components/schemas/FlagResult'
              examples:
                rewarded:
                  summary: A record of another company
                  value:
                    status: {code: 0, name: Ok}
                    data:
                      rewarded: 10
                ownRecord:
                  summary: An own record
                  value:
                    status: {code: 0, name: Ok}
                    data:
                      rewarded: 0
        '400':
          description: The body is empty, the transaction is not valid, or it names a privileged record.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                emptyBody:
                  $ref: '#/components/examples/MessageNotReadable'
                transaction:
                  $ref: '#/components/examples/TransactionNotReadable'
                tooMany:
                  $ref: '#/components/examples/TooManyEntries'
                content:
                  $ref: '#/components/examples/InstructionType'
                privileged:
                  $ref: '#/components/examples/PrivilegedRecord'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: A named record does not exist, or the company of the caller does not exist.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                notFound:
                  summary: Code 60, no such record
                  value:
                    status:
                      code: 60
                      name: ContributionNotFoundError
                      message: "Contribution with asset definition `00000000-0000-7000-8000-000000000009` not found"
                    data: null
                peerNotFound:
                  $ref: '#/components/examples/PeerNotFound'
        '409':
          $ref: '#/components/responses/ExpiredOrFlagged'
        '422':
          $ref: '#/components/responses/TokenNotReadable'
        '500':
          $ref: '#/components/responses/InternalError'
        '503':
          description: The reward tables are not configured on the platform.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                rewardsNotSet:
                  $ref: '#/components/examples/RewardsNotSet'

  /data/api/v1/contribution-management/contribution/{id}:
    get:
      operationId: lookupContribution
      tags: [Contributions]
      summary: Look up an identifier
      description: |
        Returns the active records that cover an identifier. The lookup is free of charge. Use it to find the
        `assetDefinitionId` of a record to flag.

        Matching rules:

        - A device (IMEI) matches a record with the same IMEI.
        - A single phone number or IPv4 address matches a record that is this value or a range that starts
          with it. A value inside a stored range that is not its first value is not found.
        - A range matches a stored record with exactly this range. It also matches a stored record that shares
          a value with it and whose first value begins with the characters that both ends of the asked range
          have in common. Other overlapping records are not found, so ask with the identifier or range as it
          is stored.
        - Email addresses and URLs are not found by this route.

        Flagged and expired records are not returned. A privileged record is returned only to its own company
        and to the companies it has approved.
      parameters:
        - name: id
          in: path
          required: true
          description: A phone number in E.164 form with `+`, an IPv4 address, a range of either (`first-last`), or a 15-digit IMEI.
          schema:
            type: string
          examples:
            phone:
              summary: A phone number
              value: "+447700900501"
            range:
              summary: A range of phone numbers
              value: "+447700900510-+447700900514"
            address:
              summary: An IPv4 address
              value: 198.51.100.9
            device:
              summary: A device
              value: "356938035643809"
      responses:
        '200':
          description: The records that cover the identifier. Never empty.
          content:
            application/json:
              schema:
                type: object
                required: [status, data]
                properties:
                  status:
                    $ref: '#/components/schemas/StatusOk'
                  data:
                    type: array
                    minItems: 1
                    items:
                      $ref: '#/components/schemas/Contribution'
              examples:
                found:
                  summary: One record
                  value:
                    status: {code: 0, name: Ok}
                    data:
                      - id: "+447700900501-+447700900501"
                        fraudType: Wangiri
                        origination: LV
                        destination: EE
                        expiryDate: "2026-03-16T10:00:00Z"
                        fraudStatus: Active
                        confidenceIndex: null
                        isPrivileged: false
                        peerId: example_telco
                        flagger: null
                        timestamp: "2026-01-15T10:00:00Z"
                        flagTimestamp: null
                        assetDefinitionId: 00000000-0000-7000-8000-000000000001
                        sourcePeerId: example_telco
        '400':
          description: The identifier has none of the accepted forms.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                identifier:
                  $ref: '#/components/examples/ArgumentNotValid'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: No active record covers the identifier.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                notFound:
                  summary: Code 60, nothing found
                  value:
                    status:
                      code: 60
                      name: ContributionNotFoundError
                      message: "No contributions found for provided id: `+447700900599`"
                    data: null
        '422':
          $ref: '#/components/responses/TokenNotReadable'
        '500':
          $ref: '#/components/responses/InternalError'

  /data/api/v1/contribution-management/contribution/download:
    get:
      operationId: downloadContributions
      tags: [Contributions]
      summary: Download contributions as CSV
      description: |
        Runs the same query as `GET /data/api/v1/contribution-management/contribution`, with the same parameters
        and the same charge, and answers with a CSV file. The totals of the query are in the `X-*` response
        headers.

        The file has a header line and one line per record. Lines end with CR LF. Columns: `Fraud type`,
        `ID start`, `ID end`, `Originating country`, `Terminating country`, `Timestamp`, `Fraud status`,
        `Confidence index` (reserved, always empty), `Expiry date`, `Uploader ID`, `Source ID`, `Flagger ID`, `Flag timestamp`,
        `Asset Definition ID`.

        Errors are answered as JSON in the envelope.
      parameters:
        - $ref: '#/components/parameters/Size'
        - $ref: '#/components/parameters/From'
        - $ref: '#/components/parameters/To'
        - $ref: '#/components/parameters/FraudTypes'
        - $ref: '#/components/parameters/Originations'
        - $ref: '#/components/parameters/Destinations'
        - $ref: '#/components/parameters/FetchMode'
        - $ref: '#/components/parameters/ConfidenceScore'
      responses:
        '200':
          description: The matching records as a CSV file.
          headers:
            Content-Disposition:
              description: Always `attachment; filename="contributions.csv"`.
              schema:
                type: string
            X-Contribution-Self:
              description: Number of returned records that are the company's own.
              schema:
                type: integer
            X-Contribution-Old:
              description: Number of returned records the company bought before.
              schema:
                type: integer
            X-Contribution-New:
              description: Number of returned records the company sees for the first time.
              schema:
                type: integer
            X-Contribution-New-With-CI:
              description: Reserved. Always 0.
              schema:
                type: integer
            X-Credits-Spent:
              description: Tokens taken from the balance by this download.
              schema:
                type: integer
            X-Balance-Left:
              description: Token balance after this download.
              schema:
                type: integer
            X-Contributions-Not-Returned:
              description: Number of matching records the balance did not cover.
              schema:
                type: integer
            X-Contributions-Not-Returned-Cost:
              description: Tokens needed for the records that were not returned.
              schema:
                type: integer
          content:
            text/csv:
              schema:
                type: string
              examples:
                file:
                  summary: Two records
                  value: "Fraud type,ID start,ID end,Originating country,Terminating country,Timestamp,Fraud status,Confidence index,Expiry date,Uploader ID,Source ID,Flagger ID,Flag timestamp,Asset Definition ID\r\nIPFraud,198.51.100.9,198.51.100.9,DK,PT,2026-01-15T10:00:00Z,Active,,2026-02-14T10:00:00Z,example_vendor,example_vendor,,,00000000-0000-7000-8000-000000000003\r\nIRSF,+447700900410,+447700900412,SE,GR,2026-01-15T10:00:00Z,Flagged,,2026-02-14T10:00:00Z,example_vendor,example_vendor,example_telco,2026-01-16T08:00:00Z,00000000-0000-7000-8000-000000000002\r\n"
        '400':
          $ref: '#/components/responses/BadQuery'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/ForbiddenOrNotCharged'
        '404':
          $ref: '#/components/responses/PeerNotFound'
        '422':
          $ref: '#/components/responses/TokenNotReadable'
        '500':
          $ref: '#/components/responses/InternalError'
        '503':
          $ref: '#/components/responses/PricesNotSet'

  /data/api/v1/contribution-management/contribution/price:
    get:
      operationId: getPrices
      tags: [Rates]
      summary: Get the query prices
      description: Returns what a query or download charges per identifier, in tokens.
      responses:
        '200':
          description: The prices.
          content:
            application/json:
              schema:
                type: object
                required: [status, data]
                properties:
                  status:
                    $ref: '#/components/schemas/StatusOk'
                  data:
                    $ref: '#/components/schemas/Prices'
              examples:
                prices:
                  summary: Prices per identifier
                  value:
                    status: {code: 0, name: Ok}
                    data:
                      price: 1
                      confidenceIndexPrice: 1
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/TokenNotReadable'
        '500':
          $ref: '#/components/responses/InternalError'
        '503':
          $ref: '#/components/responses/PricesNotSet'

  /data/api/v1/contribution-management/rewards:
    get:
      operationId: getRewards
      tags: [Rates]
      summary: Get the reward tables
      description: |
        Returns the tokens paid per identifier for an upload and for a flag, by company type and fraud type, and
        how the reward of an upload made for another company is split.
      responses:
        '200':
          description: The reward tables and the split ratio.
          content:
            application/json:
              schema:
                type: object
                required: [status, data]
                properties:
                  status:
                    $ref: '#/components/schemas/StatusOk'
                  data:
                    $ref: '#/components/schemas/Rewards'
              examples:
                rewards:
                  summary: Reward tables
                  value:
                    status: {code: 0, name: Ok}
                    data:
                      uploadRewardsTable:
                        LARGE_TELCO: {Wangiri: 10, IRSF: 10, StolenDevice: 10, IPFraud: 10, SMSA2P: 10, Flashcall: 10, Scam: 10}
                        MEDIUM_TELCO: {Wangiri: 10, IRSF: 10, StolenDevice: 10, IPFraud: 10, SMSA2P: 10, Flashcall: 10, Scam: 10}
                        SMALL_TELCO: {Wangiri: 10, IRSF: 10, StolenDevice: 10, IPFraud: 10, SMSA2P: 10, Flashcall: 10, Scam: 10}
                        VENDOR: {Wangiri: 10, IRSF: 10, StolenDevice: 10, IPFraud: 10, SMSA2P: 10, Flashcall: 10, Scam: 10}
                      flaggingRewardsTable:
                        LARGE_TELCO: {Wangiri: 10, IRSF: 10, StolenDevice: 10, IPFraud: 10, SMSA2P: 10, Flashcall: 10, Scam: 10}
                        MEDIUM_TELCO: {Wangiri: 10, IRSF: 10, StolenDevice: 10, IPFraud: 10, SMSA2P: 10, Flashcall: 10, Scam: 10}
                        SMALL_TELCO: {Wangiri: 10, IRSF: 10, StolenDevice: 10, IPFraud: 10, SMSA2P: 10, Flashcall: 10, Scam: 10}
                        VENDOR: {Wangiri: 10, IRSF: 10, StolenDevice: 10, IPFraud: 10, SMSA2P: 10, Flashcall: 10, Scam: 10}
                      uploaderRatio: 10
                      sourceRatio: 90
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/TokenNotReadable'
        '500':
          $ref: '#/components/responses/InternalError'
        '503':
          description: The reward split or the reward tables are not configured on the platform.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                splitNotSet:
                  summary: Code 73, the reward split is not configured
                  value:
                    status: {code: 73, name: ContributionRewardSplitRatioNotSetError, message: Contribution reward split ratio not set}
                    data: null
                rewardsNotSet:
                  $ref: '#/components/examples/RewardsNotSet'

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: The `accessToken` of a sign-in or refresh answer. Valid for 5 minutes.
    refreshToken:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: The `refreshToken` of a sign-in or refresh answer. Valid for 24 hours, works once. Used only by the refresh route.

  parameters:
    Size:
      name: size
      in: query
      required: false
      description: The most records to return. Without it all matching records are returned.
      schema:
        type: integer
        format: int32
        minimum: 0
      example: 50
    From:
      name: from
      in: query
      required: false
      description: |
        Return records uploaded at or after this time. An ISO 8601 date-time with an offset or `Z`.
        Encode a `+` of the offset as `%2B`.
      schema:
        type: string
        format: date-time
      example: "2026-01-01T00:00:00Z"
    To:
      name: to
      in: query
      required: false
      description: |
        Return records uploaded at or before this time. An ISO 8601 date-time with an offset or `Z`.
        Encode a `+` of the offset as `%2B`.
      schema:
        type: string
        format: date-time
      example: "2026-01-31T23:59:59Z"
    FraudTypes:
      name: ft
      in: query
      required: false
      description: |
        Return only records of these fraud types. Repeat the parameter for several types. Without it all types
        are returned. Names that are not fraud types are ignored. Not applied with `fetch-mode=SELF`.
      style: form
      explode: true
      schema:
        type: array
        items:
          $ref: '#/components/schemas/FraudType'
      example: [Wangiri, IRSF]
    Originations:
      name: org
      in: query
      required: false
      description: Return only records with one of these origination countries (ISO 3166-1 alpha-2). Repeat the parameter for several countries.
      style: form
      explode: true
      schema:
        type: array
        items:
          type: string
      example: [GB, IS]
    Destinations:
      name: dst
      in: query
      required: false
      description: Return only records with one of these destination countries (ISO 3166-1 alpha-2). Repeat the parameter for several countries.
      style: form
      explode: true
      schema:
        type: array
        items:
          type: string
      example: [NZ, FJ]
    FetchMode:
      name: fetch-mode
      in: query
      required: false
      description: |
        Which records to return.

        - `DEFAULT`: own records, records bought before, and records not seen before, which are bought.
        - `NEW`: only records that other companies uploaded and that the company has never bought. They are
          bought. A record another company uploaded with the caller's company as its source is included.
        - `OLD`: only own records and records bought before. Nothing is charged.
        - `SELF`: only records the company uploaded itself. Records that name it as the source are not
          included, and `ft` is not applied. Nothing is charged.
      schema:
        type: string
        enum: [DEFAULT, NEW, OLD, SELF]
        default: DEFAULT
      example: DEFAULT
    ConfidenceScore:
      name: confidence-score
      in: query
      required: false
      description: Reserved. Ignored; always empty.
      schema:
        type: boolean
        default: false
      example: false

  responses:
    Tokens:
      description: The session tokens.
      content:
        application/json:
          schema:
            type: object
            required: [status, data]
            properties:
              status:
                $ref: '#/components/schemas/StatusOk'
              data:
                $ref: '#/components/schemas/Tokens'
          examples:
            tokens:
              summary: Access and refresh token
              value:
                status: {code: 0, name: Ok}
                data:
                  accessToken: eyJ...access
                  refreshToken: eyJ...refresh
                  expirationTime: "2026-01-15T10:05:00Z"
    Empty:
      description: Done. `data` is an empty object.
      content:
        application/json:
          schema:
            type: object
            required: [status, data]
            properties:
              status:
                $ref: '#/components/schemas/StatusOk'
              data:
                type: object
                description: Always empty.
          examples:
            done:
              summary: Done
              value:
                status: {code: 0, name: Ok}
                data: {}
    Transaction:
      description: The unsigned transaction to sign.
      content:
        application/json:
          schema:
            type: object
            required: [status, data]
            properties:
              status:
                $ref: '#/components/schemas/StatusOk'
              data:
                type: string
                description: The unsigned transaction as hex. Sign it with the signing key pair and send it to the submit route.
          examples:
            transaction:
              summary: Unsigned transaction (shortened)
              value:
                status: {code: 0, name: Ok}
                data: 04a1b2c3d4e5f60718293a4b5c6d7e8f
    Unauthorized:
      description: The `Authorization` header is missing or malformed, the session has ended, or the token is expired or not valid.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            missingHeader:
              $ref: '#/components/examples/MissingHeader'
            sessionEnded:
              $ref: '#/components/examples/SessionEnded'
            expired:
              $ref: '#/components/examples/TokenExpired'
            tokenSignature:
              $ref: '#/components/examples/TokenSignature'
    TokenNotReadable:
      description: The token in the `Authorization` header cannot be read.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            tokenNotReadable:
              summary: Code 17, the token cannot be read
              value:
                status: {code: 17, name: InvalidToken, message: Could not parse token to JWT}
                data: null
    Forbidden:
      description: The user is blocked or not yet approved.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            blocked:
              $ref: '#/components/examples/Blocked'
            notApproved:
              $ref: '#/components/examples/NotApproved'
    ForbiddenBlocked:
      description: The user is blocked.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            blocked:
              $ref: '#/components/examples/Blocked'
    ForbiddenOrNotCharged:
      description: The user is blocked or not yet approved, or the query could not be charged.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            blocked:
              $ref: '#/components/examples/Blocked'
            notApproved:
              $ref: '#/components/examples/NotApproved'
            notCharged:
              summary: Code 48, the charge could not be made
              description: The balance of the company kept changing while the query ran. Retry.
              value:
                status: {code: 48, name: NotEnoughCreditsError, message: example_telco has not enough tokens}
                data: null
    BadQuery:
      description: A query parameter is not valid.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            wrongType:
              summary: Code 49, wrong size or fetch-mode
              value:
                status:
                  code: 49
                  name: MalformedParametersError
                  message: "'fetch-mode' value 'EVERYTHING' is incorrect. Required 'ContributionFetchMode' type"
                data: null
            wrongDate:
              summary: Code 11, wrong from or to
              value:
                status: {code: 11, name: ArgumentNotValid, message: Argument not valid}
                data: "Date-time data format error, please refer to example 2024-08-22T07:37:41Z"
    PeerNotFound:
      description: The company of the caller does not exist.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            peerNotFound:
              $ref: '#/components/examples/PeerNotFound'
    PricesNotSet:
      description: The prices are not configured on the platform.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            pricesNotSet:
              summary: Code 57, the prices are not configured
              value:
                status: {code: 57, name: ContributionPricesNotSetError, message: Contribution prices not set}
                data: null
    ExpiredOrFlagged:
      description: A named record has expired or is already flagged.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            expiredOrFlagged:
              summary: Code 61, expired or already flagged
              value:
                status: {code: 61, name: ExpiredContributionFlagError, message: Expired contribution can't be flagged}
                data: null
    InternalError:
      description: The request failed on the server side.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            internal:
              summary: Code 1, internal error
              value:
                status: {code: 1, name: InternalError, message: Internal server error}
                data: null

  examples:
    MissingHeader:
      summary: Code 4, no Authorization header
      value:
        status: {code: 4, name: InvalidBearer, message: "Request does not contain `Authorization` header"}
        data: null
    SessionEnded:
      summary: Code 4, the session has ended
      value:
        status: {code: 4, name: InvalidBearer, message: Invalid access token}
        data: null
    TokenExpired:
      summary: Code 6, the token has expired
      value:
        status: {code: 6, name: TokenExpired, message: Token already expired}
        data: null
    TokenSignature:
      summary: Code 2, the token signature is not valid
      value:
        status: {code: 2, name: InvalidSignature, message: Invalid signature}
        data: null
    Blocked:
      summary: Code 59, the user is blocked
      value:
        status: {code: 59, name: AccessDeniedError, message: Access denied for a blocked user}
        data: null
    NotApproved:
      summary: Code 59, the user is not yet approved
      value:
        status: {code: 59, name: AccessDeniedError, message: Access denied for a not approved user}
        data: null
    UserNotFound:
      summary: Code 3, no such user
      value:
        status: {code: 3, name: UserNotFound, message: "User with email `alice@example.com` not found"}
        data: null
    MessageNotReadable:
      summary: Code 12, the body is missing or not readable
      value:
        status: {code: 12, name: MessageNotReadable, message: Http message not readable}
        data: null
    ArgumentNotValid:
      summary: Code 11, an identifier has the wrong form
      value:
        status: {code: 11, name: ArgumentNotValid, message: Argument not valid}
        data: null
    TooManyEntries:
      summary: Code 15, more than 5000 entries
      value:
        status: {code: 15, name: InvalidTransaction, message: "Invalid transaction, limit is 5000 entries per request"}
        data: "Invalid transaction, limit is 5000 entries per request"
    TransactionNotReadable:
      summary: Code 15, the transaction cannot be read
      value:
        status: {code: 15, name: InvalidTransaction, message: Transaction is not readable}
        data: Transaction is not readable
    InstructionType:
      summary: Code 16, the transaction has the wrong content
      value:
        status: {code: 16, name: InvalidInstructionType, message: Invalid instruction type}
        data: null
    TypeMismatch:
      summary: Code 16, the identifier does not fit the fraud type
      value:
        status: {code: 16, name: InvalidInstructionType, message: "Type of contribution 356938035643809 doesn't match with value"}
        data: "Type of contribution 356938035643809 doesn't match with value"
    InvalidCountry:
      summary: Code 54, a country code is not valid
      value:
        status: {code: 54, name: InvalidContributionCountryCodeError, message: "Incorrect country code: ZZ"}
        data: null
    InvalidSource:
      summary: Code 70, the source company cannot be named
      value:
        status: {code: 70, name: ContributionSourceError, message: "Source peer 'example_vendor' doesn't exist"}
        data: null
    LifetimeMissing:
      summary: Code 28, no record lifetime for a fraud type
      value:
        status: {code: 28, name: IncorrectMetadataError, message: "Contribution time to live not found for type: Scam"}
        data: null
    RewardsNotSet:
      summary: Code 34, the reward tables are not configured
      value:
        status: {code: 34, name: RewardsTableNotSetError, message: Rewards table not set}
        data: null
    LifetimesNotSet:
      summary: Code 66, the record lifetimes are not configured
      value:
        status: {code: 66, name: ContributionTimeToLiveTableNotSetError, message: Contribution time to live table not set}
        data: null
    PrivilegedRecord:
      summary: Code 38, a privileged record
      value:
        status: {code: 38, name: PrivilegedContributionModificationError, message: Privileged contribution can't be changed}
        data: null
    PeerNotFound:
      summary: Code 43, the company does not exist
      value:
        status: {code: 43, name: PeerNotFoundError, message: "Peer `example_telco` not found"}
        data: null

  schemas:
    StatusOk:
      type: object
      description: Status of a successful answer.
      required: [code, name]
      properties:
        code:
          type: integer
          const: 0
          description: Always `0`.
        name:
          type: string
          const: Ok
          description: Always `Ok`.
    ErrorStatus:
      type: object
      description: Status of a failed answer.
      required: [code, name]
      properties:
        code:
          type: integer
          description: The numbered error. Not the HTTP status. See the table of error codes.
          examples: [59]
        name:
          type: string
          description: The name of the numbered error.
          examples: [AccessDeniedError]
        message:
          type: string
          description: A text for humans. It can change; do not match on it.
          examples: [Access denied for a blocked user]
    Error:
      type: object
      description: |
        The envelope of a failed answer. The HTTP status is 4xx or 5xx; `status.code` holds the numbered error
        listed in the table of error codes in the introduction.
      required: [status, data]
      properties:
        status:
          $ref: '#/components/schemas/ErrorStatus'
        data:
          type: [string, object, 'null']
          description: "Always present. `null`, a text with details of a validation failure, or an object: the sign-in answer with code 80 lists the second sign-in steps of the user in it."
    FraudType:
      type: string
      description: The kind of fraud. Spelling and case are exact.
      enum: [Wangiri, IRSF, StolenDevice, IPFraud, SMSA2P, Flashcall, Scam]
    PeerType:
      type: string
      description: The type of a company. It selects the reward rates.
      enum: [LARGE_TELCO, MEDIUM_TELCO, SMALL_TELCO, VENDOR]
    SignInRequest:
      type: object
      required: [email, signature, authPublicKeyHex]
      properties:
        email:
          type: string
          format: email
          description: Email of the user.
        signature:
          type: string
          description: |
            Ed25519 signature, as hex, over the BLAKE2b-256 digest of the UTF-8 email with the lowest bit of the
            last digest byte set. Made with the private key of the authorization key pair. A `0x` prefix is accepted.
        authPublicKeyHex:
          type: string
          description: Public key of the user's authorization key pair, 32 bytes as lower-case hex without a prefix. It must be written exactly as the key registered for the user.
        authCode:
          type: string
          description: The one-time code of the second step, emailed to the user or shown by the authenticator app. Needed only when the first call answered 428.
          examples: ["123456"]
        method:
          type: string
          description: Which second step `authCode` answers. Needed when the first call answered 428 with code 80. `passkey` needs a browser and cannot be used by an API client.
          enum: [email, totp, passkey]
    Tokens:
      type: object
      required: [accessToken, refreshToken, expirationTime]
      properties:
        accessToken:
          type: string
          description: Token for the `Authorization` header of every route but the refresh. Valid for 5 minutes.
        refreshToken:
          type: string
          description: Token for the refresh route. Valid for 24 hours, works once.
        expirationTime:
          type: string
          format: date-time
          description: When the access token expires. ISO 8601, UTC.
    Account:
      type: object
      description: A user and the user's company. For a user who is not yet approved the company members marked as nullable are `null`.
      required: [irohaPubKeyHex, peerCompanyName, email, accountId, authPubKeyHex, salt, role, status, phoneNumber, firstName, lastName, roleName, registrationDate, twoFactorAuthEnabled]
      properties:
        irohaPubKeyHex:
          type: string
          description: The public key of the user's signing key pair, as hex. Always present.
        peerCompanyName:
          type: string
          description: Display name of the company. Always present.
        peerOperatingCountry:
          type: [string, 'null']
          description: Country the company operates in.
        peerType:
          description: Type of the company.
          oneOf:
            - $ref: '#/components/schemas/PeerType'
            - type: 'null'
        peerConnectionType:
          type: [string, 'null']
          description: How the company connects to the Exchange.
          enum: [Web, Back, Node, null]
        peerGroup:
          type: [string, 'null']
          description: Group of companies the company belongs to, if any.
        isPrivileged:
          type: [boolean, 'null']
          description: Whether the records of the company are privileged, that is shown only to companies it has approved.
        subscriptionType:
          type: [string, 'null']
          description: Subscription of the company. Queries and downloads are charged in tokens on `FREEMIUM`. On `TRIAL` (a trial of the paid subscription) and `PAID` they are not charged.
          enum: [FREEMIUM, TRIAL, PAID, null]
        subscriptionExpiryDate:
          type: [string, 'null']
          description: When the subscription ends, as a date and time without an offset, or `null`.
          examples: ["2026-12-31T00:00"]
        email:
          type: string
          format: email
          description: Email of the user.
        accountId:
          type: string
          description: Account of the user, in the form `name@company`. The part after `@` is the id of the company.
        authPubKeyHex:
          type: string
          description: The public key of the user's authorization key pair, as hex.
        salt:
          type: string
          description: Salt the client uses to derive the user's keys.
        role:
          type: string
          description: "`ROLE_DOMAIN_ADMIN` is the admin of a company, `ROLE_PEER` another user of a company, `ROLE_ADMIN` the admin of the platform."
          enum: [ROLE_ADMIN, ROLE_DOMAIN_ADMIN, ROLE_PEER]
        status:
          type: string
          description: "`DRAFT` is a registered user who is not yet approved."
          enum: [ACTIVE, DRAFT, BLOCKED]
        phoneNumber:
          type: string
          description: Phone number of the user in E.164 form, or an empty text.
        firstName:
          type: string
          description: First name.
        lastName:
          type: string
          description: Last name.
        roleName:
          type: string
          description: Job title of the user.
        registrationDate:
          type: string
          format: date-time
          description: Registration date recorded for the user. ISO 8601, UTC.
        twoFactorAuthEnabled:
          type: boolean
          description: Whether sign-in asks for a second step.
    Balance:
      type: object
      required: [tokenId, balance]
      properties:
        tokenId:
          type: object
          description: Names the balance.
          required: [definitionId, accountId]
          properties:
            definitionId:
              type: string
              description: Always `credit#admin`.
            accountId:
              type: string
              description: "`admin@` followed by the id of the company."
        balance:
          type: integer
          format: int64
          description: Tokens the company holds.
    UploadLimit:
      type: object
      required: [used, total, updatePeriod, nextUpdate]
      properties:
        used:
          type: integer
          format: int64
          description: Records the company has used of the limit in the current period. `total` minus what is left; never below 0.
        total:
          type: integer
          format: int64
          description: Records a company may store per period, as set on the platform.
        updatePeriod:
          type: integer
          format: int64
          description: Length of the period in seconds.
        nextUpdate:
          type: string
          format: date-time
          description: When the count is reset. ISO 8601, UTC.
    UploadEntry:
      type: object
      required: [id, fraudType]
      properties:
        id:
          type: string
          description: |
            The identifier: a phone number in E.164 form with `+`, an IPv4 address, a range of either
            (`first-last`), a 15-digit IMEI, an email address or a URL. It must fit the fraud type.
          examples: ["+447700900201"]
        fraudType:
          $ref: '#/components/schemas/FraudType'
        origination:
          type: string
          description: |
            Origination country, ISO 3166-1 alpha-2. Required, except for `Scam` and for numbers that start with
            `+882` or `+883`, where it can be an empty text or left out.
          examples: [GB]
        destination:
          type: string
          description: Destination country, ISO 3166-1 alpha-2. Required, except for `Scam`, where it can be an empty text or left out.
          examples: [FR]
        sourcePeerId:
          type: string
          description: |
            Id of the company the record comes from, when it is not the uploader. The company must exist. The
            reward is then split between uploader and source. A privileged company can name only itself.
          examples: [example_vendor]
    UploadResult:
      type: object
      required: [tokenIds, rewarded]
      properties:
        tokenIds:
          type: array
          description: One element per entry of the upload, in the same order.
          items:
            type: object
            required: [definitionId, accountId]
            properties:
              definitionId:
                type: string
                description: The id of the stored record followed by `#contribution`. Accepted by the flag assemble route.
              accountId:
                type: string
                description: Account of the uploading user.
        rewarded:
          type: integer
          format: int64
          description: Tokens added to the balance of the uploader's company for this upload.
    FlagRequest:
      type: object
      required: [assetDefinitionIds]
      properties:
        assetDefinitionIds:
          type: array
          maxItems: 5000
          description: The records to flag. Each is the `assetDefinitionId` of a query or lookup answer, or the `definitionId` of an upload answer.
          items:
            type: string
    FlagResult:
      type: object
      required: [rewarded]
      properties:
        rewarded:
          type: integer
          format: int64
          description: Tokens added to the balance of the caller's company for this flag.
    Contribution:
      type: object
      description: A stored fraud record.
      required: [id, fraudType, origination, destination, expiryDate, fraudStatus, confidenceIndex, isPrivileged, peerId, flagger, timestamp, flagTimestamp, assetDefinitionId, sourcePeerId]
      properties:
        id:
          type: string
          description: The identifier as stored. A single phone number or IPv4 address is stored as a range of itself, `value-value`.
        fraudType:
          $ref: '#/components/schemas/FraudType'
        origination:
          type: string
          description: Origination country, ISO 3166-1 alpha-2, or an empty text.
        destination:
          type: string
          description: Destination country, ISO 3166-1 alpha-2, or an empty text.
        expiryDate:
          type: string
          format: date-time
          description: When the record expires. ISO 8601, UTC.
        fraudStatus:
          type: string
          description: "`Flagged` means a member has marked the record as wrong."
          enum: [Active, Flagged]
        confidenceIndex:
          type: [number, 'null']
          description: Reserved. Ignored; always empty.
        isPrivileged:
          type: boolean
          description: Whether the record is privileged.
        peerId:
          type: string
          description: Id of the company that uploaded the record.
        flagger:
          type: [string, 'null']
          description: Id of the company that flagged the record, or `null`.
        timestamp:
          type: string
          format: date-time
          description: When the record was uploaded. ISO 8601, UTC.
        flagTimestamp:
          type: [string, 'null']
          format: date-time
          description: When the record was flagged, or `null`.
        assetDefinitionId:
          type: string
          description: The id of the record. Pass it to the flag assemble route.
        sourcePeerId:
          type: string
          description: Id of the company the record comes from. Equal to `peerId` unless the upload named another source.
    QueryDetails:
      type: object
      description: What a query returned and what it cost.
      required: [self, old, new, newWithConfidenceIndex, creditsSpent, balanceLeft, contributionsNotReturned, contributionsNotReturnedCost]
      properties:
        self:
          type: integer
          description: Returned records that are the company's own.
        old:
          type: integer
          description: Returned records the company bought before.
        new:
          type: integer
          description: Returned records the company sees for the first time.
        newWithConfidenceIndex:
          type: integer
          description: Reserved. Ignored; always empty.
        creditsSpent:
          type: integer
          format: int64
          description: Tokens taken from the balance by this query.
        balanceLeft:
          type: integer
          format: int64
          description: Tokens the company holds after this query.
        contributionsNotReturned:
          type: integer
          description: Matching records the balance did not cover.
        contributionsNotReturnedCost:
          type: integer
          format: int64
          description: Tokens needed for the records that were not returned.
    QueryResult:
      type: object
      required: [contributions, details]
      properties:
        contributions:
          type: array
          description: The matching records, latest upload first.
          items:
            $ref: '#/components/schemas/Contribution'
        details:
          $ref: '#/components/schemas/QueryDetails'
    Prices:
      type: object
      required: [price, confidenceIndexPrice]
      properties:
        price:
          type: integer
          format: int64
          description: Tokens charged per identifier of a record.
        confidenceIndexPrice:
          type: integer
          format: int64
          description: Reserved. Ignored.
    RewardTable:
      type: object
      description: Tokens per identifier, by company type and then by fraud type.
      propertyNames:
        $ref: '#/components/schemas/PeerType'
      additionalProperties:
        type: object
        description: Tokens per identifier for each fraud type.
        propertyNames:
          $ref: '#/components/schemas/FraudType'
        additionalProperties:
          type: integer
          format: int64
    Rewards:
      type: object
      required: [uploadRewardsTable, flaggingRewardsTable, uploaderRatio, sourceRatio]
      properties:
        uploadRewardsTable:
          description: Tokens paid per uploaded identifier.
          $ref: '#/components/schemas/RewardTable'
        flaggingRewardsTable:
          description: Tokens paid per flagged identifier.
          $ref: '#/components/schemas/RewardTable'
        uploaderRatio:
          type: integer
          format: int64
          description: Percent of the reward the uploader keeps for a record uploaded for another company.
        sourceRatio:
          type: integer
          format: int64
          description: Percent of the reward that goes to the source company.
