§

Abstract

GoldXCoin (GXC) is a next-generation blockchain implementing a hybrid Proof-of-Work (PoW) and Proof-of-Stake (PoS) consensus mechanism with advanced fraud detection, transaction traceability, and autonomous reversal capabilities. This whitepaper presents the complete mathematical foundations, cryptographic algorithms, consensus protocols, and security mechanisms as implemented in the C++ node software.

The system introduces novel concepts including:

  • Proof of Traceability (POT) — Mathematical taint propagation for fraud detection
  • Proof of Feasibility (POF) — Cryptographic proofs for safe transaction reversals
  • Hybrid Consensus — Alternating PoW and PoS blocks for security and energy efficiency
  • Multi-Algorithm Mining — Support for SHA-256, Ethash, and GXHash algorithms
  • Self-Sustaining Fraud Detection — Automatic fee-based funding for security operations
  • Gold-Backed Token GXC-G — 100% reserve-backed, audited gold token
  • On-Chain Governance — Stake-weighted proposals, voting, and parameter changes
  • Proof of Price (PoP) Oracle — Multi-oracle consensus for reliable price feeds
  • Cross-Chain Bridge — 6 chains, 67% multi-sig threshold
01.

Introduction

1.1 · Design Philosophy

GXC addresses three fundamental blockchain challenges:

⚡
Security vs Energy

Hybrid consensus balances proof-of-work security with proof-of-stake efficiency

🔄
Finality vs Flexibility

Fraud detection enables reversals without compromising immutability

🔍
Transparency vs Privacy

Full traceability for fraud detection while maintaining pseudonymity

1.2 · System Parameters

cpp
MAX_SUPPLY                  = 31,000,000 GXC
HALVING_INTERVAL            = 1,051,200 blocks  (~4 years)
INITIAL_BLOCK_REWARD        = 50.0 GXC
TARGET_BLOCK_TIME           = 600 seconds       (10 minutes)
DIFFICULTY_ADJUSTMENT_INTERVAL = 2016 blocks    (~2 weeks)
MAX_BLOCK_SIZE              = 1,048,576 bytes   (1 MB)
MIN_TESTNET_DIFFICULTY      = 1.0
MIN_MAINNET_DIFFICULTY      = 1000.0

1.3 · Network Architecture

Mainnet
P2P: 8333
RPC: 8332
REST: 8080
Magic: "GXC\x01"
Protocol: 70015
Testnet
P2P: 18333
RPC: 18332
REST: 18080
Magic: "GXCT"
Protocol: 70015
02.

Mathematical Foundations

2.1.1 · SHA-256

Message512-bit blockCompression Fn64 roundsσ₀,σ₁,Σ₀,Σ₁,Ch,Maj256-bitDigest↺ again for SHA256d1 bit flip → ~50% output change(avalanche effect)SHA-256: preimage-resistant · collision-resistant · 128-bit security
SHA-256 Definition
SHA256(message) → digest ∈ {0,1}²⁵⁶ SHA256d(x) = SHA256(SHA256(x)) [Double SHA-256 for PoW] Properties: Preimage resistance: given h, finding x s.t. SHA256(x)=h is infeasible Collision resistance: finding x≠y s.t. SHA256(x)=SHA256(y) is infeasible Avalanche effect: 1 bit flip → ~50% output bit change

2.1.2 · Keccak-256

RATE r=1088 bitsXOR with messageCAPACITY c=512 bitsnever touched by inputKeccak-f[1600]24 roundsθ,ρ,π,χ,ι256-bithashUsed for: tx hashing · UTXO keys · validator signatures · smart contract state
Keccak-256 Sponge Construction
Keccak256(message) → digest ∈ {0,1}²⁵⁶ rate = 1088 bits capacity = 512 bits 24 rounds of Keccak-f[1600] permutation (θ,ρ,π,χ,ι) Used for: - Transaction hashing - UTXO key generation - Validator signatures - Smart contract state

2.1.3 · RIPEMD-160

RIPEMD-160 Address Generation
RIPEMD160(message) → digest ∈ {0,1}¹⁶⁰ Mainnet: Address = "GXC" || Base58(RIPEMD160(SHA256(CompressedPublicKey))) Testnet: Address = "tGXC" || Base58(RIPEMD160(SHA256(CompressedPublicKey)))
Private Key256-bit random×G →EC multiplyPublic Key264-bit compressedSHA-256hashRIPEMD-160160-bitBase58Check+GXC prefixGXC address = "GXC" + Base58Check(RIPEMD160(SHA256(CompressedPubKey)))

2.2.1 · secp256k1 Elliptic Curve

y² = x³ + 7 (mod p)secp256k1 — used by Bitcoin, Ethereum, and GXCG (generator point)Q = d·G (public key)d (private key, 256-bit random)SIGNk ∈ [1,n−1] randomσ = (r,s) = 512 bitsVERIFYw = s⁻¹ mod nr ≡ x₁ mod n?Security: 128-bit (discrete log on secp256k1) — equivalent to 3072-bit RSA
secp256k1 Parameters
Curve: y² = x³ + 7 (mod p) p = 2²⁵⁶ − 2³² − 2⁹ − 2⁸ − 2⁷ − 2⁶ − 2⁴ − 1 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F n = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 (order of generator point G) G = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8)

2.2.2 · ECDSA Key Generation & Signing

ECDSA Signature Algorithm
Key Generation: private key d ∈ [1, n-1] (random) public key Q = d·G (point multiplication) Signature of message hash h: 1. Select random k ∈ [1, n-1] 2. Compute (x₁,y₁) = k·G 3. r = x₁ mod n (if r=0, retry) 4. s = k⁻¹(h + r·d) mod n (if s=0, retry) 5. Signature σ = (r, s) → 512 bits Verification: 1. Verify r,s ∈ [1, n-1] 2. w = s⁻¹ mod n 3. u₁ = h·w mod n 4. u₂ = r·w mod n 5. (x₁,y₁) = u₁·G + u₂·Q 6. Valid if r ≡ x₁ (mod n) Security: 128-bit (equivalent to 3072-bit RSA)
03.

Cryptographic Primitives

3.1 · Block Hashing

PoW SHA-256
SHA256d(Index || PrevHash || Timestamp || MerkleRoot || Nonce || Difficulty)
PoW Ethash
Ethash(Header, Nonce, DAG_Epoch)
PoW GXHash
GXHash(Header, Nonce) // Custom memory-hard
PoS Block
SHA256(Index || PrevHash || Timestamp || MerkleRoot || ValidatorPubKey)

3.2 · Merkle Root

tx₁tx₂tx₃tx₄H(t₁||t₂)H(t₃||t₄)Merkle RootO(log n) inclusion proof · Keccak-256 at each level · odd duplication
cpp
std::string calculateMerkleRoot(std::vector<std::string> txHashes) {
    if (txHashes.empty()) return "0000...";
    if (txHashes.size() == 1) return txHashes[0];
    while (txHashes.size() > 1) {
        std::vector<std::string> newLevel;
        for (size_t i = 0; i < txHashes.size(); i += 2) {
            std::string left  = txHashes[i];
            std::string right = (i+1 < txHashes.size()) ? txHashes[i+1] : left;
            newLevel.push_back(keccak256(left + right));
        }
        txHashes = newLevel;
    }
    return txHashes[0];  // O(log n) inclusion proofs
}

3.3 · Work Receipt (PoW Binding)

Work Receipt Formula
WorkReceipt = H(PrevHash || MerkleRoot || Nonce || MinerPubKey || Difficulty || Timestamp) Validation requires ALL THREE to match: computed == block.workReceiptHash block.workReceiptHash == coinbase.workReceiptHash coinbase.blockHeight == block.index → prevents miners stealing coinbase reward from other miners
04.

Consensus Mechanisms

4.1 · Hybrid Block Selection (Animated)

⛏PoW#0🔒PoS#1⛏PoW#2🔒PoS#3⛏PoW#4🔒PoS#5⛏PoW#6🔒PoS#7⛏PoW#8Rule: even height → PoW · odd height + active validators → PoS · fallback → PoWPoW (⛏ SHA-256/Ethash/GXHash)PoS (🔒 validator signed)
cpp
BlockType Blockchain::getNextBlockType() const {
    uint32_t nextHeight = getHeight();
    if (nextHeight % 2 == 0) return BlockType::PROOF_OF_WORK;
    if (getActiveValidators().empty()) return BlockType::PROOF_OF_WORK;
    return BlockType::PROOF_OF_STAKE;
}

