← Back to Research Index View Raw Source

sovereign-cosigner.py

# Copyright © Albert Lane. All Rights Reserved.
# Proprietary and Confidential — Albert Lane Proprietary Software License v100.0
# Sovereign Aegis Protocol — Lane-VM 2-of-2 Sovereign Binding (ECDSA secp256k1, EIP-191)
# Provenance: SEC Ref 17684-273-411-436 | Service: albertlane-cosigner

from __future__ import annotations

import hashlib
import json
import re
from typing import Any, Dict, List, Optional, Tuple

# ---------------------------------------------------------------------------
# secp256k1 Curve Constants (SEC2)
# ---------------------------------------------------------------------------
SECP256K1_P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
SECP256K1_N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
SECP256K1_A = 0
SECP256K1_B = 7
SECP256K1_GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798
SECP256K1_GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8
SECP256K1_G = (SECP256K1_GX, SECP256K1_GY)

ROBOT_VALIDATOR_MODEL = "@cf/meta/llama-3.3-70b-instruct-fp8-fast"

# ---------------------------------------------------------------------------
# Pure-Python Keccak-256 (Pre-NIST padding 0x01, Ethereum / EIP-191 standard)
# ---------------------------------------------------------------------------
_KECCAK_RC = [
    0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000,
    0x000000000000808B, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009,
    0x000000000000008A, 0x0000000000000088, 0x0000000080008009, 0x000000008000000A,
    0x000000008000808B, 0x800000000000008B, 0x8000000000008089, 0x8000000000008003,
    0x8000000000008002, 0x8000000000000080, 0x000000000000800A, 0x800000008000000A,
    0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008,
]

_KECCAK_ROT = [
    [0, 36, 3, 41, 18],
    [1, 44, 10, 45, 2],
    [62, 6, 43, 15, 61],
    [28, 55, 25, 21, 56],
    [27, 20, 39, 8, 14],
]

_M64 = 0xFFFFFFFFFFFFFFFF


def _rot64(x: int, n: int) -> int:
    return ((x << n) | (x >> (64 - n))) & _M64


def _keccak_f1600(state: List[int]) -> None:
    for rc in _KECCAK_RC:
        c = [state[x] ^ state[x + 5] ^ state[x + 10] ^ state[x + 15] ^ state[x + 20] for x in range(5)]
        d = [c[(x - 1) % 5] ^ _rot64(c[(x + 1) % 5], 1) for x in range(5)]
        for x in range(5):
            for y in range(5):
                state[x + 5 * y] ^= d[x]
        b = [0] * 25
        for x in range(5):
            for y in range(5):
                b[y + 5 * ((2 * x + 3 * y) % 5)] = _rot64(state[x + 5 * y], _KECCAK_ROT[x][y])
        for x in range(5):
            for y in range(5):
                state[x + 5 * y] = b[x + 5 * y] ^ ((~b[((x + 1) % 5) + 5 * y]) & b[((x + 2) % 5) + 5 * y])
        state[0] ^= rc


