/api/raida/countcoins

GET

Query all 25 RAIDA servers to retrieve a comprehensive count of all coins stored in the network, broken down by denomination.

Description

The /api/raida/countcoins endpoint executes the RAIDA Audit command (0x0003) across all 25 RAIDA servers in parallel. This public command queries the global coin database on each RAIDA server, returning a complete breakdown of coin counts by denomination.

This endpoint is fully implemented and production-ready, utilizing multi-threaded execution to query all RAIDAs simultaneously for optimal performance.

💡 Use Case

This endpoint is perfect for:

  • Network statistics and monitoring
  • Total CloudCoin supply verification
  • RAIDA health checking and consensus monitoring
  • Denomination distribution analysis
  • Network transparency and auditing
⚠️ Important Notes
  • Global Network Count: This endpoint returns the total count of ALL coins stored across the entire RAIDA network, not user-specific balances.
  • Public Command: No authentication is required. This is a read-only operation accessible to anyone.
  • Consensus Validation: Results from multiple RAIDAs allow verification of network consistency and health.
  • Not a User Balance: For user-specific wallet balances, use /api/wallet/balance instead.

RAIDA Protocol Details

This endpoint uses the Audit (Count Coins) command with the following protocol:

RAIDA Command Specification

Command Code 0x0003
Audit / Count Coins command
Command Group 0x00 (Status)
Status and information commands
Authentication Public (None)
No admin password required despite API compatibility layer
Request Format Challenge(16) + 3E3E(2)
16-byte random challenge + 2-byte terminator (0x3E3E)
Response Format [DN(1) + Count(4)] × N + 3E3E(2)
Denomination byte + 4-byte count (little-endian), repeated for N denominations, followed by 2-byte terminator

Denomination Reference

CloudCoin denominations are encoded as signed bytes ranging from -8 to +11:

Fractional Units:
  -8: 0.00000001    -7: 0.0000001    -6: 0.000001    -5: 0.00001
  -4: 0.0001        -3: 0.001        -2: 0.01        -1: 0.1

Standard Denominations:
   0: 1             1: 5             2: 25           3: 100
   4: 250           5: 1000          6: 5000         7: 25000
   8: 100000        9: 250000       10: 1000000

Special:
  11: Key/NFT/Special

Parameters

This endpoint does not require any parameters.

Response

Returns a JSON object with comprehensive coin count data from all responding RAIDA servers.

Response Properties

status string
Always "success" when at least one RAIDA responds.
operation string
Always "raida_audit".
successful_responses integer
Number of RAIDA servers that responded successfully (0-25).
total_raidas integer
Total number of RAIDA servers queried (always 25).
raida_responses array
Array of response objects, one per successful RAIDA server.

RAIDA Response Object Properties

raida_id integer
RAIDA server identifier (0-24).
denominations array
Array of denomination objects showing count per denomination.
total_value integer
Total value of all coins stored on this RAIDA (in whole CloudCoin units).

Denomination Object Properties

denomination string
Denomination value as human-readable string (e.g., "1", "25", "100", "250").
count integer
Number of coins of this denomination stored on this RAIDA.

Example Success Response

{
  "status": "success",
  "operation": "raida_audit",
  "successful_responses": 24,
  "total_raidas": 25,
  "raida_responses": [
    {
      "raida_id": 0,
      "denominations": [
        {
          "denomination": "1",
          "count": 1500
        },
        {
          "denomination": "5",
          "count": 800
        },
        {
          "denomination": "25",
          "count": 450
        },
        {
          "denomination": "100",
          "count": 200
        },
        {
          "denomination": "250",
          "count": 100
        }
      ],
      "total_value": 50000
    },
    {
      "raida_id": 1,
      "denominations": [
        {
          "denomination": "1",
          "count": 1498
        },
        {
          "denomination": "5",
          "count": 802
        },
        {
          "denomination": "25",
          "count": 451
        },
        {
          "denomination": "100",
          "count": 199
        },
        {
          "denomination": "250",
          "count": 101
        }
      ],
      "total_value": 50123
    }
  ]
}

Error Response - No RAIDAs Available

{
  "status": "error",
  "message": "No RAIDA servers responded successfully"
}

Implementation Details

The endpoint follows this execution flow:

  1. Request Generation: Creates Audit (0x0003) requests for all 25 RAIDA servers
  2. Parallel Execution: Sends requests to all RAIDAs simultaneously using thread pool (10-second timeout)
  3. Response Parsing: Extracts denomination/count pairs from each RAIDA's response
  4. Value Calculation: Computes total value per RAIDA based on denomination × count
  5. JSON Construction: Builds comprehensive response with all successful RAIDA data
📊 Network Consensus

By comparing results across multiple RAIDAs, you can:

  • Verify network consistency (all RAIDAs should have similar counts)
  • Identify discrepancies that may indicate synchronization issues
  • Monitor RAIDA health (servers with significantly different counts may have issues)
  • Validate total coin supply across the network

Examples

JavaScript (fetch)

const API_HOST = 'http://localhost:8080';

