UNPKG

@cruxpay/js-sdk

Version:

CruxPay Javascript SDK

400 lines (399 loc) 22.9 kB
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 __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; var __spread = (this && this.__spread) || function () { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; }; import { AssertionError, deepStrictEqual } from "assert"; import { publicKeyToAddress } from "blockstack"; import { DomainRegistrationStatus } from "../../core/entities/crux-domain"; import { CruxSpec } from "../../core/entities/crux-spec"; import { SubdomainRegistrationStatus, SubdomainRegistrationStatusDetail } from "../../core/entities/crux-user"; import { BaseError, ErrorHelper, PackageErrorCode } from "../../packages/error"; import { BlockstackDomainId, BlockstackId, CruxDomainId, CruxId, } from "../../packages/identity-utils"; import { getLogger } from "../../packages/logger"; import { BlockstackNamingServiceApiClient, BlockstackSubdomainRegistrarApiClient } from "./api-clients"; var log = getLogger(__filename); var BlockstackService = /** @class */ (function () { function BlockstackService(options) { var _this = this; this.getNameDetails = function (id, tag) { return __awaiter(_this, void 0, void 0, function () { var blockstackName; return __generator(this, function (_a) { blockstackName = CruxSpec.idTranslator.cruxToBlockstack(id).toString(); return [2 /*return*/, BlockstackService.getNameDetails(blockstackName, this.bnsNodes, tag, this.cacheStorage)]; }); }); }; this.getGaiaHub = function (id, tag) { return __awaiter(_this, void 0, void 0, function () { var nameDetails, gaiaHub; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.getNameDetails(id, tag)]; case 1: nameDetails = _a.sent(); if (!nameDetails.zonefile) { throw ErrorHelper.getPackageError(null, PackageErrorCode.MissingZoneFile, id.toString()); } if (!nameDetails.address) { throw ErrorHelper.getPackageError(null, PackageErrorCode.MissingNameOwnerAddress, id.toString()); } gaiaHub = BlockstackService.getGaiaHubFromZonefile(nameDetails.zonefile); return [2 /*return*/, gaiaHub]; } }); }); }; this.getDomainRegistrationStatus = function (cruxDomainId) { return __awaiter(_this, void 0, void 0, function () { var nameDetails; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.getNameDetails(cruxDomainId)]; case 1: nameDetails = _a.sent(); return [2 /*return*/, BlockstackService.getDomainRegistrationStatusFromNameDetails(nameDetails)]; } }); }); }; this.getCruxDomainIdWithConfigKeyManager = function (keyManager, contextDomainId) { return __awaiter(_this, void 0, void 0, function () { var configSubdomainAddress, _a, registeredBlockstackIDs, registeredDomainStringArray; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = publicKeyToAddress; return [4 /*yield*/, keyManager.getPubKey()]; case 1: configSubdomainAddress = _a.apply(void 0, [_b.sent()]); return [4 /*yield*/, BlockstackService.getRegisteredBlockstackNamesByAddress(configSubdomainAddress, this.bnsNodes, this.cacheStorage)]; case 2: registeredBlockstackIDs = _b.sent(); registeredDomainStringArray = registeredBlockstackIDs .map(function (blockstackID) { return blockstackID.match(new RegExp("^_config.(.+)_crux.id$")); }) .map(function (match) { return match && match[1]; }) .filter(Boolean); // TODO: handle else case if (contextDomainId && registeredDomainStringArray.includes(contextDomainId.components.domain)) { return [2 /*return*/, contextDomainId]; } else if (registeredDomainStringArray.length === 1) { return [2 /*return*/, new CruxDomainId(registeredDomainStringArray[0])]; } return [2 /*return*/]; } }); }); }; this.getCruxIdWithKeyManager = function (keyManager, cruxDomainId) { return __awaiter(_this, void 0, void 0, function () { var userSubdomainOwnerAddress, _a, registeredBlockstackNames, registeredIdNames, registrarApiClient, subdomainRegistrarEntries; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = publicKeyToAddress; return [4 /*yield*/, keyManager.getPubKey()]; case 1: userSubdomainOwnerAddress = _a.apply(void 0, [_b.sent()]); return [4 /*yield*/, BlockstackService.getRegisteredBlockstackNamesByAddress(userSubdomainOwnerAddress, this.bnsNodes, this.cacheStorage)]; case 2: registeredBlockstackNames = _b.sent(); registeredIdNames = registeredBlockstackNames // tslint:disable-next-line: tsr-detect-non-literal-regexp .map(function (blockstackName) { return blockstackName.match(new RegExp("(.+)." + CruxSpec.idTranslator.cruxToBlockstack(cruxDomainId).toString())); }) .map(function (match) { return match && match[0]; }) .filter(Boolean); if (registeredIdNames.length > 1) { log.error("More than one cruxIDs associated with: " + userSubdomainOwnerAddress); } if (registeredIdNames[0]) { return [2 /*return*/, CruxSpec.idTranslator.blockstackToCrux(BlockstackId.fromString(registeredIdNames[0]))]; } registrarApiClient = new BlockstackSubdomainRegistrarApiClient(this.subdomainRegistrar, CruxSpec.idTranslator.cruxToBlockstack(cruxDomainId)); return [4 /*yield*/, registrarApiClient.getSubdomainRegistrarEntriesByAddress(userSubdomainOwnerAddress)]; case 3: subdomainRegistrarEntries = _b.sent(); if (subdomainRegistrarEntries.length !== 0) { return [2 /*return*/, new CruxId({ domain: cruxDomainId.components.domain, subdomain: subdomainRegistrarEntries[0].subdomainName, })]; } return [2 /*return*/]; } }); }); }; this.isCruxIdAvailable = function (cruxId) { return __awaiter(_this, void 0, void 0, function () { var blockstackId, registrarApiClient, registrarStatus, cruxUserInformation; return __generator(this, function (_a) { switch (_a.label) { case 0: CruxSpec.validations.validateSubdomainString(cruxId.components.subdomain); blockstackId = CruxSpec.idTranslator.cruxToBlockstack(cruxId); registrarApiClient = new BlockstackSubdomainRegistrarApiClient(this.subdomainRegistrar, new BlockstackDomainId(blockstackId.components.domain)); return [4 /*yield*/, registrarApiClient.getSubdomainStatus(cruxId.components.subdomain)]; case 1: registrarStatus = _a.sent(); cruxUserInformation = BlockstackService.getCruxUserInformationFromSubdomainStatus(registrarStatus); return [2 /*return*/, cruxUserInformation.registrationStatus.status === SubdomainRegistrationStatus.NONE]; } }); }); }; this.registerCruxId = function (cruxId, gaiaHub, keyManager) { return __awaiter(_this, void 0, void 0, function () { var blockstackId, registrarApiClient, _a, _b, _c, _d; return __generator(this, function (_e) { switch (_e.label) { case 0: if (!keyManager) { throw ErrorHelper.getPackageError(null, PackageErrorCode.CouldNotFindKeyPairToRegisterName); } return [4 /*yield*/, this.isCruxIdAvailable(cruxId)]; case 1: if (!(_e.sent())) { throw ErrorHelper.getPackageError(null, PackageErrorCode.CruxIDUnavailable, cruxId); } blockstackId = CruxSpec.idTranslator.cruxToBlockstack(cruxId); registrarApiClient = new BlockstackSubdomainRegistrarApiClient(this.subdomainRegistrar, new BlockstackDomainId(blockstackId.components.domain)); _b = (_a = registrarApiClient).registerSubdomain; _c = [cruxId.components.subdomain, gaiaHub]; _d = publicKeyToAddress; return [4 /*yield*/, keyManager.getPubKey()]; case 2: return [4 /*yield*/, _b.apply(_a, _c.concat([_d.apply(void 0, [_e.sent()])]))]; case 3: _e.sent(); return [2 /*return*/, this.getCruxIdInformation(cruxId)]; } }); }); }; this.getCruxIdInformation = function (cruxId, tag, onlyRegistered) { return __awaiter(_this, void 0, void 0, function () { var nameDetails, status, statusDetail, transactionHash, ownerAddress, blockstackId, registrarApiClient, registrarStatus, registrationStatus; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.getNameDetails(cruxId, tag)]; case 1: nameDetails = _a.sent(); if (nameDetails.status === "registered_subdomain") { status = SubdomainRegistrationStatus.DONE; statusDetail = SubdomainRegistrationStatusDetail.DONE; transactionHash = nameDetails.last_txid; ownerAddress = nameDetails.address; return [2 /*return*/, { ownerAddress: ownerAddress, registrationStatus: { status: status, statusDetail: statusDetail, }, transactionHash: transactionHash, }]; } if (onlyRegistered) { return [2 /*return*/, { registrationStatus: { status: SubdomainRegistrationStatus.NONE, statusDetail: SubdomainRegistrationStatusDetail.NONE, }, }]; } blockstackId = CruxSpec.idTranslator.cruxToBlockstack(cruxId); registrarApiClient = new BlockstackSubdomainRegistrarApiClient(this.subdomainRegistrar, new BlockstackDomainId(blockstackId.components.domain)); return [4 /*yield*/, registrarApiClient.getSubdomainStatus(cruxId.components.subdomain)]; case 2: registrarStatus = _a.sent(); registrationStatus = BlockstackService.getCruxUserInformationFromSubdomainStatus(registrarStatus); return [2 /*return*/, registrationStatus]; } }); }); }; this.bnsNodes = options.bnsNodes; this.subdomainRegistrar = options.subdomainRegistrar; this.cacheStorage = options.cacheStorage; } BlockstackService.getRegisteredBlockstackNamesByAddress = function (address, bnsNodes, cacheStorage) { return __awaiter(void 0, void 0, void 0, function () { var nodePromises, responseArr, commonIDs; return __generator(this, function (_a) { switch (_a.label) { case 0: nodePromises = bnsNodes.map(function (baseUrl) { return __awaiter(void 0, void 0, void 0, function () { var addressNameData; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, BlockstackNamingServiceApiClient.getNamesByAddress(baseUrl, address, cacheStorage)]; case 1: addressNameData = _a.sent(); return [2 /*return*/, addressNameData.names]; } }); }); }); return [4 /*yield*/, Promise.all(nodePromises)]; case 1: responseArr = _a.sent(); commonIDs = __spread((responseArr.map(function (arr) { return new Set(arr); }).reduce(function (a, b) { return new Set(__spread(a).filter(function (x) { return b.has(x); })); }))); return [2 /*return*/, commonIDs]; } }); }); }; BlockstackService.getNameDetails = function (blockstackName, bnsNodes, tag, cacheStorage) { return __awaiter(void 0, void 0, void 0, function () { var responsePromises, responsesArr, nameDetails; return __generator(this, function (_a) { switch (_a.label) { case 0: responsePromises = bnsNodes.map(function (baseUrl) { return BlockstackNamingServiceApiClient.getNameDetails(baseUrl, blockstackName, tag, cacheStorage); }); log.debug("BNS node response promises:", responsePromises); return [4 /*yield*/, Promise.all(responsePromises)]; case 1: responsesArr = _a.sent(); log.debug("BNS resolved JSON array:", responsesArr); nameDetails = responsesArr.reduce(function (previousResponse, response) { try { if (blockstackName.split(".").length === 2) { // compare only address field for domains if (previousResponse.address !== response.address) { throw new AssertionError({ message: "address fields do not match!" }); } } else { deepStrictEqual(previousResponse, response); } } catch (e) { if (e instanceof AssertionError) { throw ErrorHelper.getPackageError(e, PackageErrorCode.NameIntegrityCheckFailed); } log.error(e); throw e; } return response; }); log.debug(nameDetails); if (!nameDetails) { throw ErrorHelper.getPackageError(null, PackageErrorCode.BnsEmptyData); } return [2 /*return*/, nameDetails]; } }); }); }; BlockstackService.getGaiaHubFromZonefile = function (zonefile) { var gaiaHub; if (zonefile.match(new RegExp("(.+)https:\/\/hub.cruxpay.com\/hub\/(.+)\/profile.json"))) { var match = zonefile.match(new RegExp("(.+)https:\/\/(.+)\/hub\/(.+)\/profile.json", "s")); if (!match) { throw ErrorHelper.getPackageError(null, PackageErrorCode.FailedToGetGaiaUrlFromZonefile, zonefile); } gaiaHub = "https://" + match[2]; } else { var match = zonefile.match(new RegExp("https:\/\/(.+)")); if (!match) { throw ErrorHelper.getPackageError(null, PackageErrorCode.FailedToGetGaiaUrlFromZonefile, zonefile); } gaiaHub = match.slice(0, -1)[0]; } return gaiaHub; }; BlockstackService.getDomainRegistrationStatusFromNameDetails = function (nameDetails) { var domainRegistrationStatus; switch (nameDetails.status) { case "available": domainRegistrationStatus = DomainRegistrationStatus.AVAILABLE; break; case "registered": domainRegistrationStatus = DomainRegistrationStatus.REGISTERED; break; default: throw new BaseError(null, "Invalid name data for CruxDomain"); } return domainRegistrationStatus; }; BlockstackService.getCruxUserInformationFromSubdomainStatus = function (subdomainStatus) { var status; var transactionHash; var rawStatus = subdomainStatus.status; log.debug(subdomainStatus); if (rawStatus && rawStatus.includes("Your subdomain was registered in transaction")) { status = { status: SubdomainRegistrationStatus.PENDING, statusDetail: SubdomainRegistrationStatusDetail.PENDING_REGISTRAR, }; var regexMatch = rawStatus.match(new RegExp(".+transaction (.+) --.+")); if (regexMatch !== null) { transactionHash = regexMatch[1]; } } else { transactionHash = undefined; switch (rawStatus) { case "Subdomain is queued for update and should be announced within the next few blocks.": status = { status: SubdomainRegistrationStatus.PENDING, statusDetail: SubdomainRegistrationStatusDetail.PENDING_BLOCKCHAIN, }; break; case "Subdomain propagated": status = { status: SubdomainRegistrationStatus.DONE, statusDetail: SubdomainRegistrationStatusDetail.DONE, }; break; default: // used to handle "Subdomain not registered with this registrar" for now status = { status: SubdomainRegistrationStatus.NONE, statusDetail: SubdomainRegistrationStatusDetail.NONE, }; } } var cruxUserInformation = { registrationStatus: status, }; if (transactionHash) { cruxUserInformation.transactionHash = transactionHash; } return cruxUserInformation; }; return BlockstackService; }()); export { BlockstackService };