UNPKG

@firmachain/firma-js

Version:

The Official FirmaChain Javascript SDK written in Typescript

320 lines (319 loc) 17.2 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); 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 (g && (g = 0, op[0] && (_ = 0)), _) 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 __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SigningProtobufStargateClient = void 0; var encoding_1 = require("@cosmjs/encoding"); var proto_signing_1 = require("@cosmjs/proto-signing"); var tendermint_rpc_1 = require("@cosmjs/tendermint-rpc"); var utils_1 = require("@cosmjs/utils"); var crypto_1 = require("@cosmjs/crypto"); var tendermint_rpc_2 = require("@cosmjs/tendermint-rpc"); var tx_1 = require("cosmjs-types/cosmos/tx/v1beta1/tx"); var any_1 = require("cosmjs-types/google/protobuf/any"); var signing_1 = require("cosmjs-types/cosmos/tx/signing/v1beta1/signing"); var keys_1 = require("cosmjs-types/cosmos/crypto/secp256k1/keys"); var accounts_1 = require("./accounts"); var axios_1 = __importDefault(require("axios")); var StargateClient_1 = require("./StargateClient"); var SigningProtobufStargateClient = /** @class */ (function (_super) { __extends(SigningProtobufStargateClient, _super); function SigningProtobufStargateClient(cometClient, options, signer, endpoint) { var _this = _super.call(this, cometClient, options) || this; _this.signer = signer; _this._endpoint = endpoint; return _this; } SigningProtobufStargateClient.connectWithSigner = function (endpoint, signer, options) { return __awaiter(this, void 0, void 0, function () { var cometClient; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, tendermint_rpc_1.Comet38Client.connect(endpoint)]; case 1: cometClient = _a.sent(); return [2 /*return*/, new SigningProtobufStargateClient(cometClient, options, signer, endpoint)]; } }); }); }; SigningProtobufStargateClient.prototype.experimentalAdr36Sign = function (signerAddress, data) { return __awaiter(this, void 0, void 0, function () { var accountNumber, sequence, chainId, datas, msgs, accountFromSigner, txBody, fee, pubkey, signerInfo, authInfo, signDoc, signBytes, hash, rawWallet, privKey, signature, signatureBytes, jsonData; return __generator(this, function (_a) { switch (_a.label) { case 0: accountNumber = 0; sequence = 0; chainId = ""; datas = Array.isArray(data) ? data : [data]; msgs = datas.map(function (d) { return ({ typeUrl: "/cosmos.tx.v1beta1.MsgSignData", value: any_1.Any.fromPartial({ typeUrl: "/cosmos.tx.v1beta1.MsgSignData", value: new TextEncoder().encode(JSON.stringify({ signer: signerAddress, data: (0, encoding_1.toBase64)(d), })), }), }); }); return [4 /*yield*/, this.signer.getAccounts()]; case 1: accountFromSigner = (_a.sent()).find(function (account) { return account.address === signerAddress; }); if (!accountFromSigner) { throw new Error("Failed to retrieve account from signer"); } txBody = tx_1.TxBody.fromPartial({ messages: msgs.map(function (msg) { return any_1.Any.fromPartial({ typeUrl: msg.typeUrl, value: new Uint8Array(), // Simplified for ADR-036 }); }), memo: "", }); fee = tx_1.Fee.fromPartial({ amount: [], gasLimit: BigInt(0), }); pubkey = keys_1.PubKey.fromPartial({ key: accountFromSigner.pubkey, }); signerInfo = tx_1.SignerInfo.fromPartial({ publicKey: any_1.Any.fromPartial({ typeUrl: "/cosmos.crypto.secp256k1.PubKey", value: keys_1.PubKey.encode(pubkey).finish(), }), modeInfo: { single: { mode: signing_1.SignMode.SIGN_MODE_DIRECT, }, }, sequence: BigInt(sequence), }); authInfo = tx_1.AuthInfo.fromPartial({ signerInfos: [signerInfo], fee: fee, }); signDoc = tx_1.SignDoc.fromPartial({ bodyBytes: tx_1.TxBody.encode(txBody).finish(), authInfoBytes: tx_1.AuthInfo.encode(authInfo).finish(), chainId: chainId, accountNumber: BigInt(accountNumber), }); signBytes = (0, proto_signing_1.makeSignBytes)(signDoc); hash = (0, crypto_1.sha256)(signBytes); rawWallet = this.signer; privKey = rawWallet.privkey; if (!privKey) { throw new Error("Private key not accessible for ADR-036 signing"); } return [4 /*yield*/, crypto_1.Secp256k1.createSignature(hash, privKey)]; case 2: signature = _a.sent(); signatureBytes = new Uint8Array(__spreadArray(__spreadArray([], __read(signature.r(32)), false), __read(signature.s(32)), false)); jsonData = { type: "sign/MsgSignData", signer: signerAddress, data: (0, encoding_1.toBase64)(datas[0]), pubkey: (0, encoding_1.toBase64)(accountFromSigner.pubkey), signature: (0, encoding_1.toBase64)(signatureBytes) }; return [2 /*return*/, jsonData]; } }); }); }; SigningProtobufStargateClient.experimentalAdr36Verify = function (data, checkMsg) { return __awaiter(this, void 0, void 0, function () { var pubkeyBytes, signatureBytes, sourceMsg, accountNumber, sequence, chainId, txBody, fee, pubkey, signerInfo, authInfo, signDoc, signBytes, prehashed, secpSignature, rawSignerAddress, decodedSignerData, ok, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); pubkeyBytes = (0, encoding_1.fromBase64)(data.pubkey); signatureBytes = (0, encoding_1.fromBase64)(data.signature); sourceMsg = Buffer.from(data.data, 'base64').toString(); if (sourceMsg !== checkMsg) { throw new Error("Different Msg error. source:" + sourceMsg + ", target:" + checkMsg); } accountNumber = 0; sequence = 0; chainId = ""; txBody = tx_1.TxBody.fromPartial({ messages: [{ typeUrl: "/cosmos.tx.v1beta1.MsgSignData", value: new Uint8Array(), }], memo: "", }); fee = tx_1.Fee.fromPartial({ amount: [], gasLimit: BigInt(0), }); pubkey = keys_1.PubKey.fromPartial({ key: pubkeyBytes, }); signerInfo = tx_1.SignerInfo.fromPartial({ publicKey: any_1.Any.fromPartial({ typeUrl: "/cosmos.crypto.secp256k1.PubKey", value: keys_1.PubKey.encode(pubkey).finish(), }), modeInfo: { single: { mode: signing_1.SignMode.SIGN_MODE_DIRECT, }, }, sequence: BigInt(sequence), }); authInfo = tx_1.AuthInfo.fromPartial({ signerInfos: [signerInfo], fee: fee, }); signDoc = tx_1.SignDoc.fromPartial({ bodyBytes: tx_1.TxBody.encode(txBody).finish(), authInfoBytes: tx_1.AuthInfo.encode(authInfo).finish(), chainId: chainId, accountNumber: BigInt(accountNumber), }); signBytes = (0, proto_signing_1.makeSignBytes)(signDoc); prehashed = (0, crypto_1.sha256)(signBytes); secpSignature = crypto_1.Secp256k1Signature.fromFixedLength(signatureBytes); rawSignerAddress = (0, tendermint_rpc_2.rawSecp256k1PubkeyToRawAddress)(pubkeyBytes); decodedSignerData = (0, encoding_1.fromBech32)(data.signer).data; if (!(0, utils_1.arrayContentEquals)(decodedSignerData, rawSignerAddress)) { throw new Error("Found mismatch between signer in message and public key"); } return [4 /*yield*/, crypto_1.Secp256k1.verifySignature(secpSignature, prehashed, pubkeyBytes)]; case 1: ok = _a.sent(); return [2 /*return*/, ok]; case 2: error_1 = _a.sent(); return [2 /*return*/, false]; case 3: return [2 /*return*/]; } }); }); }; SigningProtobufStargateClient.prototype.toAccAddress = function (address) { return (0, encoding_1.fromBech32)(address).data; }; SigningProtobufStargateClient.prototype.getAccount = function (address) { return __awaiter(this, void 0, void 0, function () { var accAddress, hexAccAddress, axiosInstance, path, result, finalData, account, finalAccount, error_2; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); accAddress = this.toAccAddress(address); hexAccAddress = "0x01".concat(Buffer.from(accAddress).toString("hex")); axiosInstance = axios_1.default.create({ baseURL: this._endpoint, headers: { Accept: "application/json", }, timeout: 15000 }); path = "/abci_query"; return [4 /*yield*/, axiosInstance.get(path, { params: { path: '"store/acc/key"', data: hexAccAddress } })]; case 1: result = _a.sent(); finalData = result.data.result.response.value; if (!finalData) { return [2 /*return*/, null]; } account = any_1.Any.decode(Buffer.from(finalData, "base64")); finalAccount = (0, accounts_1.accountFromAny)(account); return [2 /*return*/, finalAccount]; case 2: error_2 = _a.sent(); return [2 /*return*/, null]; case 3: return [2 /*return*/]; } }); }); }; return SigningProtobufStargateClient; }(StargateClient_1.StargateClient)); exports.SigningProtobufStargateClient = SigningProtobufStargateClient;