/api/coins/authenticate

GET

Authenticates coins from Bank and Fracked folders using the RAIDA Detect protocol to verify authenticity across all 25 RAIDA servers.

Description

The /api/coins/authenticate endpoint implements the RAIDA Detect command (0x010a) to authenticate CloudCoins with all 25 RAIDA servers simultaneously. This is the primary method for validating coin authenticity by verifying that each coin's Authenticity Numbers (ANs) match the records stored in the RAIDA network.

Authentication is performed by sending each coin's denomination, serial number, and 25 ANs to all RAIDA servers. Each RAIDA independently verifies the AN at its index and returns a pass/fail/error status. The coin's POWN (Proof of Ownership) string is updated with the results from each RAIDA.

How Authentication Works

The Detect protocol validates coins through parallel verification:

  1. Client sends coin data (DN, SN, ANs) to all 25 RAIDA servers simultaneously
  2. Each RAIDA checks if the coin's AN at its index matches its database record
  3. RAIDA returns status: Pass (authentic), Fail (counterfeit), or Error (network/server issue)
  4. Client updates the coin's POWN string with results from each RAIDA
  5. Coins with 13+ passes (out of 25) are considered authentic
Use Case

Use authentication when you need to:

  • Verify newly imported coins for the first time
  • Re-verify coins after network issues or failed operations
  • Update POWN strings after potential AN changes
  • Confirm coin authenticity before critical operations

RAIDA Detect Protocol

Command: 0x010a (Detect)

The Detect command is part of RAIDA command group 0x01 (Authentication). It verifies coin ownership by validating Authenticity Numbers against the RAIDA database.

Detect Request Format:
Challenge(16 bytes)
+ [DN(1) + SN(4) + AN(16)] × N coins
+ 3E3E (2-byte terminator)

Where:
- Challenge: 12 random bytes + 4-byte CRC32
- DN: Denomination byte (1 byte)
- SN: Serial Number (4 bytes, big endian)
- AN: Authenticity Number for this RAIDA (16 bytes)
- Terminator: Always 0x3E3E

Response Format

RAIDAs respond with one of four status codes indicating the authentication results:

Response Status Codes:
- STATUS_ALL_PASS (241/0xF1): All coins authenticated
  Response: 3E3E (2 bytes)

- STATUS_ALL_FAIL (242/0xF2): All coins failed
  Response: 3E3E (2 bytes)

- STATUS_MIXED (243/0xF3): Mixed results
  Response: Bitfield(N bytes) + 3E3E
  Bitfield: 1 bit per coin (1=pass, 0=fail)

- Error Codes (1-255 except above): Server errors
  Examples:
    - ERROR_INVALID_COMMAND (6)
    - ERROR_INVALID_PACKET_LENGTH (16)
    - ERROR_INVALID_CRC (37)
    - ERROR_TOO_MANY_COINS (45)
  Mark coins as 'e' (error) in POWN string
POWN String Encoding

Authentication results are encoded in the coin's POWN (Proof of Ownership) string:

  • 'p' (0x0A): Pass - RAIDA authenticated the coin
  • 'f' (0x0F): Fail - RAIDA rejected the coin (counterfeit)
  • 'e' (0x0E): Error - RAIDA returned an error code
  • 'n' (0x0C): No reply - RAIDA timed out (network issue)
  • 'u' (0x00): Untried - Not yet authenticated

Each position in the 25-character POWN string corresponds to a RAIDA (index 0-24).

Authentication Workflow

The authentication process follows a multi-step workflow to ensure safe coin handling:

Authentication Workflow:
1. Verify Grade folder is empty
   - Grade folder must be empty before starting
   - Prevents overwriting existing authenticated coins

2. Move coins from Bank/Fracked → Grade
   - Rename files with new Task ID in memo field
   - Preserves existing POWN strings during move

3. Copy Grade → Pending (backup)
   - Creates backup in case of network failure
   - Allows recovery if authentication is interrupted