def keccak256(data: bytes) -> bytes:
    """Compute Ethereum-standard Keccak-256 (rate=1088 bits / 136 bytes, domain=0x01)."""
    rate = 136
    padded = bytearray(data)
    padded.append(0x01)
    while len(padded) % rate != 0:
        padded.append(0x00)
    padded[-1] ^= 0x80

    state = [0] * 25
    for off in range(0, len(padded), rate):
        block = padded[off : off + rate]
        for i in range(rate // 8):
            state[i] ^= int.from_bytes(block[i * 8 : (i + 1) * 8], "little")
        _keccak_f1600(state)

    out = b"".join(state[i].to_bytes(8, "little") for i in range(4))
    return out[:32]


# ---------------------------------------------------------------------------
# Pure-Python secp256k1 Elliptic Curve Arithmetic (Point Add, Mul, Recover)
# ---------------------------------------------------------------------------
def _point_add(p1: Optional[Tuple[int, int]], p2: Optional[Tuple[int, int]]) -> Optional[Tuple[int, int]]:
    if p1 is None:
        return p2
    if p2 is None:
        return p1
    x1, y1 = p1
    x2, y2 = p2
    if x1 == x2:
        if (y1 + y2) % SECP256K1_P == 0:
            return None
        lam = (3 * x1 * x1) * pow(2 * y1, -1, SECP256K1_P) % SECP256K1_P
    else:
        lam = (y2 - y1) * pow((x2 - x1) % SECP256K1_P, -1, SECP256K1_P) % SECP256K1_P
    x3 = (lam * lam - x1 - x2) % SECP256K1_P
    y3 = (lam * (x1 - x3) - y1) % SECP256K1_P
    return (x3, y3)


def _point_mul(k: int, point: Optional[Tuple[int, int]] = SECP256K1_G) -> Optional[Tuple[int, int]]:
    k %= SECP256K1_N
    res: Optional[Tuple[int, int]] = None
    addend = point
    while k > 0:
        if k & 1:
            res = _point_add(res, addend)
        addend = _point_add(addend, addend)
        k >>= 1
    return res


def _is_valid_eth_address(addr: str) -> bool:
    return bool(isinstance(addr, str) and re.fullmatch(r"0x[0-9a-fA-F]{40}", addr.strip()))


def to_checksum_address(addr: str) -> str:
    if not _is_valid_eth_address(addr):
        raise ValueError(f"Invalid secp256k1/EIP-55 address: {addr!r}")
    lower = addr.strip()[2:].lower()
    h = keccak256(lower.encode("ascii")).hex()
    return "0x" + "".join(
        ch.upper() if int(h[i], 16) >= 8 else ch for i, ch in enumerate(lower)
    )


def pubkey_point_to_address(point: Tuple[int, int]) -> str:
    x, y = point
    uncompressed_xy = x.to_bytes(32, "big") + y.to_bytes(32, "big")
    addr_hex = keccak256(uncompressed_xy)[-20:].hex()
    return to_checksum_address("0x" + addr_hex)


def private_key_to_address(priv_hex: str) -> str:
    k = int(priv_hex.strip().removeprefix("0x"), 16)
    if not (1 <= k < SECP256K1_N):
        raise ValueError("Private key out of secp256k1 scalar range.")
    pt = _point_mul(k, SECP256K1_G)
    if pt is None:
        raise ValueError("Invalid private key point.")
    return pubkey_point_to_address(pt)


# ---------------------------------------------------------------------------
# EIP-191 Personal Sign & Deterministic RFC-6979 Signing / Recovery
# ---------------------------------------------------------------------------
def eip191_hash(message: str | bytes) -> bytes:
    msg_bytes = message.encode("utf-8") if isinstance(message, str) else bytes(message)
    prefix = f"\x19Ethereum Signed Message:\n{len(msg_bytes)}".encode("ascii")
    return keccak256(prefix + msg_bytes)


def _rfc6979_k(priv_int: int, z_bytes: bytes) -> int:
    """RFC 6979 deterministic nonce generation with HMAC-SHA256 for secp256k1."""
    import hmac

    x_bytes = priv_int.to_bytes(32, "big")
    v = b"\x01" * 32
    k = b"\x00" * 32
    k = hmac.new(k, v + b"\x00" + x_bytes + z_bytes, hashlib.sha256).digest()
    v = hmac.new(k, v, hashlib.sha256).digest()
    k = hmac.new(k, v + b"\x01" + x_bytes + z_bytes, hashlib.sha256).digest()
    v = hmac.new(k, v, hashlib.sha256).digest()
    while True:
        v = hmac.new(k, v, hashlib.sha256).digest()
        cand = int.from_bytes(v, "big")
        if 1 <= cand < SECP256K1_N:
            return cand
        k = hmac.new(k, v + b"\x00", hashlib.sha256).digest()
        v = hmac.new(k, v, hashlib.sha256).digest()


def sign_eip191(message: str | bytes, priv_hex: str) -> str:
    """Sign message using EIP-191 + secp256k1 low-s deterministic ECDSA. Returns 65-byte 0x hex."""
    priv_int = int(priv_hex.strip().removeprefix("0x"), 16)
    if not (1 <= priv_int < SECP256K1_N):
        raise ValueError("Private key out of range.")
    digest = eip191_hash(message)
    z = int.from_bytes(digest, "big")
    k = _rfc6979_k(priv_int, digest)
    pt = _point_mul(k, SECP256K1_G)
    if pt is None:
        raise ValueError("Nonce produced point at infinity.")
    r = pt[0] % SECP256K1_N
    if r == 0:
        raise ValueError("r == 0")
    s = (pow(k, -1, SECP256K1_N) * (z + r * priv_int)) % SECP256K1_N
    if s == 0:
        raise ValueError("s == 0")
    rec_id = pt[1] & 1
    if s > SECP256K1_N // 2:
        s = SECP256K1_N - s
        rec_id ^= 1
    v = 27 + rec_id
    sig = r.to_bytes(32, "big") + s.to_bytes(32, "big") + bytes([v])
    return "0x" + sig.hex()


def recover_eip191(message: str | bytes, signature_hex: str) -> str:
    """Recover checksummed secp256k1 address from a 65-byte EIP-191 signature (0x + 130 hex)."""
    if not isinstance(signature_hex, str):
        raise ValueError("Signature must be a hex string.")
    clean = signature_hex.strip().removeprefix("0x")
    if len(clean) != 130 or not re.fullmatch(r"[0-9a-fA-F]{130}", clean):
        raise ValueError("Signature must be 65 bytes (130 hex characters: r[32] || s[32] || v[1]).")
    raw = bytes.fromhex(clean)
    r = int.from_bytes(raw[:32], "big")
    s = int.from_bytes(raw[32:64], "big")
    v_raw = raw[64]

    if v_raw in (0, 1):
        rec_id = v_raw
    elif v_raw in (27, 28):
        rec_id = v_raw - 27
    elif v_raw >= 35:
        rec_id = (v_raw - 35) % 2
    else:
        raise ValueError(f"Unsupported recovery id v={v_raw}.")

    if not (1 <= r < SECP256K1_N) or not (1 <= s < SECP256K1_N):
        raise ValueError("Signature (r, s) out of secp256k1 order.")
    # Enforce canonical low-s to prevent ECDSA malleability
    if s > SECP256K1_N // 2:
        raise ValueError("High-s signature rejected (EIP-2 low-s malleability check).")

    # secp256k1: p = 3 (mod 4), so sqrt(a) = a^((p+1)//4) mod p
    x = r
    if x >= SECP256K1_P:
        raise ValueError("x >= field prime P.")
    alpha = (pow(x, 3, SECP256K1_P) + SECP256K1_B) % SECP256K1_P
    beta = pow(alpha, (SECP256K1_P + 1) // 4, SECP256K1_P)
    if (beta * beta) % SECP256K1_P != alpha:
        raise ValueError("Signature r does not lie on secp256k1 curve.")
    y = beta if (beta & 1) == rec_id else (SECP256K1_P - beta)
    R = (x, y)

    digest = eip191_hash(message)
    z = int.from_bytes(digest, "big")
    r_inv = pow(r, -1, SECP256K1_N)
    u1 = (-z * r_inv) % SECP256K1_N
    u2 = (s * r_inv) % SECP256K1_N

    Q = _point_add(_point_mul(u1, SECP256K1_G), _point_mul(u2, R))
    if Q is None:
        raise ValueError("Recovered point at infinity.")
    return pubkey_point_to_address(Q)


# ---------------------------------------------------------------------------
# Lane-VM 2-of-2 Canonical Packet & Key Readiness Helpers
# ---------------------------------------------------------------------------
def build_worm_cosign_digest(record: Dict[str, Any]) -> str:
    """
    Deterministic canonical SHA-256 digest for a WORM ledger entry that both
    Albert (human owner) and Robot (machine owner) sign over using EIP-191.
    """
    canonical_packet = {
        "protocol": "LANE-VM-2-OF-2-SOVEREIGN-BINDING",
        "record_key": record["record_key"],
        "channel": record["channel"],
        "payload_sha256": record["payload_sha256"],
        "prev_chain_head": record["prev_chain_head"],
        "chain_head": record["chain_head"],
    }
    encoded = json.dumps(canonical_packet, sort_keys=True, separators=(",", ":")).encode("utf-8")
    return "0x" + hashlib.sha256(encoded).hexdigest()


def get_cosigner_key_status(env: Any) -> Dict[str, Any]:
    """
    Evaluate whether Albert's signing address and Robot's signing address/key are set.
    Per Lane-VM 2-of-2 spec: co-signing stays OFF (503) until both are configured.
    """
    albert_addr = str(getattr(env, "ALBERT_SIGNING_ADDRESS", "") or "").strip()
    robot_addr = str(getattr(env, "ROBOT_SIGNING_ADDRESS", "") or "").strip()
    robot_key_set = bool(str(getattr(env, "ROBOT_SIGNING_KEY", "") or "").strip())

    if not robot_addr and robot_key_set:
        try:
            robot_addr = private_key_to_address(str(getattr(env, "ROBOT_SIGNING_KEY")))
        except Exception:
            robot_addr = ""

    missing: List[str] = []
    if not _is_valid_eth_address(albert_addr):
        missing.append("ALBERT_SIGNING_ADDRESS")
    if not _is_valid_eth_address(robot_addr):
        missing.append("ROBOT_SIGNING_ADDRESS")

    cosigner_bound = getattr(env, "COSIGNER_SERVICE", None) is not None
    ai_bound = getattr(env, "AI", None) is not None
    cosigner_d1_bound = getattr(env, "COSIGNER_D1", None) is not None

    ready = len(missing) == 0
    return {
        "protocol": "LANE-VM-2-OF-2-SOVEREIGN-BINDING",
        "curve": "secp256k1",
        "scheme": "EIP-191",
        "signing_enabled": ready,
        "http_signing_status": 200 if ready else 503,
        "albert_signing_address": to_checksum_address(albert_addr) if _is_valid_eth_address(albert_addr) else None,
        "robot_signing_address": to_checksum_address(robot_addr) if _is_valid_eth_address(robot_addr) else None,
        "robot_signing_key_set": robot_key_set,
        "missing": missing,
        "bindings": {
            "cosigner_service": "albertlane-cosigner" if cosigner_bound else "unattached (local EIP-191 verifier active)",
            "cosigner_d1": "albertlane-cosigner-db" if cosigner_d1_bound else "fallback_to_IMMUTABLE_AUDIT_D1",
            "workers_ai_validator": ROBOT_VALIDATOR_MODEL if ai_bound else "unattached",
        },
        "veto_policy": "Robot validator (Llama 3.3 70B) veto is immutable; Albert cannot override a veto.",
    }


def verify_dual_key_attestation(
    canonical_digest: str,
    albert_signature: str,
    robot_signature: str,
    expected_albert_address: str,
    expected_robot_address: str,
    robot_verdict: str = "APPROVE",
) -> Dict[str, Any]:
    """
    Verify 2-of-2 sovereign binding over canonical_digest:
      1. Robot validator verdict MUST be APPROVE (VETO cannot be overridden).
      2. Albert's EIP-191 signature MUST recover to expected_albert_address.
      3. Robot's EIP-191 signature MUST recover to expected_robot_address.
    """
    verdict = str(robot_verdict or "").strip().upper()
    if verdict == "VETO":
        return {
            "verified": False,
            "outcome": "VETOED_BY_ROBOT",
            "http_status": 403,
            "reason": "Robot validator issued VETO; protocol forbids Albert from overriding a Robot veto.",
            "canonical_digest": canonical_digest,
            "albert_recovered": None,
            "robot_recovered": None,
        }
    if verdict != "APPROVE":
        return {
            "verified": False,
            "outcome": "INVALID_VALIDATOR_VERDICT",
            "http_status": 400,
            "reason": f"Robot validator verdict must be APPROVE or VETO, got {robot_verdict!r}.",
            "canonical_digest": canonical_digest,
            "albert_recovered": None,
            "robot_recovered": None,
        }

    exp_albert = to_checksum_address(expected_albert_address)
    exp_robot = to_checksum_address(expected_robot_address)
    if exp_albert == exp_robot:
        return {
            "verified": False,
            "outcome": "DUPLICATE_SIGNER_ADDRESS",
            "http_status": 400,
            "reason": "2-of-2 requires distinct human (Albert) and machine (Robot) signing addresses.",
            "canonical_digest": canonical_digest,
            "albert_recovered": None,
            "robot_recovered": None,
        }

    try:
        rec_albert = recover_eip191(canonical_digest, albert_signature)
    except Exception as exc:
        return {
            "verified": False,
            "outcome": "INVALID_ALBERT_SIGNATURE",
            "http_status": 403,
            "reason": f"Albert signature recovery failed: {exc}",
            "canonical_digest": canonical_digest,
            "albert_recovered": None,
            "robot_recovered": None,
        }

    try:
        rec_robot = recover_eip191(canonical_digest, robot_signature)
    except Exception as exc:
        return {
            "verified": False,
            "outcome": "INVALID_ROBOT_SIGNATURE",
            "http_status": 403,
            "reason": f"Robot signature recovery failed: {exc}",
            "canonical_digest": canonical_digest,
            "albert_recovered": rec_albert,
            "robot_recovered": None,
        }

    if rec_albert != exp_albert or rec_robot != exp_robot:
        mismatches = []
        if rec_albert != exp_albert:
            mismatches.append(f"Albert recovered {rec_albert} != expected {exp_albert}")
        if rec_robot != exp_robot:
            mismatches.append(f"Robot recovered {rec_robot} != expected {exp_robot}")
        return {
            "verified": False,
            "outcome": "SIGNER_ADDRESS_MISMATCH",
            "http_status": 403,
            "reason": "; ".join(mismatches),
            "canonical_digest": canonical_digest,
            "albert_recovered": rec_albert,
            "robot_recovered": rec_robot,
        }

    return {
        "verified": True,
        "outcome": "VERIFIED_2_OF_2",
        "http_status": 200,
        "reason": "Both Albert (human owner) and Robot (machine owner) EIP-191 secp256k1 signatures verified.",
        "canonical_digest": canonical_digest,
        "albert_recovered": rec_albert,
        "robot_recovered": rec_robot,
    }