4.2.1 · PoW Difficulty Target

Leading Zeros Requirement
Valid PoW: leading_zeros(BlockHash) ≥ Difficulty Target: hash.substr(0, requiredZeros) == string(requiredZeros, '0')

4.2.2 · Difficulty Adjustment (every 2016 blocks)

700900110013001500targetclamped ±4× per epochD_new = D_old × (T_expected / T_actual) · T_expected = 2016 × 600 = 1,209,600s
Bitcoin-Style Adjustment Formula
D_new = D_old × (T_expected / T_actual) where: T_expected = DIFFICULTY_ADJUSTMENT_INTERVAL × TARGET_BLOCK_TIME = 2016 × 600 = 1,209,600 seconds T_actual = actual time for last 2016 blocks Clamping: D_new = clamp(D_new, D_old/4, D_old×4) Minimum: D_new = max(D_new, MIN_DIFFICULTY) [1.0 testnet | 1000.0 mainnet]

4.2.3 · Security-Adjusted Difficulty

Security Score Integration
D_security = D_base × (1 + SecurityScore) SecurityScore ∈ [0, 1] based on: - Hashrate volatility - Attack detection events - Network health metrics

4.3.1 · PoS Validator Selection

Val A37.2% · 5,000 GXC · 365dVal B17.1% · 8,000 GXC · 30dVal C14.6% · 2,000 GXC · 350dVal D14.6% · 10,000 GXC · 14dVal E16.5% · 3,000 GXC · 200dw_i = stake × (days/365)^β β=0.5 · long lock + high stake = most influence
Weighted Stake Selection (β = 0.5)
w_i = stake_i × (days_i / 365)^β [β = 0.5] where: stake_i = validator's staked amount days_i = staking duration ∈ [14, 365] days β = 0.5 (time weight exponent) P(validator_i selected) = w_i / Σⱼ w_j Selection seeded by block height → deterministic, reproducible
cpp
double Validator::getWeightedStake() const {
    if (!isActive) return 0.0;
    return stakeAmount * std::pow(static_cast<double>(stakingDays)/365.0, BETA);
}

Validator Blockchain::selectValidatorForBlock() const {
    std::mt19937_64 rng(getHeight());  // deterministic seed
    std::uniform_real_distribution<double> dist(0.0, totalWeightedStake);
    double threshold = dist(rng);
    double cumulative = 0.0;
    for (const auto& v : activeValidators) {
        cumulative += v.getWeightedStake();
        if (cumulative >= threshold) return v;
    }
    return activeValidators.back();
}

4.3.2 · PoS Block Validation Requirements

cpp
bool Blockchain::validateProofOfStake(const Block& block) const {
    // 1. Validator exists and is active
    // 2. hasMinimumStake(100 GXC)
    // 3. stakingDays ∈ [14, 365]
    // 4. validator.verifySignature(block.getHash(), signature) == true
    // 5. meetsTarget(block.getHash(), 0.01)  // much easier than PoW
    return true;
}
05.

Transaction Model & Traceability

5.1 · UTXO Model

cpp
struct TransactionOutput {
    std::string address;  // Recipient
    double      amount;   // Value in GXC
    std::string script;   // Locking script
};

// UTXO Set: Map<TxHash_OutputIndex, TransactionOutput>
std::unordered_map<std::string, TransactionOutput> utxoSet;

// UTXO Key format:
utxoKey = TxHash || "_" || OutputIndex

5.2 · Transaction Structure

cpp
class Transaction {
    std::string txHash;
    TransactionType type;  // NORMAL | STAKE | UNSTAKE | REWARD | COINBASE | REVERSAL
    std::vector<TransactionInput>  inputs;
    std::vector<TransactionOutput> outputs;
    std::time_t timestamp;

    // Proof of Traceability fields
    std::string prevTxHash;       // Hash of Tᵢ₋₁
    double      referencedAmount; // Amount from Tᵢ₋₁
    std::string senderAddress;
    std::string receiverAddress;
    uint32_t    nonce;

    // Work receipt (COINBASE only)
    std::string workReceiptHash;
    uint32_t    blockHeight;

    double      fee;
    std::string memo;
};

5.3 · Proof of Traceability (POT)

POT Validation Rule
For every non-coinbase, non-genesis transaction Tᵢ: Tᵢ.inputs[0].txHash == Tᵢ.prevTxHash ← first input matches prev tx Tᵢ.inputs[0].amount == Tᵢ.referencedAmount ← amount matches Mathematical chain C = {T₀, T₁, ..., Tₙ}: ∀i ∈ [1,n]: Tᵢ.prevTxHash = Hash(Tᵢ₋₁) Properties: Transitivity: A→B and B→C ⟹ trace exists A→C Uniqueness: each tx has exactly one previous tx Acyclicity: no tx can reference itself (DAG property)

5.4 · Input-Output Balance Invariant

Conservation Law
Σ inputs = Σ outputs + fee Tolerance: |diff| < 0.00000001 GXC (8 decimal places) Coinbase exception: output_amount ≤ block_reward + Σ tx_fees
06.

Fraud Detection System

6.1 · Taint Propagation — BFS on the Transaction DAG (Animated)

T₀T₁T₂T₃T₄T₅T₆T₇τ(Tⱼ) = Σᵢ (value_from_Tᵢ / total_inputs) × τ(Tᵢ) · BFS propagation · threshold δ=0.1
Taint Score Formula
Seed: τ(T_stolen) = 1.0 Propagation for descendant Tⱼ with inputs {T₁,...,Tₖ}: τ(Tⱼ) = Σᵢ wᵢ × τ(Tᵢ) where wᵢ = value_from_Tᵢ / total_input_value Properties: Conservation: 0 ≤ τ(T) ≤ 1 ∀T Monotonic decay: τ(child) ≤ max(τ(parent)) Threshold δ=0.1 — below this, stop tracking
cpp
// BFS Taint Propagation
void FraudDetection::propagateTaint(const std::string& startTx, uint32_t maxHops) {
    std::queue<std::pair<std::string, uint32_t>> queue;
    queue.push({startTx, 0});
    while (!queue.empty()) {
        auto [currentTx, depth] = queue.front(); queue.pop();
        if (depth >= maxHops) continue;
        if (taintMap[currentTx].taintScore < TAINT_THRESHOLD) continue;
        for (const auto& desc : blockchain->getDescendantTransactions(currentTx)) {
            double t = calculateTaint(blockchain->getTransaction(desc));
            if (t > 0) { taintMap[desc] = TaintInfo(t, ...); queue.push({desc, depth+1}); }
        }
    }
}

6.2 · Five Detection Rules

Rule 1Velocity Anomaly

Rapid fund movement indicative of laundering

(t_j − t_{j−1}) < ε AND τ > 0.5 ε = 300 seconds (5 min)
Rule 2Fan-Out (Smurfing)

Splitting funds into many small outputs

|outputs| > K AND τ > δ K = 5, δ = 0.1
Rule 3Re-Aggregation

Combining split tainted funds (layering)

Σ τ(inputs) > θ AND |inputs| > 1 θ = 0.7
Rule 4Dormancy Activation

Stolen funds held dormant then suddenly moved

(now − t_stolen) > 7 days AND τ > δ
Rule 5Clean Zone Entry

Tainted funds entering regulated zones

dest ∈ CleanZones AND τ > δ {Exchanges, Staking, Merchants}

6.3 · Alert Levels

cpp
AlertLevel calculateAlertLevel(double taintScore, uint32_t ruleViolations) {
    if (taintScore >= 0.8 || ruleViolations >= 3) return CRITICAL;  // 🔴
    if (taintScore >= 0.5 || ruleViolations >= 2) return HIGH;      // 🟠
    if (taintScore >= 0.1 || ruleViolations >= 1) return MEDIUM;    // 🟡
    return LOW;                                                       // 🟢
}

Constants:
  TAINT_THRESHOLD  = 0.1   (δ)
  HIGH_TAINT       = 0.5
  CRITICAL_TAINT   = 0.8
  VELOCITY_EPSILON = 300 s
  FAN_OUT_K        = 5
  RE_AGG_THETA     = 0.7
  DORMANCY_PERIOD  = 604800 s (7 days)