4. Read all coins from Grade folder
   - Load coin data including ANs and POWN strings
   - Prepare for RAIDA communication

5. Generate Detect requests for all 25 RAIDAs
   - Create request packets with challenge + coin data
   - Each RAIDA gets coins' ANs at its index

6. Execute requests in parallel (all 25 RAIDAs)
   - Thread pool executes all RAIDAs simultaneously
   - Typical completion: 1-2 seconds vs ~25s sequential
   - Timeout: AI-calculated based on coin count (6-10 seconds)

7. Parse responses and update POWN strings
   - Update each RAIDA's position in POWN string
   - 'p' = pass, 'f' = fail, 'e' = error, 'n' = timeout

8. Write updated coins back to Grade folder
   - Coins now have current POWN strings
   - Ready for grading operation

9. Generate receipt file in Receipts folder
   - Detailed results including POWN strings
   - Task ID, timestamp, summary statistics

10. User runs Grade command to sort coins
    - 13+ passes → Bank (authentic)
    - 1-12 passes → Fracked (partial authentication)
    - 0 passes → Counterfeit (failed)
Why Two Steps? (Authenticate → Grade)

The authentication process is split into two commands for safety and flexibility:

  • Authenticate: Updates POWN strings, leaves coins in Grade folder
  • Grade: Sorts coins to final folders based on POWN status
  • This separation allows inspection of POWN strings before final sorting
  • Users can verify authentication results in receipt file first
  • Prevents accidental loss of coins due to network issues

Parameters

This endpoint does not require any parameters. It automatically operates on all coins in the Bank and Fracked folders of the active wallet.

Folder Requirements
  • Grade folder: Must be empty before authentication starts
  • Bank folder: Coins with 13+ passes (will be re-authenticated)
  • Fracked folder: Coins with 1-12 passes (will be re-authenticated)
  • Import folder coins are NOT authenticated (use import command first)

Response

Returns a JSON object with the authentication operation status.

Response Properties

status string
Always "success" when the operation completes.
operation string
Always "coins-authenticate".
message string
Human-readable message describing the operation result.
wallet string
Name of the active wallet where coins were authenticated.
note string
Instruction to check Grade folder and run grade command next.

Success Response

{
  "status": "success",
  "operation": "coins-authenticate",
  "message": "Authentication operation completed",
  "wallet": "Default",
  "note": "Check Grade folder for results, then run grade command"
}

Error Response - No Active Wallet

{
  "error": "No active wallet",
  "status": 400
}

Error Response - Authentication Failed

{
  "error": "Authentication operation failed",
  "status": 500
}

Authentication Results and Grading

After authentication completes, coins remain in the Grade folder with updated POWN strings. Run the /api/coins/grade command to sort them to final folders.

Grading Criteria (based on POWN string):
- 25 'p' (perfect):    → Bank (fully authenticated)
- 13-24 'p':           → Bank (authentic with some failures)
- 1-12 'p':            → Fracked (partial authentication)
- 0 'p' (all 'f'):     → Counterfeit (failed authentication)

Example POWN Strings:
- "ppppppppppppppppppppppppp" = 25/25 Pass → Bank
- "pppppppppppppnnnfppppppp" = 18/25 Pass → Bank
- "ppppppppppfffffnnnnnnnnn" = 10/25 Pass → Fracked
- "fffffffffffffffffffff" = 0/25 Pass → Counterfeit

Minimum Threshold:
- 13+ passes required for authenticity (majority consensus)
- Less than 13 passes = coin is not trusted as authentic
Authenticity Threshold

CloudCoin uses a 13-out-of-25 majority consensus for authenticity:

  • 25 RAIDA servers provide redundancy and fault tolerance
  • 13 is the minimum majority (52%) required for consensus
  • Allows up to 12 RAIDAs to fail/timeout without coin loss
  • Provides Byzantine fault tolerance against malicious actors

Receipt File Generation

