"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.UtxoSyncWorker = void 0;
const http = __importStar(require("http"));
const https = __importStar(require("https"));
const worker = __importStar(require("worker_threads"));
class UtxoSyncWorker {
    constructor() {
        this.parentPort = worker.parentPort;
        this.rpc = worker.workerData.rpc;
        this.stopping = false;
        this.isWorking = false;
    }
    async start() {
        this.parentPort.on('message', this.messageHandler.bind(this));
    }
    async stop() {
        this.stopping = true;
        while (this.isWorking) {
            await new Promise(r => setTimeout(r, 100));
        }
        process.exit(0);
    }
    messageHandler(msg) {
        switch (msg.message) {
            case 'shutdown':
                this.stop();
                return;
            default:
                this.fetchBlock(msg);
        }
    }
    async fetchBlock({ hash, height }) {
        if (this.stopping)
            return;
        this.isWorking = true;
        try {
            const rawBlock = await this.rpcGetRawBlock(hash);
            this.parentPort.postMessage({ message: 'sync', hash, height, rawBlock, threadId: worker.threadId });
        }
        catch (err) {
            this.parentPort.postMessage({
                message: 'sync', hash, height, notFound: true,
                error: err.message, threadId: worker.threadId
            });
        }
        finally {
            this.isWorking = false;
        }
    }
    rpcGetRawBlock(hash) {
        return new Promise((resolve, reject) => {
            const body = JSON.stringify({
                jsonrpc: '1.0',
                id: `worker-${worker.threadId}`,
                method: 'getblock',
                params: [hash, 0] // verbosity 0 = raw serialized hex
            });
            const isHttps = this.rpc.protocol === 'https';
            const options = {
                hostname: this.rpc.host,
                port: Number(this.rpc.port),
                method: 'POST',
                auth: `${this.rpc.username}:${this.rpc.password}`,
                headers: {
                    'Content-Type': 'application/json',
                    'Content-Length': Buffer.byteLength(body)
                }
            };
            const req = (isHttps ? https : http).request(options, (res) => {
                let data = '';
                res.on('data', (chunk) => data += chunk);
                res.on('end', () => {
                    try {
                        const result = JSON.parse(data);
                        if (result.error) {
                            reject(new Error(result.error.message || JSON.stringify(result.error)));
                        }
                        else {
                            resolve(result.result);
                        }
                    }
                    catch {
                        reject(new Error(`Failed to parse RPC response: ${data.substring(0, 200)}`));
                    }
                });
            });
            req.on('error', reject);
            req.setTimeout(30000, () => {
                req.destroy();
                reject(new Error('RPC request timeout'));
            });
            req.write(body);
            req.end();
        });
    }
}
exports.UtxoSyncWorker = UtxoSyncWorker;
// Worker thread entry point
worker.parentPort.once('message', async function (msg) {
    if (msg.message !== 'start') {
        throw new Error('Unknown startup message');
    }
    await new UtxoSyncWorker().start();
    return worker.parentPort.postMessage({ message: 'ready' });
});
//# sourceMappingURL=syncWorker.js.map