/** * Bitcoin-Complete Chain — Flying Whale Sovereign Protocol * * COPYRIGHT 2026 Flying Whale — zaghmout.btc | ERC-8004 #54 | ALL RIGHTS RESERVED * Flying Whale Proprietary License v3.0 — Agreement-First Policy * Owner: SP322ZK4VXT3KGDT9YQANN9R28SCT02MZ97Y24BRW * * ══════════════════════════════════════════════════════════════════════════════ * BITCOIN'S OWN FOUNDATIONS — APPLIED IN FULL * ══════════════════════════════════════════════════════════════════════════════ * * Every element Satoshi built — applied exactly, with the same logic: * * 1. SHA256d — double SHA-256: Bitcoin's actual hash function * 2. Block Header — version · prevHash · merkleRoot · time · nBits · nonce * 3. Merkle Tree — binary hash tree over all transactions (tool calls) * 4. nBits — compact 4-byte difficulty target (exactly Bitcoin's format) * 5. Proof of Physics — find nonce: SHA256d(header) < target(nBits) * 6. Difficulty — retargets every 2016 blocks (same period as Bitcoin) * 7. Halving — every 210,000 blocks, WHALE floor doubles * 8. UTXO Model — unspent access outputs; spend by signature * 9. FW Script — stack VM: OP_CHECKSIG · OP_WHALE_CHECK · OP_PSI_VERIFY * 10. Coinbase TX — first tx in every block; creates block reward * 11. Total Work — accumulated difficulty (chainwork) across all blocks * 12. Chain Select — longest chain (most accumulated PoP work) wins * * GENESIS: * Block 0 hash: 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f * (We use a FW genesis hash derived from owner address + founding constants) * * BLOCK TIME TARGET: 600,000 ms (10 minutes) — same as Bitcoin * DIFFICULTY PERIOD: 2,016 blocks — same as Bitcoin * HALVING PERIOD: 210,000 blocks — same as Bitcoin */ import type { PsiDimensions } from "./psi-consensus.js"; export declare const FW_GENESIS_HASH = "00000000001a42b4b57c4bd1e7cbe0ecf8623b90780f98da7b8e2c34844fa9200"; /** * Flying Whale Transaction — equivalent to a Bitcoin transaction. * In FW: each tool call = one transaction. * Coinbase tx = session open event (creates block reward). */ export interface FWTransaction { txid: string; type: "coinbase" | "tool_call" | "access_spend" | "whale_transfer"; tool: string; timestamp: number; result: "success" | "blocked" | "error" | "pending"; value: bigint; psiImpact: number; inputs: FWTxInput[]; outputs: FWTxOutput[]; } export interface FWTxInput { prevTxid: string; vout: number; scriptSig: string; sequence: number; } export interface FWTxOutput { value: bigint; scriptPubKey: FWScript; address: string; } /** * FW Script — simplified Bitcoin Script. * Stack-based VM for spending conditions. */ export interface FWScript { asm: string; hex: string; type: FWScriptType; } export type FWScriptType = "P2PKH" | "WHALE_GATE" | "PSI_GATE" | "SOVEREIGN_GATE" | "MULTISIG" | "NULLDATA"; /** * UTXO — Unspent Transaction Output. * In FW: an unspent access permission. * Created when: session opens, WHALE acquired, block mined. * Spent when: tool call executes, access expires. */ export interface FWUTXO { txid: string; vout: number; address: string; scriptPubKey: FWScript; value: bigint; blockHeight: number; coinbase: boolean; spent: boolean; spentByTxid?: string; } /** * FW Block — Bitcoin-complete block structure. * Header is exactly 80 bytes (like Bitcoin). */ export interface FWBlock { version: number; prevHash: string; merkleRoot: string; time: number; nBits: number; nonce: number; hash: string; height: number; totalWork: string; txCount: number; txids: string[]; transactions: FWTransaction[]; address: string; psiScore: number; tier: string; dimensions: PsiDimensions; whaleBalance: string; blockReward: string; psiChainHash: string; } /** * SHA256d(data) = SHA256(SHA256(data)) * Bitcoin uses this for EVERY hash — blocks, transactions, Merkle tree. * The double-hash eliminates length-extension attacks. */ export declare function sha256d(data: string | Buffer): string; /** SHA256d on hex-encoded input (for hashing txids, etc.) */ export declare function sha256dHex(hex: string): string; /** * Build Merkle root from list of txids. * * Bitcoin's Merkle tree: * - Leaf nodes: SHA256d of each transaction * - Parent: SHA256d(leftChild + rightChild) [concatenated 32-byte hashes] * - If odd number of leaves: duplicate the last one * - Root is stored in block header * * Any change to any transaction changes the Merkle root, which changes * the block hash, which invalidates all subsequent blocks. */ export declare function buildMerkleRoot(txids: string[]): string; /** * Build Merkle proof for a specific txid. * Returns array of {hash, position} pairs for SPV verification. */ export declare function buildMerkleProof(txids: string[], targetTxid: string): { proof: Array<{ hash: string; position: "left" | "right"; }>; root: string; verified: boolean; }; /** * Expand nBits to full 256-bit target. * * Bitcoin nBits format: * [1 byte exponent] [3 bytes coefficient] * target = coefficient × 256^(exponent - 3) * * Example: 0x1d00ffff (Bitcoin genesis) * exponent = 0x1d = 29 * coefficient = 0x00ffff * target = 0x00ffff × 256^(29-3) = 0x00000000FFFF0000...0000 */ export declare function expandNBits(nBits: number): bigint; /** * Compress a 256-bit target into nBits format. */ export declare function compressTarget(target: bigint): number; /** * Convert target to hex string (zero-padded to 64 chars). */ export declare function targetToHex(target: bigint): string; /** * Get the current Ψ-adjusted target. * Higher Ψ score (adversarial) = lower target (harder to mine) — punishes attackers. * Lower Ψ score (trustworthy) = higher target (easier to mine) — rewards cooperation. * * This mirrors Bitcoin: honest miners with more hashpower mine faster. * In FW: more trustworthy sessions mine faster (lower difficulty). */ export declare function getPsiAdjustedTarget(baseNBits: number, psiScore: number): bigint; /** * Serialize block header to 80-byte Buffer (exactly Bitcoin's format). * * Layout (little-endian integers, like Bitcoin): * [0-3] version (4 bytes, LE) * [4-35] prevHash (32 bytes, reversed byte order — Bitcoin convention) * [36-67] merkleRoot (32 bytes, reversed byte order) * [68-71] time (4 bytes, LE) * [72-75] nBits (4 bytes, LE) * [76-79] nonce (4 bytes, LE) */ export declare function serializeHeader(version: number, prevHash: string, merkleRoot: string, time: number, nBits: number, nonce: number): Buffer; /** * Mine a block: find nonce such that SHA256d(header) < target. * * This is EXACTLY what Bitcoin miners do. * In FW: we use a lenient target (most nonces will work quickly), * scaled by the session's Ψ score. Adversarial sessions may fail. * * Returns null if mining fails within MAX_NONCE iterations. * (Adversarial sessions get a harder target and may not find a valid nonce * within the 4-byte nonce space — same logic as Bitcoin difficulty.) */ export declare function mineBlock(version: number, prevHash: string, merkleRoot: string, time: number, nBits: number, psiScore: number, maxAttempts?: number): { nonce: number; hash: string; found: boolean; }; /** * Compute block reward at a given height. * * Bitcoin halving: every 210,000 blocks, reward halves. * Start: 50 BTC → 25 → 12.5 → ... * After 64 halvings: reward rounds to 0. * * FW equivalent: * - Start: 50,000,000 FW-sats (50 FW) * - Halves every 210,000 blocks * - Also: minimum WHALE floor increases with halving epoch */ export declare function blockReward(height: number): bigint; /** * Get minimum WHALE balance required at current halving epoch. * epoch 0 (blocks 0–209999): 0 WHALE * epoch 1 (blocks 210000–419999): 1 WHALE (1,000,000 micro) * epoch 2 (blocks 420000–629999): 2 WHALE * epoch 3+: epoch WHALE */ export declare function minWhaleRequired(height: number): bigint; export declare function halvingInfo(height: number): { epoch: number; blocksToNext: number; reward: bigint; minWhale: bigint; nextHalving: number; halvings: number; }; /** * Calculate new nBits after a difficulty period. * * Bitcoin's exact formula: * actualTime = time[lastBlock] - time[firstBlockInPeriod] * expectedTime = 2016 × 600 seconds * newTarget = oldTarget × actualTime / expectedTime * * Bounded: newTarget cannot change by more than 4× in either direction. * * In FW: we measure in milliseconds (same relative math). */ export declare function retargetDifficulty(oldNBits: number, actualMs: number, // actual time for last 2016 blocks expectedMs?: number): number; /** * FW Script opcodes (subset of Bitcoin Script + FW extensions). * * Bitcoin Script is a stack-based, Forth-like language. * Scripts are evaluated by pushing/popping values from a stack. * A script is valid if it leaves true (non-zero) on top of the stack. */ export declare const OP: { readonly OP_0: 0; readonly OP_PUSHDATA1: 76; readonly OP_PUSHDATA2: 77; readonly OP_NOP: 97; readonly OP_RETURN: 106; readonly OP_DUP: 118; readonly OP_DROP: 117; readonly OP_HASH160: 169; readonly OP_HASH256: 170; readonly OP_EQUALVERIFY: 136; readonly OP_CHECKSIG: 172; readonly OP_CHECKMULTISIG: 174; readonly OP_WHALE_CHECK: 240; readonly OP_PSI_VERIFY: 241; readonly OP_TIER_VERIFY: 242; }; /** Build P2PKH locking script (standard Bitcoin spending condition). */ export declare function p2pkhScript(addressHash: string): FWScript; /** Build WHALE_GATE locking script. */ export declare function whaleGateScript(minWhale: bigint): FWScript; /** Build PSI_GATE locking script. */ export declare function psiGateScript(maxScore: number): FWScript; /** Build full SOVEREIGN_GATE: must have WHALE + low Ψ + valid sig. */ export declare function sovereignGateScript(minWhale: bigint, maxScore: number): FWScript; /** Build OP_RETURN (null data) script for metadata embedding. */ export declare function opReturnScript(data: string): FWScript; /** * Execute FW Script and return whether it's valid. * Simplified — evaluates the 4 script types we support. */ export declare function executeScript(scriptPubKey: FWScript, context: { address: string; signature?: string; whaleBalance: bigint; psiScore: number; tier: string; }): { valid: boolean; reason: string; }; /** Get all unspent UTXOs for an address. */ export declare function getUtxos(address: string): Promise; /** Get total UTXO value (WHALE) for an address. */ export declare function getUtxoBalance(address: string): Promise; /** Create a new UTXO (when block is mined or WHALE acquired). */ export declare function createUtxo(txid: string, vout: number, address: string, value: bigint, blockHeight: number, coinbase: boolean, scriptType?: FWScriptType): Promise; /** Spend a UTXO (when tool call executes). Returns false if not found/already spent. */ export declare function spendUtxo(txid: string, vout: number, spentByTxid: string): Promise; /** * Build a coinbase transaction (first tx in every block). * * Bitcoin coinbase: * - Input: prevTxid = 0000...0000, vout = 0xFFFFFFFF * - Input scriptSig: arbitrary data (miners put their pool name, extra nonce, etc.) * - Output: block reward → miner's address * * FW coinbase: * - Records session opening + block height + miner address * - Creates UTXO with block reward value */ export declare function buildCoinbaseTx(blockHeight: number, minerAddress: string, minerMessage?: string): FWTransaction; /** * Build a tool-call transaction. * Each tool call = 1 transaction in the block. */ export declare function buildToolCallTx(tool: string, result: "success" | "blocked" | "error", psiImpact: number, address: string): FWTransaction; /** * Build, mine, and append a new FW block to the chain. * * This is the main function called at the end of each session: * 1. Builds coinbase tx (block reward) * 2. Includes all tool-call txs * 3. Computes Merkle root * 4. Mines the block (finds valid nonce) * 5. Appends to chain + creates reward UTXO * * Returns null if mining fails (adversarial session blocked). */ export declare function appendBlock(params: { address: string; psiScore: number; tier: string; dimensions: PsiDimensions; whaleBalance: bigint; toolCalls: Array<{ tool: string; result: "success" | "blocked" | "error"; psiImpact: number; }>; psiChainHash?: string; }): Promise; export interface ChainStats { height: number; totalBlocks: number; genesisHash: string; latestHash: string; totalWork: string; currentNBits: number; currentTarget: string; halvingInfo: ReturnType; avgBlockTimeMs: number; totalTxs: number; totalReward: bigint; integrity: boolean; topMiners: Array<{ address: string; blocks: number; reward: bigint; }>; } export declare function getChainStats(): Promise; /** Get a block by height or hash. */ export declare function getBlock(heightOrHash: number | string): Promise; /** Get block at tip. */ export declare function getLatestBlock(): Promise; /** Get current chain height. */ export declare function getChainHeight(): Promise; /** Get current nBits (for next block). */ export declare function getCurrentNBits(): Promise; /** * One milestone record per halving epoch. */ export interface FastForwardMilestone { epoch: number; height: number; hash: string; prevHash: string; nBits: number; target: string; nonce: number; reward: string; reward_fw: string; cumulative_supply: string; cumulative_fw: string; pct_of_cap: string; totalWork: string; simulated_time_days: number; psiChainHash: string; is_final: boolean; } export interface FastForwardResult { milestones: FastForwardMilestone[]; epochs_traversed: number; total_blocks: number; total_supply: string; total_supply_fw: string; max_supply: string; last_reward_block: number; final_hash: string; genesis_psi_anchor: string; complete: boolean; integrity: boolean; } /** * Carry the FW chain all the way to the last satoshi. * * Mines one real PoW block at every halving boundary (210,000 · epoch). * Timestamps are simulated at the correct 10-minute-per-block rate. * The chain stores ONLY the milestone blocks — one per epoch. * * After this function completes, the chain covers the full lifecycle: * Block 0 (genesis, epoch 0) → 50 FW reward * Block 210k (epoch 1) → 25 FW reward * Block 420k (epoch 2) → 12.5 FW reward * ... * Block 5.25M (epoch 25) → 1 FW-sat reward * Block 5.46M (epoch 26) → 0 (tail end — beyond the ceiling) */ export declare function fastForwardChain(params: { address: string; psiScore: number; tier: string; dimensions: PsiDimensions; whaleBalance: bigint; psiChainHash?: string; }): Promise; //# sourceMappingURL=btc-chain.d.ts.map