07.

Reversal System

7.1 · Proof of Feasibility (POF) — Animated Pipeline

TheftDetectedTaintPropag.POTVerifiedAdminApprovesPOFGeneratedMathValidatesReversalExecutedVictimRestored ✓Math enforces — admin cannot override infeasible reversal

7.1 · POF Structure

cpp
struct ProofOfFeasibility {
    std::string              proof_type;          // "REVERSAL_PROOF"
    std::string              stolen_tx;           // Original stolen tx
    std::string              current_tx;          // Current holding tx
    std::vector<std::string> trace_path;          // Full taint path
    double                   taint_score;         // τ ∈ [0,1]
    uint64_t                 recoverable_amount;  // R = τ × balance
    std::string              origin_owner;        // Victim address
    std::string              current_holder;      // Current holder
    std::string              approved_by;         // Admin ID
    std::string              approval_signature;  // Admin ECDSA sig
    uint64_t                 timestamp;
    uint64_t                 block_height;
    std::string              proof_hash;          // Hash(entire proof)
};

7.2 · Recoverable Amount Formula

Maximum Recoverable Amount
R = τ(T_current) × Balance(current_holder) Constraints: R ≤ stolen_amount (can't recover more than was stolen) R ≤ current_balance (can't recover more than holder has) τ(T_current) ≥ 0.1 (minimum taint threshold) Reversal Window: current_height − stolen_height ≤ 20,000 blocks (~30 days)

7.3 · Proof Generation Algorithm

cpp
ProofOfFeasibility ProofGenerator::generateProof(
    stolen_tx, current_holder, admin_id, admin_signature) {
    // 1. Verify stolen_tx is marked as stolen
    if (!fraudDetection->isStolen(stolen_tx)) return {};

    // 2. Taint score must meet threshold
    auto taintInfo = fraudDetection->getTaintInfo(currentHolderTx);
    if (taintInfo.taintScore < MIN_TAINT_THRESHOLD) return {};

    // 3. Within reversal window (20,000 blocks)
    if (currentHeight - stolenHeight > REVERSAL_WINDOW) return {};

    // 4. Calculate recoverable amount
    uint64_t recoverable = calculateRecoverableAmount(
        currentHolderTx, currentHolder, taintInfo.taintScore);

    // 5. Build + hash proof
    proof.proof_hash = generateProofHash(proof);
    return proof;
}

7.4 · Reversal Execution Steps

1. Validate proof cryptographically 2. Check current holder has sufficient balance 3. Verify admin signature on proof 4. Debit current_holder by R 5. Credit origin_owner (victim) by R 6. Pay execution fee from system pool 7. Mark original tx as reversed 8. Add reversal tx to blockchain

7.5 · Self-Sustaining Fee Pool

Fee Pool Funding Sources
Source 1 — Transaction Fee Split (automatic): fee_to_miner = tx_fee × 0.85 fee_to_pool = tx_fee × 0.15 ← 15% goes to reversal pool Source 2 — Reversal Execution Fee: pool_deposit = recovered_amount × 0.002 ← 0.2% Result: pool is self-sustaining — every tx funds future reversals
08.

Staking & Validator Economics

8.1 · Staking Pool Entry Structure

cpp
struct StakeEntry {
    std::string stakeId;
    std::string ownerAddress;
    std::string validatorAddress;
    double      amount;
    uint64_t    lockStartTime;
    uint32_t    lockPeriodDays;    // [7, 365]
    bool        isLocked;
    double      accumulatedRewards;

    // Traceability (linked to POT)
    std::string stakeTxHash;
    std::string previousTxHash;
    std::vector<std::string> inputTxHashes;
};

const uint32_t MIN_LOCK_PERIOD_DAYS = 7;
const uint32_t MAX_LOCK_PERIOD_DAYS = 365;
const double   MIN_STAKE_AMOUNT     = 10.0;  // GXC

8.2 · Validator Requirements

100 GXC
Min Validator Stake
14 days
Min Staking Period
365 days
Max Staking Period
0.5
β exponent
10 GXC
Min Pool Stake
cpp
bool Validator::isValidValidator() const {
    return hasMinimumStake(100.0) &&
           isStakingPeriodValid() &&   // days ∈ [14, 365]
           isActive &&
           !isSlashed;
}

8.3 · APY Calculation

Validator Annual Percentage Yield
blocks_per_year = 365.25 × 24 × 60 × 6 = 52,596 annual_reward = STAKING_REWARD_PER_BLOCK × blocks_per_year × weighted_stake = 0.0001 × 52,596 × weighted_stake APY = (annual_reward / stake_amount) × 100% APY_final = APY × (1.0 + commission_rate)

8.4 · Validator Pool Statistics

cpp
struct ValidatorPoolStats {
    double   ownStake;             // Validator's own stake
    double   totalDelegated;       // Delegated from others
    double   totalStake;           // ownStake + totalDelegated
    uint32_t delegatorCount;
    uint32_t blocksProduced;       // Performance metric
    uint32_t missedBlocks;         // Slashing trigger
    double   totalRewardsDistributed;
};
09.

Mining Algorithms

9.1 · SHA-256 (Bitcoin-Style)

Mining Loop
Algorithm: 1. Construct block header 2. H = SHA256(SHA256(header)) 3. if leading_zeros(H) ≥ difficulty → FOUND 4. else increment nonce → goto 2 Target: hash.substr(0, requiredZeros) == "000...0"

9.2 · Ethash (Memory-Hard, Ethereum-style)

Ethash Parameters
epoch = block_number / 30,000 Cache size per epoch: cache_size(e) = CACHE_INIT_SIZE + CACHE_GROWTH × e = 16 MB + 128 KB per epoch Dataset size per epoch: dataset_size(e) = DATASET_INIT_SIZE + DATASET_GROWTH × e = 1 GB + 8 MB per epoch Algorithm: 1. Generate cache C from seed S (epoch-dependent) 2. Generate dataset D from C (1 GB+, memory-hard) 3. For each nonce: Mix → 64 random dataset accesses → compress → check target
cpp
class EthashAlgorithm {
    explicit EthashAlgorithm(uint64_t block_number);
    bool hash_full(const uint8_t header_hash[32], uint64_t nonce,
                   uint8_t result[32], uint8_t mix_hash[32]);
    bool verify(const uint8_t header_hash[32], uint64_t nonce,
                const uint8_t expected_result[32]);
private:
    void generate_cache();     // 16MB+ from seed
    void generate_dataset();   // 1GB+ from cache (GPU-hard)
    void calc_dataset_item(uint32_t index, uint8_t* output) const;
};

9.3 · GXHash (Custom Algorithm)

GXHash is GXC's proprietary memory-hard, ASIC-resistant algorithm. Properties: memory-hard (requires significant RAM), sequential memory access (reduces GPU advantage), tunable difficulty, and fast verification. Implemented in GXHashMiner.cpp.

10.

Network Protocol

10.1 · Message Types

Magic4 bytesGXC\x01Type1 byteLength4 byteslePayloadvariableChecksum4 bytesCRC32Message Protocol — all GXC P2P messages follow this structureTestnet magic: "GXCT" · Protocol version: 70015 · MAX_MSG_SIZE: 32 MB
cpp
enum class MessageType : uint8_t {
    VERSION=0x01, VERACK=0x02, PING=0x03, PONG=0x04,
    GETADDR=0x05, ADDR=0x06, GETBLOCKS=0x07, BLOCKS=0x08,
    GETDATA=0x09, BLOCK=0x0A, TX=0x0B, MEMPOOL=0x0C,
    GETMEMPOOL=0x0D, REJECT=0x0E, ALERT=0x0F,
    MINING_WORK=0x10, MINING_SUBMIT=0x11
};

10.2 · Peer Discovery & Connection Limits

cpp
// Seed Nodes
std::vector<std::string> seedNodes = {
    "seed1.gxc.network:8333",
    "seed2.gxc.network:8333",
    "seed3.gxc.network:8333"
};

const uint32_t MAX_CONNECTIONS = 125;
const uint32_t MAX_OUTBOUND    = 8;
const uint32_t PING_INTERVAL   = 30;   // seconds
const uint32_t PEER_TIMEOUT    = 90;   // seconds

10.3 · Block Synchronization Algorithm

