@firmachain/firma-js
Version:
The Official FirmaChain Javascript SDK written in Typescript
268 lines (267 loc) • 14.9 kB
JavaScript
;
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 (_) 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.SigningAminoStargateClient = exports.isMsgSignData = void 0;
var tendermint_rpc_1 = require("@cosmjs/tendermint-rpc");
//import { StdFee } from ".";
var accounts_1 = require("./accounts");
var stargateclient_1 = require("./stargateclient");
var axios_1 = __importDefault(require("axios"));
var any_1 = require("../google/protobuf/any");
var encoding_1 = require("@cosmjs/encoding");
var amino_1 = require("@cosmjs/amino");
var fast_deep_equal_1 = __importDefault(require("fast-deep-equal"));
var utils_1 = require("@cosmjs/utils");
var tx_1 = require("@cosmjs/launchpad/build/tx");
var amino_2 = require("@cosmjs/amino");
var crypto_1 = require("@cosmjs/crypto");
var crypto_2 = require("@cosmjs/crypto");
var utils_2 = require("@cosmjs/utils");
var encoding_2 = require("@cosmjs/encoding");
var amino_3 = require("@cosmjs/amino");
var FirmaUtil_1 = require("../../FirmaUtil");
function isMsgSignData(msg) {
var castedMsg = msg;
if (castedMsg.type !== "sign/MsgSignData")
return false;
if (!utils_1.isNonNullObject(castedMsg.value))
return false;
if (typeof castedMsg.value.signer !== "string")
return false;
if (typeof castedMsg.value.data !== "string")
return false;
return true;
}
exports.isMsgSignData = isMsgSignData;
var SigningAminoStargateClient = /** @class */ (function (_super) {
__extends(SigningAminoStargateClient, _super);
function SigningAminoStargateClient(tmClient, signer) {
var _this = _super.call(this, tmClient) || this;
_this.signer = signer;
return _this;
}
SigningAminoStargateClient.connectWithSigner = function (endpoint, signer, registry) {
return __awaiter(this, void 0, void 0, function () {
var tmClient;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this._endpoint = endpoint;
return [4 /*yield*/, tendermint_rpc_1.Tendermint34Client.connect(endpoint)];
case 1:
tmClient = _a.sent();
return [2 /*return*/, new SigningAminoStargateClient(tmClient, signer)];
}
});
});
};
SigningAminoStargateClient.prototype.experimentalAdr36Sign = function (signerAddress, data) {
return __awaiter(this, void 0, void 0, function () {
var accountNumber, sequence, chainId, fee, memo, datas, msgs, accountFromSigner, signDoc, _a, signature, signed, signatureResult, decodeData, jsonData;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
accountNumber = 0;
sequence = 0;
chainId = "";
fee = {
gas: "0",
amount: [],
//granter: "" // added by DH
};
memo = "";
datas = Array.isArray(data) ? data : [data];
msgs = datas.map(function (d) { return ({
type: "sign/MsgSignData",
value: {
signer: signerAddress,
data: encoding_1.toBase64(d),
},
}); });
return [4 /*yield*/, this.signer.getAccounts()];
case 1:
accountFromSigner = (_b.sent()).find(function (account) { return account.address === signerAddress; });
if (!accountFromSigner) {
throw new Error("Failed to retrieve account from signer");
}
signDoc = amino_1.makeSignDoc(msgs, fee, chainId, memo, accountNumber, sequence);
return [4 /*yield*/, this.signer.signAmino(signerAddress, signDoc)];
case 2:
_a = _b.sent(), signature = _a.signature, signed = _a.signed;
if (!fast_deep_equal_1.default(signDoc, signed)) {
throw new Error("The signed document differs from the signing instruction. This is not supported for ADR-036.");
}
signatureResult = tx_1.makeStdTx(signDoc, signature);
decodeData = amino_1.decodeSignature(signatureResult.signatures[0]);
jsonData = {
type: "sign/MsgSignData",
signer: signatureResult.msg[0].value.signer,
data: signatureResult.msg[0].value.data,
pubkey: FirmaUtil_1.FirmaUtil.arrayBufferToBase64(decodeData.pubkey),
signature: FirmaUtil_1.FirmaUtil.arrayBufferToBase64(decodeData.signature)
};
return [2 /*return*/, jsonData];
}
});
});
};
SigningAminoStargateClient.experimentalAdr36Verify = function (data, checkMsg) {
return __awaiter(this, void 0, void 0, function () {
var newSignature, signed, accountNumber, sequence, chainId, signedMessages, sourceMsg, signatures, signature, signBytes, prehashed, secpSignature, rawSecp256k1Pubkey, rawSignerAddress, ok;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
newSignature = amino_1.encodeSecp256k1Signature(FirmaUtil_1.FirmaUtil.base64ToArrayBuffer(data.pubkey), FirmaUtil_1.FirmaUtil.base64ToArrayBuffer(data.signature));
signed = {
fee: {
gas: "0",
amount: [],
},
msg: [{
type: data.type,
value: { signer: data.signer, data: data.data }
}],
signatures: [newSignature],
memo: ""
};
// Restrictions from ADR-036
if (signed.memo !== "")
throw new Error("Memo must be empty.");
if (signed.fee.gas !== "0")
throw new Error("Fee gas must 0.");
if (signed.fee.amount.length !== 0)
throw new Error("Fee amount must be an empty array.");
accountNumber = 0;
sequence = 0;
chainId = "";
signedMessages = signed.msg;
if (!signedMessages.every(isMsgSignData)) {
throw new Error("Found message that is not the expected type.");
}
if (signedMessages.length === 0) {
throw new Error("No message found. Without messages we cannot determine the signer address.");
}
sourceMsg = Buffer.from(signedMessages[0].value.data, 'base64').toString();
if (sourceMsg !== checkMsg) {
throw new Error("Different Msg error. source:" + sourceMsg + ", target:" + checkMsg);
}
signatures = signed.signatures;
if (signatures.length !== 1)
throw new Error("Must have exactly one signature to be supported.");
signature = signatures[0];
if (!amino_2.isSecp256k1Pubkey(signature.pub_key)) {
throw new Error("Only secp256k1 signatures are supported.");
}
signBytes = amino_2.serializeSignDoc(amino_1.makeSignDoc(signed.msg, signed.fee, chainId, signed.memo, accountNumber, sequence));
prehashed = crypto_1.sha256(signBytes);
secpSignature = crypto_2.Secp256k1Signature.fromFixedLength(encoding_2.fromBase64(signature.signature));
rawSecp256k1Pubkey = encoding_2.fromBase64(signature.pub_key.value);
rawSignerAddress = amino_3.rawSecp256k1PubkeyToRawAddress(rawSecp256k1Pubkey);
if (signedMessages.some(function (msg) { return !utils_2.arrayContentEquals(encoding_1.Bech32.decode(msg.value.signer).data, rawSignerAddress); })) {
throw new Error("Found mismatch between signer in message and public key");
}
return [4 /*yield*/, crypto_2.Secp256k1.verifySignature(secpSignature, prehashed, rawSecp256k1Pubkey)];
case 1:
ok = _a.sent();
return [2 /*return*/, ok];
}
});
});
};
/**
* Takes a bech32 encoded address and returns the data part. The prefix is ignored and discarded.
* This is called AccAddress in Cosmos SDK, which is basically an alias for raw binary data.
* The result is typically 20 bytes long but not restricted to that.
*/
SigningAminoStargateClient.prototype.toAccAddress = function (address) {
return encoding_1.Bech32.decode(address).data;
};
SigningAminoStargateClient.prototype.getAccount = function (address) {
return __awaiter(this, void 0, void 0, function () {
var accAddress, hexAccAddress, axios, path, result, finalData, account, finalAccount, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
accAddress = this.toAccAddress(address);
hexAccAddress = "0x01" + Buffer.from(accAddress).toString("hex");
axios = axios_1.default.create({
baseURL: SigningAminoStargateClient._endpoint,
headers: {
Accept: "application/json",
},
timeout: 15000
});
path = "/abci_query?path=\"/store/acc/key\"";
return [4 /*yield*/, axios.get(path, { params: { data: hexAccAddress } })];
case 1:
result = _a.sent();
finalData = result.data.result.response.value;
account = any_1.Any.decode(Buffer.from(finalData, "base64"));
finalAccount = accounts_1.accountFromAny(account);
return [2 /*return*/, finalAccount];
case 2:
error_1 = _a.sent();
return [2 /*return*/, undefined];
case 3: return [2 /*return*/];
}
});
});
};
SigningAminoStargateClient._endpoint = "";
return SigningAminoStargateClient;
}(stargateclient_1.StargateClient));
exports.SigningAminoStargateClient = SigningAminoStargateClient;