async function countNetworkCoins() {
    try {
        const response = await fetch(`${API_HOST}/api/raida/countcoins`);
        const result = await response.json();

        if (result.status === 'success') {
            console.log(`Network Audit Results:`);
            console.log(`Successful RAIDAs: ${result.successful_responses}/${result.total_raidas}`);
            console.log('');

            // Calculate network totals
            let networkTotal = 0;
            let denominationTotals = {};

            result.raida_responses.forEach(raida => {
                console.log(`RAIDA ${raida.raida_id}: ${raida.total_value} CloudCoins`);
                networkTotal += raida.total_value;

                raida.denominations.forEach(denom => {
                    if (!denominationTotals[denom.denomination]) {
                        denominationTotals[denom.denomination] = 0;
                    }
                    denominationTotals[denom.denomination] += denom.count;
                });
            });

            console.log('');
            console.log(`Average per RAIDA: ${Math.round(networkTotal / result.successful_responses)} CloudCoins`);
            console.log('');
            console.log('Denomination Distribution:');
            Object.keys(denominationTotals).sort((a, b) => parseFloat(a) - parseFloat(b)).forEach(denom => {
                console.log(`  ${denom}: ${denominationTotals[denom]} coins`);
            });
        } else {
            console.error('Error:', result.message);
        }
    } catch (error) {
        console.error('Network error:', error);
    }
}

countNetworkCoins();

cURL

# Count all coins in RAIDA network
curl -X GET "http://localhost:8080/api/raida/countcoins"

# Pretty-print JSON output with jq
curl -X GET "http://localhost:8080/api/raida/countcoins" | jq .

# Extract only successful response count
curl -X GET "http://localhost:8080/api/raida/countcoins" | jq '.successful_responses'

# Show total value for each RAIDA
curl -X GET "http://localhost:8080/api/raida/countcoins" | \
  jq '.raida_responses[] | "RAIDA \(.raida_id): \(.total_value) CloudCoins"'

Go

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

const ApiHost = "http://localhost:8080"

type Denomination struct {
    Denomination string `json:"denomination"`
    Count        int    `json:"count"`
}

type RaidaResponse struct {
    RaidaID        int            `json:"raida_id"`
    Denominations  []Denomination `json:"denominations"`
    TotalValue     int            `json:"total_value"`
}

type AuditResponse struct {
    Status              string          `json:"status"`
    Operation           string          `json:"operation"`
    SuccessfulResponses int             `json:"successful_responses"`
    TotalRaidas         int             `json:"total_raidas"`
    RaidaResponses      []RaidaResponse `json:"raida_responses"`
}

func main() {
    resp, err := http.Get(fmt.Sprintf("%s/api/raida/countcoins", ApiHost))
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, _ := ioutil.ReadAll(resp.Body)

    var result AuditResponse
    if err := json.Unmarshal(body, &result); err != nil {
        panic(err)
    }

    if result.Status == "success" {
        fmt.Printf("Network Audit Results:\n")
        fmt.Printf("Successful RAIDAs: %d/%d\n\n", result.SuccessfulResponses, result.TotalRaidas)

        networkTotal := 0
        for _, raida := range result.RaidaResponses {
            fmt.Printf("RAIDA %d: %d CloudCoins\n", raida.RaidaID, raida.TotalValue)
            networkTotal += raida.TotalValue
        }

        avgPerRaida := networkTotal / result.SuccessfulResponses
        fmt.Printf("\nAverage per RAIDA: %d CloudCoins\n", avgPerRaida)
    } else {
        fmt.Printf("Error occurred\n")
    }
}

Python

import requests
from collections import defaultdict

API_HOST = "http://localhost:8080"

def count_network_coins():
    try:
        response = requests.get(f"{API_HOST}/api/raida/countcoins")
        result = response.json()

        if result['status'] == 'success':
            print("Network Audit Results:")
            print(f"Successful RAIDAs: {result['successful_responses']}/{result['total_raidas']}\n")

            # Calculate network totals
            network_total = 0
            denomination_totals = defaultdict(int)

            for raida in result['raida_responses']:
                print(f"RAIDA {raida['raida_id']}: {raida['total_value']} CloudCoins")
                network_total += raida['total_value']

                for denom in raida['denominations']:
                    denomination_totals[denom['denomination']] += denom['count']

            avg_per_raida = network_total // result['successful_responses']
            print(f"\nAverage per RAIDA: {avg_per_raida} CloudCoins\n")

            print("Denomination Distribution:")
            for denom in sorted(denomination_totals.keys(), key=lambda x: float(x)):
                print(f"  {denom}: {denomination_totals[denom]} coins")
        else:
            print(f"Error: {result.get('message', 'Unknown error')}")

    except requests.exceptions.RequestException as e:
        print(f"Network error: {e}")

if __name__ == "__main__":
    count_network_coins()

Error Responses

HTTP Status Codes

200 OK Success
At least one RAIDA responded successfully with coin count data.
503 Service Unavailable Network Error
No RAIDA servers responded successfully. Network may be down or unreachable.

Related Endpoints

/api/wallet/balance

Get user-specific wallet balance showing authenticated coins in the Bank folder.

/api/program/echo

Test RAIDA network connectivity and health status of all 25 servers.

/api/raida/version

Query RAIDA server version information across all 25 servers.