cpp
void NetworkNode::syncWithPeers() {
    uint32_t ourHeight   = blockchain->getHeight();
    uint32_t bestHeight  = getBestHeight();
    if (bestHeight <= ourHeight) return;  // already synced

    const uint32_t BATCH_SIZE = 500;
    for (uint32_t start = ourHeight+1; start <= bestHeight; start += BATCH_SIZE)
        requestBlocks(std::to_string(start), BATCH_SIZE);
}
11.

Monetary Policy

11.1 · Supply Cap

Hard Cap
MAX_SUPPLY = 31,000,000 GXC (never exceeded)

11.2 · Block Reward Halving Schedule

50'2425'2812.5'326.25'363.125'401.5625'440.78125'48R(h) = 50 / 2^H where H=floor(height/1,051,200) · MAX: 31,000,000 GXC
Halving Formula
H = floor(block_height / HALVING_INTERVAL) = floor(height / 1,051,200) R(height) = R₀ / 2^H [if H < 64, else 0] Schedule: Block 0: 50.0 GXC (epoch 0) Block 1,051,200: 25.0 GXC (1st halving ~2028) Block 2,102,400: 12.5 GXC (2nd halving ~2032) Block 3,153,600: 6.25 GXC (3rd halving ~2036) Block 4,204,800: 3.125 GXC (4th halving ~2040) ...continues until all 31M mined...

11.3 · Difficulty Multiplier Bonus (+10% max)

M_diff = 1 + min(0.10, (D − 1) / 100) Maximum bonus: +10% for high difficulty

11.4 · Time Bonus (+5% max)

M_time = 1 + min(0.05, (t_avg − t_target) / t_target) where: t_avg = average block time over last 100 blocks t_target = 600 seconds Maximum bonus: +5% if network is slow

11.5 · Final Block Reward

Combined Issuance Formula
R_final = R_base × M_diff × M_time + Σ tx_fees Subject to: totalSupply + R_final ≤ 31,000,000 GXC

11.6 · Fee Economics

fee_to_miner = tx_fee × 0.85 (85% to block producer) fee_to_pool = tx_fee × 0.15 (15% to reversal fee pool) reversal_fee = 0.1% to 0.3% of recovered amount MIN_FEE = 0.001 GXC MAX_FEE = 0.01 GXC
12.

Security Analysis

12.1 · Attack Vectors & Mitigations

AttackDescriptionGXC Mitigation
51% Attack (PoW)Attacker controls >50% hashrateHybrid consensus: need >50% stake AND >50% hashrate + checkpoint system
Nothing-at-Stake (PoS)Validators sign competing chainsSlashing for double-signing + deterministic selection + finality checkpoints
Long-Range AttackRewrite history from old blocksReversal window capped at 20,000 blocks + weak subjectivity checkpoints
Taint EvasionMixing stolen funds to dilute taintFan-out + re-aggregation + clean zone monitoring automatically flag attempts

12.2 · AI-Based Security Engine

cpp
class SecurityEngine {
public:
    double calculateSecurityScore();
    bool   detectHashrateAnomaly();
    bool   detectSpamAttack();
    double getRecommendedFee();
    // Metrics: hashrate volatility, tx spam, network partition, double-spend
};

12.3 · Cryptographic Security Levels

AlgorithmKey/Output SizeSecurity Level
SHA-256256-bit128-bit (birthday)
secp256k1256-bit private128-bit (discrete log)
ECDSA512-bit sig (r+s)128-bit
Blake2b256-bit256-bit
Argon2idconfigurableVery High (memory-hard)
13.

Implementation Specifications

13.1 · Database (LevelDB)

cpp
// Key Prefixes:
"blk_"  → Block data            "tx_"   → Transaction data
"utxo_" → UTXO set              "val_"  → Validator data
"idx_"  → Indexes

13.2 · Configuration

cpp
class Config {
    static bool     isTestnet();
    static uint32_t getTargetBlockTime();    // 600 seconds
    static uint32_t getDifficultyInterval(); // 2016 blocks
    static double   getMinDifficulty();      // 1.0 testnet | 1000.0 mainnet
    static uint64_t getMaxBlockSize();       // 1,048,576 bytes
};

13.3 · Logging System

cpp
enum class LogLevel { DEBUG, INFO, WARNING, ERROR, CRITICAL };

LOG_BLOCKCHAIN(level, message);  LOG_NETWORK(level, message);
LOG_SECURITY(level, message, component);  LOG_MINING(level, message);

13.4 · REST & RPC API Endpoints

REST API:
  GET  /api/block/:hash           GET  /api/block/height/:height
  GET  /api/transaction/:hash     GET  /api/balance/:address
  POST /api/transaction           GET  /api/stats
  GET  /api/validators            GET  /api/mempool

RPC API (JSON-RPC 2.0):
  getblockcount()   getblock(hash)   gettransaction(txid)
  sendtoaddress(address, amount)     getbalance(address)
  getmininginfo()   validateaddress(address)

13.5 · Build System

bash
# Dependencies:
#   OpenSSL 1.1.1+   LevelDB 1.23+   Boost 1.74+   CMake 3.15+

mkdir build && cd build
cmake ..
make -j$(nproc)
./gxc-node
14.

Advanced Cryptographic Algorithms

14.1 · Argon2id (Memory-Hard KDF)

Password PSalt St=3 iterationsm=64MB memoryArgon2idd-dep + d-indepp=4 threads1024-byte blocksTag (output)ASIC/GPU resistantSide-channel resistant · time-memory trade-off resistant · Very High security level
Argon2id Parameters for GXC
Argon2id(P, S, t, m, p, τ) → Tag t_cost = 3 (iterations) m_cost = 65,536 (64 MB memory) parallelism = 4 (threads) Memory: m_cost × 1024 bytes total Blocks: 1024 bytes each Security: Time-memory trade-off resistant Side-channel resistant (constant-time) GPU resistant (memory-hard design)
cpp
void argon2id_hash(
    const uint8_t* password, size_t pwdlen,
    const uint8_t* salt,     size_t saltlen,
    uint32_t t_cost,         // iterations
    uint32_t m_cost,         // memory in KB
    uint32_t parallelism,    // threads
    uint8_t* out, size_t outlen
);

14.2 · Blake2b (High-Speed Cryptographic Hash)

Blake2b Compression Function G
G(a,b,c,d,x,y): a := a + b + x d := (d ⊕ a) ≫ 32 c := c + d b := (b ⊕ c) ≫ 24 a := a + b + y d := (d ⊕ a) ≫ 16 c := c + d b := (b ⊕ c) ≫ 63 State: h[0..7] = IV[0..7] ⊕ Parameter Block Rounds: 12 Performance: ~3-4× faster than SHA-256 Use cases in GXC: - PoW alternative - Merkle tree construction (faster) - Message authentication codes (MAC)
cpp
struct Blake2bContext {
    uint64_t h[8];    // Hash state (512 bits)
    uint64_t t[2];    // Byte counter
    uint64_t f[2];    // Finalization flags
    uint8_t  buf[128];
    size_t   buflen, outlen;
};
void blake2b_init(Blake2bContext* ctx, size_t outlen);
void blake2b_update(Blake2bContext* ctx, const uint8_t* data, size_t len);
void blake2b_final(Blake2bContext* ctx, uint8_t* out);
15.

Gold-Backed Token System (GXC-G)

🏦 VaultPhysical GoldAuditedattestationsignature ✓MINTGXC-G1 token= 1 gram AuReserve RatioGold Reserves (g)Token Supply≥ 1.0 (100% backed)Burn: holder redeems → tokens destroyed · reserves decrease · 1 troy oz = 31.1035g

15.1 · Token Economics

Reserve Ratio
Symbol: GXC-G (Gold-backed GXC) Precision: 8 decimals Reserve Ratio = Total Gold Reserves (grams) / Total Token Supply Minimum Ratio = 1.0 (100% backed — never less) Conversion: 1 troy ounce = 31.1035 grams

15.2 · Gold Reserve Structure

cpp
struct GoldReserve {
    std::string vaultId;
    std::string vaultAddress;      // Blockchain address of vault
    double      goldGrams;         // Physical gold stored (grams)
    std::string attestationHash;   // Proof of reserves hash
    std::time_t lastAuditTime;
    std::string auditorSignature;  // ECDSA signature of auditor
    bool        isActive;
};

