///|
/// ═══════════════════════════════════════════════════════
/// CryptoAssert 可运行示例(moon run examples)
/// ═══════════════════════════════════════════════════════
/// 本文件与 README 的 Quick Start 示例一一对应,由 CI 实际
/// 编译并运行,保证文档示例永远可复制、可执行。
///
/// 演示内容:
///   1. ECDSA secp256k1 密钥生成、交易签名与验签
///   2. 防重放:真实 nonce / chain ID 校验(重放与跨链均被拒)
///   3. 跨链桥审计:多签阈值校验(过半 / BFT 法定人数)
///   4. 资金守恒 + 端到端验证管道
///   5. 地址格式断言(EIP-55 校验和)
/// ═══════════════════════════════════════════════════════

///|
fn show_result(r : @protocol.SecurityAssertResult) -> String {
  match r {
    Safe => "Safe"
    Warning(msg) => "Warning(\{msg})"
    Unsafe(msg) => "Unsafe(\{msg})"
  }
}

///|
/// 构造一笔资金守恒的演示交易:
///   inputs 1_000_000 == outputs 999_000 + fee 1_000
/// 并绑定 chain_id=1、nonce=7(参与签名消息,签名后不可篡改)
fn demo_transaction() -> @protocol.TransactionSpec {
  @protocol.TransactionSpec::{
    version: 2,
    inputs: [
      @protocol.TxInputSpec::{
        txid: "prev-tx-0001",
        vout: 0,
        script_sig: "",
        amount_str: "1000000",
      },
    ],
    outputs: [
      @protocol.TxOutputSpec::{
        address: "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed",
        amount_str: "999000",
        script_pubkey: "",
        is_change: false,
      },
    ],
    locktime: 0,
    fee: @protocol.FeeSpec::{
      rate_str: "1",
      total_str: "1000",
      unit_desc: "wei",
    },
    txid: "demo-tx-0001",
    nonce: Some(7UL),
    chain_id: Some(1),
    sig_scheme: @protocol.SignatureScheme::EcdsaSecp256k1,
    signature_hex: None,
    public_key_hex: None,
  }
}

///|
/// 复制交易并篡改 chain_id(模拟跨链重放攻击者)
fn retarget_chain(
  tx : @protocol.TransactionSpec,
  new_chain_id : UInt,
) -> @protocol.TransactionSpec {
  @protocol.TransactionSpec::{
    version: tx.version,
    inputs: tx.inputs,
    outputs: tx.outputs,
    locktime: tx.locktime,
    fee: tx.fee,
    txid: tx.txid,
    nonce: tx.nonce,
    chain_id: Some(new_chain_id),
    sig_scheme: tx.sig_scheme,
    signature_hex: tx.signature_hex,
    public_key_hex: tx.public_key_hex,
  }
}

///|
fn main {
  println("═══ CryptoAssert examples ═══")

  // ── 1. ECDSA secp256k1:密钥生成 → 签名 → 验签 ──────────
  println("\n[1] ECDSA secp256k1 sign / verify")
  let seed : Bytes = b"cryptoassert-demo-seed-32bytes!!"
  let (priv_hex, pub_hex) = match @protocol.generate_key_pair(seed) {
    Some(pair) => pair
    None => {
      println("    key generation failed")
      return
    }
  }
  println("    public key: \{pub_hex}")
  let tx = demo_transaction()
  let signed_tx = match @protocol.sign_transaction(tx, priv_hex) {
    Some(t) => t
    None => {
      println("    signing failed")
      return
    }
  }
  println(
    "    signature valid: \{@protocol.verify_signed_transaction(signed_tx)}",
  )

  // 签名绑定 chain_id:篡改链 ID 后同一签名立即失效
  let cross_chain_replay = retarget_chain(signed_tx, 56)
  println(
    "    tampered chain_id still valid: \{@protocol.verify_signed_transaction(cross_chain_replay)}",
  )

  // ── 2. 防重放:真实 nonce / chain ID 校验 ────────────────
  println("\n[2] Replay protection (real nonce / chain ID checks)")
  // 合法交易:chain_id 匹配、nonce 与链上期望一致
  let ok = @protocol.verify_replay_protection(
    signed_tx,
    1, // expected_chain_id
    0, // min_locktime
    expected_nonce=Some(7UL),
  )
  println("    legitimate tx        → \{show_result(ok)}")
  // 重放攻击:账户 nonce 已推进到 8,重放 nonce=7 的历史交易被拒
  let replayed = @protocol.verify_replay_protection(
    signed_tx,
    1,
    0,
    expected_nonce=Some(8UL),
  )
  println("    replayed old nonce   → \{show_result(replayed)}")
  // 跨链重放:交易带 chain_id=1,提交到 chain 56 被拒
  let wrong_chain = @protocol.verify_replay_protection(signed_tx, 56, 0)
  println("    wrong chain          → \{show_result(wrong_chain)}")

  // ── 3. 跨链桥审计:多签阈值校验 ──────────────────────────
  println("\n[3] Bridge audit (multisig threshold verification)")
  // 7-of-9:满足 BFT 法定人数 ⌊2n/3⌋+1 = 7
  let safe_bridge = @protocol.audit_bridge_security(
    "0x1234567890abcdef1234567890abcdef12345678", 137, // target chain
     "1000", // min amount
     "100000000000", // max amount
     7, // min validators
     7, // multisig threshold
     9, // total validators
  )
  println("    7-of-9 (BFT quorum)  → \{show_result(safe_bridge)}")
  // 5-of-9:过半但低于 BFT 推荐线
  let warn_bridge = @protocol.audit_bridge_security(
    "0x1234567890abcdef1234567890abcdef12345678", 137, "1000", "100000000000", 7,
    5, 9,
  )
  println("    5-of-9 (below BFT)   → \{show_result(warn_bridge)}")
  // 4-of-9:不过半,少数合谋即可放行 —— 硬性拒绝
  let unsafe_bridge = @protocol.audit_bridge_security(
    "0x1234567890abcdef1234567890abcdef12345678", 137, "1000", "100000000000", 7,
    4, 9,
  )
  println("    4-of-9 (no majority) → \{show_result(unsafe_bridge)}")

  // ── 4. 资金守恒 + 端到端验证管道 ─────────────────────────
  println("\n[4] Fund conservation + full E2E pipeline")
  println(
    "    fund conservation    → \{@protocol.verify_fund_conservation(signed_tx)}",
  )
  let pipeline = @protocol.full_tx_validation_pipeline(
    signed_tx,
    1, // expected_chain_id
    0, // min_locktime
    "1", // amount_min
    "100000000000000000000", // amount_max
    "5", // fee_max_ratio (%)
    expected_nonce=Some(7UL),
  )
  println("    full pipeline        → \{show_result(pipeline)}")

  // ── 5. 地址格式断言(EIP-55 校验和) ─────────────────────
  println("\n[5] Address format assertion (EIP-55)")
  let verifier = @protocol.DefaultVerifier::new()
  try {
    let _ = @business.assert_address_format(
      verifier,
      "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed",
      @protocol.AddressType::EthEip55,
    )
    println("    checksummed address  → Valid")
  } catch {
    _ => println("    checksummed address  → rejected")
  }
  try {
    let _ = @business.assert_address_format(
      verifier,
      "0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed",
      @protocol.AddressType::EthEip55,
    )
    println("    corrupted address    → unexpectedly Valid")
  } catch {
    _ => println("    corrupted address    → rejected (checksum mismatch)")
  }
  println("\n═══ all examples finished ═══")
}