"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EthereumProofPointRegistry = exports.ETHEREUM_PROOF_TYPE = exports.PROOF_POINT_REGISTRY_VERSION = exports.ProofPointRegistryAbi = void 0;
var ethers_1 = require("ethers");
var ethereumProofPointEventType_1 = require("./ethereumProofPointEventType");
var ProofPointRegistry_v2_json_1 = __importDefault(require("../../build/ProofPointRegistry_v2.json"));
var ProofPointRegistry_v2_json_2 = __importDefault(require("../../build/ProofPointRegistry_v2.json"));
var ethereumAddress_1 = require("./ethereumAddress");
var ethereumTransactionHash_1 = require("./ethereumTransactionHash");
var proofPointId_1 = require("../proofPointId");
exports.ProofPointRegistryAbi = [
    undefined,
    ProofPointRegistry_v2_json_1.default,
    ProofPointRegistry_v2_json_2.default,
];
exports.PROOF_POINT_REGISTRY_VERSION = 2;
exports.ETHEREUM_PROOF_TYPE = "https://open.provenance.org/ontology/ptf/v2/ProvenanceProofType1";
// Javascript wrapper around the Proof Point Registry Ethereum contract.
var EthereumProofPointRegistry = /** @class */ (function () {
    /**
     * Creates an instance of Proof Point registry for interacting with a pre-existing deployment of the registry contracts.
     * @param rootAddress The Ethereum address of the deployed eternal storage contract.
     * @param address The Ethereum address of the current deployed logic contract.
     * @param provider An ethers.providers.JsonRpcProvider to use for interacting with the blockchain.
     */
    function EthereumProofPointRegistry(rootAddress, address, provider) {
        this._rootAddress = rootAddress;
        this._address = address;
        this._provider = provider;
        this._registry = new ethers_1.ethers.Contract(this._address.toString(), exports.ProofPointRegistryAbi[exports.PROOF_POINT_REGISTRY_VERSION].abi, provider);
    }
    /**
     * Determines whether the given proof point can be authenticated using this registry.
     * @param proofPoint The proof point to check.
     * @returns True if the given proof point can be authenticated using this registry.
     */
    EthereumProofPointRegistry.prototype.isSameRegistry = function (proofPoint) {
        return (proofPoint.proof.registryRoot.toLowerCase() ===
            this._rootAddress.toString().toLowerCase());
    };
    /**
     * Issues the given proof point in this registry from the given issuer. You must control the issuer account.
     * @param id The ID of the proof point to issue.
     * @param issuerAddress The account that is issuing the proof point.
     * @returns The Ethereum transaction hash of the issuing transaction.
     */
    EthereumProofPointRegistry.prototype.issue = function (id, issuerAddress) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this._issue(id, issuerAddress, function (c, d) {
                        return c.issue(d);
                    })];
            });
        });
    };
    /**
     * Commits the given proof point in this registry from the given issuer. You must control the issuer account.
     * @param id The ID of the proof point to commit.
     * @param issuerAddress The account that is committing the proof point.
     * @returns The Ethereum transaction hash of the committing transaction.
     */
    EthereumProofPointRegistry.prototype.commit = function (id, issuerAddress) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this._issue(id, issuerAddress, function (c, d) {
                        return c.commit(d);
                    })];
            });
        });
    };
    /**
     * Revokes the given proof point from this registry using the given issuer. You must control the issuer account.
     * The issuer must be the original issuer of the proof point.
     * @param id The ID of the proof point to revoke.
     * @param issuerAddress The account that is issuing the proof point.
     * @returns The Ethereum transaction hash of the revoking transaction.
     */
    EthereumProofPointRegistry.prototype.revoke = function (id, revokerAddress) {
        return __awaiter(this, void 0, void 0, function () {
            var proofPointIdBytes, signer, registryWithSigner, transactionReceipt;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        proofPointIdBytes = this._proofPointIdToBytes(id);
                        signer = this._provider.getSigner(revokerAddress.toString());
                        registryWithSigner = this._registry.connect(signer);
                        return [4 /*yield*/, registryWithSigner.revoke(proofPointIdBytes)];
                    case 1:
                        transactionReceipt = _a.sent();
                        return [2 /*return*/, ethereumTransactionHash_1.EthereumTransactionHash.parse(transactionReceipt.hash)];
                }
            });
        });
    };
    /**
     * Determines whether the identified proof point is authentic, meaning is has been
     * issued and not revoked by the given issuer, or has been committed by the given issuer.
     * @param id The ID of proof point to check.
     * @param issuerAddress The address of the expected issuer.
     * @returns True if the proof point is issued and not revoked, or committed by the given issuer.
     */
    EthereumProofPointRegistry.prototype.isAuthentic = function (id, issuerAddress) {
        return __awaiter(this, void 0, void 0, function () {
            var proofPointIdBytes;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        proofPointIdBytes = this._proofPointIdToBytes(id);
                        return [4 /*yield*/, this._registry.validate(issuerAddress.toString(), proofPointIdBytes)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Gets a list of all events related to the given Proof Point, identified by its ID.
     * @param proofPointId The ID of the Proof Point.
     * @returns A list of {@link EthereumProofPointEvent} describing the history of the Proof Point.
     */
    EthereumProofPointRegistry.prototype.getHistory = function (proofPointId) {
        return __awaiter(this, void 0, void 0, function () {
            var version, history;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._getVersion()];
                    case 1:
                        version = _a.sent();
                        return [4 /*yield*/, this._getHistory(version, this._registry.address, proofPointId)];
                    case 2:
                        history = _a.sent();
                        return [2 /*return*/, history.sort(function (a, b) { return a.blockNumber - b.blockNumber; })];
                }
            });
        });
    };
    /**
     * Get a list of the IDs of all Proof Points ever issued or committed
     * to this registry.
     */
    EthereumProofPointRegistry.prototype.getAll = function () {
        return __awaiter(this, void 0, void 0, function () {
            var filter, publishEvents, nonUniqueIds, uniqueIds;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        filter = {
                            address: this._registry.address,
                            topics: [ethers_1.ethers.utils.id("Published(bytes)")],
                            fromBlock: 0,
                            toBlock: "latest",
                        };
                        return [4 /*yield*/, this._provider.getLogs(filter)];
                    case 1:
                        publishEvents = _a.sent();
                        nonUniqueIds = publishEvents.map(function (ev) {
                            return _this._logDataToProofPointId(ev.data);
                        });
                        uniqueIds = nonUniqueIds.filter(function (val, idx, arr) {
                            return arr.findIndex(function (id) { return id.toString() === val.toString(); }) === idx;
                        });
                        return [2 /*return*/, uniqueIds];
                }
            });
        });
    };
    EthereumProofPointRegistry.prototype._logDataToProofPointId = function (data) {
        // For some reason there are 64 bytes before the actual log data, plus the 0x
        // and the log data is zero right-padded to a multiple of 32 bytes
        var idStrHex = data.substr(130, 92);
        var idStr = ethers_1.ethers.utils.toUtf8String("0x" + idStrHex);
        return proofPointId_1.ProofPointId.parse(idStr);
    };
    EthereumProofPointRegistry.prototype._getVersion = function () {
        return __awaiter(this, void 0, void 0, function () {
            var version, e_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this._registry.getVersion()];
                    case 1:
                        version = _a.sent();
                        return [2 /*return*/, version];
                    case 2:
                        e_1 = _a.sent();
                        // version 1 does not have the getVersion method.
                        return [2 /*return*/, 1];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    EthereumProofPointRegistry.prototype._topicToEventType = function (topic) {
        if (topic === ethers_1.ethers.utils.id("Issued(address,bytes)"))
            return ethereumProofPointEventType_1.EthereumProofPointEventType.Issued;
        if (topic === ethers_1.ethers.utils.id("Committed(address,bytes)"))
            return ethereumProofPointEventType_1.EthereumProofPointEventType.Committed;
        if (topic === ethers_1.ethers.utils.id("Revoked(address,bytes)"))
            return ethereumProofPointEventType_1.EthereumProofPointEventType.Revoked;
        throw new Error("Invalid Proof Point event type topic: " + topic);
    };
    EthereumProofPointRegistry.prototype._getHistory = function (version, logicContractAddress, proofPointId) {
        return __awaiter(this, void 0, void 0, function () {
            var registry, allEvents, _a, _b, _c, _d, _e, _f, _g, _h, _j, priorAddress, priorEvents;
            return __generator(this, function (_k) {
                switch (_k.label) {
                    case 0:
                        registry = new ethers_1.ethers.Contract(logicContractAddress, exports.ProofPointRegistryAbi[version].abi, this._provider);
                        allEvents = [];
                        _b = (_a = allEvents.push).apply;
                        _c = [allEvents];
                        return [4 /*yield*/, this._getEventsByFilter(registry, registry.filters.Issued.bind(registry.filters), proofPointId)];
                    case 1:
                        _b.apply(_a, _c.concat([(_k.sent())]));
                        _e = (_d = allEvents.push).apply;
                        _f = [allEvents];
                        return [4 /*yield*/, this._getEventsByFilter(registry, registry.filters.Committed.bind(registry.filters), proofPointId)];
                    case 2:
                        _e.apply(_d, _f.concat([(_k.sent())]));
                        _h = (_g = allEvents.push).apply;
                        _j = [allEvents];
                        return [4 /*yield*/, this._getEventsByFilter(registry, registry.filters.Revoked.bind(registry.filters), proofPointId)];
                    case 3:
                        _h.apply(_g, _j.concat([(_k.sent())]));
                        if (version === 1) {
                            return [2 /*return*/, allEvents];
                        }
                        return [4 /*yield*/, registry.getPrevious()];
                    case 4:
                        priorAddress = _k.sent();
                        return [4 /*yield*/, this._getHistory(version - 1, priorAddress, proofPointId)];
                    case 5:
                        priorEvents = _k.sent();
                        allEvents.push.apply(allEvents, priorEvents);
                        return [2 /*return*/, allEvents];
                }
            });
        });
    };
    EthereumProofPointRegistry.prototype._getEventsByFilter = function (registry, filterFactory, proofPointId) {
        return __awaiter(this, void 0, void 0, function () {
            var issuerFilter, filter, eventsRaw;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        issuerFilter = null;
                        filter = filterFactory(issuerFilter, this._proofPointIdToBytes(proofPointId));
                        return [4 /*yield*/, registry.queryFilter(filter)];
                    case 1:
                        eventsRaw = _a.sent();
                        return [2 /*return*/, eventsRaw.map(function (ev) {
                                return {
                                    blockNumber: ev.blockNumber,
                                    type: _this._topicToEventType(ev.topics[0]),
                                    issuer: ethereumAddress_1.EthereumAddress.parse(ethers_1.ethers.utils.hexStripZeros(ev.topics[1])),
                                    proofPointId: proofPointId,
                                    transactionHash: ethereumTransactionHash_1.EthereumTransactionHash.parse(ev.transactionHash),
                                };
                            })];
                }
            });
        });
    };
    EthereumProofPointRegistry.prototype._proofPointIdToBytes = function (id) {
        var idBytes = ethers_1.ethers.utils.toUtf8Bytes(id.toString());
        var idBytesHex = ethers_1.ethers.utils.hexlify(idBytes);
        return idBytesHex;
    };
    EthereumProofPointRegistry.prototype._issue = function (id, issuerAddress, issueFunction) {
        return __awaiter(this, void 0, void 0, function () {
            var proofPointIdBytes, signer, registryWithSigner, transactionReceipt;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        proofPointIdBytes = this._proofPointIdToBytes(id);
                        signer = this._provider.getSigner(issuerAddress.toString());
                        registryWithSigner = this._registry.connect(signer);
                        return [4 /*yield*/, issueFunction(registryWithSigner, proofPointIdBytes)];
                    case 1:
                        transactionReceipt = _a.sent();
                        return [2 /*return*/, ethereumTransactionHash_1.EthereumTransactionHash.parse(transactionReceipt.hash)];
                }
            });
        });
    };
    return EthereumProofPointRegistry;
}());
exports.EthereumProofPointRegistry = EthereumProofPointRegistry;