isFullyBacked() = (Σ active_reserves.goldGrams ≥ totalSupply)

15.3 · Mint & Burn

MINT(recipient, goldGrams, attestation): require attestation.valid && issuer.authorized totalSupply += goldGrams totalReserves += goldGrams balances[recipient] += goldGrams emit MintEvent(recipient, goldGrams, vaultId) BURN(holder, goldGrams, redemptionCert): require balances[holder] ≥ goldGrams totalSupply -= goldGrams totalReserves -= goldGrams balances[holder] -= goldGrams emit BurnEvent(holder, goldGrams, redemptionId)

15.4 · Price Oracle Integration

isPriceDataFresh(maxAgeSeconds) = (now − lastPriceUpdate ≤ maxAgeSeconds) Default: maxAgeSeconds = 3600 (1 hour) Token value = goldGrams × currentGoldPrice (via PoP oracle)

15.5 · Transaction Chaining (same as base GXC)

cpp
// GXC-G follows same POT formula as base GXC
GoldTokenTransfer.prevTxHash    = lastTxHash[sender]
GoldTokenTransfer.popReference  = currentPriceOracleData

// Attestation generation:
attestation = Sign(H(vaultId || goldGrams || timestamp || purpose), vault_privateKey)
16.

Decentralized Governance System

PROPOSEDACTIVEVOTEDPASSEDEXECUTEDFAILEDQuorum: 15% stake · Approval: 60% · Period: 7 days · Min stake to propose: 1000 GXC

16.1 · Parameters

Governance Thresholds
DEFAULT_QUORUM_THRESHOLD = 0.15 (15% of stake must vote) DEFAULT_PASS_THRESHOLD = 0.60 (60% approval required) MINIMUM_PROPOSAL_STAKE = 1000 GXC DEFAULT_VOTING_PERIOD = 7 days [3 days min, 30 days max]

16.2 · Vote Weight & Approval

Stake-Weighted Voting
voteWeight(staker) = stakeAmount × (stakingDays/365)^0.5 (same β=0.5 as validator selection) Quorum: totalVotes / totalNetworkStake ≥ 0.15 Approval: forVotes / (forVotes + againstVotes) ≥ 0.60

16.3 · Changeable Parameters via Governance

cpp
enum class ParameterType {
    TARGET_INFLATION_RATE, TARGET_PRICE_RATIO,
    ADJUSTMENT_K1, K2, K3, BASE_BURN_RATE,
    MIN_STAKE, ORACLE_THRESHOLD, BRIDGE_THRESHOLD,
    BLOCK_REWARD, DIFFICULTY_ADJUSTMENT
};

16.4 · Proposal Structure

cpp
class Proposal {
    std::string id;  // H(proposer||title||timestamp||nonce)
    std::string proposer;
    std::vector<ParameterChange> parameterChanges;
    std::time_t createdAt, votingEndsAt;
    ProposalStatus status;  // PROPOSED→ACTIVE→PASSED|FAILED→EXECUTED
    double forVotes, againstVotes, abstainVotes;
    double quorumThreshold, passThreshold;
};
17.

Proof of Price (PoP) Oracle System

17.1 · Multi-Oracle Aggregation

Oracle Consensus
Price = median({price₁, price₂, ..., priceₙ}) Required submissions: n ≥ 5 (default) Outlier detection: if |pᵢ − median| > outlierThreshold × median: flag pᵢ as outlier reduce oracle_i.reputation Time window: max(submissions.timestamps) − min() ≤ 3600s

17.2 · Oracle Reputation System

reputation_new = { reputation_old × 0.95, if outlier min(1.0, reputation_old × 1.05), if accurate reputation_old, otherwise } Active oracles = {o | o.reputation ≥ MIN_REPUTATION_THRESHOLD = 0.5}

17.3 · Proof of Price Hash

PoPHash = H(sortedPrices || sortedOracleIds || timestamp || aggregationRound) Submission validation: verify(submission.signature, oracle.publicKey) AND (now − submission.timestamp ≤ MAX_TIMESTAMP_DRIFT) AND oracle.isActive AND oracle.reputation ≥ 0.5
18.

Cross-Chain Bridge

SourceBTC/ETHBSC/SOLlock✓✓✓··3/5 = 67%thresholdmintGXCwrappedtokensconfirmationsBTC6ETH12BSC15SOL32DOT10

18.1 · Supported Chains & Confirmation Requirements

ChainConfirmationsChain Type
GXCNativeNative
Bitcoin (BTC)6BITCOIN
Ethereum (ETH)12ETHEREUM
BNB Smart Chain15BSC
Solana (SOL)32SOLANA
Polkadot (DOT)10POLKADOT

18.2 · Multi-Signature Threshold

requiredSignatures = ⌈validatorCount × 0.67⌉ (67% threshold) validTransfer(id) = signatures.count ≥ requiredSignatures AND all signatures cryptographically valid AND source chain verification passed AND amount matches source transaction

18.3 · Transfer Lifecycle

initiateTransfer(sourceChain, asset, amount, destination)
  → transferId = H(sourceChain||asset||amount||destination||nonce)
  → status: PENDING

verifyAndSignTransfer(transferId, validatorId, signature)
  → if signatures ≥ requiredSignatures: status = READY

executeTransfer(transferId)
  → direction IN:  mintWrappedTokens(destination, amount)
  → direction OUT: releaseLockedTokens(destination, amount)
  → status: COMPLETED
19.

Stock Contract System

19.1 · Three Legal Models

Model 1
Synthetic Equity
  • → Price-tracking only
  • → NO legal ownership
  • → Cash/crypto settlement
  • → Derivatives-like structure
Model 2
Custodial-Backed
  • → 1:1 backed by real shares
  • → Custodian holds physical shares
  • → Optional voting/dividend rights
  • → Audited reserves
Model 3
Issuer-Authorized
  • → Company-issued shares on-chain
  • → Direct legal ownership
  • → On company cap table
  • → Full shareholder rights

19.2 · Corporate Actions

Dividend: dividendPerShare → for each holder: credit += shares × dividendPerShare Split(ratio): shareBalances[all] *= ratio; currentPrice /= ratio Merger(ratio, target): for each holder: target.issueShares(holder, oldShares×ratio); oldShares=0

19.3 · Price Validation

Max price deviation: |newPrice − currentPrice| / currentPrice ≤ 0.15 (15%) Max price age: timestamp age ≤ 3600 seconds (1 hour)

19.4 · Index Value

indexValue = Σᵢ (componentᵢ.price × componentᵢ.weight) Constraints: Σ weights = 1.0 (100%) componentᵢ.weight ≤ 0.30 (max 30% per component)
20.

AI-Based Security Engine

AI SecurityEngineα=0.60Hashrate SentinelEMA predictionDiff Guardadaptive adjustEmission Guardtime penaltiesFee Surge Guardmempool-basedH_pred = α×H_now+ (1-α)×H_prevsurge>12%→attack

20.1 · Hashrate Sentinel

Exponential Moving Average Prediction
H_predicted(t) = α × H_actual(t) + (1−α) × H_predicted(t−1) where α = PREDICTIVE_WEIGHT = 0.60 surge = (H_current − H_predicted) / H_predicted if surge > 0.12: attack_detected → apply_difficulty_penalty() // 51% attack suspected Convergence proof: lim(t→∞) H_predicted → H_actual ∎

20.2 · Predictive Difficulty Guard

D_new = D_old × (H_predicted / H_actual)^0.25 D_new = clamp(D_new, D_old/4, D_old×4)

20.3 · Staker-Balance Modifier

stake_influence = min(0.50, stakeRatio × 0.20) where stakeRatio = totalStaked / totalSupply D_final = D_base × (1 + stake_influence)

20.4 · Emission Guard (Anti-Inflation)

reward_multiplier = clamp(timeTaken / TARGET_BLOCK_TIME, 0.1, 1.5) Special: if timeTaken < MIN_BLOCK_TIME → multiplier = 0.1 (fast block farming penalty) final_reward = base_reward × reward_multiplier

20.5 · Fee Surge Guard

fee = clamp(MIN_FEE + mempoolSize × 0.00001, 0.001, 0.01) MIN_FEE = 0.001 GXC · MAX_FEE = 0.01 GXC

20.6 · Hybrid Penalty Logic