Authentication generates a detailed receipt file in the wallet's Receipts folder with complete authentication results.

Receipt Format: YYYY-MM-DD_HH-MM-SS.detect.txt

=== Receipt ===
Type: Detect Authentication
Date: 2025-01-31 15:30:45
Task ID: Jan-31-25_03-30-45-PM

Summary:
- Total coins processed: 10
- Authentic (13+ passes): 7
- Fracked (1-12 passes): 2
- Counterfeit (0 passes): 1

Coin Results:
SN 12345 (250): ppppppppppppppppppppppppp (25/25 Pass - Grade: Ready for Bank)
SN 67890 (100): pppppppppppppppppnnnpppppp (20/25 Pass - Grade: Ready for Bank)
SN 54321 (25):  ppppppppppfffffnnnnnnnnnnn (10/25 Pass - Grade: Ready for Fracked)
SN 11111 (1):   fffffffffffffffffffffffff (0/25 Pass - Grade: Ready for Counterfeit)
...

Notes:
- Run /api/coins/grade to sort coins to final folders
- Coins currently in Grade folder awaiting grading

Receipt files include:

  • Task ID: Unique timestamp identifier for this authentication run
  • Summary statistics: Count of authentic/fracked/counterfeit coins
  • Per-coin POWN strings: Complete 25-character authentication status
  • Pass counts: Number of successful authentications per coin
  • Final location hints: Suggested folder based on POWN status

Parallel RAIDA Execution

The authentication process uses multi-threaded parallel execution for optimal performance.

Performance

Threading provides dramatic performance improvements:

  • Sequential execution: ~25 seconds (1 second × 25 RAIDAs)
  • Parallel execution: ~1-2 seconds (network RTT + processing)
  • Speedup: 20-25x faster
  • Thread pool: 25 worker threads (one per RAIDA)
  • Timeout: AI-calculated based on coin count (typically 6-10 seconds)
Thread Pool Architecture:
- 25 dedicated worker threads (one per RAIDA)
- All requests sent simultaneously
- Independent result collection per thread
- No shared state during execution
- Thread-safe socket operations

Timeout Calculation (AI-based):
Base timeout: 5000ms (5 seconds)
+ Coin count adjustment: +1000-2000ms
= Typical range: 6000-10000ms

Example for 10 coins:
- Timeout: 6000ms (6 seconds)
- Actual completion: ~1500ms (1.5 seconds)
- Margin: 4500ms safety buffer

Examples

JavaScript (fetch)

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

async function authenticateCoins() {
    try {
        console.log('Starting authentication with RAIDA network...');
        const response = await fetch(`${API_HOST}/api/coins/authenticate`);
        const result = await response.json();

        if (result.status === 'success') {
            console.log('Authentication completed successfully');
            console.log(`Wallet: ${result.wallet}`);
            console.log(`Note: ${result.note}`);
            console.log('\nNext steps:');
            console.log('1. Check wallet Receipts folder for detailed results');
            console.log('2. Inspect POWN strings in Grade folder');
            console.log('3. Run /api/coins/grade to sort coins to final folders');

            // Automatically run grade command
            console.log('\nRunning grade command...');
            const gradeResponse = await fetch(`${API_HOST}/api/coins/grade`);
            const gradeResult = await gradeResponse.json();

            if (gradeResult.status === 'success') {
                console.log('Grading completed - coins sorted to final folders');
            }
        } else {
            console.error('Authentication failed:', result.error);
        }
    } catch (error) {
        console.error('Error during authentication:', error);
    }
}

// Execute authentication
authenticateCoins();

cURL

# Authenticate all coins in Bank and Fracked folders
curl -X GET "http://localhost:8080/api/coins/authenticate"

# Authenticate and grade in sequence
curl -X GET "http://localhost:8080/api/coins/authenticate" && \
curl -X GET "http://localhost:8080/api/coins/grade"

# Pretty-print output
curl -X GET "http://localhost:8080/api/coins/authenticate" | json_pp

