"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.ProofPointRegistryAbi = exports.PROOF_POINT_REGISTRY_VERSION = exports.ProofPointRegistry = void 0;
var ethers_1 = require("ethers");
var canonicalizeJson = require("canonicalize");
var localISOdt = require("local-iso-dt");
var ProofPointRegistry_v2_json_1 = __importDefault(require("../build/ProofPointRegistry_v2.json"));
var ProofPointRegistry_v2_json_2 = __importDefault(require("../build/ProofPointRegistry_v2.json"));
var storage_1 = require("./storage");
var proofPointStatus_1 = require("./proofPointStatus");
var proofPointEventType_1 = require("./proofPointEventType");
var proofPointEvent_1 = require("./proofPointEvent");
var httpClient_1 = require("./httpClient");
var ProofPointRegistryAbi = [
    undefined,
    ProofPointRegistry_v2_json_1.default,
    ProofPointRegistry_v2_json_2.default,
];
exports.ProofPointRegistryAbi = ProofPointRegistryAbi;
var PROOF_POINT_REGISTRY_VERSION = 2;
exports.PROOF_POINT_REGISTRY_VERSION = PROOF_POINT_REGISTRY_VERSION;
var PROOF_TYPE = "https://open.provenance.org/ontology/ptf/v2/ProvenanceProofType1";
var ProofPointRegistry = /** @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.
     * @param storage a {@link StorageProvider} to use for storing/retrieving off-chain data or null to use the default implementation.
     * @param httpClient a {@link HttpClient} to use for fetching DID documents in order to support did:web issuers or null to use the default implementation.
     */
    function ProofPointRegistry(rootAddress, address, provider, storage, httpClient) {
        if (storage === void 0) { storage = null; }
        if (httpClient === void 0) { httpClient = null; }
        this._rootAddress = rootAddress;
        this._address = address;
        this._provider = provider;
        this._storage = storage;
        if (storage === null || typeof storage === "undefined") {
            // eslint-disable-next-line no-param-reassign
            this._storage = new storage_1.IpfsStorageProvider({
                host: "ipfs-cluster.provenance.org",
                port: 443,
                protocol: "https",
            });
        }
        if (httpClient === null) {
            this._httpClient = new httpClient_1.RealHttpClient();
        }
        else {
            this._httpClient = httpClient;
        }
        this._registry = new ethers_1.ethers.Contract(this._address.toString(), ProofPointRegistryAbi[PROOF_POINT_REGISTRY_VERSION].abi, provider);
    }
    /**
     * Issue a new Proof Point
     * @param type A URI string identifying the type of Proof Point to issue. This may be one of the values defined in the Provenance ontology.
     * @param issuer A string identifying the Ethereum address from which to issue the Proof Point. This may be either an Ethereum address or a did:web URI. It must represent an account that you control and must be sufficiently funded to pay for the issuance transaction.
     * @param content A javascript object representing the type specific content of the payload. The shape of the data should conform to the specification of the @param type parameter.
     * @param [validFromDate] Optional date from which the issued Proof Point will be valid. If null then there is no earliest date at which the Proof Point is valid.
     * @param [validUntilDate] Optional date until which the issued Proof Point will be valid. If null then there is no latest date at which the Proof Point is valid.
     * @returns A ProofPointIssueResult describing the result of the action.
     */
    ProofPointRegistry.prototype.issue = function (type, issuer, content, validFromDate, validUntilDate) {
        if (validFromDate === void 0) { validFromDate = null; }
        if (validUntilDate === void 0) { validUntilDate = null; }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this._issue(type, issuer, content, function (c, d) { return c.issue(d); }, validFromDate, validUntilDate)];
            });
        });
    };
    /**
     * Commit a new Proof Point
     * @param type A URI string identifying the type of Proof Point to issue. This may be one of the values defined in the Provenance ontology.
     * @param issuer A string identifying the Ethereum address from which to commit the Proof Point. This may be either an Ethereum address or a did:web URI. It must represent an account that you control and must be sufficiently funded to pay for the issuance transaction.
     * @param content A javascript object representing the type specific content of the payload. The shape of the data should conform to the specification of the @param type parameter.
     * @param [validFromDate] Optional date from which the issued Proof Point will be valid. If null then there is no earliest date at which the Proof Point is valid.
     * @param [validUntilDate] Optional date until which the issued Proof Point will be valid. If null then there is no latest date at which the Proof Point is valid.
     * @returns A ProofPointIssueResult describing the result of the action.
     */
    ProofPointRegistry.prototype.commit = function (type, issuerAddress, content, validFromDate, validUntilDate) {
        if (validFromDate === void 0) { validFromDate = null; }
        if (validUntilDate === void 0) { validUntilDate = null; }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this._issue(type, issuerAddress, content, function (c, d) { return c.commit(d); }, validFromDate, validUntilDate)];
            });
        });
    };
    /**
     * Revoke a Proof Point identified by it's ID. You must control the account that originally issued the Proof Point. The account must be sufficiently funded to execute the revoke transaction.
     * @param proofPointId The ID of the Proof Point to revoke. This is the value returned in the @param proofPointId field of the {@link ProofPointIssueResult} when the Proof Point was issued.
     */
    ProofPointRegistry.prototype.revokeById = function (proofPointId) {
        return __awaiter(this, void 0, void 0, function () {
            var storedData, proofPointObject;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._storage.get(proofPointId.toString())];
                    case 1:
                        storedData = _a.sent();
                        proofPointObject = JSON.parse(storedData.data);
                        return [4 /*yield*/, this.revoke(proofPointObject)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Revoke a Proof Point identified by its full data. You must control the account that originally issued the Proof Point. The account must be sufficiently funded to execute the revoke transaction.
     * @param proofPointObject The full Proof Point data as returned in the @param proofPointObject parameter of the {@link ProofPointIssueResult} when the Proof Point was issued.
     */
    ProofPointRegistry.prototype.revoke = function (proofPointObject) {
        return __awaiter(this, void 0, void 0, function () {
            var issuerAddress, id, proofPointIdBytes, signer, registryWithSigner;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (proofPointObject.proof.type !== PROOF_TYPE) {
                            throw new Error("Unsupported proof type");
                        }
                        if (!this.isSameRegistry(proofPointObject)) {
                            throw new Error("Registry mismatch");
                        }
                        return [4 /*yield*/, this._resolveIssuerToEthereumAddress(proofPointObject.issuer)];
                    case 1:
                        issuerAddress = _a.sent();
                        if (issuerAddress === null) {
                            throw new Error("Cannot resolve issuer: " + proofPointObject.issuer);
                        }
                        return [4 /*yield*/, this._canonicalizeAndStoreObject(proofPointObject)];
                    case 2:
                        id = (_a.sent()).id;
                        proofPointIdBytes = this.proofPointIdToBytes(id);
                        signer = this._provider.getSigner(issuerAddress.toString());
                        registryWithSigner = this._registry.connect(signer);
                        return [4 /*yield*/, registryWithSigner.revoke(proofPointIdBytes)];
                    case 3:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Validate a Proof Point identified by its ID. This does not involve a blockchain transaction.
     * @param proofPointId The ID of the Proof Point to revoke.
     * @returns true if the Proof Point passes all validation checks, otherwise false.
     */
    ProofPointRegistry.prototype.validateById = function (proofPointId) {
        return __awaiter(this, void 0, void 0, function () {
            var storedData, proofPointObject;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._storage.get(proofPointId.toString())];
                    case 1:
                        storedData = _a.sent();
                        proofPointObject = JSON.parse(storedData.data);
                        return [2 /*return*/, this.validate(proofPointObject)];
                }
            });
        });
    };
    /**
     * Validate a Proof Point identified by its full data. This does not involve a blockchain transaction.
     * @param proofPointObject The full Proof Point data as returned in the @param proofPointObject parameter of the {@link ProofPointIssueResult} when the Proof Point was issued.
     * @returns a {@link ProofPointValidateResult} representing the validity of the Proof Point.
     */
    ProofPointRegistry.prototype.validate = function (proofPointObject) {
        return __awaiter(this, void 0, void 0, function () {
            var validFromDate, validUntilDate, issuerAddress, id, proofPointIdBytes, isValid;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (proofPointObject.proof.type !== PROOF_TYPE) {
                            return [2 /*return*/, {
                                    isValid: false,
                                    statusCode: proofPointStatus_1.ProofPointStatus.BadlyFormed,
                                    statusMessage: "The Proof Point uses an unsupported proof type.",
                                }];
                        }
                        if (typeof proofPointObject.validFrom !== "undefined") {
                            validFromDate = Date.parse(proofPointObject.validFrom);
                            if (validFromDate > Date.now()) {
                                return [2 /*return*/, {
                                        isValid: false,
                                        statusCode: proofPointStatus_1.ProofPointStatus.Pending,
                                        statusMessage: "The Proof Point will become valid at a later date.",
                                    }];
                            }
                        }
                        if (typeof proofPointObject.validUntil !== "undefined") {
                            validUntilDate = Date.parse(proofPointObject.validUntil);
                            if (validUntilDate < Date.now()) {
                                return [2 /*return*/, {
                                        isValid: false,
                                        statusCode: proofPointStatus_1.ProofPointStatus.Expired,
                                        statusMessage: "The valid-until date of the Proof Point has passed.",
                                    }];
                            }
                        }
                        if (!this.isSameRegistry(proofPointObject)) {
                            return [2 /*return*/, {
                                    isValid: false,
                                    statusCode: proofPointStatus_1.ProofPointStatus.NonTrustedRegistry,
                                    statusMessage: "The Proof Point is issued using a registry that is not trusted in this context.",
                                }];
                        }
                        return [4 /*yield*/, this._resolveIssuerToEthereumAddress(proofPointObject.issuer)];
                    case 1:
                        issuerAddress = _a.sent();
                        if (issuerAddress === null) {
                            return [2 /*return*/, {
                                    isValid: false,
                                    statusCode: proofPointStatus_1.ProofPointStatus.UnknownIssuer,
                                    statusMessage: "The issuer '" + proofPointObject.issuer + "' could not be resolved to an Ethereum address.",
                                }];
                        }
                        return [4 /*yield*/, this._canonicalizeAndStoreObject(proofPointObject)];
                    case 2:
                        id = (_a.sent()).id;
                        proofPointIdBytes = this.proofPointIdToBytes(id);
                        return [4 /*yield*/, this._registry.validate(issuerAddress.toString(), proofPointIdBytes)];
                    case 3:
                        isValid = _a.sent();
                        if (isValid) {
                            return [2 /*return*/, {
                                    isValid: true,
                                    statusCode: proofPointStatus_1.ProofPointStatus.Valid,
                                    statusMessage: null,
                                }];
                        }
                        else {
                            return [2 /*return*/, {
                                    isValid: false,
                                    statusCode: proofPointStatus_1.ProofPointStatus.NotFound,
                                    statusMessage: "The Proof Point has been revoked or was never issued.",
                                }];
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Fetch the Proof Point document identified by its ID.
     * @param proofPointId The ID of the Proof Point document to fetch.
     */
    ProofPointRegistry.prototype.getById = function (proofPointId) {
        return __awaiter(this, void 0, void 0, function () {
            var storedData, proofPointObject;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._storage.get(proofPointId.toString())];
                    case 1:
                        storedData = _a.sent();
                        proofPointObject = JSON.parse(storedData.data);
                        return [2 /*return*/, proofPointObject];
                }
            });
        });
    };
    /**
     * Get a list of the IDs of all Proof Points ever issued or committed
     * to this registry.
     */
    ProofPointRegistry.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];
                }
            });
        });
    };
    /**
     * 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 ProofPointEvent} describing the history of the Proof Point.
     */
    ProofPointRegistry.prototype.getHistoryById = 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; })];
                }
            });
        });
    };
    ProofPointRegistry.prototype.proofPointIdToBytes = function (id) {
        var idBytes = ethers_1.ethers.utils.toUtf8Bytes(id.toString());
        var idBytesHex = ethers_1.ethers.utils.hexlify(idBytes);
        return idBytesHex;
    };
    ProofPointRegistry.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 proofPointEvent_1.ProofPointId.parse(idStr);
    };
    ProofPointRegistry.prototype._topicToEventType = function (topic) {
        if (topic === ethers_1.ethers.utils.id("Issued(address,bytes)"))
            return proofPointEventType_1.ProofPointEventType.Issued;
        if (topic === ethers_1.ethers.utils.id("Committed(address,bytes)"))
            return proofPointEventType_1.ProofPointEventType.Committed;
        if (topic === ethers_1.ethers.utils.id("Revoked(address,bytes)"))
            return proofPointEventType_1.ProofPointEventType.Revoked;
        throw new Error("Invalid Proof Point event type topic: " + topic);
    };
    ProofPointRegistry.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, 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];
                }
            });
        });
    };
    ProofPointRegistry.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: proofPointEvent_1.EthereumAddress.parse(ethers_1.ethers.utils.hexStripZeros(ev.topics[1])),
                                    proofPointId: proofPointId,
                                    transactionHash: proofPointEvent_1.EthereumTransactionHash.parse(ev.transactionHash),
                                };
                            })];
                }
            });
        });
    };
    ProofPointRegistry.prototype._issue = function (type, issuer, content, issueFunction, validFromDate, validUntilDate) {
        if (validFromDate === void 0) { validFromDate = null; }
        if (validUntilDate === void 0) { validUntilDate = null; }
        return __awaiter(this, void 0, void 0, function () {
            var issuerAddress, proofPointObject, _a, id, canonicalisedObject, proofPointIdBytes, signer, connectedContract, transactionReceipt;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this._resolveIssuerToEthereumAddress(issuer)];
                    case 1:
                        issuerAddress = _b.sent();
                        if (issuerAddress === null) {
                            throw new Error("Cannot resolve issuer: " + issuer);
                        }
                        proofPointObject = this.buildJson(type, issuer, content, validFromDate, validUntilDate);
                        return [4 /*yield*/, this._canonicalizeAndStoreObject(proofPointObject)];
                    case 2:
                        _a = _b.sent(), id = _a.id, canonicalisedObject = _a.canonicalisedObject;
                        proofPointIdBytes = this.proofPointIdToBytes(id);
                        signer = this._provider.getSigner(issuerAddress.toString());
                        connectedContract = this._registry.connect(signer);
                        return [4 /*yield*/, issueFunction(connectedContract, proofPointIdBytes)];
                    case 3:
                        transactionReceipt = _b.sent();
                        return [2 /*return*/, {
                                proofPointId: id,
                                transactionHash: proofPointEvent_1.EthereumTransactionHash.parse(transactionReceipt.hash),
                                proofPointObject: canonicalisedObject,
                            }];
                }
            });
        });
    };
    ProofPointRegistry.prototype.buildJson = function (type, issuer, content, validFromDate, validUntilDate) {
        if (validFromDate === void 0) { validFromDate = null; }
        if (validUntilDate === void 0) { validUntilDate = null; }
        var proofPoint = {
            "@context": [
                "https://www.w3.org/2018/credentials/v1",
                "https://provenance.org/ontology/ptf/v2",
            ],
            type: ["VerifiableCredential", type],
            issuer: issuer,
            credentialSubject: content,
            proof: {
                type: PROOF_TYPE,
                registryRoot: this._rootAddress.toString(),
                proofPurpose: "assertionMethod",
                verificationMethod: issuer,
            },
            validFrom: undefined,
            validUntil: undefined,
        };
        if (validFromDate !== null) {
            proofPoint.validFrom = localISOdt.localISOdt(validFromDate);
        }
        if (validUntilDate !== null) {
            proofPoint.validUntil = localISOdt.localISOdt(validUntilDate);
        }
        return proofPoint;
    };
    ProofPointRegistry.prototype.isSameRegistry = function (proofPoint) {
        return (proofPoint.proof.registryRoot.toLowerCase() ===
            this._rootAddress.toString().toLowerCase());
    };
    /**
     * Did to url. Translate a did:web identifier to the URL at which the corresponding DID document can be found
     * according to spec at https://w3c-ccg.github.io/did-method-web/#crud-operation-definitions.
     * @param did a valid did:web ID string
     * @returns an https URL string representing the location of the corresponding DID document
     */
    ProofPointRegistry.prototype.didToUrl = function (did) {
        var parts = did.split(":");
        if (parts.length === 3) {
            // did:web:<x>
            var hostname = decodeURIComponent(parts[2]);
            return "https://" + hostname + "/.well-known/did.json";
        }
        else {
            // did:web:<a>:<b>:...:<z>
            var hostname = decodeURIComponent(parts[2]);
            var path = parts.slice(3).join("/");
            return "https://" + hostname + "/" + path + "/did.json";
        }
    };
    ProofPointRegistry.prototype._resolveIssuerToEthereumAddress = function (issuer) {
        return __awaiter(this, void 0, void 0, function () {
            var didDocumentUri, body, didDocument, e_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (/^0x[a-fA-F0-9]{40}$/.test(issuer)) {
                            return [2 /*return*/, proofPointEvent_1.EthereumAddress.parse(issuer)];
                        }
                        if (!/^did\:web\:.+$/.test(issuer)) return [3 /*break*/, 4];
                        didDocumentUri = this.didToUrl(issuer);
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this._httpClient.fetch(didDocumentUri)];
                    case 2:
                        body = _a.sent();
                        didDocument = JSON.parse(body);
                        if (didDocument["@context"] !== "https://w3id.org/did/v1" ||
                            didDocument.id !== issuer ||
                            typeof didDocument.publicKey === "undefined" ||
                            didDocument.publicKey[0].type !== "Secp256k1VerificationKey2018" ||
                            didDocument.publicKey[0].owner !== issuer ||
                            !/^0x[a-fA-F0-9]{40}$/.test(didDocument.publicKey[0].ethereumAddress)) {
                            // DID document is invalid or unsupported
                            return [2 /*return*/, null];
                        }
                        return [2 /*return*/, proofPointEvent_1.EthereumAddress.parse(didDocument.publicKey[0].ethereumAddress)];
                    case 3:
                        e_1 = _a.sent();
                        // DID document could not be fetched
                        return [2 /*return*/, null];
                    case 4: 
                    // Unsupported issuer format
                    return [2 /*return*/, null];
                }
            });
        });
    };
    ProofPointRegistry.removeEmptyFields = function (obj) {
        Object.keys(obj).forEach(function (key) {
            if (obj[key] && typeof obj[key] === "object")
                ProofPointRegistry.removeEmptyFields(obj[key]);
            // eslint-disable-next-line no-param-reassign
            else if (obj[key] === undefined)
                delete obj[key];
        });
        return obj;
    };
    ProofPointRegistry.prototype._canonicalizeAndStoreObject = function (dataObject) {
        return __awaiter(this, void 0, void 0, function () {
            var cleanedDataObject, dataStr, storageResult;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        cleanedDataObject = ProofPointRegistry.removeEmptyFields(dataObject);
                        dataStr = canonicalizeJson(cleanedDataObject);
                        return [4 /*yield*/, this._storage.add(dataStr)];
                    case 1:
                        storageResult = _a.sent();
                        return [2 /*return*/, {
                                id: proofPointEvent_1.ProofPointId.parse(storageResult.digest),
                                canonicalisedObject: JSON.parse(dataStr),
                            }];
                }
            });
        });
    };
    ProofPointRegistry.prototype._getVersion = function () {
        return __awaiter(this, void 0, void 0, function () {
            var version, e_2;
            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_2 = _a.sent();
                        // version 1 does not have the getVersion method.
                        return [2 /*return*/, 1];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    return ProofPointRegistry;
}());
exports.ProofPointRegistry = ProofPointRegistry;