pow_ratio = recentPoWBlocks / (recentPoWBlocks + recentPoSBlocks)
if |pow_ratio − 0.5| > 0.3:  // more than 80/20 imbalance
    penalty = 1 − |pow_ratio − 0.5|
    apply_penalty_to_overrepresented_side(penalty)

20.7 · Attack Detection Types

hashrate > predicted × 2.0  → "51% ATTACK SUSPECTED"
timeTaken < target × 0.1   → "FAST BLOCK FARMING"
consecutiveFastBlocks > 10 → "BOTNET DETECTED"
else                        → "NORMAL"
21.

Mining Infrastructure

21.1 · Stratum Protocol

PoolServerStratumProtocolmining_workmining_submitCPUMinerGPUMinerASICMinerPoolMemberShare difficulty auto-adjusts per miner · CPU/GPU/ASIC hardware detected · per-miner diff tuning
cpp
struct StratumJob {
    std::string jobId, prevHash, coinbase1, coinbase2;
    std::vector<std::string> merkleBranches;
    std::string version, nBits, nTime;
    bool        cleanJobs;
    double      difficulty;
    uint32_t    height;
};

// Per-miner difficulty auto-adjustment:
if (sharesPerMinute > TARGET × 1.2): minerDifficulty *= 1.5
if (sharesPerMinute < TARGET × 0.8): minerDifficulty *= 0.75

21.2 · Hardware Detection

cpp
enum class DeviceType { CPU, GPU, ASIC };

struct MiningDevice {
    uint32_t    id;
    DeviceType  type;
    std::string name, vendor;
    uint64_t    memory;       // bytes
    uint32_t    computeUnits; // cores/CUs
    uint32_t    clockSpeed;   // MHz
    double      temperature;  // Celsius
    double      power;        // Watts
    double      hashRate;     // H/s
};

// Supports: CPU (multi-core), NVIDIA CUDA GPUs, AMD OpenCL GPUs, ASICs

21.3 · Mining Optimization

cpp
findOptimalThreadCount():
    if CPU_MINING: return physicalCores          // avoid hyperthreading
    if GPU_MINING: return min(4, physicalCores)  // GPU driver threads

findOptimalClockSpeeds(deviceId):
    for clock in range(baseClock, maxClock, step=25MHz):
        hashrate = benchmark(deviceId, 60s)
        efficiency = hashrate / getPower(deviceId)
        if efficiency > bestEfficiency: bestClock = clock
22.

Wallet System

22.1 · Wallet Structure

cpp
class Wallet {
    std::string privateKey;   // secp256k1 256-bit
    std::string publicKey;    // compressed 264-bit
    std::string address;      // GXC address
    std::string lastTxHash;   // for POT chaining

    // Multi-wallet support
    std::unordered_map<std::string, std::string> importedAddresses;
    std::unordered_map<std::string, std::string> importedPrivateKeys;
    std::unordered_map<std::string, TransactionOutput> unspentOutputs;
};

22.2 · Key Generation Process

1. d ← random 256-bit ∈ [1, n−1] 2. Q = d·G (secp256k1 point multiply) 3. Compress Q: prefix 0x02 (y even) or 0x03 (y odd) || Q.x 4. hash1 = SHA256(CompressedPublicKey) 5. hash2 = RIPEMD160(hash1) 6. address = "GXC" || Base58Check(hash2)

22.3 · UTXO Coin Selection Algorithm

selectUTXOs(targetAmount, fee):
    utxos = getUTXOs(address).sort(descending by amount)
    selected = [], total = 0
    for utxo in utxos:
        selected.append(utxo); total += utxo.amount
        if total ≥ targetAmount + fee: break
    change = total − targetAmount − fee
    return (selected, change)

22.4 · Third-Party Wallet Integration

cpp
// Import private key:
importPrivateKey(privateKeyHex, label) →
    address = deriveAddress(derivePublicKey(privateKeyHex))
    importedPrivateKeys[address] = privateKeyHex

// Watch-only address:
importAddress(addr, label) →
    require isValidAddress(addr)
    importedAddresses[addr] = label

// Sign from specific address:
createTransactionFrom(fromAddress, toAddress, amount, fee) →
    privateKey = getPrivateKeyForAddress(fromAddress)
    return signTransactionWithKey(tx, privateKey)
23.

Address Registry System (Clean Zones)

23.1 · Entity Types

cpp
enum class EntityType { EXCHANGE, STAKING_POOL, MERCHANT, VALIDATOR, UNKNOWN };

struct EntityInfo {
    EntityType  type;
    std::string name, address, website, verificationSource;
    uint64_t    registeredAt, lastVerified;
    bool        verified;
};

23.2 · Integration with Fraud Detection

FraudDetection::checkCleanZoneEntry(tx, taint): recipient = tx.getReceiverAddress() if addressRegistry.isRegistered(recipient): type = addressRegistry.getEntityType(recipient) if type ∈ {EXCHANGE, STAKING_POOL} AND taint.score > δ: return ALERT // tainted funds entering clean zone
24.

WebSocket Real-Time API

24.1 · Message Protocol

json
// Block notification:
{"type":"new_block","data":{"height":12345,"hash":"0000abc...","timestamp":1640995200,"transactions":42,"difficulty":1000.0,"miner":"GXC...","reward":50.0}}

// Transaction notification:
{"type":"new_transaction","data":{"hash":"abc123...","from":"GXC...","to":"GXC...","amount":10.5,"fee":0.001,"confirmed":false}}

// Stats update (every 10 seconds):
{"type":"blockchain_stats","data":{"height":12345,"difficulty":1000.0,"hashrate":1.5e15,"total_supply":15000000.0,"total_staked":5000000.0,"active_validators":50,"mempool_size":120}}

24.2 · Subscription Model

json
// Client → Server:
{"action":"subscribe","topics":["blocks","transactions","stats"]}

// Server → Client:
{"status":"subscribed","topics":["blocks","transactions","stats"]}
25.

Big Integer Arithmetic (arith_uint256)

25.1 · 256-bit Integer Structure

cpp
class arith_uint256 {
private:
    static constexpr int WIDTH = 8;  // 8 × 32-bit = 256 bits
    uint32_t pn[WIDTH];
};

25.2 · Compact Difficulty Representation

Compact = (exponent << 24) | mantissa where: exponent = number of bytes (1–32) mantissa = first 3 significant bytes SetCompact(nCompact): exponent = nCompact >> 24 mantissa = nCompact & 0x00FFFFFF if exponent ≤ 3: value = mantissa >> (8×(3−exponent)) else: value = mantissa << (8×(exponent−3))

25.3 · Block Proof Calculation

BlockProof = 2²⁵⁶ / (target + 1) Chainwork = Σ BlockProof(all blocks) → determines heaviest chain (most work done)
26.

Database Layer — Complete LevelDB Specification

26.1 · Singleton + Network Isolation Guard