Go

package main

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

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

type AuthenticateResponse struct {
    Status    string `json:"status"`
    Operation string `json:"operation"`
    Message   string `json:"message"`
    Wallet    string `json:"wallet"`
    Note      string `json:"note"`
}

func authenticateCoins() error {
    fmt.Println("Starting authentication with RAIDA network...")

    resp, err := http.Get(fmt.Sprintf("%s/api/coins/authenticate", ApiHost))
    if err != nil {
        return fmt.Errorf("request failed: %v", err)
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return fmt.Errorf("failed to read response: %v", err)
    }

    var result AuthenticateResponse
    if err := json.Unmarshal(body, &result); err != nil {
        return fmt.Errorf("failed to parse response: %v", err)
    }

    if result.Status == "success" {
        fmt.Println("Authentication completed successfully")
        fmt.Printf("Wallet: %s\n", result.Wallet)
        fmt.Printf("Note: %s\n", result.Note)
        fmt.Println("\nNext steps:")
        fmt.Println("1. Check wallet Receipts folder for detailed results")
        fmt.Println("2. Inspect POWN strings in Grade folder")
        fmt.Println("3. Run /api/coins/grade to sort coins to final folders")
        return nil
    }

    return fmt.Errorf("authentication failed: %s", result.Message)
}

func main() {
    if err := authenticateCoins(); err != nil {
        panic(err)
    }
}

Important Considerations

Prerequisites
  • Active wallet required: Set a wallet before authentication
  • Grade folder must be empty: Run grade command first if needed
  • Network connectivity: Requires access to all 25 RAIDA servers
  • Coin file format: Coins must be in CloudCoin v3 binary format
Network Requirements

Authentication requires reliable network access to RAIDA servers:

  • Firewalls must allow outbound TCP connections to RAIDA IPs
  • Timeout set to 6-10 seconds per RAIDA (adjusts based on coin count)
  • RAIDAs that timeout are marked as 'n' (no reply) in POWN string
  • Up to 12 RAIDAs can fail/timeout and coin still authenticates
POWN String Preservation

During the authentication workflow:

  • POWN strings are preserved when moving coins from Bank/Fracked to Grade
  • Only failing RAIDAs (with 'f' status) are re-queried during Detect
  • Passing RAIDAs (with 'p' status) are preserved from previous authentication
  • This prevents unnecessary re-authentication of known-good RAIDAs

Related Endpoints

/api/coins/grade

Sort authenticated coins from Grade folder to Bank/Fracked/Counterfeit based on POWN status.

/api/wallet/show-coins

View all coins in the wallet including POWN strings and authentication status.

/api/coins/fix

Heal fracked coins using ticket-based authentication to improve POWN status.

/api/program/echo

Test RAIDA network connectivity and health status before authentication.

Troubleshooting

Grade Folder Not Empty

If authentication fails with "Grade folder is not empty":

  • Run /api/coins/grade to sort existing coins first
  • Check Grade folder manually and move/delete files if needed
  • Ensure no other processes are writing to Grade folder

Many RAIDAs Timeout

If many RAIDAs show 'n' (no reply) status:

  • Check network connectivity with /api/program/echo
  • Verify firewall allows outbound connections to RAIDA servers
  • Try authentication again during better network conditions
  • Check RAIDA server status (some may be offline for maintenance)

All Coins Show as Counterfeit

If all coins fail authentication (0 passes):

  • Coins may be from a different CloudCoin network (test vs production)
  • ANs may have been corrupted during file transfer
  • Verify coins are in correct binary format (v3, format ID 9)
  • Check that coins were previously authenticated on this RAIDA network

Partial Authentication (Fracked Coins)

If coins have 1-12 passes (fracked status):

  • This is normal for coins with network issues during authentication
  • Run /api/coins/fix to heal fracked coins using ticket protocol
  • Most fracked coins can be fully healed to 25/25 passes
  • Keep fracked coins - they may heal in subsequent Fix operations