Database::initialize(dbPath) → opens LevelDB, stores singleton Database::getInstance() → returns reference (throws if not init'd) Network Isolation Guard: isTestnet=true → path MUST contain "testnet" isTestnet=false → path MUST NOT contain "testnet" → prevents testnet DB corrupting mainnet state

26.2 · LevelDB Tuning Parameters

cpp
options.create_if_missing  = true
options.paranoid_checks    = true
options.max_open_files     = 100
options.write_buffer_size  = 4 MB       // in-memory write buffer
options.block_cache        = 8 MB       // LRU read cache
options.filter_policy      = Bloom(10)  // 10-bit Bloom filter per key
options.compression        = Snappy     // fast lossless compression
writeOptions.sync          = false      // async flush (chain is rebuild-able)

26.3 · Key Namespace

blk:Block JSONblkh:Hash by heighttx:Transaction JSONutxo:UTXO setaddr:Address UTXO indexval:Validator JSONtrace:Traceability recordwallet:Encrypted walletproposal:Governance proposalprice:Oracle price databridge:Bridge transfershare:Mining pool shareLevelDB · atomic WriteBatch per block · Bloom filter(10) · 8MB LRU cache · Snappy compression
// Height key zero-padding (lexicographic = numeric order):
"blkh:0000000042"  → block at height 42

// Full key examples:
"utxo:abc123def:0"              → UTXO output 0 of tx abc123def
"addr:GXC...:abc123:0"         → address index entry
"vote:proposalId:voterAddress"  → governance vote
"price:XAUUSD:1700000000"      → gold price at timestamp

26.4 · Atomic WriteBatch (per block)

saveBlock() → single atomic WriteBatch:
  1.  blk:<hash>           = Block JSON
  2.  blkh:<height>        = block hash
  3.  cfg:latest_*         = height + hash
  For each tx in block:
  4.  tx:<txHash>          = Transaction JSON
  5.  txb:<txHash>         = {block_hash, block_height}
  6.  DELETE spent UTXOs
  7.  utxo:<txHash>:<idx>  = new UTXO JSON
  8.  addr:<addr>:<tx>:<i> = address index
  9.  trace:<txHash>       = traceability record
→ Atomicity: crash = either fully applied or fully absent

26.5 · JSON Schemas (key records)

json
// Block:
{"index":12345,"hash":"0000abc...","previous_hash":"0000xyz...","merkle_root":"...","timestamp":1700000000,"difficulty":1000.0,"nonce":987654321,"miner_address":"GXC...","block_type":0,"tx_hashes":["hash1","hash2"]}

// UTXO:
{"tx_hash":"abc...","output_index":0,"address":"GXC...","amount":10.0,"script":"","block_height":12345}

// Validator:
{"address":"GXC...","stake_amount":5000.0,"staking_days":180,"is_active":true,"blocks_produced":423,"missed_blocks":2,"uptime":99.53,"is_slashed":false}

26.6 · DB Maintenance Operations

cpp
vacuum()          → db->CompactRange(nullptr, nullptr)
backup(path)      → std::filesystem::copy(dataDirectory, path, recursive)
restore(path)     → close() → remove(dir) → copy(path) → reopen()
getDatabaseSize() → Σ file_size for all files in dataDirectory
repairDatabase()  → leveldb::RepairDB(dataDirectory, options)

26.7 · Error Codes

cpp
DB_SUCCESS=0  DB_ERROR_INIT=1  DB_ERROR_NOT_FOUND=2
DB_ERROR_CORRUPT=3  DB_ERROR_DISK_FULL=4
DB_ERROR_PERMISSION=5  DB_ERROR_IO=6
27.

Block Explorer API

27.1 · Endpoints Overview

Block:        getLatestBlocks(limit) · getBlock(hashOrHeight) · getBlockTransactions(id) · searchBlocks(query)
Transaction:  getTransaction(hash) · getTransactionChain(hash) · getLatestTransactions(N) · getAddressTransactions(addr,N) · searchTransactions(query)
Address:      getAddressDetails(addr) · getAddressBalance(addr) · getAddressUtxos(addr) · getRichestAddresses(limit)
Validator:    getAllValidators() · getValidatorDetails(addr) · getTopValidators(N)
Stock:        getAllStocks() · getStockDetails(ticker) · getStockHolders(ticker) · getStockTransactions(ticker,N) · getMarketMakerStocks(addr)
Charts:       getBlockTimeChart(days) · getTransactionVolumeChart(days) · getValidatorDistributionChart() · getStockPriceChart(ticker,days)
Search:       search(query) → {blocks, transactions, addresses, validators, stocks}

27.2 · Network Statistics Response

json
getBlockchainStats():
{"total_blocks":12345,"total_transactions":987654,"total_addresses":45678,"total_supply":15000000.0,"circulating_supply":14500000.0,"total_burned":100.0,"avg_block_time":601.2}

getNetworkStats():
{"hashrate":1.5e15,"difficulty":1000.0,"active_validators":50,"total_staked":5000000.0,"stake_ratio":0.33,"mempool_size":120,"peer_count":87,"protocol_version":70015}
28.

Market Maker Administration System

28.1 · Admin Role Hierarchy

super_admin    → create/remove admins · approve/reject applications · revoke market makers · full audit log
verifier       → execute all 5 verification steps
reviewer       → assign applications · view pending
fraud_admin    → assign fraud reports · view all
fraud_approver → approve/reject fraud reports (triggers reversal pipeline)
fraud_reviewer → view fraud reports only

28.2 · Five-Step Verification Pipeline

Step 1
Verify License

Contact regulatory body (SEC/FCA/MAS), verify licenseNumber, record proofDocumentHash

Step 2
Company Reputation

Search public records, news, regulatory databases, flag disciplinary history

Step 3
Financial Standing

Review audited financials hash, verify sufficient capital

Step 4
Technical Capabilities

Review technical capabilities hash, confirm safe on-chain operation

Step 5
KYC/AML Check

Full Know Your Customer + Anti-Money Laundering, review kycDocumentsHash

28.3 · Application Status Lifecycle

PENDING → UNDER_REVIEW → LICENSE_VERIFIED → REPUTATION_CHECKED
       → FINANCIAL_REVIEWED → TECHNICAL_VERIFIED → KYC_AML_COMPLETED
       → APPROVED  (super_admin decision)
    OR → REJECTED  (at any step)
    OR → REVOKED   (post-approval)

28.4 · Fraud Report Lifecycle

submitFraudReport(txHash, reporter, amount, email, description, evidence)
  → PENDING
  → assignFraudReportToReviewer(reportId)
  → fraud_approver.approveReport(reportId)
       → FraudDetection::markAsStolen(txHash)
       → TaintPropagation starts automatically
       → ProofGenerator::generateProof()
       → ReversalExecutor::executeReversal()
       → PROTOCOL_VALIDATING → EXECUTED | INFEASIBLE
  OR → fraud_approver.rejectReport(reportId) → FACTS_REJECTED

Key principle: admins validate FACTS — protocol validates MATH
  No admin can force infeasible reversal
  No admin can block feasible fact-approved reversal

28.5 · Audit Log

cpp
struct AuditLogEntry {
    std::string logId, adminId, action;  // "verify_license", "approve_application"
    std::string applicationId, details;
    std::time_t timestamp;
    std::string ipAddress;
};
// Append-only · accessible only to super_admin
29.

Config System

cpp
class Config {
    bool        isTestnet;
    uint16_t    p2pPort;              // 8333 mainnet / 18333 testnet
    uint16_t    rpcPort;              // 8332 mainnet / 18332 testnet
    uint16_t    restPort;             // 8080
    uint32_t    targetBlockTime;      // 600s mainnet / 120s testnet
    uint32_t    difficultyAdjustInterval; // 2016 blocks
    double      minDifficulty;        // 1000.0 mainnet / 1.0 testnet
    uint64_t    maxBlockSize;         // 1,048,576 bytes
    double      initialBlockReward;   // 50.0 GXC
    uint64_t    halvingInterval;      // 1,051,200 blocks
    double      maxSupply;            // 31,000,000 GXC
    double      feePoolSplitPercentage; // 0.15
    double      minValidatorStake;    // 100.0 GXC
    uint32_t    minStakingDays;       // 14
    uint32_t    maxStakingDays;       // 365
    std::string dataDirectory;
    LogLevel    logLevel;
    std::string logFile;
};
ParameterMainnetTestnet
Block time600 s120 s
Min difficulty1000.01.0
P2P port833318333
RPC port833218332
Network magic"GXC\x01""GXCT"
Address prefix"GXC""tGXC"
DB path(no testnet)must contain 'testnet'
30.

Logger System

cpp
// Log levels:
enum class LogLevel { DEBUG, INFO, WARNING, ERROR, CRITICAL };

// All logging macros:
LOG_BLOCKCHAIN(level, message)   LOG_NETWORK(level, message)
LOG_MINING(level, message)       LOG_DATABASE(level, message)
LOG_SECURITY(level, message, component)   // → also writes to security audit trail
LOG_FRAUD(level, message)        LOG_REVERSAL(level, message)
LOG_GOVERNANCE(level, message)   LOG_BRIDGE(level, message)
LOG_ORACLE(level, message)       LOG_STAKING(level, message)
LOG_WALLET(level, message)

// LOG_SECURITY is special: writes to both standard log AND tamper-evident
// security audit trail for forensic review.
App A.

Mathematical Notation

SymbolMeaning
τ(T)Taint score of transaction T ∈ [0,1]
wᵢWeight of input i = valueᵢ / total_value
δTaint threshold (0.1)
βTime weight exponent (0.5)
HBlock hash function
DDifficulty
RBlock reward
σECDSA signature (r,s)
GGenerator point on secp256k1
nOrder of G
pPrime field of secp256k1
αEMA smoothing factor (0.60)
θRe-aggregation threshold (0.7)
εVelocity epsilon (300 s)
App B.

Complete Constants Reference

cpp
// ── Consensus ──
MAX_SUPPLY                   = 31,000,000 GXC
HALVING_INTERVAL             = 1,051,200 blocks
INITIAL_BLOCK_REWARD         = 50.0 GXC
TARGET_BLOCK_TIME            = 600 seconds
DIFFICULTY_ADJUSTMENT_INTERVAL = 2016 blocks

// ── Staking ──
MIN_STAKE_AMOUNT             = 10.0 GXC
MIN_VALIDATOR_STAKE          = 100.0 GXC
MIN_STAKING_DAYS             = 14
MAX_STAKING_DAYS             = 365
VALIDATOR_BETA               = 0.5

// ── Fraud Detection ──
TAINT_THRESHOLD              = 0.1     (δ)
HIGH_TAINT                   = 0.5
CRITICAL_TAINT               = 0.8
VELOCITY_EPSILON             = 300 s
FAN_OUT_K                    = 5
RE_AGG_THETA                 = 0.7
DORMANCY_PERIOD              = 604,800 s  (7 days)

// ── Reversal System ──
MIN_TAINT_THRESHOLD          = 0.1
MAX_TRACE_HOPS               = 20
REVERSAL_WINDOW              = 20,000 blocks (~30 days)

// ── Network ──
MAX_CONNECTIONS              = 125
MAX_OUTBOUND                 = 8
PING_INTERVAL                = 30 s
PEER_TIMEOUT                 = 90 s
MAX_MESSAGE_SIZE             = 32 MB

// ── AI Security ──
PREDICTIVE_WEIGHT (α)        = 0.60
SURGE_THRESHOLD              = 0.12
DIFFICULTY_ADJUSTMENT_FACTOR = 0.25
MAX_STAKE_INFLUENCE          = 0.50
STAKE_FACTOR                 = 0.20
MAX_DIFFICULTY_CHANGE        = 4.0
MIN_REWARD_RATIO             = 0.10
MAX_REWARD_RATIO             = 1.50

// ── Governance ──
DEFAULT_QUORUM_THRESHOLD     = 0.15
DEFAULT_PASS_THRESHOLD       = 0.60
MINIMUM_PROPOSAL_STAKE       = 1,000 GXC
DEFAULT_VOTING_PERIOD        = 7 days

// ── Bridge ──
BRIDGE_THRESHOLD             = 0.67  (67% multi-sig)
App C.

Implementation Files Reference

// Core Blockchain
Blockchain.cpp/.h  Block.cpp/.h  Transaction.cpp/.h  block.cpp/.h

// Cryptography
Crypto.cpp/.h  HashUtils.cpp/.h  Keccak256.cpp/.h
Blake2b.cpp/.h  Argon2id.cpp/.h  arith_uint256.cpp/.h

// Consensus
Validator.cpp/.h  SalectValidator.cpp  StakingPool.cpp/.h  ValidatorRegistry.cpp/.h

// Fraud & Reversal
FraudDetection.cpp/.h  ProofGenerator.cpp/.h
ReversalExecutor.cpp/.h  ReversalFeePool.cpp/.h  AddressRegistry.cpp/.h

// Tokens & Assets
GoldToken.cpp/.h  StockContract.cpp/.h
StockMarketAPI.cpp/.h  ProofOfPrice.cpp/.h

// Bridge & Governance
CrossChainBridge.cpp/.h  Governance.cpp/.h  Proposals.cpp  Voting.cpp

// Mining
EthashAlgorithm.cpp/.h  EthashMiner.cpp/.h  GXHashMiner.cpp/.h
SHA256Miner.cpp/.h  CPUMiner.cpp  MiningManager.cpp/.h
MiningOptimizer.cpp/.h  HardwareDetector.cpp/.h
PoolManager.cpp/.h  Stratum.cpp/.h

// Network
Network.cpp/.h  P2PNetwork.cpp  PeerManager.cpp/.h
MessageHandler.cpp/.h  RESTServer.cpp/.h  RPCAPI.cpp/.h  WebSocketServer.cpp/.h

// Security
SecurityEngine.cpp/.h

// Utilities
Database.cpp/.h  Logger.cpp/.h  Config.cpp/.h  Utils.cpp/.h  Wallet.cpp/.h
App D.

Complete Feature Matrix

FeatureBitcoinEthereumGXC
Hybrid PoW/PoS❌ PoW only❌ PoS only✅ Alternating
Fraud Detection❌❌✅ Taint propagation
Transaction Reversal❌❌✅ Proof of Feasibility
TraceabilityBasic UTXOAccount model✅ POT (math-enforced)
Mining AlgorithmsSHA-256None (staking)✅ SHA-256+Ethash+GXHash
Gold-Backed Token❌❌✅ GXC-G (100% reserve)
On-Chain Governance❌ off-chain BIPPartial✅ Stake-weighted
Cross-Chain BridgeLimitedYes (3rd party)✅ 6 chains, 67% multisig
Supply Cap21M BTCNo hard cap✅ 31M GXC
Price Oracle❌Chainlink (3rd party)✅ PoP (native)
Stock Contracts❌Via DeFi✅ 3 legal models
AI Security Engine❌❌✅ Hashrate sentinel
Market Maker Admin❌❌✅ 5-step regulatory
Self-Sustaining Pool❌❌✅ 15% fee split
WebSocket API3rd party3rd party✅ Native real-time
App E.

Mathematical Proofs

E.1 · Taint Conservation Proof

Theorem: sum of output taints equals input taint
Given: Transaction T with inputs I={i₁,...,iₙ} and outputs O={o₁,...,oₘ} Input taint: τ_in = Σⱼ wⱼ × τ(iⱼ) where wⱼ = value(iⱼ) / Σ value(i) Output taint: τ(oₖ) = τ_in (same taint for all outputs — proportional to input) ∴ 0 ≤ τ(T) ≤ 1 for all T ∎

E.2 · Security Engine Convergence Proof

Theorem: EMA converges to actual hashrate
H_pred(t) = α × H_actual(t) + (1−α) × H_pred(t−1) Expanding recursively: H_pred(t) = α × Σᵢ₌₀ᵗ⁻¹ (1−α)ⁱ × H_actual(t−i) + (1−α)ᵗ × H_pred(0) As t → ∞: lim(t→∞) (1−α)ᵗ = 0 [since 0 < α < 1] If H_actual is constant H: lim(t→∞) H_pred(t) = α × H × Σᵢ₌₀^∞ (1−α)ⁱ = α × H × (1/α) = H ∎
App F.

Complete Database Key Reference

blk:<blockHash>                        → Block JSON
blkh:<0000000000>                      → Block hash at given height (zero-padded)
tx:<txHash>                            → Transaction JSON
txb:<txHash>                           → {"block_hash":..., "block_height":...}
utxo:<txHash>:<outputIndex>            → UTXO JSON
addr:<address>:<txHash>:<outputIndex>  → UTXO JSON (address index)
val:<address>                          → Validator JSON
peer:<ip>:<port>                       → {"ip":..., "port":..., "last_seen":...}
cfg:<key>                              → Config string value
trace:<txHash>                         → Traceability JSON
wallet:<address>                       → {"public_key":..., "encrypted_private_key":...}
proposal:<proposalId>                  → Governance proposal JSON
vote:<proposalId>:<voter>              → {"voter":..., "type":...}
price:<asset>:<timestamp>             → {"price":..., "timestamp":...}
bridge:<transferId>                    → Bridge transfer JSON
share:<poolAddress>:<minerAddress>     → {"pool":..., "miner":..., "value":..., "timestamp":...}
App G.

Admin Permission Matrix

Actionsuper_adminverifierreviewerfraud_adminfraud_approverfraud_reviewer
Create admin✅❌❌❌❌❌
Approve/reject application✅❌❌❌❌❌
Revoke market maker✅❌❌❌❌❌
View audit log✅❌❌❌❌❌
Execute verification steps✅✅❌❌❌❌
Assign application✅❌✅❌❌❌
View pending applications✅✅✅❌❌❌
Assign fraud report✅❌❌✅❌❌
Approve/reject fraud report✅❌❌❌✅❌
View fraud reports✅❌❌✅✅✅
View dashboard✅✅✅✅✅✅